capsule_library/lifecycle/provenance.rs
1//! The append-only provenance chain: signing a lifecycle manifest, appending it under the
2//! sealing order (re-signing + re-sealing the sidecar), and the `verify_asset` self-check.
3
4use std::fs;
5
6use capsule_core::crypto::encryption::{
7 blob_ciphertext_hash, blob_nonce, encrypt_asset_vec_with_prefix, seal_metadata_blob,
8};
9use capsule_core::crypto::hash::Hash32;
10use capsule_core::crypto::keys::Amk;
11use capsule_core::crypto::provenance::{Action, AssetManifest, ManifestCore, ProvenanceRecord};
12use capsule_core::crypto::verify_asset::{
13 MetadataBinding, RejectReason, VerifyOutcome, verify_asset, verify_metadata_binding,
14};
15use capsule_core::metadata::crdt::AddId;
16use capsule_core::sidecar::SidecarV1;
17use uuid::Uuid;
18
19use super::{AlbumKeys, LifecycleError, Result, Workspace, now_rfc3339};
20
21impl Workspace {
22 /// Build a signed lifecycle manifest for `asset`, sharing the create manifest's content
23 /// fields. Used for metadata-update / delete / trash-restore. `metadata_blob_hash` is set
24 /// explicitly per the presence-by-action rule (`Some` for a metadata-update that seals a
25 /// fresh blob, `None` for delete / trash-restore) rather than inherited from `base`.
26 ///
27 /// # Who a continuation names, and why it cannot be the creator
28 ///
29 /// `created_by_user` / `created_by_device` name the **signer of this record**, re-minted per
30 /// write like `timestamp` and `client_version` — never inherited from `base`.
31 ///
32 /// That is not a preference, it is what
33 /// [`verify_asset`] requires: it resolves
34 /// `created_by_device` *inside `created_by_user`'s* published directory (step 6) and then
35 /// verifies `device_sig` under **that entry's** key (step 8). A record naming a device that
36 /// did not sign it fails step 8 and is unverifiable by every reader. Inheriting the pair
37 /// therefore broke the ordinary two-device case — device B deleting an asset created on
38 /// device A produced a manifest claiming A and signed by B — as well as every write by a
39 /// shared album's member.
40 ///
41 /// Album authority is a separate check and is unaffected: step 10 verifies `write_sig`
42 /// under the epoch's attested write-tier key, so naming the acting member as this record's
43 /// author does not weaken the owner's album.
44 ///
45 /// The asset's original creator stays recoverable where it always was — the `create` record
46 /// at the head of the provenance chain, which is append-only.
47 fn sign_lifecycle(
48 &self,
49 album: &AlbumKeys,
50 base: &ManifestCore,
51 action: Action,
52 prior: Option<Hash32>,
53 retention_until: Option<String>,
54 metadata_blob_hash: Option<Hash32>,
55 ) -> Result<AssetManifest> {
56 let core = ManifestCore {
57 action,
58 prior_provenance_hash: prior,
59 retention_until,
60 metadata_blob_hash,
61 timestamp: now_rfc3339(),
62 // This record's signer, not the asset's creator — see the doc comment above. The
63 // same pair every create path writes (`import.rs`, `drops.rs`, `drop/mod.rs`), for
64 // the same reason: it is the device whose DSK signs the bytes below.
65 created_by_user: self.account.user_id,
66 created_by_device: self.account.device.device_id,
67 // Each write records the exact client build that produced *this* record, not
68 // the creator's — so an edit by a different client identifies itself in the chain.
69 client_version: self.client_version.clone(),
70 ..base.clone()
71 };
72 Ok(core.sign(self.device_signer.as_ref(), album.write_tier_signer()?)?)
73 }
74
75 /// Run `verify_asset` for a managed asset (regenerating its ciphertext deterministically).
76 pub fn verify(&self, asset_id: &Uuid) -> Result<VerifyOutcome> {
77 let asset = self
78 .assets
79 .get(asset_id)
80 .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?;
81 let album = self.album(&asset.album_id)?;
82 let head = &asset
83 .chain
84 .records()
85 .last()
86 .expect("provenance chain is never empty")
87 .manifest;
88 let plaintext =
89 fs::read(self.media_path(asset)).map_err(|e| LifecycleError::Io(e.to_string()))?;
90 // The head's `key_mode` / `wrapped_file_key` are read before they are verified, so a
91 // tampered pair must not surface as an `Err`: a wrapped key that does not open (or a
92 // `wrapped` head with none) yields no regenerated ciphertext, and `verify_asset` then
93 // rejects it like any other content the signed manifest does not commit to. A missing
94 // epoch key is local state, not tamper, and stays an error.
95 let ciphertext = match self.original_file_key(album, &head.core) {
96 Ok(file_key) => {
97 Some(encrypt_asset_vec_with_prefix(&file_key, head.core.nonce_prefix, &plaintext).1)
98 }
99 Err(LifecycleError::Crypto(e)) => {
100 tracing::warn!(
101 asset_id = %asset_id,
102 error = %e,
103 "the head's file key does not open; verifying it against no ciphertext"
104 );
105 None
106 }
107 Err(e) => return Err(e),
108 };
109
110 // Walk the whole chain forward; the head is what enters the trusted set.
111 let prior = asset
112 .chain
113 .records()
114 .len()
115 .checked_sub(2)
116 .map(|i| asset.chain.records()[i].record_hash());
117 let outcome = verify_asset(
118 head,
119 ciphertext.as_deref().unwrap_or_default(),
120 &self.directory,
121 self.authority(&asset.album_id)?,
122 prior,
123 );
124 // No STREAM ciphertext is empty, so an accept here is unreachable; refuse it anyway
125 // rather than accept content that was never regenerated.
126 Ok(match (ciphertext, outcome) {
127 (None, VerifyOutcome::Accept) => {
128 VerifyOutcome::TerminalReject(RejectReason::CiphertextHashMismatch)
129 }
130 (_, outcome) => outcome,
131 })
132 }
133
134 pub(super) fn append_lifecycle(
135 &mut self,
136 asset_id: &Uuid,
137 action: Action,
138 retention_until: Option<String>,
139 mutate_sidecar: impl FnOnce(&mut SidecarV1, AddId),
140 ) -> Result<()> {
141 let album_id = self
142 .assets
143 .get(asset_id)
144 .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?
145 .album_id;
146 // Sealing order (1): the prior head `H` is this asset's current chain head.
147 let prior = self.assets[asset_id].chain.head();
148 let base = self.assets[asset_id]
149 .chain
150 .records()
151 .last()
152 .expect("provenance chain is never empty")
153 .manifest
154 .core
155 .clone();
156 let binds = action.binds_metadata_blob();
157 let epoch = base.amk_version.0;
158 let album_amk = {
159 let album = self.album(&album_id)?;
160 Amk::from_bytes(album.amks[&epoch])
161 };
162 // Set by the metadata-bearing branch to the freshly derived blob key (nonce-folded),
163 // for the binding self-check below.
164 let mut sealed_blob_key: Option<[u8; 32]> = None;
165
166 // Before the first edit replaces the blob the create binds, keep it: an upload carries
167 // the create, and only these bytes answer its `metadata_blob_hash`. Written before
168 // anything of the edit is, so a failure here leaves the asset untouched.
169 if binds {
170 self.keep_create_metadata_blob(asset_id)?;
171 }
172
173 // Sealing order (2)+(3) for a metadata-bearing action: mutate + re-sign the sidecar with
174 // `provenance_chain_hash = H`, then re-seal it under a fresh nonce folded into the blob
175 // key (refusing to reuse the superseded nonce) and compute the fresh blob hash.
176 // `delete` / `trash-restore` mint no new blob, so the sidecar and its stored blob are
177 // left as the last metadata-bearing write produced them (their manifests commit to no
178 // blob).
179 let metadata_blob_hash = if binds {
180 let add_id = self.counter.issue();
181 let asset = self
182 .assets
183 .get_mut(asset_id)
184 .expect("asset_id was validated above");
185 // The nonce of the blob this update supersedes — refused for the fresh draw.
186 let prior_nonce = blob_nonce(&asset.metadata_blob);
187 mutate_sidecar(&mut asset.sidecar, add_id);
188 asset.sidecar.provenance_chain_hash = prior;
189 asset.sidecar.signature = None;
190 asset.sidecar.sign(&self.account.user_ik);
191 let (blob, blob_key) = seal_metadata_blob(
192 &album_amk,
193 asset_id,
194 &asset.sidecar.to_canonical_vec(),
195 prior_nonce,
196 )?;
197 let hash = blob_ciphertext_hash(&blob);
198 asset.metadata_blob = blob;
199 sealed_blob_key = Some(blob_key);
200 Some(hash)
201 } else {
202 None
203 };
204
205 // Sealing order (4): build + sign the manifest with `prior_provenance_hash = H` and the
206 // `metadata_blob_hash` from (3); append it as the new chain head.
207 let album = self.album(&album_id)?;
208 let manifest = self.sign_lifecycle(
209 album,
210 &base,
211 action,
212 prior,
213 retention_until,
214 metadata_blob_hash,
215 )?;
216 {
217 let asset = self
218 .assets
219 .get_mut(asset_id)
220 .expect("asset_id was validated above");
221 asset
222 .chain
223 .append(ProvenanceRecord::new(*asset_id, manifest.clone(), prior))
224 .map_err(|e| LifecycleError::Cbor(format!("chain: {e}")))?;
225 }
226
227 // Self-check the metadata↔manifest binding for a metadata-bearing write, enforcement on.
228 if binds {
229 let asset = &self.assets[asset_id];
230 let binding = verify_metadata_binding(
231 &manifest,
232 &asset.metadata_blob,
233 &sealed_blob_key.expect("the metadata-bearing branch set the blob key"),
234 &asset.sidecar.to_canonical_vec(),
235 );
236 if binding != MetadataBinding::Bound {
237 return Err(LifecycleError::MetadataUnbound(binding));
238 }
239 }
240
241 // Re-borrow immutably to write the updated artifacts to disk. Only the signed
242 // artifacts: a lifecycle write never changes the original, so it neither reads nor
243 // rewrites it — a caption edit on a multi-gigabyte video touches the sidecar, the
244 // chain, and the blob, and nothing else.
245 let asset = self
246 .assets
247 .get(asset_id)
248 .expect("asset_id was validated above");
249 self.write_signed_artifacts(asset)?;
250 self.index_asset_row(asset)
251 }
252
253 /// Keep the metadata blob `asset_id`'s `create` binds when the library still holds it as
254 /// the asset's current blob, which is exactly until the first metadata-bearing edit. A
255 /// create that binds no blob, a blob an earlier edit already moved aside, and a library
256 /// written before the blob was kept (whose current blob no longer answers the create) keep
257 /// nothing.
258 pub(super) fn keep_create_metadata_blob(&self, asset_id: &Uuid) -> Result<()> {
259 let asset = &self.assets[asset_id];
260 let bound = asset
261 .chain
262 .records()
263 .first()
264 .expect("provenance chain is never empty")
265 .manifest
266 .core
267 .metadata_blob_hash;
268 match bound {
269 Some(bound)
270 if !asset.metadata_blob.is_empty()
271 && blob_ciphertext_hash(&asset.metadata_blob) == bound =>
272 {
273 self.write_create_metadata_blob(asset, &asset.metadata_blob)
274 }
275 _ => {
276 tracing::trace!(
277 asset_id = %asset_id,
278 create_binds_blob = bound.is_some(),
279 "the create's metadata blob is not the current one; nothing to keep"
280 );
281 Ok(())
282 }
283 }
284 }
285}
286
287#[cfg(test)]
288mod tests;