Skip to main content

hyprstream_core/services/
stream_network.rs

1//! Native Streams origins. Carrier admission is independent of stream payload
2//! authentication and MAC authorization performed by the producing RPC service.
3use crate::config::QuicConfig;
4use anyhow::{Context, Result};
5use hyprstream_discovery::admission_roster::{self, DeploymentRosterSource};
6use hyprstream_rpc::transport::iroh_moq::{MoqAuthzConfig, SharedIngressAuthorizer};
7use hyprstream_rpc::transport::moql_admission::{
8    AcceptedStateAuthority, MoqlAdmissionAuthenticator,
9};
10use std::sync::Arc;
11
12/// Current accepted identity and derived tenant assignment, never carrier
13/// identity. Authentication runs on the per-DID accepted-state authority;
14/// the tenant resolver runs over the roster-wide derivation (#1652): a
15/// factory service entry held UNIQUELY across the store ⇒ `local`,
16/// everything else — foreign records, ambiguous names — unresolved/deny. No
17/// DID-valued config to go stale at identity churn.
18pub fn production_stream_admission() -> Result<Arc<MoqlAdmissionAuthenticator>> {
19    let roster = hyprstream_discovery::production_deployment_roster()?;
20    // Prime the cache HERE, synchronously at construction (service startup,
21    // before any runtime serves peers): without this, the first MoQL peer
22    // would pay the synchronous first load — RocksDB open + full store
23    // verification — on the current-thread serving runtime (review round 6).
24    // The Event and standalone-Streams spawn paths prime via their
25    // self-binding checks; this constructor feeds the generic spawner path
26    // (main.rs QuicSharedConfig), which has no such check.
27    let _ = roster.roster();
28    Ok(stream_admission_over(
29        hyprstream_discovery::production_moql_accepted_state_authority()?,
30        roster,
31    ))
32}
33
34pub(crate) fn stream_admission_over(
35    authority: Arc<dyn AcceptedStateAuthority>,
36    roster: Arc<dyn DeploymentRosterSource>,
37) -> Arc<MoqlAdmissionAuthenticator> {
38    Arc::new(MoqlAdmissionAuthenticator::new(
39        authority,
40        admission_roster::derived_tenant_resolver(roster),
41    ))
42}
43
44/// Test/fixture entry: both halves over one roster (the roster carries every
45/// projected state, so the per-DID authority is a lookup into it).
46#[cfg(test)]
47pub(crate) fn stream_admission(
48    roster: Arc<dyn DeploymentRosterSource>,
49) -> Arc<MoqlAdmissionAuthenticator> {
50    let authority: Arc<dyn AcceptedStateAuthority> = {
51        let roster = Arc::clone(&roster);
52        Arc::new(move |did: &str| {
53            let snapshot = roster.roster();
54            snapshot
55                .iter()
56                .find(|(d, _)| d == did)
57                .map(|(_, state)| state.clone())
58        })
59    };
60    stream_admission_over(authority, roster)
61}
62
63/// Tenant admission never grants publishing. `quic.stream_publishers` is a
64/// deliberately-empty DID set (no production writer; empty = read-only, and
65/// an empty set cannot go stale — #1652 leaves it untouched). The tenant
66/// itself is re-derived from the live roster on every check, so removing a
67/// peer from the deployment roster — or a squatter making its name ambiguous
68/// — is effective on the next recheck without a restart.
69pub fn stream_ingress_authorizer(
70    config: &QuicConfig,
71    roster: Arc<dyn DeploymentRosterSource>,
72) -> SharedIngressAuthorizer {
73    let publishers = config.stream_publishers.clone();
74    Arc::new(
75        move |peer: &hyprstream_rpc::moq_authz::PeerIdentity, tenant: &str| {
76            peer.subject.as_deref().is_some_and(|did| {
77                publishers.contains(did) && {
78                    let snapshot = roster.roster();
79                    admission_roster::roster_tenant(
80                        &snapshot,
81                        did,
82                        hyprstream_rpc::envelope::current_timestamp(),
83                    )
84                    .as_deref()
85                        == Some(tenant)
86                }
87            })
88        },
89    )
90}
91
92fn stream_handler(
93    config: &QuicConfig,
94    roster: Arc<dyn DeploymentRosterSource>,
95    origin: &hyprstream_rpc::moq_stream::MoqStreamOrigin,
96    admission: Arc<MoqlAdmissionAuthenticator>,
97) -> hyprstream_rpc::transport::iroh_moq::IrohMoqProtocolHandler {
98    use hyprstream_rpc::transport::iroh_moq::{IrohMoqProtocolHandler, OriginShared};
99    IrohMoqProtocolHandler::with_origin(OriginShared::from_pair(
100        origin.producer().clone(),
101        origin.consumer().clone(),
102    ))
103    .with_authz(
104        MoqAuthzConfig::default()
105            .with_admission(admission)
106            .with_ingress_authorizer(stream_ingress_authorizer(config, roster)),
107    )
108}
109
110/// Owns an independent rendezvous origin. It advertises transport capability,
111/// never ownership of tracks living on Registry/Model/TUI producer endpoints.
112pub struct StreamsNetworkService {
113    secret: [u8; 32],
114    node_id: [u8; 32],
115    handler: hyprstream_rpc::transport::iroh_moq::IrohMoqProtocolHandler,
116    announce: hyprstream_service::service::factory::NativeIrohAnnouncementCallback,
117}
118
119impl StreamsNetworkService {
120    pub fn new(ctx: &hyprstream_service::ServiceContext) -> Result<Self> {
121        let config = crate::config::HyprConfig::load()?;
122        let proof = ctx
123            .moql_admission_proof("streams")?
124            .context("native Streams server proof missing")?;
125        // Self-binding (#1652): the checkpoint store must resolve THIS
126        // process's own DID to the Streams service. Refusal fails the spawn
127        // (fail-closed) — the same refuse-to-start shape as the former empty
128        // tenant map, now bound to live store state instead of config.
129        let roster = hyprstream_discovery::production_deployment_roster()?;
130        admission_roster::require_service_self_binding(&roster, "streams", &proof)?;
131        let key = hyprstream_rpc::node_identity::derive_purpose_key(
132            &ctx.service_signing_key("streams"),
133            "hyprstream-iroh-transport-v1",
134        );
135        let node_id = key.verifying_key().to_bytes();
136        let admission = stream_admission_over(
137            hyprstream_discovery::production_moql_accepted_state_authority()?,
138            Arc::clone(&roster),
139        );
140        admission.install_server_identity(
141            hyprstream_rpc::transport::moql_admission::MoqlServerIdentityProof::from_local_admission_proof(&proof)?, node_id)?;
142        let origin = hyprstream_rpc::moq_stream::MoqStreamOrigin::standalone()
143            .with_prefix(hyprstream_rpc::moq_stream::DEFAULT_PREFIX)
144            .build();
145        Ok(Self {
146            secret: key.to_bytes(),
147            node_id,
148            handler: stream_handler(&config.quic, roster, &origin, admission),
149            announce: ctx.native_iroh_announcement_callback("streams")?,
150        })
151    }
152}
153
154impl hyprstream_rpc::service::Spawnable for StreamsNetworkService {
155    fn name(&self) -> &str {
156        "streams"
157    }
158    fn registrations(
159        &self,
160    ) -> Vec<(
161        hyprstream_rpc::registry::SocketKind,
162        hyprstream_rpc::transport::TransportConfig,
163    )> {
164        vec![]
165    }
166    fn run(
167        self: Box<Self>,
168        shutdown: Arc<tokio::sync::Notify>,
169        on_ready: Option<tokio::sync::oneshot::Sender<()>>,
170    ) -> hyprstream_rpc::error::Result<()> {
171        use hyprstream_rpc::error::RpcError;
172        let runtime = tokio::runtime::Builder::new_current_thread()
173            .enable_all()
174            .build()
175            .map_err(|e| RpcError::SpawnFailed(e.to_string()))?;
176        runtime.block_on(async move {
177            let substrate = hyprstream_rpc::transport::iroh_substrate::IrohSubstrate::new(
178                self.secret, self.handler,
179                hyprstream_rpc::transport::iroh_substrate::RefuseHandler::new("Streams provides only authenticated moql"),
180            ).await.map_err(|e| RpcError::SpawnFailed(format!("native Streams bind: {e}")))?;
181            let cancellation = tokio_util::sync::CancellationToken::new();
182            let _cancel_on_exit = cancellation.clone().drop_guard();
183            let announce_cancel = cancellation.clone();
184            let announce = self.announce;
185            let node_id = self.node_id;
186            let initial = tokio::select! {
187                biased;
188                _ = shutdown.notified() => Err(RpcError::SpawnFailed("Streams stopped before announcement".into())),
189                result = tokio::task::spawn_blocking(move || announce(announce_cancel, node_id)) => {
190                    result.map_err(|e| RpcError::SpawnFailed(format!("Streams announcement task: {e}")))
191                        .and_then(|r| r.map_err(|e| RpcError::SpawnFailed(format!("Streams initial announcement: {e}"))))
192                }
193            };
194            if let Err(error) = initial {
195                cancellation.cancel();
196                let _ = substrate.shutdown().await;
197                return Err(error);
198            }
199            if let Some(ready) = on_ready { let _ = ready.send(()); }
200            let _ = hyprstream_rpc::notify::ready();
201            tokio::select! {
202                _ = shutdown.notified() => {},
203                _ = cancellation.cancelled() => {},
204                _ = async {
205                    while !substrate.router().is_shutdown() && !substrate.endpoint().is_closed() {
206                        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
207                    }
208                } => {},
209            }
210            cancellation.cancel();
211            substrate.shutdown().await.map_err(|e| RpcError::SpawnFailed(format!("Streams shutdown: {e}")))
212        })
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219    use ed25519_dalek::SigningKey;
220    use hyprstream_rpc::crypto::pq::{ml_dsa_sk_from_seed, ml_dsa_sk_to_vk_bytes};
221    use hyprstream_rpc::transport::iroh_substrate::{IrohSubstrate, RefuseHandler, ALPN_MOQ_LITE};
222    use hyprstream_rpc::transport::moql_admission::{
223        prove_moql_admission, AcceptedIdentityState, AcceptedSubjectKey, MoqlAdmissionProof,
224        MoqlServerIdentityProof,
225    };
226    use moq_net::{Client, Group, Origin, Track};
227    use std::time::Duration;
228
229    fn identity(
230        name: &str,
231        seed: u8,
232        service_ids: &[&str],
233    ) -> (MoqlAdmissionProof, AcceptedIdentityState) {
234        let ed25519 = SigningKey::from_bytes(&[seed; 32]);
235        let ml_dsa_65 = ml_dsa_sk_from_seed(&[seed; 32]);
236        let expires_at_unix_ms = hyprstream_rpc::envelope::current_timestamp() + 60_000;
237        let state = AcceptedIdentityState {
238            epoch: 1,
239            head_digest: [seed; 64],
240            expires_at_unix_ms: Some(expires_at_unix_ms),
241            subject_keys: vec![AcceptedSubjectKey {
242                ed25519: ed25519.verifying_key().to_bytes(),
243                ml_dsa_65: ml_dsa_sk_to_vk_bytes(&ml_dsa_65),
244            }],
245            service_ids: service_ids.iter().map(ToString::to_string).collect(),
246        };
247        let expected_server = hyprstream_rpc::stream_info::MoqlServerIdentity {
248            did: format!("did:at9p:{name}"),
249            epoch: 1,
250            head_digest: state.head_digest.to_vec(),
251            expires_at_unix_ms,
252            ed25519: ed25519.verifying_key().to_bytes(),
253            ml_dsa65: ml_dsa_sk_to_vk_bytes(&ml_dsa_65),
254        };
255        (
256            MoqlAdmissionProof {
257                did: expected_server.did.clone(),
258                ed25519,
259                ml_dsa_65,
260                expected_server,
261            },
262            state,
263        )
264    }
265
266    fn live_roster(
267        states: &Arc<
268            parking_lot::RwLock<std::collections::BTreeMap<String, AcceptedIdentityState>>,
269        >,
270    ) -> Arc<dyn hyprstream_discovery::admission_roster::DeploymentRosterSource> {
271        let states = Arc::clone(states);
272        Arc::new(move || states.read().clone().into_iter().collect::<Vec<_>>())
273    }
274
275    fn direct(server: &IrohSubstrate) -> iroh::EndpointAddr {
276        iroh::EndpointAddr::from_parts(
277            server.endpoint_id(),
278            server
279                .endpoint()
280                .bound_sockets()
281                .into_iter()
282                .map(iroh::TransportAddr::Ip),
283        )
284    }
285
286    async fn peer(seed: u8) -> Result<IrohSubstrate> {
287        IrohSubstrate::new(
288            [seed; 32],
289            RefuseHandler::new("no moq"),
290            RefuseHandler::new("no rpc"),
291        )
292        .await
293    }
294
295    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
296    async fn streams_readiness_requires_announcement_and_shutdown_cancels_it() -> Result<()> {
297        use hyprstream_rpc::service::Spawnable;
298        for fail_announcement in [true, false] {
299            let secret = [if fail_announcement { 71 } else { 72 }; 32];
300            let node_id = *iroh::SecretKey::from_bytes(&secret).public().as_bytes();
301            let observed = Arc::new(parking_lot::Mutex::new(None));
302            let callback_observed = Arc::clone(&observed);
303            let service = StreamsNetworkService {
304                secret,
305                node_id,
306                handler: hyprstream_rpc::transport::iroh_moq::IrohMoqProtocolHandler::new(),
307                announce: Arc::new(move |cancel, actual| {
308                    assert_eq!(actual, node_id);
309                    *callback_observed.lock() = Some(cancel);
310                    anyhow::ensure!(!fail_announcement, "fixture announcement refusal");
311                    Ok(())
312                }),
313            };
314            let shutdown = Arc::new(tokio::sync::Notify::new());
315            let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
316            let stop = Arc::clone(&shutdown);
317            let task =
318                tokio::task::spawn_blocking(move || Box::new(service).run(stop, Some(ready_tx)));
319            let ready = tokio::time::timeout(Duration::from_secs(5), ready_rx).await?;
320            if fail_announcement {
321                assert!(ready.is_err());
322                assert!(task.await?.is_err());
323            } else {
324                assert!(ready.is_ok());
325                shutdown.notify_one();
326                tokio::time::timeout(Duration::from_secs(5), task).await???;
327            }
328            assert!(observed
329                .lock()
330                .as_ref()
331                .is_some_and(tokio_util::sync::CancellationToken::is_cancelled));
332        }
333        Ok(())
334    }
335
336    /// Exercises the exact production stream handler and config-to-authority
337    /// wiring, using independent real Iroh peers and mutable accepted state.
338    /// Fixture identity acceptance grants no Event labels or production policy.
339    #[test]
340    fn native_stream_payload_tenant_ingress_and_currentness() -> Result<()> {
341        const CHILD: &str = "HYPRSTREAM_NATIVE_STREAM_PAYLOAD_TEST";
342        if std::env::var_os(CHILD).is_none() {
343            let status = std::process::Command::new(std::env::current_exe()?)
344                .args(["--exact", "services::stream_network::tests::native_stream_payload_tenant_ingress_and_currentness", "--nocapture"])
345                .env(CHILD, "1").status()?;
346            anyhow::ensure!(
347                status.success(),
348                "isolated native stream payload regression failed"
349            );
350            return Ok(());
351        }
352        tokio::runtime::Builder::new_multi_thread()
353            .worker_threads(2)
354            .enable_all()
355            .build()?
356            .block_on(stream_roundtrip())
357    }
358
359    async fn stream_roundtrip() -> Result<()> {
360        let (server_proof, server_state) = identity("streams", 61, &["#streams"]);
361        let (mut publisher, publisher_state) = identity("publisher", 62, &["#model"]);
362        let (mut reader, reader_state) = identity("reader", 63, &["#policy"]);
363        let (mut foreign, foreign_state) = identity("foreign-record", 64, &["#ns"]);
364        let server_identity = server_proof.expected_server.clone();
365        for proof in [&mut publisher, &mut reader, &mut foreign] {
366            proof.expected_server = server_identity.clone();
367        }
368        let states = Arc::new(parking_lot::RwLock::new(std::collections::BTreeMap::from(
369            [
370                (server_proof.did.clone(), server_state),
371                (publisher.did.clone(), publisher_state),
372                (reader.did.clone(), reader_state),
373                (foreign.did.clone(), foreign_state),
374            ],
375        )));
376        // #1652: no tenant map in config at all — admission derives tenants
377        // from the live authority. The Event ingress set is name-keyed; an
378        // Event grant on the reader's service must never authorize stream
379        // injection.
380        let mut config = QuicConfig::default();
381        config.stream_publishers.insert(publisher.did.clone());
382        config.event_publishers.insert("policy".to_owned());
383        let admission = stream_admission(live_roster(&states));
384        let secret = [65; 32];
385        admission.install_server_identity(
386            MoqlServerIdentityProof::from_local_admission_proof(&server_proof)?,
387            *iroh::SecretKey::from_bytes(&secret).public().as_bytes(),
388        )?;
389        let origin = hyprstream_rpc::moq_stream::MoqStreamOrigin::standalone().build();
390        let server = IrohSubstrate::new(
391            secret,
392            stream_handler(&config, live_roster(&states), &origin, admission),
393            RefuseHandler::new("streams no rpc"),
394        )
395        .await?;
396        let writer = peer(66).await?;
397        let subscriber = peer(67).await?;
398        let outsider = peer(68).await?;
399        let writer_conn = writer.connect(direct(&server), ALPN_MOQ_LITE).await?;
400        prove_moql_admission(
401            &writer_conn,
402            &publisher,
403            *writer.endpoint_id().as_bytes(),
404            Duration::from_secs(2),
405        )
406        .await?;
407        let write_origin = Origin::random().produce();
408        let writer_session = Client::new()
409            .with_origin(write_origin.clone())
410            .connect(web_transport_iroh::Session::raw(writer_conn.clone()))
411            .await?;
412        let reader_conn = subscriber.connect(direct(&server), ALPN_MOQ_LITE).await?;
413        prove_moql_admission(
414            &reader_conn,
415            &reader,
416            *subscriber.endpoint_id().as_bytes(),
417            Duration::from_secs(2),
418        )
419        .await?;
420        let read_origin = Origin::random().produce();
421        let read_consumer = read_origin.consume();
422        let reader_session = Client::new()
423            .with_origin(read_origin.clone())
424            .with_consume(read_origin.clone())
425            .connect(web_transport_iroh::Session::raw(reader_conn))
426            .await?;
427        // A foreign at9p record present in the store (arbitrary `#ns`
428        // service entry, not a factory service) must be denied at the
429        // admission exchange itself — the ∩ get_factory filter.
430        let foreign_conn = outsider.connect(direct(&server), ALPN_MOQ_LITE).await?;
431        assert!(
432            prove_moql_admission(
433                &foreign_conn,
434                &foreign,
435                *outsider.endpoint_id().as_bytes(),
436                Duration::from_secs(2),
437            )
438            .await
439            .is_err(),
440            "foreign store record must not derive a tenant"
441        );
442        // Exercise the production required-profile reach dialer too, with the
443        // authenticated producer witness and an independently provisioned peer.
444        let lookup = iroh::address_lookup::memory::MemoryLookup::new();
445        lookup.add_endpoint_info(direct(&server));
446        subscriber.endpoint().address_lookup()?.add(lookup);
447        assert!(
448            hyprstream_rpc::transport::lazy_iroh::install_iroh_client_endpoint(
449                subscriber.owned_client_endpoint()
450            )
451            .is_ok()
452        );
453        assert!(hyprstream_rpc::moq_stream::init_global_moq_admission_proof(
454            reader.clone()
455        ));
456        hyprstream_rpc::moq_stream::require_native_iroh();
457        let reach = hyprstream_rpc::moq_stream::ProducerReachConfig {
458            iroh_node_id: Some(*server.endpoint_id().as_bytes()),
459            moql_server_identity: Some(server_identity.clone()),
460            ..Default::default()
461        }
462        .reach();
463        let network_reader = tokio::time::timeout(
464            Duration::from_secs(3),
465            hyprstream_rpc::moq_stream::connect_moq_reach_for_profile(
466                &reach,
467                &server_identity,
468                true,
469            ),
470        )
471        .await??;
472        let name = "local/streams/authorized-payload";
473        let mut broadcast = write_origin
474            .create_broadcast(name)
475            .context("writer broadcast")?;
476        let mut track = broadcast.create_track(Track::new("tokens"))?;
477        let mut group = track.create_group(Group::from(0u64))?;
478        group.write_frame(bytes::Bytes::from_static(b"producer-owned frame"))?;
479        drop(group);
480        let received = tokio::time::timeout(
481            Duration::from_secs(3),
482            read_consumer.announced_broadcast(name),
483        )
484        .await?
485        .context("reader announcement")?;
486        let received_track = received.subscribe_track(&Track::new("tokens"))?;
487        let mut received_group =
488            tokio::time::timeout(Duration::from_secs(3), received_track.get_group(0))
489                .await??
490                .context("payload group")?;
491        assert_eq!(
492            received_group.read_frame().await?,
493            Some(bytes::Bytes::from_static(b"producer-owned frame"))
494        );
495        let network_broadcast = tokio::time::timeout(
496            Duration::from_secs(3),
497            network_reader.consumer.announced_broadcast(name),
498        )
499        .await?
500        .context("required-profile reader announcement")?;
501        let network_track = network_broadcast.subscribe_track(&Track::new("tokens"))?;
502        let mut network_group =
503            tokio::time::timeout(Duration::from_secs(3), network_track.get_group(0))
504                .await??
505                .context("required-profile group")?;
506        assert_eq!(
507            network_group.read_frame().await?,
508            Some(bytes::Bytes::from_static(b"producer-owned frame"))
509        );
510        let _injected = read_origin
511            .create_broadcast("local/streams/reader-injected")
512            .context("reader injection")?;
513        // An admitted-but-unlisted peer stays read-only: the reader (tenant
514        // local via #policy, absent from stream_publishers, Event grant
515        // notwithstanding) cannot inject into the shared origin.
516        assert!(tokio::time::timeout(
517            Duration::from_millis(250),
518            origin
519                .consumer()
520                .announced_broadcast("local/streams/reader-injected")
521        )
522        .await
523        .is_err());
524        // Advancing authoritative state revokes an already writable session.
525        states.write().remove(&publisher.did);
526        tokio::time::timeout(Duration::from_secs(3), writer_conn.closed()).await?;
527        let rejected = writer.connect(direct(&server), ALPN_MOQ_LITE).await?;
528        assert!(prove_moql_admission(
529            &rejected,
530            &publisher,
531            *writer.endpoint_id().as_bytes(),
532            Duration::from_secs(2)
533        )
534        .await
535        .is_err());
536        drop((writer_session, reader_session));
537        writer.shutdown().await?;
538        subscriber.shutdown().await?;
539        outsider.shutdown().await?;
540        server.shutdown().await?;
541        Ok(())
542    }
543
544    /// #1652 THE CHURN TEST (Streams, full admission exchange): a service's
545    /// DID changes — same service name re-bound to a new DID in the live
546    /// store, exactly the R1 store re-init shape — and admission for that
547    /// service keeps working in the SAME process, no restart, no config
548    /// change. Under the former DID-keyed `quic.moql_subject_tenants` map the
549    /// successor DID had no binding and every admission for it failed until
550    /// config.toml was re-projected and every container restarted.
551    #[test]
552    fn native_stream_admission_survives_did_churn_without_restart() -> Result<()> {
553        const CHILD: &str = "HYPRSTREAM_NATIVE_STREAM_CHURN_TEST";
554        if std::env::var_os(CHILD).is_none() {
555            let status = std::process::Command::new(std::env::current_exe()?)
556                .args(["--exact", "services::stream_network::tests::native_stream_admission_survives_did_churn_without_restart", "--nocapture"])
557                .env(CHILD, "1").status()?;
558            anyhow::ensure!(
559                status.success(),
560                "isolated native stream churn regression failed"
561            );
562            return Ok(());
563        }
564        tokio::runtime::Builder::new_multi_thread()
565            .worker_threads(2)
566            .enable_all()
567            .build()?
568            .block_on(stream_churn())
569    }
570
571    async fn stream_churn() -> Result<()> {
572        let (server_proof, server_state) = identity("streams", 71, &["#streams"]);
573        let (mut original, original_state) = identity("original-did", 72, &["#model"]);
574        let (mut successor, successor_state) = identity("successor-did", 73, &["#model"]);
575        let server_identity = server_proof.expected_server.clone();
576        original.expected_server = server_identity.clone();
577        successor.expected_server = server_identity.clone();
578        let states = Arc::new(parking_lot::RwLock::new(std::collections::BTreeMap::from(
579            [
580                (server_proof.did.clone(), server_state),
581                (original.did.clone(), original_state),
582            ],
583        )));
584        // The config object is built ONCE, before the churn, and never
585        // touched again — there is no tenant map to touch.
586        let config = QuicConfig::default();
587        let admission = stream_admission(live_roster(&states));
588        let secret = [75; 32];
589        admission.install_server_identity(
590            MoqlServerIdentityProof::from_local_admission_proof(&server_proof)?,
591            *iroh::SecretKey::from_bytes(&secret).public().as_bytes(),
592        )?;
593        let origin = hyprstream_rpc::moq_stream::MoqStreamOrigin::standalone().build();
594        let server = IrohSubstrate::new(
595            secret,
596            stream_handler(&config, live_roster(&states), &origin, admission),
597            RefuseHandler::new("streams no rpc"),
598        )
599        .await?;
600        let client = peer(76).await?;
601
602        // Pre-churn: the original DID admits through derived resolution.
603        let conn = client.connect(direct(&server), ALPN_MOQ_LITE).await?;
604        prove_moql_admission(
605            &conn,
606            &original,
607            *client.endpoint_id().as_bytes(),
608            Duration::from_secs(2),
609        )
610        .await?;
611        drop(conn);
612
613        // Identity churn: the same service name (#model) is re-bound to a new
614        // DID; the superseded DID leaves the store.
615        states.write().remove(&original.did);
616        states
617            .write()
618            .insert(successor.did.clone(), successor_state);
619
620        // Same process, same config: the successor DID admits.
621        let churned = client.connect(direct(&server), ALPN_MOQ_LITE).await?;
622        prove_moql_admission(
623            &churned,
624            &successor,
625            *client.endpoint_id().as_bytes(),
626            Duration::from_secs(2),
627        )
628        .await
629        .context("successor DID must admit after churn without restart or config change")?;
630        drop(churned);
631
632        // The superseded DID is denied.
633        let stale = client.connect(direct(&server), ALPN_MOQ_LITE).await?;
634        assert!(
635            prove_moql_admission(
636                &stale,
637                &original,
638                *client.endpoint_id().as_bytes(),
639                Duration::from_secs(2),
640            )
641            .await
642            .is_err(),
643            "superseded DID must stop admitting"
644        );
645        drop(stale);
646        client.shutdown().await?;
647        server.shutdown().await?;
648        Ok(())
649    }
650
651    /// #1652 revocation-on-recheck: `is_still_current` re-runs the tenant
652    /// resolver on every recheck (moql_admission.rs "removal or reassignment
653    /// closes a previously admitted scoped session"). With the former
654    /// config-cloned map that clause was inert — the map could never change
655    /// within a process. Under derivation a store-side roster edit is
656    /// effective on the next recheck: re-assigning the subject's capsule
657    /// service entry OFF the deployment roster (same DID, same keys, same
658    /// epoch, still live — only the `#service` id changes to a non-factory
659    /// entry) closes the previously admitted session. Reassignment to another
660    /// deployment service keeps the tenant, so the session legitimately
661    /// survives — the tenant, not the service name, is the session binding.
662    #[test]
663    fn derived_tenant_recheck_closes_session_on_roster_removal() -> Result<()> {
664        use hyprstream_rpc::moq_authz::PeerIdentity;
665        use hyprstream_rpc::transport::moql_admission::AdmittedMoqPeer;
666        let (server_proof, server_state) = identity("streams", 81, &["#streams"]);
667        let (model_proof, model_state) = identity("model-service", 82, &["#model"]);
668        let states = Arc::new(parking_lot::RwLock::new(std::collections::BTreeMap::from(
669            [
670                (server_proof.did.clone(), server_state),
671                (model_proof.did.clone(), model_state.clone()),
672            ],
673        )));
674        let admission = stream_admission(live_roster(&states));
675        admission.install_server_identity(
676            MoqlServerIdentityProof::from_local_admission_proof(&server_proof)?,
677            [83; 32],
678        )?;
679        let admitted = AdmittedMoqPeer {
680            peer: PeerIdentity::authenticated(model_proof.did.clone()),
681            tenant: "local".to_owned(),
682            epoch: model_state.epoch,
683            head_digest: model_state.head_digest,
684            subject_ed25519: model_proof.ed25519.verifying_key().to_bytes(),
685            carrier_node_id: [84; 32],
686        };
687        assert!(
688            admission.is_still_current(&admitted),
689            "live deployment identity must remain current"
690        );
691        // Same-tenant reassignment: another deployment service name — the
692        // derived tenant is unchanged, so the session stays current.
693        let mut moved = model_state.clone();
694        moved.service_ids = vec!["#policy".to_owned()];
695        states.write().insert(model_proof.did.clone(), moved);
696        assert!(
697            admission.is_still_current(&admitted),
698            "same-tenant service reassignment must not close the session"
699        );
700        // Off-roster reassignment: a foreign `#ns` entry (public ingest
701        // shape). Keys, epoch, digest and liveness are all unchanged — only
702        // roster membership is gone — and the session must close.
703        let mut off_roster = model_state.clone();
704        off_roster.service_ids = vec!["#ns".to_owned()];
705        states.write().insert(model_proof.did.clone(), off_roster);
706        assert!(
707            !admission.is_still_current(&admitted),
708            "roster removal must close the previously admitted session on recheck"
709        );
710        Ok(())
711    }
712}