Skip to main content

subc_daemon/supervise/
registration.rs

1//! Per-launch registration, tracked separately from nonce checks keyed by module ID.
2//! Locks only protect snapshots; neither service nor launch waits hold them.
3
4#[cfg(test)]
5#[path = "registration_read_tests.rs"]
6mod read_tests;
7#[cfg(all(test, target_os = "linux"))]
8#[path = "retirement_tests.rs"]
9mod retirement_tests;
10#[cfg(all(test, unix))]
11#[path = "registration_review_tests.rs"]
12mod review_tests;
13
14use super::*;
15use std::collections::BTreeSet;
16use std::sync::{
17    atomic::{AtomicBool, Ordering},
18    Weak,
19};
20
21/// The refusal code for any registration operation that reaches a spawn whose
22/// exit has been observed. Terminal: the channel never carries authority again.
23pub(crate) const REGISTRATION_CHANNEL_CLOSED: &str = "registration_channel_closed";
24
25/// What a consumer's launch nonce attests, from
26/// [`SupervisorHandle::attest_spawned_consumer`].
27#[derive(Debug)]
28pub(crate) enum NonceAttestation {
29    /// The nonce does not attest the module, or the launch it was minted for
30    /// had an authority record that is gone.
31    Refused,
32    /// The nonce attests the module and no launch was ever recorded for it,
33    /// so the consumer is the module with no spawn record behind it.
34    Unrecorded,
35    /// The nonce attests the module through this launch's record.
36    Spawn(Arc<crate::spawn_authority::SpawnAuthorityRecord>),
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40enum LaunchState {
41    Pending,
42    Ready,
43    Dead,
44}
45
46#[cfg(test)]
47#[derive(Debug)]
48struct RetirementPause {
49    reached: tokio::sync::oneshot::Sender<()>,
50    release: std::sync::mpsc::Receiver<()>,
51}
52
53#[derive(Debug)]
54pub(crate) struct RegistrationSpawn {
55    pub(crate) incarnation: String,
56    pub(super) binding_key: program_binding::ProgramBindingKey,
57    pub(crate) claims: std::sync::OnceLock<Arc<crate::control::claims::LaunchClaims>>,
58    pub(crate) module_id: String,
59    /// This launch's authority record, created with it. It dies in the same
60    /// retirement step that ends the channel and voids the claims.
61    pub(crate) authority: Arc<crate::spawn_authority::SpawnAuthorityRecord>,
62    pub(crate) resume_token_record: std::sync::OnceLock<crate::child_roster::ResumeTokenRecord>,
63    pub(crate) resume_witnesses: Mutex<Option<resume_hello::ResumeWitnesses>>,
64    pub(super) role: SpawnRole,
65    hello_seen: AtomicBool,
66    registered: AtomicBool,
67    nonce_registered: AtomicBool,
68    deadline: std::sync::OnceLock<Instant>,
69    launch: tokio::sync::watch::Sender<LaunchState>,
70    transition: Mutex<()>,
71    primary_sink: Mutex<Option<crate::FrameSink>>,
72    #[cfg(test)]
73    retirement_pause: Mutex<Option<RetirementPause>>,
74    #[cfg(unix)]
75    endpoint: Mutex<Option<std::os::unix::net::UnixStream>>,
76    #[cfg(windows)]
77    endpoint: Mutex<Option<subc_os::registration_channel::RegistrationPipeShutdown>>,
78    binding: Option<ProgramBindingPublication>,
79    requires_binding: bool,
80    pub(super) identity: std::sync::OnceLock<ProcessIdentity>,
81    connections: Weak<Mutex<HashMap<ConnectionId, Arc<RegistrationSpawn>>>>,
82}
83
84impl RegistrationSpawn {
85    #[cfg(all(test, unix))]
86    pub(super) fn set_wire_deadline_for_test(&self, deadline: Instant) {
87        let _ = self.deadline.set(deadline);
88    }
89    #[cfg(all(test, unix))]
90    pub(crate) fn set_content_probe_for_test(&self, probe: content_binding::ContentProbe) {
91        self.binding.as_ref().unwrap().set_content_probe(probe);
92    }
93    #[cfg(all(test, unix))]
94    pub(crate) fn defer_content_kill_for_test(&self) -> impl Drop {
95        self.binding.as_ref().unwrap().defer_content_kill_for_test()
96    }
97
98    #[cfg(all(test, unix))]
99    pub(crate) fn content_was_refused_for_test(&self) -> bool {
100        self.binding.as_ref().unwrap().content_was_refused()
101    }
102    #[cfg(test)]
103    pub(super) fn new(
104        handle: &SupervisorHandle,
105        module: &str,
106        role: SpawnRole,
107        binding: Option<ProgramBindingPublication>,
108    ) -> Arc<Self> {
109        let required = binding.is_some();
110        Self::new_with_binding_requirement(handle, module, role, binding, required)
111    }
112
113    pub(super) fn new_with_binding_requirement(
114        handle: &SupervisorHandle,
115        module: &str,
116        role: SpawnRole,
117        binding: Option<ProgramBindingPublication>,
118        requires_binding: bool,
119    ) -> Arc<Self> {
120        let binding_key = binding
121            .as_ref()
122            .map(|binding| binding.channel_key())
123            .unwrap_or_else(|| program_binding::ProgramBindingKey::new(handle));
124        // The spawn generation names this launch from now on, so a candidate
125        // that registers and opens routes before cutover attests the same
126        // number it keeps after promotion.
127        let (incarnation, generation) = handle.spawn_events.allocate_generation(module);
128        Self::create(
129            handle,
130            module,
131            role,
132            binding,
133            requires_binding,
134            binding_key,
135            incarnation,
136            generation,
137        )
138    }
139
140    /// Rebuild an unregistered launch from its validated binding key and
141    /// generation. Only `supervise::live_upgrade` imports generations; new
142    /// spawns allocate their own.
143    #[cfg(any(target_os = "linux", target_os = "macos"))]
144    pub(crate) fn adopted_from_handover(
145        handle: &SupervisorHandle,
146        module: &str,
147        role: SpawnRole,
148        binding: Option<ProgramBindingPublication>,
149        binding_key: program_binding::ProgramBindingKey,
150        generation: u64,
151    ) -> Arc<Self> {
152        handle
153            .spawn_events
154            .reserve_adopted_generation(module, generation);
155        let incarnation = binding_key.incarnation.clone();
156        let required = binding.is_some();
157        Self::create(
158            handle,
159            module,
160            role,
161            binding,
162            required,
163            binding_key,
164            incarnation,
165            generation,
166        )
167    }
168
169    #[allow(clippy::too_many_arguments)]
170    fn create(
171        handle: &SupervisorHandle,
172        module: &str,
173        role: SpawnRole,
174        binding: Option<ProgramBindingPublication>,
175        requires_binding: bool,
176        binding_key: program_binding::ProgramBindingKey,
177        incarnation: String,
178        generation: u64,
179    ) -> Arc<Self> {
180        let (launch, _) = tokio::sync::watch::channel(LaunchState::Pending);
181        let spawn = Arc::new(Self {
182            incarnation: binding_key.incarnation.clone(),
183            binding_key,
184            claims: std::sync::OnceLock::new(),
185            module_id: module.into(),
186            authority: crate::spawn_authority::SpawnAuthorityRecord::new(
187                incarnation,
188                generation,
189                module,
190            ),
191            resume_token_record: Default::default(),
192            resume_witnesses: Default::default(),
193            role,
194            hello_seen: AtomicBool::new(false),
195            registered: AtomicBool::new(false),
196            nonce_registered: AtomicBool::new(false),
197            deadline: std::sync::OnceLock::new(),
198            launch,
199            transition: Mutex::new(()),
200            primary_sink: Mutex::new(None),
201            #[cfg(test)]
202            retirement_pause: Mutex::new(None),
203            #[cfg(any(unix, windows))]
204            endpoint: Mutex::new(None),
205            binding,
206            requires_binding,
207            identity: std::sync::OnceLock::new(),
208            connections: Arc::downgrade(&handle.registration_connections),
209        });
210        if let Some(binding) = &spawn.binding {
211            binding.attach_registration(&spawn);
212        }
213        let mut launches = handle
214            .registration_launches
215            .lock()
216            .unwrap_or_else(|p| p.into_inner());
217        launches.retain(|launch| launch.strong_count() != 0);
218        launches.push(Arc::downgrade(&spawn));
219        spawn
220    }
221
222    pub(crate) fn bind(self: &Arc<Self>, connection: ConnectionId) {
223        if let Some(connections) = self.connections.upgrade() {
224            connections
225                .lock()
226                .unwrap_or_else(|p| p.into_inner())
227                .insert(connection, self.clone());
228        }
229    }
230
231    pub(super) fn ready(&self) {
232        self.launch.send_if_modified(|state| {
233            if *state == LaunchState::Pending {
234                *state = LaunchState::Ready;
235                true
236            } else {
237                false
238            }
239        });
240    }
241    pub(super) fn refuse(&self) {
242        self.retire();
243    }
244    /// The one retirement step, run at the first exit observation (and when
245    /// the launch is refused or its primary registration ends): the authority
246    /// record dies, the claims are voided, the channel is shut and the epoch
247    /// is bumped, synchronously and before the caller's next await.
248    pub(crate) fn retire(&self) {
249        self.retire_transition(
250            self.transition.lock().unwrap_or_else(|p| p.into_inner()),
251            true,
252        );
253    }
254
255    /// End the inherited transport without ending a legacy launch that may
256    /// still register by nonce. Once a child registers here, or the gate
257    /// requires this channel to bind registration to its admitted executable,
258    /// losing the transport ends its authority.
259    pub(crate) fn retire_registration_channel(&self) {
260        let transition = self.transition.lock().unwrap_or_else(|p| p.into_inner());
261        if !self.nonce_registered.load(Ordering::Acquire) {
262            self.retire_transition(transition, self.registered() || self.requires_binding);
263        }
264    }
265
266    // HELLO publication holds the transition guard, so retirement cannot miss
267    // the primary sink or race a replacement into this slot after Dead.
268    pub(crate) fn bind_primary_sink(&self, sink: crate::FrameSink) {
269        *self.primary_sink.lock().unwrap_or_else(|p| p.into_inner()) = Some(sink);
270    }
271
272    pub(crate) fn end_primary_registration(&self) {
273        let _transition = self.transition.lock().unwrap_or_else(|p| p.into_inner());
274        if let Some(claims) = self.claims.get() {
275            claims.end_primary_registration();
276        }
277    }
278
279    fn retire_unused(&self) {
280        let transition = self.transition.lock().unwrap_or_else(|p| p.into_inner());
281        if !self.registered() {
282            self.nonce_registered.store(true, Ordering::Release);
283            // The spawn registered by nonce instead: only its unused channel
284            // ends. Its authority record stays live for its nonce consumers.
285            self.retire_transition(transition, false);
286        }
287    }
288
289    fn retire_transition(&self, transition: std::sync::MutexGuard<'_, ()>, ends_authority: bool) {
290        let revoked;
291        // Marking the record dead comes first; dropping the fence at the end
292        // of this block bumps its epoch after the claims and channel ended.
293        let authority_fence = ends_authority
294            .then(|| self.authority.begin_retirement())
295            .flatten();
296        {
297            if *self.launch.borrow() == LaunchState::Dead {
298                return;
299            }
300            self.launch.send_replace(LaunchState::Dead);
301            if let Some(primary) = self
302                .primary_sink
303                .lock()
304                .unwrap_or_else(|p| p.into_inner())
305                .take()
306            {
307                primary.terminate_ingress();
308                primary.terminate_egress();
309            }
310            revoked = self.claims.get().map(|claims| claims.revoke());
311            #[cfg(any(unix, windows))]
312            if let Some(endpoint) = self
313                .endpoint
314                .lock()
315                .unwrap_or_else(|p| p.into_inner())
316                .take()
317            {
318                #[cfg(unix)]
319                let _ = endpoint.shutdown(std::net::Shutdown::Both);
320                #[cfg(windows)]
321                endpoint.shutdown();
322            }
323        }
324        drop(authority_fence);
325        drop(transition);
326        #[cfg(test)]
327        if let Some(pause) = self.retirement_pause.lock().unwrap().take() {
328            let _ = pause.reached.send(());
329            let _ = pause.release.recv_timeout(Duration::from_secs(5));
330        }
331        if let (Some(claims), Some(revoked)) = (self.claims.get(), revoked) {
332            claims.close_revoked(revoked);
333        }
334        if let Some(binding) = &self.binding {
335            binding.retire();
336        }
337    }
338
339    pub(crate) async fn wait_launch(&self) {
340        let mut state = self.launch.subscribe();
341        while *state.borrow_and_update() == LaunchState::Pending {
342            if state.changed().await.is_err() {
343                break;
344            }
345        }
346    }
347
348    pub(crate) fn launch_ready(&self) -> bool {
349        *self.launch.borrow() == LaunchState::Ready
350    }
351
352    pub(crate) fn deadline(&self) -> Instant {
353        *self
354            .deadline
355            .get()
356            .expect("served registration has a spawn deadline")
357    }
358
359    pub(crate) fn registered(&self) -> bool {
360        self.registered.load(Ordering::Acquire)
361    }
362
363    /// Serialize the registry/forwarding publication with synchronous retirement.
364    /// Image verification happens before this lock; only snapshot writes follow it.
365    pub(crate) fn begin_publication(&self) -> Result<std::sync::MutexGuard<'_, ()>, &'static str> {
366        let guard = self.transition.lock().unwrap_or_else(|p| p.into_inner());
367        if !self.launch_ready() {
368            return Err(REGISTRATION_CHANNEL_CLOSED);
369        }
370        Ok(guard)
371    }
372
373    pub(crate) async fn registration_expired(&self) {
374        tokio::time::sleep_until(self.deadline()).await;
375        if self.registered.load(Ordering::Acquire) {
376            std::future::pending::<()>().await;
377        }
378    }
379
380    pub(crate) async fn wait_closed(&self) {
381        let mut state = self.launch.subscribe();
382        loop {
383            if matches!(*state.borrow_and_update(), LaunchState::Dead) {
384                return;
385            }
386            if state.changed().await.is_err() {
387                return;
388            }
389        }
390    }
391
392    pub(crate) async fn wait_registration_failure(&self) {
393        // A launch without a required program binding can still register by
394        // nonce through an older SDK. Closing its unused channel is not a
395        // registration failure.
396        if !self.requires_binding {
397            std::future::pending::<()>().await;
398        }
399        self.wait_closed().await;
400        if self.registered() || self.nonce_registered.load(Ordering::Acquire) {
401            std::future::pending::<()>().await;
402        }
403    }
404
405    pub(crate) fn admit_hello(&self, module: Option<&str>) -> Result<(), &'static str> {
406        if self.hello_seen.swap(true, Ordering::AcqRel) {
407            return Err("registration_channel_hello_repeated");
408        }
409        if module != Some(self.module_id.as_str()) {
410            return Err("registration_channel_module_mismatch");
411        }
412        self.check()
413    }
414
415    pub(crate) fn check(&self) -> Result<(), &'static str> {
416        self.check_state()?;
417        if self
418            .binding
419            .as_ref()
420            .is_some_and(|binding| binding.check().is_err())
421        {
422            return Err("program_refused");
423        }
424        Ok(())
425    }
426
427    pub(crate) fn verdict(&self) -> Result<(), &'static str> {
428        self.check_state()?;
429        if self
430            .binding
431            .as_ref()
432            .is_some_and(|binding| binding.verdict().is_err())
433        {
434            return Err("program_refused");
435        }
436        self.check_state()
437    }
438
439    fn check_state(&self) -> Result<(), &'static str> {
440        match *self.launch.borrow() {
441            LaunchState::Dead => return Err(REGISTRATION_CHANNEL_CLOSED),
442            LaunchState::Pending => return Err("config_delivery_deferred"),
443            LaunchState::Ready => {}
444        }
445        if self.requires_binding && self.binding.is_none() {
446            return Err("program_refused");
447        }
448        Ok(())
449    }
450
451    pub(crate) fn has_program_binding(&self) -> bool {
452        self.binding.is_some()
453    }
454
455    pub(crate) fn is_candidate(&self) -> bool {
456        self.role == SpawnRole::SwapCandidate
457    }
458
459    pub(crate) fn hello_accepted(&self) {
460        self.registered.store(true, Ordering::Release);
461        #[cfg(windows)]
462        if let Some(binding) = &self.binding {
463            binding.hello_accepted();
464        }
465    }
466}
467
468#[derive(Debug, Clone)]
469pub(crate) struct RegistrationService {
470    router: Weak<crate::Router>,
471    auth: crate::server::ServerAuth,
472}
473
474impl SupervisorHandle {
475    /// Includes warming and not-yet-registered launches, not just the active slot.
476    pub(crate) fn spawn_authority_records_for_module(
477        &self,
478        module: &str,
479    ) -> Vec<Arc<crate::spawn_authority::SpawnAuthorityRecord>> {
480        self.registration_launches
481            .lock()
482            .unwrap_or_else(|p| p.into_inner())
483            .iter()
484            .filter_map(Weak::upgrade)
485            .filter(|spawn| spawn.module_id == module)
486            .map(|spawn| spawn.authority.clone())
487            .collect()
488    }
489    /// The daemon incarnation spawn generations and authority records belong to.
490    pub(crate) fn daemon_incarnation(&self) -> String {
491        self.spawn_events
492            .0
493            .lock()
494            .unwrap_or_else(|p| p.into_inner())
495            .daemon_incarnation
496            .clone()
497    }
498
499    /// Remember which launch the nonce just minted for `spawn` belongs to. A
500    /// launch that received no nonce (a gated, channel-only launch) records
501    /// nothing.
502    pub(super) fn record_nonce_launch(&self, spawn: &Arc<RegistrationSpawn>) {
503        let nonce = match spawn.role {
504            SpawnRole::Plain => self
505                .spawn_nonces
506                .lock()
507                .unwrap_or_else(|p| p.into_inner())
508                .get(&spawn.module_id)
509                .cloned(),
510            SpawnRole::SwapCandidate => self
511                .swaps
512                .lock()
513                .unwrap_or_else(|p| p.into_inner())
514                .get(&spawn.module_id)
515                .map(|swap| swap.candidate_nonce.clone()),
516        };
517        let Some(nonce) = nonce.filter(|nonce| !nonce.is_empty()) else {
518            return;
519        };
520        let current = self.current_launch_nonces();
521        let mut launches = self
522            .nonce_launches
523            .lock()
524            .unwrap_or_else(|p| p.into_inner());
525        launches.retain(|nonce, (_, launch)| launch.strong_count() != 0 || current.contains(nonce));
526        launches.insert(nonce, (spawn.module_id.clone(), Arc::downgrade(spawn)));
527    }
528
529    /// Every nonce that can still authorize a consumer: each module's recorded
530    /// spawn nonce and both nonces of each open swap.
531    fn current_launch_nonces(&self) -> std::collections::HashSet<String> {
532        let mut current = self
533            .spawn_nonces
534            .lock()
535            .unwrap_or_else(|p| p.into_inner())
536            .values()
537            .cloned()
538            .collect::<std::collections::HashSet<_>>();
539        for swap in self
540            .swaps
541            .lock()
542            .unwrap_or_else(|p| p.into_inner())
543            .values()
544        {
545            current.insert(swap.candidate_nonce.clone());
546            current.extend(swap.incumbent_nonce.clone());
547        }
548        current
549    }
550
551    /// What a consumer presenting `presented` as `module_id`'s launch nonce
552    /// attests, decided in one step: the launch the nonce was minted for is
553    /// resolved first and held, then the nonce is authorized exactly as
554    /// `spawned_consumer_authorized` decides. A launch that ends, or a nonce
555    /// that is withdrawn, after that step is caught later by the record's own
556    /// liveness, never turned into a principal with no record.
557    pub(crate) fn attest_spawned_consumer(
558        &self,
559        module_id: &str,
560        presented: &str,
561    ) -> NonceAttestation {
562        if let Some(record) = self.resumed_nonce_consumer(module_id, presented) {
563            return NonceAttestation::Spawn(record);
564        }
565        let recorded = self
566            .nonce_launches
567            .lock()
568            .unwrap_or_else(|p| p.into_inner())
569            .get(presented)
570            .map(|(module, launch)| (module.clone(), launch.upgrade()));
571        if !self.spawned_consumer_authorized(module_id, presented) {
572            return NonceAttestation::Refused;
573        }
574        match recorded {
575            // No launch was ever recorded for this nonce: the legacy launch
576            // nonce with no registration spawn behind it.
577            None => NonceAttestation::Unrecorded,
578            Some((module, Some(spawn))) if module == module_id => {
579                NonceAttestation::Spawn(spawn.authority.clone())
580            }
581            // The nonce's launch had a record and it is gone, or the launch
582            // belongs to another module. Either way the record that would
583            // fence this consumer is not there, so it attests nothing.
584            Some(_) => NonceAttestation::Refused,
585        }
586    }
587
588    /// Resolve only a nonce minted for the current ordinary launch or swap
589    /// candidate. A carried nonce hash is consumer identity, not HELLO authority.
590    pub(crate) fn nonce_hello_spawn(
591        &self,
592        module_id: &str,
593        nonce: &str,
594    ) -> Option<Arc<RegistrationSpawn>> {
595        let spawn = self
596            .nonce_launches
597            .lock()
598            .unwrap_or_else(|p| p.into_inner())
599            .get(nonce)
600            .filter(|(module, _)| module == module_id)
601            .and_then(|(_, spawn)| spawn.upgrade())?;
602        self.spawned_consumer_authorized(module_id, nonce)
603            .then_some(spawn)
604    }
605
606    pub(crate) fn retire_unused_registration_channel(&self, module: &str, candidate: bool) {
607        // Successful registration claims the id even when legacy policy did
608        // not require a nonce. Resolve its unused endpoint from our launch
609        // history, not a credential supplied by that registration.
610        let launch = self
611            .registration_launches
612            .lock()
613            .unwrap_or_else(|p| p.into_inner())
614            .iter()
615            .rev()
616            .filter_map(Weak::upgrade)
617            .find(|spawn| spawn.module_id == module && spawn.is_candidate() == candidate);
618        if let Some(launch) = launch {
619            launch.retire_unused();
620        }
621    }
622    #[cfg(test)]
623    pub(crate) fn capture_registration_channels_for_test(&self) {
624        *self.registration_test_channels.lock().unwrap() = Some(Vec::new());
625    }
626
627    #[cfg(test)]
628    pub(crate) fn registration_for_test(&self, module: &str) -> Option<Arc<RegistrationSpawn>> {
629        self.registration_test_channels
630            .lock()
631            .unwrap()
632            .as_ref()?
633            .iter()
634            .rev()
635            .find(|(spawn, _)| spawn.module_id == module)
636            .map(|(spawn, _)| spawn.clone())
637    }
638
639    #[cfg(test)]
640    pub(crate) fn registration_proof_for_test(&self, module: &str) -> Option<RegistrationProof> {
641        let Some(channel) = self.registration_for_test(module) else {
642            return self.spawn_nonce(module).map(Into::into);
643        };
644        Some(RegistrationProof {
645            key: channel
646                .binding
647                .as_ref()
648                .map(|binding| binding.key_for_test())
649                .unwrap_or_else(|| format!("channel-fixture:{:p}", Arc::as_ptr(&channel))),
650            channel: Some(channel),
651        })
652    }
653
654    #[cfg(test)]
655    pub(crate) fn candidate_registration_proof_for_test(
656        &self,
657        module: &str,
658    ) -> Option<RegistrationProof> {
659        let channel = self.registration_for_test(module)?;
660        if !channel.is_candidate() {
661            return None;
662        }
663        Some(RegistrationProof {
664            key: channel.binding.as_ref()?.key_for_test(),
665            channel: Some(channel),
666        })
667    }
668    /// Both proofs name the registration connection, not merely its module ID.
669    /// A process birth identity ties a channel to the current launch snapshot,
670    /// excluding candidates before promotion and incumbents after promotion.
671    pub(crate) fn registration_is_current_live(
672        &self,
673        registry: &Registry,
674        module: &str,
675        connection: ConnectionId,
676        nonce: Option<&str>,
677    ) -> bool {
678        if !self.registration_snapshot_is_current_live(registry, module, connection, nonce) {
679            return false;
680        }
681        if self
682            .registration_spawn(connection)
683            .is_some_and(|spawn| spawn.verdict().is_err())
684        {
685            return false;
686        }
687        self.registration_snapshot_is_current_live(registry, module, connection, nonce)
688    }
689
690    pub(crate) fn registration_snapshot_is_current_live(
691        &self,
692        registry: &Registry,
693        module: &str,
694        connection: ConnectionId,
695        nonce: Option<&str>,
696    ) -> bool {
697        if !registry
698            .get_module(module)
699            .ok()
700            .flatten()
701            .is_some_and(|registration| registration.connection_id == connection)
702        {
703            return false;
704        }
705        let Some(child) = self.get(module) else {
706            return false;
707        };
708        let Some(launch) = child.resource_launch() else {
709            return false;
710        };
711        if !launch.enabled || !launch.alive {
712            return false;
713        }
714        if let Some(spawn) = self.registration_spawn(connection) {
715            return spawn.module_id == module
716                && spawn.check_state().is_ok()
717                && (!self.module_is_gated(module) || spawn.has_program_binding())
718                && spawn.identity.get().is_some_and(|identity| {
719                    launch.pid == Some(identity.pid) && launch.start == Some(identity.start_time)
720                });
721        }
722        if self.module_is_gated(module) {
723            return false;
724        }
725        nonce.is_some_and(|presented| {
726            self.spawn_nonce(module).is_some_and(|current| {
727                !presented.is_empty() && constant_time_eq(current.as_bytes(), presented.as_bytes())
728            })
729        })
730    }
731
732    pub(crate) fn install_registration_service(
733        &self,
734        router: Weak<crate::Router>,
735        auth: crate::server::ServerAuth,
736    ) {
737        let mut service = self
738            .registration_service
739            .lock()
740            .unwrap_or_else(|p| p.into_inner());
741        debug_assert!(service.is_none(), "registration service installed twice");
742        if service.is_none() {
743            *service = Some(RegistrationService { router, auth });
744        }
745    }
746
747    pub(crate) fn registration_spawn(
748        &self,
749        connection: ConnectionId,
750    ) -> Option<Arc<RegistrationSpawn>> {
751        self.registration_connections
752            .lock()
753            .unwrap_or_else(|p| p.into_inner())
754            .get(&connection)
755            .cloned()
756    }
757
758    pub(crate) fn forget_registration_connection(&self, connection: ConnectionId) {
759        self.registration_connections
760            .lock()
761            .unwrap_or_else(|p| p.into_inner())
762            .remove(&connection);
763    }
764
765    #[cfg(any(unix, windows))]
766    pub(super) fn serve_registration(
767        &self,
768        channel: SpawnRegistrationChannel,
769        spawn: Arc<RegistrationSpawn>,
770        pid: u32,
771        deadline: Instant,
772    ) {
773        let _ = spawn.deadline.set(deadline);
774        #[cfg(unix)]
775        let endpoint = channel.try_clone();
776        #[cfg(windows)]
777        let endpoint = channel.shutdown_handle();
778        match endpoint {
779            Ok(endpoint) => {
780                let _transition = spawn.transition.lock().unwrap_or_else(|p| p.into_inner());
781                if *spawn.launch.borrow() == LaunchState::Dead {
782                    #[cfg(unix)]
783                    let _ = endpoint.shutdown(std::net::Shutdown::Both);
784                    #[cfg(windows)]
785                    endpoint.shutdown();
786                    return;
787                }
788                *spawn.endpoint.lock().unwrap_or_else(|p| p.into_inner()) = Some(endpoint);
789            }
790            Err(_) => {
791                spawn.retire_registration_channel();
792                return;
793            }
794        }
795        #[cfg(test)]
796        {
797            let mut captured = self.registration_test_channels.lock().unwrap();
798            if let Some(channels) = &mut *captured {
799                channels.push((
800                    spawn,
801                    super::CapturedRegistrationEndpoint { _channel: channel },
802                ));
803                return;
804            }
805        }
806        let service = self
807            .registration_service
808            .lock()
809            .unwrap_or_else(|p| p.into_inner())
810            .clone();
811        let Some((router, auth)) =
812            service.and_then(|service| Some((service.router.upgrade()?, service.auth)))
813        else {
814            // This transport cannot authorize registration. A legacy launch
815            // may still use its nonce; a channel-only launch loses authority.
816            spawn.retire_registration_channel();
817            #[cfg(unix)]
818            let _ = channel.shutdown(std::net::Shutdown::Both);
819            return;
820        };
821        tokio::spawn(async move {
822            let serve = async {
823                #[cfg(unix)]
824                let stream = {
825                    let _ = pid;
826                    channel.set_nonblocking(true)?;
827                    tokio::net::UnixStream::from_std(channel)?
828                };
829                #[cfg(windows)]
830                let stream = {
831                    tokio::task::spawn_blocking(move || {
832                        channel.accept_tokio_pipe_server(pid, deadline.into_std())
833                    })
834                    .await
835                    .map_err(io::Error::other)??
836                };
837                let _ = crate::server::handle_connection_with_origin(
838                    RegistrationStream {
839                        stream,
840                        spawn: spawn.clone(),
841                    },
842                    router,
843                    auth,
844                    crate::server::LocalOrigin::RegistrationChannel(spawn.clone()),
845                )
846                .await;
847                Ok::<(), io::Error>(())
848            };
849            let _ = serve.await;
850            spawn.retire_registration_channel();
851        });
852    }
853}
854
855// End registration at the transport's first EOF, including during authentication
856// or frame decoding, without waiting for the connection loop to unwind. Legacy
857// nonce authority survives an unused channel's closure. An Interrupted I/O read
858// error skips only this revoke; connection cleanup still ends registration.
859struct RegistrationStream<S> {
860    stream: S,
861    spawn: Arc<RegistrationSpawn>,
862}
863
864impl<S: tokio::io::AsyncRead + Unpin> tokio::io::AsyncRead for RegistrationStream<S> {
865    fn poll_read(
866        self: std::pin::Pin<&mut Self>,
867        cx: &mut std::task::Context<'_>,
868        buf: &mut tokio::io::ReadBuf<'_>,
869    ) -> std::task::Poll<io::Result<()>> {
870        let this = self.get_mut();
871        let before = buf.filled().len();
872        let can_read = buf.remaining() != 0;
873        let result = std::pin::Pin::new(&mut this.stream).poll_read(cx, buf);
874        let ended = match &result {
875            std::task::Poll::Ready(Ok(())) => can_read && buf.filled().len() == before,
876            std::task::Poll::Ready(Err(error)) => error.kind() != io::ErrorKind::Interrupted,
877            std::task::Poll::Pending => false,
878        };
879        if ended {
880            this.spawn.retire_registration_channel();
881        }
882        result
883    }
884}
885
886impl<S: tokio::io::AsyncWrite + Unpin> tokio::io::AsyncWrite for RegistrationStream<S> {
887    fn poll_write(
888        self: std::pin::Pin<&mut Self>,
889        cx: &mut std::task::Context<'_>,
890        buf: &[u8],
891    ) -> std::task::Poll<io::Result<usize>> {
892        std::pin::Pin::new(&mut self.get_mut().stream).poll_write(cx, buf)
893    }
894
895    fn poll_flush(
896        self: std::pin::Pin<&mut Self>,
897        cx: &mut std::task::Context<'_>,
898    ) -> std::task::Poll<io::Result<()>> {
899        std::pin::Pin::new(&mut self.get_mut().stream).poll_flush(cx)
900    }
901
902    fn poll_shutdown(
903        self: std::pin::Pin<&mut Self>,
904        cx: &mut std::task::Context<'_>,
905    ) -> std::task::Poll<io::Result<()>> {
906        std::pin::Pin::new(&mut self.get_mut().stream).poll_shutdown(cx)
907    }
908}
909
910/// A unit fixture owns the daemon endpoint while it dispatches HELLO directly,
911/// without a socket reader. Its table key locates a channel; it is not sent as a
912/// launch nonce. Full transport tests use the authenticated service instead.
913#[cfg(test)]
914#[derive(Clone, Debug)]
915pub(crate) struct RegistrationProof {
916    key: String,
917    channel: Option<Arc<RegistrationSpawn>>,
918}
919#[cfg(test)]
920impl std::ops::Deref for RegistrationProof {
921    type Target = str;
922    fn deref(&self) -> &str {
923        &self.key
924    }
925}
926#[cfg(test)]
927impl PartialEq for RegistrationProof {
928    fn eq(&self, other: &Self) -> bool {
929        self.key == other.key
930    }
931}
932#[cfg(test)]
933impl From<String> for RegistrationProof {
934    fn from(key: String) -> Self {
935        Self { key, channel: None }
936    }
937}
938#[cfg(test)]
939impl From<&str> for RegistrationProof {
940    fn from(key: &str) -> Self {
941        key.to_owned().into()
942    }
943}
944#[cfg(test)]
945impl RegistrationProof {
946    pub(crate) fn bind(&self, connection: ConnectionId) {
947        if let Some(channel) = &self.channel {
948            channel.bind(connection);
949        }
950    }
951    pub(crate) fn nonce(&self) -> Option<String> {
952        self.channel.is_none().then(|| self.key.clone())
953    }
954    #[cfg(target_os = "linux")]
955    pub(crate) fn as_str(&self) -> &str {
956        &self.key
957    }
958}
959
960#[cfg(test)]
961mod tests {
962    use super::*;
963    use serde_json::json;
964    use subc_protocol::{Frame, FrameType};
965
966    fn hello(module: &str) -> Frame {
967        let manifest = subc_protocol::manifest::ModuleManifest::builder(module, "0.1.0")
968            .protocol_ver(subc_protocol::PROTOCOL_VERSION)
969            .build();
970        Frame::build(
971            FrameType::Hello,
972            subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
973            0,
974            0,
975            10,
976            serde_json::to_vec(
977                &json!({"protocol_ver": subc_protocol::PROTOCOL_VERSION, "manifest": manifest}),
978            )
979            .unwrap(),
980        )
981        .unwrap()
982    }
983
984    fn code(frames: &[Frame]) -> String {
985        assert_eq!(frames.len(), 1);
986        assert_eq!(frames[0].header.ty, FrameType::Error);
987        serde_json::from_slice::<serde_json::Value>(&frames[0].body).unwrap()["code"]
988            .as_str()
989            .unwrap()
990            .into()
991    }
992
993    fn setup() -> (SupervisorHandle, Arc<Registry>, crate::ControlHandler) {
994        let handle = SupervisorHandle::new();
995        let registry = Arc::new(Registry::default());
996        let control = crate::ControlHandler::new(registry.clone()).with_supervisor(handle.clone());
997        (handle, registry, control)
998    }
999
1000    fn bound(handle: &SupervisorHandle, id: u64, role: SpawnRole) -> Arc<RegistrationSpawn> {
1001        let spawn = RegistrationSpawn::new(handle, "channel-module", role, None);
1002        spawn.ready();
1003        spawn.bind(ConnectionId::new(id));
1004        spawn
1005    }
1006
1007    #[cfg(unix)]
1008    async fn hello_rollback_case(candidate: bool) {
1009        let worker = if candidate {
1010            "supervise::registration::tests::candidate_hello_forwarding_rollback_worker"
1011        } else {
1012            "supervise::registration::tests::ordinary_hello_forwarding_rollback_worker"
1013        };
1014        let mut child = tokio::process::Command::new(std::env::current_exe().unwrap())
1015            .args(["--exact", worker, "--ignored", "--nocapture"])
1016            .kill_on_drop(true)
1017            .spawn()
1018            .unwrap();
1019        let result = tokio::time::timeout(Duration::from_secs(5), child.wait()).await;
1020        if result.is_err() {
1021            let _ = child.kill().await;
1022            let _ = child.wait().await;
1023        }
1024        assert!(matches!(result, Ok(Ok(status)) if status.success()),
1025            "channel HELLO rollback must finish and allow later retirement within the subprocess deadline");
1026    }
1027
1028    #[cfg(unix)]
1029    #[tokio::test]
1030    async fn ordinary_channel_hello_rollback_does_not_reenter_transition() {
1031        hello_rollback_case(false).await;
1032    }
1033
1034    #[cfg(unix)]
1035    #[tokio::test]
1036    async fn candidate_channel_hello_rollback_does_not_reenter_transition() {
1037        hello_rollback_case(true).await;
1038    }
1039
1040    #[cfg(unix)]
1041    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1042    #[ignore = "subprocess fixture; invoked only by the bounded rollback tests"]
1043    async fn ordinary_hello_forwarding_rollback_worker() {
1044        hello_forwarding_rollback_worker(false).await;
1045    }
1046
1047    #[cfg(unix)]
1048    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1049    #[ignore = "subprocess fixture; invoked only by the bounded rollback tests"]
1050    async fn candidate_hello_forwarding_rollback_worker() {
1051        hello_forwarding_rollback_worker(true).await;
1052    }
1053
1054    #[cfg(unix)]
1055    async fn hello_forwarding_rollback_worker(candidate: bool) {
1056        let (handle, registry, control) = setup();
1057        if candidate {
1058            assert_eq!(
1059                control
1060                    .handle_control(ConnectionId::new(90), hello("channel-module"))
1061                    .unwrap()[0]
1062                    .header
1063                    .ty,
1064                FrameType::HelloAck
1065            );
1066            handle.open_swap("channel-module", "candidate".into());
1067        }
1068        let forwarding = control.forwarding();
1069        forwarding.begin_daemon_drain().unwrap();
1070        let role = if candidate {
1071            SpawnRole::SwapCandidate
1072        } else {
1073            SpawnRole::Plain
1074        };
1075        let spawn = RegistrationSpawn::new(&handle, "channel-module", role, None);
1076        spawn.ready();
1077        let router = Arc::new(crate::Router::with_control_handler(Arc::new(control)));
1078        let info = subc_transport::ConnectionInfo {
1079            schema: subc_transport::SCHEMA_VERSION,
1080            wire_version: None,
1081            endpoints: Vec::new(),
1082            key: vec![0x42; 32],
1083            daemon_id: [0x24; 16],
1084            pid: std::process::id(),
1085            daemon_ver: "test".into(),
1086        };
1087        router.install_registration_service(crate::server::ServerAuth::new(
1088            info.key.clone(),
1089            info.daemon_id,
1090            "test",
1091        ));
1092        let (parent, child) = std::os::unix::net::UnixStream::pair().unwrap();
1093        child.set_nonblocking(true).unwrap();
1094        let mut child = tokio::net::UnixStream::from_std(child).unwrap();
1095        handle.serve_registration(
1096            parent,
1097            spawn.clone(),
1098            std::process::id(),
1099            Instant::now() + Duration::from_secs(5),
1100        );
1101        subc_transport::authenticate_client(&mut child, &info, Duration::from_secs(1))
1102            .await
1103            .unwrap();
1104        subc_transport::write_frame(&mut child, &hello("channel-module"))
1105            .await
1106            .unwrap();
1107        let reply = tokio::time::timeout(
1108            Duration::from_secs(1),
1109            subc_transport::read_frame(&mut child),
1110        )
1111        .await
1112        .expect("forwarding refusal must settle the channel HELLO")
1113        .unwrap();
1114        if let Some(reply) = reply {
1115            assert_eq!(reply.header.ty, FrameType::Error);
1116        }
1117        assert!(!spawn.registered());
1118        if candidate {
1119            assert!(registry.get_candidate("channel-module").unwrap().is_none());
1120        } else {
1121            assert!(registry.get_module("channel-module").unwrap().is_none());
1122        }
1123        tokio::time::timeout(
1124            Duration::from_secs(1),
1125            tokio::task::spawn_blocking(move || spawn.retire()),
1126        )
1127        .await
1128        .expect("retirement after HELLO rollback must return")
1129        .unwrap();
1130    }
1131
1132    #[test]
1133    fn registration_channel_wrong_id_consumes_hello() {
1134        let (handle, registry, control) = setup();
1135        let _spawn = bound(&handle, 1, SpawnRole::Plain);
1136        assert_eq!(
1137            code(
1138                &control
1139                    .handle_control(ConnectionId::new(1), hello("another-module"))
1140                    .unwrap()
1141            ),
1142            "registration_channel_module_mismatch"
1143        );
1144        assert_eq!(
1145            code(
1146                &control
1147                    .handle_control(ConnectionId::new(1), hello("channel-module"))
1148                    .unwrap()
1149            ),
1150            "registration_channel_hello_repeated"
1151        );
1152        assert_eq!(registry.active_registration_count().unwrap(), 0);
1153    }
1154
1155    #[test]
1156    fn registration_channel_second_hello_is_refused() {
1157        let (handle, registry, control) = setup();
1158        let _spawn = bound(&handle, 1, SpawnRole::Plain);
1159        let replies = control
1160            .handle_control(ConnectionId::new(1), hello("channel-module"))
1161            .unwrap();
1162        assert_eq!(
1163            replies[0].header.ty,
1164            FrameType::HelloAck,
1165            "{}",
1166            String::from_utf8_lossy(&replies[0].body)
1167        );
1168        assert_eq!(
1169            code(
1170                &control
1171                    .handle_control(ConnectionId::new(1), hello("channel-module"))
1172                    .unwrap()
1173            ),
1174            "registration_channel_hello_repeated"
1175        );
1176        assert_eq!(registry.active_registration_count().unwrap(), 1);
1177    }
1178
1179    #[test]
1180    fn registration_channel_hello_after_exit_is_refused() {
1181        let (handle, registry, control) = setup();
1182        let spawn = bound(&handle, 1, SpawnRole::Plain);
1183        spawn.retire();
1184        assert_eq!(
1185            code(
1186                &control
1187                    .handle_control(ConnectionId::new(1), hello("channel-module"))
1188                    .unwrap()
1189            ),
1190            "registration_channel_closed"
1191        );
1192        assert_eq!(registry.active_registration_count().unwrap(), 0);
1193    }
1194
1195    #[test]
1196    fn registration_channel_plain_respawn_during_swap_preserves_draining_slot() {
1197        let (handle, registry, control) = setup();
1198        let _incumbent = bound(&handle, 1, SpawnRole::Plain);
1199        assert_eq!(
1200            control
1201                .handle_control(ConnectionId::new(1), hello("channel-module"))
1202                .unwrap()[0]
1203                .header
1204                .ty,
1205            FrameType::HelloAck
1206        );
1207        handle.open_swap("channel-module", "legacy-swap-token".into());
1208        let _candidate = bound(&handle, 2, SpawnRole::SwapCandidate);
1209        assert_eq!(
1210            control
1211                .handle_control(ConnectionId::new(2), hello("channel-module"))
1212                .unwrap()[0]
1213                .header
1214                .ty,
1215            FrameType::HelloAck
1216        );
1217        registry
1218            .promote_candidate("channel-module")
1219            .unwrap()
1220            .unwrap();
1221        control.cleanup_connection(ConnectionId::new(2)).unwrap();
1222        assert_eq!(
1223            handle.swap_hello_admission("channel-module", None),
1224            SwapHelloAdmission::Refused
1225        );
1226        let _respawn = bound(&handle, 3, SpawnRole::Plain);
1227        assert_eq!(
1228            control
1229                .handle_control(ConnectionId::new(3), hello("channel-module"))
1230                .unwrap()[0]
1231                .header
1232                .ty,
1233            FrameType::HelloAck
1234        );
1235        assert_eq!(
1236            registry
1237                .get_module("channel-module")
1238                .unwrap()
1239                .unwrap()
1240                .connection_id,
1241            ConnectionId::new(3)
1242        );
1243        assert!(registry
1244            .get_module_by_connection(ConnectionId::new(1))
1245            .unwrap()
1246            .is_some());
1247        assert!(registry.list_modules_with_nonce_verification().unwrap().1[0].1);
1248        control.cleanup_connection(ConnectionId::new(1)).unwrap();
1249        assert_eq!(
1250            registry
1251                .get_module("channel-module")
1252                .unwrap()
1253                .unwrap()
1254                .connection_id,
1255            ConnectionId::new(3)
1256        );
1257    }
1258
1259    fn auth() -> (crate::server::ServerAuth, subc_transport::ConnectionInfo) {
1260        let key = vec![0x42; 32];
1261        let daemon_id = [0x24; 16];
1262        let info = subc_transport::ConnectionInfo {
1263            schema: subc_transport::SCHEMA_VERSION,
1264            wire_version: None,
1265            endpoints: Vec::new(),
1266            key: key.clone(),
1267            daemon_id,
1268            pid: std::process::id(),
1269            daemon_ver: "test".into(),
1270        };
1271        (crate::server::ServerAuth::new(key, daemon_id, "test"), info)
1272    }
1273
1274    #[cfg(unix)]
1275    #[tokio::test]
1276    async fn registration_channel_service_reuses_authenticated_frames_and_never_reconnects() {
1277        let (handle, registry, _) = setup();
1278        let forwarding = Arc::new(crate::ForwardingTable::default());
1279        let control = crate::ControlHandler::with_forwarding(registry.clone(), forwarding.clone())
1280            .with_supervisor(handle.clone());
1281        let router = Arc::new(crate::Router::with_control_handler(Arc::new(control)));
1282        let (auth, info) = auth();
1283        router.install_registration_service(auth);
1284        let spawn = RegistrationSpawn::new(&handle, "channel-module", SpawnRole::Plain, None);
1285        spawn.ready();
1286        let (parent, child) = std::os::unix::net::UnixStream::pair().unwrap();
1287        child.set_nonblocking(true).unwrap();
1288        let mut child = tokio::net::UnixStream::from_std(child).unwrap();
1289        handle.serve_registration(
1290            parent,
1291            spawn.clone(),
1292            std::process::id(),
1293            Instant::now() + Duration::from_secs(2),
1294        );
1295        subc_transport::authenticate_client(&mut child, &info, Duration::from_secs(2))
1296            .await
1297            .unwrap();
1298        let mut body: subc_protocol::ModuleHelloBody =
1299            serde_json::from_slice(&hello("channel-module").body).unwrap();
1300        body.control_ops = Some(vec!["health.check".into()]);
1301        let registration = Frame::build(
1302            FrameType::Hello,
1303            super::super::control_flags(),
1304            0,
1305            0,
1306            1,
1307            serde_json::to_vec(&body).unwrap(),
1308        )
1309        .unwrap();
1310        subc_transport::write_frame(&mut child, &registration)
1311            .await
1312            .unwrap();
1313        assert_eq!(
1314            subc_transport::read_frame(&mut child)
1315                .await
1316                .unwrap()
1317                .unwrap()
1318                .header
1319                .ty,
1320            FrameType::HelloAck
1321        );
1322        assert!(
1323            registry.list_modules_with_nonce_verification().unwrap().1[0].1,
1324            "the channel itself proves the spawn identity without a body nonce"
1325        );
1326        let ping = Frame::build(
1327            FrameType::Ping,
1328            subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
1329            0,
1330            0,
1331            11,
1332            Vec::new(),
1333        )
1334        .unwrap();
1335        subc_transport::write_frame(&mut child, &ping)
1336            .await
1337            .unwrap();
1338        assert_eq!(
1339            subc_transport::read_frame(&mut child)
1340                .await
1341                .unwrap()
1342                .unwrap()
1343                .header
1344                .ty,
1345            FrameType::Pong
1346        );
1347        let request = Frame::build(
1348            FrameType::Request,
1349            subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
1350            0,
1351            0,
1352            12,
1353            serde_json::to_vec(
1354                &subc_protocol::session::ModuleControlRequestFromModule::CatalogUpdate {
1355                    provides: Vec::new(),
1356                    capabilities: None,
1357                    ready: Some(true),
1358                },
1359            )
1360            .unwrap(),
1361        )
1362        .unwrap();
1363        subc_transport::write_frame(&mut child, &request)
1364            .await
1365            .unwrap();
1366        assert_eq!(
1367            subc_transport::read_frame(&mut child)
1368                .await
1369                .unwrap()
1370                .unwrap()
1371                .header
1372                .ty,
1373            FrameType::Response
1374        );
1375        let started = tokio::time::Instant::now();
1376        let pending = forwarding
1377            .begin_health_probe_rpc_for(
1378                "channel-module",
1379                "health.check",
1380                started,
1381                started + Duration::from_secs(2),
1382            )
1383            .unwrap();
1384        let health = Frame::build(
1385            FrameType::Request,
1386            super::super::control_flags(),
1387            0,
1388            0,
1389            pending.corr,
1390            serde_json::to_vec(&subc_protocol::session::ModuleControlRequest::HealthCheck {})
1391                .unwrap(),
1392        )
1393        .unwrap();
1394        pending.module_sink.send(health).await.unwrap();
1395        let health = tokio::time::timeout(
1396            Duration::from_secs(2),
1397            subc_transport::read_frame(&mut child),
1398        )
1399        .await
1400        .unwrap()
1401        .unwrap()
1402        .unwrap();
1403        assert_eq!(
1404            serde_json::from_slice::<serde_json::Value>(&health.body).unwrap(),
1405            json!({"op":"health.check"})
1406        );
1407        let reply =
1408            json!({"op":"health.check", "status":"degraded", "detail":"channel health reply"});
1409        let response = Frame::build(
1410            FrameType::Response,
1411            super::super::control_flags(),
1412            0,
1413            0,
1414            health.header.corr,
1415            serde_json::to_vec(&reply).unwrap(),
1416        )
1417        .unwrap();
1418        subc_transport::write_frame(&mut child, &response)
1419            .await
1420            .unwrap();
1421        match tokio::time::timeout(Duration::from_secs(2), pending.receiver)
1422            .await
1423            .unwrap()
1424            .unwrap()
1425        {
1426            crate::forwarding::ModuleControlRpcOutcome::Response(response) => {
1427                assert_eq!(serde_json::to_value(response).unwrap(), reply)
1428            }
1429            other => panic!("health reply did not traverse the channel: {other:?}"),
1430        }
1431        let push_body =
1432            serde_json::to_vec(&subc_protocol::config::ConfigChanged::new(7, Vec::new())).unwrap();
1433        let push = Frame::build(
1434            FrameType::Push,
1435            super::super::control_flags(),
1436            0,
1437            0,
1438            0,
1439            push_body.clone(),
1440        )
1441        .unwrap();
1442        pending.module_sink.send(push).await.unwrap();
1443        let pushed = tokio::time::timeout(
1444            Duration::from_secs(2),
1445            subc_transport::read_frame(&mut child),
1446        )
1447        .await
1448        .unwrap()
1449        .unwrap()
1450        .unwrap();
1451        assert_eq!(pushed.header.ty, FrameType::Push);
1452        assert_eq!(pushed.body, push_body);
1453        drop(pending.module_sink);
1454        spawn.retire();
1455        assert!(tokio::time::timeout(
1456            Duration::from_secs(2),
1457            subc_transport::read_frame(&mut child)
1458        )
1459        .await
1460        .unwrap()
1461        .unwrap()
1462        .is_none());
1463        tokio::time::timeout(Duration::from_secs(2), async {
1464            while registry.get_module("channel-module").unwrap().is_some() {
1465                tokio::task::yield_now().await;
1466            }
1467        })
1468        .await
1469        .unwrap();
1470    }
1471
1472    #[cfg(unix)]
1473    #[tokio::test]
1474    async fn registration_channel_missing_or_gone_service_closes_without_nonce_fallback() {
1475        let (handle, _, control) = setup();
1476        for installed in [false, true] {
1477            if installed {
1478                let router = Arc::new(crate::Router::with_control_handler(Arc::new(
1479                    control.clone(),
1480                )));
1481                router.install_registration_service(auth().0);
1482                drop(router);
1483            }
1484            let spawn = RegistrationSpawn::new(&handle, "channel-module", SpawnRole::Plain, None);
1485            let (parent, child) = std::os::unix::net::UnixStream::pair().unwrap();
1486            child.set_nonblocking(true).unwrap();
1487            let mut child = tokio::net::UnixStream::from_std(child).unwrap();
1488            handle.serve_registration(
1489                parent,
1490                spawn.clone(),
1491                1,
1492                Instant::now() + Duration::from_secs(1),
1493            );
1494            use tokio::io::AsyncReadExt;
1495            assert_eq!(child.read(&mut [0]).await.unwrap(), 0);
1496            assert_eq!(spawn.check(), Err("registration_channel_closed"));
1497            assert!(handle.spawn_nonce("channel-module").is_none());
1498        }
1499    }
1500
1501    #[test]
1502    fn registration_channel_service_installs_only_once() {
1503        let (handle, _, control) = setup();
1504        let router = Arc::new(crate::Router::with_control_handler(Arc::new(control)));
1505        router.install_registration_service(auth().0);
1506        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1507            router.install_registration_service(auth().0)
1508        }));
1509        assert_eq!(result.is_err(), cfg!(debug_assertions));
1510        assert!(handle
1511            .registration_service
1512            .lock()
1513            .unwrap_or_else(|p| p.into_inner())
1514            .is_some());
1515    }
1516
1517    #[cfg(target_os = "macos")]
1518    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1519    async fn registration_channel_macos_hello_waits_for_verified_transition_and_refusal_closes() {
1520        for refused in [false, true] {
1521            let (handle, _, control) = setup();
1522            let router = Arc::new(crate::Router::with_control_handler(Arc::new(control)));
1523            let (auth, info) = auth();
1524            router.install_registration_service(auth);
1525            let roster = ChildRoster::default();
1526            roster.set_privacy_trampoline(Ok(test_privacy_trampoline()));
1527            let scratch = cortexkit_test_support::ScratchDir::new("channel-launch");
1528            let spec = ModuleSpec {
1529                script: None,
1530                module_id: "channel-module".into(),
1531                program: "/bin/sleep".into(),
1532                args: vec!["60".into()],
1533                env: [
1534                    "HOME",
1535                    "XDG_DATA_HOME",
1536                    "XDG_RUNTIME_DIR",
1537                    "XDG_CONFIG_HOME",
1538                ]
1539                .into_iter()
1540                .map(|key| (key.into(), scratch.display().to_string()))
1541                .collect(),
1542                reserved: false,
1543                reserved_prefixes: Vec::new(),
1544                protocol: ModuleProtocol::Subc,
1545                overlap: Default::default(),
1546                carry_containment: false,
1547            };
1548            let mut spec = spec;
1549            spec.protocol = ModuleProtocol::None;
1550            let owner = super::super::suspended_spawn_tests::gated_owner(&scratch, &spec, true);
1551            let mut runtime =
1552                Supervisor::new_for_test(Arc::new(Registry::default()), RestartPolicy::default())
1553                    .with_config_runtime(owner)
1554                    .runtime_config();
1555            runtime.child_roster = roster;
1556            let mut child = spawn_child_in_slot_async(&spec, &runtime, SpawnRole::Plain, false)
1557                .await
1558                .unwrap();
1559            let spawn = RegistrationSpawn::new(&handle, "channel-module", SpawnRole::Plain, None);
1560            child.registration_spawn = Some(spawn.clone());
1561            let (parent, peer) = std::os::unix::net::UnixStream::pair().unwrap();
1562            peer.set_nonblocking(true).unwrap();
1563            let mut peer = tokio::net::UnixStream::from_std(peer).unwrap();
1564            handle.serve_registration(
1565                parent,
1566                spawn,
1567                child.pid,
1568                Instant::now() + Duration::from_secs(2),
1569            );
1570            subc_transport::authenticate_client(&mut peer, &info, Duration::from_secs(2))
1571                .await
1572                .unwrap();
1573            subc_transport::write_frame(&mut peer, &hello("channel-module"))
1574                .await
1575                .unwrap();
1576            let pid = child.pid;
1577            tokio::time::timeout(Duration::from_secs(2), async {
1578                while !subc_os::privacy_identity::SuspendedSignature::is_suspended(pid).unwrap() {
1579                    tokio::time::sleep(Duration::from_millis(1)).await;
1580                }
1581            })
1582            .await
1583            .unwrap();
1584            // The exec-acknowledgement reader returns EOF and the PID has not changed. Neither fact
1585            // authorizes HELLO before signature verification and resume.
1586            let reader = &child.privacy_exec.as_ref().unwrap().reader;
1587            let mut readiness = reader.readable().await.unwrap();
1588            assert_eq!(
1589                readiness
1590                    .try_io(|reader| {
1591                        use std::io::Read;
1592                        reader.get_ref().read(&mut [0])
1593                    })
1594                    .unwrap()
1595                    .unwrap(),
1596                0
1597            );
1598            assert_eq!(child.pid, pid);
1599            assert!(tokio::time::timeout(
1600                Duration::from_millis(50),
1601                subc_transport::read_frame(&mut peer)
1602            )
1603            .await
1604            .is_err());
1605            if refused {
1606                child.privacy_exec.as_mut().unwrap().expected = None;
1607            }
1608            child.confirm_privacy_exec().await;
1609            let reply = tokio::time::timeout(
1610                Duration::from_secs(2),
1611                subc_transport::read_frame(&mut peer),
1612            )
1613            .await
1614            .unwrap()
1615            .unwrap();
1616            if refused {
1617                assert!(reply.is_none());
1618            } else {
1619                assert_eq!(reply.unwrap().header.ty, FrameType::HelloAck);
1620            }
1621            let _ = child.start_admission_kill();
1622            child.wait().await.unwrap();
1623        }
1624    }
1625}
1626
1627pub(crate) const DEFAULT_REGISTER_TIMEOUT: Duration = Duration::from_secs(120);
1628pub(super) const REGISTRY_RELEASE_TIMEOUT: Duration = Duration::from_secs(1);
1629pub(super) const REGISTRY_RELEASE_POLL: Duration = Duration::from_millis(10);
1630
1631impl SupervisedChild {
1632    pub(super) fn retire_registration(&self) {
1633        // All exit observers enter here before cleanup can await. The retired
1634        // program-binding flag and the registration's Dead state make repeated
1635        // observations harmless, even when another task observes the group
1636        // leader retained unreaped to reserve its process-group id.
1637        if let Some(spawn) = &self.registration_spawn {
1638            spawn.retire();
1639        } else if let Some(binding) = &self._program_binding {
1640            binding.retire();
1641        }
1642        #[cfg(unix)]
1643        if let Some(channel) = &self.registration_channel {
1644            let _ = channel.shutdown(std::net::Shutdown::Both);
1645        }
1646        #[cfg(windows)]
1647        if let Some(channel) = &self.registration_channel {
1648            if let Ok(shutdown) = channel.shutdown_handle() {
1649                shutdown.shutdown();
1650            }
1651        }
1652    }
1653    pub(super) fn registered_since_spawn(&self) -> bool {
1654        self.registration_watch
1655            .as_ref()
1656            .is_some_and(|watch| *watch.changes.borrow() != watch.baseline)
1657    }
1658
1659    pub(super) fn awaiting_registration(&self) -> bool {
1660        // Admission failure retires the channel before its kill becomes
1661        // waitable. That closure must not replace the admission failure with
1662        // a registration failure and spend crash restart budget.
1663        let admission_failed = self.admission_kill_sent && self.spawn_failure.is_some();
1664        !admission_failed && !self.registered_since_spawn()
1665    }
1666}
1667
1668fn registration_release_events() -> &'static watch::Sender<u64> {
1669    static EVENTS: OnceLock<watch::Sender<u64>> = OnceLock::new();
1670    EVENTS.get_or_init(|| {
1671        let (sender, _receiver) = watch::channel(0);
1672        sender
1673    })
1674}
1675
1676pub(crate) fn notify_registration_release() {
1677    let events = registration_release_events();
1678    let next_generation = (*events.borrow()).wrapping_add(1);
1679    events.send_replace(next_generation);
1680}
1681
1682#[cfg(test)]
1683#[derive(Debug)]
1684pub(super) struct IdentitySamplePause {
1685    pub(super) reached: std::sync::mpsc::Sender<()>,
1686    pub(super) release: std::sync::mpsc::Receiver<()>,
1687}
1688
1689#[derive(Debug, Clone, PartialEq, Eq)]
1690pub(crate) enum ReservedHelloRejection {
1691    Exact {
1692        module_id: String,
1693    },
1694    Prefix {
1695        prefix: String,
1696        owner_module_id: String,
1697    },
1698}
1699
1700/// Identity facts established by the reserved-module policy for one HELLO.
1701#[derive(Debug, Default)]
1702pub(crate) struct ReservedHelloVerification {
1703    pub(crate) nonce_verified: bool,
1704    pub(crate) prefix_owner: Option<String>,
1705}
1706
1707fn matching_reserved_prefix<'a>(
1708    owners: &'a HashMap<String, String>,
1709    module_id: &str,
1710) -> Option<(&'a String, &'a String)> {
1711    owners
1712        .iter()
1713        .filter(|(prefix, _)| module_id.starts_with(prefix.as_str()))
1714        .max_by_key(|(prefix, _)| prefix.len())
1715}
1716
1717impl SupervisorHandle {
1718    /// Record the launch nonce from a supervised spawn, replacing any prior nonce so
1719    /// a respawn invalidates stale consumer identities.
1720    pub fn set_spawn_nonce(&self, module_id: &str, nonce: String) {
1721        self.spawn_nonces
1722            .lock()
1723            .unwrap_or_else(|poisoned| poisoned.into_inner())
1724            .insert(module_id.to_string(), nonce);
1725        self.refresh_program_binding_nonces(module_id);
1726    }
1727
1728    /// Record the launch nonce expected from the next HELLO for a reserved module,
1729    /// replacing any prior nonce (a respawn invalidates the previous one).
1730    pub fn set_reserved_nonce(&self, module_id: &str, nonce: String) {
1731        {
1732            let mut reserved = self
1733                .reserved_nonces
1734                .lock()
1735                .unwrap_or_else(|p| p.into_inner());
1736            self.implicit_protocol_none
1737                .lock()
1738                .unwrap_or_else(|p| p.into_inner())
1739                .remove(module_id);
1740            reserved.insert(module_id.to_string(), Some(nonce));
1741        }
1742        self.refresh_program_binding_nonces(module_id);
1743    }
1744
1745    /// Record namespace prefixes owned by a supervised module.
1746    pub fn set_reserved_prefixes(&self, owner_module_id: &str, prefixes: &[String]) {
1747        let mut owners = self
1748            .reserved_prefix_owners
1749            .lock()
1750            .unwrap_or_else(|poisoned| poisoned.into_inner());
1751        owners.retain(|_, owner| owner != owner_module_id);
1752        for prefix in prefixes {
1753            owners.insert(prefix.clone(), owner_module_id.to_string());
1754        }
1755    }
1756
1757    pub(crate) fn remove_reserved_prefix_children(&self, module_ids: &mut BTreeSet<String>) {
1758        let owners = self
1759            .reserved_prefix_owners
1760            .lock()
1761            .unwrap_or_else(|poisoned| poisoned.into_inner());
1762        module_ids.retain(|id| {
1763            matching_reserved_prefix(&owners, id).is_none_or(|(_, owner)| owner == id)
1764        });
1765    }
1766
1767    /// The launch nonce most recently minted for a module's spawn, if any.
1768    pub(crate) fn spawn_nonce(&self, module_id: &str) -> Option<String> {
1769        if self.module_is_gated(module_id) {
1770            return None;
1771        }
1772        self.spawn_nonces
1773            .lock()
1774            .unwrap_or_else(|poisoned| poisoned.into_inner())
1775            .get(module_id)
1776            .cloned()
1777    }
1778
1779    #[cfg(all(test, unix))]
1780    pub(crate) fn legacy_nonce_present_for_test(&self, module: &str) -> bool {
1781        self.spawn_nonces.lock().unwrap().contains_key(module)
1782    }
1783
1784    pub(crate) fn apply_identity_configuration(&self, spec: &ModuleSpec) {
1785        // Prefix ownership follows staged configuration, not the running
1786        // child's launch settings. A respawn may still carry an older spec.
1787        self.set_reserved_prefixes(&spec.module_id, &spec.reserved_prefixes);
1788        let protocol = self
1789            .get(&spec.module_id)
1790            .and_then(|module| {
1791                let snapshot = module.inner.snapshot.lock().ok()?;
1792                snapshot
1793                    .process_alive
1794                    .then_some(snapshot.spawned_protocol.unwrap_or(spec.protocol))
1795            })
1796            .unwrap_or(spec.protocol);
1797        self.apply_identity_policy(spec, protocol);
1798    }
1799
1800    #[cfg(all(test, unix))]
1801    pub(crate) fn pause_plain_identity_policy_for_test(
1802        &self,
1803        module: &str,
1804    ) -> (std::sync::mpsc::Receiver<()>, std::sync::mpsc::Sender<()>) {
1805        let (reached, waiting) = std::sync::mpsc::channel();
1806        let (release, paused) = std::sync::mpsc::channel();
1807        *self.plain_identity_policy_pause.lock().unwrap() = Some((
1808            module.to_owned(),
1809            IdentitySamplePause {
1810                reached,
1811                release: paused,
1812            },
1813        ));
1814        (waiting, release)
1815    }
1816
1817    pub(super) fn apply_identity_policy(&self, spec: &ModuleSpec, protocol: ModuleProtocol) {
1818        let channel_only = self.module_is_gated(&spec.module_id);
1819        let mut current_nonces = self
1820            .spawn_nonces
1821            .lock()
1822            .unwrap_or_else(|poisoned| poisoned.into_inner());
1823        if protocol == ModuleProtocol::None || channel_only {
1824            current_nonces.remove(&spec.module_id);
1825        }
1826        let spawn_nonce = current_nonces.get(&spec.module_id).cloned();
1827        #[cfg(test)]
1828        if let Some(pause) = self.identity_sample_pause.lock().unwrap().take() {
1829            pause.reached.send(()).unwrap();
1830            pause.release.recv().unwrap();
1831        }
1832        let mut reserved_nonces = self
1833            .reserved_nonces
1834            .lock()
1835            .unwrap_or_else(|poisoned| poisoned.into_inner());
1836        let mut implicit = self
1837            .implicit_protocol_none
1838            .lock()
1839            .unwrap_or_else(|p| p.into_inner());
1840        if spec.reserved {
1841            implicit.remove(&spec.module_id);
1842        } else if protocol == ModuleProtocol::None {
1843            if !reserved_nonces.contains_key(&spec.module_id) {
1844                implicit.insert(spec.module_id.clone());
1845            }
1846        } else if implicit.remove(&spec.module_id) {
1847            reserved_nonces.remove(&spec.module_id);
1848        }
1849        if spec.reserved || protocol == ModuleProtocol::None {
1850            // `None` (no spawn nonce minted) is INSERTED, not skipped: a
1851            // reserved name whose module has never spawned has no legitimate
1852            // holder, and the entry's absence is what used to leave the name
1853            // open to the first claimant.
1854            reserved_nonces.insert(spec.module_id.clone(), spawn_nonce);
1855        }
1856        drop(implicit);
1857        drop(reserved_nonces);
1858        drop(current_nonces);
1859        self.refresh_program_binding_nonces(&spec.module_id);
1860        // A later unreserved declaration must not silently unreserve an id that
1861        // was retained after its reserved configuration was removed. The explicit
1862        // release ceremony is the only operation that retires that gate.
1863        self.removal_tombstones
1864            .lock()
1865            .unwrap_or_else(|poisoned| poisoned.into_inner())
1866            .remove(&spec.module_id);
1867    }
1868
1869    /// Whether a HELLO claiming `module_id` is authorized. An exact reserved id is
1870    /// authorized only by its expected nonce; otherwise a matching reserved prefix
1871    /// is authorized by the owner module's current spawn nonce. Non-reserved ids
1872    /// with no matching prefix are always authorized.
1873    pub fn reserved_hello_authorized(&self, module_id: &str, presented: Option<&str>) -> bool {
1874        self.reserved_hello_verification(module_id, presented)
1875            .is_ok()
1876    }
1877
1878    /// Whether HELLO passed a nonce check that was actually required by reserved
1879    /// module policy, or the refusal explaining why a required check failed.
1880    pub(crate) fn reserved_hello_verification(
1881        &self,
1882        module_id: &str,
1883        presented: Option<&str>,
1884    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
1885        if self.module_is_gated(module_id) {
1886            return Err(ReservedHelloRejection::Exact {
1887                module_id: module_id.into(),
1888            });
1889        }
1890        self.hello_verification(module_id, presented, false)
1891    }
1892
1893    pub(crate) fn channel_hello_verification(
1894        &self,
1895        module_id: &str,
1896    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
1897        if self
1898            .get(module_id)
1899            .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
1900        {
1901            return Err(ReservedHelloRejection::Exact {
1902                module_id: module_id.into(),
1903            });
1904        }
1905        let mut verification = self.hello_verification(module_id, None, true)?;
1906        verification.nonce_verified = true;
1907        Ok(verification)
1908    }
1909
1910    pub(crate) fn prefix_claim_authorized(&self, owner: &str, module_id: &str) -> bool {
1911        self.prefix_claim_publication(owner, module_id).is_some()
1912    }
1913
1914    #[cfg(all(test, unix))]
1915    pub(crate) fn prefix_publication_locked_for_test(&self) -> bool {
1916        matches!(
1917            self.reserved_prefix_owners.try_lock(),
1918            Err(std::sync::TryLockError::WouldBlock)
1919        )
1920    }
1921
1922    // Keep this guard through registry/forwarding publication. Rescans replace
1923    // prefix owners without stopping their launches, so the spawn guard alone
1924    // cannot fence a reservation transfer.
1925    pub(crate) fn prefix_claim_publication(
1926        &self,
1927        owner: &str,
1928        module_id: &str,
1929    ) -> Option<std::sync::MutexGuard<'_, HashMap<String, String>>> {
1930        if subc_protocol::manifest::validate_module_id(module_id).is_err()
1931            || self.module_is_gated(module_id)
1932            || self
1933                .reserved_nonces
1934                .lock()
1935                .unwrap_or_else(|p| p.into_inner())
1936                .contains_key(module_id)
1937        {
1938            return None;
1939        }
1940        let owners = self
1941            .reserved_prefix_owners
1942            .lock()
1943            .unwrap_or_else(|p| p.into_inner());
1944        let authorized = matching_reserved_prefix(&owners, module_id)
1945            .is_some_and(|(prefix, holder)| holder == owner && module_id.len() > prefix.len());
1946        authorized.then_some(owners)
1947    }
1948
1949    fn hello_verification(
1950        &self,
1951        module_id: &str,
1952        presented: Option<&str>,
1953        channel: bool,
1954    ) -> Result<ReservedHelloVerification, ReservedHelloRejection> {
1955        let nonces = self
1956            .reserved_nonces
1957            .lock()
1958            .unwrap_or_else(|poisoned| poisoned.into_inner());
1959        if let Some(expected) = nonces.get(module_id) {
1960            // `None` = reserved with no legitimate holder: refuse every
1961            // presentation, because no process can hold a nonce that was never
1962            // minted. Only a real minted nonce admits, in constant time.
1963            let authorized = channel
1964                || match expected {
1965                    Some(expected) => presented.is_some_and(|p| {
1966                        !p.is_empty() && constant_time_eq(expected.as_bytes(), p.as_bytes())
1967                    }),
1968                    None => false,
1969                };
1970            if authorized {
1971                return Ok(ReservedHelloVerification {
1972                    nonce_verified: true,
1973                    prefix_owner: None,
1974                });
1975            }
1976            return Err(ReservedHelloRejection::Exact {
1977                module_id: module_id.to_string(),
1978            });
1979        }
1980        drop(nonces);
1981
1982        let matched_prefix = {
1983            let owners = self
1984                .reserved_prefix_owners
1985                .lock()
1986                .unwrap_or_else(|poisoned| poisoned.into_inner());
1987            matching_reserved_prefix(&owners, module_id)
1988                .map(|(prefix, owner)| (prefix.clone(), owner.clone()))
1989        };
1990        let Some((prefix, owner_module_id)) = matched_prefix else {
1991            return Ok(ReservedHelloVerification::default());
1992        };
1993
1994        if module_id.len() == prefix.len()
1995            || (!channel
1996                && (self.module_is_gated(&owner_module_id) || self.protocol_none(&owner_module_id)))
1997        {
1998            return Err(ReservedHelloRejection::Prefix {
1999                prefix,
2000                owner_module_id,
2001            });
2002        }
2003
2004        let authorized = if channel {
2005            owner_module_id == module_id
2006        } else {
2007            presented.is_some_and(|presented| {
2008                self.spawn_nonces
2009                .lock()
2010                .unwrap_or_else(|poisoned| poisoned.into_inner())
2011                .get(&owner_module_id)
2012                .is_some_and(|expected| !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes()))
2013                // While the owner is being swapped, children started by
2014                // either of its two processes hold that process's nonce.
2015                || self.swap_nonce_matches(&owner_module_id, presented)
2016            })
2017        };
2018        if authorized {
2019            Ok(ReservedHelloVerification {
2020                nonce_verified: true,
2021                prefix_owner: (owner_module_id != module_id).then_some(owner_module_id),
2022            })
2023        } else {
2024            Err(ReservedHelloRejection::Prefix {
2025                prefix,
2026                owner_module_id,
2027            })
2028        }
2029    }
2030
2031    /// Whether a consumer connection proved it came from a daemon-spawned module.
2032    ///
2033    /// Absence of an expected spawn nonce is a hard failure: consumer_identity is
2034    /// accepted only for module ids the supervisor has spawned.
2035    pub fn spawned_consumer_authorized(&self, module_id: &str, presented: &str) -> bool {
2036        if self.module_is_gated(module_id) || self.protocol_none(module_id) {
2037            return false;
2038        }
2039        let nonces = self
2040            .spawn_nonces
2041            .lock()
2042            .unwrap_or_else(|poisoned| poisoned.into_inner());
2043        let current = nonces.get(module_id).is_some_and(|expected| {
2044            !presented.is_empty() && constant_time_eq(expected.as_bytes(), presented.as_bytes())
2045        });
2046        drop(nonces);
2047        // Before cutover both launches may attest. Promotion removes the
2048        // incumbent's token even if its process still needs time to drain.
2049        current || self.swap_nonce_matches(module_id, presented)
2050    }
2051}
2052
2053impl SupervisorHandle {
2054    pub(super) fn protocol_none(&self, module: &str) -> bool {
2055        self.get(module)
2056            .is_some_and(|module| module.declared_protocol().ok() == Some(ModuleProtocol::None))
2057    }
2058}
2059
2060impl SupervisorHandle {
2061    /// Test/support lookup for the current launch nonce of a supervised spawn.
2062    pub fn spawn_launch_nonce_for(&self, module_id: &str) -> Option<String> {
2063        self.spawn_nonce(module_id)
2064    }
2065
2066    /// Test/support lookup for the HELLO-gating nonce of a reserved module.
2067    pub fn reserved_launch_nonce_for(&self, module_id: &str) -> Option<String> {
2068        if self.module_is_gated(module_id) {
2069            return None;
2070        }
2071        self.reserved_nonces
2072            .lock()
2073            .unwrap_or_else(|poisoned| poisoned.into_inner())
2074            .get(module_id)
2075            .cloned()
2076            .flatten()
2077    }
2078}
2079
2080/// Constant-time byte comparison so a reserved-nonce mismatch leaks no timing
2081/// signal about how many leading bytes matched.
2082pub(super) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
2083    if a.len() != b.len() {
2084        return false;
2085    }
2086    let mut diff = 0u8;
2087    for (x, y) in a.iter().zip(b.iter()) {
2088        diff |= x ^ y;
2089    }
2090    diff == 0
2091}
2092
2093pub(super) struct RegistrationWatch {
2094    pub(super) changes: watch::Receiver<u64>,
2095    pub(super) baseline: u64,
2096}
2097
2098// Capture before spawning: a fast child's accepted HELLO can disappear from the
2099// active registry before the monitor first runs. A pre-existing registration
2100// must not satisfy a new process's deadline either.
2101pub(super) fn watch_registration(
2102    registry: &Registry,
2103    spec: &ModuleSpec,
2104) -> Option<RegistrationWatch> {
2105    if spec.protocol != ModuleProtocol::Subc {
2106        return None;
2107    }
2108    let changes = registry.subscribe_module_changes(&spec.module_id).ok()?;
2109    let baseline = *changes.borrow();
2110    Some(RegistrationWatch { changes, baseline })
2111}
2112
2113pub(super) fn arm_registration_deadline(
2114    child: &mut SupervisedChild,
2115    budget: Duration,
2116    registration_watch: Option<RegistrationWatch>,
2117) {
2118    child.registration_watch = registration_watch;
2119    child.registration_deadline = (child.protocol == ModuleProtocol::Subc
2120        && child.awaiting_registration())
2121    .then_some(child.spawned_at + budget);
2122}
2123
2124pub(super) enum RegistrationWaitOutcome {
2125    Registered,
2126    Exited(ExitReport),
2127    TimedOut,
2128}
2129
2130pub(super) struct ReloadRegistrationFailure {
2131    pub(super) cleanup_detail: Option<String>,
2132    pub(super) exit_report: ExitReport,
2133    pub(super) reason: String,
2134}
2135
2136/// Wait for the freshly spawned child to take the ACTIVE slot for `module_id`,
2137/// the only slot a plain (non-swap) spawn can register into.
2138pub(super) async fn wait_for_registration_after_reload(
2139    registry: &Registry,
2140    module_id: &str,
2141    snapshot: &SharedSnapshot,
2142    child: &mut SupervisedChild,
2143    wait: Duration,
2144) -> Result<RegistrationWaitOutcome, SuperviseError> {
2145    wait_for_slot_registration(
2146        registry,
2147        crate::registry::RegistrationSlot::Active(module_id),
2148        module_id,
2149        snapshot,
2150        child,
2151        wait,
2152    )
2153    .await
2154}
2155
2156/// Wait for `child` to register into `slot`, or to exit, or for `wait` to pass.
2157///
2158/// Keyed on the slot rather than the bare module id because during a swap the
2159/// id's active slot is already held by the incumbent: an id-keyed wait would
2160/// report the incumbent's registration as the candidate's and a candidate that
2161/// never registers would look registered. A swap candidate waits on
2162/// `crate::registry::RegistrationSlot::Candidate`.
2163async fn wait_for_slot_registration(
2164    registry: &Registry,
2165    slot: crate::registry::RegistrationSlot<'_>,
2166    module_id: &str,
2167    snapshot: &SharedSnapshot,
2168    child: &mut SupervisedChild,
2169    wait: Duration,
2170) -> Result<RegistrationWaitOutcome, SuperviseError> {
2171    let deadline = Instant::now() + wait;
2172    loop {
2173        if registry
2174            .registration(slot)
2175            .map_err(SuperviseError::Registry)?
2176            .is_some()
2177        {
2178            return Ok(RegistrationWaitOutcome::Registered);
2179        }
2180
2181        let now = Instant::now();
2182        if now >= deadline {
2183            return Ok(RegistrationWaitOutcome::TimedOut);
2184        }
2185        let remaining = deadline.saturating_duration_since(now);
2186        let poll = remaining.min(REGISTRY_RELEASE_POLL);
2187
2188        tokio::select! {
2189            wait_result = child.wait() => {
2190                let status = wait_result.map_err(|source| SuperviseError::Wait {
2191                    module_id: module_id.to_string(),
2192                    source,
2193                })?;
2194                return Ok(RegistrationWaitOutcome::Exited(classify_reaped_child_exit(
2195                    snapshot,
2196                    child,
2197                    &status,
2198                )));
2199            }
2200            _ = sleep(poll) => {}
2201        }
2202    }
2203}
2204
2205pub(super) fn registration_failure_exit_report(mut exit_report: ExitReport) -> ExitReport {
2206    // A process stopped for missing its first HELLO did not provide service,
2207    // even if its TERM handler exits zero. Reload also uses this classification
2208    // when a replacement exits before registering.
2209    if exit_report.kind != ExitKind::DeliberateSeverance {
2210        exit_report.kind = ExitKind::Crash;
2211    }
2212    exit_report
2213}
2214
2215pub(super) async fn handle_reload_child_registration_failure(
2216    spec: &ModuleSpec,
2217    runtime: &SupervisorRuntimeConfig,
2218    registry: &Registry,
2219    process_liveness: &SupervisorProcessLiveness,
2220    snapshot: &SharedSnapshot,
2221    _child: &mut Option<SupervisedChild>,
2222    failure: ReloadRegistrationFailure,
2223) -> Result<(), SuperviseError> {
2224    let ReloadRegistrationFailure {
2225        exit_report,
2226        reason,
2227        cleanup_detail,
2228    } = failure;
2229    match on_child_exit_with_detail(
2230        spec,
2231        runtime.restart_policy,
2232        registry,
2233        snapshot,
2234        &runtime.terminal_ring,
2235        &runtime.spawn_events,
2236        &runtime.child_roster,
2237        exit_report,
2238        runtime.recovery_is_daemon,
2239        cleanup_detail,
2240    )
2241    .await
2242    {
2243        NextAction::Stop {
2244            registration_released,
2245        } => {
2246            if registration_released {
2247                process_liveness.untrack_if_current(&spec.module_id, snapshot);
2248            }
2249        }
2250        NextAction::Restart { schedule } => {
2251            let delay = schedule.map_or(runtime.restart_policy.delay_for_restart(0), |schedule| {
2252                schedule.delay
2253            });
2254            if let Some(schedule) = schedule {
2255                log_crash_respawn(&spec.module_id, schedule);
2256            }
2257            schedule_respawn(
2258                runtime,
2259                snapshot,
2260                &spec.module_id,
2261                delay,
2262                RespawnKind::after_exit(schedule),
2263                true,
2264            )?;
2265        }
2266    }
2267    Err(SuperviseError::ReloadFailed {
2268        module_id: spec.module_id.clone(),
2269        reason,
2270    })
2271}
2272
2273pub(super) async fn handle_reload_spawn_failure(
2274    spec: &ModuleSpec,
2275    runtime: &SupervisorRuntimeConfig,
2276    process_liveness: &SupervisorProcessLiveness,
2277    snapshot: &SharedSnapshot,
2278    _child: &mut Option<SupervisedChild>,
2279    reason: String,
2280) -> Result<(), SuperviseError> {
2281    let now = Instant::now();
2282    let mut schedule = None;
2283    update_snapshot(snapshot, Some(&spec.module_id), |state| {
2284        clear_current_process_facts(state);
2285        if state.enabled {
2286            schedule = state.next_crash_restart(&runtime.restart_policy, now);
2287            state.state = if schedule.is_some() {
2288                ModuleState::Restarting
2289            } else {
2290                if runtime
2291                    .failure_context(runtime.recovery_is_daemon)
2292                    .may_retry()
2293                {
2294                    state.failed_retry.schedule(&spec.module_id);
2295                }
2296                ModuleState::Failed
2297            };
2298        } else {
2299            state.state = ModuleState::Disabled;
2300        }
2301    })?;
2302    if let Some(schedule) = schedule {
2303        schedule_respawn(
2304            runtime,
2305            snapshot,
2306            &spec.module_id,
2307            schedule.delay,
2308            RespawnKind::CrashRestart,
2309            true,
2310        )?;
2311    } else {
2312        process_liveness.untrack_if_current(&spec.module_id, snapshot);
2313    }
2314    Err(SuperviseError::ReloadFailed {
2315        module_id: spec.module_id.clone(),
2316        reason,
2317    })
2318}
2319
2320/// Release a reaped child's registration before allowing another spawn.
2321///
2322/// EOF is not a process-lifetime signal: an inherited socket can stay open
2323/// indefinitely, and serial frame dispatch can be waiting on egress instead of
2324/// reading EOF. After the normal release grace, request connection close (which
2325/// cancels both reads and dispatch), then allow one more release grace for the
2326/// connection guard's forwarding cleanup. Never evict a different connection.
2327pub(super) async fn release_dead_registration(
2328    registry: &Registry,
2329    forwarding: Option<&ForwardingTable>,
2330    snapshot: &SharedSnapshot,
2331    module_id: &str,
2332    failure: &FailureContext,
2333) -> Result<(), SuperviseError> {
2334    let result = async {
2335        let registration = registry
2336            .get_module(module_id)
2337            .map_err(SuperviseError::Registry)?;
2338        match wait_for_registration_release(registry, module_id, REGISTRY_RELEASE_TIMEOUT).await {
2339            Ok(()) => return Ok(()),
2340            Err(SuperviseError::RegistrationStillActive { .. }) => {}
2341            Err(err) => return Err(err),
2342        }
2343        let pid = lock_snapshot(snapshot)?.reaped_pid;
2344        if let (Some(registration), Some(forwarding), Some(pid)) = (registration, forwarding, pid) {
2345            warn!(
2346                module_id,
2347                pid,
2348                connection_id = registration.connection_id.get(),
2349                "reaped module registration outlived release grace; closing dead connection"
2350            );
2351            forwarding.request_connection_close(
2352                registration.connection_id,
2353                CloseReason::new(
2354                    "supervised_process_reaped",
2355                    format!("module '{module_id}' pid {pid} exited"),
2356                ),
2357            );
2358            wait_for_slot_registration_release(
2359                registry,
2360                crate::registry::RegistrationSlot::Connection(registration.connection_id),
2361                REGISTRY_RELEASE_TIMEOUT,
2362            )
2363            .await?;
2364        }
2365        wait_for_registration_release(registry, module_id, Duration::ZERO).await
2366    }
2367    .await;
2368    if let Err(err) = &result {
2369        fail_snapshot(snapshot, Some(module_id), None, failure);
2370        error!(module_id, error = %err, "registration release failed after child exit; module is failed and start can retry");
2371    }
2372    result
2373}
2374
2375/// Wait for the ACTIVE registration of `module_id` to go away, which is what a
2376/// plain stop or restart waits for before it spawns a replacement.
2377pub(super) async fn wait_for_registration_release(
2378    registry: &Registry,
2379    module_id: &str,
2380    wait: Duration,
2381) -> Result<(), SuperviseError> {
2382    wait_for_slot_registration_release(
2383        registry,
2384        crate::registry::RegistrationSlot::Active(module_id),
2385        wait,
2386    )
2387    .await
2388}
2389
2390/// Wait for the registration in `slot` to go away.
2391///
2392/// Keyed on the slot rather than the bare module id because a successful swap
2393/// never empties the id's active slot (the promoted candidate is in it), so an
2394/// id-keyed wait for the incumbent's release would always time out. Draining a
2395/// swap's incumbent waits on `crate::registry::RegistrationSlot::Connection` with the
2396/// incumbent's connection instead.
2397pub(super) async fn wait_for_slot_registration_release(
2398    registry: &Registry,
2399    slot: crate::registry::RegistrationSlot<'_>,
2400    wait: Duration,
2401) -> Result<(), SuperviseError> {
2402    let deadline = Instant::now() + wait;
2403    let mut release_events = registration_release_events().subscribe();
2404    let still_active = |registration: &crate::registry::ModuleRegistration| {
2405        SuperviseError::RegistrationStillActive {
2406            module_id: registration.manifest.module_id.clone(),
2407            waited: wait,
2408        }
2409    };
2410    loop {
2411        let _observed_generation = *release_events.borrow_and_update();
2412        let Some(registration) = registry
2413            .registration(slot)
2414            .map_err(SuperviseError::Registry)?
2415        else {
2416            return Ok(());
2417        };
2418
2419        let now = Instant::now();
2420        if now >= deadline {
2421            return Err(still_active(&registration));
2422        }
2423
2424        let remaining = deadline.saturating_duration_since(now);
2425        match timeout(remaining, release_events.changed()).await {
2426            Ok(Ok(())) | Ok(Err(_)) => {}
2427            Err(_) => return Err(still_active(&registration)),
2428        }
2429    }
2430}
2431
2432pub(super) fn registration_child_is_running(child: &mut SupervisedChild) -> bool {
2433    child.try_wait().is_ok_and(|status| status.is_none())
2434}