Skip to main content

hyprstream_rpc/auth/mac/
pep.rs

1//! MoQ / event-plane MAC policy-enforcement point (epic #547, #1271; typed
2//! resolver v16 §10 / #1510).
3//!
4//! This plane consumes the shared RPC-PEP decision contract
5//! ([`MacDecision`]) rather than defining a parallel decision vocabulary,
6//! and resolves labels through this plane's **own** typed resolver
7//! ([`MoqEventLabelResolver`]). A track/prefix string is parsed into the
8//! exact typed identity ([`MoqEventObjectRef`]) exactly once at the boundary
9//! helper ([`MoqEventPep::check_event_prefix`] /
10//! [`MoqEventPep::check_stream_track`]); the resolver never sees a string,
11//! so a MoQ/event coordinate can no longer occupy the RPC/VFS resolver's
12//! service-domain slot. Unknown or noncanonical coordinates, unlisted
13//! services, missing clearance, and missing labels all deny; a failed
14//! lattice-floor check denies. Callers preserve the pre-activation behavior
15//! by not installing this PEP; dormant event/MoQ paths remain pass-through.
16
17use std::sync::Arc;
18
19#[cfg(not(target_arch = "wasm32"))]
20use super::dispatch_pep::{MacDecision, MacDenyReason};
21// The typed identity and resolver are consumed only by the native check
22// paths; on wasm32 the PEP keeps its historical type-only surface (same gate
23// pattern as the dispatch PEP).
24#[cfg(not(target_arch = "wasm32"))]
25use super::moq_resolve::{MoqEventLabelResolver, MoqEventObjectRef, MoqEventPlane};
26use super::{SecurityContext, SecurityLabel};
27use crate::envelope::Subject;
28
29/// The MoQ/event verb being authorized.
30///
31/// All actions currently apply the same mandatory label ceiling. The
32/// discriminant is retained so future IFC write-direction rules can
33/// distinguish publishing from reading without changing the API.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum MoqEventAction {
36    /// Write an event into a track or prefix.
37    Publish,
38    /// Subscribe to or read a track.
39    Subscribe,
40    /// Join an encrypted prefix or decrypt an event.
41    JoinDecrypt,
42}
43
44impl MoqEventAction {
45    /// Wire-stable discriminant for decoded ingress.
46    pub const fn discriminant(self) -> u16 {
47        match self {
48            MoqEventAction::Publish => 0,
49            MoqEventAction::Subscribe => 1,
50            MoqEventAction::JoinDecrypt => 2,
51        }
52    }
53
54    /// Decode an action discriminant. Unknown values return `None`: an
55    /// ingress carrying a verb this PEP does not know denies — it never
56    /// falls back to a coarse default action.
57    pub const fn from_discriminant(value: u16) -> Option<Self> {
58        match value {
59            0 => Some(MoqEventAction::Publish),
60            1 => Some(MoqEventAction::Subscribe),
61            2 => Some(MoqEventAction::JoinDecrypt),
62            _ => None,
63        }
64    }
65}
66
67/// Resolve a verified event/MoQ subject to its MAC security context.
68///
69/// The event plane does not have an [`EnvelopeContext`](crate::service::EnvelopeContext),
70/// so it derives its subject context from the verified identity available at
71/// this boundary. Returning `None` is fail-closed once the PEP is installed.
72///
73/// Async because the production source revalidates credential-bearing cache
74/// entries against the canonical revocation authority on every read.
75#[async_trait::async_trait]
76pub trait ClearanceSource: Send + Sync {
77    async fn clearance(&self, subject: &Subject) -> Option<SecurityContext>;
78}
79
80/// Why a MoQ MAC denial was recorded.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum MoqMacAuditReason {
83    /// A denial returned by the canonical shared MAC contract.
84    #[cfg(not(target_arch = "wasm32"))]
85    Mac(MacDenyReason),
86    /// The boundary coordinate did not decode into a typed identity.
87    ///
88    /// Malformed grammar, a noncanonical service segment, or an internal
89    /// bookkeeping key (e.g. a tenant-qualified map key) passed where an
90    /// object identity is required. The shared decision surfaces this as
91    /// `Deny(UnlabeledObject)`; this variant keeps the precise cause in the
92    /// plane's audit trail.
93    UnknownObjectIdentity,
94    /// An authorizer was installed, but moq-net exposed no per-track callback.
95    ///
96    /// The transport denies the whole session until #276 lands rather than
97    /// serving tracks that bypass the installed policy.
98    TrackAdmissionHookUnavailable,
99    /// MAC clearance is insufficient to grant a service's source/operation.
100    SourceOwnershipDenied,
101}
102
103/// Plane-neutral denial record handed to the parent crate's MAC audit adapter.
104///
105/// `hyprstream-rpc` cannot depend on `hyprstream`'s WAL without creating a
106/// crate cycle. Active construction therefore requires this record sink; the
107/// parent adapter converts it to the canonical signed [`AuditRecord`][1].
108///
109/// [1]: https://github.com/hyprstream/hyprstream/issues/573
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct MoqMacAuditRecord {
112    /// Independently verified subject, or `None` for anonymous.
113    pub subject: Option<String>,
114    /// Track or event prefix whose access was denied — an audit trail, never
115    /// an authorization input. Accepted typed objects audit their full
116    /// coordinate; a coordinate that failed to parse audits only its
117    /// bounded representation (see [`bounded_audit_coordinate`]), so the
118    /// durable record is bounded independently of attacker input.
119    pub object: String,
120    /// Operation that was denied.
121    pub action: MoqEventAction,
122    /// Resolved subject clearance, when resolution reached that step.
123    pub subject_clearance: Option<SecurityLabel>,
124    /// Resolved content label, when resolution reached that step.
125    pub object_label: Option<SecurityLabel>,
126    /// Exact denial cause.
127    pub reason: MoqMacAuditReason,
128}
129
130/// Required audit destination for an active MoQ/event MAC PEP.
131///
132/// Production supplies the parent crate's signed WAL adapter. There is
133/// deliberately no no-op/default implementation: an installed PEP must always
134/// attempt a durable audit write for every denial.
135pub trait MoqMacAuditSink: Send + Sync {
136    fn record_deny(&self, record: &MoqMacAuditRecord) -> Result<(), String>;
137}
138
139/// Verbatim prefix of a malformed coordinate kept in a deny audit record.
140/// Anything beyond it is represented by the digest/length marker of
141/// [`bounded_audit_coordinate`].
142pub const MAX_AUDIT_COORDINATE_PREFIX_BYTES: usize = 64;
143
144/// Hard upper bound on the audit object text produced for one malformed
145/// coordinate: the fixed prefix cap plus the widest marker the format emits
146/// (`"~b3:" + 16 hex digest chars + "~len:" + u64 decimal`).
147pub const BOUNDED_AUDIT_COORDINATE_MAX_BYTES: usize =
148    MAX_AUDIT_COORDINATE_PREFIX_BYTES + "~b3:0000000000000000~len:18446744073709551615".len();
149
150/// Deterministic bounded audit identity for a coordinate that failed to parse
151/// into a typed object (`PRRT_kwDONmv2Pc6a2ZGv`, v16 §14: audit is a trail,
152/// never an authorization input).
153///
154/// A malformed name can be attacker-sized, and the deny path would otherwise
155/// clone and durably persist it in full — input-sized allocation and disk
156/// amplification per denial. This representation keeps at most a
157/// [`MAX_AUDIT_COORDINATE_PREFIX_BYTES`] prefix (truncated on a UTF-8 char
158/// boundary, deterministically) plus a BLAKE3-8 digest and byte length of
159/// the *complete* raw input, so distinct oversized inputs remain
160/// distinguishable while the persisted text is bounded independently of the
161/// input. Inputs already within the prefix cap are recorded verbatim.
162///
163/// This is audit-only: it never feeds an authorization decision, and the
164/// accepted-parse deny paths keep auditing the full decoded
165/// [`MoqEventObjectRef::audit_coordinate`] (already parser-bounded).
166#[must_use]
167pub fn bounded_audit_coordinate(raw: &str) -> String {
168    if raw.len() <= MAX_AUDIT_COORDINATE_PREFIX_BYTES {
169        return raw.to_owned();
170    }
171    let mut cut = MAX_AUDIT_COORDINATE_PREFIX_BYTES;
172    while !raw.is_char_boundary(cut) {
173        cut -= 1;
174    }
175    let digest = blake3::hash(raw.as_bytes());
176    let digest_hex: String = digest.as_bytes()[..8]
177        .iter()
178        .map(|byte| format!("{byte:02x}"))
179        .collect();
180    format!("{}~b3:{digest_hex}~len:{}", &raw[..cut], raw.len())
181}
182
183/// The installed MoQ/event MAC floor.
184///
185/// Dormancy is represented by the caller not installing this PEP. Every check
186/// on an installed instance is fail-closed.
187pub struct MoqEventPep {
188    #[cfg(not(target_arch = "wasm32"))]
189    resolver: Arc<dyn MoqEventLabelResolver>,
190    clearance: Arc<dyn ClearanceSource>,
191    audit: Arc<dyn MoqMacAuditSink>,
192}
193
194impl MoqEventPep {
195    /// Audit an explicit service/source ownership denial in addition to MAC.
196    pub fn deny_event_scope(&self, subject: &Subject, prefix: &str, action: MoqEventAction) {
197        self.audit_deny(
198            subject,
199            &bounded_audit_coordinate(prefix),
200            action,
201            None,
202            None,
203            MoqMacAuditReason::SourceOwnershipDenied,
204        );
205    }
206    /// Construct an active, fail-closed PEP from this plane's typed
207    /// object-label resolver, verified-subject clearance source, and
208    /// mandatory audit sink.
209    #[cfg(not(target_arch = "wasm32"))]
210    pub fn new(
211        resolver: Arc<dyn MoqEventLabelResolver>,
212        clearance: Arc<dyn ClearanceSource>,
213        audit: Arc<dyn MoqMacAuditSink>,
214    ) -> Self {
215        Self {
216            resolver,
217            clearance,
218            audit,
219        }
220    }
221
222    fn audit_deny(
223        &self,
224        subject: &Subject,
225        track_or_prefix: &str,
226        action: MoqEventAction,
227        subject_clearance: Option<SecurityLabel>,
228        object_label: Option<SecurityLabel>,
229        reason: MoqMacAuditReason,
230    ) {
231        let record = MoqMacAuditRecord {
232            subject: subject.name().map(str::to_owned),
233            object: track_or_prefix.to_owned(),
234            action,
235            subject_clearance,
236            object_label,
237            reason,
238        };
239        if let Err(_error) = self.audit.record_deny(&record) {
240            #[cfg(not(target_arch = "wasm32"))]
241            tracing::error!(
242                target: "hyprstream.mac.audit",
243                error = %_error,
244                subject = ?record.subject,
245                object = %record.object,
246                action = ?record.action,
247                reason = ?record.reason,
248                "MoQ MAC deny could not be durably audited; enforcing deny"
249            );
250        }
251    }
252
253    /// Check the per-track/per-event label ceiling for an already-decoded
254    /// typed identity.
255    ///
256    /// This is the typed core: the object is an
257    /// [`MoqEventObjectRef`], never a string, so no caller can smuggle
258    /// another plane's coordinate into this plane's resolver.
259    #[must_use]
260    #[cfg(not(target_arch = "wasm32"))]
261    pub async fn check(
262        &self,
263        subject: &Subject,
264        object: &MoqEventObjectRef,
265        action: MoqEventAction,
266    ) -> MacDecision {
267        let Some(subject_ctx) = self.clearance.clearance(subject).await else {
268            let reason = MacDenyReason::NoClearance;
269            self.audit_deny(
270                subject,
271                &object.audit_coordinate(),
272                action,
273                None,
274                None,
275                MoqMacAuditReason::Mac(reason),
276            );
277            return MacDecision::Deny(reason);
278        };
279        let Some(object_label) = self.resolver.resolve(object) else {
280            let reason = MacDenyReason::UnlabeledObject;
281            self.audit_deny(
282                subject,
283                &object.audit_coordinate(),
284                action,
285                Some(*subject_ctx.clearance()),
286                None,
287                MoqMacAuditReason::Mac(reason),
288            );
289            return MacDecision::Deny(reason);
290        };
291        if subject_ctx.can_access(&object_label) {
292            MacDecision::Permit
293        } else {
294            let reason = MacDenyReason::FloorDeny;
295            self.audit_deny(
296                subject,
297                &object.audit_coordinate(),
298                action,
299                Some(*subject_ctx.clearance()),
300                Some(object_label),
301                MoqMacAuditReason::Mac(reason),
302            );
303            MacDecision::Deny(reason)
304        }
305    }
306
307    /// Boundary check for an event-plane topic prefix.
308    /// Fresh held-grant validation, not an attempted operation. Do not write
309    /// audit records for watchdog ticks; never cache clearance or label state.
310    #[cfg(not(target_arch = "wasm32"))]
311    pub async fn event_grant_is_current(&self, subject: &Subject, prefix: &str) -> bool {
312        let Some(object) = MoqEventObjectRef::parse(MoqEventPlane::Event, prefix) else {
313            return false;
314        };
315        let Some(context) = self.clearance.clearance(subject).await else {
316            return false;
317        };
318        self.resolver
319            .resolve(&object)
320            .is_some_and(|label| context.can_access(&label))
321    }
322
323    /// Boundary check for an event-plane topic prefix.
324    ///
325    /// Parses the dot grammar exactly once; a coordinate that does not
326    /// decode into a typed identity (including the tenant-qualified
327    /// internal map keys the confidential path uses, which are not object
328    /// identities) denies and is audited as such — with only its bounded
329    /// representation in the audit record, so a malformed attacker-sized
330    /// name cannot amplify allocation or the durable WAL.
331    #[must_use]
332    #[cfg(not(target_arch = "wasm32"))]
333    pub async fn check_event_prefix(
334        &self,
335        subject: &Subject,
336        prefix: &str,
337        action: MoqEventAction,
338    ) -> MacDecision {
339        match MoqEventObjectRef::parse(MoqEventPlane::Event, prefix) {
340            Some(object) => self.check(subject, &object, action).await,
341            None => {
342                self.audit_deny(
343                    subject,
344                    &bounded_audit_coordinate(prefix),
345                    action,
346                    None,
347                    None,
348                    MoqMacAuditReason::UnknownObjectIdentity,
349                );
350                MacDecision::Deny(MacDenyReason::UnlabeledObject)
351            }
352        }
353    }
354
355    /// Boundary check for a stream-plane track / broadcast name.
356    ///
357    /// Parses the slash grammar exactly once; malformed or noncanonical
358    /// names deny and are audited as unknown identities — bounded, as
359    /// above, so an oversized malformed track cannot amplify the audit
360    /// trail.
361    #[must_use]
362    #[cfg(not(target_arch = "wasm32"))]
363    pub async fn check_stream_track(
364        &self,
365        subject: &Subject,
366        track: &str,
367        action: MoqEventAction,
368    ) -> MacDecision {
369        match MoqEventObjectRef::parse(MoqEventPlane::Stream, track) {
370            Some(object) => self.check(subject, &object, action).await,
371            None => {
372                self.audit_deny(
373                    subject,
374                    &bounded_audit_coordinate(track),
375                    action,
376                    None,
377                    None,
378                    MoqMacAuditReason::UnknownObjectIdentity,
379                );
380                MacDecision::Deny(MacDenyReason::UnlabeledObject)
381            }
382        }
383    }
384
385    /// Audit and deny a transport session because no per-track callback exists.
386    ///
387    /// This is the fail-closed bridge to #276: an installed track authorizer
388    /// must never be retained as dead configuration while tracks are served.
389    pub async fn deny_track_admission_without_hook(&self, subject: &Subject) {
390        self.audit_deny(
391            subject,
392            "<moq-session:track-hook-unavailable>",
393            MoqEventAction::Subscribe,
394            self.clearance
395                .clearance(subject)
396                .await
397                .map(|ctx| *ctx.clearance()),
398            None,
399            MoqMacAuditReason::TrackAdmissionHookUnavailable,
400        );
401    }
402
403    #[cfg(not(target_arch = "wasm32"))]
404    pub fn resolver(&self) -> &Arc<dyn MoqEventLabelResolver> {
405        &self.resolver
406    }
407
408    pub fn clearance(&self) -> &Arc<dyn ClearanceSource> {
409        &self.clearance
410    }
411}
412
413/// Fail-closed clearance source for an installed event/MoQ PEP.
414#[derive(Debug, Clone, Default)]
415pub struct DenyAllClearanceSource;
416
417#[async_trait::async_trait]
418impl ClearanceSource for DenyAllClearanceSource {
419    async fn clearance(&self, _subject: &Subject) -> Option<SecurityContext> {
420        None
421    }
422}
423
424#[cfg(all(test, not(target_arch = "wasm32")))]
425#[allow(clippy::unwrap_used)]
426mod tests {
427    use super::*;
428    use crate::auth::mac::{
429        Assurance, CompartmentSet, DenyAllMoqEventResolver, Level, MoqEventPolicyRow,
430        MoqEventPolicyTable, VerifiedKeyMaterial,
431    };
432    use parking_lot::Mutex;
433
434    fn public_label() -> SecurityLabel {
435        SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY)
436    }
437
438    fn secret_label() -> SecurityLabel {
439        SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY)
440    }
441
442    /// Declared track policy: the event `worker` source is secret, `registry`
443    /// and the stream `streams` service are public.
444    fn declared_resolver() -> crate::auth::mac::DeclaredTrackPolicyResolver {
445        crate::auth::mac::DeclaredTrackPolicyResolver::new(
446            MoqEventPolicyTable::build(
447                1,
448                [
449                    MoqEventPolicyRow::new(MoqEventPlane::Event, "worker", secret_label()).unwrap(),
450                    MoqEventPolicyRow::new(MoqEventPlane::Event, "registry", public_label())
451                        .unwrap(),
452                    MoqEventPolicyRow::new(MoqEventPlane::Stream, "streams", public_label())
453                        .unwrap(),
454                ],
455            )
456            .unwrap(),
457        )
458    }
459
460    struct TieredClearance {
461        cleared_did: String,
462    }
463
464    #[async_trait::async_trait]
465    impl ClearanceSource for TieredClearance {
466        async fn clearance(&self, subject: &Subject) -> Option<SecurityContext> {
467            if subject.name() == Some(self.cleared_did.as_str()) {
468                Some(SecurityContext::from_clearance(
469                    secret_label(),
470                    VerifiedKeyMaterial::PqHybrid,
471                ))
472            } else {
473                Some(SecurityContext::from_clearance(
474                    public_label(),
475                    VerifiedKeyMaterial::Classical,
476                ))
477            }
478        }
479    }
480
481    #[derive(Default)]
482    struct RecordingAudit {
483        records: Mutex<Vec<MoqMacAuditRecord>>,
484    }
485
486    impl MoqMacAuditSink for RecordingAudit {
487        fn record_deny(&self, record: &MoqMacAuditRecord) -> Result<(), String> {
488            self.records.lock().push(record.clone());
489            Ok(())
490        }
491    }
492
493    fn pep(resolver: Arc<dyn MoqEventLabelResolver>, audit: &Arc<RecordingAudit>) -> MoqEventPep {
494        MoqEventPep::new(
495            resolver,
496            Arc::new(TieredClearance {
497                cleared_did: "did:web:cleared".to_owned(),
498            }),
499            audit.clone(),
500        )
501    }
502
503    #[tokio::test]
504    async fn installed_pep_audits_every_missing_clearance_deny() {
505        let audit = Arc::new(RecordingAudit::default());
506        let pep = MoqEventPep::new(
507            Arc::new(DenyAllMoqEventResolver),
508            Arc::new(DenyAllClearanceSource),
509            audit.clone(),
510        );
511        for action in [
512            MoqEventAction::Publish,
513            MoqEventAction::Subscribe,
514            MoqEventAction::JoinDecrypt,
515        ] {
516            assert_eq!(
517                pep.check_event_prefix(&Subject::anonymous(), "registry", action)
518                    .await,
519                MacDecision::Deny(MacDenyReason::NoClearance)
520            );
521        }
522        let records = audit.records.lock();
523        assert_eq!(records.len(), 3);
524        assert!(records
525            .iter()
526            .all(|record| { record.reason == MoqMacAuditReason::Mac(MacDenyReason::NoClearance) }));
527    }
528
529    #[tokio::test]
530    async fn installed_pep_denies_unlabeled_object() {
531        let audit = Arc::new(RecordingAudit::default());
532        let pep = pep(Arc::new(DenyAllMoqEventResolver), &audit);
533        assert_eq!(
534            pep.check_event_prefix(
535                &Subject::new("did:web:cleared"),
536                "inference",
537                MoqEventAction::Subscribe,
538            )
539            .await,
540            MacDecision::Deny(MacDenyReason::UnlabeledObject)
541        );
542        let records = audit.records.lock();
543        assert_eq!(records.len(), 1);
544        assert_eq!(
545            records[0].reason,
546            MoqMacAuditReason::Mac(MacDenyReason::UnlabeledObject)
547        );
548    }
549
550    #[tokio::test]
551    async fn installed_pep_enforces_label_ceiling_for_every_action() {
552        let audit = Arc::new(RecordingAudit::default());
553        let pep = pep(Arc::new(declared_resolver()), &audit);
554        for action in [
555            MoqEventAction::Publish,
556            MoqEventAction::Subscribe,
557            MoqEventAction::JoinDecrypt,
558        ] {
559            assert_eq!(
560                pep.check_event_prefix(
561                    &Subject::new("did:web:public"),
562                    "worker.sandbox1.started",
563                    action,
564                )
565                .await,
566                MacDecision::Deny(MacDenyReason::FloorDeny)
567            );
568            assert_eq!(
569                pep.check_event_prefix(
570                    &Subject::new("did:web:cleared"),
571                    "worker.sandbox1.started",
572                    action,
573                )
574                .await,
575                MacDecision::Permit
576            );
577        }
578        let records = audit.records.lock();
579        assert_eq!(records.len(), 3);
580        assert!(records
581            .iter()
582            .all(|record| record.reason == MoqMacAuditReason::Mac(MacDenyReason::FloorDeny)));
583    }
584
585    #[tokio::test]
586    async fn known_stream_tracks_resolve_and_permit_through_the_typed_boundary() {
587        let audit = Arc::new(RecordingAudit::default());
588        let pep = pep(Arc::new(declared_resolver()), &audit);
589        // Public clearance dominates the declared public `streams` label.
590        assert_eq!(
591            pep.check_stream_track(
592                &Subject::new("did:web:public"),
593                "alice/streams/run-1/i0",
594                MoqEventAction::Subscribe,
595            )
596            .await,
597            MacDecision::Permit
598        );
599        // The same service on the event plane is a different, unlisted object.
600        assert_eq!(
601            pep.check_event_prefix(
602                &Subject::new("did:web:public"),
603                "streams.session.x",
604                MoqEventAction::Subscribe,
605            )
606            .await,
607            MacDecision::Deny(MacDenyReason::UnlabeledObject)
608        );
609    }
610
611    #[tokio::test]
612    async fn unknown_or_noncanonical_coordinates_deny_as_unknown_identities() {
613        let audit = Arc::new(RecordingAudit::default());
614        let pep = pep(Arc::new(declared_resolver()), &audit);
615        let subject = Subject::new("did:web:cleared");
616
617        // Malformed event grammar (uppercase service segment, map-key form).
618        for bad in ["Worker", "5:acmeworker", "wor/ker"] {
619            assert_eq!(
620                pep.check_event_prefix(&subject, bad, MoqEventAction::Publish)
621                    .await,
622                MacDecision::Deny(MacDenyReason::UnlabeledObject),
623                "{bad:?} must not decode"
624            );
625        }
626        // Malformed stream grammar (single segment, traversal).
627        for bad in ["alice", "alice/../streams/run"] {
628            assert_eq!(
629                pep.check_stream_track(&subject, bad, MoqEventAction::Subscribe)
630                    .await,
631                MacDecision::Deny(MacDenyReason::UnlabeledObject),
632                "{bad:?} must not decode"
633            );
634        }
635
636        let records = audit.records.lock();
637        assert_eq!(records.len(), 5);
638        assert!(records
639            .iter()
640            .all(|record| record.reason == MoqMacAuditReason::UnknownObjectIdentity));
641    }
642
643    #[test]
644    fn unknown_plane_and_action_discriminants_have_no_typed_value_to_check() {
645        // An ingress that decoded an unknown plane or verb cannot construct
646        // the typed inputs of `check`; it denies before the PEP is reached.
647        for unknown in [2u16, 3, u16::MAX] {
648            assert_eq!(MoqEventPlane::from_discriminant(unknown), None);
649        }
650        for unknown in [3u16, 4, u16::MAX] {
651            assert_eq!(MoqEventAction::from_discriminant(unknown), None);
652        }
653        // The known set round-trips.
654        for action in [
655            MoqEventAction::Publish,
656            MoqEventAction::Subscribe,
657            MoqEventAction::JoinDecrypt,
658        ] {
659            assert_eq!(
660                MoqEventAction::from_discriminant(action.discriminant()),
661                Some(action)
662            );
663        }
664        for plane in [MoqEventPlane::Event, MoqEventPlane::Stream] {
665            assert_eq!(
666                MoqEventPlane::from_discriminant(plane.discriminant()),
667                Some(plane)
668            );
669        }
670    }
671
672    #[tokio::test]
673    async fn empty_declared_table_denies_every_parseable_identity() {
674        let audit = Arc::new(RecordingAudit::default());
675        let pep = pep(
676            Arc::new(crate::auth::mac::DeclaredTrackPolicyResolver::new(
677                MoqEventPolicyTable::empty(),
678            )),
679            &audit,
680        );
681        let subject = Subject::new("did:web:cleared");
682        assert_eq!(
683            pep.check_event_prefix(&subject, "worker", MoqEventAction::Publish)
684                .await,
685            MacDecision::Deny(MacDenyReason::UnlabeledObject)
686        );
687        assert_eq!(
688            pep.check_stream_track(
689                &subject,
690                "alice/streams/run-1/i0",
691                MoqEventAction::Subscribe
692            )
693            .await,
694            MacDecision::Deny(MacDenyReason::UnlabeledObject)
695        );
696    }
697
698    // ── bounded malformed-coordinate audit (PRRT_kwDONmv2Pc6a2ZGv) ────
699
700    fn oversized_event_coordinate() -> String {
701        // Second segment far beyond MAX_TRACK_SEGMENT_BYTES: parse fails at
702        // the segment cap, so this is the malformed-path deny.
703        format!("worker.{}", "x".repeat(4 * 1024 * 1024))
704    }
705
706    fn oversized_stream_coordinate() -> String {
707        // A ninth tail after eight valid segments: parse fails at the
708        // on-observation segment-count bound.
709        format!("{}/{}", ["a"; 8].join("/"), "y".repeat(4 * 1024 * 1024))
710    }
711
712    #[tokio::test]
713    async fn malformed_event_coordinate_denies_with_bounded_audited_object() {
714        let audit = Arc::new(RecordingAudit::default());
715        let pep = pep(Arc::new(declared_resolver()), &audit);
716        let subject = Subject::new("did:web:cleared");
717
718        // Fail-closed decision preserved.
719        assert_eq!(
720            pep.check_event_prefix(
721                &subject,
722                &oversized_event_coordinate(),
723                MoqEventAction::Publish,
724            )
725            .await,
726            MacDecision::Deny(MacDenyReason::UnlabeledObject)
727        );
728
729        let records = audit.records.lock();
730        assert_eq!(records.len(), 1);
731        let object = &records[0].object;
732        // Persisted audit text is bounded independently of the 4 MiB input.
733        assert!(
734            object.len() <= BOUNDED_AUDIT_COORDINATE_MAX_BYTES,
735            "audited object {object:?} exceeds the explicit cap"
736        );
737        // Carries the digest and length markers of the complete raw input.
738        let marker_start = object.rfind("~b3:").unwrap();
739        let (prefix, marker) = object.split_at(marker_start);
740        assert!(prefix.len() <= MAX_AUDIT_COORDINATE_PREFIX_BYTES);
741        let raw_len = oversized_event_coordinate().len();
742        assert_eq!(
743            marker.len(),
744            "~b3:".len() + 16 + "~len:".len() + raw_len.to_string().len(),
745            "marker is the fixed-shape 16-hex digest plus the exact raw length"
746        );
747        assert!(marker.ends_with(&format!("~len:{raw_len}")));
748    }
749
750    #[tokio::test]
751    async fn malformed_stream_coordinate_denies_with_bounded_audited_object() {
752        let audit = Arc::new(RecordingAudit::default());
753        let pep = pep(Arc::new(declared_resolver()), &audit);
754        let subject = Subject::new("did:web:cleared");
755
756        assert_eq!(
757            pep.check_stream_track(
758                &subject,
759                &oversized_stream_coordinate(),
760                MoqEventAction::Subscribe,
761            )
762            .await,
763            MacDecision::Deny(MacDenyReason::UnlabeledObject)
764        );
765
766        let records = audit.records.lock();
767        assert_eq!(records.len(), 1);
768        let object = &records[0].object;
769        assert!(object.len() <= BOUNDED_AUDIT_COORDINATE_MAX_BYTES);
770        let raw_len = oversized_stream_coordinate().len();
771        assert!(object.ends_with(&format!("~len:{raw_len}")));
772        assert!(object.contains("~b3:"));
773    }
774
775    #[tokio::test]
776    async fn differing_oversized_malformed_tails_do_not_collide_in_audit() {
777        let a = format!("worker.{}", "x".repeat(4 * 1024 * 1024));
778        let b = format!("worker.{}", "z".repeat(4 * 1024 * 1024));
779        // Same bounded prefix shape, different oversized tails.
780        let bounded_a = bounded_audit_coordinate(&a);
781        let bounded_b = bounded_audit_coordinate(&b);
782        assert_ne!(bounded_a, bounded_b, "digest must distinguish the tails");
783
784        // Through the PEP boundary too: two denies, two distinct audited
785        // objects, both under the cap.
786        let audit = Arc::new(RecordingAudit::default());
787        let pep = pep(Arc::new(declared_resolver()), &audit);
788        let subject = Subject::new("did:web:cleared");
789        for input in [&a, &b] {
790            assert_eq!(
791                pep.check_event_prefix(&subject, input, MoqEventAction::Publish)
792                    .await,
793                MacDecision::Deny(MacDenyReason::UnlabeledObject)
794            );
795        }
796        let records = audit.records.lock();
797        assert_eq!(records.len(), 2);
798        assert_ne!(records[0].object, records[1].object);
799        assert!(records[0].object.len() <= BOUNDED_AUDIT_COORDINATE_MAX_BYTES);
800        assert!(records[1].object.len() <= BOUNDED_AUDIT_COORDINATE_MAX_BYTES);
801        // And each matches the standalone helper's deterministic output.
802        assert_eq!(records[0].object, bounded_a);
803        assert_eq!(records[1].object, bounded_b);
804    }
805
806    #[test]
807    fn bounded_audit_coordinate_is_small_input_verbatim_and_utf8_safe() {
808        // Small malformed inputs (the tenant map-key form) record verbatim.
809        assert_eq!(bounded_audit_coordinate("5:tenantworker"), "5:tenantworker");
810
811        // A multibyte char straddling the prefix cut truncates on a char
812        // boundary: deterministic across calls, within the prefix cap, and
813        // never panics.
814        let straddling = format!("{}é{}", "a".repeat(63), "z".repeat(256));
815        let bounded = bounded_audit_coordinate(&straddling);
816        assert!(bounded.len() <= BOUNDED_AUDIT_COORDINATE_MAX_BYTES);
817        let prefix_end = bounded.find("~b3:").unwrap();
818        assert!(prefix_end <= MAX_AUDIT_COORDINATE_PREFIX_BYTES);
819        assert_eq!(bounded, bounded_audit_coordinate(&straddling));
820    }
821}