Skip to main content

hyprstream_core/auth/
mesh_trust.rs

1//! Admin-anchored mesh post-quantum trust store construction (#157, Option A).
2//!
3//! Builds the process-global kid-anchored [`KeyedPqTrustStore`] eagerly from the
4//! operator-configured `mesh_peers` (see [`crate::config::MeshPeerConfig`]). The
5//! store is admin-anchored and immutable after construction: only ML-DSA-65 keys
6//! an operator configured **out-of-band** are trusted, matching the
7//! `KeyedPqTrustStore` contract ("Entries MUST be established out-of-band").
8//!
9//! Each peer entry carries two inline `Multikey` (`publicKeyMultibase`) strings,
10//! copied from that peer's published DID document:
11//!   - `#mesh`    → Ed25519 mesh signer key (multicodec `ed25519-pub`, `0xed01`)
12//!   - `#mesh-pq` → ML-DSA-65 mesh verifying key (multicodec `ml-dsa-65-pub`, `0x1211`)
13//!
14//! The Ed25519 key is the kid anchor; the ML-DSA-65 key is the trusted PQ key
15//! bound to it. Empty/absent `mesh_peers` yields an empty store — unchanged
16//! behavior (Hybrid fails closed for unknown peers).
17
18use hyprstream_rpc::envelope::KeyedPqTrustStore;
19use hyprstream_rpc::Subject;
20
21// The multikey codec + multicodec constants are the single canonical home in
22// `hyprstream-crypto` (re-exported via `hyprstream_rpc::did_key`); the previous
23// local copies here were deduplicated in #916.
24use hyprstream_rpc::did_key::{decode_multikey, MULTICODEC_ED25519_PUB, MULTICODEC_ML_DSA_65_PUB};
25
26use crate::config::OAuthConfig;
27
28/// Build the kid-anchored ML-DSA-65 trust store from the admin-configured
29/// `mesh_peers` (#157, Option A — eager, admin-anchored, immutable).
30///
31/// An invalid entry is logged and skipped (fail-safe: a malformed peer key must
32/// not silently trust the wrong identity). An empty/absent `mesh_peers` yields
33/// an empty store (non-breaking default).
34pub fn build_mesh_pq_trust_store(oauth: &OAuthConfig) -> KeyedPqTrustStore {
35    let mut store = KeyedPqTrustStore::new();
36    for (label, peer) in &oauth.mesh_peers {
37        let ed_bytes = match decode_multikey(&peer.ed25519_multibase, &MULTICODEC_ED25519_PUB) {
38            Ok(b) => b,
39            Err(e) => {
40                tracing::error!("mesh_peer '{label}': invalid ed25519_multibase, skipping: {e}");
41                continue;
42            }
43        };
44        let ed_pubkey: [u8; 32] = match ed_bytes.as_slice().try_into() {
45            Ok(a) => a,
46            Err(_) => {
47                tracing::error!(
48                    "mesh_peer '{label}': ed25519 key is {} bytes (expected 32), skipping",
49                    ed_bytes.len()
50                );
51                continue;
52            }
53        };
54        let pq_bytes = match decode_multikey(&peer.mldsa65_multibase, &MULTICODEC_ML_DSA_65_PUB) {
55            Ok(b) => b,
56            Err(e) => {
57                tracing::error!("mesh_peer '{label}': invalid mldsa65_multibase, skipping: {e}");
58                continue;
59            }
60        };
61        let pq_vk = match hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(&pq_bytes) {
62            Ok(vk) => vk,
63            Err(e) => {
64                tracing::error!(
65                    "mesh_peer '{label}': invalid ML-DSA-65 verifying key, skipping: {e}"
66                );
67                continue;
68            }
69        };
70        store.bind(ed_pubkey, &pq_vk);
71        tracing::info!("mesh_peer '{label}': anchored ML-DSA-65 key for Ed25519 signer identity");
72    }
73    store
74}
75
76/// Anchor the ML-DSA-65 keys carried by the node's own `bootstrap-pubkeys`
77/// entries into `store`, keyed by the Ed25519 signer identity each entry
78/// already anchors in the classical trust store.
79///
80/// The bootstrap file is OS-owned, written out-of-band by the provisioning
81/// wizard, so it satisfies the [`KeyedPqTrustStore`] contract exactly as
82/// `mesh_peers` does. Classical-only entries contribute nothing and clear
83/// nothing: anchoring is monotonic, so a legacy file left in place after a
84/// hybrid enrollment cannot downgrade an already-anchored service.
85///
86/// A missing or unreadable file yields zero bindings — the pre-hybrid
87/// behavior, unchanged.
88///
89/// Returns the number of identities anchored from the file.
90pub fn seed_bootstrap_pq_bindings(
91    store: &mut KeyedPqTrustStore,
92    credentials_dir: &std::path::Path,
93) -> usize {
94    let entries = match crate::auth::identity_store::load_bootstrap_pubkeys_hybrid(credentials_dir)
95    {
96        Ok(entries) => entries,
97        Err(e) => {
98            tracing::error!(
99                "bootstrap-pubkeys could not be read for PQ anchoring, no bindings seeded \
100                 (re-run the provisioning wizard if hybrid services are expected): {e}"
101            );
102            return 0;
103        }
104    };
105
106    let mut anchored = 0usize;
107    for (name, entry) in &entries {
108        let ed_pubkey = entry.ed25519.to_bytes();
109        if store.register(ed_pubkey, entry.ml_dsa_65.as_ref()) && entry.is_hybrid() {
110            anchored += 1;
111            tracing::info!("bootstrap service '{name}': anchored ML-DSA-65 key for its Ed25519 signer identity");
112        }
113    }
114    anchored
115}
116
117/// Build the per-host mesh identity roster from the admin-configured
118/// `mesh_peers` (#328): each peer's Ed25519 signer pubkey → its per-host
119/// authorization subject (`service:inference:host-<label>`).
120///
121/// Reuses the SAME `mesh_peers` enrollment record as
122/// [`build_mesh_pq_trust_store`] (no new roster type): the Ed25519 key is the
123/// envelope signer identity, and the operator-assigned label is the host id.
124/// An invalid Ed25519 multibase is logged and skipped (fail-safe — never trust
125/// a malformed identity). An empty/absent `mesh_peers` yields an empty roster.
126///
127/// This is the source for fail-closed per-host identity resolution: a networked
128/// peer whose key is NOT in this roster resolves to `anonymous`, never the
129/// `"system"` god principal (#328).
130pub fn build_mesh_identity_roster(oauth: &OAuthConfig) -> Vec<([u8; 32], Subject)> {
131    let mut roster = Vec::new();
132    for (label, peer) in &oauth.mesh_peers {
133        let ed_bytes = match decode_multikey(&peer.ed25519_multibase, &MULTICODEC_ED25519_PUB) {
134            Ok(b) => b,
135            Err(e) => {
136                tracing::error!("mesh_peer '{label}': invalid ed25519_multibase, skipping identity roster entry: {e}");
137                continue;
138            }
139        };
140        let ed_pubkey: [u8; 32] = match ed_bytes.as_slice().try_into() {
141            Ok(a) => a,
142            Err(_) => {
143                tracing::error!(
144                    "mesh_peer '{label}': ed25519 key is {} bytes (expected 32), skipping identity roster entry",
145                    ed_bytes.len()
146                );
147                continue;
148            }
149        };
150        let subject = hyprstream_rpc::node_identity::mesh_host_subject(label);
151        tracing::info!(
152            "mesh_peer '{label}': enrolled as per-host subject {:?}",
153            subject.name()
154        );
155        roster.push((ed_pubkey, subject));
156    }
157    roster
158}
159
160/// Encode raw key bytes as a `Multikey` `publicKeyMultibase` string (base58btc,
161/// multicodec-prefixed). Inverse of [`decode_multikey`]; used by tests and by
162/// operators generating peer entries.
163pub fn encode_multikey(raw: &[u8], codec: &[u8; 2]) -> String {
164    let mut payload = Vec::with_capacity(2 + raw.len());
165    payload.extend_from_slice(codec);
166    payload.extend_from_slice(raw);
167    format!("z{}", bs58::encode(payload).into_string())
168}
169
170#[cfg(test)]
171#[allow(clippy::expect_used, clippy::unwrap_used)]
172mod tests {
173    use super::*;
174    use crate::config::MeshPeerConfig;
175    use ed25519_dalek::SigningKey;
176    use hyprstream_rpc::crypto::pq;
177    use rand::rngs::OsRng;
178
179    fn oauth_with_peers(peers: Vec<(&str, MeshPeerConfig)>) -> OAuthConfig {
180        let mut oauth = OAuthConfig::default();
181        for (k, v) in peers {
182            oauth.mesh_peers.insert(k.to_owned(), v);
183        }
184        oauth
185    }
186
187    #[test]
188    fn empty_mesh_peers_yields_empty_store() {
189        let oauth = OAuthConfig::default();
190        let store = build_mesh_pq_trust_store(&oauth);
191        assert!(
192            store.is_empty(),
193            "absent mesh_peers must produce an empty store"
194        );
195    }
196
197    #[test]
198    fn mesh_peer_entry_verifies_peer_signature() {
199        // A peer's mesh identity = an Ed25519 signer key + its derived ML-DSA-65
200        // mesh key. Encode both as Multikey strings (as published in the peer's
201        // DID doc), build the store, and confirm it anchors the peer's ML-DSA key
202        // keyed by the peer's Ed25519 signer identity.
203        let peer_ed = SigningKey::generate(&mut OsRng);
204        let peer_pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&peer_ed);
205        let peer_pq_vk_bytes = pq::ml_dsa_sk_to_vk_bytes(&peer_pq_sk);
206
207        let ed_mb = encode_multikey(&peer_ed.verifying_key().to_bytes(), &MULTICODEC_ED25519_PUB);
208        let pq_mb = encode_multikey(&peer_pq_vk_bytes, &MULTICODEC_ML_DSA_65_PUB);
209
210        let oauth = oauth_with_peers(vec![(
211            "peer-a",
212            MeshPeerConfig {
213                ed25519_multibase: ed_mb,
214                mldsa65_multibase: pq_mb,
215            },
216        )]);
217        let store = build_mesh_pq_trust_store(&oauth);
218        assert_eq!(store.len(), 1, "one valid peer must produce one binding");
219
220        // The store resolves the peer's Ed25519 signer identity to its ML-DSA vk.
221        use hyprstream_rpc::envelope::PqTrustStore;
222        let resolved = store
223            .ml_dsa_key_for(&peer_ed.verifying_key().to_bytes())
224            .expect("peer's ML-DSA key must be anchored");
225
226        // A signature from the peer's ML-DSA key verifies under the anchored key.
227        let msg = b"mesh peer attestation payload";
228        let sig = pq::ml_dsa_sign(&peer_pq_sk, msg);
229        pq::ml_dsa_verify(&resolved, msg, &sig).expect("peer signature must verify");
230
231        // An unknown signer identity is not anchored.
232        assert!(store.ml_dsa_key_for(&[0u8; 32]).is_none());
233    }
234
235    #[test]
236    fn malformed_peer_entry_is_skipped_not_trusted() {
237        // A bad ed25519 multibase must be skipped (fail-safe), leaving the store
238        // empty rather than trusting a wrong/garbage identity.
239        let good_pq = encode_multikey(&vec![0u8; 1952], &MULTICODEC_ML_DSA_65_PUB);
240        let oauth = oauth_with_peers(vec![(
241            "bad-peer",
242            MeshPeerConfig {
243                ed25519_multibase: "not-multibase".to_owned(),
244                mldsa65_multibase: good_pq,
245            },
246        )]);
247        let store = build_mesh_pq_trust_store(&oauth);
248        assert!(
249            store.is_empty(),
250            "malformed entry must be skipped, not trusted"
251        );
252    }
253
254    #[test]
255    fn identity_roster_maps_peers_to_per_host_subjects() {
256        // #328: each enrolled peer's Ed25519 key maps to its own granular
257        // per-host subject (service:inference:host-<label>), reusing the SAME
258        // mesh_peers enrollment record.
259        let peer_ed = SigningKey::generate(&mut OsRng);
260        let peer_pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&peer_ed);
261        let ed_mb = encode_multikey(&peer_ed.verifying_key().to_bytes(), &MULTICODEC_ED25519_PUB);
262        let pq_mb = encode_multikey(
263            &pq::ml_dsa_sk_to_vk_bytes(&peer_pq_sk),
264            &MULTICODEC_ML_DSA_65_PUB,
265        );
266        let oauth = oauth_with_peers(vec![(
267            "gpu-node-3",
268            MeshPeerConfig {
269                ed25519_multibase: ed_mb,
270                mldsa65_multibase: pq_mb,
271            },
272        )]);
273
274        let roster = build_mesh_identity_roster(&oauth);
275        assert_eq!(roster.len(), 1);
276        let (pubkey, subject) = &roster[0];
277        assert_eq!(*pubkey, peer_ed.verifying_key().to_bytes());
278        assert_eq!(subject.name(), Some("service:inference:host-gpu-node-3"));
279        // Crucially, NOT "system".
280        assert_ne!(subject.name(), Some("system"));
281    }
282
283    #[test]
284    fn identity_roster_skips_malformed_entries() {
285        let good_pq = encode_multikey(&vec![0u8; 1952], &MULTICODEC_ML_DSA_65_PUB);
286        let oauth = oauth_with_peers(vec![(
287            "bad-peer",
288            MeshPeerConfig {
289                ed25519_multibase: "not-multibase".to_owned(),
290                mldsa65_multibase: good_pq,
291            },
292        )]);
293        let roster = build_mesh_identity_roster(&oauth);
294        assert!(
295            roster.is_empty(),
296            "malformed entry must be skipped, not enrolled"
297        );
298    }
299
300    #[test]
301    fn empty_mesh_peers_yields_empty_identity_roster() {
302        let roster = build_mesh_identity_roster(&OAuthConfig::default());
303        assert!(roster.is_empty());
304    }
305
306    #[test]
307    fn decode_multikey_rejects_wrong_codec() {
308        // An ed25519 Multikey decoded as ml-dsa must be rejected on the codec.
309        let ed_mb = encode_multikey(&[7u8; 32], &MULTICODEC_ED25519_PUB);
310        assert!(decode_multikey(&ed_mb, &MULTICODEC_ML_DSA_65_PUB).is_err());
311        // Round-trips with the correct codec.
312        let raw = decode_multikey(&ed_mb, &MULTICODEC_ED25519_PUB).unwrap();
313        assert_eq!(raw, [7u8; 32]);
314    }
315
316    // ─── bootstrap-pubkeys PQ seeding ────────────────────────────────────────
317
318    fn write_entries(
319        dir: &std::path::Path,
320        entries: Vec<(&str, crate::auth::identity_store::BootstrapPubkey)>,
321    ) {
322        let map: std::collections::HashMap<String, _> = entries
323            .into_iter()
324            .map(|(k, v)| (k.to_owned(), v))
325            .collect();
326        crate::auth::identity_store::write_bootstrap_pubkeys_hybrid(dir, &map)
327            .expect("write bootstrap-pubkeys");
328    }
329
330    #[test]
331    fn hybrid_bootstrap_file_anchors_its_services() {
332        use crate::auth::identity_store::BootstrapPubkey;
333        use hyprstream_rpc::envelope::PqTrustStore;
334
335        let dir = tempfile::TempDir::new().unwrap();
336        let ed = SigningKey::generate(&mut OsRng);
337        let (_pq_sk, pq_vk) = pq::ml_dsa_generate_keypair();
338        write_entries(
339            dir.path(),
340            vec![("policy", BootstrapPubkey::hybrid(ed.verifying_key(), pq_vk))],
341        );
342
343        let mut store = KeyedPqTrustStore::new();
344        let anchored = seed_bootstrap_pq_bindings(&mut store, dir.path());
345        assert_eq!(anchored, 1, "the hybrid entry must be anchored");
346        assert!(store
347            .ml_dsa_key_for(&ed.verifying_key().to_bytes())
348            .is_some());
349    }
350
351    #[test]
352    fn classical_bootstrap_file_anchors_nothing() {
353        let dir = tempfile::TempDir::new().unwrap();
354        let ed = SigningKey::generate(&mut OsRng);
355        write_entries(
356            dir.path(),
357            vec![(
358                "policy",
359                crate::auth::identity_store::BootstrapPubkey::classical(ed.verifying_key()),
360            )],
361        );
362
363        let mut store = KeyedPqTrustStore::new();
364        let anchored = seed_bootstrap_pq_bindings(&mut store, dir.path());
365        assert_eq!(anchored, 0, "a classical-only file must anchor nothing");
366        assert!(
367            store.is_empty(),
368            "a classical-only file must change nothing"
369        );
370    }
371
372    #[test]
373    fn absent_bootstrap_file_anchors_nothing() {
374        let dir = tempfile::TempDir::new().unwrap();
375        let mut store = KeyedPqTrustStore::new();
376        assert_eq!(seed_bootstrap_pq_bindings(&mut store, dir.path()), 0);
377        assert!(store.is_empty());
378    }
379
380    #[test]
381    fn a_later_classical_file_cannot_unanchor_a_service() {
382        use crate::auth::identity_store::BootstrapPubkey;
383
384        let dir = tempfile::TempDir::new().unwrap();
385        let ed = SigningKey::generate(&mut OsRng);
386        let (_pq_sk, pq_vk) = pq::ml_dsa_generate_keypair();
387
388        let mut store = KeyedPqTrustStore::new();
389        write_entries(
390            dir.path(),
391            vec![("policy", BootstrapPubkey::hybrid(ed.verifying_key(), pq_vk))],
392        );
393        assert_eq!(seed_bootstrap_pq_bindings(&mut store, dir.path()), 1);
394
395        // Re-seeding from a file that lost its PQ half must leave the anchor.
396        write_entries(
397            dir.path(),
398            vec![("policy", BootstrapPubkey::classical(ed.verifying_key()))],
399        );
400        seed_bootstrap_pq_bindings(&mut store, dir.path());
401        assert!(
402            store.is_anchored(&ed.verifying_key().to_bytes()),
403            "a classical re-registration must not clear an established anchor"
404        );
405    }
406}