Skip to main content

hyprstream_pds/
at9p_gate.rs

1//! GATE verification pipeline for `did:at9p` genesis capsules (#884, design
2//! #879 §5.6).
3//!
4//! Given the claimed self-certifying identifier `did:at9p:<cid512>` and the raw
5//! bytes fetched for it from some untrusted locator, this module decides — as a
6//! **pure, I/O-free, synchronous** function — whether those bytes are the
7//! genuine capsule that identifier names. It composes three gates, in a fixed
8//! order:
9//!
10//! 1. **canon-gate** (R3 / A16) — decode the bytes with the strict deterministic
11//!    DAG-CBOR codec and require `reserialize(decode(bytes)) == bytes`. Non-
12//!    canonical encodings are *rejected*, never normalized, so no two byte
13//!    strings can present as "the same" capsule. [`Capsule::from_dag_cbor`]
14//!    already enforces this round-trip plus every schema gate.
15//! 2. **hash-gate** (A1 / A16) — recompute the BLAKE3-512 CID512 over the
16//!    canonical bytes and require it to equal the claimed `cid512`. This is the
17//!    self-certification binding: **the identity *is* the hash of the capsule**,
18//!    so a capsule whose bytes do not hash to the claimed identifier is rejected
19//!    even when its own self-signature is perfectly valid (A1: forging a capsule
20//!    for a known cid512 is a BLAKE3-512 second-preimage, infeasible).
21//! 3. **sig-gate** (§4.4 / R4 / A19) — composite-verify via [`verify_capsule`],
22//!    which pins Hybrid (EdDSA **and** ML-DSA-65) independent of node
23//!    `CryptoPolicy` and checks the per-record COSE context string.
24//!
25//! # Why this order (cheapest-first, and each gate depends on the prior)
26//!
27//! - **canon before hash.** The hash is only meaningful over *canonical* bytes:
28//!   without the canonical check first, an attacker could serve a non-canonical
29//!   re-encoding of a legitimate capsule whose hash differs, or (worse) rely on
30//!   decoder laxity. canon-gate is also the cheapest — one decode + one
31//!   re-encode + a `memcmp`.
32//! - **hash before sig.** The composite verification (ML-DSA-65) is by far the
33//!   most expensive step; the hash comparison is a single BLAKE3 pass. Rejecting
34//!   an identity mismatch before touching the signature avoids spending a PQ
35//!   verify on bytes that cannot possibly be the requested capsule. More
36//!   importantly, hash-gate establishes *which identity* these bytes claim to
37//!   be; sig-gate then confirms the capsule's own keys signed it. A valid self-
38//!   signature over the *wrong* cid must still be rejected (see the tests), and
39//!   ordering hash before sig makes that structural.
40//!
41//! The pipeline returns a [`VerifiedCapsule`] — a witness that all three gates
42//! passed, constructible only here — or a [`GateError`] naming the gate that
43//! rejected the input.
44
45use std::fmt;
46
47use hyprstream_rpc::cid::{decode_cid, encode_cid, Codec, HashAlgo};
48
49use crate::at9p::{at9p_capsule_cid512, Capsule, H512_LEN};
50use crate::at9p_sign::verify_capsule;
51
52/// The `did:at9p:` method prefix. A `did:at9p` identifier is exactly this prefix
53/// followed by the base32 CIDv1 (`cid512`) of the genesis capsule.
54///
55/// Re-exported from the single source of truth (`hyprstream_rpc::identity`), shared
56/// with the admission gate and `Did::is_did_at9p`, so the literal cannot drift
57/// across arms (#964). Kept at this path for the existing pds/discovery import sites.
58pub use hyprstream_rpc::identity::DID_AT9P_PREFIX;
59
60/// Which gate of the [`verify_genesis_capsule`] pipeline rejected the input.
61///
62/// The variants are ordered as the pipeline evaluates them; each names the gate
63/// so a caller (or audit record) can distinguish "these bytes are malformed"
64/// from "these bytes are not the capsule you asked for" from "these bytes are
65/// the right shape and identity but are not authentically signed".
66#[derive(Debug)]
67pub enum GateError {
68    /// The claimed identifier was not a well-formed at9p `cid512`
69    /// (`did:at9p:<cid512>`): wrong multibase, wrong multicodec, or not a
70    /// BLAKE3-512 multihash. Checked before any capsule bytes are examined so
71    /// the hash-gate always compares against a real cid512.
72    ClaimedId(anyhow::Error),
73    /// canon-gate (R3/A16): the bytes did not decode as a canonical,
74    /// schema-valid capsule — either the DAG-CBOR was malformed, non-canonical
75    /// (`reserialize(decode(bytes)) != bytes`), or violated a capsule schema
76    /// invariant.
77    Canon(anyhow::Error),
78    /// hash-gate (A1/A16): `BLAKE3-512(canonical bytes)` did not equal the
79    /// claimed `cid512`. The bytes are a well-formed capsule, but not the one
80    /// this identity names.
81    Hash {
82        /// The identifier the caller asked to verify (canonicalized).
83        claimed: String,
84        /// The identifier the supplied bytes actually hash to.
85        computed: String,
86    },
87    /// sig-gate (§4.4/R4/A19): composite verification failed under pinned
88    /// Hybrid — a missing/invalid EdDSA or ML-DSA-65 layer, a context-string
89    /// mismatch, or a signature that does not verify against the capsule's own
90    /// primary subject key.
91    Sig(anyhow::Error),
92}
93
94impl fmt::Display for GateError {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        match self {
97            Self::ClaimedId(e) => write!(f, "claimed-id gate: malformed did:at9p cid512: {e}"),
98            Self::Canon(e) => write!(f, "canon-gate: {e}"),
99            Self::Hash { claimed, computed } => write!(
100                f,
101                "hash-gate: capsule bytes hash to {computed}, not the claimed {claimed}"
102            ),
103            Self::Sig(e) => write!(f, "sig-gate: {e}"),
104        }
105    }
106}
107
108impl std::error::Error for GateError {
109    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
110        match self {
111            Self::ClaimedId(e) | Self::Canon(e) | Self::Sig(e) => Some(e.as_ref()),
112            Self::Hash { .. } => None,
113        }
114    }
115}
116
117/// A capsule that has passed the full canon → hash → sig GATE pipeline for a
118/// specific claimed `cid512`.
119///
120/// The only constructor is [`verify_genesis_capsule`], so holding a
121/// `VerifiedCapsule` is proof that: the bytes were canonical (R3), they hash to
122/// [`Self::cid512`] (self-certification), and the capsule's own primary subject
123/// key composite-signed them under pinned Hybrid (§4.4). Downstream authority
124/// (keys, endpoints, label *hints*, delegations) may be read from
125/// [`Self::capsule`] without re-checking the binding.
126#[derive(Clone, Debug, Eq, PartialEq)]
127pub struct VerifiedCapsule {
128    cid512: String,
129    capsule: Capsule,
130}
131
132impl VerifiedCapsule {
133    /// The verified `cid512` — the BLAKE3-512 self-certifying identifier these
134    /// bytes hash to (canonical form).
135    pub fn cid512(&self) -> &str {
136        &self.cid512
137    }
138
139    /// The full `did:at9p:<cid512>` identifier for the verified capsule.
140    pub fn did(&self) -> String {
141        format!("{DID_AT9P_PREFIX}{}", self.cid512)
142    }
143
144    /// The verified capsule.
145    pub fn capsule(&self) -> &Capsule {
146        &self.capsule
147    }
148
149    /// Consume the witness, yielding the verified capsule.
150    pub fn into_capsule(self) -> Capsule {
151        self.capsule
152    }
153}
154
155/// Verify that `capsule_bytes` are the genuine genesis capsule named by the
156/// claimed `did:at9p:<did_body>` identifier, where `did_body` is the bare
157/// `cid512` (no `did:at9p:` prefix).
158///
159/// Pure and I/O-free: no network, no filesystem, no async, no clock. The caller
160/// is responsible for having *fetched* the bytes for this identifier from
161/// whatever (untrusted) locator; this function decides whether to *accept*
162/// them.
163///
164/// Returns a [`VerifiedCapsule`] witness, or a [`GateError`] naming the gate
165/// that rejected the input. Gates run in order canon → hash → sig; a later gate
166/// is never reached if an earlier one fails.
167pub fn verify_genesis_capsule(
168    claimed_cid512: &str,
169    capsule_bytes: &[u8],
170) -> Result<VerifiedCapsule, GateError> {
171    // Pre-gate: the claimed identifier must be a well-formed at9p cid512 before
172    // we can meaningfully compare a computed hash against it. This is cheap and
173    // never touches the (attacker-controlled) capsule bytes.
174    let claimed = canonical_cid512(claimed_cid512).map_err(GateError::ClaimedId)?;
175
176    // GATE 1 — canon (R3 / A16): decode canonically or reject. `from_dag_cbor`
177    // requires `decode(bytes).encode() == bytes` and runs every schema gate,
178    // including PR #937's strict decoder hardening (depth limit, string-only map
179    // keys). A16 is defeated here: no non-canonical re-encoding survives.
180    let capsule = Capsule::from_dag_cbor(capsule_bytes).map_err(GateError::Canon)?;
181
182    // GATE 2 — hash (A1 / A16): recompute the self-certifying cid over the
183    // canonical bytes and bind it to the claimed identity. canon-gate proved the
184    // input is canonical, so hashing the input bytes is exactly hashing the
185    // canonical form. Forging a capsule for a fixed cid512 is a BLAKE3-512
186    // second-preimage (A1) — infeasible — so a match means these are *the* bytes
187    // the identity commits to.
188    let computed = at9p_capsule_cid512(capsule_bytes).map_err(GateError::Canon)?;
189    if computed != claimed {
190        return Err(GateError::Hash { claimed, computed });
191    }
192
193    // GATE 3 — sig (§4.4 / R4 / A19): composite verify, Hybrid pinned, per-record
194    // COSE context checked. A valid self-signature over the *wrong* identity was
195    // already rejected at hash-gate; this confirms the correctly-identified bytes
196    // are also authentically signed by the capsule's own primary subject key.
197    verify_capsule(&capsule).map_err(GateError::Sig)?;
198
199    Ok(VerifiedCapsule {
200        cid512: computed,
201        capsule,
202    })
203}
204
205/// Verify a full `did:at9p:<cid512>` identifier against fetched capsule bytes.
206///
207/// Convenience wrapper over [`verify_genesis_capsule`] that strips the
208/// `did:at9p:` method prefix. Same purity guarantees.
209pub fn verify_did_at9p(did: &str, capsule_bytes: &[u8]) -> Result<VerifiedCapsule, GateError> {
210    let cid512 = did.strip_prefix(DID_AT9P_PREFIX).ok_or_else(|| {
211        GateError::ClaimedId(anyhow::anyhow!("identifier is not a did:at9p DID: {did:?}"))
212    })?;
213    verify_genesis_capsule(cid512, capsule_bytes)
214}
215
216/// Validate that `s` is a well-formed at9p `cid512` and return its canonical
217/// string form.
218///
219/// Enforces the at9p-capsule multicodec and a BLAKE3-512 (64-byte) multihash,
220/// then re-encodes from the decoded digest so the returned value is the exact
221/// canonical CIDv1 string [`at9p_capsule_cid512`] produces. Both sides of the
222/// hash-gate comparison are therefore canonical, so a byte-exact `==` is a
223/// faithful digest comparison (no case/representation skew).
224fn canonical_cid512(s: &str) -> anyhow::Result<String> {
225    let cid = decode_cid(s)?;
226    anyhow::ensure!(
227        cid.codec == Codec::At9pCapsule,
228        "cid512 must use the at9p-capsule multicodec"
229    );
230    anyhow::ensure!(
231        cid.multihash.algo == HashAlgo::Blake3 && cid.multihash.digest.len() == H512_LEN,
232        "cid512 must be a BLAKE3-512 (64-byte) multihash"
233    );
234    encode_cid(Codec::At9pCapsule, HashAlgo::Blake3, &cid.multihash.digest)
235}
236
237#[cfg(test)]
238#[allow(
239    clippy::unwrap_used,
240    clippy::expect_used,
241    clippy::indexing_slicing,
242    clippy::panic
243)]
244mod tests {
245    use ed25519_dalek::SigningKey;
246    use hyprstream_crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes, MlDsaSigningKey};
247    use proptest::prelude::*;
248
249    use super::*;
250    use crate::at9p::{
251        Capsule, CapsuleBody, HybridKeyPair, ServiceEndpoint, ServiceEntry, ServiceType, Transport,
252        ED25519_SIGNATURE_LEN,
253    };
254    use crate::at9p_sign::sign_capsule;
255    use crate::dag_cbor::DagCbor;
256
257    struct Signer {
258        ed_sk: SigningKey,
259        pq_sk: MlDsaSigningKey,
260        keypair: HybridKeyPair,
261    }
262
263    fn signer(tag: u8) -> Signer {
264        // Deterministic-ish per-tag ed key so distinct tags give distinct DIDs;
265        // ML-DSA key is random (fine — the capsule commits to whatever it holds).
266        let mut seed = [0u8; 32];
267        seed[0] = tag;
268        seed[31] = tag.wrapping_add(7);
269        let ed_sk = SigningKey::from_bytes(&seed);
270        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
271        let keypair = HybridKeyPair::new(
272            ed_sk.verifying_key().to_bytes().to_vec(),
273            ml_dsa_vk_bytes(&pq_vk),
274        )
275        .unwrap();
276        Signer {
277            ed_sk,
278            pq_sk,
279            keypair,
280        }
281    }
282
283    fn body_for(s: &Signer, tag: u8) -> CapsuleBody {
284        let endpoint = ServiceEndpoint::new(Transport::Iroh, format!("iroh://node{tag}")).unwrap();
285        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
286        CapsuleBody::new(vec![s.keypair.clone()], vec![service]).unwrap()
287    }
288
289    /// A fully self-signed capsule, its canonical bytes, and its true cid512.
290    fn signed(tag: u8) -> (Capsule, Vec<u8>, String) {
291        let s = signer(tag);
292        let body = body_for(&s, tag);
293        let capsule = sign_capsule(body, &s.ed_sk, &s.pq_sk).unwrap();
294        let bytes = capsule.to_dag_cbor().unwrap();
295        let cid = capsule.cid512().unwrap();
296        (capsule, bytes, cid)
297    }
298
299    #[test]
300    fn accepts_a_valid_capsule() {
301        let (capsule, bytes, cid) = signed(1);
302        let verified = verify_genesis_capsule(&cid, &bytes).expect("valid capsule must pass");
303        assert_eq!(verified.cid512(), cid);
304        assert_eq!(verified.did(), format!("{DID_AT9P_PREFIX}{cid}"));
305        assert_eq!(verified.capsule(), &capsule);
306    }
307
308    #[test]
309    fn accepts_via_full_did() {
310        let (_capsule, bytes, cid) = signed(2);
311        let did = format!("{DID_AT9P_PREFIX}{cid}");
312        let verified = verify_did_at9p(&did, &bytes).expect("valid did:at9p must pass");
313        assert_eq!(verified.did(), did);
314    }
315
316    #[test]
317    fn rejects_non_did_at9p_identifier() {
318        let (_capsule, bytes, cid) = signed(3);
319        let err = verify_did_at9p(&format!("did:web:{cid}"), &bytes).unwrap_err();
320        assert!(matches!(err, GateError::ClaimedId(_)), "got {err}");
321    }
322
323    #[test]
324    fn rejects_malformed_claimed_cid() {
325        let (_capsule, bytes, _cid) = signed(4);
326        let err = verify_genesis_capsule("not-a-cid", &bytes).unwrap_err();
327        assert!(matches!(err, GateError::ClaimedId(_)), "got {err}");
328    }
329
330    /// A1 / A16: hash-binding. A capsule whose bytes do not hash to the claimed
331    /// cid512 is rejected at hash-gate even though the bytes are perfectly
332    /// canonical AND carry a valid self-signature. The identity IS the hash.
333    #[test]
334    fn valid_self_signed_capsule_under_wrong_cid_rejected() {
335        let (_c1, bytes1, cid1) = signed(10);
336        let (_c2, _bytes2, cid2) = signed(11);
337        assert_ne!(cid1, cid2);
338        // bytes1 is genuinely self-signed and canonical, but we claim it is the
339        // identity cid2. hash-gate must reject before sig-gate ever runs.
340        let err = verify_genesis_capsule(&cid2, &bytes1).unwrap_err();
341        match err {
342            GateError::Hash { claimed, computed } => {
343                assert_eq!(claimed, cid2);
344                assert_eq!(computed, cid1);
345            }
346            other => panic!("expected hash-gate rejection, got {other}"),
347        }
348    }
349
350    /// Wrong CID (a different well-formed at9p cid512) fails hash-gate.
351    #[test]
352    fn wrong_cid_fails_hash_gate() {
353        let (_capsule, bytes, cid) = signed(20);
354        // Flip one digit region of the cid to get a different (but still
355        // structurally valid) at9p cid512.
356        let other = signed(21).2;
357        assert_ne!(cid, other);
358        let err = verify_genesis_capsule(&other, &bytes).unwrap_err();
359        assert!(matches!(err, GateError::Hash { .. }), "got {err}");
360    }
361
362    /// A16 / R3: tampering the bytes fails at canon-gate (non-canonical / schema)
363    /// or hash-gate (canonical but different hash) — never silently accepted.
364    #[test]
365    fn tampered_bytes_fail_canon_or_hash() {
366        let (_capsule, bytes, cid) = signed(30);
367        for i in 0..bytes.len() {
368            let mut t = bytes.clone();
369            t[i] ^= 0x01;
370            if t == bytes {
371                continue;
372            }
373            match verify_genesis_capsule(&cid, &t) {
374                Ok(_) => panic!("tampered byte {i} was accepted"),
375                Err(GateError::Canon(_)) | Err(GateError::Hash { .. }) => {}
376                Err(other) => panic!("tampered byte {i}: unexpected {other}"),
377            }
378        }
379    }
380
381    /// Valid canonical bytes with the correct (recomputed) cid512 but a broken
382    /// signature reach and fail sig-gate. Because the cid commits to the whole
383    /// capsule (signatures included), tampering the signature changes the cid;
384    /// we therefore claim the tampered capsule's *own* recomputed cid so canon
385    /// and hash pass and only sig fails.
386    #[test]
387    fn valid_canon_bad_sig_fails_sig_gate() {
388        let (capsule, _bytes, _cid) = signed(40);
389        // Corrupt the ed25519 signature but keep it schema-valid (same length).
390        let mut broken = capsule.clone();
391        broken.signatures.ed25519_signature = vec![0u8; ED25519_SIGNATURE_LEN];
392        let bytes = broken.to_dag_cbor().unwrap();
393        // The tampered capsule is still canonical & schema-valid.
394        let reparsed = Capsule::from_dag_cbor(&bytes).expect("still canonical");
395        let cid = reparsed.cid512().unwrap();
396        let err = verify_genesis_capsule(&cid, &bytes).unwrap_err();
397        assert!(matches!(err, GateError::Sig(_)), "got {err}");
398    }
399
400    /// Non-canonical bytes (reversed top-level map) fail canon-gate — even when
401    /// they decode to a structurally identical capsule.
402    #[test]
403    fn non_canonical_bytes_fail_canon_gate() {
404        let (_capsule, bytes, cid) = signed(50);
405        let decoded = DagCbor::decode(&bytes).unwrap();
406        let DagCbor::Map(mut pairs) = decoded else {
407            panic!("capsule encodes as a map");
408        };
409        pairs.reverse();
410        let non_canonical = DagCbor::Map(pairs).encode();
411        assert_ne!(non_canonical, bytes);
412        let err = verify_genesis_capsule(&cid, &non_canonical).unwrap_err();
413        assert!(matches!(err, GateError::Canon(_)), "got {err}");
414    }
415
416    /// Garbage bytes fail canon-gate.
417    #[test]
418    fn garbage_bytes_fail_canon_gate() {
419        let (_capsule, _bytes, cid) = signed(60);
420        let err = verify_genesis_capsule(&cid, b"\xff\xff not cbor at all").unwrap_err();
421        assert!(matches!(err, GateError::Canon(_)), "got {err}");
422    }
423
424    proptest! {
425        /// A1: every genuinely self-signed capsule verifies against its own
426        /// cid512, and against NO other capsule's cid512 (hash-binding /
427        /// dedup-domain: distinct bytes ⇒ distinct BLAKE3-512 cid).
428        #[test]
429        fn prop_roundtrip_accepts_self_rejects_others(a in 0u8..40, b in 0u8..40) {
430            let (_ca, bytes_a, cid_a) = signed(a);
431            let (_cb, _bytes_b, cid_b) = signed(b);
432
433            // Accepts its own identity.
434            prop_assert!(verify_genesis_capsule(&cid_a, &bytes_a).is_ok());
435
436            if cid_a != cid_b {
437                // Rejects a different identity at hash-gate.
438                let err = verify_genesis_capsule(&cid_b, &bytes_a).unwrap_err();
439                let is_hash = matches!(err, GateError::Hash { .. });
440                prop_assert!(is_hash);
441            }
442        }
443
444        /// A16 / R3: single-bit flips are never silently accepted.
445        #[test]
446        fn prop_bitflip_never_accepted(tag in 0u8..40, idx in any::<prop::sample::Index>()) {
447            let (_c, bytes, cid) = signed(tag);
448            let i = idx.index(bytes.len());
449            let mut t = bytes.clone();
450            t[i] ^= 0x01;
451            prop_assume!(t != bytes);
452            prop_assert!(verify_genesis_capsule(&cid, &t).is_err());
453        }
454    }
455}