Skip to main content

capsule_library/lifecycle/
sync_apply.rs

1//! Applying a **remote** asset entry — the receiving half of the lifecycle.
2//!
3//! Everything else in [`lifecycle`](super) authors state this device owns. This module is the
4//! other direction: a signed manifest + sealed metadata blob that arrived from a server feed
5//! (the [download & sync] `Sync` entry), turned into **verified facts** a client may upsert
6//! into its own catalog — or into a quarantine verdict it must surface.
7//!
8//! # The chokepoint is not re-implemented here
9//!
10//! [`verify_asset`] is *the* single path by which an asset enters a client's trusted set, and
11//! this module calls it — it does not re-derive, re-check, or re-order any of its twelve
12//! steps. What this module adds is the orchestration a feed entry needs and a local import
13//! does not:
14//!
15//! 1. decode the **provenance record** from the opaque canonical CBOR the feed carries
16//!    verbatim (never re-encoded — re-encoding would detach the manifest inside it from its
17//!    signatures), check the record's `prior_provenance_hash` against the manifest's, and
18//!    refuse an asset this workspace purged (its tombstone, [`Workspace::tombstones`]);
19//! 2. run [`verify_asset`] against this workspace's device directory, the album's attested
20//!    authority, and the caller's local provenance head;
21//! 3. bind the sealed metadata blob to the manifest (content address, then AEAD open under the
22//!    nonce-folded blob key) and decode the signed [`SidecarV1`] inside it;
23//! 4. check that sidecar's own user-IK signature;
24//! 5. project the result into [`RemoteAssetFacts`].
25//!
26//! Every failure is a **verdict**, never a silent drop and never a silent accept: the three
27//! [`SyncApplyOutcome`] variants are exactly `Applied` / `Pending` (hold and retry as MLS
28//! state catches up) / `Quarantined`, mirroring [`VerifyOutcome`]'s own trichotomy.
29//!
30//! # Why the original ciphertext is required
31//!
32//! [`verify_asset`] step 5 is content integrity: the ciphertext must hash to the manifest's
33//! declared `ciphertext_hash`. There is no variant of the chokepoint that skips it, and this
34//! module does not invent one — so a caller applies an entry once it holds the original blob
35//! (the T2 rung of the tier ladder). A client that has pulled only the T0 index rung *holds*
36//! the entry; it does not yet *apply* it.
37//!
38//! An original too large to hold is applied as a [`RemoteHead`], which names the ciphertext by
39//! its SHA-256 instead of carrying it, through [`verify_asset_hashed`] — the same twelve steps
40//! over a digest. The digest is a claim until the bytes are read:
41//! [`Workspace::open_remote_original_from`] hashes the ciphertext it streams and opens nothing
42//! unless that hash is the one the chokepoint accepted.
43//!
44//! # Adopting what applied
45//!
46//! Applying is read-only: it says what is true and writes nothing. A client whose catalog *is*
47//! this workspace's library adopts the entry instead ([`Workspace::adopt_remote_head`],
48//! [`Workspace::adopt_remote_original`]): the same verdict, and then the verified record joins a
49//! chain this workspace holds — a `create` starts one, with its sidecar, sealed metadata blob and
50//! original written under `media/` and its row and user tags indexed, and a later record that
51//! chains onto the held head is appended. The chain held is the records the chokepoint accepted,
52//! byte for byte, so the asset's next signed record chains onto the head the server holds, and
53//! a reopen reads the asset back from its files like any other.
54//!
55//! A chain begins at its create and nowhere else, and the feed serves only an asset's latest
56//! record. An asset first seen at a later record is therefore not held from that record alone
57//! ([`Adoption::MissingHistory`]) — anchoring a chain at a non-create head would forge a chain
58//! that never verifies from its start — and a record that does not chain onto the held head is
59//! not appended ([`Adoption::Diverged`]). The server keeps serving an asset's superseded records
60//! by their address, so a caller walks each record's `prior_provenance_hash` back to the create
61//! and hands the records over ([`Workspace::adopt_remote_history`]): each is verified through the
62//! chokepoint in order, and the asset is held from its create.
63//!
64//! # Transport independence
65//!
66//! Nothing below names a transport. The gRPC sync feed, a REST re-fronting of the same feed, a
67//! federation pull, and a LAN peering delta all deliver the identical three byte strings, so
68//! these signatures are unaffected by which one a client speaks.
69//!
70//! # What the feed's `manifest_cbor` actually carries
71//!
72//! The **provenance blob's** bytes, unchanged — and the provenance blob is the canonical CBOR
73//! of a [`ProvenanceRecord`], not of a bare [`AssetManifest`]. That is forced, not chosen:
74//! [provenance.md § Physical Storage] makes the server-side chain an append-only sequence of
75//! envelope objects "served back unchanged", and the server's chain head is the SHA-256 of
76//! those bytes while a client's next `prior_provenance_hash` is
77//! [`record_hash()`](capsule_core::crypto::provenance::ProvenanceRecord::record_hash) — the digest of
78//! the canonical *record*. Any other encoding makes the two disagree, and no lifecycle op could
79//! ever chain onto a synced asset.
80//!
81//! The manifest is not re-encoded by the wrapper: canonical CBOR is deterministic, so the
82//! manifest sub-map inside the record is byte-identical to the manifest's own signed bytes, and
83//! [provenance.md § Asset Manifest]'s "the signed bytes are the served bytes" holds through it.
84//! [`verify_asset`] still verifies over the manifest's recomputed signing bytes, exactly as
85//! before.
86//!
87//! The record's `prior_provenance_hash` is checked against the manifest's own before either is
88//! used — [provenance.md § Chained, Append-Only Structure] calls the pair "a checked invariant,
89//! not trusted redundancy", and this is the wire path where nothing else would check it.
90//!
91//! # The payload leads with its version
92//!
93//! `manifest_cbor` is decoded through [`ProvenanceRecord::decode`], which reads the record's
94//! leading `version` before anything else (ADR-0009, superseding ADR-0008). A record from a
95//! newer writer is quarantined as `UnsupportedRecordVersion` — kept for the caller to store
96//! verbatim and retry after an update, never applied and never dropped. A byte string that is
97//! not a record is quarantined as `MalformedManifest`, never guessed at. Within a version the
98//! manifest keeps keys this build does not know under its signatures, so a newer writer that
99//! only adds a field still verifies here. The sealed sidecar inside carries its own version
100//! (`sidecar_schema`, refused forward below).
101//!
102//! [download & sync]: https://docs/design/sync/
103//! [provenance.md § Asset Manifest]: https://docs/design/cryptography/provenance/#asset-manifest
104//! [provenance.md § Chained, Append-Only Structure]: https://docs/design/cryptography/provenance/#chained-append-only-structure
105//! [provenance.md § Physical Storage]: https://docs/design/cryptography/provenance/#physical-storage
106//! [`verify_asset`]: capsule_core::crypto::verify_asset::verify_asset
107//! [`verify_asset_hashed`]: capsule_core::crypto::verify_asset::verify_asset_hashed
108//! [`VerifyOutcome`]: capsule_core::crypto::verify_asset::VerifyOutcome
109
110use std::io::{Read, Write};
111use std::path::Path;
112
113use capsule_core::content_type::extension_for;
114use capsule_core::crypto::encryption::{
115    CIPHERTEXT_CHUNK, StreamDecryptor, StreamError, blob_ciphertext_hash, blob_nonce, open_blob,
116};
117use capsule_core::crypto::hash::{Hash32, Sha256Hasher, hash_bytes};
118use capsule_core::crypto::keys::Amk;
119use capsule_core::crypto::provenance::{
120    Action, AssetManifest, ManifestCore, ProvenanceChain, ProvenanceRecord, RecordDecodeError,
121};
122use capsule_core::crypto::verify_asset::{
123    BindingReject, PendingReason, RejectReason, VerifyOutcome, diagnose_misattributed_signer,
124    verify_asset_hashed,
125};
126use capsule_core::sidecar::sidecar_v1::{SIDECAR_SCHEMA_V1, SidecarV1};
127use jiff::Timestamp;
128use uuid::Uuid;
129
130use super::open::original_extension;
131use super::{
132    AssetState, LifecycleError, Result, StackPlacement, Workspace, media_dir, media_file_path,
133};
134
135/// One remote feed entry, exactly as a sync feed delivers it: opaque bytes plus the album the
136/// entry claims and the head the receiving catalog already holds. Borrowed rather than owned so
137/// a caller hands over buffers it already has without a copy.
138#[derive(Debug, Clone, Copy)]
139pub struct RemoteEntry<'a> {
140    /// The album the feed says this entry belongs to. Cross-checked against the manifest by
141    /// [`verify_asset`](capsule_core::crypto::verify_asset::verify_asset) itself
142    /// ([`RejectReason::WrongAlbum`]), never trusted on its own.
143    pub album_id: Uuid,
144    /// The signed `AssetManifest` as **opaque canonical CBOR**, carried verbatim.
145    pub manifest_cbor: &'a [u8],
146    /// The sealed metadata blob the manifest commits to via `metadata_blob_hash`.
147    pub metadata_blob: &'a [u8],
148    /// The asset's original ciphertext — required for the chokepoint's content-integrity step.
149    pub original_ciphertext: &'a [u8],
150    /// The provenance head **the receiving catalog** holds for this asset, or `None` if it has
151    /// never seen it. Passed straight through to
152    /// [`verify_asset`](capsule_core::crypto::verify_asset::verify_asset)'s parameter of the same name,
153    /// which is what decides replay ([`RejectReason::Replayed`]) and fork
154    /// ([`RejectReason::ForgedChain`]).
155    ///
156    /// It is a caller parameter rather than something read off the workspace because the
157    /// catalog that tracks synced assets is the client's, not this workspace's asset map — an
158    /// iOS gallery, a CLI report, and a peering reconciler each hold their own head. Feed back
159    /// [`RemoteAssetFacts::provenance_head`] after applying.
160    pub local_chain_head: Option<Hash32>,
161}
162
163impl<'a> RemoteEntry<'a> {
164    /// This entry with its original named by the SHA-256 of
165    /// [`original_ciphertext`](Self::original_ciphertext) — a digest these bytes back, so the
166    /// head is no weaker.
167    #[must_use]
168    pub fn head(&self) -> RemoteHead<'a> {
169        RemoteHead {
170            album_id: self.album_id,
171            manifest_cbor: self.manifest_cbor,
172            metadata_blob: self.metadata_blob,
173            original_ciphertext_hash: hash_bytes(self.original_ciphertext),
174            local_chain_head: self.local_chain_head,
175        }
176    }
177}
178
179/// A [`RemoteEntry`] whose original ciphertext is named by its SHA-256 rather than carried: what
180/// a caller holds when the original is too large to keep in memory — a restore that streams it
181/// to disk, say.
182///
183/// [`original_ciphertext_hash`](Self::original_ciphertext_hash) stands in for the bytes at the
184/// chokepoint's content-integrity step, so on its own it is a claim. Applying a head therefore
185/// vouches for the ciphertext only once something has hashed the bytes and found this digest:
186/// [`Workspace::open_remote_original_from`] does, over exactly the bytes it decrypts.
187#[derive(Debug, Clone, Copy)]
188pub struct RemoteHead<'a> {
189    /// As [`RemoteEntry::album_id`].
190    pub album_id: Uuid,
191    /// As [`RemoteEntry::manifest_cbor`].
192    pub manifest_cbor: &'a [u8],
193    /// As [`RemoteEntry::metadata_blob`].
194    pub metadata_blob: &'a [u8],
195    /// The SHA-256 of the asset's original ciphertext: the content address the chokepoint checks
196    /// against the manifest's `ciphertext_hash`.
197    pub original_ciphertext_hash: Hash32,
198    /// As [`RemoteEntry::local_chain_head`].
199    pub local_chain_head: Option<Hash32>,
200}
201
202/// The SHA-256 and length of the original ciphertext `ciphertext` yields, read one STREAM chunk
203/// at a time: the [`RemoteHead::original_ciphertext_hash`] for an original that is on disk
204/// rather than in memory, computed in memory bounded by one chunk whatever the original's size.
205///
206/// The digest is of exactly the bytes read, so a head built from it vouches for those bytes:
207/// [`Workspace::apply_remote_head`] then checks it against the manifest's content address as
208/// [`Workspace::apply_remote_entry`] checks the bytes themselves.
209///
210/// # Errors
211///
212/// [`LifecycleError::Io`] when `ciphertext` cannot be read.
213pub fn hash_ciphertext_from<R: Read>(mut ciphertext: R) -> Result<(Hash32, u64)> {
214    let mut hasher = Sha256Hasher::new();
215    let mut window = vec![0u8; CIPHERTEXT_CHUNK];
216    let mut read: u64 = 0;
217    loop {
218        let n = match ciphertext.read(&mut window) {
219            Ok(0) => break,
220            Ok(n) => n,
221            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
222            Err(error) => {
223                return Err(LifecycleError::Io(format!(
224                    "reading the original's ciphertext: {error}"
225                )));
226            }
227        };
228        hasher.update(&window[..n]);
229        read += n as u64;
230    }
231    tracing::debug!(
232        bytes = read,
233        "sync-apply: original ciphertext hashed from a stream"
234    );
235    Ok((hasher.finalize(), read))
236}
237
238/// Why an entry was quarantined: surfaced to the user, never silently dropped.
239///
240/// Each variant names the check that refused it, so a client's quarantine surface can say what
241/// happened rather than "sync failed".
242#[derive(Debug, Clone, PartialEq, Eq)]
243pub enum QuarantineReason {
244    /// The manifest bytes are not a decodable `AssetManifest`.
245    MalformedManifest(String),
246    /// The provenance record declares a version newer than this build reads. Nothing about it
247    /// was checked or applied; the caller keeps the entry verbatim and retries it once the user
248    /// updates (versioning invariants 3 and 5).
249    UnsupportedRecordVersion {
250        /// The version the record declares.
251        found: u64,
252        /// The newest version this build reads.
253        max_known: u16,
254    },
255    /// This workspace holds no key material or authority for the album the entry names, so
256    /// there is nothing to verify it against. Not a rejection of the entry — a statement that
257    /// this device cannot adjudicate it.
258    UnknownAlbum(Uuid),
259    /// [`verify_asset`](capsule_core::crypto::verify_asset::verify_asset) terminally rejected the
260    /// manifest.
261    Rejected(RejectReason),
262    /// [`verify_asset`](capsule_core::crypto::verify_asset::verify_asset) rejected the manifest as
263    /// [`RejectReason::BadDeviceSig`], and the
264    /// rejection is the **legacy inherited-device defect** (issue #475), not a forgery: an older
265    /// client's continuation names `named_device` (inherited from the chain head) but was signed
266    /// by `signing_device`, another device of the same account, and every other step of the
267    /// chokepoint holds (see [`diagnose_misattributed_signer`]).
268    ///
269    /// Still a quarantine: the record is never accepted, the caller's chain head does not
270    /// advance, and every later record of this asset's chain is refused as
271    /// [`RejectReason::ForgedChain`] behind it. `record_hash` is this record's hash — the value
272    /// the *next* record's `prior_provenance_hash` carries — so a client can attribute that tail
273    /// to this stall rather than to an attack. SSoT: [provenance.md § Legacy Inherited-Device
274    /// Records].
275    ///
276    /// [provenance.md § Legacy Inherited-Device Records]: https://docs/design/cryptography/provenance/#legacy-inherited-device-records
277    LegacyInheritedDevice {
278        /// The device the record claims as its author (the chain head's, inherited).
279        named_device: Uuid,
280        /// The device of the same account whose DSK actually signed the record.
281        signing_device: Uuid,
282        /// The refused record's hash, where the asset's chain stalls.
283        record_hash: Hash32,
284    },
285    /// The manifest verified, but its metadata blob does not bind to it.
286    Binding(BindingReject),
287    /// The metadata blob opened, but its plaintext is not a decodable `SidecarV1`.
288    MalformedSidecar(String),
289    /// The sidecar decoded, but its hybrid signature does not verify under the account's user
290    /// identity key — the metadata was authored by something that does not hold this account's
291    /// IK.
292    SidecarSignature,
293    /// This workspace purged the asset: its tombstone ([`Workspace::tombstones`]) refuses every
294    /// later entry for it, whatever the entry says, so a feed cannot revive a purged asset. Not a
295    /// verdict on the entry's authenticity — nothing past the record's decode was checked. The
296    /// purge's own `delete` ([`Workspace::purge_record`]) is unaffected and can still be sent.
297    Purged(Uuid),
298}
299
300/// The verified facts one remote entry contributes to the receiving catalog.
301///
302/// Every field is downstream of an `Accept` from
303/// [`verify_asset`](capsule_core::crypto::verify_asset::verify_asset) plus — when the action carries
304/// metadata — a bound, correctly signed sidecar, so a client may persist all of it without
305/// re-checking anything.
306#[derive(Debug, Clone, PartialEq)]
307pub struct RemoteAssetFacts {
308    /// The asset id (the manifest's `file_id`).
309    pub asset_id: Uuid,
310    /// The album the asset belongs to.
311    pub album_id: Uuid,
312    /// The AMK epoch the asset is sealed under.
313    pub amk_version: u32,
314    /// The original's ciphertext content address.
315    pub ciphertext_hash: Hash32,
316    /// The original's plaintext length in bytes.
317    pub plaintext_size: u64,
318    /// The head manifest's lifecycle action (`create`, `metadata-update`, `delete`, …).
319    pub action: Action,
320    /// RFC3339 authoring timestamp of the head manifest.
321    pub timestamp: String,
322    /// The device that authored it, resolved in the signed device directory.
323    pub created_by_device: Uuid,
324    /// The provenance-record hash this entry establishes — the value a client persists as the
325    /// asset's new head and passes back as [`RemoteEntry::local_chain_head`] next time.
326    pub provenance_head: Hash32,
327    /// The decrypted, signature-checked sidecar: capture time, content type, dimensions, LQIP,
328    /// and the CRDT registers. Carried whole rather than pre-projected, so a client upserts
329    /// exactly the facts it indexes without this layer guessing at its schema.
330    ///
331    /// `None` exactly when the head action mints no metadata blob — `delete`,
332    /// `trash-restore`, and the derivative actions, per
333    /// [`Action::binds_metadata_blob`]. A tombstone is a legitimate, fully-verified entry that
334    /// simply carries no metadata; treating its absent blob as a binding failure would
335    /// quarantine every deletion the feed delivers.
336    pub sidecar: Option<SidecarV1>,
337}
338
339/// How applying one remote entry resolved. These three are the verdicts the
340/// [client validation duties] permit — there is no fourth, "ignored" case.
341///
342/// [client validation duties]: https://docs/design/clients/#client-validation-duties
343#[derive(Debug, Clone, PartialEq)]
344pub enum SyncApplyOutcome {
345    /// Verified end to end; the facts may be upserted.
346    Applied(Box<RemoteAssetFacts>),
347    /// Authorization is intact but the epoch's AMK has not arrived locally yet. Hold the entry
348    /// and retry — never quarantine (SSoT: [`PendingReason`]).
349    Pending(PendingReason),
350    /// Refused, with the reason to surface.
351    Quarantined(QuarantineReason),
352}
353
354impl SyncApplyOutcome {
355    /// The facts, if the entry applied.
356    pub fn facts(&self) -> Option<&RemoteAssetFacts> {
357        match self {
358            Self::Applied(facts) => Some(facts),
359            _ => None,
360        }
361    }
362}
363
364impl Workspace {
365    /// Apply one remote feed entry: verify it through the
366    /// [`verify_asset`](capsule_core::crypto::verify_asset::verify_asset) chokepoint, bind and
367    /// open its metadata blob, and project the result into [`RemoteAssetFacts`].
368    ///
369    /// Read-only with respect to this workspace — it decides *what is true* and leaves *what to
370    /// persist* to the caller's catalog. That split is deliberate: the same verdict feeds an
371    /// iOS gallery upsert, a CLI `sync` report, and a quarantine surface, none of which want
372    /// this layer writing to their index. A client whose catalog is this workspace's own adopts
373    /// the entry instead ([`adopt_remote_head`](Self::adopt_remote_head)).
374    ///
375    /// `Err` is reserved for a failure of *this workspace* (an unreadable album keystore, say).
376    /// A refused **entry** is never an `Err` — it is a [`SyncApplyOutcome::Quarantined`],
377    /// because a hostile feed must not be able to abort a whole sync by handing over one bad
378    /// row.
379    pub fn apply_remote_entry(&self, entry: RemoteEntry<'_>) -> Result<SyncApplyOutcome> {
380        self.apply_remote_head(entry.head())
381    }
382
383    /// [`apply_remote_entry`](Self::apply_remote_entry) for an entry whose original is named by
384    /// its SHA-256 ([`RemoteHead`]): the same chokepoint, metadata binding and verdicts, with
385    /// the content-integrity step run against the digest.
386    ///
387    /// An `Applied` verdict here attests the manifest and its metadata, and that the manifest
388    /// commits to `original_ciphertext_hash`; it says nothing about any bytes until the caller
389    /// has hashed them to that digest. [`open_remote_original_from`](Self::open_remote_original_from)
390    /// is the caller that does.
391    ///
392    /// # Errors
393    ///
394    /// As [`apply_remote_entry`](Self::apply_remote_entry).
395    #[tracing::instrument(skip_all, fields(album_id = %entry.album_id))]
396    pub fn apply_remote_head(&self, entry: RemoteHead<'_>) -> Result<SyncApplyOutcome> {
397        let record = match self.check_record(
398            entry.album_id,
399            entry.manifest_cbor,
400            Some(entry.original_ciphertext_hash),
401            entry.local_chain_head,
402        )? {
403            Ok(record) => record,
404            Err(refused) => return Ok(refused),
405        };
406        let manifest: AssetManifest = record.manifest;
407        let core = manifest.core.clone();
408
409        // ── Metadata: bind the blob to the manifest, then open it. ─────────────────────
410        //
411        // Only for an action that mints one. `delete`, `trash-restore`, and the derivative
412        // actions commit to no `metadata_blob_hash` by the presence-by-action rule — and
413        // `verify_asset`'s structural check already refused any manifest that disagrees with
414        // that rule, so this branch is a statement about the action, not a second guess at it.
415        // A tombstone is a fully-verified entry with no metadata; quarantining it for the
416        // absence would drop every deletion the feed delivers.
417        let sidecar = if core.action.binds_metadata_blob() {
418            match self.open_sidecar(&entry.album_id, &core, entry.metadata_blob)? {
419                Ok(sidecar) => Some(sidecar),
420                Err(refused) => return Ok(refused),
421            }
422        } else {
423            tracing::debug!(
424                action = ?core.action,
425                "sync-apply: action mints no metadata blob; applying without a sidecar"
426            );
427            None
428        };
429
430        // The record hash this entry establishes — the caller's next `local_chain_head`.
431        let provenance_head =
432            ProvenanceRecord::new(core.file_id, manifest, core.prior_provenance_hash).record_hash();
433
434        tracing::info!(
435            asset_id = %core.file_id,
436            action = ?core.action,
437            "sync-apply: entry verified and applied"
438        );
439        Ok(SyncApplyOutcome::Applied(Box::new(RemoteAssetFacts {
440            asset_id: core.file_id,
441            album_id: core.album_id,
442            amk_version: core.amk_version.0,
443            ciphertext_hash: core.ciphertext_hash,
444            plaintext_size: core.plaintext_size,
445            action: core.action,
446            timestamp: core.timestamp,
447            created_by_device: core.created_by_device,
448            provenance_head,
449            sidecar,
450        })))
451    }
452
453    /// Decode one provenance record off the wire and run it through the chokepoint: steps 1
454    /// and 2 of the module docs, everything an entry's verdict needs but its metadata.
455    ///
456    /// `original_ciphertext_hash` is the digest the content-integrity step checks against the
457    /// manifest's `ciphertext_hash`. `None` checks the record against the address it commits
458    /// to itself, which is how a **superseded** record of a fetched chain is checked
459    /// ([`Workspace::adopt_remote_history`]): the original it named may have been replaced
460    /// since, and the held original is the head's, which the head's own check binds.
461    ///
462    /// `Ok(Err(verdict))` is a refused record; `Err` only a failure of this workspace.
463    fn check_record(
464        &self,
465        album_id: Uuid,
466        manifest_cbor: &[u8],
467        original_ciphertext_hash: Option<Hash32>,
468        local_chain_head: Option<Hash32>,
469    ) -> Result<std::result::Result<ProvenanceRecord, SyncApplyOutcome>> {
470        use QuarantineReason::{
471            LegacyInheritedDevice, MalformedManifest, Purged, Rejected, UnknownAlbum,
472            UnsupportedRecordVersion,
473        };
474
475        // The feed serves the provenance blob's bytes, which are a *record* — see the module
476        // docs. Decoding them as a bare manifest is why a correctly pushed asset used to be
477        // quarantined by every receiving device.
478        let record = match ProvenanceRecord::decode(manifest_cbor) {
479            Ok(record) => record,
480            Err(RecordDecodeError::UnsupportedVersion { found, max_known }) => {
481                tracing::warn!(
482                    found,
483                    max_known,
484                    "sync-apply: provenance record from a newer writer; quarantined until update"
485                );
486                return Ok(Err(SyncApplyOutcome::Quarantined(
487                    UnsupportedRecordVersion { found, max_known },
488                )));
489            }
490            Err(RecordDecodeError::Malformed(e)) => {
491                tracing::warn!(error = %e, "sync-apply: provenance record CBOR did not decode");
492                return Ok(Err(SyncApplyOutcome::Quarantined(MalformedManifest(e))));
493            }
494        };
495        // The two copies of the chain link, checked before either is used. A record that
496        // disagrees with the manifest it carries is malformed whichever copy is right, and the
497        // manifest's is the signed one — so preferring either would be trusting a value no
498        // signature covers.
499        if !record.mirrors_manifest() {
500            tracing::warn!(
501                asset_id = %record.asset_id,
502                "sync-apply: the record's prior_provenance_hash does not mirror the manifest's"
503            );
504            return Ok(Err(SyncApplyOutcome::Quarantined(MalformedManifest(
505                "the record's prior_provenance_hash does not mirror the manifest's".to_owned(),
506            ))));
507        }
508        // The record names its asset too; a record whose subject is not the manifest's `file_id`
509        // is a splice of two assets' history and never applies.
510        if record.asset_id != record.manifest.core.file_id {
511            tracing::warn!(
512                record_asset = %record.asset_id,
513                manifest_asset = %record.manifest.core.file_id,
514                "sync-apply: the record names a different asset than its manifest"
515            );
516            return Ok(Err(SyncApplyOutcome::Quarantined(MalformedManifest(
517                format!(
518                    "record names asset {} but its manifest names {}",
519                    record.asset_id, record.manifest.core.file_id
520                ),
521            ))));
522        }
523        // A purged asset's tombstone outranks anything a feed says about it: checked before the
524        // album or the chokepoint, so no later entry, however well signed, revives it.
525        if self.purged.contains_key(&record.asset_id) {
526            tracing::warn!(
527                asset_id = %record.asset_id,
528                action = ?record.manifest.core.action,
529                "sync-apply: the asset was purged here; its tombstone refuses the entry"
530            );
531            return Ok(Err(SyncApplyOutcome::Quarantined(Purged(record.asset_id))));
532        }
533        let core = &record.manifest.core;
534        tracing::debug!(
535            asset_id = %core.file_id,
536            action = ?core.action,
537            amk_version = core.amk_version.0,
538            "sync-apply: manifest decoded"
539        );
540
541        // No keys, no authority, no verdict. Say so, rather than rejecting an entry this device
542        // simply cannot adjudicate.
543        if !self.has_album(&album_id) {
544            tracing::info!("sync-apply: no local key material for the album");
545            return Ok(Err(SyncApplyOutcome::Quarantined(UnknownAlbum(album_id))));
546        }
547        let authority = self.authority(&album_id)?;
548        let original_ciphertext_hash = original_ciphertext_hash.unwrap_or(core.ciphertext_hash);
549
550        // ── The chokepoint. Not re-implemented, not partially applied. ─────────────────
551        match verify_asset_hashed(
552            &record.manifest,
553            &original_ciphertext_hash,
554            &self.directory,
555            authority,
556            local_chain_head,
557        ) {
558            VerifyOutcome::Accept => Ok(Ok(record)),
559            VerifyOutcome::Pending(reason) => {
560                tracing::info!(?reason, "sync-apply: held pending — AMK not yet local");
561                Ok(Err(SyncApplyOutcome::Pending(reason)))
562            }
563            VerifyOutcome::TerminalReject(RejectReason::BadDeviceSig) => {
564                // Tell the pre-#475 continuation apart from a forgery. Either way it is refused.
565                if let Some(signing_device) = diagnose_misattributed_signer(
566                    &record.manifest,
567                    &original_ciphertext_hash,
568                    &self.directory,
569                    authority,
570                    local_chain_head,
571                ) {
572                    let record_hash = ProvenanceRecord::new(
573                        core.file_id,
574                        record.manifest.clone(),
575                        core.prior_provenance_hash,
576                    )
577                    .record_hash();
578                    tracing::warn!(
579                        asset_id = %core.file_id,
580                        named_device = %core.created_by_device,
581                        %signing_device,
582                        %record_hash,
583                        "sync-apply: quarantined a legacy inherited-device record; the chain stalls here"
584                    );
585                    return Ok(Err(SyncApplyOutcome::Quarantined(LegacyInheritedDevice {
586                        named_device: core.created_by_device,
587                        signing_device,
588                        record_hash,
589                    })));
590                }
591                tracing::warn!(
592                    reason = ?RejectReason::BadDeviceSig,
593                    "sync-apply: quarantined by verify_asset"
594                );
595                Ok(Err(SyncApplyOutcome::Quarantined(Rejected(
596                    RejectReason::BadDeviceSig,
597                ))))
598            }
599            VerifyOutcome::TerminalReject(reason) => {
600                tracing::warn!(?reason, "sync-apply: quarantined by verify_asset");
601                Ok(Err(SyncApplyOutcome::Quarantined(Rejected(reason))))
602            }
603        }
604    }
605
606    /// Bind `metadata_blob` to the manifest `core` the chokepoint accepted, open it, and check
607    /// the signed [`SidecarV1`] inside: steps 3 and 4 of the module docs. `core` must bind a
608    /// metadata blob ([`Action::binds_metadata_blob`]).
609    ///
610    /// `Ok(Err(verdict))` is a blob that does not bind or open, or a sidecar that does not
611    /// decode or verify; `Err` only a failure of this workspace.
612    fn open_sidecar(
613        &self,
614        album_id: &Uuid,
615        core: &ManifestCore,
616        metadata_blob: &[u8],
617    ) -> Result<std::result::Result<SidecarV1, SyncApplyOutcome>> {
618        use QuarantineReason::{Binding, MalformedSidecar, SidecarSignature};
619
620        let Some(committed) = core.metadata_blob_hash else {
621            return Ok(Err(SyncApplyOutcome::Quarantined(Binding(
622                BindingReject::NoManifestCommitment,
623            ))));
624        };
625        if blob_ciphertext_hash(metadata_blob) != committed {
626            tracing::warn!("sync-apply: metadata blob does not hash to the committed address");
627            return Ok(Err(SyncApplyOutcome::Quarantined(Binding(
628                BindingReject::BlobHashMismatch,
629            ))));
630        }
631        let album = self.album(album_id)?;
632        // `verify_asset` accepted, so the authority attests this epoch's AMK is held; a
633        // missing entry here would be a keystore inconsistency — reported as pending,
634        // never panicked.
635        let Some(amk_bytes) = album.amks.get(&core.amk_version.0).copied() else {
636            tracing::warn!(
637                epoch = core.amk_version.0,
638                "sync-apply: authority attests the AMK but the keystore holds no bytes for it"
639            );
640            return Ok(Err(SyncApplyOutcome::Pending(
641                PendingReason::AmkNotYetLocal,
642            )));
643        };
644        let Some(nonce) = blob_nonce(metadata_blob) else {
645            return Ok(Err(SyncApplyOutcome::Quarantined(Binding(
646                BindingReject::Undecryptable,
647            ))));
648        };
649        let blob_key = Amk::from_bytes(amk_bytes).derive_blob_key(&core.file_id, &nonce);
650        let Ok(plaintext) = open_blob(&blob_key, metadata_blob) else {
651            tracing::warn!("sync-apply: metadata blob failed to open under the derived blob key");
652            return Ok(Err(SyncApplyOutcome::Quarantined(Binding(
653                BindingReject::Undecryptable,
654            ))));
655        };
656
657        // `from_canonical_slice` is also where the **forward-version refusal** lives: a
658        // sidecar whose `sidecar_schema` exceeds this build's max known is refused rather
659        // than strip-and-re-signed, which is a client validation duty in its own right.
660        let sidecar = match SidecarV1::from_canonical_slice(&plaintext, SIDECAR_SCHEMA_V1) {
661            Ok(sidecar) => sidecar,
662            Err(e) => {
663                tracing::warn!(error = %e, "sync-apply: sidecar did not decode");
664                return Ok(Err(SyncApplyOutcome::Quarantined(MalformedSidecar(e))));
665            }
666        };
667        // The sidecar carries its own hybrid signature under the account's user IK (the key
668        // that also signs the device directory). Checking it here is what makes the
669        // decrypted metadata *facts* rather than merely plaintext.
670        if !sidecar.verify(&self.user_ik_public()) {
671            tracing::warn!("sync-apply: sidecar signature does not verify under the user IK");
672            return Ok(Err(SyncApplyOutcome::Quarantined(SidecarSignature)));
673        }
674        Ok(Ok(sidecar))
675    }
676
677    /// Verify a remote entry and **open its original**: run it through
678    /// [`apply_remote_entry`](Self::apply_remote_entry), recover the original's file key from
679    /// this workspace's album keys (honouring the manifest's `key_mode`), decrypt the STREAM
680    /// ciphertext, and check the plaintext digest against the signed sidecar's `hash`.
681    ///
682    /// The read half of a restore: what comes back as [`RemoteOriginal::Opened`] is byte for
683    /// byte the original the account's device signed, because every link from the bytes to a
684    /// signature has been checked — the ciphertext against the manifest's `ciphertext_hash`
685    /// (inside the chokepoint), every chunk against its AEAD tag, and the plaintext against the
686    /// sidecar's digest, which the account's identity key signs. A head that binds no metadata
687    /// blob (a `trash-restore`, say) has no sidecar, so its plaintext stands on the first two.
688    ///
689    /// An entry that does not apply is handed back unchanged as [`RemoteOriginal::Refused`] —
690    /// nothing is decrypted. Read-only with respect to this workspace, like the apply it wraps.
691    ///
692    /// # Errors
693    ///
694    /// As [`apply_remote_entry`](Self::apply_remote_entry): only a failure of this workspace
695    /// itself. A file key that cannot be recovered or bytes that do not open are verdicts
696    /// ([`RemoteOriginal::Undecryptable`], [`RemoteOriginal::DigestMismatch`]), never errors.
697    pub fn open_remote_original(&self, entry: RemoteEntry<'_>) -> Result<RemoteOriginal> {
698        self.open_remote_original_from(entry.head(), entry.original_ciphertext, Vec::new())
699    }
700
701    /// [`open_remote_original`](Self::open_remote_original) in bounded memory: the original's
702    /// ciphertext is read from `ciphertext` and its plaintext written to `plaintext` one STREAM
703    /// chunk at a time, so opening an original of any size holds a few chunks of it.
704    ///
705    /// The checks are [`open_remote_original`](Self::open_remote_original)'s, in an order a
706    /// stream allows. The head goes through the chokepoint first
707    /// ([`apply_remote_head`](Self::apply_remote_head)), against its claimed
708    /// `original_ciphertext_hash`; then every ciphertext byte read is hashed while it is
709    /// decrypted, and the original opens only if that hash is the manifest's `ciphertext_hash`,
710    /// every chunk authenticated, and the plaintext hashes to the signed sidecar's digest.
711    /// Bytes that are not the committed ciphertext are refused as the chokepoint refuses them
712    /// ([`RejectReason::CiphertextHashMismatch`]), whichever check they fail first.
713    ///
714    /// Plaintext reaches `plaintext` before those checks finish, so the writer holds
715    /// **unverified** bytes until this returns [`RemoteOriginal::Opened`], which hands the writer
716    /// back. On any other outcome the caller must discard what it wrote. An entry that does not
717    /// apply is refused before anything is read or written.
718    ///
719    /// # Errors
720    ///
721    /// As [`open_remote_original`](Self::open_remote_original), plus [`LifecycleError::Io`] when
722    /// `ciphertext` cannot be read or `plaintext` cannot be written.
723    #[tracing::instrument(skip_all, fields(album_id = %entry.album_id))]
724    pub fn open_remote_original_from<R: Read, W: Write>(
725        &self,
726        entry: RemoteHead<'_>,
727        mut ciphertext: R,
728        plaintext: W,
729    ) -> Result<RemoteOriginal<W>> {
730        let facts = match self.apply_remote_head(entry)? {
731            SyncApplyOutcome::Applied(facts) => facts,
732            refused => return Ok(RemoteOriginal::Refused(refused)),
733        };
734        // The apply decoded these exact bytes a moment ago, so this cannot fail; answered as a
735        // verdict rather than unwrapped all the same.
736        let Ok(record) = ProvenanceRecord::decode(entry.manifest_cbor) else {
737            return Ok(RemoteOriginal::Undecryptable { facts });
738        };
739        let core = &record.manifest.core;
740        let album = self.album(&facts.album_id)?;
741        let file_key = match self.original_file_key(album, core) {
742            Ok(key) => key,
743            Err(error) => {
744                tracing::warn!(asset_id = %facts.asset_id, %error, "open-remote: the file key could not be recovered");
745                return Ok(RemoteOriginal::Undecryptable { facts });
746            }
747        };
748        // One pass over the ciphertext: every byte read is hashed, and fed to the decryptor
749        // until a chunk fails authentication. The rest is still read and hashed, so bytes that
750        // are not the committed ciphertext earn the chokepoint's verdict, not a decrypt failure.
751        let mut ciphertext_hash = Sha256Hasher::new();
752        let mut decryptor = Some(StreamDecryptor::new(
753            &file_key,
754            &core.nonce_prefix,
755            DigestWriter::new(plaintext),
756        ));
757        let mut window = vec![0u8; CIPHERTEXT_CHUNK];
758        let mut read: u64 = 0;
759        loop {
760            let n = match ciphertext.read(&mut window) {
761                Ok(0) => break,
762                Ok(n) => n,
763                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
764                Err(error) => {
765                    return Err(LifecycleError::Io(format!(
766                        "reading the original's ciphertext: {error}"
767                    )));
768                }
769            };
770            ciphertext_hash.update(&window[..n]);
771            read += n as u64;
772            if let Some(open) = decryptor.as_mut() {
773                match open.update(&window[..n]) {
774                    Ok(()) => {}
775                    Err(StreamError::Auth(chunk)) => {
776                        tracing::warn!(asset_id = %facts.asset_id, chunk, "open-remote: a chunk of the original failed authentication");
777                        decryptor = None;
778                    }
779                    Err(StreamError::Io(error)) => {
780                        return Err(LifecycleError::Io(format!(
781                            "writing the original's plaintext: {error}"
782                        )));
783                    }
784                }
785            }
786        }
787        if ciphertext_hash.finalize() != core.ciphertext_hash {
788            tracing::warn!(
789                asset_id = %facts.asset_id,
790                bytes = read,
791                "open-remote: the streamed ciphertext does not hash to the manifest's content address"
792            );
793            return Ok(RemoteOriginal::Refused(SyncApplyOutcome::Quarantined(
794                QuarantineReason::Rejected(RejectReason::CiphertextHashMismatch),
795            )));
796        }
797        let Some(decryptor) = decryptor else {
798            return Ok(RemoteOriginal::Undecryptable { facts });
799        };
800        let opened = match decryptor.finish() {
801            Ok(opened) => opened,
802            Err(StreamError::Auth(chunk)) => {
803                tracing::warn!(asset_id = %facts.asset_id, chunk, "open-remote: the original's last chunk failed authentication");
804                return Ok(RemoteOriginal::Undecryptable { facts });
805            }
806            Err(StreamError::Io(error)) => {
807                return Err(LifecycleError::Io(format!(
808                    "writing the original's plaintext: {error}"
809                )));
810            }
811        };
812        let (plaintext, digest, written) = opened.into_parts();
813        if let Some(sidecar) = &facts.sidecar
814            && digest != sidecar.hash
815        {
816            tracing::warn!(
817                asset_id = %facts.asset_id,
818                "open-remote: the plaintext digest differs from the signed sidecar's"
819            );
820            return Ok(RemoteOriginal::DigestMismatch { facts });
821        }
822        tracing::debug!(
823            asset_id = %facts.asset_id,
824            ciphertext_bytes = read,
825            plaintext_bytes = written,
826            "open-remote: original verified and decrypted"
827        );
828        Ok(RemoteOriginal::Opened { facts, plaintext })
829    }
830}
831
832/// What adopting one applied entry did to the assets this workspace holds
833/// ([`Workspace::adopt_remote_head`], [`Workspace::adopt_remote_original`]).
834///
835/// Adoption never decides whether an entry is true; the chokepoint did. It decides only
836/// whether the verified record can become part of a chain this workspace holds without
837/// breaking that chain's rules: a chain starts at its `create`
838/// ([`ProvenanceChain::append`]), and each later record names the head before it.
839#[derive(Debug, Clone, Copy, PartialEq, Eq)]
840pub enum Adoption {
841    /// A `create` of an asset this workspace did not hold. Its record, sidecar, sealed metadata
842    /// blob and original are written under `media/`, its row and user tags indexed, and the
843    /// asset is held: the trash verbs, tag edits and uploads work on it, and its next signed
844    /// record chains onto the create.
845    Adopted,
846    /// A record of a held asset that chains onto its head. It is appended; the sidecar and
847    /// sealed metadata blob follow it when it binds one, the original when it replaces it, and
848    /// the index row is rewritten.
849    Advanced,
850    /// The held chain already contains this record. Nothing was written.
851    AlreadyHeld,
852    /// An asset this workspace does not hold, whose record is not its `create`. A chain cannot
853    /// start anywhere but at its create, and the feed carries only an asset's latest record, so
854    /// the asset stays unheld until its earlier records are fetched and handed to
855    /// [`Workspace::adopt_remote_history`]. Nothing was written.
856    MissingHistory,
857    /// A record that needs the plaintext original — the `create` of an unheld asset, or one
858    /// that replaces a held original — applied without it. Nothing was written; adopt it
859    /// through [`Workspace::adopt_remote_original`].
860    NeedsOriginal,
861    /// A record of a held asset that does not chain onto its head: a fork, or a gap of records
862    /// this workspace has not seen. Nothing was written; the held chain stands.
863    Diverged,
864}
865
866impl Adoption {
867    /// Whether the workspace holds the asset at the entry's record afterwards, so its own index
868    /// row and user tags describe the asset and a catalog writer has nothing to add.
869    #[must_use]
870    pub fn holds(self) -> bool {
871        matches!(self, Self::Adopted | Self::Advanced | Self::AlreadyHeld)
872    }
873}
874
875impl Workspace {
876    /// [`apply_remote_head`](Self::apply_remote_head), then **adopt** what applied: a record
877    /// that chains onto an asset this workspace holds is appended to its chain, with the
878    /// sealed metadata it binds, and written under `media/` and indexed, so the asset's next
879    /// signed record chains onto the head the server holds.
880    ///
881    /// A record that needs the original's plaintext (a `create`, or a replace) is not adopted
882    /// here: it answers [`Adoption::NeedsOriginal`], and
883    /// [`adopt_remote_original`](Self::adopt_remote_original) adopts it. A record that does
884    /// not change the original needs none, because the held original is the one it commits to.
885    ///
886    /// The verdict is exactly [`apply_remote_head`](Self::apply_remote_head)'s, and the
887    /// [`Adoption`] is `Some` only for an `Applied` one.
888    ///
889    /// # Errors
890    ///
891    /// As [`apply_remote_head`](Self::apply_remote_head), plus the I/O or index failure that
892    /// stopped an adoption's write.
893    #[tracing::instrument(skip_all, fields(album_id = %entry.album_id))]
894    pub fn adopt_remote_head(
895        &mut self,
896        entry: RemoteHead<'_>,
897    ) -> Result<(SyncApplyOutcome, Option<Adoption>)> {
898        self.adopt_remote(entry, None)
899    }
900
901    /// [`adopt_remote_head`](Self::adopt_remote_head) for an entry whose original's verified
902    /// plaintext is the file at `plaintext` — the one an
903    /// [`open_remote_original_from`](Self::open_remote_original_from) of the same head answered
904    /// [`RemoteOriginal::Opened`] for. This is what adopts a `create`: the asset is held with
905    /// that original as its library copy.
906    ///
907    /// The file is not trusted for being handed over. It is placed only if it hashes to the
908    /// digest the entry's signed sidecar commits to, and is copied into `media/` (never
909    /// hard-linked), so `plaintext` is left in place for its owner to keep or remove, and
910    /// nothing later written to it reaches the library original.
911    /// An entry that does not need the original adopts as
912    /// [`adopt_remote_head`](Self::adopt_remote_head) would, without reading the file.
913    ///
914    /// # Errors
915    ///
916    /// As [`adopt_remote_head`](Self::adopt_remote_head), and
917    /// [`LifecycleError::OriginalMismatch`] when the file is not the signed original (nothing of
918    /// the asset is written).
919    #[tracing::instrument(skip_all, fields(album_id = %entry.album_id, plaintext = %plaintext.display()))]
920    pub fn adopt_remote_original(
921        &mut self,
922        entry: RemoteHead<'_>,
923        plaintext: &Path,
924    ) -> Result<(SyncApplyOutcome, Option<Adoption>)> {
925        self.adopt_remote(entry, Some(plaintext))
926    }
927
928    /// [`adopt_remote_original`](Self::adopt_remote_original) for an asset first seen **past its
929    /// create**: `history` is every record of its chain before the entry's, oldest first and
930    /// starting at its `create`, each the canonical CBOR the server stores (the provenance blob
931    /// a record's successor names by `prior_provenance_hash`). This is what adopts an asset
932    /// [`adopt_remote_head`](Self::adopt_remote_head) answers [`Adoption::MissingHistory`] for.
933    ///
934    /// Every record goes through the chokepoint in order, each against the hash of the one
935    /// before it and the create against no head, so the chain held is one that verifies from its
936    /// start; the entry's record is then applied against the last of them, whatever
937    /// [`RemoteHead::local_chain_head`] says. A superseded record's content-integrity step is
938    /// checked against the ciphertext it commits to itself: the original it named may have been
939    /// replaced since, and the original held is the entry's, which the entry's own check binds.
940    ///
941    /// A superseded record's sealed metadata is not on the server any more (a newer blob
942    /// replaced it and the collector reclaimed it), so the sidecar is opened from the entry's
943    /// `metadata_blob`, the asset's live one: bound to the entry's record when it binds one, and
944    /// otherwise to the newest record of `history` that does. The original at `plaintext` is
945    /// placed only if it hashes to that sidecar's digest.
946    ///
947    /// The verdict returned is the first one that is not `Applied`, in chain order: a record of
948    /// `history` that does not verify, a record naming another asset, or a live metadata blob
949    /// that does not bind, refuses the whole adoption and writes nothing. An empty `history`
950    /// adopts as [`adopt_remote_original`](Self::adopt_remote_original) would, and so does an
951    /// entry of an asset this workspace already holds: the history is not read, so none of its
952    /// records can refuse the entry, and the entry is checked against
953    /// [`RemoteHead::local_chain_head`].
954    ///
955    /// # Errors
956    ///
957    /// As [`adopt_remote_original`](Self::adopt_remote_original).
958    #[tracing::instrument(skip_all, fields(album_id = %entry.album_id, records = history.len(), plaintext = %plaintext.display()))]
959    pub fn adopt_remote_history(
960        &mut self,
961        entry: RemoteHead<'_>,
962        history: &[Vec<u8>],
963        plaintext: &Path,
964    ) -> Result<(SyncApplyOutcome, Option<Adoption>)> {
965        if history.is_empty() {
966            return self.adopt_remote(entry, Some(plaintext));
967        }
968        // An asset held here already extends its own chain, so the history is not read at all:
969        // the entry is adopted exactly as `adopt_remote_original` adopts it, against the
970        // caller's `local_chain_head`, and a history record that would not verify cannot
971        // refuse an advance that verb applies. Bytes that do not decode fall through to the
972        // checks below, which refuse them.
973        if let Ok(record) = ProvenanceRecord::decode(entry.manifest_cbor)
974            && self.assets.contains_key(&record.manifest.core.file_id)
975        {
976            tracing::info!(
977                asset_id = %record.manifest.core.file_id,
978                records = history.len(),
979                "sync-adopt: the asset is held already; adopting the entry with the history unread"
980            );
981            return self.adopt_remote(entry, Some(plaintext));
982        }
983        // The superseded records, in order, each against the one before it.
984        let mut records = Vec::with_capacity(history.len() + 1);
985        let mut head = None;
986        for (position, bytes) in history.iter().enumerate() {
987            let record = match self.check_record(entry.album_id, bytes, None, head)? {
988                Ok(record) => record,
989                Err(refused) => {
990                    tracing::warn!(
991                        position,
992                        ?refused,
993                        "sync-adopt: a record of the fetched history did not verify; nothing adopted"
994                    );
995                    return Ok((refused, None));
996                }
997            };
998            head = Some(record.record_hash());
999            records.push(record);
1000        }
1001        let entry = RemoteHead {
1002            local_chain_head: head,
1003            ..entry
1004        };
1005        let outcome = self.apply_remote_head(entry)?;
1006        let SyncApplyOutcome::Applied(facts) = &outcome else {
1007            return Ok((outcome, None));
1008        };
1009        let Ok(record) = ProvenanceRecord::decode(entry.manifest_cbor) else {
1010            return Ok((outcome, None));
1011        };
1012        // A chain is one asset's. A record of another asset's history linked in by hash is a
1013        // splice, however well each record verifies on its own.
1014        if let Some(stray) = records.iter().find(|r| r.asset_id != facts.asset_id) {
1015            tracing::warn!(
1016                asset_id = %facts.asset_id,
1017                stray = %stray.asset_id,
1018                "sync-adopt: the fetched history names another asset; nothing adopted"
1019            );
1020            return Ok((
1021                SyncApplyOutcome::Quarantined(QuarantineReason::MalformedManifest(format!(
1022                    "the history of asset {} holds a record of asset {}",
1023                    facts.asset_id, stray.asset_id
1024                ))),
1025                None,
1026            ));
1027        }
1028        let sidecar = if let Some(sidecar) = facts.sidecar.clone() {
1029            sidecar
1030        } else {
1031            // A create binds a metadata blob, so a verified history always holds one.
1032            let Some(binding) = records
1033                .iter()
1034                .rev()
1035                .find(|r| r.manifest.core.action.binds_metadata_blob())
1036            else {
1037                return Err(LifecycleError::RestoredMetadata(format!(
1038                    "asset {}: a verified history binds no metadata blob",
1039                    facts.asset_id
1040                )));
1041            };
1042            match self.open_sidecar(&entry.album_id, &binding.manifest.core, entry.metadata_blob)? {
1043                Ok(sidecar) => sidecar,
1044                Err(refused) => {
1045                    tracing::warn!(
1046                        asset_id = %facts.asset_id,
1047                        ?refused,
1048                        "sync-adopt: the live metadata blob does not bind to the newest record that binds one"
1049                    );
1050                    return Ok((refused, None));
1051                }
1052            }
1053        };
1054        let mut chain = ProvenanceChain::new();
1055        for held in records.into_iter().chain(std::iter::once(record)) {
1056            chain
1057                .append(held)
1058                .map_err(|e| LifecycleError::Cbor(format!("adopted chain: {e}")))?;
1059        }
1060        let records = chain.records().len();
1061        let adoption = self.hold_adopted(chain, facts, sidecar, entry.metadata_blob, plaintext)?;
1062        tracing::info!(
1063            asset_id = %facts.asset_id,
1064            action = ?facts.action,
1065            records,
1066            ?adoption,
1067            "sync-adopt: an asset first seen past its create adopted from its fetched history"
1068        );
1069        Ok((outcome, Some(adoption)))
1070    }
1071
1072    fn adopt_remote(
1073        &mut self,
1074        entry: RemoteHead<'_>,
1075        plaintext: Option<&Path>,
1076    ) -> Result<(SyncApplyOutcome, Option<Adoption>)> {
1077        let outcome = self.apply_remote_head(entry)?;
1078        let SyncApplyOutcome::Applied(facts) = &outcome else {
1079            return Ok((outcome, None));
1080        };
1081        // The apply decoded these exact bytes a moment ago, so this cannot fail; answered as
1082        // "nothing adopted" rather than unwrapped all the same.
1083        let Ok(record) = ProvenanceRecord::decode(entry.manifest_cbor) else {
1084            return Ok((outcome, None));
1085        };
1086        let adoption = if self.assets.contains_key(&facts.asset_id) {
1087            self.advance_held(record, facts, entry.metadata_blob, plaintext)?
1088        } else {
1089            self.adopt_unheld(record, facts, entry.metadata_blob, plaintext)?
1090        };
1091        tracing::info!(
1092            asset_id = %facts.asset_id,
1093            action = ?facts.action,
1094            ?adoption,
1095            "sync-adopt: applied entry adopted"
1096        );
1097        Ok((outcome, Some(adoption)))
1098    }
1099
1100    /// Hold an asset from its verified `create`: the record, sidecar and sealed blob the entry
1101    /// carried, and the original at `plaintext`.
1102    fn adopt_unheld(
1103        &mut self,
1104        record: ProvenanceRecord,
1105        facts: &RemoteAssetFacts,
1106        metadata_blob: &[u8],
1107        plaintext: Option<&Path>,
1108    ) -> Result<Adoption> {
1109        if record.manifest.core.action != Action::Create {
1110            tracing::info!(
1111                asset_id = %facts.asset_id,
1112                action = ?facts.action,
1113                "sync-adopt: an unheld asset's record is not its create; its earlier records are not here"
1114            );
1115            return Ok(Adoption::MissingHistory);
1116        }
1117        let Some(plaintext) = plaintext else {
1118            tracing::debug!(asset_id = %facts.asset_id, "sync-adopt: a create needs its original");
1119            return Ok(Adoption::NeedsOriginal);
1120        };
1121        // A create binds a metadata blob, so the apply opened and verified its sidecar.
1122        let Some(sidecar) = facts.sidecar.clone() else {
1123            return Err(LifecycleError::RestoredMetadata(format!(
1124                "asset {}: an applied create carries no sidecar",
1125                facts.asset_id
1126            )));
1127        };
1128        let mut chain = ProvenanceChain::new();
1129        chain
1130            .append(record)
1131            .map_err(|e| LifecycleError::Cbor(format!("adopted chain: {e}")))?;
1132        self.hold_adopted(chain, facts, sidecar, metadata_blob, plaintext)
1133    }
1134
1135    /// Hold a newly adopted asset: `chain` from its create, the verified `sidecar` and the
1136    /// sealed `metadata_blob` it was opened from, and the original at `plaintext`.
1137    fn hold_adopted(
1138        &mut self,
1139        chain: ProvenanceChain,
1140        facts: &RemoteAssetFacts,
1141        sidecar: SidecarV1,
1142        metadata_blob: &[u8],
1143        plaintext: &Path,
1144    ) -> Result<Adoption> {
1145        // Filed under the sidecar's capture time, as a reopen reads it back
1146        // (`restore_one_asset` step 3) and as a restore files a new asset.
1147        let capture_utc = sidecar
1148            .capture_timestamp
1149            .parse::<Timestamp>()
1150            .or_else(|_| facts.timestamp.parse::<Timestamp>())
1151            .map_or(0, Timestamp::as_second);
1152        let stack = sidecar
1153            .stack_membership
1154            .get()
1155            .and_then(|membership| membership.as_ref().map(StackPlacement::from_membership));
1156        let mut asset = AssetState {
1157            asset_id: facts.asset_id,
1158            album_id: facts.album_id,
1159            ext: extension_for(&sidecar.content_type).to_owned(),
1160            capture_utc,
1161            chain,
1162            sidecar,
1163            metadata_blob: metadata_blob.to_vec(),
1164            stack,
1165        };
1166        let bytes = self.place_adopted_original(&mut asset, plaintext)?;
1167        self.write_signed_artifacts(&asset)?;
1168        self.index_asset_with_original(&asset, usize::try_from(bytes).unwrap_or(usize::MAX))?;
1169        self.assets.insert(asset.asset_id, asset);
1170        Ok(Adoption::Adopted)
1171    }
1172
1173    /// The library original of a newly adopted asset, placed from `plaintext`. An original the
1174    /// library already holds under the asset's name — one an app placed before the workspace
1175    /// adopted synced assets — is kept when it is the signed original, under its own extension,
1176    /// and removed when it is not.
1177    fn place_adopted_original(&self, asset: &mut AssetState, plaintext: &Path) -> Result<u64> {
1178        let dir = media_dir(&self.root, asset.capture_utc);
1179        if let Some(found) = original_extension(&dir, &asset.asset_id) {
1180            let held = media_file_path(&self.root, asset.capture_utc, asset.asset_id, &found);
1181            let (digest, len) = std::fs::File::open(&held)
1182                .map_err(|e| LifecycleError::Io(format!("open {}: {e}", held.display())))
1183                .and_then(hash_ciphertext_from)?;
1184            if digest == asset.sidecar.hash {
1185                tracing::debug!(asset_id = %asset.asset_id, ext = %found, "sync-adopt: keeping the signed original already in the library");
1186                asset.ext = found;
1187                return Ok(len);
1188            }
1189            tracing::warn!(asset_id = %asset.asset_id, ext = %found, "sync-adopt: removing a file under the asset's name that is not its signed original");
1190            std::fs::remove_file(&held)
1191                .map_err(|e| LifecycleError::Io(format!("remove {}: {e}", held.display())))?;
1192        }
1193        self.place_original_from(asset, plaintext, asset.sidecar.hash)
1194    }
1195
1196    /// Append a verified record onto the held chain it extends.
1197    fn advance_held(
1198        &mut self,
1199        record: ProvenanceRecord,
1200        facts: &RemoteAssetFacts,
1201        metadata_blob: &[u8],
1202        plaintext: Option<&Path>,
1203    ) -> Result<Adoption> {
1204        let asset_id = facts.asset_id;
1205        let held = &self.assets[&asset_id];
1206        if held
1207            .chain
1208            .records()
1209            .iter()
1210            .any(|held| held.record_hash() == facts.provenance_head)
1211        {
1212            tracing::debug!(%asset_id, "sync-adopt: the held chain already contains the record");
1213            return Ok(Adoption::AlreadyHeld);
1214        }
1215        if record.prior_provenance_hash != held.chain.head() {
1216            tracing::warn!(
1217                %asset_id,
1218                action = ?facts.action,
1219                "sync-adopt: the record does not chain onto the held head; the held chain stands"
1220            );
1221            return Ok(Adoption::Diverged);
1222        }
1223        let mut chain = held.chain.clone();
1224        chain
1225            .append(record)
1226            .map_err(|e| LifecycleError::Cbor(format!("adopted chain: {e}")))?;
1227        let held_ciphertext = held
1228            .chain
1229            .records()
1230            .last()
1231            .expect("provenance chain is never empty")
1232            .manifest
1233            .core
1234            .ciphertext_hash;
1235        let replaces_original = facts.ciphertext_hash != held_ciphertext;
1236        if replaces_original && plaintext.is_none() {
1237            tracing::debug!(%asset_id, "sync-adopt: the record replaces the original; it needs the new one");
1238            return Ok(Adoption::NeedsOriginal);
1239        }
1240        let binds = facts.action.binds_metadata_blob();
1241        // A replaced original is placed before anything of the asset changes, so an original
1242        // that is not the signed one leaves the held asset exactly as it was. It keeps the held
1243        // original's name: its shard and extension.
1244        let placed = match plaintext.filter(|_| replaces_original) {
1245            Some(plaintext) => {
1246                let expected = facts.sidecar.as_ref().map_or(held.sidecar.hash, |s| s.hash);
1247                Some(self.place_original_from(held, plaintext, expected)?)
1248            }
1249            None => None,
1250        };
1251        // The record's sealed metadata replaces the held one, so the blob the create binds is
1252        // kept first, as a local edit keeps it: an upload of the create needs those bytes.
1253        if binds {
1254            self.keep_create_metadata_blob(&asset_id)?;
1255        }
1256        let asset = self
1257            .assets
1258            .get_mut(&asset_id)
1259            .expect("the asset is held: checked above");
1260        if let Some(sidecar) = facts.sidecar.as_ref().filter(|_| binds) {
1261            asset.sidecar = sidecar.clone();
1262            asset.metadata_blob = metadata_blob.to_vec();
1263            if let Some(membership) = asset.sidecar.stack_membership.get() {
1264                asset.stack = membership.as_ref().map(StackPlacement::from_membership);
1265            }
1266        }
1267        asset.chain = chain;
1268        let asset = &self.assets[&asset_id];
1269        if let Some(bytes) = placed {
1270            self.index_original_representation(
1271                asset,
1272                usize::try_from(bytes).unwrap_or(usize::MAX),
1273            )?;
1274        }
1275        self.write_signed_artifacts(asset)?;
1276        self.index_asset_row(asset)?;
1277        Ok(Adoption::Advanced)
1278    }
1279}
1280
1281/// A writer that hashes and counts what passes through it to `inner`.
1282struct DigestWriter<W> {
1283    inner: W,
1284    hasher: Sha256Hasher,
1285    written: u64,
1286}
1287
1288impl<W> DigestWriter<W> {
1289    fn new(inner: W) -> Self {
1290        Self {
1291            inner,
1292            hasher: Sha256Hasher::new(),
1293            written: 0,
1294        }
1295    }
1296
1297    /// The inner writer, the SHA-256 of everything written, and its length.
1298    fn into_parts(self) -> (W, Hash32, u64) {
1299        (self.inner, self.hasher.finalize(), self.written)
1300    }
1301}
1302
1303impl<W: Write> Write for DigestWriter<W> {
1304    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1305        let n = self.inner.write(buf)?;
1306        self.hasher.update(&buf[..n]);
1307        self.written += n as u64;
1308        Ok(n)
1309    }
1310
1311    fn flush(&mut self) -> std::io::Result<()> {
1312        self.inner.flush()
1313    }
1314}
1315
1316/// How [`Workspace::open_remote_original`] (`P` = `Vec<u8>`) or
1317/// [`Workspace::open_remote_original_from`] (`P` = the caller's writer) resolved.
1318#[derive(Debug, Clone, PartialEq)]
1319pub enum RemoteOriginal<P = Vec<u8>> {
1320    /// Verified end to end and decrypted; when the head carries a sidecar, the plaintext hashes
1321    /// to its signed digest.
1322    Opened {
1323        /// The verified facts of the entry.
1324        facts: Box<RemoteAssetFacts>,
1325        /// The original's bytes, or the writer they were streamed into.
1326        plaintext: P,
1327    },
1328    /// The entry did not apply (held pending or quarantined), or the ciphertext streamed to
1329    /// [`Workspace::open_remote_original_from`] is not the one its head named
1330    /// ([`RejectReason::CiphertextHashMismatch`]). Nothing decrypted is to be kept.
1331    Refused(SyncApplyOutcome),
1332    /// The entry applied, but its file key could not be recovered or its ciphertext failed
1333    /// authentication under it.
1334    Undecryptable {
1335        /// The verified facts of the entry.
1336        facts: Box<RemoteAssetFacts>,
1337    },
1338    /// The ciphertext opened, but the plaintext does not hash to the signed sidecar's digest.
1339    DigestMismatch {
1340        /// The verified facts of the entry.
1341        facts: Box<RemoteAssetFacts>,
1342    },
1343}
1344
1345#[cfg(test)]
1346mod tests;