Skip to main content

hyprstream_core/mac/
moq_audit.rs

1//! Signed-WAL adapter for MoQ/event-plane MAC denials.
2//!
3//! The enforcement point lives in `hyprstream-rpc`, while the authoritative
4//! tamper-evident WAL lives in this parent crate. This adapter keeps that crate
5//! direction intact and makes every active MoQ denial use the same
6//! [`AuditRecord`] / [`AuditSink`] contract as the 9P PEP.
7
8use std::sync::Arc;
9use std::time::{SystemTime, UNIX_EPOCH};
10
11use anyhow::Context as _;
12use ed25519_dalek::SigningKey;
13use hyprstream_rpc::auth::mac::{
14    ClearanceSource, DeclaredTrackPolicyResolver, MacDenyReason, MoqEventAction,
15    MoqEventLabelResolver, MoqEventPep, MoqEventPolicyTable, MoqMacAuditReason, MoqMacAuditRecord,
16    MoqMacAuditSink, SecurityLabel,
17};
18use hyprstream_rpc::envelope::Subject;
19
20use crate::mac::audit::{AuditRecord, AuditSink, DecisionReason};
21use crate::mac::te::{Action, Decision, ObjectType, ScopeAction, SubjectType};
22
23/// Reserved audit identities for MoQ/event decisions (below the CAS PEP's
24/// `u32::MAX - 3` sentinels, and distinct from VFS at `u32::MAX - 2`).
25const MOQ_SUBJECT_TYPE: SubjectType = SubjectType(u32::MAX - 4);
26const MOQ_OBJECT_TYPE: ObjectType = ObjectType(u32::MAX - 4);
27
28/// Convert RPC-plane denial records into the authoritative MAC audit schema.
29pub struct MoqAuditSinkAdapter {
30    sink: Arc<dyn AuditSink>,
31}
32
33impl MoqAuditSinkAdapter {
34    pub fn new(sink: Arc<dyn AuditSink>) -> Self {
35        Self { sink }
36    }
37}
38
39impl MoqMacAuditSink for MoqAuditSinkAdapter {
40    fn record_deny(&self, denial: &MoqMacAuditRecord) -> Result<(), String> {
41        let policy = crate::mac::compiled_policy();
42        let generation = policy.as_ref().map_or(0, |p| p.generation);
43        let policy_hash = policy.as_ref().and_then(|p| p.policy_hash().ok());
44        let record = AuditRecord {
45            seq: 0,
46            prev_hash: [0; 32],
47            ts_unix_nanos: SystemTime::now()
48                .duration_since(UNIX_EPOCH)
49                .map_or(0, |duration| duration.as_nanos()),
50            decision: Decision::Deny,
51            generation,
52            policy_hash,
53            subject_type: MOQ_SUBJECT_TYPE,
54            // Missing labels use bottom only as an audit-schema placeholder;
55            // the reason remains authoritative and the placeholder is never
56            // fed back into the authorization decision.
57            subject_clearance: denial
58                .subject_clearance
59                .unwrap_or_else(SecurityLabel::bottom),
60            on_behalf_of: None,
61            object_type: MOQ_OBJECT_TYPE,
62            object_label: denial.object_label.unwrap_or_else(SecurityLabel::bottom),
63            action: audit_action(denial.action),
64            reason: audit_reason(denial.reason),
65            subject_id: denial.subject.clone(),
66            object_id: Some(denial.object.clone()),
67        };
68        self.sink.record(&record).map_err(|error| error.to_string())
69    }
70}
71
72/// Construct an active MoQ/event PEP whose denials flow to the canonical MAC
73/// audit sink. Production passes a signed [`crate::mac::WalAuditStore`].
74pub fn audited_moq_event_pep(
75    resolver: Arc<dyn MoqEventLabelResolver>,
76    clearance: Arc<dyn ClearanceSource>,
77    sink: Arc<dyn AuditSink>,
78) -> MoqEventPep {
79    MoqEventPep::new(
80        resolver,
81        clearance,
82        Arc::new(MoqAuditSinkAdapter::new(sink)),
83    )
84}
85
86/// Assemble the production MoQ/event PEP from the declared track-policy
87/// table, verified subject contexts, and the mandatory signed audit WAL.
88///
89/// v16 §10 / #1510: the MoQ/event plane resolves labels from **declared
90/// track policy metadata**, never from the VFS/genesis resolver — a
91/// track/prefix must not occupy the RPC/VFS service-domain coordinate. The
92/// `track_policy` table is the reviewed seam onto the generated dispatch
93/// inventory (WS-D / #1505): until that inventory lands, callers pass the
94/// empty table and every unlisted track/prefix denies. This assembly has no
95/// bootstrap exception and no legacy-resolver path.
96pub async fn production_moq_event_pep(
97    signing_key: SigningKey,
98    oauth: &crate::config::OAuthConfig,
99    audit_stream: &str,
100    track_policy: MoqEventPolicyTable,
101) -> anyhow::Result<MoqEventPep> {
102    production_moq_event_pep_with_clearance(
103        signing_key,
104        oauth,
105        audit_stream,
106        track_policy,
107        Arc::new(VerifiedClaimsMoqClearanceSource),
108    )
109    .await
110}
111
112/// Explicit authority injection for checkpoint-admitted native services. This
113/// does not manufacture JWT claims or populate the verified-claims cache.
114pub async fn production_moq_event_pep_with_clearance(
115    signing_key: SigningKey,
116    oauth: &crate::config::OAuthConfig,
117    audit_stream: &str,
118    track_policy: MoqEventPolicyTable,
119    clearance: Arc<dyn ClearanceSource>,
120) -> anyhow::Result<MoqEventPep> {
121    anyhow::ensure!(
122        !audit_stream.is_empty()
123            && audit_stream
124                .bytes()
125                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_'),
126        "invalid MoQ MAC audit stream name"
127    );
128    let secrets_dir = crate::config::HyprConfig::resolve_secrets_dir()?;
129    let ml_dsa_store = crate::auth::key_rotation::global_ml_dsa_key_store(&secrets_dir, oauth);
130    let signer = crate::mac::audit::cose::OwnedCoseAuditSigner::new(
131        Arc::new(signing_key),
132        ml_dsa_store.active_key().await,
133        hyprstream_rpc::envelope::mandatory_envelope_policy(),
134    );
135    anyhow::ensure!(
136        signer.can_sign(),
137        "MoQ MAC PEP audit signer unavailable under mandatory Hybrid policy"
138    );
139    let audit_store = crate::mac::audit::WalAuditStore::open(
140        secrets_dir.join("mac-audit").join(audit_stream),
141        signer,
142    )
143    .context("open MoQ MAC audit store")?;
144    Ok(audited_moq_event_pep(
145        Arc::new(DeclaredTrackPolicyResolver::new(track_policy)),
146        clearance,
147        Arc::new(audit_store),
148    ))
149}
150
151/// Event/MoQ subject resolver backed by the same verified-Claims cache as the
152/// direct VFS and CAS PEPs.
153#[derive(Debug, Default, Clone, Copy)]
154pub struct VerifiedClaimsMoqClearanceSource;
155
156#[async_trait::async_trait]
157impl ClearanceSource for VerifiedClaimsMoqClearanceSource {
158    async fn clearance(
159        &self,
160        subject: &Subject,
161    ) -> Option<hyprstream_rpc::auth::mac::SecurityContext> {
162        hyprstream_rpc::auth::mac::subject_context(subject, None).await
163    }
164}
165
166const fn audit_action(action: MoqEventAction) -> Action {
167    match action {
168        MoqEventAction::Publish => Action::from_scope_action(ScopeAction::Publish),
169        MoqEventAction::Subscribe | MoqEventAction::JoinDecrypt => {
170            Action::from_scope_action(ScopeAction::Subscribe)
171        }
172    }
173}
174
175const fn audit_reason(reason: MoqMacAuditReason) -> DecisionReason {
176    match reason {
177        MoqMacAuditReason::Mac(MacDenyReason::NoPepInstalled) => DecisionReason::MoqNoPepInstalled,
178        MoqMacAuditReason::Mac(MacDenyReason::NoClearance) => DecisionReason::MoqUnlabeledSubject,
179        MoqMacAuditReason::Mac(MacDenyReason::UnlabeledObject) => DecisionReason::UnlabeledObject,
180        MoqMacAuditReason::Mac(MacDenyReason::FloorDeny) => DecisionReason::FloorDeny,
181        MoqMacAuditReason::Mac(MacDenyReason::StaleAuthority) => DecisionReason::MoqStaleAuthority,
182        MoqMacAuditReason::UnknownObjectIdentity => DecisionReason::MoqUnknownObjectIdentity,
183        MoqMacAuditReason::SourceOwnershipDenied => DecisionReason::MoqSourceOwnershipDenied,
184        MoqMacAuditReason::TrackAdmissionHookUnavailable => {
185            DecisionReason::MoqTrackAdmissionHookUnavailable
186        }
187    }
188}
189
190#[cfg(test)]
191#[allow(clippy::unwrap_used)]
192mod tests {
193    use super::*;
194    use crate::mac::{AuditError, AuditSigner, AuditVerifier, WalAuditStore};
195    use hyprstream_rpc::auth::mac::{
196        Assurance, CompartmentSet, DeclaredTrackPolicyResolver, DenyAllMoqEventResolver, Level,
197        MoqEventPolicyRow, MoqEventPolicyTable, SecurityContext, VerifiedKeyMaterial,
198    };
199    use hyprstream_rpc::envelope::Subject;
200    use tempfile::tempdir;
201
202    #[derive(Clone, Copy)]
203    struct StubSigner;
204
205    impl AuditSigner for StubSigner {
206        fn sign(&self, signing_input: &[u8]) -> Result<Vec<u8>, AuditError> {
207            Ok(blake3::hash(signing_input).as_bytes().to_vec())
208        }
209    }
210
211    impl AuditVerifier for StubSigner {
212        fn verify(&self, signing_input: &[u8], signature: &[u8]) -> Result<(), AuditError> {
213            if signature == blake3::hash(signing_input).as_bytes() {
214                Ok(())
215            } else {
216                Err(AuditError::Verify("stub signature mismatch".to_owned()))
217            }
218        }
219    }
220
221    struct PublicClearance;
222
223    #[async_trait::async_trait]
224    impl ClearanceSource for PublicClearance {
225        async fn clearance(&self, _subject: &Subject) -> Option<SecurityContext> {
226            Some(SecurityContext::from_clearance(
227                SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY),
228                VerifiedKeyMaterial::Classical,
229            ))
230        }
231    }
232
233    /// Declared table: `registry` events are public; nothing else is listed.
234    fn declared_table() -> MoqEventPolicyTable {
235        MoqEventPolicyTable::build(
236            1,
237            [MoqEventPolicyRow::new(
238                hyprstream_rpc::auth::mac::MoqEventPlane::Event,
239                "registry",
240                SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY),
241            )
242            .unwrap()],
243        )
244        .unwrap()
245    }
246
247    #[tokio::test]
248    async fn unlisted_moq_prefix_deny_is_durable_in_signed_wal() {
249        let dir = tempdir().unwrap();
250        let wal = Arc::new(WalAuditStore::open(dir.path(), StubSigner).unwrap());
251        let pep = audited_moq_event_pep(
252            Arc::new(DeclaredTrackPolicyResolver::new(declared_table())),
253            Arc::new(PublicClearance),
254            wal.clone(),
255        );
256
257        // `worker` parses as a typed identity but is not in the declared
258        // table — an unlisted service denies.
259        assert_eq!(
260            pep.check_event_prefix(
261                &Subject::new("did:web:tenant-a"),
262                "worker.sandbox123.started",
263                MoqEventAction::Subscribe,
264            )
265            .await,
266            hyprstream_rpc::auth::mac::MacDecision::Deny(
267                hyprstream_rpc::auth::mac::MacDenyReason::UnlabeledObject
268            )
269        );
270
271        let records = wal.verify_journal(&StubSigner).unwrap();
272        assert_eq!(records.len(), 1);
273        assert_eq!(records[0].decision, Decision::Deny);
274        assert_eq!(records[0].reason, DecisionReason::UnlabeledObject);
275        assert_eq!(records[0].subject_type, SubjectType(u32::MAX - 4));
276        assert_eq!(records[0].object_type, ObjectType(u32::MAX - 4));
277        assert_eq!(records[0].subject_id.as_deref(), Some("did:web:tenant-a"));
278        assert_eq!(
279            records[0].object_id.as_deref(),
280            Some("worker.sandbox123.started")
281        );
282        assert_eq!(
283            records[0].action,
284            Action::from_scope_action(ScopeAction::Subscribe)
285        );
286    }
287
288    #[tokio::test]
289    async fn unknown_identity_deny_is_durable_with_its_own_reason() {
290        let dir = tempdir().unwrap();
291        let wal = Arc::new(WalAuditStore::open(dir.path(), StubSigner).unwrap());
292        let pep = audited_moq_event_pep(
293            Arc::new(DeclaredTrackPolicyResolver::new(declared_table())),
294            Arc::new(PublicClearance),
295            wal.clone(),
296        );
297
298        // The confidential path's tenant-qualified map key is not an object
299        // identity: it denies as an unknown identity, not as an unlisted one.
300        assert_eq!(
301            pep.check_event_prefix(
302                &Subject::new("did:web:tenant-a"),
303                "5:tenantworker",
304                MoqEventAction::Publish,
305            )
306            .await,
307            hyprstream_rpc::auth::mac::MacDecision::Deny(
308                hyprstream_rpc::auth::mac::MacDenyReason::UnlabeledObject
309            )
310        );
311
312        let records = wal.verify_journal(&StubSigner).unwrap();
313        assert_eq!(records.len(), 1);
314        assert_eq!(records[0].reason, DecisionReason::MoqUnknownObjectIdentity);
315        assert_eq!(records[0].object_id.as_deref(), Some("5:tenantworker"));
316    }
317
318    #[tokio::test]
319    async fn declared_public_prefix_permits_and_audits_nothing() {
320        let dir = tempdir().unwrap();
321        let wal = Arc::new(WalAuditStore::open(dir.path(), StubSigner).unwrap());
322        let pep = audited_moq_event_pep(
323            Arc::new(DeclaredTrackPolicyResolver::new(declared_table())),
324            Arc::new(PublicClearance),
325            wal.clone(),
326        );
327
328        assert_eq!(
329            pep.check_event_prefix(
330                &Subject::new("did:web:tenant-a"),
331                "registry.repo789.push",
332                MoqEventAction::Subscribe,
333            )
334            .await,
335            hyprstream_rpc::auth::mac::MacDecision::Permit
336        );
337        // Only denials flow to the deny sink today (the permit-side WAL is
338        // WS-F's class-reserved record).
339        assert!(wal.verify_journal(&StubSigner).unwrap().is_empty());
340    }
341
342    #[tokio::test]
343    async fn fail_closed_missing_artifact_deny_all_resolver() {
344        let dir = tempdir().unwrap();
345        let wal = Arc::new(WalAuditStore::open(dir.path(), StubSigner).unwrap());
346        let pep = audited_moq_event_pep(
347            Arc::new(DenyAllMoqEventResolver),
348            Arc::new(PublicClearance),
349            wal.clone(),
350        );
351        assert_eq!(
352            pep.check_event_prefix(
353                &Subject::new("did:web:tenant-a"),
354                "registry.repo789.push",
355                MoqEventAction::Subscribe,
356            )
357            .await,
358            hyprstream_rpc::auth::mac::MacDecision::Deny(
359                hyprstream_rpc::auth::mac::MacDenyReason::UnlabeledObject
360            )
361        );
362    }
363}