Skip to main content

hyprstream_crypto/
cose_sign.rs

1//! Nested-COSE hybrid composite signing for the hyprstream `SignedEnvelope`
2//! (EdDSA + ML-DSA-65).
3//!
4//! ## Where this sits in the PQUIP hybrid-signature taxonomy
5//!
6//! In the taxonomy of `draft-ietf-pquip-hybrid-signature-spectrums` §1.3.4 this
7//! construction is still **Weak Non-Separable (WNS)**, *not* Strong Non-Separable
8//! (SNS). SNS requires *fusion* — the two algorithms' signatures combined into a
9//! single object that cannot be verified by either component alone. We do not do
10//! that: we emit two distinct COSE_Sign1 signatures and bind them by nesting
11//! (the outer signs `payload ‖ inner_sig`).
12//!
13//! As of #278 the inner EdDSA layer additionally binds a hybrid-composite alg-id
14//! into its signed input when produced in Hybrid mode (see
15//! [`HYBRID_COMPOSITE_ALG_ID`] / [`build_hybrid_external_aad`]). This delivers
16//! *signature-level* non-separability for the inner component: an inner EdDSA
17//! signature lifted out of a Hybrid composite (its outer ML-DSA layer stripped)
18//! is NO LONGER a valid standalone Classical signature, because its `Sig_structure`
19//! was bound to the hybrid-alg-id that a Classical verifier does not reconstruct.
20//! A genuine *Classical*-mode inner (no hybrid-alg-id) still verifies under a
21//! Classical verifier — that intended interop is preserved. We keep the WNS label
22//! because the two signatures remain separable *objects* (no fusion) and a
23//! standalone outer ML-DSA layer is still independently meaningful; #278 closes
24//! the inner-component separability gap, not the structural one.
25//!
26//! **Downgrade resistance is now enforced by BOTH crypto and policy:**
27//!   1. signature-level non-separability (#278): a stripped-inner attack fails the
28//!      inner EdDSA *signature* check (AAD mismatch), not merely a policy gate.
29//!   2. `require_pq` (fail-closed Hybrid policy): a Hybrid verifier rejects any
30//!      envelope lacking a valid outer ML-DSA-65 layer, so an attacker who strips
31//!      the outer layer is *also* rejected by policy.
32//!   3. kid-anchoring: the PQ key is resolved from a [`PqTrustStore`] keyed by
33//!      the EdDSA signer identity, never self-asserted in the COSE object —
34//!      closing the self-certification gap a naïve two-signature scheme has.
35//!
36//! ## What the nesting *does* buy
37//!
38//! M3 (#152) replaced an earlier `COSE_Sign` with two *independent* signatures
39//! over the same payload (a fail-open, trivially strippable scheme). The nesting
40//! below is a real improvement over that: because the outer ML-DSA-65 signature
41//! covers `payload ‖ inner_eddsa_signature`, the inner signature is part of the
42//! outer's signed message — so once a verifier has *committed to checking the
43//! outer* (Hybrid policy), it cannot be fed a mismatched inner/outer pair. The
44//! nesting binds the two layers together; the *requirement* to check the outer
45//! at all comes from policy.
46//!
47//! ```text
48//! Classical:                                          external_aad
49//!   inner  = EdDSA  COSE_Sign1 over  payload          base_aad
50//!
51//! Hybrid (#278 hybrid-alg-id bound; policy-enforced): external_aad
52//!   inner  = EdDSA  COSE_Sign1 over  payload          [base_aad, hybridAlgID]
53//!   outer  = ML-DSA COSE_Sign1 over  payload‖inner_sig [base_aad, hybridAlgID]
54//! ```
55//!
56//! Both layers bind the base `external_aad` (the CBOR `[envelope_schema_id,
57//! inner_type_id]` schema binding, see [`crate::cose_sign1::build_external_aad`]),
58//! and — in **Hybrid** mode only — *additionally* bind a hybrid-composite
59//! algorithm identifier (see [`HYBRID_COMPOSITE_ALG_ID`]) into both layers'
60//! `external_aad` via [`build_hybrid_external_aad`].
61//!
62//! ## Signature-level non-separability of the inner EdDSA (#278)
63//!
64//! Per `draft-ietf-pquip-hybrid-signature-spectrums` (§ Nested Construction /
65//! Non-Separability), signature-level non-separability requires binding a
66//! `hybridAlgID` into each component's signed input: `sig = Sign(hybridAlgID ‖ m)`.
67//! We achieve this by extending the COSE `external_aad` (which RFC 9052 §4.4
68//! folds into every layer's `Sig_structure`) with the composite alg-id whenever
69//! signing in Hybrid mode.
70//!
71//! Consequence: the inner EdDSA `COSE_Sign1` to-be-signed bytes produced in
72//! Hybrid mode are now **byte-distinct** from those produced in Classical mode,
73//! so a stripped inner EdDSA signature lifted out of a Hybrid composite is *not*
74//! a valid standalone Classical signature — it fails verification at the
75//! *signature* level (not merely the `require_pq` policy check). In **Classical**
76//! mode the `external_aad` is left exactly as before (no hybrid-alg-id), so
77//! classical-only signing/verification is byte-for-byte unchanged.
78//!
79//! ## Backwards-compatibility / transition window
80//!
81//! This changes *what is signed* under Hybrid mode: a Hybrid signer at this
82//! revision binds the hybrid-alg-id, so its inner EdDSA layer will NOT verify
83//! against a pre-#278 Classical verifier that reconstructs the bare base AAD,
84//! and vice-versa. Per WNS the classical `sig`/`cnf` fields on the envelope are
85//! retained for the raw-EdDSA advertisement / JWT-cnf paths and are unaffected.
86//! During a mixed-version deployment, peers MUST agree on the same policy
87//! (Classical↔Classical or Hybrid↔Hybrid); a Hybrid producer talking to a
88//! Classical-only consumer was already rejected by the `require_pq` policy, so
89//! no *new* interop surface is broken — only the Hybrid inner AAD changed.
90//!
91//! # Wire shape (`SignedEnvelope.cose`)
92//!
93//! A definite-length CBOR array of two entries:
94//!
95//! ```text
96//! [ inner_cose_sign1_bytes : bstr,
97//!   outer_cose_sign1_bytes : bstr / null ]   ; null in Classical mode
98//! ```
99//!
100//! The signed payloads are *detached* (never embedded). Each COSE_Sign1 carries
101//! its signer's `kid` + `alg` in its protected header.
102
103use anyhow::{anyhow, bail, Context, Result};
104use ciborium::value::Value as CborValue;
105use coset::{
106    iana::{self, EnumI64},
107    CborSerializable, CoseSign1, CoseSign1Builder, HeaderBuilder,
108};
109
110use crate::pq::{ml_dsa_sign, ml_dsa_verify, MlDsaSigningKey, MlDsaVerifyingKey};
111
112/// IANA COSE algorithm id for ML-DSA-65 (FIPS 204, draft-ietf-cose-dilithium).
113pub const ALG_ML_DSA_65: i64 = iana::Algorithm::ML_DSA_65 as i64;
114
115/// Stable composite/hybrid algorithm identifier for the EdDSA + ML-DSA-65
116/// component pair signed by this nested construction.
117///
118/// Bound into the COSE `external_aad` of BOTH layers in Hybrid mode so that the
119/// inner EdDSA `Sig_structure` becomes byte-distinct from a Classical-mode one
120/// (signature-level non-separability, see this module's docs and #278).
121///
122/// Value: the ASCII bytes of the registered composite-signature name
123/// `id-MLDSA65-Ed25519` from `draft-ietf-lamps-pq-composite-sigs` (the LAMPS
124/// composite that pairs ML-DSA-65 with Ed25519). We bind a deterministic,
125/// human-auditable label rather than an integer OID-arc to keep the AAD
126/// self-describing on the wire and avoid depending on a not-yet-final IANA COSE
127/// code-point allocation. It is a fixed constant: changing it is a wire-breaking
128/// change that both signer and verifier must adopt together.
129pub const HYBRID_COMPOSITE_ALG_ID: &[u8] = b"id-MLDSA65-Ed25519";
130
131/// Extend a base `external_aad` with the [`HYBRID_COMPOSITE_ALG_ID`] binding.
132///
133/// Produces the deterministic CBOR encoding of the 2-element array
134/// `[base_aad : bstr, HYBRID_COMPOSITE_ALG_ID : bstr]`. Wrapping the (already
135/// CBOR) base AAD as a byte string inside a fresh 2-bstr array is unambiguous:
136/// the Classical AAD is the bare base bytes (a CBOR `[int,int]` array, major
137/// type 4), whereas the Hybrid AAD is a CBOR `[bstr,bstr]` array (also major
138/// type 4 but with bstr elements), so the two TBS inputs can never collide.
139///
140/// Used ONLY in Hybrid mode; Classical mode signs/verifies against the bare
141/// `base_aad` so classical-only behaviour is byte-for-byte unchanged.
142pub fn build_hybrid_external_aad(base_aad: &[u8]) -> Vec<u8> {
143    let value = CborValue::Array(vec![
144        CborValue::Bytes(base_aad.to_vec()),
145        CborValue::Bytes(HYBRID_COMPOSITE_ALG_ID.to_vec()),
146    ]);
147    let mut buf = Vec::with_capacity(base_aad.len() + HYBRID_COMPOSITE_ALG_ID.len() + 8);
148    // Infallible for this fixed [bstr,bstr] shape into an unbounded Vec. Fail
149    // LOUD rather than silently degrading the hybrid-alg-id binding to an empty
150    // (classical-equivalent) AAD on BOTH sign and verify — a silent empty return
151    // would erode the #278 non-separability property invisibly (review finding).
152    #[allow(clippy::expect_used)]
153    ciborium::ser::into_writer(&value, &mut buf)
154        .expect("CBOR serialization of the hybrid external_aad is infallible");
155    buf
156}
157
158/// Select the `external_aad` to bind into each layer for the given mode.
159///
160/// - `hybrid = true`  → bind the hybrid-composite alg-id ([`build_hybrid_external_aad`]).
161/// - `hybrid = false` → bare `base_aad` (Classical; unchanged).
162fn layer_aad(base_aad: &[u8], hybrid: bool) -> Vec<u8> {
163    if hybrid {
164        build_hybrid_external_aad(base_aad)
165    } else {
166        base_aad.to_vec()
167    }
168}
169
170/// EdDSA kid convention: raw 32-byte Ed25519 verifying key.
171fn eddsa_kid(vk: &ed25519_dalek::VerifyingKey) -> Vec<u8> {
172    vk.to_bytes().to_vec()
173}
174
175/// ML-DSA-65 kid convention: raw verifying key bytes (1952 bytes).
176fn ml_dsa_kid(vk: &MlDsaVerifyingKey) -> Vec<u8> {
177    crate::pq::ml_dsa_vk_bytes(vk)
178}
179
180/// Protected-header label under which the INNER EdDSA layer names the ML-DSA-65
181/// verifying key that must sit above it.
182///
183/// # What this closes
184///
185/// The nested construction binds inner→outer: the outer layer signs
186/// `payload ‖ inner_signature`. It does **not** bind outer→inner. Without this
187/// header the inner EdDSA layer commits to the payload and says nothing about
188/// which ML-DSA-65 key is above it, so anyone holding a *copy* of a valid inner
189/// layer — its signature bytes, not the private key — can discard the outer
190/// layer, re-sign `payload ‖ inner_signature` with an ML-DSA key of their own,
191/// and produce a composite that verifies completely: ML-DSA key theirs, Ed25519
192/// identity the victim's.
193///
194/// That asymmetry is harmless as long as the ML-DSA key is always resolved from
195/// a trust store (a wrong `kid` simply fails). It stops being harmless the
196/// moment the outer `kid` becomes a value a verifier *records*.
197///
198/// A COSE protected header is part of the `Sig_structure`, so naming the outer
199/// key here puts it under the Ed25519 signature: swapping the outer layer now
200/// contradicts the inner header, and removing the header breaks the inner
201/// signature.
202///
203/// A text label is used deliberately — it needs no IANA code point and cannot
204/// collide with a future registry allocation.
205pub const PQ_BINDING_HEADER_LABEL: &str = "hs-pq-bind";
206
207/// Build the inner EdDSA protected header.
208///
209/// `pq_binding` is the raw ML-DSA-65 verifying key this layer commits to, or
210/// `None` for the unbound form. **The unbound form is the default and is
211/// byte-for-byte what this module has always produced**, because records that
212/// persist a *decomposed* composite (at9p capsules, DID operations, the PLC
213/// directory) store only the two raw signatures and rebuild the headers
214/// deterministically on read — adding a header unconditionally would invalidate
215/// every stored signature.
216fn inner_protected(ed_kid: Vec<u8>, pq_binding: Option<&[u8]>) -> coset::Header {
217    let builder = HeaderBuilder::new()
218        .algorithm(iana::Algorithm::EdDSA)
219        .key_id(ed_kid);
220    match pq_binding {
221        Some(vk) => builder
222            .text_value(
223                PQ_BINDING_HEADER_LABEL.to_owned(),
224                CborValue::Bytes(vk.to_vec()),
225            )
226            .build(),
227        None => builder.build(),
228    }
229}
230
231/// Read the ML-DSA-65 key an inner layer commits to, if it commits to one.
232///
233/// Returns `Err` when the header is present but not a byte string — a
234/// malformed binding is a rejection, never a silently-absent one.
235fn inner_pq_binding(inner: &CoseSign1) -> Result<Option<Vec<u8>>> {
236    for (label, value) in &inner.protected.header.rest {
237        if matches!(label, coset::Label::Text(t) if t == PQ_BINDING_HEADER_LABEL) {
238            return match value {
239                CborValue::Bytes(b) => Ok(Some(b.clone())),
240                _ => bail!("inner EdDSA COSE_Sign1 PQ-binding header must be a byte string"),
241            };
242        }
243    }
244    Ok(None)
245}
246
247/// Build the inner EdDSA `COSE_Sign1` over the detached `payload`.
248fn build_inner_eddsa(
249    ed_sk: &ed25519_dalek::SigningKey,
250    payload: &[u8],
251    external_aad: &[u8],
252    pq_binding: Option<&[u8]>,
253) -> Result<CoseSign1> {
254    use ed25519_dalek::Signer as _;
255    let protected = inner_protected(eddsa_kid(&ed_sk.verifying_key()), pq_binding);
256    Ok(CoseSign1Builder::new()
257        .protected(protected)
258        .create_detached_signature(payload, external_aad, |tbs| {
259            ed_sk.sign(tbs).to_bytes().to_vec()
260        })
261        .build())
262}
263
264/// Build the outer ML-DSA-65 `COSE_Sign1` over the detached
265/// `payload ‖ inner_eddsa_signature` (the inner→outer binding).
266fn build_outer_mldsa(
267    pq_sk: &MlDsaSigningKey,
268    outer_payload: &[u8],
269    external_aad: &[u8],
270) -> Result<CoseSign1> {
271    use ml_dsa::Keypair;
272    let pq_vk = pq_sk.verifying_key().clone();
273    let protected = HeaderBuilder::new()
274        .algorithm(iana::Algorithm::ML_DSA_65)
275        .key_id(ml_dsa_kid(&pq_vk))
276        .build();
277    Ok(CoseSign1Builder::new()
278        .protected(protected)
279        .create_detached_signature(outer_payload, external_aad, |tbs| ml_dsa_sign(pq_sk, tbs))
280        .build())
281}
282
283/// Encode the nested composite as a 2-element CBOR array
284/// `[inner_bstr, outer_bstr | null]`.
285fn encode_composite(inner: Vec<u8>, outer: Option<Vec<u8>>) -> Result<Vec<u8>> {
286    let arr = CborValue::Array(vec![
287        CborValue::Bytes(inner),
288        match outer {
289            Some(o) => CborValue::Bytes(o),
290            None => CborValue::Null,
291        },
292    ]);
293    let mut buf = Vec::new();
294    ciborium::ser::into_writer(&arr, &mut buf)
295        .map_err(|e| anyhow!("failed to encode nested COSE composite: {e}"))?;
296    Ok(buf)
297}
298
299/// Decode the nested composite back into `(inner_bytes, Option<outer_bytes>)`.
300fn decode_composite(bytes: &[u8]) -> Result<(Vec<u8>, Option<Vec<u8>>)> {
301    let value: CborValue = ciborium::de::from_reader(bytes)
302        .map_err(|e| anyhow!("malformed nested COSE composite: {e}"))?;
303    let arr = match value {
304        CborValue::Array(a) => a,
305        _ => bail!("nested COSE composite must be a CBOR array"),
306    };
307    if arr.len() != 2 {
308        bail!(
309            "nested COSE composite must have exactly 2 elements, got {}",
310            arr.len()
311        );
312    }
313    let inner = match &arr[0] {
314        CborValue::Bytes(b) => b.clone(),
315        _ => bail!("nested COSE composite inner entry must be a byte string"),
316    };
317    let outer = match &arr[1] {
318        CborValue::Null => None,
319        CborValue::Bytes(b) => Some(b.clone()),
320        _ => bail!("nested COSE composite outer entry must be a byte string or null"),
321    };
322    Ok((inner, outer))
323}
324
325/// The raw inner EdDSA signature bytes (64) extracted from an inner COSE_Sign1.
326fn inner_signature_bytes(inner: &CoseSign1) -> &[u8] {
327    &inner.signature
328}
329
330/// Compute the outer payload for the inner→outer binding: `payload ‖ inner_eddsa_sig`.
331fn outer_payload(payload: &[u8], inner_sig: &[u8]) -> Vec<u8> {
332    let mut v = Vec::with_capacity(payload.len() + inner_sig.len());
333    v.extend_from_slice(payload);
334    v.extend_from_slice(inner_sig);
335    v
336}
337
338/// Sign `payload` (detached) producing the CBOR-encoded nested COSE composite.
339///
340/// - Classical (`pq_sk = None`): single inner EdDSA COSE_Sign1, outer = null.
341/// - Hybrid (`pq_sk = Some`): inner EdDSA over `payload`, outer ML-DSA-65 over
342///   `payload ‖ inner_eddsa_signature` (the inner→outer binding).
343pub fn sign_composite(
344    ed_sk: &ed25519_dalek::SigningKey,
345    pq_sk: Option<&MlDsaSigningKey>,
346    payload: &[u8],
347    external_aad: &[u8],
348) -> Result<Vec<u8>> {
349    sign_composite_inner(ed_sk, pq_sk, payload, external_aad, false)
350}
351
352/// [`sign_composite`], with the inner EdDSA layer additionally committing to the
353/// ML-DSA-65 key above it (see [`PQ_BINDING_HEADER_LABEL`]).
354///
355/// Use this wherever a verifier may *record* the composite's ML-DSA-65 key
356/// rather than resolve it from a trust store. Without the commitment, a valid
357/// composite proves possession of the ML-DSA key plus possession of one
358/// replayable Ed25519 signature — not of the Ed25519 private key.
359///
360/// Classical mode (`pq_sk = None`) has no outer key to commit to and is
361/// identical to [`sign_composite`].
362///
363/// The output stays verifiable by verifiers that predate the header: they parse
364/// the protected bucket as received, so the unknown label is carried into the
365/// `Sig_structure` and simply not interpreted.
366pub fn sign_composite_pq_bound(
367    ed_sk: &ed25519_dalek::SigningKey,
368    pq_sk: Option<&MlDsaSigningKey>,
369    payload: &[u8],
370    external_aad: &[u8],
371) -> Result<Vec<u8>> {
372    sign_composite_inner(ed_sk, pq_sk, payload, external_aad, true)
373}
374
375fn sign_composite_inner(
376    ed_sk: &ed25519_dalek::SigningKey,
377    pq_sk: Option<&MlDsaSigningKey>,
378    payload: &[u8],
379    external_aad: &[u8],
380    bind_pq: bool,
381) -> Result<Vec<u8>> {
382    use ml_dsa::Keypair;
383    // Hybrid iff an ML-DSA-65 key is present. In Hybrid mode the hybrid-composite
384    // alg-id is bound into BOTH layers' external_aad (#278); in Classical mode the
385    // bare base AAD is used so classical signatures are byte-identical to before.
386    let hybrid = pq_sk.is_some();
387    let aad = layer_aad(external_aad, hybrid);
388
389    let binding = match (bind_pq, pq_sk) {
390        (true, Some(pq)) => Some(ml_dsa_kid(&pq.verifying_key().clone())),
391        _ => None,
392    };
393    let inner = build_inner_eddsa(ed_sk, payload, &aad, binding.as_deref())?;
394    let inner_sig = inner_signature_bytes(&inner).to_vec();
395    let inner_bytes = inner
396        .to_vec()
397        .map_err(|e| anyhow!("failed to serialize inner EdDSA COSE_Sign1: {e}"))?;
398
399    let outer_bytes = match pq_sk {
400        Some(pq) => {
401            let outer_pl = outer_payload(payload, &inner_sig);
402            let outer = build_outer_mldsa(pq, &outer_pl, &aad)?;
403            Some(
404                outer
405                    .to_vec()
406                    .map_err(|e| anyhow!("failed to serialize outer ML-DSA COSE_Sign1: {e}"))?,
407            )
408        }
409        None => None,
410    };
411
412    encode_composite(inner_bytes, outer_bytes)
413}
414
415// ────────────────────────────────────────────────────────────────────────────
416// Out-of-band (async / WASM) signing API for the nested WNS composite.
417//
418// Abstract signers (e.g. the WASM `JsSigner`) cannot run inside a synchronous
419// signing closure, so they compute each layer's to-be-signed bytes, sign them
420// out-of-band, and assemble the composite here. The nesting REQUIRES the
421// outer ML-DSA layer to sign `payload ‖ inner_eddsa_signature`, so callers MUST
422// sign the inner first, take its signature, then sign the outer over
423// [`outer_tbs`].
424// ────────────────────────────────────────────────────────────────────────────
425
426/// Build an unsigned inner EdDSA `COSE_Sign1` (protected header only).
427fn unsigned_inner(ed_kid: Vec<u8>, pq_binding: Option<&[u8]>) -> CoseSign1 {
428    CoseSign1Builder::new()
429        .protected(inner_protected(ed_kid, pq_binding))
430        .build()
431}
432
433/// Build an unsigned outer ML-DSA-65 `COSE_Sign1` (protected header only).
434fn unsigned_outer(pq_kid: Vec<u8>) -> CoseSign1 {
435    CoseSign1Builder::new()
436        .protected(
437            HeaderBuilder::new()
438                .algorithm(iana::Algorithm::ML_DSA_65)
439                .key_id(pq_kid)
440                .build(),
441        )
442        .build()
443}
444
445/// Compute the inner EdDSA layer's detached to-be-signed bytes.
446///
447/// `hybrid` MUST match the composite mode the caller will assemble: when `true`
448/// the hybrid-composite alg-id is bound into the `external_aad` (#278), making
449/// the inner TBS byte-distinct from a Classical one. Pass `false` for a
450/// Classical-only composite.
451pub fn inner_tbs(ed_kid: Vec<u8>, payload: &[u8], external_aad: &[u8], hybrid: bool) -> Vec<u8> {
452    let aad = layer_aad(external_aad, hybrid);
453    unsigned_inner(ed_kid, None).tbs_detached_data(payload, &aad)
454}
455
456/// [`inner_tbs`] for a composite whose inner layer commits to the ML-DSA-65 key
457/// above it (see [`PQ_BINDING_HEADER_LABEL`]).
458///
459/// `pq_kid` MUST be the same value passed to [`outer_tbs`] and to
460/// [`assemble_composite_nested_pq_bound`]; the resulting composite is rejected
461/// if the inner commitment and the outer `kid` disagree.
462pub fn inner_tbs_pq_bound(
463    ed_kid: Vec<u8>,
464    pq_kid: &[u8],
465    payload: &[u8],
466    external_aad: &[u8],
467) -> Vec<u8> {
468    let aad = build_hybrid_external_aad(external_aad);
469    unsigned_inner(ed_kid, Some(pq_kid)).tbs_detached_data(payload, &aad)
470}
471
472/// Compute the outer ML-DSA-65 layer's detached to-be-signed bytes over
473/// `payload ‖ inner_eddsa_signature` (the inner→outer binding).
474///
475/// The outer layer only exists in Hybrid mode, so the hybrid-composite alg-id is
476/// always bound into its `external_aad` (#278) — symmetric with [`inner_tbs`]
477/// called with `hybrid = true`.
478pub fn outer_tbs(
479    pq_kid: Vec<u8>,
480    payload: &[u8],
481    inner_eddsa_sig: &[u8],
482    external_aad: &[u8],
483) -> Vec<u8> {
484    let aad = build_hybrid_external_aad(external_aad);
485    let outer_pl = outer_payload(payload, inner_eddsa_sig);
486    unsigned_outer(pq_kid).tbs_detached_data(&outer_pl, &aad)
487}
488
489/// Assemble the nested WNS composite from out-of-band signatures.
490///
491/// - `ed = (ed_kid, ed_signature)` — required; `ed_signature` is the raw 64-byte
492///   Ed25519 signature over [`inner_tbs`].
493/// - `pq = Some((pq_kid, pq_signature))` — Hybrid; `pq_signature` is the ML-DSA-65
494///   signature over [`outer_tbs`] (which was computed using `ed_signature`).
495pub fn assemble_composite_nested(
496    ed: (Vec<u8>, Vec<u8>),
497    pq: Option<(Vec<u8>, Vec<u8>)>,
498) -> Result<Vec<u8>> {
499    assemble_nested(ed, pq, false)
500}
501
502/// [`assemble_composite_nested`] for a composite whose inner layer commits to
503/// the ML-DSA-65 key above it.
504///
505/// The inner signature MUST have been produced over [`inner_tbs_pq_bound`] with
506/// the same `pq_kid` that appears in `pq`, otherwise the assembled composite
507/// will not verify.
508pub fn assemble_composite_nested_pq_bound(
509    ed: (Vec<u8>, Vec<u8>),
510    pq: (Vec<u8>, Vec<u8>),
511) -> Result<Vec<u8>> {
512    assemble_nested(ed, Some(pq), true)
513}
514
515fn assemble_nested(
516    ed: (Vec<u8>, Vec<u8>),
517    pq: Option<(Vec<u8>, Vec<u8>)>,
518    bind_pq: bool,
519) -> Result<Vec<u8>> {
520    let (ed_kid, ed_sig) = ed;
521    let binding = match (bind_pq, pq.as_ref()) {
522        (true, Some((pq_kid, _))) => Some(pq_kid.clone()),
523        _ => None,
524    };
525    let mut inner = unsigned_inner(ed_kid, binding.as_deref());
526    inner.signature = ed_sig;
527    let inner_bytes = inner
528        .to_vec()
529        .map_err(|e| anyhow!("serialize inner EdDSA COSE_Sign1: {e}"))?;
530
531    let outer_bytes = match pq {
532        Some((pq_kid, pq_sig)) => {
533            let mut outer = unsigned_outer(pq_kid);
534            outer.signature = pq_sig;
535            Some(
536                outer
537                    .to_vec()
538                    .map_err(|e| anyhow!("serialize outer ML-DSA COSE_Sign1: {e}"))?,
539            )
540        }
541        None => None,
542    };
543
544    encode_composite(inner_bytes, outer_bytes)
545}
546
547/// Test-only: decode a composite into `(inner_bytes, Option<outer_bytes>)`.
548///
549/// Exposed so integration tests in other modules (e.g. `envelope.rs`) can
550/// simulate an attacker stripping the outer ML-DSA layer.
551#[doc(hidden)]
552pub fn decode_composite_for_test(bytes: &[u8]) -> Result<(Vec<u8>, Option<Vec<u8>>)> {
553    decode_composite(bytes)
554}
555
556/// Split a nested composite blob into its raw component signatures
557/// `(ed25519_signature, Option<mldsa65_signature>)`.
558///
559/// This is the inverse projection of [`assemble_composite_nested`]: record
560/// layers that persist the composite in a *decomposed* schema (e.g. the at9p
561/// capsule/update `CoseCompositeSignature`, storing the EdDSA and ML-DSA-65
562/// signatures in separate fields) sign via [`sign_composite`], store the two
563/// raw signatures returned here, then reconstruct the nested blob with
564/// [`assemble_composite_nested`] for [`verify_composite`]. The signatures are
565/// the raw component signatures (64-byte Ed25519, 3309-byte ML-DSA-65); the
566/// kids and protected headers are deterministic and rebuilt on reassembly.
567///
568/// The inner→outer binding (the outer ML-DSA layer signs `payload ‖ inner_sig`)
569/// is preserved by that reassembly + verify round-trip — it is *not* something
570/// the decomposed store has to carry.
571pub fn split_composite(bytes: &[u8]) -> Result<(Vec<u8>, Option<Vec<u8>>)> {
572    let (inner_bytes, outer_bytes) = decode_composite(bytes)?;
573    let inner = CoseSign1::from_slice(&inner_bytes)
574        .map_err(|e| anyhow!("malformed inner EdDSA COSE_Sign1: {e}"))?;
575    let outer_sig = match outer_bytes {
576        Some(ob) => {
577            let outer = CoseSign1::from_slice(&ob)
578                .map_err(|e| anyhow!("malformed outer ML-DSA COSE_Sign1: {e}"))?;
579            Some(outer.signature)
580        }
581        None => None,
582    };
583    Ok((inner.signature, outer_sig))
584}
585
586/// Test-only: re-encode a composite from `(inner_bytes, Option<outer_bytes>)`.
587#[doc(hidden)]
588pub fn encode_composite_for_test(inner: Vec<u8>, outer: Option<Vec<u8>>) -> Result<Vec<u8>> {
589    encode_composite(inner, outer)
590}
591
592/// Test-only: serialize a standalone outer ML-DSA-65 `COSE_Sign1`.
593///
594/// Exposed so tests in other crates can build the outer-layer-substitution
595/// attack — a captured inner layer kept verbatim under a freshly signed outer —
596/// which is the case the inner layer's PQ commitment exists to reject.
597#[doc(hidden)]
598pub fn outer_layer_for_test(pq_kid: Vec<u8>, pq_signature: Vec<u8>) -> Result<Vec<u8>> {
599    let mut outer = unsigned_outer(pq_kid);
600    outer.signature = pq_signature;
601    outer
602        .to_vec()
603        .map_err(|e| anyhow!("serialize outer ML-DSA COSE_Sign1: {e}"))
604}
605
606/// The ML-DSA-65 verifying key the composite's outer layer **claims** for
607/// itself, read out of that layer's `kid` protected header.
608///
609/// # This value is not trusted
610///
611/// It is attacker-controlled wire data: whoever produced the composite chose
612/// it. It carries exactly one property — an outer signature that verifies
613/// against it proves the producer held the matching ML-DSA-65 private key —
614/// and it proves *nothing* about that key belonging to the identity in the
615/// inner EdDSA layer. [`verify_composite`] therefore never reads it as an
616/// anchor; it only compares it against a key the caller resolved from a trust
617/// source, and rejects a mismatch.
618///
619/// The one legitimate use is as a *candidate* offered to a trust-on-first-use
620/// record — and verifying the composite against it is **not** sufficient
621/// grounds to record the pairing.
622///
623/// An earlier revision of this documentation claimed that a verifying composite
624/// proves possession of both private keys. It does not, and the difference is
625/// the whole attack: the nesting binds inner→outer only, so anyone holding a
626/// *copy* of a valid inner layer can drop the outer, re-sign
627/// `payload ‖ inner_signature` with an ML-DSA key of their own, and produce a
628/// composite that verifies under the captured identity. What a plain verifying
629/// composite proves is possession of the ML-DSA-65 key plus possession of one
630/// replayable Ed25519 signature.
631///
632/// A recorded pairing therefore additionally requires
633/// [`CompositeVerified::pq_bound`] — the inner layer's signed commitment to the
634/// key above it (see [`PQ_BINDING_HEADER_LABEL`]).
635///
636/// Returns `Ok(None)` when the composite has no outer layer (classical-only) or
637/// when its outer layer carries no `kid`.
638pub fn self_asserted_outer_pq_key(
639    cose_composite_bytes: &[u8],
640) -> Result<Option<MlDsaVerifyingKey>> {
641    let (_, outer_bytes) = decode_composite(cose_composite_bytes)?;
642    let Some(ob) = outer_bytes else {
643        return Ok(None);
644    };
645    let outer = CoseSign1::from_slice(&ob)
646        .map_err(|e| anyhow!("malformed outer ML-DSA COSE_Sign1: {e}"))?;
647    let outer_alg = header_alg(&outer)?;
648    if outer_alg != ALG_ML_DSA_65 {
649        bail!("outer COSE_Sign1 must be ML-DSA-65, got alg={outer_alg}");
650    }
651    let kid = &outer.protected.header.key_id;
652    if kid.is_empty() {
653        return Ok(None);
654    }
655    crate::pq::ml_dsa_vk_from_bytes(kid).map(Some)
656}
657
658/// Outcome of composite verification.
659#[derive(Debug, Clone, PartialEq, Eq)]
660pub struct CompositeVerified {
661    /// Inner EdDSA was verified.
662    pub eddsa: bool,
663    /// Outer ML-DSA-65 layer was verified.
664    pub ml_dsa: bool,
665    /// The inner EdDSA layer named the ML-DSA-65 key above it, and that name
666    /// matched the outer layer (see [`PQ_BINDING_HEADER_LABEL`]).
667    ///
668    /// Only when this is `true` does the composite prove possession of the
669    /// **Ed25519 private key alongside** the ML-DSA-65 one. Without it a valid
670    /// composite proves possession of the ML-DSA key plus possession of one
671    /// replayable Ed25519 signature, which is not the same claim. A verifier
672    /// that intends to *record* the composite's ML-DSA-65 key — rather than
673    /// resolve it from a trust store — MUST require this.
674    pub pq_bound: bool,
675}
676
677/// Verify a CBOR-encoded nested COSE composite against a detached `payload`.
678///
679/// # kid-anchoring
680///
681/// `expected_ed_vk` is the EdDSA verifying key resolved by the caller. When
682/// `expected_pq_vk` is `Some`, it is the trust-anchored ML-DSA-65 key — the
683/// outer COSE entry's kid AND signature must verify against it, closing the
684/// self-certification gap.
685///
686/// # Policy
687///
688/// - `require_pq = true` (Hybrid verifier): the OUTER ML-DSA-65 layer MUST be
689///   present and verify against the anchored key over `payload ‖ inner_sig`, AND
690///   the inner EdDSA layer MUST verify over `payload`. If `expected_pq_vk` is
691///   `None`, verification fails (no anchor — fail-closed). **Stripping the outer
692///   layer (outer = null) is rejected.**
693/// - `require_pq = false` (Classical verifier): only the inner EdDSA layer is
694///   required and verified; any outer ML-DSA layer is IGNORED (skip-unknown
695///   interop — a Hybrid-signed envelope still verifies via its inner EdDSA).
696///
697/// # Hybrid-alg-id binding (#278)
698///
699/// The inner/outer layers in a Hybrid composite bind the hybrid-composite alg-id
700/// into their `external_aad` (see [`build_hybrid_external_aad`]). The verifier
701/// reconstructs the inner AAD from the composite's *self-describing* shape: if an
702/// outer ML-DSA layer is present, the inner was Hybrid-signed → reconstruct the
703/// hybrid inner AAD; if the outer is absent (Classical or stripped), reconstruct
704/// the bare base AAD. Consequently a Hybrid-signed inner whose outer layer has
705/// been STRIPPED (outer = null) fails the inner EdDSA *signature* check (AAD
706/// mismatch) — signature-level non-separability — independent of `require_pq`.
707pub fn verify_composite(
708    cose_composite_bytes: &[u8],
709    expected_ed_vk: &ed25519_dalek::VerifyingKey,
710    expected_pq_vk: Option<&MlDsaVerifyingKey>,
711    payload: &[u8],
712    external_aad: &[u8],
713    require_pq: bool,
714) -> Result<CompositeVerified> {
715    let (inner_bytes, outer_bytes) = decode_composite(cose_composite_bytes)?;
716
717    // The composite is self-describing: an outer ML-DSA layer means the inner was
718    // produced in Hybrid mode (hybrid-alg-id bound into its AAD). Reconstruct the
719    // inner AAD accordingly. A stripped Hybrid composite (outer=null) therefore
720    // reconstructs the *bare* AAD and FAILS the inner signature check below.
721    let inner_hybrid = outer_bytes.is_some();
722    let inner_aad = layer_aad(external_aad, inner_hybrid);
723
724    // --- Inner EdDSA layer (always required) ---
725    let inner = CoseSign1::from_slice(&inner_bytes)
726        .map_err(|e| anyhow!("malformed inner EdDSA COSE_Sign1: {e}"))?;
727
728    let inner_alg = header_alg(&inner)?;
729    if inner_alg != iana::Algorithm::EdDSA.to_i64() {
730        bail!("inner COSE_Sign1 must be EdDSA, got alg={inner_alg}");
731    }
732    let inner_kid = &inner.protected.header.key_id;
733    if !inner_kid.is_empty() && inner_kid.as_slice() != expected_ed_vk.to_bytes() {
734        bail!("inner EdDSA COSE_Sign1 kid does not match anchored EdDSA key");
735    }
736    let declared_pq = inner_pq_binding(&inner)?;
737    inner
738        .verify_detached_signature(payload, &inner_aad, |sig, tbs| {
739            ed_verify(expected_ed_vk, tbs, sig)
740        })
741        .context("inner EdDSA signature verification failed")?;
742    let eddsa_ok = true;
743
744    // The inner layer named an outer key, so the outer layer is not optional and
745    // not substitutable. Checking this before any outer work means a swapped or
746    // stripped outer is rejected on the strength of the Ed25519 signature alone.
747    let mut pq_bound = false;
748    if let Some(declared) = &declared_pq {
749        let Some(ob) = outer_bytes.as_ref() else {
750            bail!(
751                "inner EdDSA COSE_Sign1 commits to an ML-DSA-65 key but the outer layer is absent"
752            );
753        };
754        let outer = CoseSign1::from_slice(ob)
755            .map_err(|e| anyhow!("malformed outer ML-DSA COSE_Sign1: {e}"))?;
756        if outer.protected.header.key_id.as_slice() != declared.as_slice() {
757            bail!("outer ML-DSA-65 COSE_Sign1 kid does not match the key the inner EdDSA layer committed to (outer-layer substitution rejected)");
758        }
759        pq_bound = true;
760    }
761
762    // Capture the inner signature; it is bound into the outer layer's signed message.
763    let inner_sig = inner_signature_bytes(&inner).to_vec();
764
765    // --- Outer ML-DSA-65 layer (inner→outer binding) ---
766    let mut ml_dsa_ok = false;
767
768    match outer_bytes {
769        Some(ref ob) if require_pq || expected_pq_vk.is_some() => {
770            // Anchored PQ key is mandatory to verify the outer layer.
771            let Some(pq_vk) = expected_pq_vk else {
772                if require_pq {
773                    bail!("Hybrid policy requires an anchored ML-DSA-65 key, none provided");
774                }
775                // Classical verifier without an anchor: ignore the outer layer.
776                return Ok(CompositeVerified {
777                    eddsa: eddsa_ok,
778                    ml_dsa: false,
779                    pq_bound,
780                });
781            };
782            let outer = CoseSign1::from_slice(ob)
783                .map_err(|e| anyhow!("malformed outer ML-DSA COSE_Sign1: {e}"))?;
784            let outer_alg = header_alg(&outer)?;
785            if outer_alg != ALG_ML_DSA_65 {
786                bail!("outer COSE_Sign1 must be ML-DSA-65, got alg={outer_alg}");
787            }
788            let outer_kid = &outer.protected.header.key_id;
789            if !outer_kid.is_empty() && outer_kid.as_slice() != ml_dsa_kid(pq_vk).as_slice() {
790                bail!("outer ML-DSA-65 COSE_Sign1 kid does not match anchored PQ key (self-cert rejected)");
791            }
792            let outer_pl = outer_payload(payload, &inner_sig);
793            // The outer layer only exists in Hybrid mode, so it always binds the
794            // hybrid-composite alg-id into its external_aad (#278).
795            let outer_aad = build_hybrid_external_aad(external_aad);
796            outer
797                .verify_detached_signature(&outer_pl, &outer_aad, |sig, tbs| {
798                    ml_dsa_verify(pq_vk, tbs, sig)
799                })
800                .context("outer ML-DSA-65 signature verification failed")?;
801            ml_dsa_ok = true;
802        }
803        Some(_) => {
804            // require_pq is false and no anchor: ignore outer (skip-unknown).
805        }
806        None => {
807            // No outer layer present (Classical-signed).
808            if require_pq {
809                bail!("Hybrid policy requires the outer ML-DSA-65 layer, but it is absent (stripped or classical-only)");
810            }
811        }
812    }
813
814    if require_pq && !ml_dsa_ok {
815        bail!("Hybrid policy: outer ML-DSA-65 layer missing or unverified");
816    }
817
818    Ok(CompositeVerified {
819        eddsa: eddsa_ok,
820        ml_dsa: ml_dsa_ok,
821        pq_bound,
822    })
823}
824
825/// Extract the IANA alg integer from a COSE_Sign1 protected header.
826fn header_alg(cose: &CoseSign1) -> Result<i64> {
827    match cose.protected.header.alg.as_ref() {
828        Some(coset::Algorithm::Assigned(a)) => Ok(a.to_i64()),
829        Some(coset::Algorithm::PrivateUse(v)) => Ok(*v),
830        Some(coset::Algorithm::Text(s)) => bail!("unsupported text algorithm: {s}"),
831        None => bail!("COSE_Sign1 missing alg in protected header"),
832    }
833}
834
835fn ed_verify(vk: &ed25519_dalek::VerifyingKey, msg: &[u8], sig: &[u8]) -> Result<()> {
836    if sig.len() != 64 {
837        bail!("Ed25519 signature must be 64 bytes, got {}", sig.len());
838    }
839    let mut arr = [0u8; 64];
840    arr.copy_from_slice(sig);
841    let signature = ed25519_dalek::Signature::from_bytes(&arr);
842    vk.verify_strict(msg, &signature)
843        .map_err(|e| anyhow!("Ed25519 verification failed: {e}"))
844}
845
846#[cfg(test)]
847#[allow(clippy::unwrap_used, clippy::expect_used)]
848mod tests {
849    use super::*;
850    use crate::cose_sign1::build_external_aad;
851    use crate::pq::ml_dsa_generate_keypair;
852    use ed25519_dalek::SigningKey;
853    use rand::rngs::OsRng;
854
855    const SCHEMA_ID: u64 = 0xcf5e_016c_5d4a_af92;
856    const INNER_TYPE_ID: u64 = 0xdead_beef_cafe_babe;
857
858    fn aad() -> Vec<u8> {
859        build_external_aad(SCHEMA_ID, INNER_TYPE_ID)
860    }
861
862    /// The attack the PQ-binding header exists to stop: keep a victim's inner
863    /// EdDSA layer byte-for-byte and re-sign the outer layer with a key of your
864    /// own. No Ed25519 private key is involved.
865    #[test]
866    fn an_unbound_composite_lets_an_outer_layer_be_swapped_without_the_ed25519_key() {
867        use ml_dsa::Keypair;
868        let ed = SigningKey::generate(&mut OsRng);
869        let (victim_pq, _) = ml_dsa_generate_keypair();
870        let attacker_pq = crate::pq::ml_dsa_sk_from_seed(&[0xEE; 32]);
871        let attacker_vk = attacker_pq.verifying_key().clone();
872        let payload = b"captured payload";
873
874        // The victim's genuine composite, WITHOUT the binding.
875        let cose = sign_composite(&ed, Some(&victim_pq), payload, &aad()).unwrap();
876        let (ed_sig, _) = split_composite(&cose).unwrap();
877
878        // The attacker holds no Ed25519 key — only the signature bytes.
879        let attacker_kid = ml_dsa_kid(&attacker_vk);
880        let tbs = outer_tbs(attacker_kid.clone(), payload, &ed_sig, &aad());
881        let forged = assemble_composite_nested(
882            (ed.verifying_key().to_bytes().to_vec(), ed_sig),
883            Some((attacker_kid, ml_dsa_sign(&attacker_pq, &tbs))),
884        )
885        .unwrap();
886
887        let res = verify_composite(
888            &forged,
889            &ed.verifying_key(),
890            Some(&attacker_vk),
891            payload,
892            &aad(),
893            true,
894        )
895        .unwrap();
896        // It verifies — which is exactly why an unbound composite must never
897        // establish a recorded binding.
898        assert!(res.eddsa && res.ml_dsa);
899        assert!(
900            !res.pq_bound,
901            "an unbound composite must never report the both-keys-proven property"
902        );
903    }
904
905    #[test]
906    fn a_bound_composite_refuses_the_same_outer_layer_swap() {
907        use ml_dsa::Keypair;
908        let ed = SigningKey::generate(&mut OsRng);
909        let (victim_pq, victim_vk) = ml_dsa_generate_keypair();
910        let attacker_pq = crate::pq::ml_dsa_sk_from_seed(&[0xEF; 32]);
911        let attacker_vk = attacker_pq.verifying_key().clone();
912        let payload = b"captured payload";
913
914        let cose = sign_composite_pq_bound(&ed, Some(&victim_pq), payload, &aad()).unwrap();
915        let honest = verify_composite(
916            &cose,
917            &ed.verifying_key(),
918            Some(&victim_vk),
919            payload,
920            &aad(),
921            true,
922        )
923        .unwrap();
924        assert!(honest.eddsa && honest.ml_dsa && honest.pq_bound);
925
926        let (ed_sig, _) = split_composite(&cose).unwrap();
927        let attacker_kid = ml_dsa_kid(&attacker_vk);
928        let tbs = outer_tbs(attacker_kid.clone(), payload, &ed_sig, &aad());
929        let attacker_sig = ml_dsa_sign(&attacker_pq, &tbs);
930
931        // Route 1: keep the victim's inner layer byte-for-byte — binding header
932        // and all — and swap only the outer. This is the strongest form of the
933        // attack: the inner signature is untouched and still valid.
934        let (victim_inner_bytes, _) = decode_composite_for_test(&cose).unwrap();
935        let mut attacker_outer = unsigned_outer(attacker_kid.clone());
936        attacker_outer.signature = attacker_sig.clone();
937        let swapped =
938            encode_composite_for_test(victim_inner_bytes, Some(attacker_outer.to_vec().unwrap()))
939                .unwrap();
940        let err = verify_composite(
941            &swapped,
942            &ed.verifying_key(),
943            Some(&attacker_vk),
944            payload,
945            &aad(),
946            true,
947        )
948        .unwrap_err();
949        assert!(
950            format!("{err:#}").contains("committed to"),
951            "the inner layer's commitment must reject a swapped outer: {err:#}"
952        );
953
954        // Route 2: rebuild the inner layer naming the attacker's key instead.
955        // The commitment lives in the signed protected header, so rewriting it
956        // invalidates the victim's Ed25519 signature.
957        let renamed = assemble_composite_nested_pq_bound(
958            (ed.verifying_key().to_bytes().to_vec(), ed_sig.clone()),
959            (attacker_kid.clone(), attacker_sig.clone()),
960        )
961        .unwrap();
962        assert!(verify_composite(
963            &renamed,
964            &ed.verifying_key(),
965            Some(&attacker_vk),
966            payload,
967            &aad(),
968            true,
969        )
970        .is_err());
971
972        // Route 3: drop the commitment entirely, hoping to fall back to the
973        // unbound shape. Same reason: the protected header is signed.
974        let unbound = assemble_composite_nested(
975            (ed.verifying_key().to_bytes().to_vec(), ed_sig),
976            Some((attacker_kid, attacker_sig)),
977        )
978        .unwrap();
979        assert!(verify_composite(
980            &unbound,
981            &ed.verifying_key(),
982            Some(&attacker_vk),
983            payload,
984            &aad(),
985            true,
986        )
987        .is_err());
988    }
989
990    #[test]
991    fn a_bound_composite_cannot_have_its_outer_layer_stripped() {
992        let ed = SigningKey::generate(&mut OsRng);
993        let (pq_sk, _) = ml_dsa_generate_keypair();
994        let payload = b"strip me";
995        let cose = sign_composite_pq_bound(&ed, Some(&pq_sk), payload, &aad()).unwrap();
996        let (inner, _) = decode_composite_for_test(&cose).unwrap();
997        let stripped = encode_composite_for_test(inner, None).unwrap();
998
999        // Rejected even by a verifier that does not require PQ. Two independent
1000        // mechanisms catch it — the hybrid inner AAD no longer reconstructs once
1001        // the outer is gone, and the inner layer said an outer belongs here —
1002        // so this asserts the rejection rather than which one fired first.
1003        assert!(
1004            verify_composite(&stripped, &ed.verifying_key(), None, payload, &aad(), false).is_err()
1005        );
1006    }
1007
1008    #[test]
1009    fn the_binding_is_additive_for_verifiers_that_do_not_know_it() {
1010        // An unbound composite keeps reporting exactly what it always did, so
1011        // every persisted decomposed signature (at9p capsules, DID operations,
1012        // the PLC directory) verifies unchanged.
1013        let ed = SigningKey::generate(&mut OsRng);
1014        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
1015        let payload = b"legacy payload";
1016        let unbound = sign_composite(&ed, Some(&pq_sk), payload, &aad()).unwrap();
1017        let res = verify_composite(
1018            &unbound,
1019            &ed.verifying_key(),
1020            Some(&pq_vk),
1021            payload,
1022            &aad(),
1023            true,
1024        )
1025        .unwrap();
1026        assert!(res.eddsa && res.ml_dsa && !res.pq_bound);
1027
1028        // And a split/reassemble round-trip — how those records persist — is
1029        // still byte-identical.
1030        let (ed_sig, pq_sig) = split_composite(&unbound).unwrap();
1031        let rebuilt = assemble_composite_nested(
1032            (ed.verifying_key().to_bytes().to_vec(), ed_sig),
1033            Some((ml_dsa_kid(&pq_vk), pq_sig.unwrap())),
1034        )
1035        .unwrap();
1036        assert_eq!(rebuilt, unbound);
1037    }
1038
1039    #[test]
1040    fn the_out_of_band_signing_path_produces_a_bound_composite() {
1041        use ed25519_dalek::Signer as _;
1042        use ml_dsa::Keypair;
1043        let ed = SigningKey::generate(&mut OsRng);
1044        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
1045        let payload = b"browser payload";
1046        let ed_kid = ed.verifying_key().to_bytes().to_vec();
1047        let pq_kid = ml_dsa_kid(&pq_sk.verifying_key().clone());
1048
1049        let ed_sig = ed
1050            .sign(&inner_tbs_pq_bound(
1051                ed_kid.clone(),
1052                &pq_kid,
1053                payload,
1054                &aad(),
1055            ))
1056            .to_bytes()
1057            .to_vec();
1058        let pq_sig = ml_dsa_sign(&pq_sk, &outer_tbs(pq_kid.clone(), payload, &ed_sig, &aad()));
1059        let cose = assemble_composite_nested_pq_bound((ed_kid, ed_sig), (pq_kid, pq_sig)).unwrap();
1060
1061        let res = verify_composite(
1062            &cose,
1063            &ed.verifying_key(),
1064            Some(&pq_vk),
1065            payload,
1066            &aad(),
1067            true,
1068        )
1069        .unwrap();
1070        assert!(res.eddsa && res.ml_dsa && res.pq_bound);
1071    }
1072
1073    #[test]
1074    fn classical_sign_verify() {
1075        let ed = SigningKey::generate(&mut OsRng);
1076        let payload = b"classical payload";
1077        let cose = sign_composite(&ed, None, payload, &aad()).unwrap();
1078        let res =
1079            verify_composite(&cose, &ed.verifying_key(), None, payload, &aad(), false).unwrap();
1080        assert!(res.eddsa);
1081        assert!(!res.ml_dsa);
1082    }
1083
1084    #[test]
1085    fn hybrid_sign_verify_both() {
1086        let ed = SigningKey::generate(&mut OsRng);
1087        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
1088        let payload = b"hybrid payload";
1089        let cose = sign_composite(&ed, Some(&pq_sk), payload, &aad()).unwrap();
1090        let res = verify_composite(
1091            &cose,
1092            &ed.verifying_key(),
1093            Some(&pq_vk),
1094            payload,
1095            &aad(),
1096            true,
1097        )
1098        .unwrap();
1099        assert!(res.eddsa);
1100        assert!(res.ml_dsa);
1101    }
1102
1103    #[test]
1104    fn hybrid_signed_verified_by_classical_via_eddsa() {
1105        let ed = SigningKey::generate(&mut OsRng);
1106        let (pq_sk, _pq_vk) = ml_dsa_generate_keypair();
1107        let payload = b"cross payload";
1108        let cose = sign_composite(&ed, Some(&pq_sk), payload, &aad()).unwrap();
1109        // Classical verifier: no PQ key, require_pq=false → inner EdDSA only.
1110        let res =
1111            verify_composite(&cose, &ed.verifying_key(), None, payload, &aad(), false).unwrap();
1112        assert!(res.eddsa);
1113        assert!(!res.ml_dsa);
1114    }
1115
1116    #[test]
1117    fn classical_signed_rejected_by_hybrid_policy() {
1118        let ed = SigningKey::generate(&mut OsRng);
1119        let (_pq_sk, pq_vk) = ml_dsa_generate_keypair();
1120        let payload = b"classical only";
1121        let cose = sign_composite(&ed, None, payload, &aad()).unwrap();
1122        // Hybrid verifier requires the outer layer → absent → rejected.
1123        let res = verify_composite(
1124            &cose,
1125            &ed.verifying_key(),
1126            Some(&pq_vk),
1127            payload,
1128            &aad(),
1129            true,
1130        );
1131        assert!(
1132            res.is_err(),
1133            "hybrid policy must reject classical-only (no outer layer)"
1134        );
1135    }
1136
1137    #[test]
1138    fn self_cert_wrong_pq_key_rejected() {
1139        let ed = SigningKey::generate(&mut OsRng);
1140        let (pq_sk, _pq_vk) = ml_dsa_generate_keypair();
1141        let (_other_sk, other_vk) = ml_dsa_generate_keypair();
1142        let payload = b"anchored";
1143        let cose = sign_composite(&ed, Some(&pq_sk), payload, &aad()).unwrap();
1144        let res = verify_composite(
1145            &cose,
1146            &ed.verifying_key(),
1147            Some(&other_vk),
1148            payload,
1149            &aad(),
1150            true,
1151        );
1152        assert!(
1153            res.is_err(),
1154            "PQ key not matching kid-anchored key must be rejected"
1155        );
1156    }
1157
1158    #[test]
1159    fn tampered_payload_rejected() {
1160        let ed = SigningKey::generate(&mut OsRng);
1161        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
1162        let cose = sign_composite(&ed, Some(&pq_sk), b"orig", &aad()).unwrap();
1163        let res = verify_composite(
1164            &cose,
1165            &ed.verifying_key(),
1166            Some(&pq_vk),
1167            b"tampered",
1168            &aad(),
1169            true,
1170        );
1171        assert!(res.is_err());
1172    }
1173
1174    #[test]
1175    fn wrong_aad_rejected() {
1176        let ed = SigningKey::generate(&mut OsRng);
1177        let cose = sign_composite(&ed, None, b"p", &aad()).unwrap();
1178        let wrong = build_external_aad(SCHEMA_ID, INNER_TYPE_ID ^ 1);
1179        let res = verify_composite(&cose, &ed.verifying_key(), None, b"p", &wrong, false);
1180        assert!(res.is_err());
1181    }
1182
1183    /// Policy-enforced: stripping the outer ML-DSA layer (set to null) must be rejected
1184    /// under Hybrid policy. This is the attack the review found accepted before.
1185    #[test]
1186    fn strip_outer_mldsa_rejected_under_hybrid() {
1187        let ed = SigningKey::generate(&mut OsRng);
1188        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
1189        let payload = b"strip me";
1190        let cose = sign_composite(&ed, Some(&pq_sk), payload, &aad()).unwrap();
1191
1192        // Strip: rebuild the composite with the outer set to null.
1193        let (inner, _outer) = decode_composite(&cose).unwrap();
1194        let stripped = encode_composite(inner, None).unwrap();
1195
1196        let res = verify_composite(
1197            &stripped,
1198            &ed.verifying_key(),
1199            Some(&pq_vk),
1200            payload,
1201            &aad(),
1202            true,
1203        );
1204        assert!(
1205            res.is_err(),
1206            "stripping the outer ML-DSA layer must fail Hybrid policy"
1207        );
1208    }
1209
1210    /// inner→outer binding: tampering with the inner EdDSA signature invalidates the outer,
1211    /// because the outer signs `payload ‖ inner_sig`.
1212    #[test]
1213    fn tamper_inner_eddsa_invalidates_outer() {
1214        let ed = SigningKey::generate(&mut OsRng);
1215        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
1216        let payload = b"sns binding";
1217        let cose = sign_composite(&ed, Some(&pq_sk), payload, &aad()).unwrap();
1218
1219        // Re-sign the inner with a DIFFERENT EdDSA key but keep the original
1220        // outer. The inner kid won't match the anchored ed_vk, and even if it
1221        // did, the outer was bound to the original inner_sig.
1222        let (_inner, outer) = decode_composite(&cose).unwrap();
1223        let other_ed = SigningKey::generate(&mut OsRng);
1224        let forged_inner = build_inner_eddsa(&other_ed, payload, &aad(), None).unwrap();
1225        let forged_inner_bytes = forged_inner.to_vec().unwrap();
1226        let tampered = encode_composite(forged_inner_bytes, outer).unwrap();
1227
1228        // Verify under the ORIGINAL ed_vk + anchored pq_vk: inner kid mismatch
1229        // OR outer-binding mismatch → reject.
1230        let res = verify_composite(
1231            &tampered,
1232            &ed.verifying_key(),
1233            Some(&pq_vk),
1234            payload,
1235            &aad(),
1236            true,
1237        );
1238        assert!(
1239            res.is_err(),
1240            "tampering the inner EdDSA must invalidate the composite"
1241        );
1242    }
1243
1244    /// Hybrid policy with no anchored PQ key must fail closed.
1245    #[test]
1246    fn hybrid_no_anchor_rejected() {
1247        let ed = SigningKey::generate(&mut OsRng);
1248        let (pq_sk, _pq_vk) = ml_dsa_generate_keypair();
1249        let payload = b"no anchor";
1250        let cose = sign_composite(&ed, Some(&pq_sk), payload, &aad()).unwrap();
1251        let res = verify_composite(&cose, &ed.verifying_key(), None, payload, &aad(), true);
1252        assert!(res.is_err(), "Hybrid policy requires an anchored PQ key");
1253    }
1254
1255    // ── #278: hybrid-composite alg-id binding (signature-level non-separability) ──
1256
1257    /// The hybrid AAD must differ from the bare base AAD and embed the alg-id.
1258    #[test]
1259    fn hybrid_external_aad_binds_alg_id_and_differs() {
1260        let base = aad();
1261        let hybrid = build_hybrid_external_aad(&base);
1262        assert_ne!(
1263            hybrid, base,
1264            "hybrid AAD must differ from the bare base AAD"
1265        );
1266        // Determinism.
1267        assert_eq!(hybrid, build_hybrid_external_aad(&base));
1268        // The composite alg-id bytes appear in the encoded hybrid AAD.
1269        let needle = HYBRID_COMPOSITE_ALG_ID;
1270        assert!(
1271            hybrid.windows(needle.len()).any(|w| w == needle),
1272            "hybrid AAD must embed HYBRID_COMPOSITE_ALG_ID"
1273        );
1274    }
1275
1276    /// The inner EdDSA TBS / signature bytes in Hybrid mode must be byte-distinct
1277    /// from Classical mode over the same payload + base AAD.
1278    #[test]
1279    fn inner_eddsa_bytes_hybrid_distinct_from_classical() {
1280        let ed = SigningKey::generate(&mut OsRng);
1281        let payload = b"distinctness";
1282        let kid = ed.verifying_key().to_bytes().to_vec();
1283
1284        // TBS bytes differ by mode.
1285        let tbs_classical = inner_tbs(kid.clone(), payload, &aad(), false);
1286        let tbs_hybrid = inner_tbs(kid, payload, &aad(), true);
1287        assert_ne!(
1288            tbs_classical, tbs_hybrid,
1289            "inner EdDSA TBS in Hybrid mode must differ from Classical mode"
1290        );
1291
1292        // Signature bytes differ by mode (Ed25519 is deterministic, so equal TBS
1293        // would yield equal sigs; distinct TBS yields distinct sigs).
1294        let (pq_sk, _pq_vk) = ml_dsa_generate_keypair();
1295        let classical = sign_composite(&ed, None, payload, &aad()).unwrap();
1296        let hybrid = sign_composite(&ed, Some(&pq_sk), payload, &aad()).unwrap();
1297        let (inner_c, _) = decode_composite(&classical).unwrap();
1298        let (inner_h, _) = decode_composite(&hybrid).unwrap();
1299        let sig_c = CoseSign1::from_slice(&inner_c).unwrap().signature;
1300        let sig_h = CoseSign1::from_slice(&inner_h).unwrap().signature;
1301        assert_ne!(
1302            sig_c, sig_h,
1303            "inner EdDSA signature bytes must differ between Hybrid and Classical"
1304        );
1305    }
1306
1307    /// SIGNATURE-LEVEL non-separability: a Hybrid-signed composite with the outer
1308    /// ML-DSA layer stripped must FAIL standalone-Classical verification at the
1309    /// *signature* level (not merely the require_pq policy check).
1310    #[test]
1311    fn stripped_hybrid_inner_fails_classical_signature_verification() {
1312        let ed = SigningKey::generate(&mut OsRng);
1313        let (pq_sk, _pq_vk) = ml_dsa_generate_keypair();
1314        let payload = b"strip and downgrade";
1315        let cose = sign_composite(&ed, Some(&pq_sk), payload, &aad()).unwrap();
1316
1317        // Strip the outer layer → outer = null.
1318        let (inner, _outer) = decode_composite(&cose).unwrap();
1319        let stripped = encode_composite(inner, None).unwrap();
1320
1321        // Classical verifier (require_pq=false, no PQ anchor): would have ACCEPTED
1322        // the inner EdDSA before #278. Now the inner was bound to the hybrid-alg-id,
1323        // so reconstructing the bare base AAD fails the signature check.
1324        let res = verify_composite(&stripped, &ed.verifying_key(), None, payload, &aad(), false);
1325        assert!(
1326            res.is_err(),
1327            "stripped Hybrid inner must fail standalone Classical signature verification"
1328        );
1329        let msg = format!("{:#}", res.unwrap_err());
1330        assert!(
1331            msg.contains("inner EdDSA signature verification failed"),
1332            "failure must be at the signature level, got: {msg}"
1333        );
1334    }
1335
1336    /// Regression guard: a genuine Classical-signed inner still verifies under a
1337    /// Classical verifier (no hybrid-alg-id involved on either side).
1338    #[test]
1339    fn classical_roundtrip_unchanged_after_278() {
1340        let ed = SigningKey::generate(&mut OsRng);
1341        let payload = b"classical unchanged";
1342        let cose = sign_composite(&ed, None, payload, &aad()).unwrap();
1343        let res =
1344            verify_composite(&cose, &ed.verifying_key(), None, payload, &aad(), false).unwrap();
1345        assert!(res.eddsa);
1346        assert!(!res.ml_dsa);
1347    }
1348
1349    /// A genuine Classical inner is NOT mistaken for a Hybrid one: verifying a
1350    /// Classical composite with the hybrid AAD reconstruction would fail, but the
1351    /// verifier keys the inner AAD off outer-presence, so the normal Classical
1352    /// path succeeds (covered above) while a hybrid-AAD reconstruction is rejected.
1353    #[test]
1354    fn classical_inner_not_accepted_under_hybrid_aad() {
1355        let ed = SigningKey::generate(&mut OsRng);
1356        let payload = b"no false hybrid";
1357        let cose = sign_composite(&ed, None, payload, &aad()).unwrap();
1358        // Decode the classical inner and re-verify it directly against the HYBRID
1359        // AAD to prove the two TBS inputs are genuinely separated.
1360        let (inner, _) = decode_composite(&cose).unwrap();
1361        let inner_cose = CoseSign1::from_slice(&inner).unwrap();
1362        let hybrid_aad = build_hybrid_external_aad(&aad());
1363        let res = inner_cose.verify_detached_signature(payload, &hybrid_aad, |sig, tbs| {
1364            ed_verify(&ed.verifying_key(), tbs, sig)
1365        });
1366        assert!(
1367            res.is_err(),
1368            "classical inner must not verify under the hybrid AAD"
1369        );
1370    }
1371}