capsule_library/lifecycle/reseal.rs
1//! Re-sealing a **never-published** create at the album's current epoch (issue #822).
2//!
3//! The server refuses a create whose manifest names an album epoch below the album's high-water
4//! mark (invariant 18): an asset imported offline before a rotation, or one whose push lost the
5//! race to a sibling written under the newer epoch, would otherwise be stranded on the device.
6//! The refusal is final for that envelope, so the only way forward is a new one.
7//!
8//! [`Workspace::reseal_create`] writes it. A create the server refused was never published —
9//! the refusal fires only on a row with no chain head, and writes nothing — so replacing its
10//! genesis record breaks no chain anybody holds. Everything sealed under the old epoch is
11//! sealed again under the current one, because a rotation is a confidentiality boundary:
12//!
13//! - the **original** is re-encrypted under a fresh `nonce_prefix` (the same `file_id`), so its
14//! ciphertext, content address and folded file key all change;
15//! - the **metadata blob** — the same signed sidecar, whose plaintext does not name an epoch —
16//! is sealed again under a fresh nonce;
17//! - the **derivatives** are regenerated, because each embeds the original's content address in
18//! its signed `original` reference and each is encrypted under the old epoch's key. They start
19//! fresh chains: the old ones were never published and must not be linked to.
20//!
21//! No nonce is reused: every prefix the asset has spent (the old original's and every old
22//! derivative's) is excluded from the new draws, and the old metadata blob nonce is refused for
23//! the new one. Nothing old stays reachable: the old derivative bundle is removed before the new
24//! one is written, and the old chain and metadata blob are replaced in the same atomic renames
25//! every signed write uses.
26//!
27//! What a re-seal cannot do is reach an epoch this device does not hold: when this device's
28//! current epoch is no newer than the asset's, the refusal is [`ResealRefusal::NoNewerEpoch`]
29//! and the asset stays local. That covers a refusal that had nothing to do with the epoch, and
30//! one where another device rotated the album and this one has not been handed the new key.
31
32use std::collections::HashMap;
33use std::fs;
34use std::io::{self, Read};
35
36use capsule_core::crypto::encryption::{
37 NONCE_PREFIX_LEN, RekeyStreamError, blob_ciphertext_hash, blob_nonce,
38 encrypt_asset_rekey_stream_with_prefix, seal_metadata_blob,
39};
40use capsule_core::crypto::hash::Sha256Hasher;
41use capsule_core::crypto::keys::{Amk, AmkVersion};
42use capsule_core::crypto::provenance::{
43 Action, KeyMode, ManifestCore, ProvenanceChain, ProvenanceRecord,
44};
45use capsule_core::crypto::verify_asset::{
46 MetadataBinding, VerifyOutcome, verify_asset_hashed, verify_metadata_binding,
47};
48use capsule_core::crypto::{CryptoError, rng};
49use capsule_core::media::StillFormat;
50use thiserror::Error;
51use uuid::Uuid;
52
53use super::derivatives::{ExistingDerivatives, PreparedStill, StillSource, existing_derivatives};
54use super::import::{MAX_HELD_STILL_BYTES, Tee, read_head};
55use super::{AssetState, LifecycleError, Result, Workspace, media_dir, now_rfc3339};
56use crate::exif::ExifExtract;
57use crate::library::load_receipts;
58
59/// How many candidate nonce prefixes are drawn before the draw itself is called broken. A
60/// 7-byte prefix collides with a handful of spent ones at about 1 in 2^50, so running out is a
61/// broken CSPRNG, not bad luck.
62const MAX_PREFIX_DRAWS: usize = 8;
63
64/// Why [`Workspace::reseal_create`] refused an asset. Each is a state in which writing a new
65/// genesis record would be wrong or impossible; none of them writes anything.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
67pub enum ResealRefusal {
68 /// The asset's provenance chain is not a lone `create`. A later record means the asset was
69 /// edited, and an edit is only ever authored on top of a create this device already holds as
70 /// its chain; replacing that genesis would orphan the records that follow it.
71 #[error("its provenance chain is not a lone create")]
72 NotALoneCreate,
73 /// The library holds a custody receipt for the asset, so the server published it. A
74 /// published genesis is append-only history; it is never replaced.
75 #[error("the server holds a custody receipt for it, so it was published")]
76 Published,
77 /// The original's file key is **wrapped** (an adopted guest drop), not derived from the album
78 /// key. Re-sealing it would need the key re-wrapped as well as the bytes re-encrypted, which
79 /// this path does not do.
80 #[error("its original's file key is wrapped, not derived from the album key")]
81 WrappedFileKey,
82 /// The album's current epoch on this device is not newer than the one the asset is sealed
83 /// under, so there is no epoch to re-seal at. This does not say why the server refused the
84 /// create: the album's epoch may not have moved at all (a revoked device, withdrawn write
85 /// access), or another device rotated it and this one does not hold the new key yet.
86 #[error(
87 "it is sealed at album epoch {sealed} and this device's current epoch is {current}: \
88 there is no newer epoch to re-seal it at"
89 )]
90 NoNewerEpoch {
91 /// The epoch the asset's create manifest names.
92 sealed: u32,
93 /// The album's current epoch on this device.
94 current: u32,
95 },
96}
97
98/// What one re-seal did.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub struct ResealOutcome {
101 /// The re-sealed asset (its `file_id`, unchanged).
102 pub asset_id: Uuid,
103 /// The asset's album.
104 pub album_id: Uuid,
105 /// The epoch the refused create was sealed under.
106 pub from_epoch: u32,
107 /// The epoch it is sealed under now: the album's current one.
108 pub to_epoch: u32,
109 /// How many derivative manifests were regenerated at the new epoch (zero for an asset this
110 /// build makes no derivatives for).
111 pub derivatives: usize,
112}
113
114impl Workspace {
115 /// Re-seal a never-published `create` at the album's current epoch, replacing its genesis
116 /// record, so a create the server refused because the album's epoch moved past it can be
117 /// pushed again instead of being stranded on the device.
118 ///
119 /// An epoch rotation is a confidentiality boundary, so everything sealed under the old epoch
120 /// is sealed again under the current one: the original under a fresh `nonce_prefix`, the
121 /// unchanged signed sidecar under a fresh metadata-blob nonce, and the derivatives
122 /// regenerated as fresh chains. No prefix or nonce the asset has spent is drawn again, and
123 /// the old derivative bundle is removed before the new one is written.
124 ///
125 /// The caller is a push that the server refused with an epoch regression; this re-checks
126 /// every precondition locally rather than trusting it, and refuses with
127 /// [`LifecycleError::ResealRefused`] when the asset is not a lone create, holds a custody
128 /// receipt, has a wrapped file key, or when this device holds no newer epoch. A read-only
129 /// album is [`LifecycleError::AlbumReadOnly`]. A plaintext on disk that no longer hashes to
130 /// the signed sidecar is [`LifecycleError::CiphertextMismatch`].
131 ///
132 /// The new create self-verifies through `verify_asset` and the metadata binding before
133 /// anything is written. On success the asset's next [`upload_bundle`](Self::upload_bundle)
134 /// carries the new epoch, the new original ciphertext, the new metadata blob and the new
135 /// derivatives, and nothing sealed under the old epoch.
136 #[tracing::instrument(skip(self), fields(asset_id = %asset_id))]
137 pub fn reseal_create(&mut self, asset_id: &Uuid) -> Result<ResealOutcome> {
138 let refuse = |reason: ResealRefusal| {
139 tracing::warn!(asset_id = %asset_id, %reason, "reseal: refused; nothing written");
140 LifecycleError::ResealRefused {
141 asset_id: *asset_id,
142 reason,
143 }
144 };
145 let asset = self
146 .assets
147 .get(asset_id)
148 .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?;
149 let album_id = asset.album_id;
150
151 // (1) Only a lone, derived-key create, and only one the server never published.
152 let [genesis] = asset.chain.records() else {
153 return Err(refuse(ResealRefusal::NotALoneCreate));
154 };
155 let old = genesis.manifest.core.clone();
156 if old.action != Action::Create || old.prior_provenance_hash.is_some() {
157 return Err(refuse(ResealRefusal::NotALoneCreate));
158 }
159 if old.key_mode != KeyMode::Derived {
160 return Err(refuse(ResealRefusal::WrappedFileKey));
161 }
162 let receipts = load_receipts(&self.root, asset_id, Some(asset.capture_utc))
163 .map_err(|e| LifecycleError::Cbor(format!("reading the receipt log: {e}")))?;
164 if !receipts.is_empty() {
165 return Err(refuse(ResealRefusal::Published));
166 }
167
168 // (2) Only to an epoch this device holds and that is newer than the sealed one.
169 let album = self.album(&album_id)?;
170 let sealed = old.amk_version.0;
171 let current = album.current_epoch;
172 if current <= sealed {
173 return Err(refuse(ResealRefusal::NoNewerEpoch { sealed, current }));
174 }
175 let write_tier = album.write_tier_signer()?;
176 let amk = Amk::from_bytes(album.amks[¤t]);
177 tracing::info!(
178 album_id = %album_id,
179 from_epoch = sealed,
180 to_epoch = current,
181 "reseal: re-sealing a never-published create at the album's current epoch"
182 );
183
184 // Every prefix this `file_id` has spent: the old original's and every old derivative's.
185 let derivative_dir = media_dir(&self.root, asset.capture_utc).join("derivatives");
186 let ExistingDerivatives {
187 used_prefixes: mut spent,
188 ..
189 } = existing_derivatives(&derivative_dir, *asset_id);
190 spent.insert(old.nonce_prefix);
191
192 // (3) Re-encrypt the original under a fresh prefix, hashing the plaintext as it passes:
193 // the signed sidecar commits to that hash, so bytes that changed on disk since the
194 // import are refused rather than sealed under a manifest that would misdescribe them.
195 let media_path = self.media_path(asset);
196 let read_err =
197 |e: io::Error| LifecycleError::Io(format!("read {}: {e}", media_path.display()));
198 let mut source = fs::File::open(&media_path).map_err(read_err)?;
199 let size = source.metadata().map_err(read_err)?.len();
200 let head = read_head(&mut source).map_err(read_err)?;
201 let decodable =
202 StillFormat::detect(&head, &asset.ext).is_some_and(StillFormat::is_decodable);
203 let held = if decodable && size <= MAX_HELD_STILL_BYTES {
204 let mut whole = Vec::new();
205 source.read_to_end(&mut whole).map_err(read_err)?;
206 Some(whole)
207 } else {
208 None
209 };
210 let mut held_reader = held.as_deref().unwrap_or_default();
211 let reader: &mut dyn Read = if held.is_some() {
212 &mut held_reader
213 } else {
214 &mut source
215 };
216 let mut tee = Tee {
217 inner: reader,
218 hasher: Sha256Hasher::new(),
219 copy: None,
220 };
221 let prefix = draw_unspent_prefix(&spent, rng::random_array::<NONCE_PREFIX_LEN>)?;
222 let (enc, _file_key) = encrypt_asset_rekey_stream_with_prefix(
223 &amk,
224 asset_id,
225 &mut tee,
226 io::sink(),
227 prefix,
228 Some(old.nonce_prefix),
229 )
230 .map_err(|e| match e {
231 RekeyStreamError::Crypto(e) => LifecycleError::Crypto(e),
232 RekeyStreamError::Stream(e) => {
233 LifecycleError::Io(format!("encrypt {}: {e}", media_path.display()))
234 }
235 })?;
236 let plaintext_hash = tee.hasher.finalize();
237 if plaintext_hash != asset.sidecar.hash || enc.plaintext_size != old.plaintext_size {
238 tracing::error!(
239 asset_id = %asset_id,
240 expected_plaintext_size = old.plaintext_size,
241 actual_plaintext_size = enc.plaintext_size,
242 "reseal: the original on disk no longer matches its signed sidecar; refusing"
243 );
244 return Err(LifecycleError::CiphertextMismatch(*asset_id));
245 }
246 tracing::debug!(
247 plaintext_size = enc.plaintext_size,
248 spent_prefixes = spent.len(),
249 "reseal: original re-encrypted under a fresh nonce prefix"
250 );
251
252 // (4) Seal the same signed sidecar again under the current epoch, refusing the old
253 // blob's nonce for the new draw.
254 let sidecar_bytes = asset.sidecar.to_canonical_vec();
255 let (metadata_blob, blob_key) = seal_metadata_blob(
256 &amk,
257 asset_id,
258 &sidecar_bytes,
259 blob_nonce(&asset.metadata_blob),
260 )?;
261 let metadata_blob_hash = blob_ciphertext_hash(&metadata_blob);
262
263 // (5) Regenerate the derivatives at the current epoch, as fresh chains, excluding every
264 // spent prefix. Never fatal over pixels, exactly as at import.
265 spent.insert(enc.nonce_prefix);
266 let PreparedStill { derivatives, .. } = self.prepare_still_with(
267 &StillSource {
268 plaintext: held.as_deref().unwrap_or(&head),
269 size,
270 ext: &asset.ext,
271 src: &media_path,
272 exif: &ExifExtract::default(),
273 },
274 *asset_id,
275 album_id,
276 &amk,
277 &enc,
278 ExistingDerivatives {
279 heads: HashMap::new(),
280 used_prefixes: spent,
281 },
282 )?;
283 drop(held);
284
285 // (6) The new genesis: the old create's identity and declarations, with every field the
286 // epoch decides re-minted, signed by this device under the current write-tier key.
287 let core = ManifestCore {
288 amk_version: AmkVersion(current),
289 ciphertext_hash: enc.ciphertext_hash,
290 plaintext_size: enc.plaintext_size,
291 chunk_size: enc.chunk_size,
292 nonce_prefix: enc.nonce_prefix,
293 metadata_blob_hash: Some(metadata_blob_hash),
294 created_by_user: self.account.user_id,
295 created_by_device: self.account.device.device_id,
296 client_version: self.client_version.clone(),
297 timestamp: now_rfc3339(),
298 ..old
299 };
300 let manifest = core.sign(self.device_signer.as_ref(), write_tier)?;
301 let mut chain = ProvenanceChain::new();
302 chain
303 .append(ProvenanceRecord::new(*asset_id, manifest.clone(), None))
304 .map_err(|e| LifecycleError::Cbor(format!("chain: {e}")))?;
305
306 // (7) Self-check before anything is written.
307 let outcome = verify_asset_hashed(
308 &manifest,
309 &enc.ciphertext_hash,
310 &self.directory,
311 self.authority(&album_id)?,
312 None,
313 );
314 if outcome != VerifyOutcome::Accept {
315 return Err(LifecycleError::SelfVerify(outcome));
316 }
317 let binding = verify_metadata_binding(&manifest, &metadata_blob, &blob_key, &sidecar_bytes);
318 if binding != MetadataBinding::Bound {
319 return Err(LifecycleError::MetadataUnbound(binding));
320 }
321
322 let resealed = AssetState {
323 asset_id: *asset_id,
324 album_id,
325 ext: asset.ext.clone(),
326 capture_utc: asset.capture_utc,
327 chain,
328 sidecar: asset.sidecar.clone(),
329 metadata_blob,
330 stack: asset.stack.clone(),
331 };
332
333 // (8) Write. The old derivative bundle goes first: once the chain names the new epoch
334 // no manifest sealed under the old one may remain readable, and a bundle that cannot be
335 // removed fails the re-seal before anything else moves. The new derivatives then land
336 // (a failure there is logged and costs only a regenerable thumbnail), and the signed
337 // artifacts last, the chain renamed after the blob, as every signed write orders them.
338 let old_bundle = derivative_dir.join(format!("{}.derivatives.cbor", asset_id.simple()));
339 match fs::remove_file(&old_bundle) {
340 Ok(()) => tracing::debug!("reseal: old-epoch derivative bundle removed"),
341 Err(e) if e.kind() == io::ErrorKind::NotFound => {}
342 Err(e) => {
343 return Err(LifecycleError::Io(format!(
344 "remove {}: {e}",
345 old_bundle.display()
346 )));
347 }
348 }
349 self.persist_derivatives(&resealed, &derivatives);
350 self.write_signed_artifacts(&resealed)?;
351 self.index_asset_row(&resealed)?;
352 self.assets.insert(*asset_id, resealed);
353
354 tracing::info!(
355 album_id = %album_id,
356 from_epoch = sealed,
357 to_epoch = current,
358 derivatives = derivatives.len(),
359 "reseal: create re-sealed and self-verified at the album's current epoch"
360 );
361 Ok(ResealOutcome {
362 asset_id: *asset_id,
363 album_id,
364 from_epoch: sealed,
365 to_epoch: current,
366 derivatives: derivatives.len(),
367 })
368 }
369}
370
371/// Draw a nonce prefix from `draw` that is not in `spent`, redrawing a collision.
372///
373/// The CSPRNG makes a collision vanishingly unlikely; the refusal is the encryption doc's
374/// defense in depth on top of it, because a prefix is folded into the file-key salt and a
375/// reused one would reuse the key as well as the nonce.
376fn draw_unspent_prefix(
377 spent: &std::collections::HashSet<[u8; NONCE_PREFIX_LEN]>,
378 mut draw: impl FnMut() -> [u8; NONCE_PREFIX_LEN],
379) -> Result<[u8; NONCE_PREFIX_LEN]> {
380 for attempt in 0..MAX_PREFIX_DRAWS {
381 let prefix = draw();
382 if !spent.contains(&prefix) {
383 return Ok(prefix);
384 }
385 tracing::warn!(attempt, "reseal: drew a spent nonce prefix; redrawing");
386 }
387 Err(LifecycleError::Crypto(CryptoError::NonceReuse))
388}
389
390#[cfg(test)]
391mod tests;