Skip to main content

hyprstream_core/auth/
proof_enrollment.rs

1//! v16 request-proof signer enrollment manifest (design §4.4, §11).
2//!
3//! Request-proof signer keys are their **own** enrollment, with their own
4//! lifecycle. They are deliberately not derived from, and never shared with,
5//! the mesh/envelope identity: component-key separation is normative, so a key
6//! enrolled for the request-proof WNS hybrid suite MUST NOT simultaneously be
7//! enrolled for another protocol or domain separator. Relabelling the mesh
8//! Ed25519 + ML-DSA-65 pair as a proof signer would be exactly that violation,
9//! and it could not supply an enrollment epoch, validity window, revocation
10//! state, approver role, or enrollment-policy identifier either — those are
11//! enrollment facts, not transport facts, and inventing them is not enrollment.
12//!
13//! The manifest is an operator-authored file, established out-of-band like the
14//! other admin-anchored trust material. Absent manifest, nothing is enrolled
15//! and every authenticated proof denies; there is no derived fallback.
16//!
17//! Cross-protocol overlap is checked, not merely documented: an entry whose
18//! component key is already anchored as a mesh/envelope identity is rejected
19//! unless the entry names an explicit operator-approved exception policy.
20
21use std::collections::HashSet;
22use std::path::Path;
23
24use anyhow::{bail, Context, Result};
25use serde::{Deserialize, Serialize};
26use zeroize::Zeroize as _;
27
28use hyprstream_rpc::proof::enrollment::{
29    ComponentKey, EnrolledComponent, InMemoryEnrollmentResolver, SignerRole, SignerSuiteRecord,
30};
31
32/// The enrolled role a manifest entry takes.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "kebab-case")]
35pub enum ManifestRole {
36    /// A credential `cnf`-bound primary request signer.
37    Primary,
38    /// An anchored approver in an additional authorization group.
39    Approver,
40    /// The enrolled response signer for one service domain.
41    Service,
42}
43
44/// One enrolled signer in the manifest.
45///
46/// Every lifecycle field is explicit. There is no default epoch, no implied
47/// "never expires", and no inferred role: an entry that does not state them is
48/// rejected at load rather than enrolled under invented values.
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct ManifestEntry {
51    /// The enrolled principal this signer resolves to.
52    pub principal: String,
53    /// The role this entry is enrolled for.
54    pub role: ManifestRole,
55    /// The exact suite ID the signed plan must declare for this signer.
56    pub suite_id: String,
57    /// The enrollment policy this entry was issued under. Part of the replay
58    /// namespace's provenance and the only way an operator may authorize a
59    /// cross-protocol key overlap.
60    pub enrollment_policy_id: String,
61    /// Enrollment epoch. Rotating it changes the replay namespace, so a
62    /// re-enrolled signer never inherits a retired namespace's history.
63    pub epoch: u64,
64    /// Unix seconds after which this enrollment is no longer usable.
65    pub not_after: u64,
66    /// Whether this enrollment has been revoked.
67    #[serde(default)]
68    pub revoked: bool,
69    /// For `Approver` entries, the approver role a generated rule may name.
70    #[serde(default)]
71    pub approver_role: Option<String>,
72    /// For `Service` entries, the canonical service domain this signer answers
73    /// for.
74    #[serde(default)]
75    pub service_domain: Option<String>,
76    /// The pinned component keys, in the suite-declared order.
77    pub components: Vec<ManifestComponent>,
78}
79
80/// One pinned component key: its key ID and its public key material.
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub struct ManifestComponent {
83    /// Opaque key ID, hex-encoded (1..64 bytes).
84    pub kid_hex: String,
85    /// Algorithm: `ed25519` or `ml-dsa-65`.
86    pub alg: ManifestAlg,
87    /// Hex-encoded raw public key (32 bytes Ed25519, 1952 bytes ML-DSA-65).
88    pub public_hex: String,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
92#[serde(rename_all = "kebab-case")]
93pub enum ManifestAlg {
94    Ed25519,
95    #[serde(rename = "ml-dsa-65")]
96    MlDsa65,
97}
98
99/// The manifest file.
100#[derive(Debug, Clone, Default, Serialize, Deserialize)]
101pub struct ProofEnrollmentManifest {
102    #[serde(default)]
103    pub entries: Vec<ManifestEntry>,
104}
105
106impl ProofEnrollmentManifest {
107    pub fn load(path: &Path) -> Result<Self> {
108        let text = std::fs::read_to_string(path)
109            .with_context(|| format!("reading proof enrollment manifest {}", path.display()))?;
110        toml::from_str(&text)
111            .with_context(|| format!("parsing proof enrollment manifest {}", path.display()))
112    }
113}
114
115/// Build the resolver from a manifest.
116///
117/// `foreign_protocol_keys` is the set of public keys already enrolled for
118/// another protocol — in practice the mesh/envelope identities. An entry
119/// reusing one of them is rejected unless it names an exception policy, which
120/// is how §4.4's "an exception requires a separate operator-approved analysis
121/// and an explicit enrollment-policy identifier" is enforced rather than
122/// assumed.
123///
124/// A rejected entry is skipped with an error log; it is never enrolled under
125/// partial or substituted material.
126pub fn build_resolver(
127    manifest: &ProofEnrollmentManifest,
128    foreign_protocol_keys: &HashSet<Vec<u8>>,
129    exception_policy_ids: &HashSet<String>,
130    now: u64,
131) -> InMemoryEnrollmentResolver {
132    let mut resolver = InMemoryEnrollmentResolver::new();
133
134    // Component-key separation is not only cross-protocol: within the manifest
135    // a component key may appear exactly once, across every entry, suite,
136    // role, and logical group. A key present twice would let one holder occupy
137    // two logical signers, satisfy a threshold alone, or carry a suite it was
138    // not analysed for — so a repeated key disqualifies *every* entry using
139    // it, not just the later one. Detecting it up front, before enrolling
140    // anything, is what makes that possible.
141    let mut seen: std::collections::HashMap<Vec<u8>, usize> = std::collections::HashMap::new();
142    for entry in &manifest.entries {
143        for component in &entry.components {
144            if let Ok(public) = hex::decode(&component.public_hex) {
145                *seen.entry(public).or_insert(0) += 1;
146            }
147        }
148    }
149    let reused: HashSet<Vec<u8>> = seen
150        .into_iter()
151        .filter(|(_, count)| *count > 1)
152        .map(|(key, _)| key)
153        .collect();
154
155    for entry in &manifest.entries {
156        match enrol_one(
157            &mut resolver,
158            entry,
159            foreign_protocol_keys,
160            &reused,
161            exception_policy_ids,
162            now,
163        ) {
164            Ok(()) => tracing::info!(
165                "proof enrollment: '{}' enrolled as {:?} (epoch {}, suite {})",
166                entry.principal,
167                entry.role,
168                entry.epoch,
169                entry.suite_id
170            ),
171            Err(e) => tracing::error!(
172                "proof enrollment: '{}' rejected, not enrolled: {e:#}",
173                entry.principal
174            ),
175        }
176    }
177    resolver
178}
179
180#[allow(clippy::too_many_arguments)]
181fn enrol_one(
182    resolver: &mut InMemoryEnrollmentResolver,
183    entry: &ManifestEntry,
184    foreign_protocol_keys: &HashSet<Vec<u8>>,
185    reused_within_manifest: &HashSet<Vec<u8>>,
186    exception_policy_ids: &HashSet<String>,
187    now: u64,
188) -> Result<()> {
189    if entry.enrollment_policy_id.is_empty() {
190        bail!("entry names no enrollment policy");
191    }
192    if entry.not_after <= now {
193        bail!("enrollment validity ({}) is already past", entry.not_after);
194    }
195    if entry.components.is_empty() {
196        bail!("entry pins no component keys");
197    }
198
199    let mut components = Vec::with_capacity(entry.components.len());
200    for component in &entry.components {
201        let kid = hex::decode(&component.kid_hex).context("kid is not hex")?;
202        if kid.is_empty() || kid.len() > hyprstream_rpc::proof::MAX_KID_BYTES {
203            bail!(
204                "kid must be 1..{} bytes",
205                hyprstream_rpc::proof::MAX_KID_BYTES
206            );
207        }
208        let public = hex::decode(&component.public_hex).context("public key is not hex")?;
209
210        // Component-key separation (§4.4). A key may not be shared with
211        // another protocol, and may not appear twice within this manifest —
212        // across entries, suites, roles, or logical groups. Only the
213        // cross-protocol case is waivable, and only under an explicit
214        // operator-approved exception policy; intra-manifest reuse is never
215        // waivable, because no analysis can make one key two logical signers.
216        if reused_within_manifest.contains(&public) {
217            bail!(
218                "component key appears in more than one manifest entry; \
219                 a key is exactly one logical signer"
220            );
221        }
222        if foreign_protocol_keys.contains(&public)
223            && !exception_policy_ids.contains(&entry.enrollment_policy_id)
224        {
225            bail!(
226                "component key is already enrolled for another protocol; \
227                 cross-protocol reuse requires an approved exception policy"
228            );
229        }
230
231        let key = match component.alg {
232            ManifestAlg::Ed25519 => {
233                let bytes: [u8; 32] = public
234                    .as_slice()
235                    .try_into()
236                    .map_err(|_| anyhow::anyhow!("Ed25519 key must be 32 bytes"))?;
237                ComponentKey::Ed25519(
238                    ed25519_dalek::VerifyingKey::from_bytes(&bytes)
239                        .map_err(|e| anyhow::anyhow!("invalid Ed25519 key: {e}"))?,
240                )
241            }
242            ManifestAlg::MlDsa65 => ComponentKey::MlDsa65(Box::new(
243                hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(&public)?,
244            )),
245        };
246        components.push(EnrolledComponent::new(kid, key));
247    }
248
249    let role = match entry.role {
250        ManifestRole::Primary => SignerRole::Primary,
251        ManifestRole::Approver => SignerRole::Approver,
252        ManifestRole::Service => SignerRole::Service,
253    };
254    if role == SignerRole::Approver && entry.approver_role.is_none() {
255        bail!("an approver entry must name the approver role it holds");
256    }
257
258    let record = SignerSuiteRecord {
259        principal: entry.principal.clone(),
260        suite_id: entry.suite_id.clone(),
261        components,
262        epoch: entry.epoch,
263        role,
264        approver_role: entry.approver_role.clone(),
265        enrollment_policy_id: entry.enrollment_policy_id.clone(),
266        not_after: entry.not_after,
267        revoked: entry.revoked,
268    };
269
270    match entry.role {
271        ManifestRole::Primary => {
272            // The credential `cnf` key is the record's first Ed25519
273            // component: the credential binds the proof by pinning exact
274            // component keys.
275            let cnf = record
276                .components
277                .iter()
278                .find_map(|c| match &c.key {
279                    ComponentKey::Ed25519(k) => Some(*k),
280                    ComponentKey::MlDsa65(_) => None,
281                })
282                .ok_or_else(|| anyhow::anyhow!("a primary entry needs an Ed25519 component"))?;
283            resolver.enrol_primary(&cnf, record)
284        }
285        ManifestRole::Approver => resolver.enrol_approver(record),
286        ManifestRole::Service => {
287            let domain = entry
288                .service_domain
289                .as_deref()
290                .ok_or_else(|| anyhow::anyhow!("a service entry must name its service domain"))?;
291            resolver.enrol_service(domain, record)
292        }
293    }
294}
295
296/// Every public key this node already holds for another protocol, as raw
297/// public-key bytes.
298///
299/// These are exactly the keys a request-proof enrollment must not silently
300/// reuse. The set is deliberately a superset rather than one source: the mesh
301/// peer roster (remote identities) *and* this node's own bootstrap identity
302/// keys (local identities), because reuse is equally a violation in either
303/// direction. Anything unreadable is skipped — a key we cannot decode is not
304/// a key we can prove is foreign, and the cross-protocol check is a refusal,
305/// so a miss here can only make the manifest more permissive, never less
306/// correct about the keys it does know.
307pub fn foreign_protocol_keys(
308    oauth: Option<&crate::config::OAuthConfig>,
309    secrets_dir: Option<&Path>,
310) -> HashSet<Vec<u8>> {
311    use hyprstream_rpc::did_key::{
312        decode_multikey, MULTICODEC_ED25519_PUB, MULTICODEC_ML_DSA_65_PUB,
313    };
314
315    let mut keys = HashSet::new();
316
317    // Remote: the admin-anchored mesh peer roster.
318    if let Some(oauth) = oauth {
319        for peer in oauth.mesh_peers.values() {
320            if let Ok(ed) = decode_multikey(&peer.ed25519_multibase, &MULTICODEC_ED25519_PUB) {
321                keys.insert(ed);
322            }
323            if let Ok(pq) = decode_multikey(&peer.mldsa65_multibase, &MULTICODEC_ML_DSA_65_PUB) {
324                keys.insert(pq);
325            }
326        }
327    }
328
329    // Local: this node's own OS-owned key material, which anchors the local
330    // services' envelope identities. Every local protocol source is
331    // enumerated — reusing any of them as a proof-signer component key is the
332    // same violation as reusing a remote peer key.
333    if let Some(dir) = secrets_dir {
334        collect_bootstrap_pubkeys(dir, &mut keys);
335        collect_local_ca_and_node_keys(dir, &mut keys);
336    }
337
338    keys
339}
340
341/// Read this node's OS-owned bootstrap public keys via the SAME parser the
342/// identity store writes and reads them with
343/// ([`identity_store::load_bootstrap_pubkeys_hybrid`]).
344///
345/// The store format is one flat JSON file (`{ "<service>": "<base64>" }`),
346/// **not** a directory of token files. Each entry's Ed25519 anchor and its
347/// bound ML-DSA-65 half are inserted as separate raw component keys, because
348/// the overlap check compares raw component keys — a hybrid entry contributes
349/// two foreign keys, either of which a proof manifest is forbidden to reuse.
350fn collect_bootstrap_pubkeys(secrets_dir: &Path, keys: &mut HashSet<Vec<u8>>) {
351    let Ok(entries) = crate::auth::identity_store::load_bootstrap_pubkeys_hybrid(secrets_dir)
352    else {
353        return;
354    };
355    for entry in entries.values() {
356        keys.insert(entry.ed25519.as_bytes().to_vec());
357        if let Some(pq) = &entry.ml_dsa_65 {
358            keys.insert(hyprstream_rpc::crypto::pq::ml_dsa_vk_bytes(pq));
359        }
360    }
361}
362
363/// Enumerate the remaining local protocol key sources: the JWT/credential CA
364/// verifying keys (classical + post-quantum) and this node's own envelope
365/// signing key with its derived ML-DSA-65 half.
366///
367/// These are distinct protocol/domain identities from a request-proof signer,
368/// so §4.4 forbids a proof manifest from reusing their component keys. Each
369/// source is read through its identity-store loader; a source this node does
370/// not hold is simply absent, never guessed at.
371fn collect_local_ca_and_node_keys(secrets_dir: &Path, keys: &mut HashSet<Vec<u8>>) {
372    use crate::auth::identity_store;
373
374    // The credential-CA verifying keys (JWT/WIT issuance trust anchor).
375    if let Ok(ca_ed) = identity_store::load_ca_verifying_key(secrets_dir) {
376        keys.insert(ca_ed.as_bytes().to_vec());
377    }
378    if let Ok(ca_pq) = identity_store::load_ca_ml_dsa_verifying_key(secrets_dir) {
379        keys.insert(hyprstream_rpc::crypto::pq::ml_dsa_vk_bytes(&ca_pq));
380    }
381
382    // This node's own envelope/mesh signing identity: the Ed25519 verifying
383    // key and its deterministically derived ML-DSA-65 half (the same pair the
384    // response-signing default and the published `#mesh-pq` method use). Read
385    // the seed directly — enumeration must never GENERATE a key as a side
386    // effect, so the generate-on-miss loader is deliberately not used here.
387    if let Ok(Some(mut seed)) = identity_store::read_secret(secrets_dir, "signing-key") {
388        if let Ok(arr) = <[u8; 32]>::try_from(seed.as_slice()) {
389            let node_sk = ed25519_dalek::SigningKey::from_bytes(&arr);
390            keys.insert(node_sk.verifying_key().as_bytes().to_vec());
391            let node_pq = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&node_sk);
392            keys.insert(hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&node_pq));
393        }
394        seed.zeroize();
395    }
396}
397
398#[cfg(test)]
399#[allow(clippy::expect_used, clippy::unwrap_used)]
400mod tests {
401    use super::*;
402    use ed25519_dalek::SigningKey;
403    use hyprstream_rpc::proof::enrollment::EnrollmentResolver;
404    use rand::rngs::OsRng;
405
406    const NOW: u64 = 1_000;
407
408    fn ed_component(key: &SigningKey, kid: &str) -> ManifestComponent {
409        ManifestComponent {
410            kid_hex: hex::encode(kid.as_bytes()),
411            alg: ManifestAlg::Ed25519,
412            public_hex: hex::encode(key.verifying_key().to_bytes()),
413        }
414    }
415
416    fn primary_entry(key: &SigningKey) -> ManifestEntry {
417        ManifestEntry {
418            principal: "client".into(),
419            role: ManifestRole::Primary,
420            suite_id: hyprstream_rpc::proof::SUITE_CLASSICAL.into(),
421            enrollment_policy_id: "proof-signers-v1".into(),
422            epoch: 3,
423            not_after: 9_000,
424            revoked: false,
425            approver_role: None,
426            service_domain: None,
427            components: vec![ed_component(key, "client-1")],
428        }
429    }
430
431    /// Two entries sharing a component key disqualify BOTH: no analysis can
432    /// make one key two logical signers, so the reuse is never waivable.
433    #[test]
434    fn a_component_key_reused_across_entries_disqualifies_both() {
435        let key = SigningKey::generate(&mut OsRng);
436        let mut approver = primary_entry(&key);
437        approver.principal = "approver".into();
438        approver.role = ManifestRole::Approver;
439        approver.approver_role = Some("security".into());
440
441        let resolver = build(vec![primary_entry(&key), approver]);
442        assert!(
443            resolver.resolve_primary(&key.verifying_key()).is_none(),
444            "the primary entry must be disqualified"
445        );
446        assert!(
447            resolver.resolve_approver(b"client-1").is_none(),
448            "the approver entry must be disqualified too"
449        );
450    }
451
452    /// Reuse across suites is equally forbidden, and an exception policy does
453    /// not waive it — the exception covers cross-protocol reuse only.
454    #[test]
455    fn intra_manifest_reuse_is_not_waivable_by_an_exception_policy() {
456        let key = SigningKey::generate(&mut OsRng);
457        let mut hybrid = primary_entry(&key);
458        hybrid.principal = "client-hybrid".into();
459        hybrid.suite_id = hyprstream_rpc::proof::SUITE_HYBRID.into();
460        hybrid.enrollment_policy_id = "approved-overlap".into();
461        let mut classical = primary_entry(&key);
462        classical.enrollment_policy_id = "approved-overlap".into();
463
464        let mut exceptions = HashSet::new();
465        exceptions.insert("approved-overlap".to_owned());
466        let resolver = build_resolver(
467            &ProofEnrollmentManifest {
468                entries: vec![hybrid, classical],
469            },
470            &HashSet::new(),
471            &exceptions,
472            NOW,
473        );
474        assert!(resolver.resolve_primary(&key.verifying_key()).is_none());
475    }
476
477    /// A manifest still loads with no mesh configuration: the foreign set is
478    /// then whatever local material exists, and enrollment is not skipped.
479    #[test]
480    fn a_manifest_loads_without_any_mesh_configuration() {
481        let key = SigningKey::generate(&mut OsRng);
482        let foreign = foreign_protocol_keys(None, None);
483        assert!(foreign.is_empty());
484        let resolver = build_resolver(
485            &ProofEnrollmentManifest {
486                entries: vec![primary_entry(&key)],
487            },
488            &foreign,
489            &HashSet::new(),
490            NOW,
491        );
492        assert!(resolver.resolve_primary(&key.verifying_key()).is_some());
493    }
494
495    /// The node's own bootstrap identity keys are foreign to proof
496    /// enrollment: local reuse is a violation just as remote reuse is.
497    ///
498    /// The store format is the identity store's flat JSON file — written and
499    /// read through the SAME parser production uses
500    /// (`write_bootstrap_pubkeys_hybrid` / `load_bootstrap_pubkeys_hybrid`),
501    /// not the invented directory layout the previous scanner assumed. This
502    /// test therefore fails if the scanner ever regresses to reading a
503    /// directory that production never writes.
504    #[test]
505    fn local_bootstrap_keys_count_as_foreign() {
506        use crate::auth::identity_store::{write_bootstrap_pubkeys_hybrid, BootstrapPubkey};
507
508        let key = SigningKey::generate(&mut OsRng);
509        let dir = tempfile::tempdir().expect("tempdir");
510
511        // Write a real hybrid bootstrap entry the way production does.
512        let entry = BootstrapPubkey::for_service_key(&key).expect("hybrid entry");
513        let ed_bytes = key.verifying_key().to_bytes().to_vec();
514        let pq_bytes = match &entry.ml_dsa_65 {
515            Some(pq) => hyprstream_rpc::crypto::pq::ml_dsa_vk_bytes(pq),
516            None => panic!("for_service_key must produce a hybrid entry"),
517        };
518        let mut map = std::collections::HashMap::new();
519        map.insert("registry".to_owned(), entry);
520        write_bootstrap_pubkeys_hybrid(dir.path(), &map).expect("write bootstrap-pubkeys");
521
522        let foreign = foreign_protocol_keys(None, Some(dir.path()));
523        assert!(
524            foreign.contains(ed_bytes.as_slice()),
525            "the Ed25519 anchor must be foreign"
526        );
527        assert!(
528            foreign.contains(pq_bytes.as_slice()),
529            "the bound ML-DSA-65 half must be foreign too"
530        );
531
532        let resolver = build_resolver(
533            &ProofEnrollmentManifest {
534                entries: vec![primary_entry(&key)],
535            },
536            &foreign,
537            &HashSet::new(),
538            NOW,
539        );
540        assert!(
541            resolver.resolve_primary(&key.verifying_key()).is_none(),
542            "a local envelope identity key must not be enrolled as a proof signer"
543        );
544    }
545
546    /// The credential-CA verifying keys are also enumerated as foreign: a
547    /// proof manifest cannot relabel the JWT/WIT issuance anchor as a signer.
548    #[test]
549    fn local_ca_pubkeys_count_as_foreign() {
550        use crate::auth::identity_store::{write_ca_ml_dsa_verifying_key, write_ca_verifying_key};
551
552        let ca_ed = SigningKey::generate(&mut OsRng);
553        let ca_pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&ca_ed);
554        let ca_pq_vk_bytes = hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&ca_pq_sk);
555        let ca_pq_vk =
556            hyprstream_rpc::crypto::pq::ml_dsa_vk_from_bytes(&ca_pq_vk_bytes).expect("vk");
557
558        let dir = tempfile::tempdir().expect("tempdir");
559        write_ca_verifying_key(dir.path(), &ca_ed.verifying_key()).expect("write ca-pubkey");
560        write_ca_ml_dsa_verifying_key(dir.path(), &ca_pq_vk).expect("write ca-mldsa-pubkey");
561
562        let foreign = foreign_protocol_keys(None, Some(dir.path()));
563        assert!(foreign.contains(ca_ed.verifying_key().to_bytes().as_slice()));
564        assert!(foreign.contains(ca_pq_vk_bytes.as_slice()));
565    }
566
567    fn build(entries: Vec<ManifestEntry>) -> InMemoryEnrollmentResolver {
568        build_resolver(
569            &ProofEnrollmentManifest { entries },
570            &HashSet::new(),
571            &HashSet::new(),
572            NOW,
573        )
574    }
575
576    #[test]
577    fn a_manifest_entry_enrols_with_its_own_stated_lifecycle() {
578        let key = SigningKey::generate(&mut OsRng);
579        let resolver = build(vec![primary_entry(&key)]);
580        let record = resolver
581            .resolve_primary(&key.verifying_key())
582            .expect("the entry must resolve");
583        assert_eq!(record.epoch, 3, "the epoch is the manifest's, not invented");
584        assert_eq!(record.not_after, 9_000);
585        assert_eq!(record.enrollment_policy_id, "proof-signers-v1");
586        assert!(!record.revoked);
587    }
588
589    /// Component-key separation: a key already enrolled for the mesh/envelope
590    /// protocol cannot be relabelled as a request-proof signer.
591    #[test]
592    fn a_key_enrolled_for_another_protocol_is_rejected() {
593        let key = SigningKey::generate(&mut OsRng);
594        let mut foreign = HashSet::new();
595        foreign.insert(key.verifying_key().to_bytes().to_vec());
596
597        let resolver = build_resolver(
598            &ProofEnrollmentManifest {
599                entries: vec![primary_entry(&key)],
600            },
601            &foreign,
602            &HashSet::new(),
603            NOW,
604        );
605        assert!(
606            resolver.resolve_primary(&key.verifying_key()).is_none(),
607            "cross-protocol key reuse must not enrol"
608        );
609    }
610
611    /// The overlap is permitted only under an explicit operator-approved
612    /// exception policy — never inherited silently.
613    #[test]
614    fn an_approved_exception_policy_permits_a_declared_overlap() {
615        let key = SigningKey::generate(&mut OsRng);
616        let mut foreign = HashSet::new();
617        foreign.insert(key.verifying_key().to_bytes().to_vec());
618        let mut entry = primary_entry(&key);
619        entry.enrollment_policy_id = "approved-overlap-2026-08".into();
620        let mut exceptions = HashSet::new();
621        exceptions.insert("approved-overlap-2026-08".to_owned());
622
623        let resolver = build_resolver(
624            &ProofEnrollmentManifest {
625                entries: vec![entry],
626            },
627            &foreign,
628            &exceptions,
629            NOW,
630        );
631        assert!(resolver.resolve_primary(&key.verifying_key()).is_some());
632    }
633
634    #[test]
635    fn an_entry_with_no_enrollment_policy_is_rejected() {
636        let key = SigningKey::generate(&mut OsRng);
637        let mut entry = primary_entry(&key);
638        entry.enrollment_policy_id = String::new();
639        let resolver = build(vec![entry]);
640        assert!(resolver.resolve_primary(&key.verifying_key()).is_none());
641    }
642
643    #[test]
644    fn an_already_expired_entry_is_not_enrolled() {
645        let key = SigningKey::generate(&mut OsRng);
646        let mut entry = primary_entry(&key);
647        entry.not_after = NOW;
648        let resolver = build(vec![entry]);
649        assert!(resolver.resolve_primary(&key.verifying_key()).is_none());
650    }
651
652    /// A revoked entry loads — revocation is state, not a parse error — and
653    /// then denies at use, so the operator sees the record they wrote.
654    #[test]
655    fn a_revoked_entry_loads_and_denies_at_use() {
656        let key = SigningKey::generate(&mut OsRng);
657        let mut entry = primary_entry(&key);
658        entry.revoked = true;
659        let resolver = build(vec![entry]);
660        let record = resolver.resolve_primary(&key.verifying_key()).unwrap();
661        assert!(record.revoked);
662        assert!(record
663            .check_usable(NOW, NOW + 10, SignerRole::Primary)
664            .is_err());
665    }
666
667    #[test]
668    fn an_approver_entry_must_name_its_role() {
669        let key = SigningKey::generate(&mut OsRng);
670        let mut entry = primary_entry(&key);
671        entry.role = ManifestRole::Approver;
672        entry.principal = "approver".into();
673        let without = build(vec![entry.clone()]);
674        assert!(without.resolve_approver(b"client-1").is_none());
675
676        entry.approver_role = Some("security".into());
677        let with = build(vec![entry]);
678        let record = with.resolve_approver(b"client-1").expect("must resolve");
679        assert_eq!(record.approver_role.as_deref(), Some("security"));
680    }
681
682    #[test]
683    fn a_service_entry_must_name_its_service_domain() {
684        let key = SigningKey::generate(&mut OsRng);
685        let mut entry = primary_entry(&key);
686        entry.role = ManifestRole::Service;
687        let without = build(vec![entry.clone()]);
688        assert!(without
689            .resolve_service("registry.svc.hyprstream.test")
690            .is_none());
691
692        entry.service_domain = Some("registry.svc.hyprstream.test".into());
693        let with = build(vec![entry]);
694        assert!(with
695            .resolve_service("registry.svc.hyprstream.test")
696            .is_some());
697        assert!(with.resolve_service("other.svc.hyprstream.test").is_none());
698    }
699
700    #[test]
701    fn an_empty_manifest_enrols_nothing() {
702        let key = SigningKey::generate(&mut OsRng);
703        let resolver = build(vec![]);
704        assert!(resolver.resolve_primary(&key.verifying_key()).is_none());
705    }
706
707    #[test]
708    fn a_manifest_round_trips_through_its_file_format() {
709        let key = SigningKey::generate(&mut OsRng);
710        let manifest = ProofEnrollmentManifest {
711            entries: vec![primary_entry(&key)],
712        };
713        let text = toml::to_string(&manifest).expect("manifest must serialize");
714        let parsed: ProofEnrollmentManifest =
715            toml::from_str(&text).expect("manifest must parse back");
716        assert_eq!(parsed.entries.len(), 1);
717        assert_eq!(parsed.entries[0].epoch, 3);
718    }
719
720    /// The mesh roster is read only to learn which keys are *already* another
721    /// protocol's — never to enrol them.
722    #[test]
723    fn mesh_keys_are_collected_as_foreign_not_enrolled() {
724        use crate::auth::mesh_trust::encode_multikey;
725        use crate::config::MeshPeerConfig;
726        use hyprstream_rpc::did_key::{MULTICODEC_ED25519_PUB, MULTICODEC_ML_DSA_65_PUB};
727
728        let ed = SigningKey::generate(&mut OsRng);
729        let pq_sk = hyprstream_rpc::node_identity::derive_mesh_mldsa_key(&ed);
730        let mut oauth = crate::config::OAuthConfig::default();
731        oauth.mesh_peers.insert(
732            "peer-a".to_owned(),
733            MeshPeerConfig {
734                ed25519_multibase: encode_multikey(
735                    &ed.verifying_key().to_bytes(),
736                    &MULTICODEC_ED25519_PUB,
737                ),
738                mldsa65_multibase: encode_multikey(
739                    &hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq_sk),
740                    &MULTICODEC_ML_DSA_65_PUB,
741                ),
742            },
743        );
744
745        let foreign = foreign_protocol_keys(Some(&oauth), None);
746        assert!(foreign.contains(ed.verifying_key().to_bytes().as_slice()));
747
748        // And a manifest that tries to reuse the mesh key is refused.
749        let resolver = build_resolver(
750            &ProofEnrollmentManifest {
751                entries: vec![primary_entry(&ed)],
752            },
753            &foreign,
754            &HashSet::new(),
755            NOW,
756        );
757        assert!(resolver.resolve_primary(&ed.verifying_key()).is_none());
758    }
759}