Skip to main content

capsule_core/crypto/provenance/
manifest.rs

1//! The signed asset manifest and derivative manifest (SSoT: [Cryptography — Provenance]).
2//!
3//! A manifest carries **two** hybrid signatures over the same canonical core bytes:
4//! `device_sig` (provenance — which device produced it) and `write_sig` (authorization —
5//! the album's per-epoch write-tier key). Both must verify at [`verify_asset`]. The core
6//! excludes the signatures, so signing bytes are unambiguous and downgrade-resistant
7//! (both sigs cover `crypto_suite_id`, `protocol_version`, and `prior_provenance_hash`).
8//!
9//! [`verify_asset`]: crate::crypto::verify_asset::verify_asset
10//! [Cryptography — Provenance]: https://docs/design/cryptography/provenance/
11
12use std::collections::BTreeMap;
13
14use ciborium::value::Value;
15use serde::{Deserialize, Serialize};
16use uuid::Uuid;
17
18use super::action::{Action, DerivativeRole};
19use crate::cbor;
20use crate::crypto::CryptoError;
21use crate::crypto::hash::Hash32;
22use crate::crypto::keys::{AmkVersion, HybridSignature, Signer};
23
24/// Current asset-manifest schema string.
25pub const ASSET_MANIFEST_VERSION: &str = "asset-manifest/v1";
26/// Current derivative-manifest schema string.
27pub const DERIVATIVE_MANIFEST_VERSION: &str = "derivative-manifest/v1";
28
29/// How a reader obtains the asset's file key (closed enum; SSoT:
30/// [Cryptography — Provenance](https://docs/design/cryptography/provenance/)).
31///
32/// Wire-presence rule: `Derived` is the default and encodes as an **absent** map key in
33/// canonical CBOR (`skip_serializing_if`), so manifests signed before this field existed
34/// re-verify byte-identically. Emitting `key_mode: "derived"` explicitly would change the
35/// signed bytes and break verification.
36#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "kebab-case")]
38pub enum KeyMode {
39    /// The file key is recomputed from the AMK (`asset-file/v1`); nothing is stored.
40    #[default]
41    Derived,
42    /// The file key was chosen externally (an adopted web-upload drop) and is carried in
43    /// `wrapped_file_key`, sealed under the AMK (`asset-keywrap/v1`).
44    Wrapped,
45}
46
47impl KeyMode {
48    /// Serde helper: the default (`derived`) is wire-absent.
49    pub fn is_derived(&self) -> bool {
50        matches!(self, Self::Derived)
51    }
52}
53
54/// An externally-chosen file key sealed under the AMK: `wrap_nonce || AES-256-GCM(K) || tag`
55/// (the `asset-keywrap/v1` derivation — see
56/// [Encryption — Asset Key Derivation](https://docs/design/cryptography/encryption/)).
57/// Length is fixed by `crypto_suite_id`; the bytes are ciphertext, opaque to the server.
58///
59/// Serializes as a CBOR **byte string** (major type 2), like [`Hash32`] — never as an
60/// array of integers — so canonical encodings are byte-identical across implementations.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct WrappedFileKey(pub Vec<u8>);
63
64impl Serialize for WrappedFileKey {
65    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
66        s.serialize_bytes(&self.0)
67    }
68}
69
70impl<'de> Deserialize<'de> for WrappedFileKey {
71    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
72        struct V;
73        impl<'de> serde::de::Visitor<'de> for V {
74            type Value = WrappedFileKey;
75            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76                f.write_str("an AMK-wrapped file key as a byte string")
77            }
78            fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<WrappedFileKey, E> {
79                Ok(WrappedFileKey(v.to_vec()))
80            }
81            fn visit_seq<A: serde::de::SeqAccess<'de>>(
82                self,
83                mut seq: A,
84            ) -> Result<WrappedFileKey, A::Error> {
85                // Tolerate decoders that surface a byte string as a sequence.
86                let mut out = Vec::new();
87                while let Some(b) = seq.next_element()? {
88                    out.push(b);
89                }
90                Ok(WrappedFileKey(out))
91            }
92        }
93        d.deserialize_bytes(V)
94    }
95}
96
97/// The signed core of an asset manifest — every field the two signatures cover.
98///
99/// **Unknown keys survive under the signature** ([Versioning — invariant 2]). A key this build
100/// does not know is kept verbatim in [`Self::unknown`], re-emitted by the canonical encoder
101/// beside the known fields, and therefore covered by both signatures: a newer writer's manifest
102/// that only adds a field verifies here, and stripping that field fails verification. The
103/// decoder is hand-written for that reason (see the `Deserialize` impl below): `serde(flatten)`
104/// buffers unknown values through serde's private content type, which cannot hold a CBOR tag
105/// or an integer wider than 64 bits, so a future field carrying either would make the whole
106/// manifest undecodable instead of preserved.
107///
108/// [Versioning — invariant 2]: https://docs/design/versioning/#system-invariants
109#[derive(Debug, Clone, PartialEq, Serialize)]
110pub struct ManifestCore {
111    /// Schema version string (`asset-manifest/v1`).
112    pub version: String,
113    /// The primitive bundle this manifest was produced under.
114    pub crypto_suite_id: u16,
115    /// Date-based wire protocol version; matches the album pin.
116    pub protocol_version: String,
117    /// The asset's file id.
118    pub file_id: Uuid,
119    /// The album the asset belongs to.
120    pub album_id: Uuid,
121    /// The AMK epoch (and write-tier key) this manifest is authorized under.
122    pub amk_version: AmkVersion,
123    /// Content-address digest over the ciphertext.
124    pub ciphertext_hash: Hash32,
125    /// Total plaintext byte length.
126    pub plaintext_size: u64,
127    /// Plaintext bytes per STREAM chunk.
128    pub chunk_size: u32,
129    /// STREAM nonce prefix (random per file).
130    pub nonce_prefix: [u8; 7],
131    /// How the file key is obtained: `derived` (default; wire-absent) or `wrapped` (an
132    /// adopted web-upload drop). Closed enum — see [`KeyMode`] for the wire-presence rule.
133    #[serde(default, skip_serializing_if = "KeyMode::is_derived")]
134    pub key_mode: KeyMode,
135    /// The AMK-sealed file key; present iff `key_mode = wrapped`, wire-absent otherwise.
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub wrapped_file_key: Option<WrappedFileKey>,
138    /// Content address of the asset's encrypted metadata blob. Present on
139    /// `create | replace | metadata-update`; wire-absent (key omitted, never null) on
140    /// `delete | derivative-* | trash-restore`.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub metadata_blob_hash: Option<Hash32>,
143    /// The account whose device signed **this record**.
144    ///
145    /// Per-record, not per-asset: a `delete` written by a second device — or by a member of a
146    /// shared album — names that writer, not the account that created the asset. The asset's
147    /// original creator is recoverable from the `create` record at the head of the append-only
148    /// provenance chain, which is where it belongs.
149    ///
150    /// The pairing with [`Self::created_by_device`] is load-bearing rather than descriptive:
151    /// [`verify_asset`](crate::crypto::verify_asset::verify_asset) resolves the device *inside
152    /// this account's* published directory (step 6) and verifies [`AssetManifest::device_sig`]
153    /// under that entry's key (step 8), so a record naming anyone but its own signer cannot
154    /// verify. Album write authority is decided separately, by `write_sig` at step 10.
155    pub created_by_user: Uuid,
156    /// The device that signed **this record**, resolved in [`Self::created_by_user`]'s directory.
157    ///
158    /// Per-record for the same reason and with the same consequence: it must be the device whose
159    /// DSK produced [`AssetManifest::device_sig`], or step 8 of
160    /// [`verify_asset`](crate::crypto::verify_asset::verify_asset) rejects the manifest. The
161    /// server mirrors the resolvable half key-free as invariant 7 — the device must be in the
162    /// *calling* account's published directory, with `added_at` before the manifest's timestamp.
163    pub created_by_device: Uuid,
164    /// Producing client version string.
165    pub client_version: String,
166    /// Self-asserted capture/write time (RFC3339). Audit-only; never load-bearing.
167    pub timestamp: String,
168    /// The lifecycle action.
169    pub action: Action,
170    /// SHA-256 of the previous manifest in this asset's chain; null iff `action = create`.
171    pub prior_provenance_hash: Option<Hash32>,
172    /// Server-visible retention deadline (RFC3339); set only for `action = delete`.
173    pub retention_until: Option<String>,
174    /// The album this asset's album was **forked from**, when it is a fork.
175    ///
176    /// The normative link between an upgraded album and its predecessor — never the MLS group
177    /// name, which is an internal detail. A device that joins the fork reads this and can walk
178    /// back to the album the asset came from; without it, a fork looks like an unrelated album
179    /// full of assets that appeared from nowhere.
180    ///
181    /// **Wire-absent when there is none**, never present-`null`. This is inside the signed core,
182    /// so a present-`null` would change [`signing_bytes`](Self::signing_bytes) and silently break
183    /// re-verification of every manifest written before the field existed — the same trap
184    /// `dek_public` avoids, and the reason
185    /// `an_absent_lineage_is_wire_absent_and_does_not_move_the_signature` exists.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub upgraded_from: Option<crate::crypto::upgrade::UpgradeLineage>,
188    /// Keys a newer writer added that this build does not know, preserved verbatim and signed
189    /// over. Empty (and so wire-absent) on everything this build writes.
190    ///
191    /// A key here must never collide with a known field name: the decoder only ever places the
192    /// keys it did not recognise here, and a caller building a core by hand must do the same.
193    #[serde(flatten)]
194    pub unknown: BTreeMap<String, Value>,
195}
196
197// `Value` holds floats, so it is only `PartialEq`. Every known field is `Eq`; the one exception
198// is a core whose unknown map holds a NaN, which compares unequal to itself. Equality is never
199// how a manifest is trusted (signatures over the canonical bytes are), so `Eq` stays.
200impl Eq for ManifestCore {}
201
202impl<'de> Deserialize<'de> for ManifestCore {
203    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
204        let mut m = cbor::OpenMap::deserialize("asset manifest core", d)?;
205        // Struct-literal fields evaluate in order, so `version` is decoded first.
206        Ok(Self {
207            version: m.take("version")?,
208            crypto_suite_id: m.take("crypto_suite_id")?,
209            protocol_version: m.take("protocol_version")?,
210            file_id: m.take("file_id")?,
211            album_id: m.take("album_id")?,
212            amk_version: m.take("amk_version")?,
213            ciphertext_hash: m.take("ciphertext_hash")?,
214            plaintext_size: m.take("plaintext_size")?,
215            chunk_size: m.take("chunk_size")?,
216            nonce_prefix: m.take("nonce_prefix")?,
217            key_mode: m.take_opt("key_mode")?.unwrap_or_default(),
218            wrapped_file_key: m.take_opt("wrapped_file_key")?,
219            metadata_blob_hash: m.take_opt("metadata_blob_hash")?,
220            created_by_user: m.take("created_by_user")?,
221            created_by_device: m.take("created_by_device")?,
222            client_version: m.take("client_version")?,
223            timestamp: m.take("timestamp")?,
224            action: m.take("action")?,
225            prior_provenance_hash: m.take_opt("prior_provenance_hash")?,
226            retention_until: m.take_opt("retention_until")?,
227            upgraded_from: m.take_opt("upgraded_from")?,
228            unknown: m.into_unknown(),
229        })
230    }
231}
232
233/// A signed asset manifest: a [`ManifestCore`] plus its two hybrid signatures.
234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
235pub struct AssetManifest {
236    /// The signed core.
237    pub core: ManifestCore,
238    /// Hybrid signature by the uploading device's DSK (provenance).
239    pub device_sig: HybridSignature,
240    /// Hybrid signature under the epoch write-tier key (authorization).
241    pub write_sig: HybridSignature,
242}
243
244impl ManifestCore {
245    /// The canonical bytes both signatures cover.
246    pub fn signing_bytes(&self) -> Vec<u8> {
247        cbor::to_canonical_vec(self).expect("manifest core serializes")
248    }
249
250    /// Sign this core with the device DSK and the epoch write-tier key. Fallible because the
251    /// device signer may be hardware-backed (the write-tier key is always software).
252    pub fn sign(
253        self,
254        device: &dyn Signer,
255        write_tier: &dyn Signer,
256    ) -> Result<AssetManifest, CryptoError> {
257        let bytes = self.signing_bytes();
258        let device_sig = device.sign(&bytes)?;
259        let write_sig = write_tier.sign(&bytes)?;
260        Ok(AssetManifest {
261            core: self,
262            device_sig,
263            write_sig,
264        })
265    }
266}
267
268impl AssetManifest {
269    /// The canonical bytes both signatures cover.
270    pub fn signing_bytes(&self) -> Vec<u8> {
271        self.core.signing_bytes()
272    }
273
274    /// Structural well-formedness independent of any key:
275    /// - `prior_provenance_hash` is null **iff** the action is `create`;
276    /// - `retention_until` is set only for `delete`;
277    /// - `wrapped_file_key` is present **iff** `key_mode = wrapped`;
278    /// - `metadata_blob_hash` is present **iff** the action binds a metadata blob
279    ///   ([`Action::binds_metadata_blob`] — `create | replace | metadata-update`).
280    ///
281    /// The first two are mirrored by the server envelope; the wrapped-key rule is the
282    /// signature-visible presence rule for an adopted web-upload drop, enforced here at
283    /// `verify_asset`. The `metadata_blob_hash` presence-by-action rule is enforced
284    /// because the `Workspace` populates the field per the [sealing order], so `verify_asset`
285    /// can require its presence exactly on the
286    /// metadata-bearing actions and its absence on the other four. The server mirrors the
287    /// *value* half key-free at [invariant 25]
288    /// ([`check_metadata_blob_envelope`](crate::validation::check_metadata_blob_envelope)).
289    ///
290    /// [sealing order]: https://docs/design/metadata/#provenance-binding-and-sealing-order
291    /// [invariant 25]: https://docs/design/threat-model/validation/#server-side-validation-invariants
292    pub fn structural_ok(&self) -> bool {
293        let core = &self.core;
294        let prior_rule = core.prior_provenance_hash.is_none() == core.action.is_create();
295        let retention_rule = core.retention_until.is_none() || core.action == Action::Delete;
296        let wrapped_rule = core.wrapped_file_key.is_some() == (core.key_mode == KeyMode::Wrapped);
297        let blob_hash_rule = core.metadata_blob_hash.is_some() == core.action.binds_metadata_blob();
298        prior_rule && retention_rule && wrapped_rule && blob_hash_rule
299    }
300}
301
302/// The signed core of a derivative manifest (thumbnail / preview / embedding).
303#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
304pub struct DerivativeCore {
305    /// Schema version string (`derivative-manifest/v1`).
306    pub version: String,
307    /// Primitive bundle.
308    pub crypto_suite_id: u16,
309    /// Date-based wire protocol version; matches the album pin. Wire-absent only on
310    /// pre-binding fixtures; REQUIRED on every real write.
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    pub protocol_version: Option<String>,
313    /// The AMK epoch whose write-tier key produced `write_sig` — the verifier needs it to
314    /// select the verification key. Wire-absent only on pre-binding fixtures; REQUIRED on
315    /// every real write (a derivative without it cannot be authorization-verified).
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub amk_version: Option<AmkVersion>,
318    /// The asset this derivative is generated from.
319    pub source_asset_id: Uuid,
320    /// Which kind of derivative.
321    pub role: DerivativeRole,
322    /// MIME/format string, e.g. `image/avif` or `embedding/mobileclip-b`.
323    ///
324    /// **A `String`, and deliberately so, even though the still formats are a closed set.**
325    /// Two reasons, and both are about keeping a *policy* rejection from becoming a *parse*
326    /// failure:
327    ///
328    /// - the same field carries the embedding-role grammar `embedding/{model_id}`
329    ///   (`crate::ml`), which no still-format enum can model, so a single typed field would
330    ///   have to be an enum over both grammars;
331    /// - a `#[serde(try_from = "String")]` newtype would make an *older* manifest naming a
332    ///   future codec fail at deserialisation — before its signature is examined at all —
333    ///   turning "this receiver does not recognise that format" into "this manifest is
334    ///   unreadable".
335    ///
336    /// The closed set is enforced at the two boundaries instead: production, because
337    /// `media::generate_still_derivatives` only ever writes
338    /// [`DerivativeFormat::mime`](crate::derivative_format::DerivativeFormat::mime); and
339    /// verification, via
340    /// [`verify_still_format`](crate::derivative_format::verify_still_format), which rejects a
341    /// still-role manifest whose value is outside the set and leaves the embedding-role grammar
342    /// alone.
343    ///
344    /// Both live in [`crate::derivative_format`], which is **unconditional** — deliberately not
345    /// behind the `media` feature. `capsule-server` and `capsule-wasm` build
346    /// `default-features = false`, and they are exactly the crates that receive a manifest they
347    /// did not author, so a check they could not link would be a closed set only its producer
348    /// could evaluate. SSoT: [Thumbnails](https://docs/design/thumbnails/).
349    pub format: String,
350    /// Content-address digest over the derivative ciphertext.
351    pub ciphertext_hash: Hash32,
352    /// The STREAM nonce prefix the derivative ciphertext was produced under; folded into the
353    /// file-key salt, so it also selects the key.
354    ///
355    /// **Required, not `Option`.** Derivative bytes are encrypted client-side exactly like the
356    /// original ([Encryption](https://docs/design/cryptography/encryption/)), so a receiver that
357    /// cannot recover this cannot decrypt the blob at all — an absent prefix would be an
358    /// unopenable derivative rather than a tolerable gap. It is safe to make it required
359    /// because no real `derivative-manifest/v1` has ever been written to any store: derivatives
360    /// were unconditionally `DeferredNoCodec` until the decoder landed, and `crate::ml`
361    /// constructs no derivative manifest. There is nothing to stay compatible with, so the
362    /// schema string does not move.
363    pub nonce_prefix: [u8; 7],
364    /// Device that generated the derivative.
365    pub generated_by_device: Uuid,
366    /// Generating client version.
367    pub generated_by_client: String,
368    /// Model id (embeddings only).
369    pub model_id: Option<String>,
370    /// Model version (embeddings only).
371    pub model_version: Option<String>,
372    /// RFC3339 generation time.
373    pub generated_at: String,
374    /// Chain link per `(source_asset_id, role)`; null for the first of that role.
375    pub prior_provenance_hash: Option<Hash32>,
376}
377
378/// A signed derivative manifest.
379#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
380pub struct DerivativeManifest {
381    /// The signed core.
382    pub core: DerivativeCore,
383    /// Hybrid device signature.
384    pub device_sig: HybridSignature,
385    /// Hybrid write-tier signature.
386    pub write_sig: HybridSignature,
387}
388
389impl DerivativeCore {
390    /// The canonical bytes both signatures cover.
391    pub fn signing_bytes(&self) -> Vec<u8> {
392        cbor::to_canonical_vec(self).expect("derivative core serializes")
393    }
394
395    /// Sign with the device DSK and epoch write-tier key. Fallible: the device signer may be
396    /// hardware-backed.
397    pub fn sign(
398        self,
399        device: &dyn Signer,
400        write_tier: &dyn Signer,
401    ) -> Result<DerivativeManifest, CryptoError> {
402        let bytes = self.signing_bytes();
403        Ok(DerivativeManifest {
404            device_sig: device.sign(&bytes)?,
405            write_sig: write_tier.sign(&bytes)?,
406            core: self,
407        })
408    }
409}
410
411impl DerivativeManifest {
412    /// The canonical bytes both signatures cover.
413    pub fn signing_bytes(&self) -> Vec<u8> {
414        self.core.signing_bytes()
415    }
416
417    /// The chain link the next manifest of this `(source_asset_id, role)` names as its
418    /// `prior_provenance_hash`: SHA-256 over this manifest's canonical CBOR, signatures
419    /// included — the same content-hash link the asset provenance chain uses, and the value
420    /// the producer (`media::derivative`) chains with.
421    pub fn link_hash(&self) -> Hash32 {
422        crate::crypto::hash::hash_bytes(
423            &cbor::to_canonical_vec(self).expect("derivative manifest serializes"),
424        )
425    }
426}
427
428#[cfg(test)]
429mod tests;