Skip to main content

hyprstream_rpc/
did_plc.rs

1//! `did:plc` → DID document resolution — federation intake (#1161, epic #1158 E1).
2//!
3//! The epic #1158 decision: hyprstream **mints** host-form `did:web`, but
4//! **accepts federation from `did:plc` identities** — the rule governs what we
5//! mint, not what we trust. This module is the intake path that makes an
6//! external (e.g. Bluesky) user's DID resolvable here: it fetches the subject's
7//! DID document from a PLC directory and validates it before any consumer sees
8//! it.
9//!
10//! # Guarantees (#1161)
11//!
12//! - **Configurable base URL.** The PLC directory's base URL is required from
13//!   [`PlcResolverConfig`] at construction; this crate deliberately provides no
14//!   default directory. (did:plc was rejected as a *minting* method for its
15//!   single-operator dependency; hardcoding its host here would reintroduce
16//!   that dependency on the read side.)
17//! - **Self-authenticating resolution.** The returned document must claim the
18//!   DID that was asked for ([`validate_plc_document`]), and its identity-bearing
19//!   fields must equal the state derived from a verified PLC audit log. Genesis
20//!   binds to the DID; every operation CID, `prev` link, and ECDSA signature is
21//!   verified before the directory's current document is accepted.
22//! - **TTL cache.** The native resolver constructs [`HttpPlcFetcher`] from its
23//!   one [`PlcResolverConfig`], so validated documents are cached for exactly
24//!   the configured TTL and the cache is bounded to a fixed number of entries.
25//! - **Fail-closed.** Resolution failure, a malformed document, an ambiguous or
26//!   invalid DID, or a failed validation all return `Err`. The cache never
27//!   serves an expired entry and failures are never cached — there is no
28//!   cached-but-expired or partially-parsed fallback.
29//! - **Egress allowlist.** The fetcher issues requests only to the configured
30//!   base URL's origin; any URL whose origin is not on the allowlist is refused
31//!   before a request is dispatched.
32//! - **Read-only forever.** We never write to a PLC directory. This is
33//!   structural: the types in this module expose no write methods — the HTTP
34//!   client is private and used for GET only. Adding a write path is a
35//!   protocol decision, not a refactor, and belongs in its own epic.
36//!
37//! Full historical-time queries and independent recovery-window/fork-policy
38//! auditing remain E2 (#1174) through the C1 (#1167) verifier trait. This
39//! resolver nevertheless verifies the complete returned signature chain now;
40//! it does not trust the directory's current document as an unsigned assertion.
41//!
42//! # Layering
43//!
44//! - **DID → URL** ([`did_plc_url`]) — pure derivation against a validated
45//!   base URL; strict method-specific-identifier validation.
46//! - **Fetch + cache** — the injected [`DidDocFetcher`] trait (shared with
47//!   `did:web`) keeps the parse/validate path testable without a live network;
48//!   [`HttpPlcFetcher`] is the native allowlisted implementation.
49//! - **Validate** ([`validate_plc_document`]) — `doc.id` subject binding and
50//!   recognized-member validation, applied before a native document enters the
51//!   cache or any document is returned to its consumer.
52
53use anyhow::{anyhow, bail, ensure, Context, Result};
54use async_trait::async_trait;
55use serde_json::Value;
56use sha2::{Digest, Sha256};
57use url::Url;
58
59use crate::did_web::{parse_did_document_no_duplicates, DidDocFetcher};
60
61/// Maximum DID-document body we will buffer (1 MiB). A DID document is small;
62/// this ceiling bounds memory against a hostile or buggy directory streaming an
63/// unbounded body.
64const MAX_DID_DOC_BYTES: usize = 1024 * 1024;
65
66/// Maximum PLC per-DID audit history buffered for verification (8 MiB).
67const MAX_PLC_AUDIT_BYTES: usize = 8 * 1024 * 1024;
68
69/// Protocol maximum for one signed operation's canonical DAG-CBOR encoding.
70const MAX_PLC_OPERATION_BYTES: usize = 7_500;
71
72/// Maximum cached PLC document/audit responses. Cache keys are derived from
73/// validated DID URLs, but the cache remains bounded independently of volume.
74const MAX_CACHE_ENTRIES: usize = 256;
75
76struct CachedDoc {
77    doc: Value,
78    fetched_at: std::time::Instant,
79}
80
81/// Read a response body with a hard byte ceiling before parsing it as JSON.
82async fn read_capped(resp: reqwest::Response, max: usize) -> Result<Vec<u8>> {
83    use futures::StreamExt;
84
85    if let Some(len) = resp.content_length() {
86        if len > max as u64 {
87            bail!("DID document exceeds {max}-byte cap (Content-Length {len})");
88        }
89    }
90
91    let mut body = Vec::new();
92    let mut stream = resp.bytes_stream();
93    while let Some(chunk) = stream.next().await {
94        let chunk = chunk?;
95        if body.len() + chunk.len() > max {
96            bail!("DID document exceeds {max}-byte cap");
97        }
98        body.extend_from_slice(&chunk);
99    }
100    Ok(body)
101}
102
103/// Bound the cache before insertion by removing expired entries, then the
104/// oldest remaining entry when it is at capacity.
105fn evict_for_insert(
106    cache: &mut std::collections::HashMap<String, CachedDoc>,
107    ttl: std::time::Duration,
108) {
109    cache.retain(|_, entry| entry.fetched_at.elapsed() < ttl);
110    while cache.len() >= MAX_CACHE_ENTRIES {
111        let Some(oldest) = cache
112            .iter()
113            .min_by_key(|(_, entry)| entry.fetched_at)
114            .map(|(url, _)| url.clone())
115        else {
116            break;
117        };
118        cache.remove(&oldest);
119    }
120}
121
122// ── did:plc identifier validation ─────────────────────────────────────────────
123
124/// The `did:plc:` method prefix.
125pub const DID_PLC_PREFIX: &str = "did:plc:";
126
127/// Length of a `did:plc` method-specific identifier: 24 lowercase base32
128/// characters, per the did:plc method specification.
129const PLC_MSI_LEN: usize = 24;
130
131/// Whether `did` is a `did:plc` identifier (the federation-intake arm, #1161).
132pub fn is_did_plc(did: &str) -> bool {
133    did.starts_with(DID_PLC_PREFIX)
134}
135
136/// Validate a `did:plc` identifier and return its method-specific identifier.
137///
138/// Strict by construction (fail-closed on ambiguity): the msi must be exactly
139/// 24 characters of lowercase base32 (`a-z2-7`) — nothing else can appear in a
140/// conformant did:plc, and nothing else may reach URL derivation, where a
141/// looser charset could smuggle path segments (`/`, `%`, `..`) into the fetch
142/// URL. A DID URL fragment/query (`did:plc:…#atproto`) is stripped: resolution
143/// always fetches the base document.
144fn plc_msi(did: &str) -> Result<&str> {
145    let did = did.split(['#', '?']).next().unwrap_or(did);
146    let msi = did
147        .strip_prefix(DID_PLC_PREFIX)
148        .ok_or_else(|| anyhow!("not a did:plc identifier: {did}"))?;
149    if msi.len() != PLC_MSI_LEN {
150        bail!(
151            "did:plc method-specific identifier must be {PLC_MSI_LEN} characters (got {}): {did}",
152            msi.len()
153        );
154    }
155    if !msi.bytes().all(|b| matches!(b, b'a'..=b'z' | b'2'..=b'7')) {
156        bail!("did:plc method-specific identifier is not lowercase base32 (`a-z2-7`): {did}");
157    }
158    Ok(msi)
159}
160
161// ── resolver configuration ────────────────────────────────────────────────────
162
163/// Configuration for a `did:plc` resolver: the PLC directory base URL and the
164/// document-cache TTL.
165///
166/// The base URL **is** the egress boundary: every fetch is pinned beneath it
167/// and the fetcher refuses any other origin. Validated at construction —
168/// https-only (a directory fetched over plaintext HTTP would let any on-path
169/// party substitute identity documents), no credentials (they would leak to
170/// the directory operator's logs and imply an authority relationship the
171/// protocol does not have), no query/fragment (they have no meaning for a
172/// document root).
173#[derive(Clone, Debug)]
174pub struct PlcResolverConfig {
175    base_url: Url,
176    ttl: std::time::Duration,
177}
178
179impl PlcResolverConfig {
180    /// Construct a config, validating the base URL (see the type docs).
181    pub fn new(base_url: Url, ttl: std::time::Duration) -> Result<Self> {
182        validate_plc_base_url(&base_url)?;
183        Ok(Self { base_url, ttl })
184    }
185
186    /// The PLC directory base URL every fetch is pinned beneath.
187    pub fn base_url(&self) -> &Url {
188        &self.base_url
189    }
190
191    /// How long a resolved document may be served from cache.
192    pub fn ttl(&self) -> std::time::Duration {
193        self.ttl
194    }
195}
196
197/// Validate the operator-supplied PLC directory base URL.
198fn validate_plc_base_url(base_url: &Url) -> Result<()> {
199    if base_url.scheme() != "https" {
200        bail!("PLC directory base URL must use https:// (got {base_url})");
201    }
202    if base_url.host().is_none() {
203        bail!("PLC directory base URL must include a host: {base_url}");
204    }
205    if !base_url.username().is_empty() || base_url.password().is_some() {
206        bail!("PLC directory base URL must not carry credentials: {base_url}");
207    }
208    if base_url.query().is_some() || base_url.fragment().is_some() {
209        bail!("PLC directory base URL must not carry a query or fragment: {base_url}");
210    }
211    Ok(())
212}
213
214// ── did:plc → URL derivation ──────────────────────────────────────────────────
215
216/// Derive the DID-document URL for a `did:plc` identifier beneath `base_url`:
217/// `{base_url}/{full-did}`.
218///
219/// The base URL's path is treated as a directory (a trailing `/` is added if
220/// absent), so a base of `https://plc.example/mirror` resolves
221/// `did:plc:{msi}` to `https://plc.example/mirror/did:plc:{msi}`.
222///
223/// Fail-closed: returns `Err` for a non-`did:plc` or non-conformant identifier
224/// ([`plc_msi`]), and refuses — as defense in depth — any derived URL whose
225/// origin is not exactly the configured base URL's origin.
226pub fn did_plc_url(did: &str, base_url: &Url) -> Result<String> {
227    validate_plc_base_url(base_url)?;
228    plc_msi(did)?;
229    let did = did.split(['#', '?']).next().unwrap_or(did);
230
231    // Join the DID beneath the base path with exactly one separator. The base
232    // path is normalized by trimming any trailing `/` and appending a single
233    // `/` + the DID: using `Url::path_segments_mut().push()` here would *keep*
234    // the trailing empty segment and derive a double-slash target
235    // (`https://plc.example/mirror//did:plc:`), which a PLC mirror mounted
236    // below an origin path will commonly 404 on — exactly the configurable-base
237    // case this resolver exists to support. (`set_path` does not percent-encode
238    // the DID's `:` — verified by `url_derivation_configured_base` — and the
239    // `plc_msi` charset check above makes an embedded `/` impossible.)
240    let mut url = base_url.clone();
241    let trimmed = url.path().trim_end_matches('/');
242    url.set_path(&format!("{trimmed}/{did}"));
243
244    // Defense in depth: the msi charset check above already makes an
245    // origin-shift impossible, but a resolution URL must provably stay on the
246    // configured origin — check it rather than assume it.
247    if url.origin() != base_url.origin() {
248        bail!("derived did:plc URL {url} escaped the configured origin {base_url} (fail-closed)");
249    }
250    Ok(url.into())
251}
252
253// ── doc.id validation ─────────────────────────────────────────────────────────
254
255/// Validate that `doc` is a DID document **for `did`** — the subject binding
256/// that prevents a substitution oracle (#1161).
257///
258/// Checks, in order (each fail-closed):
259///
260/// 1. The document is a JSON object.
261/// 2. It carries a string `id`.
262/// 3. `id` is exactly the DID that was asked for (a fragment/query on the
263///    asked DID is ignored — resolution fetches the base document).
264/// 4. Recognized collection members, when present, have valid member shapes
265///    and no duplicate semantic identifiers.
266///
267/// Exact string equality is deliberate: a did:plc has no equivalent forms
268/// (lowercase base32, no path, no port), so any difference — case, padding,
269/// a different subject — is a mismatch.
270pub fn validate_plc_document(did: &str, doc: &Value) -> Result<()> {
271    let asked = did.split(['#', '?']).next().unwrap_or(did);
272    let object = doc.as_object().ok_or_else(|| {
273        anyhow!("did:plc document for {asked} is not a JSON object (fail-closed)")
274    })?;
275    let id = object
276        .get("id")
277        .and_then(Value::as_str)
278        .ok_or_else(|| anyhow!("did:plc document for {asked} has no string `id` (fail-closed)"))?;
279    if id != asked {
280        bail!(
281            "did:plc document id mismatch: asked {asked}, document claims {id} — substitution oracle (fail-closed)"
282        );
283    }
284
285    if let Some(also_known_as) = object.get("alsoKnownAs") {
286        validate_string_collection(asked, "alsoKnownAs", also_known_as)?;
287    }
288    if let Some(verification_methods) = object.get("verificationMethod") {
289        validate_verification_methods(asked, verification_methods)?;
290    }
291    if let Some(services) = object.get("service") {
292        validate_services(asked, services)?;
293    }
294    Ok(())
295}
296
297fn validate_string_collection(did: &str, member: &str, value: &Value) -> Result<()> {
298    let values = value.as_array().ok_or_else(|| {
299        anyhow!("did:plc document for {did} has non-array `{member}` (fail-closed)")
300    })?;
301    let mut seen = std::collections::HashSet::new();
302    for value in values {
303        let value = value
304            .as_str()
305            .filter(|value| !value.is_empty())
306            .ok_or_else(|| {
307                anyhow!("did:plc document for {did} has invalid `{member}` member (fail-closed)")
308            })?;
309        // Each member MUST be an absolute URI per DID Core (e.g. an `at://`
310        // handle or an https URL) — non-emptiness alone admits arbitrary
311        // strings, which is not the contract here.
312        if !is_absolute_uri(value) {
313            bail!("did:plc document for {did} has `{member}` member that is not a valid URI: `{value}` (fail-closed)");
314        }
315        if !seen.insert(value) {
316            bail!("did:plc document for {did} has duplicate `{member}` member `{value}` (fail-closed)");
317        }
318    }
319    Ok(())
320}
321
322// ── DID / URI reference handling ──────────────────────────────────────────────
323//
324// DID Core verification-method and service `id`s may be either absolute DID
325// URLs (`did:plc:…#key`) or relative references resolved against the subject
326// DID (`#key`, `?query`). The two forms name the **same** resource, so
327// deduplicating them as raw strings admits a semantically-duplicate pair — the
328// validator resolves every reference against the subject before the uniqueness
329// check. This is an interop surface, so classical DID Core shapes are accepted
330// and unknown algorithms ignored rather than rejected (see the material
331// validator).
332
333/// Whether `s` is a syntactically valid DID per DID Core
334/// (`did:method-name:method-specific-id`). `method-name` is lowercase ASCII
335/// alpha/digit; `method-specific-id` allows `a-zA-Z0-9._:%` (idchar plus the
336/// `:` separator and pct-encoded triples).
337fn is_did(s: &str) -> bool {
338    let Some(rest) = s.strip_prefix("did:") else {
339        return false;
340    };
341    let Some((method, msi)) = rest.split_once(':') else {
342        return false;
343    };
344    !method.is_empty()
345        && method
346            .bytes()
347            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
348        && !msi.is_empty()
349        && msi
350            .bytes()
351            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b':' | b'%'))
352}
353
354/// Whether `s` is a DID URL — a DID followed by optional path, query, and/or
355/// fragment per DID Core (`did:m:m[/path][?query][#fragment]`). The authority
356/// (method + method-specific-id) must be a valid DID; the suffix is unchecked
357/// beyond its separator-led structure.
358fn is_did_url(s: &str) -> bool {
359    let Some(rest) = s.strip_prefix("did:") else {
360        return false;
361    };
362    let authority = rest.split(['/', '?', '#']).next().unwrap_or(rest);
363    let Some((method, msi)) = authority.split_once(':') else {
364        return false;
365    };
366    !method.is_empty()
367        && method
368            .bytes()
369            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
370        && !msi.is_empty()
371        && msi
372            .bytes()
373            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b':' | b'%'))
374}
375
376/// Whether `s` is an absolute URI per RFC 3986 — a scheme
377/// (`ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )`) precedes the first path,
378/// query, or fragment separator. Used to tell absolute DID URLs / URIs from
379/// relative references (`#key`, `?query`, `./path`).
380fn is_absolute_uri(s: &str) -> bool {
381    let Some(colon) = s.find(':') else {
382        return false;
383    };
384    let first_separator = s.find(['/', '?', '#']).unwrap_or(usize::MAX);
385    if colon >= first_separator {
386        return false;
387    }
388    let scheme = &s[..colon];
389    !scheme.is_empty()
390        && scheme
391            .bytes()
392            .next()
393            .is_some_and(|b| b.is_ascii_alphabetic())
394        && scheme
395            .bytes()
396            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))
397}
398
399/// Resolve a (possibly relative) DID-URL reference against the document subject
400/// DID, returning the canonical absolute DID URL used for uniqueness checks.
401fn resolve_did_url(subject: &str, reference: &str) -> Result<String> {
402    if is_absolute_uri(reference) {
403        return Ok(reference.to_owned());
404    }
405    if reference.is_empty() {
406        bail!("empty DID-URL reference");
407    }
408    let base = subject.split(['#', '?']).next().unwrap_or(subject);
409    if reference.starts_with('#') || reference.starts_with('?') || reference.starts_with('/') {
410        Ok(format!("{base}{reference}"))
411    } else {
412        // A bare-segment relative reference; append after a path separator.
413        Ok(format!("{base}/{reference}"))
414    }
415}
416
417/// Canonicalize a verification-method or service `id`: absolute DID URLs are
418/// validated as such and used as-is; relative references are resolved against
419/// the subject DID.
420fn canonical_member_id(did: &str, id: &str, member: &str) -> Result<String> {
421    if is_absolute_uri(id) {
422        if !is_did_url(id) {
423            bail!("did:plc document for {did} has `{member}` with non-DID-URL id `{id}` (fail-closed)");
424        }
425        Ok(id.to_owned())
426    } else {
427        resolve_did_url(did, id)
428    }
429}
430
431// ── verification material ─────────────────────────────────────────────────────
432
433/// Known `publicKey*` verification-material property names recognized by DID
434/// Core / the Linked Data Security vocabularies. Exactly one must be present
435/// per verification method (DID Core §5.1); multiple known material properties
436/// is ambiguous and fail-closed.
437const KNOWN_MATERIAL_FIELDS: &[&str] = &[
438    "publicKeyJwk",
439    "publicKeyMultibase",
440    "publicKeyBase58",
441    "publicKeyHex",
442    "publicKeyPem",
443    "publicKeyPgp",
444];
445
446/// Decode the leading unsigned-varint multicodec, returning the codec value and
447/// the remaining key payload.
448fn read_multicodec(bytes: &[u8]) -> Option<(u64, &[u8])> {
449    let mut value = 0u64;
450    let mut shift = 0u32;
451    for (i, &b) in bytes.iter().enumerate() {
452        value |= ((b & 0x7f) as u64) << shift;
453        if b & 0x80 == 0 {
454            return Some((value, &bytes[i + 1..]));
455        }
456        shift = shift.checked_add(7)?;
457        if shift >= 64 {
458            return None;
459        }
460    }
461    None
462}
463
464/// Multicodec unsigned-varint values for the public-key codecs we recognize.
465mod multicodec {
466    /// `ed25519-pub`.
467    pub const ED25519_PUB: u64 = 0xed;
468    /// `secp256k1-pub`.
469    pub const SECP256K1_PUB: u64 = 0xe7;
470    /// `p256-pub`.
471    pub const P256_PUB: u64 = 0x1200;
472    /// `ml-dsa-65-pub`.
473    pub const ML_DSA_65_PUB: u64 = 0x1211;
474}
475
476/// ML-DSA-65 public-key length in bytes.
477const ML_DSA_65_PUB_KEY_LEN: usize = 1952;
478
479/// Floor for a Multikey payload whose multicodec we do not recognize. Every
480/// real public key is far larger; this only rejects obvious non-keys (`zKey`)
481/// while **accepting unknown algorithms** per the interop rule (this is a
482/// classical, read-only resolver — an unrecognized multicodec is not an attack,
483/// it is an algorithm we do not happen to admit yet).
484const MIN_UNKNOWN_MULTIKEY_PAYLOAD: usize = 16;
485
486/// Whether `s` is a structurally valid Multikey `publicKeyMultibase`: base58btc
487/// multibase (`z` prefix), a leading multicodec varint, and a key payload of
488/// the right length for the codec (exact for known codecs, floored for unknown
489/// codecs so `zKey` is rejected but an unknown algorithm with a real key is
490/// preserved).
491fn is_valid_multikey(s: &str) -> bool {
492    let Some(body) = s.strip_prefix('z') else {
493        return false;
494    };
495    let Ok(decoded) = bs58::decode(body).into_vec() else {
496        return false;
497    };
498    let Some((codec, payload)) = read_multicodec(&decoded) else {
499        return false;
500    };
501    match codec {
502        multicodec::ED25519_PUB => payload.len() == 32,
503        multicodec::SECP256K1_PUB | multicodec::P256_PUB => payload.len() == 33,
504        multicodec::ML_DSA_65_PUB => payload.len() == ML_DSA_65_PUB_KEY_LEN,
505        _ => payload.len() >= MIN_UNKNOWN_MULTIKEY_PAYLOAD,
506    }
507}
508
509/// Whether `jwk` is a syntactically valid JSON Web Key (RFC 7517/7518): a known
510/// `kty` plus its required coordinate members. `{ "garbage": true }` (no
511/// `kty`) is rejected.
512fn is_valid_jwk(jwk: &serde_json::Map<String, Value>) -> bool {
513    let Some(kty) = jwk.get("kty").and_then(Value::as_str) else {
514        return false;
515    };
516    let has_str = |k: &str| {
517        jwk.get(k)
518            .and_then(Value::as_str)
519            .is_some_and(|v| !v.is_empty())
520    };
521    match kty {
522        "EC" | "OKP" => has_str("crv") && has_str("x"),
523        "RSA" => has_str("n") && has_str("e"),
524        "oct" => has_str("k"),
525        _ => false,
526    }
527}
528
529fn required_nonempty_string<'a>(
530    did: &str,
531    member: &str,
532    object: &'a serde_json::Map<String, Value>,
533    field: &str,
534) -> Result<&'a str> {
535    object
536        .get(field)
537        .and_then(Value::as_str)
538        .filter(|value| !value.is_empty())
539        .ok_or_else(|| {
540            anyhow!(
541                "did:plc document for {did} has `{member}` member without non-empty string `{field}` (fail-closed)"
542            )
543        })
544}
545
546/// Validate the single declared verification-material property of a
547/// verification method by its own syntax (the property name fixes the encoding,
548/// independent of the method `type`).
549fn validate_verification_material(
550    did: &str,
551    id: &str,
552    method: &serde_json::Map<String, Value>,
553    field: &str,
554) -> Result<()> {
555    match field {
556        "publicKeyMultibase" => {
557            let v = method
558                .get(field)
559                .and_then(Value::as_str)
560                .filter(|s| !s.is_empty());
561            if !v.is_some_and(is_valid_multikey) {
562                bail!("did:plc document for {did} has malformed Multikey `publicKeyMultibase` in `{id}` (fail-closed)");
563            }
564        }
565        "publicKeyJwk" => {
566            let Some(v) = method.get(field).and_then(Value::as_object) else {
567                bail!("did:plc document for {did} has non-object `publicKeyJwk` in `{id}` (fail-closed)");
568            };
569            if !is_valid_jwk(v) {
570                bail!("did:plc document for {did} has malformed `publicKeyJwk` in `{id}` (fail-closed)");
571            }
572        }
573        "publicKeyBase58" | "publicKeyHex" | "publicKeyPem" | "publicKeyPgp" => {
574            if method
575                .get(field)
576                .and_then(Value::as_str)
577                .is_some_and(|v| !v.is_empty())
578            {
579                return Ok(());
580            }
581            bail!("did:plc document for {did} has empty `{field}` in `{id}` (fail-closed)");
582        }
583        _ => {}
584    }
585    Ok(())
586}
587
588fn validate_verification_methods(did: &str, value: &Value) -> Result<()> {
589    let methods = value.as_array().ok_or_else(|| {
590        anyhow!("did:plc document for {did} has non-array `verificationMethod` (fail-closed)")
591    })?;
592    let mut ids: std::collections::HashSet<String> = std::collections::HashSet::new();
593    for value in methods {
594        let method = value.as_object().ok_or_else(|| {
595            anyhow!("did:plc document for {did} has non-object `verificationMethod` member (fail-closed)")
596        })?;
597        let id = required_nonempty_string(did, "verificationMethod", method, "id")?;
598        required_nonempty_string(did, "verificationMethod", method, "type")?;
599        let controller = required_nonempty_string(did, "verificationMethod", method, "controller")?;
600        if !is_did(controller) {
601            bail!("did:plc document for {did} has `verificationMethod` `{id}` with non-DID controller `{controller}` (fail-closed)");
602        }
603
604        // Exactly one known verification-material property (DID Core §5.1).
605        // Multiple known properties is ambiguous → fail closed. Zero known
606        // properties is a material-less method → fail closed (a conforming
607        // extension still carries a standard material property).
608        let present: Vec<&str> = KNOWN_MATERIAL_FIELDS
609            .iter()
610            .copied()
611            .filter(|f| method.contains_key(*f))
612            .collect();
613        if present.len() > 1 {
614            bail!("did:plc document for {did} has `verificationMethod` `{id}` with multiple verification-material properties (fail-closed)");
615        }
616        let Some(field) = present.into_iter().next() else {
617            bail!("did:plc document for {did} has `verificationMethod` `{id}` without a recognized verification-material property (fail-closed)");
618        };
619        validate_verification_material(did, id, method, field)?;
620
621        // Canonicalize the id (relative refs resolve against the subject DID)
622        // so a relative `#key` and the absolute `did:…#key` cannot both
623        // appear — they name the same resource.
624        let canonical = canonical_member_id(did, id, "verificationMethod")?;
625        if !ids.insert(canonical) {
626            bail!("did:plc document for {did} has duplicate `verificationMethod` id `{id}` (fail-closed)");
627        }
628    }
629    Ok(())
630}
631
632fn is_valid_service_endpoint(value: &Value) -> bool {
633    match value {
634        // A string endpoint MUST be an absolute URI (DID Core).
635        Value::String(value) => !value.is_empty() && is_absolute_uri(value),
636        Value::Object(value) => !value.is_empty(),
637        Value::Array(values) => !values.is_empty() && values.iter().all(is_valid_service_endpoint),
638        _ => false,
639    }
640}
641
642fn validate_services(did: &str, value: &Value) -> Result<()> {
643    let services = value.as_array().ok_or_else(|| {
644        anyhow!("did:plc document for {did} has non-array `service` (fail-closed)")
645    })?;
646    let mut ids: std::collections::HashSet<String> = std::collections::HashSet::new();
647    for value in services {
648        let service = value.as_object().ok_or_else(|| {
649            anyhow!("did:plc document for {did} has non-object `service` member (fail-closed)")
650        })?;
651        let id = required_nonempty_string(did, "service", service, "id")?;
652        required_nonempty_string(did, "service", service, "type")?;
653        if !service
654            .get("serviceEndpoint")
655            .is_some_and(is_valid_service_endpoint)
656        {
657            bail!("did:plc document for {did} has `service` member without valid `serviceEndpoint` (fail-closed)");
658        }
659        let canonical = canonical_member_id(did, id, "service")?;
660        if !ids.insert(canonical) {
661            bail!("did:plc document for {did} has duplicate `service` id `{id}` (fail-closed)");
662        }
663    }
664    Ok(())
665}
666
667// ── PLC operation-log verification ──────────────────────────────────────────
668
669/// Derive the audit-log URL for a validated DID beneath the configured base.
670fn did_plc_audit_url(did: &str, base_url: &Url) -> Result<String> {
671    Ok(format!("{}/log/audit", did_plc_url(did, base_url)?))
672}
673
674/// Canonical DAG-CBOR encoder for the JSON value domain used by PLC operations,
675/// including RFC 8949 deterministic map-key ordering.
676fn plc_dag_cbor(value: &Value) -> Result<Vec<u8>> {
677    fn write_uint(out: &mut Vec<u8>, major: u8, value: u64) {
678        let prefix = major << 5;
679        if value < 24 {
680            out.push(prefix | value as u8);
681        } else if value <= u8::MAX as u64 {
682            out.extend_from_slice(&[prefix | 24, value as u8]);
683        } else if value <= u16::MAX as u64 {
684            out.push(prefix | 25);
685            out.extend_from_slice(&(value as u16).to_be_bytes());
686        } else if value <= u32::MAX as u64 {
687            out.push(prefix | 26);
688            out.extend_from_slice(&(value as u32).to_be_bytes());
689        } else {
690            out.push(prefix | 27);
691            out.extend_from_slice(&value.to_be_bytes());
692        }
693    }
694
695    fn encode(value: &Value, out: &mut Vec<u8>, depth: usize) -> Result<()> {
696        ensure!(depth <= 128, "PLC operation exceeds DAG-CBOR nesting limit");
697        match value {
698            Value::Null => out.push(0xf6),
699            Value::Bool(false) => out.push(0xf4),
700            Value::Bool(true) => out.push(0xf5),
701            Value::String(text) => {
702                write_uint(out, 3, text.len() as u64);
703                out.extend_from_slice(text.as_bytes());
704            }
705            Value::Array(values) => {
706                write_uint(out, 4, values.len() as u64);
707                for value in values {
708                    encode(value, out, depth + 1)?;
709                }
710            }
711            Value::Object(object) => {
712                let mut entries: Vec<_> = object.iter().collect();
713                // RFC 8949 deterministic ordering: shorter encoded text keys
714                // first, then bytewise lexical order for equal lengths.
715                entries.sort_unstable_by(|(left, _), (right, _)| {
716                    left.len()
717                        .cmp(&right.len())
718                        .then_with(|| left.as_bytes().cmp(right.as_bytes()))
719                });
720                write_uint(out, 5, entries.len() as u64);
721                for (key, value) in entries {
722                    write_uint(out, 3, key.len() as u64);
723                    out.extend_from_slice(key.as_bytes());
724                    encode(value, out, depth + 1)?;
725                }
726            }
727            Value::Number(_) => bail!("PLC operations cannot contain JSON numbers"),
728        }
729        Ok(())
730    }
731
732    let mut encoded = Vec::new();
733    encode(value, &mut encoded, 0)?;
734    ensure!(
735        encoded.len() <= MAX_PLC_OPERATION_BYTES,
736        "PLC operation exceeds {MAX_PLC_OPERATION_BYTES}-byte DAG-CBOR limit"
737    );
738    Ok(encoded)
739}
740
741fn operation_cid(operation: &Value) -> Result<String> {
742    let digest = Sha256::digest(plc_dag_cbor(operation)?);
743    let mut bytes = Vec::with_capacity(36);
744    // CIDv1 || dag-cbor || sha2-256 multihash.
745    bytes.extend_from_slice(&[0x01, 0x71, 0x12, 0x20]);
746    bytes.extend_from_slice(&digest);
747    Ok(format!(
748        "b{}",
749        data_encoding::BASE32_NOPAD
750            .encode(&bytes)
751            .to_ascii_lowercase()
752    ))
753}
754
755fn did_from_genesis(operation: &Value) -> Result<String> {
756    let digest = Sha256::digest(plc_dag_cbor(operation)?);
757    let encoded = data_encoding::BASE32_NOPAD
758        .encode(&digest)
759        .to_ascii_lowercase();
760    Ok(format!("did:plc:{}", &encoded[..PLC_MSI_LEN]))
761}
762
763fn operation_prev(operation: &Value) -> Result<Option<&str>> {
764    let object = operation
765        .as_object()
766        .ok_or_else(|| anyhow!("PLC audit operation is not an object"))?;
767    match object.get("prev") {
768        Some(Value::Null) => Ok(None),
769        Some(Value::String(prev)) if !prev.is_empty() => Ok(Some(prev)),
770        Some(_) => bail!("PLC operation has invalid `prev`"),
771        None => bail!("PLC operation omits required `prev`"),
772    }
773}
774
775fn operation_rotation_keys(operation: &Value) -> Result<Vec<&str>> {
776    let object = operation
777        .as_object()
778        .ok_or_else(|| anyhow!("PLC audit operation is not an object"))?;
779    match object.get("type").and_then(Value::as_str) {
780        Some("plc_operation") => {
781            let keys = object
782                .get("rotationKeys")
783                .and_then(Value::as_array)
784                .ok_or_else(|| anyhow!("PLC operation omits `rotationKeys`"))?;
785            ensure!(
786                (1..=5).contains(&keys.len()),
787                "PLC operation must carry 1..=5 rotation keys"
788            );
789            let mut seen = std::collections::HashSet::new();
790            keys.iter()
791                .map(|key| {
792                    let key = key
793                        .as_str()
794                        .filter(|key| !key.is_empty())
795                        .ok_or_else(|| anyhow!("PLC operation has invalid rotation key"))?;
796                    ensure!(seen.insert(key), "PLC operation has duplicate rotation key");
797                    Ok(key)
798                })
799                .collect()
800        }
801        Some("create") => {
802            let key = object
803                .get("recoveryKey")
804                .and_then(Value::as_str)
805                .filter(|key| !key.is_empty())
806                .ok_or_else(|| anyhow!("legacy PLC create operation omits `recoveryKey`"))?;
807            Ok(vec![key])
808        }
809        Some("plc_tombstone") => bail!("a PLC tombstone carries no successor rotation keys"),
810        Some(other) => bail!("unsupported PLC operation type `{other}`"),
811        None => bail!("PLC operation omits string `type`"),
812    }
813}
814
815fn verify_operation_signature(operation: &Value, rotation_keys: &[&str]) -> Result<()> {
816    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
817    use k256::ecdsa::signature::Verifier as _;
818
819    let object = operation
820        .as_object()
821        .ok_or_else(|| anyhow!("PLC audit operation is not an object"))?;
822    let signature_text = object
823        .get("sig")
824        .and_then(Value::as_str)
825        .ok_or_else(|| anyhow!("PLC operation omits string `sig`"))?;
826    let signature_bytes = URL_SAFE_NO_PAD
827        .decode(signature_text)
828        .context("PLC operation signature is not canonical base64url")?;
829    ensure!(
830        signature_bytes.len() == 64 && URL_SAFE_NO_PAD.encode(&signature_bytes) == signature_text,
831        "PLC operation signature is not canonical 64-byte base64url"
832    );
833
834    let mut unsigned = operation.clone();
835    let unsigned_object = unsigned
836        .as_object_mut()
837        .ok_or_else(|| anyhow!("PLC audit operation is not an object"))?;
838    unsigned_object.remove("sig");
839    let message = plc_dag_cbor(&unsigned)?;
840
841    for did_key in rotation_keys {
842        let Some(multibase) = did_key.strip_prefix("did:key:z") else {
843            continue;
844        };
845        let Ok(decoded) = bs58::decode(multibase).into_vec() else {
846            continue;
847        };
848        let Some((codec, key_bytes)) = read_multicodec(&decoded) else {
849            continue;
850        };
851        let verified = match codec {
852            multicodec::SECP256K1_PUB => {
853                if !decoded.starts_with(&[0xe7, 0x01]) {
854                    continue;
855                }
856                let Ok(key) = k256::ecdsa::VerifyingKey::from_sec1_bytes(key_bytes) else {
857                    continue;
858                };
859                let Ok(signature) = k256::ecdsa::Signature::from_slice(&signature_bytes) else {
860                    continue;
861                };
862                if signature.normalize_s().is_some() {
863                    continue;
864                }
865                key.verify(&message, &signature).is_ok()
866            }
867            multicodec::P256_PUB => {
868                if !decoded.starts_with(&[0x80, 0x24]) {
869                    continue;
870                }
871                let Ok(key) = p256::ecdsa::VerifyingKey::from_sec1_bytes(key_bytes) else {
872                    continue;
873                };
874                let Ok(signature) = p256::ecdsa::Signature::from_slice(&signature_bytes) else {
875                    continue;
876                };
877                if signature.normalize_s().is_some() {
878                    continue;
879                }
880                key.verify(&message, &signature).is_ok()
881            }
882            _ => false,
883        };
884        if verified {
885            return Ok(());
886        }
887    }
888    bail!("PLC operation signature did not verify under any authorized rotation key")
889}
890
891fn document_from_operation(did: &str, operation: &Value) -> Result<Value> {
892    let object = operation
893        .as_object()
894        .ok_or_else(|| anyhow!("PLC audit head operation is not an object"))?;
895    let op_type = object
896        .get("type")
897        .and_then(Value::as_str)
898        .ok_or_else(|| anyhow!("PLC audit head omits string `type`"))?;
899    if op_type == "plc_tombstone" {
900        bail!("did:plc identity {did} is deactivated");
901    }
902
903    let (verification_methods, also_known_as, services) = if op_type == "create" {
904        let signing_key = object
905            .get("signingKey")
906            .and_then(Value::as_str)
907            .ok_or_else(|| anyhow!("legacy PLC create omits `signingKey`"))?;
908        let handle = object
909            .get("handle")
910            .and_then(Value::as_str)
911            .ok_or_else(|| anyhow!("legacy PLC create omits `handle`"))?;
912        let service = object
913            .get("service")
914            .and_then(Value::as_str)
915            .ok_or_else(|| anyhow!("legacy PLC create omits `service`"))?;
916        (
917            serde_json::json!({ "atproto": signing_key }),
918            serde_json::json!([format!("at://{handle}")]),
919            serde_json::json!({
920                "atproto_pds": {
921                    "type": "AtprotoPersonalDataServer",
922                    "endpoint": service
923                }
924            }),
925        )
926    } else if op_type == "plc_operation" {
927        (
928            object
929                .get("verificationMethods")
930                .cloned()
931                .ok_or_else(|| anyhow!("PLC operation omits `verificationMethods`"))?,
932            object
933                .get("alsoKnownAs")
934                .cloned()
935                .ok_or_else(|| anyhow!("PLC operation omits `alsoKnownAs`"))?,
936            object
937                .get("services")
938                .cloned()
939                .ok_or_else(|| anyhow!("PLC operation omits `services`"))?,
940        )
941    } else {
942        bail!("unsupported PLC audit head operation type `{op_type}`");
943    };
944
945    let methods = verification_methods
946        .as_object()
947        .ok_or_else(|| anyhow!("PLC `verificationMethods` is not an object"))?
948        .iter()
949        .map(|(name, key)| {
950            ensure!(
951                !name.is_empty() && !name.starts_with('#'),
952                "invalid PLC verification-method name"
953            );
954            let multibase = key
955                .as_str()
956                .and_then(|key| key.strip_prefix("did:key:"))
957                .ok_or_else(|| anyhow!("PLC verification method `{name}` is not a did:key"))?;
958            Ok(serde_json::json!({
959                "id": format!("{did}#{name}"),
960                "type": "Multikey",
961                "controller": did,
962                "publicKeyMultibase": multibase,
963            }))
964        })
965        .collect::<Result<Vec<_>>>()?;
966
967    let rendered_services = services
968        .as_object()
969        .ok_or_else(|| anyhow!("PLC `services` is not an object"))?
970        .iter()
971        .map(|(name, service)| {
972            ensure!(
973                !name.is_empty() && !name.starts_with('#'),
974                "invalid PLC service name"
975            );
976            let service = service
977                .as_object()
978                .ok_or_else(|| anyhow!("PLC service `{name}` is not an object"))?;
979            let service_type = service
980                .get("type")
981                .and_then(Value::as_str)
982                .ok_or_else(|| anyhow!("PLC service `{name}` omits string `type`"))?;
983            let endpoint = service
984                .get("endpoint")
985                .and_then(Value::as_str)
986                .ok_or_else(|| anyhow!("PLC service `{name}` omits string `endpoint`"))?;
987            Ok(serde_json::json!({
988                "id": format!("#{name}"),
989                "type": service_type,
990                "serviceEndpoint": endpoint,
991            }))
992        })
993        .collect::<Result<Vec<_>>>()?;
994
995    Ok(serde_json::json!({
996        "id": did,
997        "alsoKnownAs": also_known_as,
998        "verificationMethod": methods,
999        "service": rendered_services,
1000    }))
1001}
1002
1003fn normalized_document_members(
1004    did: &str,
1005    member: &str,
1006    value: Option<&Value>,
1007) -> Result<std::collections::BTreeMap<String, Value>> {
1008    let values = value
1009        .and_then(Value::as_array)
1010        .ok_or_else(|| anyhow!("did:plc document omits array `{member}`"))?;
1011    values
1012        .iter()
1013        .map(|value| {
1014            let mut object = value
1015                .as_object()
1016                .cloned()
1017                .ok_or_else(|| anyhow!("did:plc document has non-object `{member}` entry"))?;
1018            let id = object
1019                .remove("id")
1020                .and_then(|id| id.as_str().map(str::to_owned))
1021                .ok_or_else(|| anyhow!("did:plc document `{member}` entry omits string `id`"))?;
1022            Ok((
1023                canonical_member_id(did, &id, member)?,
1024                Value::Object(object),
1025            ))
1026        })
1027        .collect()
1028}
1029
1030/// Verify the complete returned operation signature chain and bind the current
1031/// DID document's identity-bearing fields to the verified active head.
1032pub fn verify_plc_audit(did: &str, audit: &Value, current_document: &Value) -> Result<()> {
1033    plc_msi(did)?;
1034    validate_plc_document(did, current_document)?;
1035    let entries = audit
1036        .as_array()
1037        .filter(|entries| !entries.is_empty())
1038        .ok_or_else(|| anyhow!("PLC audit log for {did} is empty or not an array"))?;
1039    let mut cid_to_index: std::collections::HashMap<String, usize> =
1040        std::collections::HashMap::new();
1041    let mut active = Vec::new();
1042    let mut genesis_count = 0usize;
1043
1044    for (index, entry) in entries.iter().enumerate() {
1045        let entry = entry
1046            .as_object()
1047            .ok_or_else(|| anyhow!("PLC audit entry {index} is not an object"))?;
1048        ensure!(
1049            entry.get("did").and_then(Value::as_str) == Some(did),
1050            "PLC audit entry {index} is for a different DID"
1051        );
1052        let operation = entry
1053            .get("operation")
1054            .ok_or_else(|| anyhow!("PLC audit entry {index} omits `operation`"))?;
1055        if operation.get("type").and_then(Value::as_str) != Some("plc_tombstone") {
1056            // Validate every operation's published successor authority,
1057            // including the active head (which has no child to consume it).
1058            operation_rotation_keys(operation)?;
1059        }
1060        let cid = entry
1061            .get("cid")
1062            .and_then(Value::as_str)
1063            .ok_or_else(|| anyhow!("PLC audit entry {index} omits string `cid`"))?;
1064        ensure!(
1065            operation_cid(operation)? == cid,
1066            "PLC audit entry {index} CID does not match its signed operation"
1067        );
1068
1069        let prev = operation_prev(operation)?;
1070        let authorized_keys = if let Some(prev) = prev {
1071            let parent_index = *cid_to_index.get(prev).ok_or_else(|| {
1072                anyhow!("PLC operation `{cid}` references unknown or future prev `{prev}`")
1073            })?;
1074            let parent = entries[parent_index]
1075                .get("operation")
1076                .ok_or_else(|| anyhow!("PLC parent entry omits operation"))?;
1077            operation_rotation_keys(parent)?
1078        } else {
1079            genesis_count += 1;
1080            ensure!(
1081                did_from_genesis(operation)? == did,
1082                "PLC genesis operation does not bind to {did}"
1083            );
1084            operation_rotation_keys(operation)?
1085        };
1086        verify_operation_signature(operation, &authorized_keys).with_context(|| {
1087            format!("PLC audit entry {index} (`{cid}`) signature verification failed")
1088        })?;
1089        ensure!(
1090            cid_to_index.insert(cid.to_owned(), index).is_none(),
1091            "PLC audit contains duplicate operation CID `{cid}`"
1092        );
1093
1094        let nullified = entry
1095            .get("nullified")
1096            .and_then(Value::as_bool)
1097            .ok_or_else(|| anyhow!("PLC audit entry {index} omits boolean `nullified`"))?;
1098        if !nullified {
1099            active.push((cid, operation));
1100        }
1101    }
1102
1103    ensure!(
1104        genesis_count == 1,
1105        "PLC audit must contain exactly one genesis operation"
1106    );
1107    ensure!(
1108        !active.is_empty(),
1109        "PLC audit has no active operation chain"
1110    );
1111    ensure!(
1112        operation_prev(active[0].1)?.is_none(),
1113        "PLC active chain does not start at genesis"
1114    );
1115    for pair in active.windows(2) {
1116        ensure!(
1117            operation_prev(pair[1].1)? == Some(pair[0].0),
1118            "PLC active operation chain has a broken `prev` link"
1119        );
1120    }
1121
1122    let active_head = active
1123        .last()
1124        .ok_or_else(|| anyhow!("PLC audit has no active operation chain"))?;
1125    let verified_document = document_from_operation(did, active_head.1)?;
1126    ensure!(
1127        current_document.get("id") == verified_document.get("id"),
1128        "PLC current document `id` does not match the verified audit-log head"
1129    );
1130    ensure!(
1131        current_document.get("alsoKnownAs") == verified_document.get("alsoKnownAs"),
1132        "PLC current document `alsoKnownAs` does not match the verified audit-log head"
1133    );
1134    for member in ["verificationMethod", "service"] {
1135        ensure!(
1136            normalized_document_members(did, member, current_document.get(member))?
1137                == normalized_document_members(did, member, verified_document.get(member))?,
1138            "PLC current document `{member}` does not match the verified audit-log head"
1139        );
1140    }
1141    Ok(())
1142}
1143
1144// ── resolver ──────────────────────────────────────────────────────────────────
1145
1146/// A PLC fetcher must provide both the current DID document and its audit log.
1147///
1148/// Keeping the audit fetch in the resolver's required interface makes it
1149/// impossible to instantiate a resolver that silently skips chain verification.
1150#[async_trait]
1151pub trait PlcAuditFetcher: DidDocFetcher {
1152    async fn fetch_audit(&self, url: &str) -> Result<Value>;
1153}
1154
1155/// Resolves a `did:plc` identifier to its validated DID document.
1156///
1157/// Generic over a [`PlcAuditFetcher`] so the parse/validate/verify path is
1158/// testable with an injected fixture (no live network); the native
1159/// implementation is [`HttpPlcFetcher`]. This is the federation-intake
1160/// artifact E2 (#1174, foreign handle resolution) and E3 (#1175, exchange
1161/// audience) build on.
1162///
1163/// Read-only forever: there is no write path. See the module docs.
1164pub struct DidPlcResolver<F: PlcAuditFetcher> {
1165    fetcher: F,
1166    config: PlcResolverConfig,
1167}
1168
1169impl<F: PlcAuditFetcher> DidPlcResolver<F> {
1170    /// Construct a resolver over an injected document+audit fetcher. This is for
1171    /// fixtures and alternate transports; native callers should use
1172    /// [`DidPlcResolver::<HttpPlcFetcher>::new`], which couples its cache TTL
1173    /// to this resolver's one configuration object.
1174    pub fn with_fetcher(fetcher: F, config: PlcResolverConfig) -> Self {
1175        Self { fetcher, config }
1176    }
1177
1178    /// The resolver's directory configuration (base URL, TTL).
1179    pub fn config(&self) -> &PlcResolverConfig {
1180        &self.config
1181    }
1182
1183    /// Resolve `did` to its DID document, validated.
1184    ///
1185    /// Derives the pinned URL beneath the configured base URL, fetches it, and
1186    /// enforces the subject binding ([`validate_plc_document`]). Every failure
1187    /// — malformed DID, fetch error, malformed document, `doc.id` mismatch —
1188    /// is `Err` (fail-closed).
1189    pub async fn resolve_document(&self, did: &str) -> Result<Value> {
1190        let url = did_plc_url(did, self.config.base_url())?;
1191        let doc = self.fetcher.fetch(&url).await?;
1192        validate_plc_document(did, &doc)?;
1193        let audit_url = did_plc_audit_url(did, self.config.base_url())?;
1194        let audit = self.fetcher.fetch_audit(&audit_url).await?;
1195        verify_plc_audit(did, &audit, &doc)?;
1196        Ok(doc)
1197    }
1198}
1199
1200impl DidPlcResolver<HttpPlcFetcher> {
1201    /// Construct the native HTTPS resolver from one configuration object.
1202    ///
1203    /// The fetcher is created here rather than accepted from the caller, so the
1204    /// cache enforcing the TTL and the resolver advertising it cannot diverge.
1205    pub fn new(config: PlcResolverConfig) -> Result<Self> {
1206        let fetcher = HttpPlcFetcher::new(&config)?;
1207        Ok(Self { fetcher, config })
1208    }
1209}
1210
1211// ── native HTTPS fetcher (egress-allowlisted, TTL-cached, read-only) ─────────
1212
1213/// Native HTTPS `did:plc` document fetcher.
1214///
1215/// Same fetch+cache posture as the did:web fetcher
1216/// ([`crate::did_web::HttpDidDocFetcher`]) — no redirects, 10s connect/total
1217/// timeouts, a 1 MiB body cap ([`read_capped`]), a bounded TTL cache
1218/// ([`evict_for_insert`], failures never cached, expired entries never
1219/// served) — plus the #1161 **egress allowlist**: a request is dispatched only
1220/// if its URL's origin is on the allowlist, which is exactly the configured
1221/// PLC directory's origin. A mis-derived or attacker-influenced URL pointing
1222/// anywhere else (link-local metadata endpoints, loopback, a different
1223/// directory) is refused before any network I/O.
1224///
1225/// **Read-only forever:** the HTTP client is private and used for GET only;
1226/// this type exposes no write methods and no way to reach the client. That is
1227/// structural, not a convention — a PLC write path does not exist to be
1228/// misconfigured.
1229pub struct HttpPlcFetcher {
1230    http: reqwest::Client,
1231    cache: parking_lot::Mutex<std::collections::HashMap<String, CachedDoc>>,
1232    ttl: std::time::Duration,
1233    allowed_origins: Vec<url::Origin>,
1234}
1235
1236impl HttpPlcFetcher {
1237    /// Construct a fetcher for `config`'s PLC directory.
1238    ///
1239    /// Returns `Err` if the reqwest client fails to build — propagated rather
1240    /// than swallowed (a `unwrap_or_default()` would yield a client WITHOUT
1241    /// the configured timeout/redirect policy, defeating the hardening).
1242    fn new(config: &PlcResolverConfig) -> Result<Self> {
1243        let http = reqwest::Client::builder()
1244            // SSRF: do NOT follow redirects. did:plc resolution is a direct
1245            // HTTPS GET; a redirect to a loopback / link-local address would
1246            // bypass both the https-only check and the egress allowlist.
1247            .redirect(reqwest::redirect::Policy::none())
1248            // Bound how long a connect/request can hang.
1249            .connect_timeout(std::time::Duration::from_secs(10))
1250            .timeout(std::time::Duration::from_secs(10))
1251            .build()
1252            .map_err(|e| anyhow!("failed to build did:plc HTTPS client: {e}"))?;
1253        Ok(Self {
1254            http,
1255            cache: parking_lot::Mutex::new(std::collections::HashMap::new()),
1256            ttl: config.ttl(),
1257            // The egress allowlist is exactly the configured directory's
1258            // origin: the deployment's single deliberate PLC egress point.
1259            allowed_origins: vec![config.base_url().origin()],
1260        })
1261    }
1262
1263    /// The egress allowlist: the only origins this fetcher will issue
1264    /// requests to.
1265    pub fn allowed_origins(&self) -> &[url::Origin] {
1266        &self.allowed_origins
1267    }
1268
1269    fn validate_fetch_url(&self, url: &str) -> Result<Url> {
1270        let parsed = Url::parse(url)
1271            .map_err(|e| anyhow!("did:plc directory URL does not parse ({url}): {e}"))?;
1272        if parsed.scheme() != "https" {
1273            bail!("did:plc directory URL must use https:// (got {url})");
1274        }
1275        if !self.allowed_origins.contains(&parsed.origin()) {
1276            bail!(
1277                "did:plc fetch refused: origin of {url} is not in the egress allowlist (fail-closed)"
1278            );
1279        }
1280        Ok(parsed)
1281    }
1282
1283    async fn fetch_json(&self, url: &str, max_bytes: usize) -> Result<Value> {
1284        {
1285            let cache = self.cache.lock();
1286            if let Some(entry) = cache.get(url) {
1287                if entry.fetched_at.elapsed() < self.ttl {
1288                    return Ok(entry.doc.clone());
1289                }
1290            }
1291        }
1292
1293        let resp = self.http.get(url).send().await?;
1294        if !resp.status().is_success() {
1295            bail!(
1296                "did:plc directory returned non-success status {} for {url}",
1297                resp.status()
1298            );
1299        }
1300        let body = read_capped(resp, max_bytes).await?;
1301        let value = parse_did_document_no_duplicates(&body, url)?;
1302
1303        {
1304            let mut cache = self.cache.lock();
1305            evict_for_insert(&mut cache, self.ttl);
1306            cache.insert(
1307                url.to_owned(),
1308                CachedDoc {
1309                    doc: value.clone(),
1310                    fetched_at: std::time::Instant::now(),
1311                },
1312            );
1313        }
1314        Ok(value)
1315    }
1316}
1317
1318#[async_trait]
1319impl DidDocFetcher for HttpPlcFetcher {
1320    async fn fetch(&self, url: &str) -> Result<Value> {
1321        let parsed = self.validate_fetch_url(url)?;
1322        let asked = parsed
1323            .path_segments()
1324            .and_then(|mut segments| segments.next_back())
1325            .ok_or_else(|| anyhow!("did:plc document URL has no DID path segment: {url}"))?;
1326        plc_msi(asked)?;
1327        let doc = self.fetch_json(url, MAX_DID_DOC_BYTES).await?;
1328        validate_plc_document(asked, &doc)?;
1329        Ok(doc)
1330    }
1331}
1332
1333#[async_trait]
1334impl PlcAuditFetcher for HttpPlcFetcher {
1335    async fn fetch_audit(&self, url: &str) -> Result<Value> {
1336        let parsed = self.validate_fetch_url(url)?;
1337        let segments: Vec<_> = parsed
1338            .path_segments()
1339            .ok_or_else(|| anyhow!("did:plc audit URL has no path segments: {url}"))?
1340            .collect();
1341        ensure!(
1342            segments.len() >= 3
1343                && segments[segments.len() - 2] == "log"
1344                && segments[segments.len() - 1] == "audit",
1345            "did:plc audit URL must end in /log/audit"
1346        );
1347        plc_msi(segments[segments.len() - 3])?;
1348        self.fetch_json(url, MAX_PLC_AUDIT_BYTES).await
1349    }
1350}
1351
1352#[cfg(test)]
1353#[allow(clippy::unwrap_used, clippy::expect_used)]
1354mod tests {
1355    use super::*;
1356    use serde_json::json;
1357
1358    /// A spec-shaped did:plc for tests: 24 lowercase base32 chars.
1359    const DID: &str = "did:plc:ewvi7nxzyoun6zhxrhs64oiz";
1360
1361    fn configured_base() -> Url {
1362        Url::parse("https://plc.example").unwrap()
1363    }
1364
1365    // ── identifier validation ────────────────────────────────────────────
1366
1367    #[test]
1368    fn is_did_plc_prefix_check() {
1369        assert!(is_did_plc(DID));
1370        assert!(!is_did_plc("did:web:example.com"));
1371        assert!(!is_did_plc("did:plc")); // no trailing colon
1372    }
1373
1374    #[test]
1375    fn msi_accepts_conformant_did() {
1376        assert_eq!(plc_msi(DID).unwrap(), "ewvi7nxzyoun6zhxrhs64oiz");
1377        // Fragment/query strip: resolution fetches the base document.
1378        assert_eq!(
1379            plc_msi(&format!("{DID}#atproto")).unwrap(),
1380            "ewvi7nxzyoun6zhxrhs64oiz"
1381        );
1382    }
1383
1384    #[test]
1385    fn msi_rejects_non_plc_and_malformed() {
1386        assert!(plc_msi("did:web:example.com").is_err());
1387        assert!(plc_msi("did:plc:").is_err());
1388        // Wrong length (short / long).
1389        assert!(plc_msi("did:plc:abc").is_err());
1390        assert!(plc_msi("did:plc:ewvi7nxzyoun6zhxrhs64oizextra").is_err());
1391        // Uppercase is not base32-lowercase.
1392        assert!(plc_msi("did:plc:EWVI7NXZYOUN6ZHXRHS64OIZ").is_err());
1393        // `0`, `1`, `8`, `9` are not in the base32 alphabet (`a-z2-7`).
1394        assert!(plc_msi("did:plc:0wvi7nxzyoun6zhxrhs64oiz").is_err());
1395        assert!(plc_msi("did:plc:1wvi7nxzyoun6zhxrhs64oiz").is_err());
1396        assert!(plc_msi("did:plc:8wvi7nxzyoun6zhxrhs64oiz").is_err());
1397        assert!(plc_msi("did:plc:9wvi7nxzyoun6zhxrhs64oiz").is_err());
1398        // Path-injection characters can never reach URL derivation.
1399        assert!(plc_msi("did:plc:ewvi7nxzyoun6zhxrhs64oi/").is_err());
1400        assert!(plc_msi("did:plc:ewvi7nxzyoun6zhxrhs64oi%").is_err());
1401    }
1402
1403    // ── config validation ────────────────────────────────────────────────
1404
1405    #[test]
1406    fn config_accepts_https_base() {
1407        let cfg =
1408            PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap();
1409        assert_eq!(cfg.base_url().as_str(), "https://plc.example/");
1410        assert_eq!(cfg.ttl(), std::time::Duration::from_secs(60));
1411    }
1412
1413    #[test]
1414    fn config_rejects_http_credentials_query_fragment() {
1415        assert!(PlcResolverConfig::new(
1416            Url::parse("http://plc.invalid").unwrap(),
1417            std::time::Duration::from_secs(60)
1418        )
1419        .is_err());
1420        assert!(PlcResolverConfig::new(
1421            Url::parse("https://user:pass@plc.invalid").unwrap(),
1422            std::time::Duration::from_secs(60)
1423        )
1424        .is_err());
1425        assert!(PlcResolverConfig::new(
1426            Url::parse("https://plc.invalid/?token=x").unwrap(),
1427            std::time::Duration::from_secs(60)
1428        )
1429        .is_err());
1430        assert!(PlcResolverConfig::new(
1431            Url::parse("https://plc.invalid/#frag").unwrap(),
1432            std::time::Duration::from_secs(60)
1433        )
1434        .is_err());
1435    }
1436
1437    // ── URL derivation ───────────────────────────────────────────────────
1438    #[test]
1439    fn url_derivation_configured_base() {
1440        assert_eq!(
1441            did_plc_url(DID, &configured_base()).unwrap(),
1442            format!("https://plc.example/{DID}")
1443        );
1444    }
1445
1446    #[test]
1447    fn url_derivation_custom_base_with_path() {
1448        // Base path is treated as a directory: the full DID is appended, not
1449        // substituted for the last segment.
1450        let base = Url::parse("https://plc.example/mirror").unwrap();
1451        assert_eq!(
1452            did_plc_url(DID, &base).unwrap(),
1453            "https://plc.example/mirror/did:plc:ewvi7nxzyoun6zhxrhs64oiz"
1454        );
1455        // Idempotent with an existing trailing slash.
1456        let base = Url::parse("https://plc.example/mirror/").unwrap();
1457        assert_eq!(
1458            did_plc_url(DID, &base).unwrap(),
1459            "https://plc.example/mirror/did:plc:ewvi7nxzyoun6zhxrhs64oiz"
1460        );
1461        // A port survives on the origin.
1462        let base = Url::parse("https://localhost:8443").unwrap();
1463        assert_eq!(
1464            did_plc_url(DID, &base).unwrap(),
1465            "https://localhost:8443/did:plc:ewvi7nxzyoun6zhxrhs64oiz"
1466        );
1467    }
1468
1469    #[test]
1470    fn url_derivation_rejects_malformed_did() {
1471        assert!(did_plc_url("did:web:example.com", &configured_base()).is_err());
1472        assert!(did_plc_url("did:plc:tooshort", &configured_base()).is_err());
1473    }
1474
1475    // ── doc.id validation ────────────────────────────────────────────────
1476
1477    #[test]
1478    fn validate_accepts_matching_subject() {
1479        let doc = json!({ "id": DID, "verificationMethod": [] });
1480        assert!(validate_plc_document(DID, &doc).is_ok());
1481        // Fragment on the asked DID is ignored (base document).
1482        assert!(validate_plc_document(&format!("{DID}#atproto"), &doc).is_ok());
1483    }
1484
1485    #[test]
1486    fn validate_rejects_substituted_subject() {
1487        // A document for a DIFFERENT subject returned for our DID: the
1488        // substitution-oracle case (#1161).
1489        let doc = json!({ "id": "did:plc:zxcvbnmasdfghjklqwertyu", "verificationMethod": [] });
1490        let err = validate_plc_document(DID, &doc).unwrap_err();
1491        assert!(err.to_string().contains("mismatch"), "{err}");
1492    }
1493
1494    #[test]
1495    fn validate_rejects_missing_or_nonstring_id() {
1496        assert!(validate_plc_document(DID, &json!({ "verificationMethod": [] })).is_err());
1497        assert!(validate_plc_document(DID, &json!({ "id": 42 })).is_err());
1498        // Not an object at all.
1499        assert!(validate_plc_document(DID, &json!(["not", "an", "object"])).is_err());
1500    }
1501
1502    #[test]
1503    fn validate_rejects_malformed_collection_members() {
1504        assert!(validate_plc_document(DID, &json!({ "id": DID, "service": {} })).is_err());
1505        assert!(
1506            validate_plc_document(DID, &json!({ "id": DID, "verificationMethod": {} })).is_err()
1507        );
1508    }
1509
1510    #[test]
1511    fn validate_rejects_malformed_or_ambiguous_collection_members() {
1512        assert!(validate_plc_document(DID, &json!({ "id": DID, "alsoKnownAs": [null] })).is_err());
1513        assert!(validate_plc_document(
1514            DID,
1515            &json!({
1516                "id": DID,
1517                "verificationMethod": [{ "id": "#key", "type": "Multikey" }]
1518            })
1519        )
1520        .is_err());
1521        assert!(validate_plc_document(
1522            DID,
1523            &json!({
1524                "id": DID,
1525                "verificationMethod": [
1526                    {
1527                        "id": "#key",
1528                        "type": "Multikey",
1529                        "controller": DID,
1530                        "publicKeyMultibase": "zKey"
1531                    },
1532                    {
1533                        "id": "#key",
1534                        "type": "Multikey",
1535                        "controller": DID,
1536                        "publicKeyMultibase": "zOtherKey"
1537                    }
1538                ]
1539            })
1540        )
1541        .is_err());
1542        assert!(validate_plc_document(
1543            DID,
1544            &json!({
1545                "id": DID,
1546                "service": [{ "id": "#pds", "type": "AtprotoPersonalDataServer" }]
1547            })
1548        )
1549        .is_err());
1550        assert!(validate_plc_document(
1551            DID,
1552            &json!({
1553                "id": DID,
1554                "service": [
1555                    { "id": "#pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": "https://pds.example" },
1556                    { "id": "#pds", "type": "AtprotoPersonalDataServer", "serviceEndpoint": "https://other.example" }
1557                ]
1558            })
1559        )
1560        .is_err());
1561    }
1562
1563    #[test]
1564    fn parser_rejects_ambiguous_duplicate_keys() {
1565        let duplicate_id = format!(r#"{{"id":"{DID}","id":"did:plc:zxcvbnmasdfghjklqwertyu"}}"#);
1566        assert!(parse_did_document_no_duplicates(
1567            duplicate_id.as_bytes(),
1568            "https://plc.example/doc"
1569        )
1570        .is_err());
1571        assert!(parse_did_document_no_duplicates(
1572            br#"{"id":"did:plc:ewvi7nxzyoun6zhxrhs64oiz","service":[{"type":"a","type":"b"}] }"#,
1573            "https://plc.example/doc"
1574        )
1575        .is_err());
1576    }
1577
1578    #[test]
1579    fn captured_audit_verifies_cids_genesis_and_signature_chain() {
1580        verify_plc_audit(DID, &captured_audit(), &captured_document()).unwrap();
1581    }
1582
1583    #[test]
1584    fn audit_rejects_signature_tamper_even_with_recomputed_cid() {
1585        let mut audit = captured_audit();
1586        let entries = audit.as_array_mut().unwrap();
1587        let last = entries.last_mut().unwrap();
1588        let operation = last.get_mut("operation").unwrap();
1589        operation["sig"] =
1590            Value::String("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".into());
1591        last["cid"] = Value::String(operation_cid(operation).unwrap());
1592
1593        let err = verify_plc_audit(DID, &audit, &captured_document()).unwrap_err();
1594        assert!(err.to_string().contains("signature"), "{err:#}");
1595    }
1596
1597    #[test]
1598    fn audit_rejects_unsigned_current_document_substitution() {
1599        let mut substituted = captured_document();
1600        substituted["verificationMethod"][0]["publicKeyMultibase"] =
1601            Value::String("zQ3shXjHeiBuRCKmM36cuYnm7YEMzhGnCmCyW92sRJ9pribSF".into());
1602        let err = verify_plc_audit(DID, &captured_audit(), &substituted).unwrap_err();
1603        assert!(err.to_string().contains("verified audit-log head"), "{err}");
1604    }
1605
1606    #[test]
1607    fn audit_head_comparison_canonicalizes_relative_member_ids() {
1608        let mut document = captured_document();
1609        document["verificationMethod"][0]["id"] = Value::String("#atproto".into());
1610        verify_plc_audit(DID, &captured_audit(), &document).unwrap();
1611    }
1612
1613    // ── Finding 2: typed verification-material / member validation ───────
1614    //
1615    // Each case below was wrongly ACCEPTED by the prior ad-hoc presence check.
1616    // The validator must fail closed on malformed material, ambiguous members,
1617    // and semantically-duplicate identifiers, while preserving conforming
1618    // extensions (an unknown algorithm with a real key still resolves).
1619
1620    /// A `publicKeyMultibase` that is not a valid Multikey public key
1621    /// (`zKey` — too short to carry any multicodec + key) and a `publicKeyJwk`
1622    /// that is not a JWK (`{ "garbage": true }`, no `kty`) must be rejected.
1623    #[test]
1624    fn validate_rejects_malformed_verification_material() {
1625        // Multikey with a structurally-invalid `publicKeyMultibase`.
1626        assert!(validate_plc_document(
1627            DID,
1628            &json!({
1629                "id": DID,
1630                "verificationMethod": [{
1631                    "id": "#bad-multikey", "type": "Multikey", "controller": DID,
1632                    "publicKeyMultibase": "zKey"
1633                }]
1634            })
1635        )
1636        .is_err());
1637        // A `publicKeyMultibase` that is not even multibase base58btc.
1638        assert!(validate_plc_document(
1639            DID,
1640            &json!({
1641                "id": DID,
1642                "verificationMethod": [{
1643                    "id": "#bad-multikey2", "type": "Multikey", "controller": DID,
1644                    "publicKeyMultibase": "not-multibase"
1645                }]
1646            })
1647        )
1648        .is_err());
1649        // `publicKeyJwk` missing `kty` is not a JWK.
1650        assert!(validate_plc_document(
1651            DID,
1652            &json!({
1653                "id": DID,
1654                "verificationMethod": [{
1655                    "id": "#bad-jwk", "type": "JsonWebKey", "controller": DID,
1656                    "publicKeyJwk": { "garbage": true }
1657                }]
1658            })
1659        )
1660        .is_err());
1661        // A JWK with an unknown `kty` is not a recognized JWK either.
1662        assert!(validate_plc_document(
1663            DID,
1664            &json!({
1665                "id": DID,
1666                "verificationMethod": [{
1667                    "id": "#bad-jwk2", "type": "JsonWebKey", "controller": DID,
1668                    "publicKeyJwk": { "kty": "NotARealKty" }
1669                }]
1670            })
1671        )
1672        .is_err());
1673        // A verification method with NO recognized material property is
1674        // non-conforming (DID Core §5.1 requires material).
1675        assert!(validate_plc_document(
1676            DID,
1677            &json!({
1678                "id": DID,
1679                "verificationMethod": [{
1680                    "id": "#no-material", "type": "Multikey", "controller": DID
1681                }]
1682            })
1683        )
1684        .is_err());
1685    }
1686
1687    /// A conforming extension — an unknown algorithm that still carries a
1688    /// valid Multikey payload — must be preserved (interop: ignore unknown
1689    /// algs rather than failing).
1690    #[test]
1691    fn validate_preserves_unknown_algorithm_with_valid_material() {
1692        // A synthetic unknown multicodec (0x0bad) with a 32-byte payload is
1693        // structurally a real Multikey; the resolver must not reject it.
1694        let unknown_key = {
1695            let payload = [0x0bu8, 0xad, 0x01]; // varint codec 0x0bad01-ish + ...
1696            let mut bytes = vec![0xfd, 0x01]; // some unknown 2-byte codec
1697            bytes.extend_from_slice(&payload);
1698            bytes.extend_from_slice(&[0u8; 30]); // bring payload ≥ floor
1699            format!("z{}", bs58::encode(&bytes).into_string())
1700        };
1701        let doc = json!({
1702            "id": DID,
1703            "verificationMethod": [{
1704                "id": "#unknown", "type": "UnknownVerificationMethod2026",
1705                "controller": DID, "publicKeyMultibase": unknown_key
1706            }]
1707        });
1708        assert!(validate_plc_document(DID, &doc).is_ok());
1709    }
1710
1711    /// Multiple verification-material properties on one method is ambiguous
1712    /// and must fail closed (DID Core requires exactly one).
1713    #[test]
1714    fn validate_rejects_multiple_material_properties() {
1715        // A valid Ed25519 Multikey present alongside a JWK: ambiguous.
1716        let mk = "zQ3shunBKsXixLxKtC5qeSG9E4J5RkGN57im31pcTzbNQnm5w";
1717        assert!(validate_plc_document(
1718            DID,
1719            &json!({
1720                "id": DID,
1721                "verificationMethod": [{
1722                    "id": "#both", "type": "Multikey", "controller": DID,
1723                    "publicKeyMultibase": mk,
1724                    "publicKeyJwk": { "kty": "OKP", "crv": "Ed25519", "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlnw_vyHashME" }
1725                }]
1726            })
1727        )
1728        .is_err());
1729    }
1730
1731    /// A relative reference `#key` and the absolute DID URL
1732    /// `did:plc:…#key` name the SAME resource (DID Core relative-URL
1733    /// resolution); both must not be accepted together.
1734    #[test]
1735    fn validate_rejects_semantically_duplicate_ids() {
1736        let mk = "zQ3shunBKsXixLxKtC5qeSG9E4J5RkGN57im31pcTzbNQnm5w";
1737        assert!(validate_plc_document(
1738            DID,
1739            &json!({
1740                "id": DID,
1741                "verificationMethod": [
1742                    { "id": "#key", "type": "Multikey", "controller": DID, "publicKeyMultibase": mk },
1743                    { "id": format!("{DID}#key"), "type": "Multikey", "controller": DID, "publicKeyMultibase": mk }
1744                ]
1745            })
1746        )
1747        .is_err());
1748    }
1749
1750    /// DID/URI fields are checked for their required syntax, not merely
1751    /// non-emptiness: `alsoKnownAs` entries, string `serviceEndpoint`s, VM
1752    /// `id`s, and `controller`s must be URIs / DID URLs / DIDs respectively.
1753    #[test]
1754    fn validate_rejects_non_did_or_non_uri_fields() {
1755        // alsoKnownAs must be URIs.
1756        assert!(
1757            validate_plc_document(DID, &json!({ "id": DID, "alsoKnownAs": ["not-a-uri"] }))
1758                .is_err()
1759        );
1760        // controller must be a DID.
1761        assert!(validate_plc_document(
1762            DID,
1763            &json!({
1764                "id": DID,
1765                "verificationMethod": [{
1766                    "id": "#k", "type": "Multikey", "controller": "not-a-did",
1767                    "publicKeyMultibase": "zQ3shunBKsXixLxKtC5qeSG9E4J5RkGN57im31pcTzbNQnm5w"
1768                }]
1769            })
1770        )
1771        .is_err());
1772        // An absolute VM id that is not a DID URL (https URL) is rejected.
1773        assert!(validate_plc_document(
1774            DID,
1775            &json!({
1776                "id": DID,
1777                "verificationMethod": [{
1778                    "id": "https://evil.example/key", "type": "Multikey", "controller": DID,
1779                    "publicKeyMultibase": "zQ3shunBKsXixLxKtC5qeSG9E4J5RkGN57im31pcTzbNQnm5w"
1780                }]
1781            })
1782        )
1783        .is_err());
1784        // A string serviceEndpoint must be a URI.
1785        assert!(validate_plc_document(
1786            DID,
1787            &json!({
1788                "id": DID,
1789                "service": [{ "id": "#pds", "type": "T", "serviceEndpoint": "no-scheme-here" }]
1790            })
1791        )
1792        .is_err());
1793    }
1794
1795    // ── resolver over an injected fixture fetcher (no network) ───────────
1796
1797    struct FixtureFetcher {
1798        doc: Value,
1799        audit: Value,
1800    }
1801
1802    #[async_trait]
1803    impl DidDocFetcher for FixtureFetcher {
1804        async fn fetch(&self, url: &str) -> Result<Value> {
1805            assert_eq!(url, "https://plc.example/did:plc:ewvi7nxzyoun6zhxrhs64oiz");
1806            Ok(self.doc.clone())
1807        }
1808    }
1809
1810    #[async_trait]
1811    impl PlcAuditFetcher for FixtureFetcher {
1812        async fn fetch_audit(&self, url: &str) -> Result<Value> {
1813            assert_eq!(
1814                url,
1815                "https://plc.example/did:plc:ewvi7nxzyoun6zhxrhs64oiz/log/audit"
1816            );
1817            Ok(self.audit.clone())
1818        }
1819    }
1820
1821    /// A fetcher that MUST NOT be called: a malformed DID must fail before
1822    /// any fetch.
1823    struct NeverFetcher;
1824
1825    #[async_trait]
1826    impl DidDocFetcher for NeverFetcher {
1827        async fn fetch(&self, url: &str) -> Result<Value> {
1828            panic!("resolver must not fetch for a malformed DID (called with {url})");
1829        }
1830    }
1831
1832    #[async_trait]
1833    impl PlcAuditFetcher for NeverFetcher {
1834        async fn fetch_audit(&self, url: &str) -> Result<Value> {
1835            panic!("resolver must not fetch audit for a malformed DID (called with {url})");
1836        }
1837    }
1838
1839    fn captured_document() -> Value {
1840        parse_did_document_no_duplicates(
1841            include_bytes!("fixtures/plc_directory_ewvi7nxzyoun6zhxrhs64oiz.json"),
1842            "captured PLC document",
1843        )
1844        .unwrap()
1845    }
1846
1847    fn captured_audit() -> Value {
1848        parse_did_document_no_duplicates(
1849            include_bytes!("fixtures/plc_directory_ewvi7nxzyoun6zhxrhs64oiz_audit.json"),
1850            "captured PLC audit",
1851        )
1852        .unwrap()
1853    }
1854
1855    fn fixture_resolver(doc: Value) -> DidPlcResolver<FixtureFetcher> {
1856        DidPlcResolver::with_fetcher(
1857            FixtureFetcher {
1858                doc,
1859                audit: captured_audit(),
1860            },
1861            PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap(),
1862        )
1863    }
1864
1865    #[tokio::test]
1866    async fn resolve_document_returns_signature_chain_verified_doc() {
1867        let doc = captured_document();
1868        let resolver = fixture_resolver(doc.clone());
1869        let got = resolver.resolve_document(DID).await.unwrap();
1870        assert_eq!(got, doc);
1871    }
1872
1873    #[tokio::test]
1874    async fn resolve_document_accepts_captured_reference_directory_document() {
1875        // Captured unchanged from https://plc.directory/did:plc:ewvi7nxzyoun6zhxrhs64oiz
1876        // on 2026-07-22. This guards the actual reference-directory shape and
1877        // the full-DID request target, rather than a hand-written approximation.
1878        let doc = parse_did_document_no_duplicates(
1879            include_bytes!("fixtures/plc_directory_ewvi7nxzyoun6zhxrhs64oiz.json"),
1880            "https://plc.directory/did:plc:ewvi7nxzyoun6zhxrhs64oiz",
1881        )
1882        .unwrap();
1883        let resolver = fixture_resolver(doc.clone());
1884        assert_eq!(resolver.resolve_document(DID).await.unwrap(), doc);
1885    }
1886
1887    #[tokio::test]
1888    async fn resolve_document_rejects_id_mismatch() {
1889        let doc = json!({ "id": "did:plc:zxcvbnmasdfghjklqwertyu" });
1890        let resolver = fixture_resolver(doc);
1891        let err = resolver.resolve_document(DID).await.unwrap_err();
1892        assert!(err.to_string().contains("mismatch"), "{err}");
1893    }
1894
1895    #[tokio::test]
1896    async fn resolve_document_rejects_missing_id() {
1897        let resolver = fixture_resolver(json!({ "verificationMethod": [] }));
1898        assert!(resolver.resolve_document(DID).await.is_err());
1899    }
1900
1901    #[tokio::test]
1902    async fn resolve_document_fetch_failure_fails_closed() {
1903        struct FailingFetcher;
1904        #[async_trait]
1905        impl DidDocFetcher for FailingFetcher {
1906            async fn fetch(&self, url: &str) -> Result<Value> {
1907                bail!("simulated directory failure for {url}");
1908            }
1909        }
1910        #[async_trait]
1911        impl PlcAuditFetcher for FailingFetcher {
1912            async fn fetch_audit(&self, url: &str) -> Result<Value> {
1913                bail!("simulated directory failure for {url}");
1914            }
1915        }
1916        let resolver = DidPlcResolver::with_fetcher(
1917            FailingFetcher,
1918            PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap(),
1919        );
1920        assert!(resolver.resolve_document(DID).await.is_err());
1921    }
1922
1923    #[tokio::test]
1924    async fn resolve_document_malformed_did_never_fetches() {
1925        let resolver = DidPlcResolver::with_fetcher(
1926            NeverFetcher,
1927            PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap(),
1928        );
1929        assert!(resolver.resolve_document("did:plc:tooshort").await.is_err());
1930        assert!(resolver
1931            .resolve_document("did:web:example.com")
1932            .await
1933            .is_err());
1934    }
1935
1936    // ── fetcher hardening (egress allowlist / https-only) ────────────────
1937
1938    #[test]
1939    fn fetcher_allowlist_is_configured_origin() {
1940        let cfg = PlcResolverConfig::new(
1941            Url::parse("https://plc.example/mirror").unwrap(),
1942            std::time::Duration::from_secs(60),
1943        )
1944        .unwrap();
1945        let f = HttpPlcFetcher::new(&cfg).unwrap();
1946        assert_eq!(
1947            f.allowed_origins(),
1948            &[Url::parse("https://plc.example").unwrap().origin()]
1949        );
1950    }
1951
1952    #[test]
1953    fn native_resolver_uses_its_single_cache_configuration() {
1954        let config =
1955            PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(37)).unwrap();
1956        let resolver = DidPlcResolver::new(config).unwrap();
1957        assert_eq!(resolver.fetcher.ttl, resolver.config.ttl());
1958        assert_eq!(
1959            resolver.fetcher.allowed_origins,
1960            vec![resolver.config.base_url().origin()]
1961        );
1962    }
1963
1964    #[tokio::test]
1965    async fn fetcher_rejects_non_https() {
1966        let config =
1967            PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap();
1968        let f = HttpPlcFetcher::new(&config).unwrap();
1969        let err = f
1970            .fetch("http://plc.example/ewvi7nxzyoun6zhxrhs64oiz")
1971            .await
1972            .unwrap_err();
1973        assert!(err.to_string().contains("https"), "{err}");
1974    }
1975
1976    #[tokio::test]
1977    async fn fetcher_rejects_origin_outside_allowlist() {
1978        let config =
1979            PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap();
1980        let f = HttpPlcFetcher::new(&config).unwrap();
1981        // Same-shaped URL on a different origin: refused BEFORE any network
1982        // I/O (the egress allowlist, #1161).
1983        let err = f
1984            .fetch("https://evil.example/ewvi7nxzyoun6zhxrhs64oiz")
1985            .await
1986            .unwrap_err();
1987        assert!(err.to_string().contains("egress allowlist"), "{err}");
1988        // A port-shifted URL is a different origin and equally refused.
1989        let err = f
1990            .fetch("https://plc.example:4443/ewvi7nxzyoun6zhxrhs64oiz")
1991            .await
1992            .unwrap_err();
1993        assert!(err.to_string().contains("egress allowlist"), "{err}");
1994    }
1995
1996    #[tokio::test]
1997    async fn fetcher_rejects_unparseable_url() {
1998        let config =
1999            PlcResolverConfig::new(configured_base(), std::time::Duration::from_secs(60)).unwrap();
2000        let f = HttpPlcFetcher::new(&config).unwrap();
2001        assert!(f.fetch("not a url").await.is_err());
2002    }
2003}