Skip to main content

capsule_library/lifecycle/
upload.rs

1//! The per-asset **upload bundle** — everything a network layer needs to push one managed
2//! asset to a server, and nothing of the [`Workspace`] itself.
3//!
4//! Clients store plaintext locally; the ciphertext that crosses a boundary is re-derived on
5//! demand from the manifest's recorded `nonce_prefix` (the same trick
6//! [`export_backup`](Workspace::export_backup) has always used, and which now runs through
7//! this one accessor so there is exactly one copy of that crypto).
8//!
9//! **This is a post-import pass, not an implementation of
10//! [`AssetUploader`](crate::import::AssetUploader).** That trait cannot be
11//! implemented: `stream_candidate` holds `&mut Workspace` across the `uploader.upload(...)`
12//! call, so an implementor can never borrow the workspace back to read the bytes it is
13//! supposed to send. Do not try again — push reads a *committed* asset out of an
14//! immutably-borrowed workspace, which is why it is a second command
15//! (`capsule push`) rather than a flag on import.
16
17use std::fs;
18use std::io::{self, Write};
19use std::path::PathBuf;
20use std::sync::Arc;
21
22use capsule_core::cbor;
23use capsule_core::crypto::encryption::{
24    AssetEncryption, CIPHERTEXT_CHUNK, CiphertextReader, NONCE_PREFIX_LEN, StreamError, TAG_LEN,
25    blob_ciphertext_hash, ciphertext_len, encrypt_asset_vec_with_prefix, encrypt_asset_with_prefix,
26};
27use capsule_core::crypto::hash::{self, Hash32};
28use capsule_core::crypto::provenance::{
29    Action, DerivativeManifest, DerivativeRole, KeyMode, ManifestCore,
30};
31use capsule_core::derivative_format::{DerivativeFormat, verify_still_format};
32use uuid::Uuid;
33
34use super::{AlbumKeys, AssetState, LifecycleError, Result, Workspace, media_dir};
35use crate::db::upload_guard::UploadGuardRow;
36
37/// The original media types the upload protocol's closed `content_type` enum names for this
38/// protocol version (server-side validation, invariant 5). Every other blob — and every
39/// original whose type is not here — declares [`OPAQUE_CONTENT_TYPE`], which the enum also
40/// names.
41///
42/// The enum is closed per protocol version, so it cannot name every format a user owns. An
43/// original is never refused for its type (SSoT: thumbnails § Media Is Rawshift's): a RAW, an
44/// AVI, a Matroska video or a file of no known kind uploads as opaque bytes, and its true type
45/// travels inside the encrypted sidecar, where a restore reads it back. The E2E suite fails if
46/// this list names a type the server's default enum does not.
47pub const WIRE_ORIGINAL_CONTENT_TYPES: &[&str] = &[
48    "image/jpeg",
49    "image/png",
50    "image/heic",
51    "image/heif",
52    "image/webp",
53    "image/avif",
54    "image/jxl",
55    "image/gif",
56    "image/tiff",
57    "video/mp4",
58    "video/quicktime",
59    "video/webm",
60];
61
62/// The `content_type` of a blob the server is not told the kind of.
63pub const OPAQUE_CONTENT_TYPE: &str = "application/octet-stream";
64
65/// The `content_type` an original of media type `content_type` declares on the wire: itself
66/// when the protocol's closed enum names it, [`OPAQUE_CONTENT_TYPE`] otherwise.
67#[must_use]
68pub fn wire_content_type(content_type: &str) -> &str {
69    if WIRE_ORIGINAL_CONTENT_TYPES.contains(&content_type) {
70        content_type
71    } else {
72        OPAQUE_CONTENT_TYPE
73    }
74}
75
76/// One derivative blob of an asset bundle: the **ciphertext** plus the content address its
77/// signed [`DerivativeManifest`] committed to.
78#[derive(Debug, Clone)]
79pub struct DerivativeBlob {
80    /// Which derivative this is (`thumbnail` / `preview` / `embedding`).
81    pub role: DerivativeRole,
82    /// The derivative's MIME/format string, e.g. `image/avif`.
83    pub format: String,
84    /// The AMK epoch the derivative manifest was authorized under, when it recorded one.
85    pub amk_version: Option<u32>,
86    /// The derivative's transferable bytes — **ciphertext**, re-derived from the plaintext the
87    /// library holds using the nonce prefix the manifest recorded. Derivative bytes are
88    /// encrypted client-side exactly like the original
89    /// ([Encryption](https://docs/design/cryptography/encryption/)).
90    pub bytes: Vec<u8>,
91    /// The content address the signed derivative manifest committed to.
92    pub ciphertext_hash: Hash32,
93}
94
95/// Everything needed to push one managed asset: its identity, the re-derived original
96/// ciphertext, the exact sealed metadata blob, any derivative blobs, and the manifest-envelope
97/// projection fields the server validates. Carries no [`Workspace`] internals and no album key
98/// material — the AMK never leaves the workspace. The one secret it holds is the original's
99/// per-file key, privately inside [`OriginalCiphertext`], which can open that one file and
100/// nothing else.
101///
102/// Every field maps one-for-one onto the upload protocol's `POST /upload` body
103/// (`capsule_sdk::push` owns that mapping).
104#[derive(Debug, Clone)]
105pub struct UploadBundle {
106    /// The asset id — equal to the manifest's `file_id`.
107    pub asset_id: Uuid,
108    /// The album the asset belongs to.
109    pub album_id: Uuid,
110    /// The primitive bundle the manifest was produced under.
111    pub crypto_suite_id: u16,
112    /// The date-based wire protocol version the manifest is pinned to.
113    pub protocol_version: String,
114    /// The AMK epoch the asset is sealed under.
115    pub amk_version: u32,
116    /// The original's ciphertext, re-derived on demand from the plaintext on disk and the
117    /// manifest's recorded `nonce_prefix`. It is never held whole: see [`OriginalCiphertext`].
118    pub original: OriginalCiphertext,
119    /// The original ciphertext's content address (equal to the manifest's `ciphertext_hash`).
120    pub ciphertext_hash: Hash32,
121    /// Total plaintext byte length of the original.
122    pub plaintext_size: u64,
123    /// Plaintext bytes per STREAM chunk.
124    pub chunk_size: u32,
125    /// The original's `content_type` **as declared on the wire**: the signed sidecar's MIME
126    /// type when the upload protocol's closed enum names it, otherwise the opaque
127    /// `application/octet-stream` ([`wire_content_type`]). The sidecar keeps the true type;
128    /// this is only what the server is told.
129    pub content_type: String,
130    /// How the file key is obtained (`derived` / `wrapped`).
131    pub key_mode: KeyMode,
132    /// The **exact** sealed metadata-blob wire bytes the manifest commits to.
133    pub metadata_blob: Vec<u8>,
134    /// The **exact** provenance-blob wire bytes: the canonical CBOR of the chain's `create`
135    /// [`ProvenanceRecord`](capsule_core::crypto::provenance::ProvenanceRecord), its genesis.
136    /// The records after it are not uploaded: they reach the server as lifecycle ops once it
137    /// has indexed this one.
138    ///
139    /// This is the asset's *envelope object* — the `provenance` blob of
140    /// [provenance.md § Physical Storage](https://docs/design/cryptography/provenance/#physical-storage),
141    /// stored by the server verbatim and served back unchanged on the sync feed. It is the
142    /// record and not the bare manifest because the server's chain head is the SHA-256 of these
143    /// bytes, while a client's next `prior_provenance_hash` is `record_hash()` — the digest of
144    /// the canonical record — so no other encoding lets a later lifecycle op chain onto what
145    /// this upload established. The manifest travels inside it, canonically encoded and
146    /// therefore byte-identical to its own signed bytes: "the signed bytes are the served
147    /// bytes" holds through the wrapper.
148    ///
149    /// Always present, unlike [`metadata_blob_hash`](Self::metadata_blob_hash): a managed asset
150    /// always has a create record, even when it binds no metadata blob.
151    pub provenance_blob: Vec<u8>,
152    /// The content address of the sealed metadata blob, when the create binds one.
153    pub metadata_blob_hash: Option<Hash32>,
154    /// The asset's derivative blobs, if any were generated and persisted.
155    pub derivatives: Vec<DerivativeBlob>,
156    /// The **exact** `derivative_manifest`-blob wire bytes: the canonical CBOR of each signed
157    /// [`DerivativeManifest`] a receiver needs to open this bundle's derivative tiers (#556).
158    ///
159    /// One per shipped [`DerivativeBlob`], plus one per `format = "original"` sentinel tier,
160    /// which has no blob of its own and is *only* this manifest: without it a receiver could
161    /// not tell "this tier is the original" from "this tier is missing". In the order the
162    /// library recorded them. A manifest whose derivative is skipped is skipped with it, so
163    /// nothing here names a blob the bundle does not carry.
164    ///
165    /// Signed CBOR, not ciphertext: like [`Self::provenance_blob`] it is deliberately
166    /// server-visible (it holds no plaintext secret by construction), and it is served back
167    /// unchanged so the receiver verifies the bytes the producer signed.
168    pub derivative_manifests: Vec<Vec<u8>>,
169    /// The authoring user.
170    pub created_by_user: Uuid,
171    /// The authoring device.
172    pub created_by_device: Uuid,
173    /// The exact client build that authored the create manifest.
174    pub client_version: String,
175    /// RFC3339 authoring timestamp of the create manifest.
176    pub timestamp: String,
177    /// The create manifest's lifecycle action: `create`.
178    pub action: Action,
179    /// The create manifest's prior-provenance link: null, as for every `create`.
180    pub prior_provenance_hash: Option<Hash32>,
181    /// The create manifest's retention floor: unset, as it is set only for `delete`.
182    pub retention_until: Option<String>,
183}
184
185impl UploadBundle {
186    /// The original ciphertext's size in bytes — what `POST /upload` declares as `size` for
187    /// the original blob.
188    #[must_use]
189    pub fn ciphertext_size(&self) -> u64 {
190        self.original.size()
191    }
192}
193
194/// The original's ciphertext as a **source**, not a buffer: the plaintext's path on disk, the
195/// per-file key and the nonce prefix the signed manifest recorded.
196///
197/// Every read re-derives the requested ciphertext window from the plaintext
198/// ([`CiphertextReader`]), so pushing an original holds one transfer window of it, never the
199/// file — an original may be as large as the server accepts (4 GiB) and the device it is pushed
200/// from may be a phone. The bytes it yields are the bytes [`Workspace::upload_bundle`] verified
201/// against the manifest's `ciphertext_hash` when it built the bundle.
202///
203/// It carries the two source guards of
204/// [Encryption — Encryption Workflow](https://docs/design/cryptography/encryption/#encryption-workflow),
205/// both recorded by the hashing pass that verified it:
206///
207/// - **Source identity**, best effort: the plaintext file's length, modification time and, on
208///   Unix, inode and status-change time as they stood when that pass began, so
209///   [`check_unchanged`](Self::check_unchanged) answers cheaply whether the file is still the one
210///   verified.
211/// - **Chunk tags**, authoritative: every STREAM chunk's authentication tag.
212///   [`read_at`](Self::read_at) re-derives every whole chunk a window touches and refuses the
213///   read when any tag differs from the recorded one, so a window it returns is made only of
214///   chunks byte-identical to the verified ciphertext's, and re-sending it puts no second
215///   ciphertext under a nonce, whatever happened to the file.
216#[derive(Clone)]
217pub struct OriginalCiphertext {
218    path: PathBuf,
219    file_key: [u8; 32],
220    nonce_prefix: [u8; NONCE_PREFIX_LEN],
221    plaintext_size: u64,
222    identity: FileIdentity,
223    /// Every STREAM chunk's tag, in chunk order, as the verifying pass sealed it.
224    tags: Arc<[ChunkTag]>,
225}
226
227/// One STREAM chunk's authentication tag.
228type ChunkTag = [u8; TAG_LEN];
229
230/// A writer that passes a STREAM ciphertext through to `inner` and records the tag that ends
231/// each chunk: the last [`TAG_LEN`] bytes of every [`CIPHERTEXT_CHUNK`], and of the shorter
232/// final chunk.
233struct TagRecorder<W> {
234    inner: W,
235    /// Ciphertext bytes seen so far.
236    offset: u64,
237    /// The last (up to [`TAG_LEN`]) bytes of the chunk being written.
238    tail: Vec<u8>,
239    tags: Vec<ChunkTag>,
240}
241
242impl<W: Write> TagRecorder<W> {
243    fn new(inner: W) -> Self {
244        Self {
245            inner,
246            offset: 0,
247            tail: Vec::with_capacity(TAG_LEN),
248            tags: Vec::new(),
249        }
250    }
251
252    fn record(&mut self, mut bytes: &[u8]) {
253        while !bytes.is_empty() {
254            let in_chunk = (self.offset % CIPHERTEXT_CHUNK as u64) as usize;
255            let room = CIPHERTEXT_CHUNK - in_chunk;
256            let (piece, rest) = bytes.split_at(room.min(bytes.len()));
257            if piece.len() >= TAG_LEN {
258                self.tail.clear();
259                self.tail.extend_from_slice(&piece[piece.len() - TAG_LEN..]);
260            } else {
261                self.tail.extend_from_slice(piece);
262                let excess = self.tail.len().saturating_sub(TAG_LEN);
263                self.tail.drain(..excess);
264            }
265            self.offset += piece.len() as u64;
266            if piece.len() == room {
267                self.close_chunk();
268            }
269            bytes = rest;
270        }
271    }
272
273    fn close_chunk(&mut self) {
274        let mut tag = [0u8; TAG_LEN];
275        tag.copy_from_slice(&self.tail);
276        self.tags.push(tag);
277        self.tail.clear();
278    }
279
280    /// The tags of every chunk written, closing a final chunk shorter than a whole one.
281    fn finish(mut self) -> io::Result<Vec<ChunkTag>> {
282        match self.tail.len() {
283            0 => {}
284            TAG_LEN => self.close_chunk(),
285            short => {
286                return Err(io::Error::new(
287                    io::ErrorKind::InvalidData,
288                    format!("a STREAM chunk ended {short} bytes in, shorter than its tag"),
289                ));
290            }
291        }
292        Ok(self.tags)
293    }
294}
295
296impl<W: Write> Write for TagRecorder<W> {
297    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
298        let written = self.inner.write(buf)?;
299        self.record(&buf[..written]);
300        Ok(written)
301    }
302
303    fn flush(&mut self) -> io::Result<()> {
304        self.inner.flush()
305    }
306}
307
308/// The plaintext on disk is no longer the file an [`OriginalCiphertext`] was verified from.
309#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
310#[error("the original changed on disk since its ciphertext was verified: {reason}")]
311pub struct OriginalChanged {
312    /// What differs, in English, for logs.
313    pub reason: String,
314}
315
316/// What a plaintext file looked like on disk: its length, its modification time and, on Unix,
317/// its device and inode (a file replaced by a rename is another inode) and its status-change
318/// time (which a write bumps even when the modification time is set back).
319///
320/// A cheap stand-in for the content: an edit that keeps every one of these is not seen. The
321/// per-chunk authentication tags recorded beside it close that gap.
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323struct FileIdentity {
324    len: u64,
325    modified: Option<std::time::SystemTime>,
326    file_id: Option<(u64, u64)>,
327    status_changed: Option<(i64, i64)>,
328}
329
330impl FileIdentity {
331    /// The identity of the file at `path` now.
332    fn of(path: &std::path::Path) -> io::Result<Self> {
333        let meta = fs::metadata(path)?;
334        #[cfg(unix)]
335        let (file_id, status_changed) = {
336            use std::os::unix::fs::MetadataExt as _;
337            (
338                Some((meta.dev(), meta.ino())),
339                Some((meta.ctime(), meta.ctime_nsec())),
340            )
341        };
342        #[cfg(not(unix))]
343        let (file_id, status_changed) = (None, None);
344        Ok(Self {
345            len: meta.len(),
346            modified: meta.modified().ok(),
347            file_id,
348            status_changed,
349        })
350    }
351
352    /// What differs between `self` (as recorded) and `now`, or `None` when nothing does.
353    fn difference(&self, now: &Self) -> Option<String> {
354        if self.len != now.len {
355            return Some(format!("its length is {} bytes, not {}", now.len, self.len));
356        }
357        if self.file_id != now.file_id {
358            return Some("it was replaced by another file".to_owned());
359        }
360        if self.modified != now.modified {
361            return Some("its modification time changed".to_owned());
362        }
363        if self.status_changed != now.status_changed {
364            return Some("its status-change time changed".to_owned());
365        }
366        None
367    }
368
369    /// The modification time in nanoseconds since the Unix epoch, when it is representable.
370    fn modified_ns(&self) -> Option<i64> {
371        self.modified
372            .and_then(|at| at.duration_since(std::time::UNIX_EPOCH).ok())
373            .and_then(|since| i64::try_from(since.as_nanos()).ok())
374    }
375
376    /// The identity a persisted guard recorded. A modification time the row could not
377    /// represent reads back as unknown.
378    fn of_row(row: &UploadGuardRow) -> Self {
379        Self {
380            len: row.source_len as u64,
381            modified: row
382                .modified_ns
383                .and_then(|ns| u64::try_from(ns).ok())
384                .map(|ns| std::time::UNIX_EPOCH + std::time::Duration::from_nanos(ns)),
385            file_id: row
386                .file_dev
387                .zip(row.file_ino)
388                .map(|(dev, ino)| (dev as u64, ino as u64)),
389            status_changed: row.ctime_secs.zip(row.ctime_nanos),
390        }
391    }
392}
393
394impl std::fmt::Debug for OriginalCiphertext {
395    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396        f.debug_struct("OriginalCiphertext")
397            .field("path", &self.path)
398            .field("file_key", &"<redacted>")
399            .field("plaintext_size", &self.plaintext_size)
400            .field("chunk_tags", &self.tags.len())
401            .finish_non_exhaustive()
402    }
403}
404
405impl OriginalCiphertext {
406    /// The source over the plaintext at `path`, after one hashing pass over it: the file's
407    /// identity is recorded first, so a change made during the pass differs from it, then the
408    /// ciphertext is derived once, recording every chunk's tag. Returns what that pass hashed
409    /// to, for the caller to check against the signed manifest; the guards it recorded are
410    /// those of the bytes it hashed.
411    fn seal(
412        path: PathBuf,
413        file_key: [u8; 32],
414        nonce_prefix: [u8; NONCE_PREFIX_LEN],
415        plaintext_size: u64,
416    ) -> io::Result<(Self, AssetEncryption)> {
417        let identity = FileIdentity::of(&path)?;
418        let mut recorder = TagRecorder::new(io::sink());
419        let sealed = encrypt_with(&path, &file_key, nonce_prefix, &mut recorder)?;
420        let tags = recorder.finish()?;
421        let original = Self {
422            path,
423            file_key,
424            nonce_prefix,
425            plaintext_size,
426            identity,
427            tags: tags.into(),
428        };
429        Ok((original, sealed))
430    }
431
432    /// The guard row this original persists for `asset_id`, recorded at `recorded_at`.
433    fn guard_row(&self, asset_id: &Uuid, recorded_at: i64) -> UploadGuardRow {
434        UploadGuardRow {
435            asset_id: asset_id.to_string(),
436            nonce_prefix: self.nonce_prefix.to_vec(),
437            plaintext_size: self.plaintext_size as i64,
438            source_len: self.identity.len as i64,
439            modified_ns: self.identity.modified_ns(),
440            file_dev: self.identity.file_id.map(|(dev, _)| dev as i64),
441            file_ino: self.identity.file_id.map(|(_, ino)| ino as i64),
442            ctime_secs: self.identity.status_changed.map(|(secs, _)| secs),
443            ctime_nanos: self.identity.status_changed.map(|(_, nanos)| nanos),
444            chunk_tags: self.tags.iter().flatten().copied().collect(),
445            recorded_at,
446        }
447    }
448
449    /// Whether the plaintext on disk is still the file this ciphertext was verified from: the
450    /// same length, modification time and (on Unix) inode and status-change time. One `stat`,
451    /// cheap enough to run before every window is read and again after.
452    ///
453    /// `Ok` is a positive claim that every window read while it holds is the window read
454    /// before, up to one limit: an edit that keeps every one of those attributes is not seen.
455    ///
456    /// # Errors
457    ///
458    /// [`OriginalChanged`] naming what differs, or that the file can no longer be read.
459    pub fn check_unchanged(&self) -> std::result::Result<(), OriginalChanged> {
460        let now = FileIdentity::of(&self.path).map_err(|error| OriginalChanged {
461            reason: format!("it can no longer be read: {error}"),
462        })?;
463        match self.identity.difference(&now) {
464            None => Ok(()),
465            Some(reason) => {
466                tracing::warn!(path = %self.path.display(), %reason, "the original changed on disk since its ciphertext was verified");
467                Err(OriginalChanged { reason })
468            }
469        }
470    }
471
472    /// The ciphertext's length in bytes — what `POST /upload` declares as `size`.
473    #[must_use]
474    pub fn size(&self) -> u64 {
475        ciphertext_len(self.plaintext_size)
476    }
477
478    /// The ciphertext bytes `[offset, offset + len)`, clamped to the end, cut from whole STREAM
479    /// chunks each checked against the tag the verifying pass recorded. Memory is the window
480    /// plus up to three STREAM chunks.
481    ///
482    /// # Errors
483    ///
484    /// An [`io::Error`] carrying [`OriginalChanged`] (`io::Error::other`) when a chunk the window
485    /// touches re-derives to a tag other than the recorded one: the plaintext under it changed,
486    /// and none of the window is returned. Any other read failure as it occurred.
487    #[tracing::instrument(level = "trace", skip(self), fields(path = %self.path.display()))]
488    pub fn read_at(&self, offset: u64, len: usize) -> io::Result<Vec<u8>> {
489        let total = self.size();
490        let end = offset.saturating_add(len as u64).min(total);
491        if offset >= end {
492            return Ok(Vec::new());
493        }
494        let chunk = CIPHERTEXT_CHUNK as u64;
495        let first = offset / chunk;
496        let last = (end - 1) / chunk;
497        let from = first * chunk;
498        let to = ((last + 1) * chunk).min(total);
499        let file = fs::File::open(&self.path)?;
500        let mut whole =
501            CiphertextReader::new(self.file_key, self.nonce_prefix, file, self.plaintext_size)
502                .read_at(from, (to - from) as usize)?;
503        if whole.len() as u64 != to - from {
504            return Err(io::Error::new(
505                io::ErrorKind::UnexpectedEof,
506                "the original re-derived to fewer bytes than its chunks hold",
507            ));
508        }
509        for index in first..=last {
510            let at = (((index + 1) * chunk).min(total) - from) as usize;
511            let sealed = &whole[at - TAG_LEN..at];
512            let recorded = usize::try_from(index)
513                .ok()
514                .and_then(|index| self.tags.get(index));
515            if recorded.map(<[u8; TAG_LEN]>::as_slice) != Some(sealed) {
516                let reason =
517                    format!("STREAM chunk {index} re-derived to another authentication tag");
518                tracing::warn!(path = %self.path.display(), offset, len, chunk = index, "the original changed on disk since its ciphertext was verified: a re-derived chunk's tag differs; refusing the read");
519                return Err(io::Error::other(OriginalChanged { reason }));
520            }
521        }
522        let start = (offset - from) as usize;
523        whole.truncate(start + (end - offset) as usize);
524        whole.drain(..start);
525        tracing::trace!(
526            offset,
527            len = whole.len(),
528            chunks = last - first + 1,
529            "re-derived window checked against its chunk tags"
530        );
531        Ok(whole)
532    }
533
534    /// How many STREAM chunk tags this original's guard holds: one per chunk of the verified
535    /// ciphertext. For logs and diagnostics.
536    #[must_use]
537    pub fn chunk_tags(&self) -> usize {
538        self.tags.len()
539    }
540
541    /// Stream the whole ciphertext into `writer`, one STREAM chunk at a time, and return its
542    /// content address.
543    pub fn write_to<W: Write>(&self, writer: W) -> io::Result<hash::Hash32> {
544        let rederived = self.encrypt_into(writer)?;
545        if rederived.plaintext_size != self.plaintext_size {
546            return Err(io::Error::new(
547                io::ErrorKind::InvalidData,
548                "the original changed size since its manifest was signed",
549            ));
550        }
551        Ok(rederived.ciphertext_hash)
552    }
553
554    /// The whole ciphertext in memory. For small originals and tests only: it is exactly the
555    /// buffer this type exists to avoid.
556    pub fn to_vec(&self) -> io::Result<Vec<u8>> {
557        let mut out = Vec::with_capacity(usize::try_from(self.size()).unwrap_or(0));
558        self.write_to(&mut out)?;
559        Ok(out)
560    }
561
562    fn encrypt_into<W: Write>(&self, writer: W) -> io::Result<AssetEncryption> {
563        encrypt_with(&self.path, &self.file_key, self.nonce_prefix, writer)
564    }
565}
566
567/// STREAM-encrypt the plaintext at `path` into `writer` under `file_key` and `nonce_prefix`.
568fn encrypt_with<W: Write>(
569    path: &std::path::Path,
570    file_key: &[u8; 32],
571    nonce_prefix: [u8; NONCE_PREFIX_LEN],
572    writer: W,
573) -> io::Result<AssetEncryption> {
574    let file = io::BufReader::new(fs::File::open(path)?);
575    encrypt_asset_with_prefix(file_key, nonce_prefix, file, writer).map_err(|error| match error {
576        StreamError::Io(io) => io,
577        other @ StreamError::Auth(_) => io::Error::other(other),
578    })
579}
580
581/// A backup export streams the original into the artifact through [`OriginalCiphertext::write_to`],
582/// one STREAM chunk at a time, exactly as a push reads it.
583impl capsule_core::backup::CiphertextSource for OriginalCiphertext {
584    fn size(&self) -> u64 {
585        OriginalCiphertext::size(self)
586    }
587
588    fn write_to(&self, writer: &mut dyn Write) -> io::Result<hash::Hash32> {
589        OriginalCiphertext::write_to(self, writer)
590    }
591}
592
593impl Workspace {
594    /// Build the [`UploadBundle`] for one managed asset: its **`create` record** and the bytes
595    /// that record commits to.
596    ///
597    /// An upload establishes an asset on the server, and the server takes nothing but a
598    /// `create` through it. So the bundle carries the chain's genesis whatever the chain holds
599    /// now: an asset deleted and restored, or edited, before its first upload is uploaded as the
600    /// create it began as, and every record after it reaches the server as a lifecycle op once
601    /// the create is indexed (Organization — Deletion State Machine, "Held records").
602    ///
603    /// Re-derives the original ciphertext from the create's recorded `nonce_prefix` (clients
604    /// hold plaintext; ciphertext is regenerated deterministically) and gates it on the
605    /// manifest's own content address, so a bundle that reaches the network is one the signed
606    /// manifest vouches for. The sealed metadata blob the create binds is carried verbatim — it
607    /// cannot be regenerated, because `seal_metadata_blob` draws a fresh nonce per call — so an
608    /// asset edited since its import carries the copy its first edit kept, not its current blob.
609    ///
610    /// # Errors
611    ///
612    /// [`LifecycleError::CreateMetadataSuperseded`] when the create binds a metadata blob the
613    /// library no longer holds: an edit made before the library kept that blob replaced it.
614    /// [`LifecycleError::CiphertextMismatch`] when the plaintext on disk no longer re-derives to
615    /// the signed ciphertext. [`LifecycleError::Db`] when the original's source guard cannot be
616    /// persisted.
617    ///
618    /// The hashing pass that verifies the original records its source guards (identity and
619    /// every STREAM chunk's tag), and the bundle persists them in the catalog until
620    /// [`release_upload_guard`](Self::release_upload_guard) or a purge forgets them.
621    #[tracing::instrument(skip(self), fields(asset_id = %asset_id))]
622    pub fn upload_bundle(&self, asset_id: &Uuid) -> Result<UploadBundle> {
623        let asset = self
624            .assets
625            .get(asset_id)
626            .ok_or_else(|| LifecycleError::NotFound(format!("asset {asset_id}")))?;
627        let album = self.album(&asset.album_id)?;
628        let create_record = asset
629            .chain
630            .records()
631            .first()
632            .expect("provenance chain is never empty");
633        let create = &create_record.manifest.core;
634        // The envelope object, encoded once here so the SDK ladder and the FFI hand the wire
635        // the same bytes. Canonical by construction: `record_hash()` is defined as the digest
636        // of exactly this encoding, which is what makes the server's chain head and a client's
637        // next `prior_provenance_hash` the same value.
638        let provenance_blob = cbor::to_canonical_vec(create_record)
639            .map_err(|e| LifecycleError::Cbor(format!("encoding the provenance record: {e}")))?;
640
641        let metadata_blob = self.create_metadata_blob(asset, create.metadata_blob_hash)?;
642
643        let epoch = create.amk_version.0;
644        let original = self.verified_original(asset, album, create)?;
645        self.record_upload_guard(&asset.asset_id, &original)?;
646        let ciphertext_hash = create.ciphertext_hash;
647
648        let DerivativeSet {
649            blobs: derivatives,
650            manifests: derivative_manifests,
651        } = self.derivative_blobs(asset, album, epoch);
652        tracing::debug!(
653            album_id = %asset.album_id,
654            amk_version = epoch,
655            ciphertext_bytes = original.size(),
656            metadata_blob_bytes = metadata_blob.len(),
657            provenance_blob_bytes = provenance_blob.len(),
658            derivatives = derivatives.len(),
659            derivative_manifests = derivative_manifests.len(),
660            action = ?create.action,
661            later_records = asset.chain.records().len() - 1,
662            "upload bundle built"
663        );
664
665        Ok(UploadBundle {
666            asset_id: asset.asset_id,
667            album_id: asset.album_id,
668            crypto_suite_id: create.crypto_suite_id,
669            protocol_version: create.protocol_version.clone(),
670            amk_version: epoch,
671            original,
672            ciphertext_hash,
673            plaintext_size: create.plaintext_size,
674            chunk_size: create.chunk_size,
675            content_type: wire_content_type(&asset.sidecar.content_type).to_owned(),
676            key_mode: create.key_mode,
677            metadata_blob,
678            metadata_blob_hash: create.metadata_blob_hash,
679            provenance_blob,
680            derivatives,
681            derivative_manifests,
682            created_by_user: create.created_by_user,
683            created_by_device: create.created_by_device,
684            client_version: create.client_version.clone(),
685            timestamp: create.timestamp.clone(),
686            action: create.action,
687            prior_provenance_hash: create.prior_provenance_hash,
688            retention_until: create.retention_until.clone(),
689        })
690    }
691
692    /// The exact sealed metadata blob a create binding `bound` uploads with: the asset's current
693    /// blob while no edit has replaced it, otherwise the copy the first edit kept
694    /// ([`create_metadata_blob_path`](Self::create_metadata_blob_path)). A create that binds no
695    /// blob carries the current one, as it always has.
696    ///
697    /// Either candidate is checked against `bound` before it is used, so the bytes returned are
698    /// the ones the server accepts under that address.
699    ///
700    /// # Errors
701    ///
702    /// [`LifecycleError::CreateMetadataSuperseded`] when neither answers `bound`: an edit made
703    /// before the library kept the create's blob replaced it, and it is gone.
704    /// [`LifecycleError::Io`] when the kept copy exists and cannot be read.
705    pub(super) fn create_metadata_blob(
706        &self,
707        asset: &AssetState,
708        bound: Option<Hash32>,
709    ) -> Result<Vec<u8>> {
710        let Some(bound) = bound else {
711            return Ok(asset.metadata_blob.clone());
712        };
713        if blob_ciphertext_hash(&asset.metadata_blob) == bound {
714            return Ok(asset.metadata_blob.clone());
715        }
716        let path = self.create_metadata_blob_path_of(asset);
717        let kept = match fs::read(&path) {
718            Ok(kept) => Some(kept),
719            Err(e) if e.kind() == io::ErrorKind::NotFound => None,
720            Err(e) => {
721                return Err(LifecycleError::Io(format!(
722                    "the create's metadata blob {}: {e}",
723                    path.display()
724                )));
725            }
726        };
727        match kept {
728            Some(kept) if blob_ciphertext_hash(&kept) == bound => {
729                tracing::debug!(
730                    asset_id = %asset.asset_id,
731                    records = asset.chain.records().len(),
732                    "upload bundle: an edit superseded the create's metadata blob; carrying the \
733                     kept copy"
734                );
735                Ok(kept)
736            }
737            kept => {
738                tracing::warn!(
739                    asset_id = %asset.asset_id,
740                    records = asset.chain.records().len(),
741                    kept_copy = kept.is_some(),
742                    "upload bundle: the metadata blob the create binds was superseded by an edit \
743                     and no kept copy answers it"
744                );
745                Err(LifecycleError::CreateMetadataSuperseded(asset.asset_id))
746            }
747        }
748    }
749
750    /// Persist `original`'s source guard as `asset_id`'s, so it outlives the bundle, the
751    /// session and the process until the bundle is custody-confirmed or abandoned.
752    ///
753    /// The tags `original` holds were recorded by a pass that matched the signed content
754    /// address, so they are the signed ciphertext's own. A guard already recorded under the same
755    /// nonce prefix holds the same tags, and only its identity is refreshed, when the file's
756    /// attributes moved without its content. One under another prefix belonged to a create this
757    /// asset has since re-sealed, and is replaced. One whose tags differ under the same prefix
758    /// was not recorded from the signed ciphertext; it is replaced by the verified one, loudly.
759    fn record_upload_guard(&self, asset_id: &Uuid, original: &OriginalCiphertext) -> Result<()> {
760        let db = &self.library.db;
761        let id = asset_id.to_string();
762        let row = original.guard_row(asset_id, jiff::Timestamp::now().as_second());
763        let prior = db
764            .upload_guard(&id)
765            .map_err(|e| LifecycleError::Db(format!("reading the upload guard of {id}: {e}")))?;
766        match prior {
767            None => tracing::debug!(
768                %asset_id,
769                chunk_tags = original.chunk_tags(),
770                "upload guard recorded"
771            ),
772            Some(prior) if prior.nonce_prefix != row.nonce_prefix => tracing::info!(
773                %asset_id,
774                chunk_tags = original.chunk_tags(),
775                "upload guard replaced: the create was re-sealed under another nonce prefix"
776            ),
777            Some(prior) if prior.chunk_tags != row.chunk_tags => tracing::warn!(
778                %asset_id,
779                recorded_tags = prior.chunk_tags.len() / TAG_LEN,
780                chunk_tags = original.chunk_tags(),
781                "upload guard replaced: its recorded tags are not the verified ciphertext's"
782            ),
783            Some(prior) => {
784                let recorded = FileIdentity::of_row(&prior);
785                match recorded.difference(&original.identity) {
786                    None => {
787                        tracing::trace!(%asset_id, "upload guard already recorded");
788                        return Ok(());
789                    }
790                    Some(reason) => tracing::debug!(
791                        %asset_id,
792                        %reason,
793                        "upload guard identity refreshed: the original's content re-verified \
794                         unchanged"
795                    ),
796                }
797            }
798        }
799        db.upsert_upload_guard(&row)
800            .map_err(|e| LifecycleError::Db(format!("recording the upload guard of {id}: {e}")))
801    }
802
803    /// Forget `asset_id`'s upload source guard: every blob of its bundle is custody-confirmed,
804    /// or the bundle is abandoned. Returns whether one was recorded. The next
805    /// [`upload_bundle`](Self::upload_bundle) records it again.
806    ///
807    /// # Errors
808    ///
809    /// [`LifecycleError::Db`] when the catalog refuses the delete.
810    pub fn release_upload_guard(&self, asset_id: &Uuid) -> Result<bool> {
811        let released = self
812            .library
813            .db
814            .remove_upload_guard(&asset_id.to_string())
815            .map_err(|e| {
816                LifecycleError::Db(format!("releasing the upload guard of {asset_id}: {e}"))
817            })?;
818        tracing::debug!(%asset_id, released, "upload guard released");
819        Ok(released)
820    }
821
822    /// Whether `asset_id` has an upload source guard recorded: a bundle of it was built and
823    /// has not been custody-confirmed or abandoned since.
824    ///
825    /// # Errors
826    ///
827    /// [`LifecycleError::Db`] when the catalog cannot be read.
828    pub fn has_upload_guard(&self, asset_id: &Uuid) -> Result<bool> {
829        self.library
830            .db
831            .upload_guard(&asset_id.to_string())
832            .map(|guard| guard.is_some())
833            .map_err(|e| LifecycleError::Db(format!("reading the upload guard of {asset_id}: {e}")))
834    }
835
836    /// The original's ciphertext as `core` pins it, checked against `core`'s content address.
837    ///
838    /// The re-derivation is deterministic, so a mismatch means the library's bytes and its own
839    /// signed manifest disagree — never ship or export that. Hashed in one streaming pass, so
840    /// this holds one STREAM chunk of the original (and its 16-byte tag per chunk), whatever its
841    /// size; that pass records the source guards the returned original checks its reads
842    /// against. Every record of a chain pins the same original, so any of them may be `core`.
843    pub(super) fn verified_original(
844        &self,
845        asset: &AssetState,
846        album: &AlbumKeys,
847        core: &ManifestCore,
848    ) -> Result<OriginalCiphertext> {
849        let path = self.media_path(asset);
850        let (original, rederived) = OriginalCiphertext::seal(
851            path.clone(),
852            self.original_file_key(album, core)?,
853            core.nonce_prefix,
854            core.plaintext_size,
855        )
856        .map_err(|e| LifecycleError::Io(format!("{}: {e}", path.display())))?;
857        if rederived.ciphertext_hash != core.ciphertext_hash
858            || rederived.plaintext_size != core.plaintext_size
859        {
860            tracing::error!(
861                asset_id = %asset.asset_id,
862                expected = %core.ciphertext_hash.to_hex(),
863                actual = %rederived.ciphertext_hash.to_hex(),
864                expected_plaintext_size = core.plaintext_size,
865                actual_plaintext_size = rederived.plaintext_size,
866                "upload bundle: re-derived ciphertext does not match the manifest"
867            );
868            return Err(LifecycleError::CiphertextMismatch(asset.asset_id));
869        }
870        Ok(original)
871    }
872
873    /// The asset's persisted derivative blobs, read back from
874    /// `media/{YYYY}/{YYYY-MM}/derivatives/` and **encrypted** for the wire.
875    ///
876    /// The library holds derivatives as plaintext, exactly as it holds the original: the local
877    /// gallery paints them, and the ciphertext is re-derived here from the nonce prefix the
878    /// signed manifest recorded — the same round trip
879    /// [`upload_bundle`](Self::upload_bundle) performs for the original. So what leaves this
880    /// function in [`DerivativeBlob::bytes`] is ciphertext, and the field's `ciphertext_hash`
881    /// name is now true of it. A thumbnail is a recognisable low-resolution copy of a private
882    /// photo; the encryption doc admits no exception for it.
883    ///
884    /// **Still roles only.** An embedding-role manifest is skipped at `debug!` and named as out
885    /// of scope: its `embedding/{model_id}` grammar is not in the still format set, and
886    /// `capsule_core::ml` produces no derivative manifest for this reader to have an opinion about.
887    ///
888    /// Five reasons a manifest is skipped rather than shipped, and two of them are quiet:
889    ///
890    /// - the `original` sentinel, which references the original blob and has no bytes of its
891    ///   own — an **expected** absence, logged at `debug!`, whose manifest still ships;
892    /// - an embedding-role manifest, out of scope as above — also `debug!`;
893    /// - a still-role `format` outside the closed set, which is the structural rejection the
894    ///   tier table specifies;
895    /// - an `amk_version` naming an epoch this album does not hold, which would otherwise panic
896    ///   on the key lookup;
897    /// - bytes missing on disk, or bytes whose re-derived ciphertext does not match the signed
898    ///   content address.
899    ///
900    /// None of them fails the bundle: the original and its metadata are what a backup must not
901    /// lose, and a stale thumbnail is regenerable.
902    ///
903    /// Beside the blobs it returns the signed manifests a receiver opens them with (#556): one
904    /// for each blob it keeps and one for each `original` sentinel, canonically encoded. A
905    /// manifest whose derivative is skipped is skipped with it.
906    fn derivative_blobs(&self, asset: &AssetState, album: &AlbumKeys, epoch: u32) -> DerivativeSet {
907        let dir = media_dir(&self.root, asset.capture_utc).join("derivatives");
908        let stem = asset.asset_id.simple().to_string();
909        let bundle_path = dir.join(format!("{stem}.derivatives.cbor"));
910        let Ok(bytes) = fs::read(&bundle_path) else {
911            return DerivativeSet::default();
912        };
913        let manifests: Vec<DerivativeManifest> = match cbor::from_slice(&bytes) {
914            Ok(m) => m,
915            Err(e) => {
916                tracing::warn!(
917                    path = %bundle_path.display(),
918                    error = %e,
919                    "upload bundle: undecodable derivative manifest bundle; skipping derivatives"
920                );
921                return DerivativeSet::default();
922            }
923        };
924
925        let mut set = DerivativeSet {
926            blobs: Vec::with_capacity(manifests.len()),
927            manifests: Vec::with_capacity(manifests.len()),
928        };
929        for manifest in manifests {
930            let role_name = derivative_role_name(manifest.core.role);
931
932            // The closed-format check the tier table calls a structural rejection. It answers
933            // `Ok(None)` for an embedding-role manifest, whose `embedding/{model_id}` grammar
934            // this set deliberately does not model, so those pass through untouched.
935            match verify_still_format(&manifest) {
936                Ok(Some(DerivativeFormat::Original)) => {
937                    // A reference to the original blob, not a missing file: the receiver
938                    // resolves it against the original it already has. `debug!`, because an
939                    // expected absence logged as a warning trains people to ignore warnings.
940                    // The manifest still ships: it is how the receiver learns the tier *is*
941                    // the original rather than missing.
942                    tracing::debug!(
943                        asset_id = %asset.asset_id,
944                        role = role_name,
945                        "upload bundle: `original` sentinel references the original blob; \
946                         shipping its manifest and no derivative bytes"
947                    );
948                    if let Some(encoded) = encode_manifest(&manifest, asset, role_name) {
949                        set.manifests.push(encoded);
950                    }
951                    continue;
952                }
953                Ok(None) => {
954                    // An embedding-role manifest. Its `embedding/{model_id}` grammar is not in
955                    // the still format set, and nothing produces one yet: `capsule_core::ml` writes no
956                    // derivative manifest at all. Rather than invent a reader for an artefact
957                    // with no writer, this reader says plainly that embeddings are out of its
958                    // scope — at `debug!`, because encountering one is not a fault.
959                    tracing::debug!(
960                        asset_id = %asset.asset_id,
961                        role = role_name,
962                        "upload bundle: embedding-role derivatives are outside this reader's \
963                         scope until `capsule_core::ml` produces manifests for them; skipping"
964                    );
965                    continue;
966                }
967                Ok(Some(_)) => {}
968                Err(format) => {
969                    tracing::warn!(
970                        asset_id = %asset.asset_id,
971                        role = role_name,
972                        %format,
973                        "upload bundle: still-role derivative names a format outside the closed \
974                         set; skipping"
975                    );
976                    continue;
977                }
978            }
979
980            let core = &manifest.core;
981            let Some(plaintext) = read_derivative_bytes(&dir, &stem, role_name, &core.format)
982            else {
983                tracing::warn!(
984                    asset_id = %asset.asset_id,
985                    role = role_name,
986                    "upload bundle: derivative manifest has no bytes on disk; skipping"
987                );
988                continue;
989            };
990
991            // Re-derive the ciphertext from the prefix the manifest signed. The prefix is
992            // folded into the file-key salt, so it selects the key as well as the nonces —
993            // there is exactly one ciphertext this manifest can be describing.
994            //
995            // The epoch is **checked**, not indexed. It comes off an unverified `.cbor` on
996            // disk, and `file_key` reaches `album.amks[&epoch]`, which panics on a missing key
997            // — inside a function whose whole contract is that it never fails the bundle. An
998            // album recovered from a backup holds only the epochs it escrowed, so a manifest
999            // naming one it does not hold is reachable without any tampering at all.
1000            let key_epoch = core.amk_version.map_or(epoch, |v| v.0);
1001            if !album.amks.contains_key(&key_epoch) {
1002                tracing::warn!(
1003                    asset_id = %asset.asset_id,
1004                    role = role_name,
1005                    epoch = key_epoch,
1006                    "upload bundle: derivative manifest names an AMK epoch this album does not \
1007                     hold; skipping"
1008                );
1009                continue;
1010            }
1011            let file_key = self.file_key(album, key_epoch, &asset.asset_id, &core.nonce_prefix);
1012            let (_, ciphertext) =
1013                encrypt_asset_vec_with_prefix(&file_key, core.nonce_prefix, &plaintext);
1014
1015            let observed = hash::hash_bytes(&ciphertext);
1016            if observed != core.ciphertext_hash {
1017                tracing::warn!(
1018                    asset_id = %asset.asset_id,
1019                    role = role_name,
1020                    "upload bundle: derivative bytes do not match their signed manifest; skipping"
1021                );
1022                continue;
1023            }
1024            let Some(encoded) = encode_manifest(&manifest, asset, role_name) else {
1025                continue;
1026            };
1027            set.manifests.push(encoded);
1028            set.blobs.push(DerivativeBlob {
1029                role: core.role,
1030                format: core.format.clone(),
1031                amk_version: core.amk_version.map(|v| v.0),
1032                bytes: ciphertext,
1033                ciphertext_hash: observed,
1034            });
1035        }
1036        set
1037    }
1038}
1039
1040/// What [`Workspace::derivative_blobs`] reads back: the derivative ciphertexts and the signed
1041/// manifests that open them, as the two [`UploadBundle`] fields they become.
1042#[derive(Debug, Default)]
1043struct DerivativeSet {
1044    blobs: Vec<DerivativeBlob>,
1045    manifests: Vec<Vec<u8>>,
1046}
1047
1048/// The canonical CBOR of one signed derivative manifest — the `derivative_manifest` blob's
1049/// bytes — or `None`, logged, when it will not encode.
1050///
1051/// Canonical for the reason the provenance blob is: one encoding, so the bytes this device
1052/// ships and the bytes every receiver verifies are the same bytes, and a re-push of an
1053/// unchanged library names the same content address.
1054fn encode_manifest(
1055    manifest: &DerivativeManifest,
1056    asset: &AssetState,
1057    role_name: &str,
1058) -> Option<Vec<u8>> {
1059    match cbor::to_canonical_vec(manifest) {
1060        Ok(encoded) => Some(encoded),
1061        Err(e) => {
1062            tracing::warn!(
1063                asset_id = %asset.asset_id,
1064                role = role_name,
1065                error = %e,
1066                "upload bundle: a derivative manifest will not encode; skipping its tier"
1067            );
1068            None
1069        }
1070    }
1071}
1072
1073/// The on-disk / wire name of a derivative role (mirrors `persist_derivatives`' file naming).
1074fn derivative_role_name(role: DerivativeRole) -> &'static str {
1075    match role {
1076        DerivativeRole::Thumbnail => "thumbnail",
1077        DerivativeRole::Preview => "preview",
1078        DerivativeRole::Embedding => "embedding",
1079    }
1080}
1081
1082/// The persisted bytes of one derivative, addressed by **(role, format)** rather than by role
1083/// alone.
1084///
1085/// Role alone was ambiguous the moment a tier could carry more than one format: with a JXL and
1086/// an AVIF thumbnail side by side, a prefix match would take whichever sorted first and then
1087/// content-address it against the *other* manifest, so both would be skipped as mismatched.
1088/// `#437` lands exactly that pair, so this is a latent break rather than a hypothetical one.
1089///
1090/// Returns `None` for any `format` outside the closed set — including the embedding-role
1091/// grammar, which has no still extension. The caller has already skipped both cases, so reaching
1092/// this with one is not expected; it answers `None` rather than asserting, because a reader that
1093/// panics on a manifest it merely does not understand is worse than one that ships nothing. A stale file left by a
1094/// retired format is simply never read — nothing enumerates the directory any more, so an
1095/// orphan is inert rather than a candidate, and it is regenerable by design.
1096fn read_derivative_bytes(
1097    dir: &std::path::Path,
1098    stem: &str,
1099    role_name: &str,
1100    format: &str,
1101) -> Option<Vec<u8>> {
1102    let extension = DerivativeFormat::parse(format)?.extension()?;
1103    fs::read(dir.join(format!("{stem}.{role_name}.{extension}"))).ok()
1104}
1105
1106#[cfg(test)]
1107mod tests;