capsule_core/sharing/mod.rs
1//! Share links — link generation and capability validation (SSoT: [Share Links]).
2//!
3//! A share link grants **view-only** access to an asset or album to a recipient with no
4//! Capsule account: `https://server.tld/s/{opaque-id}#{secret}`. The fragment secret
5//! carries the decryption material and never reaches the server; an optional passphrase
6//! wraps it a second time via the password-based KDF, unwrapped **client-side** (the
7//! server stores and returns only the wrapped material). The serving endpoints live in
8//! the server's share module; this module owns link generation, the encapsulation
9//! crypto, and the recipient-side [`open_scope`](crate::sharing::open_scope) path.
10//!
11//! ## Cryptographic shape
12//!
13//! [Cryptography — Keys § Non-registered accounts] owns the shape: *"we encapsulate the
14//! decryption keys around the secret stored in the link ... the password-based KDF adds a
15//! second encapsulation layer on top of the link secret."* Concretely, per link:
16//!
17//! 1. A fresh random **link secret** (`fragment_secret`,
18//! [`LINK_SECRET_LEN`](crate::sharing::LINK_SECRET_LEN) bytes) is drawn from the CSPRNG. It
19//! is the URL fragment `#{secret}` and never reaches the server.
20//! 2. The scope's [`ScopeMaterial`](crate::sharing::ScopeMaterial) (a single file key, or an
21//! album's AMK ledger) is serialized to canonical CBOR and sealed under
22//! `HKDF(link_secret, salt=opaque_id)` — the *link-secret encapsulation*. The sealed bytes
23//! are opaque to the server.
24//! 3. **If** a passphrase is supplied, that sealed blob is wrapped a **second** time under
25//! an [Argon2id][pw] key ([`crate::crypto::pwkdf`]) — the passphrase never leaves the
26//! client, and the server stores only this wrapped form (served from
27//! `/s/{opaque-id}/wrapped-secret`). See [`WrappedScope`](crate::sharing::WrappedScope).
28//!
29//! The recipient reverses the layers with [`open_scope`](crate::sharing::open_scope):
30//! Argon2id-unwrap (client-side, iff passphrase-protected), then link-secret-unwrap with the
31//! fragment secret.
32//!
33//! ## The record a viewer starts from
34//!
35//! What the viewer needs besides the keys — each covered asset's content address and key-free
36//! crypto parameters — is a [`ShareMetadata`](crate::sharing::ShareMetadata) record, canonical
37//! CBOR sealed under `HKDF(link_secret, salt=opaque_id, info=share-metadata/v1)` and uploaded as
38//! the blob at the link's `metadata_hash`. [`publish_share`](crate::sharing::publish_share)
39//! builds it and [`open_share_metadata`](crate::sharing::open_share_metadata) opens it. A
40//! link-only scope travels inside the record; a passphrase scope is served only from
41//! `/s/{opaque-id}/wrapped-secret`, so the fragment alone never opens what the passphrase guards.
42//!
43//! [Share Links]: https://docs/design/share-links/
44//! [Cryptography — Keys § Non-registered accounts]: https://docs/design/cryptography/keys/#non-registered-accounts
45//! [pw]: https://docs/design/cryptography/primitives/#password-based-kdf
46
47use std::collections::BTreeMap;
48
49use serde::{Deserialize, Serialize};
50use thiserror::Error;
51use uuid::Uuid;
52
53use crate::cbor;
54use crate::crypto::encryption::{open_blob, seal_blob};
55use crate::crypto::keys::Amk;
56use crate::crypto::primitives::{Argon2Params, info};
57use crate::crypto::pwkdf::{self, WrappedSecret};
58use crate::crypto::{kdf, rng};
59
60/// Length of the random link secret carried in the URL fragment. 32 bytes = 256 bits,
61/// comfortably above the design's ≥128-bit floor for the link secret.
62pub const LINK_SECRET_LEN: usize = 32;
63
64/// Length of the opaque URL-path id: a **full 128 bits** of CSPRNG entropy — never a
65/// structured/UUIDv7 id whose embedded timestamp would cut real entropy to ~62 bits
66/// (SSoT: [Share Links] Security Contract — Opaque-id entropy).
67///
68/// [Share Links]: https://docs/design/share-links/
69pub const OPAQUE_ID_LEN: usize = 16;
70
71/// What a share link points at. The `{opaque-id}` itself carries **no** scope — the
72/// server resolves scope from the link record, so the URL leaks nothing.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum ShareScope {
75 /// A single asset.
76 Asset(Uuid),
77 /// A whole album.
78 Album(Uuid),
79}
80
81/// Identifies an issued share link for revocation. Internal owner-held handle (never in
82/// the URL), so a creation-time-leaking UUIDv7 is appropriate here — unlike the
83/// URL-exposed [`ShareLink::opaque_id`], which must be non-structured.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
85pub struct ShareLinkId(pub Uuid);
86
87/// The scope's decryption material — the "decryption keys" that get encapsulated into the
88/// link. Serialized to canonical CBOR before sealing, so two implementations encapsulate
89/// byte-identically.
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub enum ScopeMaterial {
92 /// A single asset: its per-file AES-256 key (already derived under the asset's epoch
93 /// AMK, so the recipient needs no album key).
94 Asset {
95 /// The asset / file id the key belongs to.
96 file_id: Uuid,
97 /// The asset's per-file key.
98 file_key: [u8; 32],
99 },
100 /// A whole album: the AMK for every epoch, so the recipient can derive any managed
101 /// asset's file key regardless of the epoch it was written under.
102 Album {
103 /// The album id.
104 album_id: Uuid,
105 /// AMK bytes keyed by epoch.
106 amks: BTreeMap<u32, [u8; 32]>,
107 },
108}
109
110impl ScopeMaterial {
111 /// Derive the per-file AES-256 key for `file_id`, written under epoch `amk_version` with
112 /// the manifest's `nonce_prefix`.
113 ///
114 /// For an [`Asset`](ScopeMaterial::Asset) scope the key is returned directly (and the
115 /// `file_id` must match) — the grant was minted with the asset's own `nonce_prefix`
116 /// already folded in, so the argument is unused. For an [`Album`](ScopeMaterial::Album)
117 /// scope it is derived from the requested epoch's AMK with `nonce_prefix` folded into the
118 /// salt (the fold is what re-rolls the key per write). A file/epoch this material does not
119 /// cover is [`SharingError::ScopeUnavailable`].
120 ///
121 /// The album arm assumes `key_mode = derived`: the triple carries no `wrapped_file_key`,
122 /// so it cannot recover an adopted web-upload drop's key. A caller holding the asset's
123 /// manifest uses [`file_key_for_manifest`](Self::file_key_for_manifest), which honours
124 /// `key_mode`.
125 pub fn file_key_for(
126 &self,
127 file_id: &Uuid,
128 amk_version: u32,
129 nonce_prefix: &[u8],
130 ) -> Result<[u8; 32], SharingError> {
131 match self {
132 ScopeMaterial::Asset {
133 file_id: owned,
134 file_key,
135 } => (owned == file_id)
136 .then_some(*file_key)
137 .ok_or(SharingError::ScopeUnavailable),
138 ScopeMaterial::Album { amks, .. } => amks
139 .get(&amk_version)
140 .map(|amk| Amk::from_bytes(*amk).derive_file_key(file_id, nonce_prefix))
141 .ok_or(SharingError::ScopeUnavailable),
142 }
143 }
144
145 /// Recover the per-file key of the original `core` describes, honouring its `key_mode`.
146 ///
147 /// For an [`Asset`](ScopeMaterial::Asset) scope the carried key is returned (the issuer
148 /// already resolved the key mode when it minted the grant) and `core.file_id` must match.
149 /// For an [`Album`](ScopeMaterial::Album) scope the AMK of `core.amk_version` recovers it
150 /// through [`recover_file_key`](crate::crypto::encryption::recover_file_key): a `derived`
151 /// original re-derives, a `wrapped` one (an adopted web-upload drop) unwraps
152 /// `wrapped_file_key`. A file, album, or epoch this material does not cover is
153 /// [`SharingError::ScopeUnavailable`]; a wrapped key that does not open, or is missing, is
154 /// [`SharingError::Crypto`].
155 pub fn file_key_for_manifest(
156 &self,
157 core: &crate::crypto::provenance::ManifestCore,
158 ) -> Result<[u8; 32], SharingError> {
159 match self {
160 ScopeMaterial::Asset { .. } => {
161 self.file_key_for(&core.file_id, core.amk_version.0, &core.nonce_prefix)
162 }
163 ScopeMaterial::Album { album_id, amks } => {
164 // Epoch numbers are per album, so another album's manifest at the same epoch
165 // would otherwise be handed a key this grant does not cover.
166 if core.album_id != *album_id {
167 return Err(SharingError::ScopeUnavailable);
168 }
169 let amk = amks
170 .get(&core.amk_version.0)
171 .ok_or(SharingError::ScopeUnavailable)?;
172 crate::crypto::encryption::recover_file_key(&Amk::from_bytes(*amk), core)
173 .map_err(|_| SharingError::Crypto("asset file key recovery failed"))
174 }
175 }
176 }
177
178 /// [`file_key_for_manifest`](Self::file_key_for_manifest) over the four manifest fields it
179 /// reads, for a recipient that is served those fields rather than the signed manifest: the
180 /// browser share viewer, through `capsule-wasm`.
181 ///
182 /// An [`Asset`](ScopeMaterial::Asset) scope carries its key directly, as in
183 /// [`file_key_for`](Self::file_key_for). For an [`Album`](ScopeMaterial::Album) scope the
184 /// AMK of `amk_version` recovers it through
185 /// [`recover_file_key_parts`](crate::crypto::encryption::recover_file_key_parts), which
186 /// follows `key_mode`. There is no album id to check: the caller names no album, and a
187 /// grant's material covers only its own. A wrapped key from another album does not open
188 /// under this grant's AMK, and fails closed here.
189 ///
190 /// Errors are those of `file_key_for_manifest`: an epoch the grant does not hold is
191 /// [`SharingError::ScopeUnavailable`], and a wrapped key that is missing or does not open is
192 /// [`SharingError::Crypto`].
193 pub fn file_key_for_key_mode(
194 &self,
195 file_id: &Uuid,
196 amk_version: u32,
197 nonce_prefix: &[u8],
198 key_mode: crate::crypto::provenance::KeyMode,
199 wrapped_file_key: Option<&crate::crypto::provenance::WrappedFileKey>,
200 ) -> Result<[u8; 32], SharingError> {
201 match self {
202 ScopeMaterial::Asset { .. } => self.file_key_for(file_id, amk_version, nonce_prefix),
203 ScopeMaterial::Album { amks, .. } => {
204 let amk = amks
205 .get(&amk_version)
206 .ok_or(SharingError::ScopeUnavailable)?;
207 crate::crypto::encryption::recover_file_key_parts(
208 &Amk::from_bytes(*amk),
209 file_id,
210 nonce_prefix,
211 key_mode,
212 wrapped_file_key,
213 )
214 .map_err(|_| SharingError::Crypto("asset file key recovery failed"))
215 }
216 }
217 }
218}
219
220/// The server-held, **opaque** encapsulation of a link's [`ScopeMaterial`]. The server
221/// can neither open it nor observe the passphrase; it only stores and returns these bytes.
222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
223pub enum WrappedScope {
224 /// Encapsulated around the link secret only — opened with the fragment secret alone.
225 LinkOnly {
226 /// `seal_blob(HKDF(link_secret, opaque_id), CBOR(scope_material))`.
227 blob: Vec<u8>,
228 },
229 /// The link-secret encapsulation, **additionally** wrapped under an Argon2id
230 /// passphrase key. Opened client-side (the passphrase never reaches the server); this
231 /// is the material served from `/s/{opaque-id}/wrapped-secret`.
232 Passphrase {
233 /// `pwkdf::wrap(link_only_blob, passphrase)` — self-describing Argon2id params.
234 wrapped: WrappedSecret,
235 },
236}
237
238impl WrappedScope {
239 /// Whether an Argon2id passphrase layer protects this material.
240 pub fn is_passphrase_protected(&self) -> bool {
241 matches!(self, WrappedScope::Passphrase { .. })
242 }
243}
244
245/// A published revocation record. The serving endpoint refuses a link once its record
246/// exists (within its fail-closed cache window — SSoT: [Share Links] Security Contract).
247///
248/// [Share Links]: https://docs/design/share-links/
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct RevocationRecord {
251 /// The revoked link.
252 pub link_id: ShareLinkId,
253 /// RFC 3339 revocation timestamp.
254 pub revoked_at: String,
255}
256
257/// The issuer-held record for one live share link — the authoritative state the serving
258/// endpoint consults: the opaque id it is addressed by, the scope it resolves to,
259/// the server-held wrapped material, expiry, and any revocation record.
260#[derive(Debug, Clone)]
261pub struct ShareLinkRecord {
262 /// Revocation handle.
263 pub link_id: ShareLinkId,
264 /// The random 128-bit opaque id (URL path component).
265 pub opaque_id: [u8; OPAQUE_ID_LEN],
266 /// What the link grants access to.
267 pub scope: ShareScope,
268 /// The opaque, server-held encapsulated scope material.
269 pub wrapped_scope: WrappedScope,
270 /// RFC 3339 expiry, if any.
271 pub expires_at: Option<String>,
272 /// RFC 3339 issuance timestamp.
273 pub created_at: String,
274 /// Present once the link has been revoked.
275 pub revocation: Option<RevocationRecord>,
276}
277
278impl ShareLinkRecord {
279 /// Whether the link is still live at `now`: not revoked and not past its expiry.
280 /// The serving endpoint is fail-closed; this is the authoritative predicate it caches.
281 pub fn is_live_at(&self, now: jiff::Timestamp) -> bool {
282 if self.revocation.is_some() {
283 return false;
284 }
285 match &self.expires_at {
286 None => true,
287 Some(ts) => ts.parse::<jiff::Timestamp>().is_ok_and(|exp| now < exp),
288 }
289 }
290}
291
292/// An issued share link: the server-held record fields plus the fragment secret the
293/// issuing client places in the URL. The fragment secret **never** leaves the client.
294#[derive(Debug, Clone)]
295pub struct ShareLink {
296 /// Revocation handle.
297 pub link_id: ShareLinkId,
298 /// The random 128-bit opaque id (URL path component; never structured/UUIDv7).
299 pub opaque_id: [u8; OPAQUE_ID_LEN],
300 /// What the link grants access to.
301 pub scope: ShareScope,
302 /// The URL fragment `#{secret}` — the random link secret. **Never** sent to the
303 /// server; the server holds only [`wrapped_scope`](ShareLink::wrapped_scope).
304 pub fragment_secret: [u8; LINK_SECRET_LEN],
305 /// The server-held, opaque encapsulation of the scope material.
306 pub wrapped_scope: WrappedScope,
307 /// RFC 3339 expiry, if any.
308 pub expires_at: Option<String>,
309}
310
311impl ShareLink {
312 /// Lowercase-hex of the opaque URL-path id.
313 pub fn opaque_id_hex(&self) -> String {
314 hex::encode(self.opaque_id)
315 }
316
317 /// Lowercase-hex of the URL fragment secret (the `#{secret}` component).
318 pub fn fragment_hex(&self) -> String {
319 hex::encode(self.fragment_secret)
320 }
321
322 /// Whether the link is passphrase-protected (an Argon2id layer wraps the material).
323 pub fn is_passphrase_protected(&self) -> bool {
324 self.wrapped_scope.is_passphrase_protected()
325 }
326}
327
328/// Failure surfaced by share-link issuance, revocation, and recipient-side opening.
329#[derive(Debug, Error, PartialEq, Eq)]
330pub enum SharingError {
331 /// The scope does not exist or the issuer lacks access to it.
332 #[error("share scope unavailable")]
333 ScopeUnavailable,
334 /// The link was not found (already revoked, or never issued).
335 #[error("share link not found")]
336 NotFound,
337 /// The link is passphrase-protected but no passphrase was supplied to open it.
338 #[error("share link is passphrase-protected but no passphrase was supplied")]
339 PassphraseRequired,
340 /// The supplied passphrase was wrong (or the wrapped secret was tampered with).
341 #[error("wrong passphrase or corrupt wrapped secret")]
342 WrongPassphrase,
343 /// Key material could not be prepared or opened for the link secret.
344 #[error("share crypto failure: {0}")]
345 Crypto(&'static str),
346 /// Material opened but is not a structure this reader understands (an unknown share
347 /// metadata version, or a record that breaks one of its rules).
348 #[error("malformed share material: {0}")]
349 Malformed(&'static str),
350}
351
352/// Draw a fresh opaque URL-path id: a full 128 bits of CSPRNG entropy, **not** a
353/// structured or sequential identifier (SSoT: [Share Links] Security Contract).
354///
355/// [Share Links]: https://docs/design/share-links/
356pub fn generate_opaque_id() -> [u8; OPAQUE_ID_LEN] {
357 rng::random_array::<OPAQUE_ID_LEN>()
358}
359
360/// Derive the link-secret wrapping key: `HKDF(ikm=link_secret, salt=opaque_id,
361/// info=share-scope-wrap/v1)`. Salting with the opaque id binds the encapsulation to its
362/// one link, so a wrapped blob only opens under the id it was issued for.
363fn link_wrap_key(
364 fragment_secret: &[u8; LINK_SECRET_LEN],
365 opaque_id: &[u8; OPAQUE_ID_LEN],
366) -> [u8; 32] {
367 kdf::derive_key32(fragment_secret, opaque_id, info::SHARE_SCOPE_WRAP_V1)
368}
369
370/// Encapsulate `material` around a fresh link secret, optionally adding the Argon2id
371/// passphrase layer. Pure crypto — the caller supplies the CSPRNG-drawn secrets and the
372/// resolved material, so it is unit-testable without a `Workspace`.
373///
374/// The issuer-side primitive [`open_scope`] reverses. Public so the cross-language KAT generator
375/// (`cargo xtask share-kat`) can seal fixtures byte-identically to the native issuer, then have
376/// the browser (`capsule-wasm`) reopen them.
377pub fn encapsulate_scope(
378 material: &ScopeMaterial,
379 fragment_secret: &[u8; LINK_SECRET_LEN],
380 opaque_id: &[u8; OPAQUE_ID_LEN],
381 passphrase: Option<&str>,
382 argon2: Argon2Params,
383) -> Result<WrappedScope, SharingError> {
384 let plaintext = cbor::to_canonical_vec(material)
385 .map_err(|_| SharingError::Crypto("scope serialization failed"))?;
386 let blob = seal_blob(&link_wrap_key(fragment_secret, opaque_id), &plaintext);
387 match passphrase {
388 None => Ok(WrappedScope::LinkOnly { blob }),
389 Some(pw) => {
390 let wrapped = pwkdf::wrap_with(&blob, pw.as_bytes(), argon2)
391 .map_err(|_| SharingError::Crypto("passphrase wrap failed"))?;
392 Ok(WrappedScope::Passphrase { wrapped })
393 }
394 }
395}
396
397/// Open a link's encapsulated [`ScopeMaterial`] **client-side** — the recipient path.
398///
399/// The recipient holds only the URL: the `opaque_id` (path) and `fragment_secret`
400/// (fragment). When the link is passphrase-protected the caller must supply the
401/// passphrase; the Argon2id unwrap runs **here, on the client**, and the passphrase is
402/// never transmitted (SSoT: [Share Links] — Passphrase unwrap is client-side).
403///
404/// [Share Links]: https://docs/design/share-links/
405pub fn open_scope(
406 wrapped: &WrappedScope,
407 opaque_id: &[u8; OPAQUE_ID_LEN],
408 fragment_secret: &[u8; LINK_SECRET_LEN],
409 passphrase: Option<&str>,
410) -> Result<ScopeMaterial, SharingError> {
411 let blob = match wrapped {
412 WrappedScope::LinkOnly { blob } => blob.clone(),
413 WrappedScope::Passphrase { wrapped } => {
414 let pw = passphrase.ok_or(SharingError::PassphraseRequired)?;
415 pwkdf::unwrap(wrapped, pw.as_bytes()).map_err(|_| SharingError::WrongPassphrase)?
416 }
417 };
418 let plaintext = open_blob(&link_wrap_key(fragment_secret, opaque_id), &blob)
419 .map_err(|_| SharingError::Crypto("scope decapsulation failed"))?;
420 cbor::from_slice(&plaintext).map_err(|_| SharingError::Crypto("scope deserialization failed"))
421}
422
423// ───────────────────────── The share metadata record (issue #614) ─────────────────────────
424
425/// Schema string of the share metadata record. A reader refuses any other value rather than
426/// guessing at a shape it does not know.
427pub const SHARE_METADATA_VERSION: &str = "share-metadata/v1";
428
429/// One covered asset as a share viewer is served it: every **key-free** parameter it needs to
430/// fetch the asset's ciphertext and decrypt it under the opened [`ScopeMaterial`].
431///
432/// The field names and wire rules mirror the signed manifest's
433/// ([`ManifestCore`](crate::crypto::provenance::ManifestCore)): `key_mode` is wire-absent when
434/// `derived`, and `wrapped_file_key` is present iff `key_mode = wrapped`. Nothing here is a key:
435/// the nonce prefix is public by construction and the wrapped key is AMK-sealed ciphertext.
436///
437/// The asset's capture metadata travels only in [`sidecar`](Self::sidecar), the copy the issuing
438/// client already passed through the [Privacy on Export] strip (`sidecar_for_export`, a
439/// `native` item) before sealing. Every other field
440/// is key-free crypto plumbing; a field that adds capture metadata is a boundary-crossing field
441/// and must be added already stripped.
442///
443/// [Privacy on Export]: https://docs/design/metadata/#privacy-on-export
444#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
445pub struct SharedAsset {
446 /// The asset's file id — the id its per-file key is derived or unwrapped for.
447 pub asset_id: Uuid,
448 /// The ciphertext's content address: the `{hash}` of `/s/{opaque-id}/blob/{hash}`.
449 pub content_hash: crate::crypto::hash::Hash32,
450 /// The plaintext media type, which the viewer wraps the decrypted bytes in.
451 pub content_type: String,
452 /// The plaintext byte length.
453 pub size: u64,
454 /// The AMK epoch the asset was written under; `0` for an asset-scoped grant, whose key the
455 /// scope material carries directly.
456 pub amk_version: u32,
457 /// The STREAM nonce prefix the ciphertext was written with.
458 pub nonce_prefix: [u8; crate::crypto::encryption::NONCE_PREFIX_LEN],
459 /// How the file key is obtained; wire-absent when `derived`.
460 #[serde(
461 default,
462 skip_serializing_if = "crate::crypto::provenance::KeyMode::is_derived"
463 )]
464 pub key_mode: crate::crypto::provenance::KeyMode,
465 /// The AMK-sealed file key; present iff `key_mode = wrapped`.
466 #[serde(default, skip_serializing_if = "Option::is_none")]
467 pub wrapped_file_key: Option<crate::crypto::provenance::WrappedFileKey>,
468 /// Canonical CBOR of the asset's **export** sidecar: the library sidecar after the
469 /// [Privacy on Export] strip, unsigned once anything was stripped. Wire-absent when the
470 /// issuer sent none, so a record without it encodes byte-identically to one written before
471 /// the field existed, and a reader that predates it ignores it. A `native` reader decodes
472 /// it with `SharedAsset::exported_sidecar`; the browser viewer carries it unread.
473 ///
474 /// [Privacy on Export]: https://docs/design/metadata/#privacy-on-export
475 #[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]
476 pub sidecar: Option<Vec<u8>>,
477}
478
479#[cfg(feature = "native")]
480impl SharedAsset {
481 /// Decode the [`sidecar`](Self::sidecar) the issuer sealed for this asset, if any.
482 ///
483 /// # Errors
484 ///
485 /// [`SharingError::Malformed`] when the bytes are not a sidecar this reader understands, or
486 /// are the sidecar of another asset.
487 pub fn exported_sidecar(&self) -> Result<Option<crate::sidecar::SidecarV1>, SharingError> {
488 let Some(bytes) = self.sidecar.as_deref() else {
489 return Ok(None);
490 };
491 let sidecar = crate::sidecar::SidecarV1::from_canonical_slice(
492 bytes,
493 crate::sidecar::SIDECAR_SCHEMA_V1,
494 )
495 .map_err(|_| SharingError::Malformed("a shared asset's sidecar does not decode"))?;
496 if sidecar.uuid != self.asset_id {
497 return Err(SharingError::Malformed(
498 "a shared asset's sidecar names another asset",
499 ));
500 }
501 Ok(Some(sidecar))
502 }
503}
504
505/// The record a share viewer starts from, sealed into the blob at the link's `metadata_hash`
506/// (`GET /s/{opaque-id}` names the hash; `/s/{opaque-id}/blob/{hash}` serves the bytes).
507///
508/// Sealed under `HKDF(link_secret, salt=opaque_id, info=share-metadata/v1)`, so the server, which
509/// never sees the fragment, cannot read it. Built by [`publish_share`] and read by
510/// [`open_share_metadata`].
511#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
512pub struct ShareMetadata {
513 /// Always [`SHARE_METADATA_VERSION`].
514 pub version: String,
515 /// RFC 3339 expiry the issuer set, shown to the viewer. The server enforces expiry on its own
516 /// record and never discloses it; this copy is for display only.
517 #[serde(default, skip_serializing_if = "Option::is_none")]
518 pub expires_at: Option<String>,
519 /// The link-only [`WrappedScope`], present **iff** the link has no passphrase.
520 ///
521 /// A link with no passphrase has no wrapped secret on the server, so its scope travels here.
522 /// A passphrase link's scope never does: placing it here would let the fragment alone open
523 /// what the passphrase is meant to guard, so it is served only from
524 /// `/s/{opaque-id}/wrapped-secret`.
525 #[serde(default, skip_serializing_if = "Option::is_none")]
526 pub link_scope: Option<WrappedScope>,
527 /// Every asset the link covers.
528 pub assets: Vec<SharedAsset>,
529}
530
531impl ShareMetadata {
532 /// Check the structural rules a reader relies on: the schema string, a link scope that is
533 /// the link-only form when present, and the manifest's `wrapped_file_key`-iff-`wrapped` rule.
534 fn validate(&self) -> Result<(), SharingError> {
535 if self.version != SHARE_METADATA_VERSION {
536 return Err(SharingError::Malformed("unknown share metadata version"));
537 }
538 if self
539 .link_scope
540 .as_ref()
541 .is_some_and(WrappedScope::is_passphrase_protected)
542 {
543 return Err(SharingError::Malformed(
544 "share metadata carries a passphrase-wrapped scope",
545 ));
546 }
547 let wrapped = crate::crypto::provenance::KeyMode::Wrapped;
548 if self
549 .assets
550 .iter()
551 .any(|asset| asset.wrapped_file_key.is_some() != (asset.key_mode == wrapped))
552 {
553 return Err(SharingError::Malformed(
554 "a shared asset's wrapped_file_key disagrees with its key_mode",
555 ));
556 }
557 Ok(())
558 }
559}
560
561/// What an issuing client hands the server for one link: the sealed metadata blob to upload, and
562/// the fields of `POST /v1/shares`.
563#[derive(Debug, Clone, PartialEq, Eq)]
564pub struct SharePublication {
565 /// The sealed [`ShareMetadata`] blob, uploaded at [`metadata_hash`](Self::metadata_hash).
566 pub metadata_blob: Vec<u8>,
567 /// The metadata blob's content address — the request's `metadata_hash`.
568 pub metadata_hash: crate::crypto::hash::Hash32,
569 /// Every address the link may serve: the metadata blob first, then each covered asset's
570 /// ciphertext, without repeats — the request's `serves`.
571 pub serves: Vec<crate::crypto::hash::Hash32>,
572 /// Canonical CBOR of the passphrase [`WrappedScope`], present iff the link is
573 /// passphrase-protected — the request's `wrapped_secret` (base64 on the wire), served back
574 /// byte for byte from `/s/{opaque-id}/wrapped-secret`.
575 pub wrapped_secret: Option<Vec<u8>>,
576}
577
578/// Derive the metadata-record key: `HKDF(ikm=link_secret, salt=opaque_id,
579/// info=share-metadata/v1)`.
580fn metadata_key(
581 fragment_secret: &[u8; LINK_SECRET_LEN],
582 opaque_id: &[u8; OPAQUE_ID_LEN],
583) -> [u8; 32] {
584 kdf::derive_key32(fragment_secret, opaque_id, info::SHARE_METADATA_V1)
585}
586
587/// Prepare everything the server needs to serve a link whose scope is already encapsulated
588/// (`wrapped`, from [`encapsulate_scope`] under the same `fragment_secret` and `opaque_id`).
589///
590/// Decides where the scope travels: a link-only scope goes inside the sealed record, a passphrase
591/// scope goes to [`SharePublication::wrapped_secret`] and nowhere else. The record is sealed under
592/// the fragment-derived metadata key, so it opens with the URL alone.
593///
594/// # Errors
595///
596/// [`SharingError::Malformed`] when `assets` breaks the `wrapped_file_key`-iff-`wrapped` rule,
597/// and [`SharingError::Crypto`] when a record cannot be serialized.
598pub fn publish_share(
599 wrapped: &WrappedScope,
600 fragment_secret: &[u8; LINK_SECRET_LEN],
601 opaque_id: &[u8; OPAQUE_ID_LEN],
602 expires_at: Option<String>,
603 assets: Vec<SharedAsset>,
604) -> Result<SharePublication, SharingError> {
605 let (link_scope, wrapped_secret) = match wrapped {
606 WrappedScope::LinkOnly { .. } => (Some(wrapped.clone()), None),
607 WrappedScope::Passphrase { .. } => {
608 let bytes = cbor::to_canonical_vec(wrapped)
609 .map_err(|_| SharingError::Crypto("wrapped scope serialization failed"))?;
610 (None, Some(bytes))
611 }
612 };
613 let record = ShareMetadata {
614 version: SHARE_METADATA_VERSION.to_owned(),
615 expires_at,
616 link_scope,
617 assets,
618 };
619 record.validate()?;
620 let plaintext = cbor::to_canonical_vec(&record)
621 .map_err(|_| SharingError::Crypto("share metadata serialization failed"))?;
622 let metadata_blob = seal_blob(&metadata_key(fragment_secret, opaque_id), &plaintext);
623 let metadata_hash = crate::crypto::hash::hash_bytes(&metadata_blob);
624
625 let mut serves = vec![metadata_hash];
626 for asset in &record.assets {
627 if !serves.contains(&asset.content_hash) {
628 serves.push(asset.content_hash);
629 }
630 }
631 tracing::debug!(
632 assets = record.assets.len(),
633 passphrase = wrapped_secret.is_some(),
634 blob_len = metadata_blob.len(),
635 "share metadata sealed"
636 );
637 Ok(SharePublication {
638 metadata_blob,
639 metadata_hash,
640 serves,
641 wrapped_secret,
642 })
643}
644
645/// Open the sealed metadata record a viewer fetched from the link's `metadata_hash` — the
646/// recipient half of [`publish_share`], run client-side with the URL's opaque id and fragment.
647///
648/// # Errors
649///
650/// [`SharingError::Crypto`] when the blob does not open under this URL's fragment (a wrong
651/// fragment, a wrong opaque id, or a tampered blob, which are indistinguishable), and
652/// [`SharingError::Malformed`] when it opens but is not a record this reader understands.
653pub fn open_share_metadata(
654 blob: &[u8],
655 opaque_id: &[u8; OPAQUE_ID_LEN],
656 fragment_secret: &[u8; LINK_SECRET_LEN],
657) -> Result<ShareMetadata, SharingError> {
658 let plaintext = open_blob(&metadata_key(fragment_secret, opaque_id), blob)
659 .map_err(|_| SharingError::Crypto("share metadata decapsulation failed"))?;
660 let record: ShareMetadata = cbor::from_slice(&plaintext)
661 .map_err(|_| SharingError::Malformed("share metadata is not a record"))?;
662 record.validate()?;
663 Ok(record)
664}
665
666/// Issues and revokes view-only share links on a trusted client — the seam
667/// `lifecycle::Workspace` implements. Issuance encapsulates the scope's decryption
668/// material around a fresh link secret; the optional passphrase adds the second,
669/// client-side-unwrapped encapsulation layer.
670pub trait ShareLinkIssuer {
671 /// Issue a view-only link for `scope`, optionally expiring and/or
672 /// passphrase-wrapped.
673 fn create_link(
674 &mut self,
675 scope: ShareScope,
676 expires_at: Option<String>,
677 passphrase: Option<&str>,
678 ) -> Result<ShareLink, SharingError>;
679
680 /// Revoke a link; the serve path refuses it within its fail-closed cache window.
681 fn revoke_link(&mut self, link: ShareLinkId) -> Result<(), SharingError>;
682}
683
684#[cfg(test)]
685mod tests;