Skip to main content

hyprstream_core/services/
native_event_policy.rs

1//! Finite internal Event policy. Enrollment grants clearance; accepted state
2//! supplies live identity/key/currentness. Neither source alone grants access.
3use crate::auth::service_enrollment::ServiceEnrollmentManifest;
4use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
5use hyprstream_discovery::admission_roster::{self, DeploymentRosterSource};
6use hyprstream_rpc::auth::mac::{
7    Assurance, ClearanceSource, CompartmentSet, Level, MoqEventAction, MoqEventPlane,
8    MoqEventPolicyRow, MoqEventPolicyTable, SecurityContext, SecurityLabel, VerifiedKeyMaterial,
9    SUPPORTED_TRACK_POLICY_REVISION,
10};
11use hyprstream_rpc::envelope::Subject;
12use hyprstream_rpc::events::{EventAuthz, MacEventAuthz, INTERNAL_EVENT_SOURCES};
13use hyprstream_rpc::transport::moql_admission::AcceptedStateAuthority;
14use std::sync::Arc;
15
16// Lifecycle producers run in these standalone processes. System consumption
17// is the existing native capability probe. Worker/workflow is not in this bus.
18pub const INTERNAL_EVENT_SERVICES: &[&str] = &[
19    "policy",
20    "discovery",
21    "event",
22    "registry",
23    "streams",
24    "model",
25    "oauth",
26    "oai",
27    "mcp",
28];
29
30pub fn internal_event_policy() -> anyhow::Result<MoqEventPolicyTable> {
31    let label = SecurityLabel::new(Level::Internal, Assurance::PqHybrid, CompartmentSet::EMPTY);
32    MoqEventPolicyTable::build(
33        SUPPORTED_TRACK_POLICY_REVISION,
34        INTERNAL_EVENT_SOURCES
35            .iter()
36            .map(|source| MoqEventPolicyRow::new(MoqEventPlane::Event, *source, label))
37            .collect::<Result<Vec<_>, _>>()?,
38    )
39    .map_err(Into::into)
40}
41
42pub struct EnrolledEventAuthority {
43    pub(crate) manifest: Arc<ServiceEnrollmentManifest>,
44    pub(crate) accepted: Arc<dyn AcceptedStateAuthority>,
45    pub(crate) roster: Arc<dyn DeploymentRosterSource>,
46}
47
48impl EnrolledEventAuthority {
49    fn key_is_enrolled(&self, subject: &Subject, ed25519: &[u8; 32]) -> bool {
50        let Some((name, _)) = self.binding(subject) else {
51            return false;
52        };
53        URL_SAFE_NO_PAD
54            .decode(&self.manifest.services[&name].ed25519_pubkey)
55            .ok()
56            .is_some_and(|key| key.as_slice() == ed25519)
57    }
58    /// Both key halves must match one atomic current accepted key pair. Foreign
59    /// capsules cannot obtain enrollment clearance by naming a known service.
60    pub(crate) fn binding(&self, subject: &Subject) -> Option<(String, SecurityContext)> {
61        let did = subject.name()?;
62        let now = hyprstream_rpc::envelope::current_timestamp();
63        let state = self.accepted.accepted_state(did)?;
64        if !state.is_live(now) || state.epoch == 0 || state.expires_at_unix_ms.is_none() {
65            return None;
66        }
67        let snapshot = self.roster.roster();
68        // Reject stale cached roster projections rather than using them to
69        // extend an old key/head after an uncached authority advance.
70        if snapshot.iter().find(|(d, _)| d == did)?.1 != state {
71            return None;
72        }
73        let name = admission_roster::roster_service_name(&snapshot, did, now)?;
74        if !INTERNAL_EVENT_SERVICES.contains(&name.as_str()) {
75            return None;
76        }
77        let entry = self.manifest.services.get(&name)?;
78        let ed: [u8; 32] = URL_SAFE_NO_PAD
79            .decode(&entry.ed25519_pubkey)
80            .ok()?
81            .try_into()
82            .ok()?;
83        let pq = URL_SAFE_NO_PAD.decode(entry.ml_dsa_pubkey.as_ref()?).ok()?;
84        if pq.len() != 1952 || state.subject_key_for(&ed)?.ml_dsa_65 != pq {
85            return None;
86        }
87        Some((
88            name,
89            SecurityContext::from_clearance(entry.clearance, VerifiedKeyMaterial::PqHybrid),
90        ))
91    }
92}
93
94#[async_trait::async_trait]
95impl ClearanceSource for EnrolledEventAuthority {
96    async fn clearance(&self, subject: &Subject) -> Option<SecurityContext> {
97        self.binding(subject).map(|(_, clearance)| clearance)
98    }
99}
100
101pub struct NativeEventAuthz {
102    pub(crate) authority: Arc<EnrolledEventAuthority>,
103    pub(crate) mac: MacEventAuthz,
104}
105
106/// Local publishers bind their installed proof to the same enrolled key as
107/// remote admitted sessions. A DID lookup alone never installs identity.
108pub fn require_enrolled_event_identity(
109    proof: &hyprstream_rpc::transport::moql_admission::MoqlAdmissionProof,
110) -> anyhow::Result<()> {
111    let authority = EnrolledEventAuthority {
112        manifest: crate::auth::service_enrollment::global_service_enrollment()
113            .cloned()
114            .ok_or_else(|| anyhow::anyhow!("native Event requires validated service enrollment"))?,
115        accepted: hyprstream_discovery::production_moql_accepted_state_authority()?,
116        roster: hyprstream_discovery::production_deployment_roster()?,
117    };
118    anyhow::ensure!(
119        authority.key_is_enrolled(
120            &Subject::new(proof.did.clone()),
121            &proof.ed25519.verifying_key().to_bytes()
122        ),
123        "native Event proof key is not its current authority-enrolled service key",
124    );
125    let (name, _) = authority
126        .binding(&Subject::new(proof.did.clone()))
127        .ok_or_else(|| anyhow::anyhow!("native Event enrollment became stale"))?;
128    let enrolled_pq = URL_SAFE_NO_PAD.decode(
129        authority.manifest.services[&name]
130            .ml_dsa_pubkey
131            .as_ref()
132            .ok_or_else(|| anyhow::anyhow!("native Event enrollment lacks hybrid key"))?,
133    )?;
134    anyhow::ensure!(
135        enrolled_pq == hyprstream_rpc::crypto::pq::ml_dsa_sk_to_vk_bytes(&proof.ml_dsa_65),
136        "native Event proof PQ key is not its authority-enrolled key"
137    );
138    Ok(())
139}
140
141#[async_trait::async_trait]
142impl EventAuthz for NativeEventAuthz {
143    fn admission_is_current(
144        &self,
145        peer: &hyprstream_rpc::transport::moql_admission::AdmittedMoqPeer,
146    ) -> bool {
147        let Some(did) = peer.peer.subject.as_ref() else {
148            return false;
149        };
150        let subject = Subject::new(did.clone());
151        peer.tenant == admission_roster::LOCAL_TENANT
152            && self
153                .authority
154                .key_is_enrolled(&subject, &peer.subject_ed25519)
155            && self
156                .authority
157                .accepted
158                .accepted_state(did)
159                .is_some_and(|state| {
160                    state.epoch == peer.epoch && state.head_digest == peer.head_digest
161                })
162    }
163    async fn revalidate_publish(&self, subject: &Subject, source: &str) -> bool {
164        let Some((name, _)) = self.authority.binding(subject) else {
165            return false;
166        };
167        (source == "system" || (source == "model" && name == "model"))
168            && self.mac.revalidate_publish(subject, source).await
169    }
170    async fn revalidate_subscribe(&self, subject: &Subject, source: &str) -> bool {
171        source == "system"
172            && self.authority.binding(subject).is_some()
173            && self.mac.revalidate_subscribe(subject, source).await
174    }
175    async fn can_publish(&self, subject: &Subject, source: &str) -> bool {
176        if !self.mac.can_publish(subject, source).await {
177            return false;
178        }
179        let Some((name, _)) = self.authority.binding(subject) else {
180            return self
181                .mac
182                .deny_scope(subject, source, MoqEventAction::Publish);
183        };
184        // The independent live event_publishers allowlist is enforced by the
185        // transport before ingress. MAC and source ownership are additional.
186        if source == "system" || (source == "model" && name == "model") {
187            return true;
188        }
189        self.mac
190            .deny_scope(subject, source, MoqEventAction::Publish)
191    }
192
193    async fn can_subscribe(&self, subject: &Subject, source: &str) -> bool {
194        if !self.mac.can_subscribe(subject, source).await {
195            return false;
196        }
197        if self.authority.binding(subject).is_some() && source == "system" {
198            return true;
199        }
200        self.mac
201            .deny_scope(subject, source, MoqEventAction::Subscribe)
202    }
203}
204
205/// Shared by both production constructors. The authority manifest was already
206/// validated against bootstrap keys at startup; absence fails native startup.
207pub async fn production_event_authz(
208    signing_key: ed25519_dalek::SigningKey,
209    config: &crate::config::HyprConfig,
210    audit_stream: &str,
211) -> anyhow::Result<Arc<dyn EventAuthz>> {
212    let policy = internal_event_policy()?;
213    if !config.quic.iroh_required() && !hyprstream_discovery::native_network_required() {
214        return Ok(Arc::new(MacEventAuthz::new(
215            crate::mac::production_moq_event_pep(signing_key, &config.oauth, audit_stream, policy)
216                .await?,
217        )));
218    }
219    let authority = Arc::new(EnrolledEventAuthority {
220        manifest: crate::auth::service_enrollment::global_service_enrollment()
221            .cloned()
222            .ok_or_else(|| anyhow::anyhow!("native Event requires validated service enrollment"))?,
223        accepted: hyprstream_discovery::production_moql_accepted_state_authority()?,
224        roster: hyprstream_discovery::production_deployment_roster()?,
225    });
226    let pep = crate::mac::production_moq_event_pep_with_clearance(
227        signing_key,
228        &config.oauth,
229        audit_stream,
230        policy,
231        authority.clone(),
232    )
233    .await?;
234    Ok(Arc::new(NativeEventAuthz {
235        authority,
236        mac: MacEventAuthz::new(pep),
237    }))
238}
239
240#[cfg(test)]
241#[allow(clippy::expect_used)]
242#[path = "native_event_policy_tests.rs"]
243mod tests;