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