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