hyprstream_pds/at9p_alias.rs
1//! Authoritative direction for `did:web` / `did:key` ↔ `did:at9p` aliasing
2//! (#896 / D4; design #879 Q4, ratified #905 §2/§6).
3//!
4//! This is the **pure, I/O-free core** of the D4 aliasing bridge — the rule
5//! that decides, given a classical DID's `alsoKnownAs` claim and a
6//! GATE-verified [`VerifiedCapsule`], whether the two identities are *mutually*
7//! attested and — when they are — which one is authoritative. The I/O half
8//! (fetch the capsule bytes from an untrusted locator, run GATE) composes this
9//! rule and lives in `hyprstream-discovery::at9p_alias`, sibling to the D1
10//! capsule resolver.
11//!
12//! # The authoritative-direction rule
13//!
14//! A `did:web` / `did:key` identity can declare (via `alsoKnownAs`) that it is
15//! *also* a `did:at9p`. The reverse vouch lives inside the at9p capsule body
16//! (the [`CapsuleBody::also_known_as`] field, #896 schema). Two legs therefore
17//! exist, of **different strength**:
18//!
19//! | leg | carrier | signature strength |
20//! |-----|---------|--------------------|
21//! | at9p → classical | the GATE-verified capsule body's `alsoKnownAs` | **Hybrid** (EdDSA + ML-DSA-65, pinned) |
22//! | classical → at9p | the classical DID document's `alsoKnownAs` | **Classical** (the doc's best) |
23//!
24//! The ratified semantics (#905 §2/§6) are:
25//!
26//! 1. **Bidirectional to be believed.** Both documents must name each other. A
27//! one-way claim is not trusted → [`Err`].
28//! 2. **at9p is authoritative.** The content-verified capsule (BLAKE3-512
29//! self-certifying, hybrid-signed) is the stronger identity. When the
30//! attestation is mutual, the at9p identity is authoritative at `PqHybrid`
31//! assurance — the assurance of the capsule leg actually walked.
32//! 3. **Assurance = the leg walked, never the max.** A verifier reaching the
33//! identity *through* the classical leg lands `Classical`; reaching it
34//! *through* the GATE-verified capsule lands `PqHybrid`. This rule is only
35//! ever evaluated with a [`VerifiedCapsule`] in hand (the capsule leg was
36//! walked), so its result is `PqHybrid`.
37//!
38//! at9p is the PQ **upgrade path**, additive to — not a replacement for — a
39//! principal's classical atproto identity (the method-allowlist bridge: public
40//! atproto infra accepts only `did:plc`/`did:web` as repo authorities, so
41//! public records publish under the classical DID with `alsoKnownAs` to the
42//! at9p identity; our own PDS accepts `did:at9p` natively, #908/G3).
43
44use anyhow::{ensure, Result};
45
46use hyprstream_rpc::auth::mac::Assurance;
47use hyprstream_rpc::identity::Did;
48
49use crate::at9p_gate::VerifiedCapsule;
50
51/// The authoritative identity resolved through the at9p aliasing bridge.
52///
53/// Produced by [`resolve_authoritative_alias`] only when a classical DID and a
54/// GATE-verified `did:at9p` capsule mutually attest each other. The at9p
55/// identity is authoritative; `assurance` is `PqHybrid` (the capsule leg).
56#[derive(Clone, Debug, Eq, PartialEq)]
57pub struct AuthoritativeIdentity {
58 /// The content-verified `did:at9p:<cid512>` — the stronger identity.
59 pub at9p_did: Did,
60 /// The classical DID that bidirectionally attests to the at9p identity.
61 pub classical_did: Did,
62 /// The assurance established: `PqHybrid` (reached via the GATE-verified
63 /// capsule leg — never the classical leg's best).
64 pub assurance: Assurance,
65}
66
67/// Resolve the authoritative identity for `classical_did` via mutual
68/// `alsoKnownAs` attestation with a GATE-verified `did:at9p` capsule.
69///
70/// - `classical_did` — the classical (`did:web` / `did:key` / `did:plc`)
71/// identity the caller reached.
72/// - `classical_aka_at9p` — the **classical leg's** claim: the `did:at9p` the
73/// classical DID document names in its own `alsoKnownAs`. Classical-signed,
74/// best-effort.
75/// - `verified` — the **capsule leg**: the [`VerifiedCapsule`] fetched for
76/// `classical_aka_at9p` and passed by the GATE pipeline. Its own
77/// `alsoKnownAs` is the hybrid-signed reciprocal vouch.
78///
79/// Returns the authoritative at9p identity at `PqHybrid` assurance when both
80/// legs name each other; **fail-closed** (`Err`) on any one-way or
81/// unattested claim. See the module docs for the full rule.
82pub fn resolve_authoritative_alias(
83 classical_did: &Did,
84 classical_aka_at9p: &Did,
85 verified: &VerifiedCapsule,
86) -> Result<AuthoritativeIdentity> {
87 // The capsule is the authoritative leg — its did is the stronger identity.
88 let at9p_did = Did::new(verified.did());
89
90 // Leg 1 (classical): the classical DID document names THIS capsule as its
91 // at9p alias. A classical leg pointing at a different capsule is a one-way
92 // (or cross-identity) claim — fail-closed.
93 ensure!(
94 classical_aka_at9p == &at9p_did,
95 "aliasing bridge: classical leg {} does not name the verified capsule {} \
96 (one-way claim — fail-closed)",
97 classical_aka_at9p,
98 at9p_did,
99 );
100
101 // Leg 2 (hybrid): the GATE-verified capsule reciprocally names the
102 // classical DID in its alsoKnownAs. Exact string match is the
103 // conservative, fail-closed choice (no normalization that could widen trust).
104 let reciprocated = capsule_names(verified, classical_did);
105 ensure!(
106 reciprocated,
107 "aliasing bridge: verified capsule {} does not name {} in its alsoKnownAs \
108 (one-way claim — fail-closed)",
109 at9p_did,
110 classical_did,
111 );
112
113 Ok(AuthoritativeIdentity {
114 at9p_did,
115 classical_did: classical_did.clone(),
116 // The capsule leg was walked ⇒ PqHybrid. Never the classical leg's max.
117 assurance: Assurance::PqHybrid,
118 })
119}
120
121/// Whether a verified capsule's `alsoKnownAs` names `did`.
122fn capsule_names(verified: &VerifiedCapsule, did: &Did) -> bool {
123 verified
124 .capsule()
125 .body
126 .also_known_as
127 .as_deref()
128 .unwrap_or(&[])
129 .iter()
130 .any(|alias| Did::new(alias.clone()) == *did)
131}
132
133/// The classical aliases a verified `did:at9p` capsule attests to — the
134/// **method-allowlist bridge** (#905 §6).
135///
136/// Public atproto infra (PLC directory, Bluesky, Tangled) allowlists only
137/// `did:plc` / `did:web` as repo authorities, so public `at://` records
138/// publish under the classical DID with `alsoKnownAs` to the `did:at9p`
139/// identity. This accessor projects a verified capsule back to those classical
140/// aliases — the at9p → classical direction — so a holder can publish under a
141/// classical authority while the at9p identity remains the PQ upgrade path.
142/// Returned in the capsule's declared order.
143pub fn classical_aliases(verified: &VerifiedCapsule) -> Vec<Did> {
144 verified
145 .capsule()
146 .body
147 .also_known_as
148 .as_deref()
149 .unwrap_or(&[])
150 .iter()
151 .map(|alias| Did::new(alias.clone()))
152 .collect()
153}
154
155#[cfg(test)]
156#[allow(clippy::unwrap_used, clippy::expect_used)]
157mod tests {
158 use super::*;
159 use crate::at9p::{
160 CapsuleBody, HybridKeyPair, ServiceEndpoint, ServiceEntry, ServiceType, Transport,
161 };
162 use crate::at9p_gate::verify_did_at9p;
163 use crate::at9p_sign::sign_capsule;
164
165 use ed25519_dalek::SigningKey;
166 use hyprstream_crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes, MlDsaSigningKey};
167
168 struct Signer {
169 ed_sk: SigningKey,
170 pq_sk: MlDsaSigningKey,
171 keypair: HybridKeyPair,
172 }
173
174 fn signer(tag: u8) -> Signer {
175 let mut seed = [0u8; 32];
176 seed[0] = tag;
177 seed[31] = tag.wrapping_add(7);
178 let ed_sk = SigningKey::from_bytes(&seed);
179 let (pq_sk, pq_vk) = ml_dsa_generate_keypair();
180 let keypair = HybridKeyPair::new(
181 ed_sk.verifying_key().to_bytes().to_vec(),
182 ml_dsa_vk_bytes(&pq_vk),
183 )
184 .unwrap();
185 Signer {
186 ed_sk,
187 pq_sk,
188 keypair,
189 }
190 }
191
192 /// Build a GATE-verified capsule that attests `aliases` as its classical
193 /// `alsoKnownAs`, returning (verified, did).
194 fn verified_with_aliases(aliases: Vec<String>) -> (VerifiedCapsule, String) {
195 let s = signer(1);
196 let endpoint = ServiceEndpoint::new(Transport::Iroh, "iroh://node1").unwrap();
197 let service = ServiceEntry::new("#ns", ServiceType::NinePExport, endpoint).unwrap();
198 let mut body = CapsuleBody::new(vec![s.keypair.clone()], vec![service]).unwrap();
199 if !aliases.is_empty() {
200 body.also_known_as = Some(aliases);
201 }
202 let capsule = sign_capsule(body, &s.ed_sk, &s.pq_sk).unwrap();
203 let bytes = capsule.to_dag_cbor().unwrap();
204 let did = format!("did:at9p:{}", capsule.cid512().unwrap());
205 let verified = verify_did_at9p(&did, &bytes).unwrap();
206 (verified, did)
207 }
208
209 #[test]
210 fn mutual_attestation_resolves_authoritative_at9p_at_pqhybrid() {
211 let classical = Did::new("did:web:node.example".to_owned());
212 // Capsule attests the classical alias (hybrid leg).
213 let (verified, did) = verified_with_aliases(vec![classical.as_str().to_owned()]);
214 let at9p = Did::new(did.clone());
215 // Classical leg names the capsule (classical leg).
216 let res = resolve_authoritative_alias(&classical, &at9p, &verified).unwrap();
217 assert_eq!(res.at9p_did, at9p);
218 assert_eq!(res.classical_did, classical);
219 assert_eq!(res.assurance, Assurance::PqHybrid);
220 }
221
222 #[test]
223 fn one_way_classical_claim_fails_closed() {
224 let classical = Did::new("did:web:node.example".to_owned());
225 let (verified, _did) = verified_with_aliases(vec![classical.as_str().to_owned()]);
226 // Classical leg names a DIFFERENT capsule than the one verified.
227 let other = Did::new("did:at9p:bafyDIFFERENT".to_owned());
228 let err = resolve_authoritative_alias(&classical, &other, &verified).unwrap_err();
229 assert!(
230 err.to_string()
231 .contains("does not name the verified capsule"),
232 "{err}"
233 );
234 }
235
236 #[test]
237 fn one_way_capsule_claim_fails_closed() {
238 // Capsule attests alice; the classical DID reaching us is bob — the
239 // capsule does not reciprocate bob.
240 let (verified, did) = verified_with_aliases(vec!["did:web:alice.example".to_owned()]);
241 let at9p = Did::new(did);
242 let bob = Did::new("did:web:bob.example".to_owned());
243 let err = resolve_authoritative_alias(&bob, &at9p, &verified).unwrap_err();
244 assert!(err.to_string().contains("does not name"), "{err}");
245 }
246
247 #[test]
248 fn capsule_with_no_aliases_fails_closed() {
249 let (verified, did) = verified_with_aliases(Vec::new()); // no aliases
250 let at9p = Did::new(did);
251 let classical = Did::new("did:web:node.example".to_owned());
252 let err = resolve_authoritative_alias(&classical, &at9p, &verified).unwrap_err();
253 assert!(err.to_string().contains("does not name"), "{err}");
254 }
255
256 #[test]
257 fn classical_aliases_project_method_allowlist_bridge() {
258 let a = "did:web:node.example".to_owned();
259 let b = "did:key:z6Mkalias".to_owned();
260 let (verified, _did) = verified_with_aliases(vec![a.clone(), b.clone()]);
261 let aliases = classical_aliases(&verified);
262 assert_eq!(
263 aliases,
264 vec![Did::new(a), Did::new(b)],
265 "projected in declared order"
266 );
267 }
268}