Skip to main content

hyprstream_rpc/
identity_resolver.rs

1//! Method-dispatched [`IdentityResolver`] — the real `Did → IdentityKeys` binding (#579).
2//!
3//! This is the single, non-mirror implementation of the canonical
4//! [`crate::identity::IdentityResolver`] contract. It replaces the fixture /
5//! test-double resolvers that stood in for it while the #549 perimeter gateway
6//! and #137 admission gate were built against the interface.
7//!
8//! # Division of labor
9//!
10//! The resolver owns **verification + assurance derivation**; it does *not* own
11//! object labelling, the `KeyedPqTrustStore.bind` mesh anchor (#894), or any
12//! perimeter policy — those consumers are generic over the trait and unchanged.
13//!
14//! # Method dispatch
15//!
16//! [`resolve_identity_keys`](IdentityResolver::resolve_identity_keys) branches on
17//! the DID method:
18//!
19//! - **`did:web`** — resolve the DID document and extract its verification
20//!   methods. An Ed25519 identity VM (for example `#mesh`) is the classical anchor;
21//!   its explicitly named ML-DSA-65 companion (`#mesh-pq`, multicodec `0x1211`)
22//!   makes that candidate [`Assurance::PqHybrid`]. Other candidates remain
23//!   [`Assurance::Classical`]. No Ed25519 VM ⇒ nothing to bind ⇒ `Err` (fail-closed).
24//! - **`did:key`** — a single Ed25519 key decoded from the DID string itself; no
25//!   fetch. A single classical key can never be hybrid, so the honest ceiling is
26//!   [`Assurance::Classical`].
27//! - **`did:at9p`** — the self-certifying hybrid-PQC capsule identity (#879/#880
28//!   D2, #894). The resolver delegates to an injected [`At9pCapsuleResolver`]
29//!   that runs the A4 GATE pipeline (canon→hash→sig, #884) over the capsule and
30//!   returns its content-verified subject keys; a verified capsule yields
31//!   [`Assurance::PqHybrid`]. With no capsule resolver configured the arm fails
32//!   closed (production wiring of the mainline locator is Track C, #890).
33//! - **any other method** — `Err` (fail-closed).
34//!
35//! # Fail-closed
36//!
37//! Per the [`IdentityResolver`] contract, every inability to establish key
38//! material — an unknown method, a fetch failure, a malformed document, a
39//! did:web with no Ed25519 VM — returns `Err`. A resolver **never** returns a
40//! default-`Unverified` `Ok`.
41//!
42//! # Sync trait over an async fetch
43//!
44//! The contract is synchronous and enrollment happens **off the auth path**
45//! (once, at session establishment), so did:web document retrieval is abstracted
46//! behind a synchronous [`DidDocumentProvider`]. This keeps the decode +
47//! assurance-derivation core pure and testable with an injected fixture (no live
48//! network), mirroring the injected-fetcher pattern in [`crate::did_web`]. The
49//! async→sync bridge to the live [`crate::did_web::HttpDidDocFetcher`] is a
50//! wiring concern for the accept-path integration (there is no production
51//! construction site of the perimeter gateway today).
52
53use std::sync::Arc;
54
55use anyhow::{anyhow, Result};
56use serde_json::Value;
57
58use crate::crypto::pq::{ml_dsa_vk_from_bytes, MlDsaVerifyingKey};
59use crate::did_web::{
60    decode_ed25519_multikey, decode_multikey, did_key_to_ed25519, MULTICODEC_ML_DSA_65_PUB,
61};
62use crate::identity::{Did, IdentityKeyCandidate, IdentityKeys, IdentityResolver};
63
64/// A synchronous DID-document provider for the did:web arm.
65///
66/// Abstracted so the resolver's decode/assurance core is testable with an
67/// injected fixture (no network). Enrollment is off the auth path, so a blocking
68/// implementation is acceptable; the trait keeps that policy out of the resolver.
69pub trait DidDocumentProvider: Send + Sync {
70    /// Fetch and parse the DID document for `did` (already known to be `did:web`).
71    fn document(&self, did: &str) -> Result<Value>;
72}
73
74/// One content-verified atomic hybrid subject key: an Ed25519 identity key and
75/// the ML-DSA-65 key **bound to it in the same capsule entry** (#1188 / #1183).
76///
77/// The pairing is atomic: the ML-DSA-65 half is never recombined with a
78/// different Ed25519 half. Selecting a subject key by its Ed25519 identity
79/// therefore yields exactly the PQ key the capsule author bound to it, which is
80/// what overlap rotation and PQ-hybrid rollout require — publish several keys,
81/// let each verifier take the whole pair it recognizes.
82#[derive(Clone)]
83pub struct VerifiedAt9pKey {
84    ed25519: [u8; 32],
85    ml_dsa_65: MlDsaVerifyingKey,
86}
87
88impl VerifiedAt9pKey {
89    /// The content-verified Ed25519 identity key.
90    pub fn ed25519(&self) -> &[u8; 32] {
91        &self.ed25519
92    }
93
94    /// The ML-DSA-65 key atomically bound to [`Self::ed25519`] in the capsule.
95    pub fn ml_dsa_65(&self) -> &MlDsaVerifyingKey {
96        &self.ml_dsa_65
97    }
98}
99
100/// The content-verified subject key **set** of a `did:at9p` capsule, re-expressed
101/// in the rpc-local key types so this crate need not depend on `hyprstream-pds`
102/// (pds depends on rpc; the dependency does not reverse).
103///
104/// `subjectKeys` is a *set* of currently-usable identity keys, never an ordered
105/// list with a positional "primary" (#1188 / #1183): a producer publishes the
106/// new key alongside the old to rotate without a flag day, and a classical key
107/// beside a PQ/composite key for hybrid rollout. A consumer selects the member
108/// it recognizes — here [`Self::for_ed25519`], keyed on the Ed25519 application
109/// signer identity — and skips the rest, never letting position confer
110/// authority. The set is non-empty and its Ed25519 halves are unique (enforced
111/// by the capsule schema), so selection is unambiguous.
112///
113/// A [`VerifiedAt9pKeys`] is only constructable via the GATE mints
114/// ([`VerifiedAt9pKeys::new_gate_verified`] / [`VerifiedAt9pKeys::new_gate_verified_set`]),
115/// which only an [`At9pCapsuleResolver`] that ran the A4 GATE pipeline
116/// (canon→hash→sig, #884) to completion reaches. The private field makes the
117/// "only constructable after the GATE ran" provenance a type-level invariant
118/// rather than a bare rustdoc claim: arbitrary code cannot build one with an
119/// unverified `ed25519`↔`ml_dsa_65` binding, so holding one is proof the binding
120/// came from **content-verified capsule material**, not a config file or a
121/// caller assertion (the D2/#894 provenance boundary, hardened in #964).
122#[derive(Clone)]
123pub struct VerifiedAt9pKeys {
124    /// The content-verified subject key set — non-empty, unique Ed25519 halves.
125    keys: Vec<VerifiedAt9pKey>,
126}
127
128impl VerifiedAt9pKeys {
129    /// The GATE mint for a **single** verified subject key — a convenience over
130    /// [`Self::new_gate_verified_set`] for the (common) single-key capsule.
131    ///
132    /// This is the constructor-witness chokepoint: the field is private, so the
133    /// *only* way to produce a `VerifiedAt9pKeys` is one of these mints, which
134    /// encode the GATE-ran provenance in their names. Trusted callers are the A4
135    /// GATE resolver implementations (the real [`At9pCapsuleResolver`] impl in
136    /// `hyprstream-pds::at9p_resolver`, plus in-crate test fixtures). Code that
137    /// has not run the GATE has no business calling this — review a new call site
138    /// as a provenance decision, not a mechanical field set.
139    ///
140    /// (Rust cannot seal this across crates — `hyprstream-pds` is a *dependent* of
141    /// `hyprstream-rpc`, so rpc has no way to grant pds the mint while denying it
142    /// to arbitrary code. The private field + named mints convert the provenance
143    /// from "any code can write the struct literal" to "any code must go through
144    /// one review-visible chokepoint", which is the proportionate hardening; the
145    /// trust root remains "whoever injects the gate is trusted".)
146    pub fn new_gate_verified(ed25519: [u8; 32], ml_dsa_65: MlDsaVerifyingKey) -> Self {
147        Self {
148            keys: vec![VerifiedAt9pKey { ed25519, ml_dsa_65 }],
149        }
150    }
151
152    /// The GATE mint for the full verified subject key **set** (#1188).
153    ///
154    /// The projected set MUST be non-empty (the schema guarantees it) and MUST
155    /// have unique Ed25519 halves so [`Self::for_ed25519`] selection is
156    /// unambiguous — the same discipline the capsule schema enforces on
157    /// `subjectKeys`. A violation is a projection bug, not attacker input, so it
158    /// is a fail-closed `Err` rather than a silent first-wins.
159    pub fn new_gate_verified_set(keys: Vec<VerifiedAt9pKey>) -> Result<Self> {
160        if keys.is_empty() {
161            return Err(anyhow!(
162                "VerifiedAt9pKeys: capsule projected an empty subject key set (fail-closed)"
163            ));
164        }
165        for (i, a) in keys.iter().enumerate() {
166            if keys[i + 1..].iter().any(|b| b.ed25519 == a.ed25519) {
167                return Err(anyhow!(
168                    "VerifiedAt9pKeys: duplicate Ed25519 subject key in projected set — \
169                     ambiguous selection (fail-closed)"
170                ));
171            }
172        }
173        Ok(Self { keys })
174    }
175
176    /// Build a [`VerifiedAt9pKey`] for the set mint — pds-side projection helper.
177    pub fn key(ed25519: [u8; 32], ml_dsa_65: MlDsaVerifyingKey) -> VerifiedAt9pKey {
178        VerifiedAt9pKey { ed25519, ml_dsa_65 }
179    }
180
181    /// Select the verified subject key whose Ed25519 half equals `ed25519`, if
182    /// the capsule published one — the set-semantics accessor (#1188).
183    ///
184    /// A consumer holding an Ed25519 application-signer identity finds *its*
185    /// hybrid pair by identity and takes the atomically-bound ML-DSA-65 half from
186    /// the same entry. Returns `None` when no published key matches; the caller
187    /// then rejects fail-closed rather than falling back to a positional key.
188    pub fn for_ed25519(&self, ed25519: &[u8; 32]) -> Option<&VerifiedAt9pKey> {
189        self.keys.iter().find(|k| &k.ed25519 == ed25519)
190    }
191
192    /// Whether `ed25519` is one of the published, content-verified subject keys.
193    pub fn publishes_ed25519(&self, ed25519: &[u8; 32]) -> bool {
194        self.for_ed25519(ed25519).is_some()
195    }
196
197    /// All content-verified subject keys in the set (non-empty).
198    pub fn keys(&self) -> &[VerifiedAt9pKey] {
199        &self.keys
200    }
201}
202
203/// Verifies a `did:at9p` capsule and yields its content-verified subject keys.
204///
205/// The A4 GATE pipeline (`canon-gate → hash-gate(H512 == cid512) → sig-gate`,
206/// #884) lives in `hyprstream-pds` beside the capsule schema. The lower
207/// `hyprstream-rpc` crate — which both the admission gate (`crate::admission`) and
208/// this resolver belong to — cannot depend on pds, so the GATE is abstracted
209/// behind this object-safe trait and implemented in pds over
210/// `hyprstream_pds::at9p_gate::verify_did_at9p`.
211///
212/// Two entry points, each fail-closed on any GATE failure (never a default-`Ok`):
213///
214/// - [`verify_bytes`](Self::verify_bytes) — the **admission path**: the peer
215///   presented its capsule bytes over the channel; the GATE decides whether to
216///   accept them. Used by `admit_key_against_did`'s `did:at9p` arm to bind the
217///   verified hybrid keys into the [`crate::envelope::KeyedPqTrustStore`] (#894).
218/// - [`resolve`](Self::resolve) — the **resolver path**: fetch the capsule bytes
219///   for `did` from the (untrusted) mainline locator (#890, Track C) and GATE-verify
220///   them. Used by this module's `did:at9p` arm to derive `PqHybrid` assurance.
221///
222/// The default impls return `Err` so a configuration that supplies only one path
223/// (admission today; the locator is not wired) leaves the other fail-closed rather
224/// than silently degrading.
225pub trait At9pCapsuleResolver: Send + Sync {
226    /// GATE-verify `capsule_bytes` the peer presented for `did:at9p:<cid512>`
227    /// (admission path). Pure over the bytes — no fetch, no I/O.
228    fn verify_bytes(&self, did: &str, capsule_bytes: &[u8]) -> Result<VerifiedAt9pKeys> {
229        let _ = (did, capsule_bytes);
230        Err(anyhow!(
231            "at9p capsule-byte verification is not configured (fail-closed)"
232        ))
233    }
234
235    /// Fetch the capsule for `did` from the untrusted locator and GATE-verify it
236    /// (resolver path). The locator itself is Track C (#890); until it is wired an
237    /// honest implementation returns `Err`.
238    fn resolve(&self, did: &str) -> Result<VerifiedAt9pKeys> {
239        let _ = did;
240        Err(anyhow!(
241            "at9p capsule resolution (locator fetch) is not configured (fail-closed)"
242        ))
243    }
244}
245
246/// The real, method-dispatched [`IdentityResolver`] (#579).
247///
248/// Generic over a [`DidDocumentProvider`] so the did:web fetch is injectable
249/// (fixture in tests, blocking HTTPS fetcher in production wiring). The optional
250/// [`At9pCapsuleResolver`] supplies the `did:at9p` arm (D2/#894); when `None` a
251/// `did:at9p` identity fails closed exactly as it did before the arm existed.
252pub struct MethodDispatchResolver<P: DidDocumentProvider> {
253    docs: P,
254    at9p: Option<Arc<dyn At9pCapsuleResolver>>,
255    now: Arc<dyn Fn() -> i64 + Send + Sync>,
256}
257
258impl<P: DidDocumentProvider> MethodDispatchResolver<P> {
259    /// Construct a resolver over a DID-document provider.
260    pub fn new(docs: P) -> Self {
261        Self {
262            docs,
263            at9p: None,
264            now: Arc::new(|| {
265                std::time::SystemTime::now()
266                    .duration_since(std::time::UNIX_EPOCH)
267                    .map_or(0, |duration| duration.as_secs() as i64)
268            }),
269        }
270    }
271
272    /// Override the wall clock used to enforce bounded DID verification methods.
273    ///
274    /// Production uses Unix time. Tests and embedders can inject a deterministic
275    /// clock to prove overlap and retirement behavior without sleeping.
276    pub fn with_clock(mut self, now: impl Fn() -> i64 + Send + Sync + 'static) -> Self {
277        self.now = Arc::new(now);
278        self
279    }
280
281    /// Attach the `did:at9p` capsule resolver (D2/#894). Without it a `did:at9p`
282    /// identity fails closed; with it, a GATE-verified capsule yields `PqHybrid`.
283    pub fn with_at9p(mut self, at9p: Arc<dyn At9pCapsuleResolver>) -> Self {
284        self.at9p = Some(at9p);
285        self
286    }
287
288    /// The did:web arm: resolve the document and derive key material + assurance.
289    ///
290    /// Each usable Ed25519 VM becomes a named candidate. A same-name `-pq` VM
291    /// explicitly upgrades only that candidate to `PqHybrid`; unrelated PQ VMs
292    /// are never paired by document order.
293    /// - No Ed25519 VM ⇒ `Err` (fail-closed: nothing to anchor).
294    ///
295    /// # Assurance quality — the at9p asymmetry
296    ///
297    /// Unlike the `did:at9p` arm, where the `ed25519`↔`ml_dsa_65` pair is
298    /// **content-verified** by the GATE over a self-certifying capsule, the
299    /// `did:web` arm's `PqHybrid` rests on **co-presence in a TLS-fetched
300    /// document**, not on a content-binding between the two keys. Two caveats
301    /// follow, consistent with the ratified #579/D1 "did:web we operate" model:
302    ///
303    /// - **Named pairing:** an Ed25519 VM `#mesh-old` may be paired only with
304    ///   the explicitly named ML-DSA-65 VM `#mesh-old-pq`. This gives each
305    ///   overlap slot an independent hybrid binding; a PQ VM with no matching
306    ///   Ed25519 VM is ignored rather than attached to an arbitrary key.
307    /// - **No content binding:** the document attests both keys, but nothing in the
308    ///   TLS fetch proves the Ed25519 and ML-DSA-65 keys belong to the same
309    ///   principal beyond the document's own say-so. The at9p capsule proves this
310    ///   cryptographically; did:web trusts the (TLS-transported) document.
311    fn resolve_did_web(&self, did: &Did) -> Result<IdentityKeys> {
312        let doc = self
313            .docs
314            .document(did.as_str())
315            .map_err(|e| anyhow!("did:web {did} document did not resolve: {e}"))?;
316
317        let candidates = did_web_key_candidates(&doc, (self.now)());
318        if candidates.is_empty() {
319            anyhow::bail!("did:web {did}: no Ed25519 verificationMethod to anchor — fail-closed");
320        }
321        Ok(IdentityKeys::new(candidates))
322    }
323
324    /// The did:key arm: a single self-certifying Ed25519 key, no fetch.
325    ///
326    /// A `did:key` encodes exactly one key; a single classical key can never be
327    /// hybrid, so assurance is `Classical` (the honest ceiling).
328    fn resolve_did_key(&self, did: &Did) -> Result<IdentityKeys> {
329        let ed25519 = did_key_to_ed25519(did.as_str())
330            .map_err(|e| anyhow!("did:key {did} is not a valid Ed25519 identity: {e}"))?;
331        Ok(IdentityKeys::single_ed25519(did.as_str(), ed25519))
332    }
333
334    /// The did:at9p arm (#894, D2): GATE-verify the capsule and derive `PqHybrid`.
335    ///
336    /// Delegates to the configured [`At9pCapsuleResolver`], which runs the A4
337    /// canon→hash→sig pipeline (#884). Only a verified capsule reaches here: both
338    /// the classical Ed25519 and the bound ML-DSA-65 keys come from
339    /// content-verified material, so the honest assurance ceiling is `PqHybrid`
340    /// (the classical→hybrid trust upgrade). Any GATE failure, and a missing
341    /// capsule resolver, fail closed.
342    ///
343    /// # Set semantics (#1188 / #1183)
344    ///
345    /// The capsule publishes a *set* of subject keys so overlap rotation and
346    /// PQ-hybrid rollout work. Every content-verified pair becomes a candidate;
347    /// callers select by the admitted Ed25519 signer, never by capsule position.
348    fn resolve_did_at9p(&self, did: &Did) -> Result<IdentityKeys> {
349        let at9p = self.at9p.as_ref().ok_or_else(|| {
350            anyhow!("did:at9p {did}: no capsule resolver configured — fail-closed")
351        })?;
352        let verified = at9p
353            .resolve(did.as_str())
354            .map_err(|e| anyhow!("did:at9p {did}: capsule GATE failed: {e}"))?;
355        Ok(IdentityKeys::new(
356            verified
357                .keys()
358                .iter()
359                .map(|key| IdentityKeyCandidate {
360                    id: format!(
361                        "{}#subject-{}",
362                        did.as_str(),
363                        bs58::encode(key.ed25519()).into_string()
364                    ),
365                    ed25519: *key.ed25519(),
366                    ml_dsa_65: Some(key.ml_dsa_65().clone()),
367                })
368                .collect(),
369        ))
370    }
371}
372
373/// Decode the named DID verification-method set into compatible candidates.
374///
375/// DID VM ids are the selector. An Ed25519 VM `id` is upgraded only by an
376/// ML-DSA-65 VM whose id is `"{id}-pq"`; this is the mesh's stable, explicit
377/// hybrid binding convention (`#mesh` ↔ `#mesh-pq`). The function deliberately
378/// does not expose a positional selection API: callers receive every usable
379/// candidate and choose using a verified signer or another protocol selector.
380fn did_web_key_candidates(doc: &Value, now: i64) -> Vec<IdentityKeyCandidate> {
381    let Some(vms) = doc.get("verificationMethod").and_then(Value::as_array) else {
382        return Vec::new();
383    };
384
385    let mut ed25519 = Vec::new();
386    let mut ml_dsa_65 = std::collections::HashMap::new();
387    for vm in vms {
388        let (Some(id), Some(multibase)) = (
389            vm.get("id").and_then(Value::as_str),
390            vm.get("publicKeyMultibase").and_then(Value::as_str),
391        ) else {
392            continue;
393        };
394        if !verification_method_is_live(vm, now) {
395            continue;
396        }
397        if let Ok(key) = decode_ed25519_multikey(multibase) {
398            ed25519.push((id.to_owned(), key));
399            continue;
400        }
401        let Ok(raw) = decode_multikey(multibase, &MULTICODEC_ML_DSA_65_PUB) else {
402            continue;
403        };
404        match ml_dsa_vk_from_bytes(&raw) {
405            Ok(key) => {
406                ml_dsa_65.insert(id.to_owned(), key);
407            }
408            Err(error) => {
409                tracing::debug!(%error, verification_method = %id, "skipping invalid ML-DSA-65 DID verification method");
410            }
411        }
412    }
413
414    let legacy_pq_id = doc
415        .get("id")
416        .and_then(Value::as_str)
417        .map(|did| format!("{did}#mesh-pq"));
418    let legacy_singleton = ed25519.len() == 1 && ed25519[0].0.ends_with("#key-1");
419
420    ed25519
421        .into_iter()
422        .map(|(id, ed25519)| {
423            let pq_id = format!("{id}-pq");
424            let explicit = ml_dsa_65.remove(&pq_id);
425            // Rolling-upgrade bridge for the previously published singleton
426            // `#key-1` + `#mesh-pq` document. It is deliberately restricted to
427            // that exact one-Ed25519 legacy shape so an unrelated PQ method can
428            // never be attached in a multi-candidate document.
429            let legacy = legacy_singleton
430                .then_some(legacy_pq_id.as_ref())
431                .flatten()
432                .and_then(|legacy_id| ml_dsa_65.remove(legacy_id));
433            IdentityKeyCandidate {
434                id,
435                ed25519,
436                ml_dsa_65: explicit.or(legacy),
437            }
438        })
439        .collect()
440}
441
442fn verification_method_is_live(vm: &Value, now: i64) -> bool {
443    let not_before = match vm.get("nbf") {
444        None => true,
445        Some(value) => value.as_i64().is_some_and(|nbf| now >= nbf),
446    };
447    let not_expired = match vm.get("exp") {
448        None => true,
449        Some(value) => value.as_i64().is_some_and(|exp| now < exp),
450    };
451    not_before && not_expired
452}
453
454impl<P: DidDocumentProvider> IdentityResolver for MethodDispatchResolver<P> {
455    fn resolve_identity_keys(&self, did: &Did) -> Result<IdentityKeys> {
456        if did.is_did_web() {
457            self.resolve_did_web(did)
458        } else if did.is_did_key() {
459            self.resolve_did_key(did)
460        } else if did.is_did_at9p() {
461            self.resolve_did_at9p(did)
462        } else {
463            // Unknown DID method — fail closed (never a default-Unverified Ok).
464            Err(anyhow!(
465                "unsupported DID method for {did}: no resolver arm — fail-closed"
466            ))
467        }
468    }
469}
470
471#[cfg(test)]
472#[allow(clippy::unwrap_used, clippy::expect_used)]
473mod tests {
474    use super::*;
475    use crate::auth::mac::Assurance;
476    use crate::crypto::pq::{ml_dsa_generate_keypair, ml_dsa_sk_to_vk_bytes, ml_dsa_vk_bytes};
477    use crate::did_key::{ed25519_to_did_key, MULTICODEC_ED25519_PUB, MULTICODEC_ML_DSA_65_PUB};
478    use ed25519_dalek::SigningKey;
479    use rand::rngs::OsRng;
480    use serde_json::json;
481
482    fn rand_ed25519() -> [u8; 32] {
483        SigningKey::generate(&mut OsRng).verifying_key().to_bytes()
484    }
485
486    fn encode_multikey(raw: &[u8], codec: [u8; 2]) -> String {
487        let mut payload = Vec::with_capacity(2 + raw.len());
488        payload.extend_from_slice(&codec);
489        payload.extend_from_slice(raw);
490        format!("z{}", bs58::encode(payload).into_string())
491    }
492
493    /// A DID document with an Ed25519 `#mesh` VM and, optionally, an ML-DSA-65
494    /// `#mesh-pq` VM.
495    fn did_doc(ed: &[u8; 32], ml_dsa_vk_bytes: Option<&[u8]>) -> Value {
496        did_doc_with_named_vms(&[("mesh", ed)], ml_dsa_vk_bytes.map(|pq| ("mesh-pq", pq)))
497    }
498
499    fn did_doc_with_named_vms(
500        ed25519: &[(&str, &[u8; 32])],
501        ml_dsa_65: Option<(&str, &[u8])>,
502    ) -> Value {
503        let mut vms = Vec::with_capacity(ed25519.len() + usize::from(ml_dsa_65.is_some()));
504        for (name, key) in ed25519 {
505            vms.push(json!({
506                "id": format!("{DID_WEB}#{name}"),
507                "type": "Multikey",
508                "controller": DID_WEB,
509                "publicKeyMultibase": encode_multikey(*key, MULTICODEC_ED25519_PUB),
510            }));
511        }
512        if let Some((name, key)) = ml_dsa_65 {
513            vms.push(json!({
514                "id": format!("{DID_WEB}#{name}"),
515                "type": "Multikey",
516                "controller": DID_WEB,
517                "publicKeyMultibase": encode_multikey(key, MULTICODEC_ML_DSA_65_PUB),
518            }));
519        }
520        json!({
521            "@context": ["https://www.w3.org/ns/did/v1"],
522            "id": DID_WEB,
523            "verificationMethod": vms,
524            "service": [],
525        })
526    }
527
528    fn did_doc_with_two_hybrid_pairs(
529        old_ed: &[u8; 32],
530        old_pq: &[u8],
531        new_ed: &[u8; 32],
532        new_pq: &[u8],
533    ) -> Value {
534        let vms = vec![
535            json!({
536                "id": "did:web:peer.example#mesh-old",
537                "type": "Multikey",
538                "controller": "did:web:peer.example",
539                "publicKeyMultibase": encode_multikey(old_ed, MULTICODEC_ED25519_PUB),
540            }),
541            json!({
542                "id": "did:web:peer.example#mesh-old-pq",
543                "type": "Multikey",
544                "controller": "did:web:peer.example",
545                "publicKeyMultibase": encode_multikey(old_pq, MULTICODEC_ML_DSA_65_PUB),
546            }),
547            json!({
548                "id": "did:web:peer.example#mesh-new",
549                "type": "Multikey",
550                "controller": "did:web:peer.example",
551                "publicKeyMultibase": encode_multikey(new_ed, MULTICODEC_ED25519_PUB),
552            }),
553            json!({
554                "id": "did:web:peer.example#mesh-new-pq",
555                    "type": "Multikey",
556                    "controller": "did:web:peer.example",
557                "publicKeyMultibase": encode_multikey(new_pq, MULTICODEC_ML_DSA_65_PUB),
558            }),
559        ];
560        json!({
561            "@context": ["https://www.w3.org/ns/did/v1"],
562            "id": "did:web:peer.example",
563            "verificationMethod": vms,
564            "service": [],
565        })
566    }
567
568    /// Fixture provider returning a fixed document.
569    struct FixtureDocs(Value);
570    impl DidDocumentProvider for FixtureDocs {
571        fn document(&self, _did: &str) -> Result<Value> {
572            Ok(self.0.clone())
573        }
574    }
575
576    #[derive(Clone)]
577    struct RotatingDocs(std::sync::Arc<parking_lot::Mutex<Value>>);
578    impl RotatingDocs {
579        fn new(document: Value) -> Self {
580            Self(std::sync::Arc::new(parking_lot::Mutex::new(document)))
581        }
582
583        fn publish(&self, document: Value) {
584            *self.0.lock() = document;
585        }
586    }
587    impl DidDocumentProvider for RotatingDocs {
588        fn document(&self, _did: &str) -> Result<Value> {
589            Ok(self.0.lock().clone())
590        }
591    }
592
593    /// Provider that always fails — exercises the fail-closed fetch path.
594    struct FailingDocs;
595    impl DidDocumentProvider for FailingDocs {
596        fn document(&self, did: &str) -> Result<Value> {
597            Err(anyhow!("simulated fetch failure for {did}"))
598        }
599    }
600
601    /// A provider that MUST NOT be called (did:key / did:at9p never fetch).
602    struct NeverDocs;
603    impl DidDocumentProvider for NeverDocs {
604        fn document(&self, did: &str) -> Result<Value> {
605            panic!("resolver must not fetch a document for {did}");
606        }
607    }
608
609    const DID_WEB: &str = "did:web:peer.example";
610
611    #[test]
612    fn did_web_ed25519_only_is_classical() {
613        let ed = rand_ed25519();
614        let resolver = MethodDispatchResolver::new(FixtureDocs(did_doc(&ed, None)));
615        let keys = resolver
616            .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
617            .expect("ed25519-only did:web resolves");
618        let candidate = keys
619            .candidate_for_ed25519(&ed)
620            .expect("published candidate");
621        assert_eq!(candidate.assurance(), Assurance::Classical);
622        assert!(candidate.ml_dsa_65.is_none());
623    }
624
625    #[test]
626    fn did_web_with_ml_dsa_is_pqhybrid() {
627        let ed = rand_ed25519();
628        let (_sk, vk) = ml_dsa_generate_keypair();
629        let pq_bytes = ml_dsa_vk_bytes(&vk);
630        let resolver = MethodDispatchResolver::new(FixtureDocs(did_doc(&ed, Some(&pq_bytes))));
631        let keys = resolver
632            .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
633            .expect("hybrid did:web resolves");
634        let candidate = keys
635            .candidate_for_ed25519(&ed)
636            .expect("published candidate");
637        assert_eq!(candidate.assurance(), Assurance::PqHybrid);
638        // The resolved PQ key is exactly the published one.
639        let resolved = candidate.ml_dsa_65.as_ref().expect("PQ anchor present");
640        assert_eq!(ml_dsa_vk_bytes(resolved), pq_bytes);
641    }
642
643    #[test]
644    fn legacy_key_1_mesh_pq_document_remains_hybrid_during_upgrade() {
645        let ed = rand_ed25519();
646        let (_, pq) = ml_dsa_generate_keypair();
647        let pq = ml_dsa_vk_bytes(&pq);
648        let doc = did_doc_with_named_vms(&[("key-1", &ed)], Some(("mesh-pq", &pq)));
649        let keys = MethodDispatchResolver::new(FixtureDocs(doc))
650            .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
651            .expect("legacy singleton resolves");
652        let candidate = keys
653            .candidate_for_ed25519(&ed)
654            .expect("legacy signer candidate");
655        assert_eq!(candidate.assurance(), Assurance::PqHybrid);
656        assert_eq!(ml_dsa_vk_bytes(candidate.ml_dsa_65.as_ref().unwrap()), pq);
657    }
658
659    #[test]
660    fn authentication_relationship_is_not_a_second_inconsistent_authority_parser() {
661        let ed = rand_ed25519();
662        let mut doc = did_doc(&ed, None);
663        // Admission and identity resolution both consume verificationMethod.
664        // A malformed, relative, or embedded relationship cannot disable or
665        // tighten a separate enrollment-only filter because no such filter is
666        // applied here.
667        for authentication in [
668            json!("bad"),
669            json!({}),
670            json!(["#mesh"]),
671            json!([{
672                "id": format!("{DID_WEB}#mesh"),
673                "type": "Multikey",
674                "controller": DID_WEB,
675                "publicKeyMultibase": encode_multikey(&ed, MULTICODEC_ED25519_PUB),
676            }]),
677        ] {
678            doc["authentication"] = authentication;
679            let keys = MethodDispatchResolver::new(FixtureDocs(doc.clone()))
680                .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
681                .expect("verificationMethod remains authoritative");
682            assert!(keys.candidate_for_ed25519(&ed).is_some());
683        }
684    }
685
686    #[test]
687    fn bounded_verification_methods_follow_the_injected_clock() {
688        let old = rand_ed25519();
689        let new = rand_ed25519();
690        let mut doc = did_doc_with_named_vms(&[("mesh-old", &old), ("mesh-new", &new)], None);
691        let vms = doc["verificationMethod"].as_array_mut().unwrap();
692        vms[0]["nbf"] = json!(100);
693        vms[0]["exp"] = json!(200);
694        vms[1]["nbf"] = json!(150);
695        vms[1]["exp"] = json!(300);
696
697        let now = Arc::new(std::sync::atomic::AtomicI64::new(175));
698        let clock = Arc::clone(&now);
699        let resolver = MethodDispatchResolver::new(FixtureDocs(doc))
700            .with_clock(move || clock.load(std::sync::atomic::Ordering::SeqCst));
701        let did = Did::new(DID_WEB.to_owned());
702        let overlap = resolver.resolve_identity_keys(&did).unwrap();
703        assert!(overlap.candidate_for_ed25519(&old).is_some());
704        assert!(overlap.candidate_for_ed25519(&new).is_some());
705
706        now.store(200, std::sync::atomic::Ordering::SeqCst);
707        let retired = resolver.resolve_identity_keys(&did).unwrap();
708        assert!(retired.candidate_for_ed25519(&old).is_none());
709        assert!(retired.candidate_for_ed25519(&new).is_some());
710    }
711
712    #[test]
713    fn did_web_derives_pq_key_from_signing_key_roundtrip() {
714        // A mesh-derived ML-DSA key (as node_identity produces) round-trips
715        // through the VM extractor into a usable verifying key.
716        let ed = rand_ed25519();
717        let peer_ed = SigningKey::generate(&mut OsRng);
718        let peer_pq_sk = crate::node_identity::derive_mesh_mldsa_key(&peer_ed);
719        let pq_bytes = ml_dsa_sk_to_vk_bytes(&peer_pq_sk);
720        let resolver = MethodDispatchResolver::new(FixtureDocs(did_doc(&ed, Some(&pq_bytes))));
721        let keys = resolver
722            .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
723            .expect("hybrid did:web resolves");
724        let candidate = keys
725            .candidate_for_ed25519(&ed)
726            .expect("published candidate");
727        assert_eq!(candidate.assurance(), Assurance::PqHybrid);
728        assert_eq!(
729            ml_dsa_vk_bytes(candidate.ml_dsa_65.as_ref().unwrap()),
730            pq_bytes
731        );
732    }
733
734    #[test]
735    fn did_web_classical_overlap_accepts_both_then_rejects_retired_key_after_drain_window() {
736        let old = rand_ed25519();
737        let new = rand_ed25519();
738        let docs = RotatingDocs::new(did_doc_with_named_vms(
739            &[("mesh-old", &old), ("mesh-new", &new)],
740            None,
741        ));
742        let resolver = MethodDispatchResolver::new(docs.clone());
743
744        let overlap = resolver
745            .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
746            .expect("overlap document resolves");
747        assert_eq!(overlap.len(), 2);
748        assert_eq!(
749            overlap.candidate_for_ed25519(&old).unwrap().id,
750            format!("{DID_WEB}#mesh-old")
751        );
752        assert_eq!(
753            overlap.candidate_for_ed25519(&new).unwrap().id,
754            format!("{DID_WEB}#mesh-new")
755        );
756
757        // The old VM remains usable for the bounded drain window, then the
758        // publisher removes it. A fresh resolution must no longer accept it.
759        docs.publish(did_doc_with_named_vms(&[("mesh-new", &new)], None));
760        let after_drain = resolver
761            .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
762            .expect("post-drain document resolves");
763        assert!(after_drain.candidate_for_ed25519(&old).is_none());
764        assert!(after_drain.candidate_for_ed25519(&new).is_some());
765    }
766
767    #[test]
768    fn did_web_two_hybrid_pairs_remain_independent_overlap_candidates() {
769        let old_ed = rand_ed25519();
770        let new_ed = rand_ed25519();
771        let (_, old_pq) = ml_dsa_generate_keypair();
772        let (_, new_pq) = ml_dsa_generate_keypair();
773        let old_pq = ml_dsa_vk_bytes(&old_pq);
774        let new_pq = ml_dsa_vk_bytes(&new_pq);
775        let resolver = MethodDispatchResolver::new(FixtureDocs(did_doc_with_two_hybrid_pairs(
776            &old_ed, &old_pq, &new_ed, &new_pq,
777        )));
778
779        let keys = resolver
780            .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
781            .expect("hybrid overlap document resolves");
782        let old = keys
783            .candidate_for_ed25519(&old_ed)
784            .expect("old hybrid candidate");
785        let new = keys
786            .candidate_for_ed25519(&new_ed)
787            .expect("new hybrid candidate");
788        assert_eq!(old.assurance(), Assurance::PqHybrid);
789        assert_eq!(new.assurance(), Assurance::PqHybrid);
790        assert_eq!(ml_dsa_vk_bytes(old.ml_dsa_65.as_ref().unwrap()), old_pq);
791        assert_eq!(ml_dsa_vk_bytes(new.ml_dsa_65.as_ref().unwrap()), new_pq);
792    }
793
794    #[test]
795    fn did_web_no_ed25519_vm_fails_closed() {
796        // A doc with only an ML-DSA VM (no Ed25519 anchor) cannot be bound.
797        let (_sk, vk) = ml_dsa_generate_keypair();
798        let doc = json!({
799            "id": DID_WEB,
800            "verificationMethod": [{
801                "id": "did:web:peer.example#mesh-pq",
802                "publicKeyMultibase": encode_multikey(&ml_dsa_vk_bytes(&vk), MULTICODEC_ML_DSA_65_PUB),
803            }],
804        });
805        let resolver = MethodDispatchResolver::new(FixtureDocs(doc));
806        assert!(resolver
807            .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
808            .is_err());
809    }
810
811    #[test]
812    fn did_web_empty_doc_fails_closed() {
813        let doc = json!({ "id": DID_WEB, "verificationMethod": [] });
814        let resolver = MethodDispatchResolver::new(FixtureDocs(doc));
815        assert!(resolver
816            .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
817            .is_err());
818    }
819
820    #[test]
821    fn did_web_fetch_failure_fails_closed() {
822        let resolver = MethodDispatchResolver::new(FailingDocs);
823        assert!(resolver
824            .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
825            .is_err());
826    }
827
828    #[test]
829    fn did_key_is_classical_without_fetch() {
830        let ed = rand_ed25519();
831        let did = ed25519_to_did_key(&ed);
832        let resolver = MethodDispatchResolver::new(NeverDocs);
833        let keys = resolver
834            .resolve_identity_keys(&Did::new(did))
835            .expect("did:key resolves without fetch");
836        let candidate = keys.candidate_for_ed25519(&ed).expect("did:key candidate");
837        assert_eq!(candidate.assurance(), Assurance::Classical);
838        assert!(candidate.ml_dsa_65.is_none());
839    }
840
841    #[test]
842    fn did_key_malformed_fails_closed() {
843        let resolver = MethodDispatchResolver::new(NeverDocs);
844        let did = Did::new("did:key:zNotAValidEd25519Multikey".to_owned());
845        assert!(resolver.resolve_identity_keys(&did).is_err());
846    }
847
848    #[test]
849    fn did_at9p_arm_fails_closed_without_a_capsule_resolver() {
850        // No At9pCapsuleResolver configured ⇒ did:at9p fails closed (the arm
851        // exists but has nothing to verify against).
852        let resolver = MethodDispatchResolver::new(NeverDocs);
853        let did = Did::new("did:at9p:cid512abcdef".to_owned());
854        // `IdentityKeys` is not `Debug` (the ML-DSA key type isn't), so match on
855        // the result rather than `unwrap_err`.
856        match resolver.resolve_identity_keys(&did) {
857            Ok(_) => panic!("did:at9p must fail closed without a capsule resolver"),
858            Err(err) => {
859                assert!(
860                    err.to_string().contains("fail-closed"),
861                    "missing-resolver arm should fail closed: {err}"
862                );
863            }
864        }
865    }
866
867    // ── did:at9p arm (D2/#894) ───────────────────────────────────────────────
868
869    use super::{At9pCapsuleResolver, VerifiedAt9pKeys};
870    use parking_lot::Mutex;
871    use std::sync::Arc;
872
873    /// A capsule resolver that returns a fixed [`VerifiedAt9pKeys`] (the GATE is
874    /// abstracted in rpc; pds owns the real implementation). Records the calls it
875    /// received so tests can assert the arm routed through it.
876    struct FixtureCapsule {
877        keys: VerifiedAt9pKeys,
878        calls: Mutex<Vec<String>>,
879        fail: bool,
880    }
881
882    impl At9pCapsuleResolver for FixtureCapsule {
883        fn resolve(&self, did: &str) -> Result<VerifiedAt9pKeys> {
884            self.calls.lock().push(did.to_owned());
885            if self.fail {
886                Err(anyhow!("simulated GATE failure"))
887            } else {
888                Ok(self.keys.clone())
889            }
890        }
891    }
892
893    fn verified_keys() -> VerifiedAt9pKeys {
894        let (_sk, vk) = ml_dsa_generate_keypair();
895        VerifiedAt9pKeys::new_gate_verified([9u8; 32], vk)
896    }
897
898    #[test]
899    fn did_at9p_with_verified_capsule_is_pqhybrid() {
900        // A GATE-verified capsule yields PqHybrid assurance, carrying the
901        // capsule's own Ed25519 + ML-DSA-65 keys (crypto-derived, not asserted).
902        let keys = verified_keys();
903        let fixture = Arc::new(FixtureCapsule {
904            keys: keys.clone(),
905            calls: Mutex::new(vec![]),
906            fail: false,
907        });
908        let resolver = MethodDispatchResolver::new(NeverDocs).with_at9p(fixture.clone());
909        let did = Did::new("did:at9p:cid512abcdef".to_owned());
910        let resolved = resolver
911            .resolve_identity_keys(&did)
912            .expect("verified capsule resolves at PqHybrid");
913        let only = &keys.keys()[0];
914        let candidate = resolved
915            .candidate_for_ed25519(only.ed25519())
916            .expect("capsule candidate");
917        assert_eq!(candidate.assurance(), Assurance::PqHybrid);
918        assert_eq!(
919            ml_dsa_vk_bytes(candidate.ml_dsa_65.as_ref().unwrap()),
920            ml_dsa_vk_bytes(only.ml_dsa_65())
921        );
922        // The arm routed through the capsule resolver exactly once.
923        assert_eq!(fixture.calls.lock().as_slice(), &["did:at9p:cid512abcdef"]);
924    }
925
926    #[test]
927    fn did_at9p_multi_key_capsule_preserves_the_full_candidate_set() {
928        let (_, old_pq) = ml_dsa_generate_keypair();
929        let (_, new_pq) = ml_dsa_generate_keypair();
930        let old = [10u8; 32];
931        let new = [11u8; 32];
932        let verified = VerifiedAt9pKeys::new_gate_verified_set(vec![
933            VerifiedAt9pKeys::key(old, old_pq),
934            VerifiedAt9pKeys::key(new, new_pq),
935        ])
936        .unwrap();
937        let fixture = Arc::new(FixtureCapsule {
938            keys: verified,
939            calls: Mutex::new(vec![]),
940            fail: false,
941        });
942        let resolved = MethodDispatchResolver::new(NeverDocs)
943            .with_at9p(fixture)
944            .resolve_identity_keys(&Did::new("did:at9p:cid512overlap".to_owned()))
945            .expect("verified overlap set resolves");
946        assert_eq!(resolved.len(), 2);
947        assert_eq!(
948            resolved.candidate_for_ed25519(&old).unwrap().assurance(),
949            Assurance::PqHybrid
950        );
951        assert_eq!(
952            resolved.candidate_for_ed25519(&new).unwrap().assurance(),
953            Assurance::PqHybrid
954        );
955    }
956
957    #[test]
958    fn did_at9p_gate_failure_fails_closed() {
959        // A capsule that fails the GATE (bad sig / wrong cid) is rejected — no
960        // default assurance, no Ok.
961        let fixture = Arc::new(FixtureCapsule {
962            keys: verified_keys(),
963            calls: Mutex::new(vec![]),
964            fail: true,
965        });
966        let resolver = MethodDispatchResolver::new(NeverDocs).with_at9p(fixture);
967        let did = Did::new("did:at9p:cid512abcdef".to_owned());
968        assert!(resolver.resolve_identity_keys(&did).is_err());
969    }
970
971    #[test]
972    fn did_at9p_assurance_is_not_asserted_by_other_arms() {
973        // The did:web and did:key arms must never produce PqHybrid from a path
974        // text or hint — only the verified-capsule arm does. (Provenance: a
975        // did:web with no PQ VM is Classical, regardless of any at9p resolver.)
976        let fixture = Arc::new(FixtureCapsule {
977            keys: verified_keys(),
978            calls: Mutex::new(vec![]),
979            fail: false,
980        });
981        let ed = rand_ed25519();
982        let resolver =
983            MethodDispatchResolver::new(FixtureDocs(did_doc(&ed, None))).with_at9p(fixture);
984        let keys = resolver
985            .resolve_identity_keys(&Did::new(DID_WEB.to_owned()))
986            .expect("did:web resolves");
987        assert_eq!(
988            keys.candidate_for_ed25519(&ed).unwrap().assurance(),
989            Assurance::Classical
990        );
991    }
992
993    #[test]
994    fn unknown_method_fails_closed() {
995        let resolver = MethodDispatchResolver::new(NeverDocs);
996        let did = Did::new("did:plc:unsupported".to_owned());
997        assert!(resolver.resolve_identity_keys(&did).is_err());
998    }
999}