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