Skip to main content

subc_daemon/
control.rs

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