Skip to main content

hyprstream_pds/
at9p_resolver.rs

1//! `hyprstream-pds` implementation of `hyprstream_rpc::identity_resolver::At9pCapsuleResolver`
2//! — the bridge from the A4 GATE pipeline (#884) to the `did:at9p` admission and
3//! resolver arms (D2/#894).
4//!
5//! `hyprstream-rpc` owns the admission gate and the method-dispatched identity
6//! resolver, but the GATE (`canon → hash → sig`) and the capsule schema live here
7//! in `hyprstream-pds` (which depends on rpc, so the dependency does not reverse).
8//! The rpc crate therefore abstracts capsule verification behind the
9//! [`At9pCapsuleResolver`] trait; this module is its real implementation, a thin
10//! wrapper over [`crate::at9p_gate::verify_did_at9p`] that re-expresses the
11//! capsule's content-verified subject keys in the rpc-local key types.
12//!
13//! # Provenance
14//!
15//! A [`VerifiedAt9pKeys`] returned here is only constructable after the full GATE
16//! pipeline passed over canonical bytes whose BLAKE3-512 hash equals the claimed
17//! `cid512` and whose composite signature (pinned Hybrid) verified against the
18//! capsule's own primary subject key. The Ed25519/ML-DSA-65 pair is therefore
19//! **content-verified**, never config-supplied — the D2/#894 provenance boundary.
20
21use anyhow::{anyhow, Result};
22
23use hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes;
24use hyprstream_rpc::identity_resolver::{At9pCapsuleResolver, VerifiedAt9pKeys};
25
26use crate::at9p::ED25519_PUBLIC_KEY_LEN;
27use crate::at9p_gate::verify_did_at9p;
28
29/// The production [`At9pCapsuleResolver`] — the A4 GATE pipeline over a fetched
30/// or peer-presented capsule.
31///
32/// Construct with [`At9pGateResolver::new`]; the locator-backed `resolve` path is
33/// Track C (#890) and returns `Err` until a locator is wired, but
34/// [`verify_bytes`](At9pCapsuleResolver::verify_bytes) — the admission path the
35/// peer presents bytes over — is fully functional today.
36#[derive(Default)]
37pub struct At9pGateResolver;
38
39impl At9pGateResolver {
40    /// Construct the GATE-backed capsule resolver.
41    pub fn new() -> Self {
42        Self
43    }
44}
45
46impl At9pCapsuleResolver for At9pGateResolver {
47    fn verify_bytes(&self, did: &str, capsule_bytes: &[u8]) -> Result<VerifiedAt9pKeys> {
48        // The A4 GATE: canon → hash(H512 == cid512) → sig (pinned Hybrid). Only a
49        // capsule that passes all three gates reaches the Ok, so the keys below
50        // are content-verified binding material.
51        let verified = verify_did_at9p(did, capsule_bytes)
52            .map_err(|e| anyhow!("did:at9p {did} GATE rejected: {e}"))?;
53        let capsule = verified.capsule();
54
55        // Project the WHOLE published subject key SET (#1188 / #1183), not a
56        // positional "primary". `subjectKeys` is a set of currently-usable
57        // identity keys — an overlap-rotating or hybrid-rolling out identity
58        // publishes several at once — and the consumer (admission #894) selects
59        // its member by Ed25519 identity, never by index. Each entry's ML-DSA-65
60        // half stays atomically bound to the Ed25519 half it was published with.
61        // The schema guarantees a non-empty set with unique Ed25519 halves.
62        let keys = capsule
63            .body
64            .subject_keys
65            .iter()
66            .map(|subject| {
67                let ed25519: [u8; 32] =
68                    subject.ed25519_pub.as_slice().try_into().map_err(|_| {
69                        anyhow!("ed25519 subject key is not {ED25519_PUBLIC_KEY_LEN} bytes")
70                    })?;
71                let ml_dsa_65 = ml_dsa_vk_from_bytes(&subject.mldsa65_pub)?;
72                Ok(VerifiedAt9pKeys::key(ed25519, ml_dsa_65))
73            })
74            .collect::<Result<Vec<_>>>()?;
75
76        VerifiedAt9pKeys::new_gate_verified_set(keys)
77    }
78
79    fn resolve(&self, did: &str) -> Result<VerifiedAt9pKeys> {
80        // The locator fetch (mainline DHT, Track C / #890) is not wired yet. Until
81        // it is, the resolver path fails closed — admission (verify_bytes, with
82        // peer-presented bytes) is the live D2 path.
83        Err(anyhow!(
84            "did:at9p {did}: mainline locator fetch is not wired (#890) — resolve fails closed"
85        ))
86    }
87}
88
89#[cfg(test)]
90#[allow(
91    clippy::unwrap_used,
92    clippy::expect_used,
93    clippy::panic,
94    clippy::indexing_slicing
95)]
96mod tests {
97    use super::*;
98    use crate::at9p::{
99        Capsule, CapsuleBody, HybridKeyPair, ServiceEndpoint, ServiceEntry, ServiceType, Transport,
100        ED25519_SIGNATURE_LEN,
101    };
102    use crate::at9p_gate::DID_AT9P_PREFIX;
103    use crate::at9p_sign::sign_capsule;
104
105    use ed25519_dalek::SigningKey;
106    use hyprstream_crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes, MlDsaSigningKey};
107    use hyprstream_rpc::admission::{
108        admit_key_against_did, AdmissionTrustSurface, At9pAdmission, VerifiedApplicationSigner,
109    };
110    use hyprstream_rpc::envelope::{KeyedPqTrustStore, PqTrustStore};
111
112    use anyhow::Result as AnyResult;
113    use async_trait::async_trait;
114    use serde_json::Value;
115
116    struct Signer {
117        ed_sk: SigningKey,
118        pq_sk: MlDsaSigningKey,
119        keypair: HybridKeyPair,
120    }
121
122    fn signer(tag: u8) -> Signer {
123        let mut seed = [0u8; 32];
124        seed[0] = tag;
125        seed[31] = tag.wrapping_add(7);
126        let ed_sk = SigningKey::from_bytes(&seed);
127        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
128        let keypair = HybridKeyPair::new(
129            ed_sk.verifying_key().to_bytes().to_vec(),
130            ml_dsa_vk_bytes(&pq_vk),
131        )
132        .unwrap();
133        Signer {
134            ed_sk,
135            pq_sk,
136            keypair,
137        }
138    }
139
140    fn body_for(s: &Signer, tag: u8) -> CapsuleBody {
141        let endpoint = ServiceEndpoint::new(Transport::Iroh, format!("iroh://node{tag}")).unwrap();
142        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
143        CapsuleBody::new(vec![s.keypair.clone()], vec![service]).unwrap()
144    }
145
146    /// A fully self-signed capsule, its canonical bytes, and its `did:at9p:<cid>`.
147    fn signed(tag: u8) -> (Capsule, Vec<u8>, String) {
148        let s = signer(tag);
149        let body = body_for(&s, tag);
150        let capsule = sign_capsule(body, &s.ed_sk, &s.pq_sk).unwrap();
151        let bytes = capsule.to_dag_cbor().unwrap();
152        let did = format!("{DID_AT9P_PREFIX}{}", capsule.cid512().unwrap());
153        (capsule, bytes, did)
154    }
155
156    /// A did:web resolver that MUST NOT be called for the did:at9p admission arm.
157    struct NeverResolve;
158    #[async_trait]
159    impl hyprstream_rpc::admission::DidDocResolve for NeverResolve {
160        async fn resolve_doc(&self, did: &str) -> AnyResult<Value> {
161            panic!("did:at9p admission must not resolve a DID document (called for {did})");
162        }
163    }
164
165    #[test]
166    fn gate_resolver_returns_verified_subject_keys() {
167        let (capsule, bytes, did) = signed(1);
168        let primary = capsule.body.subject_keys[0].clone();
169        let verified = At9pGateResolver::new()
170            .verify_bytes(&did, &bytes)
171            .expect("GATE passes");
172        let ed_arr: [u8; 32] = primary.ed25519_pub.as_slice().try_into().unwrap();
173        let selected = verified
174            .for_ed25519(&ed_arr)
175            .expect("published subject key selectable by its Ed25519 identity");
176        assert_eq!(selected.ed25519().as_slice(), primary.ed25519_pub);
177        assert_eq!(ml_dsa_vk_bytes(selected.ml_dsa_65()), primary.mldsa65_pub);
178    }
179
180    #[test]
181    fn gate_resolver_rejects_bad_signature() {
182        // Corrupt the Ed25519 signature (keep it schema-valid) and claim the
183        // tampered capsule's own recomputed cid so canon/hash pass — only sig-gate
184        // can reject.
185        let (mut capsule, _bytes, _did) = signed(2);
186        capsule.signatures.ed25519_signature = vec![0u8; ED25519_SIGNATURE_LEN];
187        let bytes = capsule.to_dag_cbor().unwrap();
188        let cid = Capsule::from_dag_cbor(&bytes).unwrap().cid512().unwrap();
189        let did = format!("{DID_AT9P_PREFIX}{cid}");
190        assert!(At9pGateResolver::new().verify_bytes(&did, &bytes).is_err());
191    }
192
193    #[test]
194    fn gate_resolver_rejects_wrong_cid() {
195        // A genuine capsule claimed under a different (well-formed) cid fails
196        // hash-gate.
197        let (_c1, bytes1, did1) = signed(3);
198        let did_other = signed(4).2;
199        assert_ne!(did1, did_other);
200        assert!(At9pGateResolver::new()
201            .verify_bytes(&did_other, &bytes1)
202            .is_err());
203    }
204
205    #[tokio::test]
206    async fn admission_binds_hybrid_keys_from_gate_verified_capsule() {
207        // End-to-end D2: a real self-signed capsule → GATE passes → the verified
208        // ed25519→ml_dsa_65 pair is bound into KeyedPqTrustStore. The binding
209        // provably comes from the capsule (the store was empty; the bound PQ key
210        // equals the capsule's), not from any out-of-band config.
211        let (capsule, bytes, did) = signed(5);
212        let ed = capsule.body.subject_keys[0].ed25519_pub.clone();
213        let primary_pq = capsule.body.subject_keys[0].mldsa65_pub.clone();
214        let ed_arr: [u8; 32] = ed.as_slice().try_into().unwrap();
215
216        let gate = At9pGateResolver::new();
217        let mut store = KeyedPqTrustStore::new();
218        assert!(store.is_empty());
219
220        let admitted = admit_key_against_did(
221            &NeverResolve,
222            "https://peer.example",
223            VerifiedApplicationSigner::pq_hybrid(ed_arr),
224            AdmissionTrustSurface::Native,
225            &did,
226            None,
227            Some(At9pAdmission {
228                capsule_bytes: &bytes,
229                gate: &gate,
230                pq_store: &mut store,
231            }),
232        )
233        .await
234        .expect("verified capsule admits and binds");
235
236        assert_eq!(admitted.did.as_deref(), Some(did.as_str()));
237        assert_eq!(admitted.key, ed_arr);
238        assert_eq!(store.len(), 1);
239        let bound = store
240            .ml_dsa_key_for(&ed_arr)
241            .expect("hybrid binding installed");
242        assert_eq!(ml_dsa_vk_bytes(&bound), primary_pq);
243    }
244
245    /// A capsule that publishes TWO subject keys (`s1` signs, `s2` also
246    /// published — overlap rotation / hybrid rollout) and whose *first* published
247    /// key does the self-certification. A peer presenting the SECOND published
248    /// key as its application signer must be admitted, and the binding installed
249    /// must be `s2`'s atomically-bound ML-DSA-65 half — never `s1`'s. The pre-fix
250    /// admission arm compared only `subject_keys.first()` and would reject the
251    /// second key (and, had it matched, bound the wrong PQ half). This is the #1188
252    /// end-to-end two-key overlap admission test.
253    #[tokio::test]
254    async fn admission_admits_second_published_subject_key_and_binds_its_pair() {
255        // signer 8 self-certifies; signer 9 is also published in the same set.
256        let s1 = signer(8);
257        let s2 = signer(9);
258        let endpoint = ServiceEndpoint::new(Transport::Iroh, "iroh://node8").unwrap();
259        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
260        // s1 listed FIRST, s2 second.
261        let body =
262            CapsuleBody::new(vec![s1.keypair.clone(), s2.keypair.clone()], vec![service]).unwrap();
263        // Self-certify with s1 (the first key).
264        let capsule = sign_capsule(body, &s1.ed_sk, &s1.pq_sk).unwrap();
265        let bytes = capsule.to_dag_cbor().unwrap();
266        let did = format!("{DID_AT9P_PREFIX}{}", capsule.cid512().unwrap());
267
268        // The peer's application signer is the SECOND published key.
269        let ed2: [u8; 32] = s2.keypair.ed25519_pub.as_slice().try_into().unwrap();
270        let ed1: [u8; 32] = s1.keypair.ed25519_pub.as_slice().try_into().unwrap();
271        assert_ne!(ed1, ed2);
272
273        let gate = At9pGateResolver::new();
274        let mut store = KeyedPqTrustStore::new();
275        let admitted = admit_key_against_did(
276            &NeverResolve,
277            "https://peer.example",
278            VerifiedApplicationSigner::pq_hybrid(ed2),
279            AdmissionTrustSurface::Native,
280            &did,
281            None,
282            Some(At9pAdmission {
283                capsule_bytes: &bytes,
284                gate: &gate,
285                pq_store: &mut store,
286            }),
287        )
288        .await
289        .expect("a peer presenting the second published subject key must be admitted");
290        assert_eq!(admitted.key, ed2);
291
292        // The binding is s2's ATOMIC pair — bound under ed2, equal to s2's PQ half.
293        assert_eq!(store.len(), 1);
294        let bound = store
295            .ml_dsa_key_for(&ed2)
296            .expect("s2 hybrid binding installed");
297        assert_eq!(ml_dsa_vk_bytes(&bound), s2.keypair.mldsa65_pub);
298        // And nothing was bound under s1 (no positional collapse).
299        assert!(store.ml_dsa_key_for(&ed1).is_none());
300    }
301
302    /// A peer whose application signer matches NONE of the published subject keys
303    /// is rejected and binds nothing — set membership is required.
304    #[tokio::test]
305    async fn admission_rejects_signer_absent_from_subject_key_set() {
306        let s1 = signer(10);
307        let s2 = signer(11);
308        let outsider = signer(12);
309        let endpoint = ServiceEndpoint::new(Transport::Iroh, "iroh://node10").unwrap();
310        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
311        let body =
312            CapsuleBody::new(vec![s1.keypair.clone(), s2.keypair.clone()], vec![service]).unwrap();
313        let capsule = sign_capsule(body, &s1.ed_sk, &s1.pq_sk).unwrap();
314        let bytes = capsule.to_dag_cbor().unwrap();
315        let did = format!("{DID_AT9P_PREFIX}{}", capsule.cid512().unwrap());
316        let ed_out: [u8; 32] = outsider.keypair.ed25519_pub.as_slice().try_into().unwrap();
317
318        let gate = At9pGateResolver::new();
319        let mut store = KeyedPqTrustStore::new();
320        let res = admit_key_against_did(
321            &NeverResolve,
322            "https://peer.example",
323            VerifiedApplicationSigner::pq_hybrid(ed_out),
324            AdmissionTrustSurface::Native,
325            &did,
326            None,
327            Some(At9pAdmission {
328                capsule_bytes: &bytes,
329                gate: &gate,
330                pq_store: &mut store,
331            }),
332        )
333        .await;
334        assert!(res.is_err(), "a non-member signer must be rejected");
335        assert!(store.is_empty(), "a rejected peer must bind nothing");
336    }
337
338    #[tokio::test]
339    async fn admission_rejects_gate_failure_and_binds_nothing() {
340        // Tampered signature → GATE rejects → admission fails closed and NOTHING
341        // is bound into the trust store.
342        let (mut capsule, _bytes, _did) = signed(6);
343        capsule.signatures.ed25519_signature = vec![0u8; ED25519_SIGNATURE_LEN];
344        let bytes = capsule.to_dag_cbor().unwrap();
345        let cid = Capsule::from_dag_cbor(&bytes).unwrap().cid512().unwrap();
346        let did = format!("{DID_AT9P_PREFIX}{cid}");
347        let ed: [u8; 32] = capsule.body.subject_keys[0]
348            .ed25519_pub
349            .as_slice()
350            .try_into()
351            .unwrap();
352
353        let gate = At9pGateResolver::new();
354        let mut store = KeyedPqTrustStore::new();
355        let res = admit_key_against_did(
356            &NeverResolve,
357            "https://peer.example",
358            VerifiedApplicationSigner::pq_hybrid(ed),
359            AdmissionTrustSurface::Native,
360            &did,
361            None,
362            Some(At9pAdmission {
363                capsule_bytes: &bytes,
364                gate: &gate,
365                pq_store: &mut store,
366            }),
367        )
368        .await;
369        assert!(res.is_err(), "GATE failure must reject");
370        assert!(store.is_empty(), "a rejected capsule must bind nothing");
371    }
372
373    #[test]
374    fn resolve_fails_closed_until_locator_wired() {
375        // The resolver path (locator fetch, #890) is not wired; it must fail
376        // closed rather than silently degrade.
377        let (_c, _bytes, did) = signed(7);
378        assert!(At9pGateResolver::new().resolve(&did).is_err());
379    }
380}