Skip to main content

hyprstream_rpc/
moq_authz.rs

1//! Subscribe-time authorization + per-tenant announce scoping for the moq
2//! streaming plane (#276).
3//!
4//! ## Why this module exists
5//!
6//! #274 made the moq streaming plane network-reachable (served on
7//! `web_transport_quinn` at `/moq`, and over the iroh `moql` ALPN via
8//! [`crate::transport::iroh_moq::IrohMoqProtocolHandler`]). That moved the
9//! *open-subscribe surface* onto the network. This is **not** a content hole —
10//! stream content is already protected by the §7.5 trust model (a 64-hex
11//! DH-derived HKDF-of-ECDH capability **topic**, unguessable and learned only
12//! from a signed `StreamInfo` over authenticated RPC, plus a per-frame chained
13//! HMAC). #276 is **metadata defense-in-depth**:
14//!
15//! 1. A *connected* peer can announce-enumerate broadcast (topic) names — moq
16//!    announces broadcasts by prefix, so a subscriber's `announced()` cursor
17//!    sees every broadcast under its allowed prefix. Without scoping, a peer in
18//!    tenant `A` could enumerate tenant `B`'s broadcast names.
19//! 2. Subscribe-time authorization: a *public* stream stays open (preserving
20//!    the working same-tenant subscribe model), but a *private* stream is gated
21//!    through the existing policy engine.
22//!
23//! ## moq-net's authorization primitive
24//!
25//! `moq_net::Server` exposes **no per-subscribe callback**. Authorization in
26//! moq-net is enforced *structurally*: a session can only enumerate/subscribe
27//! to broadcasts that are visible through the [`OriginConsumer`] handed to
28//! `Server::with_publish`. [`OriginConsumer::scope`] / [`OriginConsumer::with_root`]
29//! narrow that visibility by path prefix. So **per-tenant announce scoping** is
30//! implemented by handing each accepted session a tenant-scoped consumer
31//! (see [`tenant_scoped_consumer`]) — a subscriber that cannot *see* a
32//! broadcast cannot subscribe to it either.
33//!
34//! The **subscribe authorization hook** ([`SubscribeAuthorizer`]) is the
35//! pluggable policy layer on top of that structural scoping, for the
36//! public-vs-private distinction within a tenant. Until moq-net exposes the
37//! per-track callback tracked by #276, installing an authorizer rejects the
38//! session at admission. This is intentionally coarse but fail-closed: an
39//! installed policy is never retained as dead configuration while tracks are
40//! served around it.
41//!
42//! Track names are hierarchical `{tenant}/{service}/{topic}/{instance}` (the
43//! #134 CDN-portability invariant). The first path segment is the tenant.
44
45use std::sync::Arc;
46
47#[cfg(not(target_arch = "wasm32"))]
48use moq_net::{OriginConsumer, Path};
49
50use crate::auth::mac::{MacDecision, MoqEventAction, MoqEventPep};
51use crate::envelope::Subject;
52
53/// The hierarchical track-name separator (`{tenant}/{service}/{topic}/{instance}`).
54pub const TRACK_NAME_SEP: char = '/';
55
56/// Return whether `tenant` is one non-empty MoQ path segment.
57///
58/// This validation is security-sensitive: `moq_net::Path::new` normalizes an
59/// empty or slash-only string to the empty path, and an empty prefix is a
60/// wildcard matching every broadcast. Tenant-derived scopes must therefore
61/// reject empty and multi-segment values before constructing a [`Path`].
62pub fn is_valid_tenant_segment(tenant: &str) -> bool {
63    !tenant.is_empty() && !tenant.contains(TRACK_NAME_SEP)
64}
65
66/// Extract the `{tenant}` segment from a hierarchical track / broadcast name.
67///
68/// Names are `{tenant}/{service}/{topic}/{instance}`; the tenant is the first
69/// path segment. Returns `None` for an empty name or a name whose first segment
70/// is empty (e.g. a leading `/`).
71///
72/// ```
73/// use hyprstream_rpc::moq_authz::tenant_of;
74/// assert_eq!(tenant_of("alice/streams/run-1/i0"), Some("alice"));
75/// assert_eq!(tenant_of("alice"), Some("alice"));
76/// assert_eq!(tenant_of(""), None);
77/// assert_eq!(tenant_of("/leading"), None);
78/// ```
79pub fn tenant_of(track_name: &str) -> Option<&str> {
80    match track_name.split(TRACK_NAME_SEP).next() {
81        Some(t) if !t.is_empty() => Some(t),
82        _ => None,
83    }
84}
85
86/// Build the tenant prefix (`{tenant}/`) used to scope announce enumeration.
87///
88/// The trailing separator is significant: moq prefix matching is segment-aware,
89/// so `"alice/"` matches `alice/...` but NOT a sibling tenant `alicent/...`.
90pub fn tenant_prefix(tenant: &str) -> String {
91    format!("{tenant}{TRACK_NAME_SEP}")
92}
93
94/// Pure per-tenant announce filter — the independently-testable core of the
95/// scoping behaviour.
96///
97/// Given a set of broadcast/track names and a tenant, returns only the names
98/// belonging to that tenant (i.e. whose first `{tenant}` segment equals
99/// `tenant`). This is what a peer in `tenant` is permitted to enumerate; names
100/// from other tenants are filtered out so cross-tenant broadcast-name
101/// enumeration is impossible.
102///
103/// Matching is segment-exact on the tenant (`alice` does not match `alicent`).
104pub fn filter_announces_by_tenant<'a, I>(names: I, tenant: &str) -> Vec<&'a str>
105where
106    I: IntoIterator<Item = &'a str>,
107{
108    names
109        .into_iter()
110        .filter(|name| tenant_of(name) == Some(tenant))
111        .collect()
112}
113
114/// Restrict an [`OriginConsumer`] to a single tenant's broadcasts.
115///
116/// This is the live, network-side enforcement of per-tenant announce scoping:
117/// the returned consumer's `announced()` cursor only ever yields broadcasts
118/// under `{tenant}/`, and `subscribe`/`announced_broadcast` for any path outside
119/// that prefix returns `None`. Hand the scoped consumer to
120/// `moq_net::Server::with_publish` for the accepted session and the peer cannot
121/// see — let alone subscribe to — another tenant's broadcasts.
122///
123/// Returns `None` if the requested prefix is outside the consumer's existing
124/// allowed prefixes (the moq-net `scope` contract); callers should treat that
125/// as "this tenant has no visible broadcasts" (serve an empty scope) rather
126/// than falling back to the unscoped consumer.
127#[cfg(not(target_arch = "wasm32"))]
128pub fn tenant_scoped_consumer(consumer: &OriginConsumer, tenant: &str) -> Option<OriginConsumer> {
129    if !is_valid_tenant_segment(tenant) {
130        return None;
131    }
132    let prefix = tenant_prefix(tenant);
133    consumer.scope(&[Path::new(&prefix)])
134}
135
136/// Whether a stream is publicly subscribable or policy-gated.
137///
138/// Public streams preserve the existing open model (any connected, correctly
139/// tenant-scoped peer may subscribe). Private streams are gated through
140/// [`SubscribeAuthorizer`] / the policy engine.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum Visibility {
143    /// Open subscribe (subject only to tenant scoping).
144    Public,
145    /// Subscribe must be authorized by policy.
146    Private,
147}
148
149/// The outcome of a subscribe-authorization check.
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub enum SubscribeDecision {
152    /// The subscribe is permitted.
153    Allow,
154    /// The subscribe is denied (fail-closed for private + unauthorized).
155    Deny,
156}
157
158impl SubscribeDecision {
159    /// `true` iff the decision permits the subscribe.
160    pub fn is_allowed(self) -> bool {
161        matches!(self, SubscribeDecision::Allow)
162    }
163}
164
165/// Identity of the subscribing peer, as far as the moq accept path can
166/// determine it.
167///
168/// Carrier metadata such as an iroh NodeId is not an authorization identity.
169/// Without fresh application proof, peers have `subject == None` and must be
170/// treated as unauthenticated.
171#[derive(Debug, Clone, Default)]
172pub struct PeerIdentity {
173    /// Stable independently verified application subject for policy lookups, or
174    /// `None` for an unauthenticated/anonymous peer.
175    pub subject: Option<String>,
176}
177
178impl PeerIdentity {
179    /// An anonymous peer (no authenticated identity).
180    pub fn anonymous() -> Self {
181        Self { subject: None }
182    }
183
184    /// A peer authenticated as `subject`.
185    pub fn authenticated(subject: impl Into<String>) -> Self {
186        Self {
187            subject: Some(subject.into()),
188        }
189    }
190
191    /// `true` iff this peer carries an authenticated subject.
192    pub fn is_authenticated(&self) -> bool {
193        self.subject.is_some()
194    }
195}
196
197/// Pluggable subscribe-time authorization hook for the moq accept path.
198///
199/// Implementors decide, given the (best-effort) peer identity and the
200/// hierarchical track name, whether a subscribe is permitted. The intended
201/// composition is: **structural tenant scoping** ([`tenant_scoped_consumer`])
202/// gates *visibility / cross-tenant enumeration*, and this hook gates
203/// *public-vs-private* within what's visible.
204///
205/// ## Wiring status
206///
207/// - **iroh `moql` path** ([`crate::transport::iroh_moq::IrohMoqProtocolHandler`]):
208///   `remote_id()` is carrier metadata, never identity. With a
209///   [`crate::transport::moql_admission::MoqlAdmissionAuthenticator`] installed
210///   (#1027) the hook receives the admitted (verified) peer; without one it
211///   receives anonymous and the accept path refuses.
212/// - **quinn `/moq` path** ([`crate::transport::quinn_transport::QuinnRpcServer`]):
213///   as of #1153 the CONNECT is authenticated by
214///   [`crate::transport::moq_connect_auth::MoqConnectAuthz`] (bearer JWT,
215///   verified before the handshake completes); the tenant is resolved from the
216///   *verified* subject and a `tenant_scoped_consumer` is served. With no
217///   `MoqConnectAuthz` installed, the peer is anonymous and the hook receives
218///   [`PeerIdentity::anonymous`] (single-tenant/open model); a policy-gated
219///   authorizer will deny *private* subscribes from anonymous quinn peers
220///   (fail-closed) while public broadcasts remain open.
221///
222/// Async because the MAC-backed authorizer revalidates credential-bearing
223/// cached subject contexts against the canonical revocation authority on
224/// every decision.
225#[async_trait::async_trait]
226pub trait SubscribeAuthorizer: Send + Sync {
227    /// Decide whether `peer` may subscribe to `track_name`.
228    async fn authorize(&self, peer: &PeerIdentity, track_name: &str) -> SubscribeDecision;
229
230    /// Decide admission while moq-net provides no track name callback (#276).
231    ///
232    /// The default is deny. Implementations with an audit path should override
233    /// this method to record the coarse session denial.
234    async fn authorize_without_track_hook(&self, _peer: &PeerIdentity) -> SubscribeDecision {
235        SubscribeDecision::Deny
236    }
237}
238
239/// Classifies a track name as public or private. Returning [`Visibility::Public`]
240/// keeps the existing open model; [`Visibility::Private`] routes through the
241/// policy gate.
242pub type VisibilityFn = Arc<dyn Fn(&str) -> Visibility + Send + Sync>;
243
244/// Evaluates a policy decision for a (subject, tenant, track) tuple. Returns
245/// `true` to allow. This is the seam onto the existing Casbin/PolicyService
246/// (`PolicyManager::check_with_domain`) without `hyprstream-rpc` depending on
247/// the `hyprstream` crate.
248pub type PolicyGate = Arc<dyn Fn(&PeerIdentity, &str) -> bool + Send + Sync>;
249
250/// Default authorizer: **public streams are open, private streams are
251/// policy-gated, and unknown classification fails closed for safety**.
252///
253/// - If [`Visibility::Public`] → always [`SubscribeDecision::Allow`] (preserves
254///   the working same-tenant open-subscribe model).
255/// - If [`Visibility::Private`] → delegate to the [`PolicyGate`]; allow iff the
256///   gate returns `true`. With no gate installed, private subscribes are denied
257///   (fail-closed) — we never invent fail-dangerous behaviour.
258///
259/// When constructed with [`DefaultAuthorizer::permissive`], every track is
260/// treated as public (the pre-#276 behaviour) — used as the default until a
261/// deployment opts into private-stream classification.
262#[derive(Clone)]
263pub struct DefaultAuthorizer {
264    visibility: VisibilityFn,
265    policy: Option<PolicyGate>,
266}
267
268impl DefaultAuthorizer {
269    /// Permissive default: every track is treated as public (open subscribe).
270    /// Per-tenant announce scoping still applies independently.
271    pub fn permissive() -> Self {
272        Self {
273            visibility: Arc::new(|_| Visibility::Public),
274            policy: None,
275        }
276    }
277
278    /// Build with a custom visibility classifier and a policy gate for private
279    /// streams. Private + (no gate or gate-denied) → denied.
280    pub fn new(visibility: VisibilityFn, policy: Option<PolicyGate>) -> Self {
281        Self { visibility, policy }
282    }
283
284    /// Set/replace the visibility classifier.
285    pub fn with_visibility(mut self, visibility: VisibilityFn) -> Self {
286        self.visibility = visibility;
287        self
288    }
289
290    /// Set/replace the policy gate used for private streams.
291    pub fn with_policy(mut self, policy: PolicyGate) -> Self {
292        self.policy = Some(policy);
293        self
294    }
295}
296
297#[async_trait::async_trait]
298impl SubscribeAuthorizer for DefaultAuthorizer {
299    async fn authorize(&self, peer: &PeerIdentity, track_name: &str) -> SubscribeDecision {
300        match (self.visibility)(track_name) {
301            Visibility::Public => SubscribeDecision::Allow,
302            Visibility::Private => match &self.policy {
303                // Fail-closed: a private stream with no policy gate is denied.
304                None => SubscribeDecision::Deny,
305                Some(gate) => {
306                    if gate(peer, track_name) {
307                        SubscribeDecision::Allow
308                    } else {
309                        SubscribeDecision::Deny
310                    }
311                }
312            },
313        }
314    }
315}
316
317/// Shared handle to a [`SubscribeAuthorizer`] suitable for stashing on a
318/// long-lived server/handler.
319pub type SharedSubscribeAuthorizer = Arc<dyn SubscribeAuthorizer>;
320
321// ────────────────────────────────────────────────────────────────────────────
322// MAC-backed subscribe authorizer (issue #1271, epic #547 track T3)
323// ────────────────────────────────────────────────────────────────────────────
324
325/// [`SubscribeAuthorizer`] backed by the shared [`MoqEventPep`] MAC floor.
326///
327/// Maps the [`PeerIdentity`]'s verified subject to a [`Subject`], resolves the
328/// track label + subject clearance via the PEP's seams, and applies
329/// `can_access`. Both seams fail closed (`None` ⇒ [`SubscribeDecision::Deny`]);
330/// there is no permissive bypass (epic #547: no permissive mode). Key possession
331/// (the §7.5 DH-derived topic capability) never substitutes for this decision —
332/// it gates metadata visibility, the MAC floor gates the labeled content.
333///
334/// Typed identity (v16 §10 / #1510): the track name is parsed into the
335/// stream-plane typed identity exactly once at this boundary; a name that
336/// does not decode denies as an unknown identity.
337///
338/// Constructing this adapter installs an active PEP, so missing clearance and
339/// missing labels deny. Leaving the containing transport's authorizer unset is
340/// the dormant pre-activation state and remains pass-through.
341pub struct MacSubscribeAuthorizer {
342    pep: MoqEventPep,
343}
344
345impl MacSubscribeAuthorizer {
346    /// Build with a caller-supplied PEP (real resolver + clearance source).
347    pub fn new(pep: MoqEventPep) -> Self {
348        Self { pep }
349    }
350}
351
352#[async_trait::async_trait]
353impl SubscribeAuthorizer for MacSubscribeAuthorizer {
354    async fn authorize(&self, peer: &PeerIdentity, track_name: &str) -> SubscribeDecision {
355        let subject = match &peer.subject {
356            Some(s) => Subject::new(s.clone()),
357            None => Subject::anonymous(),
358        };
359        if matches!(
360            self.pep
361                .check_stream_track(&subject, track_name, MoqEventAction::Subscribe)
362                .await,
363            MacDecision::Permit
364        ) {
365            SubscribeDecision::Allow
366        } else {
367            SubscribeDecision::Deny
368        }
369    }
370
371    async fn authorize_without_track_hook(&self, peer: &PeerIdentity) -> SubscribeDecision {
372        let subject = match &peer.subject {
373            Some(s) => Subject::new(s.clone()),
374            None => Subject::anonymous(),
375        };
376        self.pep.deny_track_admission_without_hook(&subject).await;
377        SubscribeDecision::Deny
378    }
379}
380
381#[cfg(test)]
382#[allow(clippy::expect_used, clippy::unwrap_used)]
383mod tests {
384    use super::*;
385
386    #[test]
387    fn tenant_of_extracts_first_segment() {
388        assert_eq!(tenant_of("alice/streams/run-1/i0"), Some("alice"));
389        assert_eq!(tenant_of("bob/svc/topic/inst"), Some("bob"));
390        assert_eq!(tenant_of("solo"), Some("solo"));
391        assert_eq!(tenant_of(""), None);
392        assert_eq!(tenant_of("/leading"), None);
393    }
394
395    #[test]
396    fn tenant_prefix_is_segment_significant() {
397        assert_eq!(tenant_prefix("alice"), "alice/");
398    }
399
400    #[test]
401    fn tenant_segment_validation_rejects_root_wildcards_and_nested_scopes() {
402        assert!(is_valid_tenant_segment("alice"));
403        assert!(!is_valid_tenant_segment(""));
404        assert!(!is_valid_tenant_segment("/"));
405        assert!(!is_valid_tenant_segment("///"));
406        assert!(!is_valid_tenant_segment("/alice"));
407        assert!(!is_valid_tenant_segment("alice/"));
408        assert!(!is_valid_tenant_segment("alice/bob"));
409    }
410
411    #[test]
412    fn tenant_scoped_consumer_rejects_invalid_tenant_before_path_normalization() {
413        let producer = moq_net::Origin::random().produce();
414        let consumer = producer.consume();
415
416        for tenant in ["", "/", "///", "/alice", "alice/", "alice/bob"] {
417            assert!(
418                tenant_scoped_consumer(&consumer, tenant).is_none(),
419                "invalid tenant {tenant:?} must not become a root or nested scope"
420            );
421        }
422    }
423
424    #[test]
425    fn announce_filter_scopes_to_one_tenant() {
426        let names = [
427            "alice/streams/run-1/i0",
428            "alice/streams/run-2/i0",
429            "bob/streams/run-9/i0",
430            "carol/streams/run-3/i0",
431        ];
432        let a = filter_announces_by_tenant(names.iter().copied(), "alice");
433        assert_eq!(a, vec!["alice/streams/run-1/i0", "alice/streams/run-2/i0"]);
434        // Tenant A sees ONLY A's names — not B's or C's.
435        assert!(!a.iter().any(|n| n.starts_with("bob/")));
436        assert!(!a.iter().any(|n| n.starts_with("carol/")));
437
438        let b = filter_announces_by_tenant(names.iter().copied(), "bob");
439        assert_eq!(b, vec!["bob/streams/run-9/i0"]);
440    }
441
442    #[test]
443    fn announce_filter_is_segment_exact_no_prefix_bleed() {
444        // "alice" must NOT match a sibling tenant "alicent".
445        let names = ["alice/s/t/i", "alicent/s/t/i"];
446        let a = filter_announces_by_tenant(names.iter().copied(), "alice");
447        assert_eq!(a, vec!["alice/s/t/i"]);
448    }
449
450    #[test]
451    fn announce_filter_empty_for_unknown_tenant() {
452        let names = ["alice/s/t/i", "bob/s/t/i"];
453        assert!(filter_announces_by_tenant(names.iter().copied(), "zzz").is_empty());
454    }
455
456    #[tokio::test]
457    async fn public_stream_is_allowed_even_anonymous() {
458        let authz = DefaultAuthorizer::permissive();
459        let decision = authz
460            .authorize(&PeerIdentity::anonymous(), "alice/s/t/i")
461            .await;
462        assert_eq!(decision, SubscribeDecision::Allow);
463        assert!(decision.is_allowed());
464    }
465
466    #[tokio::test]
467    async fn private_stream_without_gate_is_denied() {
468        // All-private classifier, no gate installed → fail-closed deny.
469        let authz = DefaultAuthorizer::new(Arc::new(|_| Visibility::Private), None);
470        let decision = authz
471            .authorize(
472                &PeerIdentity::authenticated("did:key:z6Mk..."),
473                "alice/s/t/i",
474            )
475            .await;
476        assert_eq!(decision, SubscribeDecision::Deny);
477    }
478
479    #[tokio::test]
480    async fn private_stream_authorized_peer_is_allowed() {
481        // Private classifier + gate that allows a specific subject.
482        let gate: PolicyGate = Arc::new(|peer: &PeerIdentity, _track: &str| {
483            peer.subject.as_deref() == Some("alice-node")
484        });
485        let authz = DefaultAuthorizer::new(Arc::new(|_| Visibility::Private), Some(gate));
486
487        let allowed = authz
488            .authorize(&PeerIdentity::authenticated("alice-node"), "alice/s/t/i")
489            .await;
490        assert_eq!(allowed, SubscribeDecision::Allow);
491    }
492
493    #[tokio::test]
494    async fn private_stream_unauthorized_peer_is_rejected() {
495        let gate: PolicyGate = Arc::new(|peer: &PeerIdentity, _track: &str| {
496            peer.subject.as_deref() == Some("alice-node")
497        });
498        let authz = DefaultAuthorizer::new(Arc::new(|_| Visibility::Private), Some(gate));
499
500        // Different subject → denied.
501        let denied = authz
502            .authorize(&PeerIdentity::authenticated("mallory-node"), "alice/s/t/i")
503            .await;
504        assert_eq!(denied, SubscribeDecision::Deny);
505
506        // Anonymous peer on a private stream → denied (fail-closed).
507        let anon = authz
508            .authorize(&PeerIdentity::anonymous(), "alice/s/t/i")
509            .await;
510        assert_eq!(anon, SubscribeDecision::Deny);
511    }
512
513    #[tokio::test]
514    async fn mixed_visibility_routes_public_open_private_gated() {
515        // Public iff under "pub/" prefix; everything else private.
516        let visibility: VisibilityFn = Arc::new(|track: &str| {
517            if tenant_of(track) == Some("pub") {
518                Visibility::Public
519            } else {
520                Visibility::Private
521            }
522        });
523        let gate: PolicyGate =
524            Arc::new(|peer: &PeerIdentity, _| peer.subject.as_deref() == Some("priv-allowed"));
525        let authz = DefaultAuthorizer::new(visibility, Some(gate));
526
527        // Public stream: open even to anonymous.
528        assert_eq!(
529            authz
530                .authorize(&PeerIdentity::anonymous(), "pub/s/t/i")
531                .await,
532            SubscribeDecision::Allow
533        );
534        // Private stream: authorized subject allowed.
535        assert_eq!(
536            authz
537                .authorize(&PeerIdentity::authenticated("priv-allowed"), "alice/s/t/i")
538                .await,
539            SubscribeDecision::Allow
540        );
541        // Private stream: other subject denied.
542        assert_eq!(
543            authz
544                .authorize(&PeerIdentity::authenticated("nope"), "alice/s/t/i")
545                .await,
546            SubscribeDecision::Deny
547        );
548    }
549
550    #[test]
551    fn peer_identity_constructors() {
552        assert!(!PeerIdentity::anonymous().is_authenticated());
553        assert!(PeerIdentity::authenticated("x").is_authenticated());
554        assert_eq!(
555            PeerIdentity::authenticated("x").subject.as_deref(),
556            Some("x")
557        );
558    }
559}
560
561#[cfg(all(test, not(target_arch = "wasm32")))]
562#[allow(clippy::expect_used, clippy::unwrap_used)]
563mod scope_tests {
564    use super::*;
565    use moq_net::Origin;
566
567    /// A tenant-scoped consumer sees ONLY its own tenant's broadcasts on the
568    /// announce cursor — the live (network-side) analogue of
569    /// [`filter_announces_by_tenant`]. Tenant A must not enumerate B's names.
570    #[tokio::test]
571    async fn tenant_scoped_consumer_filters_announces() {
572        let producer = Origin::random().produce();
573        let base = producer.consume();
574
575        // Publish broadcasts for two tenants.
576        let _a1 = producer.create_broadcast("alice/streams/run-1/i0").unwrap();
577        let _a2 = producer.create_broadcast("alice/streams/run-2/i0").unwrap();
578        let _b1 = producer.create_broadcast("bob/streams/run-9/i0").unwrap();
579
580        // Scope a consumer to tenant "alice".
581        let mut scoped = tenant_scoped_consumer(&base, "alice").expect("alice scope should exist");
582
583        // Drain everything currently announced through the scoped cursor.
584        // `OriginAnnounce` is `(path, Some(broadcast))` for an announce and
585        // `(path, None)` for an unannounce; we only collect announces.
586        let mut seen = Vec::new();
587        while let Some((path, active)) = scoped.try_announced() {
588            if active.is_some() {
589                // path is absolute and always under the scoped prefix.
590                seen.push(path.as_str().to_owned());
591            }
592        }
593        seen.sort();
594
595        assert_eq!(
596            seen,
597            vec![
598                "alice/streams/run-1/i0".to_owned(),
599                "alice/streams/run-2/i0".to_owned(),
600            ]
601        );
602        // Crucially: bob's broadcast is NOT visible to the alice-scoped consumer.
603        assert!(!seen.iter().any(|n| n.starts_with("bob/")));
604    }
605
606    /// A scoped consumer cannot subscribe to another tenant's broadcast even by
607    /// exact path: `announced_broadcast` for an out-of-scope path returns None.
608    #[tokio::test]
609    async fn tenant_scoped_consumer_cannot_reach_other_tenant() {
610        let producer = Origin::random().produce();
611        let base = producer.consume();
612        let _b1 = producer.create_broadcast("bob/streams/run-9/i0").unwrap();
613
614        let scoped = tenant_scoped_consumer(&base, "alice").expect("alice scope should exist");
615
616        // bob/... is outside alice's scope → not reachable.
617        let reached = scoped.announced_broadcast("bob/streams/run-9/i0").await;
618        assert!(
619            reached.is_none(),
620            "alice-scoped consumer must not reach bob's broadcast"
621        );
622    }
623
624    // ── #1271: MAC-backed subscribe authorizer ─────────────────────────────
625
626    #[test]
627    fn dormant_subscribe_authorizer_is_absent() {
628        let config = crate::transport::iroh_moq::MoqAuthzConfig::default();
629        assert!(config.authorizer.is_none());
630    }
631
632    #[tokio::test]
633    async fn mac_subscribe_authorizer_fail_closed_denies_all() {
634        use crate::auth::mac::{
635            DenyAllClearanceSource, DenyAllMoqEventResolver, MoqMacAuditReason, MoqMacAuditRecord,
636            MoqMacAuditSink,
637        };
638        use parking_lot::Mutex;
639
640        #[derive(Default)]
641        struct RecordingAudit {
642            records: Mutex<Vec<MoqMacAuditRecord>>,
643        }
644        impl MoqMacAuditSink for RecordingAudit {
645            fn record_deny(&self, record: &MoqMacAuditRecord) -> Result<(), String> {
646                self.records.lock().push(record.clone());
647                Ok(())
648            }
649        }
650
651        // Once installed, missing clearance/labels deny.
652        let audit = Arc::new(RecordingAudit::default());
653        let authz = Arc::new(super::MacSubscribeAuthorizer::new(
654            crate::auth::mac::MoqEventPep::new(
655                Arc::new(DenyAllMoqEventResolver),
656                Arc::new(DenyAllClearanceSource),
657                audit.clone(),
658            ),
659        ));
660        assert_eq!(
661            authz.authorize(&PeerIdentity::anonymous(), "t").await,
662            SubscribeDecision::Deny
663        );
664        assert_eq!(
665            authz
666                .authorize(&PeerIdentity::authenticated("did:web:x"), "t")
667                .await,
668            SubscribeDecision::Deny
669        );
670        let config = crate::transport::iroh_moq::MoqAuthzConfig::default().with_authorizer(authz);
671        assert_eq!(
672            config
673                .authorize_without_track_hook(&PeerIdentity::authenticated("did:web:x"))
674                .await,
675            SubscribeDecision::Deny
676        );
677        let records = audit.records.lock();
678        assert_eq!(records.len(), 3);
679        assert_eq!(
680            records[2].reason,
681            MoqMacAuditReason::TrackAdmissionHookUnavailable
682        );
683    }
684}