Skip to main content

capsule_library/lifecycle/
import.rs

1//! The signed import path: EXIF scan, encrypt, sign the create manifest, seal the sidecar,
2//! self-verify, and write through to the queryable index.
3
4use std::collections::BTreeMap;
5use std::fs;
6use std::io::{self, Read, Seek, SeekFrom, Write};
7use std::path::Path;
8
9use capsule_core::cbor;
10use capsule_core::crypto::encryption::{
11    RekeyStreamError, blob_ciphertext_hash, encrypt_asset_rekey_stream, seal_metadata_blob,
12};
13use capsule_core::crypto::hash;
14use capsule_core::crypto::hash::{Hash32, Sha256Hasher};
15use capsule_core::crypto::keys::{Amk, AmkVersion};
16use capsule_core::crypto::primitives::{CRYPTO_SUITE_ID, PROTOCOL_VERSION};
17use capsule_core::crypto::provenance::{
18    ASSET_MANIFEST_VERSION, Action, KeyMode, ManifestCore, ProvenanceChain, ProvenanceRecord,
19};
20use capsule_core::crypto::verify_asset::{
21    MetadataBinding, VerifyOutcome, verify_asset_hashed, verify_metadata_binding,
22};
23use capsule_core::media::{MAX_DECODE_PIXELS, StillFormat};
24use capsule_core::metadata::crdt::{Lww, OrSet};
25use capsule_core::sidecar::normalize_label;
26use capsule_core::sidecar::sidecar_v1::{
27    Gps, GpsSource, SIDECAR_SCHEMA_V1, SidecarV1, StackMembership, StackRole,
28};
29use jiff::Timestamp;
30use uuid::Uuid;
31
32use super::derivatives::{PreparedStill, StillSource};
33use super::{
34    AssetState, DerivativeStatus, LifecycleError, Result, SidecarEnrichment, SignedImport,
35    SignedImportOptions, StackPlacement, StreamedImport, Workspace, asset_is_deleted, media_dir,
36    media_file_path, now_rfc3339,
37};
38use crate::db::{AssetRow, CachedRepresentationRow};
39use crate::exif::{ExifExtract, extract_exif, resolve_timezone};
40use crate::library::{ReleaseDecision, RetainReason, StorageVerifier, release_move_source};
41use crate::utils::paths::{sync_dir, tmp_path};
42
43/// A rename in [`Workspace::write_signed_artifacts`] a test can make fail after its `.tmp`
44/// write — the crash the temp-then-rename writes exist to survive (maintenance doc, Atomic
45/// Writes).
46#[cfg(test)]
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub(super) enum WriteFault {
49    /// Before the signed sidecar is renamed into place.
50    SidecarRename,
51    /// Before the provenance chain is renamed into place — the sidecar and blob already are.
52    ChainRename,
53}
54
55// The armed fault and how many matching renames to let through before it fires.
56// `#[cfg(test)]` and thread-local for the same reasons as `derivatives::SealerFault`: absent
57// from a release build, and a test seam that stays out of a production signature.
58#[cfg(test)]
59thread_local! {
60    static WRITE_FAULT: std::cell::Cell<Option<(WriteFault, u32)>> =
61        const { std::cell::Cell::new(None) };
62}
63
64/// Run `body` with the `skip + 1`-th rename at `point` failing after its `.tmp` write (the
65/// earlier ones succeed), disarming after.
66#[cfg(test)]
67pub(super) fn with_write_fault<T>(point: WriteFault, skip: u32, body: impl FnOnce() -> T) -> T {
68    WRITE_FAULT.with(|slot| slot.set(Some((point, skip))));
69    let out = body();
70    WRITE_FAULT.with(|slot| slot.set(None));
71    out
72}
73
74/// Whether the armed fault fires at `point` now; counts down the renames it lets through.
75#[cfg(test)]
76fn write_fault_fires(point: WriteFault) -> bool {
77    WRITE_FAULT.with(|slot| match slot.get() {
78        Some((armed, 0)) if armed == point => {
79            slot.set(None);
80            true
81        }
82        Some((armed, n)) if armed == point => {
83            slot.set(Some((armed, n - 1)));
84            false
85        }
86        _ => false,
87    })
88}
89
90/// Fail with an injected-fault error when the armed fault fires at `point`.
91#[cfg(test)]
92fn inject_write_fault(point: WriteFault) -> Result<()> {
93    if write_fault_fires(point) {
94        return Err(LifecycleError::Io(format!(
95            "injected fault: crashed before the {point:?} rename"
96        )));
97    }
98    Ok(())
99}
100
101/// A file written to `{target}.tmp`, waiting to be renamed over `target`.
102#[must_use = "a staged file lands only when committed"]
103struct Staged {
104    tmp: std::path::PathBuf,
105    target: std::path::PathBuf,
106}
107
108impl Staged {
109    /// Rename the staged file into place: atomic on one filesystem, so `target` holds either
110    /// its previous bytes or the new ones, never a torn mix.
111    fn commit(self) -> Result<()> {
112        fs::rename(&self.tmp, &self.target)
113            .map_err(|e| LifecycleError::Io(format!("rename into {}: {e}", self.target.display())))
114    }
115}
116
117/// Write `bytes` to `{target}.tmp` and fsync it, without touching `target`. The data is on disk
118/// before the rename can publish it, so a crash after the rename never exposes an empty file.
119fn stage(target: &Path, bytes: &[u8]) -> Result<Staged> {
120    let tmp = tmp_path(target);
121    write_synced(&tmp, bytes)
122        .map_err(|e| LifecycleError::Io(format!("stage {}: {e}", tmp.display())))?;
123    Ok(Staged {
124        tmp,
125        target: target.to_path_buf(),
126    })
127}
128
129/// Write `bytes` to `path` and fsync the file before returning.
130fn write_synced(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
131    use std::io::Write as _;
132    let mut file = fs::File::create(path)?;
133    file.write_all(bytes)?;
134    file.sync_all()
135}
136
137/// Create `dir` and every missing ancestor, fsyncing each new directory's entry in its parent,
138/// so a crash after an import cannot lose the shard directory its files were written into.
139fn create_dir_durable(dir: &Path) -> Result<()> {
140    let missing: Vec<&Path> = dir.ancestors().take_while(|p| !p.is_dir()).collect();
141    fs::create_dir_all(dir)
142        .map_err(|e| LifecycleError::Io(format!("create {}: {e}", dir.display())))?;
143    for created in missing {
144        if let Some(parent) = created.parent() {
145            sync_dir_entries(parent)?;
146        }
147    }
148    Ok(())
149}
150
151/// Fsync `dir`, making the entries just written or renamed into it durable.
152fn sync_dir_entries(dir: &Path) -> Result<()> {
153    sync_dir(dir).map_err(|e| LifecycleError::Io(format!("fsync {}: {e}", dir.display())))
154}
155
156/// How much of a source's head is read to identify it: [`StillFormat::detect`] looks at the
157/// first 12 bytes, so this is headroom, not a format's requirement.
158const SNIFF_LEN: u64 = 64;
159
160/// The largest still an import holds in memory for the decoder: an uncompressed frame at the
161/// pixel budget, four 16-bit channels per pixel. No still the decoder would accept is larger
162/// (its pixels would exceed [`MAX_DECODE_PIXELS`]), so a file over this that names itself a
163/// still by its header is streamed like any other original and gets no derivatives.
164pub(super) const MAX_HELD_STILL_BYTES: u64 = MAX_DECODE_PIXELS * 8;
165
166/// The EXIF of the `size`-byte file at `src`, or nothing for a file over
167/// [`MAX_HELD_STILL_BYTES`].
168///
169/// The EXIF reader can buffer a whole file whatever its container: a TIFF always (its IFD
170/// offsets may point anywhere), and a HEIF, PNG or WebP whose box or chunk sizes claim more than
171/// they hold. So the scan is bounded by the file's size, the same bound the decoder is held to,
172/// and every container is treated alike. Nothing real is lost: no camera still is that large, and
173/// the reader parses no video container, which is what files that large are.
174fn scan_exif(src: &Path, size: u64) -> ExifExtract {
175    if size > MAX_HELD_STILL_BYTES {
176        tracing::debug!(
177            path = %src.display(),
178            size,
179            limit = MAX_HELD_STILL_BYTES,
180            "import: file too large to scan for EXIF; capture time and GPS fall back"
181        );
182        return ExifExtract::default();
183    }
184    extract_exif(src).unwrap_or_default()
185}
186
187/// Read the first [`SNIFF_LEN`] bytes of `file` (fewer for a shorter file) and rewind it.
188pub(super) fn read_head(file: &mut fs::File) -> io::Result<Vec<u8>> {
189    let mut head = Vec::with_capacity(SNIFF_LEN as usize);
190    Read::by_ref(file).take(SNIFF_LEN).read_to_end(&mut head)?;
191    file.seek(SeekFrom::Start(0))?;
192    Ok(head)
193}
194
195/// The plaintext on its way into the encryptor: hashed as it passes and, when the caller stages
196/// a copy, copied into the staged library file (reseal stages none, so `copy` is `None`) — so
197/// one read of the source yields the signed `hash`, the ciphertext address and any library copy,
198/// and holds one STREAM chunk at a time.
199pub(super) struct Tee<R> {
200    pub(super) inner: R,
201    pub(super) hasher: Sha256Hasher,
202    pub(super) copy: Option<fs::File>,
203}
204
205impl<R: Read> Read for Tee<R> {
206    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
207        let n = self.inner.read(buf)?;
208        let passed = &buf[..n];
209        self.hasher.update(passed);
210        if let Some(copy) = self.copy.as_mut() {
211            copy.write_all(passed)?;
212        }
213        Ok(n)
214    }
215}
216
217/// A writer that only hashes what it is given: the sink [`io::copy`] streams a file into to
218/// digest it one buffer at a time.
219struct HashSink<'a>(&'a mut Sha256Hasher);
220
221impl Write for HashSink<'_> {
222    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
223        self.0.update(buf);
224        Ok(buf.len())
225    }
226
227    fn flush(&mut self) -> io::Result<()> {
228        Ok(())
229    }
230}
231
232/// An import's library copy of its original, written to `{media}.tmp` while it is encrypted
233/// and renamed into place only once the asset has self-verified. Dropped uncommitted — the
234/// import failed after the copy began — it removes the `.tmp`, so a failed import leaves no
235/// plaintext behind; a crash leaves it to the startup scrub.
236struct StagedOriginal(Option<Staged>);
237
238impl StagedOriginal {
239    /// Rename the copy into place.
240    fn commit(mut self) -> Result<()> {
241        self.0.take().map_or(Ok(()), Staged::commit)
242    }
243}
244
245impl Drop for StagedOriginal {
246    fn drop(&mut self) {
247        if let Some(staged) = self.0.take() {
248            let _ = fs::remove_file(&staged.tmp);
249        }
250    }
251}
252
253/// Render a Unix-second capture time as the sidecar's RFC 3339 `capture_timestamp`.
254fn capture_rfc3339(secs: i64) -> String {
255    Timestamp::from_second(secs)
256        .unwrap_or(Timestamp::UNIX_EPOCH)
257        .to_string()
258}
259
260/// The sidecar `stack_membership` register an import starts life with.
261///
262/// A standalone import returns the **never-written** register, which is wire-absent — the
263/// absent-key discipline every signed-struct field carries, and what keeps an unstacked
264/// asset's sidecar bytes identical to one written before the register existed. A stacked
265/// member returns the register with `membership` stamped `(now, device_id)`.
266fn stack_membership_register(
267    membership: Option<StackMembership>,
268    device_id: Uuid,
269) -> Lww<Option<StackMembership>> {
270    let mut register = Lww::new();
271    if membership.is_some() {
272        register.set(membership, now_rfc3339(), device_id);
273    }
274    register
275}
276
277/// Which side the sidecar's `capture_timestamp` was taken from — logged so an import decision
278/// can be reconstructed after the fact.
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280enum CaptureSource {
281    /// This file's own EXIF, resolved to a UTC instant at the write site.
282    Embedded,
283    /// The adapter's folded value: an EXIF time the write site could not resolve on
284    /// its own, else the exporter's taken-time. Which of the two is recorded by the executor's
285    /// `taken_time_source` log line for the same file.
286    Folded,
287    /// Neither side carried a capture time — the import's own clock.
288    ImportTime,
289}
290
291impl CaptureSource {
292    const fn as_str(self) -> &'static str {
293        match self {
294            Self::Embedded => "embedded-exif",
295            Self::Folded => "adapter-fold",
296            Self::ImportTime => "import-time",
297        }
298    }
299}
300
301/// Capture-time [precedence] at the write site: the file's own embedded EXIF wins; the
302/// adapter's folded value is the fallback; the import clock is the last resort.
303///
304/// [precedence]: https://docs/design/import/pipeline/#third-party-importers
305fn folded_capture(embedded_utc: Option<i64>, folded: Option<Timestamp>) -> (i64, CaptureSource) {
306    match (embedded_utc, folded) {
307        (Some(secs), _) => (secs, CaptureSource::Embedded),
308        (None, Some(t)) => (t.as_second(), CaptureSource::Folded),
309        (None, None) => (Timestamp::now().as_second(), CaptureSource::ImportTime),
310    }
311}
312
313/// GPS [precedence](folded_capture) at the write site: this file's own EXIF fix wins over the
314/// exporter's record, which fills in only where the bytes carried none.
315fn folded_gps(embedded: Option<Gps>, folded: Option<&Gps>) -> Option<Gps> {
316    embedded.or_else(|| folded.cloned())
317}
318
319/// The sidecar `content_type` for a file whose bytes named no still image Capsule models.
320///
321/// The **fallback only**: [`Workspace::prepare_still`] sniffs the header first, so a still's
322/// media type comes from [`StillFormat::mime`](capsule_core::media::StillFormat::mime) and a `.jpg`
323/// that is really a HEIC is typed `image/heic`. What is left for this table is the non-still
324/// suffixes — video above all, which has no detection path.
325fn content_type_for(ext: &str) -> String {
326    match ext {
327        "mp4" | "m4v" => "video/mp4",
328        "mov" | "qt" => "video/quicktime",
329        "mkv" => "video/x-matroska",
330        "webm" => "video/webm",
331        "avi" => "video/x-msvideo",
332        _ => "application/octet-stream",
333    }
334    .to_string()
335}
336
337/// A video's derivatives are **deferred**, not inapplicable: the tier table commits to a
338/// first-frame still and an H.264 preview for every video, and no build links the codec for
339/// them yet (SSoT: thumbnails § Video Previews). The still path sees a video as
340/// [`DerivativeStatus::NotAKnownStill`], so it is reclassified here, where the content type is
341/// known, and the import summary counts it with every other deferral. Any other status passes
342/// through unchanged.
343fn video_derivatives_deferred(status: DerivativeStatus, content_type: &str) -> DerivativeStatus {
344    if status == DerivativeStatus::NotAKnownStill && content_type.starts_with("video/") {
345        DerivativeStatus::DeferredNoCodec
346    } else {
347        status
348    }
349}
350
351fn asset_type_for(content_type: &str) -> String {
352    if content_type.starts_with("video/") {
353        "video"
354    } else {
355        "photo"
356    }
357    .to_string()
358}
359
360fn rfc3339_to_secs(s: &str) -> i64 {
361    s.parse::<Timestamp>().map_or(0, Timestamp::as_second)
362}
363
364/// Map a managed asset's in-memory state to its queryable `assets` index row. Deletion state is
365/// derived from the provenance chain's lifecycle actions; media-derived fields (dimensions,
366/// duration, chromahash) stay NULL — they are out of scope in this offline core.
367fn asset_row_from_state(asset: &AssetState) -> AssetRow {
368    let mut is_deleted = false;
369    let mut deleted_at = None;
370    for rec in asset.chain.records() {
371        match rec.manifest.core.action {
372            Action::Delete => {
373                is_deleted = true;
374                deleted_at = Some(rfc3339_to_secs(&rec.manifest.core.timestamp));
375            }
376            Action::TrashRestore => {
377                is_deleted = false;
378                deleted_at = None;
379            }
380            _ => {}
381        }
382    }
383    debug_assert_eq!(is_deleted, asset_is_deleted(asset));
384    // Stack columns are a projection of the signed `stack_membership` register — the
385    // same projection `library::rebuild::signed_asset_row` applies, so the write path and a
386    // rebuild agree on what the views show. A *written* register is authoritative in both arms:
387    // `Some(m)` is a placement, a stamped `None` is an explicit departure from a stack. Only a
388    // never-written register falls back to `AssetState::stack`, the index-only placement a
389    // import from before the register existed left behind.
390    let (stack_id, is_stack_hidden) = match asset.sidecar.stack_membership.get() {
391        Some(membership) => membership.as_ref().map_or((None, false), |m| {
392            (Some(m.stack_id.to_string()), m.role != StackRole::Primary)
393        }),
394        None => asset
395            .stack
396            .as_ref()
397            .map_or((None, false), |s| (Some(s.stack_id.clone()), s.hidden)),
398    };
399    // Capture time is projected from the **signed sidecar**, not from `AssetState::capture_utc`
400    // — exactly as `library::rebuild::signed_asset_row` projects it, so the write path and a
401    // rebuild agree. The two values are equal at import; they part ways after a capture-time
402    // correction (`Workspace::set_capture_timestamp`), which by design re-signs the
403    // sidecar and leaves the `media/{YYYY}/{YYYY-MM}` shard — and therefore `capture_utc`,
404    // which names it — where the files already are. Reading the shard here would keep the
405    // timeline on the wrong date until the next rebuild while the rebuild read the right one.
406    // The instant projected is the *effective* one: the user's correction when one was written,
407    // else the as-imported value.
408    let capture = asset.sidecar.effective_capture_timestamp();
409    let capture_utc = capture.parse::<Timestamp>().map_or_else(
410        |_| {
411            tracing::warn!(
412                asset_id = %asset.asset_id,
413                capture_timestamp = %capture,
414                "index: unparseable capture timestamp; indexing it as the epoch"
415            );
416            0
417        },
418        Timestamp::as_second,
419    );
420    AssetRow {
421        uuid: asset.asset_id.to_string(),
422        asset_type: asset_type_for(&asset.sidecar.content_type),
423        capture_timestamp: capture_utc,
424        capture_utc: Some(capture_utc),
425        capture_tz_source: None,
426        import_timestamp: rfc3339_to_secs(&asset.sidecar.import_timestamp),
427        hash_sha256: asset.sidecar.hash.to_hex(),
428        width: asset.sidecar.dimensions.as_ref().map(|d| d.width as i64),
429        height: asset.sidecar.dimensions.as_ref().map(|d| d.height as i64),
430        duration_ms: None,
431        stack_id,
432        is_stack_hidden,
433        chromahash: None,
434        dominant_color: None,
435        album_id: Some(asset.album_id.to_string()),
436        rating: asset.sidecar.rating.get().copied().unwrap_or(0) as i64,
437        is_deleted,
438        deleted_at,
439        // Projection of the sidecar `hidden` LWW register: a never-written register
440        // means visible, the wire-absent default.
441        is_hidden: asset.sidecar.hidden.get().copied().unwrap_or(false),
442        // Projections of the `caption` register and the effective location — the same rule
443        // `library::rebuild::signed_asset_row` applies, so a rebuild agrees with this row.
444        caption: asset
445            .sidecar
446            .caption
447            .get()
448            .filter(|c| !c.is_empty())
449            .cloned(),
450        latitude: asset.sidecar.effective_gps().map(|g| g.lat),
451        longitude: asset.sidecar.effective_gps().map(|g| g.lon),
452    }
453}
454
455/// Whether `a` and `b` resolve to the same existing file.
456fn is_same_file(a: &Path, b: &Path) -> bool {
457    match (fs::canonicalize(a), fs::canonicalize(b)) {
458        (Ok(x), Ok(y)) => x == y,
459        _ => false,
460    }
461}
462
463/// One signed create, as [`Workspace::commit_signed_create`] takes it: everything a caller
464/// decides *before* the sealing order starts.
465pub(super) struct CreateRequest<'a> {
466    /// The asset id. An import mints `Uuid::now_v7()`.
467    pub asset_id: Uuid,
468    /// The owning album; must be held with write capability.
469    pub album_id: Uuid,
470    /// The plaintext to admit. When this already *is* the asset's own media path, the bytes are
471    /// left where they are rather than rewritten over themselves.
472    pub src: &'a Path,
473    /// Move-mode release, stack placement, and exporter enrichment.
474    pub opts: &'a SignedImportOptions,
475}
476
477impl Workspace {
478    /// Write an asset's plaintext and its signed artifacts.
479    ///
480    /// The plaintext is written only when the media path does not already hold it: an
481    /// original that is already correct is never rewritten over itself, which would only open
482    /// a crash window in which the one copy is truncated. The decision is made from the
483    /// buffer — a `stat` of the media path, a length comparison, and `hash_bytes(plaintext)`
484    /// against the sidecar's `hash` — with no second read of the disk, so a metadata edit
485    /// costs one read of the original and no write.
486    ///
487    /// **Caller rule.** `plaintext` must be either the bytes read from the media path
488    /// (`append_lifecycle`) or the file about to become it (a restored backup, an adopted drop).
489    /// An import does not come through here: `commit_signed_create` streams its original into
490    /// the library without a buffer and then calls
491    /// [`write_signed_artifacts`](Self::write_signed_artifacts). A caller whose buffer may
492    /// legitimately differ from a *same-length* file already at the media path is not covered
493    /// by this guard and must decide the overwrite itself; `import_backup` restores into a
494    /// workspace where the media path does not exist, so it never meets that case.
495    pub(super) fn write_asset_files(&self, asset: &AssetState, plaintext: &[u8]) -> Result<()> {
496        let dir = media_dir(&self.root, asset.capture_utc);
497        create_dir_durable(&dir)?;
498        let media_path = self.media_path(asset);
499        let already_correct = fs::metadata(&media_path)
500            .is_ok_and(|m| m.is_file() && m.len() == plaintext.len() as u64)
501            && hash::hash_bytes(plaintext) == asset.sidecar.hash;
502        if already_correct {
503            tracing::debug!(
504                asset_id = %asset.asset_id,
505                "original already on disk with the signed hash; not rewriting it"
506            );
507        } else {
508            // Fsynced here, and its directory entry with the signed artifacts' below: the
509            // library copy is what a Move source is checked against before it is deleted, so
510            // it must be on disk rather than in the page cache.
511            write_synced(&media_path, plaintext)
512                .map_err(|e| LifecycleError::Io(format!("write {}: {e}", media_path.display())))?;
513        }
514        self.write_signed_artifacts(asset)
515    }
516
517    /// Place the plaintext original at `src` as `asset`'s library original, durably, and only if
518    /// it hashes to `expected`. Returns its length.
519    ///
520    /// The file is copied to `{media}.tmp`, the staged copy is hashed, and it is renamed over
521    /// the media path only once its SHA-256 is `expected`, then fsynced with its directory.
522    /// Hashing the staged copy rather than `src` means the bytes checked are the bytes placed.
523    /// The copy is never a hard link: `src` stays where it is for the caller to keep, and a
524    /// linked original would share its inode, so a later in-place write to `src` would change
525    /// the library original unchecked. `fs::copy` clones the extents where the filesystem can
526    /// (`clonefile` on APFS, `copy_file_range` on Btrfs and XFS), which is copy-on-write and
527    /// so equally independent of `src`. On a mismatch the staged copy is removed and
528    /// [`LifecycleError::OriginalMismatch`] returned; nothing reaches the media path.
529    pub(super) fn place_original_from(
530        &self,
531        asset: &AssetState,
532        src: &Path,
533        expected: Hash32,
534    ) -> Result<u64> {
535        let dir = media_dir(&self.root, asset.capture_utc);
536        create_dir_durable(&dir)?;
537        let target = self.media_path(asset);
538        let tmp = tmp_path(&target);
539        let _ = fs::remove_file(&tmp);
540        fs::copy(src, &tmp).map_err(|e| {
541            LifecycleError::Io(format!("copy {} to {}: {e}", src.display(), tmp.display()))
542        })?;
543        let staged = StagedOriginal(Some(Staged {
544            tmp: tmp.clone(),
545            target: target.clone(),
546        }));
547        let mut file = fs::File::open(&tmp)
548            .map_err(|e| LifecycleError::Io(format!("open {}: {e}", tmp.display())))?;
549        let mut hasher = Sha256Hasher::new();
550        let len = io::copy(&mut file, &mut HashSink(&mut hasher))
551            .map_err(|e| LifecycleError::Io(format!("read {}: {e}", tmp.display())))?;
552        if hasher.finalize() != expected {
553            tracing::warn!(
554                asset_id = %asset.asset_id,
555                src = %src.display(),
556                "the original handed over does not hash to its signed digest; not placing it"
557            );
558            return Err(LifecycleError::OriginalMismatch(asset.asset_id));
559        }
560        file.sync_all()
561            .map_err(|e| LifecycleError::Io(format!("fsync {}: {e}", tmp.display())))?;
562        staged.commit()?;
563        sync_dir_entries(&dir)?;
564        tracing::debug!(
565            asset_id = %asset.asset_id,
566            bytes = len,
567            "verified original copied into the library"
568        );
569        Ok(len)
570    }
571
572    /// The signed half of [`write_asset_files`](Self::write_asset_files): the sidecar, the
573    /// provenance chain, and the sealed metadata blob — everything but the plaintext. The
574    /// right call for a writer whose plaintext is already on disk and unchanged (a metadata
575    /// edit), which then needs neither to read nor to write the original.
576    ///
577    /// Every file is staged to `{name}.tmp` and renamed into place (the single-file atomic
578    /// write of the maintenance doc), so a crash mid-write leaves the previous file intact
579    /// rather than a torn one. All three are staged before any is renamed, and the renames run
580    /// sidecar, then sealed metadata blob, then provenance chain: the chain is what anchors an
581    /// asset ([`find_unanchored`](super::unanchored::find_unanchored)), so it lands last, and a
582    /// crash before it leaves a chainless signed sidecar that `open` reports rather than a torn
583    /// chain that counts as anchored and hides the asset. A stale `.tmp` is the startup
584    /// scrub's to remove. The per-asset *bundle* (sidecar, chain, blob renamed as one unit)
585    /// remains separate work.
586    pub(super) fn write_signed_artifacts(&self, asset: &AssetState) -> Result<()> {
587        let dir = media_dir(&self.root, asset.capture_utc);
588        create_dir_durable(&dir)?;
589        let prov = cbor::to_canonical_vec(&asset.chain.records().to_vec())
590            .map_err(|e| LifecycleError::Cbor(e.to_string()))?;
591        let sidecar = stage(&self.sidecar_path(asset), &asset.sidecar.to_canonical_vec())?;
592        // The sealed metadata blob. Un-regenerable (its nonce is folded into the blob
593        // key), AMK ciphertext, and required by `export_backup` and upload — so it is written
594        // beside the chain rather than held only in memory. An action that mints no blob
595        // (`delete` / `trash-restore`) leaves the previous file in place.
596        let blob = if asset.metadata_blob.is_empty() {
597            None
598        } else {
599            Some(stage(
600                &self.metadata_blob_path(asset),
601                &asset.metadata_blob,
602            )?)
603        };
604        let chain = stage(&self.provenance_path(asset), &prov)?;
605
606        #[cfg(test)]
607        inject_write_fault(WriteFault::SidecarRename)?;
608        sidecar.commit()?;
609        if let Some(blob) = blob {
610            blob.commit()?;
611        }
612        #[cfg(test)]
613        inject_write_fault(WriteFault::ChainRename)?;
614        chain.commit()?;
615        // One directory fsync makes every rename above durable, and with them an original
616        // `write_asset_files` wrote into the same directory.
617        sync_dir_entries(&dir)?;
618        tracing::trace!(
619            asset_id = %asset.asset_id,
620            "signed artifacts renamed into place and fsynced: sidecar, blob, chain"
621        );
622        Ok(())
623    }
624
625    /// Durably keep `blob`, the sealed metadata blob `asset`'s `create` binds, at
626    /// [`create_metadata_blob_path`](Self::create_metadata_blob_path): staged, renamed and
627    /// fsynced before the edit that supersedes it renames anything of its own, so a crash
628    /// between the two leaves the create's bytes on disk twice rather than nowhere.
629    pub(super) fn write_create_metadata_blob(&self, asset: &AssetState, blob: &[u8]) -> Result<()> {
630        let path = self.create_metadata_blob_path_of(asset);
631        let dir = path
632            .parent()
633            .expect("the create-metadata path has a shard directory")
634            .to_path_buf();
635        create_dir_durable(&dir)?;
636        stage(&path, blob)?.commit()?;
637        sync_dir_entries(&dir)?;
638        tracing::debug!(
639            asset_id = %asset.asset_id,
640            bytes = blob.len(),
641            "the metadata blob the create binds is kept before an edit replaces it"
642        );
643        Ok(())
644    }
645
646    /// Write the queryable index row + user tags for `asset` into `library.sqlite`. Re-syncs on
647    /// every change (import, metadata edit, soft-delete/restore), so the index reflects the
648    /// asset's current rating, tags, and deletion state. Upsert keeps it conflict-safe even
649    /// though the legacy importer shares the same `assets` table.
650    ///
651    /// Atomic: the row and the tag replace are one
652    /// [`with_transaction`](crate::db::DatabaseDriver::with_transaction) scope, so a failure
653    /// part-way leaves the previous row and tags rather than a new row with half its tags. Inside
654    /// an import batch it nests as a savepoint.
655    pub(super) fn index_asset_row(&self, asset: &AssetState) -> Result<()> {
656        let db = &self.library.db;
657        db.with_transaction(|| self.write_asset_row(asset))
658            .map_err(|e| LifecycleError::Db(e.to_string()))?;
659        tracing::debug!(asset_id = %asset.asset_id, "index: asset row and tags written");
660        Ok(())
661    }
662
663    /// [`index_asset_row`](Self::index_asset_row) and
664    /// [`index_original_representation`](Self::index_original_representation) as **one**
665    /// atomic catalog write: a newly placed asset is either fully indexed or not at all, never a
666    /// row without its original's cache entry.
667    pub(super) fn index_asset_with_original(
668        &self,
669        asset: &AssetState,
670        original_bytes: usize,
671    ) -> Result<()> {
672        let db = &self.library.db;
673        let representation = self.original_representation_row(asset, original_bytes);
674        db.with_transaction(|| {
675            self.write_asset_row(asset)?;
676            db.upsert_representation(&representation)
677        })
678        .map_err(|e| LifecycleError::Db(e.to_string()))?;
679        tracing::debug!(
680            asset_id = %asset.asset_id,
681            original_bytes,
682            "index: asset row, tags and original representation written"
683        );
684        Ok(())
685    }
686
687    /// The row + tag writes [`index_asset_row`](Self::index_asset_row) wraps, unwrapped so a
688    /// caller can fold them into a larger scope.
689    fn write_asset_row(&self, asset: &AssetState) -> rusqlite::Result<()> {
690        let db = &self.library.db;
691        db.upsert_asset(&asset_row_from_state(asset))?;
692        let tags: Vec<String> = asset.sidecar.tags_user.value().into_iter().collect();
693        db.replace_asset_tags(&asset.asset_id.to_string(), &tags)
694    }
695
696    /// Record the asset's own original as a device-owned cache representation — exempt from the
697    /// automatic eviction sweep, and the real lifecycle data that sweep then operates on.
698    pub(super) fn index_original_representation(
699        &self,
700        asset: &AssetState,
701        bytes: usize,
702    ) -> Result<()> {
703        self.library
704            .db
705            .upsert_representation(&self.original_representation_row(asset, bytes))
706            .map_err(|e| LifecycleError::Db(e.to_string()))
707    }
708
709    fn original_representation_row(
710        &self,
711        asset: &AssetState,
712        bytes: usize,
713    ) -> CachedRepresentationRow {
714        CachedRepresentationRow {
715            uuid: asset.asset_id.to_string(),
716            tier: "original".to_string(),
717            format: Some(asset.ext.clone()),
718            bytes: bytes as i64,
719            path: self.media_path(asset).to_string_lossy().into_owned(),
720            last_accessed_at: Timestamp::now().as_second(),
721            pinned: false,
722            is_owned_original: true,
723        }
724    }
725
726    /// Import a file into `album_id`: encrypt, build the signed create manifest + provenance,
727    /// write the signed sidecar, and self-verify through `verify_asset` **and** the
728    /// metadata↔manifest binding. Follows the [sealing order] so the manifest commits to the
729    /// content address of the sidecar it seals, without a cycle. Returns the asset id.
730    ///
731    /// [sealing order]: https://docs/design/metadata/#provenance-binding-and-sealing-order
732    pub fn import_asset(&mut self, album_id: Uuid, src: &Path) -> Result<Uuid> {
733        Ok(self
734            .import_asset_with(album_id, src, &SignedImportOptions::default())?
735            .asset_id)
736    }
737
738    /// Import **bytes already in memory** into `album_id` under the file name `file_name`
739    /// (consulted for its extension and nothing else), returning the asset id.
740    ///
741    /// This is the entry point a platform app needs and the CLI does not: PhotoKit, the Android
742    /// MediaStore, and a browser upload all hand over a byte buffer rather than a path the
743    /// library may read at leisure. It stages those bytes in the library's own scratch
744    /// directory and drives the **one** signed write path —
745    /// [`import_asset_with`](Self::import_asset_with) in Move mode, so the staged copy is
746    /// released by the same durable-commit rule that releases any other moved source. There is
747    /// no second sealing implementation here and none is wanted: the file key derivation, STREAM
748    /// encryption, manifest, sidecar, provenance chain, and `verify_asset` self-check are
749    /// byte-for-byte the path a file import takes.
750    ///
751    /// EXIF is read back off the staged file, so a JPEG carrying capture time and GPS is scanned
752    /// exactly as it would be on a file import.
753    #[tracing::instrument(skip_all, fields(album_id = %album_id, file_name, bytes = bytes.len()))]
754    pub fn import_bytes(&mut self, album_id: Uuid, file_name: &str, bytes: &[u8]) -> Result<Uuid> {
755        let ext = Path::new(file_name)
756            .extension()
757            .map_or_else(|| "bin".to_string(), |e| e.to_string_lossy().to_lowercase());
758        let staging = self.root().join(".library").join("staging");
759        fs::create_dir_all(&staging)
760            .map_err(|e| LifecycleError::Io(format!("create staging dir: {e}")))?;
761        let staged = staging.join(format!("{}.{ext}", Uuid::now_v7().simple()));
762        fs::write(&staged, bytes)
763            .map_err(|e| LifecycleError::Io(format!("stage {}: {e}", staged.display())))?;
764
765        let opts = SignedImportOptions {
766            // The staged copy is scratch, and the caller still holds the buffer it handed over,
767            // so releasing on the local durable commit is right: nothing is the only copy.
768            move_source: true,
769            defer_source_release: false,
770            stack: None,
771            enrichment: None,
772        };
773        let imported = self.import_asset_with(album_id, &staged, &opts);
774        if imported.is_err() {
775            // A failed import must not leave staged plaintext behind.
776            let _ = fs::remove_file(&staged);
777        }
778        let asset_id = imported?.asset_id;
779        tracing::info!(asset_id = %asset_id, "imported in-memory bytes as a signed asset");
780        Ok(asset_id)
781    }
782
783    /// As [`import_asset`](Self::import_asset) but with executor-supplied [`SignedImportOptions`]
784    /// (Move-mode source release + stack placement). This is the single signed write path the
785    /// import executor drives: every imported member lands as a signed `SidecarV1` +
786    /// manifest + append-only provenance, self-verified through
787    /// [`verify_asset`](capsule_core::crypto::verify_asset::verify_asset), and — when the
788    /// still decodes — with a chromahash `lqip` in the sidecar and signed thumbnail derivatives
789    /// on disk (the private `prepare_still`).
790    ///
791    /// Returns a [`SignedImport`]: the asset id, the
792    /// [`DerivativeStatus`] saying whether derivatives were generated
793    /// and, if not, why, and the per-format deferral count. A format this build has no
794    /// codec for **still imports** — the original is the backup, the thumbnail is a bonus — so
795    /// the status is a report, never a rejection.
796    #[tracing::instrument(skip_all, fields(album_id = %album_id, src = %src.display()))]
797    pub fn import_asset_with(
798        &mut self,
799        album_id: Uuid,
800        src: &Path,
801        opts: &SignedImportOptions,
802    ) -> Result<SignedImport> {
803        self.commit_signed_create(&CreateRequest {
804            asset_id: Uuid::now_v7(),
805            album_id,
806            src,
807            opts,
808        })
809    }
810
811    /// The signed create commit every import goes through: EXIF scan, encrypt, derivatives,
812    /// author + sign the sidecar, seal it, build + sign the create manifest, self-verify,
813    /// write, index. The [`CreateRequest`] carries the few things a caller decides beforehand.
814    #[tracing::instrument(
815        skip_all,
816        fields(asset_id = %req.asset_id, album_id = %req.album_id, src = %req.src.display())
817    )]
818    pub(super) fn commit_signed_create(&mut self, req: &CreateRequest<'_>) -> Result<SignedImport> {
819        let src = req.src;
820        let asset_id = req.asset_id;
821        let album_id = req.album_id;
822        let opts = req.opts;
823        let read_err = |e: io::Error| LifecycleError::Io(format!("read {}: {e}", src.display()));
824        let ext = src
825            .extension()
826            .map_or_else(|| "bin".into(), |e| e.to_string_lossy().to_lowercase());
827
828        // **Bounded memory, whatever the file's size.** The original is never read whole for
829        // its own sake: it is hashed, encrypted and copied into the library in one streamed
830        // pass below. The one exception is a still this build can decode, which the decoder
831        // takes as a buffer — at most `MAX_HELD_STILL_BYTES` — and which is then streamed from
832        // that same buffer, so the pixels and the signed hash come from the same bytes. Whether
833        // a file is such a still is settled from its head alone, exactly as the decoder's own
834        // gate settles it.
835        let mut source = fs::File::open(src).map_err(read_err)?;
836        let size = source.metadata().map_err(read_err)?.len();
837        let head = read_head(&mut source).map_err(read_err)?;
838        let decodable = StillFormat::detect(&head, &ext).is_some_and(StillFormat::is_decodable);
839        let held = if decodable && size <= MAX_HELD_STILL_BYTES {
840            let mut whole = Vec::new();
841            source.read_to_end(&mut whole).map_err(read_err)?;
842            Some(whole)
843        } else {
844            None
845        };
846        tracing::debug!(
847            asset_id = %asset_id,
848            decodable,
849            size,
850            held_bytes = held.as_ref().map_or(0, Vec::len),
851            "import: source identified; streaming the original"
852        );
853
854        // Scan & extract: capture time, dimensions, and GPS from the file's EXIF. Missing values
855        // degrade cleanly (capture → now; dimensions/GPS → absent).
856        let exif = scan_exif(src, size);
857        let tz = resolve_timezone(&exif);
858        // A third-party import arrives with the adapter's folded exporter record. Its
859        // capture time and GPS are *fallbacks* — the file's own EXIF wins wherever it yields a
860        // value, which is the pipeline doc's precedence rule applied at the write site.
861        let enrichment = opts.enrichment.as_ref();
862        let (capture_utc, capture_source) =
863            folded_capture(tz.capture_utc, enrichment.and_then(|e| e.capture_time));
864        // EXIF GPS is the near-universal WGS-84 camera datum (metadata doc, Geolocation);
865        // stored verbatim, so the wire-absent default datum applies.
866        let embedded_gps = exif.gps_lat.zip(exif.gps_lon).map(|(lat, lon)| Gps {
867            lat,
868            lon,
869            source: GpsSource::Exif,
870            datum: capsule_core::domain::GpsDatum::Wgs84,
871        });
872        let gps = folded_gps(embedded_gps, enrichment.and_then(|e| e.gps.as_ref()));
873
874        // Exporter-authoritative registers: the description, favorite flag, and album
875        // membership the file bytes never carried. Each is stamped `(now, device_id)` exactly as
876        // the `stack_membership` register is, so a later edit on any device converges under the
877        // same LWW rule; each album title gets its own `add_id` so it stays individually
878        // removable. Nothing folded ⇒ every register stays at its default, and the sidecar
879        // encodes byte-identically to a plain filesystem import's.
880        let device_id = self.account.device.device_id;
881        let stamp = now_rfc3339();
882        let mut caption = Lww::new();
883        if let Some(text) = enrichment.and_then(|e| e.caption.as_deref()) {
884            caption.set(text.to_string(), stamp.clone(), device_id);
885        }
886        let mut rating = Lww::new();
887        if let Some(stars) = enrichment.and_then(|e| e.rating) {
888            rating.set(stars, stamp.clone(), device_id);
889        }
890        // Each exporter tag becomes an asset label, so it passes through the one label rule
891        // (`normalize_label`: NFC, trimmed, 1–256 bytes) exactly as `tag_add` does. A title the
892        // rule refuses is dropped rather than failing the import: the photo itself is the thing
893        // being imported, and an unusable album title must not cost the user the asset.
894        let mut tags_user = OrSet::new();
895        for tag in enrichment.map_or(&[][..], |e| e.tags.as_slice()) {
896            match normalize_label(tag) {
897                Ok(label) => {
898                    let add_id = self.counter.issue();
899                    tags_user.add(label, add_id);
900                }
901                Err(error) => tracing::warn!(
902                    asset_id = %asset_id,
903                    tag_bytes = tag.len(),
904                    %error,
905                    "import: exporter tag refused by the label rule; dropped"
906                ),
907            }
908        }
909        // Logged for *every* import, enriched or not: which side each contested field came from
910        // is what makes a surprising capture time or location explainable after the fact. User
911        // content stays out — sizes and counts are what a decision has to be reconstructed from,
912        // not the caption text or the album titles.
913        tracing::debug!(
914            asset_id = %asset_id,
915            enriched = enrichment.is_some(),
916            capture_source = capture_source.as_str(),
917            capture_utc,
918            gps_source = ?gps.as_ref().map(|g| g.source),
919            caption_bytes = enrichment.and_then(|e| e.caption.as_ref()).map_or(0, String::len),
920            rating = ?enrichment.and_then(|e| e.rating),
921            tags = enrichment.map_or(0, |e| e.tags.len()),
922            "import: sidecar metadata resolved"
923        );
924
925        let album = self.album(&album_id)?;
926        let epoch = album.current_epoch;
927        let amk = Amk::from_bytes(album.amks[&epoch]);
928        // The media bucket every file of this asset resolves to: the resolved capture time.
929        let bucket = capture_utc;
930        let media_path = media_file_path(&self.root, bucket, asset_id, &ext);
931        // The original is copied to `{media}.tmp` in the same pass that encrypts it. The asset
932        // id is fresh, so its media path cannot already name the source.
933        create_dir_durable(&media_dir(&self.root, bucket))?;
934        let tmp = tmp_path(&media_path);
935        let staged = StagedOriginal(Some(Staged {
936            tmp: tmp.clone(),
937            target: media_path.clone(),
938        }));
939        let copy = Some(
940            fs::File::create(&tmp)
941                .map_err(|e| LifecycleError::Io(format!("stage {}: {e}", tmp.display())))?,
942        );
943        let mut held_reader = held.as_deref().unwrap_or_default();
944        let reader: &mut dyn Read = if held.is_some() {
945            &mut held_reader
946        } else {
947            &mut source
948        };
949        let mut tee = Tee {
950            inner: reader,
951            hasher: Sha256Hasher::new(),
952            copy,
953        };
954        // First write: draw a fresh nonce prefix and derive the folded file key together
955        // (nothing to replace on a create).
956        //
957        // **Before** the derivatives, and that ordering is load-bearing: the `original`
958        // sentinel is a signed *reference* to this blob, so it commits to this ciphertext's
959        // address and this nonce prefix, neither of which exists until now.
960        //
961        // The ciphertext goes to a sink: the manifest commits to its address, which the
962        // encryptor hashes as the chunks pass, and an upload re-derives it from the library
963        // copy and the recorded prefix.
964        let (enc, _file_key) =
965            encrypt_asset_rekey_stream(&amk, &asset_id, &mut tee, io::sink(), None).map_err(
966                |e| match e {
967                    RekeyStreamError::Crypto(e) => LifecycleError::Crypto(e),
968                    RekeyStreamError::Stream(e) => {
969                        LifecycleError::Io(format!("encrypt {}: {e}", src.display()))
970                    }
971                },
972            )?;
973        let Tee { hasher, copy, .. } = tee;
974        let plaintext_hash = hasher.finalize();
975        if let Some(copy) = copy {
976            // Fsynced before the rename can publish it: the library copy is what a Move source
977            // is checked against before it is deleted, so it must be on disk rather than in the
978            // page cache.
979            copy.sync_all()
980                .map_err(|e| LifecycleError::Io(format!("fsync {}: {e}", media_path.display())))?;
981        }
982        tracing::debug!(
983            asset_id = %asset_id,
984            plaintext_size = enc.plaintext_size,
985            "import: original hashed, encrypted and staged in one pass"
986        );
987
988        // Still-derived sidecar metadata, from one decode pass over the plaintext: the
989        // header-derived `content_type`, pixel `dimensions`, the chromahash `lqip`, and the
990        // signed thumbnail derivatives to persist once the asset's own files are durable. Each
991        // generated derivative is encrypted under its own fresh nonce prefix as it is signed —
992        // derivative bytes cross the network encrypted exactly like the original.
993        //
994        // Never fatal. A still this build cannot decode — or cannot decode *these bytes* of —
995        // commits exactly as before: EXIF dimensions, no LQIP, no derivatives, and a
996        // `DerivativeStatus` recording which reason applied so the gap is reportable rather
997        // than silent.
998        let PreparedStill {
999            format,
1000            dimensions,
1001            lqip,
1002            derivatives,
1003            deferred_formats,
1004            status: derivative_status,
1005        } = self.prepare_still(
1006            &StillSource {
1007                // The whole file for a held still; for anything else its head, which is all
1008                // the decoder's gate reads before it refuses.
1009                plaintext: held.as_deref().unwrap_or(&head),
1010                size,
1011                ext: &ext,
1012                src,
1013                exif: &exif,
1014            },
1015            asset_id,
1016            album_id,
1017            bucket,
1018            &amk,
1019            &enc,
1020        )?;
1021        drop(held);
1022        // Header-derived wherever the bytes name a still Capsule models; the extension table is
1023        // the fallback for everything else (video, unknown suffixes).
1024        let content_type = format.map_or_else(|| content_type_for(&ext), |f| f.mime().to_string());
1025        let derivative_status = video_derivatives_deferred(derivative_status, &content_type);
1026
1027        // Sealing order (1) the prior head `H` is `None` on a create; (2) author + sign the
1028        // sidecar with `provenance_chain_hash = H`.
1029        let mut sidecar = SidecarV1 {
1030            sidecar_schema: SIDECAR_SCHEMA_V1,
1031            crypto_suite_id: CRYPTO_SUITE_ID,
1032            uuid: asset_id,
1033            hash: plaintext_hash,
1034            capture_timestamp: capture_rfc3339(capture_utc),
1035            // An import records what the file says; a user correction is a later write.
1036            capture_timestamp_user: Lww::new(),
1037            import_timestamp: now_rfc3339(),
1038            content_type,
1039            dimensions,
1040            lqip,
1041            tags_user,
1042            tags_ai: Default::default(),
1043            caption,
1044            rating,
1045            // An importer-formed stack is written into the signed sidecar exactly as the
1046            // manual `set_stack_membership` path writes it, stamped with this device id +
1047            // now so it converges under the same `(ts, device_id)` LWW rule. A standalone
1048            // import leaves the register at its default, which is wire-absent — a sidecar for
1049            // an unstacked asset encodes byte-identically to one with no register at all.
1050            stack_membership: stack_membership_register(
1051                opts.stack.clone(),
1052                self.account.device.device_id,
1053            ),
1054            regions: Default::default(),
1055            cull: Lww::new(),
1056            hidden: Lww::new(),
1057            camera_id: None,
1058            device_id: self.account.device.device_id,
1059            session_id: Uuid::now_v7(),
1060            gps,
1061            gps_user: Lww::new(),
1062            provenance_chain_hash: None,
1063            unknown: BTreeMap::new(),
1064            signature: None,
1065        };
1066        sidecar.sign(&self.account.user_ik);
1067
1068        // (3) Seal the sidecar into the metadata blob (fresh nonce folded into the blob key;
1069        // nothing to replace on a create); compute its content hash.
1070        let (metadata_blob, blob_key) =
1071            seal_metadata_blob(&amk, &asset_id, &sidecar.to_canonical_vec(), None)?;
1072        let metadata_blob_hash = blob_ciphertext_hash(&metadata_blob);
1073
1074        // (4) Build + sign the manifest with `prior_provenance_hash = H` (None) and the
1075        // `metadata_blob_hash` from (3); append it as the new chain head.
1076        let core = ManifestCore {
1077            version: ASSET_MANIFEST_VERSION.into(),
1078            crypto_suite_id: CRYPTO_SUITE_ID,
1079            protocol_version: PROTOCOL_VERSION.into(),
1080            file_id: asset_id,
1081            album_id,
1082            amk_version: AmkVersion(epoch),
1083            ciphertext_hash: enc.ciphertext_hash,
1084            plaintext_size: enc.plaintext_size,
1085            chunk_size: enc.chunk_size,
1086            nonce_prefix: enc.nonce_prefix,
1087            key_mode: KeyMode::Derived,
1088            wrapped_file_key: None,
1089            metadata_blob_hash: Some(metadata_blob_hash),
1090            created_by_user: self.account.user_id,
1091            created_by_device: self.account.device.device_id,
1092            client_version: self.client_version.clone(),
1093            timestamp: now_rfc3339(),
1094            action: Action::Create,
1095            prior_provenance_hash: None,
1096            upgraded_from: None,
1097            unknown: Default::default(),
1098            retention_until: None,
1099        };
1100        let manifest = core.sign(self.device_signer.as_ref(), album.write_tier_signer()?)?;
1101
1102        let mut chain = ProvenanceChain::new();
1103        chain
1104            .append(ProvenanceRecord::new(asset_id, manifest.clone(), None))
1105            .map_err(|e| LifecycleError::Cbor(format!("chain: {e}")))?;
1106
1107        // Self-check: the asset must verify through the one chokepoint, and the sealed metadata
1108        // blob must round-trip to the signed sidecar and the committed hash, before we accept it.
1109        let authority = self.authority(&album_id)?;
1110        // Over the address the encryptor computed from every chunk it produced: the ciphertext
1111        // itself was never held.
1112        let outcome = verify_asset_hashed(
1113            &manifest,
1114            &enc.ciphertext_hash,
1115            &self.directory,
1116            authority,
1117            None,
1118        );
1119        if outcome != VerifyOutcome::Accept {
1120            return Err(LifecycleError::SelfVerify(outcome));
1121        }
1122        let binding = verify_metadata_binding(
1123            &manifest,
1124            &metadata_blob,
1125            &blob_key,
1126            &sidecar.to_canonical_vec(),
1127        );
1128        if binding != MetadataBinding::Bound {
1129            return Err(LifecycleError::MetadataUnbound(binding));
1130        }
1131
1132        let asset = AssetState {
1133            asset_id,
1134            album_id,
1135            ext,
1136            capture_utc: bucket,
1137            chain,
1138            sidecar,
1139            metadata_blob,
1140            // Kept in step with the register it is projected from; only an asset imported
1141            // before the register existed reaches `AssetState::stack` by any other route.
1142            stack: opts.stack.as_ref().map(StackPlacement::from_membership),
1143        };
1144        debug_assert_eq!(media_path, self.media_path(&asset));
1145        // The library copy lands first, then the signed artifacts, whose directory fsync makes
1146        // the copy's rename durable with theirs.
1147        staged.commit()?;
1148        self.write_signed_artifacts(&asset)?;
1149        // After the asset's own files, and deliberately: a derivative is regenerable, so a
1150        // failure to write one must never fail an import whose signed original is already
1151        // durable. `persist_derivatives` logs and continues rather than returning.
1152        self.persist_derivatives(&asset, &derivatives);
1153        self.index_asset_with_original(&asset, enc.plaintext_size as usize)?;
1154
1155        // Move mode: release the source only after the durable, self-verified commit — unless
1156        // the caller defers release to its server-side verify-before-destroy gate,
1157        // where the source is the only copy until the *server* durably holds it.
1158        if opts.move_source && !opts.defer_source_release {
1159            if self.library.db.in_transaction() {
1160                // The index rows above are not durable until an enclosing batch commits, so the
1161                // source is not released from inside one: keeping it never loses data, and a
1162                // batch caller defers release anyway.
1163                tracing::warn!(
1164                    asset_id = %asset_id,
1165                    src = %src.display(),
1166                    "import: catalog batch still open; Move source kept rather than released \
1167                     before its index rows commit"
1168                );
1169            } else {
1170                let _ = fs::remove_file(src);
1171            }
1172        }
1173
1174        self.assets.insert(asset_id, asset);
1175        Ok(SignedImport {
1176            asset_id,
1177            derivatives: derivative_status,
1178            deferred_formats: deferred_formats as u32,
1179        })
1180    }
1181
1182    /// Import a file on the signed path for a **streaming** import: identical to
1183    /// [`import_asset_with`](Self::import_asset_with) but with `defer_source_release` forced on,
1184    /// and returning the [`StreamedImport`] descriptor the streaming window drives its per-asset
1185    /// upload → verify → release step from. The local original (and any Move-mode source) is left
1186    /// in place — the [streaming executor](crate::import::execute_streaming) releases it only
1187    /// after the server's `durable` verdict + custody receipt clear the release gate.
1188    ///
1189    /// `enrichment` carries the folded third-party exporter metadata for this file exactly as
1190    /// [`import_asset_with`](Self::import_asset_with) takes it. It is a parameter and
1191    /// not a hard-wired `None` because the enrichment is written *inside the signed sidecar*:
1192    /// dropping it here would make a streamed Takeout import silently lossier than a bulk one,
1193    /// and the difference would be unrecoverable without re-importing.
1194    #[tracing::instrument(
1195        skip_all,
1196        fields(album_id = %album_id, src = %src.display(), move_source, enriched = enrichment.is_some())
1197    )]
1198    pub fn import_asset_streaming(
1199        &mut self,
1200        album_id: Uuid,
1201        src: &Path,
1202        move_source: bool,
1203        stack: Option<StackMembership>,
1204        enrichment: Option<SidecarEnrichment>,
1205    ) -> Result<StreamedImport> {
1206        let opts = SignedImportOptions {
1207            move_source,
1208            defer_source_release: true,
1209            stack,
1210            enrichment,
1211        };
1212        let asset_id = self.import_asset_with(album_id, src, &opts)?.asset_id;
1213        let asset = self
1214            .assets
1215            .get(&asset_id)
1216            .expect("asset just inserted by import_asset_with");
1217        Ok(StreamedImport {
1218            asset_id,
1219            blob_hashes: release_blob_hashes(asset),
1220            local_original: self.media_path(asset),
1221            move_source: move_source.then(|| src.to_path_buf()),
1222        })
1223    }
1224
1225    /// Delete a Move-mode `src` that the library holds as `asset_id` — only on server custody
1226    /// (invariant 7), and only when both copies still read back as the signed original.
1227    ///
1228    /// In order, and every step before the delete is a reason to keep the source:
1229    ///
1230    /// 1. **Read-back.** The library's copy and `src` are each read back and hashed; both must
1231    ///    equal the hash the signed sidecar commits to. A library copy that is torn or missing,
1232    ///    or a source edited since it was imported, is [`RetainReason::ReadBackMismatch`] —
1233    ///    whatever the server says, deleting `src` could lose bytes nothing else holds.
1234    /// 2. **The gate.** [`release_move_source`] over
1235    ///    `verifier` for the asset's required blobs (original ciphertext and sealed metadata
1236    ///    blob), with a fresh `verify_asset` as the crypto half: a `durable` verdict and a
1237    ///    verified custody receipt, or the source stays.
1238    ///
1239    /// `src` that resolves to the asset's own media file is never deleted.
1240    ///
1241    /// # Errors
1242    ///
1243    /// [`LifecycleError::NotFound`] when the workspace does not hold `asset_id`.
1244    #[tracing::instrument(skip(self, verifier), fields(%asset_id, src = %src.display()))]
1245    pub fn release_move_source<V: StorageVerifier + ?Sized>(
1246        &self,
1247        verifier: &V,
1248        asset_id: Uuid,
1249        src: &Path,
1250    ) -> Result<ReleaseDecision> {
1251        let asset = self
1252            .assets
1253            .get(&asset_id)
1254            .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?;
1255        let media_path = self.media_path(asset);
1256        if is_same_file(src, &media_path) {
1257            tracing::warn!("move release: the source is the library copy itself; keeping it");
1258            return Ok(ReleaseDecision::Retain(RetainReason::ReadBackMismatch));
1259        }
1260        let signed = asset.sidecar.hash;
1261        let reads_back = |path: &Path| fs::read(path).is_ok_and(|b| hash::hash_bytes(&b) == signed);
1262        if !reads_back(&media_path) {
1263            tracing::warn!(
1264                media = %media_path.display(),
1265                "move release: the library copy does not read back as the signed original; keeping the source"
1266            );
1267            return Ok(ReleaseDecision::Retain(RetainReason::ReadBackMismatch));
1268        }
1269        if !reads_back(src) {
1270            tracing::warn!(
1271                "move release: the source no longer hashes to the signed original; keeping it"
1272            );
1273            return Ok(ReleaseDecision::Retain(RetainReason::ReadBackMismatch));
1274        }
1275        let verify_asset_accepted = self
1276            .verify(&asset_id)
1277            .is_ok_and(|outcome| outcome == VerifyOutcome::Accept);
1278        let decision = release_move_source(
1279            verifier,
1280            asset_id,
1281            src,
1282            &release_blob_hashes(asset),
1283            verify_asset_accepted,
1284        );
1285        match &decision {
1286            ReleaseDecision::Release => {
1287                tracing::info!("move release: source deleted on server custody");
1288            }
1289            ReleaseDecision::Retain(reason) => {
1290                tracing::info!(?reason, "move release: source kept");
1291            }
1292        }
1293        Ok(decision)
1294    }
1295}
1296
1297/// The blobs a release of `asset`'s original waits on — the original ciphertext and, when the
1298/// head binds one, the sealed metadata blob — from the provenance chain head.
1299fn release_blob_hashes(asset: &AssetState) -> Vec<Hash32> {
1300    let head = &asset
1301        .chain
1302        .records()
1303        .last()
1304        .expect("provenance chain is never empty")
1305        .manifest
1306        .core;
1307    let mut blob_hashes = vec![head.ciphertext_hash];
1308    if let Some(h) = head.metadata_blob_hash {
1309        blob_hashes.push(h);
1310    }
1311    blob_hashes
1312}
1313
1314#[cfg(test)]
1315mod stream_tests;
1316
1317#[cfg(test)]
1318mod tests;