capsule_core/drop/mod.rs
1//! Web-upload guest drops — **contract skeleton** (SSoT: [Web Upload]).
2//!
3//! A guest with an upload link seals each asset under a fresh random key `K`,
4//! encapsulates `K` to the link's Drop Key, and uploads the sealed bytes to the
5//! provisioning user's staging inbox. Nothing becomes a library asset until one of that
6//! user's trusted clients **adopts** the drop — decapsulating `K`, rewrapping it under the
7//! album AMK (`asset-keywrap/v1`, [`KeyMode::Wrapped`]), and signing an ordinary `create`
8//! manifest. The guest is never a signer; drops never flow through `verify_asset`.
9//!
10//! This module owns the client-side halves: link issuance, drop sealing (compiled to WASM
11//! for `capsule-web`), and adoption. The server halves (drop store, inbox, atomic
12//! inbox→album promotion) live in the server's drop module.
13//!
14//! [Web Upload]: https://docs/design/web-upload/
15//! [`KeyMode::Wrapped`]: crate::crypto::provenance::KeyMode
16
17use serde::{Deserialize, Serialize};
18use thiserror::Error;
19use uuid::Uuid;
20
21use crate::crypto::encryption::{
22 NONCE_PREFIX_LEN, encrypt_asset_vec_with_prefix, open_blob, seal_blob_with_nonce,
23};
24use crate::crypto::hash::Hash32;
25use crate::crypto::keys::{
26 DEK_CIPHERTEXT_LEN, DekKeypair, ESEED_LEN, encapsulate_to_public_derand,
27};
28use crate::crypto::primitives::Argon2Params;
29use crate::crypto::provenance::{AssetManifest, ProvenanceRecord};
30use crate::crypto::{pwkdf, rng};
31
32/// Length of an upload-link opaque URL-path id: a **full 128 bits** of CSPRNG entropy —
33/// never a structured/UUIDv7 id (identical rule to a [share link], whose embedded v7
34/// timestamp would cut real entropy to ~62 bits). SSoT: [Web Upload] Security Contract.
35///
36/// [share link]: https://docs/design/share-links/#security-contract
37/// [Web Upload]: https://docs/design/web-upload/
38pub const OPAQUE_ID_LEN: usize = 16;
39
40/// Draw a fresh opaque upload-link URL-path id: a full 128 bits of CSPRNG entropy, **not** a
41/// structured or sequential identifier. Mirrors the share-link opaque-id discipline exactly
42/// (SSoT: [Web Upload] Security Contract — the URL is `.../u/{opaque-id}#{drop_pubkey}`).
43///
44/// [Web Upload]: https://docs/design/web-upload/
45pub fn generate_opaque_id() -> [u8; OPAQUE_ID_LEN] {
46 rng::random_array::<OPAQUE_ID_LEN>()
47}
48
49/// A provisioned upload link: the server-held record plus the fragment-delivered public
50/// half. The `opaque_id` follows the share-link rule (random ≥128-bit, never structured);
51/// `drop_pubkey` travels only in the URL fragment and never reaches the server.
52#[derive(Debug, Clone)]
53pub struct UploadLink {
54 /// Revocation handle (internal owner-held; never in the URL, so a creation-time-leaking
55 /// UUIDv7 is fine here — unlike [`opaque_id`](UploadLink::opaque_id), which is
56 /// URL-exposed and must be non-structured).
57 pub link_id: UploadLinkId,
58 /// The link's random 128-bit opaque id (the URL path component).
59 pub opaque_id: [u8; 16],
60 /// The Drop Key public half (KEM encapsulation key; URL fragment only).
61 pub drop_pubkey: Vec<u8>,
62 /// The caps this link was provisioned with.
63 pub caps: LinkCaps,
64}
65
66/// Identifies a provisioned upload link for revocation.
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
68pub struct UploadLinkId(pub Uuid);
69
70/// Identifies a pending drop in the provisioning user's inbox.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72pub struct DropId(pub Uuid);
73
74/// Per-link caps, enforced server-side at the no-key layer on every drop-session
75/// creation ([Web Upload — Security Contract](https://docs/design/web-upload/)).
76#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
77pub struct LinkCaps {
78 /// RFC 3339 expiry; `None` = no expiry (revocation still applies).
79 pub expires_at: Option<String>,
80 /// Cumulative byte cap across all drops on this link.
81 pub max_total_bytes: Option<u64>,
82 /// Maximum number of files this link may deposit.
83 pub max_file_count: Option<u32>,
84 /// Maximum single-file size.
85 pub max_file_size: Option<u64>,
86 /// Whether the link dies after its first successful drop.
87 pub single_use: bool,
88}
89
90/// The unsigned descriptor a guest uploads beside the sealed ciphertext. Deliberately
91/// **not** an `AssetManifest`: no signatures, no `album_id`, no provenance link. Its
92/// integrity is established only when a trusted client decapsulates `K` and the STREAM
93/// tags verify.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95pub struct DropDescriptor {
96 /// Closed enum for the link's pinned `protocol_version` (same set as a manifest's).
97 pub content_type: String,
98 /// Total plaintext byte length.
99 pub plaintext_size: u64,
100 /// The STREAM plaintext chunk size (owned by Encryption).
101 pub chunk_size: u32,
102 /// The STREAM nonce prefix used for this seal.
103 pub nonce_prefix: [u8; 7],
104 /// Content-address digest of the STREAM ciphertext.
105 pub ciphertext_hash: Hash32,
106 /// `K` encapsulated to the link's Drop Key; length fixed by `crypto_suite_id`.
107 #[serde(with = "serde_bytes")]
108 pub kem_ct: Vec<u8>,
109 /// Guest-supplied, unverified; advisory only.
110 pub suggested_filename: Option<String>,
111}
112
113/// A sealed drop ready for upload: the descriptor plus the STREAM ciphertext.
114#[derive(Debug, Clone)]
115pub struct SealedDrop {
116 /// The unsigned descriptor.
117 pub descriptor: DropDescriptor,
118 /// The STREAM ciphertext bytes.
119 pub ciphertext: Vec<u8>,
120}
121
122/// A drop awaiting review in the provisioning user's inbox.
123#[derive(Debug, Clone)]
124pub struct PendingDrop {
125 /// The inbox row id.
126 pub drop_id: DropId,
127 /// The guest's descriptor.
128 pub descriptor: DropDescriptor,
129 /// The link it arrived through.
130 pub via_link: UploadLinkId,
131 /// Server-attested arrival time (RFC 3339, `received_at`).
132 pub received_at: String,
133}
134
135/// What adopting a drop produced: the asset it became, and the index tier a push publishes.
136///
137/// The drop's ciphertext is not here — the server already holds it as the inbox blob the
138/// manifest's `ciphertext_hash` names, and adoption promotes it in place. What the server does
139/// not hold until the owner uploads it is the **index tier**: the provenance record (the
140/// asset's chain head) and the sealed metadata blob. Both are un-regenerable — the blob's nonce
141/// is folded into its key — so they are handed back rather than left for a caller to rebuild.
142#[derive(Debug, Clone)]
143pub struct AdoptedDrop {
144 /// The signed adopting `create` manifest (`key_mode = wrapped`). Its `file_id` is the new
145 /// asset's id.
146 pub manifest: AssetManifest,
147 /// The **exact** sealed metadata-blob wire bytes `manifest.core.metadata_blob_hash` commits
148 /// to.
149 pub metadata_blob: Vec<u8>,
150 /// The asset's one provenance record — the `create` that heads its chain.
151 pub record: ProvenanceRecord,
152 /// Whether the import still pipeline produced thumbnail derivatives, dimensions and an
153 /// LQIP for the adopted bytes, and if not, why — the same report an import returns.
154 /// Adoption never fails over unreadable pixels, so this is a report, not a rejection.
155 ///
156 /// Native-only: the pipeline lives in `lifecycle`, which the WASM sealing build omits,
157 /// and only a native client adopts.
158 #[cfg(feature = "native")]
159 pub derivatives: crate::derivative_format::DerivativeStatus,
160 /// How many `(tier, format)` pairs the tier table commits to and this build cannot
161 /// encode; zero when the still did not decode, because nothing was attempted.
162 #[cfg(feature = "native")]
163 pub deferred_formats: u32,
164}
165
166impl AdoptedDrop {
167 /// The adopted asset's id (the manifest's `file_id`).
168 #[must_use]
169 pub fn asset_id(&self) -> Uuid {
170 self.manifest.core.file_id
171 }
172}
173
174/// Failure surfaced by the drop lifecycle.
175#[derive(Debug, Error)]
176pub enum DropError {
177 /// The link is expired, revoked, or over a cap.
178 #[error("upload link refused: {0}")]
179 LinkRefused(&'static str),
180 /// The KEM decapsulation or STREAM verification failed.
181 #[error("drop crypto failure: {0}")]
182 Crypto(&'static str),
183 /// The drop was not found in the caller's inbox.
184 #[error("pending drop not found")]
185 NotFound,
186 /// The verified adoption could not be written into the library (its files or its index
187 /// row). The drop stays in the inbox, so the adoption can be retried.
188 #[error("adopted drop could not be registered: {0}")]
189 Register(String),
190}
191
192/// An Argon2id **abuse-gate** verifier for a passphrase-protected upload link. Unlike a
193/// [share-link passphrase] (which wraps a *read* secret the client unwraps locally), this
194/// gates a **write**, so the server must verify possession: the link record stores the
195/// `salt` + Argon2id-derived `verifier`, and the guest proves possession at drop-session
196/// creation. The passphrase itself is never transmitted or stored, and this adds **no**
197/// confidentiality — the guest already encrypts every asset (SSoT: [Web Upload] Security
198/// Contract — Optional passphrase).
199///
200/// [share-link passphrase]: https://docs/design/share-links/#security-contract
201/// [Web Upload]: https://docs/design/web-upload/
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct PassphraseVerifier {
204 /// Argon2id memory cost (KiB) used to derive the verifier.
205 pub mem_kib: u32,
206 /// Argon2id iteration cost `t`.
207 pub t_cost: u32,
208 /// Argon2id parallelism `p`.
209 pub p_cost: u32,
210 /// 16-byte CSPRNG salt.
211 pub salt: [u8; 16],
212 /// The Argon2id output the guest's proof must equal.
213 pub verifier: [u8; 32],
214}
215
216impl PassphraseVerifier {
217 /// Derive a fresh verifier for `passphrase` under `params` (a fresh random salt each
218 /// time). The KDF cost rate-limits guessing on top of the serve path's per-IP/per-link
219 /// limiters.
220 pub fn derive(passphrase: &str, params: Argon2Params) -> Result<Self, DropError> {
221 let salt = rng::random_array::<16>();
222 let verifier = pwkdf::derive_wrap_key(passphrase.as_bytes(), &salt, params)
223 .map_err(|_| DropError::Crypto("passphrase verifier derivation failed"))?;
224 Ok(Self {
225 mem_kib: params.mem_kib,
226 t_cost: params.t_cost,
227 p_cost: params.p_cost,
228 salt,
229 verifier,
230 })
231 }
232
233 /// Constant-time check that `passphrase` reproduces the stored verifier. The serve path
234 /// calls this to gate a drop-session; a wrong passphrase is refused.
235 pub fn verify(&self, passphrase: &str) -> bool {
236 let params = Argon2Params {
237 mem_kib: self.mem_kib,
238 t_cost: self.t_cost,
239 p_cost: self.p_cost,
240 };
241 match pwkdf::derive_wrap_key(passphrase.as_bytes(), &self.salt, params) {
242 Ok(proof) => {
243 proof
244 .iter()
245 .zip(self.verifier.iter())
246 .fold(0u8, |acc, (a, b)| acc | (a ^ b))
247 == 0
248 }
249 Err(_) => false,
250 }
251 }
252}
253
254/// Issues and revokes upload links on a trusted (native) client — the seam
255/// `lifecycle::Workspace` will implement. Provisioning mints the Drop Key, wraps its
256/// private half under the master key + OGK escrow, and registers the link record.
257pub trait UploadLinkIssuer {
258 /// Provision an upload link with `caps`; `passphrase` adds the server-verified
259 /// Argon2id abuse gate (never transmitted — the record stores a verifier).
260 fn create_link(
261 &mut self,
262 caps: LinkCaps,
263 passphrase: Option<&str>,
264 ) -> Result<UploadLink, DropError>;
265
266 /// Revoke a link; the serve path refuses it within its fail-closed cache window.
267 fn revoke_link(&mut self, link: UploadLinkId) -> Result<(), DropError>;
268}
269
270/// Reviews and adopts pending drops on a trusted (native) client — decapsulate `K`,
271/// rewrap under the destination album's AMK, author the sidecar, sign the `create`
272/// manifest with `key_mode = wrapped`, and submit the atomic inbox→album promotion.
273pub trait DropAdopter {
274 /// The provisioning user's pending drops.
275 fn list_inbox(&self) -> Result<Vec<PendingDrop>, DropError>;
276
277 /// Adopt a drop into `album_id` in place (no byte re-upload). The drop becomes a
278 /// library asset — registered with its one-record provenance chain and sealed metadata
279 /// blob, exactly as an import registers one, including the import's still pipeline
280 /// (header-derived `content_type`, pixel dimensions, LQIP, signed thumbnail derivatives)
281 /// — and the returned [`AdoptedDrop`] carries what publishing it needs: the signed
282 /// adopting `create` manifest (whose `ciphertext_hash` references the inbox blob), the
283 /// sealed metadata blob, and the provenance record.
284 fn adopt(&mut self, drop: DropId, album_id: Uuid) -> Result<AdoptedDrop, DropError>;
285
286 /// Discard a pending drop; its bytes are GC'd and the quota freed.
287 fn discard(&mut self, drop: DropId) -> Result<(), DropError>;
288}
289
290/// Seal `plaintext` for a guest drop: draw a fresh random `K`, STREAM-encrypt under it,
291/// and encapsulate `K` to `drop_pubkey` (the link's KEM public half, from the URL
292/// fragment). Runs in the browser (WASM) and on native clients alike — it is the **only**
293/// path compiled to `wasm32-unknown-unknown`.
294///
295/// The `kem_ct` is a KEM-DEM: the X-Wing ciphertext (encapsulating a fresh shared secret
296/// `ss` to the Drop Key) followed by `seal_blob(ss, K)`. `K` was chosen by the guest and is
297/// **carried** wrapped — it is never derived from an AMK — so a weak or reused `K`
298/// compromises at most its own drop (SSoT: [Web Upload] Failure Modes). The output length
299/// is fixed by the suite: [`DEK_CIPHERTEXT_LEN`] + the sealed-blob overhead.
300///
301/// [Web Upload]: https://docs/design/web-upload/
302pub fn seal_drop(
303 plaintext: &[u8],
304 drop_pubkey: &[u8],
305 content_type: &str,
306) -> Result<SealedDrop, DropError> {
307 // The production path draws every value the seal randomizes — the asset key `K`, the STREAM
308 // nonce prefix, the KEM encapsulation seed, and the key-wrap nonce — from the OS CSPRNG, then
309 // delegates to the deterministic core so the two share one implementation.
310 let k = rng::random_array::<32>();
311 let nonce_prefix = rng::random_array::<NONCE_PREFIX_LEN>();
312 let eseed = rng::random_array::<ESEED_LEN>();
313 let blob_nonce = rng::random_array::<12>();
314 seal_drop_derand(
315 plaintext,
316 drop_pubkey,
317 content_type,
318 &k,
319 &nonce_prefix,
320 &eseed,
321 &blob_nonce,
322 )
323}
324
325/// The deterministic core of [`seal_drop`]: every randomized value is supplied explicitly.
326///
327/// **Exposed for known-answer testing only** — the public path is [`seal_drop`], which draws all
328/// four values from the CSPRNG. Feeding fixed `k`, `nonce_prefix`, `eseed`, and `blob_nonce`
329/// makes the sealed bytes reproducible so the browser (WASM) seal can be proven byte-identical to
330/// this Rust implementation across the language boundary (the cross-language KAT), and so the
331/// fixture that a Rust adopter consumes is a pure function of its inputs. **Never** reuse a
332/// `(k, nonce_prefix)` pair for two distinct plaintexts (STREAM nonce reuse) outside a KAT.
333///
334/// - `k` — the 32-byte asset key.
335/// - `nonce_prefix` — the 7-byte STREAM nonce prefix.
336/// - `eseed` — the 64-byte X-Wing encapsulation seed (`m ‖ x25519-ephemeral`).
337/// - `blob_nonce` — the 12-byte AEAD nonce wrapping `K` under the KEM shared secret.
338pub fn seal_drop_derand(
339 plaintext: &[u8],
340 drop_pubkey: &[u8],
341 content_type: &str,
342 k: &[u8; 32],
343 nonce_prefix: &[u8; NONCE_PREFIX_LEN],
344 eseed: &[u8; ESEED_LEN],
345 blob_nonce: &[u8; 12],
346) -> Result<SealedDrop, DropError> {
347 // 1. STREAM-encrypt the asset under K with the given nonce prefix, hashing the ciphertext.
348 let (enc, ciphertext) = encrypt_asset_vec_with_prefix(k, *nonce_prefix, plaintext);
349
350 // 2. Encapsulate K to the Drop Key public half (KEM-DEM): X-Wing ciphertext ‖ seal(ss, K).
351 let (kem_ct, ss) = encapsulate_to_public_derand(drop_pubkey, eseed)
352 .map_err(|_| DropError::Crypto("drop key encapsulation failed"))?;
353 let wrapped_k = seal_blob_with_nonce(&ss, *blob_nonce, k);
354 let mut kem_ct_dem = Vec::with_capacity(kem_ct.len() + wrapped_k.len());
355 kem_ct_dem.extend_from_slice(&kem_ct);
356 kem_ct_dem.extend_from_slice(&wrapped_k);
357
358 // 3. Emit the unsigned descriptor beside the ciphertext.
359 let descriptor = DropDescriptor {
360 content_type: content_type.to_owned(),
361 plaintext_size: enc.plaintext_size,
362 chunk_size: enc.chunk_size,
363 nonce_prefix: enc.nonce_prefix,
364 ciphertext_hash: enc.ciphertext_hash,
365 kem_ct: kem_ct_dem,
366 suggested_filename: None,
367 };
368 Ok(SealedDrop {
369 descriptor,
370 ciphertext,
371 })
372}
373
374/// Recover the guest-chosen asset key `K` from a drop's `kem_ct` using the Drop Key's
375/// private half — the first step of [adoption]. Splits the X-Wing ciphertext from the
376/// AEAD-wrapped key, decapsulates the shared secret, and opens the wrap. A truncated
377/// `kem_ct`, a foreign/tampered ciphertext, or a wrong Drop Key all fail closed
378/// ([`DropError::Crypto`]).
379///
380/// [adoption]: https://docs/design/web-upload/#4-review-and-adopt-in-place-native-client-provisioning-user
381pub fn open_drop_key(drop_key: &DekKeypair, kem_ct: &[u8]) -> Result<[u8; 32], DropError> {
382 if kem_ct.len() <= DEK_CIPHERTEXT_LEN {
383 return Err(DropError::Crypto("kem_ct too short"));
384 }
385 let (ct, wrapped_k) = kem_ct.split_at(DEK_CIPHERTEXT_LEN);
386 let ss = drop_key
387 .decapsulate(ct)
388 .map_err(|_| DropError::Crypto("drop key decapsulation failed"))?;
389 let k =
390 open_blob(&ss, wrapped_k).map_err(|_| DropError::Crypto("wrapped drop key open failed"))?;
391 k.as_slice()
392 .try_into()
393 .map_err(|_| DropError::Crypto("recovered key wrong length"))
394}
395
396#[cfg(test)]
397mod tests;