Skip to main content

hyprstream_discovery/
at9p_alias.rs

1//! `did:web` / `did:key` → `did:at9p` aliasing resolver (#896 / D4; design
2//! #879 Q4, #905 §2/§6).
3//!
4//! This is the **I/O half** of the D4 aliasing bridge. It composes the
5//! untrusted [`CapsuleSource`] + GATE pipeline (D1 / #893) with the pure
6//! authoritative-direction rule (`hyprstream_pds::at9p_alias`) to resolve a
7//! classical DID to its authoritative `did:at9p` identity when — and only when
8//! — the two are mutually `alsoKnownAs`-attested. Sibling to
9//! [`crate::at9p_resolver::At9pResolver`]: where that turns a `did:at9p` into
10//! dialable reach, this turns a classical DID + its at9p claim into the
11//! authoritative at9p *identity* (and its assurance).
12//!
13//! # Fail-closed posture
14//!
15//! An authoritative identity is emitted **only** when:
16//!
17//! 1. the capsule named by the classical leg fetches and passes the full GATE
18//!    pipeline (canon → hash → sig), and
19//! 2. both legs name each other (mutual attestation).
20//!
21//! Any GATE failure, a classical leg pointing at a different capsule, or a
22//! capsule that does not reciprocate the classical DID returns `Err` — never a
23//! partial or one-way trust upgrade. See `hyprstream_pds::at9p_alias` for the
24//! authoritative-direction rule and the two-leg strength table.
25
26use std::sync::Arc;
27
28use anyhow::Result;
29
30use hyprstream_pds::at9p_alias::{resolve_authoritative_alias, AuthoritativeIdentity};
31use hyprstream_pds::at9p_gate::{verify_did_at9p, VerifiedCapsule};
32use hyprstream_rpc::identity::Did;
33
34use crate::at9p_resolver::CapsuleSource;
35
36/// `did:web` / `did:key` → `did:at9p` aliasing resolver.
37///
38/// Wraps an untrusted [`CapsuleSource`] (the mainline locator is the production
39/// implementation) and resolves a classical DID to its authoritative at9p
40/// identity via mutual `alsoKnownAs` attestation + the GATE pipeline.
41pub struct At9pAliasResolver {
42    source: Arc<dyn CapsuleSource>,
43}
44
45impl At9pAliasResolver {
46    /// Build an aliasing resolver over an untrusted capsule source.
47    pub fn new(source: Arc<dyn CapsuleSource>) -> Self {
48        Self { source }
49    }
50
51    /// Resolve `classical_did` to its authoritative `did:at9p` identity.
52    ///
53    /// `classical_aka_at9p` is the **classical leg's** claim — the `did:at9p`
54    /// identifier the classical DID document names in its own `alsoKnownAs`
55    /// (classical-signed, best-effort). This fetches the capsule for that at9p
56    /// DID from the (untrusted) source, runs the full GATE pipeline over the
57    /// bytes, and applies the mutual-attestation / authoritative-direction rule.
58    ///
59    /// Fails closed at the first GATE failure or any one-way / unattested
60    /// claim. On success the at9p identity is authoritative at `PqHybrid`
61    /// assurance (the capsule leg walked).
62    pub async fn resolve_authoritative(
63        &self,
64        classical_did: &Did,
65        classical_aka_at9p: &Did,
66    ) -> Result<AuthoritativeIdentity> {
67        Ok(self
68            .resolve_authoritative_with_capsule(classical_did, classical_aka_at9p)
69            .await?
70            .0)
71    }
72
73    /// Resolve a mutually-attested identity and retain the exact GATE witness.
74    ///
75    /// Consumers that install trust material must source it from this verified
76    /// capsule, not from the classical DID document that only supplies the
77    /// reciprocal identifier vouch.
78    pub async fn resolve_authoritative_with_capsule(
79        &self,
80        classical_did: &Did,
81        classical_aka_at9p: &Did,
82    ) -> Result<(AuthoritativeIdentity, VerifiedCapsule)> {
83        let did_str = classical_aka_at9p.as_str();
84        // The locator derives zero authority — GATE is what makes the bytes
85        // trustworthy, not the source.
86        let bytes = self.source.fetch_capsule(did_str).await?;
87        // GATE — canon → hash → sig. The only place capsule authority is granted.
88        let verified = verify_did_at9p(did_str, &bytes)?;
89        // Authoritative-direction rule — mutual attestation or fail closed.
90        let identity = resolve_authoritative_alias(classical_did, classical_aka_at9p, &verified)?;
91        Ok((identity, verified))
92    }
93}
94
95#[cfg(test)]
96#[allow(clippy::unwrap_used, clippy::expect_used)]
97mod tests {
98    use super::*;
99    use crate::at9p_resolver::CapsuleSource;
100
101    use ed25519_dalek::SigningKey;
102    use hyprstream_crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes, MlDsaSigningKey};
103    use hyprstream_pds::at9p::{
104        CapsuleBody, HybridKeyPair, ServiceEndpoint, ServiceEntry, ServiceType, Transport,
105    };
106    use hyprstream_pds::at9p_sign::sign_capsule;
107    use hyprstream_rpc::auth::mac::Assurance;
108
109    /// Serve a fixed capsule's bytes for any requested did.
110    struct FixedSource {
111        bytes: Vec<u8>,
112    }
113
114    #[async_trait::async_trait]
115    impl CapsuleSource for FixedSource {
116        async fn fetch_capsule(&self, _did: &str) -> Result<Vec<u8>> {
117            Ok(self.bytes.clone())
118        }
119    }
120
121    struct Signer {
122        ed_sk: SigningKey,
123        pq_sk: MlDsaSigningKey,
124        keypair: HybridKeyPair,
125    }
126
127    fn signer(tag: u8) -> Signer {
128        let mut seed = [0u8; 32];
129        seed[0] = tag;
130        seed[31] = tag.wrapping_add(7);
131        let ed_sk = SigningKey::from_bytes(&seed);
132        let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
133        let keypair = HybridKeyPair::new(
134            ed_sk.verifying_key().to_bytes().to_vec(),
135            ml_dsa_vk_bytes(&pq_vk),
136        )
137        .unwrap();
138        Signer {
139            ed_sk,
140            pq_sk,
141            keypair,
142        }
143    }
144
145    /// A signed capsule that attests `aliases`, its bytes, and its did.
146    fn signed_with_aliases(aliases: Vec<String>) -> (Vec<u8>, String) {
147        let s = signer(5);
148        let endpoint = ServiceEndpoint::new(Transport::Iroh, "iroh://node5").unwrap();
149        let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
150        let mut body = CapsuleBody::new(vec![s.keypair.clone()], vec![service]).unwrap();
151        if !aliases.is_empty() {
152            body.also_known_as = Some(aliases);
153        }
154        let capsule = sign_capsule(body, &s.ed_sk, &s.pq_sk).unwrap();
155        let bytes = capsule.to_dag_cbor().unwrap();
156        let did = format!("did:at9p:{}", capsule.cid512().unwrap());
157        (bytes, did)
158    }
159
160    #[tokio::test]
161    async fn resolver_mutual_attestation_yields_authoritative_at9p() {
162        let classical = Did::new("did:web:node.example".to_owned());
163        let (bytes, did) = signed_with_aliases(vec![classical.as_str().to_owned()]);
164        let at9p = Did::new(did);
165        let resolver = At9pAliasResolver::new(Arc::new(FixedSource { bytes }));
166        let res = resolver
167            .resolve_authoritative(&classical, &at9p)
168            .await
169            .unwrap();
170        assert_eq!(res.at9p_did, at9p);
171        assert_eq!(res.classical_did, classical);
172        assert_eq!(res.assurance, Assurance::PqHybrid);
173    }
174
175    #[tokio::test]
176    async fn resolver_one_way_capsule_claim_fails_closed() {
177        // Capsule attests alice, but we reach it claiming to be bob.
178        let (bytes, did) = signed_with_aliases(vec!["did:web:alice.example".to_owned()]);
179        let at9p = Did::new(did);
180        let bob = Did::new("did:web:bob.example".to_owned());
181        let resolver = At9pAliasResolver::new(Arc::new(FixedSource { bytes }));
182        let err = resolver
183            .resolve_authoritative(&bob, &at9p)
184            .await
185            .unwrap_err();
186        assert!(err.to_string().contains("does not name"), "{err}");
187    }
188
189    #[tokio::test]
190    async fn resolver_classical_leg_pointing_elsewhere_fails_closed() {
191        // Capsule genuinely attests the classical DID, but the classical leg
192        // names a DIFFERENT valid at9p identity than the one the source serves.
193        let classical = Did::new("did:web:node.example".to_owned());
194        let (bytes, _did) = signed_with_aliases(vec![classical.as_str().to_owned()]);
195        // A second, genuinely-valid capsule → a real distinct did:at9p cid512.
196        let (_other_bytes, other_did) = signed_with_aliases(Vec::new());
197        let wrong_at9p = Did::new(other_did);
198        let resolver = At9pAliasResolver::new(Arc::new(FixedSource { bytes }));
199        let err = resolver
200            .resolve_authoritative(&classical, &wrong_at9p)
201            .await
202            .unwrap_err();
203        // GATE hash-gate rejects (the served bytes hash to a different cid) before
204        // the aliasing rule ever runs — the classical leg's claim is not believed.
205        let msg = err.to_string();
206        assert!(
207            msg.contains("hash-gate") || msg.contains("does not name the verified capsule"),
208            "expected GATE or aliasing rejection, got: {msg}"
209        );
210    }
211}