capsule_library/lifecycle/album.rs
1//! Container albums: key material (AMK epochs, write-tier + admin keys), the attested
2//! [`Authority`] behind the album-authority seam, offline epoch rotation, and per-file key
3//! re-derivation.
4
5use std::collections::{BTreeMap, BTreeSet, HashMap};
6use std::fs;
7use std::path::{Path, PathBuf};
8
9use capsule_core::crypto::authority::{Authority, ReferenceAuthority};
10use capsule_core::crypto::keys::albumstore::{
11 AlbumStore, AlbumStoreError, EscrowCoverage, PersistedAlbum, PersistedAuthority,
12};
13use capsule_core::crypto::keys::{Amk, AmkVersion, HybridSigningKey};
14use capsule_core::metadata::crdt::{AddId, OrSet};
15use capsule_core::sidecar::{ALBUM_DOC_SCHEMA_V1, AlbumDocV1, normalize_label};
16use serde_bytes::ByteBuf;
17use uuid::Uuid;
18
19use super::{AlbumKeys, LifecycleError, Result, Workspace, now_rfc3339};
20use crate::album_store::AlbumStoreFile;
21use crate::utils::paths::tmp_path;
22
23/// What [`Workspace::plan_album_key_escrows`] decided, per album, in album id order.
24#[derive(Debug, Clone, Default, PartialEq, Eq)]
25pub struct AlbumKeyEscrowPlan {
26 /// Albums whose escrow the server lacks or that this device strictly extends: store each.
27 pub to_store: Vec<Uuid>,
28 /// Albums whose server escrow already covers every epoch this device holds.
29 pub current: usize,
30 /// Albums whose server escrow disagrees with this device or does not open under its master
31 /// key: left alone, and this device's epochs of them are not covered by the server.
32 pub uncovered: Vec<Uuid>,
33}
34
35/// What [`Workspace::adopt_album_key_escrows`] did.
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
37pub struct AdoptedAlbumKeys {
38 /// Albums the library did not hold and now does.
39 pub adopted: usize,
40 /// The epochs those albums brought with them.
41 pub epochs: usize,
42 /// Escrowed albums the library already held, left as they were.
43 pub already_held: usize,
44 /// Escrows that did not open under this account's master key — sealed under another one —
45 /// and were skipped.
46 pub unopenable: usize,
47}
48
49impl Workspace {
50 /// Create a container album: mint AMK_v1 + write-tier + admin keys and an attested
51 /// authority, then **persist** the album keystore. Returns the new album id.
52 ///
53 /// Fallible because the keys only exist once they are on disk: a workspace that reports an
54 /// album it could not persist would hand the caller an album whose assets become
55 /// undecryptable at the next close.
56 pub fn create_album(&mut self, name: &str) -> Result<Uuid> {
57 self.create_album_with_id(Uuid::now_v7(), name)
58 }
59
60 /// Create an album with a specific id (e.g. the derived default-album id).
61 ///
62 /// Refuses with [`LifecycleError::AlbumExists`] if the workspace already holds key material
63 /// for `album_id`: minting over it would discard the AMKs every existing asset in that album
64 /// was encrypted under. Use [`ensure_album`](Self::ensure_album) for resolve-or-create.
65 ///
66 /// The name follows the label rule, as [`rename_album`](Self::rename_album)'s does, so
67 /// creation never accepts a name a rename would refuse: [`LifecycleError::InvalidLabel`]
68 /// before any key is minted.
69 #[tracing::instrument(skip_all, fields(album_id = %album_id, name = name))]
70 pub fn create_album_with_id(&mut self, album_id: Uuid, name: &str) -> Result<Uuid> {
71 if self.albums.contains_key(&album_id) {
72 return Err(LifecycleError::AlbumExists(album_id));
73 }
74 let name = normalize_label(name)?;
75 let name = name.as_str();
76 let amk = Amk::generate();
77 let write_tier = HybridSigningKey::generate();
78 let admin = HybridSigningKey::generate();
79 let mut amks = BTreeMap::new();
80 amks.insert(1, *amk.as_bytes());
81
82 let authority = ReferenceAuthority::new(album_id, admin.verifying_key()).with_epoch(
83 &admin,
84 AmkVersion(1),
85 &write_tier.verifying_key(),
86 true,
87 );
88 // Offline default: the reference ledger authority. The live `OpenMlsAuthority` drops into
89 // the same `Authority` slot behind the seam once membership ceremonies land.
90 self.authorities
91 .insert(album_id, Authority::Reference(Box::new(authority)));
92 self.albums.insert(
93 album_id,
94 AlbumKeys {
95 album_id,
96 name: name.to_string(),
97 amks,
98 write_tier: Some(write_tier),
99 admin: Some(admin),
100 current_epoch: 1,
101 },
102 );
103 self.persist_albums()?;
104 // The album's label record, carrying the name so a restored or newly joined device sees
105 // it rather than `Recovered album`.
106 let mut doc = AlbumDocV1::new(album_id);
107 doc.name.set(
108 name.to_string(),
109 now_rfc3339(),
110 self.account.device.device_id,
111 );
112 self.store_album_doc(doc)?;
113 tracing::info!("album created: AMK_v1 minted, authority attested, keystore persisted");
114 Ok(album_id)
115 }
116
117 /// Resolve `album_id` to the album this workspace already holds, or create it under `name`.
118 ///
119 /// This is the verb a client's "default album" wiring wants: minting a fresh
120 /// `Imports` album on **every run** would leave a reopened library unable to decrypt or
121 /// extend its own prior imports.
122 pub fn ensure_album(&mut self, album_id: Uuid, name: &str) -> Result<Uuid> {
123 if self.albums.contains_key(&album_id) {
124 tracing::debug!(album_id = %album_id, "album resolved from the durable keystore");
125 return Ok(album_id);
126 }
127 self.create_album_with_id(album_id, name)
128 }
129
130 /// Whether this workspace holds key material for `album_id`.
131 pub fn has_album(&self, album_id: &Uuid) -> bool {
132 self.albums.contains_key(album_id)
133 }
134
135 /// Every album this workspace holds key material for, as `(album_id, name)`, in the album
136 /// order ([`AlbumRecency`](crate::db::AlbumRecency)): the album with the most recent
137 /// visible, untrashed asset first; an empty album by its id's creation time; ties by
138 /// ascending id. Every client lists albums in this order rather than sorting its own.
139 ///
140 /// Recency is read from the index on each call. Should that read fail, the albums are
141 /// listed by creation time and id alone (logged at `ERROR`): a listing that is complete but
142 /// coarser rather than one that loses albums.
143 #[tracing::instrument(level = "debug", skip_all, fields(albums = self.albums.len()))]
144 pub fn albums(&self) -> Vec<(Uuid, String)> {
145 let mut out: Vec<(Uuid, String)> = self
146 .albums
147 .values()
148 .map(|a| (a.album_id, a.name.clone()))
149 .collect();
150 let recency = self.library.db.album_recency().unwrap_or_else(|error| {
151 tracing::error!(
152 %error,
153 "album recency unreadable from the index; listing albums by creation time"
154 );
155 crate::db::AlbumRecency::default()
156 });
157 recency.sort(&mut out, |(id, _)| id.to_string());
158 out
159 }
160
161 /// `album_id`'s server-side key escrow: the whole album — every epoch's AMK, its signing
162 /// seeds and its authority — sealed under the account master key
163 /// ([`PersistedAlbum::seal_escrow`]). The bytes a client stores at
164 /// `PUT /v1/auth/escrow/albums/{album_id}`; the master key never leaves the workspace.
165 ///
166 /// # Errors
167 ///
168 /// [`LifecycleError::NotFound`] for an album this workspace holds no keys for, and
169 /// [`LifecycleError::AlbumStore`] when the album does not encode.
170 #[tracing::instrument(skip_all, fields(album_id = %album_id))]
171 pub fn album_key_escrow(&self, album_id: &Uuid) -> Result<Vec<u8>> {
172 let store = self.album_store_snapshot()?;
173 let album = store
174 .get(album_id)
175 .ok_or_else(|| LifecycleError::NotFound(format!("album {album_id}")))?;
176 let blob = album.seal_escrow(&self.account.master)?;
177 tracing::debug!(
178 epochs = album.amks.len(),
179 bytes = blob.len(),
180 "album key escrow sealed under the master key"
181 );
182 Ok(blob)
183 }
184
185 /// What to do about each album's key escrow, given `escrowed` (album id → the escrow the
186 /// server holds): which albums to store, and which this device's epochs the server's escrow
187 /// does not cover and cannot safely be made to.
188 ///
189 /// **An escrow is never shrunk.** An album is stored only when the server holds none for it,
190 /// or holds one this album strictly extends ([`EscrowCoverage::Superseded`]). An escrow that
191 /// holds epochs this device lacks ([`EscrowCoverage::Behind`], another device rotated
192 /// further), or the same epochs plus a signing seed or authority this device lacks (a
193 /// read-only device restored from a backup), is left alone and counts as covering this
194 /// device's epochs. One that disagrees
195 /// with this device ([`EscrowCoverage::Divergent`]) or does not open under this master key
196 /// ([`EscrowCoverage::Unreadable`]) is left alone too, and the album is reported
197 /// [`uncovered`](AlbumKeyEscrowPlan::uncovered): replacing it could lose epochs a recovery
198 /// needs, so the caller holds the album's assets back instead.
199 ///
200 /// Network-free. A client fetches what the server holds, asks this, and stores
201 /// [`album_key_escrow`](Self::album_key_escrow) for each album in
202 /// [`to_store`](AlbumKeyEscrowPlan::to_store) — before any asset of that album or epoch
203 /// leaves the device, so the server never holds ciphertext whose key it does not also hold
204 /// sealed under the master key.
205 ///
206 /// # Errors
207 ///
208 /// [`LifecycleError::AlbumStore`] when the live album state cannot be captured.
209 pub fn plan_album_key_escrows(
210 &self,
211 escrowed: &BTreeMap<Uuid, Vec<u8>>,
212 ) -> Result<AlbumKeyEscrowPlan> {
213 let store = self.album_store_snapshot()?;
214 let mut plan = AlbumKeyEscrowPlan::default();
215 for album in store.albums() {
216 let Some(blob) = escrowed.get(&album.album_id) else {
217 plan.to_store.push(album.album_id);
218 continue;
219 };
220 match album.escrow_coverage(blob, &self.account.master) {
221 EscrowCoverage::Current => plan.current += 1,
222 EscrowCoverage::Behind => {
223 tracing::info!(
224 album_id = %album.album_id,
225 "album key escrow holds epochs or capabilities this device lacks; left \
226 as it is"
227 );
228 plan.current += 1;
229 }
230 EscrowCoverage::Superseded => plan.to_store.push(album.album_id),
231 coverage @ (EscrowCoverage::Divergent | EscrowCoverage::Unreadable) => {
232 tracing::warn!(
233 album_id = %album.album_id,
234 ?coverage,
235 "album key escrow cannot be replaced without losing epochs or \
236 capabilities; the album is held back"
237 );
238 plan.uncovered.push(album.album_id);
239 }
240 }
241 }
242 tracing::debug!(
243 albums = store.albums().len(),
244 escrowed = escrowed.len(),
245 to_store = plan.to_store.len(),
246 current = plan.current,
247 uncovered = plan.uncovered.len(),
248 "album key escrows compared against what the server holds"
249 );
250 Ok(plan)
251 }
252
253 /// Adopt the account's escrowed albums into this library — the step `capsule auth recover`
254 /// runs on a library it has just created from the master key, **before** anything calls
255 /// [`ensure_album`](Self::ensure_album). An album recovered here is held as the device that
256 /// escrowed it held it, so `ensure_album` resolves the derived default album rather than
257 /// minting a fresh AMK under an id the account's other devices already wrote under.
258 ///
259 /// Every escrow is opened and every carried authority re-verified before the keystore is
260 /// written, and an escrow that opens but is inconsistent refuses the whole adoption with
261 /// nothing persisted — a library that silently lacked one album would mint over it at the
262 /// next `ensure_album`. An album this workspace already holds keeps its own keys and is
263 /// counted in [`AdoptedAlbumKeys::already_held`]: a held content key is never swapped
264 /// underneath the authority that attests it.
265 ///
266 /// An escrow that does **not open** under this master key is skipped and counted in
267 /// [`AdoptedAlbumKeys::unopenable`]. It is sealed under another master key — the escrow was
268 /// later replaced from another library of the account — and its albums are that key's, never
269 /// this one's: their ids cannot collide with this master key's derived default album, and
270 /// refusing them would lock the account out of recovery for good, since nothing can remove
271 /// them. Skipping one costs no more than a server omitting it from the listing would.
272 ///
273 /// # Errors
274 ///
275 /// [`LifecycleError::AlbumStore`] when an escrow opens but is not an album key escrow, holds
276 /// another album than the id it was served under, or carries an authority that does not
277 /// re-verify, or when the keystore cannot be written.
278 #[tracing::instrument(skip_all, fields(escrowed = escrowed.len()))]
279 pub fn adopt_album_key_escrows(
280 &mut self,
281 escrowed: &[(Uuid, Vec<u8>)],
282 ) -> Result<AdoptedAlbumKeys> {
283 let mut store = self.album_store_snapshot()?;
284 let mut adopted = Vec::new();
285 let mut already_held = 0;
286 let mut unopenable = 0;
287 for (album_id, blob) in escrowed {
288 let album = match PersistedAlbum::open_escrow(blob, &self.account.master, *album_id) {
289 Ok(album) => album,
290 Err(AlbumStoreError::Crypto(error)) => {
291 tracing::warn!(
292 album_id = %album_id,
293 %error,
294 "an album key escrow is sealed under another master key; skipped"
295 );
296 unopenable += 1;
297 continue;
298 }
299 Err(error) => {
300 tracing::warn!(album_id = %album_id, %error, "an album key escrow is inconsistent");
301 return Err(error.into());
302 }
303 };
304 if store.get(album_id).is_some() {
305 tracing::info!(album_id = %album_id, "album already held; its escrow is not adopted");
306 already_held += 1;
307 continue;
308 }
309 if let Some(authority) = &album.authority {
310 authority.restore(*album_id, &album.held_epochs())?;
311 }
312 tracing::debug!(
313 album_id = %album_id,
314 epochs = album.amks.len(),
315 writable = album.write_tier_seed64.is_some(),
316 "album key escrow opened"
317 );
318 adopted.push(album);
319 }
320 let report = AdoptedAlbumKeys {
321 adopted: adopted.len(),
322 epochs: adopted.iter().map(|album| album.amks.len()).sum(),
323 already_held,
324 unopenable,
325 };
326 if adopted.is_empty() {
327 tracing::info!(already_held, unopenable, "no album key escrow to adopt");
328 return Ok(report);
329 }
330 for album in adopted {
331 store.upsert(album);
332 }
333 store.save(&self.root, &self.account.master)?;
334 self.apply_album_store(&store);
335 tracing::info!(
336 adopted = report.adopted,
337 epochs = report.epochs,
338 already_held,
339 unopenable,
340 "album key escrows adopted into the keystore"
341 );
342 Ok(report)
343 }
344
345 /// Rotate `album_id` to a fresh epoch: mint AMK_v{n+1} and a new write-tier key, have the
346 /// album admin attest the new epoch, and advance the current epoch — the design's
347 /// "AMK bump + write-tier rotation are one commit" atomicity. The admin key (the ledger
348 /// root) is stable across epochs, and existing assets stay verifiable under their original
349 /// epoch. Returns the new epoch. Membership changes / the MLS `Welcome` flow remain deferred
350 /// (see `SLICES.md`).
351 #[tracing::instrument(skip_all, fields(album_id = %album_id))]
352 pub fn rotate_epoch(&mut self, album_id: Uuid) -> Result<u32> {
353 // Refuse up front on a read-only (backup-recovered) album: a rotation needs the admin key
354 // to attest the new epoch, so half-mutating the AMK map first would leave the workspace
355 // holding a content key no authority covers.
356 self.album(&album_id)?.admin_signer()?;
357 let next = {
358 let album = self
359 .albums
360 .get_mut(&album_id)
361 .ok_or_else(|| LifecycleError::NotFound(format!("album {album_id}")))?;
362 let next = album.current_epoch + 1;
363 album.amks.insert(next, *Amk::generate().as_bytes());
364 album.write_tier = Some(HybridSigningKey::generate());
365 album.current_epoch = next;
366 next
367 };
368 // Disjoint fields: read the album's keys while mutably attesting in its authority. Offline
369 // rotation is a reference-ledger attestation; the live MLS backend rotates via a
370 // self-update commit through the membership ceremonies, not this path — hence the
371 // reference-only accessor.
372 let album = self.albums.get(&album_id).expect("album just mutated");
373 let admin = album.admin_signer()?.clone();
374 let write_tier_pub = album.write_tier_signer()?.verifying_key();
375 let authority = self
376 .authorities
377 .get_mut(&album_id)
378 .and_then(Authority::as_reference_mut)
379 .ok_or_else(|| LifecycleError::NotFound(format!("reference authority {album_id}")))?;
380 authority.attest_epoch(&admin, AmkVersion(next), &write_tier_pub, true);
381 // The new AMK and write-tier key exist only once they are durable; an unpersisted
382 // rotation would make every asset written under the new epoch unreadable after a close.
383 self.persist_albums()?;
384 tracing::info!(epoch = next, "album epoch rotated and keystore persisted");
385 Ok(next)
386 }
387
388 /// The album's authority, behind the [`AlbumAuthority`](capsule_core::crypto::authority::AlbumAuthority)
389 /// seam. A [`NotFound`](LifecycleError::NotFound) rather than a panic: a backup-recovered
390 /// album holds content keys with no attested authority, and asking it to verify must be a
391 /// typed refusal, not an index-out-of-bounds.
392 pub(super) fn authority(&self, album_id: &Uuid) -> Result<&Authority> {
393 self.authorities
394 .get(album_id)
395 .ok_or_else(|| LifecycleError::NotFound(format!("authority for album {album_id}")))
396 }
397
398 /// Snapshot the workspace's live album state as a [`AlbumStore`] — the single conversion
399 /// between the in-memory maps and the sealed on-disk form, so the two can never drift.
400 pub(super) fn album_store_snapshot(&self) -> Result<AlbumStore> {
401 let mut store = AlbumStore::new();
402 for (album_id, keys) in &self.albums {
403 let authority = self
404 .authorities
405 .get(album_id)
406 .map(PersistedAuthority::capture)
407 .transpose()?;
408 store.upsert(PersistedAlbum {
409 album_id: *album_id,
410 name: keys.name.clone(),
411 amks: keys
412 .amks
413 .iter()
414 .map(|(epoch, amk)| (*album_id, *epoch, *amk))
415 .collect(),
416 current_epoch: keys.current_epoch,
417 write_tier_seed64: keys
418 .write_tier
419 .as_ref()
420 .map(|k| ByteBuf::from(k.to_seed_bytes().to_vec())),
421 admin_seed64: keys
422 .admin
423 .as_ref()
424 .map(|k| ByteBuf::from(k.to_seed_bytes().to_vec())),
425 authority,
426 });
427 }
428 Ok(store)
429 }
430
431 /// Seal and durably replace `{root}/.library/albums.cbor` from the live album maps. Called
432 /// after every mutation of album key material.
433 pub(super) fn persist_albums(&self) -> Result<()> {
434 self.album_store_snapshot()?
435 .save(&self.root, &self.account.master)?;
436 Ok(())
437 }
438
439 /// Replace the live album + authority maps with `store`'s contents.
440 ///
441 /// A per-album failure is a `warn` and a skip rather than a failed open: one album whose
442 /// authority ledger no longer verifies (or whose MLS state this build cannot decode) must not
443 /// make the whole library unopenable. The album's **content keys are restored regardless** —
444 /// an unusable authority costs verification and new writes, never read access — so a warn here
445 /// is a degraded album, not a lost one.
446 pub(super) fn apply_album_store(&mut self, store: &AlbumStore) {
447 let mut albums = HashMap::new();
448 let mut authorities = HashMap::new();
449 for persisted in store.albums() {
450 let album_id = persisted.album_id;
451 let (write_tier, admin) = match (persisted.write_tier_key(), persisted.admin_key()) {
452 (Ok(w), Ok(a)) => (w, a),
453 (Err(e), _) | (_, Err(e)) => {
454 tracing::warn!(
455 album_id = %album_id,
456 error = %e,
457 "album store: undecodable signing seed; album restored read-only"
458 );
459 (None, None)
460 }
461 };
462 if let Some(persisted_authority) = &persisted.authority {
463 match persisted_authority.restore(album_id, &persisted.held_epochs()) {
464 Ok(authority) => {
465 authorities.insert(album_id, authority);
466 }
467 Err(e) => tracing::warn!(
468 album_id = %album_id,
469 error = %e,
470 "album store: authority could not be restored; album is readable but \
471 cannot verify or author writes until its authority is re-established"
472 ),
473 }
474 }
475 albums.insert(
476 album_id,
477 AlbumKeys {
478 album_id,
479 name: persisted.name.clone(),
480 amks: persisted
481 .amks
482 .iter()
483 .map(|(_, epoch, amk)| (*epoch, *amk))
484 .collect(),
485 write_tier,
486 admin,
487 current_epoch: persisted.current_epoch,
488 },
489 );
490 }
491 tracing::info!(
492 albums = albums.len(),
493 authorities = authorities.len(),
494 "album store: applied to the workspace"
495 );
496 self.albums = albums;
497 self.authorities = authorities;
498 }
499
500 pub(super) fn album(&self, album_id: &Uuid) -> Result<&AlbumKeys> {
501 self.albums
502 .get(album_id)
503 .ok_or_else(|| LifecycleError::NotFound(format!("album {album_id}")))
504 }
505
506 /// Re-derive the per-file key under a *specific* epoch's AMK for a known `nonce_prefix`
507 /// (the value recorded in the manifest). Callers pass the epoch the asset was written
508 /// under (`amk_version`), never assuming the album's current epoch — so an asset imported
509 /// before a rotation still derives the key it was encrypted with. Because the fresh
510 /// `nonce_prefix` is folded into the salt, this is the read/regenerate path; a *fresh*
511 /// write goes through
512 /// [`encrypt_asset_rekey`](capsule_core::crypto::encryption::encrypt_asset_rekey), which draws the
513 /// nonce and derives together.
514 pub(super) fn file_key(
515 &self,
516 album: &AlbumKeys,
517 epoch: u32,
518 file_id: &Uuid,
519 nonce_prefix: &[u8],
520 ) -> [u8; 32] {
521 let amk = Amk::from_bytes(album.amks[&epoch]);
522 amk.derive_file_key(file_id, nonce_prefix)
523 }
524
525 /// The file key of the **original** a manifest describes, honouring its `key_mode`.
526 ///
527 /// Resolves the epoch's AMK from `album` and recovers the key through
528 /// [`recover_file_key`](capsule_core::crypto::encryption::recover_file_key): a `derived` original
529 /// re-derives, a `wrapped` one — an adopted web-upload drop, whose key a guest chose and
530 /// nobody can derive — unwraps `wrapped_file_key` under the epoch's AMK
531 /// (`asset-keywrap/v1`). Every workspace reader of an original's key goes through here —
532 /// verify, upload and share-link issue — so an adopted asset behaves exactly as an
533 /// imported one does.
534 pub(super) fn original_file_key(
535 &self,
536 album: &AlbumKeys,
537 core: &capsule_core::crypto::provenance::ManifestCore,
538 ) -> Result<[u8; 32]> {
539 let epoch = core.amk_version.0;
540 let amk_bytes = album
541 .amks
542 .get(&epoch)
543 .ok_or_else(|| LifecycleError::NotFound(format!("album epoch {epoch} key")))?;
544 Ok(capsule_core::crypto::encryption::recover_file_key(
545 &Amk::from_bytes(*amk_bytes),
546 core,
547 )?)
548 }
549}
550
551// ── Album labels and name: the album's `AlbumDocV1` (owner: Organization — Labels) ──────────
552//
553// The record is persisted beside the album keystore as signed canonical CBOR — local plaintext,
554// like every sidecar — and sealed under the album's current AMK whenever it leaves the device.
555// An album that predates the record reads as one whose name was written at the Unix epoch by
556// this device, so any real rename on any device wins the LWW merge over it.
557
558/// The stamp of a name an album held before it had an [`AlbumDocV1`].
559const LEGACY_NAME_TS: &str = "1970-01-01T00:00:00Z";
560
561fn docs_dir(root: &Path, kind: &str) -> PathBuf {
562 root.join(".library").join("docs").join(kind)
563}
564
565/// Where an album's signed label record lives in the library.
566pub(super) fn album_doc_path(root: &Path, album_id: &Uuid) -> PathBuf {
567 docs_dir(root, "albums").join(format!("{}.cbor", album_id.simple()))
568}
569
570/// Where a stack's signed label record lives in the library.
571pub(super) fn stack_doc_path(root: &Path, stack_id: &Uuid) -> PathBuf {
572 docs_dir(root, "stacks").join(format!("{}.cbor", stack_id.simple()))
573}
574
575/// Temp-then-rename, so a crash mid-write leaves the previous record intact.
576pub(super) fn write_doc_file(path: &Path, bytes: &[u8]) -> Result<()> {
577 if let Some(parent) = path.parent() {
578 fs::create_dir_all(parent).map_err(|e| LifecycleError::Io(e.to_string()))?;
579 }
580 let tmp = tmp_path(path);
581 fs::write(&tmp, bytes).map_err(|e| LifecycleError::Io(e.to_string()))?;
582 fs::rename(&tmp, path).map_err(|e| LifecycleError::Io(e.to_string()))
583}
584
585/// Read a record file, `None` when absent.
586pub(super) fn read_doc_file(path: &Path) -> Result<Option<Vec<u8>>> {
587 match fs::read(path) {
588 Ok(bytes) => Ok(Some(bytes)),
589 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
590 Err(e) => Err(LifecycleError::Io(e.to_string())),
591 }
592}
593
594/// Remove every live add of `label` from `labels` (observed-remove), returning how many.
595pub(super) fn remove_label(labels: &mut OrSet<String>, label: &str) -> usize {
596 let targets: Vec<AddId> = labels
597 .entries()
598 .into_iter()
599 .filter(|(_, el)| el == label)
600 .map(|(id, _)| id)
601 .collect();
602 for id in &targets {
603 labels
604 .remove(*id)
605 .expect("a live entry's add_id was observed");
606 }
607 targets.len()
608}
609
610impl Workspace {
611 /// Issue an `add_id` for an add into `set`, a label set held in a document rather than a
612 /// sidecar. The open-time counter reseed sweeps sidecars only, so the issued counter is
613 /// floored at one past the highest this device ever wrote into `set` — never re-issuing an
614 /// `add_id` the set already holds.
615 pub(super) fn issue_add_id_for(&mut self, set: &OrSet<String>) -> AddId {
616 let mut id = self.counter.issue();
617 if let Some(max) = set.max_add_counter_for(&id.device)
618 && id.counter <= max
619 {
620 id.counter = max + 1;
621 }
622 id
623 }
624
625 /// `album_id`'s label record: the persisted one, or — for an album that predates the
626 /// record — one holding the keystore's name under the legacy stamp.
627 ///
628 /// # Errors
629 ///
630 /// [`LifecycleError::NotFound`] for an album this workspace holds no keys for;
631 /// [`LifecycleError::UnverifiedDocument`] when the persisted record does not verify.
632 pub fn album_doc(&self, album_id: &Uuid) -> Result<AlbumDocV1> {
633 let album = self.album(album_id)?;
634 if let Some(bytes) = read_doc_file(&album_doc_path(&self.root, album_id))? {
635 let doc = AlbumDocV1::from_canonical_slice(&bytes, ALBUM_DOC_SCHEMA_V1)?;
636 if doc.album_id != *album_id || !doc.verify(&self.account.user_ik.verifying_key()) {
637 return Err(LifecycleError::UnverifiedDocument(*album_id));
638 }
639 return Ok(doc);
640 }
641 let mut doc = AlbumDocV1::new(*album_id);
642 doc.name.set(
643 album.name.clone(),
644 LEGACY_NAME_TS,
645 self.account.device.device_id,
646 );
647 doc.sign(&self.account.user_ik);
648 Ok(doc)
649 }
650
651 /// Sign and persist `doc`, and make the keystore's name follow the record's.
652 fn store_album_doc(&mut self, mut doc: AlbumDocV1) -> Result<()> {
653 if !doc.verify(&self.account.user_ik.verifying_key()) {
654 doc.sign(&self.account.user_ik);
655 }
656 write_doc_file(
657 &album_doc_path(&self.root, &doc.album_id),
658 &doc.to_canonical_vec(),
659 )?;
660 if let Some(name) = doc.current_name() {
661 let album = self
662 .albums
663 .get_mut(&doc.album_id)
664 .ok_or_else(|| LifecycleError::NotFound(format!("album {}", doc.album_id)))?;
665 if album.name != name {
666 album.name = name.to_string();
667 self.persist_albums()?;
668 }
669 }
670 tracing::debug!(
671 album_id = %doc.album_id,
672 labels = doc.labels.value().len(),
673 "album label record persisted"
674 );
675 Ok(())
676 }
677
678 /// Rename an album: a stamped write to its record's name register, so concurrent renames
679 /// on two devices converge on the later one. The name follows the label rule.
680 #[tracing::instrument(skip(self, name), fields(album_id = %album_id))]
681 pub fn rename_album(&mut self, album_id: Uuid, name: &str) -> Result<()> {
682 let name = normalize_label(name)?;
683 let mut doc = self.album_doc(&album_id)?;
684 doc.name
685 .set(name, now_rfc3339(), self.account.device.device_id);
686 doc.signature = None;
687 self.store_album_doc(doc)?;
688 tracing::info!("album renamed");
689 Ok(())
690 }
691
692 /// Add a label to an album.
693 #[tracing::instrument(skip(self, label), fields(album_id = %album_id))]
694 pub fn add_album_label(&mut self, album_id: Uuid, label: &str) -> Result<()> {
695 let label = normalize_label(label)?;
696 let mut doc = self.album_doc(&album_id)?;
697 let add_id = self.issue_add_id_for(&doc.labels);
698 doc.labels.add(label, add_id);
699 doc.signature = None;
700 self.store_album_doc(doc)
701 }
702
703 /// Remove a label from an album: every add of it this device has observed. Returns how
704 /// many adds were removed (0 when the album does not carry the label).
705 #[tracing::instrument(skip(self, label), fields(album_id = %album_id))]
706 pub fn remove_album_label(&mut self, album_id: Uuid, label: &str) -> Result<usize> {
707 let label = normalize_label(label)?;
708 let mut doc = self.album_doc(&album_id)?;
709 let removed = remove_label(&mut doc.labels, &label);
710 if removed > 0 {
711 doc.signature = None;
712 self.store_album_doc(doc)?;
713 }
714 Ok(removed)
715 }
716
717 /// The album's current labels.
718 pub fn album_labels(&self, album_id: &Uuid) -> Result<BTreeSet<String>> {
719 Ok(self.album_doc(album_id)?.labels.value())
720 }
721
722 /// Seal the album's record under its current-epoch AMK — the bytes that travel to the
723 /// album's other members and into a backup.
724 pub fn seal_album_doc(&self, album_id: &Uuid) -> Result<Vec<u8>> {
725 let album = self.album(album_id)?;
726 let amk = Amk::from_bytes(album.amks[&album.current_epoch]);
727 Ok(self.album_doc(album_id)?.seal(&amk)?)
728 }
729
730 /// Open a sealed record another device of this account sent for `album_id`, verify it under
731 /// this account's identity key, and merge it into the local one. Every epoch this workspace
732 /// holds is tried, newest first, since the sender may be an epoch ahead or behind.
733 ///
734 /// # Errors
735 ///
736 /// [`LifecycleError::Document`] when no held AMK opens it or it does not decode;
737 /// [`LifecycleError::UnverifiedDocument`] when it does not verify. Nothing is merged.
738 #[tracing::instrument(skip(self, wire), fields(album_id = %album_id))]
739 pub fn apply_remote_album_doc(&mut self, album_id: Uuid, wire: &[u8]) -> Result<()> {
740 let album = self.album(&album_id)?;
741 let mut last_err = None;
742 let mut opened = None;
743 for amk in album.amks.values().rev() {
744 match AlbumDocV1::open_sealed(
745 wire,
746 &Amk::from_bytes(*amk),
747 &album_id,
748 ALBUM_DOC_SCHEMA_V1,
749 ) {
750 Ok(doc) => {
751 opened = Some(doc);
752 break;
753 }
754 Err(e) => last_err = Some(e),
755 }
756 }
757 let remote = match (opened, last_err) {
758 (Some(doc), _) => doc,
759 (None, Some(e)) => return Err(e.into()),
760 (None, None) => return Err(LifecycleError::NotFound(format!("album {album_id} keys"))),
761 };
762 if !remote.verify(&self.account.user_ik.verifying_key()) {
763 tracing::warn!("remote album label record does not verify; refused");
764 return Err(LifecycleError::UnverifiedDocument(album_id));
765 }
766 self.merge_album_doc(&remote)
767 }
768
769 /// Merge an already-trusted record into the local one and persist the result.
770 pub(super) fn merge_album_doc(&mut self, remote: &AlbumDocV1) -> Result<()> {
771 let mut doc = self.album_doc(&remote.album_id)?;
772 doc.merge(remote)?;
773 self.store_album_doc(doc)?;
774 tracing::info!(album_id = %remote.album_id, "album label record merged");
775 Ok(())
776 }
777}
778
779#[cfg(test)]
780mod tests;