Skip to main content

capsule_library/lifecycle/
drops.rs

1//! Guest (web-upload) drops: issuing upload links, staging sealed drops, and adopting them
2//! in place. The only `lifecycle` file that reaches [`capsule_core::drop`].
3
4use std::collections::BTreeMap;
5
6use capsule_core::crypto::encryption::{
7    blob_ciphertext_hash, decrypt_asset_vec, encrypt_asset_vec_with_prefix, seal_file_key,
8    seal_metadata_blob,
9};
10use capsule_core::crypto::hash;
11use capsule_core::crypto::keys::{Amk, AmkVersion, DekKeypair};
12use capsule_core::crypto::primitives::{CRYPTO_SUITE_ID, PROTOCOL_VERSION};
13use capsule_core::crypto::provenance::{
14    ASSET_MANIFEST_VERSION, Action, KeyMode, ManifestCore, ProvenanceChain, ProvenanceRecord,
15    WrappedFileKey,
16};
17use capsule_core::crypto::verify_asset::{
18    MetadataBinding, VerifyOutcome, verify_asset, verify_metadata_binding,
19};
20// The `UploadLinkIssuer` / `DropAdopter` traits are referenced by full path in their impl
21// headers below and pulled into scope locally at their (UFCS) call sites — keeping them out
22// of module scope avoids a `create_link`/`revoke_link` name clash with `ShareLinkIssuer`.
23use capsule_core::drop::{
24    AdoptedDrop, DropDescriptor, DropError, DropId, LinkCaps, PassphraseVerifier, PendingDrop,
25    SealedDrop, UploadLink, UploadLinkId, generate_opaque_id as generate_drop_id, open_drop_key,
26};
27use capsule_core::metadata::crdt::Lww;
28use capsule_core::sidecar::sidecar_v1::{SIDECAR_SCHEMA_V1, SidecarV1};
29use uuid::Uuid;
30
31use super::derivatives::{PreparedStill, StillSource};
32use super::{AssetState, Workspace, now_rfc3339};
33use crate::exif::ExifExtract;
34
35/// The issuer-held state for one live upload link. The Drop Key private half is **escrowed**
36/// (sealed under the account master key) so it never sits in the clear at rest, mirroring
37/// how the account file seals device keys; the public half is returned to the caller for the
38/// URL fragment and never persisted server-side.
39pub(super) struct IssuedLink {
40    /// The random 128-bit opaque URL-path id.
41    opaque_id: [u8; 16],
42    /// The per-link caps the serve path enforces at drop-session creation.
43    caps: LinkCaps,
44    /// The Drop Key public half (KEM encapsulation key; travels in the URL fragment only).
45    drop_pubkey: Vec<u8>,
46    /// The Drop Key private half (X-Wing 32-byte seed) sealed under the account master key.
47    escrowed_drop_seed: Vec<u8>,
48    /// Optional Argon2id write-abuse-gate verifier.
49    passphrase: Option<PassphraseVerifier>,
50    /// RFC 3339 issuance time.
51    created_at: String,
52    /// Set once revoked; the serve path then refuses the link.
53    revoked_at: Option<String>,
54}
55
56/// One pending drop staged in the owner's inbox: the guest's unsigned descriptor, the sealed
57/// ciphertext (the server-held blob, referenced in place on adoption), and the link it
58/// arrived through (so adoption can unwrap the right Drop Key).
59pub(super) struct InboxEntry {
60    descriptor: DropDescriptor,
61    ciphertext: Vec<u8>,
62    via_link: UploadLinkId,
63    received_at: String,
64}
65
66/// The longest file extension an adopted drop's media path may carry.
67const MAX_ADOPTED_EXT_LEN: usize = 10;
68
69/// The on-disk extension of an adopted drop, from the guest's `suggested_filename`.
70///
71/// The name is guest-supplied and unverified, and the extension becomes part of a library
72/// path, so it is admitted only as a short run of ASCII alphanumerics (lowercased); anything
73/// else — no name, no extension, a separator, a dot-only or overlong suffix — is `bin`, the
74/// same fallback an extensionless import gets. The extension is a filing hint only: the
75/// sidecar's `content_type` and the signed hash are what describe the bytes.
76fn adopted_extension(suggested_filename: Option<&str>) -> String {
77    suggested_filename
78        .and_then(|name| name.rsplit_once('.'))
79        .map(|(_, ext)| ext)
80        .filter(|ext| {
81            !ext.is_empty()
82                && ext.len() <= MAX_ADOPTED_EXT_LEN
83                && ext.bytes().all(|b| b.is_ascii_alphanumeric())
84        })
85        .map_or_else(|| "bin".to_string(), str::to_ascii_lowercase)
86}
87
88impl Workspace {
89    /// The public (fragment) half of an issued upload link, if this workspace issued it.
90    /// Exposed for tests and clients rebuilding the `.../u/{opaque-id}#{drop_pubkey}` URL.
91    pub fn upload_link_pubkey(&self, link: &UploadLinkId) -> Option<&[u8]> {
92        self.upload_links
93            .get(link)
94            .map(|l| l.drop_pubkey.as_slice())
95    }
96
97    /// The opaque URL-path id of an issued upload link (the `.../u/{opaque-id}` component).
98    pub fn upload_link_opaque_id(&self, link: &UploadLinkId) -> Option<[u8; 16]> {
99        self.upload_links.get(link).map(|l| l.opaque_id)
100    }
101
102    /// The optional Argon2id write-abuse verifier of an issued link — the record the serve
103    /// path consults to gate a drop-session on passphrase possession.
104    pub fn upload_link_passphrase(&self, link: &UploadLinkId) -> Option<&PassphraseVerifier> {
105        self.upload_links
106            .get(link)
107            .and_then(|l| l.passphrase.as_ref())
108    }
109
110    /// RFC 3339 issuance time of an issued upload link.
111    pub fn upload_link_created_at(&self, link: &UploadLinkId) -> Option<&str> {
112        self.upload_links.get(link).map(|l| l.created_at.as_str())
113    }
114
115    /// Whether an issued upload link is still live at `now` (not revoked, not past expiry).
116    pub fn upload_link_is_live(&self, link: &UploadLinkId, now: jiff::Timestamp) -> bool {
117        self.upload_links.get(link).is_some_and(|l| {
118            l.revoked_at.is_none()
119                && l.caps
120                    .expires_at
121                    .as_ref()
122                    .is_none_or(|ts| ts.parse::<jiff::Timestamp>().is_ok_and(|exp| now < exp))
123        })
124    }
125
126    /// Stage a guest's [`SealedDrop`] into this owner's inbox, modeling the server's stage
127    /// step so the offline core can drive the full seal → stage → adopt path. Refuses
128    /// a drop through an unknown or revoked link (a fail-closed stand-in for the serve
129    /// path's cap/quota checks). Returns the new inbox drop id.
130    pub fn receive_drop(
131        &mut self,
132        via_link: UploadLinkId,
133        sealed: SealedDrop,
134    ) -> std::result::Result<DropId, DropError> {
135        let link = self
136            .upload_links
137            .get(&via_link)
138            .ok_or(DropError::NotFound)?;
139        if link.revoked_at.is_some() {
140            return Err(DropError::LinkRefused("link revoked"));
141        }
142        let drop_id = DropId(Uuid::now_v7());
143        self.inbox.insert(
144            drop_id,
145            InboxEntry {
146                descriptor: sealed.descriptor,
147                ciphertext: sealed.ciphertext,
148                via_link,
149                received_at: now_rfc3339(),
150            },
151        );
152        Ok(drop_id)
153    }
154
155    /// Recover the Drop Key keypair for an issued link by unsealing its escrowed seed.
156    fn drop_keypair(&self, link: &UploadLinkId) -> std::result::Result<DekKeypair, DropError> {
157        let issued = self.upload_links.get(link).ok_or(DropError::NotFound)?;
158        let seed = self
159            .account
160            .master
161            .open(&issued.escrowed_drop_seed)
162            .map_err(|_| DropError::Crypto("drop key escrow unseal failed"))?;
163        let seed: [u8; 32] = seed
164            .as_slice()
165            .try_into()
166            .map_err(|_| DropError::Crypto("drop key seed wrong length"))?;
167        Ok(DekKeypair::from_seed(&seed))
168    }
169}
170
171impl capsule_core::drop::UploadLinkIssuer for Workspace {
172    /// Provision an upload link: mint a fresh [Drop Key](capsule_core::crypto::keys::DekKeypair)
173    /// (X-Wing KEM), escrow its private half under the account master key (the OGK re-wrap
174    /// that lets *any* enrolled device decapsulate rides the multi-device escrow seam),
175    /// draw a 128-bit opaque id, derive the optional Argon2id write-abuse verifier, and
176    /// record the link for revocation. The public half is returned for the URL fragment and
177    /// never persisted server-side. SSoT: [Web Upload].
178    ///
179    /// [Web Upload]: https://docs/design/web-upload/
180    fn create_link(
181        &mut self,
182        caps: LinkCaps,
183        passphrase: Option<&str>,
184    ) -> std::result::Result<UploadLink, DropError> {
185        let drop_key = DekKeypair::generate();
186        let drop_pubkey = drop_key.public_bytes();
187        let escrowed_drop_seed = self.account.master.seal(&drop_key.to_seed_bytes());
188        let opaque_id = generate_drop_id();
189        let passphrase = passphrase
190            .map(|pw| PassphraseVerifier::derive(pw, self.argon2_params))
191            .transpose()?;
192        let link_id = UploadLinkId(Uuid::now_v7());
193        self.upload_links.insert(
194            link_id,
195            IssuedLink {
196                opaque_id,
197                caps: caps.clone(),
198                drop_pubkey: drop_pubkey.clone(),
199                escrowed_drop_seed,
200                passphrase,
201                created_at: now_rfc3339(),
202                revoked_at: None,
203            },
204        );
205        Ok(UploadLink {
206            link_id,
207            opaque_id,
208            drop_pubkey,
209            caps,
210        })
211    }
212
213    /// Revoke a link; the serve path refuses it within its fail-closed cache window.
214    /// Revoking an unknown link is [`DropError::NotFound`]; re-revocation keeps the original
215    /// timestamp (idempotent).
216    fn revoke_link(&mut self, link: UploadLinkId) -> std::result::Result<(), DropError> {
217        let issued = self
218            .upload_links
219            .get_mut(&link)
220            .ok_or(DropError::NotFound)?;
221        if issued.revoked_at.is_none() {
222            issued.revoked_at = Some(now_rfc3339());
223        }
224        Ok(())
225    }
226}
227
228impl capsule_core::drop::DropAdopter for Workspace {
229    /// This owner's pending drops, newest-arrival order unspecified.
230    fn list_inbox(&self) -> std::result::Result<Vec<PendingDrop>, DropError> {
231        Ok(self
232            .inbox
233            .iter()
234            .map(|(drop_id, e)| PendingDrop {
235                drop_id: *drop_id,
236                descriptor: e.descriptor.clone(),
237                via_link: e.via_link,
238                received_at: e.received_at.clone(),
239            })
240            .collect())
241    }
242
243    /// Adopt a pending drop into `album_id` **in place** (no byte re-upload): decapsulate the
244    /// guest-chosen `K`, run the import's still pipeline over the plaintext (`prepare_still`:
245    /// header-derived `content_type`, pixel dimensions, LQIP, signed thumbnail derivatives —
246    /// never fatal over pixels, reported in [`AdoptedDrop::derivatives`]), rewrap `K` under
247    /// the album AMK (`asset-keywrap/v1`), author + sign a `create` manifest with `key_mode = wrapped` whose `ciphertext_hash` references the
248    /// staged blob, self-verify through [`verify_asset`], register the asset in the library
249    /// (chain, sidecar, sealed metadata blob, plaintext, derivatives, index row — the same
250    /// writes `commit_signed_create` makes for an import), and only then drop the inbox row. A
251    /// registration failure leaves the drop in the inbox. Returns the [`AdoptedDrop`]: the
252    /// signed manifest plus the metadata blob and provenance record a push publishes. SSoT:
253    /// [Web Upload] — Review and adopt-in-place.
254    ///
255    /// [Web Upload]: https://docs/design/web-upload/
256    #[tracing::instrument(skip_all, fields(drop_id = %drop.0, album_id = %album_id))]
257    fn adopt(
258        &mut self,
259        drop: DropId,
260        album_id: Uuid,
261    ) -> std::result::Result<AdoptedDrop, DropError> {
262        let entry = self.inbox.get(&drop).ok_or(DropError::NotFound)?;
263        let descriptor = entry.descriptor.clone();
264        let ciphertext = entry.ciphertext.clone();
265        let via_link = entry.via_link;
266
267        // Decapsulate the guest-chosen K with the link's escrowed Drop Key private half.
268        let drop_key = self.drop_keypair(&via_link)?;
269        let file_key = open_drop_key(&drop_key, &descriptor.kem_ct)?;
270
271        let album = self
272            .album(&album_id)
273            .map_err(|_| DropError::LinkRefused("destination album not found"))?;
274        let epoch = album.current_epoch;
275        let amk = Amk::from_bytes(album.amks[&epoch]);
276        let file_id = Uuid::now_v7();
277
278        // The adopter can decrypt the staged bytes (it now holds K) to author the sidecar's
279        // plaintext hash and preview; the bulk ciphertext itself never moves.
280        let plaintext = decrypt_asset_vec(&file_key, &descriptor.nonce_prefix, &ciphertext)
281            .map_err(|_| DropError::Crypto("staged drop ciphertext failed to decrypt"))?;
282
283        // The library keeps the plaintext and regenerates the ciphertext from it (`verify`,
284        // `upload_bundle`), so the staged bytes must be exactly the canonical re-encryption
285        // under K and the descriptor's nonce prefix. STREAM decryption alone admits encodings
286        // that do not round-trip (a trailing empty last chunk on a chunk-multiple plaintext),
287        // and the descriptor's sizes are guest-asserted; either would register an asset that
288        // then fails its own `verify` and can never be pushed.
289        let (canonical, canonical_bytes) =
290            encrypt_asset_vec_with_prefix(&file_key, descriptor.nonce_prefix, &plaintext);
291        if canonical_bytes != ciphertext
292            || canonical.plaintext_size != descriptor.plaintext_size
293            || canonical.chunk_size != descriptor.chunk_size
294        {
295            tracing::warn!(
296                drop_id = %drop.0,
297                staged_len = ciphertext.len(),
298                canonical_len = canonical_bytes.len(),
299                declared_plaintext_size = descriptor.plaintext_size,
300                plaintext_len = plaintext.len(),
301                "refusing a non-canonical guest drop"
302            );
303            return Err(DropError::Crypto(
304                "staged drop is not the canonical encryption of its plaintext",
305            ));
306        }
307
308        let ext = adopted_extension(descriptor.suggested_filename.as_deref());
309        let capture_timestamp = now_rfc3339();
310        let capture_utc = capture_timestamp
311            .parse::<jiff::Timestamp>()
312            .map_or(0, jiff::Timestamp::as_second);
313
314        // The import's still pipeline over the decrypted plaintext, before the sidecar is
315        // signed: header-derived `content_type`, pixel `dimensions`, the chromahash `lqip`, and
316        // signed thumbnail derivatives to persist once the asset's own files are durable. Each
317        // derivative is sealed under its own AMK-derived key and fresh nonce prefix — the
318        // guest's `K` covers the original only — and the `original` sentinel references the
319        // staged blob through `canonical`, which is that blob's address and prefix. Never fatal
320        // over pixels: an undecodable drop adopts with the reason in `status`. A drop has no
321        // path and no EXIF yet, so the source is labelled by drop id for logs and carries an
322        // empty extract (dimensions then come from decoded pixels or not at all).
323        let source_label = std::path::PathBuf::from(format!("drop:{}", drop.0));
324        let PreparedStill {
325            format,
326            dimensions,
327            lqip,
328            derivatives,
329            deferred_formats,
330            status: derivative_status,
331        } = self
332            .prepare_still(
333                &StillSource {
334                    plaintext: &plaintext,
335                    size: plaintext.len() as u64,
336                    ext: &ext,
337                    src: &source_label,
338                    exif: &ExifExtract::default(),
339                },
340                file_id,
341                album_id,
342                capture_utc,
343                &amk,
344                &canonical,
345            )
346            .map_err(|e| {
347                tracing::error!(
348                    asset_id = %file_id,
349                    drop_id = %drop.0,
350                    error = %e,
351                    "adoption: the workspace could not author signed derivatives; the drop stays \
352                     in the inbox"
353                );
354                DropError::Register(format!("derivatives: {e}"))
355            })?;
356        tracing::debug!(
357            asset_id = %file_id,
358            drop_id = %drop.0,
359            status = ?derivative_status,
360            derivatives = derivatives.len(),
361            deferred_formats,
362            "adoption: still pipeline ran over the drop's plaintext"
363        );
364
365        // Author + sign the sidecar. `created_by`/author is the adopter — the guest is never
366        // a signer; its origin is an unverified, self-asserted descriptive note.
367        let mut sidecar = SidecarV1 {
368            sidecar_schema: SIDECAR_SCHEMA_V1,
369            crypto_suite_id: CRYPTO_SUITE_ID,
370            uuid: file_id,
371            hash: hash::hash_bytes(&plaintext),
372            capture_timestamp,
373            capture_timestamp_user: Lww::new(),
374            import_timestamp: now_rfc3339(),
375            // Header-derived wherever the bytes name a still Capsule models; the guest's
376            // self-asserted type is the fallback for everything else (a video, say).
377            content_type: format
378                .map_or_else(|| descriptor.content_type.clone(), |f| f.mime().to_string()),
379            dimensions,
380            lqip,
381            tags_user: Default::default(),
382            tags_ai: Default::default(),
383            caption: Default::default(),
384            rating: Default::default(),
385            stack_membership: Lww::new(),
386            regions: Default::default(),
387            cull: Lww::new(),
388            hidden: Lww::new(),
389            camera_id: None,
390            device_id: self.account.device.device_id,
391            session_id: Uuid::now_v7(),
392            gps: None,
393            gps_user: Lww::new(),
394            provenance_chain_hash: None,
395            unknown: BTreeMap::new(),
396            signature: None,
397        };
398        sidecar.sign(&self.account.user_ik);
399
400        // Seal the sidecar into the metadata blob (fresh nonce folded into the blob key; the
401        // adoption is a create, so there is no prior nonce to refuse).
402        let (metadata_blob, blob_key) =
403            seal_metadata_blob(&amk, &file_id, &sidecar.to_canonical_vec(), None)
404                .map_err(|_| DropError::Crypto("adopted metadata blob seal failed"))?;
405        let metadata_blob_hash = blob_ciphertext_hash(&metadata_blob);
406
407        // Rewrap K under the album AMK (`asset-keywrap/v1`) — K is *carried* wrapped, not
408        // derived, because an external party chose it.
409        let wrapped_file_key = seal_file_key(&amk, &file_id, &file_key);
410
411        let core = ManifestCore {
412            version: ASSET_MANIFEST_VERSION.into(),
413            crypto_suite_id: CRYPTO_SUITE_ID,
414            protocol_version: PROTOCOL_VERSION.into(),
415            file_id,
416            album_id,
417            amk_version: AmkVersion(epoch),
418            ciphertext_hash: descriptor.ciphertext_hash,
419            plaintext_size: descriptor.plaintext_size,
420            chunk_size: descriptor.chunk_size,
421            nonce_prefix: descriptor.nonce_prefix,
422            key_mode: KeyMode::Wrapped,
423            wrapped_file_key: Some(WrappedFileKey(wrapped_file_key)),
424            metadata_blob_hash: Some(metadata_blob_hash),
425            created_by_user: self.account.user_id,
426            created_by_device: self.account.device.device_id,
427            client_version: self.client_version.clone(),
428            timestamp: now_rfc3339(),
429            action: Action::Create,
430            prior_provenance_hash: None,
431            upgraded_from: None,
432            unknown: Default::default(),
433            retention_until: None,
434        };
435        let manifest = core
436            .sign(
437                self.device_signer.as_ref(),
438                album
439                    .write_tier_signer()
440                    .map_err(|_| DropError::Crypto("album holds no write capability"))?,
441            )
442            .map_err(|_| DropError::Crypto("adopting manifest signing failed"))?;
443
444        // Self-verify through the one chokepoint against the unchanged staged ciphertext, and
445        // confirm the sealed metadata blob binds to the signed sidecar, before committing.
446        let authority = self
447            .authority(&album_id)
448            .map_err(|_| DropError::Crypto("album has no attested authority"))?;
449        if verify_asset(&manifest, &ciphertext, &self.directory, authority, None)
450            != VerifyOutcome::Accept
451        {
452            return Err(DropError::Crypto(
453                "adopting manifest failed self-verification",
454            ));
455        }
456        if verify_metadata_binding(
457            &manifest,
458            &metadata_blob,
459            &blob_key,
460            &sidecar.to_canonical_vec(),
461        ) != MetadataBinding::Bound
462        {
463            return Err(DropError::Crypto(
464                "adopted metadata blob failed its binding",
465            ));
466        }
467
468        // Register the asset exactly as `commit_signed_create` does for an import: a
469        // one-record chain headed by the adopting `create`, the sealed metadata blob kept
470        // beside it (it cannot be regenerated), the plaintext at the asset's media path (the
471        // library holds plaintext; the wrapped key regenerates the guest's ciphertext from it),
472        // and the queryable index row.
473        let record = ProvenanceRecord::new(file_id, manifest.clone(), None);
474        let mut chain = ProvenanceChain::new();
475        chain
476            .append(record.clone())
477            .map_err(|e| DropError::Register(format!("chain: {e}")))?;
478        let asset = AssetState {
479            asset_id: file_id,
480            album_id,
481            ext,
482            capture_utc,
483            chain,
484            sidecar,
485            metadata_blob: metadata_blob.clone(),
486            stack: None,
487        };
488        let register = |ws: &Self| -> super::Result<()> {
489            ws.write_asset_files(&asset, &plaintext)?;
490            // After the asset's own files, as on import: a derivative is regenerable, so a
491            // failure to write one is logged and never fails the adoption.
492            ws.persist_derivatives(&asset, &derivatives);
493            ws.index_asset_with_original(&asset, plaintext.len())
494        };
495        if let Err(e) = register(self) {
496            tracing::error!(
497                asset_id = %file_id,
498                drop_id = %drop.0,
499                error = %e,
500                "adoption verified but the asset could not be registered; the drop stays in the inbox"
501            );
502            return Err(DropError::Register(e.to_string()));
503        }
504        self.assets.insert(file_id, asset);
505
506        // The drop is now a library asset — remove the inbox row (atomic on the server side).
507        self.inbox.remove(&drop);
508        tracing::info!(
509            asset_id = %file_id,
510            drop_id = %drop.0,
511            album_id = %album_id,
512            derivatives = ?derivative_status,
513            "adopted a guest drop into the library"
514        );
515        Ok(AdoptedDrop {
516            manifest,
517            metadata_blob,
518            record,
519            derivatives: derivative_status,
520            deferred_formats: deferred_formats as u32,
521        })
522    }
523
524    /// Discard a pending drop the owner rejects; its bytes are GC'd and the quota freed.
525    fn discard(&mut self, drop: DropId) -> std::result::Result<(), DropError> {
526        self.inbox.remove(&drop).ok_or(DropError::NotFound)?;
527        Ok(())
528    }
529}
530
531#[cfg(test)]
532mod tests;