Skip to main content

hyprstream_discovery/
did_anchored.rs

1//! DID-anchored deployment trust bootstrap (#1136).
2//!
3//! This module resolves two public operator pins into verification-only
4//! deployment material. Network responses are never authority by themselves:
5//! the fetched capsule must pass the canon -> hash -> signature GATE for the
6//! configured `did:at9p`, and the fetched `did:web` document must reciprocally
7//! name that exact identity before the pair is trusted. The deployment CA and
8//! Discovery reach come exclusively from the GATE-verified capsule; document
9//! keys and services remain advisory.
10
11use std::sync::Arc;
12use std::time::Duration;
13
14use anyhow::{bail, Context, Result};
15use async_trait::async_trait;
16use hyprstream_pds::at9p::{ServiceType, Transport as At9pTransport};
17use hyprstream_pds::at9p_alias::AuthoritativeIdentity;
18use hyprstream_pds::at9p_gate::VerifiedCapsule;
19use hyprstream_rpc::did_web::{did_web_to_url, DidWebResolver, HttpDidDocFetcher};
20use hyprstream_rpc::identity::Did;
21use hyprstream_rpc::transport::{EndpointType, TransportConfig};
22use serde_json::Value;
23
24use crate::at9p_alias::At9pAliasResolver;
25use crate::at9p_resolver::CapsuleSource;
26use crate::service::{DeploymentAuthorityLog, HybridDeploymentCa};
27
28const MAX_CAPSULE_BYTES: usize = 4 * 1024 * 1024;
29const DEPLOYMENT_REACH_SERVICE: &str = "#ns";
30
31/// The two public, non-secret anchors for DID-backed deployment trust.
32#[derive(Clone, Debug, Eq, PartialEq)]
33pub struct DidAnchors {
34    pub cluster_at9p_did: String,
35    pub cluster_did_web: String,
36    /// Optional extra TLS root (PEM) for private-PKI deployments whose
37    /// did:web host terminates with an internal CA. ADDITIVE — the public
38    /// WebPKI roots remain enabled; this never disables verification.
39    pub extra_root_cert_pem: Option<Vec<u8>>,
40}
41
42impl DidAnchors {
43    /// Attach an extra TLS root for private-PKI did:web termination.
44    pub fn with_root_cert_pem(mut self, pem: Vec<u8>) -> Self {
45        self.extra_root_cert_pem = Some(pem);
46        self
47    }
48}
49
50/// Explicit startup trust-source selection.
51///
52/// There is deliberately no fallback between variants: once `DidAnchored` is
53/// selected, any fetch, verification, or liveness failure is terminal.
54#[derive(Clone, Debug, Eq, PartialEq)]
55pub enum DeploymentTrustSource {
56    OsOwnedFiles,
57    DidAnchored(DidAnchors),
58}
59
60impl DeploymentTrustSource {
61    /// Select a trust source from the public anchor pair.
62    ///
63    /// Both unset preserves the historical OS-owned-file behavior exactly.
64    /// Supplying only one anchor is rejected rather than silently downgrading.
65    pub fn from_anchors(
66        cluster_at9p_did: Option<&str>,
67        cluster_did_web: Option<&str>,
68    ) -> Result<Self> {
69        match (cluster_at9p_did, cluster_did_web) {
70            (None, None) => Ok(Self::OsOwnedFiles),
71            (Some(at9p), Some(web)) => {
72                anyhow::ensure!(
73                    at9p.starts_with(hyprstream_pds::at9p_gate::DID_AT9P_PREFIX),
74                    "cluster_at9p_did must be a did:at9p identifier"
75                );
76                anyhow::ensure!(
77                    web.starts_with("did:web:"),
78                    "cluster_did_web must be a did:web identifier"
79                );
80                anyhow::ensure!(
81                    at9p.trim() == at9p && web.trim() == web,
82                    "DID deployment anchors must not contain surrounding whitespace"
83                );
84                // Validate the did:web method-specific identifier before any I/O.
85                did_web_to_url(web).context("cluster_did_web is malformed")?;
86                Ok(Self::DidAnchored(DidAnchors {
87                    cluster_at9p_did: at9p.to_owned(),
88                    cluster_did_web: web.to_owned(),
89                    extra_root_cert_pem: None,
90                }))
91            }
92            _ => bail!(
93                "cluster_at9p_did and cluster_did_web must be configured together; partial DID trust configuration is forbidden"
94            ),
95        }
96    }
97}
98
99/// Verified public material extracted from a mutually-attested identity pair.
100pub(crate) struct DidAnchoredTrust {
101    pub ca_verifying_key: HybridDeploymentCa,
102    pub discovery_transport: TransportConfig,
103    pub authoritative_identity: AuthoritativeIdentity,
104    /// The current CA-signed registry deployment credential, fetched from the
105    /// same well-known endpoint family as the capsule. Like the capsule, it
106    /// is integrity-protected by design (CA signature + one-hour freshness
107    /// profile, enforced by `validate_registry_deployment_credential_profile`),
108    /// so the byte channel needs no trust of its own.
109    pub registry_credential: String,
110    /// Current root-anchored authority log fetched beside the credential.
111    /// Its verified head must match the independently provisioned local
112    /// checkpoint before the credential is accepted.
113    pub authority_log: DeploymentAuthorityLog,
114    /// The document's `#mesh-kem` hybrid-KEM recipient public, when published.
115    /// Required by the REMOTE-node bootstrap arm (QUIC forbids cleartext
116    /// envelopes); the same-node arm never encrypts over the local fabric.
117    pub mesh_kem_recipient: Option<hyprstream_rpc::crypto::hybrid_kem::RecipientPublic>,
118    /// The document's ML-DSA-65 verification methods (`#mesh-pq`). The
119    /// remote-node arm requires exactly one — the discovery service's mesh
120    /// PQ verifying key — to anchor response authentication.
121    pub ml_dsa_65_keys: Vec<hyprstream_rpc::crypto::pq::MlDsaVerifyingKey>,
122}
123
124/// Fetch capsules from the deployment's static well-known content endpoint.
125///
126/// A root `did:web:host` document at `/.well-known/did.json` maps capsule CIDs
127/// to `/.well-known/at9p/<cid>.cbor`; a path-form DID maps them beside its
128/// `did.json`. This endpoint is an untrusted byte transport only: the configured
129/// CID and GATE pipeline decide whether the bytes are accepted.
130struct HttpWellKnownCapsuleSource {
131    http: reqwest::Client,
132    document_url: String,
133}
134
135/// Maximum accepted size of the registry deployment credential response.
136/// A compact EdDSA JWT is well under 4 KiB; 64 KiB is generous headroom.
137const MAX_CREDENTIAL_BYTES: usize = 64 * 1024;
138
139impl HttpWellKnownCapsuleSource {
140    fn new(did_web: &str, extra_root_pem: Option<&[u8]>) -> Result<Self> {
141        let document_url = did_web_to_url(did_web)?;
142        let mut builder = reqwest::Client::builder()
143            .redirect(reqwest::redirect::Policy::none())
144            .connect_timeout(Duration::from_secs(10))
145            .timeout(Duration::from_secs(10));
146        if let Some(pem) = extra_root_pem {
147            let cert = reqwest::Certificate::from_pem(pem)
148                .context("extra well-known TLS root is not a valid PEM certificate")?;
149            builder = builder.add_root_certificate(cert);
150        }
151        let http = builder
152            .build()
153            .context("failed to build at9p capsule HTTPS client")?;
154        Ok(Self { http, document_url })
155    }
156
157    /// Fetch the current registry deployment credential from beside the
158    /// capsule (`{prefix}deployment/registry-service.jwt`). The bytes are an
159    /// untrusted transport only: `validate_registry_deployment_credential_profile`
160    /// decides whether they are accepted (CA signature + freshness window).
161    async fn fetch_registry_credential(&self) -> Result<String> {
162        let prefix = self
163            .document_url
164            .strip_suffix("did.json")
165            .ok_or_else(|| anyhow::anyhow!("derived did:web URL does not end in did.json"))?;
166        let url = format!("{prefix}deployment/registry-service.jwt");
167        let mut response = self
168            .http
169            .get(&url)
170            .send()
171            .await
172            .with_context(|| format!("failed to fetch registry deployment credential from {url}"))?
173            .error_for_status()
174            .with_context(|| format!("registry deployment credential endpoint rejected {url}"))?;
175        if let Some(length) = response.content_length() {
176            anyhow::ensure!(
177                length <= MAX_CREDENTIAL_BYTES as u64,
178                "registry deployment credential exceeds {MAX_CREDENTIAL_BYTES}-byte limit"
179            );
180        }
181        let mut bytes = Vec::new();
182        while let Some(chunk) = response
183            .chunk()
184            .await
185            .context("failed to read registry deployment credential body")?
186        {
187            anyhow::ensure!(
188                bytes.len().saturating_add(chunk.len()) <= MAX_CREDENTIAL_BYTES,
189                "registry deployment credential exceeds {MAX_CREDENTIAL_BYTES}-byte limit"
190            );
191            bytes.extend_from_slice(&chunk);
192        }
193        String::from_utf8(bytes).context("registry deployment credential is not UTF-8")
194    }
195
196    /// Fetch the current root-anchored authority log from beside the registry
197    /// credential. HTTPS transports untrusted bytes; the capsule-derived root
198    /// and independent local head checkpoint authenticate them later.
199    async fn fetch_authority_log(&self) -> Result<DeploymentAuthorityLog> {
200        let prefix = self
201            .document_url
202            .strip_suffix("did.json")
203            .ok_or_else(|| anyhow::anyhow!("derived did:web URL does not end in did.json"))?;
204        let url = format!("{prefix}deployment/deployment-authority.log.json");
205        let mut response = self
206            .http
207            .get(&url)
208            .send()
209            .await
210            .with_context(|| format!("failed to fetch deployment authority log from {url}"))?
211            .error_for_status()
212            .with_context(|| format!("deployment authority-log endpoint rejected {url}"))?;
213        if let Some(length) = response.content_length() {
214            anyhow::ensure!(
215                length <= MAX_CREDENTIAL_BYTES as u64,
216                "deployment authority log exceeds {MAX_CREDENTIAL_BYTES}-byte limit"
217            );
218        }
219        let mut bytes = Vec::new();
220        while let Some(chunk) = response
221            .chunk()
222            .await
223            .context("failed to read deployment authority-log body")?
224        {
225            anyhow::ensure!(
226                bytes.len().saturating_add(chunk.len()) <= MAX_CREDENTIAL_BYTES,
227                "deployment authority log exceeds {MAX_CREDENTIAL_BYTES}-byte limit"
228            );
229            bytes.extend_from_slice(&chunk);
230        }
231        serde_json::from_slice(&bytes).context("deployment authority log is malformed")
232    }
233
234    fn capsule_url(&self, did: &str) -> Result<String> {
235        let cid = did
236            .strip_prefix(hyprstream_pds::at9p_gate::DID_AT9P_PREFIX)
237            .ok_or_else(|| anyhow::anyhow!("capsule fetch requested for a non-at9p DID"))?;
238        // The full CID parser runs in GATE after fetch. Constrain the URL path
239        // before I/O so a malformed configured identifier cannot inject path,
240        // query, or authority syntax.
241        anyhow::ensure!(
242            !cid.is_empty()
243                && cid
244                    .bytes()
245                    .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit()),
246            "did:at9p CID contains URL-unsafe characters"
247        );
248        let prefix = self
249            .document_url
250            .strip_suffix("did.json")
251            .ok_or_else(|| anyhow::anyhow!("derived did:web URL does not end in did.json"))?;
252        Ok(format!("{prefix}at9p/{cid}.cbor"))
253    }
254}
255
256#[async_trait]
257impl CapsuleSource for HttpWellKnownCapsuleSource {
258    async fn fetch_capsule(&self, did: &str) -> Result<Vec<u8>> {
259        let url = self.capsule_url(did)?;
260        let mut response = self
261            .http
262            .get(&url)
263            .send()
264            .await
265            .with_context(|| format!("failed to fetch at9p capsule from {url}"))?
266            .error_for_status()
267            .with_context(|| format!("at9p capsule endpoint rejected {url}"))?;
268        if let Some(length) = response.content_length() {
269            anyhow::ensure!(
270                length <= MAX_CAPSULE_BYTES as u64,
271                "at9p capsule exceeds {MAX_CAPSULE_BYTES}-byte limit"
272            );
273        }
274        let mut bytes = Vec::new();
275        while let Some(chunk) = response.chunk().await? {
276            anyhow::ensure!(
277                bytes.len().saturating_add(chunk.len()) <= MAX_CAPSULE_BYTES,
278                "at9p capsule exceeds {MAX_CAPSULE_BYTES}-byte limit"
279            );
280            bytes.extend_from_slice(&chunk);
281        }
282        Ok(bytes)
283    }
284}
285
286fn document_names_at9p(document: &Value, at9p_did: &str) -> bool {
287    document
288        .get("alsoKnownAs")
289        .and_then(Value::as_array)
290        .is_some_and(|aliases| aliases.iter().any(|alias| alias.as_str() == Some(at9p_did)))
291}
292
293fn missing_deployment_reach_error() -> anyhow::Error {
294    anyhow::anyhow!(
295        "capsule has no NinePExport service entry {DEPLOYMENT_REACH_SERVICE:?} for deployment reach; \
296         the pinned did:at9p must be an ANCHOR capsule signed by the deployment CA, not a node's \
297         own identity capsule (e.g. the `#pds` capsule a node's OAuth service renders for \
298         itself) — mint one with `hyprstream trust mint-anchor-capsule` and publish it \
299         (with its did.json) under the deployment well-known directory"
300    )
301}
302
303/// Enforce the deployment-specific, closed anchor-capsule profile.
304///
305/// Generic at9p capsules intentionally have set semantics and may carry
306/// rotation or delegation material. A deployment anchor is narrower: every
307/// signed claim must be one the anchor minter and this resolver consume.
308fn validate_deployment_anchor_profile(
309    verified: &VerifiedCapsule,
310    configured_did_web: &str,
311) -> Result<()> {
312    let body = &verified.capsule().body;
313    anyhow::ensure!(
314        body.subject_keys.len() == 1,
315        "closed deployment-anchor profile violation: subjectKeys must contain exactly one pinned-Hybrid signer (got {})",
316        body.subject_keys.len()
317    );
318    // A node's ordinary `#pds` capsule is the most likely wrong input here.
319    // Keep the closed-profile violation as the primary rejection while retaining
320    // the dedicated operator guidance that explains how to mint the missing
321    // deployment anchor. When a valid #ns entry exists alongside extras, the
322    // cardinality check below still rejects it as an over-broad profile.
323    let service = body
324        .services
325        .iter()
326        .find(|service| {
327            service.id == DEPLOYMENT_REACH_SERVICE
328                && service.service_type == ServiceType::NinePExport
329        })
330        .ok_or_else(missing_deployment_reach_error)
331        .context(
332            "closed deployment-anchor profile violation: capsule must contain a #ns NinePExport deployment-reach service",
333        )?;
334    anyhow::ensure!(
335        body.services.len() == 1,
336        "closed deployment-anchor profile violation: services must contain exactly one #ns NinePExport entry (got {})",
337        body.services.len()
338    );
339    let aliases = body.also_known_as.as_deref().unwrap_or_default();
340    anyhow::ensure!(
341        aliases.len() == 1 && aliases[0] == configured_did_web,
342        "closed deployment-anchor profile violation: alsoKnownAs must contain exactly the configured did:web {configured_did_web:?}"
343    );
344    anyhow::ensure!(
345        body.next_key_commitments.is_empty(),
346        "closed deployment-anchor profile violation: nextKeyCommitments are forbidden"
347    );
348    anyhow::ensure!(
349        body.label_hints.is_none(),
350        "closed deployment-anchor profile violation: labelHints are forbidden"
351    );
352    anyhow::ensure!(
353        body.delegations.is_none(),
354        "closed deployment-anchor profile violation: delegations are forbidden"
355    );
356    anyhow::ensure!(
357        body.witnesses.is_none(),
358        "closed deployment-anchor profile violation: witnesses are forbidden"
359    );
360    anyhow::ensure!(
361        service.endpoint.export.is_none(),
362        "closed deployment-anchor profile violation: the #ns endpoint export field is forbidden"
363    );
364    match service.endpoint.transport {
365        At9pTransport::Iroh => {}
366        At9pTransport::Quic => anyhow::ensure!(
367            service.endpoint.node_id.is_none() && service.endpoint.relay.is_none(),
368            "closed deployment-anchor profile violation: QUIC #ns endpoints must not carry iroh nodeId or relay fields"
369        ),
370        ref other => bail!(
371            "closed deployment-anchor profile violation: #ns transport must be iroh or quic (got {other:?})"
372        ),
373    }
374    Ok(())
375}
376
377/// Extract the deployment CA from the sole hybrid subject key that signed the
378/// GATE-verified, closed-profile capsule.
379fn ca_key_from_capsule(verified: &VerifiedCapsule) -> Result<HybridDeploymentCa> {
380    let [subject] = verified.capsule().body.subject_keys.as_slice() else {
381        bail!("closed deployment-anchor profile violation: subjectKeys must contain exactly one pinned-Hybrid signer");
382    };
383    HybridDeploymentCa::from_public_key_bytes(&subject.ed25519_pub, &subject.mldsa65_pub)
384        .context("capsule sole subject key is not a valid hybrid deployment CA")
385}
386
387/// Extract Discovery reach from the capsule's typed `#ns` service. The
388/// independent nodeId is transport reach only; the signed ping remains pinned
389/// to the separately authenticated Discovery application key.
390fn reach_from_capsule(verified: &VerifiedCapsule, document: &Value) -> Result<TransportConfig> {
391    let entry = verified
392        .capsule()
393        .body
394        .services
395        .iter()
396        .find(|service| {
397            service.id == DEPLOYMENT_REACH_SERVICE
398                && service.service_type == ServiceType::NinePExport
399        })
400        .ok_or_else(missing_deployment_reach_error)?;
401    match entry.endpoint.transport {
402        At9pTransport::Iroh => {
403            let node_id_multibase = entry.endpoint.node_id.as_deref().ok_or_else(|| {
404                anyhow::anyhow!(
405                    "capsule deployment reach {DEPLOYMENT_REACH_SERVICE:?} carries no independent iroh nodeId"
406                )
407            })?;
408            let node_id = hyprstream_rpc::did_key::decode_ed25519_multikey(node_id_multibase)
409                .context("capsule deployment reach nodeId is not a valid Ed25519 Multikey")?;
410            Ok(TransportConfig::iroh(
411                node_id,
412                Vec::new(),
413                entry.endpoint.relay.clone(),
414            ))
415        }
416        At9pTransport::Quic => {
417            let carrier = entry
418                .endpoint
419                .address
420                .strip_prefix("quic://")
421                .ok_or_else(|| {
422                    anyhow::anyhow!("capsule QUIC reach must use a quic:// socket carrier")
423                })?;
424            let address = carrier
425                .parse()
426                .context("capsule QUIC reach is not an IP socket address")?;
427            // The capsule remains authoritative for WHERE to dial. The
428            // did:web service may only contribute channel mechanics (SNI,
429            // WebPKI policy, and certificate hashes) for that exact
430            // capsule-bound socket. Those mechanics cannot select application
431            // identity: the signed ping is still pinned independently.
432            //
433            // A hostname-based document URI (`https://host:port`) decodes to
434            // an unspecified address with only the port populated, so the match
435            // accepts either an exact address equality or a port-only match
436            // when the document entry carries an unspecified IP.
437            let document_transport = hyprstream_rpc::did_web::transport_entries(document)
438                .into_iter()
439                .map(|decoded| decoded.config)
440                .find(|config| {
441                    matches!(
442                        &config.endpoint,
443                        EndpointType::Quic { addr, .. }
444                            if *addr == address
445                                || (addr.ip().is_unspecified() && addr.port() == address.port())
446                    )
447                })
448                .map(|mut config| {
449                    // A hostname-based document URI decodes to an unspecified
450                    // IP with only the port populated. The capsule carries the
451                    // real dial address, so substitute it: without this rewrite
452                    // the config would dial 0.0.0.0:port and never connect,
453                    // turning a verified capsule into an unusable one.
454                    if let EndpointType::Quic { addr, .. } = &mut config.endpoint {
455                        if addr.ip().is_unspecified() {
456                            *addr = address;
457                        }
458                    }
459                    config
460                });
461            Ok(document_transport.unwrap_or_else(|| {
462                tracing::warn!(
463                    "capsule QUIC reach {} has no matching QuicTransport entry in the did:web \
464                     document; falling back to bare-IP dial without SNI or certificate pins — \
465                     the deployment will not be reachable via hostname or WebPKI-validated TLS",
466                    address
467                );
468                TransportConfig::quic(address, address.ip().to_string()).with_connect_mode()
469            }))
470        }
471        ref other => bail!(
472            "capsule deployment reach {DEPLOYMENT_REACH_SERVICE:?} is not an iroh or QUIC endpoint (got {other:?})"
473        ),
474    }
475}
476
477/// Deployment material an anchor capsule contributes, once the capsule and the
478/// `did:web` document have mutually attested to each other.
479///
480/// This is the verification-only half of the DID-anchored bootstrap — the part
481/// a minting ceremony can self-check offline, before publication and before any
482/// registry credential or authority log exists.
483#[derive(Clone, Debug)]
484pub struct VerifiedAnchorMaterial {
485    /// The GATE-verified `did:at9p` the document reciprocally names.
486    pub at9p_did: String,
487    /// Raw hybrid deployment root taken from the capsule's primary subject
488    /// key: the 32-byte Ed25519 key followed by the 1952-byte ML-DSA-65 key,
489    /// the same layout the OS-owned `deployment-ca.hybrid` pin uses.
490    pub deployment_ca_public: Vec<u8>,
491    /// Deployment reach decoded from the capsule's `#ns` NinePExport entry.
492    pub discovery_transport: TransportConfig,
493}
494
495/// Verify an anchor capsule against its `did:web` document through the
496/// production resolution path, without needing the registry credential or
497/// authority log the live bootstrap also fetches.
498///
499/// Minting ceremonies call this on their own output: material this rejects is
500/// material a node would refuse at boot.
501pub async fn verify_anchor_material(
502    anchors: &DidAnchors,
503    document: &Value,
504    capsule_source: Arc<dyn CapsuleSource>,
505) -> Result<VerifiedAnchorMaterial> {
506    let (identity, ca, discovery_transport) =
507        resolve_anchor_pair(anchors, document, capsule_source).await?;
508    let mut deployment_ca_public = ca.ed25519_bytes().to_vec();
509    deployment_ca_public.extend_from_slice(&ca.ml_dsa_65_bytes());
510    Ok(VerifiedAnchorMaterial {
511        at9p_did: identity.at9p_did.as_str().to_owned(),
512        deployment_ca_public,
513        discovery_transport,
514    })
515}
516
517/// Shared core of the DID-anchored trust decision: reciprocal naming, the
518/// capsule GATE, and the CA + reach the GATE-verified capsule carries.
519async fn resolve_anchor_pair(
520    anchors: &DidAnchors,
521    document: &Value,
522    capsule_source: Arc<dyn CapsuleSource>,
523) -> Result<(AuthoritativeIdentity, HybridDeploymentCa, TransportConfig)> {
524    anyhow::ensure!(
525        document.get("id").and_then(Value::as_str) == Some(anchors.cluster_did_web.as_str()),
526        "did:web document id does not match configured cluster_did_web"
527    );
528    anyhow::ensure!(
529        document_names_at9p(document, &anchors.cluster_at9p_did),
530        "did:web document does not name the configured did:at9p in alsoKnownAs"
531    );
532
533    let classical = Did::new(anchors.cluster_did_web.clone());
534    let at9p = Did::new(anchors.cluster_at9p_did.clone());
535    let (authoritative_identity, verified) = At9pAliasResolver::new(capsule_source)
536        .resolve_authoritative_with_capsule(&classical, &at9p)
537        .await
538        .context("DID deployment anchors failed mutual-alias verification")?;
539    anyhow::ensure!(
540        authoritative_identity.at9p_did == at9p,
541        "mutual-alias resolver did not preserve configured at9p authority"
542    );
543
544    validate_deployment_anchor_profile(&verified, &anchors.cluster_did_web)?;
545
546    // The document contributes only the reciprocal identifier vouch above.
547    // Everything installed is content-bound to the configured did:at9p pin.
548    let ca_verifying_key = ca_key_from_capsule(&verified)?;
549    let discovery_transport = reach_from_capsule(&verified, document)?;
550    anyhow::ensure!(
551        matches!(
552            discovery_transport.endpoint,
553            EndpointType::Iroh { .. } | EndpointType::Quic { .. }
554        ),
555        "capsule deployment reach is not a network transport"
556    );
557    Ok((
558        authoritative_identity,
559        ca_verifying_key,
560        discovery_transport,
561    ))
562}
563
564pub(crate) async fn verify_did_anchored_document(
565    anchors: &DidAnchors,
566    document: &Value,
567    capsule_source: Arc<dyn CapsuleSource>,
568    registry_credential: String,
569    authority_log: DeploymentAuthorityLog,
570) -> Result<DidAnchoredTrust> {
571    let (authoritative_identity, ca_verifying_key, discovery_transport) =
572        resolve_anchor_pair(anchors, document, capsule_source).await?;
573    Ok(DidAnchoredTrust {
574        ca_verifying_key,
575        discovery_transport,
576        authoritative_identity,
577        registry_credential,
578        authority_log,
579        mesh_kem_recipient: hyprstream_rpc::did_web::mesh_kem_recipient(document),
580        ml_dsa_65_keys: hyprstream_rpc::did_web::verification_method_ml_dsa_65_keys(document),
581    })
582}
583
584pub(crate) async fn resolve_did_anchored_trust(anchors: &DidAnchors) -> Result<DidAnchoredTrust> {
585    let extra_root = anchors.extra_root_cert_pem.as_deref();
586    let document = DidWebResolver::new(match extra_root {
587        Some(pem) => HttpDidDocFetcher::with_extra_root(Duration::from_secs(3600), pem)?,
588        None => HttpDidDocFetcher::new(Duration::from_secs(3600))?,
589    })
590    .resolve_document(&anchors.cluster_did_web)
591    .await
592    .context("failed to fetch configured cluster did:web document")?;
593    let capsule_source = Arc::new(HttpWellKnownCapsuleSource::new(
594        &anchors.cluster_did_web,
595        extra_root,
596    )?);
597    // Fetch the registry credential from the same well-known family BEFORE
598    // trusting anything: a missing/refusing endpoint must fail the bootstrap
599    // even when the document and capsule are otherwise valid.
600    let registry_credential = capsule_source
601        .fetch_registry_credential()
602        .await
603        .context("failed to fetch registry deployment credential")?;
604    let authority_log = capsule_source
605        .fetch_authority_log()
606        .await
607        .context("failed to fetch deployment authority log")?;
608    let trust = verify_did_anchored_document(
609        anchors,
610        &document,
611        capsule_source,
612        registry_credential,
613        authority_log,
614    )
615    .await?;
616    tracing::info!(
617        at9p = %trust.authoritative_identity.at9p_did,
618        did_web = %trust.authoritative_identity.classical_did,
619        "verified mutually-attested DID deployment trust anchors from GATE-verified capsule"
620    );
621    Ok(trust)
622}
623
624#[cfg(test)]
625#[allow(clippy::unwrap_used, clippy::expect_used)]
626mod tests {
627    use super::*;
628    use base64::{
629        engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
630        Engine as _,
631    };
632    use ed25519_dalek::{Signer as _, SigningKey};
633    use hyprstream_crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes, MlDsaSigningKey};
634    use hyprstream_pds::at9p::{
635        CapsuleBody, Delegation, HybridKeyPair, ServiceEndpoint, ServiceEntry, ServiceType,
636        Transport, ML_DSA65_PUBLIC_KEY_LEN,
637    };
638    use hyprstream_pds::at9p_gate::verify_did_at9p;
639    use hyprstream_pds::at9p_sign::sign_capsule;
640    use hyprstream_pds::dag_cbor::DagCbor;
641    use hyprstream_rpc::{
642        auth::ucan::{
643            Ability, Capability, CaveatValue, Caveats, Did as UcanDid, Resource, Ucan, UcanPayload,
644        },
645        crypto::{
646            cose_sign::{assemble_composite_nested, inner_tbs, outer_tbs, split_composite},
647            pq::{ml_dsa_sign, ml_dsa_sk_to_vk_bytes},
648        },
649    };
650    use serde_json::json;
651    use std::collections::BTreeMap;
652    use std::net::SocketAddr;
653
654    struct FixedCapsuleSource(Vec<u8>);
655
656    #[async_trait]
657    impl CapsuleSource for FixedCapsuleSource {
658        async fn fetch_capsule(&self, _did: &str) -> Result<Vec<u8>> {
659            Ok(self.0.clone())
660        }
661    }
662
663    struct CapsuleSigner {
664        ed: SigningKey,
665        pq: MlDsaSigningKey,
666        pair: HybridKeyPair,
667    }
668
669    fn capsule_signer(tag: u8) -> CapsuleSigner {
670        let ed = SigningKey::from_bytes(&[tag; 32]);
671        let (pq, pq_vk) = ml_dsa_generate_keypair();
672        let pair = HybridKeyPair::new(
673            ed.verifying_key().to_bytes().to_vec(),
674            ml_dsa_vk_bytes(&pq_vk),
675        )
676        .unwrap();
677        CapsuleSigner { ed, pq, pair }
678    }
679
680    fn multikey(key: &[u8; 32]) -> String {
681        hyprstream_rpc::did_key::ed25519_to_did_key(key)
682            .strip_prefix("did:key:")
683            .unwrap()
684            .to_owned()
685    }
686
687    fn capsule_ca(tag: u8) -> [u8; 32] {
688        SigningKey::from_bytes(&[tag; 32])
689            .verifying_key()
690            .to_bytes()
691    }
692
693    fn unused_authority_log() -> DeploymentAuthorityLog {
694        DeploymentAuthorityLog {
695            schema: "unused-test-schema".to_owned(),
696            deployment_domain: "unused-test-domain".to_owned(),
697            did: "did:plc:unusedtestauthoritylog".to_owned(),
698            operations_b64: vec![],
699        }
700    }
701
702    fn sign_nested_for_test(
703        payload: &[u8],
704        aad: &[u8],
705        ed: &SigningKey,
706        pq: &MlDsaSigningKey,
707    ) -> Vec<u8> {
708        let ed_signature = ed.sign(&inner_tbs(
709            ed.verifying_key().to_bytes().to_vec(),
710            payload,
711            aad,
712            true,
713        ));
714        let pq_public =
715            hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(&ml_dsa_sk_to_vk_bytes(pq)).unwrap();
716        let pq_signature = ml_dsa_sign(
717            pq,
718            &outer_tbs(
719                ml_dsa_vk_bytes(&pq_public),
720                payload,
721                &ed_signature.to_bytes(),
722                aad,
723            ),
724        );
725        assemble_composite_nested(
726            (
727                ed.verifying_key().to_bytes().to_vec(),
728                ed_signature.to_bytes().to_vec(),
729            ),
730            Some((ml_dsa_vk_bytes(&pq_public), pq_signature)),
731        )
732        .unwrap()
733    }
734
735    fn authority_log_and_checkpoint(
736        root: &CapsuleSigner,
737        deployment_domain: &str,
738    ) -> (
739        DeploymentAuthorityLog,
740        crate::service::DeploymentAuthorityCheckpoint,
741    ) {
742        let mut genesis = crate::did_op::DidOp {
743            sequence: 0,
744            prev: None,
745            rotation_keys: vec![crate::did_op::HybridRotationKey::new(
746                root.ed.verifying_key().to_bytes(),
747                ml_dsa_sk_to_vk_bytes(&root.pq),
748            )
749            .unwrap()],
750            signature: crate::did_op::HybridDidOpSignature {
751                ed25519: vec![0; 64],
752                mldsa65: vec![0; 3_309],
753            },
754        };
755        let composite = sign_nested_for_test(
756            &genesis.signable_bytes(),
757            crate::did_op::DID_OP_SIGNATURE_CONTEXT,
758            &root.ed,
759            &root.pq,
760        );
761        let (ed25519, mldsa65) = split_composite(&composite).unwrap();
762        genesis.signature = crate::did_op::HybridDidOpSignature {
763            ed25519,
764            mldsa65: mldsa65.unwrap(),
765        };
766        let did = genesis.genesis_did().unwrap();
767        let verified = crate::did_op::verify_did_op_log(&did, &[genesis.clone()]).unwrap();
768        (
769            DeploymentAuthorityLog {
770                schema: "hyprstream.deployment-authority-log.v1".to_owned(),
771                deployment_domain: deployment_domain.to_owned(),
772                did: did.clone(),
773                operations_b64: vec![STANDARD.encode(genesis.to_dag_cbor())],
774            },
775            crate::service::DeploymentAuthorityCheckpoint {
776                schema: "hyprstream.deployment-authority-checkpoint.v1".to_owned(),
777                deployment_domain: deployment_domain.to_owned(),
778                did,
779                sequence: verified.sequence,
780                head_cid: verified.head_cid,
781            },
782        )
783    }
784
785    fn delegated_registry_credential(
786        root: &CapsuleSigner,
787        authority_log: &DeploymentAuthorityLog,
788        deployment_domain: &str,
789        registry: &SigningKey,
790    ) -> String {
791        let delegated_ed = SigningKey::from_bytes(&[0xA2; 32]);
792        let (delegated_pq, _) = ml_dsa_generate_keypair();
793        let mut delegated_public = delegated_ed.verifying_key().to_bytes().to_vec();
794        delegated_public.extend_from_slice(&ml_dsa_sk_to_vk_bytes(&delegated_pq));
795        let now = u64::try_from(chrono::Utc::now().timestamp()).unwrap();
796        let mut caveats = BTreeMap::new();
797        caveats.insert(
798            "audience".to_owned(),
799            CaveatValue::Text("urn:hyprstream:service:registry".to_owned()),
800        );
801        caveats.insert(
802            "deployment_domain".to_owned(),
803            CaveatValue::Text(deployment_domain.to_owned()),
804        );
805        caveats.insert(
806            "delegated_public_key_b64".to_owned(),
807            CaveatValue::Text(STANDARD.encode(&delegated_public)),
808        );
809        caveats.insert("max_ttl_seconds".to_owned(), CaveatValue::Int(3_600));
810        caveats.insert(
811            "profile".to_owned(),
812            CaveatValue::Text("hyprstream.registry-deployment.v1".to_owned()),
813        );
814        let payload = UcanPayload {
815            issuer: UcanDid::from_ed25519(&root.ed.verifying_key().to_bytes()),
816            audience: UcanDid::from_ed25519(&delegated_ed.verifying_key().to_bytes()),
817            capabilities: vec![Capability::with_caveats(
818                Resource::new(format!(
819                    "hyprstream://deployment/{deployment_domain}/service/registry"
820                )),
821                Ability::new("mint-registry-jwt"),
822                Caveats(caveats),
823            )],
824            not_before: Some(now),
825            expiration: Some(now + 3_600),
826            nonce: vec![0xA3; 16],
827        };
828        let ucan = Ucan {
829            signature: sign_nested_for_test(
830                &payload.signing_bytes().unwrap(),
831                hyprstream_rpc::auth::ucan::token::UCAN_AAD,
832                &root.ed,
833                &root.pq,
834            ),
835            payload,
836            proofs: vec![],
837        };
838        let artifact = crate::service::RegistryDelegationArtifact {
839            schema: "hyprstream.registry-delegation.v1".to_owned(),
840            deployment_domain: deployment_domain.to_owned(),
841            authority_log_did: authority_log.did.clone(),
842            delegated_public_key_b64: STANDARD.encode(&delegated_public),
843            ucan_b64: STANDARD.encode(ucan.to_cbor().unwrap()),
844        };
845        let exp = i64::try_from(now + 60).unwrap();
846        let now = i64::try_from(now).unwrap();
847        let kid = hyprstream_rpc::auth::composite_kid(
848            &hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(&ml_dsa_sk_to_vk_bytes(
849                &delegated_pq,
850            ))
851            .unwrap(),
852            &delegated_ed.verifying_key(),
853        );
854        let protected = URL_SAFE_NO_PAD.encode(
855            serde_json::to_vec(&json!({
856                "alg": "ML-DSA-65-Ed25519",
857                "typ": "wit+jwt",
858                "kid": kid,
859            }))
860            .unwrap(),
861        );
862        let claims = URL_SAFE_NO_PAD.encode(
863            serde_json::to_vec(&json!({
864                "iss": format!("urn:hyprstream:deployment:{deployment_domain}"),
865                "sub": "service:registry",
866                "aud": "urn:hyprstream:service:registry",
867                "exp": exp,
868                "nbf": now,
869                "iat": now,
870                "deployment_domain": deployment_domain,
871                "profile": "hyprstream.registry-deployment.v1",
872                "cnf": {"jwk": {
873                    "kty": "OKP",
874                    "crv": "Ed25519",
875                    "x": URL_SAFE_NO_PAD.encode(registry.verifying_key().as_bytes()),
876                }},
877                "delegation": URL_SAFE_NO_PAD.encode(serde_json::to_vec(&artifact).unwrap()),
878            }))
879            .unwrap(),
880        );
881        let signing_input = format!("{protected}.{claims}");
882        let mut signature = ml_dsa_sign(&delegated_pq, signing_input.as_bytes());
883        signature.extend_from_slice(&delegated_ed.sign(signing_input.as_bytes()).to_bytes());
884        format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode(signature))
885    }
886
887    fn capsule_with_carrier(
888        classical_alias: &str,
889        tag: u8,
890        carrier: Option<[u8; 32]>,
891    ) -> (Vec<u8>, String) {
892        let signer = capsule_signer(tag);
893        let mut endpoint =
894            ServiceEndpoint::new(Transport::Iroh, format!("iroh://node{tag}")).unwrap();
895        endpoint.node_id = carrier.map(|key| multikey(&key));
896        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
897        let mut body = CapsuleBody::new(vec![signer.pair], vec![service]).unwrap();
898        body.also_known_as = Some(vec![classical_alias.to_owned()]);
899        let capsule = sign_capsule(body, &signer.ed, &signer.pq).unwrap();
900        let bytes = capsule.to_dag_cbor().unwrap();
901        let did = format!("did:at9p:{}", capsule.cid512().unwrap());
902        (bytes, did)
903    }
904
905    fn capsule(classical_alias: &str, tag: u8) -> (Vec<u8>, String) {
906        capsule_with_carrier(classical_alias, tag, Some([0xC0; 32]))
907    }
908
909    fn anchor_body(classical_alias: &str, signer: &CapsuleSigner) -> CapsuleBody {
910        let mut endpoint = ServiceEndpoint::new(Transport::Iroh, "iroh://anchor").unwrap();
911        endpoint.node_id = Some(multikey(&[0xC0; 32]));
912        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
913        let mut body = CapsuleBody::new(vec![signer.pair.clone()], vec![service]).unwrap();
914        body.also_known_as = Some(vec![classical_alias.to_owned()]);
915        body
916    }
917
918    fn signed_capsule(body: CapsuleBody, signer: &CapsuleSigner) -> (Vec<u8>, String) {
919        let capsule = sign_capsule(body, &signer.ed, &signer.pq).unwrap();
920        let bytes = capsule.to_dag_cbor().unwrap();
921        let did = format!("did:at9p:{}", capsule.cid512().unwrap());
922        (bytes, did)
923    }
924
925    async fn closed_profile_error(web: &str, bytes: Vec<u8>, at9p: String) -> anyhow::Error {
926        let anchors = DidAnchors {
927            cluster_at9p_did: at9p.clone(),
928            cluster_did_web: web.to_owned(),
929            extra_root_cert_pem: None,
930        };
931        verify_anchor_material(
932            &anchors,
933            &document(web, Some(&at9p)),
934            Arc::new(FixedCapsuleSource(bytes)),
935        )
936        .await
937        .expect_err("non-profile anchor capsule unexpectedly accepted")
938    }
939
940    fn assert_closed_profile_error(error: &anyhow::Error, field: &str) {
941        let chain = format!("{error:#}");
942        assert!(
943            chain.contains("closed deployment-anchor profile violation"),
944            "failure did not come from the closed profile: {chain}"
945        );
946        assert!(
947            chain.contains(field),
948            "closed-profile failure did not identify {field}: {chain}"
949        );
950    }
951
952    fn document(web: &str, at9p: Option<&str>) -> Value {
953        let mut document = json!({ "id": web });
954        if let Some(at9p) = at9p {
955            document["alsoKnownAs"] = json!([at9p]);
956        }
957        document
958    }
959
960    fn document_with_ca_and_reach(
961        web: &str,
962        at9p: Option<&str>,
963        ca: [u8; 32],
964        iroh_node: [u8; 32],
965    ) -> Value {
966        let mut document = json!({
967            "id": web,
968            "verificationMethod": [{
969                "id": format!("{web}#deployment-ca"),
970                "type": "Multikey",
971                "controller": web,
972                "publicKeyMultibase": multikey(&ca),
973            }],
974            "service": [{
975                "id": format!("{web}#iroh"),
976                "type": "IrohTransport",
977                "serviceEndpoint": hyprstream_rpc::service_entry::encode_iroh(
978                    &iroh_node,
979                    &[],
980                    &["hyprstream-rpc/1"],
981                ),
982            }],
983        });
984        if let Some(at9p) = at9p {
985            document["alsoKnownAs"] = json!([at9p]);
986        }
987        document
988    }
989
990    fn remove_primary_ml_dsa_key(capsule: &[u8]) -> Vec<u8> {
991        let mut value = DagCbor::decode(capsule).expect("test capsule DAG-CBOR");
992        let DagCbor::Map(capsule_members) = &mut value else {
993            panic!("capsule map");
994        };
995        let body = capsule_members
996            .iter_mut()
997            .find_map(|(key, value)| {
998                matches!(key, DagCbor::Text(name) if name == "body").then_some(value)
999            })
1000            .expect("capsule body");
1001        let DagCbor::Map(body_members) = body else {
1002            panic!("body map");
1003        };
1004        let subject_keys = body_members
1005            .iter_mut()
1006            .find_map(|(key, value)| {
1007                matches!(key, DagCbor::Text(name) if name == "subjectKeys").then_some(value)
1008            })
1009            .expect("subject keys");
1010        let DagCbor::List(subject_keys) = subject_keys else {
1011            panic!("subject key list");
1012        };
1013        let DagCbor::Map(primary_members) = subject_keys.first_mut().expect("primary subject key")
1014        else {
1015            panic!("primary subject key map");
1016        };
1017        primary_members
1018            .retain(|(key, _)| !matches!(key, DagCbor::Text(name) if name == "mldsa65Pub"));
1019        value.encode()
1020    }
1021
1022    #[test]
1023    fn unset_anchors_preserve_os_owned_files_selection() {
1024        assert_eq!(
1025            DeploymentTrustSource::from_anchors(None, None).unwrap(),
1026            DeploymentTrustSource::OsOwnedFiles
1027        );
1028        assert!(DeploymentTrustSource::from_anchors(Some("did:at9p:x"), None).is_err());
1029        assert!(DeploymentTrustSource::from_anchors(None, Some("did:web:example.com")).is_err());
1030    }
1031
1032    #[tokio::test]
1033    async fn capsule_hash_mismatch_is_rejected() {
1034        let web = "did:web:cluster.example";
1035        let (served_bytes, _served_did) = capsule(web, 1);
1036        let (_other_bytes, configured_did) = capsule(web, 2);
1037        let anchors = DidAnchors {
1038            cluster_at9p_did: configured_did.clone(),
1039            cluster_did_web: web.to_owned(),
1040            extra_root_cert_pem: None,
1041        };
1042        let error = verify_did_anchored_document(
1043            &anchors,
1044            &document(web, Some(&configured_did)),
1045            Arc::new(FixedCapsuleSource(served_bytes)),
1046            "unused-test-credential".to_owned(),
1047            unused_authority_log(),
1048        )
1049        .await
1050        .err()
1051        .expect("mismatched capsule unexpectedly accepted");
1052        assert!(error.to_string().contains("mutual-alias"), "{error:#}");
1053        assert!(format!("{error:#}").contains("hash-gate"), "{error:#}");
1054    }
1055
1056    #[tokio::test]
1057    async fn one_way_alias_is_rejected() {
1058        let web = "did:web:cluster.example";
1059        let (bytes, at9p) = capsule("did:web:someone-else.example", 3);
1060        let anchors = DidAnchors {
1061            cluster_at9p_did: at9p.clone(),
1062            cluster_did_web: web.to_owned(),
1063            extra_root_cert_pem: None,
1064        };
1065        let error = verify_did_anchored_document(
1066            &anchors,
1067            &document(web, Some(&at9p)),
1068            Arc::new(FixedCapsuleSource(bytes)),
1069            "unused-test-credential".to_owned(),
1070            unused_authority_log(),
1071        )
1072        .await
1073        .err()
1074        .expect("one-way alias unexpectedly accepted");
1075        assert!(format!("{error:#}").contains("does not name"), "{error:#}");
1076    }
1077
1078    #[tokio::test]
1079    async fn closed_anchor_profile_preserves_the_exact_minted_deployment_ca() {
1080        let web = "did:web:cluster.example";
1081        let signer = capsule_signer(4);
1082        let mut deployment_ca = signer.pair.ed25519_pub.clone();
1083        deployment_ca.extend_from_slice(&signer.pair.mldsa65_pub);
1084        let (bytes, at9p) = signed_capsule(anchor_body(web, &signer), &signer);
1085        let anchors = DidAnchors {
1086            cluster_at9p_did: at9p.clone(),
1087            cluster_did_web: web.to_owned(),
1088            extra_root_cert_pem: None,
1089        };
1090        let verified = verify_anchor_material(
1091            &anchors,
1092            &document(web, Some(&at9p)),
1093            Arc::new(FixedCapsuleSource(bytes)),
1094        )
1095        .await
1096        .unwrap();
1097        assert_eq!(verified.at9p_did, at9p);
1098        assert_eq!(
1099            verified.deployment_ca_public, deployment_ca,
1100            "resolved deployment CA must be byte-identical to deployment-ca.hybrid"
1101        );
1102        assert_eq!(
1103            verified.deployment_ca_public.len(),
1104            32 + ML_DSA65_PUBLIC_KEY_LEN
1105        );
1106        match verified.discovery_transport.endpoint {
1107            EndpointType::Iroh { node_id, .. } => assert_eq!(node_id, [0xC0; 32]),
1108            other => panic!("expected iroh reach from capsule, got {other:?}"),
1109        }
1110    }
1111
1112    #[tokio::test]
1113    async fn closed_anchor_profile_rejects_two_subject_keys_signed_by_the_second() {
1114        let web = "did:web:cluster.example";
1115        let untrusted_first = capsule_signer(0x41);
1116        let actual_signer = capsule_signer(0x42);
1117        let mut body = anchor_body(web, &actual_signer);
1118        body.subject_keys = vec![untrusted_first.pair, actual_signer.pair.clone()];
1119        let (bytes, at9p) = signed_capsule(body, &actual_signer);
1120
1121        verify_did_at9p(&at9p, &bytes)
1122            .expect("generic set-semantic GATE must accept the second subject as signer");
1123        let error = closed_profile_error(web, bytes, at9p).await;
1124        assert_closed_profile_error(&error, "subjectKeys");
1125    }
1126
1127    #[tokio::test]
1128    async fn closed_anchor_profile_rejects_an_extra_service() {
1129        let web = "did:web:cluster.example";
1130        let signer = capsule_signer(0x43);
1131        let mut body = anchor_body(web, &signer);
1132        let endpoint = ServiceEndpoint::new(Transport::Https, "https://pds.example").unwrap();
1133        body.services
1134            .push(ServiceEntry::new("#pds", ServiceType::AtprotoPds, endpoint).unwrap());
1135        let (bytes, at9p) = signed_capsule(body, &signer);
1136
1137        verify_did_at9p(&at9p, &bytes).expect("extra-service capsule must pass generic GATE");
1138        let error = closed_profile_error(web, bytes, at9p).await;
1139        assert_closed_profile_error(&error, "services");
1140    }
1141
1142    #[tokio::test]
1143    async fn closed_anchor_profile_rejects_an_extra_alias() {
1144        let web = "did:web:cluster.example";
1145        let signer = capsule_signer(0x44);
1146        let mut body = anchor_body(web, &signer);
1147        body.also_known_as = Some(vec![
1148            web.to_owned(),
1149            "did:web:unexpected.example".to_owned(),
1150        ]);
1151        let (bytes, at9p) = signed_capsule(body, &signer);
1152
1153        verify_did_at9p(&at9p, &bytes).expect("extra-alias capsule must pass generic GATE");
1154        let error = closed_profile_error(web, bytes, at9p).await;
1155        assert_closed_profile_error(&error, "alsoKnownAs");
1156    }
1157
1158    #[tokio::test]
1159    async fn closed_anchor_profile_rejects_forbidden_signed_authority_metadata() {
1160        let web = "did:web:cluster.example";
1161        let signer = capsule_signer(0x45);
1162
1163        let mut next_key = anchor_body(web, &signer);
1164        next_key
1165            .next_key_commitments
1166            .push(signer.pair.commitment_digest());
1167        let mut label_hints = anchor_body(web, &signer);
1168        label_hints.label_hints = Some(vec!["deployment".to_owned()]);
1169        let mut delegations = anchor_body(web, &signer);
1170        delegations.delegations = Some(vec![Delegation::new(
1171            "operator",
1172            "did:web:delegate.example",
1173            vec!["admin".to_owned()],
1174        )
1175        .unwrap()]);
1176        let mut witnesses = anchor_body(web, &signer);
1177        witnesses.witnesses = Some(vec!["did:web:witness.example".to_owned()]);
1178
1179        for (field, body) in [
1180            ("nextKeyCommitments", next_key),
1181            ("labelHints", label_hints),
1182            ("delegations", delegations),
1183            ("witnesses", witnesses),
1184        ] {
1185            let (bytes, at9p) = signed_capsule(body, &signer);
1186            verify_did_at9p(&at9p, &bytes)
1187                .unwrap_or_else(|error| panic!("{field} capsule must pass generic GATE: {error}"));
1188            let error = closed_profile_error(web, bytes, at9p).await;
1189            assert_closed_profile_error(&error, field);
1190        }
1191    }
1192
1193    #[tokio::test]
1194    async fn delegated_registry_token_bootstraps_through_did_anchored_log_and_checkpoint() {
1195        let web = "did:web:cluster.example";
1196        let root = capsule_signer(0x51);
1197        let mut endpoint =
1198            ServiceEndpoint::new(Transport::Iroh, "iroh://delegated-bootstrap").unwrap();
1199        endpoint.node_id = Some(multikey(&[0xC1; 32]));
1200        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
1201        let mut body = CapsuleBody::new(vec![root.pair.clone()], vec![service]).unwrap();
1202        body.also_known_as = Some(vec![web.to_owned()]);
1203        let capsule = sign_capsule(body, &root.ed, &root.pq).unwrap();
1204        let capsule_bytes = capsule.to_dag_cbor().unwrap();
1205        let at9p = format!("did:at9p:{}", capsule.cid512().unwrap());
1206        let anchors = DidAnchors {
1207            cluster_at9p_did: at9p.clone(),
1208            cluster_did_web: web.to_owned(),
1209            extra_root_cert_pem: None,
1210        };
1211        let root_pq =
1212            hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(&ml_dsa_sk_to_vk_bytes(&root.pq))
1213                .unwrap();
1214        let deployment_domain =
1215            hyprstream_rpc::auth::composite_kid(&root_pq, &root.ed.verifying_key());
1216        let (authority_log, checkpoint) = authority_log_and_checkpoint(&root, &deployment_domain);
1217        let registry = SigningKey::from_bytes(&[0x52; 32]);
1218        let credential =
1219            delegated_registry_credential(&root, &authority_log, &deployment_domain, &registry);
1220
1221        let trust = verify_did_anchored_document(
1222            &anchors,
1223            &document(web, Some(&at9p)),
1224            Arc::new(FixedCapsuleSource(capsule_bytes)),
1225            credential,
1226            authority_log,
1227        )
1228        .await
1229        .unwrap();
1230        let verifier = crate::service::authenticate_resolved_did_trust(trust, checkpoint)
1231            .expect("delegated DID-anchored deployment credential");
1232        assert!(verifier.matches(&registry.verifying_key()));
1233    }
1234
1235    #[tokio::test]
1236    async fn substituted_document_ca_and_reach_are_ignored() {
1237        let web = "did:web:cluster.example";
1238        let (bytes, at9p) = capsule(web, 4);
1239        let anchors = DidAnchors {
1240            cluster_at9p_did: at9p.clone(),
1241            cluster_did_web: web.to_owned(),
1242            extra_root_cert_pem: None,
1243        };
1244
1245        let honest = verify_did_anchored_document(
1246            &anchors,
1247            &document_with_ca_and_reach(web, Some(&at9p), [0x07; 32], [0x45; 32]),
1248            Arc::new(FixedCapsuleSource(bytes.clone())),
1249            "unused-test-credential".to_owned(),
1250            unused_authority_log(),
1251        )
1252        .await
1253        .unwrap();
1254        let substituted = verify_did_anchored_document(
1255            &anchors,
1256            &document_with_ca_and_reach(web, Some(&at9p), [0x66; 32], [0xEE; 32]),
1257            Arc::new(FixedCapsuleSource(bytes)),
1258            "unused-test-credential".to_owned(),
1259            unused_authority_log(),
1260        )
1261        .await
1262        .unwrap();
1263
1264        assert_eq!(
1265            honest.ca_verifying_key.ed25519_bytes(),
1266            substituted.ca_verifying_key.ed25519_bytes()
1267        );
1268        assert_eq!(
1269            honest.ca_verifying_key.ml_dsa_65_bytes(),
1270            substituted.ca_verifying_key.ml_dsa_65_bytes()
1271        );
1272        assert_eq!(honest.discovery_transport, substituted.discovery_transport);
1273        assert_eq!(honest.ca_verifying_key.ed25519_bytes(), capsule_ca(4));
1274        match honest.discovery_transport.endpoint {
1275            EndpointType::Iroh { node_id, .. } => assert_eq!(node_id, [0xC0; 32]),
1276            other => panic!("expected capsule-bound iroh reach, got {other:?}"),
1277        }
1278    }
1279
1280    #[tokio::test]
1281    async fn classical_only_capsule_cannot_supply_the_deployment_root() {
1282        let web = "did:web:cluster.example";
1283        let (bytes, at9p) = capsule(web, 0x46);
1284        let classical_only = remove_primary_ml_dsa_key(&bytes);
1285        let anchors = DidAnchors {
1286            cluster_at9p_did: at9p.clone(),
1287            cluster_did_web: web.to_owned(),
1288            extra_root_cert_pem: None,
1289        };
1290        let error = verify_did_anchored_document(
1291            &anchors,
1292            &document(web, Some(&at9p)),
1293            Arc::new(FixedCapsuleSource(classical_only)),
1294            "unused-test-credential".to_owned(),
1295            unused_authority_log(),
1296        )
1297        .await
1298        .err()
1299        .expect("classical-only capsule unexpectedly supplied deployment root");
1300        assert!(
1301            format!("{error:#}").contains("mldsa65Pub"),
1302            "failure did not identify the missing PQ root half: {error:#}"
1303        );
1304    }
1305
1306    #[tokio::test]
1307    async fn reach_without_carrier_node_id_fails_closed() {
1308        let web = "did:web:cluster.example";
1309        let (bytes, at9p) = capsule_with_carrier(web, 4, None);
1310        let anchors = DidAnchors {
1311            cluster_at9p_did: at9p.clone(),
1312            cluster_did_web: web.to_owned(),
1313            extra_root_cert_pem: None,
1314        };
1315        let error = verify_did_anchored_document(
1316            &anchors,
1317            &document(web, Some(&at9p)),
1318            Arc::new(FixedCapsuleSource(bytes)),
1319            "unused-test-credential".to_owned(),
1320            unused_authority_log(),
1321        )
1322        .await
1323        .err()
1324        .expect("carrier-less reach unexpectedly accepted");
1325        assert!(format!("{error:#}").contains("no independent iroh nodeId"));
1326    }
1327
1328    #[tokio::test]
1329    async fn capsule_bound_quic_reach_is_accepted() {
1330        let web = "did:web:cluster.example";
1331        let signer = capsule_signer(5);
1332        let endpoint = ServiceEndpoint::new(Transport::Quic, "quic://127.0.0.1:7443").unwrap();
1333        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
1334        let mut body = CapsuleBody::new(vec![signer.pair], vec![service]).unwrap();
1335        body.also_known_as = Some(vec![web.to_owned()]);
1336        let capsule = sign_capsule(body, &signer.ed, &signer.pq).unwrap();
1337        let bytes = capsule.to_dag_cbor().unwrap();
1338        let at9p = format!("did:at9p:{}", capsule.cid512().unwrap());
1339        let anchors = DidAnchors {
1340            cluster_at9p_did: at9p.clone(),
1341            cluster_did_web: web.to_owned(),
1342            extra_root_cert_pem: None,
1343        };
1344        let channel_auth =
1345            hyprstream_rpc::transport::QuicServerAuth::pinned(vec![[0xA5; 32]]).unwrap();
1346        let mut document = document(web, Some(&at9p));
1347        document["service"] = json!([{
1348            "id": format!("{web}#quic"),
1349            "type": "QuicTransport",
1350            "serviceEndpoint": hyprstream_rpc::service_entry::encode_quic(
1351                "https://127.0.0.1:7443",
1352                &channel_auth,
1353                &["hyprstream-rpc/1"],
1354            ),
1355        }]);
1356
1357        let trust = verify_did_anchored_document(
1358            &anchors,
1359            &document,
1360            Arc::new(FixedCapsuleSource(bytes)),
1361            "unused-test-credential".to_owned(),
1362            unused_authority_log(),
1363        )
1364        .await
1365        .unwrap();
1366        match trust.discovery_transport.endpoint {
1367            EndpointType::Quic { addr, auth, .. } => {
1368                assert_eq!(addr, "127.0.0.1:7443".parse().unwrap());
1369                assert!(!auth.require_web_pki());
1370                assert_eq!(auth.accept_cert_hashes(), &[[0xA5; 32]]);
1371            }
1372            other => panic!("expected capsule-bound QUIC reach, got {other:?}"),
1373        }
1374    }
1375
1376    /// When the document QUIC entry uses a hostname URI (decoding to an
1377    /// unspecified IP) and the port matches the capsule's real address, the
1378    /// port-match relaxation must fire AND the returned config must dial the
1379    /// capsule's real socket address — not `0.0.0.0:port`.
1380    ///
1381    /// Removing the address-rewrite in `reach_from_capsule` turns this test
1382    /// red: the config would dial an unspecified address and never connect.
1383    #[tokio::test]
1384    async fn quic_port_match_with_hostname_uri_rewrites_dial_address() {
1385        let web = "did:web:cluster.example";
1386        let signer = capsule_signer(7);
1387        let capsule_addr: SocketAddr = "203.0.113.10:443".parse().unwrap();
1388        let endpoint =
1389            ServiceEndpoint::new(Transport::Quic, format!("quic://{capsule_addr}")).unwrap();
1390        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
1391        let mut body = CapsuleBody::new(vec![signer.pair], vec![service]).unwrap();
1392        body.also_known_as = Some(vec![web.to_owned()]);
1393        let capsule = sign_capsule(body, &signer.ed, &signer.pq).unwrap();
1394        let bytes = capsule.to_dag_cbor().unwrap();
1395        let at9p = format!("did:at9p:{}", capsule.cid512().unwrap());
1396        let anchors = DidAnchors {
1397            cluster_at9p_did: at9p.clone(),
1398            cluster_did_web: web.to_owned(),
1399            extra_root_cert_pem: None,
1400        };
1401        let channel_auth =
1402            hyprstream_rpc::transport::QuicServerAuth::pinned(vec![[0xB7; 32]]).unwrap();
1403        let mut document = document(web, Some(&at9p));
1404        // Hostname URI decodes to 0.0.0.0:443 — port matches, IP does not.
1405        document["service"] = json!([{
1406            "id": format!("{web}#quic"),
1407            "type": "QuicTransport",
1408            "serviceEndpoint": hyprstream_rpc::service_entry::encode_quic(
1409                "https://staging.example.com:443",
1410                &channel_auth,
1411                &["hyprstream-rpc/1"],
1412            ),
1413        }]);
1414
1415        let trust = verify_did_anchored_document(
1416            &anchors,
1417            &document,
1418            Arc::new(FixedCapsuleSource(bytes)),
1419            "unused-test-credential".to_owned(),
1420            unused_authority_log(),
1421        )
1422        .await
1423        .expect("hostname-URI port match must verify");
1424        match trust.discovery_transport.endpoint {
1425            EndpointType::Quic { addr, auth, .. } => {
1426                assert_eq!(
1427                    addr, capsule_addr,
1428                    "dial address must be the capsule's real socket, not 0.0.0.0"
1429                );
1430                assert!(!auth.require_web_pki());
1431                assert_eq!(auth.accept_cert_hashes(), &[[0xB7; 32]]);
1432            }
1433            other => panic!("expected capsule-bound QUIC reach, got {other:?}"),
1434        }
1435    }
1436
1437    /// When the document QUIC entry's port does NOT match the capsule's address
1438    /// (and the IP is unspecified from a hostname URI), no entry matches and the
1439    /// resolver falls back to a bare-IP dial without SNI or certificate pins.
1440    #[tokio::test]
1441    async fn quic_neither_port_nor_address_match_falls_back_to_bare_ip() {
1442        let web = "did:web:cluster.example";
1443        let signer = capsule_signer(9);
1444        let capsule_addr: SocketAddr = "203.0.113.20:443".parse().unwrap();
1445        let endpoint =
1446            ServiceEndpoint::new(Transport::Quic, format!("quic://{capsule_addr}")).unwrap();
1447        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
1448        let mut body = CapsuleBody::new(vec![signer.pair], vec![service]).unwrap();
1449        body.also_known_as = Some(vec![web.to_owned()]);
1450        let capsule = sign_capsule(body, &signer.ed, &signer.pq).unwrap();
1451        let bytes = capsule.to_dag_cbor().unwrap();
1452        let at9p = format!("did:at9p:{}", capsule.cid512().unwrap());
1453        let anchors = DidAnchors {
1454            cluster_at9p_did: at9p.clone(),
1455            cluster_did_web: web.to_owned(),
1456            extra_root_cert_pem: None,
1457        };
1458        let channel_auth =
1459            hyprstream_rpc::transport::QuicServerAuth::pinned(vec![[0xC9; 32]]).unwrap();
1460        let mut document = document(web, Some(&at9p));
1461        // Port 8443 does not match the capsule's port 443.
1462        document["service"] = json!([{
1463            "id": format!("{web}#quic"),
1464            "type": "QuicTransport",
1465            "serviceEndpoint": hyprstream_rpc::service_entry::encode_quic(
1466                "https://staging.example.com:8443",
1467                &channel_auth,
1468                &["hyprstream-rpc/1"],
1469            ),
1470        }]);
1471
1472        let trust = verify_did_anchored_document(
1473            &anchors,
1474            &document,
1475            Arc::new(FixedCapsuleSource(bytes)),
1476            "unused-test-credential".to_owned(),
1477            unused_authority_log(),
1478        )
1479        .await
1480        .expect("fallback to bare-IP dial must still verify");
1481        match trust.discovery_transport.endpoint {
1482            EndpointType::Quic { addr, auth, .. } => {
1483                // Fallback: bare capsule address, WebPKI default, no cert pins.
1484                assert_eq!(addr, capsule_addr);
1485                assert!(auth.require_web_pki());
1486                assert!(auth.accept_cert_hashes().is_empty());
1487            }
1488            other => panic!("expected fallback QUIC reach, got {other:?}"),
1489        }
1490    }
1491}