Skip to main content

hyprstream_rpc/proof/
enrollment.rs

1//! Per-entry enrollment resolution for authenticated proofs.
2//!
3//! An authenticated proof's signer keys are never self-certified by a header.
4//! Each logical signer group resolves to exactly one **signer-suite record**
5//! that pins, by construction:
6//!
7//! - the exact suite ID the group must declare,
8//! - the exact ordered public component keys (classical and post-quantum),
9//! - the principal,
10//! - the enrollment epoch, and
11//! - the role the record may take in a proof.
12//!
13//! A component signature verifying under any key not pinned in that record
14//! denies — even a key validly enrolled to the same principal (design §4.4).
15//! The credential `cnf` thumbprint selects the primary record; additional
16//! authorization groups resolve through anchored approver enrollments; a
17//! response proof's signer resolves from the service enrollment for the
18//! request's signed service domain (§9.4).
19//!
20//! This module owns the *seam*, not the manifest: the production resolver is
21//! the enrollment-manifest consumer (workstream B). Nothing resolves by
22//! default — an absent resolver denies, it never falls back to a permissive
23//! or self-asserted key source.
24
25use std::collections::HashMap;
26use std::sync::OnceLock;
27
28use anyhow::{bail, Result};
29
30use super::{ALG_ED25519, ALG_ML_DSA_65};
31
32// ---------------------------------------------------------------------------
33// Pinned component keys
34// ---------------------------------------------------------------------------
35
36/// A public component key pinned by an enrollment record.
37#[derive(Debug, Clone)]
38pub enum ComponentKey {
39    Ed25519(ed25519_dalek::VerifyingKey),
40    MlDsa65(Box<crate::crypto::pq::MlDsaVerifyingKey>),
41}
42
43impl ComponentKey {
44    /// The fully-specified COSE algorithm this key material signs with.
45    pub fn alg(&self) -> i64 {
46        match self {
47            Self::Ed25519(_) => ALG_ED25519,
48            Self::MlDsa65(_) => ALG_ML_DSA_65,
49        }
50    }
51
52    /// The canonical public-key encoding, used for pin comparison and for the
53    /// replay-namespace thumbprint.
54    pub fn encoded(&self) -> Vec<u8> {
55        match self {
56            Self::Ed25519(k) => k.to_bytes().to_vec(),
57            Self::MlDsa65(k) => crate::crypto::pq::ml_dsa_vk_bytes(k),
58        }
59    }
60
61    /// Verify `sig` over `data` under this exact pinned key.
62    pub fn verify(&self, sig: &[u8], data: &[u8]) -> Result<()> {
63        match self {
64            Self::Ed25519(k) => {
65                use ed25519_dalek::Verifier;
66                let bytes: [u8; 64] = sig
67                    .try_into()
68                    .map_err(|_| anyhow::anyhow!("Ed25519 signature must be 64 bytes"))?;
69                k.verify(data, &ed25519_dalek::Signature::from_bytes(&bytes))
70                    .map_err(|_| anyhow::anyhow!("Ed25519 verification failed"))
71            }
72            Self::MlDsa65(k) => crate::crypto::pq::ml_dsa_verify(k, data, sig),
73        }
74    }
75}
76
77/// One pinned component of an enrolled signer suite: exact algorithm, exact
78/// key ID, exact public key.
79#[derive(Debug, Clone)]
80pub struct EnrolledComponent {
81    pub alg: i64,
82    pub kid: Vec<u8>,
83    pub key: ComponentKey,
84}
85
86impl EnrolledComponent {
87    pub fn new(kid: impl Into<Vec<u8>>, key: ComponentKey) -> Self {
88        Self {
89            alg: key.alg(),
90            kid: kid.into(),
91            key,
92        }
93    }
94}
95
96/// The role an enrolled record may take. A record is usable in exactly the
97/// role it was enrolled for: an approver enrollment can never stand in as the
98/// credential-bound primary signer, and neither can stand in as the enrolled
99/// service response signer.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum SignerRole {
102    /// The credential `cnf`-bound primary request signer.
103    Primary,
104    /// An anchored approver in an additional authorization group.
105    Approver,
106    /// The enrolled response signer for one service domain.
107    Service,
108}
109
110/// One enrolled signer-suite record — the exact chain a `cnf` thumbprint,
111/// approver anchor, or service domain resolves to.
112#[derive(Debug, Clone)]
113pub struct SignerSuiteRecord {
114    /// The enrolled principal. Distinct logical signer groups in one proof
115    /// MUST resolve to distinct principals.
116    pub principal: String,
117    /// The exact suite ID the signed plan must declare for this group.
118    pub suite_id: String,
119    /// The pinned component keys, in the suite-declared order.
120    pub components: Vec<EnrolledComponent>,
121    /// Enrollment epoch — part of the authenticated replay namespace, so a
122    /// re-enrollment cannot reuse a retired namespace.
123    pub epoch: u64,
124    /// The role this record is enrolled for.
125    pub role: SignerRole,
126    /// The named approver role this enrollment holds, for role-specific
127    /// threshold rules. Meaningful only for [`SignerRole::Approver`]; the
128    /// name is enrollment data, never taken from the request.
129    pub approver_role: Option<String>,
130    /// The enrollment policy this record was issued under (§4.4).
131    ///
132    /// Component-key separation is normative: a key enrolled for the WNS
133    /// hybrid suite MUST NOT simultaneously be enrolled for a standalone
134    /// suite, a different hybrid, another protocol or domain separator, or a
135    /// different logical signer group. An exception requires a separate
136    /// operator-approved cryptographic analysis and an explicit policy
137    /// identifier — this field carries it, so an overlap can never be
138    /// silently inherited from a key's other role.
139    pub enrollment_policy_id: String,
140    /// Credential/session expiry. A proof whose `exp` exceeds this denies.
141    pub not_after: u64,
142    /// Whether the enrollment has been revoked.
143    pub revoked: bool,
144}
145
146impl SignerSuiteRecord {
147    /// Check the record is usable right now for a proof expiring at
148    /// `proof_exp`. Revocation, enrollment expiry, and a proof outliving its
149    /// credential are all `Rejected`, never downgraded.
150    pub fn check_usable(&self, now: u64, proof_exp: u64, role: SignerRole) -> Result<()> {
151        if self.revoked {
152            bail!("enrollment for principal '{}' is revoked", self.principal);
153        }
154        if self.role != role {
155            bail!(
156                "enrollment for principal '{}' is enrolled as {:?}, presented as {:?}",
157                self.principal,
158                self.role,
159                role
160            );
161        }
162        if now >= self.not_after {
163            bail!(
164                "enrollment for principal '{}' expired at {}",
165                self.principal,
166                self.not_after
167            );
168        }
169        if proof_exp > self.not_after {
170            bail!(
171                "proof exp {} exceeds credential/session expiry {} for principal '{}'",
172                proof_exp,
173                self.not_after,
174                self.principal
175            );
176        }
177        Ok(())
178    }
179
180    /// Whether this record pins the given Ed25519 key as one of its exact
181    /// component keys.
182    pub fn pins_ed25519(&self, key: &ed25519_dalek::VerifyingKey) -> bool {
183        self.components.iter().any(|c| match &c.key {
184            ComponentKey::Ed25519(k) => k.to_bytes() == key.to_bytes(),
185            ComponentKey::MlDsa65(_) => false,
186        })
187    }
188
189    /// Resolve the pinned key for an exact `(alg, kid)` pair.
190    pub fn component(&self, alg: i64, kid: &[u8]) -> Option<&EnrolledComponent> {
191        self.components
192            .iter()
193            .find(|c| c.alg == alg && c.kid == kid)
194    }
195
196    /// The authenticated-proof replay namespace thumbprint: SHA-256 over the
197    /// canonical deterministic encoding of the exact suite ID, ordered public
198    /// component keys, and enrollment epoch, under the authenticated-proof
199    /// domain separator (§4.5).
200    ///
201    /// Approver groups are deliberately excluded, so every allowed approver
202    /// subset for the same primary-signed request stays in one namespace.
203    pub fn replay_thumbprint(&self) -> [u8; 32] {
204        let keys = self
205            .components
206            .iter()
207            .map(|c| c.key.encoded())
208            .collect::<Vec<_>>();
209        authenticated_replay_namespace(&self.suite_id, &keys, self.epoch)
210    }
211}
212
213/// Compute the same authenticated-proof namespace from an already trusted
214/// active session's ordered raw component keys and positive database epoch.
215/// Policy uses this to compare the verifier's proof-derived namespace before
216/// consuming durable replay; this function is a hash, not proof verification.
217pub fn authenticated_replay_namespace(
218    suite: &str,
219    ordered_public_keys: &[Vec<u8>],
220    epoch: u64,
221) -> [u8; 32] {
222    super::thumbprint::authenticated(suite, ordered_public_keys, epoch)
223}
224
225// ---------------------------------------------------------------------------
226// Resolver seam
227// ---------------------------------------------------------------------------
228
229/// Resolves the enrolled signer-suite records an authenticated proof's groups
230/// must verify against.
231///
232/// Every method returns `None` for anything it does not have an exact,
233/// unambiguous enrollment for; the caller denies. There is no permissive
234/// default implementation and no self-certified fallback.
235pub trait EnrollmentResolver: Send + Sync {
236    /// Resolve the primary signer-suite record pinned by a credential `cnf`
237    /// Ed25519 key.
238    fn resolve_primary(&self, cnf: &ed25519_dalek::VerifyingKey) -> Option<SignerSuiteRecord>;
239
240    /// Resolve an anchored approver record by the key ID of the group's first
241    /// component.
242    fn resolve_approver(&self, kid: &[u8]) -> Option<SignerSuiteRecord>;
243
244    /// Resolve the enrolled response signer for one canonical service domain.
245    fn resolve_service(&self, service_domain: &str) -> Option<SignerSuiteRecord>;
246}
247
248/// An in-memory resolver over an explicit enrollment table.
249///
250/// This is the shape a manifest consumer produces; it holds no defaults and
251/// resolves only what was explicitly enrolled.
252#[derive(Default)]
253pub struct InMemoryEnrollmentResolver {
254    /// Primary records keyed by the credential `cnf` Ed25519 public key.
255    primary: HashMap<[u8; 32], SignerSuiteRecord>,
256    /// Approver records keyed by their first component's key ID.
257    approver: HashMap<Vec<u8>, SignerSuiteRecord>,
258    /// Service response signers keyed by canonical service domain.
259    service: HashMap<String, SignerSuiteRecord>,
260}
261
262impl InMemoryEnrollmentResolver {
263    pub fn new() -> Self {
264        Self::default()
265    }
266
267    /// Enrol a primary record, anchored by the credential `cnf` key.
268    ///
269    /// The `cnf` key MUST be one of the record's pinned components: the
270    /// credential binds the proof by pinning the exact component keys, not by
271    /// naming a principal.
272    pub fn enrol_primary(
273        &mut self,
274        cnf: &ed25519_dalek::VerifyingKey,
275        record: SignerSuiteRecord,
276    ) -> Result<()> {
277        if record.role != SignerRole::Primary {
278            bail!("enrol_primary: record role is {:?}", record.role);
279        }
280        if !record.pins_ed25519(cnf) {
281            bail!("enrol_primary: cnf key is not a pinned component of the record");
282        }
283        self.primary.insert(cnf.to_bytes(), record);
284        Ok(())
285    }
286
287    /// Enrol an anchored approver record, keyed by its first component's kid.
288    pub fn enrol_approver(&mut self, record: SignerSuiteRecord) -> Result<()> {
289        if record.role != SignerRole::Approver {
290            bail!("enrol_approver: record role is {:?}", record.role);
291        }
292        let kid = record
293            .components
294            .first()
295            .ok_or_else(|| anyhow::anyhow!("enrol_approver: record has no components"))?
296            .kid
297            .clone();
298        self.approver.insert(kid, record);
299        Ok(())
300    }
301
302    /// Enrol the response signer for one canonical service domain.
303    pub fn enrol_service(&mut self, service_domain: &str, record: SignerSuiteRecord) -> Result<()> {
304        if record.role != SignerRole::Service {
305            bail!("enrol_service: record role is {:?}", record.role);
306        }
307        self.service.insert(service_domain.to_owned(), record);
308        Ok(())
309    }
310}
311
312impl EnrollmentResolver for InMemoryEnrollmentResolver {
313    fn resolve_primary(&self, cnf: &ed25519_dalek::VerifyingKey) -> Option<SignerSuiteRecord> {
314        self.primary.get(&cnf.to_bytes()).cloned()
315    }
316
317    fn resolve_approver(&self, kid: &[u8]) -> Option<SignerSuiteRecord> {
318        self.approver.get(kid).cloned()
319    }
320
321    fn resolve_service(&self, service_domain: &str) -> Option<SignerSuiteRecord> {
322        self.service.get(service_domain).cloned()
323    }
324}
325
326// ---------------------------------------------------------------------------
327// Process-global registration
328// ---------------------------------------------------------------------------
329
330static ENROLLMENT_RESOLVER: OnceLock<Box<dyn EnrollmentResolver>> = OnceLock::new();
331
332/// Install the process enrollment resolver. There is no auto-install: an
333/// authenticated proof presented with no resolver denies.
334pub fn set_global_enrollment_resolver(
335    resolver: Box<dyn EnrollmentResolver>,
336) -> std::result::Result<(), Box<dyn EnrollmentResolver>> {
337    ENROLLMENT_RESOLVER.set(resolver)
338}
339
340pub fn global_enrollment_resolver() -> Option<&'static dyn EnrollmentResolver> {
341    ENROLLMENT_RESOLVER.get().map(|r| &**r)
342}
343
344#[cfg(test)]
345#[allow(clippy::unwrap_used, clippy::expect_used)]
346mod tests {
347    use super::*;
348
349    fn ed(seed: u8) -> ed25519_dalek::VerifyingKey {
350        ed25519_dalek::SigningKey::from_bytes(&[seed; 32]).verifying_key()
351    }
352
353    fn record(role: SignerRole, key: ed25519_dalek::VerifyingKey) -> SignerSuiteRecord {
354        SignerSuiteRecord {
355            principal: "p".into(),
356            suite_id: super::super::SUITE_CLASSICAL.into(),
357            components: vec![EnrolledComponent::new(
358                b"kid-1".to_vec(),
359                ComponentKey::Ed25519(key),
360            )],
361            epoch: 1,
362            role,
363            approver_role: None,
364            enrollment_policy_id: "test-enrollment-v1".to_owned(),
365            not_after: 2_000,
366            revoked: false,
367        }
368    }
369
370    #[test]
371    fn revoked_enrollment_is_rejected() {
372        let mut r = record(SignerRole::Primary, ed(1));
373        r.revoked = true;
374        assert!(r.check_usable(1_000, 1_010, SignerRole::Primary).is_err());
375    }
376
377    #[test]
378    fn expired_enrollment_is_rejected() {
379        let r = record(SignerRole::Primary, ed(1));
380        assert!(r.check_usable(2_000, 2_010, SignerRole::Primary).is_err());
381    }
382
383    #[test]
384    fn proof_outliving_the_credential_is_rejected() {
385        let r = record(SignerRole::Primary, ed(1));
386        assert!(r.check_usable(1_000, 2_001, SignerRole::Primary).is_err());
387        assert!(r.check_usable(1_000, 2_000, SignerRole::Primary).is_ok());
388    }
389
390    #[test]
391    fn a_record_cannot_be_used_in_another_role() {
392        let approver = record(SignerRole::Approver, ed(1));
393        assert!(approver
394            .check_usable(1_000, 1_010, SignerRole::Primary)
395            .is_err());
396        let service = record(SignerRole::Service, ed(1));
397        assert!(service
398            .check_usable(1_000, 1_010, SignerRole::Approver)
399            .is_err());
400    }
401
402    #[test]
403    fn primary_enrollment_requires_the_cnf_key_to_be_pinned() {
404        let mut resolver = InMemoryEnrollmentResolver::new();
405        let r = record(SignerRole::Primary, ed(1));
406        assert!(resolver.enrol_primary(&ed(2), r.clone()).is_err());
407        assert!(resolver.enrol_primary(&ed(1), r).is_ok());
408    }
409
410    #[test]
411    fn a_role_mismatch_cannot_be_enrolled() {
412        let mut resolver = InMemoryEnrollmentResolver::new();
413        assert!(resolver
414            .enrol_primary(&ed(1), record(SignerRole::Approver, ed(1)))
415            .is_err());
416        assert!(resolver
417            .enrol_approver(record(SignerRole::Primary, ed(1)))
418            .is_err());
419        assert!(resolver
420            .enrol_service("svc", record(SignerRole::Primary, ed(1)))
421            .is_err());
422    }
423
424    /// The replay namespace must change when the enrollment epoch rotates,
425    /// otherwise a re-enrolled signer inherits a retired namespace's history.
426    #[test]
427    fn replay_thumbprint_binds_suite_keys_and_epoch() {
428        let base = record(SignerRole::Primary, ed(1));
429        let mut rotated = base.clone();
430        rotated.epoch = 2;
431        let mut other_key = base.clone();
432        other_key.components[0].key = ComponentKey::Ed25519(ed(9));
433        let mut other_suite = base.clone();
434        other_suite.suite_id = super::super::SUITE_HYBRID.into();
435
436        assert_ne!(base.replay_thumbprint(), rotated.replay_thumbprint());
437        assert_ne!(base.replay_thumbprint(), other_key.replay_thumbprint());
438        assert_ne!(base.replay_thumbprint(), other_suite.replay_thumbprint());
439
440        // The principal is not part of the namespace; the pinned keys are.
441        let mut renamed = base.clone();
442        renamed.principal = "someone-else".into();
443        assert_eq!(base.replay_thumbprint(), renamed.replay_thumbprint());
444    }
445
446    /// Approver groups are excluded from the primary namespace by
447    /// construction: the thumbprint is computed from the primary record only.
448    #[test]
449    fn approver_membership_does_not_change_the_primary_namespace() {
450        let primary = record(SignerRole::Primary, ed(1));
451        let before = primary.replay_thumbprint();
452        let _approver = record(SignerRole::Approver, ed(2));
453        assert_eq!(before, primary.replay_thumbprint());
454    }
455}