Skip to main content

capsule_core/crypto/
verify_asset.rs

1//! The single asset-acknowledgement chokepoint (SSoT: [Keys — Write Authorization]).
2//!
3//! `verify_asset` is the **only** path by which a client accepts an asset into its trusted
4//! set. It returns one of three outcomes — never a silent drop, never a silent accept:
5//!
6//! - [`VerifyOutcome::Accept`] — both signatures valid, epoch within the MLS-attested
7//!   ceiling, chain head matches, AMK locally held.
8//! - [`VerifyOutcome::TerminalReject`] — reader-signed / removed-writer / wrong-epoch /
9//!   forged-chain / replayed / suite-downgrade / bad device sig … → quarantine.
10//! - [`VerifyOutcome::Pending`] — epoch is within the attested range but its AMK content
11//!   key has not arrived yet → hold and retry, never quarantine.
12//!
13//! Authorization authority is the album's admin-signed MLS commit chain (the
14//! [`AlbumAuthority`]), never the server. It ships with an exhaustive negative-case test
15//! surface, since every negative is a real damage scenario.
16//!
17//! [Keys — Write Authorization]: https://docs/design/cryptography/keys/#write-authorization
18
19use uuid::Uuid;
20
21use crate::crypto::authority::AlbumAuthority;
22use crate::crypto::encryption::{blob_ciphertext_hash, open_blob};
23use crate::crypto::hash::{self, Hash32};
24use crate::crypto::keys::{AmkVersion, DeviceDirectory, HybridSignature};
25use crate::crypto::primitives::SuiteId;
26use crate::crypto::provenance::AssetManifest;
27
28/// Why a manifest was terminally rejected. Each maps to a damage scenario.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum RejectReason {
31    /// The album authority's admin chain does not verify — untrusted state.
32    UntrustedAuthority,
33    /// The manifest names a different album than this authority speaks for.
34    WrongAlbum,
35    /// `crypto_suite_id` is not in the current inventory (downgrade / unknown).
36    SuiteDowngrade,
37    /// Structural rule violated (e.g. non-create with null prior; retention off a delete).
38    Structural,
39    /// Recomputed ciphertext hash does not match the manifest's declared hash.
40    CiphertextHashMismatch,
41    /// The signing device is not in the user's published directory.
42    UnknownDevice,
43    /// The device's `added_at` postdates the manifest timestamp (key older than itself).
44    DeviceAddedAfter,
45    /// A timestamp field was not valid RFC3339.
46    BadTimestamp,
47    /// The device signature (`device_sig`) did not verify.
48    BadDeviceSig,
49    /// `amk_version` exceeds the MLS-attested epoch ceiling (fabricated future epoch).
50    WrongEpoch,
51    /// The write-tier signature did not verify for the claimed epoch (reader-signed,
52    /// removed-writer, or wrong-epoch signature).
53    BadWriteSig,
54    /// `prior_provenance_hash` does not match the local chain head (stale / forked / replay).
55    ForgedChain,
56    /// A `create` for an asset that already exists locally (replay).
57    Replayed,
58    /// A derivative manifest names a `source_asset_id` other than the asset it is being
59    /// opened for — a derivative transplanted from another asset
60    /// ([`verify_derivative`](crate::crypto::verify_derivative::verify_derivative)).
61    WrongAsset,
62}
63
64/// Why a manifest is pending rather than accepted.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum PendingReason {
67    /// The epoch is attested but its AMK content key has not arrived locally yet.
68    AmkNotYetLocal,
69}
70
71/// The outcome of [`verify_asset`].
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum VerifyOutcome {
74    /// Acknowledge the asset.
75    Accept,
76    /// Reject and quarantine, with a structured reason.
77    TerminalReject(RejectReason),
78    /// Hold and retry as MLS state catches up.
79    Pending(PendingReason),
80}
81
82impl VerifyOutcome {
83    /// Convenience: did verification accept?
84    pub fn is_accept(self) -> bool {
85        matches!(self, VerifyOutcome::Accept)
86    }
87}
88
89/// `a <= b` over two RFC 3339 timestamps; `None` when either does not parse.
90pub(super) fn rfc3339_le(a: &str, b: &str) -> Option<bool> {
91    let pa = a.parse::<jiff::Timestamp>().ok()?;
92    let pb = b.parse::<jiff::Timestamp>().ok()?;
93    Some(pa <= pb)
94}
95
96/// Verify a manifest against the device directory, the album's MLS-attested authority, and
97/// the local provenance chain head. The one path by which an asset is acknowledged.
98///
99/// - `ciphertext` is the asset's ciphertext, used to confirm the content hash (integrity);
100///   it need not be decryptable here.
101/// - `local_chain_head` is the hash of the current head provenance record for this asset,
102///   or `None` if the asset is unknown locally.
103pub fn verify_asset(
104    manifest: &AssetManifest,
105    ciphertext: &[u8],
106    directory: &DeviceDirectory,
107    authority: &dyn AlbumAuthority,
108    local_chain_head: Option<Hash32>,
109) -> VerifyOutcome {
110    verify_asset_hashed(
111        manifest,
112        &hash::hash_bytes(ciphertext),
113        directory,
114        authority,
115        local_chain_head,
116    )
117}
118
119/// [`verify_asset`] over the ciphertext's SHA-256 rather than its bytes, for a caller that
120/// streams a ciphertext too large to hold. Step 5 compares `ciphertext_hash` with the manifest's
121/// content address, so it vouches for the bytes only as far as the caller's digest does: a
122/// caller that has not hashed them yet must hash what it then reads and refuse it unless the
123/// result equals this argument. Every other step is [`verify_asset`]'s, unchanged.
124pub fn verify_asset_hashed(
125    manifest: &AssetManifest,
126    ciphertext_hash: &Hash32,
127    directory: &DeviceDirectory,
128    authority: &dyn AlbumAuthority,
129    local_chain_head: Option<Hash32>,
130) -> VerifyOutcome {
131    use RejectReason::{
132        CiphertextHashMismatch, Structural, SuiteDowngrade, UntrustedAuthority, WrongAlbum,
133    };
134    use VerifyOutcome::TerminalReject as Reject;
135    let core = &manifest.core;
136
137    // 1. The authority's own admin chain must verify — never trust an unsigned ledger.
138    if !authority.admin_chain_verifies() {
139        return Reject(UntrustedAuthority);
140    }
141    // 2. The manifest must be for the album this authority speaks for.
142    if core.album_id != authority.album_id() {
143        return Reject(WrongAlbum);
144    }
145    // 3. The crypto suite must be one this build implements (fail-closed).
146    if SuiteId::from_u16(core.crypto_suite_id).is_none() {
147        return Reject(SuiteDowngrade);
148    }
149    // 4. Structural rules (prior-hash/create coupling; retention only on delete).
150    if !manifest.structural_ok() {
151        return Reject(Structural);
152    }
153    // 5. Content integrity: the ciphertext must hash to the declared content address.
154    if *ciphertext_hash != core.ciphertext_hash {
155        return Reject(CiphertextHashMismatch);
156    }
157    // 6–8. The signing device is in this user's directory, was added before it signed, and its
158    //      key produced `device_sig`.
159    if let Err(reason) = verify_device_signature(manifest, directory) {
160        return Reject(reason);
161    }
162    let signing_bytes = manifest.signing_bytes();
163    // 9–11. Epoch ceiling, write-tier signature, chain placement.
164    if let Some(reason) = authorize_and_place(manifest, &signing_bytes, authority, local_chain_head)
165    {
166        return Reject(reason);
167    }
168    // 12. Everything authorizes; accept iff the AMK is locally held, else hold as pending.
169    if authority.has_amk(core.amk_version) {
170        VerifyOutcome::Accept
171    } else {
172        VerifyOutcome::Pending(PendingReason::AmkNotYetLocal)
173    }
174}
175
176/// Steps 6–8 of [`verify_asset`]: the manifest's signer is a device of `directory`, added no
177/// later than the manifest's timestamp, and its signing key produced `device_sig`.
178///
179/// Public because the server's index rebuild checks exactly this against the directory version
180/// its owner ledger recorded, and a second implementation of the device check would be a second
181/// answer to a question the threat model allows one answer to. Revocation is not judged here: a
182/// device a later directory revoked still verifies the manifests it signed before, and whether a
183/// revoked entry may sign at all is the caller's rule.
184///
185/// # Errors
186///
187/// [`RejectReason::UnknownDevice`] when `directory` is another user's or does not list the
188/// device, [`RejectReason::BadTimestamp`] or [`RejectReason::DeviceAddedAfter`] for step 7, and
189/// [`RejectReason::BadDeviceSig`] when the signature does not verify under the entry's key.
190pub fn verify_device_signature(
191    manifest: &AssetManifest,
192    directory: &DeviceDirectory,
193) -> Result<(), RejectReason> {
194    let core = &manifest.core;
195    // 6. The signing device must be in this user's published directory.
196    if directory.core.user_id != core.created_by_user {
197        return Err(RejectReason::UnknownDevice);
198    }
199    let Some(entry) = directory.device(&core.created_by_device) else {
200        return Err(RejectReason::UnknownDevice);
201    };
202    // 7. The device cannot have been added after it claims to have signed.
203    match rfc3339_le(&entry.added_at, &core.timestamp) {
204        None => return Err(RejectReason::BadTimestamp),
205        Some(false) => return Err(RejectReason::DeviceAddedAfter),
206        Some(true) => {}
207    }
208    // 8. The device signature must verify under the entry's **declared classical algorithm**.
209    //    The directory entry's `dsk_public` is algorithm-tagged — Ed25519 (software) or
210    //    ECDSA-P256 (hardware secure elements) — so verification dispatches on that tag. A
211    //    signature whose classical half is a *different* algorithm than the entry declares is a
212    //    cross-algorithm forgery and is rejected before the (algorithm-specific) verify.
213    if manifest.device_sig.classical_algorithm() != entry.dsk_public.classical_algorithm() {
214        return Err(RejectReason::BadDeviceSig);
215    }
216    if !entry
217        .dsk_public
218        .verify(&manifest.signing_bytes(), &manifest.device_sig)
219    {
220        return Err(RejectReason::BadDeviceSig);
221    }
222    Ok(())
223}
224
225/// Steps 9–11 of [`verify_asset`]: epoch ceiling, write-tier signature, chain placement.
226/// `None` when all three hold. Shared with [`diagnose_misattributed_signer`] so the diagnosis
227/// can never hold a record to a weaker standard than the chokepoint does.
228fn authorize_and_place(
229    manifest: &AssetManifest,
230    signing_bytes: &[u8],
231    authority: &dyn AlbumAuthority,
232    local_chain_head: Option<Hash32>,
233) -> Option<RejectReason> {
234    let core = &manifest.core;
235    // 9–10. Epoch ceiling and write-tier signature.
236    if let Some(reason) = authorize_write(
237        core.amk_version,
238        signing_bytes,
239        &manifest.write_sig,
240        authority,
241    ) {
242        return Some(reason);
243    }
244    // 11. Chain placement: a create must be new; a non-create must chain to the local head.
245    if core.action.is_create() {
246        if local_chain_head.is_some() {
247            return Some(RejectReason::Replayed);
248        }
249    } else if core.prior_provenance_hash.is_none() || core.prior_provenance_hash != local_chain_head
250    {
251        return Some(RejectReason::ForgedChain);
252    }
253    None
254}
255
256/// Steps 9–10 of [`verify_asset`], shared with
257/// [`verify_derivative`](crate::crypto::verify_derivative::verify_derivative) so a derivative
258/// is authorized by exactly the rule an asset is: the epoch must be within the MLS-attested
259/// ceiling (no fabricated future epoch), and `write_sig` must verify — both hybrid halves —
260/// under that epoch's attested write-tier key. Reader-signed and removed-writer records both
261/// fail the second check. `None` when both hold.
262pub(super) fn authorize_write(
263    amk_version: AmkVersion,
264    signing_bytes: &[u8],
265    write_sig: &HybridSignature,
266    authority: &dyn AlbumAuthority,
267) -> Option<RejectReason> {
268    if amk_version > authority.epoch_ceiling() {
269        return Some(RejectReason::WrongEpoch);
270    }
271    let Some(write_pub) = authority.write_tier_pubkey(amk_version) else {
272        return Some(RejectReason::WrongEpoch);
273    };
274    if !write_pub.verify(signing_bytes, write_sig) {
275        return Some(RejectReason::BadWriteSig);
276    }
277    None
278}
279
280/// Diagnose a [`RejectReason::BadDeviceSig`] as the **legacy inherited-device defect** (issue
281/// #475) rather than a forgery, returning the directory device that actually signed the record.
282///
283/// Before the fix, `sign_lifecycle` built every continuation (`delete`, `trash-restore`,
284/// `metadata-update`) with `created_by_user`/`created_by_device` copied from the chain head while
285/// signing with the *current* device. A record written that way from a second device of the same
286/// account names a real directory device that did not sign it, so [`verify_asset`] step 8 rejects
287/// it — the same verdict a forged signature earns. This function separates the two, and returns
288/// `Some(signer)` only when **every** fact below holds:
289///
290/// 1. [`verify_asset`] itself returns `TerminalReject(BadDeviceSig)` — this never reclassifies
291///    any other verdict, and never turns a rejection into an acceptance;
292/// 2. the record is a continuation (not a `create`): the create paths always named their signer;
293/// 3. `device_sig` verifies under a **different** device of the same published directory, under
294///    that entry's declared classical algorithm, and that device was added no later than the
295///    record's timestamp (steps 7–8 hold for the true signer);
296/// 4. steps 9–11 hold unchanged: the epoch is attested, `write_sig` verifies under its write-tier
297///    key, and the record chains to `local_chain_head`.
298///
299/// So `Some` means "this record would have been accepted had it named its own signer" — a
300/// signature by a device the account's IK vouches for, carrying album write authority, in the
301/// right chain position. A forger holding none of this account's device keys cannot produce it.
302///
303/// The record is **still refused**: `created_by_device` is covered by both signatures, so the
304/// misattribution cannot be corrected without re-signing history, and accepting the record would
305/// teach the chokepoint to trust a field it cannot verify. The caller quarantines it with the
306/// distinct signal this function enables; see [provenance.md § Legacy Inherited-Device Records].
307///
308/// [provenance.md § Legacy Inherited-Device Records]: https://docs/design/cryptography/provenance/#legacy-inherited-device-records
309pub fn diagnose_misattributed_signer(
310    manifest: &AssetManifest,
311    ciphertext_hash: &Hash32,
312    directory: &DeviceDirectory,
313    authority: &dyn AlbumAuthority,
314    local_chain_head: Option<Hash32>,
315) -> Option<Uuid> {
316    let core = &manifest.core;
317    if verify_asset_hashed(
318        manifest,
319        ciphertext_hash,
320        directory,
321        authority,
322        local_chain_head,
323    ) != VerifyOutcome::TerminalReject(RejectReason::BadDeviceSig)
324    {
325        return None;
326    }
327    if core.action.is_create() {
328        return None;
329    }
330    let signing_bytes = manifest.signing_bytes();
331    let signer = directory.core.devices.iter().find(|entry| {
332        entry.device_id != core.created_by_device
333            && rfc3339_le(&entry.added_at, &core.timestamp) == Some(true)
334            && manifest.device_sig.classical_algorithm() == entry.dsk_public.classical_algorithm()
335            && entry
336                .dsk_public
337                .verify(&signing_bytes, &manifest.device_sig)
338    })?;
339    if authorize_and_place(manifest, &signing_bytes, authority, local_chain_head).is_some() {
340        return None;
341    }
342    tracing::debug!(
343        asset_id = %core.file_id,
344        named_device = %core.created_by_device,
345        signing_device = %signer.device_id,
346        "verify_asset: BadDeviceSig diagnosed as a legacy inherited-device record"
347    );
348    Some(signer.device_id)
349}
350
351/// Why a metadata blob fails to bind to its manifest and the locally-signed sidecar.
352#[derive(Debug, Clone, Copy, PartialEq, Eq)]
353pub enum BindingReject {
354    /// The manifest commits to no `metadata_blob_hash` — a metadata-bearing action must
355    /// (`create | replace | metadata-update`); a caller should not seek a binding otherwise.
356    NoManifestCommitment,
357    /// The blob's content hash does not equal the manifest's committed `metadata_blob_hash`.
358    /// This is the key-free half — the same comparison the server runs as [invariant 25].
359    ///
360    /// [invariant 25]: crate::validation::check_metadata_blob_envelope
361    BlobHashMismatch,
362    /// The blob did not decrypt/authenticate under the derived blob key (tampered ciphertext,
363    /// wrong key, or a truncated wire).
364    Undecryptable,
365    /// The blob decrypted, but its plaintext is not byte-identical to the locally-signed
366    /// sidecar — the client would be persisting one sidecar while its manifest commits to a
367    /// different one.
368    SidecarMismatch,
369}
370
371/// The outcome of the metadata↔manifest round-trip binding check (client-side; SSoT:
372/// [Metadata — Local and Server Metadata Equivalence]).
373///
374/// This is a **distinct class** from a [`verify_asset`] terminal-reject: a manifest's two
375/// signatures can be perfectly valid while the metadata blob a client was handed diverges from
376/// what the manifest commits to. Per the [client-side invariant] a divergence is
377/// **quarantined** — surfaced, never silently persisted — exactly like the pending→timeout and
378/// terminal-reject cases funnel into quarantine, but reached from a different check.
379///
380/// [Metadata — Local and Server Metadata Equivalence]: https://docs/design/metadata/#local-and-server-metadata-equivalence
381/// [client-side invariant]: https://docs/design/threat-model/validation/#client-side-validation-invariants
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
383pub enum MetadataBinding {
384    /// The blob decrypts to the byte-identical signed sidecar and hashes to the manifest field.
385    Bound,
386    /// The blob diverges from the manifest or the signed sidecar — quarantine, never persist.
387    Quarantine(BindingReject),
388}
389
390impl MetadataBinding {
391    /// Convenience: did the metadata blob bind?
392    pub fn is_bound(self) -> bool {
393        matches!(self, MetadataBinding::Bound)
394    }
395}
396
397/// Run the metadata↔manifest round-trip equivalence check for a metadata-bearing manifest
398/// (SSoT: [Metadata — Local and Server Metadata Equivalence], [Encryption — Local–server
399/// equivalence]). Two facts must hold, both funnelling a failure into a
400/// [quarantine](MetadataBinding::Quarantine):
401///
402/// 1. **Content address** — the metadata blob's content hash equals the manifest's committed
403///    `metadata_blob_hash` (the key-free half; the server enforces the same value at
404///    [invariant 25](crate::validation::check_metadata_blob_envelope)).
405/// 2. **Round-trip** — decrypting the blob under `blob_key` yields canonical CBOR
406///    byte-identical to `signed_sidecar` (the sidecar the client persists locally).
407///
408/// A client therefore never persists a sidecar that does not round-trip to the committed
409/// `metadata_blob_hash`.
410///
411/// [Metadata — Local and Server Metadata Equivalence]: https://docs/design/metadata/#local-and-server-metadata-equivalence
412/// [Encryption — Local–server equivalence]: https://docs/design/cryptography/encryption/#metadata-encryption
413pub fn verify_metadata_binding(
414    manifest: &AssetManifest,
415    metadata_blob: &[u8],
416    blob_key: &[u8; 32],
417    signed_sidecar: &[u8],
418) -> MetadataBinding {
419    use MetadataBinding::Quarantine;
420
421    let Some(committed) = manifest.core.metadata_blob_hash else {
422        return Quarantine(BindingReject::NoManifestCommitment);
423    };
424    // (1) Key-free content address: the ciphertext blob hashes to the committed value.
425    if blob_ciphertext_hash(metadata_blob) != committed {
426        return Quarantine(BindingReject::BlobHashMismatch);
427    }
428    // (2) Round-trip: the blob decrypts to the byte-identical signed sidecar.
429    match open_blob(blob_key, metadata_blob) {
430        Err(_) => Quarantine(BindingReject::Undecryptable),
431        Ok(plaintext) if plaintext != signed_sidecar => Quarantine(BindingReject::SidecarMismatch),
432        Ok(_) => MetadataBinding::Bound,
433    }
434}
435
436#[cfg(test)]
437mod tests;