capsule_library/lifecycle/open.rs
1//! Workspace construction and opening: account create/unlock, device-directory publication,
2//! and the injected client / still-encoder seams.
3
4use std::collections::{BTreeMap, HashMap};
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8
9use capsule_core::cbor;
10use capsule_core::crypto::CryptoError;
11use capsule_core::crypto::keys::albumstore::AlbumStore;
12use capsule_core::crypto::keys::directory::{DekPublic, DeviceEntry, DirectoryCore};
13use capsule_core::crypto::keys::{
14 Account, AccountFile, DeviceDirectory, HardwareKeyAgreement, HybridVerifyingKey, Signer,
15};
16use capsule_core::crypto::provenance::{Action, ProvenanceChain, ProvenanceRecord};
17use capsule_core::metadata::crdt::Counter;
18use capsule_core::sidecar::sidecar_v1::{SIDECAR_SCHEMA_V1, SidecarV1};
19use jiff::civil::Date;
20use jiff::tz::TimeZone;
21use uuid::Uuid;
22use walkdir::WalkDir;
23
24use super::unanchored::find_unanchored;
25use super::{
26 AssetState, LifecycleError, Result, StackPlacement, Workspace, media_dir, now_rfc3339,
27};
28use crate::account::{DeviceSignerRecord, HardwareSignerBinding};
29use crate::album_store::AlbumStoreFile;
30
31/// A device is treated as added far in the past so any import timestamp postdates it.
32const DEVICE_ADDED_AT: &str = "2020-01-01T00:00:00Z";
33
34/// The signed device directory's file under `{root}/.library/` (#562).
35const DIRECTORY_FILE: &str = "directory.cbor";
36
37/// A request to bind this workspace's **device encryption key** to a per-platform secure element:
38/// the P-256 key-agreement element itself plus the alias its key is held under.
39///
40/// Supplying one makes the DEK's classical half hardware-held for the life of the account — see
41/// [`DeviceDek`](capsule_core::crypto::keys::DeviceDek). Omitting it keeps the software X-Wing DEK,
42/// which is the design's explicit fallback for hosts with no element, not a degraded mode.
43///
44/// The alias is used only when the account is **created**; on reopen the alias recorded in the
45/// account file wins, so renaming it here can never silently re-bind an existing account to a
46/// different hardware key.
47#[derive(Clone)]
48pub struct HardwareDekBinding {
49 /// The secure element performing the P-256 ECDH (Secure Enclave / StrongBox / TPM).
50 pub element: Arc<dyn HardwareKeyAgreement>,
51 /// The element's alias for this device's key-agreement key.
52 pub key_alias: String,
53}
54
55impl std::fmt::Debug for HardwareDekBinding {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 f.debug_struct("HardwareDekBinding")
58 .field("key_alias", &self.key_alias)
59 .finish_non_exhaustive()
60 }
61}
62
63/// Recover `device`'s `add_id` high-water mark by sweeping the signed sidecars under
64/// `root/media` — the maximum `add_id.counter` this device has ever written, across every
65/// `AddId`-bearing OR-set of every sidecar.
66///
67/// `None` means the device provably issued nothing: no sidecar on disk bears its `device_id` in
68/// any OR-set, so [`Counter::reseed_from_max`] may safely reset to zero. Anything else is one
69/// past the maximum, which is what makes the counter monotonic over the `device_id`'s lifetime
70/// rather than merely within one process (SSoT: [Metadata — Add-id Binding § Counter durability
71/// across restarts]).
72///
73/// The sweep reads the sidecars **without re-verifying their signatures**, for the same reason
74/// [`rebuild_index`](crate::library::rebuild_index) does not: these are the device's own
75/// local plaintext files, and the value recovered is only ever a *floor* on the next counter.
76/// An unreadable or foreign-schema sidecar is warned about and skipped rather than failing the
77/// open — but note that skipping can only lower the floor, so the warning is load-bearing for
78/// after-the-fact recovery, not cosmetic.
79///
80/// [Metadata — Add-id Binding § Counter durability across restarts]: https://docs/design/metadata/#add-id-binding
81#[tracing::instrument(skip_all, fields(root = %root.display(), device = %device))]
82fn sweep_max_add_counter(root: &Path, device: &Uuid) -> Option<u64> {
83 let media = root.join("media");
84 if !media.exists() {
85 tracing::debug!("add-id reseed: no media directory; device has issued nothing");
86 return None;
87 }
88
89 let mut max: Option<u64> = None;
90 let mut scanned = 0usize;
91 let mut skipped = 0usize;
92 for entry in WalkDir::new(&media)
93 .into_iter()
94 .filter_map(std::result::Result::ok)
95 {
96 let path = entry.path();
97 if !path.is_file() {
98 continue;
99 }
100 // The signed sidecar is exactly `{uuid}.cbor`; the sibling `{uuid}.provenance.cbor`,
101 // `{uuid}.receipts.cbor` and `{uuid}.attestations.cbor` logs and the
102 // `derivatives/{uuid}.derivatives.cbor` bundle carry no OR-sets and must not be parsed
103 // as sidecars.
104 let name = path.file_name().unwrap_or_default().to_string_lossy();
105 if !crate::library::paths::is_sidecar_file_name(&name) {
106 continue;
107 }
108 let bytes = match fs::read(path) {
109 Ok(b) => b,
110 Err(e) => {
111 skipped += 1;
112 tracing::warn!(sidecar = %path.display(), error = %e, "add-id reseed: unreadable sidecar; skipping");
113 continue;
114 }
115 };
116 match SidecarV1::from_canonical_slice(&bytes, SIDECAR_SCHEMA_V1) {
117 Ok(sidecar) => {
118 scanned += 1;
119 // Every `AddId`-bearing OR-set on the sidecar — user and AI tags and each
120 // region's labels. The LWW registers (caption, rating, cull, hidden, stack)
121 // stamp `(ts, device_id)` and issue no `add_id`.
122 if let Some(candidate) = sidecar.max_add_counter_for(device) {
123 max = Some(max.map_or(candidate, |m: u64| m.max(candidate)));
124 }
125 }
126 Err(e) => {
127 skipped += 1;
128 tracing::warn!(sidecar = %path.display(), error = %e, "add-id reseed: undecodable sidecar; skipping");
129 }
130 }
131 }
132 tracing::debug!(scanned, skipped, max_issued = ?max, "add-id reseed: sidecar sweep complete");
133 max
134}
135
136/// The extension of an asset's **original** media file in `dir`: the sibling named
137/// `{uuid}.{ext}` that is not one of the sidecar / provenance / receipts / attestations /
138/// metadata-blob artifacts the lifecycle writes beside it.
139pub(super) fn original_extension(dir: &Path, asset_id: &Uuid) -> Option<String> {
140 let prefix = format!("{}.", asset_id.simple());
141 let entries = fs::read_dir(dir).ok()?;
142 for entry in entries.filter_map(std::result::Result::ok) {
143 let name = entry.file_name().to_string_lossy().into_owned();
144 let Some(ext) = name.strip_prefix(&prefix) else {
145 continue;
146 };
147 if matches!(
148 ext,
149 "cbor" | "provenance.cbor" | "receipts.cbor" | "attestations.cbor" | "metadata.bin"
150 ) || std::path::Path::new(ext)
151 .extension()
152 .is_some_and(|e| e.eq_ignore_ascii_case("tmp"))
153 {
154 continue;
155 }
156 return Some(ext.to_string());
157 }
158 None
159}
160
161/// The UTC timestamp of the first instant of the `{YYYY}/{YYYY-MM}` bucket `dir` names — a value
162/// that provably resolves back to `dir` through [`media_dir`], used as the fallback when an
163/// asset's recorded capture time does not.
164pub(super) fn month_dir_timestamp(dir: &Path) -> i64 {
165 let parse = || -> Option<i64> {
166 let name = dir.file_name()?.to_string_lossy().into_owned();
167 let (year, month) = name.split_once('-')?;
168 let date = Date::new(year.parse().ok()?, month.parse().ok()?, 1).ok()?;
169 Some(
170 date.to_zoned_datetime(TimeZone::UTC)
171 .ok()?
172 .timestamp()
173 .as_second(),
174 )
175 };
176 parse().unwrap_or(0)
177}
178
179/// Read a `{uuid}.provenance.cbor` file, replayed through `append` so the chain's own link
180/// invariants are re-checked rather than assumed.
181fn read_chain(provenance_path: &Path) -> Result<ProvenanceChain> {
182 let bytes = fs::read(provenance_path).map_err(|e| LifecycleError::Io(e.to_string()))?;
183 let records: Vec<ProvenanceRecord> =
184 cbor::from_slice(&bytes).map_err(|e| LifecycleError::Cbor(e.to_string()))?;
185 let mut chain = ProvenanceChain::new();
186 for rec in records {
187 chain
188 .append(rec)
189 .map_err(|e| LifecycleError::Cbor(format!("provenance chain: {e}")))?;
190 }
191 Ok(chain)
192}
193
194/// The asset id and kept chain of a purged asset: a provenance chain that reads whole, is
195/// headed by a `delete`, and has neither a sidecar nor an original beside it. `None` for
196/// anything else, which is damage (a lost sidecar of a live, restored or trashed asset, a
197/// corrupt chain) rather than a purge.
198fn purged_chain(provenance_path: &Path, stem: &str) -> Option<(Uuid, ProvenanceChain)> {
199 let dir = provenance_path.parent()?;
200 let asset_id = Uuid::parse_str(stem).ok()?;
201 if provenance_path
202 .with_file_name(format!("{stem}.cbor"))
203 .exists()
204 || original_extension(dir, &asset_id).is_some()
205 {
206 return None;
207 }
208 let chain = read_chain(provenance_path).ok()?;
209 let headed_by_delete = chain.records().last()?.manifest.core.action == Action::Delete;
210 headed_by_delete.then_some((asset_id, chain))
211}
212
213impl Workspace {
214 /// Create a fresh workspace: initialise the library directory and a new account, and
215 /// publish a device directory. `passphrase` guards the on-disk account; `tier` sets the
216 /// Argon2id cost.
217 pub fn create(
218 root: &Path,
219 passphrase: &[u8],
220 tier: capsule_core::crypto::primitives::DeviceTier,
221 ) -> Result<Self> {
222 Self::create_with_params(root, passphrase, tier.params())
223 }
224
225 /// As [`create`](Self::create) but with explicit Argon2id parameters (tests use a fast cost).
226 pub fn create_with_params(
227 root: &Path,
228 passphrase: &[u8],
229 params: capsule_core::crypto::primitives::Argon2Params,
230 ) -> Result<Self> {
231 Self::create_inner(root, passphrase, params, None, None)
232 }
233
234 /// As [`create_with_params`](Self::create_with_params) but signs with a caller-supplied
235 /// device signer — e.g. a [hardware-backed key](capsule_core::crypto::keys::HardwareBackedSigner)
236 /// (Secure Enclave / StrongBox / TPM). The published device directory and every asset
237 /// manifest are then signed by `device_signer`, and its public half is what peers trust.
238 pub fn create_with_hardware_signer(
239 root: &Path,
240 passphrase: &[u8],
241 params: capsule_core::crypto::primitives::Argon2Params,
242 device_signer: Box<dyn Signer>,
243 ) -> Result<Self> {
244 Self::create_inner(root, passphrase, params, Some(device_signer), None)
245 }
246
247 /// As [`create_with_params`](Self::create_with_params) but with the device **signing** key's
248 /// classical half enrolled in `binding`'s secure element over ECDSA-P256, composed with the
249 /// ML-DSA-65 half derived from `ml_seed`. Unlike
250 /// [`create_with_hardware_signer`](Self::create_with_hardware_signer), which signs only for
251 /// the session that created the library, this records the binding (alias, sealed `ml_seed`,
252 /// published key) beside the account, so
253 /// [`open_with_hardware_signer`](Self::open_with_hardware_signer) rebuilds the same key on
254 /// every later launch.
255 ///
256 /// The element is enrolled before anything is written under `root`, so a refusal leaves no
257 /// library behind. Nothing falls back to the software key: a caller that accepts software
258 /// keys calls [`create_with_params`](Self::create_with_params) itself.
259 #[tracing::instrument(skip_all, fields(root = %root.display(), key_alias = %binding.key_alias))]
260 pub fn create_with_p256_hardware_signer(
261 root: &Path,
262 passphrase: &[u8],
263 params: capsule_core::crypto::primitives::Argon2Params,
264 binding: HardwareSignerBinding,
265 ml_seed: &[u8; 32],
266 ) -> Result<Self> {
267 let account = Account::create(crate::ambient::system_ids());
268 let (signer, record) = DeviceSignerRecord::enroll(binding, ml_seed, &account.master)?;
269 let library = crate::library::init::init_library(root, "Capsule")
270 .map_err(|e| LifecycleError::Io(format!("init library: {e}")))?;
271 // Before the account file: a library whose account exists always has its record, and a
272 // record with no account beside it is the leftover the first open removes.
273 record.persist(root)?;
274 Self::finish_create(
275 root,
276 library,
277 passphrase,
278 params,
279 account,
280 Some(Box::new(signer)),
281 )
282 }
283
284 /// As [`create_with_params`](Self::create_with_params) but with the device **encryption** key's
285 /// classical half generated inside `binding`'s secure element and never leaving it.
286 /// The ML-KEM-768 half is software-sealed under the master key as usual, so the account file
287 /// round-trips; reopening the library needs the same element back, via
288 /// [`open_with_hardware_dek`](Self::open_with_hardware_dek).
289 ///
290 /// This is the DEK counterpart of
291 /// [`create_with_hardware_signer`](Self::create_with_hardware_signer); the two are independent
292 /// (an element may back one, the other, or both — see
293 /// [`create_with_hardware_keys`](Self::create_with_hardware_keys)).
294 pub fn create_with_hardware_dek(
295 root: &Path,
296 passphrase: &[u8],
297 params: capsule_core::crypto::primitives::Argon2Params,
298 binding: HardwareDekBinding,
299 ) -> Result<Self> {
300 Self::create_inner(root, passphrase, params, None, Some(binding))
301 }
302
303 /// The general hardware-binding constructor: bind the device signing key, the device
304 /// encryption key, both, or neither. `None`/`None` is exactly
305 /// [`create_with_params`](Self::create_with_params) — the software fallback the design keeps
306 /// for hosts with no secure element.
307 pub fn create_with_hardware_keys(
308 root: &Path,
309 passphrase: &[u8],
310 params: capsule_core::crypto::primitives::Argon2Params,
311 device_signer: Option<Box<dyn Signer>>,
312 dek_binding: Option<HardwareDekBinding>,
313 ) -> Result<Self> {
314 Self::create_inner(root, passphrase, params, device_signer, dek_binding)
315 }
316
317 /// Create a fresh library on a **new device** that opens *as an existing account*: the
318 /// recovery path ("bootstrap a new device via passphrase and escrow", design/backup-recovery).
319 ///
320 /// - `master` is the account master key, e.g. from
321 /// [`recover_master_key`](capsule_core::backup::recover_master_key) over the server escrow;
322 /// - `user_id` is the account's id — the **server's** id for a registered account, so the
323 /// directory and every manifest this library authors name the account the server knows;
324 /// - `sealed_identity` is the account's user identity key sealed under `master`
325 /// ([`Workspace::sealed_identity`] on a device that has it). The IK is random, not derived
326 /// from the master key, and the server pins it on first publish, so a recovered device
327 /// must carry the same one rather than mint its own.
328 ///
329 /// The device is new — a fresh `device_id`, software DSK and software DEK — and the default
330 /// album id is the account's, since it derives from `master`. Album keys are not here: they
331 /// arrive through [`import_backup`](Self::import_backup) or MLS, exactly as on any new device.
332 ///
333 /// Fails with [`CryptoError::Auth`] (before anything is written under `root`) when
334 /// `sealed_identity` was not sealed under `master` — which is also the check that `master`
335 /// is this account's key at all.
336 ///
337 /// The directory this returns lists only the new device, at `directory_version` 1. That is
338 /// **not** publishable on an account that already has a directory: the server refuses it as
339 /// stale, and accepting it would drop every other device. Before publishing, fetch the
340 /// account's signed directory and pass it to
341 /// [`extend_account_directory`](Self::extend_account_directory), then publish what that
342 /// returns.
343 #[tracing::instrument(skip_all, fields(root = %root.display(), user_id = %user_id))]
344 pub fn create_from_master(
345 root: &Path,
346 passphrase: &[u8],
347 params: capsule_core::crypto::primitives::Argon2Params,
348 master: capsule_core::crypto::keys::MasterKey,
349 user_id: Uuid,
350 sealed_identity: &[u8],
351 ) -> Result<Self> {
352 let user_ik = Account::open_sealed_identity(&master, sealed_identity).inspect_err(|e| {
353 tracing::warn!(error = %e, "workspace create from master: the sealed identity did not open");
354 })?;
355 let account = Account::from_parts(
356 crate::ambient::system_ids(),
357 user_id,
358 master,
359 user_ik,
360 capsule_core::crypto::keys::DeviceDek::Software(
361 capsule_core::crypto::keys::DekKeypair::generate(),
362 ),
363 );
364 let library = crate::library::init::init_library(root, "Capsule")
365 .map_err(|e| LifecycleError::Io(format!("init library: {e}")))?;
366 tracing::info!(
367 device = %account.device.device_id,
368 "workspace create from master: a new device of an existing account"
369 );
370 Self::finish_create(root, library, passphrase, params, account, None)
371 }
372
373 /// Rebind this library to the account id the **server** assigned at registration.
374 ///
375 /// A library mints its own `user_id` when it is created; a server mints another when the
376 /// account registers, and refuses a device directory or a manifest that names any id but its
377 /// own. This adopts the server's id: the account file is rewritten (the id is stored beside
378 /// the wrapped keys, not inside them, so no passphrase is needed) and the device directory is
379 /// re-signed at the next `directory_version` naming it.
380 ///
381 /// Refused with [`LifecycleError::AccountRebind`] once the library holds any asset: every
382 /// manifest already signed names the old id as `created_by_user`, and rebinding under them
383 /// would leave a library whose history contradicts its own account. Binding the same id again
384 /// is a no-op.
385 #[tracing::instrument(skip_all, fields(from = %self.account.user_id, to = %user_id))]
386 pub fn bind_account_id(&mut self, user_id: Uuid) -> Result<()> {
387 if self.account.user_id == user_id {
388 // An earlier bind may have rewritten the account file and failed to persist the
389 // re-signed directory; this retry is what writes it, so the next open restores it
390 // rather than re-signing the stale one.
391 if Self::persisted_directory_is(&self.root, &self.directory) {
392 tracing::debug!("account id already bound; nothing to do");
393 return Ok(());
394 }
395 tracing::info!(
396 directory_version = self.directory.core.directory_version,
397 "account id already bound; persisting the directory an earlier bind failed to write"
398 );
399 return Self::persist_directory(&self.root, &self.directory);
400 }
401 if !self.assets.is_empty() {
402 tracing::warn!(
403 assets = self.assets.len(),
404 "account rebind refused: the library already authored assets under its old id"
405 );
406 return Err(LifecycleError::AccountRebind(format!(
407 "{} asset(s) already name {} as created_by_user",
408 self.assets.len(),
409 self.account.user_id
410 )));
411 }
412 let path = self.root.join(".library").join("account.cbor");
413 let bytes = fs::read(&path).map_err(|e| LifecycleError::Io(e.to_string()))?;
414 let mut file: AccountFile =
415 cbor::from_slice(&bytes).map_err(|e| LifecycleError::Cbor(e.to_string()))?;
416 file.user_id = user_id;
417 let bytes =
418 cbor::to_canonical_vec(&file).map_err(|e| LifecycleError::Cbor(e.to_string()))?;
419 // Temp-then-rename: this file is the only local wrapped copy of the master and identity
420 // keys, so a crash mid-write must leave the old file intact rather than truncated.
421 let tmp = crate::utils::paths::tmp_path(&path);
422 fs::write(&tmp, &bytes).map_err(|e| LifecycleError::Io(e.to_string()))?;
423 fs::rename(&tmp, &path).map_err(|e| LifecycleError::Io(e.to_string()))?;
424
425 self.account.user_id = user_id;
426 let mut core = self.directory.core.clone();
427 core.user_id = user_id;
428 core.directory_version += 1;
429 core.updated_at = now_rfc3339();
430 // Adopted in memory before it is persisted, unlike the other directory changes: the
431 // account file above already names the new id, so a retry is a no-op and memory must not
432 // keep a directory naming the old one. Should this write fail, a retry with the same id
433 // writes it; failing that, the next open finds the directory naming the old id, signed
434 // by this account's IK, and re-signs it under the new id at the next version, keeping
435 // every device it lists (`restore_directory`).
436 self.directory = core.sign(&self.account.user_ik);
437 tracing::info!(
438 directory_version = self.directory.core.directory_version,
439 "account rebound to the server-assigned id"
440 );
441 Self::persist_directory(&self.root, &self.directory)
442 }
443
444 /// Build this device's directory on the account's **published** one instead of replacing it
445 /// (#550): the step a device that joined an existing account — a recovered device from
446 /// [`create_from_master`](Self::create_from_master) — takes before it publishes.
447 ///
448 /// `published` is the account's current signed directory as the server serves it. It is
449 /// verified under this workspace's user IK (the one opened from the sealed identity) and must
450 /// name this workspace's account; then this device's own entry is appended at
451 /// `published.directory_version + 1`, the result is re-signed under the user IK, adopted as
452 /// this workspace's directory, and returned for publication. Every device `published` lists
453 /// is kept, revoked entries included.
454 ///
455 /// Returns `Ok(None)` when `published` already lists this device under the signing key it
456 /// signs with: the published directory is adopted unchanged and there is nothing to publish.
457 /// A recovered device that extends again after publishing lands here. Either way the adopted
458 /// directory is persisted, so [`open`](Self::open) restores it.
459 ///
460 /// Refused, leaving this workspace's directory unchanged, with
461 /// [`LifecycleError::UntrustedDirectory`] when `published` does not verify or names another
462 /// account, and with [`LifecycleError::Directory`] when it lists this device's id under
463 /// another key (or revoked), lists this device's signing key under another id, or its version
464 /// cannot advance.
465 #[tracing::instrument(
466 skip_all,
467 fields(
468 user_id = %self.account.user_id,
469 device_id = %self.account.device.device_id,
470 published_version = published.core.directory_version,
471 )
472 )]
473 pub fn extend_account_directory(
474 &mut self,
475 published: &DeviceDirectory,
476 ) -> Result<Option<DeviceDirectory>> {
477 if !published.verify(&self.account.user_ik.verifying_key()) {
478 tracing::warn!("account directory refused: it does not verify under the user IK");
479 return Err(LifecycleError::UntrustedDirectory(
480 "the signature does not verify under this account's user identity key".into(),
481 ));
482 }
483 if published.core.user_id != self.account.user_id {
484 tracing::warn!(
485 published_user = %published.core.user_id,
486 "account directory refused: it names another account"
487 );
488 return Err(LifecycleError::UntrustedDirectory(format!(
489 "it names account {}, not {}",
490 published.core.user_id, self.account.user_id
491 )));
492 }
493
494 let device_id = self.account.device.device_id;
495 let own = self.directory.device(&device_id).cloned().ok_or_else(|| {
496 LifecycleError::NotFound(format!("device {device_id} in its own directory"))
497 })?;
498 if published.device(&device_id).is_some_and(|listed| {
499 listed.dsk_public == own.dsk_public && listed.revoked_at.is_none()
500 }) {
501 self.adopt_directory(published.clone())?;
502 tracing::info!(
503 directory_version = published.core.directory_version,
504 devices = published.core.devices.len(),
505 "account directory already lists this device; adopted unchanged"
506 );
507 return Ok(None);
508 }
509
510 let mut core = published.core.clone();
511 core.add_device(own, now_rfc3339()).inspect_err(|e| {
512 tracing::warn!(error = %e, "account directory refused: this device cannot be appended");
513 })?;
514 self.adopt_directory(core.sign(&self.account.user_ik))?;
515 tracing::info!(
516 directory_version = self.directory.core.directory_version,
517 devices = self.directory.core.devices.len(),
518 "account directory extended with this device"
519 );
520 Ok(Some(self.directory.clone()))
521 }
522
523 fn create_inner(
524 root: &Path,
525 passphrase: &[u8],
526 params: capsule_core::crypto::primitives::Argon2Params,
527 device_signer: Option<Box<dyn Signer>>,
528 dek_binding: Option<HardwareDekBinding>,
529 ) -> Result<Self> {
530 let library = crate::library::init::init_library(root, "Capsule")
531 .map_err(|e| LifecycleError::Io(format!("init library: {e}")))?;
532 let account = match dek_binding {
533 Some(binding) => {
534 tracing::info!(
535 key_alias = %binding.key_alias,
536 "workspace create: enrolling the device encryption key's classical half in the \
537 secure element"
538 );
539 Account::create_with_hardware_dek(
540 crate::ambient::system_ids(),
541 binding.element,
542 binding.key_alias,
543 )
544 .map_err(|e| {
545 // The element's own reason (unavailable / cancelled / backend) is the only
546 // thing that tells an operator whether to retry, so it is logged before it
547 // is flattened into the `&'static str` the crypto error carries.
548 tracing::error!(error = %e, "workspace create: hardware DEK enrollment failed");
549 CryptoError::Key("hardware DEK enrollment failed")
550 })?
551 }
552 None => Account::create(crate::ambient::system_ids()),
553 };
554 Self::finish_create(root, library, passphrase, params, account, device_signer)
555 }
556
557 /// The tail every `create*` constructor shares once it holds an initialised `library` and an
558 /// unlocked `account`: persist the account and an empty album keystore, sign the device
559 /// directory, and assemble the workspace.
560 fn finish_create(
561 root: &Path,
562 library: crate::library::Library,
563 passphrase: &[u8],
564 params: capsule_core::crypto::primitives::Argon2Params,
565 account: Account,
566 device_signer: Option<Box<dyn Signer>>,
567 ) -> Result<Self> {
568 let file = account.to_file_with(passphrase, params)?;
569 let acct_bytes =
570 cbor::to_canonical_vec(&file).map_err(|e| LifecycleError::Cbor(e.to_string()))?;
571 fs::write(root.join(".library").join("account.cbor"), &acct_bytes)
572 .map_err(|e| LifecycleError::Io(e.to_string()))?;
573
574 // The album keystore exists from day one, even empty: a library whose `albums.cbor` is
575 // simply absent is indistinguishable from one written before keys were durable, and
576 // `open` treats that as "keys were never persisted" rather than "there are no albums
577 // yet".
578 AlbumStore::new().save(root, &account.master)?;
579
580 // Default to the account's own software DSK; a hardware signer overrides it.
581 let device_signer: Box<dyn Signer> =
582 device_signer.unwrap_or_else(|| Box::new(account.device.dsk.clone()));
583 let directory = Self::build_directory(&account, device_signer.verifying_key());
584 Self::persist_directory(root, &directory)?;
585 // A freshly minted `device_id` over a freshly initialised (provably empty) library has
586 // provably issued no `add_id`, so it starts at zero with no sweep — the one case the
587 // add-id durability rule licenses a reset. Every *re*-open goes through
588 // [`open`](Self::open), which reseeds from the sidecars on disk.
589 let counter = Counter::new(account.device.device_id);
590 Ok(Self {
591 root: root.to_path_buf(),
592 account,
593 device_signer,
594 directory,
595 client_version: capsule_core::client_build::core_client_version(),
596 counter,
597 albums: HashMap::new(),
598 authorities: HashMap::new(),
599 assets: HashMap::new(),
600 group_assertions: HashMap::new(),
601 library,
602 argon2_params: params,
603 share_links: HashMap::new(),
604 upload_links: HashMap::new(),
605 inbox: HashMap::new(),
606 unanchored: Vec::new(),
607 purged: BTreeMap::new(),
608 })
609 }
610
611 /// Set the reporting client identity every manifest and derivative this workspace authors
612 /// carries: `client_id` names the product (`capsule-cli`, `capsule-ios`, …) and
613 /// `semver` is that client's own version. The build-embedded commit + dirty flag are appended
614 /// per the [`client_version` grammar](capsule_core::client_build), so an in-repo app supplies only
615 /// its id and version. Without this, a workspace reports the bare-core
616 /// `capsule-core/{semver}+{commit}` default.
617 #[must_use]
618 pub fn with_client_id(mut self, client_id: &str, semver: &str) -> Self {
619 self.client_version = capsule_core::client_build::client_version(client_id, semver);
620 self
621 }
622
623 /// Open an **existing** library at `root` as a signed workspace, unlocking (or, on first use,
624 /// creating + persisting) the account under `passphrase`. `params` sets the Argon2id cost for
625 /// a first-time account and the share-link wrap tier.
626 ///
627 /// This restores the workspace's durable state rather than starting empty:
628 ///
629 /// - **album keys + authorities** from the sealed [`AlbumStore`], so a reopened library can
630 /// decrypt and keep writing into the albums it already has;
631 /// - **every managed asset** from its signed artifacts on disk (chain, sidecar, sealed
632 /// metadata blob), a `warn`-and-skip per asset rather than a failed open;
633 /// - **the `add_id` counter**, reseeded past everything this device has ever written;
634 /// - **the signed device directory** from `{root}/.library/directory.cbor` (#562), once it
635 /// verifies under the user IK and lists this device live (re-signed under this account's
636 /// id at the next version when it still names the id from before a rebind); otherwise a
637 /// fresh version-1 directory listing only this device, with a `warn` naming why.
638 ///
639 /// A library with no `albums.cbor` predates this and opens with zero albums plus a `warn`
640 /// naming backup restore — see [`AlbumStore::load`].
641 ///
642 /// A library holding sidecars **no provenance chain anchors** — an interrupted write, a
643 /// torn or foreign file, a retired unsigned pre-signed-path record — still opens: those
644 /// assets are not restored, but each is reported through
645 /// [`unanchored_sidecars`](Self::unanchored_sidecars) with a `warn`, and never touched.
646 ///
647 /// Still session-scoped by design, and dropped on close: the federation group assertions
648 /// (re-delivered by the feed), the pending guest-drop inbox (server-authoritative), and the
649 /// issued share/upload link records — see the [`Workspace`] fields for why each is deferred.
650 ///
651 /// A library whose device signing key is hardware-bound is refused here; it opens through
652 /// [`open_with_hardware_signer`](Self::open_with_hardware_signer).
653 pub fn open(
654 root: &Path,
655 passphrase: &[u8],
656 params: capsule_core::crypto::primitives::Argon2Params,
657 ) -> Result<Self> {
658 Self::open_inner(root, passphrase, params, None, None)
659 }
660
661 /// As [`open`](Self::open), re-attaching the secure element that holds this device's
662 /// hardware-bound DEK. Required for a library created by
663 /// [`create_with_hardware_dek`](Self::create_with_hardware_dek): its DEK's classical half is
664 /// non-exportable, so plain [`open`](Self::open) refuses it rather than degrading to software.
665 ///
666 /// Safe to call for a software-DEK library too — the binding recorded in the account file
667 /// decides, and a software account simply ignores the element. On a **first** open of an
668 /// empty library (no account yet) the fresh account is created hardware-bound under
669 /// `binding.key_alias`.
670 pub fn open_with_hardware_dek(
671 root: &Path,
672 passphrase: &[u8],
673 params: capsule_core::crypto::primitives::Argon2Params,
674 binding: HardwareDekBinding,
675 ) -> Result<Self> {
676 Self::open_inner(root, passphrase, params, Some(binding), None)
677 }
678
679 /// As [`open`](Self::open), re-attaching the secure element that holds this device's
680 /// hardware-bound **signing** key. Required for a library created by
681 /// [`create_with_p256_hardware_signer`](Self::create_with_p256_hardware_signer): the element
682 /// is asked for the key under the alias the library recorded, the ML-DSA-65 half is rebuilt
683 /// from its sealed seed, and the result must be the key this device published. Plain
684 /// [`open`](Self::open) refuses such a library rather than signing with the software key,
685 /// which would change the key the device directory publishes.
686 ///
687 /// The recorded binding decides, never the caller: a library with no record (every library
688 /// created with the software key, including those from before this binding existed) opens
689 /// on its software key and ignores the element. On a **first** open of an empty library (no
690 /// account yet) the fresh account's signing key is enrolled in the element under
691 /// `binding.key_alias` with a freshly drawn ML-DSA-65 seed.
692 ///
693 /// Refused with [`CryptoError::Key`] when the element does not hold the recorded key (it was
694 /// removed, or the element is unavailable) or holds another key under that alias; the element
695 /// is never asked to mint a replacement.
696 #[tracing::instrument(skip_all, fields(root = %root.display()))]
697 pub fn open_with_hardware_signer(
698 root: &Path,
699 passphrase: &[u8],
700 params: capsule_core::crypto::primitives::Argon2Params,
701 binding: HardwareSignerBinding,
702 ) -> Result<Self> {
703 Self::open_inner(root, passphrase, params, None, Some(binding))
704 }
705
706 fn open_inner(
707 root: &Path,
708 passphrase: &[u8],
709 params: capsule_core::crypto::primitives::Argon2Params,
710 dek_binding: Option<HardwareDekBinding>,
711 signer_binding: Option<HardwareSignerBinding>,
712 ) -> Result<Self> {
713 let library = crate::library::open_library(root)?;
714 let account_path = root.join(".library").join("account.cbor");
715 let (account, device_signer) = if account_path.exists() {
716 let bytes = fs::read(&account_path).map_err(|e| LifecycleError::Io(e.to_string()))?;
717 let file: AccountFile =
718 cbor::from_slice(&bytes).map_err(|e| LifecycleError::Cbor(e.to_string()))?;
719 let account = file.unlock_with_element(passphrase, dek_binding.map(|b| b.element))?;
720 let device_signer = Self::reopen_device_signer(root, &account, signer_binding)?;
721 (account, device_signer)
722 } else {
723 let account = match dek_binding {
724 Some(binding) => Account::create_with_hardware_dek(
725 crate::ambient::system_ids(),
726 binding.element,
727 binding.key_alias,
728 )
729 .map_err(|e| {
730 tracing::error!(error = %e, "workspace open: hardware DEK enrollment failed");
731 CryptoError::Key("hardware DEK enrollment failed")
732 })?,
733 None => Account::create(crate::ambient::system_ids()),
734 };
735 // Any record here was left by a creation that stopped before its account file was
736 // written; it is sealed under a master key nothing holds, so it is replaced or
737 // removed, and always before the account file is written.
738 let device_signer: Box<dyn Signer> = if let Some(binding) = signer_binding {
739 let ml_seed = capsule_core::crypto::rng::random_array::<32>();
740 let (signer, record) =
741 DeviceSignerRecord::enroll(binding, &ml_seed, &account.master)?;
742 record.persist(root)?;
743 Box::new(signer)
744 } else {
745 DeviceSignerRecord::remove_stale(root)?;
746 Box::new(account.device.dsk.clone())
747 };
748 let file = account.to_file_with(passphrase, params)?;
749 let acct_bytes =
750 cbor::to_canonical_vec(&file).map_err(|e| LifecycleError::Cbor(e.to_string()))?;
751 fs::write(&account_path, &acct_bytes).map_err(|e| LifecycleError::Io(e.to_string()))?;
752 // First use of this library: seed an empty album keystore alongside the account, so
753 // the next open sees "no albums yet" rather than the keys-never-persisted migration
754 // case.
755 AlbumStore::new().save(root, &account.master)?;
756 (account, device_signer)
757 };
758
759 let dsk_public = device_signer.verifying_key();
760 let built = Self::build_directory(&account, dsk_public.clone());
761 // #562: the directory this device last signed — cross-signed devices, a rebound id, an
762 // extension of the account's published one — survives the close.
763 let directory = Self::restore_directory(root, &account, &dsk_public, built);
764 let user_id = account.user_id;
765 // Reseed the `add_id` counter to one past the maximum this device has ever
766 // written, recovered from its own signed sidecars. Without this a reopened library
767 // reissues counters from zero and aliases two distinct OR-set adds.
768 let device_id = account.device.device_id;
769 let mut counter = Counter::new(device_id);
770 counter.reseed_from_max(sweep_max_add_counter(root, &device_id));
771 tracing::info!(
772 device = %device_id,
773 next_add_counter = counter.peek(),
774 "workspace open: add-id counter reseeded"
775 );
776 let mut ws = Self {
777 root: root.to_path_buf(),
778 account,
779 device_signer,
780 directory,
781 client_version: capsule_core::client_build::core_client_version(),
782 counter,
783 albums: HashMap::new(),
784 authorities: HashMap::new(),
785 assets: HashMap::new(),
786 group_assertions: HashMap::new(),
787 library,
788 argon2_params: params,
789 share_links: HashMap::new(),
790 upload_links: HashMap::new(),
791 inbox: HashMap::new(),
792 unanchored: Vec::new(),
793 purged: BTreeMap::new(),
794 };
795 // Album keys, authorities, and every managed asset come back from disk here.
796 // Without this the reopened workspace would hold an unlocked account and nothing else.
797 ws.restore_durable_state()?;
798 // After the restore, which is what knows every bundle on disk: index the ones an
799 // interrupted import left without a catalog row.
800 ws.reconcile_index();
801 tracing::info!(
802 user_id = %user_id,
803 albums = ws.albums.len(),
804 assets = ws.assets.len(),
805 "workspace opened"
806 );
807 Ok(ws)
808 }
809
810 /// The signer an existing account reopens with: the hardware key its record describes,
811 /// re-attached through `binding`'s element, or the account's software DSK when the library
812 /// has no record. A recorded library opened without an element is refused, never moved onto
813 /// the software key.
814 fn reopen_device_signer(
815 root: &Path,
816 account: &Account,
817 binding: Option<HardwareSignerBinding>,
818 ) -> Result<Box<dyn Signer>> {
819 let Some(record) = DeviceSignerRecord::load(root)? else {
820 if binding.is_some() {
821 tracing::info!(
822 "workspace open: this library signs with its software key; the offered \
823 secure element is not used"
824 );
825 }
826 return Ok(Box::new(account.device.dsk.clone()));
827 };
828 let Some(binding) = binding else {
829 tracing::error!(
830 "workspace open: this library's device signing key is hardware-bound and no \
831 secure element was supplied; refusing rather than signing with another key"
832 );
833 return Err(CryptoError::Key(
834 "this library's device signing key is hardware-bound: a HardwareSigner element \
835 is required to open it",
836 )
837 .into());
838 };
839 if binding.key_alias != record.key_alias() {
840 tracing::warn!(
841 offered = %binding.key_alias,
842 recorded = %record.key_alias(),
843 "workspace open: the offered alias differs from the recorded one; the recorded alias is used"
844 );
845 }
846 Ok(Box::new(record.reattach(&account.master, binding.element)?))
847 }
848
849 /// Restore the durable half of the workspace after unlocking the account:
850 /// album key material + authorities from `{root}/.library/albums.cbor`, then every managed
851 /// asset's in-memory state from the artifacts on disk.
852 ///
853 /// **Migration.** A library with no `albums.cbor` predates durable album keys: its keys
854 /// were session-scoped and therefore never written anywhere. It opens with zero albums and a
855 /// `warn` naming backup restore as the recovery path. That is not a regression introduced
856 /// here: those assets were already undecryptable across a restart, because the only copy of
857 /// their AMK died with the process that minted it.
858 #[tracing::instrument(skip_all, fields(root = %self.root.display()))]
859 fn restore_durable_state(&mut self) -> Result<()> {
860 // A read failure here — wrong master key, tampered file, unsupported version — is fatal
861 // rather than a warn: silently continuing with zero albums would look exactly like the
862 // migration case above and would let a subsequent `create_album` overwrite the store.
863 if let Some(store) = AlbumStore::load(&self.root, &self.account.master)? {
864 self.apply_album_store(&store);
865 } else {
866 tracing::warn!(
867 path = %AlbumStore::path(&self.root).display(),
868 "no album keystore: this library predates durable album keys, so it opens \
869 with zero albums. Its existing assets can only be recovered through a backup \
870 artifact (`import_backup`), which escrows their AMKs."
871 );
872 }
873 self.restore_assets();
874 Ok(())
875 }
876
877 /// Rebuild `self.assets` by walking the signed artifacts under `root/media`.
878 ///
879 /// The provenance chain is the per-asset anchor: one `{uuid}.provenance.cbor` is one managed
880 /// asset, and its head manifest names the owning album. The sidecar, the sealed metadata blob,
881 /// and the original bytes are read from its siblings; the queryable index row supplies only
882 /// stack placement, which lives nowhere else.
883 ///
884 /// The filesystem, not the SQLite index, is the source of truth here for the same
885 /// recovery-first reason [`rebuild_index`](crate::library::rebuild_index) exists: an
886 /// index can be rebuilt from the signed artifacts, but an artifact the index has forgotten is
887 /// gone. A missing or undecodable piece for one asset is a `warn` and a skip — never a failed
888 /// open, which would take the whole library down for one bad file.
889 fn restore_assets(&mut self) {
890 let media = self.root.join("media");
891 if !media.exists() {
892 return;
893 }
894 let mut restored = 0usize;
895 let mut skipped = 0usize;
896 let mut purged = 0usize;
897 for entry in WalkDir::new(&media)
898 .into_iter()
899 .filter_map(std::result::Result::ok)
900 {
901 let path = entry.path();
902 if !path.is_file() {
903 continue;
904 }
905 let name = path.file_name().unwrap_or_default().to_string_lossy();
906 let Some(stem) = name.strip_suffix(".provenance.cbor") else {
907 continue;
908 };
909 match self.restore_one_asset(path, stem) {
910 Ok(asset) => {
911 restored += 1;
912 tracing::trace!(asset_id = %asset.asset_id, album_id = %asset.album_id, "asset restored");
913 self.assets.insert(asset.asset_id, asset);
914 }
915 // A purge keeps the chain, ends it with a `delete`, and removes the sidecar and
916 // the original (`Workspace::purge`): a chain headed by a `delete` with no
917 // sidecar beside it is that record, not damage. Anything else falls through to
918 // the warning below.
919 Err(e) => {
920 if let Some((asset_id, chain)) = purged_chain(path, stem) {
921 purged += 1;
922 tracing::trace!(provenance = %path.display(), %asset_id, records = chain.records().len(), restore_error = %e, "workspace open: purged asset; only its provenance chain is kept");
923 self.purged.insert(asset_id, chain);
924 } else {
925 skipped += 1;
926 tracing::warn!(
927 provenance = %path.display(),
928 error = %e,
929 "workspace open: could not restore this asset; skipping it"
930 );
931 }
932 }
933 }
934 }
935 tracing::info!(
936 restored,
937 skipped,
938 purged,
939 "workspace open: assets restored from disk"
940 );
941
942 // Second pass: the sidecars no chain anchors. A signed sidecar without one is a write
943 // interrupted before its chain landed; anything else is torn, foreign, or a retired
944 // unsigned record. None is restorable here — open must not author signed records
945 // unasked — so each is recorded and named, never silently dropped.
946 self.unanchored = find_unanchored(&self.root);
947 for found in &self.unanchored {
948 tracing::warn!(
949 sidecar = %found.path.display(),
950 asset_id = ?found.asset_id,
951 shape = ?found.shape,
952 "workspace open: sidecar with no provenance chain; the asset is invisible"
953 );
954 }
955 if !self.unanchored.is_empty() {
956 tracing::info!(
957 unanchored = self.unanchored.len(),
958 "workspace open: sidecars with no provenance chain found; left untouched"
959 );
960 }
961 }
962
963 /// Index every restored asset the catalog has no `assets` row for.
964 ///
965 /// An import makes its bundle durable — original, sidecar, chain, directory fsync — before
966 /// it writes index rows, and a bulk import commits those rows once per batch, so a crash in
967 /// between leaves bundles this workspace restores but no view can see. This closes that
968 /// window on the next open, through the same per-asset path
969 /// [`rebuild_index`](crate::library::rebuild_index) uses, plus the device-owned original's
970 /// cache row the import would have written.
971 ///
972 /// Cheap when nothing is missing: one key-only `SELECT uuid FROM assets` compared against
973 /// the ids already restored in memory; no file is re-read unless its id is missing. A
974 /// failure is a `warn`, never a failed open — the bundles are intact and the next open
975 /// retries.
976 #[tracing::instrument(skip_all, fields(root = %self.root.display(), restored = self.assets.len()))]
977 pub(super) fn reconcile_index(&self) {
978 let indexed = match self.library.db.asset_ids() {
979 Ok(ids) => ids,
980 Err(e) => {
981 tracing::warn!(error = %e, "reconcile: could not list indexed assets; skipping");
982 return;
983 }
984 };
985 let missing: Vec<&AssetState> = self
986 .assets
987 .values()
988 .filter(|asset| !indexed.contains(&asset.asset_id.to_string()))
989 .collect();
990 if missing.is_empty() {
991 tracing::debug!(
992 indexed = indexed.len(),
993 "reconcile: every restored asset has an index row"
994 );
995 return;
996 }
997 for asset in &missing {
998 tracing::debug!(
999 asset_id = %asset.asset_id,
1000 album_id = %asset.album_id,
1001 "reconcile: bundle on disk has no index row"
1002 );
1003 }
1004 let sidecars: Vec<PathBuf> = missing.iter().map(|a| self.sidecar_path(a)).collect();
1005 let reindexed = match crate::library::rebuild::reindex_sidecars(&self.library, &sidecars) {
1006 Ok(ids) => ids.into_iter().collect::<std::collections::HashSet<Uuid>>(),
1007 Err(e) => {
1008 tracing::warn!(
1009 missing = missing.len(),
1010 error = %e,
1011 "reconcile: re-indexing unindexed bundles failed; the next open retries"
1012 );
1013 return;
1014 }
1015 };
1016 for asset in missing
1017 .iter()
1018 .filter(|asset| reindexed.contains(&asset.asset_id))
1019 {
1020 let bytes = asset
1021 .chain
1022 .records()
1023 .last()
1024 .map_or(0, |head| head.manifest.core.plaintext_size);
1025 if let Err(e) = self
1026 .index_original_representation(asset, usize::try_from(bytes).unwrap_or(usize::MAX))
1027 {
1028 tracing::warn!(
1029 asset_id = %asset.asset_id,
1030 error = %e,
1031 "reconcile: original's cache row not written; the asset is indexed"
1032 );
1033 }
1034 }
1035 tracing::info!(
1036 missing = missing.len(),
1037 reconciled = reindexed.len(),
1038 "reconcile: unindexed bundles re-indexed from their sidecars"
1039 );
1040 }
1041
1042 fn restore_one_asset(&self, provenance_path: &Path, stem: &str) -> Result<AssetState> {
1043 let asset_id = Uuid::parse_str(stem)
1044 .map_err(|e| LifecycleError::NotFound(format!("asset id in {stem}: {e}")))?;
1045 let dir = provenance_path
1046 .parent()
1047 .ok_or_else(|| LifecycleError::Io("provenance file has no parent".into()))?;
1048
1049 // (1) The provenance chain — the anchor.
1050 let chain = read_chain(provenance_path)?;
1051 let head = &chain
1052 .records()
1053 .last()
1054 .ok_or_else(|| LifecycleError::Cbor("empty provenance chain".into()))?
1055 .manifest;
1056 let album_id = head.core.album_id;
1057
1058 // (2) The signed sidecar.
1059 let sidecar_bytes = fs::read(dir.join(format!("{}.cbor", asset_id.simple())))
1060 .map_err(|e| LifecycleError::Io(format!("sidecar: {e}")))?;
1061 let sidecar = SidecarV1::from_canonical_slice(&sidecar_bytes, SIDECAR_SCHEMA_V1)
1062 .map_err(LifecycleError::Cbor)?;
1063
1064 // (3) `capture_utc` decides which media directory every subsequent write for this asset
1065 // resolves to, so it must reproduce the directory the files were actually found in. The
1066 // sidecar's own capture timestamp is the value the import used; if it disagrees with the
1067 // directory (a library written by an older build), fall back to the directory itself so
1068 // the paths keep resolving, and say so.
1069 let mut capture_utc = sidecar
1070 .capture_timestamp
1071 .parse::<jiff::Timestamp>()
1072 .map_or(0, |t: jiff::Timestamp| t.as_second());
1073 if media_dir(&self.root, capture_utc) != dir {
1074 let from_dir = month_dir_timestamp(dir);
1075 tracing::warn!(
1076 asset_id = %asset_id,
1077 sidecar_capture = %sidecar.capture_timestamp,
1078 dir = %dir.display(),
1079 "asset's capture timestamp does not resolve to its own media directory; \
1080 using the directory's month so its files stay reachable"
1081 );
1082 capture_utc = from_dir;
1083 }
1084
1085 // (4) The original's extension: the sibling that is neither a sidecar, a provenance
1086 // chain, a receipt log, nor the sealed metadata blob.
1087 let ext = original_extension(dir, &asset_id).ok_or_else(|| {
1088 LifecycleError::NotFound(format!("original media file for asset {asset_id}"))
1089 })?;
1090
1091 // (5) The sealed metadata blob. Absence is tolerated: libraries written before album
1092 // keys were durable never persisted it. Such an asset reads and verifies fine; only
1093 // `export_backup` and upload need the blob, and both fail loudly on the empty value
1094 // rather than shipping a wrong one.
1095 let blob_path = dir.join(format!("{}.metadata.bin", asset_id.simple()));
1096 let metadata_blob = match fs::read(&blob_path) {
1097 Ok(b) => b,
1098 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1099 tracing::warn!(
1100 asset_id = %asset_id,
1101 "no sealed metadata blob on disk (asset written before sealed metadata existed); it cannot be exported or \
1102 uploaded until its metadata is rewritten"
1103 );
1104 Vec::new()
1105 }
1106 Err(e) => return Err(LifecycleError::Io(format!("metadata blob: {e}"))),
1107 };
1108
1109 // (6) Stack placement. The durable record is the sidecar's signed
1110 // `stack_membership` register, so a written register is authoritative — `Some` is a
1111 // placement, a stamped `None` an explicit departure from a stack. Reading the index is
1112 // the compatibility path for an asset imported before that register existed, whose
1113 // placement was written only as `assets.stack_id` / `is_stack_hidden` and exists
1114 // nowhere else.
1115 let stack = match sidecar.stack_membership.get() {
1116 Some(membership) => membership.as_ref().map(StackPlacement::from_membership),
1117 None => self
1118 .library
1119 .db
1120 .find_by_uuid(&asset_id.to_string())
1121 .ok()
1122 .flatten()
1123 .and_then(|row| {
1124 row.stack_id.map(|stack_id| StackPlacement {
1125 stack_id,
1126 hidden: row.is_stack_hidden,
1127 })
1128 }),
1129 };
1130
1131 Ok(AssetState {
1132 asset_id,
1133 album_id,
1134 ext,
1135 capture_utc,
1136 chain,
1137 sidecar,
1138 metadata_blob,
1139 stack,
1140 })
1141 }
1142
1143 fn build_directory(account: &Account, dsk_public: HybridVerifyingKey) -> DeviceDirectory {
1144 DirectoryCore {
1145 user_id: account.user_id,
1146 directory_version: 1,
1147 updated_at: now_rfc3339(),
1148 devices: vec![DeviceEntry {
1149 device_id: account.device.device_id,
1150 dsk_public,
1151 // The published half of this device's encryption key, so a peer can encapsulate
1152 // to it using the directory alone. `public_bytes()` is the single seam for both
1153 // compositions and the recipient tells them apart by length, which is why
1154 // nothing here says which one it is holding.
1155 dek_public: Some(DekPublic(account.device.dek.public_bytes())),
1156 added_at: DEVICE_ADDED_AT.into(),
1157 revoked_at: None,
1158 unknown: Default::default(),
1159 }],
1160 unknown: Default::default(),
1161 }
1162 .sign(&account.user_ik)
1163 }
1164
1165 /// Where this library keeps its signed device directory: beside `account.cbor` (#562).
1166 pub(super) fn directory_path(root: &Path) -> PathBuf {
1167 root.join(".library").join(DIRECTORY_FILE)
1168 }
1169
1170 /// Write `directory` to [`directory_path`](Self::directory_path), temp-then-rename like
1171 /// `account.cbor`, so a crash mid-write leaves the previous directory intact rather than a
1172 /// truncated one that would no longer verify.
1173 fn persist_directory(root: &Path, directory: &DeviceDirectory) -> Result<()> {
1174 let path = Self::directory_path(root);
1175 let bytes =
1176 cbor::to_canonical_vec(directory).map_err(|e| LifecycleError::Cbor(e.to_string()))?;
1177 let tmp = crate::utils::paths::tmp_path(&path);
1178 fs::write(&tmp, &bytes).map_err(|e| LifecycleError::Io(e.to_string()))?;
1179 fs::rename(&tmp, &path).map_err(|e| LifecycleError::Io(e.to_string()))?;
1180 tracing::debug!(
1181 directory_version = directory.core.directory_version,
1182 devices = directory.core.devices.len(),
1183 "device directory persisted"
1184 );
1185 Ok(())
1186 }
1187
1188 /// Whether the directory file at `root` already holds exactly `directory`.
1189 fn persisted_directory_is(root: &Path, directory: &DeviceDirectory) -> bool {
1190 let Ok(on_disk) = fs::read(Self::directory_path(root)) else {
1191 return false;
1192 };
1193 cbor::to_canonical_vec(directory).is_ok_and(|bytes| bytes == on_disk)
1194 }
1195
1196 /// Persist `directory` and only then adopt it as this workspace's directory, so a failed
1197 /// write leaves memory and disk agreeing on the previous one.
1198 pub(super) fn adopt_directory(&mut self, directory: DeviceDirectory) -> Result<()> {
1199 Self::persist_directory(&self.root, &directory).inspect_err(|e| {
1200 tracing::warn!(error = %e, "device directory not adopted: persisting it failed");
1201 })?;
1202 self.directory = directory;
1203 Ok(())
1204 }
1205
1206 /// The directory a reopened workspace starts from (#562): the persisted one when it is
1207 /// trustworthy and at least as new as `built` (this device's freshly signed version-1
1208 /// directory), otherwise `built`.
1209 ///
1210 /// The persisted file is trusted only when it verifies under the account's user IK and lists
1211 /// this device live under the signing key it signs with. One that names another account id
1212 /// under this account's own IK is the directory a failed [`bind_account_id`](Self::bind_account_id)
1213 /// left behind, and is re-signed under the bound id at the next version. Anything else —
1214 /// missing (a library written before #562), unreadable, tampered, foreign, or one that
1215 /// revoked this device — falls back to `built` with a log line naming why, the behaviour
1216 /// every reopen had before the directory was persisted. The fallback is not written back,
1217 /// so the refused file stays on disk for inspection until the next directory change.
1218 fn restore_directory(
1219 root: &Path,
1220 account: &Account,
1221 dsk_public: &HybridVerifyingKey,
1222 built: DeviceDirectory,
1223 ) -> DeviceDirectory {
1224 let path = Self::directory_path(root);
1225 let bytes = match fs::read(&path) {
1226 Ok(bytes) => bytes,
1227 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1228 tracing::debug!("workspace open: no persisted device directory; using a fresh one");
1229 return built;
1230 }
1231 Err(e) => {
1232 tracing::warn!(error = %e, "workspace open: persisted device directory unreadable; using a fresh one");
1233 return built;
1234 }
1235 };
1236 let persisted: DeviceDirectory = match cbor::from_slice(&bytes) {
1237 Ok(directory) => directory,
1238 Err(e) => {
1239 tracing::warn!(error = %e, "workspace open: persisted device directory does not decode; using a fresh one");
1240 return built;
1241 }
1242 };
1243 if let Some(reason) = Self::refuse_persisted_directory(&persisted, account, dsk_public) {
1244 tracing::warn!(
1245 reason,
1246 persisted_version = persisted.core.directory_version,
1247 "workspace open: persisted device directory refused; using a fresh one"
1248 );
1249 return built;
1250 }
1251 let persisted = if persisted.core.user_id == account.user_id {
1252 persisted
1253 } else {
1254 // Signed by this account's own IK yet naming another id: the directory from before a
1255 // `bind_account_id` whose directory write never landed (the account file is the
1256 // authority on the id). Re-sign it under the bound id at the next version, as that
1257 // bind did, rather than dropping every device it lists for a version-1 rebuild.
1258 tracing::warn!(
1259 persisted_version = persisted.core.directory_version,
1260 from = %persisted.core.user_id,
1261 to = %account.user_id,
1262 "workspace open: persisted device directory names the pre-rebind account id; re-signing it under the bound id"
1263 );
1264 let mut core = persisted.core;
1265 core.user_id = account.user_id;
1266 core.directory_version += 1;
1267 core.updated_at = now_rfc3339();
1268 core.sign(&account.user_ik)
1269 };
1270 if persisted.core.directory_version < built.core.directory_version {
1271 tracing::warn!(
1272 persisted_version = persisted.core.directory_version,
1273 "workspace open: persisted device directory is older than a fresh one; using the fresh one"
1274 );
1275 return built;
1276 }
1277 tracing::info!(
1278 directory_version = persisted.core.directory_version,
1279 devices = persisted.core.devices.len(),
1280 "workspace open: persisted device directory restored"
1281 );
1282 persisted
1283 }
1284
1285 /// Why a persisted directory may not be adopted on open, or `None` when it may.
1286 fn refuse_persisted_directory(
1287 persisted: &DeviceDirectory,
1288 account: &Account,
1289 dsk_public: &HybridVerifyingKey,
1290 ) -> Option<&'static str> {
1291 if !persisted.verify(&account.user_ik.verifying_key()) {
1292 return Some("it does not verify under the user identity key");
1293 }
1294 match persisted.device(&account.device.device_id) {
1295 None => Some("it does not list this device"),
1296 Some(entry) if entry.dsk_public != *dsk_public => {
1297 Some("it lists this device under another signing key")
1298 }
1299 Some(entry) if entry.revoked_at.is_some() => Some("it lists this device as revoked"),
1300 Some(_) => None,
1301 }
1302 }
1303}
1304
1305#[cfg(test)]
1306mod tests;