Skip to main content

hyprstream_rpc/
did_web.rs

1//! `did:web` → dialable [`TransportConfig`] resolution (#279).
2//!
3//! The mesh's only live [`crate::resolver::Resolver`] is the
4//! [`crate::registry::EndpointRegistry`] (service-name → local endpoint). This
5//! module adds the *federated* reach path: a [`DidWebResolver`] that turns a
6//! `did:web` identifier into one-or-more dialable [`TransportConfig`]s by
7//! fetching the subject's DID document and decoding its typed transport
8//! `service` entries.
9//!
10//! # Layering
11//!
12//! - **DID → URL** ([`did_web_to_url`]) — pure, per the did:web spec.
13//! - **DID-doc → reach** ([`transport_entries`] / [`preferred_transport`]) —
14//!   reuses [`crate::service_entry::decode_service_entry`] (the canonical
15//!   transport codec; this module never re-implements transport decoding) and
16//!   applies a deterministic preference order.
17//! - **Fetch + cache** ([`DidDocFetcher`]) — abstracted behind a trait so the
18//!   parse/decode path is testable with an injected fixture (no live network).
19//!   The native HTTPS implementation lives in [`HttpDidDocFetcher`] (TTL-cached,
20//!   mirroring the JWKS fetch+cache posture in `FederationKeyResolver`).
21//!
22//! # Scope (#279)
23//!
24//! Transport **reach** only. Peer *identity* anchoring (`#mesh` ML-DSA, the
25//! PQ trust store) is #157/#154/#137 (already landed) and is NOT done here.
26//! `did:key` resolution is #281 (a later ticket); only `did:web` here.
27
28use anyhow::{anyhow, bail, Result};
29use async_trait::async_trait;
30use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
31use serde_json::Value;
32
33use crate::did_url::percent_decode;
34use crate::registry::SocketKind;
35use crate::resolver::Resolver;
36use crate::service_entry::{decode_service_entry, DecodedEntry};
37use crate::transport::{EndpointType, TransportConfig};
38
39/// Parse a DID document while rejecting duplicate JSON object keys at every
40/// depth. `serde_json::Value` otherwise keeps only the last duplicate key,
41/// which makes the value ambiguous to another DID-document consumer that
42/// keeps the first one instead.
43pub(crate) fn parse_did_document_no_duplicates(body: &[u8], url: &str) -> Result<Value> {
44    serde_json::from_slice::<NoDuplicateJson>(body)
45        .map(|document| document.0)
46        .map_err(|e| anyhow!("DID document at {url} is invalid or ambiguous JSON: {e}"))
47}
48
49struct NoDuplicateJson(Value);
50
51impl<'de> Deserialize<'de> for NoDuplicateJson {
52    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
53    where
54        D: Deserializer<'de>,
55    {
56        struct NoDuplicateVisitor;
57
58        impl<'de> Visitor<'de> for NoDuplicateVisitor {
59            type Value = Value;
60
61            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62                formatter.write_str("valid JSON without duplicate object keys")
63            }
64
65            fn visit_bool<E: de::Error>(self, value: bool) -> std::result::Result<Value, E> {
66                Ok(Value::Bool(value))
67            }
68
69            fn visit_i64<E: de::Error>(self, value: i64) -> std::result::Result<Value, E> {
70                Ok(Value::Number(value.into()))
71            }
72
73            fn visit_u64<E: de::Error>(self, value: u64) -> std::result::Result<Value, E> {
74                Ok(Value::Number(value.into()))
75            }
76
77            fn visit_f64<E: de::Error>(self, value: f64) -> std::result::Result<Value, E> {
78                serde_json::Number::from_f64(value)
79                    .map(Value::Number)
80                    .ok_or_else(|| E::custom("JSON number is not finite"))
81            }
82
83            fn visit_str<E: de::Error>(self, value: &str) -> std::result::Result<Value, E> {
84                Ok(Value::String(value.to_owned()))
85            }
86
87            fn visit_string<E: de::Error>(self, value: String) -> std::result::Result<Value, E> {
88                Ok(Value::String(value))
89            }
90
91            fn visit_none<E: de::Error>(self) -> std::result::Result<Value, E> {
92                Ok(Value::Null)
93            }
94
95            fn visit_unit<E: de::Error>(self) -> std::result::Result<Value, E> {
96                Ok(Value::Null)
97            }
98
99            fn visit_seq<A: SeqAccess<'de>>(
100                self,
101                mut seq: A,
102            ) -> std::result::Result<Value, A::Error> {
103                let mut values = Vec::new();
104                while let Some(value) = seq.next_element::<NoDuplicateJson>()? {
105                    values.push(value.0);
106                }
107                Ok(Value::Array(values))
108            }
109
110            fn visit_map<A: MapAccess<'de>>(
111                self,
112                mut map: A,
113            ) -> std::result::Result<Value, A::Error> {
114                let mut keys = std::collections::HashSet::new();
115                let mut values = serde_json::Map::new();
116                while let Some(key) = map.next_key::<String>()? {
117                    if !keys.insert(key.clone()) {
118                        return Err(de::Error::custom(format!(
119                            "duplicate JSON object key `{key}`"
120                        )));
121                    }
122                    let value = map.next_value::<NoDuplicateJson>()?;
123                    values.insert(key, value.0);
124                }
125                Ok(Value::Object(values))
126            }
127        }
128
129        deserializer.deserialize_any(NoDuplicateVisitor).map(Self)
130    }
131}
132
133// ── did:web → URL derivation ──────────────────────────────────────────────────
134
135/// Derive the HTTPS DID-document URL for a `did:web` identifier, per the did:web
136/// spec (<https://w3c-ccg.github.io/did-method-web/#read-resolve>).
137///
138/// Two forms:
139///
140/// - **Bare host** — `did:web:{host}` → `https://{host}/.well-known/did.json`.
141///   `{host}` may carry a percent-encoded port (`%3A` → `:`), e.g.
142///   `did:web:localhost%3A8443` → `https://localhost:8443/.well-known/did.json`.
143/// - **Path** — `did:web:{host}:{p1}:{p2}…` → `https://{host}/{p1}/{p2}…/did.json`.
144///   The method-specific identifier's colons separate path segments; within each
145///   segment, percent-encoding is decoded (so a literal colon in a segment is
146///   `%3A`). Only the *first* segment is the host (it alone may carry a port).
147///
148/// Returns `Err` if the input is not a `did:web` identifier or has an empty host.
149pub fn did_web_to_url(did: &str) -> Result<String> {
150    // Strip any DID URL fragment / query (we resolve the base document).
151    let did = did.split(['#', '?']).next().unwrap_or(did);
152    let msi = did
153        .strip_prefix("did:web:")
154        .ok_or_else(|| anyhow!("not a did:web identifier: {did}"))?;
155    if msi.is_empty() {
156        bail!("did:web has empty method-specific identifier: {did}");
157    }
158
159    // Colons delimit the host then path segments; percent-decode each.
160    let mut segments = msi.split(':');
161    let host_raw = segments.next().unwrap_or_default();
162    let host = percent_decode(host_raw)?;
163    if host.is_empty() {
164        bail!("did:web has empty host: {did}");
165    }
166    // SECURITY: a percent-decoded host may legitimately carry a port
167    // (`host:port`, the only place `:` survives decoding here), but must never
168    // contain path-y / control content that the `url` crate could normalize into
169    // a different authority or inject a path. Reject `/`, `\`, and NUL.
170    validate_host_segment(&host, did)?;
171
172    // SECURITY: percent-decoding a path segment can yield `/` (`%2F`), `..`
173    // (`%2E%2E`), `\`, or NUL — all of which the `url` crate would normalize into
174    // a DIFFERENT document path (path traversal). Reject any such segment, plus
175    // `.`/`..`/empty, before joining. (`split` already drops the empty segments
176    // produced by consecutive colons; this also rejects a segment that decodes to
177    // empty.)
178    let mut path_segments: Vec<String> = Vec::new();
179    for raw in segments.filter(|s| !s.is_empty()) {
180        let seg = percent_decode(raw)?;
181        validate_path_segment(&seg, did)?;
182        path_segments.push(seg);
183    }
184
185    if path_segments.is_empty() {
186        // Bare host form → well-known document.
187        Ok(format!("https://{host}/.well-known/did.json"))
188    } else {
189        // Path form → document at the joined path.
190        Ok(format!(
191            "https://{host}/{}/did.json",
192            path_segments.join("/")
193        ))
194    }
195}
196
197/// Reject a decoded host that contains path-injecting or control characters.
198///
199/// A did:web host may carry an encoded port (`%3A` → `:`), so `:` is allowed
200/// here, but `/`, `\`, and NUL would let an attacker inject a path or smuggle a
201/// different authority once interpolated into the URL.
202fn validate_host_segment(host: &str, did: &str) -> Result<()> {
203    if host.contains(['/', '\\', '\0']) {
204        bail!("did:web host contains an illegal character (`/`, `\\`, or NUL): {did}");
205    }
206    Ok(())
207}
208
209/// Reject a decoded path segment that would cause path traversal / injection.
210///
211/// After percent-decoding, a segment must be a single non-empty path component:
212/// not `.` or `..`, and free of `/`, `\`, and NUL. This blocks `%2F`/`%2E%2E`
213/// style segments that the `url` crate would otherwise normalize into a
214/// different document path.
215fn validate_path_segment(seg: &str, did: &str) -> Result<()> {
216    if seg.is_empty() || seg == "." || seg == ".." {
217        bail!("did:web path segment is empty, `.`, or `..` (traversal): {did}");
218    }
219    if seg.contains(['/', '\\', '\0']) {
220        bail!("did:web path segment contains an illegal character (`/`, `\\`, or NUL): {did}");
221    }
222    Ok(())
223}
224
225// ── DID-doc → reach (preference-ordered) ──────────────────────────────────────
226
227/// Decode all typed transport `service` entries from a DID document into
228/// dialable [`DecodedEntry`]s, in **preference order**.
229///
230/// Preference (deterministic):
231///   1. By transport class: `IrohTransport` before `QuicTransport`. This is a
232///      reach preference only; neither carrier supplies application identity.
233///   2. Within a class, document order is preserved (stable sort) — operators
234///      can express secondary preference by ordering entries in the doc.
235///
236/// Entries that aren't recognized transport services (`HyprstreamService`,
237/// `AtprotoPersonalDataServer`, etc.) or that fail to decode are skipped
238/// silently — a DID document with no transport reach resolves to an **empty**
239/// vec (graceful), not an error.
240pub fn transport_entries(doc: &Value) -> Vec<DecodedEntry> {
241    let Some(services) = doc.get("service").and_then(Value::as_array) else {
242        return Vec::new();
243    };
244
245    // (preference_rank, doc_index, decoded)
246    let mut ranked: Vec<(u8, usize, DecodedEntry)> = Vec::new();
247    for (idx, entry) in services.iter().enumerate() {
248        let ty = entry
249            .get("type")
250            .and_then(Value::as_str)
251            .unwrap_or_default();
252        let rank = match ty {
253            "IrohTransport" => 0,
254            "QuicTransport" => 1,
255            "OnionTransport" => {
256                // The DID-doc builder may emit OnionTransport, but neither
257                // `service_entry::decode_service_entry` nor the `dial`/`dial_stream`
258                // layer can represent or dial an onion endpoint yet (there is no
259                // `EndpointType::Onion`). Don't silently drop it — note that a
260                // reachable onion entry was skipped so it's diagnosable.
261                // TODO(onion): #279 — add an onion EndpointType + dial support and
262                // fold this into the preference order (after quic).
263                tracing::debug!(
264                    service_type = %ty,
265                    "skipping OnionTransport DID-doc reach: onion is not yet dialable (no EndpointType::Onion)"
266                );
267                continue;
268            }
269            // Not a transport service entry — skip without attempting to decode.
270            _ => continue,
271        };
272        // `decode_service_entry` is the canonical codec; tolerate per-entry
273        // failures (e.g. a malformed pin) by skipping rather than failing the
274        // whole resolve.
275        match decode_service_entry(entry) {
276            Ok(decoded) => ranked.push((rank, idx, decoded)),
277            Err(e) => {
278                tracing::debug!(error = %e, service_type = %ty, "skipping undecodable transport service entry");
279            }
280        }
281    }
282
283    // Stable sort by (rank, doc index): preserves document order within a class.
284    ranked.sort_by_key(|(rank, idx, _)| (*rank, *idx));
285    ranked.into_iter().map(|(_, _, d)| d).collect()
286}
287
288/// The single most-preferred transport [`TransportConfig`] from a DID document,
289/// optionally constrained to a [`SocketKind`].
290///
291/// When `kind` is `Some(SocketKind::Quic)`, only QUIC entries are considered
292/// (the [`Resolver`] contract asks for a specific socket kind). `None` returns
293/// the overall top preference from [`transport_entries`]. Returns `None` when no
294/// matching reach exists.
295pub fn preferred_transport(doc: &Value, kind: Option<SocketKind>) -> Option<TransportConfig> {
296    let entries = transport_entries(doc);
297    entries
298        .into_iter()
299        .find(|d| match kind {
300            Some(SocketKind::Quic) => matches!(d.config.endpoint, EndpointType::Quic { .. }),
301            // The DID-doc reach is always network transport (Iroh/Quic); any
302            // other requested kind has no federated reach to offer.
303            Some(_) => false,
304            None => true,
305        })
306        .map(|d| d.config)
307}
308
309// ── DID-doc → verification-method keys (#137 admission stage 2) ────────────────
310
311// The `did:key` (Ed25519) codec — `MULTICODEC_ED25519_PUB`,
312// `decode_ed25519_multikey`, `did_key_to_ed25519`, `ed25519_to_did_key` — lives
313// in the cross-target [`crate::did_key`] module so the native `did_web` resolver
314// (#279/#137/#281) share one implementation and cannot drift. WASM iroh reach
315// APIs intentionally do not consume it. These are re-exported here so
316// existing `crate::did_web::*` callers (admission gate, federation tests) are
317// unaffected.
318pub use crate::did_key::{
319    decode_ed25519_multikey, decode_multikey, did_key_to_ed25519, ed25519_to_did_key,
320    MULTICODEC_ML_DSA_65_PUB,
321};
322// Only the test multikey helper references the raw multicodec constant now.
323#[cfg(test)]
324use crate::did_key::MULTICODEC_ED25519_PUB;
325
326/// Whether `did` is a `did:key` identifier (the self-certifying interop arm).
327///
328/// The admission gate (#137) uses this to route a `did:key` peer down the
329/// self-certifying path (the key *is* the identity — no DID-doc resolution /
330/// fetch) instead of the `did:web` resolver path.
331pub fn is_did_key(did: &str) -> bool {
332    did.starts_with("did:key:")
333}
334
335/// Extract every Ed25519 public key published in a DID document's
336/// `verificationMethod` array, decoded to raw 32-byte keys (#137 stage 2).
337///
338/// Only `Multikey` / `Ed25519VerificationKey2020`-shaped entries with a
339/// `publicKeyMultibase` carrying the `ed25519-pub` multicodec are returned (the
340/// identity VMs such as `#mesh`). Entries with a different
341/// codec, a non-multibase encoding (e.g. `publicKeyJwk`-only), or that fail to
342/// decode are skipped — a malformed VM must not be admitted, and a doc with no
343/// Ed25519 VM yields an **empty** vec (the caller treats empty as "no match →
344/// reject", preserving §4.4 fail-closed posture).
345pub fn verification_method_ed25519_keys(doc: &Value) -> Vec<[u8; 32]> {
346    let Some(vms) = doc.get("verificationMethod").and_then(Value::as_array) else {
347        return Vec::new();
348    };
349    let mut keys = Vec::new();
350    for vm in vms {
351        let Some(mb) = vm.get("publicKeyMultibase").and_then(Value::as_str) else {
352            continue;
353        };
354        match decode_ed25519_multikey(mb) {
355            Ok(k) => keys.push(k),
356            Err(e) => {
357                tracing::debug!(error = %e, "skipping undecodable verificationMethod Multikey");
358            }
359        }
360    }
361    keys
362}
363
364/// multicodec `x25519-pub` unsigned-varint prefix (matches the publisher in
365/// `hyprstream::services::oauth::did_document`).
366const MULTICODEC_X25519_PUB: [u8; 2] = [0xec, 0x01];
367/// multicodec `mlkem-768-pub` unsigned-varint prefix.
368const MULTICODEC_ML_KEM_768_PUB: [u8; 2] = [0x8c, 0x24];
369
370/// Extract the `#mesh-kem` hybrid-KEM recipient public from a DID document's
371/// `keyAgreement` relationship (#1137 remote-node bootstrap).
372///
373/// The publisher emits one `Multikey` VM per suite leg (X25519, then
374/// ML-KEM-768, multicodec-prefixed base58btc). The extractor requires EXACTLY
375/// one of each, reassembles them in the pinned suite's component order, and
376/// runs [`RecipientPublic::validate`] — a partial, duplicated, reordered, or
377/// malformed relationship is `None` (caller fails closed), never a partial
378/// recipient.
379pub fn mesh_kem_recipient(doc: &Value) -> Option<crate::crypto::hybrid_kem::RecipientPublic> {
380    let kas = doc.get("keyAgreement")?.as_array()?;
381    let mut x25519: Option<Vec<u8>> = None;
382    let mut mlkem768: Option<Vec<u8>> = None;
383    for vm in kas {
384        let mb = vm.get("publicKeyMultibase").and_then(Value::as_str)?;
385        let payload = bs58::decode(mb.strip_prefix('z')?).into_vec().ok()?;
386        let (codec, key) = payload.split_at_checked(2)?;
387        match codec {
388            c if c == MULTICODEC_X25519_PUB => {
389                if x25519.replace(key.to_vec()).is_some() {
390                    return None; // duplicated leg — ambiguous, fail closed
391                }
392            }
393            c if c == MULTICODEC_ML_KEM_768_PUB => {
394                if mlkem768.replace(key.to_vec()).is_some() {
395                    return None;
396                }
397            }
398            _ => return None, // unexpected keyAgreement leg — fail closed
399        }
400    }
401    let recipient = crate::crypto::hybrid_kem::RecipientPublic {
402        suite_id: crate::crypto::hybrid_kem::SuiteId::HyKemX25519MlKem768,
403        eks: vec![x25519?, mlkem768?],
404    };
405    recipient.validate().ok()?;
406    Some(recipient)
407}
408
409/// Extract every ML-DSA-65 verifying key published in a DID document's
410/// `verificationMethod` array (#579 multi-alg VM extraction).
411///
412/// The PQ counterpart to [`verification_method_ed25519_keys`]: it scans the same
413/// `verificationMethod` array but keeps the `Multikey` entries whose
414/// `publicKeyMultibase` carries the `ml-dsa-65-pub` multicodec (`0x1211`) — the
415/// mesh's `#mesh-pq` verification method. Each candidate is decoded via the
416/// codec-agile [`decode_multikey`] and validated as a real ML-DSA-65 key by
417/// [`crate::crypto::pq::ml_dsa_vk_from_bytes`] (a malformed / wrong-length key is
418/// skipped, never trusted). Ed25519 (`0xed01`) VMs decode to a different codec
419/// and are skipped here, so the two extractors partition the same document by
420/// algorithm without interfering.
421///
422/// A document with no ML-DSA-65 VM yields an **empty** vec (the classical-only
423/// case): the caller treats "no PQ anchor" as `Assurance::Classical`, not an
424/// error.
425pub fn verification_method_ml_dsa_65_keys(
426    doc: &Value,
427) -> Vec<crate::crypto::pq::MlDsaVerifyingKey> {
428    let Some(vms) = doc.get("verificationMethod").and_then(Value::as_array) else {
429        return Vec::new();
430    };
431    let mut keys = Vec::new();
432    for vm in vms {
433        let Some(mb) = vm.get("publicKeyMultibase").and_then(Value::as_str) else {
434            continue;
435        };
436        // Only ml-dsa-65-pub Multikeys; an ed25519 (or other) codec is not an
437        // error here — it belongs to the Ed25519 extractor — so skip quietly.
438        let raw = match decode_multikey(mb, &MULTICODEC_ML_DSA_65_PUB) {
439            Ok(raw) => raw,
440            Err(_) => continue,
441        };
442        match crate::crypto::pq::ml_dsa_vk_from_bytes(&raw) {
443            Ok(vk) => keys.push(vk),
444            Err(e) => {
445                tracing::debug!(error = %e, "skipping ml-dsa-65 verificationMethod: not a valid ML-DSA-65 key");
446            }
447        }
448    }
449    keys
450}
451
452/// Extract every Ed25519 public key from a JWKS document (RFC 7517), decoded to
453/// raw 32-byte keys (#137 stage 2, JWKS fallback path).
454///
455/// Mirrors `FederationKeyResolver::fetch_ed25519_key`'s parse: an OKP key with
456/// `crv == "Ed25519"` and a base64url `x` of exactly 32 bytes. Keys that don't
457/// match that shape (wrong `kty`/`crv`, malformed `x`) are skipped. A JWKS with
458/// no usable Ed25519 key yields an **empty** vec (→ no match → reject).
459///
460/// NOTE: this does not itself enforce a "federation"-tagged `use`; the caller
461/// supplies the federation JWKS document (e.g. the per-issuer `jwks_uri` already
462/// resolved/cached by `FederationKeyResolver`), and tag filtering, if any, is the
463/// caller's policy. This keeps the decode pure and reuses the existing JWKS cache
464/// rather than adding a new fetch pipeline.
465pub fn jwks_ed25519_keys(jwks: &Value) -> Vec<[u8; 32]> {
466    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
467    let Some(keys) = jwks.get("keys").and_then(Value::as_array) else {
468        return Vec::new();
469    };
470    let mut out = Vec::new();
471    for key in keys {
472        if key.get("kty").and_then(Value::as_str) != Some("OKP") {
473            continue;
474        }
475        if key.get("crv").and_then(Value::as_str) != Some("Ed25519") {
476            continue;
477        }
478        let Some(x) = key.get("x").and_then(Value::as_str) else {
479            continue;
480        };
481        match URL_SAFE_NO_PAD
482            .decode(x)
483            .ok()
484            .and_then(|raw| <[u8; 32]>::try_from(raw).ok())
485        {
486            Some(k) => out.push(k),
487            None => {
488                tracing::debug!("skipping JWKS OKP/Ed25519 key with malformed/wrong-length 'x'");
489            }
490        }
491    }
492    out
493}
494
495// ── fetcher abstraction ───────────────────────────────────────────────────────
496
497/// Fetches a DID document (parsed JSON) for a resolved HTTPS URL.
498///
499/// Abstracted so the resolver's parse/decode path is testable without a live
500/// network (inject a fixture). The native HTTPS+cache implementation is
501/// [`HttpDidDocFetcher`].
502#[async_trait]
503pub trait DidDocFetcher: Send + Sync {
504    /// Fetch and parse the DID document at `url` (already derived from the DID).
505    async fn fetch(&self, url: &str) -> Result<Value>;
506}
507
508// ── resolver ──────────────────────────────────────────────────────────────────
509
510/// A [`Resolver`] that turns a `did:web` identifier into a dialable
511/// [`TransportConfig`].
512///
513/// The resolver's `name` argument is the `did:web` identifier; the `kind`
514/// constrains the desired socket (today only [`SocketKind::Quic`] has a
515/// federated reach). Non-`did:web` names are rejected — chain this *behind* the
516/// registry resolver (see [`ChainedResolver`]) so local service-name lookups
517/// still work.
518pub struct DidWebResolver<F: DidDocFetcher> {
519    fetcher: F,
520}
521
522impl<F: DidDocFetcher> DidWebResolver<F> {
523    /// Construct a resolver over a document fetcher.
524    pub fn new(fetcher: F) -> Self {
525        Self { fetcher }
526    }
527
528    /// Resolve a `did:web` identifier to its preference-ordered reach list.
529    ///
530    /// Empty vec when the document has no transport service entries.
531    pub async fn resolve_all(&self, did: &str) -> Result<Vec<DecodedEntry>> {
532        let url = did_web_to_url(did)?;
533        let doc = self.fetcher.fetch(&url).await?;
534        Ok(transport_entries(&doc))
535    }
536
537    /// Resolve a `did:web` identifier to its **raw** DID document JSON.
538    ///
539    /// `resolve`/`resolve_all` discard everything but transport reach; the #137
540    /// admission gate needs the full document to read `verificationMethod` (the
541    /// peer's published Ed25519 keys). Reuses the same derive-URL + cached fetch
542    /// path — no new fetch/cache infra.
543    pub async fn resolve_document(&self, did: &str) -> Result<Value> {
544        let url = did_web_to_url(did)?;
545        self.fetcher.fetch(&url).await
546    }
547}
548
549#[async_trait]
550impl<F: DidDocFetcher> Resolver for DidWebResolver<F> {
551    async fn resolve(&self, name: &str, kind: SocketKind) -> Result<TransportConfig> {
552        let url = did_web_to_url(name)?;
553        let doc = self.fetcher.fetch(&url).await?;
554        preferred_transport(&doc, Some(kind)).ok_or_else(|| {
555            anyhow!("did:web {name}: no dialable {kind:?} transport reach in DID document")
556        })
557    }
558}
559
560/// Composes a primary resolver with a fallback: tries `primary` first, and on
561/// error falls back to `fallback`.
562///
563/// Use this to install [`DidWebResolver`] *without* clobbering the registry's
564/// local service-name resolution: `ChainedResolver::new(did_web, registry)`
565/// resolves `did:web:*` via the DID resolver and everything else via the
566/// registry (the DID resolver rejects non-`did:web` names, so it falls
567/// through). Install via [`crate::resolver::set_global`].
568pub struct ChainedResolver {
569    primary: std::sync::Arc<dyn Resolver>,
570    fallback: std::sync::Arc<dyn Resolver>,
571}
572
573impl ChainedResolver {
574    /// Try `primary`, fall back to `fallback` on error.
575    pub fn new(
576        primary: std::sync::Arc<dyn Resolver>,
577        fallback: std::sync::Arc<dyn Resolver>,
578    ) -> Self {
579        Self { primary, fallback }
580    }
581}
582
583#[async_trait]
584impl Resolver for ChainedResolver {
585    async fn resolve(&self, name: &str, kind: SocketKind) -> Result<TransportConfig> {
586        match self.primary.resolve(name, kind).await {
587            Ok(cfg) => Ok(cfg),
588            Err(primary_err) => self.fallback.resolve(name, kind).await.map_err(|fb_err| {
589                anyhow!(
590                    "resolve {name}: primary failed ({primary_err}); fallback failed ({fb_err})"
591                )
592            }),
593        }
594    }
595}
596
597/// Install a [`DidWebResolver`] as the global resolver, chained in front of the
598/// existing global resolver (typically the registry) so local service-name
599/// lookups still resolve.
600///
601/// No-op replacement of the global resolver if none is currently set: in that
602/// case the DID resolver is installed alone (callers should normally
603/// `registry::init()` first).
604pub fn install_chained<F: DidDocFetcher + 'static>(did_web: DidWebResolver<F>) {
605    let did_web: std::sync::Arc<dyn Resolver> = std::sync::Arc::new(did_web);
606    match crate::resolver::try_global() {
607        Some(existing) => {
608            crate::resolver::set_global(std::sync::Arc::new(ChainedResolver::new(
609                did_web, existing,
610            )));
611        }
612        None => crate::resolver::set_global(did_web),
613    }
614}
615
616// ── native HTTPS fetcher (TTL-cached) ─────────────────────────────────────────
617
618/// Maximum DID-document body we will buffer (1 MiB). A DID document is small;
619/// this ceiling bounds memory against a hostile or buggy peer streaming an
620/// unbounded body. Bodies larger than this are rejected.
621const MAX_DID_DOC_BYTES: usize = 1024 * 1024;
622
623/// Maximum number of cached DID documents. The cache is keyed by an
624/// attacker-influenceable URL, so it is bounded: on insert we sweep expired
625/// entries and, if still at the cap, evict the oldest (least-recently-fetched)
626/// entry. Keeps cache memory O(MAX_CACHE_ENTRIES) regardless of distinct DIDs.
627const MAX_CACHE_ENTRIES: usize = 256;
628
629/// Native HTTPS DID-document fetcher with a TTL cache.
630///
631/// Mirrors the JWKS fetch+cache posture in `FederationKeyResolver`
632/// (`crates/hyprstream/src/auth/federation.rs`): HTTPS-only by default, a
633/// `reqwest` client with a request timeout, and a single `Mutex`-guarded cache
634/// so concurrent misses for the same URL serialize on one fetch. The cache key
635/// is the resolved document URL.
636///
637/// HTTPS is required (did:web mandates it). A `Mutex` (not `RwLock`) serializes
638/// reads and writes so a second waiter re-checks after the first finishes.
639///
640/// # SSRF / DoS hardening
641///
642/// - **No redirects.** The client is built with
643///   [`reqwest::redirect::Policy::none()`]: the did:web spec retrieves the
644///   document by a direct HTTPS GET, so an upstream `302` to
645///   `http://169.254.169.254/…` or `http://127.0.0.1:…` cannot bypass the
646///   https-only check (SSRF). The https-only check on the resolved URL is kept.
647/// - **Bounded body.** Responses are read with a [`MAX_DID_DOC_BYTES`] ceiling
648///   (read N+1 bytes; error if exceeded) before JSON parsing — bounds memory.
649/// - **Bounded cache.** The TTL cache is capped at [`MAX_CACHE_ENTRIES`]
650///   (sweep-expired + evict-oldest on insert) so an attacker-driven flood of
651///   distinct DIDs cannot grow it without bound. Failures are never cached.
652pub struct HttpDidDocFetcher {
653    http: reqwest::Client,
654    cache: parking_lot::Mutex<std::collections::HashMap<String, CachedDoc>>,
655    ttl: std::time::Duration,
656}
657
658struct CachedDoc {
659    doc: Value,
660    fetched_at: std::time::Instant,
661}
662
663impl HttpDidDocFetcher {
664    /// Construct a fetcher with a cache TTL (mirrors the JWKS cache TTL default
665    /// of one hour; callers honoring per-issuer TTL should pass it through).
666    ///
667    /// Returns `Err` if the reqwest client fails to build — propagated rather
668    /// than swallowed (a `unwrap_or_default()` would yield a client WITHOUT the
669    /// configured timeout/redirect policy, defeating the SSRF/DoS hardening).
670    pub fn new(ttl: std::time::Duration) -> Result<Self> {
671        Self::build(ttl, None)
672    }
673
674    /// Construct a fetcher that additionally trusts an extra root certificate
675    /// (PEM), for private-PKI deployments whose did:web host terminates TLS
676    /// with an internal CA. This ADDS a trust anchor — the public WebPKI roots
677    /// remain enabled, and all other hardening (https-only, no redirects,
678    /// timeouts, size cap) is unchanged. Returns `Err` on an unreadable or
679    /// malformed PEM rather than silently degrading.
680    pub fn with_extra_root(ttl: std::time::Duration, extra_root_pem: &[u8]) -> Result<Self> {
681        Self::build(ttl, Some(extra_root_pem))
682    }
683
684    fn build(ttl: std::time::Duration, extra_root_pem: Option<&[u8]>) -> Result<Self> {
685        let mut builder = reqwest::Client::builder()
686            // SSRF: do NOT follow redirects. did:web is a direct HTTPS GET; a
687            // redirect to http://127.0.0.1 / link-local would bypass https-only.
688            .redirect(reqwest::redirect::Policy::none())
689            // Bound how long a connect/request can hang.
690            .connect_timeout(std::time::Duration::from_secs(10))
691            .timeout(std::time::Duration::from_secs(10));
692        if let Some(pem) = extra_root_pem {
693            let cert = reqwest::Certificate::from_pem(pem).map_err(|e| {
694                anyhow!("extra did:web TLS root is not a valid PEM certificate: {e}")
695            })?;
696            builder = builder.add_root_certificate(cert);
697        }
698        let http = builder
699            .build()
700            .map_err(|e| anyhow!("failed to build did:web HTTPS client: {e}"))?;
701        Ok(Self {
702            http,
703            cache: parking_lot::Mutex::new(std::collections::HashMap::new()),
704            ttl,
705        })
706    }
707}
708
709impl Default for HttpDidDocFetcher {
710    // The reqwest client builder is infallible by contract for this fixed
711    // config; surface a clear panic message if that ever changes rather than a
712    // silently-misconfigured client (the `unwrap_or_default()` anti-pattern).
713    #[allow(clippy::expect_used)]
714    fn default() -> Self {
715        // One hour, matching `default_client_jwks_uri_cache_ttl()`.
716        Self::new(std::time::Duration::from_secs(3600))
717            .expect("did:web HTTPS client must build with the default configuration")
718    }
719}
720
721#[async_trait]
722impl DidDocFetcher for HttpDidDocFetcher {
723    async fn fetch(&self, url: &str) -> Result<Value> {
724        // did:web is HTTPS-only.
725        if !url.starts_with("https://") {
726            bail!("did:web document URL must use https:// (got {url})");
727        }
728
729        // Cache hit (not expired)?
730        {
731            let cache = self.cache.lock();
732            if let Some(entry) = cache.get(url) {
733                if entry.fetched_at.elapsed() < self.ttl {
734                    return Ok(entry.doc.clone());
735                }
736            }
737        }
738
739        // Miss / expired — fetch over HTTPS (lock not held across await).
740        let resp = self.http.get(url).send().await?.error_for_status()?;
741        let body = read_capped(resp, MAX_DID_DOC_BYTES).await?;
742        let doc = parse_did_document_no_duplicates(&body, url)?;
743
744        {
745            let mut cache = self.cache.lock();
746            evict_for_insert(&mut cache, self.ttl);
747            cache.insert(
748                url.to_owned(),
749                CachedDoc {
750                    doc: doc.clone(),
751                    fetched_at: std::time::Instant::now(),
752                },
753            );
754        }
755        Ok(doc)
756    }
757}
758
759/// Read a response body with a hard ceiling: stream chunks and error if the
760/// accumulated size would exceed `max` bytes (memory-DoS guard). Returns the
761/// buffered body on success.
762async fn read_capped(resp: reqwest::Response, max: usize) -> Result<Vec<u8>> {
763    use futures::StreamExt;
764
765    // Fast reject when the server advertises an oversized body up front.
766    if let Some(len) = resp.content_length() {
767        if len > max as u64 {
768            bail!("did:web document exceeds {max}-byte cap (Content-Length {len})");
769        }
770    }
771
772    let mut buf: Vec<u8> = Vec::new();
773    let mut stream = resp.bytes_stream();
774    while let Some(chunk) = stream.next().await {
775        let chunk = chunk?;
776        push_capped(&mut buf, &chunk, max)?;
777    }
778    Ok(buf)
779}
780
781/// Append `chunk` to `buf`, erroring if the result would exceed `max` bytes.
782/// The cap-enforcement core of [`read_capped`], factored out for direct
783/// testing (constructing a real `reqwest::Response` cross-version is brittle).
784fn push_capped(buf: &mut Vec<u8>, chunk: &[u8], max: usize) -> Result<()> {
785    // Read up to max+1 bytes' worth: as soon as we cross the ceiling, error.
786    if buf.len() + chunk.len() > max {
787        bail!("did:web document exceeds {max}-byte cap");
788    }
789    buf.extend_from_slice(chunk);
790    Ok(())
791}
792
793/// Bound the cache before an insert: drop expired entries, then — if still at or
794/// over the cap — evict the oldest (least-recently-fetched) entry. Keeps size
795/// ≤ [`MAX_CACHE_ENTRIES`] after the caller's subsequent insert.
796fn evict_for_insert(
797    cache: &mut std::collections::HashMap<String, CachedDoc>,
798    ttl: std::time::Duration,
799) {
800    // Sweep expired entries first (cheap, also reclaims stale memory).
801    cache.retain(|_, entry| entry.fetched_at.elapsed() < ttl);
802
803    // If still at/over the cap, evict the oldest until there's room for one more.
804    while cache.len() >= MAX_CACHE_ENTRIES {
805        let Some(oldest) = cache
806            .iter()
807            .min_by_key(|(_, entry)| entry.fetched_at)
808            .map(|(k, _)| k.clone())
809        else {
810            break;
811        };
812        cache.remove(&oldest);
813    }
814}
815
816#[cfg(test)]
817#[allow(clippy::unwrap_used, clippy::expect_used)]
818mod tests {
819    use super::*;
820    use crate::service_entry::{encode_iroh, encode_quic};
821    use crate::transport::QuicServerAuth;
822    use serde_json::json;
823
824    #[test]
825    fn parser_rejects_ambiguous_duplicate_keys() {
826        assert!(parse_did_document_no_duplicates(
827            br#"{"id":"did:web:example.com","id":"did:web:attacker.example"}"#,
828            "https://example.com/.well-known/did.json",
829        )
830        .is_err());
831    }
832
833    // ── did:web → URL derivation ──────────────────────────────────────────
834
835    #[test]
836    fn url_bare_host() {
837        assert_eq!(
838            did_web_to_url("did:web:example.com").unwrap(),
839            "https://example.com/.well-known/did.json"
840        );
841    }
842
843    #[test]
844    fn url_bare_host_with_encoded_port() {
845        // did:web:localhost%3A8443 → https://localhost:8443/.well-known/did.json
846        assert_eq!(
847            did_web_to_url("did:web:localhost%3A8443").unwrap(),
848            "https://localhost:8443/.well-known/did.json"
849        );
850    }
851
852    #[test]
853    fn url_path_form() {
854        assert_eq!(
855            did_web_to_url("did:web:example.com:users:alice").unwrap(),
856            "https://example.com/users/alice/did.json"
857        );
858    }
859
860    #[test]
861    fn url_path_form_with_encoded_port() {
862        assert_eq!(
863            did_web_to_url("did:web:127.0.0.1%3A6791:users:12345").unwrap(),
864            "https://127.0.0.1:6791/users/12345/did.json"
865        );
866    }
867
868    #[test]
869    fn url_strips_fragment_and_query() {
870        assert_eq!(
871            did_web_to_url("did:web:example.com#mesh").unwrap(),
872            "https://example.com/.well-known/did.json"
873        );
874        assert_eq!(
875            did_web_to_url("did:web:example.com:users:alice?versionId=1").unwrap(),
876            "https://example.com/users/alice/did.json"
877        );
878    }
879
880    #[test]
881    fn url_rejects_non_did_web() {
882        assert!(did_web_to_url("did:key:z6Mk...").is_err());
883        assert!(did_web_to_url("https://example.com").is_err());
884        assert!(did_web_to_url("did:web:").is_err());
885    }
886
887    #[test]
888    fn url_rejects_invalid_utf8_percent_encoding() {
889        assert!(did_web_to_url("did:web:example%FF.com").is_err());
890        assert!(did_web_to_url("did:web:example.com:path%FE").is_err());
891    }
892
893    #[test]
894    fn url_rejects_path_traversal() {
895        // Encoded `/` in the host smuggles a path.
896        assert!(did_web_to_url("did:web:victim.com:..%2F..%2Fsecret").is_err());
897        // A path segment that decodes to `..` (traversal).
898        assert!(did_web_to_url("did:web:victim.com:%2E%2E").is_err());
899        assert!(did_web_to_url("did:web:victim.com:..").is_err());
900        // A path segment that decodes to contain `/`.
901        assert!(did_web_to_url("did:web:victim.com:a%2Fb").is_err());
902        // A path segment that decodes to `.`.
903        assert!(did_web_to_url("did:web:victim.com:%2E").is_err());
904        // Backslash / NUL in a segment.
905        assert!(did_web_to_url("did:web:victim.com:a%5Cb").is_err());
906        assert!(did_web_to_url("did:web:victim.com:a%00b").is_err());
907        // Host with an injected path separator.
908        assert!(did_web_to_url("did:web:victim.com%2Fevil").is_err());
909        // Sanity: an encoded-port host with a legit path still works (regression).
910        assert_eq!(
911            did_web_to_url("did:web:127.0.0.1%3A6791:users:12345").unwrap(),
912            "https://127.0.0.1:6791/users/12345/did.json"
913        );
914    }
915
916    // ── DID-doc → reach extraction + preference order ──────────────────────
917
918    /// Build a DID document with the given (already-encoded) transport service
919    /// entries, matching the `did_document.rs` builder's shape.
920    fn doc_with_services(services: Vec<Value>) -> Value {
921        json!({
922            "@context": ["https://www.w3.org/ns/did/v1"],
923            "id": "did:web:example.com",
924            "verificationMethod": [],
925            "service": services,
926        })
927    }
928
929    fn iroh_service(node_id: [u8; 32]) -> Value {
930        json!({
931            "id": "did:web:example.com#iroh",
932            "type": "IrohTransport",
933            "serviceEndpoint": encode_iroh(&node_id, &["https://relay.example".to_owned()], &["hyprstream-rpc/1", "moql"]),
934        })
935    }
936
937    fn quic_service(uri: &str, hash: [u8; 32]) -> Value {
938        let auth = QuicServerAuth::pinned(vec![hash]).unwrap();
939        json!({
940            "id": "did:web:example.com#quic",
941            "type": "QuicTransport",
942            "serviceEndpoint": encode_quic(uri, &auth, &["hyprstream-rpc/1", "moql"]),
943        })
944    }
945
946    #[test]
947    fn extract_orders_iroh_before_quic() {
948        // Doc order: quic first, then iroh — preference must reorder iroh first.
949        let doc = doc_with_services(vec![
950            quic_service("https://10.0.0.1:4433", [1u8; 32]),
951            iroh_service([7u8; 32]),
952        ]);
953        let entries = transport_entries(&doc);
954        assert_eq!(entries.len(), 2);
955        assert!(
956            matches!(entries[0].config.endpoint, EndpointType::Iroh { .. }),
957            "iroh must be preferred first"
958        );
959        assert!(matches!(
960            entries[1].config.endpoint,
961            EndpointType::Quic { .. }
962        ));
963        // Neither transport entry carries an application identity key.
964    }
965
966    #[test]
967    fn extract_preserves_doc_order_within_class() {
968        let doc = doc_with_services(vec![
969            quic_service("https://10.0.0.1:4433", [1u8; 32]),
970            quic_service("https://10.0.0.2:4433", [2u8; 32]),
971        ]);
972        let entries = transport_entries(&doc);
973        assert_eq!(entries.len(), 2);
974        match (&entries[0].config.endpoint, &entries[1].config.endpoint) {
975            (EndpointType::Quic { addr: a, .. }, EndpointType::Quic { addr: b, .. }) => {
976                assert_eq!(a.to_string(), "10.0.0.1:4433");
977                assert_eq!(b.to_string(), "10.0.0.2:4433");
978            }
979            other => panic!("expected two Quic entries, got {other:?}"),
980        }
981    }
982
983    #[test]
984    fn extract_skips_non_transport_services() {
985        let doc = doc_with_services(vec![
986            json!({
987                "id": "did:web:example.com#hyprstream",
988                "type": "HyprstreamService",
989                "serviceEndpoint": "https://example.com",
990            }),
991            json!({
992                "id": "did:web:example.com#atproto_pds",
993                "type": "AtprotoPersonalDataServer",
994                "serviceEndpoint": "https://example.com",
995            }),
996            quic_service("https://10.0.0.1:4433", [1u8; 32]),
997        ]);
998        let entries = transport_entries(&doc);
999        assert_eq!(entries.len(), 1);
1000        assert!(matches!(
1001            entries[0].config.endpoint,
1002            EndpointType::Quic { .. }
1003        ));
1004    }
1005
1006    #[test]
1007    fn extract_no_transport_entries_is_empty() {
1008        // A doc with only non-transport services → empty (graceful, not panic/err).
1009        let doc = doc_with_services(vec![json!({
1010            "id": "did:web:example.com#hyprstream",
1011            "type": "HyprstreamService",
1012            "serviceEndpoint": "https://example.com",
1013        })]);
1014        assert!(transport_entries(&doc).is_empty());
1015
1016        // A doc with no `service` array at all → empty.
1017        let doc = json!({ "id": "did:web:example.com", "verificationMethod": [] });
1018        assert!(transport_entries(&doc).is_empty());
1019    }
1020
1021    #[test]
1022    fn extract_skips_undecodable_entry_gracefully() {
1023        // A QuicTransport with webpki=false AND no certHashes is undecodable
1024        // (no auth). It must be skipped, not panic, and the valid iroh remains.
1025        let doc = doc_with_services(vec![
1026            json!({
1027                "id": "did:web:example.com#quic",
1028                "type": "QuicTransport",
1029                "serviceEndpoint": { "uri": "https://10.0.0.1:4433", "webpki": false },
1030            }),
1031            iroh_service([7u8; 32]),
1032        ]);
1033        let entries = transport_entries(&doc);
1034        assert_eq!(entries.len(), 1);
1035        assert!(matches!(
1036            entries[0].config.endpoint,
1037            EndpointType::Iroh { .. }
1038        ));
1039    }
1040
1041    #[test]
1042    fn extract_skips_onion_transport() {
1043        // OnionTransport is recognized but not yet dialable — it must be skipped
1044        // (logged) and the valid quic entry must remain.
1045        let doc = doc_with_services(vec![
1046            json!({
1047                "id": "did:web:example.com#onion",
1048                "type": "OnionTransport",
1049                "serviceEndpoint": { "uri": "abcdef.onion:443" },
1050            }),
1051            quic_service("https://10.0.0.1:4433", [1u8; 32]),
1052        ]);
1053        let entries = transport_entries(&doc);
1054        assert_eq!(entries.len(), 1);
1055        assert!(matches!(
1056            entries[0].config.endpoint,
1057            EndpointType::Quic { .. }
1058        ));
1059    }
1060
1061    #[test]
1062    fn preferred_transport_filters_by_kind() {
1063        let doc = doc_with_services(vec![
1064            iroh_service([7u8; 32]),
1065            quic_service("https://10.0.0.1:4433", [1u8; 32]),
1066        ]);
1067        // None → overall top preference = iroh.
1068        assert!(matches!(
1069            preferred_transport(&doc, None).unwrap().endpoint,
1070            EndpointType::Iroh { .. }
1071        ));
1072        // Quic kind → the quic entry, skipping the (preferred) iroh.
1073        assert!(matches!(
1074            preferred_transport(&doc, Some(SocketKind::Quic))
1075                .unwrap()
1076                .endpoint,
1077            EndpointType::Quic { .. }
1078        ));
1079        // A kind with no federated reach → None.
1080        assert!(preferred_transport(&doc, Some(SocketKind::Rep)).is_none());
1081    }
1082
1083    // ── resolver over an injected fixture fetcher (no network) ─────────────
1084
1085    struct FixtureFetcher {
1086        doc: Value,
1087    }
1088
1089    #[async_trait]
1090    impl DidDocFetcher for FixtureFetcher {
1091        async fn fetch(&self, url: &str) -> Result<Value> {
1092            assert_eq!(url, "https://example.com/.well-known/did.json");
1093            Ok(self.doc.clone())
1094        }
1095    }
1096
1097    #[tokio::test]
1098    async fn resolver_resolves_quic_from_fixture_doc() {
1099        let doc = doc_with_services(vec![
1100            iroh_service([7u8; 32]),
1101            quic_service("https://10.0.0.1:4433", [1u8; 32]),
1102        ]);
1103        let resolver = DidWebResolver::new(FixtureFetcher { doc });
1104        let cfg = resolver
1105            .resolve("did:web:example.com", SocketKind::Quic)
1106            .await
1107            .unwrap();
1108        match cfg.endpoint {
1109            EndpointType::Quic { addr, .. } => assert_eq!(addr.to_string(), "10.0.0.1:4433"),
1110            other => panic!("expected Quic, got {other:?}"),
1111        }
1112    }
1113
1114    #[tokio::test]
1115    async fn resolver_resolve_all_returns_preference_order() {
1116        let doc = doc_with_services(vec![
1117            quic_service("https://10.0.0.1:4433", [1u8; 32]),
1118            iroh_service([7u8; 32]),
1119        ]);
1120        let resolver = DidWebResolver::new(FixtureFetcher { doc });
1121        let all = resolver.resolve_all("did:web:example.com").await.unwrap();
1122        assert_eq!(all.len(), 2);
1123        assert!(matches!(all[0].config.endpoint, EndpointType::Iroh { .. }));
1124        assert!(matches!(all[1].config.endpoint, EndpointType::Quic { .. }));
1125    }
1126
1127    #[tokio::test]
1128    async fn resolver_empty_doc_errors_for_kind() {
1129        let doc = doc_with_services(vec![]);
1130        let resolver = DidWebResolver::new(FixtureFetcher { doc });
1131        let res = resolver
1132            .resolve("did:web:example.com", SocketKind::Quic)
1133            .await;
1134        assert!(
1135            res.is_err(),
1136            "no reach → resolve() errors (resolve_all would be empty)"
1137        );
1138    }
1139
1140    // ── chaining ───────────────────────────────────────────────────────────
1141
1142    struct AlwaysOk(TransportConfig);
1143    #[async_trait]
1144    impl Resolver for AlwaysOk {
1145        async fn resolve(&self, _name: &str, _kind: SocketKind) -> Result<TransportConfig> {
1146            Ok(self.0.clone())
1147        }
1148    }
1149    struct AlwaysErr;
1150    #[async_trait]
1151    impl Resolver for AlwaysErr {
1152        async fn resolve(&self, _name: &str, _kind: SocketKind) -> Result<TransportConfig> {
1153            bail!("nope")
1154        }
1155    }
1156
1157    #[tokio::test]
1158    async fn chained_falls_back_on_primary_error() {
1159        let fallback = TransportConfig::inproc("hyprstream/local");
1160        let chained = ChainedResolver::new(
1161            std::sync::Arc::new(AlwaysErr),
1162            std::sync::Arc::new(AlwaysOk(fallback.clone())),
1163        );
1164        let cfg = chained.resolve("anything", SocketKind::Rep).await.unwrap();
1165        assert_eq!(cfg.endpoint_string(), fallback.endpoint_string());
1166    }
1167
1168    #[tokio::test]
1169    async fn chained_prefers_primary() {
1170        let primary = TransportConfig::inproc("hyprstream/primary");
1171        let fallback = TransportConfig::inproc("hyprstream/fallback");
1172        let chained = ChainedResolver::new(
1173            std::sync::Arc::new(AlwaysOk(primary.clone())),
1174            std::sync::Arc::new(AlwaysOk(fallback)),
1175        );
1176        let cfg = chained.resolve("anything", SocketKind::Rep).await.unwrap();
1177        assert_eq!(cfg.endpoint_string(), primary.endpoint_string());
1178    }
1179
1180    // ── fetcher hardening (SSRF / DoS) ─────────────────────────────────────
1181
1182    #[test]
1183    fn fetcher_constructs_with_hardened_client() {
1184        // The constructor returns Ok (client built with the redirect/timeout
1185        // config). A build failure would surface here rather than a silent
1186        // unwrap_or_default() yielding an unhardened client.
1187        let f = HttpDidDocFetcher::new(std::time::Duration::from_secs(1));
1188        assert!(f.is_ok(), "hardened client must build");
1189        // Default is also infallible by contract.
1190        let _ = HttpDidDocFetcher::default();
1191    }
1192
1193    #[tokio::test]
1194    async fn fetcher_rejects_non_https() {
1195        let f = HttpDidDocFetcher::new(std::time::Duration::from_secs(1)).unwrap();
1196        let err = f
1197            .fetch("http://example.com/.well-known/did.json")
1198            .await
1199            .unwrap_err();
1200        assert!(
1201            err.to_string().contains("https"),
1202            "must reject non-https: {err}"
1203        );
1204    }
1205
1206    #[test]
1207    fn push_capped_rejects_oversized_body() {
1208        // Accumulating past the cap (across chunks) must error at the boundary,
1209        // not buffer the whole oversized body (memory-DoS guard).
1210        let mut buf = Vec::new();
1211        // Fill to the cap exactly — OK.
1212        assert!(push_capped(&mut buf, &vec![b'x'; MAX_DID_DOC_BYTES], MAX_DID_DOC_BYTES).is_ok());
1213        assert_eq!(buf.len(), MAX_DID_DOC_BYTES);
1214        // One more byte crosses the ceiling — Err.
1215        let err = push_capped(&mut buf, b"!", MAX_DID_DOC_BYTES).unwrap_err();
1216        assert!(err.to_string().contains("cap"), "{err}");
1217        // Buffer was NOT grown past the cap.
1218        assert_eq!(buf.len(), MAX_DID_DOC_BYTES);
1219    }
1220
1221    #[test]
1222    fn push_capped_accepts_under_cap() {
1223        let mut buf = Vec::new();
1224        push_capped(&mut buf, b"{\"ok\":", 16).unwrap();
1225        push_capped(&mut buf, b"true}", 16).unwrap();
1226        assert_eq!(buf, b"{\"ok\":true}");
1227    }
1228
1229    #[test]
1230    fn cache_is_bounded() {
1231        let mut cache: std::collections::HashMap<String, CachedDoc> =
1232            std::collections::HashMap::new();
1233        let ttl = std::time::Duration::from_secs(3600);
1234        // Insert far more than the cap; eviction must keep it bounded.
1235        for i in 0..(MAX_CACHE_ENTRIES * 3) {
1236            evict_for_insert(&mut cache, ttl);
1237            cache.insert(
1238                format!("https://h{i}.example/.well-known/did.json"),
1239                CachedDoc {
1240                    doc: json!({ "i": i }),
1241                    fetched_at: std::time::Instant::now(),
1242                },
1243            );
1244            assert!(
1245                cache.len() <= MAX_CACHE_ENTRIES,
1246                "cache exceeded cap at i={i}: len={}",
1247                cache.len()
1248            );
1249        }
1250        assert!(cache.len() <= MAX_CACHE_ENTRIES);
1251    }
1252
1253    // ── did:key (Ed25519) interop (#281) ───────────────────────────────────
1254
1255    /// Encode raw Ed25519 bytes as an `ed25519-pub` Multikey `publicKeyMultibase`
1256    /// (`z` + base58btc(0xed01 ‖ key)). Mirrors `#280`'s `ed25519_to_multibase`
1257    /// and `mesh_trust::encode_multikey`; kept local to the test.
1258    fn ed25519_multikey(raw: &[u8; 32]) -> String {
1259        let mut payload = Vec::with_capacity(2 + 32);
1260        payload.extend_from_slice(&MULTICODEC_ED25519_PUB);
1261        payload.extend_from_slice(raw);
1262        format!("z{}", bs58::encode(payload).into_string())
1263    }
1264
1265    fn rand_ed25519() -> [u8; 32] {
1266        use ed25519_dalek::SigningKey;
1267        use rand::rngs::OsRng;
1268        SigningKey::generate(&mut OsRng).verifying_key().to_bytes()
1269    }
1270
1271    #[test]
1272    fn did_key_decodes_known_fixture() {
1273        // The canonical did:key test vector for an all-zero Ed25519 public key
1274        // (multibase-base58btc of 0xed01 followed by 32 zero bytes). This is a
1275        // stable, spec-shaped fixture: the multicodec header + payload, not a
1276        // random key, so it pins the exact wire format we interoperate on.
1277        let did = ed25519_to_did_key(&[0u8; 32]);
1278        assert!(
1279            did.starts_with("did:key:z6Mk"),
1280            "ed25519 did:key must start with z6Mk: {did}"
1281        );
1282        assert_eq!(did_key_to_ed25519(&did).unwrap(), [0u8; 32]);
1283    }
1284
1285    #[test]
1286    fn did_key_roundtrips_random_key() {
1287        for _ in 0..16 {
1288            let raw = rand_ed25519();
1289            assert_eq!(did_key_to_ed25519(&ed25519_to_did_key(&raw)).unwrap(), raw);
1290        }
1291    }
1292
1293    #[test]
1294    fn did_key_strips_fragment() {
1295        // A did:key with a fragment (self-referencing VM id) decodes the base key.
1296        let raw = [3u8; 32];
1297        let base = ed25519_to_did_key(&raw);
1298        let mb = base.strip_prefix("did:key:").unwrap();
1299        let with_fragment = format!("{base}#{mb}");
1300        assert_eq!(did_key_to_ed25519(&with_fragment).unwrap(), raw);
1301    }
1302
1303    #[test]
1304    fn did_key_rejects_non_did_key() {
1305        assert!(did_key_to_ed25519("did:web:example.com").is_err());
1306        assert!(did_key_to_ed25519("https://example.com").is_err());
1307        assert!(did_key_to_ed25519("did:key:").is_err());
1308        assert!(!is_did_key("did:web:example.com"));
1309        assert!(is_did_key("did:key:z6MkfooBar"));
1310    }
1311
1312    #[test]
1313    fn did_key_rejects_wrong_multicodec() {
1314        // A Multikey carrying a p256-pub multicodec (0x1200 → 0x80 0x24), not
1315        // ed25519-pub, must be rejected — only Ed25519 did:key is in scope.
1316        let mut payload = vec![0x80u8, 0x24];
1317        payload.extend_from_slice(&[0u8; 33]); // compressed p256-shaped body
1318        let did = format!("did:key:z{}", bs58::encode(payload).into_string());
1319        assert!(did_key_to_ed25519(&did).is_err());
1320    }
1321
1322    #[test]
1323    fn did_key_rejects_bad_length() {
1324        // ed25519-pub multicodec but a 31-byte payload (wrong length).
1325        let mut payload = vec![0xedu8, 0x01];
1326        payload.extend_from_slice(&[0u8; 31]);
1327        let did = format!("did:key:z{}", bs58::encode(payload).into_string());
1328        assert!(did_key_to_ed25519(&did).is_err());
1329    }
1330
1331    #[test]
1332    fn did_key_rejects_non_base58btc_multibase() {
1333        // 'b' is base32 multibase, not the base58btc 'z' Multikey uses.
1334        assert!(did_key_to_ed25519("did:key:bMkfoo").is_err());
1335    }
1336
1337    #[test]
1338    fn did_key_equivalent_to_vm_multikey() {
1339        // Equivalence: our Ed25519 VM `publicKeyMultibase` (#280 form) is exactly
1340        // the method-specific id of the did:key for the same key — one multicodec
1341        // source of truth, no divergence between did:web VMs and did:key.
1342        let raw = rand_ed25519();
1343        let vm_multibase = ed25519_multikey(&raw); // == #280 ed25519_to_multibase
1344        let did_key = ed25519_to_did_key(&raw);
1345        assert_eq!(did_key, format!("did:key:{vm_multibase}"));
1346        // And both decode to the same key.
1347        assert_eq!(decode_ed25519_multikey(&vm_multibase).unwrap(), raw);
1348        assert_eq!(did_key_to_ed25519(&did_key).unwrap(), raw);
1349    }
1350
1351    #[test]
1352    fn did_key_identity_is_independent_of_iroh_reach_equality() {
1353        let identity = rand_ed25519();
1354        let unrelated_reach = rand_ed25519();
1355        let did = ed25519_to_did_key(&identity);
1356        for node_id in [identity, unrelated_reach] {
1357            let doc = json!({
1358                "id": did,
1359                "verificationMethod": [{
1360                    "id": format!("{did}#key-1"), "type": "Multikey",
1361                    "controller": did, "publicKeyMultibase": ed25519_multikey(&identity),
1362                }],
1363                "service": [{
1364                    "id": format!("{did}#iroh"), "type": "IrohTransport",
1365                    "serviceEndpoint": encode_iroh(&node_id, &[], &["hyprstream-rpc/1"]),
1366                }],
1367            });
1368            assert_eq!(verification_method_ed25519_keys(&doc), vec![identity]);
1369            let reach = transport_entries(&doc);
1370            assert!(matches!(&reach[0].config.endpoint,
1371                crate::transport::EndpointType::Iroh { node_id: got, .. } if *got == node_id));
1372        }
1373    }
1374}