Skip to main content

hyprstream_discovery/
at9p_resolver.rs

1//! `did:at9p` capsule resolver — GATE-verified reach as a `TransportConfig`
2//! (#893, design #879 §9; epic #880 Track D / D1).
3//!
4//! This is the **D1 sibling to `hyprstream_rpc::service_entry::decode_iroh`**:
5//! where `decode_iroh` turns a DID-document `IrohTransport` service entry into a
6//! dialable [`TransportConfig`], this module turns a *GATE-verified `did:at9p`
7//! capsule* into the same shape. It is explicitly **not** a [`RecordResolver`]
8//! impl — a `RecordResolver` returns an atproto CAR (the wrong output shape for
9//! "how do I dial this peer"). The capsule→reach path is a separate resolution
10//! arm, injected at the network-profile resolver seam (`Resolver::set_global`,
11//! the future `NetworkDiscoveryResolver` of #873).
12//!
13//! # Why a genesis capsule cannot mint a dial target
14//!
15//! GATE makes genesis fields content-bound claims; it does not prove current
16//! state, liveness, or possession. The schema carries a relay claim but no
17//! independent carrier `EndpointId`, so this resolver fails closed rather than
18//! deriving reach from the subject Ed25519 key (#1031).
19//!
20//! # Service selection (#893 update; design #905 §4, #879 §5.1a)
21//!
22//! A capsule carries a **map** of named services (the `#882` `services` field),
23//! each typed (`NinePExport`, `AtprotoPds`). The resolver takes an optional
24//! service selector (default [`DEFAULT_AT9P_SERVICE`] = `#ns`, the 9P export a
25//! client attaches to) and validates **that selected `NinePExport` service
26//! entry only**. A missing id, a wrong-type entry, a non-iroh transport, or the
27//! absence of an independent carrier EndpointId **fails closed** — never an
28//! unrequested, wrong-shape, or identity-derived endpoint.
29//! This is the seam #906 (the DID-URL dereferencer, G1) pins against, and the
30//! one #877's attach profile consumes.
31
32use std::sync::Arc;
33
34use anyhow::{anyhow, ensure, Result};
35
36use hyprstream_pds::at9p::{ServiceType, Transport as At9pTransport};
37use hyprstream_pds::at9p_gate::{verify_did_at9p, VerifiedCapsule};
38use hyprstream_rpc::transport::TransportConfig;
39
40/// Default at9p service selector — the `NinePExport` entry a client attaches to.
41///
42/// Matches the canonical 9P export name (`#ns`) used across the namespace
43/// delivery layer (#877 attach `aname` / `exportRef`).
44pub const DEFAULT_AT9P_SERVICE: &str = "#ns";
45
46/// Map a **GATE-verified** `did:at9p` capsule to a dialable iroh
47/// [`TransportConfig`], selecting the `NinePExport` service entry named `service`
48/// (default [`DEFAULT_AT9P_SERVICE`]).
49///
50/// This is the pure, I/O-free core of D1 — a sibling to
51/// `service_entry::decode_iroh`. It takes a [`VerifiedCapsule`] (so GATE has
52/// already passed before this is reachable) and:
53///
54/// 1. selects the requested `NinePExport` service entry — fail closed if the id
55///    is absent or the entry is the wrong type;
56/// 2. requires that entry's transport to be iroh — fail closed otherwise;
57/// 3. rejects the capsule because the current schema has no independent
58///    carrier EndpointId. The signed relay remains a reach claim, but cannot
59///    turn the genesis subject identity key into a live dial target.
60pub fn capsule_to_iroh_reach(
61    verified: &VerifiedCapsule,
62    service: Option<&str>,
63) -> Result<TransportConfig> {
64    let capsule = verified.capsule();
65    let svc_id = service.unwrap_or(DEFAULT_AT9P_SERVICE);
66
67    // Select the requested NinePExport service entry. Wrong type / missing id
68    // ⇒ fail closed: we never emit reach from an unrequested or non-9P entry.
69    let entry = capsule
70        .body
71        .services
72        .iter()
73        .find(|s| s.id == svc_id && s.service_type == ServiceType::NinePExport)
74        .ok_or_else(|| {
75            anyhow!("at9p capsule has no NinePExport service entry for selector {svc_id:?}")
76        })?;
77
78    // The selected entry must be iroh-reachable. A QUIC/MoQ/HTTPS entry under a
79    // NinePExport is a wrong-shape capsule for this resolver — fail closed.
80    ensure!(
81        entry.endpoint.transport == At9pTransport::Iroh,
82        "at9p service {svc_id:?} is not an iroh endpoint (got {:?})",
83        entry.endpoint.transport,
84    );
85
86    let relay = entry.endpoint.relay.as_deref().unwrap_or("<none>");
87    Err(anyhow!(
88        "at9p service {svc_id:?} carries relay claim {relay:?} but no independent iroh EndpointId; refusing to derive transport reach from the genesis identity key (#1031)"
89    ))
90}
91
92/// Untrusted source of capsule bytes for a `did:at9p:<cid>` identifier.
93///
94/// The mainline locator (#890 / C2) is the production implementation; for D1
95/// the trait abstracts *how* the bytes are fetched so the resolver only depends
96/// on the GATE decision over them. The locator derives **zero authority**: the
97/// [`verify_did_at9p`] gate is what makes the bytes trustworthy, not the source.
98#[async_trait::async_trait]
99pub trait CapsuleSource: Send + Sync {
100    /// Fetch the raw (canonical DAG-CBOR) capsule bytes advertised for `did`.
101    ///
102    /// The bytes are attacker-controlled until GATE verifies them.
103    async fn fetch_capsule(&self, did: &str) -> Result<Vec<u8>>;
104}
105
106/// `did:at9p` capsule resolver — turns a `did:at9p:<cid>` into a dialable
107/// [`TransportConfig`] over a [`CapsuleSource`] + the GATE pipeline.
108///
109/// This is the injectable capsule source for the `Resolver::set_global` /
110/// `NetworkDiscoveryResolver` seam (#873 network profile): a future network
111/// resolver that recognizes `did:at9p:` peer addresses may compose this after
112/// the capsule schema carries independently authenticated live reach.
113///
114/// # Fail-closed posture
115///
116/// The capsule must pass [`verify_did_at9p`] (canon → hash → sig), but that
117/// proves only the genesis claim. Until an independent EndpointId is available,
118/// even a valid capsule returns `Err`; other GATE and service-selection failures
119/// also return `Err`, never partial or identity-derived reach.
120pub struct At9pResolver {
121    source: Arc<dyn CapsuleSource>,
122}
123
124impl At9pResolver {
125    /// Build a resolver over an untrusted capsule source.
126    pub fn new(source: Arc<dyn CapsuleSource>) -> Self {
127        Self { source }
128    }
129
130    /// Resolve `did:at9p:<cid>` to a dialable [`TransportConfig`], selecting the
131    /// `NinePExport` service entry named `service` (default `#ns`).
132    ///
133    /// Fetches the capsule bytes from the (untrusted) [`CapsuleSource`], runs the
134    /// full GATE pipeline, and validates the selected reach claim. It fails
135    /// closed because the current capsule has no independent live EndpointId.
136    pub async fn resolve_did(&self, did: &str, service: Option<&str>) -> Result<TransportConfig> {
137        let bytes = self.source.fetch_capsule(did).await?;
138        // GATE — the only place authority is granted. Fail closed on any gate.
139        let verified = verify_did_at9p(did, &bytes)?;
140        capsule_to_iroh_reach(&verified, service)
141    }
142}
143
144#[cfg(test)]
145#[allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
146mod tests {
147    use super::*;
148    use ed25519_dalek::SigningKey;
149    use hyprstream_crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes, MlDsaSigningKey};
150    use hyprstream_pds::at9p::{
151        Capsule, CapsuleBody, HybridKeyPair, ServiceEndpoint, ServiceEntry, Transport,
152    };
153    use hyprstream_pds::at9p_gate::DID_AT9P_PREFIX;
154    use hyprstream_pds::at9p_sign::sign_capsule;
155
156    /// A test signer with matching hybrid subject keys.
157    struct Signer {
158        ed_sk: SigningKey,
159        pq_sk: MlDsaSigningKey,
160        keypair: HybridKeyPair,
161    }
162
163    fn signer(tag: u8) -> Signer {
164        let mut seed = [0u8; 32];
165        seed[0] = tag;
166        seed[31] = tag.wrapping_add(7);
167        let ed_sk = SigningKey::from_bytes(&seed);
168        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
169        let keypair = HybridKeyPair::new(
170            ed_sk.verifying_key().to_bytes().to_vec(),
171            ml_dsa_vk_bytes(&pq_vk),
172        )
173        .unwrap();
174        Signer {
175            ed_sk,
176            pq_sk,
177            keypair,
178        }
179    }
180
181    /// A capsule body exposing three services: `#ns` (NinePExport/iroh — the
182    /// dialable one), `#quic` (NinePExport but QUIC — wrong transport), and
183    /// `#pds` (AtprotoPds/https — wrong type). Lets both selection gates be
184    /// exercised.
185    fn body_with_services(s: &Signer, tag: u8) -> CapsuleBody {
186        let mut ns = ServiceEndpoint::new(Transport::Iroh, format!("iroh://node{tag}")).unwrap();
187        ns.relay = Some(format!("https://relay{tag}.example"));
188        let ns_entry = ServiceEntry::new("#ns", ServiceType::NinePExport, ns).unwrap();
189        let quic = ServiceEndpoint::new(Transport::Quic, format!("quic://node{tag}")).unwrap();
190        let quic_entry = ServiceEntry::new("#quic", ServiceType::NinePExport, quic).unwrap();
191        let pds =
192            ServiceEndpoint::new(Transport::Https, format!("https://pds{tag}.example")).unwrap();
193        let pds_entry = ServiceEntry::new("#pds", ServiceType::AtprotoPds, pds).unwrap();
194        CapsuleBody::new(
195            vec![s.keypair.clone()],
196            vec![ns_entry, quic_entry, pds_entry],
197        )
198        .unwrap()
199    }
200
201    /// A fully-signed capsule, its canonical bytes, its cid512, and its DID.
202    fn signed(tag: u8) -> (Capsule, Vec<u8>, String, String) {
203        let s = signer(tag);
204        let body = body_with_services(&s, tag);
205        let capsule = sign_capsule(body, &s.ed_sk, &s.pq_sk).unwrap();
206        let bytes = capsule.to_dag_cbor().unwrap();
207        let cid = capsule.cid512().unwrap();
208        let did = format!("{DID_AT9P_PREFIX}{cid}");
209        (capsule, bytes, cid, did)
210    }
211
212    #[test]
213    fn signed_capsule_relay_claim_does_not_mint_live_reach() {
214        let (_capsule, bytes, _cid, did) = signed(1);
215
216        // Reach comes from the GATE witness, not the raw capsule.
217        let verified = verify_did_at9p(&did, &bytes).unwrap();
218        let err = capsule_to_iroh_reach(&verified, None).unwrap_err();
219        assert!(err.to_string().contains("no independent iroh EndpointId"));
220    }
221
222    #[test]
223    fn explicit_service_selector_selects_named_entry() {
224        let (capsule, bytes, _cid, did) = signed(2);
225        let verified = verify_did_at9p(&did, &bytes).unwrap();
226        // Default `#ns` is signed, but cannot mint live reach.
227        assert!(capsule_to_iroh_reach(&verified, None).is_err());
228        let _ = capsule; // keep capsule alive for clarity
229                         // `#quic` is a NinePExport but QUIC → wrong transport, fail closed.
230        let err = capsule_to_iroh_reach(&verified, Some("#quic")).unwrap_err();
231        assert!(
232            err.to_string().contains("not an iroh endpoint"),
233            "expected non-iroh rejection, got: {err}"
234        );
235    }
236
237    #[test]
238    fn missing_service_selector_fails_closed() {
239        let (_capsule, bytes, _cid, did) = signed(3);
240        let verified = verify_did_at9p(&did, &bytes).unwrap();
241        // `#pds` is AtprotoPds → wrong type, treated as a missing NinePExport.
242        let err = capsule_to_iroh_reach(&verified, Some("#pds")).unwrap_err();
243        assert!(
244            err.to_string().contains("no NinePExport service entry"),
245            "expected wrong-type rejection, got: {err}"
246        );
247        // A totally absent selector id fails closed the same way.
248        let err = capsule_to_iroh_reach(&verified, Some("#nope")).unwrap_err();
249        assert!(
250            err.to_string().contains("no NinePExport service entry"),
251            "expected missing-service rejection, got: {err}"
252        );
253    }
254
255    /// A capsule that fails GATE yields no reach: pass valid bytes but claim a
256    /// different identity → hash-gate rejects before reach is ever computed.
257    #[test]
258    fn capsule_failing_gate_emits_no_reach() {
259        let (_capsule, bytes, _cid_a, _did_a) = signed(10);
260        let (_capsule_b, _bytes_b, _cid_b, did_b) = signed(11);
261        // bytes are genuinely self-signed and canonical, but we claim the
262        // identity of a *different* capsule → GATE fails closed.
263        let gate = verify_did_at9p(&did_b, &bytes);
264        assert!(gate.is_err(), "GATE must reject the mismatched identity");
265        // No VerifiedCapsule exists, so capsule_to_iroh_reach is unreachable —
266        // i.e. no reach can be emitted. (Mirrored at the resolver level below.)
267    }
268
269    /// `At9pResolver::resolve_did` threads GATE through: a valid capsule
270    /// resolves; a GATE failure (wrong identity) emits no reach.
271    struct FixedSource {
272        bytes: Vec<u8>,
273    }
274
275    #[async_trait::async_trait]
276    impl CapsuleSource for FixedSource {
277        async fn fetch_capsule(&self, _did: &str) -> Result<Vec<u8>> {
278            Ok(self.bytes.clone())
279        }
280    }
281
282    #[tokio::test]
283    async fn resolver_valid_capsule_without_transport_id_fails_closed() {
284        let (_capsule, bytes, _cid, did) = signed(20);
285        let resolver = At9pResolver::new(Arc::new(FixedSource {
286            bytes: bytes.clone(),
287        }));
288        let err = resolver.resolve_did(&did, None).await.unwrap_err();
289        assert!(err.to_string().contains("no independent iroh EndpointId"));
290    }
291
292    #[tokio::test]
293    async fn resolver_capsule_failing_gate_emits_no_reach() {
294        // Serve capsule A's bytes under B's identity — GATE must fail closed.
295        let (_a, bytes_a, _cid_a, _did_a) = signed(30);
296        let (_b, _bytes_b, _cid_b, did_b) = signed(31);
297        let resolver = At9pResolver::new(Arc::new(FixedSource { bytes: bytes_a }));
298        let err = resolver.resolve_did(&did_b, None).await.unwrap_err();
299        assert!(
300            err.to_string().contains("hash-gate"),
301            "expected a GATE rejection surfaced, got: {err}"
302        );
303    }
304}