Skip to main content

hyprstream_rpc/
events.rs

1//! Unified EventService publisher/subscriber (epic #600).
2//!
3//! Public publishers preserve the existing plaintext MoQ event path. Confidential
4//! publishers use controller-managed group epochs: the controller atomically
5//! prepares and commits each membership-version/epoch transition, then distributes
6//! the fresh epoch secret separately to each accepted member with HyKEM
7//! (X25519 + ML-KEM-768) and COSE_Encrypt0. The stock relay only forwards opaque
8//! event bytes and never receives an epoch grant.
9//!
10//! Event objects derive distinct sender/track AEAD keys and deterministic nonce
11//! domains from the epoch secret. Their AAD binds publisher, track, membership
12//! version, epoch, and sequence; subscribers reject nonce misuse, replay, unknown
13//! epochs, and retired objects. Publisher identity is anchored by the controller
14//! grant and attested with mandatory Ed25519 + ML-DSA-65 composite signatures.
15//! Ed25519 keys and subscriber-generated blinded Ristretto presentations are never
16//! used as KEX keys.
17//!
18//! # Wire format
19//!
20//! `EventPrivacy::Public` publishes payloads unmodified. Confidential modes encode
21//! an [`EncryptedEvent`] as a versioned, length-prefixed MoQ payload:
22//!
23//! ```text
24//! [1B version][16B session_id][12B nonce][16B key_commitment]
25//! [4B tag_len][tag][4B ciphertext_len][ciphertext][4B lk_tag_len][lk_tag]
26//! [8B timestamp BE][8B membership_version][8B epoch][8B sequence]
27//! [32B publisher_pubkey][4B signature_len][hybrid signature]
28//! ```
29//!
30//! The topic remains the MoQ frame topic. It is authenticated by the hybrid
31//! signature; deployments requiring routing opacity bind the controller's opaque
32//! routing policy into each member grant.
33
34use std::collections::{HashMap, HashSet, VecDeque};
35use std::sync::{Arc, OnceLock};
36use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
37
38use anyhow::{anyhow, Result};
39use ed25519_dalek::SigningKey;
40use rand::RngCore;
41use tokio::sync::RwLock;
42use tracing::debug;
43use zeroize::Zeroizing;
44
45use crate::auth::mac::{MacDecision, MoqEventAction, MoqEventPep};
46use crate::crypto::cose_sign::{sign_composite, verify_composite};
47use crate::crypto::event_crypto::{
48    build_epoch_event_sig_message, decrypt_epoch_event, derive_event_nonce, encrypt_epoch_event,
49    EventPrivacy,
50};
51use crate::crypto::group_key::{open_epoch_grant, EpochGrant};
52use crate::crypto::hybrid_kem::RecipientKeypair;
53use crate::crypto::keyed_mac;
54use crate::crypto::pq::{ml_dsa_vk_bytes, MlDsaSigningKey};
55use crate::envelope::Subject;
56// The four shared event types + the rotation constants are canonical in the
57// keyable-group primitive (`crypto::group_key`); re-export them here so the
58// `hyprstream_rpc::events::*` surface downstream consumers already use stays
59// stable. (Only the EventService-specific `EncryptedEvent` wire codec + the
60// `EventPublisher`/`EventSubscriber`/`KeyRing` types are defined in this module.)
61pub use crate::crypto::group_key::{
62    EncryptedEvent, RekeyPolicy, RotationResult, WrappedKeyEntry, DEFAULT_ROTATION_INTERVAL,
63    GRACE_PERIOD, MAX_KEY_LIFETIME,
64};
65use crate::moq_event::{
66    global_moq_event_origin, BackfillMode, MoqEventPublisher, MoqEventSubscriber,
67};
68
69// ============================================================================
70// Rekey policy — the type + its constants live in the keyable-group primitive
71// (`crypto::group_key`); this module re-imports them above. Only the
72// subscriber-side grace constant below is specific to this module.
73// ============================================================================
74
75/// Maximum grace period in which a subscriber accepts authenticated objects
76/// from the prior epoch, bounded by the controller-supplied last-issued
77/// sequence. Security-triggered transitions install zero grace.
78pub const DEFAULT_SUBSCRIBER_GRACE_PERIOD: Duration = Duration::from_secs(30);
79/// Maximum accepted event identities retained for one subscriber prefix. Older
80/// identities age out of this replay window rather than growing memory for the
81/// entire lifetime of a long-running epoch.
82pub const MAX_REPLAY_WINDOW: usize = 4_096;
83
84// Rekey policy configuration remains an API-level scheduling hint. Every
85// controller membership/security transition nevertheless prepares a fresh
86// epoch and O(M) per-member HyKEM/COSE grants; EventPublisher cannot rotate or
87// distribute epochs itself.
88//
89// Recommended use: `Scheduled`/`Jittered` for the steady state; switch a
90// specific prefix to `Immediate` only around an explicit revocation, then
91// switch back.
92//
93// The type itself + its `Default`/`validate` impls live in the keyable-group
94// primitive ([`crate::crypto::group_key`]); this module re-uses them.
95
96// ============================================================================
97// EncryptedEvent — wire-encodable result of encrypting an event
98// ============================================================================
99
100const WIRE_VERSION: u8 = 3;
101const EVENT_ATTESTATION_SCHEMA_ID: u64 = 0x86fe_5f45_a782_3a11;
102const EVENT_ATTESTATION_TYPE_ID: u64 = 0x4576_7448_7942_3032; // "EvtHyB02"
103
104fn event_attestation_aad() -> Vec<u8> {
105    crate::crypto::cose_sign1::build_external_aad(
106        EVENT_ATTESTATION_SCHEMA_ID,
107        EVENT_ATTESTATION_TYPE_ID,
108    )
109}
110
111impl EncryptedEvent {
112    /// Encode the non-topic fields into a wire frame body (see module docs
113    /// for the exact layout). `topic` travels separately as the moq frame's
114    /// topic field and is reattached by [`Self::decode_body`].
115    fn encode_body(&self) -> Vec<u8> {
116        let mut buf = Vec::with_capacity(
117            1 + 16
118                + 12
119                + 16
120                + 4
121                + self.tag.len()
122                + 4
123                + self.ciphertext.len()
124                + 4
125                + self.lk_tag.len()
126                + 8
127                + 8
128                + 8
129                + 8
130                + 32
131                + 4
132                + self.signature.len(),
133        );
134        buf.push(WIRE_VERSION);
135        buf.extend_from_slice(&self.session_id);
136        buf.extend_from_slice(&self.nonce);
137        buf.extend_from_slice(&self.key_commitment);
138        push_lenprefixed(&mut buf, &self.tag);
139        push_lenprefixed(&mut buf, &self.ciphertext);
140        push_lenprefixed(&mut buf, &self.lk_tag);
141        buf.extend_from_slice(&self.timestamp.to_be_bytes());
142        buf.extend_from_slice(&self.membership_version.to_be_bytes());
143        buf.extend_from_slice(&self.epoch.to_be_bytes());
144        buf.extend_from_slice(&self.sequence.to_be_bytes());
145        buf.extend_from_slice(&self.publisher_pubkey);
146        push_lenprefixed(&mut buf, &self.signature);
147        buf
148    }
149
150    /// Decode a wire frame body produced by [`Self::encode_body`], reattaching
151    /// the `topic` the moq frame carried separately.
152    fn decode_body(topic: &str, buf: &[u8]) -> Result<Self> {
153        let mut off = 0usize;
154        let version = read_u8(buf, &mut off)?;
155        if version != WIRE_VERSION {
156            return Err(anyhow!("unsupported event wire version {version}"));
157        }
158        let session_id: [u8; 16] = read_array(buf, &mut off)?;
159        let nonce: [u8; 12] = read_array(buf, &mut off)?;
160        let key_commitment: [u8; 16] = read_array(buf, &mut off)?;
161        let tag = read_lenprefixed(buf, &mut off)?;
162        let ciphertext = read_lenprefixed(buf, &mut off)?;
163        let lk_tag = read_lenprefixed(buf, &mut off)?;
164        let timestamp_bytes: [u8; 8] = read_array(buf, &mut off)?;
165        let timestamp = i64::from_be_bytes(timestamp_bytes);
166        let membership_version = u64::from_be_bytes(read_array(buf, &mut off)?);
167        let epoch = u64::from_be_bytes(read_array(buf, &mut off)?);
168        let sequence = u64::from_be_bytes(read_array(buf, &mut off)?);
169        let publisher_pubkey: [u8; 32] = read_array(buf, &mut off)?;
170        let signature = read_lenprefixed(buf, &mut off)?;
171        if off != buf.len() {
172            return Err(anyhow!("event wire: trailing bytes"));
173        }
174        Ok(Self {
175            topic: topic.to_owned(),
176            tag,
177            ciphertext,
178            nonce,
179            key_commitment,
180            lk_tag,
181            signature,
182            publisher_pubkey,
183            timestamp,
184            session_id,
185            membership_version,
186            epoch,
187            sequence,
188        })
189    }
190}
191
192fn push_lenprefixed(buf: &mut Vec<u8>, data: &[u8]) {
193    buf.extend_from_slice(&(data.len() as u32).to_be_bytes());
194    buf.extend_from_slice(data);
195}
196
197fn read_u8(buf: &[u8], off: &mut usize) -> Result<u8> {
198    let b = *buf
199        .get(*off)
200        .ok_or_else(|| anyhow!("event wire: truncated reading version byte"))?;
201    *off += 1;
202    Ok(b)
203}
204
205fn read_array<const N: usize>(buf: &[u8], off: &mut usize) -> Result<[u8; N]> {
206    let end = *off + N;
207    let slice = buf
208        .get(*off..end)
209        .ok_or_else(|| anyhow!("event wire: truncated reading {N}-byte field"))?;
210    *off = end;
211    slice
212        .try_into()
213        .map_err(|_| anyhow!("event wire: array conversion failed"))
214}
215
216fn read_lenprefixed(buf: &[u8], off: &mut usize) -> Result<Vec<u8>> {
217    let len_bytes: [u8; 4] = read_array(buf, off)?;
218    let len = u32::from_be_bytes(len_bytes) as usize;
219    let end = *off + len;
220    let slice = buf
221        .get(*off..end)
222        .ok_or_else(|| anyhow!("event wire: truncated reading {len}-byte length-prefixed field"))?;
223    *off = end;
224    Ok(slice.to_vec())
225}
226
227fn now_millis() -> i64 {
228    SystemTime::now()
229        .duration_since(UNIX_EPOCH)
230        .unwrap_or_default()
231        .as_millis() as i64
232}
233
234fn hash_prefix_bytes(data: &[u8]) -> [u8; 32] {
235    *blake3::hash(data).as_bytes()
236}
237
238fn tenant_prefix_key(tenant: &str, prefix: &str) -> String {
239    format!("{}:{tenant}{prefix}", tenant.len())
240}
241
242fn tenant_prefix_source(tenant: &str, prefix: &str) -> String {
243    let key = tenant_prefix_key(tenant, prefix);
244    format!("secure-{}", blake3::hash(key.as_bytes()).to_hex())
245}
246
247// ============================================================================
248// EventPublisher — the canonical broadcast publisher
249// ============================================================================
250
251/// Controller-installed crypto state for one encrypted prefix.
252///
253/// EventService never invents or distributes this key. The controller creates
254/// the epoch through `GroupKeyRegistry`, commits membership+epoch atomically,
255/// and installs the resulting secret here on an authorized publisher.
256struct PrefixCrypto {
257    membership_version: u64,
258    epoch: u64,
259    current: Zeroizing<[u8; 32]>,
260    sequence: u64,
261    session_id: [u8; 16],
262    created_at: Instant,
263}
264
265/// Per-prefix state: the moq transport for `local/events/{prefix}`, plus
266/// optional encryption state.
267struct PrefixState {
268    moq: MoqEventPublisher,
269    confidential: bool,
270    crypto: Option<PrefixCrypto>,
271}
272
273// ============================================================================
274// Event-plane authorization + publisher identity (EV4, epic #600)
275//
276// This is the EventService PEP (Policy Enforcement Point) for the
277// `publish`/`subscribe` ScopeActions. The load-bearing membership gate for
278// obtaining `K_group` is the fail-closed `MembershipResolver` used by
279// `GroupKeyRegistry::prepare_change`; these checks guard the event paths.
280//
281// The reference-monitor enforcement at the *generated 9P mount* is S2 (#568,
282// blocked on #539) — that is a separate PEP. EV4 wires the event-plane PEP;
283// when S2 lands the two share S1's subject/label model but stay distinct
284// enforcement points (mount-namespace vs event-plane).
285// ============================================================================
286
287/// The caller attempting an event-plane op (`publish`/`subscribe`). Carries the
288/// verified subject identity (a DID when available). Until #446 lands, IPC
289/// callers may resolve as `anonymous` — see [`PublisherIdentity`].
290///
291/// Async because the MAC-backed adapter revalidates credential-bearing cached
292/// subject contexts against the canonical revocation authority on every check.
293#[async_trait::async_trait]
294pub trait EventAuthz: Send + Sync {
295    /// Bind a verified carrier witness to the authority granting clearance.
296    #[cfg(not(target_arch = "wasm32"))]
297    fn admission_is_current(
298        &self,
299        _peer: &crate::transport::moql_admission::AdmittedMoqPeer,
300    ) -> bool {
301        true
302    }
303    /// Finite source inventory used at session admission. A held session only
304    /// revalidates its acquired grants; adding scope requires new admission.
305    fn sources(&self) -> &[&str] {
306        INTERNAL_EVENT_SOURCES
307    }
308    /// Watchdog checks must consult current authority without sampling or
309    /// suppressing audits on actual attempted operations.
310    async fn revalidate_publish(&self, caller: &Subject, prefix: &str) -> bool {
311        self.can_publish(caller, prefix).await
312    }
313    async fn revalidate_subscribe(&self, caller: &Subject, prefix: &str) -> bool {
314        self.can_subscribe(caller, prefix).await
315    }
316    /// May `caller` publish to the group/`prefix`? Maps to the `publish`
317    /// ScopeAction.
318    async fn can_publish(&self, caller: &Subject, prefix: &str) -> bool;
319    /// May `caller` subscribe to the group/`prefix`? Maps to the `subscribe`
320    /// ScopeAction.
321    async fn can_subscribe(&self, caller: &Subject, prefix: &str) -> bool;
322    /// May `caller` receive an encrypted epoch key and decrypt this prefix?
323    async fn can_join_decrypt(&self, caller: &Subject, prefix: &str) -> bool {
324        self.can_subscribe(caller, prefix).await
325    }
326}
327
328static EVENT_AUTHZ: OnceLock<Arc<dyn EventAuthz>> = OnceLock::new();
329
330/// Reviewed native health/lifecycle producers. Worker workflows are separate.
331pub const INTERNAL_EVENT_SOURCES: &[&str] = &["system", "model"];
332
333/// Clone the process reference monitor for authenticated network Event sessions.
334pub fn installed_event_authz() -> Option<Arc<dyn EventAuthz>> {
335    EVENT_AUTHZ.get().cloned()
336}
337
338/// Whether the process-wide event reference monitor has been installed.
339#[must_use]
340pub fn event_authz_installed() -> bool {
341    EVENT_AUTHZ.get().is_some()
342}
343
344/// Install the process-wide production event authorization adapter.
345///
346/// This is one-shot because replacing a live reference monitor would create a
347/// policy gap between already-constructed and new publishers.
348pub fn install_event_authz(authz: Arc<dyn EventAuthz>) -> std::result::Result<(), &'static str> {
349    EVENT_AUTHZ
350        .set(authz)
351        .map_err(|_| "event authorization already installed")
352}
353
354/// Fail-closed authz: denies every publish/subscribe. The default for the
355/// encrypted (`ZeroKnowledge`/`LimitedKnowledge`) profile — MAC deny-by-default
356/// by construction. Production wires a real UCAN/capability-backed impl (S3/S4
357/// vocab on main) via [`EventPublisher::with_authz`].
358pub struct DenyAllEventAuthz;
359#[async_trait::async_trait]
360impl EventAuthz for DenyAllEventAuthz {
361    async fn can_publish(&self, _caller: &Subject, _prefix: &str) -> bool {
362        false
363    }
364    async fn can_subscribe(&self, _caller: &Subject, _prefix: &str) -> bool {
365        false
366    }
367}
368
369/// Explicit permissive authz for callers that deliberately construct a public
370/// firehose or a test fixture. It is never an implicit fallback.
371pub struct AllowAllEventAuthz;
372#[async_trait::async_trait]
373impl EventAuthz for AllowAllEventAuthz {
374    async fn can_publish(&self, _caller: &Subject, _prefix: &str) -> bool {
375        true
376    }
377    async fn can_subscribe(&self, _caller: &Subject, _prefix: &str) -> bool {
378        true
379    }
380}
381
382/// Adapter from the canonical MAC contract to the event authorization surface.
383///
384/// Constructing this type installs an active PEP, so all missing clearance or
385/// object labels fail closed. Uninstalled publishers/subscribers use
386/// [`DenyAllEventAuthz`], never a dormant permit fallback.
387///
388/// Typed identity (v16 §10 / #1510): each check parses the topic-prefix
389/// grammar exactly once at this boundary. Tenant-qualified internal map keys
390/// (for example `"5:tenantworker"`) are bookkeeping keys, not identities,
391/// and must never cross this boundary. Confidential callers retain those keys
392/// only for state lookup, while presenting the underlying Event prefix here.
393pub struct MacEventAuthz {
394    pep: MoqEventPep,
395}
396
397impl MacEventAuthz {
398    /// Service-specific ownership is independent of the MAC lattice floor.
399    pub fn deny_scope(&self, subject: &Subject, prefix: &str, action: MoqEventAction) -> bool {
400        self.pep.deny_event_scope(subject, prefix, action);
401        false
402    }
403    pub fn new(pep: MoqEventPep) -> Self {
404        Self { pep }
405    }
406}
407
408#[async_trait::async_trait]
409impl EventAuthz for MacEventAuthz {
410    async fn revalidate_publish(&self, caller: &Subject, prefix: &str) -> bool {
411        self.pep.event_grant_is_current(caller, prefix).await
412    }
413    async fn revalidate_subscribe(&self, caller: &Subject, prefix: &str) -> bool {
414        self.pep.event_grant_is_current(caller, prefix).await
415    }
416    async fn can_publish(&self, caller: &Subject, prefix: &str) -> bool {
417        matches!(
418            self.pep
419                .check_event_prefix(caller, prefix, MoqEventAction::Publish)
420                .await,
421            MacDecision::Permit
422        )
423    }
424
425    async fn can_subscribe(&self, caller: &Subject, prefix: &str) -> bool {
426        matches!(
427            self.pep
428                .check_event_prefix(caller, prefix, MoqEventAction::Subscribe)
429                .await,
430            MacDecision::Permit
431        )
432    }
433
434    async fn can_join_decrypt(&self, caller: &Subject, prefix: &str) -> bool {
435        matches!(
436            self.pep
437                .check_event_prefix(caller, prefix, MoqEventAction::JoinDecrypt)
438                .await,
439            MacDecision::Permit
440        )
441    }
442}
443
444/// The publisher's verified identity (EV4 authn-on-publish). Binds a publish to
445/// a DID when the verified identity is available.
446///
447/// **#446-gated stub:** until #446 lands, service-to-service IPC callers
448/// resolve as `anonymous` (key-derived identity lost over UDS), so `did` is
449/// `None` on those paths. A `None` DID is treated as **fail-closed** for the
450/// confidential profile (an anonymous publisher cannot be bound to a DID), with
451/// a `// TODO(#446)` seam for the real identity. Do NOT fake a verified DID.
452#[derive(Debug, Clone)]
453pub struct PublisherIdentity {
454    /// The publisher's verified DID, when known. `None` on #446-affected IPC
455    /// paths (anonymous) — confidential publish fails-closed in that case.
456    pub did: Option<String>,
457}
458
459impl PublisherIdentity {
460    /// An anonymous publisher (no verified DID) — the #446-affected default.
461    pub fn anonymous() -> Self {
462        Self { did: None }
463    }
464    /// A publisher with a verified DID (post-#446, or non-IPC paths).
465    pub fn verified(did: impl Into<String>) -> Self {
466        Self {
467            did: Some(did.into()),
468        }
469    }
470    /// Is a verified DID bound? (Confidential publish requires this.)
471    pub fn is_verified(&self) -> bool {
472        self.did.is_some()
473    }
474}
475
476/// The local Event caller selected by checkpoint-verified process bootstrap.
477/// This supplies an identity to MAC, never a clearance or authorization grant.
478static NETWORK_EVENT_IDENTITY: OnceLock<PublisherIdentity> = OnceLock::new();
479
480/// Bind Event publishers/subscribers before construction in a single-identity
481/// native process. A later service cannot silently replace that process identity.
482pub fn install_network_event_identity(
483    proof: &crate::transport::moql_admission::MoqlAdmissionProof,
484) -> Result<()> {
485    anyhow::ensure!(
486        proof.did.starts_with("did:at9p:"),
487        "native Event identity must be checkpointed did:at9p"
488    );
489    let installed =
490        NETWORK_EVENT_IDENTITY.get_or_init(|| PublisherIdentity::verified(proof.did.clone()));
491    anyhow::ensure!(
492        installed.did.as_ref() == Some(&proof.did),
493        "Event process identity already bound to another DID"
494    );
495    Ok(())
496}
497
498impl Default for PublisherIdentity {
499    fn default() -> Self {
500        Self::anonymous()
501    }
502}
503
504/// The canonical broadcast event publisher (EV1, epic #600).
505///
506/// One instance manages publishing to one or more `local/events/{prefix}`
507/// broadcasts. Each registered prefix gets its own moq transport and — for
508/// encrypted privacy modes — its own group key and Ristretto255 ephemeral
509/// keypair.
510pub struct EventPublisher {
511    /// The prefix this publisher is primarily bound to (set by
512    /// `new`/`new_with_oid`/`new_oid_only`; used by the `publish(entity,
513    /// event, payload)` convenience method). Empty for multi-prefix
514    /// `new_encrypted` publishers, which must use `publish_raw`.
515    primary_source: String,
516    prefixes: Arc<RwLock<HashMap<String, PrefixState>>>,
517    /// One verified tenant/domain per confidential publisher instance.
518    tenant: Arc<RwLock<Option<String>>>,
519    /// Dedicated hybrid publisher attestation keys. Both are absent for Public.
520    signing_key: Option<SigningKey>,
521    pq_signing_key: Option<MlDsaSigningKey>,
522    privacy_mode: EventPrivacy,
523    rekey_policy: RekeyPolicy,
524    /// Event-plane authz (EV4). Uninstalled state is `DenyAll`; an explicit
525    /// public firehose or test fixture must inject [`AllowAllEventAuthz`] via
526    /// [`Self::with_authz`].
527    authz: Arc<dyn EventAuthz>,
528    /// Publisher's verified identity (EV4 authn-on-publish). `None` DID
529    /// (anonymous) is fail-closed for confidential publish until #446.
530    publisher_identity: PublisherIdentity,
531}
532
533impl EventPublisher {
534    /// Create a plaintext (`EventPrivacy::Public`) publisher for `source`.
535    ///
536    /// Wire-identical to the pre-EV1 plaintext publisher: requires the
537    /// process-global moq event bus to have been initialized via
538    /// `init_global_moq_event_origin` (done by the event-service factory at
539    /// startup).
540    pub fn new(source: &str) -> Result<Self> {
541        let origin = global_moq_event_origin().ok_or_else(|| {
542            anyhow!("moq event bus not initialized; start the event service first")
543        })?;
544        let moq = origin.publisher(source)?;
545        Self::from_public_prefix(source, moq)
546    }
547
548    /// Plaintext publisher for `source` that ALSO mirrors every event to the
549    /// per-OID (#393) publication track for `oid` (transition path).
550    pub fn new_with_oid(source: &str, oid: &str) -> Result<Self> {
551        let origin = global_moq_event_origin().ok_or_else(|| {
552            anyhow!("moq event bus not initialized; start the event service first")
553        })?;
554        let moq = origin.publisher_with_oid(source, oid)?;
555        Self::from_public_prefix(source, moq)
556    }
557
558    /// Plaintext publisher that writes ONLY to the per-OID (#393) publication
559    /// track for `oid` (no flat-track mirror; post-migration).
560    pub fn new_oid_only(source: &str, oid: &str) -> Result<Self> {
561        let origin = global_moq_event_origin().ok_or_else(|| {
562            anyhow!("moq event bus not initialized; start the event service first")
563        })?;
564        let moq = origin.publisher_oid_only(source, oid)?;
565        Self::from_public_prefix(source, moq)
566    }
567
568    fn from_public_prefix(source: &str, moq: MoqEventPublisher) -> Result<Self> {
569        let mut map = HashMap::new();
570        map.insert(
571            source.to_owned(),
572            PrefixState {
573                moq,
574                confidential: false,
575                crypto: None,
576            },
577        );
578        Ok(Self {
579            primary_source: source.to_owned(),
580            prefixes: Arc::new(RwLock::new(map)),
581            tenant: Arc::new(RwLock::new(None)),
582            signing_key: None,
583            pq_signing_key: None,
584            privacy_mode: EventPrivacy::Public,
585            rekey_policy: RekeyPolicy::default(),
586            // An omitted production installation is a hard deny at rest.
587            authz: installed_event_authz().unwrap_or_else(|| Arc::new(DenyAllEventAuthz)),
588            publisher_identity: NETWORK_EVENT_IDENTITY.get().cloned().unwrap_or_default(),
589        })
590    }
591
592    /// Create an encrypted (`ZeroKnowledge`/`LimitedKnowledge`) publisher.
593    /// No prefix is bound at construction — call [`Self::register_prefix`]
594    /// for each `local/events/{prefix}` broadcast this publisher will write
595    /// to, then [`Self::publish_raw`] with a fully-qualified
596    /// `{prefix}.{entity}.{event}` topic (the convenience
597    /// `publish(entity, event, payload)` method is only available on
598    /// single-prefix `Public`-mode publishers from `new`/`new_with_oid`/
599    /// `new_oid_only`).
600    pub fn new_encrypted(
601        signing_key: SigningKey,
602        privacy_mode: EventPrivacy,
603        rekey_policy: RekeyPolicy,
604    ) -> Result<Self, String> {
605        if privacy_mode == EventPrivacy::Public {
606            return Err(
607                "new_encrypted requires ZeroKnowledge or LimitedKnowledge; use EventPublisher::new for Public mode".to_owned(),
608            );
609        }
610        rekey_policy.validate()?;
611        let pq_signing_key = crate::node_identity::derive_mesh_mldsa_key(&signing_key);
612        Ok(Self {
613            primary_source: String::new(),
614            prefixes: Arc::new(RwLock::new(HashMap::new())),
615            tenant: Arc::new(RwLock::new(None)),
616            signing_key: Some(signing_key),
617            pq_signing_key: Some(pq_signing_key),
618            privacy_mode,
619            rekey_policy,
620            // Confidential profile: deny-by-default (MAC) until a real authz is
621            // injected via `with_authz`; anonymous identity until #446 is wired
622            // via `with_publisher_identity`.
623            authz: Arc::new(DenyAllEventAuthz),
624            publisher_identity: PublisherIdentity::anonymous(),
625        })
626    }
627
628    /// Inject the event-plane authz (EV4). The encrypted profile defaults to
629    /// [`DenyAllEventAuthz`] (fail-closed); production wires a UCAN/capability-
630    /// backed impl (S3/S4 vocab) here. Returns `self` for chaining.
631    pub fn with_authz(mut self, authz: Arc<dyn EventAuthz>) -> Self {
632        self.authz = authz;
633        self
634    }
635
636    /// Inject the publisher's verified identity (EV4 authn-on-publish). Until
637    /// #446 lands the default is anonymous, which fail-closes confidential
638    /// publish; a non-IPC path (or post-#446) supplies a verified DID here.
639    pub fn with_publisher_identity(mut self, identity: PublisherIdentity) -> Self {
640        self.publisher_identity = identity;
641        self
642    }
643
644    /// Register a confidential MOQT prefix. No key is generated here: publish
645    /// remains fail-closed until the controller installs a committed epoch.
646    pub async fn register_prefix(&self, tenant: &str, prefix: &str) -> Result<(), String> {
647        if self.privacy_mode == EventPrivacy::Public {
648            return Err("register_prefix is only valid on encrypted (ZK/LK) publishers".to_owned());
649        }
650        if tenant.is_empty() || tenant == "*" {
651            return Err(
652                "encrypted event prefixes require a verified non-wildcard tenant".to_owned(),
653            );
654        }
655        {
656            let mut registered_tenant = self.tenant.write().await;
657            match registered_tenant.as_deref() {
658                Some(existing) if existing != tenant => {
659                    return Err(format!(
660                        "encrypted publisher is already bound to tenant '{existing}'"
661                    ));
662                }
663                Some(_) => {}
664                None => *registered_tenant = Some(tenant.to_owned()),
665            }
666        }
667        let key = tenant_prefix_key(tenant, prefix);
668        let mut prefixes = self.prefixes.write().await;
669        if prefixes.contains_key(&key) {
670            return Err(format!(
671                "prefix '{prefix}' is already registered; replacement could reset a live crypto domain"
672            ));
673        }
674        let origin = global_moq_event_origin().ok_or_else(|| {
675            "moq event bus not initialized; start the event service first".to_owned()
676        })?;
677        let source = tenant_prefix_source(tenant, prefix);
678        let moq = origin.publisher(&source).map_err(|e| e.to_string())?;
679        prefixes.insert(
680            key,
681            PrefixState {
682                moq,
683                confidential: true,
684                crypto: None,
685            },
686        );
687        Ok(())
688    }
689
690    /// Install an epoch only after the controller atomically committed the same
691    /// membership-version/epoch coordinates.
692    pub async fn install_committed_epoch(
693        &self,
694        prefix: &str,
695        membership_version: u64,
696        epoch: u64,
697        epoch_secret: Zeroizing<[u8; 32]>,
698    ) -> Result<(), String> {
699        if membership_version == 0 || epoch == 0 {
700            return Err(
701                "confidential EventService epochs start at committed version/epoch 1".to_owned(),
702            );
703        }
704        if self.verifying_key().is_none() {
705            return Err("encrypted publisher has no hybrid identity".to_owned());
706        }
707        let key = self.encrypted_prefix_key(prefix).await?;
708        let mut prefixes = self.prefixes.write().await;
709        let state = prefixes
710            .get_mut(&key)
711            .ok_or_else(|| format!("prefix '{prefix}' not registered"))?;
712        if !state.confidential {
713            return Err("cannot install an epoch on a public prefix".to_owned());
714        }
715        if let Some(current) = &state.crypto {
716            if membership_version <= current.membership_version || epoch <= current.epoch {
717                return Err(
718                    "epoch installation must advance membership version and epoch".to_owned(),
719                );
720            }
721        }
722        let mut rng = rand::rngs::OsRng;
723        let session_id =
724            ((u128::from(rng.next_u64()) << 64) | u128::from(rng.next_u64())).to_be_bytes();
725        state.crypto = Some(PrefixCrypto {
726            membership_version,
727            epoch,
728            current: epoch_secret,
729            sequence: 0,
730            session_id,
731            created_at: Instant::now(),
732        });
733        Ok(())
734    }
735
736    /// Classical Ristretto wrapping was removed. Epoch release is exclusively
737    /// per-member HyKEM/COSE via `GroupKeyRegistry::prepare_change`.
738    pub async fn wrap_for_subscriber(
739        &self,
740        _prefix: &str,
741        _subscriber_pubkey: &[u8; 32],
742    ) -> Result<Vec<u8>, String> {
743        Err("classical event key wrapping removed; use controller HyKEM epoch grants".to_owned())
744    }
745
746    pub async fn wrap_for_new_subscribers(
747        &self,
748        _prefix: &str,
749        _subscriber_pubkeys: &[[u8; 32]],
750    ) -> Result<Vec<([u8; 32], Vec<u8>)>, String> {
751        Err("classical event key wrapping removed; use controller HyKEM epoch grants".to_owned())
752    }
753
754    /// Publish `{primary_source}.{entity}.{event}` (matches the pre-EV1
755    /// plaintext `EventPublisher::publish(entity, event, payload)` call
756    /// shape). Only valid on single-prefix publishers from `new`/
757    /// `new_with_oid`/`new_oid_only`; multi-prefix `new_encrypted` publishers
758    /// must use [`Self::publish_raw`] with a fully-qualified topic.
759    pub async fn publish(&self, entity: &str, event: &str, payload: &[u8]) -> Result<()> {
760        if entity.contains('.') {
761            return Err(anyhow!("Entity name cannot contain '.': {entity}"));
762        }
763        if event.contains('.') {
764            return Err(anyhow!("Event name cannot contain '.': {event}"));
765        }
766        if self.primary_source.is_empty() {
767            return Err(anyhow!(
768                "no primary source bound; use publish_raw with a fully-qualified topic, or construct via EventPublisher::new(source)"
769            ));
770        }
771        let topic = format!("{}.{}.{}", self.primary_source, entity, event);
772        self.publish_raw(&topic, payload).await
773    }
774
775    /// Publish a pre-formatted `{prefix}.{...}` topic + payload.
776    ///
777    /// In `Public` mode the payload is written unmodified (byte-identical to
778    /// the pre-EV1 plaintext path). In `ZeroKnowledge`/`LimitedKnowledge`
779    /// mode the payload is signed + encrypted and wrapped in a wire frame
780    /// (see module docs) before being written to the shared moq track for
781    /// the topic's prefix (`topic.split('.').next()`).
782    pub async fn publish_raw(&self, topic: &str, payload: &[u8]) -> Result<()> {
783        let prefix = topic.split('.').next().unwrap_or(topic).to_owned();
784        let key = if self.privacy_mode == EventPrivacy::Public {
785            prefix.clone()
786        } else {
787            self.encrypted_prefix_key(&prefix)
788                .await
789                .map_err(anyhow::Error::msg)?
790        };
791        let mut prefixes = self.prefixes.write().await;
792        let state = prefixes
793            .get_mut(&key)
794            .ok_or_else(|| anyhow!("prefix '{prefix}' not registered"))?;
795
796        let caller = match &self.publisher_identity.did {
797            Some(did) => Subject::new(did.clone()),
798            None => Subject::anonymous(),
799        };
800        if !self.authz.can_publish(&caller, &prefix).await {
801            return Err(anyhow!(
802                "publish denied by event-plane authz for prefix '{prefix}'"
803            ));
804        }
805        if !state.confidential {
806            return state.moq.publish_raw(topic, payload);
807        }
808        let crypto = state.crypto.as_mut().ok_or_else(|| {
809            anyhow!("confidential prefix '{prefix}' has no committed controller epoch installed")
810        })?;
811        let signing_key = self
812            .signing_key
813            .as_ref()
814            .ok_or_else(|| anyhow!("encrypted privacy mode requires an Ed25519 signing key"))?;
815        let pq_signing_key = self
816            .pq_signing_key
817            .as_ref()
818            .ok_or_else(|| anyhow!("encrypted privacy mode requires an ML-DSA-65 signing key"))?;
819        let publisher_pubkey = signing_key.verifying_key().to_bytes();
820        let timestamp = now_millis();
821        let sequence = crypto
822            .sequence
823            .checked_add(1)
824            .ok_or_else(|| anyhow!("event sequence exhausted; rotate epoch"))?;
825        let (tag, ciphertext, nonce, commitment) = encrypt_epoch_event(
826            &crypto.current,
827            &prefix,
828            &publisher_pubkey,
829            &crypto.session_id,
830            crypto.membership_version,
831            crypto.epoch,
832            sequence,
833            payload,
834        )
835        .map_err(|e| anyhow!(e))?;
836        let sig_message = build_epoch_event_sig_message(
837            topic,
838            payload,
839            timestamp,
840            &crypto.session_id,
841            crypto.membership_version,
842            crypto.epoch,
843            sequence,
844        );
845        let signature = sign_composite(
846            signing_key,
847            Some(pq_signing_key),
848            &sig_message,
849            &event_attestation_aad(),
850        )?;
851        crypto.sequence = sequence;
852        let lk_tag = match self.privacy_mode {
853            EventPrivacy::LimitedKnowledge => {
854                keyed_mac(&crypto.current, prefix.as_bytes())[..16].to_vec()
855            }
856            EventPrivacy::ZeroKnowledge | EventPrivacy::Public => vec![],
857        };
858        let encrypted = EncryptedEvent {
859            topic: topic.to_owned(),
860            tag,
861            ciphertext,
862            nonce,
863            key_commitment: commitment,
864            lk_tag,
865            signature,
866            publisher_pubkey,
867            timestamp,
868            session_id: crypto.session_id,
869            membership_version: crypto.membership_version,
870            epoch: crypto.epoch,
871            sequence,
872        };
873        state.moq.publish_raw(topic, &encrypted.encode_body())
874    }
875
876    /// True if a key rotation is due for `prefix` per this publisher's
877    /// [`RekeyPolicy`].
878    pub async fn needs_rotation(&self, prefix: &str) -> bool {
879        let Ok(key) = self.encrypted_prefix_key(prefix).await else {
880            return false;
881        };
882        let prefixes = self.prefixes.read().await;
883        let Some(state) = prefixes.get(&key) else {
884            return false;
885        };
886        let Some(crypto) = state.crypto.as_ref() else {
887            return false;
888        };
889        let age = crypto.created_at.elapsed();
890        match &self.rekey_policy {
891            RekeyPolicy::Scheduled { interval } => age >= *interval,
892            RekeyPolicy::Immediate => false,
893            RekeyPolicy::Jittered { interval, jitter } => {
894                let jitter_offset = {
895                    let h = hash_prefix_bytes(prefix.as_bytes());
896                    let frac = (h[0] as u64 * 256 + h[1] as u64) as f64 / 65536.0;
897                    Duration::from_secs_f64(jitter.as_secs_f64() * frac)
898                };
899                age >= *interval + jitter_offset
900            }
901        }
902    }
903
904    /// EventService cannot rotate or distribute epochs by itself. The
905    /// controller must prepare+commit through `GroupKeyRegistry`, deliver each
906    /// HyKEM grant out of band, then call [`Self::install_committed_epoch`].
907    pub async fn rotate_key(
908        &self,
909        _prefix: &str,
910        _effective_delay: Duration,
911    ) -> Result<RotationResult, String> {
912        Err("controller-managed epochs cannot be rotated by EventPublisher".to_owned())
913    }
914
915    /// The privacy mode this publisher was constructed with.
916    pub fn privacy_mode(&self) -> EventPrivacy {
917        self.privacy_mode
918    }
919
920    /// The Ed25519 verifying key bytes, if this is an encrypted publisher.
921    pub fn verifying_key(&self) -> Option<[u8; 32]> {
922        self.signing_key
923            .as_ref()
924            .map(|k| k.verifying_key().to_bytes())
925    }
926
927    async fn encrypted_prefix_key(&self, prefix: &str) -> Result<String, String> {
928        let tenant = self
929            .tenant
930            .read()
931            .await
932            .clone()
933            .ok_or_else(|| "encrypted publisher has no verified tenant binding".to_owned())?;
934        Ok(tenant_prefix_key(&tenant, prefix))
935    }
936
937    /// The bound primary source (single-prefix publishers only; empty for
938    /// multi-prefix `new_encrypted` publishers).
939    pub fn source(&self) -> &str {
940        &self.primary_source
941    }
942}
943
944// ============================================================================
945// KeyRing + RekeyEvent — publisher-side state (EventService-specific; the
946// reusable keyable-group primitive is `crypto::group_key::GroupKeyRegistry`).
947// ============================================================================
948
949// ============================================================================
950// EventSubscriber — the canonical broadcast subscriber
951// ============================================================================
952
953/// One installed controller epoch.
954struct InstalledEpoch {
955    membership_version: u64,
956    epoch: u64,
957    expires_at_millis: i64,
958    key: Zeroizing<[u8; 32]>,
959}
960
961struct PriorEpoch {
962    installed: InstalledEpoch,
963    grace_until: Instant,
964    /// Only objects the publisher had already issued before the transition are
965    /// eligible for grace. The controller supplies this authenticated cutoff.
966    last_issued_sequence: u64,
967}
968
969/// Externally anchored controller-authorized hybrid publisher identity.
970#[derive(Clone)]
971pub struct EventPublisherAnchor {
972    pub ed25519: ed25519_dalek::VerifyingKey,
973    pub ml_dsa_65: crate::crypto::pq::MlDsaVerifyingKey,
974}
975
976impl EventPublisherAnchor {
977    fn matches(&self, other: &Self) -> bool {
978        self.ed25519 == other.ed25519
979            && ml_dsa_vk_bytes(&self.ml_dsa_65) == ml_dsa_vk_bytes(&other.ml_dsa_65)
980    }
981}
982
983#[derive(Clone)]
984struct ConfidentialPrefixExpectation {
985    controller_did: String,
986    publisher: EventPublisherAnchor,
987}
988
989struct InstalledPrefixState {
990    current: InstalledEpoch,
991    previous: Option<PriorEpoch>,
992    publisher: EventPublisherAnchor,
993    seen_objects: HashSet<(u64, [u8; 16], u64)>,
994    seen_nonces: HashSet<([u8; 16], [u8; 12])>,
995    replay_order: VecDeque<((u64, [u8; 16], u64), ([u8; 16], [u8; 12]))>,
996}
997
998enum SubscriberPrefixState {
999    Expected(Box<ConfidentialPrefixExpectation>),
1000    Installed(Box<InstalledPrefixState>),
1001}
1002
1003/// A pending controller epoch notification.
1004#[derive(Debug)]
1005pub struct RekeyEvent {
1006    pub prefix: String,
1007    pub membership_version: u64,
1008    pub epoch: u64,
1009    pub effective_at: Instant,
1010}
1011
1012/// Canonical EventService subscriber. Public tracks pass through. Confidential
1013/// tracks are installed only from per-member HyKEM/COSE controller grants.
1014pub struct EventSubscriber {
1015    inner: MoqEventSubscriber,
1016    prefixes: Arc<RwLock<HashMap<String, SubscriberPrefixState>>>,
1017    /// One verified tenant/domain per confidential subscriber instance.
1018    tenant: Arc<RwLock<Option<String>>>,
1019    /// Deny-all by default; an injected MAC adapter is active and fail-closed.
1020    authz: Arc<dyn EventAuthz>,
1021    /// Verified subscriber identity, or anonymous when the carrier has not
1022    /// supplied an independently authenticated application subject.
1023    caller: Subject,
1024}
1025
1026impl EventSubscriber {
1027    pub fn new() -> Result<Self> {
1028        Ok(Self {
1029            inner: MoqEventSubscriber::new(),
1030            prefixes: Arc::new(RwLock::new(HashMap::new())),
1031            tenant: Arc::new(RwLock::new(None)),
1032            authz: installed_event_authz().unwrap_or_else(|| Arc::new(DenyAllEventAuthz)),
1033            caller: NETWORK_EVENT_IDENTITY
1034                .get()
1035                .and_then(|identity| identity.did.clone())
1036                .map(Subject::new)
1037                .unwrap_or_else(Subject::anonymous),
1038        })
1039    }
1040
1041    /// Install event-plane authorization. Installing [`MacEventAuthz`] makes
1042    /// missing subject clearance and missing object labels deny.
1043    pub fn with_authz(mut self, authz: Arc<dyn EventAuthz>) -> Self {
1044        self.authz = authz;
1045        self
1046    }
1047
1048    /// Bind the subscriber to an independently verified application subject.
1049    pub fn with_caller(mut self, caller: Subject) -> Self {
1050        self.caller = caller;
1051        self
1052    }
1053
1054    pub fn subscribe(&mut self, pattern: &str) -> Result<()> {
1055        self.inner.subscribe(pattern)
1056    }
1057
1058    pub fn subscribe_all(&mut self) -> Result<()> {
1059        self.inner.subscribe_all()
1060    }
1061
1062    pub fn unsubscribe(&mut self, pattern: &str) -> Result<()> {
1063        self.inner.unsubscribe(pattern)
1064    }
1065
1066    pub fn subscribe_oid(&mut self, oid: &str) -> Result<()> {
1067        self.inner.subscribe_oid(oid)
1068    }
1069
1070    pub fn with_backfill(&mut self, mode: BackfillMode) -> Result<()> {
1071        self.inner.with_backfill(mode)
1072    }
1073
1074    pub fn with_qos(&mut self, qos: crate::stream_info::StreamOpt) -> Result<()> {
1075        self.inner.with_qos(qos)
1076    }
1077
1078    pub fn with_resume_from(&mut self, sequence: u64) -> Result<()> {
1079        self.inner.with_resume_from(sequence)
1080    }
1081
1082    pub fn last_sequence(&self) -> u64 {
1083        self.inner.last_sequence()
1084    }
1085
1086    pub fn dropped_count(&self) -> u64 {
1087        self.inner.dropped_count()
1088    }
1089
1090    /// Mark a subscribed prefix as confidential before any grant is delivered.
1091    ///
1092    /// The controller and publisher anchor come from the caller's authenticated
1093    /// control-plane configuration, rather than from a subsequently received
1094    /// grant. Frames for an expected prefix fail closed until a matching grant
1095    /// is installed.
1096    pub async fn expect_confidential_prefix(
1097        &self,
1098        tenant: &str,
1099        prefix: &str,
1100        controller_did: impl Into<String>,
1101        publisher: EventPublisherAnchor,
1102    ) -> Result<(), String> {
1103        if tenant.is_empty() || tenant == "*" {
1104            return Err(
1105                "confidential event prefixes require a verified non-wildcard tenant".to_owned(),
1106            );
1107        }
1108        if prefix.is_empty() {
1109            return Err("confidential prefix must not be empty".to_owned());
1110        }
1111        {
1112            let mut expected_tenant = self.tenant.write().await;
1113            match expected_tenant.as_deref() {
1114                Some(existing) if existing != tenant => {
1115                    return Err(format!(
1116                        "confidential subscriber is already bound to tenant '{existing}'"
1117                    ));
1118                }
1119                Some(_) => {}
1120                None => *expected_tenant = Some(tenant.to_owned()),
1121            }
1122        }
1123        let key = tenant_prefix_key(tenant, prefix);
1124        let expectation = ConfidentialPrefixExpectation {
1125            controller_did: controller_did.into(),
1126            publisher,
1127        };
1128        if expectation.controller_did.is_empty() {
1129            return Err("expected controller DID must not be empty".to_owned());
1130        }
1131        let mut prefixes = self.prefixes.write().await;
1132        match prefixes.get(&key) {
1133            None => {
1134                prefixes.insert(key, SubscriberPrefixState::Expected(Box::new(expectation)));
1135                Ok(())
1136            }
1137            Some(SubscriberPrefixState::Expected(existing))
1138                if existing.controller_did == expectation.controller_did
1139                    && existing.publisher.matches(&expectation.publisher) =>
1140            {
1141                Ok(())
1142            }
1143            Some(_) => Err("confidential prefix is already configured".to_owned()),
1144        }
1145    }
1146
1147    /// Install a per-member epoch grant after policy/accepted-state admission.
1148    ///
1149    /// `prior_last_issued_sequence` is mandatory for an advance and bounds old
1150    /// epoch grace to objects issued before the transition. Grace is clamped to
1151    /// [`DEFAULT_SUBSCRIBER_GRACE_PERIOD`]; security-triggered transitions pass
1152    /// `Some(Duration::ZERO)`.
1153    pub async fn install_epoch_grant(
1154        &self,
1155        prefix: &str,
1156        recipient: &RecipientKeypair,
1157        grant: &EpochGrant,
1158        publisher: EventPublisherAnchor,
1159        prior_last_issued_sequence: Option<u64>,
1160        grace_period: Option<Duration>,
1161    ) -> Result<(), String> {
1162        if prefix.is_empty() || grant.membership_version == 0 || grant.epoch == 0 {
1163            return Err("invalid confidential event epoch coordinates".to_owned());
1164        }
1165        if grant.expires_at_millis <= now_millis() {
1166            return Err("epoch grant is expired".to_owned());
1167        }
1168        if grant.sender_ed25519 != publisher.ed25519.to_bytes()
1169            || grant.sender_ml_dsa_65 != ml_dsa_vk_bytes(&publisher.ml_dsa_65)
1170            || grant.sender_did.is_empty()
1171            || grant.retention_policy.is_empty()
1172            || grant.opaque_routing_policy.is_empty()
1173        {
1174            return Err(
1175                "publisher anchor or relay profile does not match the authenticated epoch grant"
1176                    .to_owned(),
1177            );
1178        }
1179        let prefix_key = self.encrypted_prefix_key(prefix).await?;
1180        if !self.authz.can_join_decrypt(&self.caller, prefix).await {
1181            return Err(format!(
1182                "join/decrypt denied by event-plane MAC for prefix '{prefix}'"
1183            ));
1184        }
1185        let key = open_epoch_grant(recipient, grant)?;
1186        let mut prefixes = self.prefixes.write().await;
1187        match prefixes.get_mut(&prefix_key) {
1188            None => Err(
1189                "confidential prefix has no independently configured controller expectation"
1190                    .to_owned(),
1191            ),
1192            Some(prefix_state) => {
1193                if let SubscriberPrefixState::Expected(expectation) = prefix_state {
1194                    let expected_controller = expectation.controller_did.clone();
1195                    let expected_publisher = expectation.publisher.clone();
1196                    if grant.controller_did != expected_controller
1197                        || !expected_publisher.matches(&publisher)
1198                    {
1199                        return Err(
1200                            "epoch grant does not match the configured controller expectation"
1201                                .to_owned(),
1202                        );
1203                    }
1204                    *prefix_state =
1205                        SubscriberPrefixState::Installed(Box::new(InstalledPrefixState {
1206                            current: InstalledEpoch {
1207                                membership_version: grant.membership_version,
1208                                epoch: grant.epoch,
1209                                expires_at_millis: grant.expires_at_millis,
1210                                key,
1211                            },
1212                            previous: None,
1213                            publisher: expected_publisher,
1214                            seen_objects: HashSet::new(),
1215                            seen_nonces: HashSet::new(),
1216                            replay_order: VecDeque::new(),
1217                        }));
1218                    return Ok(());
1219                }
1220                let SubscriberPrefixState::Installed(state) = prefix_state else {
1221                    unreachable!("expected state is handled above")
1222                };
1223                if !state.publisher.matches(&publisher) {
1224                    return Err(
1225                        "publisher anchor changed without a controller-authorized rotation"
1226                            .to_owned(),
1227                    );
1228                }
1229                if grant.membership_version != state.current.membership_version + 1
1230                    || grant.epoch != state.current.epoch + 1
1231                {
1232                    return Err(
1233                        "epoch grant is unknown, stale, skipped, or future-before-install"
1234                            .to_owned(),
1235                    );
1236                }
1237                let last_issued_sequence = prior_last_issued_sequence.ok_or_else(|| {
1238                    "epoch advance requires a prior last-issued cutoff".to_owned()
1239                })?;
1240                let grace = grace_period
1241                    .unwrap_or(DEFAULT_SUBSCRIBER_GRACE_PERIOD)
1242                    .min(DEFAULT_SUBSCRIBER_GRACE_PERIOD);
1243                let old = std::mem::replace(
1244                    &mut state.current,
1245                    InstalledEpoch {
1246                        membership_version: grant.membership_version,
1247                        epoch: grant.epoch,
1248                        expires_at_millis: grant.expires_at_millis,
1249                        key,
1250                    },
1251                );
1252                state.previous = Some(PriorEpoch {
1253                    installed: old,
1254                    grace_until: Instant::now() + grace,
1255                    last_issued_sequence,
1256                });
1257                state.seen_objects.retain(|(epoch, _, _)| {
1258                    *epoch == state.current.epoch || *epoch + 1 == state.current.epoch
1259                });
1260                state.seen_nonces.clear();
1261                state.replay_order.clear();
1262                Ok(())
1263            }
1264        }
1265    }
1266
1267    /// Removed classical admission API: an Ed25519/Ristretto key can never be
1268    /// substituted for an accepted `#mesh-kem` recipient.
1269    pub async fn join_prefix(
1270        &self,
1271        _prefix: &str,
1272        _publisher_dh_pubkey: &[u8; 32],
1273        _wrapped_key_blob: &[u8],
1274    ) -> Result<[u8; 32], String> {
1275        Err("classical event join removed; install a controller HyKEM epoch grant".to_owned())
1276    }
1277
1278    pub async fn handle_rekey(
1279        &self,
1280        _prefix: &str,
1281        _wrapped_blobs: &[Vec<u8>],
1282        _new_publisher_dh_pubkey: &[u8; 32],
1283        _effective_at: Instant,
1284    ) -> Result<(), String> {
1285        Err("classical event rekey removed; install a controller HyKEM epoch grant".to_owned())
1286    }
1287
1288    pub async fn promote_key(
1289        &self,
1290        _prefix: &str,
1291        _new_key: Zeroizing<[u8; 32]>,
1292        _grace_period: Option<Duration>,
1293    ) -> Result<(), String> {
1294        Err("raw symmetric epoch promotion removed; install an authenticated grant".to_owned())
1295    }
1296
1297    pub async fn gc_expired_keys(&self) {
1298        let mut prefixes = self.prefixes.write().await;
1299        for prefix_state in prefixes.values_mut() {
1300            let SubscriberPrefixState::Installed(state) = prefix_state else {
1301                continue;
1302            };
1303            if state
1304                .previous
1305                .as_ref()
1306                .is_some_and(|previous| Instant::now() >= previous.grace_until)
1307            {
1308                state.previous = None;
1309                let current_epoch = state.current.epoch;
1310                state
1311                    .seen_objects
1312                    .retain(|(epoch, _, _)| *epoch == current_epoch);
1313            }
1314        }
1315    }
1316
1317    /// Receive the next event.
1318    ///
1319    /// Unconfigured prefixes remain byte-identical `Public` passthrough;
1320    /// explicitly expected confidential prefixes fail closed until their grant
1321    /// is installed. For an installed confidential prefix, the wire frame must
1322    /// match a current or bounded prior epoch, use the required nonce domain,
1323    /// decrypt under the sender/track key, and verify against the externally
1324    /// anchored Ed25519 + ML-DSA-65 publisher identity. Invalid frames are
1325    /// dropped and the loop continues, matching best-effort event delivery.
1326    pub async fn recv(&mut self) -> Result<(String, Vec<u8>)> {
1327        loop {
1328            let (topic, raw) = self.inner.recv().await?;
1329            match self.decode_frame(&topic, &raw).await {
1330                FrameOutcome::Passthrough => return Ok((topic, raw)),
1331                FrameOutcome::Decoded(payload) => return Ok((topic, payload)),
1332                FrameOutcome::Drop(reason) => {
1333                    debug!(
1334                        topic,
1335                        reason, "dropping undecodable/unverifiable event frame"
1336                    );
1337                    continue;
1338                }
1339            }
1340        }
1341    }
1342
1343    /// Receive with a timeout. Same decode/decrypt behavior as [`Self::recv`].
1344    pub async fn recv_timeout(&mut self, timeout: Duration) -> Result<Option<(String, Vec<u8>)>> {
1345        match tokio::time::timeout(timeout, self.recv()).await {
1346            Ok(result) => result.map(Some),
1347            Err(_elapsed) => Ok(None),
1348        }
1349    }
1350
1351    /// Try to receive without blocking. Same decode/decrypt behavior as
1352    /// [`Self::recv`], except a frame that fails to decode/verify/decrypt is
1353    /// dropped and `Ok(None)` returned immediately rather than continuing to
1354    /// poll (this method must not block). Authorization denials are different:
1355    /// they are returned as an explicit error (and an installed MAC adapter
1356    /// audits the denial) so callers cannot confuse enforcement with an empty
1357    /// queue.
1358    ///
1359    /// Async only because the authorization check may revalidate a
1360    /// credential-bearing cached subject against the revocation authority; the
1361    /// receive itself remains non-blocking.
1362    pub async fn try_recv(&mut self) -> Result<Option<(String, Vec<u8>)>> {
1363        let Some((topic, raw)) = self.inner.try_recv()? else {
1364            return Ok(None);
1365        };
1366        let prefix = topic.split('.').next().unwrap_or(&topic);
1367        if self.prefix_is_confidential(prefix)? {
1368            // An encrypted prefix; decoding requires the async path. Callers
1369            // needing non-blocking receive on encrypted prefixes should use
1370            // `recv_timeout(Duration::ZERO)` instead.
1371            return Err(anyhow!(
1372                "try_recv() does not support decoding encrypted prefixes; use recv_timeout(Duration::ZERO)"
1373            ));
1374        }
1375        if !self.authz.can_subscribe(&self.caller, prefix).await {
1376            return Err(anyhow!(
1377                "subscribe denied by event-plane MAC for prefix '{prefix}'"
1378            ));
1379        }
1380        Ok(Some((topic, raw)))
1381    }
1382
1383    fn prefix_is_confidential(&self, prefix: &str) -> Result<bool> {
1384        let tenant = self.tenant.try_read().map_err(|_| {
1385            anyhow!(
1386                "cannot determine tenant binding for prefix '{prefix}' while state is locked; refusing passthrough"
1387            )
1388        })?;
1389        let Some(tenant) = tenant.as_deref() else {
1390            return Ok(false);
1391        };
1392        let key = tenant_prefix_key(tenant, prefix);
1393        let prefixes = self.prefixes.try_read().map_err(|_| {
1394            anyhow!(
1395                "cannot determine whether prefix '{prefix}' is confidential while state is locked; refusing passthrough"
1396            )
1397        })?;
1398        Ok(prefixes.contains_key(&key))
1399    }
1400
1401    async fn decode_frame(&self, topic: &str, raw: &[u8]) -> FrameOutcome {
1402        let prefix = topic.split('.').next().unwrap_or(topic);
1403        let Ok(key) = self.encrypted_prefix_key(prefix).await else {
1404            return if self.authz.can_subscribe(&self.caller, prefix).await {
1405                FrameOutcome::Passthrough
1406            } else {
1407                FrameOutcome::Drop(
1408                    "subscribe denied by event-plane MAC for public prefix".to_owned(),
1409                )
1410            };
1411        };
1412        if !self.authz.can_subscribe(&self.caller, prefix).await {
1413            return FrameOutcome::Drop(
1414                "subscribe denied by event-plane MAC for confidential prefix".to_owned(),
1415            );
1416        }
1417        let mut prefixes = self.prefixes.write().await;
1418        let state = match prefixes.get_mut(&key) {
1419            None => return FrameOutcome::Passthrough,
1420            Some(SubscriberPrefixState::Expected(_)) => {
1421                return FrameOutcome::Drop(
1422                    "confidential prefix is awaiting a controller epoch grant".to_owned(),
1423                );
1424            }
1425            Some(SubscriberPrefixState::Installed(state)) => state,
1426        };
1427        let encrypted = match EncryptedEvent::decode_body(topic, raw) {
1428            Ok(event) => event,
1429            Err(error) => return FrameOutcome::Drop(format!("decode: {error}")),
1430        };
1431        if encrypted.publisher_pubkey != state.publisher.ed25519.to_bytes() {
1432            return FrameOutcome::Drop(
1433                "publisher key is not the controller-authorized anchor".to_owned(),
1434            );
1435        }
1436        if state
1437            .seen_objects
1438            .contains(&(encrypted.epoch, encrypted.session_id, encrypted.sequence))
1439        {
1440            return FrameOutcome::Drop("replayed event object".to_owned());
1441        }
1442        if state
1443            .seen_nonces
1444            .contains(&(encrypted.session_id, encrypted.nonce))
1445        {
1446            return FrameOutcome::Drop("reused event nonce".to_owned());
1447        }
1448
1449        let epoch_key = if encrypted.membership_version == state.current.membership_version
1450            && encrypted.epoch == state.current.epoch
1451            && now_millis() < state.current.expires_at_millis
1452        {
1453            &state.current.key
1454        } else if let Some(previous) = &state.previous {
1455            if encrypted.membership_version == previous.installed.membership_version
1456                && encrypted.epoch == previous.installed.epoch
1457                && Instant::now() < previous.grace_until
1458                && now_millis() < previous.installed.expires_at_millis
1459                && encrypted.sequence <= previous.last_issued_sequence
1460            {
1461                &previous.installed.key
1462            } else {
1463                return FrameOutcome::Drop(
1464                    "unknown, future-before-install, retired, or non-in-flight epoch object"
1465                        .to_owned(),
1466                );
1467            }
1468        } else {
1469            return FrameOutcome::Drop(
1470                "unknown, future-before-install, or retired epoch object".to_owned(),
1471            );
1472        };
1473        let expected_nonce = match derive_event_nonce(&encrypted.session_id, encrypted.sequence) {
1474            Ok(nonce) => nonce,
1475            Err(error) => return FrameOutcome::Drop(error),
1476        };
1477        if encrypted.nonce != expected_nonce {
1478            return FrameOutcome::Drop("event nonce is outside the sender/track domain".to_owned());
1479        }
1480        let plaintext = match decrypt_epoch_event(
1481            epoch_key,
1482            prefix,
1483            &encrypted.publisher_pubkey,
1484            &encrypted.session_id,
1485            encrypted.membership_version,
1486            encrypted.epoch,
1487            encrypted.sequence,
1488            &encrypted.nonce,
1489            &encrypted.tag,
1490            &encrypted.ciphertext,
1491            &encrypted.key_commitment,
1492        ) {
1493            Ok(plaintext) => plaintext,
1494            Err(error) => return FrameOutcome::Drop(format!("decrypt: {error}")),
1495        };
1496        let signed = build_epoch_event_sig_message(
1497            topic,
1498            &plaintext,
1499            encrypted.timestamp,
1500            &encrypted.session_id,
1501            encrypted.membership_version,
1502            encrypted.epoch,
1503            encrypted.sequence,
1504        );
1505        if let Err(error) = verify_composite(
1506            &encrypted.signature,
1507            &state.publisher.ed25519,
1508            Some(&state.publisher.ml_dsa_65),
1509            &signed,
1510            &event_attestation_aad(),
1511            true,
1512        ) {
1513            return FrameOutcome::Drop(format!("hybrid publisher attestation failed: {error}"));
1514        }
1515        record_replay(
1516            state,
1517            (encrypted.epoch, encrypted.session_id, encrypted.sequence),
1518            (encrypted.session_id, encrypted.nonce),
1519        );
1520        FrameOutcome::Decoded(plaintext)
1521    }
1522
1523    async fn encrypted_prefix_key(&self, prefix: &str) -> Result<String, String> {
1524        let tenant =
1525            self.tenant.read().await.clone().ok_or_else(|| {
1526                "confidential subscriber has no verified tenant binding".to_owned()
1527            })?;
1528        Ok(tenant_prefix_key(&tenant, prefix))
1529    }
1530}
1531
1532fn record_replay(
1533    state: &mut InstalledPrefixState,
1534    object: (u64, [u8; 16], u64),
1535    nonce: ([u8; 16], [u8; 12]),
1536) {
1537    state.seen_objects.insert(object);
1538    state.seen_nonces.insert(nonce);
1539    state.replay_order.push_back((object, nonce));
1540    if state.replay_order.len() > MAX_REPLAY_WINDOW {
1541        if let Some((expired_object, expired_nonce)) = state.replay_order.pop_front() {
1542            state.seen_objects.remove(&expired_object);
1543            state.seen_nonces.remove(&expired_nonce);
1544        }
1545    }
1546}
1547
1548#[derive(Debug)]
1549enum FrameOutcome {
1550    /// Prefix not joined — Public-mode passthrough, raw bytes already correct.
1551    Passthrough,
1552    /// Decoded, verified, and decrypted plaintext.
1553    Decoded(Vec<u8>),
1554    /// Drop the frame; carries a debug-log reason.
1555    Drop(String),
1556}
1557
1558// ============================================================================
1559// Tests
1560// ============================================================================
1561
1562#[cfg(test)]
1563#[allow(clippy::unwrap_used, clippy::expect_used)]
1564mod tests {
1565    use super::*;
1566    use crate::auth::mac::{
1567        Assurance, ClearanceSource, CompartmentSet, DeclaredTrackPolicyResolver, Level,
1568        MoqEventPlane, MoqEventPolicyRow, MoqEventPolicyTable, MoqMacAuditRecord, MoqMacAuditSink,
1569        SecurityContext, SecurityLabel, VerifiedKeyMaterial,
1570    };
1571    use crate::crypto::group_key::{
1572        recipient_key_id, ControllerBinding, GroupKeyRegistry, GroupMembership, GroupRef,
1573        MembershipChange, MembershipResolver,
1574    };
1575    use crate::crypto::hybrid_kem::{generate_recipient, RecipientKeypair, SuiteId};
1576    use ml_dsa::Keypair;
1577    use parking_lot::Mutex;
1578
1579    const TEST_TENANT: &str = "tenant-test";
1580
1581    struct AllowExact;
1582    impl MembershipResolver for AllowExact {
1583        fn resolve(&self, requested: &GroupMembership) -> Result<GroupMembership, String> {
1584            Ok(requested.clone())
1585        }
1586    }
1587
1588    fn signing_key() -> SigningKey {
1589        let mut secret = [0u8; 32];
1590        rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut secret);
1591        SigningKey::from_bytes(&secret)
1592    }
1593
1594    fn public_label() -> SecurityLabel {
1595        SecurityLabel::new(Level::Public, Assurance::Classical, CompartmentSet::EMPTY)
1596    }
1597
1598    struct PublicClearance;
1599
1600    #[async_trait::async_trait]
1601    impl ClearanceSource for PublicClearance {
1602        async fn clearance(&self, _subject: &Subject) -> Option<SecurityContext> {
1603            Some(SecurityContext::from_clearance(
1604                public_label(),
1605                VerifiedKeyMaterial::Classical,
1606            ))
1607        }
1608    }
1609
1610    struct NoopAudit;
1611
1612    impl MoqMacAuditSink for NoopAudit {
1613        fn record_deny(&self, _record: &MoqMacAuditRecord) -> Result<(), String> {
1614            Ok(())
1615        }
1616    }
1617
1618    /// A test-only wrapper around the production MAC adapter. It proves which
1619    /// identity actually reaches the typed Event PEP rather than merely
1620    /// asserting the internal map-key implementation detail.
1621    struct RecordingMacEventAuthz {
1622        inner: MacEventAuthz,
1623        calls: Mutex<Vec<(MoqEventAction, String)>>,
1624    }
1625
1626    impl RecordingMacEventAuthz {
1627        fn declared_worker() -> Arc<Self> {
1628            let table = MoqEventPolicyTable::build(
1629                1,
1630                [MoqEventPolicyRow::new(MoqEventPlane::Event, "worker", public_label()).unwrap()],
1631            )
1632            .unwrap();
1633            Arc::new(Self {
1634                inner: MacEventAuthz::new(MoqEventPep::new(
1635                    Arc::new(DeclaredTrackPolicyResolver::new(table)),
1636                    Arc::new(PublicClearance),
1637                    Arc::new(NoopAudit),
1638                )),
1639                calls: Mutex::new(Vec::new()),
1640            })
1641        }
1642
1643        fn empty() -> Arc<Self> {
1644            Arc::new(Self {
1645                inner: MacEventAuthz::new(MoqEventPep::new(
1646                    Arc::new(DeclaredTrackPolicyResolver::new(
1647                        MoqEventPolicyTable::empty(),
1648                    )),
1649                    Arc::new(PublicClearance),
1650                    Arc::new(NoopAudit),
1651                )),
1652                calls: Mutex::new(Vec::new()),
1653            })
1654        }
1655
1656        fn calls(&self) -> Vec<(MoqEventAction, String)> {
1657            self.calls.lock().clone()
1658        }
1659
1660        fn record(&self, action: MoqEventAction, prefix: &str) {
1661            self.calls.lock().push((action, prefix.to_owned()));
1662        }
1663    }
1664
1665    #[async_trait::async_trait]
1666    impl EventAuthz for RecordingMacEventAuthz {
1667        async fn can_publish(&self, caller: &Subject, prefix: &str) -> bool {
1668            self.record(MoqEventAction::Publish, prefix);
1669            self.inner.can_publish(caller, prefix).await
1670        }
1671
1672        async fn can_subscribe(&self, caller: &Subject, prefix: &str) -> bool {
1673            self.record(MoqEventAction::Subscribe, prefix);
1674            self.inner.can_subscribe(caller, prefix).await
1675        }
1676
1677        async fn can_join_decrypt(&self, caller: &Subject, prefix: &str) -> bool {
1678            self.record(MoqEventAction::JoinDecrypt, prefix);
1679            self.inner.can_join_decrypt(caller, prefix).await
1680        }
1681    }
1682
1683    #[tokio::test]
1684    async fn try_recv_surfaces_subscribe_denial_as_error() {
1685        let origin = crate::moq_event::MoqEventOrigin::new();
1686        let source = format!("mac-deny-{}", rand::random::<u64>());
1687        let mut publisher = origin.publisher(&source).unwrap();
1688        let mut subscriber = EventSubscriber {
1689            inner: MoqEventSubscriber::new_for_test(origin.consumer()),
1690            prefixes: Arc::new(RwLock::new(HashMap::new())),
1691            tenant: Arc::new(RwLock::new(None)),
1692            authz: Arc::new(DenyAllEventAuthz),
1693            caller: Subject::new("did:web:denied"),
1694        };
1695        subscriber.subscribe(&format!("{source}.")).unwrap();
1696
1697        // Start the background reader, then publish until it has relayed a
1698        // frame into this subscriber's non-blocking queue.
1699        assert!(subscriber.try_recv().await.unwrap().is_none());
1700        for _ in 0..50 {
1701            publisher.publish("object", "changed", b"payload").unwrap();
1702            tokio::time::sleep(Duration::from_millis(10)).await;
1703            match subscriber.try_recv().await {
1704                Err(error) => {
1705                    assert!(error
1706                        .to_string()
1707                        .contains("subscribe denied by event-plane MAC"));
1708                    return;
1709                }
1710                Ok(None) => {}
1711                Ok(Some(_)) => panic!("denied event must never be returned"),
1712            }
1713        }
1714        panic!("subscriber did not observe the test frame");
1715    }
1716
1717    #[tokio::test]
1718    async fn declared_event_identity_authorizes_plaintext_and_confidential_paths() {
1719        let authz = RecordingMacEventAuthz::declared_worker();
1720
1721        let origin = crate::moq_event::MoqEventOrigin::new();
1722        let public =
1723            EventPublisher::from_public_prefix("worker", origin.publisher("worker").unwrap())
1724                .unwrap()
1725                .with_authz(authz.clone());
1726        public
1727            .publish("sandbox1", "started", b"plaintext")
1728            .await
1729            .unwrap();
1730
1731        let public_subscriber = EventSubscriber::new().unwrap().with_authz(authz.clone());
1732        assert!(matches!(
1733            public_subscriber
1734                .decode_frame("worker.sandbox1.started", b"plaintext")
1735                .await,
1736            FrameOutcome::Passthrough
1737        ));
1738
1739        let recipient = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
1740        let ed = signing_key();
1741        let pq = crate::node_identity::derive_mesh_mldsa_key(&ed);
1742        let (grant, key) = grant_for(&recipient, &ed, &pq).await;
1743        let confidential = EventSubscriber::new()
1744            .unwrap()
1745            .with_authz(authz.clone())
1746            .with_caller(Subject::new("did:web:member"));
1747        expect_confidential(&confidential, "worker", &ed, &pq).await;
1748        confidential
1749            .install_epoch_grant("worker", &recipient, &grant, anchor(&ed, &pq), None, None)
1750            .await
1751            .unwrap();
1752        let encrypted = event(&key, &ed, &pq, b"confidential", 1);
1753        assert!(matches!(
1754            confidential
1755                .decode_frame(&encrypted.topic, &encrypted.encode_body())
1756                .await,
1757            FrameOutcome::Decoded(ref plaintext) if plaintext == b"confidential"
1758        ));
1759
1760        assert_eq!(
1761            authz.calls(),
1762            vec![
1763                (MoqEventAction::Publish, "worker".to_owned()),
1764                (MoqEventAction::Subscribe, "worker".to_owned()),
1765                (MoqEventAction::JoinDecrypt, "worker".to_owned()),
1766                (MoqEventAction::Subscribe, "worker".to_owned()),
1767            ],
1768            "the MAC boundary must receive the typed Event prefix, never a tenant bookkeeping key"
1769        );
1770
1771        let undeclared = RecordingMacEventAuthz::declared_worker();
1772        let undeclared_subscriber = EventSubscriber::new()
1773            .unwrap()
1774            .with_authz(undeclared.clone())
1775            .with_caller(Subject::new("did:web:member"));
1776        expect_confidential(&undeclared_subscriber, "registry", &ed, &pq).await;
1777        assert!(undeclared_subscriber
1778            .install_epoch_grant("registry", &recipient, &grant, anchor(&ed, &pq), None, None)
1779            .await
1780            .unwrap_err()
1781            .contains("join/decrypt denied by event-plane MAC"));
1782        assert_eq!(
1783            undeclared.calls(),
1784            vec![(MoqEventAction::JoinDecrypt, "registry".to_owned())]
1785        );
1786
1787        let empty = RecordingMacEventAuthz::empty();
1788        let empty_subscriber = EventSubscriber::new()
1789            .unwrap()
1790            .with_authz(empty.clone())
1791            .with_caller(Subject::new("did:web:member"));
1792        expect_confidential(&empty_subscriber, "worker", &ed, &pq).await;
1793        assert!(empty_subscriber
1794            .install_epoch_grant("worker", &recipient, &grant, anchor(&ed, &pq), None, None)
1795            .await
1796            .unwrap_err()
1797            .contains("join/decrypt denied by event-plane MAC"));
1798        assert_eq!(
1799            empty.calls(),
1800            vec![(MoqEventAction::JoinDecrypt, "worker".to_owned())]
1801        );
1802    }
1803
1804    fn member(recipient: &RecipientKeypair, did: &str, blind: u8) -> GroupMembership {
1805        let public = recipient.public();
1806        GroupMembership {
1807            group_uri: "at://did:web:controller/ai.hyprstream.event.group/g1".to_owned(),
1808            subject_did: did.to_owned(),
1809            accepted_state: b"cid512:accepted-a".to_vec(),
1810            capability: format!("event:g1:subscribe:{did}").into_bytes(),
1811            recipient_key_id: recipient_key_id(&public),
1812            recipient: public,
1813            blinded_routing_key: [blind; 32],
1814            expires_at_millis: i64::MAX,
1815        }
1816    }
1817
1818    async fn grant_for(
1819        recipient: &RecipientKeypair,
1820        ed: &SigningKey,
1821        pq: &MlDsaSigningKey,
1822    ) -> (EpochGrant, Zeroizing<[u8; 32]>) {
1823        let group = GroupRef::new(
1824            "at://did:web:controller/ai.hyprstream.event.group/g1",
1825            "ks-0",
1826        );
1827        let registry = GroupKeyRegistry::new(RekeyPolicy::Immediate, AllowExact).unwrap();
1828        registry
1829            .register_group(
1830                group.clone(),
1831                ControllerBinding {
1832                    controller_did: "did:web:controller".to_owned(),
1833                    accepted_state: b"cid512:accepted-a".to_vec(),
1834                    sender_did: "did:web:publisher".to_owned(),
1835                    sender_ed25519: ed.verifying_key().to_bytes(),
1836                    sender_ml_dsa_65: crate::crypto::pq::ml_dsa_sk_to_vk_bytes(pq),
1837                    retention_policy: b"retention:bounded-v1".to_vec(),
1838                    opaque_routing_policy: b"routing:stock-moq-opaque-v1".to_vec(),
1839                    expires_at_millis: i64::MAX,
1840                },
1841            )
1842            .await
1843            .unwrap();
1844        let prepared = registry
1845            .prepare_change(
1846                &group,
1847                MembershipChange::Join(member(recipient, "did:web:member", 7)),
1848                "ks-1",
1849            )
1850            .await
1851            .unwrap();
1852        let grant = prepared.grants[0].clone();
1853        registry
1854            .commit_prepared(&group, prepared.membership_version, prepared.epoch)
1855            .await
1856            .unwrap();
1857        (
1858            grant,
1859            Zeroizing::new(registry.k_group(&group).await.unwrap()),
1860        )
1861    }
1862
1863    fn event(
1864        epoch_key: &[u8; 32],
1865        ed_sk: &SigningKey,
1866        pq_sk: &MlDsaSigningKey,
1867        payload: &[u8],
1868        sequence: u64,
1869    ) -> EncryptedEvent {
1870        event_at(epoch_key, ed_sk, pq_sk, payload, 1, 1, sequence)
1871    }
1872
1873    fn event_at(
1874        epoch_key: &[u8; 32],
1875        ed_sk: &SigningKey,
1876        pq_sk: &MlDsaSigningKey,
1877        payload: &[u8],
1878        membership_version: u64,
1879        epoch: u64,
1880        sequence: u64,
1881    ) -> EncryptedEvent {
1882        let topic = "worker.sandbox1.started";
1883        let prefix = "worker";
1884        let kid = ed_sk.verifying_key().to_bytes();
1885        let session_digest = blake3::hash(&epoch.to_be_bytes());
1886        let session_id: [u8; 16] = session_digest.as_bytes()[..16]
1887            .try_into()
1888            .expect("BLAKE3 output contains a 16-byte test session ID");
1889        let (tag, ciphertext, nonce, key_commitment) = encrypt_epoch_event(
1890            epoch_key,
1891            prefix,
1892            &kid,
1893            &session_id,
1894            membership_version,
1895            epoch,
1896            sequence,
1897            payload,
1898        )
1899        .unwrap();
1900        let timestamp = 1_700_000_000_000;
1901        let signed = build_epoch_event_sig_message(
1902            topic,
1903            payload,
1904            timestamp,
1905            &session_id,
1906            membership_version,
1907            epoch,
1908            sequence,
1909        );
1910        let signature =
1911            sign_composite(ed_sk, Some(pq_sk), &signed, &event_attestation_aad()).unwrap();
1912        EncryptedEvent {
1913            topic: topic.to_owned(),
1914            tag,
1915            ciphertext,
1916            nonce,
1917            key_commitment,
1918            lk_tag: Vec::new(),
1919            signature,
1920            publisher_pubkey: kid,
1921            timestamp,
1922            session_id,
1923            membership_version,
1924            epoch,
1925            sequence,
1926        }
1927    }
1928
1929    fn anchor(ed_sk: &SigningKey, pq_sk: &MlDsaSigningKey) -> EventPublisherAnchor {
1930        EventPublisherAnchor {
1931            ed25519: ed_sk.verifying_key(),
1932            ml_dsa_65: pq_sk.verifying_key().clone(),
1933        }
1934    }
1935
1936    fn permissive_test_subscriber() -> EventSubscriber {
1937        EventSubscriber::new()
1938            .unwrap()
1939            .with_authz(Arc::new(AllowAllEventAuthz))
1940    }
1941
1942    async fn expect_confidential(
1943        subscriber: &EventSubscriber,
1944        prefix: &str,
1945        ed_sk: &SigningKey,
1946        pq_sk: &MlDsaSigningKey,
1947    ) {
1948        subscriber
1949            .expect_confidential_prefix(
1950                TEST_TENANT,
1951                prefix,
1952                "did:web:controller",
1953                anchor(ed_sk, pq_sk),
1954            )
1955            .await
1956            .unwrap();
1957    }
1958
1959    #[test]
1960    fn encrypted_event_wire_roundtrip_and_trailing_bytes_rejected() {
1961        let ed = signing_key();
1962        let pq = crate::node_identity::derive_mesh_mldsa_key(&ed);
1963        let event = event(&[9; 32], &ed, &pq, b"payload", 4);
1964        let encoded = event.encode_body();
1965        let decoded = EncryptedEvent::decode_body(&event.topic, &encoded).unwrap();
1966        assert_eq!(decoded.membership_version, 1);
1967        assert_eq!(decoded.epoch, 1);
1968        assert_eq!(decoded.sequence, 4);
1969        assert_eq!(decoded.signature, event.signature);
1970        let mut trailing = encoded;
1971        trailing.push(0);
1972        assert!(EncryptedEvent::decode_body(&event.topic, &trailing).is_err());
1973    }
1974
1975    #[tokio::test]
1976    async fn grant_install_relay_forward_and_hybrid_verify() {
1977        let recipient = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
1978        let ed = signing_key();
1979        let pq = crate::node_identity::derive_mesh_mldsa_key(&ed);
1980        let (grant, key) = grant_for(&recipient, &ed, &pq).await;
1981        let subscriber = permissive_test_subscriber();
1982        expect_confidential(&subscriber, "worker", &ed, &pq).await;
1983        subscriber
1984            .install_epoch_grant("worker", &recipient, &grant, anchor(&ed, &pq), None, None)
1985            .await
1986            .unwrap();
1987
1988        let object = event(&key, &ed, &pq, b"relay cannot read this", 1);
1989        let wire = object.encode_body();
1990        // A stock relay performs only byte-identical forward/cache operations.
1991        let relayed = wire.clone();
1992        assert_eq!(relayed, wire);
1993        assert!(!relayed
1994            .windows(b"relay cannot read this".len())
1995            .any(|window| window == b"relay cannot read this"));
1996        match subscriber.decode_frame(&object.topic, &relayed).await {
1997            FrameOutcome::Decoded(payload) => assert_eq!(payload, b"relay cannot read this"),
1998            other => panic!("expected decoded object, got {other:?}"),
1999        }
2000    }
2001
2002    #[tokio::test]
2003    async fn expected_confidential_prefix_without_grant_drops_plaintext() {
2004        let ed = signing_key();
2005        let pq = crate::node_identity::derive_mesh_mldsa_key(&ed);
2006        let subscriber = permissive_test_subscriber();
2007        expect_confidential(&subscriber, "worker", &ed, &pq).await;
2008
2009        assert!(matches!(
2010            subscriber.decode_frame("worker.sandbox1.started", b"attacker plaintext").await,
2011            FrameOutcome::Drop(reason) if reason.contains("awaiting a controller epoch grant")
2012        ));
2013    }
2014
2015    #[tokio::test]
2016    async fn contended_confidential_state_never_allows_passthrough() {
2017        let ed = signing_key();
2018        let pq = crate::node_identity::derive_mesh_mldsa_key(&ed);
2019        let subscriber = permissive_test_subscriber();
2020        expect_confidential(&subscriber, "worker", &ed, &pq).await;
2021
2022        let _held = subscriber.prefixes.write().await;
2023        assert!(subscriber.prefix_is_confidential("worker").is_err());
2024    }
2025
2026    #[tokio::test]
2027    async fn stock_relay_multi_member_revocation_conformance() {
2028        let member_a = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
2029        let member_b = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
2030        let relay_recipient = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
2031        let ed = signing_key();
2032        let pq = crate::node_identity::derive_mesh_mldsa_key(&ed);
2033        let group = GroupRef::new(
2034            "at://did:web:controller/ai.hyprstream.event.group/g1",
2035            "ks-0",
2036        );
2037        let registry = GroupKeyRegistry::new(RekeyPolicy::Immediate, AllowExact).unwrap();
2038        registry
2039            .register_group(
2040                group.clone(),
2041                ControllerBinding {
2042                    controller_did: "did:web:controller".to_owned(),
2043                    accepted_state: b"cid512:accepted-a".to_vec(),
2044                    sender_did: "did:web:publisher".to_owned(),
2045                    sender_ed25519: ed.verifying_key().to_bytes(),
2046                    sender_ml_dsa_65: crate::crypto::pq::ml_dsa_sk_to_vk_bytes(&pq),
2047                    retention_policy: b"retention:bounded-v1".to_vec(),
2048                    opaque_routing_policy: b"routing:stock-moq-opaque-v1".to_vec(),
2049                    expires_at_millis: i64::MAX,
2050                },
2051            )
2052            .await
2053            .unwrap();
2054
2055        let joined_a = registry
2056            .prepare_change(
2057                &group,
2058                MembershipChange::Join(member(&member_a, "did:web:member-a", 7)),
2059                "ks-1",
2060            )
2061            .await
2062            .unwrap();
2063        registry
2064            .commit_prepared(&group, joined_a.membership_version, joined_a.epoch)
2065            .await
2066            .unwrap();
2067        let joined_b = registry
2068            .prepare_change(
2069                &group,
2070                MembershipChange::Join(member(&member_b, "did:web:member-b", 8)),
2071                "ks-2",
2072            )
2073            .await
2074            .unwrap();
2075        assert_eq!(joined_b.grants.len(), 2);
2076        registry
2077            .commit_prepared(&group, joined_b.membership_version, joined_b.epoch)
2078            .await
2079            .unwrap();
2080        let key_epoch_2 = Zeroizing::new(registry.k_group(&group).await.unwrap());
2081
2082        let grant_a_2 = joined_b
2083            .grants
2084            .iter()
2085            .find(|grant| grant.subject_did == "did:web:member-a")
2086            .unwrap();
2087        let grant_b_2 = joined_b
2088            .grants
2089            .iter()
2090            .find(|grant| grant.subject_did == "did:web:member-b")
2091            .unwrap();
2092        assert!(crate::crypto::group_key::open_epoch_grant(&relay_recipient, grant_a_2).is_err());
2093        let subscriber_a = permissive_test_subscriber();
2094        let subscriber_b = permissive_test_subscriber();
2095        expect_confidential(&subscriber_a, "worker", &ed, &pq).await;
2096        expect_confidential(&subscriber_b, "worker", &ed, &pq).await;
2097        subscriber_a
2098            .install_epoch_grant("worker", &member_a, grant_a_2, anchor(&ed, &pq), None, None)
2099            .await
2100            .unwrap();
2101        subscriber_b
2102            .install_epoch_grant("worker", &member_b, grant_b_2, anchor(&ed, &pq), None, None)
2103            .await
2104            .unwrap();
2105
2106        let before = event_at(&key_epoch_2, &ed, &pq, b"members only", 2, 2, 1);
2107        let wire = before.encode_body();
2108        let relayed = wire.clone();
2109        assert_eq!(relayed, wire);
2110        assert!(!relayed
2111            .windows(b"members only".len())
2112            .any(|window| window == b"members only"));
2113        for subscriber in [&subscriber_a, &subscriber_b] {
2114            assert!(matches!(
2115                subscriber.decode_frame(&before.topic, &relayed).await,
2116                FrameOutcome::Decoded(ref payload) if payload == b"members only"
2117            ));
2118        }
2119
2120        let revoked = registry
2121            .prepare_change(
2122                &group,
2123                MembershipChange::Revoke {
2124                    subject_did: "did:web:member-b".to_owned(),
2125                },
2126                "ks-3",
2127            )
2128            .await
2129            .unwrap();
2130        assert_eq!(revoked.grants.len(), 1);
2131        assert_eq!(revoked.grants[0].subject_did, "did:web:member-a");
2132        registry
2133            .commit_prepared(&group, revoked.membership_version, revoked.epoch)
2134            .await
2135            .unwrap();
2136        assert!(!registry.contains_member(&group, "did:web:member-b").await);
2137        let key_epoch_3 = Zeroizing::new(registry.k_group(&group).await.unwrap());
2138        subscriber_a
2139            .install_epoch_grant(
2140                "worker",
2141                &member_a,
2142                &revoked.grants[0],
2143                anchor(&ed, &pq),
2144                Some(1),
2145                Some(Duration::ZERO),
2146            )
2147            .await
2148            .unwrap();
2149
2150        let after = event_at(&key_epoch_3, &ed, &pq, b"after revoke", 3, 3, 1);
2151        let relayed_after = after.encode_body();
2152        assert!(!relayed_after
2153            .windows(b"after revoke".len())
2154            .any(|window| window == b"after revoke"));
2155        assert!(matches!(
2156            subscriber_a.decode_frame(&after.topic, &relayed_after).await,
2157            FrameOutcome::Decoded(ref payload) if payload == b"after revoke"
2158        ));
2159        assert!(matches!(
2160            subscriber_b.decode_frame(&after.topic, &relayed_after).await,
2161            FrameOutcome::Drop(ref reason) if reason.contains("future-before-install")
2162        ));
2163    }
2164
2165    #[tokio::test]
2166    async fn replay_nonce_mutation_and_stripped_pq_fail_closed() {
2167        let recipient = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
2168        let ed = signing_key();
2169        let pq = crate::node_identity::derive_mesh_mldsa_key(&ed);
2170        let (grant, key) = grant_for(&recipient, &ed, &pq).await;
2171        let subscriber = permissive_test_subscriber();
2172        expect_confidential(&subscriber, "worker", &ed, &pq).await;
2173        subscriber
2174            .install_epoch_grant("worker", &recipient, &grant, anchor(&ed, &pq), None, None)
2175            .await
2176            .unwrap();
2177
2178        let first = event(&key, &ed, &pq, b"one", 1);
2179        assert!(matches!(
2180            subscriber
2181                .decode_frame(&first.topic, &first.encode_body())
2182                .await,
2183            FrameOutcome::Decoded(_)
2184        ));
2185        assert!(matches!(
2186            subscriber.decode_frame(&first.topic, &first.encode_body()).await,
2187            FrameOutcome::Drop(reason) if reason.contains("replayed")
2188        ));
2189
2190        let mut bad_nonce = event(&key, &ed, &pq, b"two", 2);
2191        bad_nonce.nonce[0] ^= 1;
2192        assert!(matches!(
2193            subscriber.decode_frame(&bad_nonce.topic, &bad_nonce.encode_body()).await,
2194            FrameOutcome::Drop(reason) if reason.contains("nonce")
2195        ));
2196
2197        let mut stripped = event(&key, &ed, &pq, b"three", 3);
2198        let signed = build_epoch_event_sig_message(
2199            &stripped.topic,
2200            b"three",
2201            stripped.timestamp,
2202            &stripped.session_id,
2203            1,
2204            1,
2205            3,
2206        );
2207        stripped.signature = sign_composite(&ed, None, &signed, &event_attestation_aad()).unwrap();
2208        assert!(matches!(
2209            subscriber.decode_frame(&stripped.topic, &stripped.encode_body()).await,
2210            FrameOutcome::Drop(reason) if reason.contains("attestation")
2211        ));
2212    }
2213
2214    #[tokio::test]
2215    async fn replay_tracking_is_bounded_to_its_window() {
2216        let recipient = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
2217        let ed = signing_key();
2218        let pq = crate::node_identity::derive_mesh_mldsa_key(&ed);
2219        let (grant, _) = grant_for(&recipient, &ed, &pq).await;
2220        let subscriber = permissive_test_subscriber();
2221        expect_confidential(&subscriber, "worker", &ed, &pq).await;
2222        subscriber
2223            .install_epoch_grant("worker", &recipient, &grant, anchor(&ed, &pq), None, None)
2224            .await
2225            .unwrap();
2226
2227        let mut prefixes = subscriber.prefixes.write().await;
2228        let key = tenant_prefix_key(TEST_TENANT, "worker");
2229        let Some(SubscriberPrefixState::Installed(state)) = prefixes.get_mut(&key) else {
2230            panic!("installed state must exist");
2231        };
2232        for sequence in 1..=MAX_REPLAY_WINDOW as u64 + 1 {
2233            let mut session_id = [0; 16];
2234            session_id[..8].copy_from_slice(&sequence.to_be_bytes());
2235            let nonce = derive_event_nonce(&session_id, sequence).unwrap();
2236            record_replay(state, (1, session_id, sequence), (session_id, nonce));
2237        }
2238        assert_eq!(state.replay_order.len(), MAX_REPLAY_WINDOW);
2239        assert_eq!(state.seen_objects.len(), MAX_REPLAY_WINDOW);
2240        let mut first_session = [0; 16];
2241        first_session[..8].copy_from_slice(&1u64.to_be_bytes());
2242        assert!(!state.seen_objects.contains(&(1, first_session, 1)));
2243    }
2244
2245    #[tokio::test]
2246    async fn installed_epoch_expiry_is_enforced_while_receiving() {
2247        let recipient = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
2248        let ed = signing_key();
2249        let pq = crate::node_identity::derive_mesh_mldsa_key(&ed);
2250        let (grant, key) = grant_for(&recipient, &ed, &pq).await;
2251        let subscriber = permissive_test_subscriber();
2252        expect_confidential(&subscriber, "worker", &ed, &pq).await;
2253        subscriber
2254            .install_epoch_grant("worker", &recipient, &grant, anchor(&ed, &pq), None, None)
2255            .await
2256            .unwrap();
2257        {
2258            let mut prefixes = subscriber.prefixes.write().await;
2259            let key = tenant_prefix_key(TEST_TENANT, "worker");
2260            let Some(SubscriberPrefixState::Installed(state)) = prefixes.get_mut(&key) else {
2261                panic!("installed state must exist");
2262            };
2263            state.current.expires_at_millis = now_millis() - 1;
2264        }
2265        let frame = event(&key, &ed, &pq, b"expired", 1);
2266        assert!(matches!(
2267            subscriber.decode_frame(&frame.topic, &frame.encode_body()).await,
2268            FrameOutcome::Drop(reason) if reason.contains("unknown")
2269        ));
2270    }
2271
2272    #[tokio::test]
2273    async fn duplicate_registration_preserves_live_crypto_domain() {
2274        let _ =
2275            crate::moq_event::init_global_moq_event_origin(crate::moq_event::MoqEventOrigin::new());
2276        let prefix = format!("hardening-duplicate-{}", rand::random::<u64>());
2277        let publisher = EventPublisher::new_encrypted(
2278            signing_key(),
2279            EventPrivacy::ZeroKnowledge,
2280            RekeyPolicy::Immediate,
2281        )
2282        .unwrap();
2283        publisher
2284            .register_prefix(TEST_TENANT, &prefix)
2285            .await
2286            .unwrap();
2287        publisher
2288            .install_committed_epoch(&prefix, 1, 1, Zeroizing::new([0x61; 32]))
2289            .await
2290            .unwrap();
2291        {
2292            let mut prefixes = publisher.prefixes.write().await;
2293            let key = tenant_prefix_key(TEST_TENANT, &prefix);
2294            prefixes
2295                .get_mut(&key)
2296                .unwrap()
2297                .crypto
2298                .as_mut()
2299                .unwrap()
2300                .sequence = 7;
2301        }
2302        let (session_before, sequence_before) = {
2303            let prefixes = publisher.prefixes.read().await;
2304            let key = tenant_prefix_key(TEST_TENANT, &prefix);
2305            let crypto = prefixes.get(&key).unwrap().crypto.as_ref().unwrap();
2306            (crypto.session_id, crypto.sequence)
2307        };
2308
2309        let error = publisher
2310            .register_prefix(TEST_TENANT, &prefix)
2311            .await
2312            .unwrap_err();
2313        assert!(error.contains("already registered"));
2314        let prefixes = publisher.prefixes.read().await;
2315        let key = tenant_prefix_key(TEST_TENANT, &prefix);
2316        let crypto = prefixes.get(&key).unwrap().crypto.as_ref().unwrap();
2317        assert_eq!(crypto.session_id, session_before);
2318        assert_eq!(crypto.sequence, sequence_before);
2319    }
2320
2321    #[tokio::test]
2322    async fn independent_installations_cannot_reuse_key_nonce_pair() {
2323        let _ =
2324            crate::moq_event::init_global_moq_event_origin(crate::moq_event::MoqEventOrigin::new());
2325        let prefix = format!("hardening-failover-{}", rand::random::<u64>());
2326        let signing = signing_key();
2327        let secret = signing.to_bytes();
2328        let publisher_a = EventPublisher::new_encrypted(
2329            SigningKey::from_bytes(&secret),
2330            EventPrivacy::ZeroKnowledge,
2331            RekeyPolicy::Immediate,
2332        )
2333        .unwrap();
2334        let publisher_b = EventPublisher::new_encrypted(
2335            SigningKey::from_bytes(&secret),
2336            EventPrivacy::ZeroKnowledge,
2337            RekeyPolicy::Immediate,
2338        )
2339        .unwrap();
2340        publisher_a
2341            .register_prefix(TEST_TENANT, &prefix)
2342            .await
2343            .unwrap();
2344        publisher_b
2345            .register_prefix(TEST_TENANT, &prefix)
2346            .await
2347            .unwrap();
2348        let epoch_secret = [0x71u8; 32];
2349        publisher_a
2350            .install_committed_epoch(&prefix, 1, 1, Zeroizing::new(epoch_secret))
2351            .await
2352            .unwrap();
2353        publisher_b
2354            .install_committed_epoch(&prefix, 1, 1, Zeroizing::new(epoch_secret))
2355            .await
2356            .unwrap();
2357
2358        let session_a = publisher_a
2359            .prefixes
2360            .read()
2361            .await
2362            .get(&tenant_prefix_key(TEST_TENANT, &prefix))
2363            .unwrap()
2364            .crypto
2365            .as_ref()
2366            .unwrap()
2367            .session_id;
2368        let session_b = publisher_b
2369            .prefixes
2370            .read()
2371            .await
2372            .get(&tenant_prefix_key(TEST_TENANT, &prefix))
2373            .unwrap()
2374            .crypto
2375            .as_ref()
2376            .unwrap()
2377            .session_id;
2378        let kid = publisher_a.verifying_key().unwrap();
2379        let key_a = crate::crypto::event_crypto::derive_sender_track_key(
2380            &epoch_secret,
2381            &kid,
2382            &prefix,
2383            &session_a,
2384        );
2385        let key_b = crate::crypto::event_crypto::derive_sender_track_key(
2386            &epoch_secret,
2387            &kid,
2388            &prefix,
2389            &session_b,
2390        );
2391        let nonce = derive_event_nonce(&session_a, 1).unwrap();
2392
2393        assert_ne!(session_a, session_b);
2394        assert_ne!((&*key_a, nonce), (&*key_b, nonce));
2395    }
2396
2397    #[tokio::test]
2398    async fn signing_key_cannot_substitute_for_mesh_kem_recipient() {
2399        let recipient = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
2400        let wrong = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
2401        let ed = signing_key();
2402        let pq = crate::node_identity::derive_mesh_mldsa_key(&ed);
2403        let (grant, _) = grant_for(&recipient, &ed, &pq).await;
2404        let subscriber = permissive_test_subscriber();
2405        expect_confidential(&subscriber, "worker", &ed, &pq).await;
2406        assert!(subscriber
2407            .install_epoch_grant("worker", &wrong, &grant, anchor(&ed, &pq), None, None)
2408            .await
2409            .is_err());
2410        assert!(subscriber
2411            .join_prefix(
2412                "worker",
2413                &ed.verifying_key().to_bytes(),
2414                &grant.sealed_epoch_secret
2415            )
2416            .await
2417            .is_err());
2418    }
2419
2420    #[test]
2421    fn tenant_qualified_event_transport_keys_do_not_collide() {
2422        let a_key = tenant_prefix_key("tenant-a", "orders");
2423        let b_key = tenant_prefix_key("tenant-b", "orders");
2424        assert_ne!(a_key, b_key);
2425        assert_ne!(
2426            tenant_prefix_source("tenant-a", "orders"),
2427            tenant_prefix_source("tenant-b", "orders")
2428        );
2429    }
2430
2431    #[tokio::test]
2432    async fn confidential_subscriber_rejects_cross_tenant_rebinding() {
2433        let ed = signing_key();
2434        let pq = crate::node_identity::derive_mesh_mldsa_key(&ed);
2435        let subscriber = permissive_test_subscriber();
2436        subscriber
2437            .expect_confidential_prefix(
2438                "tenant-a",
2439                "orders",
2440                "did:web:controller",
2441                anchor(&ed, &pq),
2442            )
2443            .await
2444            .unwrap();
2445
2446        let error = subscriber
2447            .expect_confidential_prefix(
2448                "tenant-b",
2449                "orders",
2450                "did:web:controller",
2451                anchor(&ed, &pq),
2452            )
2453            .await
2454            .unwrap_err();
2455        assert!(error.contains("already bound to tenant 'tenant-a'"));
2456    }
2457
2458    #[tokio::test]
2459    async fn rekey_policy_and_authz_are_fail_closed() {
2460        assert!(RekeyPolicy::Scheduled {
2461            interval: Duration::from_secs(100_000),
2462        }
2463        .validate()
2464        .is_err());
2465        let deny = DenyAllEventAuthz;
2466        assert!(!deny.can_publish(&Subject::anonymous(), "worker").await);
2467        assert!(!deny.can_subscribe(&Subject::anonymous(), "worker").await);
2468        assert!(EventPublisher::new_encrypted(
2469            signing_key(),
2470            EventPrivacy::Public,
2471            RekeyPolicy::default(),
2472        )
2473        .is_err());
2474    }
2475
2476    #[tokio::test]
2477    async fn uninstalled_public_event_authz_denies_at_rest() {
2478        assert!(
2479            !event_authz_installed(),
2480            "unit-test process must not install the production singleton"
2481        );
2482        let origin = crate::moq_event::MoqEventOrigin::new();
2483        let source = format!("uninstalled-authz-{}", rand::random::<u64>());
2484        let moq = origin.publisher(&source).unwrap();
2485        let publisher = EventPublisher::from_public_prefix(&source, moq).unwrap();
2486        let error = publisher
2487            .publish("object", "changed", b"payload")
2488            .await
2489            .unwrap_err();
2490        assert!(error
2491            .to_string()
2492            .contains("publish denied by event-plane authz"));
2493
2494        let subscriber = EventSubscriber::new().unwrap();
2495        assert!(
2496            !subscriber
2497                .authz
2498                .can_subscribe(&Subject::anonymous(), &source)
2499                .await
2500        );
2501    }
2502}