hyprstream_rpc/admission.rs
1//! Federation admission gate over DID/key binding (#137, milestone M3).
2//!
3//! A transport-agnostic, two-stage **fail-closed** gate that decides whether an
4//! inbound federated peer may be admitted over *any*
5//! [`crate::transport_traits::Transport`]-backed session (QUIC/WebTransport,
6//! iroh, …). It is deliberately independent of the concrete transport: the
7//! accept path supplies the peer's already-authenticated material; this module
8//! makes the trust decision.
9//!
10//! # The two stages (both must pass)
11//!
12//! 1. **Origin admission** — is the peer's *origin* (RFC 6454: scheme + host +
13//! non-default port) permitted by policy? This reuses the existing unified
14//! federation trust gate (Casbin `federation:register`, the CIMD /
15//! `FederationKeyResolver` decision point) via the [`OriginAdmission`] trait,
16//! implemented in the `hyprstream` crate over `PolicyService` (the lower
17//! `hyprstream-rpc` crate has no `PolicyService` client, so the live decision
18//! is injected). The gate calls it unchanged.
19//!
20//! 2. **Key binding** — does the independently verified application-envelope
21//! signer key bind to the peer's DID? Carrier keys are never accepted here.
22//! Two DID-method paths:
23//!
24//! - **`did:web`** — match the key against a `verificationMethod` in the
25//! peer's *resolved* DID document (for example `#mesh`), OR an
26//! Ed25519 key in a federation JWKS the caller supplies. The DID document is
27//! resolved via the [`crate::did_web::DidWebResolver`] landed in #279 (no new
28//! fetch/cache infra); the VM extraction is
29//! [`crate::did_web::verification_method_ed25519_keys`] (#280 Multikey decode).
30//! - **`did:key` (Tiles interop, #281)** — a `did:key` is **self-certifying**:
31//! the Ed25519 key *is* the identity (`did:key:z6Mk…` =
32//! `multibase(0xed01 ‖ pubkey)`). There is **no document to resolve and no
33//! network fetch**; the gate decodes the key from the DID
34//! ([`crate::did_web::did_key_to_ed25519`]) and admits iff the application
35//! signer key equals it. Reach is resolved separately, never from this DID.
36//!
37//! Either stage failing — or any resolution / I/O error — rejects (§4.4
38//! fail-closed). A successful run yields an [`AdmittedIdentity`] binding the
39//! origin to the matched key.
40//!
41//! # What is wired vs. what is a documented seam
42//!
43//! Stage 2's *logic* (resolve DID doc → extract VM keys → constant-time-ish
44//! membership match, with JWKS fallback) is fully implemented and unit-tested
45//! here against fixtures. Live callers must feed stage 2 only the signer key from
46//! a verified application envelope. A NodeId, EndpointId, TLS certificate key,
47//! endpoint field, or caller assertion is not a [`VerifiedApplicationSigner`]. If a
48//! network path has no verified application proof, it must not invoke this gate
49//! as though carrier establishment supplied one.
50
51use anyhow::{anyhow, Result};
52use async_trait::async_trait;
53use serde_json::Value;
54
55use crate::auth::mac::VerifiedKeyMaterial;
56use crate::did_web::{
57 did_key_to_ed25519, is_did_key, jwks_ed25519_keys, verification_method_ed25519_keys,
58 DidDocFetcher, DidWebResolver,
59};
60use crate::envelope::KeyedPqTrustStore;
61use crate::identity::DID_AT9P_PREFIX;
62use crate::identity_resolver::At9pCapsuleResolver;
63
64/// Whether `did` is a `did:at9p` identifier (the self-certifying hybrid-PQC arm).
65///
66/// Delegates to the shared [`DID_AT9P_PREFIX`] literal (the single source of
67/// truth shared with [`crate::identity::Did::is_did_at9p`] and `hyprstream-pds`'s
68/// GATE code) so the prefix cannot drift across arms (#964).
69fn is_did_at9p(did: &str) -> bool {
70 did.starts_with(DID_AT9P_PREFIX)
71}
72
73/// Inputs for the `did:at9p` admission arm (D2/#894).
74///
75/// Parallel to the `is_did_key` arm, but a `did:at9p` proof upgrades a verified
76/// application signer to a hybrid-PQC anchor, so the arm additionally needs:
77/// - the **capsule bytes** carried with the application proof,
78/// - a **GATE verifier** ([`At9pCapsuleResolver`]) that runs the A4
79/// canon→hash→sig pipeline (#884) and returns the content-verified subject keys,
80/// - the **[`KeyedPqTrustStore`]** to bind those verified hybrid keys into — the
81/// atomic `ed25519 → ml_dsa_65` binding that replaces the out-of-band
82/// `mesh_peers` config path for `did:at9p` peers.
83///
84/// The arm is exercised by passing `Some(At9pAdmission { .. })` to
85/// [`admit_key_against_did`]; the live mesh admission flow is not wired beyond
86/// this arm, so [`FederationAdmissionGate::admit`] passes `None` (a `did:at9p`
87/// peer reaching that path fails closed until the accept path feeds capsule bytes).
88pub struct At9pAdmission<'a> {
89 /// The raw genesis capsule bytes the peer presented for `did:at9p:<cid512>`.
90 pub capsule_bytes: &'a [u8],
91 /// The GATE verifier (implemented in `hyprstream-pds` over `verify_did_at9p`).
92 pub gate: &'a dyn At9pCapsuleResolver,
93 /// The native PQ trust store to bind the verified hybrid keys into.
94 pub pq_store: &'a mut KeyedPqTrustStore,
95}
96
97/// The raw Ed25519 signer key from independently verified application proof.
98///
99/// # Where this comes from (integration seam)
100///
101/// Peer identity is established at the application layer. The key here is the
102/// verified COSE envelope signer (`cnf`, 32 bytes) after the surrounding proof
103/// policy succeeds. It must never be sourced from iroh NodeId/EndpointId or any
104/// other carrier key, even when the bytes happen to be equal.
105///
106/// This newtype keeps the gate honest about *which* bytes it is matching and
107/// makes the seam explicit at every call site.
108#[derive(Clone, Copy, PartialEq, Eq)]
109pub struct ApplicationSignerKey(pub [u8; 32]);
110
111impl ApplicationSignerKey {
112 /// The raw 32-byte Ed25519 public key.
113 pub fn as_bytes(&self) -> &[u8; 32] {
114 &self.0
115 }
116}
117
118impl std::fmt::Debug for ApplicationSignerKey {
119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120 // Render a short fingerprint, not the full key, to keep logs tidy.
121 write!(
122 f,
123 "ApplicationSignerKey({:02x}{:02x}…)",
124 self.0[0], self.0[1]
125 )
126 }
127}
128
129/// The trust boundary on which admission is being attempted.
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub enum AdmissionTrustSurface {
132 /// A native/SPINE trust surface. Classical-only proof is a downgrade and
133 /// must fail closed.
134 Native,
135 /// A named third-party interoperability perimeter where a foreign identity
136 /// may only provide classical signing material.
137 ThirdPartyInterop,
138}
139
140/// Application signer plus the assurance actually established by envelope
141/// verification. This is crypto-derived evidence, never a DID-document claim.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub struct VerifiedApplicationSigner {
144 key: ApplicationSignerKey,
145 key_material: VerifiedKeyMaterial,
146}
147
148impl VerifiedApplicationSigner {
149 /// A signer whose Ed25519 + bound ML-DSA-65 composite verified.
150 pub fn pq_hybrid(key: [u8; 32]) -> Self {
151 Self {
152 key: ApplicationSignerKey(key),
153 key_material: VerifiedKeyMaterial::PqHybrid,
154 }
155 }
156
157 /// A classical signer verified specifically at a third-party interop edge.
158 ///
159 /// The deliberately long name prevents a generic/native caller from
160 /// selecting classical verification as an accidental default.
161 pub fn third_party_interop_classical(key: [u8; 32]) -> Self {
162 Self {
163 key: ApplicationSignerKey(key),
164 key_material: VerifiedKeyMaterial::Classical,
165 }
166 }
167
168 pub fn key(&self) -> ApplicationSignerKey {
169 self.key
170 }
171
172 pub fn key_material(&self) -> VerifiedKeyMaterial {
173 self.key_material
174 }
175}
176
177fn require_key_assurance(
178 origin: &str,
179 signer: VerifiedApplicationSigner,
180 surface: AdmissionTrustSurface,
181) -> Result<ApplicationSignerKey> {
182 match (surface, signer.key_material()) {
183 (AdmissionTrustSurface::Native, VerifiedKeyMaterial::PqHybrid)
184 | (
185 AdmissionTrustSurface::ThirdPartyInterop,
186 VerifiedKeyMaterial::Classical | VerifiedKeyMaterial::PqHybrid,
187 ) => Ok(signer.key()),
188 (AdmissionTrustSurface::Native, _) => Err(admission_reject(
189 origin,
190 signer.key(),
191 "native/SPINE admission requires verified PQ-hybrid application proof; classical Ed25519 alone is a downgrade",
192 )),
193 (_, VerifiedKeyMaterial::Unverified) => Err(admission_reject(
194 origin,
195 signer.key(),
196 "application signer proof is unverified",
197 )),
198 }
199}
200
201/// Stage 1: origin admission decision (RFC 6454 origin → permitted?).
202///
203/// Implemented in the `hyprstream` crate over `PolicyService`
204/// (`federation:register`), the same unified federation trust gate used by CIMD
205/// client registration and `FederationKeyResolver`. Abstracted as a trait so the
206/// lower `hyprstream-rpc` crate (which has no `PolicyService` client) can run the
207/// gate, and so the decision is independently testable.
208///
209/// **Fail-closed contract:** implementations MUST return `Ok(())` only when the
210/// origin is affirmatively permitted, and `Err(_)` on denial **or** on any
211/// inability to reach the policy decision (RPC outage) — never default-allow.
212#[async_trait]
213pub trait OriginAdmission: Send + Sync {
214 /// Permit the given RFC 6454 origin, or return why it is rejected.
215 async fn admit_origin(&self, origin: &str) -> Result<()>;
216}
217
218/// Resolves a peer DID identifier to its DID document JSON.
219///
220/// Implemented for [`DidWebResolver`] below (reusing #279's fetch+cache); a
221/// fixture impl makes the gate testable without a network.
222#[async_trait]
223pub trait DidDocResolve: Send + Sync {
224 /// Fetch and parse the DID document for `did`.
225 async fn resolve_doc(&self, did: &str) -> Result<Value>;
226}
227
228#[async_trait]
229impl<F: DidDocFetcher> DidDocResolve for DidWebResolver<F> {
230 async fn resolve_doc(&self, did: &str) -> Result<Value> {
231 // Reuse the resolver's derive-URL + cached fetch path (#279); we want the
232 // raw document so stage 2 can read `verificationMethod`, which the
233 // transport-only `resolve`/`resolve_all` discard.
234 self.resolve_document(did).await
235 }
236}
237
238/// A configured `did:plc` resolver can serve the existing federation admission
239/// boundary. Its URL derivation, egress allowlist, cache, and `doc.id` binding
240/// are all enforced before this gate inspects verification methods.
241#[async_trait]
242impl<F: crate::did_plc::PlcAuditFetcher> DidDocResolve for crate::did_plc::DidPlcResolver<F> {
243 async fn resolve_doc(&self, did: &str) -> Result<Value> {
244 self.resolve_document(did).await
245 }
246}
247
248/// The result of a successful two-stage admission: the peer's normalized origin
249/// bound to the authenticated key that matched its published DID-doc VM / JWKS.
250#[derive(Clone, Debug, PartialEq, Eq)]
251pub struct AdmittedIdentity {
252 /// The RFC 6454 origin that passed stage 1.
253 pub origin: String,
254 /// The peer DID identifier whose document carried the matched VM (when the
255 /// match came from a DID document; `None` if matched via JWKS fallback).
256 pub did: Option<String>,
257 /// The authenticated Ed25519 key that matched (32 bytes).
258 pub key: [u8; 32],
259}
260
261/// The federation admission gate: stage 1 (origin) then stage 2 (key binding),
262/// fail-closed if **either** fails.
263///
264/// Transport-agnostic: construct it once with the origin-admission handle and a
265/// DID-doc resolver, then call [`admit`](FederationAdmissionGate::admit) from
266/// any transport accept path with the per-connection (origin, application signer key, did,
267/// optional federation JWKS).
268pub struct FederationAdmissionGate<O: OriginAdmission, R: DidDocResolve> {
269 origin_admission: O,
270 resolver: R,
271}
272
273impl<O: OriginAdmission, R: DidDocResolve> FederationAdmissionGate<O, R> {
274 /// Construct a gate over an origin-admission handle and a DID-doc resolver.
275 pub fn new(origin_admission: O, resolver: R) -> Self {
276 Self {
277 origin_admission,
278 resolver,
279 }
280 }
281
282 /// Run the two-stage gate for an inbound peer.
283 ///
284 /// - `origin` — the peer's RFC 6454 origin (caller extracts it from the peer
285 /// DID / advertised issuer with `extract_origin`).
286 /// - `application_signer` — the verified application-envelope signer key and assurance (see
287 /// [`VerifiedApplicationSigner`]).
288 /// - `trust_surface` — explicit native/SPINE vs third-party interop
289 /// classification. Native admission requires PQ-hybrid proof.
290 /// - `did` — the peer's DID identifier for stage 2 (`did:web:…` resolved via
291 /// the DID-doc resolver, or `did:key:…` self-certifying / no fetch — #281).
292 /// - `federation_jwks` — an optional already-resolved federation JWKS
293 /// document (e.g. from the existing `jwks_uri` cache) used as a **fallback**
294 /// key source when the DID document carries no matching Ed25519 VM. Reuses
295 /// the caller's JWKS cache; this module never fetches JWKS itself.
296 ///
297 /// Returns the [`AdmittedIdentity`] on success; `Err` (reject) if stage 1
298 /// denies, if DID resolution fails, or if no VM/JWKS key matches the application signer key.
299 pub async fn admit(
300 &self,
301 origin: &str,
302 application_signer: VerifiedApplicationSigner,
303 trust_surface: AdmissionTrustSurface,
304 did: &str,
305 federation_jwks: Option<&Value>,
306 ) -> Result<AdmittedIdentity> {
307 // ── Stage 1: origin admission (fail-closed) ───────────────────────────
308 // Run FIRST so a disallowed origin is rejected before we ever fetch its
309 // DID document (no SSRF/work amplification for un-permitted peers).
310 self.origin_admission
311 .admit_origin(origin)
312 .await
313 .map_err(|e| anyhow!("admission stage 1 (origin {origin}) denied: {e}"))?;
314
315 // ── Stage 2: key binding (fail-closed) ────────────────────────────────
316 admit_key_against_did(
317 &self.resolver,
318 origin,
319 application_signer,
320 trust_surface,
321 did,
322 federation_jwks,
323 None,
324 )
325 .await
326 }
327}
328
329/// Stage 2 core, factored out so it is independently unit-testable: bind the
330/// verified application signer key to its DID's published key material, and
331/// admit iff it matches.
332///
333/// The assurance floor is enforced before DID dispatch: native/SPINE surfaces
334/// require verified PQ-hybrid proof; classical proof is accepted only when the
335/// caller explicitly names [`AdmissionTrustSurface::ThirdPartyInterop`].
336///
337/// Three DID-method paths (chosen by the DID string):
338///
339/// - **`did:key` (self-certifying, #281)** — Tiles-style Ed25519 device/account
340/// identity. The key *is* the identity: `did:key:z6Mk…` is exactly
341/// `multibase(0xed01 ‖ pubkey)`, so there is **no document to fetch and no
342/// resolver call**. We decode the key directly ([`did_key_to_ed25519`]) and
343/// admit iff `application_signer_key` equals it. Reach is an independent resolver output.
344/// - **`did:at9p` (self-certifying hybrid-PQC, #894/D2)** — the capsule *is* the
345/// hybrid key commitment: GATE-verify the peer-presented bytes
346/// (canon→hash→sig, #884) via the supplied [`At9pCapsuleResolver`], admit iff
347/// the verified application signer equals the capsule's Ed25519 subject key,
348/// and bind
349/// the verified `ed25519 → ml_dsa_65` pair into the [`KeyedPqTrustStore`].
350/// This is the classical→hybrid trust upgrade, populated from content-verified
351/// material (no config trust). No resolver/fetch: the capsule is
352/// self-certifying. Requires `at9p = Some(_)`; otherwise fail-closed.
353/// - **`did:web` (resolver fetch, #279/#137)** — resolve the peer DID document
354/// and admit iff `application_signer_key` matches one of its Ed25519 `verificationMethod`
355/// keys, falling back to a supplied federation JWKS.
356///
357/// Fail-closed: a parse error, a resolution error, an empty/absent VM set with no
358/// JWKS match, or a key mismatch all return `Err`.
359pub async fn admit_key_against_did<R: DidDocResolve>(
360 resolver: &R,
361 origin: &str,
362 application_signer: VerifiedApplicationSigner,
363 trust_surface: AdmissionTrustSurface,
364 did: &str,
365 federation_jwks: Option<&Value>,
366 at9p: Option<At9pAdmission<'_>>,
367) -> Result<AdmittedIdentity> {
368 let application_signer_key = require_key_assurance(origin, application_signer, trust_surface)?;
369 // ── did:key self-certifying arm (#281) ────────────────────────────────────
370 // A did:key carries its own Ed25519 key — no DID-doc resolution / network
371 // fetch. The verified application signer MUST equal the key the DID
372 // encodes; any mismatch or parse error fails closed.
373 if is_did_key(did) {
374 let did_key = did_key_to_ed25519(did).map_err(|e| {
375 admission_reject(
376 origin,
377 application_signer_key,
378 &format!("did:key {did} is invalid: {e}"),
379 )
380 })?;
381 if key_eq(&did_key, application_signer_key.as_bytes()) {
382 return Ok(AdmittedIdentity {
383 origin: origin.to_owned(),
384 did: Some(did.to_owned()),
385 key: *application_signer_key.as_bytes(),
386 });
387 }
388 return Err(admission_reject(
389 origin,
390 application_signer_key,
391 &format!(
392 "application signer key does not match the self-certifying did:key identity {did}"
393 ),
394 ));
395 }
396
397 // ── did:at9p self-certifying hybrid arm (#894/D2) ──────────────────────────
398 // The capsule proves the ed25519→ml_dsa_65 binding (GATE pipeline #884), so no
399 // DID-doc fetch and no out-of-band config trust: the binding is installed
400 // straight from content-verified material. A GATE failure rejects and binds
401 // nothing; a missing admission context rejects too (the live accept path does
402 // not yet feed capsule bytes — `FederationAdmissionGate::admit` passes None).
403 if is_did_at9p(did) {
404 let ctx = at9p.ok_or_else(|| {
405 admission_reject(
406 origin,
407 application_signer_key,
408 &format!(
409 "did:at9p {did} presented without a capsule/admission context — fail-closed"
410 ),
411 )
412 })?;
413 let verified = ctx.gate.verify_bytes(did, ctx.capsule_bytes).map_err(|e| {
414 admission_reject(
415 origin,
416 application_signer_key,
417 &format!("did:at9p {did} capsule GATE rejected: {e}"),
418 )
419 })?;
420 // `subjectKeys` is a published SET, not a positional singleton (#1188 /
421 // #1183): the separately verified application signer must equal *some*
422 // published subject key — its position in the set is irrelevant. An
423 // overlap-rotating or hybrid-rolling out identity publishes several
424 // usable keys at once; a peer that presents any of them is the same
425 // identity. This comparison says nothing about carrier reach or liveness.
426 let matched = verified
427 .for_ed25519(application_signer_key.as_bytes())
428 .ok_or_else(|| {
429 admission_reject(
430 origin,
431 application_signer_key,
432 &format!(
433 "application signer key does not match any did:at9p capsule Ed25519 subject key {did}"
434 ),
435 )
436 })?;
437 // Atomic hybrid binding from the verified capsule — the ML-DSA-65 half
438 // bound to *this* matched Ed25519 key, never a positional one. Replaces
439 // the out-of-band `mesh_peers` config path for did:at9p peers (#894).
440 ctx.pq_store.bind(*matched.ed25519(), matched.ml_dsa_65());
441 return Ok(AdmittedIdentity {
442 origin: origin.to_owned(),
443 did: Some(did.to_owned()),
444 key: *application_signer_key.as_bytes(),
445 });
446 }
447
448 // ── did:web resolver arm (#279/#137) ──────────────────────────────────────
449 // Resolve the peer's DID document. A resolution failure is fail-closed:
450 // without the published key material we cannot bind the application signer.
451 let doc = resolver.resolve_doc(did).await.map_err(|e| {
452 admission_reject(
453 origin,
454 application_signer_key,
455 &format!("DID {did} did not resolve: {e}"),
456 )
457 })?;
458
459 let vm_keys = verification_method_ed25519_keys(&doc);
460 if vm_keys
461 .iter()
462 .any(|k| key_eq(k, application_signer_key.as_bytes()))
463 {
464 return Ok(AdmittedIdentity {
465 origin: origin.to_owned(),
466 did: Some(did.to_owned()),
467 key: *application_signer_key.as_bytes(),
468 });
469 }
470
471 // Fallback: a federation-tagged JWKS the caller already resolved/cached.
472 if let Some(jwks) = federation_jwks {
473 if jwks_ed25519_keys(jwks)
474 .iter()
475 .any(|k| key_eq(k, application_signer_key.as_bytes()))
476 {
477 return Ok(AdmittedIdentity {
478 origin: origin.to_owned(),
479 // Matched via JWKS, not a specific DID-doc VM.
480 did: None,
481 key: *application_signer_key.as_bytes(),
482 });
483 }
484 }
485
486 Err(admission_reject(
487 origin,
488 application_signer_key,
489 &format!(
490 "application signer key does not match any Ed25519 verificationMethod in DID doc for {did}{}",
491 if federation_jwks.is_some() { " (nor the federation JWKS)" } else { "" }
492 ),
493 ))
494}
495
496/// Constant-time-ish equality for two 32-byte keys.
497///
498/// The keys here are *public* (no secret to leak), so a data-dependent compare is
499/// not a vulnerability; we still fold over all bytes to avoid an early-exit habit
500/// leaking into copies of this matcher elsewhere.
501fn key_eq(a: &[u8; 32], b: &[u8; 32]) -> bool {
502 let mut diff = 0u8;
503 for i in 0..32 {
504 diff |= a[i] ^ b[i];
505 }
506 diff == 0
507}
508
509/// Build a uniform rejection error (also a single tracing point so denials are
510/// diagnosable without leaking the full key).
511fn admission_reject(origin: &str, key: ApplicationSignerKey, why: &str) -> anyhow::Error {
512 tracing::warn!(origin = %origin, application_signer_key = ?key, "federation admission stage 2 rejected: {why}");
513 anyhow!("admission stage 2 (origin {origin}) rejected: {why}")
514}
515
516/// Convenience rejection for a network path lacking verified application proof.
517pub fn reject_no_application_signer_proof(origin: &str) -> anyhow::Error {
518 anyhow!(
519 "admission stage 2 (origin {origin}): verified application signer proof is unavailable; \
520 carrier NodeId/EndpointId is not an admission key — failing closed"
521 )
522}
523
524#[cfg(test)]
525#[allow(clippy::expect_used, clippy::unwrap_used)]
526mod tests {
527 use super::*;
528 use crate::did_web::decode_ed25519_multikey;
529 use anyhow::bail;
530 use ed25519_dalek::SigningKey;
531 use rand::rngs::OsRng;
532 use serde_json::json;
533
534 /// Encode raw Ed25519 bytes as an `ed25519-pub` Multikey `publicKeyMultibase`
535 /// (`z` + base58btc(multicodec || key)). Mirrors `mesh_trust::encode_multikey`
536 /// for the Ed25519 codec; kept local to the test (no `hyprstream` dep).
537 fn ed25519_multikey(raw: &[u8; 32]) -> String {
538 let mut payload = Vec::with_capacity(2 + 32);
539 payload.extend_from_slice(&[0xed, 0x01]);
540 payload.extend_from_slice(raw);
541 format!("z{}", bs58::encode(payload).into_string())
542 }
543
544 fn random_ed25519() -> [u8; 32] {
545 SigningKey::generate(&mut OsRng).verifying_key().to_bytes()
546 }
547
548 fn interop_signer(key: [u8; 32]) -> VerifiedApplicationSigner {
549 VerifiedApplicationSigner::third_party_interop_classical(key)
550 }
551
552 fn hybrid_signer(key: [u8; 32]) -> VerifiedApplicationSigner {
553 VerifiedApplicationSigner::pq_hybrid(key)
554 }
555
556 /// Decode-roundtrip sanity: our local Multikey encode is the inverse of the
557 /// did_web decoder (same wire format as `mesh_trust`).
558 #[test]
559 fn multikey_roundtrip() {
560 let raw = random_ed25519();
561 let mb = ed25519_multikey(&raw);
562 assert_eq!(decode_ed25519_multikey(&mb).unwrap(), raw);
563 }
564
565 fn did_doc_with_vm(keys: &[[u8; 32]]) -> Value {
566 let vms: Vec<Value> = keys
567 .iter()
568 .enumerate()
569 .map(|(i, k)| {
570 json!({
571 "id": format!("did:web:peer.example#key-{i}"),
572 "type": "Multikey",
573 "controller": "did:web:peer.example",
574 "publicKeyMultibase": ed25519_multikey(k),
575 })
576 })
577 .collect();
578 json!({
579 "@context": ["https://www.w3.org/ns/did/v1"],
580 "id": "did:web:peer.example",
581 "verificationMethod": vms,
582 "service": [],
583 })
584 }
585
586 fn jwks_with_keys(keys: &[[u8; 32]]) -> Value {
587 use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
588 let ks: Vec<Value> = keys
589 .iter()
590 .map(|k| json!({ "kty": "OKP", "crv": "Ed25519", "x": URL_SAFE_NO_PAD.encode(k) }))
591 .collect();
592 json!({ "keys": ks })
593 }
594
595 // ── Test doubles ───────────────────────────────────────────────────────
596
597 struct AllowOrigin;
598 #[async_trait]
599 impl OriginAdmission for AllowOrigin {
600 async fn admit_origin(&self, _origin: &str) -> Result<()> {
601 Ok(())
602 }
603 }
604
605 struct DenyOrigin;
606 #[async_trait]
607 impl OriginAdmission for DenyOrigin {
608 async fn admit_origin(&self, origin: &str) -> Result<()> {
609 bail!("origin {origin} not permitted by policy (federation:register denied)")
610 }
611 }
612
613 struct FixtureDoc(Value);
614 #[async_trait]
615 impl DidDocResolve for FixtureDoc {
616 async fn resolve_doc(&self, _did: &str) -> Result<Value> {
617 Ok(self.0.clone())
618 }
619 }
620
621 struct FailingResolve;
622 #[async_trait]
623 impl DidDocResolve for FailingResolve {
624 async fn resolve_doc(&self, did: &str) -> Result<Value> {
625 bail!("simulated resolution failure for {did}")
626 }
627 }
628
629 const DID: &str = "did:web:peer.example";
630 const ORIGIN: &str = "https://peer.example";
631
632 // ── Stage 2: extractor sanity ────────────────────────────────────────────
633
634 #[test]
635 fn vm_extraction_returns_published_ed25519_keys() {
636 let k1 = random_ed25519();
637 let k2 = random_ed25519();
638 let doc = did_doc_with_vm(&[k1, k2]);
639 let got = verification_method_ed25519_keys(&doc);
640 assert_eq!(got, vec![k1, k2]);
641 }
642
643 #[test]
644 fn vm_extraction_skips_undecodable_and_non_ed25519() {
645 let good = random_ed25519();
646 let doc = json!({
647 "verificationMethod": [
648 // wrong multibase prefix
649 { "id": "#a", "publicKeyMultibase": "Qbogus" },
650 // a publicKeyJwk-only VM (no multibase) → skipped
651 { "id": "#b", "publicKeyJwk": { "kty": "OKP", "crv": "Ed25519", "x": "AAAA" } },
652 // valid ed25519 Multikey
653 { "id": "#c", "publicKeyMultibase": ed25519_multikey(&good) },
654 ],
655 });
656 assert_eq!(verification_method_ed25519_keys(&doc), vec![good]);
657 }
658
659 #[test]
660 fn vm_extraction_empty_when_no_vm() {
661 assert!(verification_method_ed25519_keys(&json!({ "id": DID })).is_empty());
662 assert!(verification_method_ed25519_keys(&json!({ "verificationMethod": [] })).is_empty());
663 }
664
665 // ── Two-stage gate behavior ──────────────────────────────────────────────
666
667 #[tokio::test]
668 async fn admits_when_application_signer_key_matches_did_vm() {
669 let key = random_ed25519();
670 let gate = FederationAdmissionGate::new(AllowOrigin, FixtureDoc(did_doc_with_vm(&[key])));
671 let admitted = gate
672 .admit(
673 ORIGIN,
674 interop_signer(key),
675 AdmissionTrustSurface::ThirdPartyInterop,
676 DID,
677 None,
678 )
679 .await
680 .expect("matching VM must admit");
681 assert_eq!(admitted.origin, ORIGIN);
682 assert_eq!(admitted.did.as_deref(), Some(DID));
683 assert_eq!(admitted.key, key);
684 }
685
686 #[tokio::test]
687 async fn rejects_when_application_signer_key_mismatches_did_vm() {
688 // Doc publishes a different key than the peer presents.
689 let published = random_ed25519();
690 let peer = random_ed25519();
691 let gate =
692 FederationAdmissionGate::new(AllowOrigin, FixtureDoc(did_doc_with_vm(&[published])));
693 let err = gate
694 .admit(
695 ORIGIN,
696 interop_signer(peer),
697 AdmissionTrustSurface::ThirdPartyInterop,
698 DID,
699 None,
700 )
701 .await
702 .expect_err("mismatched key must reject");
703 assert!(err.to_string().contains("stage 2"), "{err}");
704 }
705
706 #[tokio::test]
707 async fn rejects_when_did_doc_has_no_matching_vm() {
708 // Doc has no verificationMethod at all → no key to match → reject.
709 let peer = random_ed25519();
710 let doc = json!({ "id": DID, "verificationMethod": [], "service": [] });
711 let gate = FederationAdmissionGate::new(AllowOrigin, FixtureDoc(doc));
712 let err = gate
713 .admit(
714 ORIGIN,
715 interop_signer(peer),
716 AdmissionTrustSurface::ThirdPartyInterop,
717 DID,
718 None,
719 )
720 .await
721 .expect_err("no VM must reject");
722 assert!(err.to_string().contains("stage 2"), "{err}");
723 }
724
725 #[tokio::test]
726 async fn rejects_when_origin_denied_before_stage2() {
727 // DenyOrigin rejects at stage 1; the (otherwise matching) DID doc is
728 // never even consulted. Use a FailingResolve to prove stage 2 isn't run:
729 // if it were, the error would be a resolution failure, not a stage-1 one.
730 let peer = random_ed25519();
731 let gate = FederationAdmissionGate::new(DenyOrigin, FailingResolve);
732 let err = gate
733 .admit(
734 ORIGIN,
735 interop_signer(peer),
736 AdmissionTrustSurface::ThirdPartyInterop,
737 DID,
738 None,
739 )
740 .await
741 .expect_err("denied origin must reject");
742 assert!(
743 err.to_string().contains("stage 1"),
744 "expected stage-1 rejection, got: {err}"
745 );
746 assert!(
747 !err.to_string().contains("did not resolve"),
748 "stage 2 must not run: {err}"
749 );
750 }
751
752 #[tokio::test]
753 async fn rejects_when_did_resolution_fails() {
754 let peer = random_ed25519();
755 let gate = FederationAdmissionGate::new(AllowOrigin, FailingResolve);
756 let err = gate
757 .admit(
758 ORIGIN,
759 interop_signer(peer),
760 AdmissionTrustSurface::ThirdPartyInterop,
761 DID,
762 None,
763 )
764 .await
765 .expect_err("resolution failure must reject (fail-closed)");
766 assert!(err.to_string().contains("did not resolve"), "{err}");
767 }
768
769 #[tokio::test]
770 async fn native_surface_rejects_classical_ed25519_before_resolution() {
771 let peer = random_ed25519();
772 let err = admit_key_against_did(
773 &NeverResolve,
774 ORIGIN,
775 interop_signer(peer),
776 AdmissionTrustSurface::Native,
777 &ed25519_to_did_key(&peer),
778 None,
779 None,
780 )
781 .await
782 .expect_err("native admission must require PQ-hybrid assurance");
783 assert!(err.to_string().contains("PQ-hybrid"), "{err}");
784 assert!(err.to_string().contains("downgrade"), "{err}");
785 }
786
787 #[tokio::test]
788 async fn native_surface_accepts_verified_hybrid_proof() {
789 let peer = random_ed25519();
790 let did = ed25519_to_did_key(&peer);
791 let admitted = admit_key_against_did(
792 &NeverResolve,
793 ORIGIN,
794 hybrid_signer(peer),
795 AdmissionTrustSurface::Native,
796 &did,
797 None,
798 None,
799 )
800 .await
801 .expect("hybrid proof satisfies the native assurance floor");
802 assert_eq!(admitted.key, peer);
803 }
804
805 // ── JWKS fallback path ───────────────────────────────────────────────────
806
807 #[tokio::test]
808 async fn admits_via_jwks_fallback_when_no_did_vm_match() {
809 // DID doc has a non-matching VM; the federation JWKS carries the application signer key.
810 let published = random_ed25519();
811 let peer = random_ed25519();
812 let jwks = jwks_with_keys(&[peer]);
813 let gate =
814 FederationAdmissionGate::new(AllowOrigin, FixtureDoc(did_doc_with_vm(&[published])));
815 let admitted = gate
816 .admit(
817 ORIGIN,
818 interop_signer(peer),
819 AdmissionTrustSurface::ThirdPartyInterop,
820 DID,
821 Some(&jwks),
822 )
823 .await
824 .expect("JWKS fallback must admit");
825 // Matched via JWKS, not a specific DID-doc VM.
826 assert_eq!(admitted.did, None);
827 assert_eq!(admitted.key, peer);
828 }
829
830 #[tokio::test]
831 async fn jwks_fallback_still_rejects_unknown_key() {
832 let published = random_ed25519();
833 let jwks_key = random_ed25519();
834 let peer = random_ed25519(); // in neither the doc nor the JWKS
835 let jwks = jwks_with_keys(&[jwks_key]);
836 let gate =
837 FederationAdmissionGate::new(AllowOrigin, FixtureDoc(did_doc_with_vm(&[published])));
838 let err = gate
839 .admit(
840 ORIGIN,
841 interop_signer(peer),
842 AdmissionTrustSurface::ThirdPartyInterop,
843 DID,
844 Some(&jwks),
845 )
846 .await
847 .expect_err("key in neither source must reject");
848 assert!(err.to_string().contains("nor the federation JWKS"), "{err}");
849 }
850
851 #[test]
852 fn no_application_signer_proof_helper_is_fail_closed() {
853 let err = reject_no_application_signer_proof(ORIGIN);
854 assert!(err.to_string().contains("failing closed"), "{err}");
855 assert!(
856 err.to_string().contains("carrier NodeId/EndpointId"),
857 "{err}"
858 );
859 }
860
861 // ── did:key self-certifying arm (#281) ───────────────────────────────────
862
863 use crate::did_web::ed25519_to_did_key;
864
865 /// A resolver that MUST NOT be called: the did:key arm is self-certifying and
866 /// must never fetch/resolve. If the gate calls it, the test fails loudly.
867 struct NeverResolve;
868 #[async_trait]
869 impl DidDocResolve for NeverResolve {
870 async fn resolve_doc(&self, did: &str) -> Result<Value> {
871 panic!("did:key admission must not resolve a DID document (called for {did})");
872 }
873 }
874
875 #[tokio::test]
876 async fn admits_did_key_peer_whose_application_signer_matches() {
877 // Self-certifying: the verified application signer equals the did:key
878 // encodes. No DID-doc resolution — NeverResolve proves the gate never
879 // calls the resolver for a did:key.
880 let key = random_ed25519();
881 let did = ed25519_to_did_key(&key);
882 let gate = FederationAdmissionGate::new(AllowOrigin, NeverResolve);
883 let admitted = gate
884 .admit(
885 ORIGIN,
886 interop_signer(key),
887 AdmissionTrustSurface::ThirdPartyInterop,
888 &did,
889 None,
890 )
891 .await
892 .expect("matching did:key must admit (self-certifying)");
893 assert_eq!(admitted.origin, ORIGIN);
894 assert_eq!(admitted.did.as_deref(), Some(did.as_str()));
895 assert_eq!(admitted.key, key);
896 }
897
898 #[tokio::test]
899 async fn rejects_did_key_peer_on_key_mismatch() {
900 // The peer presents a different key than the did:key identity encodes.
901 let identity = random_ed25519();
902 let peer = random_ed25519();
903 let did = ed25519_to_did_key(&identity);
904 let gate = FederationAdmissionGate::new(AllowOrigin, NeverResolve);
905 let err = gate
906 .admit(
907 ORIGIN,
908 interop_signer(peer),
909 AdmissionTrustSurface::ThirdPartyInterop,
910 &did,
911 None,
912 )
913 .await
914 .expect_err("mismatched did:key must reject");
915 assert!(err.to_string().contains("stage 2"), "{err}");
916 assert!(err.to_string().contains("self-certifying"), "{err}");
917 }
918
919 #[tokio::test]
920 async fn did_key_still_enforces_stage1_origin() {
921 // Even a self-certifying did:key whose key would match must be rejected
922 // when stage 1 (origin) denies — stage 1 runs first and the did:key arm
923 // is never reached (NeverResolve also guards against any resolve attempt).
924 let key = random_ed25519();
925 let did = ed25519_to_did_key(&key);
926 let gate = FederationAdmissionGate::new(DenyOrigin, NeverResolve);
927 let err = gate
928 .admit(
929 ORIGIN,
930 interop_signer(key),
931 AdmissionTrustSurface::ThirdPartyInterop,
932 &did,
933 None,
934 )
935 .await
936 .expect_err("denied origin must reject a did:key peer");
937 assert!(
938 err.to_string().contains("stage 1"),
939 "expected stage-1 rejection, got: {err}"
940 );
941 }
942
943 #[tokio::test]
944 async fn rejects_invalid_did_key_fail_closed() {
945 // A malformed did:key (ed25519-pub multicodec absent / wrong) must fail
946 // closed without resolving.
947 let peer = random_ed25519();
948 let bad_did = "did:key:zNotAValidEd25519Multikey";
949 let gate = FederationAdmissionGate::new(AllowOrigin, NeverResolve);
950 let err = gate
951 .admit(
952 ORIGIN,
953 interop_signer(peer),
954 AdmissionTrustSurface::ThirdPartyInterop,
955 bad_did,
956 None,
957 )
958 .await
959 .expect_err("invalid did:key must reject (fail-closed)");
960 assert!(err.to_string().contains("stage 2"), "{err}");
961 }
962
963 // ── did:at9p self-certifying hybrid arm (D2/#894) ──────────────────────────
964
965 use crate::crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes};
966 use crate::envelope::PqTrustStore;
967 use crate::identity_resolver::{At9pCapsuleResolver, VerifiedAt9pKeys};
968
969 const AT9P_DID: &str = "did:at9p:fakecid512";
970
971 /// A capsule gate test double: returns a fixed [`VerifiedAt9pKeys`] on
972 /// `verify_bytes`, or `Err` when `fail` is set (simulating a GATE rejection —
973 /// bad sig / wrong cid). The real GATE lives in `hyprstream-pds`
974 /// (`at9p_resolver::At9pGateResolver`); this fixture keeps the arm testable in
975 /// the lower rpc crate without a pds dependency.
976 struct FixtureGate {
977 keys: VerifiedAt9pKeys,
978 fail: bool,
979 }
980
981 impl At9pCapsuleResolver for FixtureGate {
982 fn verify_bytes(&self, _did: &str, _capsule_bytes: &[u8]) -> Result<VerifiedAt9pKeys> {
983 if self.fail {
984 bail!("simulated GATE failure (bad sig / wrong cid)");
985 }
986 Ok(self.keys.clone())
987 }
988 }
989
990 fn verified_subject(ed: [u8; 32]) -> VerifiedAt9pKeys {
991 let (_sk, vk) = ml_dsa_generate_keypair();
992 VerifiedAt9pKeys::new_gate_verified(ed, vk)
993 }
994
995 #[tokio::test]
996 async fn admits_did_at9p_peer_and_binds_hybrid_keys_from_capsule() {
997 // Valid capsule → GATE passes → the verified ed25519→ml_dsa_65 pair is
998 // bound into KeyedPqTrustStore, atomic hybrid binding from content-verified
999 // material (no config trust).
1000 let ed = random_ed25519();
1001 let keys = verified_subject(ed);
1002 let gate = FixtureGate {
1003 keys: keys.clone(),
1004 fail: false,
1005 };
1006 let mut store = KeyedPqTrustStore::new();
1007 assert!(store.is_empty(), "store starts empty (no config trust)");
1008
1009 let admitted = admit_key_against_did(
1010 &NeverResolve,
1011 ORIGIN,
1012 hybrid_signer(ed),
1013 AdmissionTrustSurface::Native,
1014 AT9P_DID,
1015 None,
1016 Some(At9pAdmission {
1017 capsule_bytes: b"<capsule>",
1018 gate: &gate,
1019 pq_store: &mut store,
1020 }),
1021 )
1022 .await
1023 .expect("verified capsule must admit");
1024
1025 assert_eq!(admitted.did.as_deref(), Some(AT9P_DID));
1026 assert_eq!(admitted.key, ed);
1027 // The binding is exactly the capsule's verified keys — comes from the
1028 // capsule, not config.
1029 assert_eq!(store.len(), 1, "exactly one hybrid binding installed");
1030 let bound = store.ml_dsa_key_for(&ed).expect("ed25519→ml_dsa_65 bound");
1031 assert_eq!(
1032 ml_dsa_vk_bytes(&bound),
1033 ml_dsa_vk_bytes(keys.keys()[0].ml_dsa_65())
1034 );
1035 }
1036
1037 #[tokio::test]
1038 async fn rejects_did_at9p_on_gate_failure_and_binds_nothing() {
1039 // A capsule that fails GATE (bad sig / wrong cid) → reject, and crucially
1040 // NOTHING is bound into the trust store (no downgrade, no partial trust).
1041 let ed = random_ed25519();
1042 let gate = FixtureGate {
1043 keys: verified_subject(ed),
1044 fail: true,
1045 };
1046 let mut store = KeyedPqTrustStore::new();
1047
1048 let err = admit_key_against_did(
1049 &NeverResolve,
1050 ORIGIN,
1051 hybrid_signer(ed),
1052 AdmissionTrustSurface::Native,
1053 AT9P_DID,
1054 None,
1055 Some(At9pAdmission {
1056 capsule_bytes: b"<capsule>",
1057 gate: &gate,
1058 pq_store: &mut store,
1059 }),
1060 )
1061 .await
1062 .expect_err("GATE failure must reject (fail-closed)");
1063 assert!(err.to_string().contains("stage 2"), "{err}");
1064 assert!(err.to_string().contains("GATE"), "{err}");
1065 assert!(store.is_empty(), "a rejected capsule must bind nothing");
1066 }
1067
1068 #[tokio::test]
1069 async fn rejects_did_at9p_on_application_signer_mismatch_and_binds_nothing() {
1070 // The capsule verifies, but the application signer is not the capsule's
1071 // Ed25519 subject key, so reject and bind nothing.
1072 let identity = random_ed25519();
1073 let peer = random_ed25519();
1074 assert_ne!(identity, peer);
1075 let gate = FixtureGate {
1076 keys: verified_subject(identity),
1077 fail: false,
1078 };
1079 let mut store = KeyedPqTrustStore::new();
1080
1081 let err = admit_key_against_did(
1082 &NeverResolve,
1083 ORIGIN,
1084 hybrid_signer(peer),
1085 AdmissionTrustSurface::Native,
1086 AT9P_DID,
1087 None,
1088 Some(At9pAdmission {
1089 capsule_bytes: b"<capsule>",
1090 gate: &gate,
1091 pq_store: &mut store,
1092 }),
1093 )
1094 .await
1095 .expect_err("application-signer mismatch must reject");
1096 assert!(err.to_string().contains("stage 2"), "{err}");
1097 assert!(store.is_empty(), "a mismatched peer must bind nothing");
1098 }
1099
1100 #[tokio::test]
1101 async fn rejects_did_at9p_without_an_admission_context() {
1102 // did:at9p presented but no capsule/admission context supplied (the live
1103 // accept path does not feed bytes yet) → fail closed.
1104 let peer = random_ed25519();
1105 let err = admit_key_against_did(
1106 &NeverResolve,
1107 ORIGIN,
1108 hybrid_signer(peer),
1109 AdmissionTrustSurface::Native,
1110 AT9P_DID,
1111 None,
1112 None,
1113 )
1114 .await
1115 .expect_err("missing capsule context must reject");
1116 assert!(err.to_string().contains("stage 2"), "{err}");
1117 assert!(err.to_string().contains("fail-closed"), "{err}");
1118 }
1119
1120 #[tokio::test]
1121 async fn did_at9p_still_enforces_stage1_origin() {
1122 // Stage 1 (origin) runs first; a denied origin rejects before the at9p arm.
1123 let ed = random_ed25519();
1124 let gate = FederationAdmissionGate::new(DenyOrigin, NeverResolve);
1125 let err = gate
1126 .admit(
1127 ORIGIN,
1128 hybrid_signer(ed),
1129 AdmissionTrustSurface::Native,
1130 AT9P_DID,
1131 None,
1132 )
1133 .await
1134 .expect_err("denied origin must reject a did:at9p peer");
1135 // gate.admit passes None for the at9p context, so stage 1's denial is what
1136 // surfaces (stage 2 never runs).
1137 assert!(
1138 err.to_string().contains("stage 1"),
1139 "expected stage-1 rejection, got: {err}"
1140 );
1141 }
1142}