Skip to main content

hyprstream_rpc/
service_entry.rs

1//! DID-document transport `service`-entry codec.
2//!
3//! The canonical encoder/decoder for the typed transport entries a node
4//! publishes in its DID document, shared by the producer (the did:web document
5//! builder) and the consumer (the DID resolver that feeds [`crate::dial::dial`]).
6//!
7//! # Layering (settled design)
8//!
9//! Peer **identity** is established at the application layer — the response
10//! `SignedEnvelope` is verified against the node's published keys (the `#mesh`
11//! verification method / JWKS). The transport entries here carry **reach info +
12//! channel mechanics**, not the identity root. An iroh `nodeId` is an endpoint
13//! address and must not manufacture identity or key authority (#1031).
14//!
15//! # Wire shape
16//!
17//! `serviceEndpoint` is a DIDComm-style map (W3C DID Core §5.4 permits a map).
18//! Binary values use multibase (`z` = base58btc) over a multiformats prefix,
19//! matching the doc's `Multikey` `publicKeyMultibase` encoding (#280; ed25519
20//! VMs were formerly `Ed25519VerificationKey2020`):
21//!
22//! ```jsonc
23//! // type: "IrohTransport"
24//! { "nodeId": "z<multicodec ed25519-pub || key>", "relays": ["https://…"], "accept": ["hyprstream-rpc/1","moql"] }
25//! // type: "QuicTransport"
26//! { "uri": "https://host:port", "webpki": false,
27//!   "certHashes": ["z<multihash sha2-256 || digest>"], "accept": [...] }
28//! ```
29//!
30//! `certHashes` is a multibase-encoded **multihash** (self-describing algorithm,
31//! `sha2-256` = 0x12), a **set** so cert rotation can overlap. Whole-cert pins
32//! are the browser-compatible projection of the identity key — see #185 / #200.
33
34use std::net::{IpAddr, Ipv4Addr, SocketAddr};
35
36use anyhow::{anyhow, bail, Context, Result};
37use base64::Engine as _;
38use serde_json::{json, Value};
39
40use crate::did_key::MULTICODEC_ED25519_PUB;
41use crate::transport::{EndpointType, QuicServerAuth, TransportConfig};
42
43/// multihash prefix for `sha2-256` with a 32-byte digest (`0x12` code, `0x20` len).
44const MULTIHASH_SHA2_256: [u8; 2] = [0x12, 0x20];
45
46/// A decoded transport entry containing only dialable reach information.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct DecodedEntry {
49    /// Dial target for [`crate::dial::dial`].
50    pub config: TransportConfig,
51}
52
53/// Browser projection of the primary live QUIC reach.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct BrowserQuicReach {
56    /// URL copied from the validated live `QuicTransport` entry.
57    pub quic_url: String,
58    /// Standard-base64 SHA-256 leaf-certificate hash for WebTransport.
59    pub cert_hash: String,
60}
61
62// ── multibase helpers ────────────────────────────────────────────────────────
63
64fn multibase_encode(prefix: &[u8], payload: &[u8]) -> String {
65    let mut buf = Vec::with_capacity(prefix.len() + payload.len());
66    buf.extend_from_slice(prefix);
67    buf.extend_from_slice(payload);
68    format!("z{}", bs58::encode(buf).into_string())
69}
70
71/// Decode a multibase base58btc string carrying `prefix || <32-byte payload>`.
72fn multibase_decode_32(s: &str, prefix: [u8; 2], what: &str) -> Result<[u8; 32]> {
73    let b58 = s
74        .strip_prefix('z')
75        .ok_or_else(|| anyhow!("{what}: expected multibase base58btc ('z' prefix)"))?;
76    let bytes = bs58::decode(b58)
77        .into_vec()
78        .map_err(|e| anyhow!("{what}: invalid base58: {e}"))?;
79    if bytes.len() != prefix.len() + 32 {
80        bail!(
81            "{what}: expected {} bytes, got {}",
82            prefix.len() + 32,
83            bytes.len()
84        );
85    }
86    if bytes[..2] != prefix[..] {
87        bail!("{what}: wrong multiformats prefix");
88    }
89    let mut out = [0u8; 32];
90    out.copy_from_slice(&bytes[2..]);
91    Ok(out)
92}
93
94// ── encode (producer side) ───────────────────────────────────────────────────
95
96/// Encode an `IrohTransport` `serviceEndpoint` map for a peer identified by
97/// `node_id` (its Ed25519 `EndpointId`), reachable via `relays`.
98pub fn encode_iroh(node_id: &[u8; 32], relays: &[String], accept: &[&str]) -> Value {
99    json!({
100        "nodeId": multibase_encode(&MULTICODEC_ED25519_PUB, node_id),
101        "relays": relays,
102        "accept": accept,
103    })
104}
105
106/// Encode a `QuicTransport` `serviceEndpoint` map.
107pub fn encode_quic(uri: &str, auth: &QuicServerAuth, accept: &[&str]) -> Value {
108    let cert_hashes: Vec<String> = auth
109        .accept_cert_hashes()
110        .iter()
111        .map(|h| multibase_encode(&MULTIHASH_SHA2_256, h))
112        .collect();
113    json!({
114        "uri": uri,
115        "webpki": auth.require_web_pki(),
116        "certHashes": cert_hashes,
117        "accept": accept,
118    })
119}
120
121// ── decode (consumer / resolver side) ────────────────────────────────────────
122
123/// Decode one DID-doc transport `service` entry (`{type, serviceEndpoint}`) into
124/// a dialable [`DecodedEntry`]. Unknown `type`s error so the caller can skip
125/// them.
126pub fn decode_service_entry(entry: &Value) -> Result<DecodedEntry> {
127    let ty = entry
128        .get("type")
129        .and_then(Value::as_str)
130        .ok_or_else(|| anyhow!("service entry missing string `type`"))?;
131    let svc = entry
132        .get("serviceEndpoint")
133        .ok_or_else(|| anyhow!("service entry missing `serviceEndpoint`"))?;
134    match ty {
135        "IrohTransport" => decode_iroh(svc),
136        "QuicTransport" => decode_quic(svc),
137        other => bail!("unsupported transport service type: {other}"),
138    }
139}
140
141/// Validate a live `QuicTransport` service entry and project its certificate
142/// pin into the singular browser registration shape.
143///
144/// Discovery models `certHashes` as a set for rotation overlap, while the
145/// registration contract currently has one `certHash`. Ambiguous overlap
146/// therefore fails closed instead of selecting a pin with no defined primary.
147pub fn decode_browser_quic_reach(entry: &Value) -> Result<BrowserQuicReach> {
148    let decoded = decode_service_entry(entry)?;
149    let EndpointType::Quic { auth, .. } = &decoded.config.endpoint else {
150        bail!("browser QUIC reach requires a QuicTransport service entry");
151    };
152    let [cert_hash] = auth.accept_cert_hashes() else {
153        bail!("browser QUIC reach requires exactly one live certificate hash");
154    };
155    let quic_url = entry
156        .get("serviceEndpoint")
157        .and_then(|endpoint| endpoint.get("uri"))
158        .and_then(Value::as_str)
159        .ok_or_else(|| anyhow!("quic: missing `uri`"))?
160        .to_owned();
161    Ok(BrowserQuicReach {
162        quic_url,
163        cert_hash: base64::engine::general_purpose::STANDARD.encode(cert_hash),
164    })
165}
166
167fn decode_iroh(svc: &Value) -> Result<DecodedEntry> {
168    let node_id = multibase_decode_32(
169        svc.get("nodeId")
170            .and_then(Value::as_str)
171            .ok_or_else(|| anyhow!("iroh: missing `nodeId`"))?,
172        MULTICODEC_ED25519_PUB,
173        "iroh nodeId",
174    )?;
175    let relays: Vec<String> = svc
176        .get("relays")
177        .and_then(Value::as_array)
178        .map(|a| {
179            a.iter()
180                .filter_map(|v| v.as_str().map(str::to_owned))
181                .collect()
182        })
183        .unwrap_or_default();
184    // Direct addresses are not published (privacy + iroh discovery); the resolver
185    // supplies a relay and lets iroh discover direct paths.
186    let relay_url = relays.into_iter().next();
187    Ok(DecodedEntry {
188        config: TransportConfig::iroh(node_id, Vec::new(), relay_url),
189    })
190}
191
192fn decode_quic(svc: &Value) -> Result<DecodedEntry> {
193    let uri = svc
194        .get("uri")
195        .and_then(Value::as_str)
196        .ok_or_else(|| anyhow!("quic: missing `uri`"))?;
197    let (host, port) = parse_https_authority(uri)?;
198    // Default `webpki` to true (safe-by-default: a CA-fronted public peer).
199    let require_web_pki = svc.get("webpki").and_then(Value::as_bool).unwrap_or(true);
200    let cert_hashes: Vec<[u8; 32]> = svc
201        .get("certHashes")
202        .and_then(Value::as_array)
203        .map(|a| -> Result<Vec<[u8; 32]>> {
204            a.iter()
205                .map(|v| {
206                    let s = v
207                        .as_str()
208                        .ok_or_else(|| anyhow!("quic certHashes: non-string entry"))?;
209                    multibase_decode_32(s, MULTIHASH_SHA2_256, "quic certHash")
210                })
211                .collect()
212        })
213        .transpose()?
214        .unwrap_or_default();
215
216    let auth = match (require_web_pki, cert_hashes.is_empty()) {
217        (true, true) => QuicServerAuth::web_pki(),
218        (false, false) => QuicServerAuth::pinned(cert_hashes)?,
219        (true, false) => QuicServerAuth::web_pki_pinned(cert_hashes)?,
220        (false, true) => bail!("quic entry has no auth (webpki=false and no certHashes)"),
221    };
222
223    // Pinned dials by IP; WebPKI dials by `server_name` (DNS), ignoring the IP —
224    // so a hostname `uri` gets an unspecified placeholder address with the real
225    // port, and the host becomes the validation name.
226    let addr: SocketAddr = match host.parse::<IpAddr>() {
227        Ok(ip) => SocketAddr::new(ip, port),
228        Err(_) => SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), port),
229    };
230    Ok(DecodedEntry {
231        config: TransportConfig::quic_with_auth(addr, host, auth),
232    })
233}
234
235/// Parse `https://host:port` (or `quic://…`) into `(host, port)`. Defaults to
236/// 443 when no port is given.
237fn parse_https_authority(uri: &str) -> Result<(String, u16)> {
238    let url = url::Url::parse(uri).with_context(|| format!("quic uri parse: {uri}"))?;
239    let host = url
240        .host_str()
241        .ok_or_else(|| anyhow!("quic uri has no host: {uri}"))?
242        .to_owned();
243    let port = url.port().unwrap_or(443);
244    Ok((host, port))
245}
246
247#[cfg(test)]
248#[allow(clippy::unwrap_used, clippy::expect_used)]
249mod tests {
250    use super::*;
251    use crate::transport::EndpointType;
252
253    #[test]
254    fn iroh_round_trip() {
255        let node_id = [7u8; 32];
256        let relays = vec!["https://relay.example".to_owned()];
257        let entry = json!({
258            "id": "did:web:ex#iroh",
259            "type": "IrohTransport",
260            "serviceEndpoint": encode_iroh(&node_id, &relays, &["hyprstream-rpc/1", "moql"]),
261        });
262        let decoded = decode_service_entry(&entry).unwrap();
263        match &decoded.config.endpoint {
264            EndpointType::Iroh {
265                node_id: n,
266                relay_url,
267                direct_addrs,
268            } => {
269                assert_eq!(*n, node_id);
270                assert_eq!(relay_url.as_deref(), Some("https://relay.example"));
271                assert!(direct_addrs.is_empty());
272            }
273            other => panic!("expected Iroh, got {other:?}"),
274        }
275    }
276
277    #[test]
278    fn quic_pinned_round_trip() {
279        let auth = QuicServerAuth::pinned(vec![[1u8; 32], [2u8; 32]]).unwrap();
280        let entry = json!({
281            "type": "QuicTransport",
282            "serviceEndpoint": encode_quic("https://10.0.0.1:4433", &auth, &["hyprstream-rpc/1"]),
283        });
284        let decoded = decode_service_entry(&entry).unwrap();
285        match &decoded.config.endpoint {
286            EndpointType::Quic {
287                addr,
288                server_name,
289                auth: a,
290            } => {
291                assert_eq!(addr.to_string(), "10.0.0.1:4433");
292                assert_eq!(server_name, "10.0.0.1");
293                assert!(!a.require_web_pki());
294                assert_eq!(a.accept_cert_hashes(), &[[1u8; 32], [2u8; 32]]);
295            }
296            other => panic!("expected Quic, got {other:?}"),
297        }
298    }
299
300    #[test]
301    fn browser_quic_projection_uses_the_live_pin() {
302        let auth = QuicServerAuth::pinned(vec![[3u8; 32]]).unwrap();
303        let entry = json!({
304            "type": "QuicTransport",
305            "serviceEndpoint": encode_quic(
306                "https://pds.example:4433/wt",
307                &auth,
308                &["hyprstream-rpc/1"],
309            ),
310        });
311
312        let browser = decode_browser_quic_reach(&entry).unwrap();
313        assert_eq!(browser.quic_url, "https://pds.example:4433/wt");
314        assert_eq!(
315            browser.cert_hash,
316            base64::engine::general_purpose::STANDARD.encode([3u8; 32])
317        );
318    }
319
320    #[test]
321    fn browser_quic_projection_rejects_rotation_overlap_ambiguity() {
322        let auth = QuicServerAuth::pinned(vec![[3u8; 32], [4u8; 32]]).unwrap();
323        let entry = json!({
324            "type": "QuicTransport",
325            "serviceEndpoint": encode_quic(
326                "https://pds.example:4433/wt",
327                &auth,
328                &["hyprstream-rpc/1"],
329            ),
330        });
331
332        let error = decode_browser_quic_reach(&entry).unwrap_err();
333        assert!(error.to_string().contains("exactly one"), "{error:#}");
334    }
335
336    #[test]
337    fn quic_webpki_default_and_hostname_placeholder() {
338        // No `webpki` field ⇒ default true; no certHashes ⇒ WebPKI only.
339        let entry = json!({
340            "type": "QuicTransport",
341            "serviceEndpoint": { "uri": "https://host.example:8443", "accept": ["hyprstream-rpc/1"] },
342        });
343        let decoded = decode_service_entry(&entry).unwrap();
344        match &decoded.config.endpoint {
345            EndpointType::Quic {
346                addr,
347                server_name,
348                auth,
349            } => {
350                assert!(auth.require_web_pki());
351                assert!(auth.accept_cert_hashes().is_empty());
352                assert_eq!(server_name, "host.example");
353                assert_eq!(addr.port(), 8443);
354                assert!(addr.ip().is_unspecified(), "hostname ⇒ placeholder IP");
355            }
356            other => panic!("expected Quic, got {other:?}"),
357        }
358    }
359
360    #[test]
361    fn quic_web_pki_pinned() {
362        let entry = json!({
363            "type": "QuicTransport",
364            "serviceEndpoint": {
365                "uri": "https://host.example:4433",
366                "webpki": true,
367                "certHashes": [multibase_encode(&MULTIHASH_SHA2_256, &[9u8; 32])],
368            },
369        });
370        let decoded = decode_service_entry(&entry).unwrap();
371        if let EndpointType::Quic { auth, .. } = &decoded.config.endpoint {
372            assert!(auth.require_web_pki());
373            assert_eq!(auth.accept_cert_hashes(), &[[9u8; 32]]);
374        } else {
375            panic!("expected Quic");
376        }
377    }
378
379    #[test]
380    fn rejects_no_auth_and_unknown_type() {
381        // webpki:false + no certHashes ⇒ no auth ⇒ reject.
382        let bad = json!({
383            "type": "QuicTransport",
384            "serviceEndpoint": { "uri": "https://10.0.0.1:4433", "webpki": false },
385        });
386        assert!(decode_service_entry(&bad).is_err());
387
388        let unknown = json!({ "type": "OnionTransport", "serviceEndpoint": {} });
389        assert!(decode_service_entry(&unknown).is_err());
390    }
391
392    #[test]
393    fn rejects_malformed_multibase() {
394        // Wrong multicodec prefix (a sha2-256 multihash where an ed25519 key is expected).
395        let entry = json!({
396            "type": "IrohTransport",
397            "serviceEndpoint": { "nodeId": multibase_encode(&MULTIHASH_SHA2_256, &[0u8; 32]), "relays": [] },
398        });
399        assert!(decode_service_entry(&entry).is_err());
400    }
401}