Skip to main content

hyprstream_rpc/auth/mac/
moq_resolve.rs

1//! Typed MoQ/event object identity + declared track-policy resolver (v16 §10,
2//! WS-I / #1510).
3//!
4//! The MoQ/event plane previously passed its track/prefix string into the
5//! *RPC/VFS* resolver's service-domain coordinate
6//! (`pep.rs` → [`super::dispatch_pep::RpcObjectLabelResolver`]), so a track
7//! name was reinterpreted as a VFS path. v16 §10 removes that shared string
8//! coordinate: every plane owns a typed object reference and a plane-specific
9//! resolver, and "strings are parsed exactly once at the plane boundary and
10//! cannot be reinterpreted by another resolver".
11//!
12//! This module is that end state for MoQ/event:
13//!
14//! - [`MoqEventObjectRef`] is the exact decoded typed identity. A boundary
15//!   string parses into it exactly once ([`MoqEventObjectRef::parse`]) or the
16//!   check denies — there is no string path fallback and no rewriting of
17//!   unknown input after the fact.
18//! - The service coordinate inside the identity is validated by the **one**
19//!   canonical service-domain rule
20//!   ([`validate_service_domain`][crate::envelope::validate_service_domain],
21//!   1..=[`MAX_SERVICE_DOMAIN_BYTES`] bytes) — not a second, plane-local
22//!   identity rule.
23//! - [`MoqEventLabelResolver`] is the plane's own resolver trait
24//!   (a `MoqEventObjectRef` in, a [`SecurityLabel`] out). It is deliberately
25//!   *not* the RPC resolver: dispatch, VFS/9P, CAS, and MoQ/event coordinates
26//!   cannot cross resolver types.
27//! - [`MoqEventPolicyTable`] is the declared track-policy metadata — the
28//!   authoritative label source for this plane. Lookup is an exact typed match
29//!   against declared rows; unknown, unlisted, or newer-vocabulary inputs
30//!   deny. There is no floor allowlist and no bootstrap exception: a table
31//!   that declares nothing labels nothing.
32//!
33//! ## Dependency on the generated dispatch inventory (WS-D)
34//!
35//! The end-state source of declared rows is the generated method-policy
36//! inventory (WS-D / #1505), which emits one reviewed row per annotated leaf
37//! across the service schemas. Until that inventory lands, the table is the
38//! **interface seam**: it is built from explicitly declared
39//! [`MoqEventPolicyRow`]s and rejects (not ignores) malformed input at
40//! construction. WS-D's generated code converts its inventory into rows here
41//! through one reviewed conversion — this module must not duplicate the
42//! annotation table.
43//!
44//! This module compiles for wasm32 (pure types + the shared canonicalization
45//! rule); the PEP that consumes it remains native-only, matching
46//! [`super::pep`].
47
48use std::collections::BTreeMap;
49
50use super::label::SecurityLabel;
51use crate::envelope::{validate_service_domain, MAX_SERVICE_DOMAIN_BYTES};
52
53/// Maximum number of segments in a track/prefix identity. A bound on parse
54/// work per admission check; not the service-domain rule (which is
55/// byte-length based and applies only to the service segment).
56pub const MAX_TRACK_SEGMENTS: usize = 8;
57
58/// Maximum length in bytes of one non-service identity segment. Distinct from
59/// [`MAX_SERVICE_DOMAIN_BYTES`], which bounds only the canonical service
60/// domain through the shared rule.
61pub const MAX_TRACK_SEGMENT_BYTES: usize = 128;
62
63/// The track-policy vocabulary revision this resolver understands. A policy
64/// table stamped with a *newer* revision (emitted by a newer generator whose
65/// vocabulary this build does not know) is rejected rather than partially
66/// interpreted — the "newer identities deny" rule.
67pub const SUPPORTED_TRACK_POLICY_REVISION: u32 = 1;
68
69/// Drift guard: the plane grammar is specified against the shared canonical
70/// service-domain cap (Gate-2 value 7 froze `aud` at 128 bytes through the
71/// same constant). If the shared rule's bound changes, this module's bounds
72/// must be re-reviewed together.
73const _: () = assert!(
74    MAX_SERVICE_DOMAIN_BYTES == 128,
75    "the shared canonical service-domain cap changed; re-review the MoQ/event plane grammar bounds"
76);
77
78/// The MoQ data plane a coordinate belongs to. Closed and exhaustive: adding
79/// a plane is a resolver-contract change, not a string reinterpretation.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
81pub enum MoqEventPlane {
82    /// Event-bus topic prefixes (`{source}.{entity}.{event}` dot grammar;
83    /// the authz coordinate is the `{source}` prefix).
84    Event,
85    /// MoQ stream tracks / broadcast paths (`{tenant}/{service}/{topic}/…`
86    /// and `local/{service}/…` slash grammars).
87    Stream,
88}
89
90impl MoqEventPlane {
91    /// Wire-stable discriminant for decoded ingress.
92    pub const fn discriminant(self) -> u16 {
93        match self {
94            MoqEventPlane::Event => 0,
95            MoqEventPlane::Stream => 1,
96        }
97    }
98
99    /// Decode a plane discriminant. Unknown values return `None` — the
100    /// boundary denies rather than falling back to a default plane.
101    pub const fn from_discriminant(value: u16) -> Option<Self> {
102        match value {
103            0 => Some(MoqEventPlane::Event),
104            1 => Some(MoqEventPlane::Stream),
105            _ => None,
106        }
107    }
108}
109
110/// The exact decoded track/prefix identity for one MoQ/event object.
111///
112/// Constructed only by [`Self::parse`] at the plane boundary. The service
113/// coordinate is canonical (shared 1..=128-byte rule); the remaining segments
114/// are preserved verbatim so the identity is exact, and the plane makes it
115/// non-reinterpretable by any other plane's resolver.
116#[derive(Debug, Clone, PartialEq, Eq, Hash)]
117pub struct MoqEventObjectRef {
118    plane: MoqEventPlane,
119    service_domain: String,
120    segments: Box<[String]>,
121}
122
123impl MoqEventObjectRef {
124    /// Parse the plane's coordinate grammar exactly once.
125    ///
126    /// Returns `None` for every deviation — wrong segment count, empty or
127    /// oversized segments, path-traversal segments, a `/` inside an event
128    /// coordinate (which would alias the broadcast-path namespace), or a
129    /// noncanonical service segment. Unknown input denies; it is never
130    /// rewritten.
131    pub fn parse(plane: MoqEventPlane, coordinate: &str) -> Option<Self> {
132        match plane {
133            MoqEventPlane::Event => Self::parse_dot_coordinate(coordinate),
134            MoqEventPlane::Stream => Self::parse_slash_coordinate(coordinate),
135        }
136    }
137
138    /// Parse an event-plane topic prefix: dot-separated, 1..=
139    /// [`MAX_TRACK_SEGMENTS`] segments, segment 0 is the canonical service
140    /// domain (the event `source`). Segments never contain `/`: the event
141    /// namespace is flat per source, and a `/` would alias a broadcast path.
142    ///
143    /// The ninth segment is rejected on observation — before it is cloned or
144    /// otherwise worked on — so an attacker-controlled name cannot amplify
145    /// allocation past `MAX_TRACK_SEGMENTS` bounded segments no matter how
146    /// many separators it carries.
147    fn parse_dot_coordinate(coordinate: &str) -> Option<Self> {
148        let mut segments = Vec::with_capacity(MAX_TRACK_SEGMENTS);
149        for segment in coordinate.split('.') {
150            if segments.len() == MAX_TRACK_SEGMENTS {
151                return None;
152            }
153            check_segment(segment)?;
154            // The event namespace is flat per source: a `/` in an event
155            // segment would alias the slash-separated broadcast-path
156            // namespace, so it denies here rather than parse ambiguously.
157            if segment.contains('/') {
158                return None;
159            }
160            segments.push(segment.to_owned());
161        }
162        let service_domain = canonical_domain(&segments[0])?;
163        Some(Self {
164            plane: MoqEventPlane::Event,
165            service_domain,
166            segments: segments.into(),
167        })
168    }
169
170    /// Parse a stream-plane track/broadcast name: slash-separated,
171    /// 2..=[`MAX_TRACK_SEGMENTS`] segments, segment 1 is the canonical
172    /// service domain (`{tenant}/{service}/…` and `local/{service}/…` both
173    /// carry it at index 1). A lone segment has no service coordinate and
174    /// denies.
175    ///
176    /// Like the event grammar, the ninth segment is rejected on observation,
177    /// before it is cloned or otherwise worked on: allocation is structurally
178    /// bounded at `MAX_TRACK_SEGMENTS` segments however long the name is.
179    fn parse_slash_coordinate(coordinate: &str) -> Option<Self> {
180        let mut segments = Vec::with_capacity(MAX_TRACK_SEGMENTS);
181        for segment in coordinate.split('/') {
182            if segments.len() == MAX_TRACK_SEGMENTS {
183                return None;
184            }
185            check_segment(segment)?;
186            segments.push(segment.to_owned());
187        }
188        if segments.len() < 2 {
189            return None;
190        }
191        let service_domain = canonical_domain(&segments[1])?;
192        Some(Self {
193            plane: MoqEventPlane::Stream,
194            service_domain,
195            segments: segments.into(),
196        })
197    }
198
199    /// The plane this identity belongs to.
200    pub fn plane(&self) -> MoqEventPlane {
201        self.plane
202    }
203
204    /// The canonical service domain of the declaring service.
205    pub fn service_domain(&self) -> &str {
206        &self.service_domain
207    }
208
209    /// The exact (verbatim, post-validation) identity segments.
210    pub fn segments(&self) -> &[String] {
211        &self.segments
212    }
213
214    /// The raw coordinate this ref would audit as (plane-tagged; the audit
215    /// trail records what was decoded, never a reinterpretation).
216    pub fn audit_coordinate(&self) -> String {
217        let separator = match self.plane {
218            MoqEventPlane::Event => '.',
219            MoqEventPlane::Stream => '/',
220        };
221        let mut out = String::new();
222        for segment in &self.segments[..] {
223            if !out.is_empty() {
224                out.push(separator);
225            }
226            out.push_str(segment);
227        }
228        out
229    }
230}
231
232/// Validate one non-service identity segment: non-empty, bounded, no NUL, no
233/// path-traversal names. (The service segment additionally passes the shared
234/// canonical service-domain rule.)
235fn check_segment(segment: &str) -> Option<()> {
236    if segment.is_empty()
237        || segment.len() > MAX_TRACK_SEGMENT_BYTES
238        || segment == "."
239        || segment == ".."
240        || segment.as_bytes().contains(&0)
241    {
242        return None;
243    }
244    Some(())
245}
246
247/// Apply the one canonical service-domain rule. A segment that is not
248/// already canonical denies — it is never rewritten.
249fn canonical_domain(segment: &str) -> Option<String> {
250    validate_service_domain(segment).ok()?;
251    Some(segment.to_owned())
252}
253
254/// The MoQ/event plane's own object-label resolver (v16 §10).
255///
256/// Takes the typed [`MoqEventObjectRef`] only — never a bare string, never
257/// another plane's coordinate. `None` ⇒ unlabeled ⇒ deny (D2/D3).
258pub trait MoqEventLabelResolver: Send + Sync {
259    fn resolve(&self, object: &MoqEventObjectRef) -> Option<SecurityLabel>;
260}
261
262/// Fail-closed resolver: every object is unlabeled. The structural default
263/// when no declared track-policy table exists; combined with an installed
264/// PEP it denies everything regardless of clearance.
265#[derive(Debug, Default, Clone, Copy)]
266pub struct DenyAllMoqEventResolver;
267
268impl MoqEventLabelResolver for DenyAllMoqEventResolver {
269    fn resolve(&self, _object: &MoqEventObjectRef) -> Option<SecurityLabel> {
270        None
271    }
272}
273
274/// Why a declared track-policy table could not be built. Construction
275/// failure is fail-closed: the caller keeps no partial table.
276#[derive(Debug, Clone, PartialEq, Eq)]
277pub enum TrackPolicyError {
278    /// The table's vocabulary revision is newer than
279    /// [`SUPPORTED_TRACK_POLICY_REVISION`]; this build refuses to partially
280    /// interpret it.
281    UnsupportedRevision { table: u32, supported: u32 },
282    /// A row declares a service domain that fails the canonical rule.
283    NoncanonicalServiceDomain(String),
284    /// Two rows declare the same plane + service domain with different
285    /// labels. Ambiguous declarations are rejected, never merged.
286    DuplicateDeclaration {
287        plane: MoqEventPlane,
288        service_domain: String,
289    },
290    /// A row declares a service domain that the declared plane's coordinate
291    /// grammar can never produce, so the row can match nothing and the
292    /// objects it names would instead resolve through a shorter prefix
293    /// row's label. Event coordinates split on `.` and reject `/` outright;
294    /// stream coordinates split on `/`.
295    UnrepresentableServiceDomain {
296        plane: MoqEventPlane,
297        service_domain: String,
298    },
299}
300
301impl std::fmt::Display for TrackPolicyError {
302    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
303        match self {
304            TrackPolicyError::UnsupportedRevision { table, supported } => write!(
305                f,
306                "track-policy revision {table} is newer than supported revision {supported}"
307            ),
308            TrackPolicyError::NoncanonicalServiceDomain(domain) => write!(
309                f,
310                "track-policy row declares noncanonical service domain {domain:?}"
311            ),
312            TrackPolicyError::DuplicateDeclaration {
313                plane,
314                service_domain,
315            } => write!(
316                f,
317                "duplicate track-policy declaration for plane {:?} service {service_domain:?}",
318                plane
319            ),
320            TrackPolicyError::UnrepresentableServiceDomain {
321                plane,
322                service_domain,
323            } => write!(
324                f,
325                "track-policy row declares service domain {service_domain:?} that the {:?} \
326                 plane grammar can never represent",
327                plane
328            ),
329        }
330    }
331}
332
333impl std::error::Error for TrackPolicyError {}
334
335/// One declared track-policy row: the declaring service's label for its
336/// objects on one plane. The generated dispatch inventory (WS-D) is the
337/// end-state producer; rows are otherwise declared explicitly.
338#[derive(Debug, Clone, PartialEq, Eq)]
339pub struct MoqEventPolicyRow {
340    /// The plane this declaration covers.
341    pub plane: MoqEventPlane,
342    /// The canonical service domain of the declaring service.
343    pub service_domain: String,
344    /// The label for the declared service's objects on that plane.
345    pub label: SecurityLabel,
346}
347
348/// Plane-representability guard: a declared service domain must be
349/// producible by the declared plane's own coordinate grammar, or the row is
350/// dead — it can match nothing, while the object it names still parses with
351/// the domain's *prefix* as its service coordinate and can silently take a
352/// weaker neighbouring row's label.
353///
354/// This is deliberately **not** a second identity rule: the canonical rule
355/// ([`validate_service_domain`]) stays the one authority on what a service
356/// domain *is* (and it admits `.`/`/` because the RPC/VFS planes use
357/// dotted and path-shaped domains). This guard only asks whether this
358/// plane's grammar — which splits the event coordinate on `.` (segment 0 =
359/// service, `/` rejected outright as a broadcast-path alias) and the
360/// stream coordinate on `/` (segment 1 = service) — could ever yield the
361/// declared domain back.
362fn check_plane_representable(
363    plane: MoqEventPlane,
364    service_domain: &str,
365) -> Result<(), TrackPolicyError> {
366    let unrepresentable = match plane {
367        MoqEventPlane::Event => service_domain.contains('.') || service_domain.contains('/'),
368        MoqEventPlane::Stream => service_domain.contains('/'),
369    };
370    if unrepresentable {
371        return Err(TrackPolicyError::UnrepresentableServiceDomain {
372            plane,
373            service_domain: service_domain.to_owned(),
374        });
375    }
376    Ok(())
377}
378
379impl MoqEventPolicyRow {
380    /// Build a row, rejecting a noncanonical service domain (the shared
381    /// rule — there is no plane-local rewrite) and a domain the declared
382    /// plane's grammar can never represent. `MoqEventPolicyTable::build`
383    /// re-checks both: this type's fields are public, so a struct literal
384    /// bypasses this constructor.
385    pub fn new(
386        plane: MoqEventPlane,
387        service_domain: impl Into<String>,
388        label: SecurityLabel,
389    ) -> Result<Self, TrackPolicyError> {
390        let service_domain = service_domain.into();
391        if validate_service_domain(&service_domain).is_err() {
392            return Err(TrackPolicyError::NoncanonicalServiceDomain(service_domain));
393        }
394        check_plane_representable(plane, &service_domain)?;
395        Ok(Self {
396            plane,
397            service_domain,
398            label,
399        })
400    }
401}
402
403/// Declared track-policy metadata: the closed, validated set of rows the
404/// resolver trusts. This is the reviewed seam onto the generated inventory.
405///
406/// Lookup is an exact typed match on `(plane, canonical service domain)`.
407/// Anything not declared — unknown service, other plane, empty table — is
408/// unlabeled and denies. There is no ancestor walk, no floor, and no
409/// bootstrap exception.
410#[derive(Debug, Clone, PartialEq, Eq)]
411pub struct MoqEventPolicyTable {
412    revision: u32,
413    rows: BTreeMap<(MoqEventPlane, String), SecurityLabel>,
414}
415
416impl MoqEventPolicyTable {
417    /// Build the table from declared rows.
418    ///
419    /// Fails (returning no table) on a revision newer than supported, a
420    /// noncanonical service domain, a service domain the declared plane's
421    /// grammar can never represent (checked here, not only in
422    /// [`MoqEventPolicyRow::new`], because the row fields are public and a
423    /// struct literal must not bypass the guard), or two rows declaring the
424    /// same plane + service with different labels. Older or equal revisions
425    /// are accepted: a newer *server* understanding an older table is
426    /// forward-compatible; the reverse is not, and denies.
427    pub fn build(
428        revision: u32,
429        rows: impl IntoIterator<Item = MoqEventPolicyRow>,
430    ) -> Result<Self, TrackPolicyError> {
431        if revision > SUPPORTED_TRACK_POLICY_REVISION {
432            return Err(TrackPolicyError::UnsupportedRevision {
433                table: revision,
434                supported: SUPPORTED_TRACK_POLICY_REVISION,
435            });
436        }
437        let mut map = BTreeMap::new();
438        for row in rows {
439            if validate_service_domain(&row.service_domain).is_err() {
440                return Err(TrackPolicyError::NoncanonicalServiceDomain(
441                    row.service_domain,
442                ));
443            }
444            check_plane_representable(row.plane, &row.service_domain)?;
445            let key = (row.plane, row.service_domain);
446            if let Some(existing) = map.get(&key) {
447                if *existing != row.label {
448                    return Err(TrackPolicyError::DuplicateDeclaration {
449                        plane: row.plane,
450                        service_domain: key.1,
451                    });
452                }
453                continue;
454            }
455            map.insert(key, row.label);
456        }
457        Ok(Self {
458            revision,
459            rows: map,
460        })
461    }
462
463    /// The table that declares nothing. Every lookup is unlisted and denies;
464    /// this is the honest pre-inventory state, not a bypass.
465    pub fn empty() -> Self {
466        Self {
467            revision: SUPPORTED_TRACK_POLICY_REVISION,
468            rows: BTreeMap::new(),
469        }
470    }
471
472    /// The vocabulary revision this table was declared at.
473    pub fn revision(&self) -> u32 {
474        self.revision
475    }
476
477    /// Number of declared rows.
478    pub fn len(&self) -> usize {
479        self.rows.len()
480    }
481
482    /// Whether no rows are declared.
483    pub fn is_empty(&self) -> bool {
484        self.rows.is_empty()
485    }
486
487    /// Exact typed lookup: the declared label for this object's plane +
488    /// canonical service domain, or `None` when unlisted.
489    pub fn resolve(&self, object: &MoqEventObjectRef) -> Option<SecurityLabel> {
490        self.rows
491            .get(&(object.plane, object.service_domain.clone()))
492            .copied()
493    }
494}
495
496/// The production resolver: exact-match lookup against a validated declared
497/// track-policy table.
498#[derive(Debug, Clone)]
499pub struct DeclaredTrackPolicyResolver {
500    table: MoqEventPolicyTable,
501}
502
503impl DeclaredTrackPolicyResolver {
504    /// Wrap a validated table.
505    pub fn new(table: MoqEventPolicyTable) -> Self {
506        Self { table }
507    }
508
509    /// The declared table this resolver enforces.
510    pub fn table(&self) -> &MoqEventPolicyTable {
511        &self.table
512    }
513}
514
515impl MoqEventLabelResolver for DeclaredTrackPolicyResolver {
516    fn resolve(&self, object: &MoqEventObjectRef) -> Option<SecurityLabel> {
517        self.table.resolve(object)
518    }
519}
520
521#[cfg(test)]
522#[allow(clippy::unwrap_used, clippy::expect_used)]
523mod tests {
524    use super::*;
525    use crate::auth::mac::{Assurance, CompartmentSet, Level};
526
527    fn public_label() -> SecurityLabel {
528        SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY)
529    }
530
531    fn secret_label() -> SecurityLabel {
532        SecurityLabel::new(Level::Secret, Assurance::PqHybrid, CompartmentSet::EMPTY)
533    }
534
535    // ── plane discriminants ───────────────────────────────────────────
536
537    #[test]
538    fn plane_discriminants_decode_exactly_the_known_set() {
539        assert_eq!(
540            MoqEventPlane::from_discriminant(MoqEventPlane::Event.discriminant()),
541            Some(MoqEventPlane::Event)
542        );
543        assert_eq!(
544            MoqEventPlane::from_discriminant(MoqEventPlane::Stream.discriminant()),
545            Some(MoqEventPlane::Stream)
546        );
547        for unknown in [2u16, 3, 7, u16::MAX] {
548            assert_eq!(MoqEventPlane::from_discriminant(unknown), None);
549        }
550    }
551
552    // ── event-prefix identity ─────────────────────────────────────────
553
554    #[test]
555    fn event_prefix_parses_source_as_canonical_service_domain() {
556        let object =
557            MoqEventObjectRef::parse(MoqEventPlane::Event, "worker").expect("bare source parses");
558        assert_eq!(object.plane(), MoqEventPlane::Event);
559        assert_eq!(object.service_domain(), "worker");
560        assert_eq!(object.segments(), ["worker"].map(String::from).as_slice());
561
562        let object = MoqEventObjectRef::parse(MoqEventPlane::Event, "registry.repo789.push")
563            .expect("topic prefix parses");
564        assert_eq!(object.service_domain(), "registry");
565        assert_eq!(
566            object.segments(),
567            ["registry", "repo789", "push"].map(String::from).as_slice()
568        );
569    }
570
571    #[test]
572    fn event_prefix_rejects_noncanonical_service_domains() {
573        // The shared canonical rule: lowercase-initial, charset, 1..=128
574        // bytes. None of these are rewritten — they deny.
575        for bad in [
576            "", "Worker",  // uppercase
577            "_worker", // starts with underscore, not letter/digit
578            "wor ker", // space
579            "wo:rker", // internal map-key separator
580            "wor/ker", // broadcast-path alias
581        ] {
582            assert!(
583                MoqEventObjectRef::parse(MoqEventPlane::Event, bad).is_none(),
584                "{bad:?} must not parse as an event prefix"
585            );
586        }
587    }
588
589    #[test]
590    fn event_prefix_rejects_oversized_segments_and_domain() {
591        let long_segment = "w".repeat(MAX_TRACK_SEGMENT_BYTES + 1);
592        assert!(MoqEventObjectRef::parse(MoqEventPlane::Event, &long_segment).is_none());
593
594        let oversized_domain = "w".repeat(MAX_SERVICE_DOMAIN_BYTES + 1);
595        assert!(
596            MoqEventObjectRef::parse(MoqEventPlane::Event, &oversized_domain).is_none(),
597            "service domain beyond the shared 128-byte rule denies"
598        );
599    }
600
601    // ── segment-count bound: reject the ninth on observation ──────────
602
603    fn dot_name(count: usize) -> String {
604        vec!["worker"; count].join(".")
605    }
606
607    fn slash_name(count: usize) -> String {
608        vec!["worker"; count].join("/")
609    }
610
611    #[test]
612    fn exactly_eight_segments_parse_in_both_syntaxes() {
613        let event = MoqEventObjectRef::parse(MoqEventPlane::Event, &dot_name(MAX_TRACK_SEGMENTS))
614            .expect("eight dot segments parse");
615        assert_eq!(event.segments().len(), MAX_TRACK_SEGMENTS);
616
617        let stream =
618            MoqEventObjectRef::parse(MoqEventPlane::Stream, &slash_name(MAX_TRACK_SEGMENTS))
619                .expect("eight slash segments parse");
620        assert_eq!(stream.segments().len(), MAX_TRACK_SEGMENTS);
621    }
622
623    #[test]
624    fn ninth_segment_rejects_in_both_syntaxes() {
625        // Every segment is individually valid; only the count rejects.
626        assert!(
627            MoqEventObjectRef::parse(MoqEventPlane::Event, &dot_name(MAX_TRACK_SEGMENTS + 1))
628                .is_none()
629        );
630        assert!(MoqEventObjectRef::parse(
631            MoqEventPlane::Stream,
632            &slash_name(MAX_TRACK_SEGMENTS + 1)
633        )
634        .is_none());
635    }
636
637    #[test]
638    fn very_large_names_reject_without_segment_amplification() {
639        // A million individually-valid segments: the parsers reject on
640        // observing the ninth, so neither clones segment 9..=N. Before the
641        // on-observation bound this loop cloned every attacker-controlled
642        // segment before the count check.
643        let million_dots = ["a"; 1_000_000].join(".");
644        assert!(MoqEventObjectRef::parse(MoqEventPlane::Event, &million_dots).is_none());
645        let million_slashes = ["a"; 1_000_000].join("/");
646        assert!(MoqEventObjectRef::parse(MoqEventPlane::Stream, &million_slashes).is_none());
647
648        // A very large ninth tail after eight valid segments: rejected at the
649        // ninth boundary too, bounding both work and allocation by segment
650        // count rather than by name length.
651        let huge_tail = format!(
652            "{}.{}",
653            dot_name(MAX_TRACK_SEGMENTS),
654            "x".repeat(4 * 1024 * 1024)
655        );
656        assert!(MoqEventObjectRef::parse(MoqEventPlane::Event, &huge_tail).is_none());
657        let huge_tail = format!(
658            "{}/{}",
659            slash_name(MAX_TRACK_SEGMENTS),
660            "x".repeat(4 * 1024 * 1024)
661        );
662        assert!(MoqEventObjectRef::parse(MoqEventPlane::Stream, &huge_tail).is_none());
663    }
664
665    #[test]
666    fn event_prefix_rejects_empty_segments() {
667        for bad in [".worker", "worker.", "worker..push", "wor..ker"] {
668            assert!(MoqEventObjectRef::parse(MoqEventPlane::Event, bad).is_none());
669        }
670    }
671
672    // ── stream-track identity ─────────────────────────────────────────
673
674    #[test]
675    fn stream_track_parses_service_at_second_segment() {
676        let object = MoqEventObjectRef::parse(MoqEventPlane::Stream, "alice/streams/run-1/i0")
677            .expect("tenant track parses");
678        assert_eq!(object.plane(), MoqEventPlane::Stream);
679        assert_eq!(object.service_domain(), "streams");
680        assert_eq!(
681            object.segments(),
682            ["alice", "streams", "run-1", "i0"]
683                .map(String::from)
684                .as_slice()
685        );
686
687        let object = MoqEventObjectRef::parse(MoqEventPlane::Stream, "local/streams/deadbeef")
688            .expect("broadcast path parses");
689        assert_eq!(object.service_domain(), "streams");
690
691        let object = MoqEventObjectRef::parse(MoqEventPlane::Stream, "local/events/worker")
692            .expect("event broadcast path parses under the stream grammar");
693        assert_eq!(object.service_domain(), "events");
694    }
695
696    #[test]
697    fn stream_track_rejects_single_segment_and_bad_grammar() {
698        // A lone segment has no service coordinate.
699        assert!(MoqEventObjectRef::parse(MoqEventPlane::Stream, "alice").is_none());
700        // Empty segments and traversal names deny.
701        for bad in [
702            "/streams/x",
703            "alice//run",
704            "alice/streams/run/",
705            "./streams/x",
706            "alice/../streams/run",
707        ] {
708            assert!(
709                MoqEventObjectRef::parse(MoqEventPlane::Stream, bad).is_none(),
710                "{bad:?} must not parse"
711            );
712        }
713        // Noncanonical service segment denies.
714        assert!(MoqEventObjectRef::parse(MoqEventPlane::Stream, "alice/Streams/x").is_none());
715    }
716
717    #[test]
718    fn identities_are_not_reinterpretable_across_grammars() {
719        // An event coordinate with a '/' cannot smuggle a broadcast path.
720        assert!(MoqEventObjectRef::parse(MoqEventPlane::Event, "local/events/worker").is_none());
721        // A stream coordinate and an event coordinate for similar-looking
722        // strings remain distinct typed identities (different plane, domain).
723        let stream = MoqEventObjectRef::parse(MoqEventPlane::Stream, "local/events/worker")
724            .expect("stream grammar applies");
725        let event = MoqEventObjectRef::parse(MoqEventPlane::Event, "events.worker")
726            .expect("event grammar applies");
727        assert_eq!(stream.service_domain(), "events");
728        assert_eq!(event.service_domain(), "events");
729        assert_ne!(stream, event, "plane is part of identity");
730    }
731
732    #[test]
733    fn audit_coordinate_round_trips_the_decoded_segments() {
734        let object = MoqEventObjectRef::parse(MoqEventPlane::Stream, "alice/streams/run-1/i0")
735            .expect("parses");
736        assert_eq!(object.audit_coordinate(), "alice/streams/run-1/i0");
737        let object =
738            MoqEventObjectRef::parse(MoqEventPlane::Event, "registry.repo789.push").unwrap();
739        assert_eq!(object.audit_coordinate(), "registry.repo789.push");
740    }
741
742    // ── declared policy table ─────────────────────────────────────────
743
744    fn declared_table() -> MoqEventPolicyTable {
745        MoqEventPolicyTable::build(
746            SUPPORTED_TRACK_POLICY_REVISION,
747            [
748                MoqEventPolicyRow::new(MoqEventPlane::Event, "worker", secret_label()).unwrap(),
749                MoqEventPolicyRow::new(MoqEventPlane::Event, "registry", public_label()).unwrap(),
750                MoqEventPolicyRow::new(MoqEventPlane::Stream, "streams", public_label()).unwrap(),
751            ],
752        )
753        .unwrap()
754    }
755
756    #[test]
757    fn table_resolves_exactly_the_declared_plane_and_service() {
758        let table = declared_table();
759        let worker =
760            MoqEventObjectRef::parse(MoqEventPlane::Event, "worker.sandbox1.started").unwrap();
761        assert_eq!(table.resolve(&worker), Some(secret_label()));
762
763        // The same service on the *other* plane is a different object:
764        // `worker` is declared for events only, so a stream track whose
765        // service segment is `worker` is unlisted.
766        let worker_as_stream =
767            MoqEventObjectRef::parse(MoqEventPlane::Stream, "tenant/worker/topic1/i0").unwrap();
768        assert_eq!(worker_as_stream.service_domain(), "worker");
769        assert_eq!(table.resolve(&worker_as_stream), None);
770
771        let streams = MoqEventObjectRef::parse(MoqEventPlane::Stream, "a/streams/b/c").unwrap();
772        assert_eq!(table.resolve(&streams), Some(public_label()));
773    }
774
775    #[test]
776    fn unlisted_services_and_empty_table_deny() {
777        let table = declared_table();
778        let unknown = MoqEventObjectRef::parse(MoqEventPlane::Event, "inference.session.x")
779            .expect("parses, but is unlisted");
780        assert_eq!(table.resolve(&unknown), None);
781
782        let empty = MoqEventPolicyTable::empty();
783        assert!(empty.is_empty());
784        let declared = MoqEventObjectRef::parse(MoqEventPlane::Event, "worker").unwrap();
785        assert_eq!(
786            empty.resolve(&declared),
787            None,
788            "empty table denies everything"
789        );
790    }
791
792    #[test]
793    fn newer_table_revision_is_rejected_not_partially_interpreted() {
794        let err = MoqEventPolicyTable::build(
795            SUPPORTED_TRACK_POLICY_REVISION + 1,
796            [MoqEventPolicyRow::new(MoqEventPlane::Event, "worker", public_label()).unwrap()],
797        )
798        .unwrap_err();
799        assert_eq!(
800            err,
801            TrackPolicyError::UnsupportedRevision {
802                table: SUPPORTED_TRACK_POLICY_REVISION + 1,
803                supported: SUPPORTED_TRACK_POLICY_REVISION,
804            }
805        );
806        // An older/equal revision is accepted (forward compatibility runs one
807        // way: newer server, older table).
808        MoqEventPolicyTable::build(
809            SUPPORTED_TRACK_POLICY_REVISION,
810            [MoqEventPolicyRow::new(MoqEventPlane::Event, "worker", public_label()).unwrap()],
811        )
812        .unwrap();
813    }
814
815    #[test]
816    fn table_construction_is_fail_closed() {
817        // Noncanonical row domain rejects.
818        let err =
819            MoqEventPolicyRow::new(MoqEventPlane::Event, "Worker", public_label()).unwrap_err();
820        assert_eq!(
821            err,
822            TrackPolicyError::NoncanonicalServiceDomain("Worker".to_owned())
823        );
824
825        // Conflicting duplicate declarations reject — never merged.
826        let err = MoqEventPolicyTable::build(
827            SUPPORTED_TRACK_POLICY_REVISION,
828            [
829                MoqEventPolicyRow::new(MoqEventPlane::Event, "worker", public_label()).unwrap(),
830                MoqEventPolicyRow::new(MoqEventPlane::Event, "worker", secret_label()).unwrap(),
831            ],
832        )
833        .unwrap_err();
834        assert_eq!(
835            err,
836            TrackPolicyError::DuplicateDeclaration {
837                plane: MoqEventPlane::Event,
838                service_domain: "worker".to_owned(),
839            }
840        );
841
842        // Identical duplicate rows are idempotent, not ambiguous.
843        MoqEventPolicyTable::build(
844            SUPPORTED_TRACK_POLICY_REVISION,
845            [
846                MoqEventPolicyRow::new(MoqEventPlane::Event, "worker", public_label()).unwrap(),
847                MoqEventPolicyRow::new(MoqEventPlane::Event, "worker", public_label()).unwrap(),
848            ],
849        )
850        .unwrap();
851    }
852
853    // ── plane representability: no dead stronger rows (B1) ───────────
854
855    /// The exact B1 event shape: a dead `foo.bar` SECRET row next to a live
856    /// `foo` PUBLIC row. Before the guard, both were accepted, the
857    /// `foo.bar` row matched nothing (the event grammar splits on `.`, so
858    /// `foo.bar.created` parses with service `foo`), and the object silently
859    /// took the weaker PUBLIC label. Now the declaration refuses.
860    #[test]
861    fn unrepresentable_event_domain_cannot_downgrade_declared_label() {
862        // The constructor rejects early…
863        let err =
864            MoqEventPolicyRow::new(MoqEventPlane::Event, "foo.bar", secret_label()).unwrap_err();
865        assert_eq!(
866            err,
867            TrackPolicyError::UnrepresentableServiceDomain {
868                plane: MoqEventPlane::Event,
869                service_domain: "foo.bar".to_owned(),
870            }
871        );
872        // …and so does `/`, which the event grammar rejects outright.
873        MoqEventPolicyRow::new(MoqEventPlane::Event, "foo/bar", secret_label()).unwrap_err();
874
875        // The struct-literal bypass (row fields are pub) is caught at
876        // `build`, which re-runs the guard for exactly that reason.
877        let literal_row = MoqEventPolicyRow {
878            plane: MoqEventPlane::Event,
879            service_domain: "foo.bar".to_owned(),
880            label: secret_label(),
881        };
882        let prefix_row =
883            MoqEventPolicyRow::new(MoqEventPlane::Event, "foo", public_label()).unwrap();
884        let err =
885            MoqEventPolicyTable::build(SUPPORTED_TRACK_POLICY_REVISION, [literal_row, prefix_row])
886                .unwrap_err();
887        assert_eq!(
888            err,
889            TrackPolicyError::UnrepresentableServiceDomain {
890                plane: MoqEventPlane::Event,
891                service_domain: "foo.bar".to_owned(),
892            }
893        );
894
895        // Causal shape, for the record: with only the representable `foo`
896        // row declared, the object the dead row was written to protect
897        // parses under service `foo` and takes its label — which is why an
898        // unrepresentable stronger row must refuse construction instead of
899        // being accepted as dead.
900        let table = MoqEventPolicyTable::build(
901            SUPPORTED_TRACK_POLICY_REVISION,
902            [MoqEventPolicyRow::new(MoqEventPlane::Event, "foo", public_label()).unwrap()],
903        )
904        .unwrap();
905        let object = MoqEventObjectRef::parse(MoqEventPlane::Event, "foo.bar.created").unwrap();
906        assert_eq!(object.service_domain(), "foo");
907        assert_eq!(table.resolve(&object), Some(public_label()));
908    }
909
910    /// The stream shape: a dead `a/b` SECRET row next to a live `a` PUBLIC
911    /// row (`t/a/b/c` parses with service `a`). Same guard, same refusal.
912    #[test]
913    fn unrepresentable_stream_domain_cannot_downgrade_declared_label() {
914        let err = MoqEventPolicyRow::new(MoqEventPlane::Stream, "a/b", secret_label()).unwrap_err();
915        assert_eq!(
916            err,
917            TrackPolicyError::UnrepresentableServiceDomain {
918                plane: MoqEventPlane::Stream,
919                service_domain: "a/b".to_owned(),
920            }
921        );
922
923        // Struct-literal bypass attempt at `build`.
924        let literal_row = MoqEventPolicyRow {
925            plane: MoqEventPlane::Stream,
926            service_domain: "a/b".to_owned(),
927            label: secret_label(),
928        };
929        let prefix_row =
930            MoqEventPolicyRow::new(MoqEventPlane::Stream, "a", public_label()).unwrap();
931        let err =
932            MoqEventPolicyTable::build(SUPPORTED_TRACK_POLICY_REVISION, [literal_row, prefix_row])
933                .unwrap_err();
934        assert_eq!(
935            err,
936            TrackPolicyError::UnrepresentableServiceDomain {
937                plane: MoqEventPlane::Stream,
938                service_domain: "a/b".to_owned(),
939            }
940        );
941
942        // Causal shape: `t/a/b/c` parses with service `a` and takes the
943        // declared `a` label.
944        let table = MoqEventPolicyTable::build(
945            SUPPORTED_TRACK_POLICY_REVISION,
946            [MoqEventPolicyRow::new(MoqEventPlane::Stream, "a", public_label()).unwrap()],
947        )
948        .unwrap();
949        let object = MoqEventObjectRef::parse(MoqEventPlane::Stream, "t/a/b/c").unwrap();
950        assert_eq!(object.service_domain(), "a");
951        assert_eq!(table.resolve(&object), Some(public_label()));
952    }
953
954    #[test]
955    fn deny_all_resolver_labels_nothing() {
956        let resolver = DenyAllMoqEventResolver;
957        let object = MoqEventObjectRef::parse(MoqEventPlane::Event, "worker").unwrap();
958        assert_eq!(resolver.resolve(&object), None);
959    }
960}