Skip to main content

subc_daemon/
control.rs

1#[path = "control/list_diagnostics.rs"]
2pub(crate) mod list_diagnostics;
3mod route_open_refusal_log;
4
5use std::{
6    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
7    fmt,
8    net::SocketAddr,
9    path::{Path, PathBuf},
10    sync::{Arc, Mutex, RwLock},
11    time::{Duration, Instant as StdInstant},
12};
13
14use crate::scopes::admission::denied_capability;
15use serde::{Deserialize, Serialize};
16use subc_control::{
17    ops, CapabilityRequirementStatus, CatalogEntry, ClientControlPush, ClientControlRequest,
18    ClientControlResponse, ConsumerIdentity, DaemonBuildProvenance, DaemonObservedProcess,
19    ModuleDeclaredProvenance, ModuleProtocol, NotReadyReason, PendingReloadVerdict, PollKind,
20    ReloadPathAgreement, ReloadPathUnavailableReason, RouteCloseReason, SpawnCursor,
21    StderrCaptureState, StderrTail, StderrTailEntry, SupervisorDaemonProvenance, SupervisorEntry,
22    SupervisorHealthEntry, SupervisorModuleProvenance, SupervisorObservedProcess,
23    SupervisorRescanResult, SupervisorRoute, SupervisorRouteConsumer, SupervisorRouteModule,
24};
25use subc_protocol::{
26    call_mode::{derive_call_mode, CALL_MODES_CAPABILITY},
27    error_codes,
28    manifest::{
29        validate_hello_capability_grammar, validate_hello_confirm_operations,
30        validate_hello_display_name, validate_hello_event_declarations,
31        validate_hello_flow_operations, validate_hello_operation_deferral,
32        validate_hello_rich_ui_descriptor, validate_hello_role_declarations,
33        validate_hello_self_signal_declarations, validate_role_declarations_value,
34        CapabilityDeclarations, CapabilityNeed, Concurrency, ManifestProvenance, ModuleManifest,
35        ProviderRole,
36    },
37    peer::{
38        ObservedPeer, RouteBindPeer, OBSERVED_PEER_CAPABILITY, OPERATOR_APP_CAPABILITY,
39        PEER_BUILD_CAPABILITY,
40    },
41    provider_declarations::ProviderDeclarations,
42    scope::{
43        ScopeEnd, ScopeRecord, ScopeRecordOutcome, ScopeRecordResult, ScopeSelector,
44        CAP_ROUTE_ROLE_VERSIONS_V1, CAP_SCOPES_V1, SCOPE_APPLY_OP, SCOPE_DESCRIBE_OP,
45        SCOPE_SYNC_OP,
46    },
47    session::{
48        validate_role_versions, HealthReport, ModuleControlPush, ModuleControlRequest,
49        ModuleControlRequestFromModule, ModuleControlResponse, ModuleControlResponseToModule,
50        OperatorConfirmRequest, MODULE_CONTROL_OP_HEALTH_CHECK, MODULE_TO_SUBC_OP_CATALOG_UPDATE,
51        MODULE_TO_SUBC_OP_CATALOG_UPDATE_ROLE_DECLARATIONS, ROLE_VERSIONS_FIELD,
52    },
53    BindIdentity, ErrorBody, Flags, FrameType, ModuleHelloAckBody, ModuleHelloBody, Principal,
54    Priority, RouteTarget, PROTOCOL_VERSION,
55};
56use tokio::time::{timeout_at, Instant};
57use tracing::{debug, info, instrument::WithSubscriber, warn};
58
59use crate::{
60    caller_identity::CallerIdentity,
61    capability_requirements::{
62        log_duplicate_claim_events, log_manifest_change, log_requirement_events,
63        CapabilityRequirementEvaluator, CapabilityVerdict, DuplicateClaimSource, RegisteredModule,
64        RequirementStatus, RuntimeModule,
65    },
66    child_roster::DaemonShutdownFlag,
67    daemon_config::{PrivilegedOperatorPrompt, RestartRequiredSection},
68    forwarding::{
69        CloseReason, EndpointRoute, ForwardingError, ForwardingTable, GoodbyeTarget,
70        ModuleControlRpcCompletion, ModuleControlRpcOutcome, ModuleEndpointId,
71        PendingModuleControlRpc, RouteBindRelayOutcome, RoutePollSnapshot, RouteRelease,
72    },
73    observability::{
74        ROUTE_OPEN_REFUSED_DECLARED_NOT_READY, ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED,
75    },
76    privileged_prompt::{prompt_text, PrivilegedOperation},
77    provenance::{
78        process_start_time, spawned_file_identity, ExecutableIdentityProbe, SpawnedFileIdentity,
79    },
80    registry::{ChannelState, ConnectionId, RegistrationEndReason, Registry, RegistryError},
81    router::{daemon_error_flags, RouteCtx, RouterError},
82    scopes::{HelloLaunchNonces, ScopeRecords, ScopeTable},
83    server::MAX_PENDING_ROUTE_BINDS_PER_TARGET,
84    stderr_tail::{CaptureState, TailEntry},
85    supervise::{
86        validate_spec, ModuleProcessLiveness, ReservedHelloRejection, ReservedHelloVerification,
87        SpawnSubscribeRefusal, SupervisorHandle, SwapHelloAdmission,
88    },
89    ConnectedClients, DaemonCounters, Frame, ProjectRootId, Supervisor,
90};
91
92/// Lowest envelope version this subc build will negotiate.
93///
94/// Module HELLO negotiation is exact: peers must use the daemon's locked
95/// protocol version. Older and newer peers receive `version_unsupported` and
96/// are not registered.
97pub const MIN_SUPPORTED_VERSION: u8 = PROTOCOL_VERSION;
98
99mod route_open;
100use route_open::is_routable_role;
101use route_open::principal_label;
102#[cfg(test)]
103use route_open::RouteBindAdmission;
104pub(crate) use route_open::RouteBindBreakers;
105pub(crate) use route_open::RouteBindConcurrency;
106use route_open::RouteOpenCaller;
107use route_open::RouteOpenRequest;
108use route_open::RouteOpenTimings;
109pub use route_open::DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN;
110pub use route_open::DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD;
111pub use route_open::DEFAULT_ROUTE_BIND_RELAY_TIMEOUT;
112
113mod server_describe;
114use server_describe::subc_ops;
115use server_describe::CAP_ADMISSION_FACTS_RELAY;
116use server_describe::CAP_CHANNEL_LIFECYCLE;
117use server_describe::CAP_MANIFEST_REGISTRATION;
118use server_describe::CAP_PING_PONG;
119use server_describe::CAP_SESSION_ATTACH;
120
121mod supervisor_operations;
122use supervisor_operations::launch_spec_agreement;
123#[cfg(test)]
124use supervisor_operations::reload_verdict;
125use supervisor_operations::DaemonProvenanceFacts;
126use supervisor_operations::ModuleControlRpcGuard;
127use supervisor_operations::DEFAULT_HEALTH_PROBE_TIMEOUT;
128
129mod activity;
130#[cfg(test)]
131use activity::ActivityRequestPause;
132
133mod scopes;
134#[cfg(test)]
135use scopes::ScopeOutcomeCounts;
136
137mod module_operations;
138use module_operations::is_known_module_request_op;
139use module_operations::manifest_concurrency;
140#[cfg(test)]
141use module_operations::manifest_concurrency_was_defaulted;
142#[cfg(test)]
143use module_operations::module_baseline_control_ops;
144use module_operations::module_control_request_op;
145use module_operations::module_registration_grants_op;
146use module_operations::parse_module_control_request_from_module;
147#[cfg(all(test, unix, feature = "test-support"))]
148use module_operations::MODULE_TO_SUBC_UNADVERTISED_OPS;
149mod advertised_ops;
150use advertised_ops::*;
151#[cfg(target_os = "macos")]
152#[path = "operator_apps/trust_ops.rs"]
153mod app_trust_ops;
154mod caller_attestation;
155mod channel_operations;
156#[cfg(all(test, unix, feature = "test-support"))]
157#[path = "control/channel_operations_tests.rs"]
158mod channel_operations_tests;
159pub(crate) mod claims;
160#[cfg(test)]
161#[path = "control/config_advertisement_tests.rs"]
162mod config_advertisement_tests;
163mod config_gate;
164#[path = "operator_apps/connection.rs"]
165mod peer_identity;
166use caller_attestation::scope_acts_for_another;
167mod activity_reservations;
168#[cfg(all(test, unix, feature = "test-support"))]
169#[path = "control/caller_attestation_tests.rs"]
170mod caller_attestation_tests;
171mod capability_census;
172use capability_census::append_capability_problem_detail;
173use capability_census::capability_census_trigger;
174mod route_bind_settlement;
175mod scope_expiry;
176mod scope_watch;
177mod usage;
178
179mod agent_commands;
180pub(crate) mod catalog;
181mod policy_root;
182mod rescan_checked;
183pub(crate) mod upgrade_in_place;
184use rescan_checked::RescanMode;
185use rescan_checked::SupervisorRescanContext;
186
187const SLOW_CONTROL_DISPATCH_THRESHOLD: Duration = Duration::from_secs(1);
188
189/// A test hold: signal arrival, then wait for release on the holding thread.
190#[cfg(test)]
191type TestPause = (
192    tokio::sync::oneshot::Sender<()>,
193    std::sync::mpsc::Receiver<()>,
194);
195
196/// A test hook run once at a fixed point in a handler.
197#[cfg(test)]
198type TestHook = Box<dyn FnOnce() + Send>;
199
200/// A test hold for async code: signal arrival, then await release.
201#[cfg(test)]
202type AsyncTestPause = (
203    tokio::sync::oneshot::Sender<()>,
204    tokio::sync::oneshot::Receiver<()>,
205);
206
207/// Accept-time diagnostics, kept apart from peer observations used for trust.
208#[derive(Clone)]
209pub(crate) enum RouteOpenerConnection {
210    Local(Option<subc_os::local_peer::DiagnosticProcess>),
211    Tcp,
212}
213
214/// Real channel-0 control handler for subc itself.
215#[derive(Clone)]
216pub struct ControlHandler {
217    #[cfg(test)]
218    activity_request_pause: Arc<Mutex<Option<Arc<ActivityRequestPause>>>>,
219    /// Holds connection cleanup at a numbered point: 0 is just after the agent
220    /// declaration queue closes, 1 just after the registration channel is
221    /// forgotten.
222    #[cfg(test)]
223    cleanup_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
224    /// Runs once in `route.open`'s launch-nonce attestation, right after the
225    /// nonce is resolved, to interleave a nonce withdrawal there.
226    #[cfg(test)]
227    after_nonce_attestation: Arc<Mutex<Option<TestHook>>>,
228    /// Holds a registration channel's HELLO after its reader resolved the
229    /// channel and before the blocking HELLO handler starts.
230    #[cfg(test)]
231    hello_ingress_pause: Arc<Mutex<Option<AsyncTestPause>>>,
232    /// Holds an agent command declaration at a numbered point in its handler.
233    #[cfg(test)]
234    agent_commands_pause: Arc<Mutex<Option<(u8, TestPause)>>>,
235    claims: Arc<claims::Claims>,
236    registry: Arc<Registry>,
237    control_usage: Arc<Mutex<usage::ControlUsage>>,
238    catalog_cache: Arc<Mutex<catalog::CatalogCache>>,
239    catalog_readiness_revision: Arc<std::sync::atomic::AtomicU64>,
240    config_runtime: Option<Arc<crate::config_gate::runtime::RuntimeOwner>>,
241    config_review_admission: Arc<dyn crate::config_gate::ReviewAdmission>,
242    config_review_admission_is_default: bool,
243    activity: Option<crate::activity::ActivityLedger>,
244    activity_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
245    activity_reservations: activity_reservations::ActivityReservations,
246    catalog_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
247    config_settings_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
248    scope_streams: Arc<Mutex<HashMap<(ConnectionId, u64), tokio::task::AbortHandle>>>,
249    forwarding: Arc<ForwardingTable>,
250    process_liveness: Option<Arc<dyn ModuleProcessLiveness>>,
251    supervisor: SupervisorHandle,
252    pub(crate) resource_tracker: Arc<crate::resource_totals::Tracker>,
253    agent_declarations: agent_commands::Queues,
254    list_admission: Arc<tokio::sync::Semaphore>,
255    subc_capabilities: Arc<[String]>,
256    /// Daemon-wide route.bind relay budget. Used as the fallback when the
257    /// target module has no per-module override in
258    /// `route_bind_relay_timeouts`.
259    route_bind_relay_timeout: Duration,
260    /// Per-module route.bind relay budget overrides, keyed by module id. When
261    /// `handle_route_open` resolves the deadline for a target module, a
262    /// per-module entry wins over the daemon-wide value above.
263    route_bind_relay_timeouts: BTreeMap<String, Duration>,
264    /// Per-target-module bind-relay breaker state. Shared with the forwarding
265    /// table, which is where a new module connection resets it.
266    route_bind_breakers: RouteBindBreakers,
267    /// Live relay admissions keyed by target module. Shared through the
268    /// forwarding table so cloned or separately built handlers enforce one cap.
269    route_bind_concurrency: RouteBindConcurrency,
270    /// Start and end of each module's not-serving period as seen by
271    /// `route.open`, so an outage gets one line at each edge instead of only
272    /// the per-refusal INFO lines. Taken from the forwarding table, so every
273    /// handler built over one table shares it.
274    route_outages: Arc<crate::route_outage::RouteOutageTracker>,
275    route_refusal_log: route_open_refusal_log::RefusalLog,
276    /// Consecutive relay timeouts that open a module's breaker.
277    route_bind_breaker_threshold: u32,
278    /// How long a breaker stays open before one probe is admitted.
279    route_bind_breaker_cooldown: Duration,
280    health_probe_timeout: Duration,
281    /// Central storage policy. When set, each registering module receives its
282    /// resolved storage descriptor in HELLO_ACK; `None` leaves the field absent.
283    storage_config: Option<crate::daemon_config::StorageConfig>,
284    /// The machine id established at boot, served on every HELLO_ACK and on
285    /// `server.describe`. Fixed for the daemon's lifetime: `ck machine adopt`
286    /// changes the file, never this value. `None` serves no id.
287    machine_id: Option<crate::machine_id::MachineId>,
288    admission_facts_carrier_module_id: Option<String>,
289    admission_facts_targets: Option<Vec<String>>,
290    /// Scope records with their sync authorities and tombstones; see
291    /// `crate::scopes`. Shared by clones of this handler, so every connection
292    /// reads and writes one table.
293    scopes: Arc<RwLock<ScopeTable>>,
294    /// Wakes the expiry loop when an accepted scope change may have added a
295    /// deadline, so the loop can wait without ticking while no live scope has
296    /// one. A permit is stored when nothing waits, so no wake is lost.
297    scope_deadline_added: Arc<tokio::sync::Notify>,
298    /// The configured `scope_authority_owners`, kept so a rescan can report a
299    /// changed value as needing a daemon restart; rescan never applies it.
300    scope_authority_owners: Vec<String>,
301    flow_scope_authority_owners: Vec<String>,
302    federated_scope_owner: String,
303    /// Fixed at startup so rescan cannot change the policy that guards rescan itself.
304    privileged_operator_prompt: PrivilegedOperatorPrompt,
305    /// The local and peer address of each accepted TCP client connection, read
306    /// from the daemon's own socket, so a privileged request can name its caller.
307    caller_endpoints: Arc<Mutex<HashMap<ConnectionId, (SocketAddr, SocketAddr)>>>,
308    route_openers: Arc<Mutex<HashMap<ConnectionId, RouteOpenerConnection>>>,
309    build_class_warned: Arc<Mutex<HashSet<ConnectionId>>>,
310    observed_peers: Arc<Mutex<HashMap<ConnectionId, ObservedPeer>>>,
311    captured_peers: Arc<Mutex<HashMap<ConnectionId, Arc<peer_identity::PeerCapture>>>>,
312    config_desktop_stamps:
313        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
314    local_connections: Arc<Mutex<HashSet<ConnectionId>>>,
315    pub(crate) operator_app_policy: crate::operator_apps::OperatorAppPolicy,
316    pub(crate) operator_apps:
317        Arc<Mutex<HashMap<ConnectionId, crate::operator_apps::OperatorAppStamp>>>,
318    /// One launch entry per app, behind a leaf lock: no other lock is taken
319    /// while it is held. Entries are memory-only, so a daemon or
320    /// installed-service restart drops them and a relaunched daemon never
321    /// mistakes an older process for its own launch.
322    pub(crate) launch_table: std::sync::Arc<crate::app_open::LaunchTable>,
323    /// Serializes `app.open` launches: the liveness check in the decision and
324    /// the later publish must not interleave across concurrent calls, or two
325    /// calls could both launch and the second publish would orphan the first
326    /// process. Refusals and `already_running` answers share the same lock;
327    /// `app.open` is rare, so the cost is negligible.
328    pub(crate) app_open_launch_lock: std::sync::Arc<tokio::sync::Mutex<()>>,
329    // Portable wire samples exercise dispatch without starting an OS process.
330    #[cfg(test)]
331    pub(crate) app_open_test_platform: Option<crate::operator_apps::AppOpenPlatform>,
332    #[cfg(test)]
333    pub(crate) app_open_test_launch: Option<fn() -> Result<u32, crate::app_open::AppOpenRefusal>>,
334    #[cfg(test)]
335    pub(crate) config_review_test_reply: Option<subc_protocol::config::ConfigReviewReply>,
336    #[cfg(test)]
337    pub(crate) config_review_test_replies:
338        std::collections::BTreeMap<String, subc_protocol::config::ConfigReviewReply>,
339    #[cfg(test)]
340    pub(crate) config_review_test_seen: Option<tokio::sync::mpsc::UnboundedSender<String>>,
341    #[cfg(test)]
342    pub(crate) config_review_test_refuse: Arc<std::sync::Mutex<std::collections::BTreeSet<String>>>,
343    #[cfg(test)]
344    pub(crate) config_review_test_fail_once: Arc<std::sync::atomic::AtomicBool>,
345    #[cfg(test)]
346    recovery_exit_test_after_step: Option<fn(usize) -> Result<(), crate::config_gate::GateError>>,
347    #[cfg(test)]
348    recovery_exit_test_completed: Option<fn(u64)>,
349    #[cfg(test)]
350    apply_reconcile_pause: Arc<Mutex<Option<AsyncTestPause>>>,
351    #[cfg(test)]
352    recovery_exit_test_quiet_retry: bool,
353    #[cfg(test)]
354    recovery_exit_test_retry_pause: Option<fn(u64) -> Option<PathBuf>>,
355    #[cfg(test)]
356    config_delivery_test_wakes:
357        Option<tokio::sync::mpsc::UnboundedSender<(&'static str, tokio::time::Instant)>>,
358    #[cfg(all(test, unix))]
359    config_delivery_test_idle:
360        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
361    #[cfg(all(test, unix))]
362    settings_poll_test_idle:
363        Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
364    /// Test-only Windows signature and flash hooks. Production builds carry
365    /// neither: with the publisher unset, the production table never reaches
366    /// verification, and the default attention hook only logs.
367    #[allow(dead_code)]
368    #[cfg(windows)]
369    pub(crate) windows_verify: Option<crate::app_open::WindowsVerifyFn>,
370    #[allow(dead_code)]
371    #[cfg(windows)]
372    pub(crate) windows_flash: Option<crate::app_open::WindowsFlashFn>,
373    /// Test-only tracking fault hook: makes opening the tracking handle on
374    /// the launched pid fail, so a test can prove an untrackable launch is
375    /// stopped rather than left running.
376    #[allow(dead_code)]
377    #[cfg(windows)]
378    pub(crate) windows_track: Option<crate::app_open::WindowsTrackFn>,
379    /// Test-only count of Windows spawn attempts, so a test can prove a
380    /// refused launch started no process. Unit tests only.
381    #[cfg(all(test, windows))]
382    pub(crate) windows_spawn_attempts: Arc<std::sync::atomic::AtomicU64>,
383    #[cfg(test)]
384    caller_lookup: Option<TestCallerLookup>,
385    /// The launch nonce each module connection presented at HELLO, which is how
386    /// a `scope.sync` is matched to the owner's current launch.
387    hello_launch_nonces: Arc<Mutex<HelloLaunchNonces>>,
388    rescan: Option<SupervisorRescanContext>,
389    connected_clients: ConnectedClients,
390    counters: DaemonCounters,
391    /// Why this daemon serves no local endpoint, when binding one failed. `None`
392    /// when the endpoint is served, and also on a handler that was never told.
393    local_endpoint_unavailable: Option<String>,
394    capability_evaluator: Arc<CapabilityRequirementEvaluator>,
395    /// The supervisor's daemon-shutdown flag. Once it is set, requirement
396    /// changes are logged at INFO with `cause=daemon_shutdown` instead of at
397    /// their usual severity (see [`log_requirement_events`]). A handler built
398    /// without one has a flag that is never set.
399    daemon_shutdown: DaemonShutdownFlag,
400    #[cfg(any(target_os = "linux", target_os = "macos"))]
401    pub(crate) upgrade: Option<Arc<upgrade_in_place::Runtime>>,
402    daemon_provenance: DaemonProvenanceFacts,
403    #[cfg(test)]
404    control_dispatch_delay: Option<Duration>,
405    #[cfg(test)]
406    provenance_probe_override: Option<subc_control::RunningImageAgreement>,
407    /// Holds `route.open` after the route.bind is queued to the module and
408    /// before it is marked enqueued, so a test can make the module's reply (or
409    /// a client teardown) land exactly inside that window.
410    #[cfg(test)]
411    route_bind_relay_sent_hold: Option<Arc<tokio::sync::Barrier>>,
412    #[cfg(all(test, target_os = "macos"))]
413    route_bind_before_reservation_hold: Option<Arc<tokio::sync::Barrier>>,
414    /// Holds a HELLO after its registry entry is reserved and before its
415    /// forwarding endpoint is installed, so a test can read the catalog and
416    /// open routes while the module is registered but not yet routable. A
417    /// blocking barrier because the HELLO handler is synchronous; the test
418    /// runs the HELLO on its own thread.
419    #[cfg(test)]
420    hello_registry_to_forwarding_hold: Option<Arc<std::sync::Barrier>>,
421    #[cfg(test)]
422    hello_ack_to_publication_hold: Option<Arc<std::sync::Barrier>>,
423    #[cfg(test)]
424    hello_before_publication_hold: Option<Arc<std::sync::Barrier>>,
425    #[cfg(test)]
426    hello_after_launch_check_hold: Option<Arc<std::sync::Barrier>>,
427    #[cfg(test)]
428    hello_inside_publication_hold: Option<Arc<std::sync::Barrier>>,
429}
430
431impl fmt::Debug for ControlHandler {
432    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
433        f.debug_struct("ControlHandler")
434            .field("registry", &self.registry)
435            .field("forwarding", &self.forwarding)
436            .field("process_liveness", &self.process_liveness.is_some())
437            .field("supervisor", &self.supervisor)
438            .field("subc_capabilities", &self.subc_capabilities)
439            .finish()
440    }
441}
442
443impl ControlHandler {
444    pub(crate) fn install_registration_service(
445        &self,
446        router: std::sync::Weak<crate::Router>,
447        auth: crate::server::ServerAuth,
448    ) {
449        self.supervisor.install_registration_service(router, auth);
450    }
451    pub fn new(registry: Arc<Registry>) -> Self {
452        Self::with_forwarding(registry, Arc::new(ForwardingTable::default()))
453    }
454
455    pub fn with_forwarding(registry: Arc<Registry>, forwarding: Arc<ForwardingTable>) -> Self {
456        let counters = forwarding.counters();
457        // Taken from the forwarding table rather than created here, so that the
458        // breaker a `route.open` consults is the same one a module's
459        // registration resets, however many handlers are built over one table.
460        let route_bind_breakers = forwarding.route_bind_breakers();
461        let route_bind_concurrency = forwarding.route_bind_concurrency();
462        let route_outages = forwarding.route_outages();
463        Self {
464            registry,
465            control_usage: Arc::new(Mutex::new(usage::ControlUsage::default())),
466            catalog_cache: Arc::new(Mutex::new(catalog::CatalogCache::default())),
467            catalog_readiness_revision: Arc::new(std::sync::atomic::AtomicU64::new(0)),
468            #[cfg(test)]
469            activity_request_pause: Arc::new(Mutex::new(None)),
470            #[cfg(test)]
471            cleanup_pause: Arc::new(Mutex::new(None)),
472            #[cfg(test)]
473            after_nonce_attestation: Arc::new(Mutex::new(None)),
474            #[cfg(test)]
475            hello_ingress_pause: Arc::new(Mutex::new(None)),
476            #[cfg(test)]
477            agent_commands_pause: Arc::new(Mutex::new(None)),
478            claims: Arc::new(claims::Claims::default()),
479            config_runtime: None,
480            config_review_admission: Arc::new(crate::config_gate::MissingReviewAdmission),
481            config_review_admission_is_default: true,
482            activity: None,
483            activity_streams: Arc::new(Mutex::new(HashMap::new())),
484            activity_reservations: Default::default(),
485            catalog_streams: Arc::new(Mutex::new(HashMap::new())),
486            config_settings_streams: Arc::new(Mutex::new(HashMap::new())),
487            scope_streams: Arc::new(Mutex::new(HashMap::new())),
488            forwarding,
489            process_liveness: None,
490            supervisor: SupervisorHandle::new(),
491            resource_tracker: Arc::new(crate::resource_totals::Tracker::new(
492                env!("CARGO_PKG_VERSION").to_owned(),
493            )),
494            agent_declarations: agent_commands::Queues::default(),
495            list_admission: Arc::new(tokio::sync::Semaphore::new(4)),
496            subc_capabilities: Arc::from([
497                CAP_MANIFEST_REGISTRATION.to_string(),
498                CAP_CHANNEL_LIFECYCLE.to_string(),
499                CAP_PING_PONG.to_string(),
500                CAP_SESSION_ATTACH.to_string(),
501                CAP_ADMISSION_FACTS_RELAY.to_string(),
502                CAP_SCOPES_V1.to_string(),
503                subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY.to_string(),
504                subc_protocol::scope::SCOPE_FEDERATED_V2_CAPABILITY.to_string(),
505                subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY.to_string(),
506                PEER_BUILD_CAPABILITY.to_string(),
507                CAP_ROUTE_ROLE_VERSIONS_V1.to_string(),
508                subc_protocol::manifest::CAP_CATALOG_EVENTS_V1.to_string(),
509                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V1.to_string(),
510                subc_protocol::manifest::CAP_SCOPE_BIND_PROOF_V2.to_string(),
511                subc_protocol::manifest::CAP_SCOPE_REPLACE_IF_IDLE_V1.to_string(),
512                subc_protocol::scope::SCOPE_ON_BEHALF_OF_CAPABILITY.to_string(),
513                subc_protocol::scope::WORKER_RUNS_CAPABILITY.to_string(),
514                subc_protocol::scope::SCOPE_WORKDIR_CAPABILITY.to_string(),
515                subc_protocol::scope::FLOW_IDENTITY_SCOPES_CAPABILITY.to_string(),
516                subc_protocol::scope::SCOPE_SERVED_BY_CAPABILITY.to_string(),
517                subc_control::ACTIVITY_LEDGER_CAPABILITY.to_string(),
518                subc_protocol::ROUTE_CLOSE_REASONS_CAPABILITY.to_string(),
519                subc_protocol::session::ACCEPTING_DRAIN_CAPABILITY.to_string(),
520            ]),
521            route_bind_relay_timeout: DEFAULT_ROUTE_BIND_RELAY_TIMEOUT,
522            route_bind_relay_timeouts: BTreeMap::new(),
523            route_bind_breakers,
524            route_bind_concurrency,
525            route_outages,
526            route_refusal_log: Default::default(),
527            route_bind_breaker_threshold: DEFAULT_ROUTE_BIND_BREAKER_THRESHOLD,
528            route_bind_breaker_cooldown: DEFAULT_ROUTE_BIND_BREAKER_COOLDOWN,
529            health_probe_timeout: DEFAULT_HEALTH_PROBE_TIMEOUT,
530            storage_config: None,
531            machine_id: None,
532            admission_facts_carrier_module_id: None,
533            admission_facts_targets: None,
534            scopes: Arc::new(RwLock::new(ScopeTable::new(
535                crate::daemon_config::default_scope_authority_owners(),
536            ))),
537            scope_deadline_added: Arc::new(tokio::sync::Notify::new()),
538            scope_authority_owners: crate::daemon_config::default_scope_authority_owners(),
539            flow_scope_authority_owners: Vec::new(),
540            federated_scope_owner: crate::daemon_config::default_federated_scope_owner(),
541            privileged_operator_prompt: PrivilegedOperatorPrompt::default(),
542            caller_endpoints: Arc::new(Mutex::new(HashMap::new())),
543            route_openers: Arc::new(Mutex::new(HashMap::new())),
544            build_class_warned: Arc::new(Mutex::new(HashSet::new())),
545            observed_peers: Arc::new(Mutex::new(HashMap::new())),
546            captured_peers: Arc::new(Mutex::new(HashMap::new())),
547            config_desktop_stamps: Arc::new(Mutex::new(HashMap::new())),
548            local_connections: Arc::new(Mutex::new(HashSet::new())),
549            operator_app_policy: Default::default(),
550            operator_apps: Arc::new(Mutex::new(HashMap::new())),
551            launch_table: std::sync::Arc::new(crate::app_open::LaunchTable::new()),
552            app_open_launch_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
553            #[cfg(test)]
554            app_open_test_platform: None,
555            #[cfg(test)]
556            app_open_test_launch: None,
557            #[cfg(test)]
558            config_review_test_reply: None,
559            #[cfg(test)]
560            config_review_test_replies: Default::default(),
561            #[cfg(test)]
562            config_review_test_seen: None,
563            #[cfg(test)]
564            config_review_test_refuse: Default::default(),
565            #[cfg(test)]
566            config_review_test_fail_once: Default::default(),
567            #[cfg(test)]
568            recovery_exit_test_after_step: None,
569            #[cfg(test)]
570            recovery_exit_test_completed: None,
571            #[cfg(test)]
572            apply_reconcile_pause: Arc::new(Mutex::new(None)),
573            #[cfg(test)]
574            recovery_exit_test_quiet_retry: false,
575            #[cfg(test)]
576            recovery_exit_test_retry_pause: None,
577            #[cfg(test)]
578            config_delivery_test_wakes: None,
579            #[cfg(all(test, unix))]
580            config_delivery_test_idle: None,
581            #[cfg(all(test, unix))]
582            settings_poll_test_idle: None,
583            #[cfg(windows)]
584            windows_verify: None,
585            #[cfg(windows)]
586            windows_flash: None,
587            #[cfg(windows)]
588            windows_track: None,
589            #[cfg(all(test, windows))]
590            windows_spawn_attempts: Arc::new(std::sync::atomic::AtomicU64::new(0)),
591            #[cfg(test)]
592            caller_lookup: None,
593            hello_launch_nonces: Arc::new(Mutex::new(HelloLaunchNonces::default())),
594            rescan: None,
595            connected_clients: ConnectedClients::new(),
596            local_endpoint_unavailable: None,
597            counters,
598            capability_evaluator: Arc::new(CapabilityRequirementEvaluator::new()),
599            daemon_shutdown: DaemonShutdownFlag::default(),
600            #[cfg(any(target_os = "linux", target_os = "macos"))]
601            upgrade: None,
602            daemon_provenance: DaemonProvenanceFacts::default(),
603            #[cfg(test)]
604            control_dispatch_delay: None,
605            #[cfg(test)]
606            provenance_probe_override: None,
607            #[cfg(test)]
608            route_bind_relay_sent_hold: None,
609            #[cfg(all(test, target_os = "macos"))]
610            route_bind_before_reservation_hold: None,
611            #[cfg(test)]
612            hello_registry_to_forwarding_hold: None,
613            #[cfg(test)]
614            hello_ack_to_publication_hold: None,
615            #[cfg(test)]
616            hello_before_publication_hold: None,
617            #[cfg(test)]
618            hello_after_launch_check_hold: None,
619            #[cfg(test)]
620            hello_inside_publication_hold: None,
621        }
622    }
623
624    /// Set the central storage policy: registering modules then receive their
625    /// resolved storage descriptor in HELLO_ACK.
626    pub fn with_storage_config(
627        mut self,
628        storage_config: Option<crate::daemon_config::StorageConfig>,
629    ) -> Self {
630        self.storage_config = storage_config;
631        self
632    }
633
634    /// Set the machine id served to every registering module (HELLO_ACK) and on
635    /// `server.describe`.
636    pub fn with_machine_id(mut self, machine_id: Option<crate::machine_id::MachineId>) -> Self {
637        self.machine_id = machine_id;
638        self
639    }
640
641    /// Configure the exact reserved module and target ids permitted to relay
642    /// opaque admission facts. Config-file loading validates this authority;
643    /// this builder keeps the same policy available to embedded test daemons.
644    pub fn with_admission_facts_config(
645        mut self,
646        carrier_module_id: Option<String>,
647        targets: Option<Vec<String>>,
648    ) -> Self {
649        self.admission_facts_carrier_module_id = carrier_module_id;
650        self.admission_facts_targets = targets;
651        self
652    }
653
654    /// Set the module ids whose scopes may carry `agent_id` and `delegates`.
655    /// Replaces the scope table with an empty one under the new list, so call it
656    /// while building the handler, before any module can sync.
657    pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
658        self.scopes = Arc::new(RwLock::new(
659            ScopeTable::new(owners.iter().cloned())
660                .with_flow_scope_authority_owners(self.flow_scope_authority_owners.iter().cloned())
661                .with_federated_owner(self.federated_scope_owner.clone()),
662        ));
663        self.scope_authority_owners = owners;
664        self
665    }
666
667    /// Set the module ids with narrow authority over head and ephemeral flow
668    /// scopes. Like the full authority list, this replaces an empty table and
669    /// must be called before any module can sync.
670    pub fn with_flow_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
671        self.scopes = Arc::new(RwLock::new(
672            ScopeTable::new(self.scope_authority_owners.iter().cloned())
673                .with_flow_scope_authority_owners(owners.iter().cloned())
674                .with_federated_owner(self.federated_scope_owner.clone()),
675        ));
676        self.flow_scope_authority_owners = owners;
677        self
678    }
679
680    /// Set the exclusive federated owner while building the handler, before syncs.
681    pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
682        self.scopes = Arc::new(RwLock::new(
683            ScopeTable::new(self.scope_authority_owners.iter().cloned())
684                .with_flow_scope_authority_owners(self.flow_scope_authority_owners.iter().cloned())
685                .with_federated_owner(owner.clone()),
686        ));
687        self.federated_scope_owner = owner;
688        self
689    }
690
691    /// Set the startup policy before installing the rescan context or serving requests.
692    pub fn with_privileged_operator_prompt(mut self, mode: PrivilegedOperatorPrompt) -> Self {
693        self.privileged_operator_prompt = mode;
694        self
695    }
696
697    #[cfg(test)]
698    pub(crate) fn with_control_dispatch_delay(mut self, delay: Duration) -> Self {
699        self.control_dispatch_delay = Some(delay);
700        self
701    }
702
703    pub fn with_process_liveness(
704        mut self,
705        process_liveness: Arc<dyn ModuleProcessLiveness>,
706    ) -> Self {
707        self.process_liveness = Some(process_liveness);
708        self
709    }
710
711    pub fn with_supervisor(mut self, supervisor: SupervisorHandle) -> Self {
712        self.supervisor = supervisor;
713        if let Some(owner) = &self.config_runtime {
714            self.supervisor.install_binding_retirement(owner);
715        }
716        self.supervisor.set_activity(self.activity.clone());
717        self
718    }
719
720    /// Install the configured module set and its reserved capability bindings.
721    /// Bindings are configuration-scoped and may point at a provider that has not
722    /// been installed yet, so this does not require the bound module to exist.
723    pub fn with_capability_config(
724        self,
725        modules: impl IntoIterator<Item = (String, bool)>,
726        reserved_capabilities: BTreeMap<String, String>,
727    ) -> Self {
728        self.capability_evaluator
729            .configure(modules, reserved_capabilities);
730        self
731    }
732
733    /// Share the supervisor's daemon-shutdown flag with this handler, so
734    /// requirement changes after the daemon has begun its announced shutdown
735    /// are not reported as faults.
736    pub(crate) fn with_daemon_shutdown_flag(mut self, flag: DaemonShutdownFlag) -> Self {
737        self.daemon_shutdown = flag;
738        self
739    }
740
741    pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
742        self.connected_clients = connected_clients;
743        self
744    }
745
746    /// Report why this daemon serves no local endpoint, in `server.describe`, so
747    /// an operator can see a bind failure without reading the daemon log.
748    pub fn with_local_endpoint_unavailable(mut self, reason: Option<String>) -> Self {
749        self.local_endpoint_unavailable = reason;
750        self
751    }
752
753    pub fn forwarding(&self) -> Arc<ForwardingTable> {
754        Arc::clone(&self.forwarding)
755    }
756
757    pub(crate) fn counters(&self) -> DaemonCounters {
758        self.counters.clone()
759    }
760
761    /// Remove a connection's registry entries WITHOUT signalling the supervisor's
762    /// registration-release watch. The signal is what the supervisor waits on
763    /// before spawning a replacement, so it must only fire once forwarding
764    /// teardown is also done (see [`Self::cleanup_connection`] /
765    /// [`Self::handle_goodbye`]). Unpublished HELLO rollback uses the separate
766    /// registry-only path below because publication already owns the spawn lock.
767    fn deregister_connection(
768        &self,
769        connection_id: ConnectionId,
770        reason: RegistrationEndReason,
771    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
772        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
773            spawn.end_primary_registration();
774        }
775        self.registry
776            .deregister_connection_with_reason(connection_id, reason)
777    }
778
779    fn request_refusal_close(
780        &self,
781        connection: ConnectionId,
782        sink: Option<&crate::FrameSink>,
783        reason: CloseReason,
784    ) {
785        if let Some(sink) = sink {
786            sink.terminate_ingress();
787        }
788        if self.claims.close_notifications_enabled() {
789            self.forwarding.request_connection_close(connection, reason);
790        }
791    }
792
793    /// Test-only compatibility entry point for unit control handling that does not have a socket sink.
794    ///
795    /// The real server path uses [`Self::handle_control_frame`] so module HELLO registration can
796    /// record the module connection's [`crate::FrameSink`] and session attach can await the module
797    /// relay response. This seam stays cfg(test) so production has only one channel-0 path.
798    #[cfg(test)]
799    pub fn handle_control(
800        &self,
801        connection_id: ConnectionId,
802        frame: Frame,
803    ) -> Result<Vec<Frame>, RouterError> {
804        match frame.header.ty {
805            FrameType::Ping => Ok(vec![pong(&frame)?]),
806            FrameType::Hello => self.handle_hello(connection_id, None, frame),
807            FrameType::Goodbye => self.handle_goodbye(connection_id),
808            ty => Ok(vec![control_error_frame(
809                &frame,
810                "unsupported_control_frame",
811                format!("unsupported channel-0 frame {ty:?}"),
812            )?]),
813        }
814    }
815
816    pub async fn handle_control_frame(
817        &self,
818        ctx: &RouteCtx,
819        frame: Frame,
820    ) -> Result<Vec<Frame>, RouterError> {
821        self.handle_control_frame_timed(ctx, frame, None).await
822    }
823
824    #[cfg(any(test, feature = "test-support"))]
825    pub fn with_test_operator_app_policy(
826        mut self,
827        policy: crate::operator_apps::TestOperatorAppPolicy,
828    ) -> Self {
829        self.operator_app_policy = policy.into();
830        self
831    }
832
833    /// Inject the Windows signature check for tests. The injected check
834    /// answers the verified version string or the rejection reason; the
835    /// daemon enforces the floor itself on the returned version.
836    #[cfg(all(windows, any(test, feature = "test-support")))]
837    pub fn with_test_windows_verifier(mut self, verify: crate::app_open::WindowsVerifyFn) -> Self {
838        self.windows_verify = Some(verify);
839        self
840    }
841
842    /// Record which pids the daemon would flash for `already_running`.
843    #[cfg(all(windows, any(test, feature = "test-support")))]
844    pub fn with_test_windows_flash(mut self, flash: crate::app_open::WindowsFlashFn) -> Self {
845        self.windows_flash = Some(flash);
846        self
847    }
848
849    /// Inject a tracking failure for tests: makes `track_launched_process`
850    /// fail so a test can prove a launch that cannot be tracked is stopped,
851    /// never left running.
852    #[cfg(all(windows, any(test, feature = "test-support")))]
853    pub fn with_test_windows_track(mut self, track: crate::app_open::WindowsTrackFn) -> Self {
854        self.windows_track = Some(track);
855        self
856    }
857
858    pub(crate) fn record_local_connection(&self, connection: ConnectionId) {
859        self.local_connections
860            .lock()
861            .unwrap_or_else(|p| p.into_inner())
862            .insert(connection);
863    }
864
865    pub(crate) fn record_route_opener(
866        &self,
867        connection: ConnectionId,
868        opener: RouteOpenerConnection,
869    ) {
870        self.route_openers
871            .lock()
872            .unwrap_or_else(|p| p.into_inner())
873            .insert(connection, opener);
874    }
875
876    // Keep the connection-level delivery decision shared with route.bind. The
877    // target's capability opt-in is separate from recognition of the caller.
878    fn connection_operator_app(
879        &self,
880        stamp: Option<&crate::operator_apps::OperatorAppStamp>,
881    ) -> Option<subc_protocol::peer::OperatorApp> {
882        stamp
883            .filter(|stamp| stamp.delivery_enabled(&self.operator_app_policy))
884            .map(|stamp| stamp.app.clone())
885    }
886
887    pub(crate) fn record_observed_peer(
888        &self,
889        connection: ConnectionId,
890        peer: subc_os::local_peer::ObservedPeer,
891    ) {
892        use subc_os::local_peer::{ObservedPeer as OsPeer, PeerUser};
893        let peer = match peer {
894            OsPeer::Unobserved => ObservedPeer::unobserved(),
895            OsPeer::Observed(peer) => {
896                let observed = match peer.user {
897                    PeerUser::Uid(uid) => ObservedPeer::observed_uid(uid),
898                    PeerUser::Sid(sid) => ObservedPeer::observed_sid(sid),
899                };
900                observed
901                    .with_exe(
902                        peer.exe
903                            .and_then(|path| path.into_os_string().into_string().ok()),
904                    )
905                    .with_signing_id(peer.signing_id)
906            }
907        };
908        self.observed_peers
909            .lock()
910            .unwrap_or_else(|p| p.into_inner())
911            .insert(connection, peer);
912    }
913
914    pub(crate) fn record_caller_endpoints(
915        &self,
916        connection: ConnectionId,
917        endpoints: Option<(SocketAddr, SocketAddr)>,
918    ) {
919        let mut callers = self
920            .caller_endpoints
921            .lock()
922            .unwrap_or_else(|p| p.into_inner());
923        callers.remove(&connection);
924        if let Some(endpoints) = endpoints {
925            callers.insert(connection, endpoints);
926        }
927    }
928
929    #[cfg(test)]
930    pub(crate) fn with_caller_lookup_for_test(
931        mut self,
932        lookup: impl Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync + 'static,
933    ) -> Self {
934        self.caller_lookup = Some(Arc::new(lookup));
935        self
936    }
937
938    async fn resolve_caller(&self, connection: ConnectionId) -> CallerIdentity {
939        let endpoints = self
940            .caller_endpoints
941            .lock()
942            .unwrap_or_else(|p| p.into_inner())
943            .get(&connection)
944            .copied();
945        #[cfg(test)]
946        let lookup = self.caller_lookup.clone();
947        tokio::task::spawn_blocking(move || {
948            #[cfg(test)]
949            if let Some(lookup) = lookup {
950                return lookup(endpoints);
951            }
952            endpoints
953                .map(|(local, peer)| CallerIdentity::lookup_endpoints(local, peer))
954                .unwrap_or_default()
955        })
956        .await
957        .unwrap_or_default()
958    }
959
960    pub(crate) fn defers_privileged_control(&self, ctx: &RouteCtx, frame: &Frame) -> bool {
961        frame.header.channel == 0
962            && frame.header.ty == FrameType::Request
963            && self
964                .forwarding
965                .module_endpoint_for_connection(ctx.connection_id)
966                .is_ok_and(|endpoint| endpoint.is_none())
967            && parse_client_control_request(&frame.body)
968                .ok()
969                .is_some_and(|request| privileged_operation(&request).is_some())
970    }
971
972    pub(crate) async fn handle_control_frame_timed(
973        &self,
974        ctx: &RouteCtx,
975        frame: Frame,
976        dispatch_started_at: Option<StdInstant>,
977    ) -> Result<Vec<Frame>, RouterError> {
978        let first = ctx.egress.first_ingress_frame();
979        self.handle_control_frame_ingress(ctx, frame, dispatch_started_at, first)
980            .await
981    }
982
983    pub(crate) async fn handle_control_frame_ingress(
984        &self,
985        ctx: &RouteCtx,
986        frame: Frame,
987        dispatch_started_at: Option<StdInstant>,
988        first: bool,
989    ) -> Result<Vec<Frame>, RouterError> {
990        if ctx.egress.ingress_terminal() {
991            return Ok(Vec::new());
992        }
993        #[cfg(test)]
994        self.claims.record_dispatch(frame.header.corr);
995        let claim_binding = self.claims.binding(ctx.connection_id);
996        let mut prefix_attempt = (frame.header.ty == FrameType::Hello
997            && claim_binding
998                .as_ref()
999                .is_some_and(|binding| binding.prefix_module_id().is_some()))
1000        .then(|| self.prefix_hello_attempt(ctx));
1001        if claim_binding
1002            .as_ref()
1003            .is_some_and(|binding| binding.prefix_module_id().is_some())
1004        {
1005            let registered = self
1006                .forwarding
1007                .module_endpoint_for_connection(ctx.connection_id)
1008                .map_err(RouterError::Forwarding)?
1009                .is_some();
1010            if !registered && frame.header.ty != FrameType::Hello {
1011                return self
1012                    .refuse_claim_connection(ctx, &frame, "claim_hello_required")
1013                    .await;
1014            }
1015            if registered && frame.header.ty == FrameType::Goodbye {
1016                ctx.egress.terminate_ingress();
1017                let result = self.handle_goodbye(ctx.connection_id);
1018                self.claims.connection_closed(ctx.connection_id);
1019                self.request_refusal_close(
1020                    ctx.connection_id,
1021                    Some(&ctx.egress),
1022                    CloseReason::new("claim_registration_ended", "prefix registration ended"),
1023                );
1024                return result;
1025            }
1026            if registered && frame.header.ty == FrameType::Request {
1027                let allowed =
1028                    serde_json::from_slice::<ControlOpProbe>(&frame.body).is_ok_and(|probe| {
1029                        matches!(
1030                            probe.op.as_str(),
1031                            "catalog.update"
1032                                | "catalog.update_role_declarations"
1033                                | "scope.describe"
1034                                | "scope.watch"
1035                                | "supervisor.live_roots"
1036                                | subc_protocol::policy_root::GET_OP
1037                                | "activity.record"
1038                        )
1039                    });
1040                if !allowed {
1041                    return Ok(vec![control_error_frame(
1042                        &frame,
1043                        channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
1044                        "prefix registrations have only brokered module operations",
1045                    )?]);
1046                }
1047            }
1048            if registered
1049                && frame.header.ty == FrameType::Push
1050                && !serde_json::from_slice::<ControlOpProbe>(&frame.body)
1051                    .is_ok_and(|probe| probe.op == "route.status")
1052            {
1053                return Ok(vec![control_error_frame(
1054                    &frame,
1055                    channel_operations::CLAIM_OPERATION_NOT_ALLOWED,
1056                    "prefix registrations may push only route.status for routes they serve",
1057                )?]);
1058            }
1059        }
1060        match frame.header.ty {
1061            FrameType::Ping => Ok(vec![pong(&frame)?]),
1062            FrameType::Hello => {
1063                if claim_binding
1064                    .as_ref()
1065                    .is_some_and(|binding| binding.prefix_module_id().is_none())
1066                {
1067                    return self
1068                        .refuse_claim_connection(ctx, &frame, "claim_hello_not_allowed")
1069                        .await;
1070                }
1071                // Resolve before the blocking HELLO can outlive channel cleanup.
1072                let channel_spawn = self.supervisor.registration_spawn(ctx.connection_id);
1073                if let Some(spawn) = &channel_spawn {
1074                    spawn.wait_launch().await;
1075                    // Refused launches close the channel. Leave their pending
1076                    // HELLO unanswered instead of racing a reply against shutdown.
1077                    if !spawn.launch_ready() {
1078                        ctx.egress.terminate_ingress();
1079                        return Ok(Vec::new());
1080                    }
1081                    #[cfg(test)]
1082                    self.pause_hello_ingress_for_test().await;
1083                } else if claim_binding.is_none() {
1084                    if let Ok(hello) = serde_json::from_slice::<serde_json::Value>(&frame.body) {
1085                        if crate::supervise::resume_hello::has_resume_token(&hello) {
1086                            self.wait_for_resume_preparation(ctx.connection_id, &hello)
1087                                .await;
1088                        } else if let (Some(module), Some(nonce)) = (
1089                            hello
1090                                .get("manifest")
1091                                .and_then(|value| value.get("module_id"))
1092                                .and_then(|value| value.as_str()),
1093                            hello.get("launch_nonce").and_then(|value| value.as_str()),
1094                        ) {
1095                            if !self
1096                                .config_runtime
1097                                .as_ref()
1098                                .is_some_and(|owner| owner.module_is_gated(module))
1099                                && !self.supervisor.wait_program_binding(module, nonce).await
1100                            {
1101                                self.request_refusal_close(
1102                                    ctx.connection_id,
1103                                    Some(&ctx.egress),
1104                                    CloseReason::new(
1105                                        "program_refused",
1106                                        "the spawned program binding failed",
1107                                    ),
1108                                );
1109                                return Ok(vec![control_error_frame(
1110                                    &frame,
1111                                    if self
1112                                        .config_runtime
1113                                        .as_ref()
1114                                        .is_some_and(|owner| owner.is_recovering())
1115                                    {
1116                                        "config_gated"
1117                                    } else {
1118                                        "program_refused"
1119                                    },
1120                                    "the spawned program binding failed",
1121                                )?]);
1122                            }
1123                            if let Some(spawn) = self.supervisor.nonce_hello_spawn(module, nonce) {
1124                                // The child can dial before the supervisor has
1125                                // installed its durable roster entry.
1126                                spawn.wait_launch().await;
1127                            }
1128                        }
1129                    }
1130                }
1131                let handler = self.clone();
1132                let connection = ctx.connection_id;
1133                let egress = ctx.egress.clone();
1134                let correlation = frame.header.corr;
1135                let dispatcher = tracing::dispatcher::get_default(|dispatcher| dispatcher.clone());
1136                let span = tracing::Span::current();
1137                let hello_binding = claim_binding.clone();
1138                let replies = tokio::task::spawn_blocking(move || {
1139                    tracing::dispatcher::with_default(&dispatcher, || {
1140                        span.in_scope(|| {
1141                            handler.handle_hello_checked(
1142                                connection,
1143                                Some(egress),
1144                                frame,
1145                                true,
1146                                hello_binding,
1147                                channel_spawn,
1148                            )
1149                        })
1150                    })
1151                })
1152                .await
1153                .map_err(|error| RouterError::backend(0, correlation, error.to_string()))??;
1154                #[cfg(test)]
1155                if prefix_attempt.is_some() {
1156                    self.claims.pause_prefix_commit_for_test(false).await;
1157                }
1158                if let Some(attempt) = &mut prefix_attempt {
1159                    let accepted = !replies
1160                        .iter()
1161                        .any(|reply| reply.header.ty == FrameType::Error)
1162                        && self
1163                            .registry
1164                            .get_module_by_connection(ctx.connection_id)
1165                            .map_err(|err| RouterError::backend(0, correlation, err.to_string()))?
1166                            .is_some();
1167                    if accepted {
1168                        attempt.accepted = true;
1169                    } else {
1170                        ctx.egress.terminate_ingress();
1171                        for reply in replies {
1172                            ctx.egress.send_flushed(reply).await?;
1173                        }
1174                        return Ok(Vec::new());
1175                    }
1176                }
1177                Ok(replies)
1178            }
1179            FrameType::Goodbye => self.handle_goodbye(ctx.connection_id),
1180            FrameType::Cancel => {
1181                // Channel-0 cancellation withdraws approvals and subscriptions
1182                // and fences pending agent declarations;
1183                // successful cancellation has no ordinary reply.
1184                // A config Apply may also own an OS prompt. Cancel that prompt
1185                // before config cancellation can report the request handled.
1186                if self
1187                    .agent_declarations
1188                    .cancel(ctx.connection_id, frame.header.corr)
1189                    || self
1190                        .forwarding
1191                        .operator_confirms()
1192                        .cancel(ctx.connection_id, frame.header.corr)
1193                    || self.cancel_config_approval(ctx.connection_id, frame.header.corr)
1194                    || self
1195                        .supervisor
1196                        .cancel_spawn_subscription(ctx.connection_id, frame.header.corr)
1197                    || self.cancel_activity_subscription(ctx, &frame)?
1198                    || self.cancel_catalog_subscription(ctx.connection_id, frame.header.corr)
1199                    || self
1200                        .cancel_config_settings_subscription(ctx.connection_id, frame.header.corr)
1201                    || self.cancel_scope_subscription(ctx.connection_id, frame.header.corr)
1202                {
1203                    Ok(Vec::new())
1204                } else {
1205                    Ok(vec![control_error_frame(
1206                        &frame,
1207                        "unknown_subscription",
1208                        "no subscription has this correlation id",
1209                    )?])
1210                }
1211            }
1212            FrameType::Request => {
1213                // This additive operation is not part of the existing exhaustive
1214                // module-control enum. Probe the op before decoding that enum.
1215                let op = serde_json::from_slice::<ControlOpProbe>(&frame.body).ok();
1216                if let Some(probe) = &op {
1217                    self.record_control_usage(ctx.connection_id, &probe.op);
1218                }
1219                let claim_present = op.as_ref().is_some_and(|probe| probe.op == "claim.present");
1220                if let Some(refusal) = self.recovery_request_refusal(
1221                    ctx,
1222                    &frame,
1223                    op.as_ref().map(|probe| probe.op.as_str()),
1224                )? {
1225                    if claim_present {
1226                        self.reclaim_presented_expiry(&frame);
1227                        return self
1228                            .refuse_claim_connection(ctx, &frame, "config_gated")
1229                            .await;
1230                    }
1231                    return Ok(vec![refusal]);
1232                }
1233                if claim_present {
1234                    return self.handle_claim_present(ctx, &frame, first).await;
1235                }
1236                if op.as_ref().is_some_and(|probe| probe.op == "claim.mint") {
1237                    return self.handle_claim_mint(ctx, &frame).await;
1238                }
1239                if let Some(refusal) = self.registration_operation_refusal(
1240                    ctx,
1241                    &frame,
1242                    op.as_ref().map(|probe| probe.op.as_str()),
1243                )? {
1244                    return Ok(vec![refusal]);
1245                }
1246                if let Some(probe) = op.as_ref().filter(|probe| policy_root::is_op(&probe.op)) {
1247                    return self.handle_policy_root(ctx, frame, &probe.op).await;
1248                }
1249                if op
1250                    .as_ref()
1251                    .is_some_and(|probe| probe.op == ops::CATALOG_WATCH)
1252                {
1253                    return self.handle_catalog_watch(ctx, frame);
1254                }
1255                if op
1256                    .as_ref()
1257                    .is_some_and(|probe| probe.op == ops::SCOPE_WATCH)
1258                {
1259                    return self.handle_scope_watch(ctx, frame);
1260                }
1261                if op
1262                    .as_ref()
1263                    .is_some_and(|probe| probe.op == MODULE_TO_SUBC_OP_CATALOG_UPDATE)
1264                    && subc_protocol::provider_declarations::catalog_update_has_provider_declarations(&frame.body)
1265                        .unwrap_or(false)
1266                {
1267                    return Ok(vec![control_error_frame(
1268                        &frame,
1269                        error_codes::CATALOG_UPDATE_FROZEN_DECLARATIONS,
1270                        "provider_declarations are fixed at HELLO; restart the module to change them",
1271                    )?]);
1272                }
1273                if let Some(probe) = op
1274                    .as_ref()
1275                    .filter(|probe| config_gate::is_module_config_op(&probe.op))
1276                {
1277                    return self
1278                        .handle_module_config_request(ctx, frame, &probe.op)
1279                        .await;
1280                }
1281                if let Some(probe) = op
1282                    .as_ref()
1283                    .filter(|probe| config_gate::is_config_op(&probe.op))
1284                {
1285                    return self.handle_config_gate_request(ctx, frame, &probe.op).await;
1286                }
1287                if op
1288                    .as_ref()
1289                    .is_some_and(|probe| probe.op == ops::ACTIVITY_RECORD)
1290                {
1291                    return self.handle_activity_record(ctx, frame).await;
1292                }
1293                if op.as_ref().is_some_and(|probe| {
1294                    probe.op == ops::ACTIVITY_QUERY || probe.op == ops::ACTIVITY_SUBSCRIBE
1295                }) {
1296                    // A refusal and a CANCEL that won must not both end the stream.
1297                    let key = (ctx.connection_id, frame.header.corr);
1298                    let replies = self.handle_activity_read(ctx, frame).await?;
1299                    return Ok(self.activity_reservations.settle(key, replies));
1300                }
1301                if op
1302                    .as_ref()
1303                    .is_some_and(|probe| probe.op == "operator.confirm")
1304                {
1305                    return self.handle_operator_confirm(ctx, frame).await;
1306                }
1307                if op.as_ref().is_some_and(|probe| probe.op == ops::APP_OPEN) {
1308                    return self
1309                        .observe_control_wait(
1310                            ctx,
1311                            None,
1312                            ops::APP_OPEN,
1313                            self.handle_app_open(ctx, frame),
1314                        )
1315                        .await;
1316                }
1317                #[cfg(target_os = "macos")]
1318                if let Some(probe) = op.as_ref().filter(|p| {
1319                    matches!(
1320                        p.op.as_str(),
1321                        ops::APP_TRUST | ops::APP_TRUSTED | ops::APP_UNTRUST
1322                    )
1323                }) {
1324                    return self.handle_app_trust_ops(ctx, frame, &probe.op).await;
1325                }
1326                if op
1327                    .as_ref()
1328                    .is_some_and(|probe| probe.op == ops::CONNECTION_DESCRIBE)
1329                {
1330                    return self.handle_connection_describe(ctx, frame).await;
1331                }
1332                if op
1333                    .as_ref()
1334                    .is_some_and(|probe| probe.op == subc_control::SCOPE_SERVED_BY_OP)
1335                {
1336                    return self.handle_scope_served_by(ctx.connection_id, frame);
1337                }
1338                if self
1339                    .forwarding
1340                    .module_endpoint_for_connection(ctx.connection_id)
1341                    .map_err(RouterError::Forwarding)?
1342                    .is_some()
1343                {
1344                    if !is_known_module_request_op(&frame.body) {
1345                        return Ok(vec![control_error_frame(
1346                            &frame,
1347                            "unsupported_control_frame",
1348                            "module-originated channel-0 REQUEST is not supported",
1349                        )?]);
1350                    }
1351                    if op.as_ref().is_some_and(|probe| {
1352                        probe.op == subc_protocol::session::MODULE_DRAIN_READY_OP
1353                    }) {
1354                        return self.handle_module_drain_ready(ctx.connection_id, frame);
1355                    }
1356                    let request = match parse_module_control_request_from_module(&frame.body) {
1357                        Ok(request) => request,
1358                        Err((err, ControlRequestBodyError::UnknownOp)) => {
1359                            return Ok(vec![control_error_frame(
1360                                &frame,
1361                                "unsupported_control_frame",
1362                                format!("unsupported module-originated channel-0 REQUEST: {err}"),
1363                            )?])
1364                        }
1365                        Err((err, ControlRequestBodyError::InvalidBody)) => {
1366                            return Ok(vec![control_error_frame(
1367                                &frame,
1368                                "invalid_control_body",
1369                                format!("malformed module control body: {err}"),
1370                            )?])
1371                        }
1372                    };
1373                    let op = module_control_request_op(&request);
1374                    let corr = frame.header.corr;
1375                    log_control_dispatch_arrival(op, ctx.connection_id, corr);
1376                    if let ModuleControlRequestFromModule::AgentCommands {
1377                        started,
1378                        finished,
1379                        known,
1380                    } = request
1381                    {
1382                        return self
1383                            .agent_declarations
1384                            .enqueue(
1385                                self,
1386                                ctx,
1387                                frame,
1388                                crate::resource_totals::Declaration {
1389                                    started,
1390                                    finished,
1391                                    known,
1392                                },
1393                            )
1394                            .await;
1395                    }
1396                    let result =
1397                        self.handle_module_control_request(ctx.connection_id, frame, request);
1398                    log_slow_control_dispatch(
1399                        dispatch_started_at,
1400                        op,
1401                        ctx.connection_id,
1402                        corr,
1403                        None,
1404                    );
1405                    return result;
1406                }
1407
1408                if is_known_module_request_op(&frame.body) {
1409                    let is_agents = serde_json::from_slice::<ControlOpProbe>(&frame.body)
1410                        .is_ok_and(|probe| probe.op == "supervisor.agent_commands");
1411                    let code = if is_agents {
1412                        "not_supervised"
1413                    } else if op
1414                        .as_ref()
1415                        .is_some_and(|probe| probe.op == subc_protocol::scope::ROUTE_AUTHORIZE_OP)
1416                    {
1417                        error_codes::ROUTE_AUTHORIZE_NOT_PERMITTED
1418                    } else {
1419                        "not_registered"
1420                    };
1421                    return Ok(vec![control_error_frame(
1422                        &frame,
1423                        code,
1424                        "module-originated control requests require the module's own registered connection",
1425                    )?]);
1426                }
1427
1428                let request = match parse_client_control_request(&frame.body) {
1429                    Ok(request) => request,
1430                    Err((err, ControlRequestBodyError::UnknownOp)) => {
1431                        return Ok(vec![control_error_frame(
1432                            &frame,
1433                            "unknown_control_op",
1434                            format!("unknown client control op: {err}"),
1435                        )?])
1436                    }
1437                    Err((err, ControlRequestBodyError::InvalidBody)) => {
1438                        return Ok(vec![control_error_frame(
1439                            &frame,
1440                            "invalid_control_body",
1441                            format!("malformed client control body: {err}"),
1442                        )?])
1443                    }
1444                };
1445                let op = client_control_request_op(&request);
1446                let corr = frame.header.corr;
1447                log_control_dispatch_arrival(op, ctx.connection_id, corr);
1448                let mut route_open_timings = (op == ops::ROUTE_OPEN).then(RouteOpenTimings::new);
1449                #[cfg(test)]
1450                if let Some(delay) = self.control_dispatch_delay {
1451                    tokio::time::sleep(delay).await;
1452                }
1453                let result = self
1454                    .handle_client_control_request(ctx, frame, request, &mut route_open_timings)
1455                    .await;
1456                if let Some(timings) = route_open_timings.as_mut() {
1457                    timings.finish();
1458                }
1459                log_slow_control_dispatch(
1460                    dispatch_started_at,
1461                    op,
1462                    ctx.connection_id,
1463                    corr,
1464                    route_open_timings.as_ref(),
1465                );
1466                result
1467            }
1468            FrameType::Push => {
1469                let Some(endpoint) = self
1470                    .forwarding
1471                    .module_endpoint_for_connection(ctx.connection_id)
1472                    .map_err(RouterError::Forwarding)?
1473                else {
1474                    return Ok(vec![control_error_frame(
1475                        &frame,
1476                        "unsupported_control_frame",
1477                        "client-originated channel-0 PUSH is not supported",
1478                    )?]);
1479                };
1480                self.handle_status_update(endpoint, frame)
1481            }
1482            FrameType::Response | FrameType::Error
1483                if self
1484                    .forwarding
1485                    .module_endpoint_for_connection(ctx.connection_id)
1486                    .map_err(RouterError::Forwarding)?
1487                    .is_some() =>
1488            {
1489                self.handle_module_relay_response(ctx.connection_id, frame)
1490            }
1491            ty => Ok(vec![control_error_frame(
1492                &frame,
1493                "unsupported_control_frame",
1494                format!("unsupported channel-0 frame {ty:?}"),
1495            )?]),
1496        }
1497    }
1498
1499    #[cfg(test)]
1500    fn pause_cleanup_for_test(&self, stage: u8) {
1501        let mut slot = self.cleanup_pause.lock().unwrap_or_else(|p| p.into_inner());
1502        if slot.as_ref().is_some_and(|(at, _)| *at == stage) {
1503            let (_, (reached, release)) = slot.take().unwrap();
1504            drop(slot);
1505            let _ = reached.send(());
1506            let _ = release.recv_timeout(Duration::from_secs(5));
1507        }
1508    }
1509
1510    /// Run `hook` once, in the next `route.open` that attests a launch nonce,
1511    /// right after the nonce is resolved.
1512    #[cfg(all(test, unix, feature = "test-support"))]
1513    pub(crate) fn after_nonce_attestation_for_test(&self, hook: impl FnOnce() + Send + 'static) {
1514        *self
1515            .after_nonce_attestation
1516            .lock()
1517            .unwrap_or_else(|p| p.into_inner()) = Some(Box::new(hook));
1518    }
1519
1520    #[cfg(test)]
1521    pub(super) fn pause_after_nonce_attestation_for_test(&self) {
1522        let hook = self
1523            .after_nonce_attestation
1524            .lock()
1525            .unwrap_or_else(|p| p.into_inner())
1526            .take();
1527        if let Some(hook) = hook {
1528            hook();
1529        }
1530    }
1531
1532    pub fn cleanup_connection(
1533        &self,
1534        connection_id: ConnectionId,
1535    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1536        // The server loop joins its offloaded request tasks (route opens,
1537        // privileged requests and activity reads) before this cleanup runs, and
1538        // inline dispatch has ended. Two kinds of work are not joined. Agent
1539        // command declarations run on their queue's detached worker, so the
1540        // queue is closed first: every declaration still queued or validating
1541        // has its commit fence cancelled before anything below can change how
1542        // the connection resolves. A HELLO whose reader was dropped keeps
1543        // running on its blocking thread. It carries the channel spawn its
1544        // reader resolved at ingress instead of re-reading the index forgotten
1545        // below, so it is still judged as that channel's HELLO: the retired
1546        // spawn refuses it before it records anything, and a channel HELLO
1547        // never records a launch nonce, so it cannot leave this connection any
1548        // nonce authority.
1549        self.agent_declarations.close(connection_id);
1550        self.close_catalog_subscriptions(connection_id);
1551        self.close_config_settings_subscriptions(connection_id);
1552        self.close_scope_subscriptions(connection_id);
1553        #[cfg(test)]
1554        self.pause_cleanup_for_test(0);
1555        if let Some(spawn) = self.supervisor.registration_spawn(connection_id) {
1556            spawn.retire_registration_channel();
1557        }
1558        self.supervisor
1559            .forget_registration_connection(connection_id);
1560        #[cfg(test)]
1561        self.pause_cleanup_for_test(1);
1562        self.local_connections
1563            .lock()
1564            .unwrap_or_else(|p| p.into_inner())
1565            .remove(&connection_id);
1566        self.caller_endpoints
1567            .lock()
1568            .unwrap_or_else(|p| p.into_inner())
1569            .remove(&connection_id);
1570        self.route_openers
1571            .lock()
1572            .unwrap_or_else(|p| p.into_inner())
1573            .remove(&connection_id);
1574        self.build_class_warned
1575            .lock()
1576            .unwrap_or_else(|p| p.into_inner())
1577            .remove(&connection_id);
1578        // Retire the capture before its published facts so an in-flight
1579        // verification cannot recreate them after cleanup.
1580        self.captured_peers
1581            .lock()
1582            .unwrap_or_else(|p| p.into_inner())
1583            .remove(&connection_id);
1584        self.observed_peers
1585            .lock()
1586            .unwrap_or_else(|p| p.into_inner())
1587            .remove(&connection_id);
1588        self.config_desktop_stamps
1589            .lock()
1590            .unwrap_or_else(|p| p.into_inner())
1591            .remove(&connection_id);
1592        self.operator_apps
1593            .lock()
1594            .unwrap_or_else(|p| p.into_inner())
1595            .remove(&connection_id);
1596        self.forwarding
1597            .operator_confirms()
1598            .connection_closed(connection_id);
1599        let cleanup = self.cleanup_connection_with_end_reason(
1600            connection_id,
1601            RegistrationEndReason::ConnectionClosed,
1602        );
1603        // A draining writer can still be reached by a route until forwarding
1604        // cleanup finishes. Keep its claim sink visible to launch retirement.
1605        self.claims.connection_closed(connection_id);
1606        cleanup
1607    }
1608
1609    fn cleanup_connection_with_end_reason(
1610        &self,
1611        connection_id: ConnectionId,
1612        requested_reason: RegistrationEndReason,
1613    ) -> Result<Vec<crate::registry::ModuleRegistration>, RegistryError> {
1614        #[cfg(test)]
1615        if let Some(pause) = self
1616            .activity_request_pause
1617            .lock()
1618            .unwrap()
1619            .as_ref()
1620            .filter(|pause| pause.connection == connection_id)
1621        {
1622            pause
1623                .cleanup_started
1624                .store(true, std::sync::atomic::Ordering::Release);
1625        }
1626        if let Some(runtime) = &self.config_runtime {
1627            runtime.disconnected(connection_id);
1628        }
1629        self.agent_declarations.close(connection_id);
1630        let end_reason = if requested_reason == RegistrationEndReason::ConnectionClosed {
1631            self.registry
1632                .get_module_by_connection(connection_id)?
1633                .and_then(|registration| self.supervisor.get(&registration.manifest.module_id))
1634                .and_then(|module| module.registration_end_reason().ok().flatten())
1635                .unwrap_or(requested_reason)
1636        } else {
1637            requested_reason
1638        };
1639        let crash_closed = self
1640            .registry
1641            .get_module_by_connection(connection_id)?
1642            .and_then(|registration| {
1643                self.forwarding
1644                    .module_endpoint_for_connection(connection_id)
1645                    .ok()
1646                    .flatten()
1647                    .and_then(|endpoint| self.forwarding.endpoint_routes(endpoint).ok())
1648                    .map(|routes| (registration.manifest.module_id, routes))
1649            });
1650        let crash_closed = crash_closed.map(|(module_id, routes)| {
1651            let terminal = match self.supervisor.get(&module_id) {
1652                None => false,
1653                Some(module) => match module.will_recover_after_connection_loss() {
1654                    Ok(will_recover) => !will_recover,
1655                    Err(err) => {
1656                        warn!(
1657                            %module_id,
1658                            error = %err,
1659                            "failed to read crash recovery verdict; reporting non-terminal conservatively"
1660                        );
1661                        false
1662                    }
1663                },
1664            };
1665            // The forwarding table gates all providers at the start of daemon
1666            // shutdown, before their connections are closed. An ordinary
1667            // module disconnect still reports crash if that gate is not set.
1668            let (reason, drained) = match self
1669                .forwarding
1670                .daemon_drain_result_for_connection(connection_id)
1671            {
1672                Ok(Some(drained)) => (RouteCloseReason::Restart, drained),
1673                Ok(None) => (RouteCloseReason::Crash, false),
1674                Err(err) => {
1675                    warn!(error = %err, "failed to read daemon drain state; reporting crash conservatively");
1676                    (RouteCloseReason::Crash, false)
1677                }
1678            };
1679            (module_id, routes, reason, drained, terminal)
1680        });
1681        let registrations = self.deregister_connection(connection_id, end_reason);
1682        // Read before teardown: the spawn whose registration this connection
1683        // was. Its registration ending is an authority change for it.
1684        let ended_authority = self
1685            .forwarding
1686            .target_authority_for_connection(connection_id)
1687            .ok()
1688            .flatten();
1689        let cleanup = if crash_closed.is_some() {
1690            self.forwarding.cleanup_connection_counted(connection_id)
1691        } else {
1692            // A module connection's teardown needs the count of abandoned
1693            // route.bind relays for its route.closed notice below. Any other
1694            // connection, such as a client's, sends no such notice and needs
1695            // only its routes released, so it uses the route-only wrapper and
1696            // reports zero.
1697            self.forwarding
1698                .cleanup_connection(connection_id)
1699                .map(|released| crate::forwarding::ConnectionCleanup {
1700                    released,
1701                    abandoned_relays: 0,
1702                })
1703        };
1704        // The route.closed push waits for forwarding teardown because only
1705        // teardown knows how many pending route.bind relays it aborted. It still
1706        // goes out before the GOODBYEs for the released routes, and its targets
1707        // were captured above, before teardown removed those routes.
1708        if let Some((module_id, routes, reason, drained, terminal)) = crash_closed {
1709            let abandoned = cleanup
1710                .as_ref()
1711                .map_or(0, |cleanup| cleanup.abandoned_relays);
1712            send_route_control_pushes(
1713                &self.forwarding,
1714                routes,
1715                ClientControlPush::RouteClosed {
1716                    module_id,
1717                    channels: Vec::new(),
1718                    reason,
1719                    drained,
1720                    abandoned,
1721                    excluded_subscriptions: 0,
1722                    terminal: Some(terminal),
1723                },
1724            );
1725        }
1726        if let Ok(cleanup) = cleanup {
1727            self.emit_route_goodbyes(cleanup.released);
1728        }
1729        if let Some(record) = ended_authority {
1730            self.change_spawn_authority(&record);
1731        }
1732        // Signal the registration-release watch only now that BOTH registry and
1733        // forwarding teardown are done, so a supervisor waiting to spawn a
1734        // replacement never observes release while old routes still exist.
1735        if matches!(&registrations, Ok(r) if !r.is_empty()) {
1736            crate::supervise::notify_registration_release();
1737            self.capability_evaluator.wake_deadline_loop();
1738            self.refresh_capability_requirements();
1739        }
1740        self.supervisor.remove_spawn_subscribers(connection_id);
1741        self.activity_streams
1742            .lock()
1743            .unwrap_or_else(|p| p.into_inner())
1744            .retain(|(id, _), task| {
1745                if *id == connection_id {
1746                    task.abort();
1747                    false
1748                } else {
1749                    true
1750                }
1751            });
1752        // Sync authority dies with its connection, so the owner's next
1753        // connection can take it; the owner's scopes stay as they are.
1754        self.hello_launch_nonces
1755            .lock()
1756            .unwrap_or_else(|poisoned| poisoned.into_inner())
1757            .forget(connection_id);
1758        self.scopes
1759            .write()
1760            .unwrap_or_else(|poisoned| poisoned.into_inner())
1761            .release_connection(connection_id);
1762        registrations
1763    }
1764
1765    pub(crate) fn handle_route_goodbye(
1766        &self,
1767        connection_id: ConnectionId,
1768        route_channel: u16,
1769        route_epoch: u32,
1770    ) -> Result<bool, RouterError> {
1771        debug!(
1772            connection_id = connection_id.get(),
1773            route_channel, route_epoch, "handling route GOODBYE"
1774        );
1775        let RouteRelease::Removed(released_route) = self
1776            .forwarding
1777            .release_client_route(connection_id, route_channel, route_epoch)
1778            .map_err(RouterError::Forwarding)?
1779        else {
1780            return Ok(false);
1781        };
1782        self.emit_route_goodbyes(vec![released_route]);
1783        Ok(true)
1784    }
1785
1786    fn emit_route_goodbyes(&self, released_routes: Vec<GoodbyeTarget>) {
1787        scope_expiry::ScopeExpiryContext::new(self).emit_route_goodbyes(released_routes);
1788    }
1789
1790    async fn handle_client_control_request(
1791        &self,
1792        ctx: &RouteCtx,
1793        frame: Frame,
1794        request: ClientControlRequest,
1795        route_open_timings: &mut Option<RouteOpenTimings>,
1796    ) -> Result<Vec<Frame>, RouterError> {
1797        if let Some(owner) = &self.config_runtime {
1798            let module = match &request {
1799                ClientControlRequest::SupervisorRestart { module_id, .. }
1800                | ClientControlRequest::SupervisorReload { module_id }
1801                | ClientControlRequest::SupervisorSwap { module_id, .. }
1802                | ClientControlRequest::SupervisorSetEnabled {
1803                    module_id,
1804                    enabled: true,
1805                } => Some(module_id.as_str()),
1806                _ => None,
1807            };
1808            let rescan = matches!(
1809                &request,
1810                ClientControlRequest::SupervisorRescan { preview: false }
1811                    | ClientControlRequest::SupervisorRescanChecked { preview: false, .. }
1812            );
1813            let held = if module.is_some() || rescan {
1814                let module = module.map(str::to_owned);
1815                owner
1816                    .on_blocking(move |owner| owner.checked_admission_hold(module.as_deref()))
1817                    .await
1818            } else {
1819                Ok(())
1820            };
1821            if let Err(error) = held {
1822                if error.code != "config_delivery_deferred" {
1823                    let code = if error.code == "store_tampered" {
1824                        "store_tampered"
1825                    } else {
1826                        "config_gated"
1827                    };
1828                    return Ok(vec![control_error_frame(&frame, code, error.detail)?]);
1829                }
1830            }
1831        }
1832        if let Some(operation) = privileged_operation(&request) {
1833            #[cfg(any(target_os = "macos", target_os = "linux"))]
1834            if operation == PrivilegedOperation::UpgradeInPlace {
1835                if let Some(upgrade) = &self.upgrade {
1836                    if !upgrade.wait_for_identity().await {
1837                        return Ok(vec![control_error_frame(
1838                            &frame,
1839                            subc_control::upgrade_in_place::UPGRADE_IN_PLACE_UNSUPPORTED,
1840                            "running executable identity is unavailable",
1841                        )?]);
1842                    }
1843                }
1844            }
1845            let caller = self.resolve_caller(ctx.connection_id).await;
1846            let op = client_control_request_op(&request);
1847            let text = prompt_text(operation, &caller);
1848            match if operation == PrivilegedOperation::UpgradeInPlace {
1849                PrivilegedOperatorPrompt::Enforce
1850            } else {
1851                self.privileged_operator_prompt
1852            } {
1853                PrivilegedOperatorPrompt::Log => {
1854                    info!(target: "subc_daemon::privileged_prompt", operation = op,
1855                        target = ?operation, caller = %caller.description(), summary = %text,
1856                        "privileged request would prompt the operator");
1857                }
1858                PrivilegedOperatorPrompt::Enforce => {
1859                    let key =
1860                        crate::operator_confirm::DeclineKey::for_caller(&caller, ctx.connection_id);
1861                    let shortcut = if operation == PrivilegedOperation::UpgradeInPlace {
1862                        None
1863                    } else {
1864                        self.operator_shortcut_stamp(ctx.connection_id)
1865                            .await
1866                            .map(|stamp| {
1867                                self.shortcut_context(Some(stamp), None, None, ctx.connection_id)
1868                            })
1869                    };
1870                    let outcome = self
1871                        .forwarding
1872                        .operator_confirms()
1873                        .approve_privileged_with_shortcut(
1874                            ctx,
1875                            &frame,
1876                            op,
1877                            text,
1878                            caller.description(),
1879                            key,
1880                            shortcut,
1881                        )
1882                        .await;
1883                    if outcome.code != "confirmed" {
1884                        return Ok(vec![outcome.frame(&frame)]);
1885                    }
1886                }
1887            }
1888        }
1889        match request {
1890            ClientControlRequest::DaemonUpgradeInPlace { executable_sha256 } => {
1891                self.upgrade_in_place(ctx, frame, executable_sha256)
1892            }
1893            ClientControlRequest::DaemonShutdownIntent { intent } => {
1894                self.daemon_restart_intent(frame, intent).await
1895            }
1896            // Clients probe capabilities here before opening routes. A cold
1897            // boot hash is optional metadata, not a prerequisite to serving.
1898            ClientControlRequest::ServerDescribe {} => self.handle_server_describe(frame),
1899            ClientControlRequest::PolicyRoot(_)
1900            | ClientControlRequest::PolicyRootSet(_)
1901            | ClientControlRequest::PolicyRootRecover(_) => {
1902                unreachable!("policy root ops dispatch before the client-only path")
1903            }
1904            ClientControlRequest::CatalogList { module_id } => {
1905                self.handle_catalog_list(frame, module_id)
1906            }
1907            ClientControlRequest::RouteOpen {
1908                target,
1909                identity,
1910                consumer_identity,
1911                consumer_capabilities,
1912                role_versions,
1913                busy_refusals,
1914                admission_facts,
1915                scope,
1916                ..
1917            } => {
1918                let extensions = match serde_json::from_slice::<subc_control::RouteOpenRequestExt>(
1919                    &frame.body,
1920                ) {
1921                    Ok(extensions) => extensions,
1922                    Err(err) => {
1923                        return Ok(vec![control_error_frame(
1924                            &frame,
1925                            "invalid_control_body",
1926                            format!("malformed route.open extensions: {err}"),
1927                        )?]);
1928                    }
1929                };
1930                self.handle_route_open(
1931                    ctx,
1932                    frame,
1933                    RouteOpenRequest {
1934                        target,
1935                        identity,
1936                        consumer_identity,
1937                        consumer_capabilities,
1938                        role_versions,
1939                        busy_refusals,
1940                        admission_facts,
1941                        scope,
1942                        accepts_close_reasons: extensions.accepts_close_reasons,
1943                    },
1944                    route_open_timings.get_or_insert_with(RouteOpenTimings::new),
1945                )
1946                .await
1947            }
1948            ClientControlRequest::RoutePoll {
1949                route_channel,
1950                route_epoch,
1951                kind,
1952            } => self.handle_route_poll(ctx, frame, route_channel, route_epoch, kind),
1953            ClientControlRequest::SupervisorList {} => {
1954                let Ok(permit) = Arc::clone(&self.list_admission).try_acquire_owned() else {
1955                    self.agent_declarations.refuse(
1956                        self,
1957                        ctx,
1958                        control_error_frame(
1959                            &frame,
1960                            "busy",
1961                            "supervisor list work is at capacity; retry",
1962                        )?,
1963                    );
1964                    return Ok(Vec::new());
1965                };
1966                // Filesystem-backed diagnostics must not hold up this connection's reader.
1967                let handler = self.clone();
1968                let sink = ctx.egress.clone();
1969                tokio::spawn(
1970                    async move {
1971                        let _permit = permit;
1972                        let result = handler.handle_supervisor_list(frame.clone()).await;
1973                        let replies = match result {
1974                            Ok(replies) => replies,
1975                            Err(error) => {
1976                                control_error_frame(&frame, "backend_error", error.to_string())
1977                                    .into_iter()
1978                                    .collect()
1979                            }
1980                        };
1981                        for reply in replies {
1982                            if !matches!(
1983                                tokio::time::timeout(Duration::from_millis(200), sink.send(reply))
1984                                    .await,
1985                                Ok(Ok(()))
1986                            ) {
1987                                break;
1988                            }
1989                        }
1990                    }
1991                    .with_current_subscriber(),
1992                );
1993                Ok(Vec::new())
1994            }
1995            ClientControlRequest::SupervisorSpawnSnapshot {} => {
1996                self.handle_supervisor_spawn_snapshot(frame)
1997            }
1998            ClientControlRequest::SupervisorSpawnSubscribe { since } => {
1999                self.handle_supervisor_spawn_subscribe(ctx, frame, since)
2000            }
2001            ClientControlRequest::SupervisorRestart {
2002                module_id,
2003                drain_timeout_ms,
2004            } => {
2005                self.log_supervisor_request_received(
2006                    ctx,
2007                    frame.header.corr,
2008                    ops::SUPERVISOR_RESTART,
2009                    Some(&module_id),
2010                    None,
2011                )?;
2012                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2013                self.handle_supervisor_restart(frame, module_id, drain_timeout_ms, requester)
2014                    .await
2015            }
2016            ClientControlRequest::SupervisorSwap {
2017                module_id,
2018                ready_timeout_ms,
2019            } => {
2020                self.log_supervisor_request_received(
2021                    ctx,
2022                    frame.header.corr,
2023                    ops::SUPERVISOR_SWAP,
2024                    Some(&module_id),
2025                    None,
2026                )?;
2027                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2028                self.handle_supervisor_swap(frame, module_id, ready_timeout_ms, requester)
2029                    .await
2030            }
2031            ClientControlRequest::SupervisorReload { module_id } => {
2032                self.log_supervisor_request_received(
2033                    ctx,
2034                    frame.header.corr,
2035                    ops::SUPERVISOR_RELOAD,
2036                    Some(&module_id),
2037                    None,
2038                )?;
2039                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2040                self.handle_supervisor_reload(frame, module_id, requester)
2041                    .await
2042            }
2043            ClientControlRequest::SupervisorRescan { preview } => {
2044                if !preview {
2045                    self.log_supervisor_request_received(
2046                        ctx,
2047                        frame.header.corr,
2048                        ops::SUPERVISOR_RESCAN,
2049                        None,
2050                        None,
2051                    )?;
2052                }
2053                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2054                let operation = self.handle_supervisor_rescan(
2055                    frame,
2056                    if preview {
2057                        RescanMode::Preview
2058                    } else {
2059                        RescanMode::Execute
2060                    },
2061                    requester,
2062                );
2063                self.observe_control_wait(ctx, None, ops::SUPERVISOR_RESCAN, operation)
2064                    .await
2065            }
2066            ClientControlRequest::SupervisorRescanChecked {
2067                preview,
2068                candidate,
2069                expect,
2070            } => {
2071                self.observe_control_wait(
2072                    ctx,
2073                    None,
2074                    ops::SUPERVISOR_RESCAN,
2075                    self.handle_supervisor_rescan_checked(ctx, frame, preview, candidate, expect),
2076                )
2077                .await
2078            }
2079            ClientControlRequest::SupervisorReleaseReserved { module_id } => {
2080                self.log_supervisor_request_received(
2081                    ctx,
2082                    frame.header.corr,
2083                    ops::SUPERVISOR_RELEASE_RESERVED,
2084                    Some(&module_id),
2085                    None,
2086                )?;
2087                self.handle_supervisor_release_reserved(frame, module_id)
2088                    .await
2089            }
2090            ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
2091                self.log_supervisor_request_received(
2092                    ctx,
2093                    frame.header.corr,
2094                    ops::SUPERVISOR_SET_ENABLED,
2095                    Some(&module_id),
2096                    Some(enabled),
2097                )?;
2098                let requester = self.supervisor_requester(ctx, frame.header.corr)?;
2099                self.handle_supervisor_set_enabled(frame, module_id, enabled, requester)
2100                    .await
2101            }
2102            ClientControlRequest::SupervisorHealthProbe { module_id } => {
2103                self.handle_supervisor_health_probe(ctx, frame, module_id)
2104                    .await
2105            }
2106            ClientControlRequest::SupervisorHealth {} => self.handle_supervisor_health(frame),
2107            ClientControlRequest::SupervisorRoutes { module_id } => {
2108                self.handle_supervisor_routes(frame, module_id)
2109            }
2110            ClientControlRequest::SupervisorProvenance { module_id } => {
2111                self.handle_supervisor_provenance(ctx, frame, module_id)
2112                    .await
2113            }
2114            ClientControlRequest::SupervisorStderrTail {
2115                module_id,
2116                max_lines,
2117                max_bytes,
2118            } => self.handle_supervisor_stderr_tail(frame, module_id, max_lines, max_bytes),
2119            ClientControlRequest::SupervisorTerminals { module_id } => {
2120                self.handle_supervisor_terminals(ctx, frame, module_id)
2121                    .await
2122            }
2123        }
2124    }
2125
2126    /// Explicit test-only phone policy; daemon configuration cannot select it.
2127    #[cfg(any(test, feature = "test-support"))]
2128    pub fn with_test_phone_shortcut(mut self, enabled: bool) -> Self {
2129        self.operator_app_policy.phone_enabled = enabled;
2130        self
2131    }
2132
2133    fn handle_goodbye(&self, connection_id: ConnectionId) -> Result<Vec<Frame>, RouterError> {
2134        debug!(connection_id = connection_id.get(), "handling GOODBYE");
2135        // GOODBYE ends the connection's logical session even when its socket
2136        // stays open. Use disconnect teardown so verdicts, client notices and
2137        // scope authority are released at the same lifecycle boundary.
2138        self.cleanup_connection_with_end_reason(
2139            connection_id,
2140            RegistrationEndReason::ExplicitGoodbye,
2141        )
2142        .map_err(|err| RouterError::backend(0, 0, err.to_string()))?;
2143        Ok(Vec::new())
2144    }
2145}
2146
2147impl Default for ControlHandler {
2148    fn default() -> Self {
2149        Self::new(Arc::new(Registry::default()))
2150    }
2151}
2152
2153impl crate::supervise::SwapPromotionObserver for ControlHandler {
2154    fn swap_promoted(&self, registration: &crate::registry::ModuleRegistration) {
2155        self.apply_registration_capabilities(registration);
2156    }
2157}
2158
2159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2160enum ControlRequestBodyError {
2161    UnknownOp,
2162    InvalidBody,
2163}
2164
2165#[derive(Debug, Deserialize)]
2166struct ControlOpProbe {
2167    op: String,
2168}
2169
2170fn log_control_dispatch_arrival(op: &'static str, connection_id: ConnectionId, corr: u64) {
2171    debug!(
2172        op = %op,
2173        connection_id = connection_id.get(),
2174        corr,
2175        "control dispatch"
2176    );
2177}
2178
2179fn log_slow_control_dispatch(
2180    dispatch_started_at: Option<StdInstant>,
2181    op: &'static str,
2182    connection_id: ConnectionId,
2183    corr: u64,
2184    route_open_timings: Option<&RouteOpenTimings>,
2185) {
2186    let Some(dispatch_started_at) = dispatch_started_at else {
2187        return;
2188    };
2189    // Use the same monotonic clock as the phase timers and relay deadline.
2190    let elapsed = Instant::from_std(dispatch_started_at).elapsed();
2191    if elapsed >= SLOW_CONTROL_DISPATCH_THRESHOLD {
2192        if let Some(timings) = route_open_timings {
2193            warn!(
2194                op = %op,
2195                connection_id = connection_id.get(),
2196                corr,
2197                elapsed_ms = elapsed.as_millis() as u64,
2198                module_id = ?timings.module_id,
2199                principal = %timings.principal,
2200                admission_ms = timings.admission.as_millis() as u64,
2201                project_root_ms = timings.project_root.as_millis() as u64,
2202                egress_reservation_ms = timings.egress_reservation.as_millis() as u64,
2203                bind_send_ms = timings.bind_send.as_millis() as u64,
2204                bind_ack_wait_ms = timings.bind_ack_wait.as_millis() as u64,
2205                "slow control dispatch"
2206            );
2207            return;
2208        }
2209        warn!(
2210            op = %op,
2211            connection_id = connection_id.get(),
2212            corr,
2213            elapsed_ms = elapsed.as_millis() as u64,
2214            "slow control dispatch"
2215        );
2216    }
2217}
2218
2219/// A test stand-in for the OS caller lookup, given the recorded endpoints.
2220#[cfg(test)]
2221type TestCallerLookup =
2222    Arc<dyn Fn(Option<(SocketAddr, SocketAddr)>) -> CallerIdentity + Send + Sync>;
2223
2224/// Every new client operation needs an explicit privilege decision here.
2225fn privileged_operation(request: &impl PrivilegedRequest) -> Option<PrivilegedOperation<'_>> {
2226    request.privileged_operation()
2227}
2228
2229trait PrivilegedRequest {
2230    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>>;
2231}
2232
2233impl PrivilegedRequest for ClientControlRequest {
2234    fn privileged_operation(&self) -> Option<PrivilegedOperation<'_>> {
2235        let request = self;
2236        match request {
2237        ClientControlRequest::SupervisorRestart { module_id, .. } => {
2238            Some(PrivilegedOperation::Restart { module_id })
2239        }
2240        ClientControlRequest::DaemonUpgradeInPlace { .. } => Some(PrivilegedOperation::UpgradeInPlace),
2241        ClientControlRequest::SupervisorSwap { module_id, .. } => {
2242            Some(PrivilegedOperation::Swap { module_id })
2243        }
2244        ClientControlRequest::SupervisorReload { module_id } => {
2245            Some(PrivilegedOperation::Reload { module_id })
2246        }
2247        ClientControlRequest::SupervisorRescan { preview } => {
2248            if *preview {
2249                None
2250            } else {
2251                Some(PrivilegedOperation::Rescan)
2252            }
2253        }
2254        // Only the well-formed apply can change state, so only it needs approval.
2255        ClientControlRequest::SupervisorRescanChecked {
2256            preview,
2257            candidate,
2258            expect,
2259        } => (!*preview && candidate.is_none() && expect.is_some())
2260            .then_some(PrivilegedOperation::Rescan),
2261        ClientControlRequest::SupervisorSetEnabled { module_id, enabled } => {
2262            Some(PrivilegedOperation::SetEnabled {
2263                module_id,
2264                enabled: *enabled,
2265            })
2266        }
2267        ClientControlRequest::SupervisorReleaseReserved { module_id } => {
2268            Some(PrivilegedOperation::ReleaseReserved { module_id })
2269        }
2270        ClientControlRequest::ServerDescribe {}
2271        | ClientControlRequest::PolicyRoot(_)
2272        | ClientControlRequest::PolicyRootSet(_)
2273        | ClientControlRequest::PolicyRootRecover(_)
2274        // A restart announcement cannot stop anything and requires no prompt.
2275        | ClientControlRequest::DaemonShutdownIntent { .. }
2276        | ClientControlRequest::CatalogList { .. }
2277        | ClientControlRequest::RouteOpen { .. }
2278        | ClientControlRequest::RoutePoll { .. }
2279        | ClientControlRequest::SupervisorList {}
2280        | ClientControlRequest::SupervisorHealth {}
2281        | ClientControlRequest::SupervisorHealthProbe { .. }
2282        | ClientControlRequest::SupervisorRoutes { .. }
2283        | ClientControlRequest::SupervisorProvenance { .. }
2284        | ClientControlRequest::SupervisorStderrTail { .. }
2285        | ClientControlRequest::SupervisorTerminals { .. }
2286        | ClientControlRequest::SupervisorSpawnSnapshot {}
2287        | ClientControlRequest::SupervisorSpawnSubscribe { .. } => None,
2288    }
2289    }
2290}
2291
2292fn client_control_request_op(request: &ClientControlRequest) -> &'static str {
2293    match request {
2294        ClientControlRequest::PolicyRoot(_) => subc_protocol::policy_root::GET_OP,
2295        ClientControlRequest::PolicyRootSet(_) => subc_control::policy_root::SET_OP,
2296        ClientControlRequest::PolicyRootRecover(_) => subc_control::policy_root::RECOVER_OP,
2297        ClientControlRequest::DaemonShutdownIntent { .. } => ops::DAEMON_SHUTDOWN_INTENT,
2298        ClientControlRequest::DaemonUpgradeInPlace { .. } => ops::DAEMON_UPGRADE_IN_PLACE,
2299        ClientControlRequest::ServerDescribe {} => ops::SERVER_DESCRIBE,
2300        ClientControlRequest::SupervisorProvenance { .. } => ops::SUPERVISOR_PROVENANCE,
2301        ClientControlRequest::CatalogList { .. } => ops::CATALOG_LIST,
2302        ClientControlRequest::RouteOpen { .. } => ops::ROUTE_OPEN,
2303        ClientControlRequest::RoutePoll { .. } => ops::ROUTE_POLL,
2304        ClientControlRequest::SupervisorList {} => ops::SUPERVISOR_LIST,
2305        ClientControlRequest::SupervisorSpawnSnapshot {} => ops::SUPERVISOR_SPAWN_SNAPSHOT,
2306        ClientControlRequest::SupervisorSpawnSubscribe { .. } => ops::SUPERVISOR_SPAWN_SUBSCRIBE,
2307        ClientControlRequest::SupervisorRestart { .. } => ops::SUPERVISOR_RESTART,
2308        ClientControlRequest::SupervisorSwap { .. } => ops::SUPERVISOR_SWAP,
2309        ClientControlRequest::SupervisorReload { .. } => ops::SUPERVISOR_RELOAD,
2310        ClientControlRequest::SupervisorRescan { .. } => ops::SUPERVISOR_RESCAN,
2311        ClientControlRequest::SupervisorRescanChecked { .. } => ops::SUPERVISOR_RESCAN_CHECKED,
2312        ClientControlRequest::SupervisorReleaseReserved { .. } => ops::SUPERVISOR_RELEASE_RESERVED,
2313        ClientControlRequest::SupervisorSetEnabled { .. } => ops::SUPERVISOR_SET_ENABLED,
2314        ClientControlRequest::SupervisorHealthProbe { .. } => ops::SUPERVISOR_HEALTH_PROBE,
2315        ClientControlRequest::SupervisorHealth {} => ops::SUPERVISOR_HEALTH,
2316        ClientControlRequest::SupervisorRoutes { .. } => ops::SUPERVISOR_ROUTES,
2317        ClientControlRequest::SupervisorStderrTail { .. } => ops::SUPERVISOR_STDERR_TAIL,
2318        ClientControlRequest::SupervisorTerminals { .. } => ops::SUPERVISOR_TERMINALS,
2319    }
2320}
2321
2322fn parse_client_control_request(
2323    body: &[u8],
2324) -> Result<ClientControlRequest, (serde_json::Error, ControlRequestBodyError)> {
2325    serde_json::from_slice::<ClientControlRequest>(body).map_err(|err| {
2326        let classification = match serde_json::from_slice::<ControlOpProbe>(body) {
2327            Ok(probe)
2328                if SUBC_CONTROL_OPS.contains(&probe.op.as_str())
2329                    || SUBC_UNADVERTISED_CONTROL_OPS.contains(&probe.op.as_str()) =>
2330            {
2331                ControlRequestBodyError::InvalidBody
2332            }
2333            Ok(_) => ControlRequestBodyError::UnknownOp,
2334            Err(_) => ControlRequestBodyError::InvalidBody,
2335        };
2336        (err, classification)
2337    })
2338}
2339
2340fn pong(frame: &Frame) -> Result<Frame, RouterError> {
2341    Frame::build_with_version(
2342        response_version(frame),
2343        FrameType::Pong,
2344        frame.header.flags,
2345        0,
2346        0,
2347        frame.header.corr,
2348        Vec::new(),
2349    )
2350    .map_err(RouterError::FrameBuild)
2351}
2352
2353pub(crate) fn control_error_frame(
2354    frame: &Frame,
2355    code: &'static str,
2356    message: impl Into<String>,
2357) -> Result<Frame, RouterError> {
2358    control_error_body_frame(
2359        frame,
2360        ErrorBody {
2361            code: code.to_string(),
2362            message: message.into(),
2363            detail: None,
2364        },
2365    )
2366}
2367
2368/// A channel-0 ERROR for a refusal the daemon decided itself: every
2369/// route.open refusal, the drain `module_reloading` and scope-change/end
2370/// bodies, spawn-subscription and supervisor refusals. Carries the
2371/// daemon-origin bit, which is what lets a client treat `module_reloading`
2372/// as proof that its request never reached a module. Response, push,
2373/// goodbye and relay-request frames keep the plain control flags in their
2374/// own builders.
2375pub(crate) fn control_error_body_frame(
2376    frame: &Frame,
2377    error: ErrorBody,
2378) -> Result<Frame, RouterError> {
2379    control_error_frame_with_flags(frame, error, daemon_error_flags())
2380}
2381
2382/// A channel-0 ERROR relaying a module's own rejection body unchanged: a
2383/// refused route.bind answered as a route.open refusal, or a refused
2384/// module-control RPC. Plain control flags — the code and message are
2385/// module-chosen, so the frame must not claim daemon authorship, even when
2386/// the module picks a daemon code like `module_reloading`.
2387fn control_relayed_error_body_frame(frame: &Frame, error: ErrorBody) -> Result<Frame, RouterError> {
2388    control_error_frame_with_flags(frame, error, control_flags())
2389}
2390
2391fn control_error_frame_with_flags(
2392    frame: &Frame,
2393    error: ErrorBody,
2394    flags: Flags,
2395) -> Result<Frame, RouterError> {
2396    let body = serde_json::to_vec(&error).map_err(|err| {
2397        RouterError::backend(
2398            0,
2399            frame.header.corr,
2400            format!("failed to encode control ERROR: {err}"),
2401        )
2402    })?;
2403
2404    Frame::build_with_version(
2405        response_version(frame),
2406        FrameType::Error,
2407        flags,
2408        0,
2409        0,
2410        frame.header.corr,
2411        body,
2412    )
2413    .map_err(RouterError::FrameBuild)
2414}
2415
2416pub(crate) fn control_response_body_frame<T: Serialize>(
2417    frame: &Frame,
2418    reply: &T,
2419    label: &'static str,
2420) -> Result<Frame, RouterError> {
2421    let body = serde_json::to_vec(reply).map_err(|err| {
2422        RouterError::backend(
2423            0,
2424            frame.header.corr,
2425            format!("failed to encode {label}: {err}"),
2426        )
2427    })?;
2428
2429    Frame::build_with_version(
2430        response_version(frame),
2431        FrameType::Response,
2432        control_flags(),
2433        0,
2434        0,
2435        frame.header.corr,
2436        body,
2437    )
2438    .map_err(RouterError::FrameBuild)
2439}
2440
2441fn forwarding_error_code(err: &ForwardingError) -> &'static str {
2442    match err {
2443        ForwardingError::ConnectionRoleConflict { .. } => "invalid_request",
2444        ForwardingError::NoModuleConnection => "target_unavailable",
2445        ForwardingError::ModuleReloading { .. } => "module_reloading",
2446        ForwardingError::ClientRouteChannelExhausted { .. }
2447        | ForwardingError::ModuleRouteChannelExhausted { .. } => "route_limit",
2448        ForwardingError::StaleModuleEndpoint
2449        | ForwardingError::UnknownReservation { .. }
2450        | ForwardingError::ConnectionClosing { .. }
2451        | ForwardingError::ClientEgressClosed { .. }
2452        | ForwardingError::ModuleEgressUnavailable { .. } => "target_unavailable",
2453        // Only a swap candidate's registration can produce this, and it means
2454        // exactly what a second active HELLO for a live id means.
2455        ForwardingError::CandidateSlotOccupied { .. } => "duplicate_module_id",
2456        ForwardingError::HelloRegistrationRefused(code) => code,
2457        ForwardingError::TargetRegistrationChanged(_) => "capability_forbidden",
2458        ForwardingError::RelayDeadlineElapsed => "module_timeout",
2459        ForwardingError::RelayCorrelationExhausted
2460        | ForwardingError::RouteOpenBuild(_)
2461        | ForwardingError::Poisoned => "forwarding_error",
2462    }
2463}
2464
2465fn response_version(frame: &Frame) -> u8 {
2466    if (MIN_SUPPORTED_VERSION..=PROTOCOL_VERSION).contains(&frame.header.ver) {
2467        frame.header.ver
2468    } else {
2469        PROTOCOL_VERSION
2470    }
2471}
2472
2473pub(crate) fn control_flags() -> Flags {
2474    Flags::new(false, Priority::Passive, false)
2475}
2476
2477/// GOODBYE for a route.bind the daemon gave up on after reserving the module's
2478/// channel. The target is the module (a client never saw the route), so this
2479/// takes the module path: delivered late rather than dropped when the module's
2480/// queue is momentarily full, and never closing its connection.
2481fn send_goodbye_target_best_effort(
2482    counters: &DaemonCounters,
2483    target: &GoodbyeTarget,
2484    context: &'static str,
2485) {
2486    let Ok(frame) = Frame::build_with_version(
2487        target.negotiated_ver,
2488        FrameType::Goodbye,
2489        control_flags(),
2490        target.channel,
2491        target.epoch,
2492        0,
2493        Vec::new(),
2494    ) else {
2495        return;
2496    };
2497    crate::forwarding::send_module_route_goodbye(
2498        counters,
2499        &target.sink,
2500        frame,
2501        target.module_id.as_deref(),
2502        context,
2503    );
2504}
2505
2506fn route_close_reason_for_opener(
2507    reason: RouteCloseReason,
2508    accepts_close_reasons: Option<&[String]>,
2509) -> RouteCloseReason {
2510    if reason == RouteCloseReason::AuthorityChanged
2511        && !accepts_close_reasons
2512            .is_some_and(|reasons| reasons.iter().any(|reason| reason == "authority_changed"))
2513    {
2514        // Older readers forbid reopening for unknown reasons. Reload already
2515        // permits reopening and, like an authority change, requires a new bind.
2516        RouteCloseReason::Reload
2517    } else {
2518        reason
2519    }
2520}
2521
2522pub(crate) fn send_route_control_pushes(
2523    forwarding: &ForwardingTable,
2524    routes: Vec<EndpointRoute>,
2525    push: ClientControlPush,
2526) {
2527    let reason = match &push {
2528        ClientControlPush::RouteClosing { reason, .. }
2529        | ClientControlPush::RouteClosed { reason, .. } => *reason,
2530    };
2531    let mut targets: Vec<(GoodbyeTarget, RouteCloseReason, Vec<u16>)> = Vec::new();
2532    for route in routes {
2533        let recipient_reason =
2534            route_close_reason_for_opener(reason, route.accepts_close_reasons.as_deref());
2535        let target = route.goodbye_target;
2536        if let Some((existing, _, channels)) = targets.iter_mut().find(|(existing, reason, _)| {
2537            existing.connection_id == target.connection_id && *reason == recipient_reason
2538        }) {
2539            debug_assert_eq!(
2540                existing.negotiated_ver, target.negotiated_ver,
2541                "one connection cannot negotiate multiple frame versions"
2542            );
2543            if !channels.contains(&target.channel) {
2544                channels.push(target.channel);
2545            }
2546            continue;
2547        }
2548        let channel = target.channel;
2549        targets.push((target, recipient_reason, vec![channel]));
2550    }
2551    for (target, recipient_reason, mut channels) in targets {
2552        channels.sort_unstable();
2553        let mut push = push.clone();
2554        match &mut push {
2555            ClientControlPush::RouteClosing {
2556                channels: covered,
2557                reason,
2558                ..
2559            }
2560            | ClientControlPush::RouteClosed {
2561                channels: covered,
2562                reason,
2563                ..
2564            } => {
2565                *covered = channels;
2566                *reason = recipient_reason;
2567            }
2568        }
2569        let body = match serde_json::to_vec(&push) {
2570            Ok(body) => body,
2571            Err(err) => {
2572                warn!(error = %err, "failed to serialize route lifecycle control PUSH");
2573                continue;
2574            }
2575        };
2576        let frame = match Frame::build_with_version(
2577            target.negotiated_ver,
2578            FrameType::Push,
2579            control_flags(),
2580            0,
2581            0,
2582            0,
2583            body.clone(),
2584        ) {
2585            Ok(frame) => frame,
2586            Err(err) => {
2587                warn!(
2588                    route_channel = target.channel,
2589                    error = %err,
2590                    "failed to build route lifecycle control PUSH frame"
2591                );
2592                continue;
2593            }
2594        };
2595        if let Err(err) = target.sink.try_send(frame) {
2596            if target.close_on_delivery_failure() {
2597                warn!(
2598                    target_connection_id = target.connection_id.get(),
2599                    route_channel = target.channel,
2600                    error = %err,
2601                    "route lifecycle control PUSH was not delivered to client; closing target connection"
2602                );
2603                let _ = forwarding.escalate_client_delivery_failure(
2604                    target.connection_id,
2605                    target.channel,
2606                    target.epoch,
2607                    CloseReason::new(
2608                        "route_lifecycle_push_delivery_failed",
2609                        format!(
2610                            "failed to enqueue route lifecycle control PUSH for channel {}: {err}",
2611                            target.channel
2612                        ),
2613                    ),
2614                    crate::forwarding::UndeliveredFrame {
2615                        module_id: target.module_id.as_deref(),
2616                        sink: &target.sink,
2617                    },
2618                );
2619            }
2620        }
2621    }
2622}
2623
2624#[cfg(test)]
2625#[path = "control/scope_outcome_count_tests.rs"]
2626mod scope_outcome_count_tests;
2627
2628#[cfg(test)]
2629#[path = "control/control_tests.rs"]
2630mod tests;
2631
2632#[cfg(test)]
2633#[path = "control/concurrency_default_exposure_tests.rs"]
2634mod concurrency_default_exposure_tests;