hyprstream_rpc/identity.rs
1//! Identity provider abstraction for unified key management.
2//!
3//! Three implementations cover the trust boundaries:
4//! - `NodeIdentityProvider` — native server/CLI (file + keyring)
5//! - `AegisIdentityProvider` — browser (aegis-vault via JS callback)
6//! - `FederatedIdentityProvider` — cross-node (entity statements)
7//!
8//! HKDF derivation: `HKDF(root_seed, purpose_bytes)` — no prefix.
9//! The purpose string IS the domain separator.
10
11use std::fmt;
12use std::str::FromStr;
13
14use anyhow::Result;
15use async_trait::async_trait;
16
17use crate::auth::mac::Assurance;
18use crate::crypto::pq::MlDsaVerifyingKey;
19use serde::{Deserialize, Serialize};
20
21use crate::Subject;
22
23/// A W3C Decentralized Identifier (`did:key:…`, `did:web:…`, …), carried on capnp wires as
24/// `Text` (W3C DID strings — see <https://www.w3.org/TR/did-core/>) and mapped to this Rust
25/// newtype via a field-level `$domainType("hyprstream_rpc::identity::Did")` annotation. The
26/// generated ToCapnp/FromCapnp impls write via [`Did::as_str`] and read via [`Did::new`].
27///
28/// Construction is **lenient** — [`Did::new`] performs no validation, so deserializing a
29/// malformed wire value never fails at the boundary. **Strict validation lives at the
30/// admission gate** (`crate::admission`); this type is a typed string, not a policy check.
31///
32/// `did:key` is the self-certifying interop arm (the key *is* the identity; algorithm-agile
33/// via multicodec and iroh-convertible), while `did:web` covers operated nodes whose keys
34/// live as DID-document verification methods.
35///
36/// Wire representation is `Text`; serde (de)serializes transparently as the inner string.
37/// Cloneable, hashable, orderable (lexicographic on the inner string), and usable as a map
38/// key — including ordered maps / `TtlCache<Did, _>` (#524 placement liveness directory).
39/// `Default` yields an empty DID (`Did("")`) — the generated capnp data structs that carry a
40/// `Did` field derive `Default`, and an absent `Text` field reads back as the empty string.
41#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
42pub struct Did(String);
43
44/// The `did:at9p:` method prefix — the single source of truth for the
45/// self-certifying hybrid-PQC capsule identity (#879/#880). A `did:at9p`
46/// identifier is this prefix followed by the base32 CIDv1 (`cid512`) of the
47/// genesis capsule (#884).
48///
49/// Shared by the admission gate (`crate::admission`), this method check
50/// ([`Did::is_did_at9p`]), and the GATE/capsule code in `hyprstream-pds`
51/// (`at9p_gate`) so the literal cannot drift across the three arms (D2/#964).
52pub const DID_AT9P_PREFIX: &str = "did:at9p:";
53
54/// Reserved sentinel naming the credential-absence floor.
55///
56/// This string is not a DID subject: it has no keys, document, genesis
57/// operation, hosted account, or local tenant. Clients cannot authenticate as
58/// it; servers apply the unauthenticated floor only when no credential is
59/// presented. Identity directories, federation intake, and inventory read
60/// models must reject or omit it rather than treating it as a real identity.
61pub const UNAUTHENTICATED_DID_SENTINEL: &str = "did:unknown";
62
63impl Did {
64 /// Wrap a DID string verbatim. **No validation** — strict checks belong at the
65 /// admission gate (see the type docs).
66 pub fn new(did: String) -> Self {
67 Did(did)
68 }
69
70 /// Borrow the underlying DID string.
71 pub fn as_str(&self) -> &str {
72 self.0.as_str()
73 }
74
75 /// Consume the newtype, returning the owned DID string.
76 pub fn into_string(self) -> String {
77 self.0
78 }
79
80 /// Whether this is a `did:key` identifier (the self-certifying interop arm).
81 pub fn is_did_key(&self) -> bool {
82 // `did_web` is native-only; mirror its canonical check on wasm so the API is
83 // uniform across targets. The two implementations are intentionally identical.
84 #[cfg(not(target_arch = "wasm32"))]
85 {
86 crate::did_web::is_did_key(self.0.as_str())
87 }
88 #[cfg(target_arch = "wasm32")]
89 {
90 self.0.starts_with("did:key:")
91 }
92 }
93
94 /// Whether this is a `did:web` identifier (operated nodes resolved via DID document).
95 pub fn is_did_web(&self) -> bool {
96 self.0.starts_with("did:web:")
97 }
98
99 /// Whether this is a `did:at9p` identifier — the PQC-hybrid, self-certifying
100 /// identity (`did:at9p:<cid512>`, #879). The authoritative end of the
101 /// `alsoKnownAs` aliasing bridge (#896 / D4): when a `did:web` / `did:key`
102 /// and a `did:at9p` mutually attest each other, the content-verified at9p
103 /// capsule is the stronger identity.
104 ///
105 /// The capsule GATE pipeline that verifies a `did:at9p` and derives its
106 /// `PqHybrid` key material is epic #880 (D2); the method-dispatched resolver
107 /// reserves the arm but does not yet resolve it (fails closed until #894).
108 pub fn is_did_at9p(&self) -> bool {
109 self.0.starts_with(DID_AT9P_PREFIX)
110 }
111
112 /// Decode the raw 32-byte Ed25519 public key from a `did:key` identifier.
113 ///
114 /// Returns `Err` for a non-`did:key` DID, a non-Ed25519 multicodec, or a malformed body.
115 pub fn to_ed25519(&self) -> Result<[u8; 32]> {
116 crate::did_key::did_key_to_ed25519(self.0.as_str())
117 }
118
119 /// Construct a `did:key` (Ed25519) identifier from a raw 32-byte public key.
120 pub fn from_ed25519(key: &[u8; 32]) -> Self {
121 Did(crate::did_key::ed25519_to_did_key(key))
122 }
123}
124
125impl fmt::Display for Did {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 f.write_str(&self.0)
128 }
129}
130
131impl FromStr for Did {
132 /// Parsing is infallible — construction is lenient (see [`Did::new`]).
133 type Err = std::convert::Infallible;
134
135 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
136 Ok(Did(s.to_owned()))
137 }
138}
139
140impl From<String> for Did {
141 fn from(s: String) -> Self {
142 Did(s)
143 }
144}
145
146impl From<&str> for Did {
147 fn from(s: &str) -> Self {
148 Did(s.to_owned())
149 }
150}
151
152/// A purpose-keyed signing identity derived from a root seed.
153///
154/// Holds a derived Ed25519 keypair for a specific purpose (e.g.,
155/// `"hyprstream-rpc-envelope-v1"`). The private key never leaves
156/// the identity provider — callers get the pubkey and a sign function.
157#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
158#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
159pub trait SigningIdentity: Send + Sync {
160 /// 32-byte Ed25519 public key for this purpose.
161 fn pubkey(&self) -> [u8; 32];
162
163 /// Sign canonical bytes. Returns 64-byte Ed25519 signature.
164 async fn sign(&self, canonical_bytes: &[u8]) -> Result<[u8; 64]>;
165}
166
167/// Unified identity provider — key management + trust resolution.
168///
169/// Implementations manage key storage, derivation, and peer trust.
170/// The `Signer` trait (used by `RpcClientImpl`) adapts over this.
171#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
172#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
173pub trait IdentityProvider: Send + Sync {
174 /// Open a purpose-keyed signing identity.
175 ///
176 /// Derives a unique Ed25519 keypair via `HKDF(root_seed, purpose)`.
177 /// Same purpose always produces the same keypair from the same root.
178 async fn identity_open(&self, purpose: &str) -> Result<Box<dyn SigningIdentity>>;
179
180 /// Resolve a peer's verified pubkey to a subject (authorization identity).
181 ///
182 /// Called after Ed25519 signature verification succeeds. Maps the
183 /// cryptographically verified signer pubkey to a permission subject.
184 fn resolve(&self, pubkey: &[u8; 32]) -> Subject;
185}
186
187#[cfg(test)]
188#[allow(clippy::expect_used, clippy::unwrap_used)]
189mod did_tests {
190 use super::*;
191
192 #[test]
193 fn new_as_str_into_string_roundtrip() {
194 let did = Did::new("did:web:example.com".to_owned());
195 assert_eq!(did.as_str(), "did:web:example.com");
196 assert_eq!(did.clone().into_string(), "did:web:example.com");
197 }
198
199 #[test]
200 fn is_did_key_and_is_did_web() {
201 let key = Did::new("did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK".to_owned());
202 assert!(key.is_did_key());
203 assert!(!key.is_did_web());
204
205 let web = Did::new("did:web:example.com".to_owned());
206 assert!(web.is_did_web());
207 assert!(!web.is_did_key());
208
209 let neither = Did::new("did:plc:abc123".to_owned());
210 assert!(!neither.is_did_key());
211 assert!(!neither.is_did_web());
212 assert!(!neither.is_did_at9p());
213
214 let at9p = Did::new("did:at9p:bafyabcd".to_owned());
215 assert!(at9p.is_did_at9p());
216 assert!(!at9p.is_did_key());
217 assert!(!at9p.is_did_web());
218 }
219
220 #[test]
221 fn did_key_ed25519_roundtrip() {
222 // A fixed 32-byte key → did:key → back to the same bytes.
223 let key = [7u8; 32];
224 let did = Did::from_ed25519(&key);
225 assert!(
226 did.is_did_key(),
227 "from_ed25519 must produce a did:key: {did}"
228 );
229 assert_eq!(did.to_ed25519().expect("decode"), key);
230 }
231
232 #[test]
233 fn to_ed25519_rejects_non_did_key() {
234 let web = Did::new("did:web:example.com".to_owned());
235 assert!(web.to_ed25519().is_err());
236 }
237
238 #[test]
239 fn from_str_is_infallible() {
240 let did: Did = "did:key:abc".parse().expect("infallible");
241 assert_eq!(did.as_str(), "did:key:abc");
242 }
243
244 #[test]
245 fn display_renders_inner_string() {
246 let did = Did::new("did:web:node.example".to_owned());
247 assert_eq!(format!("{did}"), "did:web:node.example");
248 }
249
250 #[test]
251 fn serde_is_transparent_string() {
252 let did = Did::new("did:key:z6Mkxyz".to_owned());
253 let json = serde_json::to_string(&did).expect("serialize");
254 assert_eq!(json, "\"did:key:z6Mkxyz\"");
255 let back: Did = serde_json::from_str(&json).expect("deserialize");
256 assert_eq!(back, did);
257 }
258}
259
260// ============================================================================
261// Identity-resolution contract (#579)
262//
263// The canonical `Did -> verified key material` contract. A method-dispatched
264// resolver (did:web VM extractor / did:key single-Ed25519 / did:at9p capsule
265// arm, #894) implements `IdentityResolver`; consumers — the ATProto perimeter
266// gateway (`auth::atproto_perimeter`) and mesh admission (`admission`) — are
267// generic over it and never see key bytes directly. One definition lives here;
268// do not re-declare it elsewhere.
269// ============================================================================
270
271/// Raw 32-byte Ed25519 verifying key.
272pub type Ed25519Vk = [u8; 32];
273
274/// ML-DSA-65 verifying key (FIPS 204), pinned to the always-compiled PQ
275/// primitive ([`crate::crypto::pq::MlDsaVerifyingKey`]).
276pub type MlDsaVk = MlDsaVerifyingKey;
277
278/// One named verification-key candidate published by an identity.
279///
280/// A DID document is a key *set*, not a positional one-key container. `id` is
281/// the verification-method identifier that names this candidate. A hybrid
282/// candidate carries the ML-DSA key explicitly paired with this Ed25519 key;
283/// it is never formed by pairing unrelated entries based on document order.
284#[derive(Clone)]
285pub struct IdentityKeyCandidate {
286 /// Stable DID verification-method identifier.
287 pub id: String,
288 /// The candidate's classical Ed25519 verifying key.
289 pub ed25519: Ed25519Vk,
290 /// The ML-DSA-65 key explicitly bound to this candidate, when published.
291 pub ml_dsa_65: Option<MlDsaVk>,
292}
293
294impl IdentityKeyCandidate {
295 /// Crypto-derived assurance for this one candidate.
296 pub fn assurance(&self) -> Assurance {
297 if self.ml_dsa_65.is_some() {
298 Assurance::PqHybrid
299 } else {
300 Assurance::Classical
301 }
302 }
303}
304
305/// The named verification-key candidates a resolver returns for an identity.
306///
307/// Consumers must select a candidate using a protocol-provided key identifier
308/// or verified signer, and must never use document order to choose authority.
309/// `did:key` is represented as a one-candidate set because its one-key wire
310/// format is intentional and self-certifying.
311#[derive(Clone, Default)]
312pub struct IdentityKeys {
313 candidates: Vec<IdentityKeyCandidate>,
314}
315
316impl IdentityKeys {
317 /// Construct a named candidate set.
318 ///
319 /// The collection stays private so authority cannot accidentally be chosen
320 /// with `.first()` or an index. Callers must use a protocol selector such as
321 /// [`Self::candidate_for_ed25519`].
322 pub fn new(candidates: Vec<IdentityKeyCandidate>) -> Self {
323 Self { candidates }
324 }
325
326 /// Number of published candidates, for diagnostics and set-cardinality tests.
327 pub fn len(&self) -> usize {
328 self.candidates.len()
329 }
330
331 /// Whether the identity published no usable candidate.
332 pub fn is_empty(&self) -> bool {
333 self.candidates.is_empty()
334 }
335
336 /// Return the named candidate whose Ed25519 key authenticated the peer.
337 pub fn candidate_for_ed25519(&self, key: &Ed25519Vk) -> Option<&IdentityKeyCandidate> {
338 let mut matches = self
339 .candidates
340 .iter()
341 .filter(|candidate| &candidate.ed25519 == key);
342 let candidate = matches.next()?;
343 let binding = candidate
344 .ml_dsa_65
345 .as_ref()
346 .map(crate::crypto::pq::ml_dsa_vk_bytes);
347 // Compatibility aliases for the same signer are safe only when every
348 // alias carries the same hybrid binding. Differing bindings remain
349 // ambiguous and fail closed.
350 matches
351 .all(|other| {
352 other
353 .ml_dsa_65
354 .as_ref()
355 .map(crate::crypto::pq::ml_dsa_vk_bytes)
356 == binding
357 })
358 .then_some(candidate)
359 }
360
361 /// Construct the intentional single-key `did:key` representation.
362 pub fn single_ed25519(id: impl Into<String>, ed25519: Ed25519Vk) -> Self {
363 Self::new(vec![IdentityKeyCandidate {
364 id: id.into(),
365 ed25519,
366 ml_dsa_65: None,
367 }])
368 }
369}
370
371/// Resolves a `Did` to its verified key material.
372///
373/// **Fail-closed contract:** an implementation MUST return `Err` on any inability
374/// to establish key material (network failure, unknown DID, malformed document) —
375/// never a default-`Unverified` `Ok`. Consumers treat `Err` as "not enrolled".
376pub trait IdentityResolver: Send + Sync {
377 /// Resolve `did` to its verified key material, or `Err` (fail-closed).
378 fn resolve_identity_keys(&self, did: &Did) -> Result<IdentityKeys>;
379}