1use std::{
2 collections::BTreeMap,
3 env,
4 error::Error,
5 ffi::OsString,
6 fmt, fs, io,
7 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
8 path::{Path, PathBuf},
9 process,
10 time::Duration,
11};
12
13use fs4::{FileExt, TryLockError};
14use subc_protocol::PROTOCOL_VERSION;
15pub use subc_transport::user_connection_token;
16use subc_transport::{
17 authenticate_client, connection_file, generate_daemon_id, generate_key,
18 write_atomic_with_local_endpoint, AuthError, ConnectionFileError, ConnectionInfo, Endpoint,
19 LocalEndpoint, SCHEMA_VERSION,
20};
21use tokio::{
22 net::{TcpListener, TcpStream},
23 task::{JoinError, JoinHandle},
24 time::{sleep, timeout},
25};
26use tracing::{error, info, warn};
27
28use crate::{
29 daemon_config::{self, ConfiguredModule, DaemonConfigError},
30 local_listener::{self, BoundLocalListener, LocalListenerConfig},
31 server::{serve_listeners, serve_local_listener, ServerAuth, ServerError},
32 supervise::HealthConfig,
33 ConnectedClients, ControlHandler, DaemonSelfWatchdog, DaemonSelfWatchdogConfig,
34 ForwardingTable, Registry, RestartPolicy, Router, Supervisor, SupervisorHandle,
35 SupervisorProcessLiveness,
36};
37use std::sync::Arc;
38
39#[cfg(windows)]
40mod windows_connection_copy;
41
42pub const DEFAULT_SUBC_PORT: u16 = 8757;
43pub const SUBC_PORT_ENV: &str = "SUBC_PORT";
44use subc_transport::CONNECTION_FILE_NAME;
45const DAEMON_VERSION: &str = env!("CARGO_PKG_VERSION");
46const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
47const PROBE_AUTH_DEADLINE: Duration = Duration::from_secs(2);
48const START_LOCK_RETRIES: usize = 40;
49const START_LOCK_RETRY_DELAY: Duration = Duration::from_millis(25);
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum ConnectionFileSource {
53 XdgRuntimeDir,
54 TempDirFallback,
55 Explicit,
56}
57
58impl ConnectionFileSource {
59 fn reason(self) -> &'static str {
60 match self {
61 Self::XdgRuntimeDir => "XDG_RUNTIME_DIR set and non-empty",
62 Self::TempDirFallback => "XDG_RUNTIME_DIR unset or empty",
63 Self::Explicit => "configured path",
64 }
65 }
66}
67
68impl fmt::Display for ConnectionFileSource {
69 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
70 formatter.write_str(match self {
71 Self::XdgRuntimeDir => "xdg_runtime_dir",
72 Self::TempDirFallback => "temp_dir_fallback",
73 Self::Explicit => "explicit",
74 })
75 }
76}
77
78#[derive(Debug, Clone, Default)]
82struct AdmissionFactsConfig {
83 carrier_module_id: Option<String>,
84 targets: Option<Vec<String>>,
85}
86
87#[derive(Debug, Clone, Default, PartialEq, Eq)]
96pub enum CgroupPlacementConfig {
97 #[default]
98 Disabled,
99 Current,
100 Root(PathBuf),
101}
102
103#[derive(Debug, Clone)]
104pub struct BootstrapConfig {
105 #[cfg(feature = "test-support")]
106 shutdown_intent_window: Duration,
107 pub operator_queue_wait: Duration,
108 pub operator_timeout: Duration,
109 pub operator_stuck_grace: Duration,
110 #[cfg(feature = "test-support")]
111 pub operator_script: Option<PathBuf>,
112 #[cfg(feature = "test-support")]
113 pub operator_events: Option<PathBuf>,
114 pub connection_file_path: PathBuf,
115 pub port: u16,
116 pub daemon_ver: String,
117 configured_modules: Vec<ConfiguredModule>,
118 storage_config: Option<daemon_config::StorageConfig>,
119 admission_facts: AdmissionFactsConfig,
120 scope_authority_owners: Vec<String>,
122 federated_scope_owner: String,
123 privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt,
124 activity_config: daemon_config::ActivityConfig,
125 daemon_config_path: Option<PathBuf>,
126 config_store_root: Option<PathBuf>,
129 defer_file_load: bool,
130 #[cfg(test)]
133 file_derived_test_probe: Option<Vec<String>>,
134 #[cfg(all(test, feature = "test-support"))]
135 test_store_factory:
136 Option<fn(crate::config_store::StoreRoot) -> crate::config_store::ConfigStore>,
137 #[cfg(all(test, feature = "test-support"))]
138 test_control: Option<fn(ControlHandler) -> ControlHandler>,
139 #[cfg(all(test, feature = "test-support"))]
140 test_listener_bind: Option<fn(&mut BootstrapConfig)>,
141 configured_port: Option<u16>,
142 route_bind_relay_default_ms: Option<u64>,
146 reserved_capabilities: BTreeMap<String, String>,
147 watchdog_config: DaemonSelfWatchdogConfig,
148 connection_file_source: ConnectionFileSource,
149 #[cfg(all(test, windows))]
150 profile_override: Option<PathBuf>,
151 cgroup_placement: CgroupPlacementConfig,
154 capture_logs_dir: Option<PathBuf>,
158 terminal_journal_path: Option<PathBuf>,
166 machine_id_path: Option<PathBuf>,
172
173 local_listener: LocalListenerConfig,
180 live_children_path: Option<PathBuf>,
188 privacy_trampoline: Option<PathBuf>,
189}
190
191impl BootstrapConfig {
192 pub fn with_config_store_root(mut self, root: PathBuf) -> Result<Self, BootstrapError> {
193 crate::config_store::StoreRoot::from_service_definition(root.clone())
194 .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?;
195 let parent = root.parent().ok_or_else(|| {
196 BootstrapError::ConfigStore("config store root needs a parent directory".into())
197 })?;
198 std::fs::read_dir(parent).map_err(|e| {
199 BootstrapError::ConfigStore(format!("config store parent is unreadable: {e}"))
200 })?;
201 self.config_store_root = Some(root);
202 Ok(self)
203 }
204 #[cfg(feature = "test-support")]
206 pub fn with_shutdown_intent_window(mut self, window: Duration) -> Self {
207 self.shutdown_intent_window = window;
208 self
209 }
210
211 pub fn new(connection_file_path: impl Into<PathBuf>, port: u16) -> Self {
212 Self {
213 #[cfg(feature = "test-support")]
214 shutdown_intent_window: Duration::from_secs(120),
215 connection_file_path: connection_file_path.into(),
216 operator_queue_wait: Duration::from_secs(150),
217 operator_timeout: Duration::from_secs(120),
218 operator_stuck_grace: Duration::from_secs(10),
219 #[cfg(feature = "test-support")]
220 operator_script: None,
221 #[cfg(feature = "test-support")]
222 operator_events: None,
223 port,
224 daemon_ver: DAEMON_VERSION.to_owned(),
225 configured_modules: Vec::new(),
226 storage_config: None,
227 admission_facts: AdmissionFactsConfig::default(),
228 scope_authority_owners: daemon_config::default_scope_authority_owners(),
229 federated_scope_owner: daemon_config::default_federated_scope_owner(),
230 privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt::default(),
231 activity_config: daemon_config::ActivityConfig::default(),
232 daemon_config_path: None,
233 config_store_root: None,
234 defer_file_load: false,
235 #[cfg(test)]
236 file_derived_test_probe: None,
237 #[cfg(all(test, feature = "test-support"))]
238 test_store_factory: None,
239 #[cfg(all(test, feature = "test-support"))]
240 test_control: None,
241 #[cfg(all(test, feature = "test-support"))]
242 test_listener_bind: None,
243 configured_port: None,
244 route_bind_relay_default_ms: None,
245 reserved_capabilities: BTreeMap::new(),
246 watchdog_config: DaemonSelfWatchdogConfig::default(),
247 connection_file_source: ConnectionFileSource::Explicit,
248 #[cfg(all(test, windows))]
249 profile_override: None,
250 cgroup_placement: CgroupPlacementConfig::default(),
251 capture_logs_dir: None,
252 terminal_journal_path: None,
253 machine_id_path: None,
254 local_listener: LocalListenerConfig { socket_dir: None },
255 live_children_path: None,
256 privacy_trampoline: None,
257 }
258 }
259
260 pub fn with_local_listener_socket_dir(mut self, dir: impl Into<PathBuf>) -> Self {
263 self.local_listener = LocalListenerConfig::in_socket_dir(dir);
264 self
265 }
266
267 pub fn with_local_listener(mut self, config: LocalListenerConfig) -> Self {
269 self.local_listener = config;
270 self
271 }
272
273 pub fn with_live_children_record(mut self, path: impl Into<PathBuf>) -> Self {
277 self.live_children_path = Some(path.into());
278 self
279 }
280
281 pub fn with_privacy_trampoline(mut self, path: impl Into<PathBuf>) -> Self {
284 self.privacy_trampoline = Some(path.into());
285 self
286 }
287
288 pub fn with_machine_id_path(mut self, path: impl Into<PathBuf>) -> Self {
292 self.machine_id_path = Some(path.into());
293 self
294 }
295
296 pub fn with_cgroup_placement(mut self, placement: CgroupPlacementConfig) -> Self {
298 self.cgroup_placement = placement;
299 self
300 }
301
302 pub fn with_capture_logs_dir(mut self, dir: impl Into<PathBuf>) -> Self {
306 self.capture_logs_dir = Some(dir.into());
307 self
308 }
309
310 pub fn with_terminal_journal_path(mut self, path: impl Into<PathBuf>) -> Self {
313 self.terminal_journal_path = Some(path.into());
314 self
315 }
316
317 pub fn from_env() -> Result<Self, BootstrapError> {
318 Self::from_env_with_daemon_config_path(daemon_config::default_config_path())
319 }
320
321 pub fn from_env_for_daemon_binary() -> Result<Self, BootstrapError> {
330 let run_dir = daemon_config::daemon_run_dir().map_err(BootstrapError::RunDir)?;
331 let machine_id_path =
332 crate::machine_id::default_machine_id_path().map_err(BootstrapError::MachineId)?;
333 let (connection_file, source) =
336 connection_file_path_with_source(non_empty_os_var("XDG_RUNTIME_DIR"));
337 let mut config = Self::new(connection_file, DEFAULT_SUBC_PORT)
338 .with_connection_file_source(source)
339 .with_daemon_config_source(daemon_config::default_config_path(), None)
340 .with_local_listener(LocalListenerConfig::in_socket_dir(&run_dir))
341 .with_capture_logs_dir(run_dir.join("logs"))
342 .with_terminal_journal_path(run_dir.join("terminals.jsonl"))
343 .with_live_children_record(crate::live_children::record_path(&run_dir))
344 .with_machine_id_path(machine_id_path);
345 config.defer_file_load = true;
346 #[cfg(feature = "test-support")]
347 let config = {
348 let mut config = config;
349 config.operator_script =
350 std::env::var_os("SUBC_TEST_OPERATOR_SCRIPT").map(PathBuf::from);
351 config.operator_events =
352 std::env::var_os("SUBC_TEST_OPERATOR_EVENTS").map(PathBuf::from);
353 for (name, value) in [
354 (
355 "SUBC_TEST_OPERATOR_QUEUE_WAIT_MS",
356 &mut config.operator_queue_wait,
357 ),
358 (
359 "SUBC_TEST_OPERATOR_TIMEOUT_MS",
360 &mut config.operator_timeout,
361 ),
362 (
363 "SUBC_TEST_OPERATOR_STUCK_MS",
364 &mut config.operator_stuck_grace,
365 ),
366 ] {
367 if let Ok(ms) = std::env::var(name) {
368 if let Ok(ms) = ms.parse::<u64>() {
369 *value = Duration::from_millis(ms);
370 }
371 }
372 }
373 config
374 };
375 Ok(config)
376 }
377
378 pub fn from_env_with_daemon_config_path(
383 daemon_config_path: impl AsRef<Path>,
384 ) -> Result<Self, BootstrapError> {
385 let daemon_config_path = daemon_config_path.as_ref().to_path_buf();
386 let (daemon_config, activity_config) =
387 daemon_config::load_with_activity(&daemon_config_path)
388 .map_err(BootstrapError::DaemonConfig)?
389 .map(|(config, activity)| (Some(config), activity))
390 .unwrap_or_default();
391 let config_port = daemon_config.as_ref().and_then(|config| config.port);
392 let storage_config = daemon_config
393 .as_ref()
394 .and_then(|config| config.storage.clone());
395 let admission_facts_carrier_module_id = daemon_config
396 .as_ref()
397 .and_then(|config| config.admission_facts_carrier_module_id.clone());
398 let admission_facts_targets = daemon_config
399 .as_ref()
400 .and_then(|config| config.admission_facts_targets.clone());
401 let scope_authority_owners = daemon_config
402 .as_ref()
403 .map(|config| config.scope_authority_owners.clone())
404 .unwrap_or_else(daemon_config::default_scope_authority_owners);
405 let federated_scope_owner = daemon_config
406 .as_ref()
407 .map(|config| config.federated_scope_owner.clone())
408 .unwrap_or_else(daemon_config::default_federated_scope_owner);
409 let privileged_operator_prompt = daemon_config
410 .as_ref()
411 .map(|config| config.privileged_operator_prompt)
412 .unwrap_or_default();
413 let route_bind_relay_default_ms = daemon_config
414 .as_ref()
415 .and_then(|config| config.route_bind_relay_timeout_ms);
416 let reserved_capabilities = daemon_config
417 .as_ref()
418 .map(|config| config.reserved_capabilities.clone())
419 .unwrap_or_default();
420 let configured_modules = daemon_config
421 .map(|config| config.modules)
422 .unwrap_or_default();
423
424 let port = match env::var(SUBC_PORT_ENV) {
425 Ok(raw) if !raw.trim().is_empty() => {
426 let port = raw
427 .parse::<u16>()
428 .map_err(|source| BootstrapError::InvalidPort { raw, source })?;
429 if let Some(config_port) = config_port {
430 info!(
431 env = SUBC_PORT_ENV,
432 env_port = port,
433 config_port,
434 "SUBC_PORT overrides daemon config port"
435 );
436 }
437 port
438 }
439 Ok(_) | Err(_) => config_port.unwrap_or(DEFAULT_SUBC_PORT),
440 };
441
442 let (connection_file_path, connection_file_source) =
443 connection_file_path_with_source(non_empty_os_var("XDG_RUNTIME_DIR"));
444 let config = Self::new(connection_file_path, port)
445 .with_configured_modules(configured_modules)
446 .with_storage_config(storage_config)
447 .with_admission_facts_config(admission_facts_carrier_module_id, admission_facts_targets)
448 .with_scope_authority_owners(scope_authority_owners)
449 .with_federated_scope_owner(federated_scope_owner)
450 .with_privileged_operator_prompt(privileged_operator_prompt)
451 .with_activity_config(activity_config)
452 .with_route_bind_relay_default_ms(route_bind_relay_default_ms)
453 .with_reserved_capabilities(reserved_capabilities)
454 .with_daemon_config_source(daemon_config_path, config_port)
455 .with_connection_file_source(connection_file_source);
456 #[cfg(test)]
457 let config = {
458 let mut config = config;
459 config.file_derived_test_probe = Some(config.scope_authority_owners.clone());
460 config
461 };
462 Ok(config)
463 }
464
465 pub fn with_daemon_config_path(
470 mut self,
471 daemon_config_path: impl AsRef<Path>,
472 ) -> Result<Self, BootstrapError> {
473 let daemon_config_path = daemon_config_path.as_ref().to_path_buf();
474 if self.config_store_root.is_some() {
475 self.defer_file_load = true;
476 return Ok(self.with_daemon_config_source(daemon_config_path, None));
477 }
478 let (daemon_config, activity_config) =
479 daemon_config::load_with_activity(&daemon_config_path)
480 .map_err(BootstrapError::DaemonConfig)?
481 .map(|(config, activity)| (Some(config), activity))
482 .unwrap_or_default();
483 let configured_port = daemon_config.as_ref().and_then(|config| config.port);
484 Ok(self
485 .with_parsed_daemon_config(daemon_config, activity_config)
486 .with_daemon_config_source(daemon_config_path, configured_port))
487 }
488
489 fn with_parsed_daemon_config(
490 self,
491 daemon_config: Option<daemon_config::DaemonConfig>,
492 activity_config: daemon_config::ActivityConfig,
493 ) -> Self {
494 let storage_config = daemon_config
495 .as_ref()
496 .and_then(|config| config.storage.clone());
497 let admission_facts_carrier_module_id = daemon_config
498 .as_ref()
499 .and_then(|config| config.admission_facts_carrier_module_id.clone());
500 let admission_facts_targets = daemon_config
501 .as_ref()
502 .and_then(|config| config.admission_facts_targets.clone());
503 let scope_authority_owners = daemon_config
504 .as_ref()
505 .map(|config| config.scope_authority_owners.clone())
506 .unwrap_or_else(daemon_config::default_scope_authority_owners);
507 let federated_scope_owner = daemon_config
508 .as_ref()
509 .map(|config| config.federated_scope_owner.clone())
510 .unwrap_or_else(daemon_config::default_federated_scope_owner);
511 let privileged_operator_prompt = daemon_config
512 .as_ref()
513 .map(|config| config.privileged_operator_prompt)
514 .unwrap_or_default();
515 let route_bind_relay_default_ms = daemon_config
516 .as_ref()
517 .and_then(|config| config.route_bind_relay_timeout_ms);
518 let reserved_capabilities = daemon_config
519 .as_ref()
520 .map(|config| config.reserved_capabilities.clone())
521 .unwrap_or_default();
522 let configured_modules = daemon_config
523 .map(|config| config.modules)
524 .unwrap_or_default();
525 self.with_configured_modules(configured_modules)
526 .with_storage_config(storage_config)
527 .with_admission_facts_config(admission_facts_carrier_module_id, admission_facts_targets)
528 .with_scope_authority_owners(scope_authority_owners)
529 .with_federated_scope_owner(federated_scope_owner)
530 .with_privileged_operator_prompt(privileged_operator_prompt)
531 .with_activity_config(activity_config)
532 .with_route_bind_relay_default_ms(route_bind_relay_default_ms)
533 .with_reserved_capabilities(reserved_capabilities)
534 }
535
536 pub fn with_configured_modules(
537 mut self,
538 modules: impl IntoIterator<Item = ConfiguredModule>,
539 ) -> Self {
540 self.configured_modules = modules.into_iter().collect();
541 self.configured_modules
542 .sort_by(|left, right| left.module_id.cmp(&right.module_id));
543 self
544 }
545
546 pub fn with_storage_config(
547 mut self,
548 storage_config: Option<daemon_config::StorageConfig>,
549 ) -> Self {
550 self.storage_config = storage_config;
551 self
552 }
553
554 pub fn with_admission_facts_config(
555 mut self,
556 carrier_module_id: Option<String>,
557 targets: Option<Vec<String>>,
558 ) -> Self {
559 self.admission_facts = AdmissionFactsConfig {
560 carrier_module_id,
561 targets,
562 };
563 self
564 }
565
566 pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
569 self.scope_authority_owners = owners;
570 self
571 }
572
573 pub fn with_federated_scope_owner(mut self, owner: String) -> Self {
574 self.federated_scope_owner = owner;
575 self
576 }
577
578 pub fn with_privileged_operator_prompt(
580 mut self,
581 mode: daemon_config::PrivilegedOperatorPrompt,
582 ) -> Self {
583 self.privileged_operator_prompt = mode;
584 self
585 }
586
587 pub fn with_activity_config(mut self, config: daemon_config::ActivityConfig) -> Self {
588 self.activity_config = config;
589 self
590 }
591
592 pub fn with_route_bind_relay_default_ms(mut self, ms: Option<u64>) -> Self {
597 self.route_bind_relay_default_ms = ms;
598 self
599 }
600
601 pub fn with_reserved_capabilities(
602 mut self,
603 reserved_capabilities: BTreeMap<String, String>,
604 ) -> Self {
605 self.reserved_capabilities = reserved_capabilities;
606 self
607 }
608
609 fn with_daemon_config_source(
610 mut self,
611 daemon_config_path: PathBuf,
612 configured_port: Option<u16>,
613 ) -> Self {
614 self.daemon_config_path = Some(daemon_config_path);
615 self.configured_port = configured_port;
616 self
617 }
618
619 fn with_connection_file_source(mut self, source: ConnectionFileSource) -> Self {
620 self.connection_file_source = source;
621 self
622 }
623
624 pub fn with_watchdog_config(mut self, watchdog_config: DaemonSelfWatchdogConfig) -> Self {
625 self.watchdog_config = watchdog_config;
626 self
627 }
628}
629
630#[allow(clippy::large_enum_variant)]
634#[derive(Debug)]
635pub enum Outcome {
636 AlreadyRunning,
638 Bound(BoundDaemon),
641}
642
643#[derive(Debug)]
644pub struct BoundDaemon {
645 pub listeners: Vec<TcpListener>,
646 pub local_listener: Option<BoundLocalListener>,
650 pub local_endpoint_unavailable: Option<String>,
653 pub local_endpoint: Option<LocalEndpoint>,
656 pub connection_info: ConnectionInfo,
657 pub connection_file_path: PathBuf,
658 pub connection_file_source: ConnectionFileSource,
659 #[cfg(windows)]
660 connection_file_copy: Option<PathBuf>,
661 pub machine_id: Option<crate::machine_id::MachineId>,
664 run_dir_lock: Option<crate::run_dir_lock::RunDirLock>,
668 publication_lock: Option<StartLock>,
674}
675
676pub fn connection_file_path() -> PathBuf {
683 connection_file_path_with_source(non_empty_os_var("XDG_RUNTIME_DIR")).0
684}
685
686fn connection_file_path_with_source(
687 runtime_dir: Option<OsString>,
688) -> (PathBuf, ConnectionFileSource) {
689 if let Some(runtime_dir) = runtime_dir.filter(|value| !value.is_empty()) {
690 return (
691 PathBuf::from(runtime_dir).join(CONNECTION_FILE_NAME),
692 ConnectionFileSource::XdgRuntimeDir,
693 );
694 }
695
696 (
697 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token())),
698 ConnectionFileSource::TempDirFallback,
699 )
700}
701
702pub async fn run() -> Result<(), BootstrapError> {
708 run_with_config(
711 BootstrapConfig::from_env_for_daemon_binary()?
712 .with_cgroup_placement(CgroupPlacementConfig::Current),
713 )
714 .await
715}
716
717#[cfg(feature = "test-support")]
718mod config_test_seam {
719 #[cfg(not(test))]
720 use super::BootstrapError;
721
722 pub(super) fn enabled() -> bool {
723 std::env::var_os("SUBC_TEST_CONFIG_GATE").as_deref() == Some(std::ffi::OsStr::new("1"))
724 && std::env::current_exe().ok().is_some_and(|path| {
725 path.file_name()
726 .is_some_and(|name| name.to_string_lossy().starts_with("ckdev-"))
727 })
728 }
729
730 #[cfg(not(test))]
731 pub(super) fn open(
732 root: crate::config_store::StoreRoot,
733 ) -> Result<crate::config_store::ConfigStore, BootstrapError> {
734 if !enabled() {
735 return Ok(crate::config_store::ConfigStore::open(root));
736 }
737 crate::config_store::testing::TestSupport::new(
740 root.path().to_path_buf(),
741 Some(root.path().join("test-key")),
742 )
743 .and_then(|hooks| {
744 hooks
745 .with_anchor_failure_file(root.path().join("fail-anchor"))
746 .open()
747 })
748 .map_err(|error| BootstrapError::ConfigStore(error.to_string()))
749 }
750}
751
752pub async fn run_with_config(config: BootstrapConfig) -> Result<(), BootstrapError> {
776 let Some(start_lock) = singleton_start_lock(&config.connection_file_path).await? else {
777 info!("subc daemon already running");
778 return Ok(());
779 };
780 let (config, opened_store, start_lock) = tokio::task::spawn_blocking(move || {
781 let mut opened_store = config
782 .config_store_root
783 .as_ref()
784 .map(|root| {
785 let (root, lock) = crate::config_store::StoreWriterLock::acquire(root)
786 .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?;
787 #[cfg(all(test, feature = "test-support"))]
788 let store = if let Some(factory) = config.test_store_factory {
789 crate::config_store::testing::TestSupport::new(root.path().to_path_buf(), None)
790 .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?;
791 factory(root)
792 } else {
793 crate::config_store::ConfigStore::open(root)
794 };
795 #[cfg(all(feature = "test-support", not(test)))]
796 let store = config_test_seam::open(root)?;
797 #[cfg(not(feature = "test-support"))]
798 let store = crate::config_store::ConfigStore::open(root);
799 Ok::<_, BootstrapError>((store, lock))
800 })
801 .transpose()?;
802 let config =
803 load_bootstrap_authority(config, opened_store.as_mut().map(|(store, _)| store))?;
804 #[cfg(all(test, feature = "test-support"))]
805 let config = {
806 let mut config = config;
807 if let Some(bind) = config.test_listener_bind {
808 bind(&mut config);
811 }
812 config
813 };
814 Ok::<_, BootstrapError>((config, opened_store, start_lock))
815 })
816 .await
817 .map_err(|e| BootstrapError::ConfigStore(e.to_string()))??;
818 #[cfg(feature = "test-support")]
819 let shutdown_intent_window = config.shutdown_intent_window;
820 let forwarding = Arc::new(ForwardingTable::default());
821 forwarding.operator_confirms().configure_bootstrap(&config);
822 let configured_modules = config.configured_modules.clone();
823 let storage_config = config.storage_config.clone();
824 let admission_facts = config.admission_facts.clone();
825 let scope_authority_owners = config.scope_authority_owners.clone();
826 let federated_scope_owner = config.federated_scope_owner.clone();
827 let privileged_operator_prompt = config.privileged_operator_prompt;
828 let activity_config = config.activity_config;
829 let daemon_config_path = config.daemon_config_path.clone();
830 let configured_port = config.configured_port;
831 let route_bind_relay_default_ms = config.route_bind_relay_default_ms;
832 let reserved_capabilities = config.reserved_capabilities.clone();
833 let watchdog_config = config.watchdog_config.clone();
834 let cgroup_placement_config = config.cgroup_placement.clone();
835 let capture_logs_dir = config.capture_logs_dir.clone();
836 let terminal_journal_path = config.terminal_journal_path.clone();
837 let live_children_path = config.live_children_path.clone();
838 let privacy_trampoline = config.privacy_trampoline.clone();
839 #[cfg(all(test, feature = "test-support"))]
840 let test_control = config.test_control;
841 match ensure_singleton_with_start_lock(config, false, start_lock).await? {
842 Outcome::AlreadyRunning => {
843 info!("subc daemon already running");
844 Ok(())
845 }
846 Outcome::Bound(bound) => {
847 #[cfg(target_os = "linux")]
848 let cgroup_placement = prepare_cgroup_placement(&cgroup_placement_config);
849 #[cfg(not(target_os = "linux"))]
850 let _ = cgroup_placement_config;
851 serve_bound_daemon(
852 bound,
853 forwarding,
854 configured_modules,
855 storage_config,
856 admission_facts,
857 scope_authority_owners,
858 federated_scope_owner,
859 privileged_operator_prompt,
860 activity_config,
861 daemon_config_path,
862 opened_store,
863 configured_port,
864 route_bind_relay_default_ms,
865 reserved_capabilities,
866 watchdog_config,
867 capture_logs_dir,
868 terminal_journal_path,
869 live_children_path,
870 privacy_trampoline,
871 #[cfg(all(test, feature = "test-support"))]
872 test_control,
873 #[cfg(feature = "test-support")]
874 shutdown_intent_window,
875 #[cfg(target_os = "linux")]
876 cgroup_placement,
877 )
878 .await
879 }
880 }
881}
882
883fn load_bootstrap_authority(
886 config: BootstrapConfig,
887 mut store: Option<&mut crate::config_store::ConfigStore>,
888) -> Result<BootstrapConfig, BootstrapError> {
889 let store_state = store.as_mut().map(|store| store.status().state);
890 let recovery = matches!(
891 store_state,
892 Some(
893 crate::config_store::StoreState::StoreUnverified
894 | crate::config_store::StoreState::StoreMissing
895 )
896 );
897 let authority = if recovery {
898 BootstrapConfig::new(&config.connection_file_path, DEFAULT_SUBC_PORT)
899 } else if store_state == Some(crate::config_store::StoreState::Stamped) {
900 let store = store.expect("stamped store was just checked");
901 match stamped_authority(&config.connection_file_path, store) {
902 Ok(authority) => authority,
903 Err(reason) => {
904 tracing::error!(%reason, "approved configuration unusable; starting in recovery");
907 store.enter_recovery(&reason);
908 BootstrapConfig::new(&config.connection_file_path, DEFAULT_SUBC_PORT)
909 }
910 }
911 } else if config.defer_file_load {
912 BootstrapConfig::from_env_with_daemon_config_path(
913 config
914 .daemon_config_path
915 .as_ref()
916 .expect("binary config path"),
917 )?
918 } else {
919 return Ok(config);
920 };
921 Ok(BootstrapConfig {
924 connection_file_path: config.connection_file_path,
925 connection_file_source: config.connection_file_source,
926 daemon_ver: config.daemon_ver,
927 daemon_config_path: config.daemon_config_path,
928 config_store_root: config.config_store_root,
929 defer_file_load: config.defer_file_load,
930 operator_queue_wait: config.operator_queue_wait,
931 operator_timeout: config.operator_timeout,
932 operator_stuck_grace: config.operator_stuck_grace,
933 watchdog_config: config.watchdog_config,
934 cgroup_placement: config.cgroup_placement,
935 capture_logs_dir: config.capture_logs_dir,
936 terminal_journal_path: config.terminal_journal_path,
937 machine_id_path: config.machine_id_path,
938 local_listener: config.local_listener,
939 live_children_path: config.live_children_path,
940 privacy_trampoline: config.privacy_trampoline,
941 #[cfg(feature = "test-support")]
942 shutdown_intent_window: config.shutdown_intent_window,
943 #[cfg(feature = "test-support")]
944 operator_script: config.operator_script,
945 #[cfg(feature = "test-support")]
946 operator_events: config.operator_events,
947 #[cfg(all(test, windows))]
948 profile_override: config.profile_override,
949 #[cfg(all(test, feature = "test-support"))]
950 test_store_factory: config.test_store_factory,
951 #[cfg(all(test, feature = "test-support"))]
952 test_control: config.test_control,
953 #[cfg(all(test, feature = "test-support"))]
954 test_listener_bind: config.test_listener_bind,
955 ..authority
956 })
957}
958
959fn stamped_authority(
962 connection_file_path: &Path,
963 store: &mut crate::config_store::ConfigStore,
964) -> Result<BootstrapConfig, String> {
965 let generation = store
966 .select_boot_generation()
967 .map_err(|error| error.to_string())?;
968 let body = store.body().map_err(|error| error.to_string())?;
969 let layer = body
970 .generations
971 .get(&generation)
972 .and_then(|entry| entry.delivery.as_ref())
973 .and_then(|delivery| delivery.daemon.as_ref())
974 .ok_or("approved daemon snapshot is absent")?;
975 let bytes = layer
976 .bytes
977 .as_deref()
978 .ok_or("approved daemon bytes are absent")?;
979 let path = layer
980 .path
981 .as_deref()
982 .ok_or("approved daemon path is absent")?;
983 let doc = std::str::from_utf8(bytes).map_err(|error| error.to_string())?;
984 let (daemon, activity) = daemon_config::parse_with_activity(doc, Path::new(path))
985 .map_err(|error| format!("approved daemon configuration is invalid: {error}"))?;
986 let port = daemon.port;
987 Ok(
988 BootstrapConfig::new(connection_file_path, port.unwrap_or(DEFAULT_SUBC_PORT))
989 .with_parsed_daemon_config(Some(daemon), activity)
990 .with_daemon_config_source(PathBuf::from(path), port),
991 )
992}
993
994#[cfg(target_os = "linux")]
995fn prepare_cgroup_placement(config: &CgroupPlacementConfig) -> Option<subc_cgroup::Placement> {
996 let result = match config {
997 CgroupPlacementConfig::Disabled => return None,
998 CgroupPlacementConfig::Current => subc_cgroup::prepare_current(),
999 CgroupPlacementConfig::Root(root) => subc_cgroup::prepare_at(root),
1000 };
1001
1002 match result {
1003 Ok(Some(placement)) => Some(placement),
1004 Ok(None) => {
1005 warn!(
1006 placement = ?config,
1007 "module cgroup placement is disabled: configured cgroup root is not delegated"
1008 );
1009 None
1010 }
1011 Err(error) => {
1012 warn!(
1013 placement = ?config,
1014 error = %error,
1015 "module cgroup placement is disabled by an unexpected cgroup probe error"
1016 );
1017 None
1018 }
1019 }
1020}
1021
1022#[cfg(unix)]
1029const NOFILE_TARGET: u64 = 65536;
1030
1031#[cfg(unix)]
1035fn raise_nofile_limit() {
1036 #[cfg(target_os = "macos")]
1037 let ceiling = subc_os::child_spawn::output(
1038 std::process::Command::new("/usr/sbin/sysctl").args(["-n", "kern.maxfilesperproc"]),
1039 )
1040 .ok()
1041 .filter(|output| output.status.success())
1042 .and_then(|output| String::from_utf8(output.stdout).ok())
1043 .and_then(|value| value.trim().parse::<u64>().ok())
1044 .filter(|value| *value > 0);
1045 #[cfg(not(target_os = "macos"))]
1046 let ceiling = None;
1047 raise_nofile_limit_with_ceiling(ceiling);
1048}
1049
1050#[cfg(unix)]
1051fn raise_nofile_limit_with_ceiling(kernel_ceiling: Option<u64>) {
1052 match rlimit::Resource::NOFILE.get() {
1053 Ok((soft, hard)) => {
1054 let target = NOFILE_TARGET
1058 .min(hard)
1059 .min(kernel_ceiling.unwrap_or(u64::MAX));
1060 if soft >= target {
1061 return;
1062 }
1063 match rlimit::Resource::NOFILE.set(target, hard) {
1064 Ok(()) => info!(
1065 previous_soft = soft,
1066 new_soft = target,
1067 hard,
1068 "raised open-file soft limit for daemon and module children"
1069 ),
1070 Err(err) => warn!(
1071 soft,
1072 hard,
1073 error = %err,
1074 "could not raise open-file soft limit; multi-root modules may exhaust descriptors"
1075 ),
1076 }
1077 }
1078 Err(err) => warn!(error = %err, "could not read open-file limit"),
1079 }
1080}
1081
1082#[cfg(windows)]
1089fn raise_nofile_limit() {
1090 const MAXSTDIO_TARGET: u32 = 8192;
1091 let current = rlimit::getmaxstdio();
1092 if current >= MAXSTDIO_TARGET {
1093 return;
1094 }
1095 match rlimit::setmaxstdio(MAXSTDIO_TARGET) {
1096 Ok(new_max) => info!(
1097 previous = current,
1098 new_max, "raised CRT stdio-stream limit for daemon"
1099 ),
1100 Err(err) => warn!(
1101 current,
1102 error = %err,
1103 "could not raise CRT stdio-stream limit"
1104 ),
1105 }
1106}
1107
1108#[cfg(not(any(unix, windows)))]
1109fn raise_nofile_limit() {}
1110
1111pub async fn run_with_daemon_config_path(
1112 config: BootstrapConfig,
1113 daemon_config_path: impl AsRef<Path>,
1114) -> Result<(), BootstrapError> {
1115 run_with_config(config.with_daemon_config_path(daemon_config_path)?).await
1116}
1117
1118#[allow(clippy::too_many_arguments)]
1119async fn serve_bound_daemon(
1120 bound: BoundDaemon,
1121 forwarding: Arc<ForwardingTable>,
1122 configured_modules: Vec<ConfiguredModule>,
1123 storage_config: Option<daemon_config::StorageConfig>,
1124 admission_facts: AdmissionFactsConfig,
1125 scope_authority_owners: Vec<String>,
1126 federated_scope_owner: String,
1127 privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt,
1128 activity_config: daemon_config::ActivityConfig,
1129 daemon_config_path: Option<PathBuf>,
1130 opened_store: Option<(
1131 crate::config_store::ConfigStore,
1132 crate::config_store::StoreWriterLock,
1133 )>,
1134 configured_port: Option<u16>,
1135 route_bind_relay_default_ms: Option<u64>,
1136 reserved_capabilities: BTreeMap<String, String>,
1137 watchdog_config: DaemonSelfWatchdogConfig,
1138 capture_logs_dir: Option<PathBuf>,
1139 terminal_journal_path: Option<PathBuf>,
1140 live_children_path: Option<PathBuf>,
1141 privacy_trampoline: Option<PathBuf>,
1142 #[cfg(all(test, feature = "test-support"))] test_control: Option<
1143 fn(ControlHandler) -> ControlHandler,
1144 >,
1145 #[cfg(feature = "test-support")] shutdown_intent_window: Duration,
1146 #[cfg(target_os = "linux")] cgroup_placement: Option<subc_cgroup::Placement>,
1147) -> Result<(), BootstrapError> {
1148 let _stall_witness = crate::stall_witness::Witness::start_if_daemon_logging();
1149 #[cfg(unix)]
1150 let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
1151 .map_err(BootstrapError::Signal)?;
1152 raise_nofile_limit();
1155 #[cfg(windows)]
1156 if let Err(error) = subc_jobobject::ensure_root_job() {
1157 warn!(%error, "module launches disabled: Windows root job setup failed");
1160 }
1161
1162 info!(
1163 connection_file = %bound.connection_file_path.display(),
1164 connection_file_source = %bound.connection_file_source,
1165 connection_file_source_reason = bound.connection_file_source.reason(),
1166 endpoints = ?bound.connection_info.endpoints,
1167 configured_modules = configured_modules.len(),
1168 machine_id = bound.machine_id.as_ref().map(|id| id.as_str()).unwrap_or("none"),
1169 "subc daemon starting"
1170 );
1171
1172 let run_dir_lock = bound.run_dir_lock;
1183 let publication_lock = bound.publication_lock;
1184 if let Some(owner) = &run_dir_lock {
1185 #[cfg(target_os = "linux")]
1186 crate::live_children::sweep_orphans_with_placement(
1187 owner,
1188 &crate::live_children::AdoptedPids::none(),
1189 crate::live_children::SweepBounds::default(),
1190 cgroup_placement.as_ref(),
1191 )
1192 .await;
1193 #[cfg(not(target_os = "linux"))]
1194 crate::live_children::sweep_orphans(
1195 owner,
1196 &crate::live_children::AdoptedPids::none(),
1197 crate::live_children::SweepBounds::default(),
1198 )
1199 .await;
1200 }
1201
1202 let registry = Arc::new(Registry::default());
1203 let process_liveness = Arc::new(SupervisorProcessLiveness::new());
1204 let supervisor_handle = SupervisorHandle::new();
1205 let _host_health_task = AbortOnDrop::new(supervisor_handle.spawn_host_health_monitor());
1206 #[cfg(feature = "test-support")]
1207 supervisor_handle.set_shutdown_intent_window(shutdown_intent_window);
1208 let connected_clients = ConnectedClients::new();
1209 let daemon_incarnation = format!(
1210 "{:032x}",
1211 u128::from_be_bytes(bound.connection_info.daemon_id)
1212 );
1213 let config_runtime = if let Some((store, writer_lock)) = opened_store {
1214 let path = daemon_config_path.clone().ok_or_else(|| {
1215 BootstrapError::ConfigStore(
1216 "an explicit daemon config path is required with a config store".into(),
1217 )
1218 })?;
1219 let config_home = daemon_config::default_config_home();
1220 let incarnation = daemon_incarnation.clone();
1221 let projects = Arc::new(
1222 crate::config_gate::project_registry::EntorhinalProjectRegistry::new(
1223 registry.clone(),
1224 forwarding.clone(),
1225 ),
1226 );
1227 Some(Arc::new(
1228 tokio::task::spawn_blocking(move || {
1229 crate::config_gate::runtime::RuntimeOwner::new(
1230 incarnation,
1231 store,
1232 crate::config_gate::capture::ConfigCapturer {
1233 daemon_path: path,
1234 config_home,
1235 projects,
1236 },
1237 )
1238 .with_policy_root_data(daemon_config::default_data_home().join("cortexkit"))
1239 .retain_writer_lock(writer_lock)
1240 .map_err(io::Error::other)
1241 })
1242 .await
1243 .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?
1244 .map_err(|e| BootstrapError::ConfigStore(e.to_string()))?,
1245 ))
1246 } else {
1247 None
1248 };
1249 let _config_plan_sweep = config_runtime.as_ref().map(|runtime| {
1250 let runtime = Arc::downgrade(runtime);
1251 AbortOnDrop::new(tokio::spawn(async move {
1252 let mut interval =
1253 tokio::time::interval(crate::config_gate::runtime::PLAN_SWEEP_INTERVAL);
1254 loop {
1255 interval.tick().await;
1256 let Some(runtime) = runtime.upgrade() else {
1257 break;
1258 };
1259 match tokio::task::spawn_blocking(move || runtime.sweep_expired()).await {
1260 Ok(Ok(())) => {}
1261 result => tracing::warn!(?result, "configuration plan expiry sweep failed"),
1262 }
1263 }
1264 }))
1265 });
1266 let supervisor = Supervisor::new(Arc::clone(®istry), RestartPolicy::default())
1267 .with_process_liveness(process_liveness.clone())
1268 .with_forwarding(Arc::clone(&forwarding))
1269 .with_handle(supervisor_handle.clone())
1270 .with_connection_file_path(bound.connection_file_path.clone())
1271 .with_daemon_incarnation(daemon_incarnation.clone());
1272 let supervisor = match &config_runtime {
1273 Some(owner) => supervisor.with_config_runtime(owner.clone()),
1274 None => supervisor,
1275 };
1276 let supervisor = match privacy_trampoline {
1277 Some(path) => supervisor.with_privacy_trampoline(path),
1278 None => supervisor,
1279 };
1280 let activity_run_dir = terminal_journal_path
1320 .as_ref()
1321 .and_then(|path| path.parent())
1322 .map(Path::to_path_buf);
1323 let supervisor = match terminal_journal_path {
1324 Some(path) => supervisor.with_terminal_journal(path, daemon_incarnation.clone()),
1325 None => supervisor,
1326 };
1327 let supervisor = match capture_logs_dir {
1328 Some(dir) => supervisor.with_capture_logs_dir(dir),
1329 None => supervisor,
1330 };
1331 let supervisor = match live_children_path {
1332 Some(path) => supervisor.with_live_children_record(path),
1333 None => supervisor,
1334 };
1335 #[cfg(target_os = "linux")]
1336 let supervisor = supervisor.with_cgroup_placement(cgroup_placement);
1337 let route_bind_relay_timeouts = configured_modules
1343 .iter()
1344 .filter_map(|module| {
1345 module
1346 .route_bind_relay_timeout_ms
1347 .map(|ms| (module.module_id.clone(), Duration::from_millis(ms)))
1348 })
1349 .collect::<std::collections::BTreeMap<_, _>>();
1350 let control_start_clock = crate::clock::StartClock::capture();
1351 let mut control = ControlHandler::with_forwarding(Arc::clone(®istry), forwarding)
1352 .with_daemon_version(bound.connection_info.daemon_ver.clone())
1353 .with_process_liveness(process_liveness)
1354 .with_supervisor(supervisor_handle)
1355 .with_daemon_shutdown_flag(supervisor.daemon_shutdown_flag())
1358 .with_connected_clients(connected_clients.clone())
1359 .with_local_endpoint_unavailable(bound.local_endpoint_unavailable.clone())
1360 .with_storage_config(storage_config)
1361 .with_machine_id(bound.machine_id.clone())
1362 .with_admission_facts_config(admission_facts.carrier_module_id, admission_facts.targets)
1363 .with_scope_authority_owners(scope_authority_owners)
1364 .with_federated_scope_owner(federated_scope_owner)
1365 .with_privileged_operator_prompt(privileged_operator_prompt)
1366 .with_route_bind_relay_timeouts(route_bind_relay_timeouts)
1367 .with_daemon_provenance(
1368 bound.connection_info.pid,
1369 control_start_clock.started_at_ms(),
1370 std::env::current_exe().ok(),
1371 normalized_build_provenance(env!("SUBC_BUILD_GIT_SHA")),
1372 normalized_build_provenance(env!("SUBC_BUILD_LOCK_DIGEST")),
1373 )
1374 .with_daemon_start_clock(control_start_clock)
1375 .with_capability_config(
1376 configured_modules
1377 .iter()
1378 .map(|module| (module.module_id.clone(), module.enabled)),
1379 reserved_capabilities,
1380 );
1381 if let Some(run_dir) = activity_run_dir {
1382 control =
1383 control.with_activity_ledger_config(&run_dir, daemon_incarnation, activity_config);
1384 }
1385 let daemon_ready_runtime = config_runtime.clone();
1386 if let Some(runtime) = config_runtime {
1387 control = control.with_explicit_config_store(runtime);
1388 }
1389 #[cfg(feature = "test-support")]
1390 if config_test_seam::enabled() {
1391 control = control.with_config_os_prompt_policy_for_tests();
1392 }
1393 if let Some(ms) = route_bind_relay_default_ms {
1394 control = control.with_route_bind_relay_timeout(Duration::from_millis(ms));
1397 }
1398 if let Some(config_path) = daemon_config_path {
1399 control = control.with_supervisor_rescan(supervisor.clone(), config_path, configured_port);
1400 control = control.with_supervisor_rescan_entries(&configured_modules);
1401 }
1402 #[cfg(all(test, feature = "test-support"))]
1403 let control = if let Some(adapt) = test_control {
1404 let executable =
1406 std::env::current_exe().map_err(|e| BootstrapError::ConfigStore(e.to_string()))?;
1407 if !executable
1408 .file_name()
1409 .is_some_and(|name| name.to_string_lossy().starts_with("ckdev-"))
1410 {
1411 return Err(BootstrapError::ConfigStore(
1412 "test control requires a ckdev executable".into(),
1413 ));
1414 }
1415 adapt(control)
1416 } else {
1417 control
1418 };
1419 let control = Arc::new(control);
1420 let router = Arc::new(Router::with_control_handler(Arc::clone(&control)));
1421 let auth = ServerAuth::new(
1422 bound.connection_info.key.clone(),
1423 bound.connection_info.daemon_id,
1424 bound.connection_info.daemon_ver.clone(),
1425 )
1426 .with_connected_clients(connected_clients);
1427
1428 let mut registered_modules = Vec::with_capacity(configured_modules.len());
1432 for configured in configured_modules {
1433 let enabled = configured.enabled;
1434 let health = configured.health.clone();
1435 let module_id = configured.module_id.clone();
1436 let registered = match supervisor.register_configured_with_health(
1437 configured.module_spec(),
1438 enabled,
1439 health.clone(),
1440 configured.drain_timeout_ms,
1441 configured.restart,
1442 configured.register_timeout,
1443 ) {
1444 Ok(registered) => registered,
1445 Err(err) => {
1446 error!(module_id = %module_id, error = %err, "failed to supervise configured module; continuing daemon startup");
1447 continue;
1448 }
1449 };
1450 registered_modules.push(registered);
1451 let default_threshold = HealthConfig::default().failure_threshold;
1454 if enabled && health.failure_threshold > default_threshold {
1455 warn!(
1456 module_id = %module_id,
1457 failure_threshold = health.failure_threshold,
1458 default_threshold,
1459 tolerance_secs = health.cadence.as_secs() * u64::from(health.failure_threshold),
1460 "health failure threshold is relaxed above the default; a wedged module stays unflagged for longer"
1461 );
1462 }
1463 info!(module_id = %module_id, enabled, "configured module registered");
1464 }
1465 control.refresh_capability_requirements();
1466
1467 let local_serve_task = bound.local_listener.map(|local_listener| {
1470 AbortOnDrop::new(tokio::spawn(serve_local_listener(
1471 local_listener,
1472 Arc::clone(&router),
1473 auth.clone(),
1474 )))
1475 });
1476 #[cfg(windows)]
1479 let _local_serve_task = local_serve_task;
1480 let mut serve_task =
1481 AbortOnDrop::new(tokio::spawn(serve_listeners(bound.listeners, router, auth)));
1482 verify_serving(&bound.connection_info).await?;
1483 let (published, publication_lock) = publish_connection_file(
1490 &bound.connection_file_path,
1491 #[cfg(windows)]
1492 bound.connection_file_copy.as_deref(),
1493 &bound.connection_info,
1494 bound.local_endpoint.as_ref(),
1495 publication_lock,
1496 )
1497 .await;
1498 published?;
1499 if let Some(owner) = daemon_ready_runtime {
1503 if let Err(error) = owner.on_blocking(|owner| owner.record_daemon_ready()).await {
1504 warn!(%error, "daemon readiness was not recorded in the approved store");
1505 }
1506 }
1507 #[cfg(test)]
1508 startup_publication_hook::run(&bound.connection_file_path).await;
1509 drop(publication_lock);
1510 let _clock_step_task = AbortOnDrop::new(crate::watchdog::spawn_clock_step_monitor());
1511 #[cfg(target_os = "linux")]
1513 let _kill_mode_check = AbortOnDrop::new(tokio::spawn(
1514 crate::systemd_kill_mode::warn_if_kill_mode_defeats_ordered_shutdown(),
1515 ));
1516 let _watchdog_task = AbortOnDrop::new(
1517 DaemonSelfWatchdog::new(
1518 bound.connection_info.clone(),
1519 bound.connection_file_path.clone(),
1520 )
1521 .with_config(watchdog_config)
1522 .spawn(),
1523 );
1524
1525 for registered in registered_modules {
1526 match supervisor
1527 .start_registered_configured_async(registered, None, true)
1528 .await
1529 {
1530 Ok(module) => {
1531 info!(module_id = %module.module_id(), "configured module supervised");
1532 }
1533 Err(err) => {
1534 error!(error = %err, "failed to start configured module; continuing daemon startup");
1535 }
1536 }
1537 }
1538
1539 control.refresh_capability_requirements();
1540 Arc::clone(&control).spawn_capability_deadline_loop();
1541 Arc::clone(&control).spawn_scope_expiry_loop();
1542 let _config_delivery_task = control.spawn_config_delivery_worker().map(AbortOnDrop::new);
1543 control.spawn_resource_sampler();
1544
1545 #[cfg(unix)]
1546 {
1547 tokio::select! {
1548 result = serve_task.join() => {
1549 return result.map_err(BootstrapError::ServeJoin)?.map_err(BootstrapError::Serve);
1550 }
1551 _ = terminate.recv() => {}
1552 }
1553 supervisor.begin_daemon_shutdown();
1558 drop(_watchdog_task);
1562 drop(serve_task);
1566 drop(local_serve_task);
1567 let second_sigterm = async {
1568 terminate.recv().await;
1569 std::time::Instant::now()
1570 };
1571 tokio::pin!(second_sigterm);
1572 let mut escalation_started = tokio::select! {
1573 biased;
1574 at = second_sigterm.as_mut() => {
1575 info!("second SIGTERM: abandoning daemon shutdown wait");
1576 Some(at)
1577 }
1578 result = supervisor.drain_for_daemon_shutdown() => {
1579 if let Err(error) = result {
1580 warn!(%error, "daemon shutdown drain failed; exiting anyway");
1581 }
1582 None
1583 }
1584 };
1585 let already_escalated = escalation_started.is_some();
1592 supervisor
1593 .end_children_for_daemon_shutdown(already_escalated, async {
1594 if already_escalated {
1595 std::future::pending::<()>().await;
1596 } else {
1597 escalation_started = Some(second_sigterm.await);
1598 }
1599 })
1600 .await;
1601 if let Some(at) = escalation_started {
1602 info!(
1603 second_sigterm_elapsed_ms = at.elapsed().as_millis() as u64,
1604 "daemon shutdown wait ended after second SIGTERM"
1605 );
1606 }
1607 info!("daemon exiting: SIGTERM shutdown complete");
1608 Ok(())
1609 }
1610 #[cfg(not(unix))]
1611 serve_task
1612 .join()
1613 .await
1614 .map_err(BootstrapError::ServeJoin)?
1615 .map_err(BootstrapError::Serve)
1616}
1617
1618fn normalized_build_provenance(value: &str) -> Option<String> {
1619 match value.trim() {
1620 "" | "unavailable" => None,
1621 value => Some(value.to_string()),
1622 }
1623}
1624
1625pub async fn ensure_singleton(
1633 connection_file_path: impl AsRef<Path>,
1634 port: u16,
1635) -> Result<Outcome, BootstrapError> {
1636 ensure_singleton_with_config(BootstrapConfig::new(connection_file_path.as_ref(), port)).await
1637}
1638
1639pub async fn ensure_singleton_with_config(
1640 config: BootstrapConfig,
1641) -> Result<Outcome, BootstrapError> {
1642 ensure_singleton_inner(config, true).await
1643}
1644
1645async fn ensure_singleton_inner(
1646 config: BootstrapConfig,
1647 publish: bool,
1648) -> Result<Outcome, BootstrapError> {
1649 let Some(lock) = singleton_start_lock(&config.connection_file_path).await? else {
1650 return Ok(Outcome::AlreadyRunning);
1651 };
1652 ensure_singleton_with_start_lock(config, publish, lock).await
1653}
1654
1655async fn singleton_start_lock(path: &Path) -> Result<Option<StartLock>, BootstrapError> {
1656 if stable_peer(path).await? {
1657 return Ok(None);
1658 }
1659
1660 let lock = StartLock::acquire(path).await?;
1661
1662 if stable_peer(path).await? {
1666 return Ok(None);
1667 }
1668 Ok(Some(lock))
1669}
1670
1671async fn ensure_singleton_with_start_lock(
1672 config: BootstrapConfig,
1673 publish: bool,
1674 lock: StartLock,
1675) -> Result<Outcome, BootstrapError> {
1676 #[cfg(windows)]
1677 let copy_path = windows_connection_copy::resolve(&config);
1678 let path = config.connection_file_path;
1679 let run_dir_lock = config
1685 .live_children_path
1686 .as_deref()
1687 .map(crate::run_dir_lock::RunDirLock::acquire)
1688 .transpose()?;
1689
1690 remove_stale_connection_file_if_present(&path)?;
1691 #[cfg(windows)]
1692 let copy_path = windows_connection_copy::reclaim(&path, copy_path).await;
1693
1694 let (machine_id, lock, run_dir_lock) = match config.machine_id_path {
1702 None => (None, lock, run_dir_lock),
1703 Some(machine_id_path) => {
1704 let task_path = machine_id_path.clone();
1705 match run_blocking_holding((lock, run_dir_lock), move || {
1706 crate::machine_id::load_or_mint(&task_path)
1707 })
1708 .await
1709 {
1710 Ok((Ok(id), (lock, run_dir_lock))) => (Some(id), lock, run_dir_lock),
1711 Ok((Err(error), _locks)) => return Err(BootstrapError::MachineId(error)),
1712 Err(join_error) => {
1713 return Err(BootstrapError::MachineId(
1714 crate::machine_id::MachineIdFileError::Write {
1715 path: machine_id_path,
1716 source: io::Error::other(describe_blocking_task_failure(
1717 "loading or minting the machine id",
1718 &join_error,
1719 )),
1720 },
1721 ))
1722 }
1723 }
1724 }
1725 };
1726
1727 let (listeners, endpoints) = bind_loopback(config.port).await?;
1728 let (local_listener, local_endpoint, local_endpoint_unavailable) =
1734 if config.local_listener.configured_dir().is_some() {
1735 match local_listener::bind(&config.local_listener, &path) {
1736 Ok(local_listener) => {
1737 let endpoint = local_listener.endpoint();
1738 (Some(local_listener), Some(endpoint), None)
1739 }
1740 Err(error) => {
1741 let reason = error.to_string();
1742 warn!(
1743 error = %reason,
1744 "the local endpoint is unavailable; serving loopback TCP only"
1745 );
1746 (None, None, Some(reason))
1747 }
1748 }
1749 } else {
1750 (None, None, None)
1751 };
1752 let connection_info = ConnectionInfo {
1753 schema: SCHEMA_VERSION,
1754 wire_version: Some(PROTOCOL_VERSION),
1755 endpoints,
1756 key: generate_key().map_err(BootstrapError::GenerateConnectionFile)?,
1757 daemon_id: generate_daemon_id().map_err(BootstrapError::GenerateConnectionFile)?,
1758 pid: process::id(),
1759 daemon_ver: config.daemon_ver,
1760 };
1761
1762 let publication_lock = if publish {
1766 let (published, lock) = publish_connection_file(
1767 &path,
1768 #[cfg(windows)]
1769 copy_path.as_deref(),
1770 &connection_info,
1771 local_endpoint.as_ref(),
1772 lock,
1773 )
1774 .await;
1775 if let Err(error) = published {
1776 if let Some(local_listener) = local_listener.as_ref() {
1777 local_listener::release(local_listener);
1778 }
1779 drop(listeners);
1780 return Err(error);
1781 }
1782 drop(lock);
1783 None
1784 } else {
1785 Some(lock)
1786 };
1787
1788 Ok(Outcome::Bound(BoundDaemon {
1789 listeners,
1790 local_listener,
1791 local_endpoint,
1792 local_endpoint_unavailable,
1793 connection_info,
1794 connection_file_path: path,
1795 connection_file_source: config.connection_file_source,
1796 #[cfg(windows)]
1797 connection_file_copy: copy_path,
1798 machine_id,
1799 run_dir_lock,
1800 publication_lock,
1801 }))
1802}
1803
1804#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1805enum Probe {
1806 Live,
1807 StaleOrAbsent,
1808}
1809
1810async fn stable_peer(path: &Path) -> Result<bool, BootstrapError> {
1811 if !matches!(probe_existing(path).await?, Probe::Live) {
1812 return Ok(false);
1813 }
1814 tokio::time::sleep(Duration::from_millis(1500)).await;
1820 Ok(matches!(probe_existing(path).await?, Probe::Live))
1821}
1822
1823async fn probe_existing(path: &Path) -> Result<Probe, BootstrapError> {
1824 let info = match connection_file::read(path) {
1825 Ok(info) => info,
1826 Err(source) if is_absent_or_stale_connection_file(&source) => {
1827 return Ok(Probe::StaleOrAbsent)
1828 }
1829 Err(source) => {
1830 return Err(BootstrapError::ConnectionFileRead {
1831 path: path.to_path_buf(),
1832 source,
1833 })
1834 }
1835 };
1836
1837 for endpoint in &info.endpoints {
1838 if matches!(probe_endpoint(&info, endpoint).await, Probe::Live) {
1839 return Ok(Probe::Live);
1840 }
1841 }
1842
1843 Ok(Probe::StaleOrAbsent)
1844}
1845
1846async fn probe_endpoint(info: &ConnectionInfo, endpoint: &Endpoint) -> Probe {
1847 let Ok(ip) = endpoint.host.parse::<IpAddr>() else {
1848 return Probe::StaleOrAbsent;
1849 };
1850 if !ip.is_loopback() {
1851 return Probe::StaleOrAbsent;
1852 }
1853 let addr = SocketAddr::new(ip, endpoint.port);
1854
1855 let mut stream = match timeout(CONNECT_TIMEOUT, TcpStream::connect(addr)).await {
1856 Ok(Ok(stream)) => stream,
1857 Ok(Err(_)) | Err(_) => return Probe::StaleOrAbsent,
1858 };
1859
1860 match authenticate_client(&mut stream, info, PROBE_AUTH_DEADLINE).await {
1861 Ok(()) => Probe::Live,
1862 Err(AuthError::DaemonIdMismatch)
1863 | Err(AuthError::InvalidServerProof)
1864 | Err(AuthError::UnexpectedEof { .. })
1865 | Err(AuthError::Timeout { .. })
1866 | Err(AuthError::JsonEncode { .. })
1867 | Err(AuthError::JsonDecode { .. })
1868 | Err(AuthError::Io { .. })
1869 | Err(AuthError::MessageTooLarge { .. })
1870 | Err(AuthError::KeyTooShort { .. })
1871 | Err(AuthError::Random(_))
1872 | Err(AuthError::InvalidClientAuth) => Probe::StaleOrAbsent,
1873 }
1874}
1875
1876async fn verify_serving(info: &ConnectionInfo) -> Result<(), BootstrapError> {
1877 if let Some(endpoint) = info.endpoints.first() {
1881 if matches!(probe_endpoint(info, endpoint).await, Probe::Live) {
1882 return Ok(());
1883 }
1884 }
1885 Err(BootstrapError::StartupNotServing)
1886}
1887
1888async fn run_blocking_holding<G, T>(
1903 guards: G,
1904 work: impl FnOnce() -> T + Send + 'static,
1905) -> Result<(T, G), JoinError>
1906where
1907 G: Send + 'static,
1908 T: Send + 'static,
1909{
1910 tokio::task::spawn_blocking(move || {
1911 let output = work();
1912 (output, guards)
1913 })
1914 .await
1915}
1916
1917fn describe_blocking_task_failure(work: &str, join_error: &JoinError) -> String {
1919 if join_error.is_panic() {
1920 format!("the background thread {work} panicked before finishing: {join_error}")
1921 } else {
1922 format!(
1923 "the background thread {work} was cancelled before finishing, because the async runtime is shutting down: {join_error}"
1924 )
1925 }
1926}
1927
1928async fn publish_connection_file<G: Send + 'static>(
1945 path: &Path,
1946 #[cfg(windows)] copy_path: Option<&Path>,
1947 info: &ConnectionInfo,
1948 local_endpoint: Option<&LocalEndpoint>,
1949 guard: G,
1950) -> (Result<(), BootstrapError>, Option<G>) {
1951 let task_path = path.to_path_buf();
1952 let task_info = info.clone();
1953 let task_endpoint = local_endpoint.cloned();
1954 #[cfg(windows)]
1955 let copy = windows_connection_copy::claim_for_publication(path, copy_path, info).await;
1956 let outcome = run_blocking_holding(guard, move || {
1957 write_connection_file(&task_path, &task_info, task_endpoint.as_ref())?;
1958 #[cfg(windows)]
1959 if let Some((copy_path, _lock)) = copy {
1960 if let Err(error) =
1961 write_connection_file(©_path, &task_info, task_endpoint.as_ref())
1962 {
1963 windows_connection_copy::warn_unavailable(&task_path, Some(©_path), &error);
1964 }
1965 }
1966 Ok(())
1967 })
1968 .await;
1969 match outcome {
1970 Ok((Ok(()), guard)) => (Ok(()), Some(guard)),
1971 Ok((Err(source), guard)) => (
1972 Err(BootstrapError::ConnectionFileWrite {
1973 path: path.to_path_buf(),
1974 source,
1975 }),
1976 Some(guard),
1977 ),
1978 Err(join_error) => (
1979 Err(BootstrapError::ConnectionFileWrite {
1980 path: path.to_path_buf(),
1981 source: ConnectionFileError::Io {
1982 op: "write",
1983 path: path.to_path_buf(),
1984 source: io::Error::other(describe_blocking_task_failure(
1985 "writing the connection file",
1986 &join_error,
1987 )),
1988 },
1989 }),
1990 None,
1991 ),
1992 }
1993}
1994
1995fn write_connection_file(
2002 path: &Path,
2003 info: &ConnectionInfo,
2004 local_endpoint: Option<&LocalEndpoint>,
2005) -> Result<(), ConnectionFileError> {
2006 #[cfg(test)]
2007 connection_file_write_hook::run(path);
2008 write_atomic_with_local_endpoint(path, info, local_endpoint)
2009}
2010
2011#[cfg(test)]
2014mod connection_file_write_hook {
2015 use std::{
2016 path::{Path, PathBuf},
2017 sync::{Mutex, PoisonError},
2018 };
2019
2020 type Hook = Box<dyn FnOnce() + Send>;
2021
2022 static HOOKS: Mutex<Vec<(PathBuf, Hook)>> = Mutex::new(Vec::new());
2025
2026 pub(super) fn install(path: &Path, hook: impl FnOnce() + Send + 'static) {
2028 HOOKS
2029 .lock()
2030 .unwrap_or_else(PoisonError::into_inner)
2031 .push((path.to_path_buf(), Box::new(hook)));
2032 }
2033
2034 pub(super) fn run(path: &Path) {
2035 let hook = {
2036 let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
2037 hooks
2038 .iter()
2039 .position(|(hooked, _)| hooked == path)
2040 .map(|index| hooks.swap_remove(index).1)
2041 };
2042 if let Some(hook) = hook {
2043 hook();
2044 }
2045 }
2046}
2047
2048#[cfg(test)]
2051mod startup_publication_hook {
2052 use std::{
2053 path::{Path, PathBuf},
2054 sync::{Mutex, PoisonError},
2055 };
2056 use tokio::sync::oneshot;
2057
2058 type Barrier = (oneshot::Sender<()>, oneshot::Receiver<()>);
2059 static BARRIERS: Mutex<Vec<(PathBuf, Barrier)>> = Mutex::new(Vec::new());
2060
2061 pub(super) fn install(path: &Path) -> (oneshot::Receiver<()>, oneshot::Sender<()>) {
2062 let (entered_tx, entered_rx) = oneshot::channel();
2063 let (release_tx, release_rx) = oneshot::channel();
2064 BARRIERS
2065 .lock()
2066 .unwrap_or_else(PoisonError::into_inner)
2067 .push((path.to_path_buf(), (entered_tx, release_rx)));
2068 (entered_rx, release_tx)
2069 }
2070
2071 pub(super) async fn run(path: &Path) {
2072 let barrier = {
2073 let mut barriers = BARRIERS.lock().unwrap_or_else(PoisonError::into_inner);
2074 barriers
2075 .iter()
2076 .position(|(hooked, _)| hooked == path)
2077 .map(|index| barriers.swap_remove(index).1)
2078 };
2079 if let Some((entered, release)) = barrier {
2080 let _ = entered.send(());
2081 let _ = release.await;
2082 }
2083 }
2084}
2085
2086fn is_absent_or_stale_connection_file(err: &ConnectionFileError) -> bool {
2087 match err {
2088 ConnectionFileError::Io { source, .. } if source.kind() == io::ErrorKind::NotFound => true,
2089 ConnectionFileError::JsonRead { .. }
2090 | ConnectionFileError::UnsupportedSchema { .. }
2091 | ConnectionFileError::Invalid { .. }
2092 | ConnectionFileError::KeyTooShort { .. }
2093 | ConnectionFileError::InsecurePermissions { .. } => true,
2097 ConnectionFileError::MissingParent { .. }
2098 | ConnectionFileError::MissingFileName { .. }
2099 | ConnectionFileError::InsecureParentDirectory { .. }
2103 | ConnectionFileError::Io { .. }
2104 | ConnectionFileError::JsonWrite { .. }
2105 | ConnectionFileError::Random(_)
2106 | ConnectionFileError::WireVersionMismatch { .. } => false,
2109 }
2110}
2111
2112fn remove_stale_connection_file_if_present(path: &Path) -> Result<(), BootstrapError> {
2113 match fs::remove_file(path) {
2114 Ok(()) => Ok(()),
2115 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
2116 Err(source) => Err(BootstrapError::RemoveStale {
2117 path: path.to_path_buf(),
2118 source,
2119 }),
2120 }
2121}
2122
2123async fn bind_loopback(port: u16) -> Result<(Vec<TcpListener>, Vec<Endpoint>), BootstrapError> {
2124 bind_loopback_with(port, |port| TcpListener::bind((Ipv6Addr::LOCALHOST, port))).await
2125}
2126
2127async fn bind_loopback_with<F, Fut>(
2128 port: u16,
2129 mut bind_v6: F,
2130) -> Result<(Vec<TcpListener>, Vec<Endpoint>), BootstrapError>
2131where
2132 F: FnMut(u16) -> Fut,
2133 Fut: std::future::Future<Output = io::Result<TcpListener>>,
2134{
2135 let v4_host = Ipv4Addr::LOCALHOST;
2136 let v4 = TcpListener::bind((v4_host, port))
2137 .await
2138 .map_err(|source| BootstrapError::Bind {
2139 host: v4_host.to_string(),
2140 port,
2141 source,
2142 })?;
2143 let actual_port = v4
2144 .local_addr()
2145 .map_err(|source| BootstrapError::LocalAddr {
2146 host: v4_host.to_string(),
2147 source,
2148 })?
2149 .port();
2150
2151 let mut listeners = vec![v4];
2152 let mut endpoints = vec![Endpoint {
2153 host: v4_host.to_string(),
2154 port: actual_port,
2155 }];
2156
2157 let v6_host = Ipv6Addr::LOCALHOST;
2158 match bind_v6(actual_port).await {
2159 Ok(v6) => {
2160 listeners.push(v6);
2161 endpoints.push(Endpoint {
2162 host: v6_host.to_string(),
2163 port: actual_port,
2164 });
2165 }
2166 Err(err)
2167 if ipv6_loopback_unavailable(&err)
2168 || (port == 0 && err.kind() == io::ErrorKind::AddrInUse) =>
2169 {
2170 warn!(
2171 port = actual_port,
2172 error = %err,
2173 "IPv6 loopback unavailable; serving only IPv4 loopback"
2174 );
2175 }
2176 Err(source) => {
2177 drop(listeners);
2178 return Err(BootstrapError::Bind {
2179 host: v6_host.to_string(),
2180 port: actual_port,
2181 source,
2182 });
2183 }
2184 }
2185
2186 Ok((listeners, endpoints))
2187}
2188
2189fn ipv6_loopback_unavailable(err: &io::Error) -> bool {
2190 matches!(
2191 err.kind(),
2192 io::ErrorKind::AddrNotAvailable | io::ErrorKind::Unsupported
2193 ) || matches!(err.raw_os_error(), Some(47) | Some(49) | Some(97))
2194}
2195
2196struct AbortOnDrop<T> {
2197 handle: JoinHandle<T>,
2198}
2199
2200impl<T> AbortOnDrop<T> {
2201 fn new(handle: JoinHandle<T>) -> Self {
2202 Self { handle }
2203 }
2204
2205 async fn join(&mut self) -> Result<T, JoinError> {
2206 (&mut self.handle).await
2207 }
2208}
2209
2210impl<T> Drop for AbortOnDrop<T> {
2211 fn drop(&mut self) {
2212 if !self.handle.is_finished() {
2213 self.handle.abort();
2214 }
2215 }
2216}
2217
2218#[derive(Debug)]
2219struct StartLock {
2220 _file: fs::File,
2222}
2223
2224impl Drop for StartLock {
2225 fn drop(&mut self) {
2226 if let Err(error) = FileExt::unlock(&self._file) {
2230 tracing::warn!(%error, "failed to release the singleton start lock");
2231 }
2232 }
2233}
2234
2235impl StartLock {
2236 async fn acquire(connection_file_path: &Path) -> Result<Self, BootstrapError> {
2237 let path = start_lock_path(connection_file_path);
2238 for _ in 0..START_LOCK_RETRIES {
2239 let file = match open_owner_only_lock(&path) {
2240 Ok(file) => file,
2241 Err(source) => return Err(BootstrapError::StartLockCreate { path, source }),
2242 };
2243 match FileExt::try_lock(&file) {
2244 Ok(()) => return Ok(Self { _file: file }),
2245 Err(TryLockError::WouldBlock) => sleep(START_LOCK_RETRY_DELAY).await,
2246 Err(TryLockError::Error(source)) => {
2247 return Err(BootstrapError::StartLockCreate { path, source });
2248 }
2249 }
2250 }
2251
2252 Err(BootstrapError::StartLockBusy {
2253 path,
2254 attempts: START_LOCK_RETRIES,
2255 })
2256 }
2257}
2258
2259pub(crate) fn open_owner_only_lock(path: &Path) -> io::Result<fs::File> {
2260 let mut options = fs::OpenOptions::new();
2261 options.read(true).write(true).create(true);
2262 #[cfg(unix)]
2263 {
2264 use std::os::unix::fs::OpenOptionsExt;
2265 options.mode(0o600);
2266 }
2267 options.open(path)
2268}
2269
2270fn start_lock_path(connection_file_path: &Path) -> PathBuf {
2271 let file_name = connection_file_path
2272 .file_name()
2273 .map(|name| name.to_string_lossy())
2274 .unwrap_or_else(|| CONNECTION_FILE_NAME.into());
2275 let lock_name = format!("{file_name}.start-lock");
2276 connection_file_path
2277 .parent()
2278 .filter(|parent| !parent.as_os_str().is_empty())
2279 .unwrap_or_else(|| Path::new("."))
2280 .join(lock_name)
2281}
2282
2283fn non_empty_os_var(key: &str) -> Option<OsString> {
2284 let value = env::var_os(key)?;
2285 if value.is_empty() {
2286 None
2287 } else {
2288 Some(value)
2289 }
2290}
2291
2292#[derive(Debug)]
2295#[non_exhaustive]
2296pub enum BootstrapError {
2297 ConfigStore(String),
2298 StartupNotServing,
2300 #[cfg(unix)]
2301 Signal(io::Error),
2302 InvalidPort {
2303 raw: String,
2304 source: std::num::ParseIntError,
2305 },
2306 ConnectionFileRead {
2307 path: PathBuf,
2308 source: ConnectionFileError,
2309 },
2310 ConnectionFileWrite {
2311 path: PathBuf,
2312 source: ConnectionFileError,
2313 },
2314 GenerateConnectionFile(ConnectionFileError),
2315 StartLockCreate {
2316 path: PathBuf,
2317 source: io::Error,
2318 },
2319 StartLockBusy {
2320 path: PathBuf,
2321 attempts: usize,
2322 },
2323 RunDirLockCreate {
2325 path: PathBuf,
2326 source: io::Error,
2327 },
2328 RunDirBusy {
2333 path: PathBuf,
2334 holder_pid: Option<u32>,
2335 },
2336 RemoveStale {
2337 path: PathBuf,
2338 source: io::Error,
2339 },
2340 Bind {
2341 host: String,
2342 port: u16,
2343 source: io::Error,
2344 },
2345 LocalAddr {
2346 host: String,
2347 source: io::Error,
2348 },
2349 DaemonConfig(DaemonConfigError),
2350 MachineId(crate::machine_id::MachineIdFileError),
2353 RunDir(daemon_config::DaemonRunDirError),
2356 Serve(ServerError),
2357 ServeJoin(tokio::task::JoinError),
2358}
2359
2360impl From<ServerError> for BootstrapError {
2361 fn from(error: ServerError) -> Self {
2362 Self::Serve(error)
2363 }
2364}
2365
2366impl fmt::Display for BootstrapError {
2367 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2368 match self {
2369 Self::ConfigStore(error) => write!(f, "configuration store startup refused: {error}"),
2370 Self::StartupNotServing => write!(f, "bound daemon did not authenticate its readiness probe; connection file was not published"),
2371 #[cfg(unix)]
2372 Self::Signal(error) => write!(f, "failed to register SIGTERM handler: {error}"),
2373 Self::InvalidPort { raw, source } => {
2374 write!(f, "invalid {SUBC_PORT_ENV} value '{raw}': {source}")
2375 }
2376 Self::ConnectionFileRead { path, source } => write!(
2377 f,
2378 "failed to read connection file {}: {source}",
2379 path.display()
2380 ),
2381 Self::ConnectionFileWrite { path, source } => write!(
2382 f,
2383 "failed to publish connection file {}: {source}",
2384 path.display()
2385 ),
2386 Self::GenerateConnectionFile(err) => {
2387 write!(f, "failed to generate connection-file auth material: {err}")
2388 }
2389 Self::StartLockCreate { path, source } => {
2390 write!(
2391 f,
2392 "failed to create start lock {}: {source}",
2393 path.display()
2394 )
2395 }
2396 Self::StartLockBusy { path, attempts } => write!(
2397 f,
2398 "start lock {} remained busy after {attempts} attempts",
2399 path.display()
2400 ),
2401 Self::RunDirLockCreate { path, source } => write!(
2402 f,
2403 "refusing to start: failed to lock run directory via {}: {source}",
2404 path.display()
2405 ),
2406 Self::RunDirBusy { path, holder_pid } => {
2407 write!(
2408 f,
2409 "refusing to start: run directory lock {} is held by another daemon",
2410 path.display()
2411 )?;
2412 if let Some(pid) = holder_pid {
2413 write!(f, " (pid {pid})")?;
2414 }
2415 write!(
2416 f,
2417 "; a live daemon owns this data home's run state (typically one started with a different XDG_RUNTIME_DIR)"
2418 )
2419 }
2420 Self::RemoveStale { path, source } => write!(
2421 f,
2422 "failed to remove stale connection file {}: {source}",
2423 path.display()
2424 ),
2425 Self::Bind { host, port, source } if source.kind() == io::ErrorKind::AddrInUse => {
2426 write!(
2427 f,
2428 "port {port} in use on loopback {host}: {source}; set the port in config"
2429 )
2430 }
2431 Self::Bind { host, port, source } => {
2432 write!(f, "failed to bind loopback TCP {host}:{port}: {source}")
2433 }
2434 Self::LocalAddr { host, source } => {
2435 write!(f, "failed to read local address for {host}: {source}")
2436 }
2437 Self::DaemonConfig(err) => write!(f, "failed to load daemon config: {err}"),
2438 Self::MachineId(err) => write!(f, "refusing to start: {err}"),
2439 Self::RunDir(err) => write!(f, "refusing to start: {err}"),
2440 Self::Serve(err) => write!(f, "daemon server failed: {err}"),
2441 Self::ServeJoin(err) => write!(f, "daemon server task failed: {err}"),
2442 }
2443 }
2444}
2445
2446impl Error for BootstrapError {
2447 fn source(&self) -> Option<&(dyn Error + 'static)> {
2448 match self {
2449 Self::ConfigStore(_) => None,
2450 Self::StartupNotServing => None,
2451 #[cfg(unix)]
2452 Self::Signal(source) => Some(source),
2453 Self::InvalidPort { source, .. } => Some(source),
2454 Self::ConnectionFileRead { source, .. }
2455 | Self::ConnectionFileWrite { source, .. }
2456 | Self::GenerateConnectionFile(source) => Some(source),
2457 Self::StartLockCreate { source, .. }
2458 | Self::RunDirLockCreate { source, .. }
2459 | Self::RemoveStale { source, .. }
2460 | Self::Bind { source, .. }
2461 | Self::LocalAddr { source, .. } => Some(source),
2462 Self::DaemonConfig(err) => Some(err),
2463 Self::MachineId(err) => Some(err),
2464 Self::RunDir(err) => Some(err),
2465 Self::Serve(err) => Some(err),
2466 Self::ServeJoin(err) => Some(err),
2467 Self::StartLockBusy { .. } | Self::RunDirBusy { .. } => None,
2468 }
2469 }
2470}
2471
2472#[cfg(all(test, feature = "test-support", unix))]
2473#[path = "bootstrap_recovery_tests.rs"]
2474mod recovery_tests;
2475
2476#[cfg(test)]
2477mod tests {
2478 mod activity {
2479 include!("activity_bootstrap_tests.rs");
2480 }
2481 mod startup_order {
2482 include!("startup_order_tests.rs");
2483 }
2484 use super::*;
2485 use crate::server::ServerAuth;
2486 use cortexkit_test_support::ScratchDir;
2487 #[cfg(target_os = "linux")]
2488 use std::collections::BTreeSet;
2489 use std::sync::Mutex;
2490 #[cfg(target_os = "linux")]
2491 use subc_control::ModuleProtocol;
2492 use subc_transport::{write_atomic, MIN_KEY_LEN};
2493 use tokio::io::AsyncReadExt;
2494 use tokio::task::JoinHandle;
2495
2496 #[cfg(unix)]
2497 use std::os::unix::fs::PermissionsExt;
2498
2499 static ENV_LOCK: Mutex<()> = Mutex::new(());
2500
2501 #[test]
2502 fn normalized_build_provenance_preserves_real_values() {
2503 assert_eq!(normalized_build_provenance("abc"), Some("abc".to_string()));
2504 }
2505
2506 #[test]
2507 fn config_recovery_bootstrap_preserves_all_loaded_fields_and_only_argument_overrides() {
2508 let _env_lock = ENV_LOCK.lock().unwrap();
2509 let scratch = unique_temp_dir("bootstrap-loaded-fields");
2510 let file = scratch.join("subc.jsonc");
2511 std::fs::write(
2512 &file,
2513 br#"{"version":1,"modules":{},"scope_authority_owners":["file-owner"]}"#,
2514 )
2515 .unwrap();
2516 let mut config = BootstrapConfig::new(scratch.join("connection.json"), 0)
2517 .with_daemon_config_source(file.clone(), None);
2518 config.defer_file_load = true;
2519 config.operator_timeout = Duration::from_secs(7);
2520 let selected = load_bootstrap_authority(config, None).unwrap();
2521 assert_eq!(
2522 selected.file_derived_test_probe,
2523 Some(vec!["file-owner".into()])
2524 );
2525 assert_eq!(selected.operator_timeout, Duration::from_secs(7));
2526 assert_eq!(selected.daemon_config_path, Some(file));
2527 assert_eq!(
2528 selected.connection_file_path,
2529 scratch.join("connection.json")
2530 );
2531 }
2532
2533 #[test]
2534 fn config_recovery_bootstrap_ignores_invalid_live_file_and_poisoned_settings() {
2535 let scratch = unique_temp_dir("recovery-bootstrap");
2536 let root = scratch.join("store");
2537 std::fs::create_dir_all(&root).unwrap();
2538 std::fs::write(
2539 root.join(crate::config_store::STORE_FILE),
2540 br#"{"format_version":999}"#,
2541 )
2542 .unwrap();
2543 let mut store = crate::config_store::ConfigStore::open_digest_only_for_tests(
2544 crate::config_store::StoreRoot::from_service_definition(root).unwrap(),
2545 );
2546 assert_eq!(
2547 store.status().state,
2548 crate::config_store::StoreState::StoreUnverified
2549 );
2550 let file = scratch.join("subc.jsonc");
2551 std::fs::write(&file, b"invalid live config").unwrap();
2552 let mut config = BootstrapConfig::new(scratch.join("connection.json"), 1)
2553 .with_daemon_config_source(file, Some(1))
2554 .with_scope_authority_owners(vec!["untrusted".into()])
2555 .with_reserved_capabilities(BTreeMap::from([("untrusted".into(), "untrusted".into())]));
2556 config.defer_file_load = true;
2557 config.file_derived_test_probe = Some(vec!["untrusted".into()]);
2558 let config = load_bootstrap_authority(config, Some(&mut store)).unwrap();
2559 assert_eq!(config.file_derived_test_probe, None);
2560 assert_eq!(config.port, DEFAULT_SUBC_PORT);
2561 assert!(config.configured_modules.is_empty());
2562 assert_eq!(
2563 config.scope_authority_owners,
2564 daemon_config::default_scope_authority_owners()
2565 );
2566 assert!(config.reserved_capabilities.is_empty());
2567 assert_eq!(
2568 config.privileged_operator_prompt,
2569 daemon_config::PrivilegedOperatorPrompt::default()
2570 );
2571 }
2572
2573 fn approved_port_entry(
2576 kind: crate::config_store::CommitKind,
2577 port: u16,
2578 ) -> crate::config_store::HistoryEntry {
2579 use subc_protocol::config::{ConfigLayer, ConfigLayerSnapshot};
2580 crate::config_store::HistoryEntry {
2581 generation: subc_config::Generation::new(
2582 0,
2583 subc_config::ApprovalChannel::OsPrompt,
2584 subc_config::raw_digest(b"approved-plan"),
2585 subc_config::InputVector::default(),
2586 subc_config::Changeset::new(),
2587 ),
2588 kind,
2589 approval_id: "approval".into(),
2590 outcome: "approved".into(),
2591 tuples: Default::default(),
2592 project_outcomes: Default::default(),
2593 configuration: Default::default(),
2594 delivery: Some(crate::config_store::DeliverySnapshot {
2595 daemon: Some(ConfigLayerSnapshot::file(
2596 "subc",
2597 ConfigLayer::User,
2598 "/approved/subc.jsonc",
2599 Some(format!(r#"{{"version":1,"port":{port},"modules":{{}}}}"#).into_bytes()),
2600 )),
2601 ..crate::config_store::DeliverySnapshot::default()
2602 }),
2603 }
2604 }
2605
2606 fn approve_port(
2607 store: &mut crate::config_store::ConfigStore,
2608 kind: crate::config_store::CommitKind,
2609 port: u16,
2610 ) {
2611 store
2612 .commit_generation(
2613 approved_port_entry(kind, port),
2614 Default::default(),
2615 Default::default(),
2616 1,
2617 )
2618 .unwrap();
2619 }
2620
2621 fn stamped_boot(
2622 scratch: &Path,
2623 store: &mut crate::config_store::ConfigStore,
2624 ) -> BootstrapConfig {
2625 let mut config = BootstrapConfig::new(scratch.join("connection.json"), 1)
2626 .with_daemon_config_source(scratch.join("subc.jsonc"), Some(1));
2627 config.defer_file_load = true;
2628 load_bootstrap_authority(config, Some(store)).unwrap()
2629 }
2630
2631 #[test]
2632 fn config_stamped_boot_uses_last_active_generation_until_restart_intent() {
2633 use crate::config_store::{CommitKind, ConfigStore, StoreRoot};
2634 let scratch = unique_temp_dir("stamped-boot-selection");
2635 let root = scratch.join("store");
2636 std::fs::create_dir_all(&root).unwrap();
2637 let open = || {
2638 ConfigStore::open_digest_only_for_tests(
2639 StoreRoot::from_service_definition(root.clone()).unwrap(),
2640 )
2641 };
2642 let mut store = open();
2643 approve_port(&mut store, CommitKind::Stamp, 41001);
2644 approve_port(&mut store, CommitKind::Approved, 41002);
2645 drop(store);
2646 let mut store = open();
2647 assert_eq!(
2648 stamped_boot(&scratch, &mut store).port,
2649 41001,
2650 "an ordinary start must not boot an approval still waiting for a daemon restart"
2651 );
2652 assert_eq!(store.assign_daemon_restart().unwrap(), Some(2));
2653 drop(store);
2654 let mut store = open();
2655 assert_eq!(stamped_boot(&scratch, &mut store).port, 41002);
2656 }
2657
2658 #[test]
2659 fn config_stamped_boot_enters_recovery_when_anchor_retry_fails_at_start() {
2660 use crate::config_store::{CommitKind, ConfigStore, StoreRoot, StoreState, TestStoreKey};
2661 let scratch = unique_temp_dir("stamped-boot-anchor-pending");
2662 let root = scratch.join("store");
2663 std::fs::create_dir_all(&root).unwrap();
2664 let key = TestStoreKey::default();
2665 let open = || {
2666 ConfigStore::open_sealed_for_tests(
2667 StoreRoot::from_service_definition(root.clone()).unwrap(),
2668 key.clone(),
2669 )
2670 };
2671 let mut store = open();
2672 approve_port(&mut store, CommitKind::Stamp, 41001);
2673 key.fail_anchor(true);
2676 assert!(store
2677 .commit_generation(
2678 approved_port_entry(CommitKind::Approved, 41001),
2679 Default::default(),
2680 Default::default(),
2681 2,
2682 )
2683 .is_err());
2684 drop(store);
2685 let mut store = open();
2686 let status = store.status();
2687 assert_eq!(status.state, StoreState::Stamped);
2688 assert!(status.anchor_pending);
2689 let config = stamped_boot(&scratch, &mut store);
2690 assert_eq!(config.port, DEFAULT_SUBC_PORT);
2691 assert!(config.configured_modules.is_empty());
2692 assert_eq!(store.status().state, StoreState::StoreUnverified);
2693 }
2694
2695 #[test]
2696 fn normalized_build_provenance_omits_unavailable_and_empty_values() {
2697 assert_eq!(normalized_build_provenance("unavailable"), None);
2698 assert_eq!(normalized_build_provenance(""), None);
2699 }
2700
2701 #[cfg(target_os = "linux")]
2702 fn current_cgroup_path_for_test() -> io::Result<PathBuf> {
2703 let cgroups = fs::read_to_string("/proc/self/cgroup")?;
2704 let relative = cgroups
2705 .lines()
2706 .find_map(|line| line.strip_prefix("0::"))
2707 .ok_or_else(|| {
2708 io::Error::new(io::ErrorKind::Unsupported, "cgroup v2 is unavailable")
2709 })?;
2710 Ok(Path::new("/sys/fs/cgroup").join(relative.trim_start_matches('/')))
2711 }
2712
2713 #[cfg(target_os = "linux")]
2714 fn module_cgroup_directories() -> io::Result<BTreeSet<OsString>> {
2715 let modules = current_cgroup_path_for_test()?.join("subc-modules");
2716 let entries = match fs::read_dir(modules) {
2717 Ok(entries) => entries,
2718 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(BTreeSet::new()),
2719 Err(error) => return Err(error),
2720 };
2721 let mut directories = BTreeSet::new();
2722 for entry in entries {
2723 let entry = entry?;
2724 if entry.file_type()?.is_dir() {
2725 directories.insert(entry.file_name());
2726 }
2727 }
2728 Ok(directories)
2729 }
2730
2731 #[cfg(target_os = "linux")]
2732 async fn wait_for_path(path: &Path, task: &JoinHandle<Result<(), BootstrapError>>) {
2733 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
2734 while !path.exists() && tokio::time::Instant::now() < deadline {
2735 assert!(
2736 !task.is_finished(),
2737 "daemon exited before creating {}",
2738 path.display()
2739 );
2740 sleep(Duration::from_millis(10)).await;
2741 }
2742 assert!(path.exists(), "daemon did not create {}", path.display());
2743 }
2744
2745 #[cfg(target_os = "linux")]
2750 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2751 async fn run_with_config_does_not_reconcile_the_ambient_cgroup_by_default() {
2752 let temp = unique_temp_dir("bootstrap-cgroup-default-disabled");
2753 let module_id = format!("cgroup-isolation-probe-{}", process::id());
2754 let before = module_cgroup_directories().expect("read ambient module cgroups before boot");
2755 assert!(
2756 !before.contains(&OsString::from(&module_id)),
2757 "isolation probe cgroup already exists before this daemon starts"
2758 );
2759 let capture = temp.join("logs").join(format!("{module_id}.stderr.log"));
2760 let module = ConfiguredModule {
2761 script: None,
2762 carry_containment: false,
2763 module_id,
2764 program: PathBuf::from("sh"),
2765 args: vec!["-c".to_string(), "sleep 30".to_string()],
2766 env: Vec::new(),
2767 log: None,
2768 enabled: true,
2769 registration_channel: false,
2770 reserved: false,
2771 reserved_prefixes: Vec::new(),
2772 protocol: ModuleProtocol::None,
2773 overlap: Default::default(),
2774 health: HealthConfig::default(),
2775 drain_timeout_ms: None,
2776 register_timeout: crate::supervise::DEFAULT_REGISTER_TIMEOUT,
2777 route_bind_relay_timeout_ms: None,
2778 restart: RestartPolicy::default(),
2779 };
2780 let config = config_with_a_short_socket(BootstrapConfig::new(temp.join("c"), 0))
2781 .with_configured_modules([module])
2782 .with_capture_logs_dir(temp.join("logs"))
2783 .with_terminal_journal_path(temp.join("terminals.jsonl"));
2784 let task = tokio::spawn(run_with_config(config));
2785
2786 wait_for_path(&capture, &task).await;
2787 let after = module_cgroup_directories().expect("read ambient module cgroups after boot");
2788
2789 task.abort();
2790 assert!(task
2791 .await
2792 .expect_err("aborted daemon task must cancel")
2793 .is_cancelled());
2794 assert_eq!(
2795 before, after,
2796 "an in-process daemon must not create or reconcile ambient module cgroups"
2797 );
2798 }
2799
2800 #[cfg(target_os = "linux")]
2801 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2802 async fn explicit_cgroup_root_is_prepared_inside_the_fixture_tree() {
2803 let temp = unique_temp_dir("bootstrap-cgroup-explicit-root");
2804 let cgroup_root = temp.join("cgroup");
2805 fs::create_dir(&cgroup_root).expect("create scratch cgroup root");
2806 fs::write(cgroup_root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
2807 let modules = cgroup_root.join("subc-modules");
2808 let config = config_with_a_short_socket(BootstrapConfig::new(temp.join("c"), 0))
2809 .with_cgroup_placement(CgroupPlacementConfig::Root(cgroup_root))
2810 .with_terminal_journal_path(temp.join("terminals.jsonl"));
2811 let task = tokio::spawn(run_with_config(config));
2812
2813 wait_for_path(&modules, &task).await;
2814
2815 task.abort();
2816 assert!(task
2817 .await
2818 .expect_err("aborted daemon task must cancel")
2819 .is_cancelled());
2820 assert!(
2821 fs::read_dir(&modules)
2822 .expect("read prepared modules directory")
2823 .next()
2824 .is_none(),
2825 "the delegation probe must clean up after itself"
2826 );
2827 }
2828
2829 struct EnvGuard {
2830 key: &'static str,
2831 previous: Option<OsString>,
2832 }
2833
2834 impl EnvGuard {
2835 fn set(key: &'static str, value: &Path) -> Self {
2836 let previous = env::var_os(key);
2837 env::set_var(key, value);
2838 Self { key, previous }
2839 }
2840
2841 fn set_str(key: &'static str, value: &str) -> Self {
2842 let previous = env::var_os(key);
2843 env::set_var(key, value);
2844 Self { key, previous }
2845 }
2846
2847 fn unset(key: &'static str) -> Self {
2848 let previous = env::var_os(key);
2849 env::remove_var(key);
2850 Self { key, previous }
2851 }
2852 }
2853
2854 impl Drop for EnvGuard {
2855 fn drop(&mut self) {
2856 match &self.previous {
2857 Some(value) => env::set_var(self.key, value),
2858 None => env::remove_var(self.key),
2859 }
2860 }
2861 }
2862
2863 fn unique_temp_dir(name: &str) -> ScratchDir {
2864 ScratchDir::new(name)
2865 }
2866
2867 fn temp_connection_file_path(name: &str) -> (ScratchDir, PathBuf) {
2868 let dir = unique_temp_dir(name);
2869 let path = dir.join("conn.json");
2870 (dir, path)
2871 }
2872
2873 fn auth_for(info: &ConnectionInfo) -> ServerAuth {
2874 ServerAuth::new(info.key.clone(), info.daemon_id, info.daemon_ver.clone())
2875 }
2876
2877 fn start_server(bound: BoundDaemon) -> JoinHandle<Result<(), ServerError>> {
2878 let auth = auth_for(&bound.connection_info);
2879 tokio::spawn(serve_listeners(
2880 bound.listeners,
2881 Arc::new(Router::with_default_self_handler()),
2882 auth,
2883 ))
2884 }
2885
2886 fn expect_bound(outcome: Outcome) -> BoundDaemon {
2887 match outcome {
2888 Outcome::Bound(bound) => bound,
2889 Outcome::AlreadyRunning => panic!("fresh connection file unexpectedly had a daemon"),
2890 }
2891 }
2892
2893 async fn connect_from_info(conn: &ConnectionInfo) -> io::Result<TcpStream> {
2894 let endpoint = conn
2895 .endpoints
2896 .first()
2897 .expect("test connection file should have an endpoint");
2898 let ip: IpAddr = endpoint.host.parse().unwrap();
2899 TcpStream::connect(SocketAddr::new(ip, endpoint.port)).await
2900 }
2901
2902 fn make_connection_info(port: u16) -> ConnectionInfo {
2903 ConnectionInfo {
2904 schema: SCHEMA_VERSION,
2905 wire_version: Some(PROTOCOL_VERSION),
2906 endpoints: vec![Endpoint {
2907 host: "127.0.0.1".to_owned(),
2908 port,
2909 }],
2910 key: generate_key().unwrap(),
2911 daemon_id: generate_daemon_id().unwrap(),
2912 pid: process::id(),
2913 daemon_ver: "test-subc".to_owned(),
2914 }
2915 }
2916
2917 fn write_raw_owner_only_connection_file(path: &Path, contents: &[u8]) {
2918 fs::write(path, contents).unwrap();
2919 #[cfg(unix)]
2920 fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
2921 }
2922
2923 fn assert_owner_only_connection_file(path: &Path) {
2924 #[cfg(unix)]
2927 {
2928 let mode = fs::metadata(path).unwrap().permissions().mode() & 0o777;
2929 assert_eq!(mode, 0o600);
2930 }
2931 #[cfg(not(unix))]
2932 let _ = path;
2933 }
2934
2935 #[test]
2936 fn connection_file_path_uses_xdg_runtime_dir_when_set() {
2937 let _env_lock = ENV_LOCK.lock().unwrap();
2938 let runtime_dir = unique_temp_dir("xdg-runtime");
2939 let _xdg = EnvGuard::set("XDG_RUNTIME_DIR", runtime_dir.path());
2940
2941 assert_eq!(
2942 connection_file_path(),
2943 runtime_dir.join(CONNECTION_FILE_NAME)
2944 );
2945 }
2946
2947 #[test]
2948 fn connection_file_path_source_is_xdg_runtime_dir_when_set() {
2949 let runtime_dir = OsString::from("/run/user/1000");
2950
2951 let (path, source) = connection_file_path_with_source(Some(runtime_dir));
2952
2953 assert_eq!(
2954 path,
2955 PathBuf::from("/run/user/1000").join(CONNECTION_FILE_NAME)
2956 );
2957 assert_eq!(source, ConnectionFileSource::XdgRuntimeDir);
2958 }
2959
2960 #[test]
2961 fn connection_file_path_falls_back_to_temp_dir_with_user_token_when_xdg_unset() {
2962 let _env_lock = ENV_LOCK.lock().unwrap();
2963 let _xdg = EnvGuard::unset("XDG_RUNTIME_DIR");
2964
2965 assert_eq!(
2966 connection_file_path(),
2967 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
2968 );
2969 }
2970
2971 #[test]
2972 fn connection_file_path_source_is_temp_dir_when_xdg_unset() {
2973 let (path, source) = connection_file_path_with_source(None);
2974
2975 assert_eq!(
2976 path,
2977 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
2978 );
2979 assert_eq!(source, ConnectionFileSource::TempDirFallback);
2980 }
2981
2982 #[test]
2987 fn user_connection_token_is_stable_under_concurrent_callers() {
2988 let expected = user_connection_token();
2989 let workers: Vec<_> = (0..32)
2990 .map(|_| {
2991 std::thread::spawn(|| (0..40).map(|_| user_connection_token()).collect::<Vec<_>>())
2992 })
2993 .collect();
2994 for worker in workers {
2995 for token in worker.join().expect("probe thread") {
2996 assert_eq!(token, expected, "token diverged under concurrent probes");
2997 }
2998 }
2999 }
3000
3001 #[test]
3002 fn connection_file_path_source_is_temp_dir_when_xdg_empty() {
3003 let (path, source) = connection_file_path_with_source(Some(OsString::new()));
3004
3005 assert_eq!(
3006 path,
3007 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
3008 );
3009 assert_eq!(source, ConnectionFileSource::TempDirFallback);
3010 }
3011
3012 #[test]
3016 fn daemon_binary_config_journals_and_captures_into_the_run_dir() {
3017 let _env_lock = ENV_LOCK.lock().unwrap();
3018 let root = unique_temp_dir("daemon-binary-config");
3019 let data_home = root.join("data");
3020 let _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
3021 let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
3022 let _port = EnvGuard::unset(SUBC_PORT_ENV);
3023
3024 let config = BootstrapConfig::from_env_for_daemon_binary().unwrap();
3025
3026 let run_dir = data_home.join("cortexkit").join("run");
3027 assert_eq!(
3028 config.terminal_journal_path,
3029 Some(run_dir.join("terminals.jsonl"))
3030 );
3031 assert_eq!(config.capture_logs_dir, Some(run_dir.join("logs")));
3032 assert_eq!(
3033 BootstrapConfig::new(root.join("connection.json"), 0).terminal_journal_path,
3034 None,
3035 "an in-process config must not journal anywhere unless asked to"
3036 );
3037 }
3038
3039 #[test]
3040 fn daemon_binary_config_refuses_a_relative_data_home() {
3041 let _env_lock = ENV_LOCK.lock().unwrap();
3042 let root = unique_temp_dir("daemon-binary-relative-data");
3043 let _data = EnvGuard::set_str("XDG_DATA_HOME", "relative-data-home");
3044 let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
3045 let _port = EnvGuard::unset(SUBC_PORT_ENV);
3046
3047 let error = BootstrapConfig::from_env_for_daemon_binary()
3048 .expect_err("a relative data home must refuse the daemon binary's config");
3049 assert!(
3050 matches!(error, BootstrapError::RunDir(_)),
3051 "expected a run-directory refusal, got {error}"
3052 );
3053 assert!(error.to_string().contains("XDG_DATA_HOME"), "{error}");
3054 }
3055
3056 #[test]
3057 fn privileged_operator_prompt_is_loaded_by_both_bootstrap_config_paths() {
3058 let _env_lock = ENV_LOCK.lock().unwrap();
3059 let _port = EnvGuard::unset(SUBC_PORT_ENV);
3060 let (_dir, conn_path) = temp_connection_file_path("privileged-operator-prompt");
3061 let config_path = conn_path.with_file_name("subc.jsonc");
3062 for (doc, expected) in [
3063 (None, daemon_config::PrivilegedOperatorPrompt::Log),
3064 (
3065 Some(r#"{"version":1}"#),
3066 daemon_config::PrivilegedOperatorPrompt::Log,
3067 ),
3068 (
3069 Some(r#"{"version":1,"privileged_operator_prompt":"log"}"#),
3070 daemon_config::PrivilegedOperatorPrompt::Log,
3071 ),
3072 (
3073 Some(r#"{"version":1,"privileged_operator_prompt":"enforce"}"#),
3074 daemon_config::PrivilegedOperatorPrompt::Enforce,
3075 ),
3076 ] {
3077 if let Some(doc) = doc {
3078 fs::write(&config_path, doc).unwrap();
3079 }
3080 assert_eq!(
3081 BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3082 .unwrap()
3083 .privileged_operator_prompt,
3084 expected
3085 );
3086 assert_eq!(
3087 BootstrapConfig::new(&conn_path, 0)
3088 .with_daemon_config_path(&config_path)
3089 .unwrap()
3090 .privileged_operator_prompt,
3091 expected
3092 );
3093 }
3094 }
3095
3096 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3097 async fn privileged_operator_prompt_is_snapshotted_by_running_daemon() {
3098 let dir = unique_temp_dir("privileged-operator-prompt-bootstrap");
3099 let connection_path = dir.join("connection.json");
3100 let config_path = dir.join("subc.jsonc");
3101 fs::write(
3102 &config_path,
3103 r#"{"version":1,"privileged_operator_prompt":"enforce"}"#,
3104 )
3105 .unwrap();
3106 let config = config_with_a_short_socket(BootstrapConfig::new(&connection_path, 0))
3107 .with_daemon_config_path(&config_path)
3108 .unwrap();
3109 let connection_path = config.connection_file_path.clone();
3110 let daemon = AbortOnDrop::new(tokio::spawn(run_with_config(config)));
3111 tokio::time::timeout(Duration::from_secs(5), async {
3112 while !connection_path.exists() {
3113 assert!(
3114 !daemon.handle.is_finished(),
3115 "daemon exited before publishing"
3116 );
3117 tokio::task::yield_now().await;
3118 }
3119 })
3120 .await
3121 .unwrap();
3122 let info = connection_file::read(&connection_path).unwrap();
3123 let mut client = connect_from_info(&info).await.unwrap();
3124 authenticate_client(&mut client, &info, Duration::from_secs(5))
3125 .await
3126 .unwrap();
3127 for (correlation, mode, expected) in [
3128 (1, "enforce", Vec::new()),
3129 (2, "log", vec!["privileged_operator_prompt"]),
3130 (3, "log", vec!["privileged_operator_prompt"]),
3131 ] {
3132 fs::write(
3133 &config_path,
3134 serde_json::json!({"version":1,"privileged_operator_prompt":mode}).to_string(),
3135 )
3136 .unwrap();
3137 let frame = crate::Frame::build(
3138 subc_protocol::FrameType::Request,
3139 subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
3140 0,
3141 0,
3142 correlation,
3143 serde_json::to_vec(&subc_control::ClientControlRequest::SupervisorRescan {
3144 preview: true,
3145 })
3146 .unwrap(),
3147 )
3148 .unwrap();
3149 crate::write_frame(&mut client, &frame).await.unwrap();
3150 let reply =
3151 tokio::time::timeout(Duration::from_secs(5), crate::read_frame(&mut client))
3152 .await
3153 .unwrap()
3154 .unwrap()
3155 .unwrap();
3156 assert_eq!(reply.header.ty, subc_protocol::FrameType::Response);
3157 assert_eq!(reply.header.corr, correlation);
3158 let subc_control::ClientControlResponse::SupervisorRescan { result } =
3159 serde_json::from_slice(&reply.body).unwrap()
3160 else {
3161 panic!("expected a rescan response");
3162 };
3163 assert_eq!(result.restart_required, expected);
3164 }
3165 }
3166
3167 #[test]
3168 fn configured_port_uses_default_config_and_env_override() {
3169 let _env_lock = ENV_LOCK.lock().unwrap();
3170 let (_dir, conn_path) = temp_connection_file_path("daemon-config-port");
3171 let config_path = conn_path.with_file_name("subc.jsonc");
3172
3173 let _port = EnvGuard::unset(SUBC_PORT_ENV);
3174 assert_eq!(
3175 BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3176 .unwrap()
3177 .port,
3178 DEFAULT_SUBC_PORT
3179 );
3180
3181 fs::write(&config_path, r#"{ "version": 1, "port": 8123 }"#).unwrap();
3182 assert_eq!(
3183 BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3184 .unwrap()
3185 .port,
3186 8123
3187 );
3188
3189 let _port = EnvGuard::set_str(SUBC_PORT_ENV, "9012");
3190 assert_eq!(
3191 BootstrapConfig::from_env_with_daemon_config_path(&config_path)
3192 .unwrap()
3193 .port,
3194 9012
3195 );
3196 }
3197
3198 #[tokio::test]
3199 async fn singleton_does_not_accept_a_peer_that_answers_once_then_exits() {
3200 let (_dir, path) = temp_connection_file_path("departing-peer");
3201 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
3202 let info = make_connection_info(listener.local_addr().unwrap().port());
3203 write_connection_file(&path, &info, None).unwrap();
3204 let peer = tokio::spawn(async move {
3205 let (mut stream, _) = listener.accept().await.unwrap();
3206 subc_transport::authenticate_server(
3207 &mut stream,
3208 &info.key,
3209 &info.daemon_id,
3210 &info.daemon_ver,
3211 PROBE_AUTH_DEADLINE,
3212 )
3213 .await
3214 .unwrap();
3215 });
3216 let outcome = ensure_singleton(&path, 0).await.unwrap();
3217 peer.await.unwrap();
3218 assert!(
3219 matches!(outcome, Outcome::Bound(_)),
3220 "a departing peer is not AlreadyRunning"
3221 );
3222 }
3223
3224 #[tokio::test]
3225 async fn second_singleton_probe_against_served_tcp_daemon_reports_already_running() {
3226 let (_dir, path) = temp_connection_file_path("already-running");
3227
3228 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3229 let server = start_server(bound);
3230
3231 let second = ensure_singleton(&path, 0).await.unwrap();
3232 assert!(matches!(second, Outcome::AlreadyRunning));
3233
3234 server.abort();
3235 let _ = server.await;
3236 }
3237
3238 #[tokio::test]
3239 async fn daemon_connection_file_publishes_protocol_wire_version() {
3240 let (_dir, path) = temp_connection_file_path("wire-version");
3241 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3242 assert_eq!(bound.connection_info.wire_version, Some(PROTOCOL_VERSION));
3243 assert_eq!(
3244 connection_file::read(&path).unwrap().wire_version,
3245 Some(PROTOCOL_VERSION)
3246 );
3247
3248 drop(bound.listeners);
3249 }
3250
3251 #[tokio::test]
3252 async fn stale_unbound_connection_file_is_reclaimed() {
3253 let (_dir, path) = temp_connection_file_path("stale-reclaim");
3254 let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
3255 let stale_port = stale.local_addr().unwrap().port();
3256 drop(stale);
3257 let stale_info = make_connection_info(stale_port);
3258 write_atomic(&path, &stale_info).unwrap();
3259
3260 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3261 assert_ne!(bound.connection_info.key, stale_info.key);
3262 drop(bound.listeners);
3263 }
3264
3265 #[cfg(unix)]
3266 #[tokio::test]
3267 async fn ensure_singleton_reclaims_insecure_connection_file() {
3268 let (_dir, path) = temp_connection_file_path("insecure-reclaim");
3269 let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
3270 let stale_port = stale.local_addr().unwrap().port();
3271 drop(stale);
3272 let stale_info = make_connection_info(stale_port);
3273 write_atomic(&path, &stale_info).unwrap();
3274 fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
3275
3276 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3277 assert_ne!(bound.connection_info.key, stale_info.key);
3278 assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
3279 assert_owner_only_connection_file(&path);
3280
3281 drop(bound.listeners);
3282 }
3283
3284 #[tokio::test]
3285 async fn ensure_singleton_reclaims_non_loopback_connection_file() {
3286 let (_dir, path) = temp_connection_file_path("non-loopback-reclaim");
3287 let mut stale_info = make_connection_info(8757);
3288 stale_info.endpoints = vec![Endpoint {
3289 host: "192.0.2.10".to_owned(),
3290 port: 8757,
3291 }];
3292 write_atomic(&path, &stale_info).unwrap();
3293
3294 let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0));
3295 let bound = expect_bound(ensure_singleton_with_config(config).await.unwrap());
3296 assert_ne!(bound.connection_info.key, stale_info.key);
3297 assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
3298 assert!(bound
3299 .connection_info
3300 .endpoints
3301 .iter()
3302 .all(|endpoint| endpoint.host.parse::<IpAddr>().unwrap().is_loopback()));
3303 assert_owner_only_connection_file(&path);
3304
3305 drop(bound.listeners);
3306 }
3307
3308 #[tokio::test]
3309 async fn ensure_singleton_reclaims_invalid_connection_file_shapes() {
3310 let mut unsupported_schema = make_connection_info(8757);
3311 unsupported_schema.schema = SCHEMA_VERSION + 1;
3312
3313 let mut empty_endpoints = make_connection_info(8757);
3314 empty_endpoints.endpoints.clear();
3315
3316 let mut short_key = make_connection_info(8757);
3317 short_key.key = vec![0x5A; MIN_KEY_LEN - 1];
3318
3319 let cases = vec![
3320 (
3321 "unsupported-schema",
3322 serde_json::to_vec(&unsupported_schema).unwrap(),
3323 Some(unsupported_schema),
3324 ),
3325 (
3326 "empty-endpoints",
3327 serde_json::to_vec(&empty_endpoints).unwrap(),
3328 Some(empty_endpoints),
3329 ),
3330 (
3331 "short-key",
3332 serde_json::to_vec(&short_key).unwrap(),
3333 Some(short_key),
3334 ),
3335 ("invalid-json", b"{not valid connection json".to_vec(), None),
3336 ];
3337
3338 for (label, contents, old_info) in cases {
3339 let (_dir, path) = temp_connection_file_path(label);
3340 write_raw_owner_only_connection_file(&path, &contents);
3341
3342 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3343 if let Some(old_info) = old_info {
3344 assert_ne!(bound.connection_info.key, old_info.key, "{label}");
3345 assert_ne!(
3346 bound.connection_info.daemon_id, old_info.daemon_id,
3347 "{label}"
3348 );
3349 }
3350 assert!(bound.connection_info.key.len() >= MIN_KEY_LEN, "{label}");
3351 assert_ne!(bound.connection_info.daemon_id, [0u8; 16], "{label}");
3352 assert_owner_only_connection_file(&path);
3353
3354 drop(bound.listeners);
3355 }
3356 }
3357
3358 #[tokio::test]
3359 async fn foreign_reused_port_connection_file_is_reclaimed_after_auth_probe_fails() {
3360 let (_dir, path) = temp_connection_file_path("foreign-reclaim");
3361 let foreign = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
3362 let foreign_port = foreign.local_addr().unwrap().port();
3363 write_atomic(&path, &make_connection_info(foreign_port)).unwrap();
3364 let foreign_task = tokio::spawn(async move {
3365 if let Ok((mut stream, _)) = foreign.accept().await {
3366 let mut buf = [0u8; 64];
3367 let _ = stream.read(&mut buf).await;
3368 }
3369 });
3370
3371 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3372 assert!(bound
3373 .connection_info
3374 .endpoints
3375 .iter()
3376 .all(|endpoint| endpoint.port != foreign_port));
3377
3378 drop(bound.listeners);
3379 let _ = foreign_task.await;
3380 }
3381
3382 #[tokio::test]
3383 async fn stale_start_lock_file_is_reclaimable() {
3384 let (_dir, path) = temp_connection_file_path("start-lock-stale-file");
3385 let lock_path = start_lock_path(&path);
3386 drop(open_owner_only_lock(&lock_path).unwrap());
3387 assert!(lock_path.is_file());
3388
3389 let lock = StartLock::acquire(&path).await.unwrap();
3390 assert!(lock_path.is_file());
3391
3392 drop(lock);
3393 assert!(lock_path.is_file());
3394 }
3395
3396 #[tokio::test]
3397 async fn held_start_lock_blocks_second_acquire_until_release() {
3398 let (_dir, path) = temp_connection_file_path("start-lock-held");
3399 let lock_path = start_lock_path(&path);
3400 let first = StartLock::acquire(&path).await.unwrap();
3401
3402 let err = match StartLock::acquire(&path).await {
3403 Ok(_) => panic!("second acquire while held must stay busy"),
3404 Err(err) => err,
3405 };
3406 assert!(matches!(
3407 err,
3408 BootstrapError::StartLockBusy {
3409 ref path,
3410 attempts: START_LOCK_RETRIES,
3411 } if path == &lock_path
3412 ));
3413
3414 drop(first);
3415
3416 let second = StartLock::acquire(&path)
3417 .await
3418 .expect("released advisory lock should be reclaimable");
3419 drop(second);
3420 }
3421
3422 #[tokio::test]
3423 async fn bind_conflict_on_fixed_port_fails_loud_without_reselecting() {
3424 let (_dir, path) = temp_connection_file_path("bind-conflict");
3425 let occupied = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
3426 let occupied_port = occupied.local_addr().unwrap().port();
3427
3428 let err = ensure_singleton(&path, occupied_port).await.unwrap_err();
3429 assert!(matches!(
3430 err,
3431 BootstrapError::Bind { ref source, .. } if source.kind() == io::ErrorKind::AddrInUse
3432 ));
3433 assert!(err.to_string().contains("set the port in config"));
3434
3435 drop(occupied);
3436 }
3437
3438 #[tokio::test]
3439 async fn ephemeral_ipv6_collision_still_serves_ipv4() {
3440 let (listeners, endpoints) = bind_loopback_with(0, |port| async move {
3441 let occupied = TcpListener::bind((Ipv6Addr::LOCALHOST, port)).await?;
3442 let result = TcpListener::bind((Ipv6Addr::LOCALHOST, port)).await;
3443 drop(occupied);
3444 result
3445 })
3446 .await
3447 .expect("an incidental IPv6 collision must not prevent an ephemeral daemon from starting");
3448 assert_eq!(endpoints.len(), 1);
3449 assert_eq!(endpoints[0].host, "127.0.0.1");
3450 TcpStream::connect((Ipv4Addr::LOCALHOST, endpoints[0].port))
3451 .await
3452 .unwrap();
3453 drop(listeners);
3454 }
3455
3456 #[tokio::test]
3457 async fn unpublished_boot_holds_singleton_lock_until_publication() {
3458 let dir = ScratchDir::new("ul");
3459 let path = dir.join("c");
3460 let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0));
3461 let bound = expect_bound(ensure_singleton_inner(config, false).await.unwrap());
3462 assert!(!path.exists());
3463 let contender = open_owner_only_lock(&start_lock_path(&path)).unwrap();
3464 assert!(
3465 matches!(FileExt::try_lock(&contender), Err(TryLockError::WouldBlock)),
3466 "an unpublished boot must keep its singleton claim"
3467 );
3468 drop(bound);
3469 FileExt::try_lock(&contender).unwrap();
3470 }
3471
3472 #[tokio::test]
3473 async fn start_lock_drop_releases_claim_with_a_shared_file_description() {
3474 let dir = ScratchDir::new("sl");
3475 let path = dir.join("c");
3476 let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0));
3477 let bound = expect_bound(ensure_singleton_inner(config, false).await.unwrap());
3478 let inherited = bound
3481 .publication_lock
3482 .as_ref()
3483 .unwrap()
3484 ._file
3485 .try_clone()
3486 .unwrap();
3487 let contender = open_owner_only_lock(&start_lock_path(&path)).unwrap();
3488 assert!(matches!(
3489 FileExt::try_lock(&contender),
3490 Err(TryLockError::WouldBlock)
3491 ));
3492 drop(bound);
3493 FileExt::try_lock(&contender).expect("dropping bootstrap releases even an inherited lock");
3494 drop(inherited);
3495 }
3496
3497 #[tokio::test]
3498 async fn readiness_probe_requires_an_authenticating_server() {
3499 let dir = ScratchDir::new("unserved-readiness");
3500 let bound = expect_bound(
3501 ensure_singleton_inner(BootstrapConfig::new(dir.join("connection.json"), 0), false)
3502 .await
3503 .unwrap(),
3504 );
3505 assert!(matches!(
3506 verify_serving(&bound.connection_info).await,
3507 Err(BootstrapError::StartupNotServing)
3508 ));
3509 }
3510
3511 #[cfg(unix)]
3512 #[tokio::test]
3513 async fn orphan_sweep_finishes_before_connection_file_publication() {
3514 use crate::live_children::{ExecutableIdentity, LiveChild};
3515 let dir = ScratchDir::new("pas");
3516 let path = dir.join("c");
3520 let record = dir.join("live-children.json");
3521 let ready = dir.join("ready");
3522 let mut child = std::process::Command::new("/bin/sh")
3523 .args([
3524 "-c",
3525 "trap '' TERM; : > \"$0\"; read -r _",
3526 ready.to_str().unwrap(),
3527 ])
3528 .stdin(std::process::Stdio::piped())
3529 .env("XDG_DATA_HOME", dir.path())
3530 .env("XDG_RUNTIME_DIR", dir.path())
3531 .env("XDG_CONFIG_HOME", dir.path())
3532 .spawn()
3533 .unwrap();
3534 timeout(Duration::from_secs(5), async {
3535 while !ready.exists() {
3536 sleep(Duration::from_millis(5)).await;
3537 }
3538 })
3539 .await
3540 .unwrap();
3541 let observed = subc_os::Process::open(child.id())
3542 .unwrap()
3543 .unwrap()
3544 .observe()
3545 .unwrap();
3546 crate::live_children::write_record(
3547 &record,
3548 &[LiveChild {
3549 container: None,
3550 module_id: "old-sleep".into(),
3551 pid: child.id(),
3552 protocol: subc_control::ModuleProtocol::None,
3553 start_time: Some(observed.start_time),
3554 executable: observed.executable.map(ExecutableIdentity::from),
3555 cgroup_name: None,
3556 }],
3557 )
3558 .unwrap();
3559 let config = config_with_a_short_socket(BootstrapConfig::new(&path, 0))
3560 .with_live_children_record(&record);
3561 let daemon = tokio::spawn(run_with_config(config));
3562 timeout(Duration::from_secs(5), async {
3563 while !path.exists() {
3564 sleep(Duration::from_millis(5)).await;
3565 }
3566 })
3567 .await
3568 .unwrap();
3569 assert!(path.exists());
3570 let ended = child.try_wait().unwrap().is_some();
3571 if !ended {
3572 child.kill().unwrap();
3573 }
3574 child.wait().unwrap();
3575 if ended {
3576 assert!(matches!(probe_existing(&path).await.unwrap(), Probe::Live));
3577 }
3578 daemon.abort();
3579 let _ = daemon.await;
3580 assert!(
3581 ended,
3582 "the published daemon must not still owe its orphan sweep"
3583 );
3584 }
3585
3586 #[tokio::test(flavor = "current_thread")]
3593 async fn connection_file_publication_leaves_the_async_runtime_free() {
3594 use std::sync::atomic::{AtomicBool, Ordering};
3595
3596 let (_dir, path) = temp_connection_file_path("publish-off-runtime");
3597 let write_started = Arc::new(AtomicBool::new(false));
3598 let (progress_tx, progress_rx) = std::sync::mpsc::channel::<()>();
3599 let (verdict_tx, verdict_rx) = std::sync::mpsc::channel::<bool>();
3600 let hook_started = Arc::clone(&write_started);
3601 connection_file_write_hook::install(&path, move || {
3602 hook_started.store(true, Ordering::SeqCst);
3603 let progressed = progress_rx.recv_timeout(Duration::from_secs(5)).is_ok();
3604 let _ = verdict_tx.send(progressed);
3605 });
3606 let ticker = tokio::spawn(async move {
3609 loop {
3610 if write_started.load(Ordering::SeqCst) {
3611 let _ = progress_tx.send(());
3612 return;
3613 }
3614 sleep(Duration::from_millis(5)).await;
3615 }
3616 });
3617
3618 let daemon = tokio::spawn(run_with_config(BootstrapConfig::new(&path, 0)));
3619 let published = timeout(Duration::from_secs(15), async {
3620 while !path.exists() && !daemon.is_finished() {
3621 sleep(Duration::from_millis(5)).await;
3622 }
3623 })
3624 .await;
3625 let daemon_exited = daemon.is_finished();
3626 daemon.abort();
3627 let daemon_result = daemon.await;
3628 ticker.abort();
3629
3630 assert!(
3631 published.is_ok() && !daemon_exited,
3632 "the daemon must start and publish its connection file: {daemon_result:?}"
3633 );
3634 match verdict_rx.try_recv() {
3635 Ok(true) => {}
3636 Ok(false) => panic!(
3637 "no other task on the runtime ran while the connection file was being written: the write is blocking the async worker thread"
3638 ),
3639 Err(_) => panic!("startup published the connection file without the hooked write"),
3640 }
3641 }
3642
3643 #[tokio::test]
3646 async fn a_panicking_connection_file_write_fails_startup() {
3647 let (_dir, path) = temp_connection_file_path("publish-panics");
3648 connection_file_write_hook::install(&path, || {
3649 panic!("deliberate panic inside the connection-file write")
3650 });
3651
3652 let error = timeout(
3653 Duration::from_secs(15),
3654 run_with_config(BootstrapConfig::new(&path, 0)),
3655 )
3656 .await
3657 .expect("startup must end once the write task fails")
3658 .expect_err("startup must fail when the connection-file write panics");
3659
3660 assert!(
3661 matches!(&error, BootstrapError::ConnectionFileWrite { path: failed, .. } if failed == &path),
3662 "expected a connection-file write error, got {error:?}"
3663 );
3664 let message = error.to_string();
3665 assert!(message.contains(&path.display().to_string()), "{message}");
3666 assert!(message.contains("panicked"), "{message}");
3667 assert!(!path.exists(), "no connection file may be published");
3668 }
3669
3670 #[cfg(target_os = "macos")]
3671 #[test]
3672 fn nofile_raise_worker() {
3673 let Some(path) = std::env::var_os("SUBC_NOFILE_TEST_FILE") else {
3674 return;
3675 };
3676 let (_, hard) = rlimit::Resource::NOFILE.get().unwrap();
3677 rlimit::Resource::NOFILE.set(256, hard).unwrap();
3678 raise_nofile_limit_with_ceiling(Some(10240));
3679 std::fs::write(path, rlimit::Resource::NOFILE.get().unwrap().0.to_string()).unwrap();
3680 }
3681
3682 #[cfg(target_os = "macos")]
3683 #[test]
3684 fn macos_nofile_raise_clamps_to_kernel_ceiling() {
3685 let dir = ScratchDir::new("nofile-ceiling");
3686 let result = dir.join("soft");
3687 let status = std::process::Command::new(std::env::current_exe().unwrap())
3688 .args(["--exact", "bootstrap::tests::nofile_raise_worker"])
3689 .env("SUBC_NOFILE_TEST_FILE", &result)
3690 .env("XDG_DATA_HOME", dir.path())
3691 .env("XDG_RUNTIME_DIR", dir.path())
3692 .env("XDG_CONFIG_HOME", dir.path())
3693 .status()
3694 .unwrap();
3695 assert!(status.success());
3696 let soft: u64 = std::fs::read_to_string(result).unwrap().parse().unwrap();
3697 assert!(
3698 soft > 256 && soft <= 10240,
3699 "the inherited limit must be raised within the kernel ceiling; got {soft}"
3700 );
3701 }
3702
3703 #[tokio::test]
3704 async fn key_rotation_republishes_new_material_and_old_file_fails_auth() {
3705 let (_dir, path) = temp_connection_file_path("key-rotation");
3706 let first = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3707 let old_info = first.connection_info.clone();
3708 let fixed_port = old_info.endpoints[0].port;
3709 drop(first.listeners);
3710
3711 let second = expect_bound(ensure_singleton(&path, fixed_port).await.unwrap());
3712 let new_info = second.connection_info.clone();
3713 assert_ne!(old_info.key, new_info.key);
3714 assert_ne!(old_info.daemon_id, new_info.daemon_id);
3715 let server = start_server(second);
3716
3717 let mut old_stream = connect_from_info(&old_info).await.unwrap();
3718 let old_auth = authenticate_client(&mut old_stream, &old_info, PROBE_AUTH_DEADLINE).await;
3719 assert!(
3720 old_auth.is_err(),
3721 "old key must not authenticate after restart"
3722 );
3723
3724 let reread = connection_file::read(&path).unwrap();
3725 let mut new_stream = connect_from_info(&reread).await.unwrap();
3726 authenticate_client(&mut new_stream, &reread, PROBE_AUTH_DEADLINE)
3727 .await
3728 .unwrap();
3729
3730 server.abort();
3731 let _ = server.await;
3732 }
3733
3734 #[cfg(unix)]
3735 #[tokio::test]
3736 async fn published_connection_file_permissions_are_owner_only() {
3737 let (_dir, path) = temp_connection_file_path("permissions");
3738 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
3739
3740 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
3741 assert_eq!(mode, 0o600);
3742
3743 drop(bound.listeners);
3744 }
3745
3746 fn config_with_a_short_socket(config: BootstrapConfig) -> BootstrapConfig {
3754 let dir = config
3755 .connection_file_path
3756 .parent()
3757 .map(Path::to_path_buf)
3758 .unwrap_or_else(|| PathBuf::from("."));
3759 #[cfg(unix)]
3760 let config = BootstrapConfig {
3761 connection_file_path: dir.join("c"),
3762 local_listener: LocalListenerConfig::in_socket_dir(dir.join("s")),
3763 ..config
3764 };
3765 #[cfg(not(unix))]
3766 let _ = dir;
3767 config
3768 }
3769
3770 #[cfg(unix)]
3773 #[test]
3774 fn the_daemon_binary_puts_its_socket_in_the_run_directory() {
3775 let _env_lock = ENV_LOCK.lock().unwrap();
3776 let root = ScratchDir::new("binary-local-socket");
3777 let data_home = root.join("data");
3778 let _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
3779 let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
3780 let _port = EnvGuard::unset(SUBC_PORT_ENV);
3781
3782 let config = BootstrapConfig::from_env_for_daemon_binary().unwrap();
3783
3784 let run_dir = data_home.join("cortexkit").join("run");
3785 assert_eq!(
3786 config.local_listener.configured_dir(),
3787 Some(run_dir.as_path()),
3788 "the binary serves from its run directory"
3789 );
3790 let socket = local_listener::socket_path_for(Some(&run_dir), &config.connection_file_path)
3791 .expect("the binary config names a directory");
3792 assert_eq!(socket.parent().unwrap(), run_dir);
3793 assert_eq!(
3794 socket.file_name().unwrap().to_string_lossy(),
3795 "subc.sock",
3796 "a fixed name: the run directory belongs to one data home"
3797 );
3798 }
3799
3800 #[cfg(unix)]
3807 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3808 async fn an_in_process_daemon_without_a_configured_directory_serves_no_local_endpoint() {
3809 let root = ScratchDir::new("in-process-no-local-socket");
3810 let data_home = root.join("data");
3811 fs::create_dir_all(&data_home).unwrap();
3812 let connection_path = root.join("c");
3813 let _data;
3814 let _config;
3815 let _port;
3816 {
3817 let _env_lock = ENV_LOCK.lock().unwrap();
3818 _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
3819 _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
3820 _port = EnvGuard::unset(SUBC_PORT_ENV);
3821 }
3822
3823 let bound = expect_bound(ensure_singleton(&connection_path, 0).await.unwrap());
3824
3825 assert!(bound.local_endpoint.is_none());
3826 assert!(bound.local_endpoint_unavailable.is_none());
3827 let published = connection_file::read_with_local_endpoint(&connection_path).unwrap();
3828 assert!(published.local_endpoint.is_none());
3829 assert!(
3830 local_listener::socket_path_for(None, &connection_path).is_none(),
3831 "no configured directory, no socket"
3832 );
3833 let mut leftovers = Vec::new();
3834 let mut pending = vec![data_home.clone()];
3835 while let Some(dir) = pending.pop() {
3836 for entry in fs::read_dir(&dir).unwrap() {
3837 let entry = entry.unwrap();
3838 let path = entry.path();
3839 if entry.file_type().unwrap().is_dir() {
3840 pending.push(path.clone());
3841 }
3842 if entry.file_name().to_string_lossy().ends_with(".sock") {
3843 leftovers.push(path);
3844 }
3845 }
3846 }
3847 assert!(
3848 leftovers.is_empty(),
3849 "an in-process daemon must not create a socket in the data home: {leftovers:?}"
3850 );
3851 }
3852
3853 #[cfg(unix)]
3858 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3859 async fn a_daemon_whose_socket_path_is_too_long_still_serves_tcp() {
3860 let dir = ScratchDir::new("tcp-only");
3861 let canonical = std::fs::canonicalize(&dir).unwrap();
3862 let connection_path = canonical.join("c");
3863 let deep = canonical.join("x".repeat(80));
3866 fs::create_dir(&deep).unwrap();
3867 fs::set_permissions(&deep, fs::Permissions::from_mode(0o700)).unwrap();
3868 let config =
3869 BootstrapConfig::new(&connection_path, 0).with_local_listener_socket_dir(&deep);
3870 let bound = expect_bound(ensure_singleton_with_config(config).await.unwrap());
3871 assert!(
3872 bound.local_endpoint.is_none(),
3873 "a socket that cannot be bound is not published"
3874 );
3875 assert!(
3876 bound
3877 .local_endpoint_unavailable
3878 .as_deref()
3879 .is_some_and(|reason| reason.contains("too long")),
3880 "{:?}",
3881 bound.local_endpoint_unavailable
3882 );
3883 let published = connection_file::read_with_local_endpoint(&connection_path).unwrap();
3884 assert!(published.local_endpoint.is_none());
3885 assert!(
3886 !published.info.endpoints.is_empty(),
3887 "TCP is still published"
3888 );
3889
3890 let server = start_server(bound);
3892 let info = connection_file::read(&connection_path).unwrap();
3893 let mut client = connect_from_info(&info).await.unwrap();
3894 authenticate_client(&mut client, &info, PROBE_AUTH_DEADLINE)
3895 .await
3896 .expect("a TCP client still completes the handshake");
3897 server.abort();
3898 let _ = server.await;
3899 }
3900
3901 #[cfg(unix)]
3904 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3905 async fn published_connection_file_names_the_served_local_endpoint() {
3906 let (_dir, path) = temp_connection_file_path("local-endpoint");
3907 let short_socket_dir = std::env::temp_dir().join(format!("subc-bt-{}", std::process::id()));
3911 let config =
3912 BootstrapConfig::new(&path, 0).with_local_listener_socket_dir(&short_socket_dir);
3913 let bound = expect_bound(ensure_singleton_with_config(config).await.unwrap());
3914 let endpoint = connection_file::read_with_local_endpoint(&path)
3915 .unwrap()
3916 .local_endpoint
3917 .expect("the daemon serves a local endpoint, so the file names it");
3918 assert_eq!(Some(&endpoint), bound.local_endpoint.as_ref());
3919 let LocalEndpoint::Unix { path: socket_path } = &endpoint else {
3920 panic!("a Unix daemon publishes a socket path");
3921 };
3922 assert_eq!(socket_path.parent().unwrap(), short_socket_dir);
3923 assert_eq!(
3924 fs::metadata(socket_path).unwrap().permissions().mode() & 0o777,
3925 0o600
3926 );
3927
3928 let router = Arc::new(Router::with_default_self_handler());
3929 let auth = auth_for(&bound.connection_info);
3930 let server = tokio::spawn(serve_local_listener(
3931 bound.local_listener.expect("the local listener is bound"),
3932 router,
3933 auth,
3934 ));
3935 let mut client = tokio::net::UnixStream::connect(socket_path).await.unwrap();
3936 authenticate_client(&mut client, &bound.connection_info, Duration::from_secs(5))
3937 .await
3938 .expect("a socket client completes the same handshake as a TCP client");
3939
3940 server.abort();
3941 drop(bound.listeners);
3942 }
3943
3944 #[cfg(unix)]
3947 #[test]
3948 fn a_socket_directory_that_is_a_file_refuses() {
3949 let dir = ScratchDir::new("local-listener-file-as-dir");
3950 let file = dir.join("not-a-directory");
3951 fs::write(&file, b"x").unwrap();
3952 let error = local_listener::bind(
3953 &LocalListenerConfig::in_socket_dir(file),
3954 &dir.join("connection.json"),
3955 )
3956 .expect_err("a path that is not a directory cannot hold the socket");
3957 assert!(matches!(error, ServerError::LocalAccept { .. }), "{error}");
3958 }
3959
3960 #[cfg(unix)]
3964 #[test]
3965 fn the_socket_path_stays_within_the_unix_limit() {
3966 let run_dir = PathBuf::from("/tmp/short-run");
3967 assert!(
3968 local_listener::socket_path_for(None, &run_dir.join("one.json")).is_none(),
3969 "no configured directory means no socket"
3970 );
3971 let socket = local_listener::socket_path_for(Some(&run_dir), &run_dir.join("one.json"))
3972 .expect("a configured directory gets a socket");
3973 assert_eq!(socket, run_dir.join("subc.sock"));
3974 assert_eq!(
3975 socket,
3976 local_listener::socket_path_for(Some(&run_dir), &run_dir.join("two.json")).unwrap(),
3977 "the name does not come from the connection file"
3978 );
3979
3980 let deep = PathBuf::from(format!("/tmp/{}", "x".repeat(60)));
3981 let long = local_listener::socket_path_for(Some(&deep), &deep.join("conn.json"))
3982 .expect("a configured directory gets a socket");
3983 assert!(
3984 long.as_os_str().len() < 104,
3985 "{} is {} bytes",
3986 long.display(),
3987 long.as_os_str().len()
3988 );
3989 }
3990}