Skip to main content

capsule_core/crypto/
verify_derivative.rs

1//! The derivative-manifest arm of the acknowledgement chokepoint (SSoT: [Cryptography —
2//! Provenance § Derivative Provenance]).
3//!
4//! [`verify_derivative`] is the one path by which a client trusts a received
5//! [`DerivativeManifest`] — the manifest that names the epoch, the source asset and the nonce
6//! prefix a thumbnail or preview is decrypted with. "A derivative whose manifest fails
7//! verification is surfaced, never silently applied": it answers with the same three-way
8//! [`VerifyOutcome`] [`verify_asset`](crate::crypto::verify_asset::verify_asset) does, and holds a
9//! derivative to the same two signatures:
10//!
11//! - `device_sig` under the generating device's entry in the published directory, dispatched on
12//!   the entry's declared classical algorithm;
13//! - `write_sig` under the album's write-tier key for the epoch `amk_version` selects — through
14//!   the very helper `verify_asset` uses, so a derivative can never be authorized by a weaker
15//!   rule than an asset.
16//!
17//! Two bindings an asset manifest does not need are added: `source_asset_id` must name the asset
18//! the derivative is being opened for (a validly signed derivative of *another* asset is a
19//! transplant), and `prior_provenance_hash` must chain to the receiver's head for
20//! `(source_asset_id, role)` — the derivative-poisoning defense.
21//!
22//! [Cryptography — Provenance § Derivative Provenance]: https://docs/design/cryptography/provenance/#derivative-provenance
23
24use uuid::Uuid;
25
26use crate::crypto::authority::AlbumAuthority;
27use crate::crypto::hash::Hash32;
28use crate::crypto::keys::DeviceDirectory;
29use crate::crypto::primitives::SuiteId;
30use crate::crypto::provenance::{DERIVATIVE_MANIFEST_VERSION, DerivativeManifest};
31use crate::crypto::verify_asset::{
32    PendingReason, RejectReason, VerifyOutcome, authorize_write, rfc3339_le,
33};
34
35/// Verify a received derivative manifest for the asset `asset_id`.
36///
37/// - `directory` is the published directory of the account whose device generated the
38///   derivative; `generated_by_device` is resolved in it.
39/// - `role_head` is the [`link_hash`](DerivativeManifest::link_hash) of the manifest this
40///   receiver already trusts as the head of `(asset_id, role)`, or `None` when it trusts none
41///   yet. A manifest whose `prior_provenance_hash` is `None` starts the role's chain and is only
42///   placed when there is no head; any other must name the head exactly.
43///
44/// The derivative's ciphertext is not an argument: its content address is checked where the
45/// bytes arrive (the blob fetch recomputes it against the address the manifest names), and a
46/// manifest is verified before any byte is fetched.
47///
48/// Steps, in order — the first that fails decides the [`RejectReason`]:
49///
50/// 1. the authority's admin chain verifies ([`RejectReason::UntrustedAuthority`]);
51/// 2. `version` is `derivative-manifest/v1`, and the two fields that are wire-optional only on
52///    pre-binding fixtures — `amk_version` and `protocol_version` — are present
53///    ([`RejectReason::Structural`]): without `amk_version` there is no key to check `write_sig`
54///    under;
55/// 3. `crypto_suite_id` is implemented by this build ([`RejectReason::SuiteDowngrade`]);
56/// 4. `source_asset_id` is `asset_id` ([`RejectReason::WrongAsset`]);
57/// 5. `generated_by_device` is in `directory` ([`RejectReason::UnknownDevice`]) and was added no
58///    later than `generated_at` ([`RejectReason::DeviceAddedAfter`] /
59///    [`RejectReason::BadTimestamp`]);
60/// 6. `device_sig` verifies under that entry's key and declared algorithm
61///    ([`RejectReason::BadDeviceSig`]);
62/// 7. the epoch is within the attested ceiling and `write_sig` verifies under its write-tier key
63///    ([`RejectReason::WrongEpoch`] / [`RejectReason::BadWriteSig`]);
64/// 8. chain placement against `role_head` ([`RejectReason::Replayed`] for a chain start when a
65///    head exists, [`RejectReason::ForgedChain`] for any other mismatch);
66/// 9. accept iff the epoch's AMK is held locally, else
67///    [`VerifyOutcome::Pending`]`(`[`PendingReason::AmkNotYetLocal`]`)`.
68#[tracing::instrument(
69    level = "debug",
70    skip_all,
71    fields(%asset_id, role = ?manifest.core.role, device = %manifest.core.generated_by_device)
72)]
73pub fn verify_derivative(
74    manifest: &DerivativeManifest,
75    asset_id: Uuid,
76    directory: &DeviceDirectory,
77    authority: &dyn AlbumAuthority,
78    role_head: Option<Hash32>,
79) -> VerifyOutcome {
80    let outcome = verify_steps(manifest, asset_id, directory, authority, role_head);
81    match outcome {
82        VerifyOutcome::Accept => tracing::trace!("derivative manifest accepted"),
83        VerifyOutcome::Pending(reason) => tracing::debug!(?reason, "derivative manifest pending"),
84        VerifyOutcome::TerminalReject(reason) => {
85            tracing::debug!(?reason, "derivative manifest rejected");
86        }
87    }
88    outcome
89}
90
91fn verify_steps(
92    manifest: &DerivativeManifest,
93    asset_id: Uuid,
94    directory: &DeviceDirectory,
95    authority: &dyn AlbumAuthority,
96    role_head: Option<Hash32>,
97) -> VerifyOutcome {
98    use RejectReason::{
99        BadDeviceSig, BadTimestamp, DeviceAddedAfter, ForgedChain, Replayed, Structural,
100        SuiteDowngrade, UnknownDevice, UntrustedAuthority, WrongAsset,
101    };
102    use VerifyOutcome::TerminalReject as Reject;
103    let core = &manifest.core;
104
105    // 1. Never trust an unsigned ledger.
106    if !authority.admin_chain_verifies() {
107        return Reject(UntrustedAuthority);
108    }
109    // 2. Schema, and the two fields every real write carries.
110    let Some(amk_version) = core.amk_version else {
111        return Reject(Structural);
112    };
113    if core.version != DERIVATIVE_MANIFEST_VERSION || core.protocol_version.is_none() {
114        return Reject(Structural);
115    }
116    // 3. Fail closed on a suite this build does not implement.
117    if SuiteId::from_u16(core.crypto_suite_id).is_none() {
118        return Reject(SuiteDowngrade);
119    }
120    // 4. A derivative of another asset is a transplant, however well it is signed.
121    if core.source_asset_id != asset_id {
122        return Reject(WrongAsset);
123    }
124    // 5. The generating device is published, and was published before it generated this.
125    let Some(entry) = directory.device(&core.generated_by_device) else {
126        return Reject(UnknownDevice);
127    };
128    match rfc3339_le(&entry.added_at, &core.generated_at) {
129        None => return Reject(BadTimestamp),
130        Some(false) => return Reject(DeviceAddedAfter),
131        Some(true) => {}
132    }
133    // 6. Provenance: the device signature, under the entry's declared classical algorithm.
134    let signing_bytes = manifest.signing_bytes();
135    if manifest.device_sig.classical_algorithm() != entry.dsk_public.classical_algorithm()
136        || !entry
137            .dsk_public
138            .verify(&signing_bytes, &manifest.device_sig)
139    {
140        return Reject(BadDeviceSig);
141    }
142    // 7. Authorization: the epoch write-tier signature, by the rule assets are held to.
143    if let Some(reason) =
144        authorize_write(amk_version, &signing_bytes, &manifest.write_sig, authority)
145    {
146        return Reject(reason);
147    }
148    // 8. Chain placement per (asset, role): the derivative-poisoning defense.
149    match (core.prior_provenance_hash, role_head) {
150        (None, None) => {}
151        (None, Some(_)) => return Reject(Replayed),
152        (Some(prior), Some(head)) if prior == head => {}
153        (Some(_), _) => return Reject(ForgedChain),
154    }
155    // 9. Everything authorizes; accept iff the epoch's AMK is here.
156    if authority.has_amk(amk_version) {
157        VerifyOutcome::Accept
158    } else {
159        VerifyOutcome::Pending(PendingReason::AmkNotYetLocal)
160    }
161}
162
163#[cfg(test)]
164mod tests;