Skip to main content

hyprstream_pds/
at9p_sign.rs

1//! Policy-gated composite signing and verification for `did:at9p` records
2//! (capsules and update-records), per design #879 §4.4 (Hybrid-pinning) and
3//! review rules R4/R8 (findings A18/A19).
4//!
5//! # GATE 2: Hybrid is PINNED, not configurable
6//!
7//! `CryptoPolicy::{Hybrid, Classical}` is per-node runtime configuration for
8//! the general RPC plane. at9p records do **not** honor it: capsule,
9//! update-record, and manifest signatures **always** require BOTH composite
10//! components (EdDSA + ML-DSA-65) to verify, regardless of the node's policy.
11//! A `Classical`-configured node still rejects an Ed25519-only-valid capsule
12//! (§4.4, A19/R4) — otherwise an attacker holding only a stolen classical key
13//! could forge identities for every such node.
14//!
15//! The pin is built into this module's API surface so it cannot be bypassed:
16//!
17//! - **Signing** takes a `&MlDsaSigningKey` by value, never an `Option`. There
18//!   is no code path that calls the underlying
19//!   [`hyprstream_crypto::cose_sign::sign_composite`] with `pq_sk = None`
20//!   (review rule R4 — `sign_composite` does *not* self-enforce policy; its
21//!   callers do). The one call site is [`sign_record`], and it always passes
22//!   `Some(pq_sk)`.
23//! - **Verification** always calls
24//!   [`hyprstream_crypto::cose_sign::verify_composite`] with `require_pq = true`
25//!   and a non-`None` anchored ML-DSA-65 key. A missing outer layer (stripped
26//!   or classical-only) fails closed.
27//!
28//! # Per-record-type COSE context strings (R8, A18)
29//!
30//! Every at9p record type binds its context string
31//! (`at9p-capsule/1`, `at9p-update/1`) into the COSE protected header, which is
32//! folded into BOTH signature layers as `external_aad` (RFC 9052 §4.4). The
33//! context is **checked** on verify against the record type being verified, so
34//! a signature minted for one record type (or an RPC envelope) cannot be
35//! replayed as another — cross-context signature reuse (A18) is defeated.
36
37use anyhow::{ensure, Context, Result};
38use ed25519_dalek::{SigningKey, VerifyingKey};
39
40use hyprstream_crypto::cose_sign::{
41    assemble_composite_nested, inner_tbs, outer_tbs, sign_composite, split_composite,
42    verify_composite,
43};
44use hyprstream_crypto::pq::{
45    ml_dsa_sign, ml_dsa_sk_to_vk_bytes, ml_dsa_vk_bytes, ml_dsa_vk_from_bytes, MlDsaSigningKey,
46    MlDsaVerifyingKey,
47};
48
49use crate::at9p::{
50    Capsule, CapsuleBody, CoseCompositeSignature, HybridKeyPair, UpdateRecord,
51    CAPSULE_SIGNATURE_CONTEXT, ED25519_PUBLIC_KEY_LEN, UPDATE_SIGNATURE_CONTEXT,
52};
53use crate::dag_cbor::DagCbor;
54
55/// Composite/hybrid algorithm identifier bound into every at9p protected
56/// header. Matches the LAMPS composite name the underlying nested COSE
57/// construction binds (`draft-ietf-lamps-pq-composite-sigs`,
58/// `id-MLDSA65-Ed25519`). Pinning it here documents on the wire that at9p
59/// records are hybrid-only.
60const AT9P_COMPOSITE_ALG_ID: &str = "id-MLDSA65-Ed25519";
61
62/// Build the deterministic COSE protected-header bytes that bind the
63/// composite alg-id and the record-type `context` string.
64///
65/// These bytes are both stored in `CoseCompositeSignature.protected` and used
66/// as the `external_aad` for the composite signature, so the context is folded
67/// into both signature layers. Encoded with the crate's canonical DAG-CBOR
68/// codec (sorted keys, minimal ints) so it is byte-stable across signer and
69/// verifier.
70fn context_protected_header(context: &str) -> Vec<u8> {
71    DagCbor::str_map([
72        ("alg", DagCbor::Text(AT9P_COMPOSITE_ALG_ID.to_owned())),
73        ("context", DagCbor::Text(context.to_owned())),
74    ])
75    .encode()
76}
77
78/// Derive the concrete verifying keys from a declared hybrid keypair.
79fn verifying_keys(keypair: &HybridKeyPair) -> Result<(VerifyingKey, MlDsaVerifyingKey)> {
80    keypair.validate()?;
81    let ed_bytes: [u8; ED25519_PUBLIC_KEY_LEN] = keypair
82        .ed25519_pub
83        .as_slice()
84        .try_into()
85        .context("ed25519 subject key must be 32 bytes")?;
86    let ed_vk = VerifyingKey::from_bytes(&ed_bytes)
87        .context("declared ed25519 subject key is not a valid point")?;
88    let pq_vk = ml_dsa_vk_from_bytes(&keypair.mldsa65_pub)
89        .context("declared ML-DSA-65 subject key is invalid")?;
90    Ok((ed_vk, pq_vk))
91}
92
93/// Sign `payload` under the pinned-Hybrid composite path, binding `context`.
94///
95/// R4: the sole `sign_composite` call site — always `Some(pq_sk)`, never the
96/// classical-only production.
97fn sign_record(
98    payload: &[u8],
99    context: &str,
100    ed_sk: &SigningKey,
101    pq_sk: &MlDsaSigningKey,
102) -> Result<CoseCompositeSignature> {
103    let protected = context_protected_header(context);
104    // GATE 2 / R4: Hybrid pinned — pq_sk is mandatory, so the composite always
105    // carries the outer ML-DSA-65 layer. `sign_composite` is never invoked with
106    // `pq_sk = None` from at9p code.
107    let composite = sign_composite(ed_sk, Some(pq_sk), payload, &protected)
108        .context("at9p composite signing failed")?;
109
110    let (ed_sig, pq_sig) = split_composite(&composite)?;
111    let pq_sig = pq_sig
112        .ok_or_else(|| anyhow::anyhow!("at9p composite signing produced no ML-DSA-65 layer"))?;
113
114    CoseCompositeSignature::new(context, protected, ed_sig, pq_sig)
115}
116
117/// Verify a decomposed at9p composite signature under PINNED Hybrid policy.
118///
119/// Enforces (independent of node `CryptoPolicy`):
120/// 1. the stored context matches `expected_context` (R8/A18);
121/// 2. the stored protected header matches the canonical binding for that
122///    context (defense in depth);
123/// 3. BOTH the inner EdDSA and outer ML-DSA-65 layers verify against the
124///    anchored keys over `payload` (`require_pq = true`).
125fn verify_record(
126    payload: &[u8],
127    sig: &CoseCompositeSignature,
128    expected_context: &str,
129    ed_vk: &VerifyingKey,
130    pq_vk: &MlDsaVerifyingKey,
131) -> Result<()> {
132    // R8/A18: the context string is CHECKED, not decorative.
133    ensure!(
134        sig.context == expected_context,
135        "at9p signature context mismatch: expected {expected_context:?}, got {:?}",
136        sig.context
137    );
138
139    // The external_aad is derived from the EXPECTED record type, not from the
140    // attacker-controlled stored bytes: a signature minted under a different
141    // context reconstructs a different aad and fails the crypto check below,
142    // even if its `context`/`protected` fields were rewritten.
143    let expected_protected = context_protected_header(expected_context);
144    ensure!(
145        sig.protected == expected_protected,
146        "at9p signature protected header does not match the canonical binding for {expected_context:?}"
147    );
148
149    // Reassemble the nested composite from the decomposed raw signatures. The
150    // kids are the anchored public keys; the protected headers are rebuilt
151    // deterministically, so the inner→outer binding round-trips exactly.
152    let ed_kid = ed_vk.to_bytes().to_vec();
153    let pq_kid = ml_dsa_vk_bytes(pq_vk);
154    let composite = assemble_composite_nested(
155        (ed_kid, sig.ed25519_signature.clone()),
156        Some((pq_kid, sig.mldsa65_signature.clone())),
157    )
158    .context("failed to reassemble at9p composite for verification")?;
159
160    // GATE 2: Hybrid PINNED — require_pq = true, always. A stripped or
161    // classical-only composite fails closed regardless of node policy.
162    let verified = verify_composite(
163        &composite,
164        ed_vk,
165        Some(pq_vk),
166        payload,
167        &expected_protected,
168        /* require_pq = */ true,
169    )
170    .context("at9p composite verification failed")?;
171
172    // Belt-and-suspenders: verify_composite already fails closed when either
173    // layer is missing under require_pq, but assert the invariant explicitly.
174    ensure!(
175        verified.eddsa && verified.ml_dsa,
176        "at9p verification did not confirm both composite layers (eddsa={}, ml_dsa={})",
177        verified.eddsa,
178        verified.ml_dsa
179    );
180    Ok(())
181}
182
183/// An Ed25519 capsule signer whose secret half may live outside the process.
184///
185/// The deployment-authority ceremony keeps its classical leg in a YubiKey PIV
186/// slot, so the inner EdDSA layer cannot be produced from an in-process
187/// [`SigningKey`]. Implementors sign the inner COSE layer's detached
188/// to-be-signed bytes out-of-band and return the raw 64-byte signature; the
189/// ML-DSA-65 leg is still an in-process key, so GATE 2 (hybrid PINNED) is
190/// unchanged — this trait only relocates the classical half.
191pub trait CapsuleEd25519Signer {
192    /// The public half the capsule publishes as its subject key.
193    fn verifying_key(&self) -> VerifyingKey;
194
195    /// Sign the inner EdDSA layer's detached to-be-signed bytes.
196    fn sign_detached(&self, tbs: &[u8]) -> Result<[u8; 64]>;
197}
198
199impl CapsuleEd25519Signer for SigningKey {
200    fn verifying_key(&self) -> VerifyingKey {
201        SigningKey::verifying_key(self)
202    }
203
204    fn sign_detached(&self, tbs: &[u8]) -> Result<[u8; 64]> {
205        use ed25519_dalek::Signer as _;
206        Ok(self.sign(tbs).to_bytes())
207    }
208}
209
210/// Sign `payload` under the pinned-Hybrid composite path with an out-of-band
211/// classical signer, binding `context`.
212///
213/// Layer-for-layer equivalent to [`sign_record`]: the inner EdDSA to-be-signed
214/// bytes come from [`inner_tbs`] with `hybrid = true` (the same
215/// `layer_aad` binding `sign_composite` applies), and the outer ML-DSA-65 layer
216/// signs `payload ‖ inner_signature` via [`outer_tbs`]. The outer key is still
217/// mandatory, so there is no classical-only production here either (R4).
218fn sign_record_detached(
219    payload: &[u8],
220    context: &str,
221    ed: &dyn CapsuleEd25519Signer,
222    pq_sk: &MlDsaSigningKey,
223) -> Result<CoseCompositeSignature> {
224    let protected = context_protected_header(context);
225    let ed_kid = ed.verifying_key().to_bytes().to_vec();
226    let ed_sig = ed.sign_detached(&inner_tbs(ed_kid.clone(), payload, &protected, true))?;
227    let pq_kid = ml_dsa_sk_to_vk_bytes(pq_sk);
228    let pq_sig = ml_dsa_sign(
229        pq_sk,
230        &outer_tbs(pq_kid.clone(), payload, &ed_sig, &protected),
231    );
232    // Round-trip through the canonical composite encoding so the decomposed
233    // signatures stored on the record are exactly what the assembled nested
234    // composite carries — the shape `verify_record` will rebuild.
235    let composite = assemble_composite_nested((ed_kid, ed_sig.to_vec()), Some((pq_kid, pq_sig)))
236        .context("at9p detached composite assembly failed")?;
237    let (ed_sig, pq_sig) = split_composite(&composite)?;
238    let pq_sig = pq_sig
239        .ok_or_else(|| anyhow::anyhow!("at9p detached signing produced no ML-DSA-65 layer"))?;
240    CoseCompositeSignature::new(context, protected, ed_sig, pq_sig)
241}
242
243/// Sign a capsule body with one of its subject keys, producing a fully-signed
244/// [`Capsule`]. Self-certifying: the signing keys MUST match **some** published
245/// `body.subject_keys` entry (an atomic Ed25519↔ML-DSA-65 pair), not a
246/// positional "primary" — `subjectKeys` is a set (#1188 / #1183).
247pub fn sign_capsule(
248    body: CapsuleBody,
249    ed_sk: &SigningKey,
250    pq_sk: &MlDsaSigningKey,
251) -> Result<Capsule> {
252    sign_capsule_detached(body, ed_sk, pq_sk)
253}
254
255/// [`sign_capsule`] for an authority whose Ed25519 leg signs out-of-band
256/// (YubiKey PIV, KMS). Applies the identical subject-key self-certification
257/// checks and the identical pinned-Hybrid composite construction.
258pub fn sign_capsule_detached(
259    body: CapsuleBody,
260    ed: &dyn CapsuleEd25519Signer,
261    pq_sk: &MlDsaSigningKey,
262) -> Result<Capsule> {
263    body.validate()?;
264    // Select the subject key the signer claims to be by its Ed25519 identity,
265    // then require the ML-DSA-65 half to match the SAME entry — the atomic hybrid
266    // binding. This admits any published key as the self-cert signer while
267    // forbidding a mismatched cross-pair.
268    let signer_ed = ed.verifying_key().to_bytes();
269    let entry = body.subject_key_for_ed25519(&signer_ed).ok_or_else(|| {
270        anyhow::anyhow!("signing ed25519 key is not a published capsule subject key")
271    })?;
272    ensure!(
273        entry.mldsa65_pub == ml_dsa_sk_to_vk_bytes(pq_sk),
274        "signing ML-DSA-65 key does not match the atomically-bound subject key"
275    );
276
277    let payload = body.to_dag_cbor()?;
278    let signatures = sign_record_detached(&payload, CAPSULE_SIGNATURE_CONTEXT, ed, pq_sk)?;
279    Capsule::new(body, signatures)
280}
281
282/// Verify a genesis/self-certifying [`Capsule`]: the composite signature must
283/// verify (pinned Hybrid) against **some** published subject key.
284///
285/// `subjectKeys` is a published set (#1188 / #1183), so which member signed the
286/// self-certifying capsule is not positional. Try each published subject key and
287/// accept the capsule iff its composite signature verifies under one of them —
288/// the "try each candidate" rule for a set with no wire-level selector. A capsule
289/// signed by a key it does not publish, or signed by none, fails closed.
290pub fn verify_capsule(capsule: &Capsule) -> Result<()> {
291    capsule.body.validate()?;
292    let payload = capsule.body.to_dag_cbor()?;
293    let mut last_err = None;
294    for subject in &capsule.body.subject_keys {
295        let (ed_vk, pq_vk) = match verifying_keys(subject) {
296            Ok(keys) => keys,
297            Err(e) => {
298                last_err = Some(e);
299                continue;
300            }
301        };
302        match verify_record(
303            &payload,
304            &capsule.signatures,
305            CAPSULE_SIGNATURE_CONTEXT,
306            &ed_vk,
307            &pq_vk,
308        ) {
309            Ok(()) => return Ok(()),
310            Err(e) => last_err = Some(e),
311        }
312    }
313    Err(last_err.unwrap_or_else(|| {
314        anyhow::anyhow!("capsule self-signature verified under no published subject key")
315    }))
316}
317
318/// Sign an update-record's content with the authorizing hybrid keypair,
319/// producing a fully-signed [`UpdateRecord`].
320///
321/// The signature covers everything except the `signatures` field. Which key is
322/// *authorized* to sign a rotation (the pre-rotation subject key) is the
323/// rotation-chain gate's concern (#884); this function only mints the
324/// pinned-Hybrid, context-bound signature over the supplied content.
325#[allow(clippy::too_many_arguments)]
326pub fn sign_update_record(
327    subject_cid512: String,
328    epoch: u64,
329    prev_record_digest: [u8; crate::at9p::H512_LEN],
330    new_capsule_body: CapsuleBody,
331    expires_at: String,
332    ed_sk: &SigningKey,
333    pq_sk: &MlDsaSigningKey,
334) -> Result<UpdateRecord> {
335    new_capsule_body.validate()?;
336    // Placeholder signature so we can build the record and compute its
337    // canonical signable bytes; it is replaced by the real signature below.
338    let placeholder = CoseCompositeSignature::new(
339        UPDATE_SIGNATURE_CONTEXT,
340        context_protected_header(UPDATE_SIGNATURE_CONTEXT),
341        vec![0u8; crate::at9p::ED25519_SIGNATURE_LEN],
342        vec![0u8; crate::at9p::ML_DSA65_SIGNATURE_LEN],
343    )?;
344    let mut record = UpdateRecord {
345        subject_cid512,
346        epoch,
347        prev_record_digest,
348        new_capsule_body,
349        expires_at,
350        signatures: placeholder,
351    };
352    let payload = record.signable_bytes()?;
353    record.signatures = sign_record(&payload, UPDATE_SIGNATURE_CONTEXT, ed_sk, pq_sk)?;
354    // Round-trip through the canonical codec to enforce every schema gate.
355    UpdateRecord::from_dag_cbor(&record.to_dag_cbor()?)
356}
357
358/// Verify an [`UpdateRecord`] under PINNED Hybrid policy against the authorizing
359/// `signer` keypair. The caller (rotation-chain validator, #884) decides which
360/// key is authorized; this function enforces the crypto + context binding.
361pub fn verify_update_record(record: &UpdateRecord, signer: &HybridKeyPair) -> Result<()> {
362    let (ed_vk, pq_vk) = verifying_keys(signer)?;
363    let payload = record.signable_bytes()?;
364    verify_record(
365        &payload,
366        &record.signatures,
367        UPDATE_SIGNATURE_CONTEXT,
368        &ed_vk,
369        &pq_vk,
370    )
371}
372
373#[cfg(test)]
374#[allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
375mod tests {
376    use super::*;
377    use crate::at9p::{
378        ServiceEndpoint, ServiceEntry, ServiceType, Transport, ML_DSA65_SIGNATURE_LEN,
379    };
380    use ed25519_dalek::SigningKey;
381    use hyprstream_crypto::pq::ml_dsa_generate_keypair;
382    use rand::rngs::OsRng;
383
384    struct Signer {
385        ed_sk: SigningKey,
386        pq_sk: MlDsaSigningKey,
387        keypair: HybridKeyPair,
388    }
389
390    fn signer() -> Signer {
391        let ed_sk = SigningKey::generate(&mut OsRng);
392        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
393        let keypair = HybridKeyPair::new(
394            ed_sk.verifying_key().to_bytes().to_vec(),
395            ml_dsa_vk_bytes(&pq_vk),
396        )
397        .unwrap();
398        Signer {
399            ed_sk,
400            pq_sk,
401            keypair,
402        }
403    }
404
405    fn capsule_body(keypair: HybridKeyPair) -> CapsuleBody {
406        let endpoint = ServiceEndpoint::new(Transport::Iroh, "iroh://node0").unwrap();
407        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
408        CapsuleBody::new(vec![keypair], vec![service]).unwrap()
409    }
410
411    fn signed_capsule() -> (Signer, Capsule) {
412        let s = signer();
413        let body = capsule_body(s.keypair.clone());
414        let capsule = sign_capsule(body, &s.ed_sk, &s.pq_sk).unwrap();
415        (s, capsule)
416    }
417
418    fn signed_update(s: &Signer) -> UpdateRecord {
419        let body = capsule_body(s.keypair.clone());
420        let subject_cid512 = Capsule::new(
421            body.clone(),
422            // any valid-shaped signature just to derive a cid for the field
423            sign_record(
424                &body.to_dag_cbor().unwrap(),
425                CAPSULE_SIGNATURE_CONTEXT,
426                &s.ed_sk,
427                &s.pq_sk,
428            )
429            .unwrap(),
430        )
431        .unwrap()
432        .cid512()
433        .unwrap();
434        sign_update_record(
435            subject_cid512,
436            7,
437            [9u8; crate::at9p::H512_LEN],
438            body,
439            "2026-07-09T00:00:00Z".to_owned(),
440            &s.ed_sk,
441            &s.pq_sk,
442        )
443        .unwrap()
444    }
445
446    #[test]
447    fn capsule_sign_verify_round_trip() {
448        let (_s, capsule) = signed_capsule();
449        verify_capsule(&capsule).expect("capsule must verify");
450        // Survives a canonical encode/decode round-trip.
451        let bytes = capsule.to_dag_cbor().unwrap();
452        let decoded = Capsule::from_dag_cbor(&bytes).unwrap();
453        verify_capsule(&decoded).expect("decoded capsule must verify");
454    }
455
456    #[test]
457    fn update_record_sign_verify_round_trip() {
458        let s = signer();
459        let record = signed_update(&s);
460        verify_update_record(&record, &s.keypair).expect("update must verify");
461        let bytes = record.to_dag_cbor().unwrap();
462        let decoded = UpdateRecord::from_dag_cbor(&bytes).unwrap();
463        verify_update_record(&decoded, &s.keypair).expect("decoded update must verify");
464    }
465
466    /// A18/R8: a capsule signature replayed as an update signature (and vice
467    /// versa) is rejected — the context binding differs.
468    #[test]
469    fn cross_type_replay_rejected() {
470        let (s, capsule) = signed_capsule();
471        // Take the capsule's valid composite and try to pass it off as an
472        // update signature over the same body bytes.
473        let mut forged = capsule.signatures.clone();
474        // Rewrite the fields to claim it is an update signature; the crypto aad
475        // for the update context won't match, so it must still fail.
476        forged.context = UPDATE_SIGNATURE_CONTEXT.to_owned();
477        forged.protected = context_protected_header(UPDATE_SIGNATURE_CONTEXT);
478        let (ed_vk, pq_vk) = verifying_keys(&s.keypair).unwrap();
479        let res = verify_record(
480            &capsule.body.to_dag_cbor().unwrap(),
481            &forged,
482            UPDATE_SIGNATURE_CONTEXT,
483            &ed_vk,
484            &pq_vk,
485        );
486        assert!(
487            res.is_err(),
488            "cross-context signature reuse must be rejected"
489        );
490
491        // And verifying the genuine capsule signature while EXPECTING the update
492        // context is rejected too.
493        let res2 = verify_record(
494            &capsule.body.to_dag_cbor().unwrap(),
495            &capsule.signatures,
496            UPDATE_SIGNATURE_CONTEXT,
497            &ed_vk,
498            &pq_vk,
499        );
500        assert!(res2.is_err(), "wrong expected context must be rejected");
501    }
502
503    /// A19/R4: a classical-only (Ed25519-only) capsule is rejected even under a
504    /// node configured `Classical`. There is no node-policy input to
505    /// `verify_capsule` at all — Hybrid is pinned — so we prove it by crafting a
506    /// classical-only composite and confirming it cannot verify.
507    #[test]
508    fn classical_only_signature_rejected_under_classical_policy() {
509        let s = signer();
510        let body = capsule_body(s.keypair.clone());
511        let payload = body.to_dag_cbor().unwrap();
512        let protected = context_protected_header(CAPSULE_SIGNATURE_CONTEXT);
513
514        // Directly emit a CLASSICAL-only composite (pq_sk = None) — the exact
515        // thing R4 forbids in at9p code, done here only to prove verification
516        // rejects it. Extract the EdDSA sig; there is no ML-DSA layer, so we
517        // cannot even construct a schema-valid CoseCompositeSignature (which
518        // requires a 3309-byte ML-DSA sig). Substitute a bogus ML-DSA sig of the
519        // right LENGTH to get past the schema and prove the CRYPTO gate rejects.
520        let classical = sign_composite(&s.ed_sk, None, &payload, &protected).unwrap();
521        let (ed_sig, pq_sig) = split_composite(&classical).unwrap();
522        assert!(pq_sig.is_none(), "classical composite has no ML-DSA layer");
523
524        let forged = CoseCompositeSignature::new(
525            CAPSULE_SIGNATURE_CONTEXT,
526            protected,
527            ed_sig,
528            vec![0u8; ML_DSA65_SIGNATURE_LEN],
529        )
530        .unwrap();
531        let capsule = Capsule::new(body, forged).unwrap();
532
533        // verify_capsule pins Hybrid: the bogus ML-DSA layer cannot verify.
534        let res = verify_capsule(&capsule);
535        assert!(
536            res.is_err(),
537            "classical-only / missing-PQ capsule must be rejected under pinned Hybrid"
538        );
539    }
540
541    /// Tampering the signed body invalidates the signature.
542    #[test]
543    fn tampered_payload_rejected() {
544        let (s, capsule) = signed_capsule();
545        let (ed_vk, pq_vk) = verifying_keys(&s.keypair).unwrap();
546        let mut tampered = capsule.body.to_dag_cbor().unwrap();
547        // Flip a byte in the payload.
548        let last = tampered.len() - 1;
549        tampered[last] ^= 0x01;
550        let res = verify_record(
551            &tampered,
552            &capsule.signatures,
553            CAPSULE_SIGNATURE_CONTEXT,
554            &ed_vk,
555            &pq_vk,
556        );
557        assert!(res.is_err(), "tampered payload must fail verification");
558    }
559
560    /// A signature verifies only against the key it was minted with; a
561    /// different subject key is rejected.
562    #[test]
563    fn wrong_key_rejected() {
564        let (_s, capsule) = signed_capsule();
565        let other = signer();
566        let res = verify_update_record(
567            &UpdateRecord {
568                subject_cid512: capsule.cid512().unwrap(),
569                epoch: 0,
570                prev_record_digest: [0u8; crate::at9p::H512_LEN],
571                new_capsule_body: capsule.body.clone(),
572                expires_at: "2026-07-09T00:00:00Z".to_owned(),
573                signatures: capsule.signatures.clone(),
574            },
575            &other.keypair,
576        );
577        assert!(res.is_err(), "verification under the wrong key must fail");
578    }
579
580    /// The API forbids classical-only signing by construction: `sign_capsule`
581    /// requires a `&MlDsaSigningKey`, so a valid capsule always carries a
582    /// verifiable ML-DSA-65 layer. This asserts the produced signature has a
583    /// real (non-zero, correct-length) PQ component that verifies.
584    #[test]
585    fn signing_always_hybrid() {
586        let (_s, capsule) = signed_capsule();
587        assert_eq!(
588            capsule.signatures.mldsa65_signature.len(),
589            ML_DSA65_SIGNATURE_LEN
590        );
591        assert!(
592            capsule.signatures.mldsa65_signature.iter().any(|&b| b != 0),
593            "ML-DSA-65 signature must be a real signature, not a placeholder"
594        );
595        verify_capsule(&capsule).unwrap();
596    }
597
598    // ── #1188 / #1183: subjectKeys is a published SET. A self-certifying capsule
599    //    may be signed by ANY published subject key, not positionally the first.
600    //    These FAIL against the pre-fix `subject_keys.first()` signer rule. ─────
601
602    fn two_key_body(first: &Signer, second: &Signer) -> CapsuleBody {
603        let endpoint = ServiceEndpoint::new(Transport::Iroh, "iroh://node0").unwrap();
604        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
605        CapsuleBody::new(
606            vec![first.keypair.clone(), second.keypair.clone()],
607            vec![service],
608        )
609        .unwrap()
610    }
611
612    /// Overlap/hybrid: a capsule publishes two subject keys and is signed by the
613    /// SECOND one. `sign_capsule` must accept any published key as the self-cert
614    /// signer, and `verify_capsule` must accept by trying each. The pre-fix code
615    /// required the signer to equal `subject_keys[0]`, so signing failed outright.
616    #[test]
617    fn capsule_signed_by_non_first_subject_key_verifies() {
618        let (k1, k2) = (signer(), signer());
619        let body = two_key_body(&k1, &k2);
620        // Sign with the SECOND published key.
621        let capsule = sign_capsule(body, &k2.ed_sk, &k2.pq_sk)
622            .expect("any published subject key may self-certify the capsule");
623        verify_capsule(&capsule).expect("capsule signed by a published key must verify");
624        // Round-trips through canonical bytes.
625        let decoded = Capsule::from_dag_cbor(&capsule.to_dag_cbor().unwrap()).unwrap();
626        verify_capsule(&decoded).expect("decoded two-key capsule must verify");
627    }
628
629    /// A capsule signed by a key it does NOT publish is rejected — set semantics
630    /// widens *which published key* may sign, never admits an unpublished one.
631    #[test]
632    fn capsule_signed_by_unpublished_key_rejected() {
633        let (k1, k2, outsider) = (signer(), signer(), signer());
634        let body = two_key_body(&k1, &k2);
635        // The body legitimately publishes k1,k2; forge a signature by `outsider`
636        // over the same bytes, then splice it in so schema still passes.
637        let capsule = sign_capsule(body.clone(), &k1.ed_sk, &k1.pq_sk).unwrap();
638        let payload = capsule.body.to_dag_cbor().unwrap();
639        let forged = sign_record(
640            &payload,
641            CAPSULE_SIGNATURE_CONTEXT,
642            &outsider.ed_sk,
643            &outsider.pq_sk,
644        )
645        .unwrap();
646        let spliced = Capsule::new(capsule.body, forged).unwrap();
647        assert!(
648            verify_capsule(&spliced).is_err(),
649            "a capsule signed by an unpublished key must fail closed"
650        );
651    }
652
653    /// The schema rejects an ambiguous subject key SET: a repeated Ed25519 half
654    /// across pairs would make application-signer selection ambiguous (#1188).
655    #[test]
656    fn duplicate_ed25519_subject_key_rejected() {
657        let k = signer();
658        let endpoint = ServiceEndpoint::new(Transport::Iroh, "iroh://node0").unwrap();
659        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
660        let err = CapsuleBody::new(vec![k.keypair.clone(), k.keypair.clone()], vec![service])
661            .expect_err("a duplicate subject key must be rejected");
662        assert!(
663            err.to_string().contains("subjectKeys") || err.to_string().contains("subject"),
664            "unexpected error: {err}"
665        );
666    }
667}