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, write_atomic,
18 AuthError, ConnectionFileError, ConnectionInfo, Endpoint, SCHEMA_VERSION,
19};
20use tokio::{
21 net::{TcpListener, TcpStream},
22 task::{JoinError, JoinHandle},
23 time::{sleep, timeout},
24};
25use tracing::{error, info, warn};
26
27use crate::{
28 daemon_config::{self, ConfiguredModule, DaemonConfigError},
29 server::{serve_listeners, ServerAuth, ServerError},
30 supervise::HealthConfig,
31 ConnectedClients, ControlHandler, DaemonSelfWatchdog, DaemonSelfWatchdogConfig,
32 ForwardingTable, Registry, RestartPolicy, Router, Supervisor, SupervisorHandle,
33 SupervisorProcessLiveness,
34};
35use std::sync::Arc;
36
37pub const DEFAULT_SUBC_PORT: u16 = 8757;
38pub const SUBC_PORT_ENV: &str = "SUBC_PORT";
39use subc_transport::CONNECTION_FILE_NAME;
40const DAEMON_VERSION: &str = env!("CARGO_PKG_VERSION");
41const CONNECT_TIMEOUT: Duration = Duration::from_secs(2);
42const PROBE_AUTH_DEADLINE: Duration = Duration::from_secs(2);
43const START_LOCK_RETRIES: usize = 40;
44const START_LOCK_RETRY_DELAY: Duration = Duration::from_millis(25);
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum ConnectionFileSource {
48 XdgRuntimeDir,
49 TempDirFallback,
50 Explicit,
51}
52
53impl ConnectionFileSource {
54 fn reason(self) -> &'static str {
55 match self {
56 Self::XdgRuntimeDir => "XDG_RUNTIME_DIR set and non-empty",
57 Self::TempDirFallback => "XDG_RUNTIME_DIR unset or empty",
58 Self::Explicit => "configured path",
59 }
60 }
61}
62
63impl fmt::Display for ConnectionFileSource {
64 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65 formatter.write_str(match self {
66 Self::XdgRuntimeDir => "xdg_runtime_dir",
67 Self::TempDirFallback => "temp_dir_fallback",
68 Self::Explicit => "explicit",
69 })
70 }
71}
72
73#[derive(Debug, Clone, Default)]
77struct AdmissionFactsConfig {
78 carrier_module_id: Option<String>,
79 targets: Option<Vec<String>>,
80}
81
82#[derive(Debug, Clone, Default, PartialEq, Eq)]
91pub enum CgroupPlacementConfig {
92 #[default]
93 Disabled,
94 Current,
95 Root(PathBuf),
96}
97
98#[derive(Debug, Clone)]
99pub struct BootstrapConfig {
100 pub operator_queue_wait: Duration,
101 pub operator_timeout: Duration,
102 pub operator_stuck_grace: Duration,
103 #[cfg(feature = "test-support")]
104 pub operator_script: Option<PathBuf>,
105 #[cfg(feature = "test-support")]
106 pub operator_events: Option<PathBuf>,
107 pub connection_file_path: PathBuf,
108 pub port: u16,
109 pub daemon_ver: String,
110 configured_modules: Vec<ConfiguredModule>,
111 storage_config: Option<daemon_config::StorageConfig>,
112 admission_facts: AdmissionFactsConfig,
113 scope_authority_owners: Vec<String>,
115 privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt,
116 activity_config: daemon_config::ActivityConfig,
117 daemon_config_path: Option<PathBuf>,
118 configured_port: Option<u16>,
119 route_bind_relay_default_ms: Option<u64>,
123 reserved_capabilities: BTreeMap<String, String>,
124 watchdog_config: DaemonSelfWatchdogConfig,
125 connection_file_source: ConnectionFileSource,
126 cgroup_placement: CgroupPlacementConfig,
129 capture_logs_dir: Option<PathBuf>,
133 terminal_journal_path: Option<PathBuf>,
141 machine_id_path: Option<PathBuf>,
147 live_children_path: Option<PathBuf>,
155 privacy_trampoline: Option<PathBuf>,
156}
157
158impl BootstrapConfig {
159 pub fn new(connection_file_path: impl Into<PathBuf>, port: u16) -> Self {
160 Self {
161 connection_file_path: connection_file_path.into(),
162 operator_queue_wait: Duration::from_secs(150),
163 operator_timeout: Duration::from_secs(120),
164 operator_stuck_grace: Duration::from_secs(10),
165 #[cfg(feature = "test-support")]
166 operator_script: None,
167 #[cfg(feature = "test-support")]
168 operator_events: None,
169 port,
170 daemon_ver: DAEMON_VERSION.to_owned(),
171 configured_modules: Vec::new(),
172 storage_config: None,
173 admission_facts: AdmissionFactsConfig::default(),
174 scope_authority_owners: daemon_config::default_scope_authority_owners(),
175 privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt::default(),
176 activity_config: daemon_config::ActivityConfig::default(),
177 daemon_config_path: None,
178 configured_port: None,
179 route_bind_relay_default_ms: None,
180 reserved_capabilities: BTreeMap::new(),
181 watchdog_config: DaemonSelfWatchdogConfig::default(),
182 connection_file_source: ConnectionFileSource::Explicit,
183 cgroup_placement: CgroupPlacementConfig::default(),
184 capture_logs_dir: None,
185 terminal_journal_path: None,
186 machine_id_path: None,
187 live_children_path: None,
188 privacy_trampoline: None,
189 }
190 }
191
192 pub fn with_live_children_record(mut self, path: impl Into<PathBuf>) -> Self {
196 self.live_children_path = Some(path.into());
197 self
198 }
199
200 pub fn with_privacy_trampoline(mut self, path: impl Into<PathBuf>) -> Self {
203 self.privacy_trampoline = Some(path.into());
204 self
205 }
206
207 pub fn with_machine_id_path(mut self, path: impl Into<PathBuf>) -> Self {
211 self.machine_id_path = Some(path.into());
212 self
213 }
214
215 pub fn with_cgroup_placement(mut self, placement: CgroupPlacementConfig) -> Self {
217 self.cgroup_placement = placement;
218 self
219 }
220
221 pub fn with_capture_logs_dir(mut self, dir: impl Into<PathBuf>) -> Self {
225 self.capture_logs_dir = Some(dir.into());
226 self
227 }
228
229 pub fn with_terminal_journal_path(mut self, path: impl Into<PathBuf>) -> Self {
232 self.terminal_journal_path = Some(path.into());
233 self
234 }
235
236 pub fn from_env() -> Result<Self, BootstrapError> {
237 Self::from_env_with_daemon_config_path(daemon_config::default_config_path())
238 }
239
240 pub fn from_env_for_daemon_binary() -> Result<Self, BootstrapError> {
249 let run_dir = daemon_config::daemon_run_dir().map_err(BootstrapError::RunDir)?;
250 let machine_id_path =
251 crate::machine_id::default_machine_id_path().map_err(BootstrapError::MachineId)?;
252 let config = Self::from_env()?
253 .with_capture_logs_dir(run_dir.join("logs"))
254 .with_terminal_journal_path(run_dir.join("terminals.jsonl"))
255 .with_live_children_record(crate::live_children::record_path(&run_dir))
256 .with_machine_id_path(machine_id_path);
257 #[cfg(feature = "test-support")]
258 let config = {
259 let mut config = config;
260 config.operator_script =
261 std::env::var_os("SUBC_TEST_OPERATOR_SCRIPT").map(PathBuf::from);
262 config.operator_events =
263 std::env::var_os("SUBC_TEST_OPERATOR_EVENTS").map(PathBuf::from);
264 for (name, value) in [
265 (
266 "SUBC_TEST_OPERATOR_QUEUE_WAIT_MS",
267 &mut config.operator_queue_wait,
268 ),
269 (
270 "SUBC_TEST_OPERATOR_TIMEOUT_MS",
271 &mut config.operator_timeout,
272 ),
273 (
274 "SUBC_TEST_OPERATOR_STUCK_MS",
275 &mut config.operator_stuck_grace,
276 ),
277 ] {
278 if let Ok(ms) = std::env::var(name) {
279 if let Ok(ms) = ms.parse::<u64>() {
280 *value = Duration::from_millis(ms);
281 }
282 }
283 }
284 config
285 };
286 Ok(config)
287 }
288
289 pub fn from_env_with_daemon_config_path(
290 daemon_config_path: impl AsRef<Path>,
291 ) -> Result<Self, BootstrapError> {
292 let daemon_config_path = daemon_config_path.as_ref().to_path_buf();
293 let (daemon_config, activity_config) =
294 daemon_config::load_with_activity(&daemon_config_path)
295 .map_err(BootstrapError::DaemonConfig)?
296 .map(|(config, activity)| (Some(config), activity))
297 .unwrap_or_default();
298 let config_port = daemon_config.as_ref().and_then(|config| config.port);
299 let storage_config = daemon_config
300 .as_ref()
301 .and_then(|config| config.storage.clone());
302 let admission_facts_carrier_module_id = daemon_config
303 .as_ref()
304 .and_then(|config| config.admission_facts_carrier_module_id.clone());
305 let admission_facts_targets = daemon_config
306 .as_ref()
307 .and_then(|config| config.admission_facts_targets.clone());
308 let scope_authority_owners = daemon_config
309 .as_ref()
310 .map(|config| config.scope_authority_owners.clone())
311 .unwrap_or_else(daemon_config::default_scope_authority_owners);
312 let privileged_operator_prompt = daemon_config
313 .as_ref()
314 .map(|config| config.privileged_operator_prompt)
315 .unwrap_or_default();
316 let route_bind_relay_default_ms = daemon_config
317 .as_ref()
318 .and_then(|config| config.route_bind_relay_timeout_ms);
319 let reserved_capabilities = daemon_config
320 .as_ref()
321 .map(|config| config.reserved_capabilities.clone())
322 .unwrap_or_default();
323 let configured_modules = daemon_config
324 .map(|config| config.modules)
325 .unwrap_or_default();
326
327 let port = match env::var(SUBC_PORT_ENV) {
328 Ok(raw) if !raw.trim().is_empty() => {
329 let port = raw
330 .parse::<u16>()
331 .map_err(|source| BootstrapError::InvalidPort { raw, source })?;
332 if let Some(config_port) = config_port {
333 info!(
334 env = SUBC_PORT_ENV,
335 env_port = port,
336 config_port,
337 "SUBC_PORT overrides daemon config port"
338 );
339 }
340 port
341 }
342 Ok(_) | Err(_) => config_port.unwrap_or(DEFAULT_SUBC_PORT),
343 };
344
345 let (connection_file_path, connection_file_source) =
346 connection_file_path_with_source(non_empty_os_var("XDG_RUNTIME_DIR"));
347 Ok(Self::new(connection_file_path, port)
348 .with_configured_modules(configured_modules)
349 .with_storage_config(storage_config)
350 .with_admission_facts_config(admission_facts_carrier_module_id, admission_facts_targets)
351 .with_scope_authority_owners(scope_authority_owners)
352 .with_privileged_operator_prompt(privileged_operator_prompt)
353 .with_activity_config(activity_config)
354 .with_route_bind_relay_default_ms(route_bind_relay_default_ms)
355 .with_reserved_capabilities(reserved_capabilities)
356 .with_daemon_config_source(daemon_config_path, config_port)
357 .with_connection_file_source(connection_file_source))
358 }
359
360 pub fn with_daemon_config_path(
361 self,
362 daemon_config_path: impl AsRef<Path>,
363 ) -> Result<Self, BootstrapError> {
364 let daemon_config_path = daemon_config_path.as_ref().to_path_buf();
365 let (daemon_config, activity_config) =
366 daemon_config::load_with_activity(&daemon_config_path)
367 .map_err(BootstrapError::DaemonConfig)?
368 .map(|(config, activity)| (Some(config), activity))
369 .unwrap_or_default();
370 let configured_port = daemon_config.as_ref().and_then(|config| config.port);
371 let storage_config = daemon_config
372 .as_ref()
373 .and_then(|config| config.storage.clone());
374 let admission_facts_carrier_module_id = daemon_config
375 .as_ref()
376 .and_then(|config| config.admission_facts_carrier_module_id.clone());
377 let admission_facts_targets = daemon_config
378 .as_ref()
379 .and_then(|config| config.admission_facts_targets.clone());
380 let scope_authority_owners = daemon_config
381 .as_ref()
382 .map(|config| config.scope_authority_owners.clone())
383 .unwrap_or_else(daemon_config::default_scope_authority_owners);
384 let privileged_operator_prompt = daemon_config
385 .as_ref()
386 .map(|config| config.privileged_operator_prompt)
387 .unwrap_or_default();
388 let route_bind_relay_default_ms = daemon_config
389 .as_ref()
390 .and_then(|config| config.route_bind_relay_timeout_ms);
391 let reserved_capabilities = daemon_config
392 .as_ref()
393 .map(|config| config.reserved_capabilities.clone())
394 .unwrap_or_default();
395 let configured_modules = daemon_config
396 .map(|config| config.modules)
397 .unwrap_or_default();
398 Ok(self
399 .with_configured_modules(configured_modules)
400 .with_storage_config(storage_config)
401 .with_admission_facts_config(admission_facts_carrier_module_id, admission_facts_targets)
402 .with_scope_authority_owners(scope_authority_owners)
403 .with_privileged_operator_prompt(privileged_operator_prompt)
404 .with_activity_config(activity_config)
405 .with_route_bind_relay_default_ms(route_bind_relay_default_ms)
406 .with_reserved_capabilities(reserved_capabilities)
407 .with_daemon_config_source(daemon_config_path, configured_port))
408 }
409
410 pub fn with_configured_modules(
411 mut self,
412 modules: impl IntoIterator<Item = ConfiguredModule>,
413 ) -> Self {
414 self.configured_modules = modules.into_iter().collect();
415 self.configured_modules
416 .sort_by(|left, right| left.module_id.cmp(&right.module_id));
417 self
418 }
419
420 pub fn with_storage_config(
421 mut self,
422 storage_config: Option<daemon_config::StorageConfig>,
423 ) -> Self {
424 self.storage_config = storage_config;
425 self
426 }
427
428 pub fn with_admission_facts_config(
429 mut self,
430 carrier_module_id: Option<String>,
431 targets: Option<Vec<String>>,
432 ) -> Self {
433 self.admission_facts = AdmissionFactsConfig {
434 carrier_module_id,
435 targets,
436 };
437 self
438 }
439
440 pub fn with_scope_authority_owners(mut self, owners: Vec<String>) -> Self {
443 self.scope_authority_owners = owners;
444 self
445 }
446
447 pub fn with_privileged_operator_prompt(
449 mut self,
450 mode: daemon_config::PrivilegedOperatorPrompt,
451 ) -> Self {
452 self.privileged_operator_prompt = mode;
453 self
454 }
455
456 pub fn with_activity_config(mut self, config: daemon_config::ActivityConfig) -> Self {
457 self.activity_config = config;
458 self
459 }
460
461 pub fn with_route_bind_relay_default_ms(mut self, ms: Option<u64>) -> Self {
466 self.route_bind_relay_default_ms = ms;
467 self
468 }
469
470 pub fn with_reserved_capabilities(
471 mut self,
472 reserved_capabilities: BTreeMap<String, String>,
473 ) -> Self {
474 self.reserved_capabilities = reserved_capabilities;
475 self
476 }
477
478 fn with_daemon_config_source(
479 mut self,
480 daemon_config_path: PathBuf,
481 configured_port: Option<u16>,
482 ) -> Self {
483 self.daemon_config_path = Some(daemon_config_path);
484 self.configured_port = configured_port;
485 self
486 }
487
488 fn with_connection_file_source(mut self, source: ConnectionFileSource) -> Self {
489 self.connection_file_source = source;
490 self
491 }
492
493 pub fn with_watchdog_config(mut self, watchdog_config: DaemonSelfWatchdogConfig) -> Self {
494 self.watchdog_config = watchdog_config;
495 self
496 }
497}
498
499#[allow(clippy::large_enum_variant)]
503#[derive(Debug)]
504pub enum Outcome {
505 AlreadyRunning,
507 Bound(BoundDaemon),
510}
511
512#[derive(Debug)]
513pub struct BoundDaemon {
514 pub listeners: Vec<TcpListener>,
515 pub connection_info: ConnectionInfo,
516 pub connection_file_path: PathBuf,
517 pub connection_file_source: ConnectionFileSource,
518 pub machine_id: Option<crate::machine_id::MachineId>,
521 run_dir_lock: Option<crate::run_dir_lock::RunDirLock>,
525 publication_lock: Option<StartLock>,
531}
532
533pub fn connection_file_path() -> PathBuf {
540 connection_file_path_with_source(non_empty_os_var("XDG_RUNTIME_DIR")).0
541}
542
543fn connection_file_path_with_source(
544 runtime_dir: Option<OsString>,
545) -> (PathBuf, ConnectionFileSource) {
546 if let Some(runtime_dir) = runtime_dir.filter(|value| !value.is_empty()) {
547 return (
548 PathBuf::from(runtime_dir).join(CONNECTION_FILE_NAME),
549 ConnectionFileSource::XdgRuntimeDir,
550 );
551 }
552
553 (
554 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token())),
555 ConnectionFileSource::TempDirFallback,
556 )
557}
558
559pub async fn run() -> Result<(), BootstrapError> {
565 run_with_config(
568 BootstrapConfig::from_env_for_daemon_binary()?
569 .with_cgroup_placement(CgroupPlacementConfig::Current),
570 )
571 .await
572}
573
574pub async fn run_with_config(config: BootstrapConfig) -> Result<(), BootstrapError> {
598 let forwarding = Arc::new(ForwardingTable::default());
599 forwarding.operator_confirms().configure_bootstrap(&config);
600 let configured_modules = config.configured_modules.clone();
601 let storage_config = config.storage_config.clone();
602 let admission_facts = config.admission_facts.clone();
603 let scope_authority_owners = config.scope_authority_owners.clone();
604 let privileged_operator_prompt = config.privileged_operator_prompt;
605 let activity_config = config.activity_config;
606 let daemon_config_path = config.daemon_config_path.clone();
607 let configured_port = config.configured_port;
608 let route_bind_relay_default_ms = config.route_bind_relay_default_ms;
609 let reserved_capabilities = config.reserved_capabilities.clone();
610 let watchdog_config = config.watchdog_config.clone();
611 let cgroup_placement_config = config.cgroup_placement.clone();
612 let capture_logs_dir = config.capture_logs_dir.clone();
613 let terminal_journal_path = config.terminal_journal_path.clone();
614 let live_children_path = config.live_children_path.clone();
615 let privacy_trampoline = config.privacy_trampoline.clone();
616 match ensure_singleton_inner(config, false).await? {
617 Outcome::AlreadyRunning => {
618 info!("subc daemon already running");
619 Ok(())
620 }
621 Outcome::Bound(bound) => {
622 #[cfg(target_os = "linux")]
623 let cgroup_placement = prepare_cgroup_placement(&cgroup_placement_config);
624 #[cfg(not(target_os = "linux"))]
625 let _ = cgroup_placement_config;
626 serve_bound_daemon(
627 bound,
628 forwarding,
629 configured_modules,
630 storage_config,
631 admission_facts,
632 scope_authority_owners,
633 privileged_operator_prompt,
634 activity_config,
635 daemon_config_path,
636 configured_port,
637 route_bind_relay_default_ms,
638 reserved_capabilities,
639 watchdog_config,
640 capture_logs_dir,
641 terminal_journal_path,
642 live_children_path,
643 privacy_trampoline,
644 #[cfg(target_os = "linux")]
645 cgroup_placement,
646 )
647 .await
648 }
649 }
650}
651
652#[cfg(target_os = "linux")]
653fn prepare_cgroup_placement(config: &CgroupPlacementConfig) -> Option<subc_cgroup::Placement> {
654 let result = match config {
655 CgroupPlacementConfig::Disabled => return None,
656 CgroupPlacementConfig::Current => subc_cgroup::prepare_current(),
657 CgroupPlacementConfig::Root(root) => subc_cgroup::prepare_at(root),
658 };
659
660 match result {
661 Ok(Some(placement)) => Some(placement),
662 Ok(None) => {
663 warn!(
664 placement = ?config,
665 "module cgroup placement is disabled: configured cgroup root is not delegated"
666 );
667 None
668 }
669 Err(error) => {
670 warn!(
671 placement = ?config,
672 error = %error,
673 "module cgroup placement is disabled by an unexpected cgroup probe error"
674 );
675 None
676 }
677 }
678}
679
680#[cfg(unix)]
687const NOFILE_TARGET: u64 = 65536;
688
689#[cfg(unix)]
693fn raise_nofile_limit() {
694 #[cfg(target_os = "macos")]
695 let ceiling = std::process::Command::new("/usr/sbin/sysctl")
696 .args(["-n", "kern.maxfilesperproc"])
697 .output()
698 .ok()
699 .filter(|output| output.status.success())
700 .and_then(|output| String::from_utf8(output.stdout).ok())
701 .and_then(|value| value.trim().parse::<u64>().ok())
702 .filter(|value| *value > 0);
703 #[cfg(not(target_os = "macos"))]
704 let ceiling = None;
705 raise_nofile_limit_with_ceiling(ceiling);
706}
707
708#[cfg(unix)]
709fn raise_nofile_limit_with_ceiling(kernel_ceiling: Option<u64>) {
710 match rlimit::Resource::NOFILE.get() {
711 Ok((soft, hard)) => {
712 let target = NOFILE_TARGET
716 .min(hard)
717 .min(kernel_ceiling.unwrap_or(u64::MAX));
718 if soft >= target {
719 return;
720 }
721 match rlimit::Resource::NOFILE.set(target, hard) {
722 Ok(()) => info!(
723 previous_soft = soft,
724 new_soft = target,
725 hard,
726 "raised open-file soft limit for daemon and module children"
727 ),
728 Err(err) => warn!(
729 soft,
730 hard,
731 error = %err,
732 "could not raise open-file soft limit; multi-root modules may exhaust descriptors"
733 ),
734 }
735 }
736 Err(err) => warn!(error = %err, "could not read open-file limit"),
737 }
738}
739
740#[cfg(windows)]
747fn raise_nofile_limit() {
748 const MAXSTDIO_TARGET: u32 = 8192;
749 let current = rlimit::getmaxstdio();
750 if current >= MAXSTDIO_TARGET {
751 return;
752 }
753 match rlimit::setmaxstdio(MAXSTDIO_TARGET) {
754 Ok(new_max) => info!(
755 previous = current,
756 new_max, "raised CRT stdio-stream limit for daemon"
757 ),
758 Err(err) => warn!(
759 current,
760 error = %err,
761 "could not raise CRT stdio-stream limit"
762 ),
763 }
764}
765
766#[cfg(not(any(unix, windows)))]
767fn raise_nofile_limit() {}
768
769pub async fn run_with_daemon_config_path(
770 config: BootstrapConfig,
771 daemon_config_path: impl AsRef<Path>,
772) -> Result<(), BootstrapError> {
773 run_with_config(config.with_daemon_config_path(daemon_config_path)?).await
774}
775
776#[allow(clippy::too_many_arguments)]
777async fn serve_bound_daemon(
778 bound: BoundDaemon,
779 forwarding: Arc<ForwardingTable>,
780 configured_modules: Vec<ConfiguredModule>,
781 storage_config: Option<daemon_config::StorageConfig>,
782 admission_facts: AdmissionFactsConfig,
783 scope_authority_owners: Vec<String>,
784 privileged_operator_prompt: daemon_config::PrivilegedOperatorPrompt,
785 activity_config: daemon_config::ActivityConfig,
786 daemon_config_path: Option<PathBuf>,
787 configured_port: Option<u16>,
788 route_bind_relay_default_ms: Option<u64>,
789 reserved_capabilities: BTreeMap<String, String>,
790 watchdog_config: DaemonSelfWatchdogConfig,
791 capture_logs_dir: Option<PathBuf>,
792 terminal_journal_path: Option<PathBuf>,
793 live_children_path: Option<PathBuf>,
794 privacy_trampoline: Option<PathBuf>,
795 #[cfg(target_os = "linux")] cgroup_placement: Option<subc_cgroup::Placement>,
796) -> Result<(), BootstrapError> {
797 #[cfg(unix)]
798 let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
799 .map_err(BootstrapError::Signal)?;
800 raise_nofile_limit();
803 #[cfg(windows)]
804 if let Err(error) = subc_jobobject::ensure_root_job() {
805 warn!(%error, "module launches disabled: Windows root job setup failed");
808 }
809
810 info!(
811 connection_file = %bound.connection_file_path.display(),
812 connection_file_source = %bound.connection_file_source,
813 connection_file_source_reason = bound.connection_file_source.reason(),
814 endpoints = ?bound.connection_info.endpoints,
815 configured_modules = configured_modules.len(),
816 machine_id = bound.machine_id.as_ref().map(|id| id.as_str()).unwrap_or("none"),
817 "subc daemon starting"
818 );
819
820 let run_dir_lock = bound.run_dir_lock;
831 let publication_lock = bound.publication_lock;
832 if let Some(owner) = &run_dir_lock {
833 crate::live_children::sweep_orphans(
834 owner,
835 &crate::live_children::AdoptedPids::none(),
836 crate::live_children::SweepBounds::default(),
837 )
838 .await;
839 }
840
841 let registry = Arc::new(Registry::default());
842 let process_liveness = Arc::new(SupervisorProcessLiveness::new());
843 let supervisor_handle = SupervisorHandle::new();
844 let connected_clients = ConnectedClients::new();
845 let daemon_incarnation = format!(
846 "{:032x}",
847 u128::from_be_bytes(bound.connection_info.daemon_id)
848 );
849 let supervisor = Supervisor::new(Arc::clone(®istry), RestartPolicy::default())
850 .with_process_liveness(process_liveness.clone())
851 .with_forwarding(Arc::clone(&forwarding))
852 .with_handle(supervisor_handle.clone())
853 .with_connection_file_path(bound.connection_file_path.clone())
854 .with_daemon_incarnation(daemon_incarnation.clone());
855 let supervisor = match privacy_trampoline {
856 Some(path) => supervisor.with_privacy_trampoline(path),
857 None => supervisor,
858 };
859 let activity_run_dir = terminal_journal_path
899 .as_ref()
900 .and_then(|path| path.parent())
901 .map(Path::to_path_buf);
902 let supervisor = match terminal_journal_path {
903 Some(path) => supervisor.with_terminal_journal(path, daemon_incarnation.clone()),
904 None => supervisor,
905 };
906 let supervisor = match capture_logs_dir {
907 Some(dir) => supervisor.with_capture_logs_dir(dir),
908 None => supervisor,
909 };
910 let supervisor = match live_children_path {
911 Some(path) => supervisor.with_live_children_record(path),
912 None => supervisor,
913 };
914 #[cfg(target_os = "linux")]
915 let supervisor = supervisor.with_cgroup_placement(cgroup_placement);
916 let route_bind_relay_timeouts = configured_modules
922 .iter()
923 .filter_map(|module| {
924 module
925 .route_bind_relay_timeout_ms
926 .map(|ms| (module.module_id.clone(), Duration::from_millis(ms)))
927 })
928 .collect::<std::collections::BTreeMap<_, _>>();
929 let control_start_clock = crate::clock::StartClock::capture();
930 let mut control = ControlHandler::with_forwarding(Arc::clone(®istry), forwarding)
931 .with_process_liveness(process_liveness)
932 .with_supervisor(supervisor_handle)
933 .with_connected_clients(connected_clients.clone())
934 .with_storage_config(storage_config)
935 .with_machine_id(bound.machine_id.clone())
936 .with_admission_facts_config(admission_facts.carrier_module_id, admission_facts.targets)
937 .with_scope_authority_owners(scope_authority_owners)
938 .with_privileged_operator_prompt(privileged_operator_prompt)
939 .with_route_bind_relay_timeouts(route_bind_relay_timeouts)
940 .with_daemon_provenance(
941 bound.connection_info.pid,
942 control_start_clock.started_at_ms(),
943 std::env::current_exe().ok(),
944 normalized_build_provenance(env!("SUBC_BUILD_GIT_SHA")),
945 normalized_build_provenance(env!("SUBC_BUILD_LOCK_DIGEST")),
946 )
947 .with_daemon_start_clock(control_start_clock)
948 .with_capability_config(
949 configured_modules
950 .iter()
951 .map(|module| (module.module_id.clone(), module.enabled)),
952 reserved_capabilities,
953 );
954 if let Some(run_dir) = activity_run_dir {
955 control =
956 control.with_activity_ledger_config(&run_dir, daemon_incarnation, activity_config);
957 }
958 if let Some(ms) = route_bind_relay_default_ms {
959 control = control.with_route_bind_relay_timeout(Duration::from_millis(ms));
962 }
963 if let Some(config_path) = daemon_config_path {
964 control = control.with_supervisor_rescan(supervisor.clone(), config_path, configured_port);
965 }
966 let control = Arc::new(control);
967 let router = Arc::new(Router::with_control_handler(Arc::clone(&control)));
968 let auth = ServerAuth::new(
969 bound.connection_info.key.clone(),
970 bound.connection_info.daemon_id,
971 bound.connection_info.daemon_ver.clone(),
972 )
973 .with_connected_clients(connected_clients);
974
975 let mut registered_modules = Vec::with_capacity(configured_modules.len());
979 for configured in configured_modules {
980 let enabled = configured.enabled;
981 let health = configured.health.clone();
982 let module_id = configured.module_id.clone();
983 let registered = match supervisor.register_configured_with_health(
984 configured.module_spec(),
985 enabled,
986 health.clone(),
987 configured.drain_timeout_ms,
988 configured.restart,
989 ) {
990 Ok(registered) => registered,
991 Err(err) => {
992 error!(module_id = %module_id, error = %err, "failed to supervise configured module; continuing daemon startup");
993 continue;
994 }
995 };
996 registered_modules.push(registered);
997 let default_threshold = HealthConfig::default().failure_threshold;
1000 if enabled && health.failure_threshold > default_threshold {
1001 warn!(
1002 module_id = %module_id,
1003 failure_threshold = health.failure_threshold,
1004 default_threshold,
1005 tolerance_secs = health.cadence.as_secs() * u64::from(health.failure_threshold),
1006 "health failure threshold is relaxed above the default; a wedged module stays unflagged for longer"
1007 );
1008 }
1009 info!(module_id = %module_id, enabled, "configured module registered");
1010 }
1011 control.refresh_capability_requirements();
1012
1013 let mut serve_task =
1014 AbortOnDrop::new(tokio::spawn(serve_listeners(bound.listeners, router, auth)));
1015 verify_serving(&bound.connection_info).await?;
1016 let (published, publication_lock) = publish_connection_file(
1023 &bound.connection_file_path,
1024 &bound.connection_info,
1025 publication_lock,
1026 )
1027 .await;
1028 published?;
1029 #[cfg(test)]
1030 startup_publication_hook::run(&bound.connection_file_path).await;
1031 drop(publication_lock);
1032 let _clock_step_task = AbortOnDrop::new(crate::watchdog::spawn_clock_step_monitor());
1033 #[cfg(target_os = "linux")]
1035 let _kill_mode_check = AbortOnDrop::new(tokio::spawn(
1036 crate::systemd_kill_mode::warn_if_kill_mode_defeats_ordered_shutdown(),
1037 ));
1038 let _watchdog_task = AbortOnDrop::new(
1039 DaemonSelfWatchdog::new(
1040 bound.connection_info.clone(),
1041 bound.connection_file_path.clone(),
1042 )
1043 .with_config(watchdog_config)
1044 .spawn(),
1045 );
1046
1047 for registered in registered_modules {
1048 match supervisor.start_registered_configured(registered, None) {
1049 Ok(module) => {
1050 info!(module_id = %module.module_id(), "configured module supervised");
1051 }
1052 Err(err) => {
1053 error!(error = %err, "failed to start configured module; continuing daemon startup");
1054 }
1055 }
1056 }
1057
1058 control.refresh_capability_requirements();
1059 Arc::clone(&control).spawn_capability_deadline_loop();
1060 Arc::clone(&control).spawn_scope_expiry_loop();
1061
1062 #[cfg(unix)]
1063 {
1064 tokio::select! {
1065 result = serve_task.join() => {
1066 return result.map_err(BootstrapError::ServeJoin)?.map_err(BootstrapError::Serve);
1067 }
1068 _ = terminate.recv() => {}
1069 }
1070 supervisor.begin_daemon_shutdown();
1075 drop(_watchdog_task);
1079 drop(serve_task);
1082 let escalated = tokio::select! {
1083 biased;
1084 _ = terminate.recv() => {
1085 info!("second SIGTERM: abandoning daemon shutdown wait");
1086 true
1087 }
1088 result = supervisor.drain_for_daemon_shutdown() => {
1089 if let Err(error) = result {
1090 warn!(%error, "daemon shutdown drain failed; exiting anyway");
1091 }
1092 false
1093 }
1094 };
1095 supervisor
1102 .end_children_for_daemon_shutdown(escalated, async {
1103 terminate.recv().await;
1104 })
1105 .await;
1106 info!("daemon exiting: SIGTERM shutdown complete");
1107 Ok(())
1108 }
1109 #[cfg(not(unix))]
1110 serve_task
1111 .join()
1112 .await
1113 .map_err(BootstrapError::ServeJoin)?
1114 .map_err(BootstrapError::Serve)
1115}
1116
1117fn normalized_build_provenance(value: &str) -> Option<String> {
1118 match value.trim() {
1119 "" | "unavailable" => None,
1120 value => Some(value.to_string()),
1121 }
1122}
1123
1124pub async fn ensure_singleton(
1132 connection_file_path: impl AsRef<Path>,
1133 port: u16,
1134) -> Result<Outcome, BootstrapError> {
1135 ensure_singleton_with_config(BootstrapConfig::new(connection_file_path.as_ref(), port)).await
1136}
1137
1138pub async fn ensure_singleton_with_config(
1139 config: BootstrapConfig,
1140) -> Result<Outcome, BootstrapError> {
1141 ensure_singleton_inner(config, true).await
1142}
1143
1144async fn ensure_singleton_inner(
1145 config: BootstrapConfig,
1146 publish: bool,
1147) -> Result<Outcome, BootstrapError> {
1148 let path = config.connection_file_path;
1149
1150 if matches!(probe_existing(&path).await?, Probe::Live) {
1151 return Ok(Outcome::AlreadyRunning);
1152 }
1153
1154 let lock = StartLock::acquire(&path).await?;
1155
1156 if matches!(probe_existing(&path).await?, Probe::Live) {
1160 return Ok(Outcome::AlreadyRunning);
1161 }
1162
1163 let run_dir_lock = config
1169 .live_children_path
1170 .as_deref()
1171 .map(crate::run_dir_lock::RunDirLock::acquire)
1172 .transpose()?;
1173
1174 remove_stale_connection_file_if_present(&path)?;
1175
1176 let (machine_id, lock, run_dir_lock) = match config.machine_id_path {
1184 None => (None, lock, run_dir_lock),
1185 Some(machine_id_path) => {
1186 let task_path = machine_id_path.clone();
1187 match run_blocking_holding((lock, run_dir_lock), move || {
1188 crate::machine_id::load_or_mint(&task_path)
1189 })
1190 .await
1191 {
1192 Ok((Ok(id), (lock, run_dir_lock))) => (Some(id), lock, run_dir_lock),
1193 Ok((Err(error), _locks)) => return Err(BootstrapError::MachineId(error)),
1194 Err(join_error) => {
1195 return Err(BootstrapError::MachineId(
1196 crate::machine_id::MachineIdFileError::Write {
1197 path: machine_id_path,
1198 source: io::Error::other(describe_blocking_task_failure(
1199 "loading or minting the machine id",
1200 &join_error,
1201 )),
1202 },
1203 ))
1204 }
1205 }
1206 }
1207 };
1208
1209 let (listeners, endpoints) = bind_loopback(config.port).await?;
1210 let connection_info = ConnectionInfo {
1211 schema: SCHEMA_VERSION,
1212 wire_version: Some(PROTOCOL_VERSION),
1213 endpoints,
1214 key: generate_key().map_err(BootstrapError::GenerateConnectionFile)?,
1215 daemon_id: generate_daemon_id().map_err(BootstrapError::GenerateConnectionFile)?,
1216 pid: process::id(),
1217 daemon_ver: config.daemon_ver,
1218 };
1219
1220 let publication_lock = if publish {
1224 let (published, lock) = publish_connection_file(&path, &connection_info, lock).await;
1225 if let Err(error) = published {
1226 drop(listeners);
1227 return Err(error);
1228 }
1229 drop(lock);
1230 None
1231 } else {
1232 Some(lock)
1233 };
1234
1235 Ok(Outcome::Bound(BoundDaemon {
1236 listeners,
1237 connection_info,
1238 connection_file_path: path,
1239 connection_file_source: config.connection_file_source,
1240 machine_id,
1241 run_dir_lock,
1242 publication_lock,
1243 }))
1244}
1245
1246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1247enum Probe {
1248 Live,
1249 StaleOrAbsent,
1250}
1251
1252async fn probe_existing(path: &Path) -> Result<Probe, BootstrapError> {
1253 let info = match connection_file::read(path) {
1254 Ok(info) => info,
1255 Err(source) if is_absent_or_stale_connection_file(&source) => {
1256 return Ok(Probe::StaleOrAbsent)
1257 }
1258 Err(source) => {
1259 return Err(BootstrapError::ConnectionFileRead {
1260 path: path.to_path_buf(),
1261 source,
1262 })
1263 }
1264 };
1265
1266 for endpoint in &info.endpoints {
1267 if matches!(probe_endpoint(&info, endpoint).await, Probe::Live) {
1268 return Ok(Probe::Live);
1269 }
1270 }
1271
1272 Ok(Probe::StaleOrAbsent)
1273}
1274
1275async fn probe_endpoint(info: &ConnectionInfo, endpoint: &Endpoint) -> Probe {
1276 let Ok(ip) = endpoint.host.parse::<IpAddr>() else {
1277 return Probe::StaleOrAbsent;
1278 };
1279 if !ip.is_loopback() {
1280 return Probe::StaleOrAbsent;
1281 }
1282 let addr = SocketAddr::new(ip, endpoint.port);
1283
1284 let mut stream = match timeout(CONNECT_TIMEOUT, TcpStream::connect(addr)).await {
1285 Ok(Ok(stream)) => stream,
1286 Ok(Err(_)) | Err(_) => return Probe::StaleOrAbsent,
1287 };
1288
1289 match authenticate_client(&mut stream, info, PROBE_AUTH_DEADLINE).await {
1290 Ok(()) => Probe::Live,
1291 Err(AuthError::DaemonIdMismatch)
1292 | Err(AuthError::InvalidServerProof)
1293 | Err(AuthError::UnexpectedEof { .. })
1294 | Err(AuthError::Timeout { .. })
1295 | Err(AuthError::JsonEncode { .. })
1296 | Err(AuthError::JsonDecode { .. })
1297 | Err(AuthError::Io { .. })
1298 | Err(AuthError::MessageTooLarge { .. })
1299 | Err(AuthError::KeyTooShort { .. })
1300 | Err(AuthError::Random(_))
1301 | Err(AuthError::InvalidClientAuth) => Probe::StaleOrAbsent,
1302 }
1303}
1304
1305async fn verify_serving(info: &ConnectionInfo) -> Result<(), BootstrapError> {
1306 if let Some(endpoint) = info.endpoints.first() {
1310 if matches!(probe_endpoint(info, endpoint).await, Probe::Live) {
1311 return Ok(());
1312 }
1313 }
1314 Err(BootstrapError::StartupNotServing)
1315}
1316
1317async fn run_blocking_holding<G, T>(
1332 guards: G,
1333 work: impl FnOnce() -> T + Send + 'static,
1334) -> Result<(T, G), JoinError>
1335where
1336 G: Send + 'static,
1337 T: Send + 'static,
1338{
1339 tokio::task::spawn_blocking(move || {
1340 let output = work();
1341 (output, guards)
1342 })
1343 .await
1344}
1345
1346fn describe_blocking_task_failure(work: &str, join_error: &JoinError) -> String {
1348 if join_error.is_panic() {
1349 format!("the background thread {work} panicked before finishing: {join_error}")
1350 } else {
1351 format!(
1352 "the background thread {work} was cancelled before finishing, because the async runtime is shutting down: {join_error}"
1353 )
1354 }
1355}
1356
1357async fn publish_connection_file<G: Send + 'static>(
1367 path: &Path,
1368 info: &ConnectionInfo,
1369 guard: G,
1370) -> (Result<(), BootstrapError>, Option<G>) {
1371 let task_path = path.to_path_buf();
1372 let task_info = info.clone();
1373 let outcome =
1374 run_blocking_holding(guard, move || write_connection_file(&task_path, &task_info)).await;
1375 match outcome {
1376 Ok((Ok(()), guard)) => (Ok(()), Some(guard)),
1377 Ok((Err(source), guard)) => (
1378 Err(BootstrapError::ConnectionFileWrite {
1379 path: path.to_path_buf(),
1380 source,
1381 }),
1382 Some(guard),
1383 ),
1384 Err(join_error) => (
1385 Err(BootstrapError::ConnectionFileWrite {
1386 path: path.to_path_buf(),
1387 source: ConnectionFileError::Io {
1388 op: "write",
1389 path: path.to_path_buf(),
1390 source: io::Error::other(describe_blocking_task_failure(
1391 "writing the connection file",
1392 &join_error,
1393 )),
1394 },
1395 }),
1396 None,
1397 ),
1398 }
1399}
1400
1401fn write_connection_file(path: &Path, info: &ConnectionInfo) -> Result<(), ConnectionFileError> {
1404 #[cfg(test)]
1405 connection_file_write_hook::run(path);
1406 write_atomic(path, info)
1407}
1408
1409#[cfg(test)]
1412mod connection_file_write_hook {
1413 use std::{
1414 path::{Path, PathBuf},
1415 sync::{Mutex, PoisonError},
1416 };
1417
1418 type Hook = Box<dyn FnOnce() + Send>;
1419
1420 static HOOKS: Mutex<Vec<(PathBuf, Hook)>> = Mutex::new(Vec::new());
1423
1424 pub(super) fn install(path: &Path, hook: impl FnOnce() + Send + 'static) {
1426 HOOKS
1427 .lock()
1428 .unwrap_or_else(PoisonError::into_inner)
1429 .push((path.to_path_buf(), Box::new(hook)));
1430 }
1431
1432 pub(super) fn run(path: &Path) {
1433 let hook = {
1434 let mut hooks = HOOKS.lock().unwrap_or_else(PoisonError::into_inner);
1435 hooks
1436 .iter()
1437 .position(|(hooked, _)| hooked == path)
1438 .map(|index| hooks.swap_remove(index).1)
1439 };
1440 if let Some(hook) = hook {
1441 hook();
1442 }
1443 }
1444}
1445
1446#[cfg(test)]
1449mod startup_publication_hook {
1450 use std::{
1451 path::{Path, PathBuf},
1452 sync::{Mutex, PoisonError},
1453 };
1454 use tokio::sync::oneshot;
1455
1456 type Barrier = (oneshot::Sender<()>, oneshot::Receiver<()>);
1457 static BARRIERS: Mutex<Vec<(PathBuf, Barrier)>> = Mutex::new(Vec::new());
1458
1459 pub(super) fn install(path: &Path) -> (oneshot::Receiver<()>, oneshot::Sender<()>) {
1460 let (entered_tx, entered_rx) = oneshot::channel();
1461 let (release_tx, release_rx) = oneshot::channel();
1462 BARRIERS
1463 .lock()
1464 .unwrap_or_else(PoisonError::into_inner)
1465 .push((path.to_path_buf(), (entered_tx, release_rx)));
1466 (entered_rx, release_tx)
1467 }
1468
1469 pub(super) async fn run(path: &Path) {
1470 let barrier = {
1471 let mut barriers = BARRIERS.lock().unwrap_or_else(PoisonError::into_inner);
1472 barriers
1473 .iter()
1474 .position(|(hooked, _)| hooked == path)
1475 .map(|index| barriers.swap_remove(index).1)
1476 };
1477 if let Some((entered, release)) = barrier {
1478 let _ = entered.send(());
1479 let _ = release.await;
1480 }
1481 }
1482}
1483
1484fn is_absent_or_stale_connection_file(err: &ConnectionFileError) -> bool {
1485 match err {
1486 ConnectionFileError::Io { source, .. } if source.kind() == io::ErrorKind::NotFound => true,
1487 ConnectionFileError::JsonRead { .. }
1488 | ConnectionFileError::UnsupportedSchema { .. }
1489 | ConnectionFileError::Invalid { .. }
1490 | ConnectionFileError::KeyTooShort { .. }
1491 | ConnectionFileError::InsecurePermissions { .. } => true,
1495 ConnectionFileError::MissingParent { .. }
1496 | ConnectionFileError::MissingFileName { .. }
1497 | ConnectionFileError::InsecureParentDirectory { .. }
1501 | ConnectionFileError::Io { .. }
1502 | ConnectionFileError::JsonWrite { .. }
1503 | ConnectionFileError::Random(_)
1504 | ConnectionFileError::WireVersionMismatch { .. } => false,
1507 }
1508}
1509
1510fn remove_stale_connection_file_if_present(path: &Path) -> Result<(), BootstrapError> {
1511 match fs::remove_file(path) {
1512 Ok(()) => Ok(()),
1513 Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
1514 Err(source) => Err(BootstrapError::RemoveStale {
1515 path: path.to_path_buf(),
1516 source,
1517 }),
1518 }
1519}
1520
1521async fn bind_loopback(port: u16) -> Result<(Vec<TcpListener>, Vec<Endpoint>), BootstrapError> {
1522 bind_loopback_with(port, |port| TcpListener::bind((Ipv6Addr::LOCALHOST, port))).await
1523}
1524
1525async fn bind_loopback_with<F, Fut>(
1526 port: u16,
1527 mut bind_v6: F,
1528) -> Result<(Vec<TcpListener>, Vec<Endpoint>), BootstrapError>
1529where
1530 F: FnMut(u16) -> Fut,
1531 Fut: std::future::Future<Output = io::Result<TcpListener>>,
1532{
1533 let v4_host = Ipv4Addr::LOCALHOST;
1534 let v4 = TcpListener::bind((v4_host, port))
1535 .await
1536 .map_err(|source| BootstrapError::Bind {
1537 host: v4_host.to_string(),
1538 port,
1539 source,
1540 })?;
1541 let actual_port = v4
1542 .local_addr()
1543 .map_err(|source| BootstrapError::LocalAddr {
1544 host: v4_host.to_string(),
1545 source,
1546 })?
1547 .port();
1548
1549 let mut listeners = vec![v4];
1550 let mut endpoints = vec![Endpoint {
1551 host: v4_host.to_string(),
1552 port: actual_port,
1553 }];
1554
1555 let v6_host = Ipv6Addr::LOCALHOST;
1556 match bind_v6(actual_port).await {
1557 Ok(v6) => {
1558 listeners.push(v6);
1559 endpoints.push(Endpoint {
1560 host: v6_host.to_string(),
1561 port: actual_port,
1562 });
1563 }
1564 Err(err)
1565 if ipv6_loopback_unavailable(&err)
1566 || (port == 0 && err.kind() == io::ErrorKind::AddrInUse) =>
1567 {
1568 warn!(
1569 port = actual_port,
1570 error = %err,
1571 "IPv6 loopback unavailable; serving only IPv4 loopback"
1572 );
1573 }
1574 Err(source) => {
1575 drop(listeners);
1576 return Err(BootstrapError::Bind {
1577 host: v6_host.to_string(),
1578 port: actual_port,
1579 source,
1580 });
1581 }
1582 }
1583
1584 Ok((listeners, endpoints))
1585}
1586
1587fn ipv6_loopback_unavailable(err: &io::Error) -> bool {
1588 matches!(
1589 err.kind(),
1590 io::ErrorKind::AddrNotAvailable | io::ErrorKind::Unsupported
1591 ) || matches!(err.raw_os_error(), Some(47) | Some(49) | Some(97))
1592}
1593
1594struct AbortOnDrop<T> {
1595 handle: JoinHandle<T>,
1596}
1597
1598impl<T> AbortOnDrop<T> {
1599 fn new(handle: JoinHandle<T>) -> Self {
1600 Self { handle }
1601 }
1602
1603 async fn join(&mut self) -> Result<T, JoinError> {
1604 (&mut self.handle).await
1605 }
1606}
1607
1608impl<T> Drop for AbortOnDrop<T> {
1609 fn drop(&mut self) {
1610 if !self.handle.is_finished() {
1611 self.handle.abort();
1612 }
1613 }
1614}
1615
1616#[derive(Debug)]
1617struct StartLock {
1618 _file: fs::File,
1620}
1621
1622impl Drop for StartLock {
1623 fn drop(&mut self) {
1624 if let Err(error) = FileExt::unlock(&self._file) {
1628 tracing::warn!(%error, "failed to release the singleton start lock");
1629 }
1630 }
1631}
1632
1633impl StartLock {
1634 async fn acquire(connection_file_path: &Path) -> Result<Self, BootstrapError> {
1635 let path = start_lock_path(connection_file_path);
1636 for _ in 0..START_LOCK_RETRIES {
1637 let file = match open_owner_only_lock(&path) {
1638 Ok(file) => file,
1639 Err(source) => return Err(BootstrapError::StartLockCreate { path, source }),
1640 };
1641 match FileExt::try_lock(&file) {
1642 Ok(()) => return Ok(Self { _file: file }),
1643 Err(TryLockError::WouldBlock) => sleep(START_LOCK_RETRY_DELAY).await,
1644 Err(TryLockError::Error(source)) => {
1645 return Err(BootstrapError::StartLockCreate { path, source });
1646 }
1647 }
1648 }
1649
1650 Err(BootstrapError::StartLockBusy {
1651 path,
1652 attempts: START_LOCK_RETRIES,
1653 })
1654 }
1655}
1656
1657pub(crate) fn open_owner_only_lock(path: &Path) -> io::Result<fs::File> {
1658 let mut options = fs::OpenOptions::new();
1659 options.read(true).write(true).create(true);
1660 #[cfg(unix)]
1661 {
1662 use std::os::unix::fs::OpenOptionsExt;
1663 options.mode(0o600);
1664 }
1665 options.open(path)
1666}
1667
1668fn start_lock_path(connection_file_path: &Path) -> PathBuf {
1669 let file_name = connection_file_path
1670 .file_name()
1671 .map(|name| name.to_string_lossy())
1672 .unwrap_or_else(|| CONNECTION_FILE_NAME.into());
1673 let lock_name = format!("{file_name}.start-lock");
1674 connection_file_path
1675 .parent()
1676 .filter(|parent| !parent.as_os_str().is_empty())
1677 .unwrap_or_else(|| Path::new("."))
1678 .join(lock_name)
1679}
1680
1681fn non_empty_os_var(key: &str) -> Option<OsString> {
1682 let value = env::var_os(key)?;
1683 if value.is_empty() {
1684 None
1685 } else {
1686 Some(value)
1687 }
1688}
1689
1690#[derive(Debug)]
1693pub enum BootstrapError {
1694 StartupNotServing,
1696 #[cfg(unix)]
1697 Signal(io::Error),
1698 InvalidPort {
1699 raw: String,
1700 source: std::num::ParseIntError,
1701 },
1702 ConnectionFileRead {
1703 path: PathBuf,
1704 source: ConnectionFileError,
1705 },
1706 ConnectionFileWrite {
1707 path: PathBuf,
1708 source: ConnectionFileError,
1709 },
1710 GenerateConnectionFile(ConnectionFileError),
1711 StartLockCreate {
1712 path: PathBuf,
1713 source: io::Error,
1714 },
1715 StartLockBusy {
1716 path: PathBuf,
1717 attempts: usize,
1718 },
1719 RunDirLockCreate {
1721 path: PathBuf,
1722 source: io::Error,
1723 },
1724 RunDirBusy {
1729 path: PathBuf,
1730 holder_pid: Option<u32>,
1731 },
1732 RemoveStale {
1733 path: PathBuf,
1734 source: io::Error,
1735 },
1736 Bind {
1737 host: String,
1738 port: u16,
1739 source: io::Error,
1740 },
1741 LocalAddr {
1742 host: String,
1743 source: io::Error,
1744 },
1745 DaemonConfig(DaemonConfigError),
1746 MachineId(crate::machine_id::MachineIdFileError),
1749 RunDir(daemon_config::DaemonRunDirError),
1752 Serve(ServerError),
1753 ServeJoin(tokio::task::JoinError),
1754}
1755
1756impl fmt::Display for BootstrapError {
1757 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1758 match self {
1759 Self::StartupNotServing => write!(f, "bound daemon did not authenticate its readiness probe; connection file was not published"),
1760 #[cfg(unix)]
1761 Self::Signal(error) => write!(f, "failed to register SIGTERM handler: {error}"),
1762 Self::InvalidPort { raw, source } => {
1763 write!(f, "invalid {SUBC_PORT_ENV} value '{raw}': {source}")
1764 }
1765 Self::ConnectionFileRead { path, source } => write!(
1766 f,
1767 "failed to read connection file {}: {source}",
1768 path.display()
1769 ),
1770 Self::ConnectionFileWrite { path, source } => write!(
1771 f,
1772 "failed to publish connection file {}: {source}",
1773 path.display()
1774 ),
1775 Self::GenerateConnectionFile(err) => {
1776 write!(f, "failed to generate connection-file auth material: {err}")
1777 }
1778 Self::StartLockCreate { path, source } => {
1779 write!(
1780 f,
1781 "failed to create start lock {}: {source}",
1782 path.display()
1783 )
1784 }
1785 Self::StartLockBusy { path, attempts } => write!(
1786 f,
1787 "start lock {} remained busy after {attempts} attempts",
1788 path.display()
1789 ),
1790 Self::RunDirLockCreate { path, source } => write!(
1791 f,
1792 "refusing to start: failed to lock run directory via {}: {source}",
1793 path.display()
1794 ),
1795 Self::RunDirBusy { path, holder_pid } => {
1796 write!(
1797 f,
1798 "refusing to start: run directory lock {} is held by another daemon",
1799 path.display()
1800 )?;
1801 if let Some(pid) = holder_pid {
1802 write!(f, " (pid {pid})")?;
1803 }
1804 write!(
1805 f,
1806 "; a live daemon owns this data home's run state (typically one started with a different XDG_RUNTIME_DIR)"
1807 )
1808 }
1809 Self::RemoveStale { path, source } => write!(
1810 f,
1811 "failed to remove stale connection file {}: {source}",
1812 path.display()
1813 ),
1814 Self::Bind { host, port, source } if source.kind() == io::ErrorKind::AddrInUse => {
1815 write!(
1816 f,
1817 "port {port} in use on loopback {host}: {source}; set the port in config"
1818 )
1819 }
1820 Self::Bind { host, port, source } => {
1821 write!(f, "failed to bind loopback TCP {host}:{port}: {source}")
1822 }
1823 Self::LocalAddr { host, source } => {
1824 write!(f, "failed to read local address for {host}: {source}")
1825 }
1826 Self::DaemonConfig(err) => write!(f, "failed to load daemon config: {err}"),
1827 Self::MachineId(err) => write!(f, "refusing to start: {err}"),
1828 Self::RunDir(err) => write!(f, "refusing to start: {err}"),
1829 Self::Serve(err) => write!(f, "daemon server failed: {err}"),
1830 Self::ServeJoin(err) => write!(f, "daemon server task failed: {err}"),
1831 }
1832 }
1833}
1834
1835impl Error for BootstrapError {
1836 fn source(&self) -> Option<&(dyn Error + 'static)> {
1837 match self {
1838 Self::StartupNotServing => None,
1839 #[cfg(unix)]
1840 Self::Signal(source) => Some(source),
1841 Self::InvalidPort { source, .. } => Some(source),
1842 Self::ConnectionFileRead { source, .. }
1843 | Self::ConnectionFileWrite { source, .. }
1844 | Self::GenerateConnectionFile(source) => Some(source),
1845 Self::StartLockCreate { source, .. }
1846 | Self::RunDirLockCreate { source, .. }
1847 | Self::RemoveStale { source, .. }
1848 | Self::Bind { source, .. }
1849 | Self::LocalAddr { source, .. } => Some(source),
1850 Self::DaemonConfig(err) => Some(err),
1851 Self::MachineId(err) => Some(err),
1852 Self::RunDir(err) => Some(err),
1853 Self::Serve(err) => Some(err),
1854 Self::ServeJoin(err) => Some(err),
1855 Self::StartLockBusy { .. } | Self::RunDirBusy { .. } => None,
1856 }
1857 }
1858}
1859
1860#[cfg(test)]
1861mod tests {
1862 mod activity {
1863 include!("activity_bootstrap_tests.rs");
1864 }
1865 mod startup_order {
1866 include!("startup_order_tests.rs");
1867 }
1868 use super::*;
1869 use crate::server::ServerAuth;
1870 use cortexkit_test_support::ScratchDir;
1871 #[cfg(target_os = "linux")]
1872 use std::collections::BTreeSet;
1873 use std::sync::Mutex;
1874 #[cfg(target_os = "linux")]
1875 use subc_control::ModuleProtocol;
1876 use subc_transport::MIN_KEY_LEN;
1877 use tokio::io::AsyncReadExt;
1878 use tokio::task::JoinHandle;
1879
1880 #[cfg(unix)]
1881 use std::os::unix::fs::PermissionsExt;
1882
1883 static ENV_LOCK: Mutex<()> = Mutex::new(());
1884
1885 #[test]
1886 fn normalized_build_provenance_preserves_real_values() {
1887 assert_eq!(normalized_build_provenance("abc"), Some("abc".to_string()));
1888 }
1889
1890 #[test]
1891 fn normalized_build_provenance_omits_unavailable_and_empty_values() {
1892 assert_eq!(normalized_build_provenance("unavailable"), None);
1893 assert_eq!(normalized_build_provenance(""), None);
1894 }
1895
1896 #[cfg(target_os = "linux")]
1897 fn current_cgroup_path_for_test() -> io::Result<PathBuf> {
1898 let cgroups = fs::read_to_string("/proc/self/cgroup")?;
1899 let relative = cgroups
1900 .lines()
1901 .find_map(|line| line.strip_prefix("0::"))
1902 .ok_or_else(|| {
1903 io::Error::new(io::ErrorKind::Unsupported, "cgroup v2 is unavailable")
1904 })?;
1905 Ok(Path::new("/sys/fs/cgroup").join(relative.trim_start_matches('/')))
1906 }
1907
1908 #[cfg(target_os = "linux")]
1909 fn module_cgroup_directories() -> io::Result<BTreeSet<OsString>> {
1910 let modules = current_cgroup_path_for_test()?.join("subc-modules");
1911 let entries = match fs::read_dir(modules) {
1912 Ok(entries) => entries,
1913 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(BTreeSet::new()),
1914 Err(error) => return Err(error),
1915 };
1916 let mut directories = BTreeSet::new();
1917 for entry in entries {
1918 let entry = entry?;
1919 if entry.file_type()?.is_dir() {
1920 directories.insert(entry.file_name());
1921 }
1922 }
1923 Ok(directories)
1924 }
1925
1926 #[cfg(target_os = "linux")]
1927 async fn wait_for_path(path: &Path, task: &JoinHandle<Result<(), BootstrapError>>) {
1928 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
1929 while !path.exists() && tokio::time::Instant::now() < deadline {
1930 assert!(
1931 !task.is_finished(),
1932 "daemon exited before creating {}",
1933 path.display()
1934 );
1935 sleep(Duration::from_millis(10)).await;
1936 }
1937 assert!(path.exists(), "daemon did not create {}", path.display());
1938 }
1939
1940 #[cfg(target_os = "linux")]
1945 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1946 async fn run_with_config_does_not_reconcile_the_ambient_cgroup_by_default() {
1947 let temp = unique_temp_dir("bootstrap-cgroup-default-disabled");
1948 let module_id = format!("cgroup-isolation-probe-{}", process::id());
1949 let before = module_cgroup_directories().expect("read ambient module cgroups before boot");
1950 assert!(
1951 !before.contains(&OsString::from(&module_id)),
1952 "isolation probe cgroup already exists before this daemon starts"
1953 );
1954 let capture = temp.join("logs").join(format!("{module_id}.stderr.log"));
1955 let module = ConfiguredModule {
1956 module_id,
1957 program: PathBuf::from("sh"),
1958 args: vec!["-c".to_string(), "sleep 30".to_string()],
1959 env: Vec::new(),
1960 log: None,
1961 enabled: true,
1962 reserved: false,
1963 reserved_prefixes: Vec::new(),
1964 protocol: ModuleProtocol::None,
1965 overlap: Default::default(),
1966 health: HealthConfig::default(),
1967 drain_timeout_ms: None,
1968 route_bind_relay_timeout_ms: None,
1969 restart: RestartPolicy::default(),
1970 };
1971 let config = BootstrapConfig::new(temp.join("connection.json"), 0)
1972 .with_configured_modules([module])
1973 .with_capture_logs_dir(temp.join("logs"))
1974 .with_terminal_journal_path(temp.join("terminals.jsonl"));
1975 let task = tokio::spawn(run_with_config(config));
1976
1977 wait_for_path(&capture, &task).await;
1978 let after = module_cgroup_directories().expect("read ambient module cgroups after boot");
1979
1980 task.abort();
1981 assert!(task
1982 .await
1983 .expect_err("aborted daemon task must cancel")
1984 .is_cancelled());
1985 assert_eq!(
1986 before, after,
1987 "an in-process daemon must not create or reconcile ambient module cgroups"
1988 );
1989 }
1990
1991 #[cfg(target_os = "linux")]
1992 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1993 async fn explicit_cgroup_root_is_prepared_inside_the_fixture_tree() {
1994 let temp = unique_temp_dir("bootstrap-cgroup-explicit-root");
1995 let cgroup_root = temp.join("cgroup");
1996 fs::create_dir(&cgroup_root).expect("create scratch cgroup root");
1997 fs::write(cgroup_root.join("cgroup.procs"), b"").expect("write scratch cgroup marker");
1998 let modules = cgroup_root.join("subc-modules");
1999 let config = BootstrapConfig::new(temp.join("connection.json"), 0)
2000 .with_cgroup_placement(CgroupPlacementConfig::Root(cgroup_root))
2001 .with_terminal_journal_path(temp.join("terminals.jsonl"));
2002 let task = tokio::spawn(run_with_config(config));
2003
2004 wait_for_path(&modules, &task).await;
2005
2006 task.abort();
2007 assert!(task
2008 .await
2009 .expect_err("aborted daemon task must cancel")
2010 .is_cancelled());
2011 assert!(
2012 fs::read_dir(&modules)
2013 .expect("read prepared modules directory")
2014 .next()
2015 .is_none(),
2016 "the delegation probe must clean up after itself"
2017 );
2018 }
2019
2020 struct EnvGuard {
2021 key: &'static str,
2022 previous: Option<OsString>,
2023 }
2024
2025 impl EnvGuard {
2026 fn set(key: &'static str, value: &Path) -> Self {
2027 let previous = env::var_os(key);
2028 env::set_var(key, value);
2029 Self { key, previous }
2030 }
2031
2032 fn set_str(key: &'static str, value: &str) -> Self {
2033 let previous = env::var_os(key);
2034 env::set_var(key, value);
2035 Self { key, previous }
2036 }
2037
2038 fn unset(key: &'static str) -> Self {
2039 let previous = env::var_os(key);
2040 env::remove_var(key);
2041 Self { key, previous }
2042 }
2043 }
2044
2045 impl Drop for EnvGuard {
2046 fn drop(&mut self) {
2047 match &self.previous {
2048 Some(value) => env::set_var(self.key, value),
2049 None => env::remove_var(self.key),
2050 }
2051 }
2052 }
2053
2054 fn unique_temp_dir(name: &str) -> ScratchDir {
2055 ScratchDir::new(name)
2056 }
2057
2058 fn temp_connection_file_path(name: &str) -> (ScratchDir, PathBuf) {
2059 let dir = unique_temp_dir(name);
2060 let path = dir.join("conn.json");
2061 (dir, path)
2062 }
2063
2064 fn auth_for(info: &ConnectionInfo) -> ServerAuth {
2065 ServerAuth::new(info.key.clone(), info.daemon_id, info.daemon_ver.clone())
2066 }
2067
2068 fn start_server(bound: BoundDaemon) -> JoinHandle<Result<(), ServerError>> {
2069 let auth = auth_for(&bound.connection_info);
2070 tokio::spawn(serve_listeners(
2071 bound.listeners,
2072 Arc::new(Router::with_default_self_handler()),
2073 auth,
2074 ))
2075 }
2076
2077 fn expect_bound(outcome: Outcome) -> BoundDaemon {
2078 match outcome {
2079 Outcome::Bound(bound) => bound,
2080 Outcome::AlreadyRunning => panic!("fresh connection file unexpectedly had a daemon"),
2081 }
2082 }
2083
2084 async fn connect_from_info(conn: &ConnectionInfo) -> io::Result<TcpStream> {
2085 let endpoint = conn
2086 .endpoints
2087 .first()
2088 .expect("test connection file should have an endpoint");
2089 let ip: IpAddr = endpoint.host.parse().unwrap();
2090 TcpStream::connect(SocketAddr::new(ip, endpoint.port)).await
2091 }
2092
2093 fn make_connection_info(port: u16) -> ConnectionInfo {
2094 ConnectionInfo {
2095 schema: SCHEMA_VERSION,
2096 wire_version: Some(PROTOCOL_VERSION),
2097 endpoints: vec![Endpoint {
2098 host: "127.0.0.1".to_owned(),
2099 port,
2100 }],
2101 key: generate_key().unwrap(),
2102 daemon_id: generate_daemon_id().unwrap(),
2103 pid: process::id(),
2104 daemon_ver: "test-subc".to_owned(),
2105 }
2106 }
2107
2108 fn write_raw_owner_only_connection_file(path: &Path, contents: &[u8]) {
2109 fs::write(path, contents).unwrap();
2110 #[cfg(unix)]
2111 fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();
2112 }
2113
2114 fn assert_owner_only_connection_file(path: &Path) {
2115 #[cfg(unix)]
2118 {
2119 let mode = fs::metadata(path).unwrap().permissions().mode() & 0o777;
2120 assert_eq!(mode, 0o600);
2121 }
2122 #[cfg(not(unix))]
2123 let _ = path;
2124 }
2125
2126 #[test]
2127 fn connection_file_path_uses_xdg_runtime_dir_when_set() {
2128 let _env_lock = ENV_LOCK.lock().unwrap();
2129 let runtime_dir = unique_temp_dir("xdg-runtime");
2130 let _xdg = EnvGuard::set("XDG_RUNTIME_DIR", runtime_dir.path());
2131
2132 assert_eq!(
2133 connection_file_path(),
2134 runtime_dir.join(CONNECTION_FILE_NAME)
2135 );
2136 }
2137
2138 #[test]
2139 fn connection_file_path_source_is_xdg_runtime_dir_when_set() {
2140 let runtime_dir = OsString::from("/run/user/1000");
2141
2142 let (path, source) = connection_file_path_with_source(Some(runtime_dir));
2143
2144 assert_eq!(
2145 path,
2146 PathBuf::from("/run/user/1000").join(CONNECTION_FILE_NAME)
2147 );
2148 assert_eq!(source, ConnectionFileSource::XdgRuntimeDir);
2149 }
2150
2151 #[test]
2152 fn connection_file_path_falls_back_to_temp_dir_with_user_token_when_xdg_unset() {
2153 let _env_lock = ENV_LOCK.lock().unwrap();
2154 let _xdg = EnvGuard::unset("XDG_RUNTIME_DIR");
2155
2156 assert_eq!(
2157 connection_file_path(),
2158 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
2159 );
2160 }
2161
2162 #[test]
2163 fn connection_file_path_source_is_temp_dir_when_xdg_unset() {
2164 let (path, source) = connection_file_path_with_source(None);
2165
2166 assert_eq!(
2167 path,
2168 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
2169 );
2170 assert_eq!(source, ConnectionFileSource::TempDirFallback);
2171 }
2172
2173 #[test]
2178 fn user_connection_token_is_stable_under_concurrent_callers() {
2179 let expected = user_connection_token();
2180 let workers: Vec<_> = (0..32)
2181 .map(|_| {
2182 std::thread::spawn(|| (0..40).map(|_| user_connection_token()).collect::<Vec<_>>())
2183 })
2184 .collect();
2185 for worker in workers {
2186 for token in worker.join().expect("probe thread") {
2187 assert_eq!(token, expected, "token diverged under concurrent probes");
2188 }
2189 }
2190 }
2191
2192 #[test]
2193 fn connection_file_path_source_is_temp_dir_when_xdg_empty() {
2194 let (path, source) = connection_file_path_with_source(Some(OsString::new()));
2195
2196 assert_eq!(
2197 path,
2198 env::temp_dir().join(format!("subc-{}.connection.json", user_connection_token()))
2199 );
2200 assert_eq!(source, ConnectionFileSource::TempDirFallback);
2201 }
2202
2203 #[test]
2207 fn daemon_binary_config_journals_and_captures_into_the_run_dir() {
2208 let _env_lock = ENV_LOCK.lock().unwrap();
2209 let root = unique_temp_dir("daemon-binary-config");
2210 let data_home = root.join("data");
2211 let _data = EnvGuard::set("XDG_DATA_HOME", &data_home);
2212 let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
2213 let _port = EnvGuard::unset(SUBC_PORT_ENV);
2214
2215 let config = BootstrapConfig::from_env_for_daemon_binary().unwrap();
2216
2217 let run_dir = data_home.join("cortexkit").join("run");
2218 assert_eq!(
2219 config.terminal_journal_path,
2220 Some(run_dir.join("terminals.jsonl"))
2221 );
2222 assert_eq!(config.capture_logs_dir, Some(run_dir.join("logs")));
2223 assert_eq!(
2224 BootstrapConfig::new(root.join("connection.json"), 0).terminal_journal_path,
2225 None,
2226 "an in-process config must not journal anywhere unless asked to"
2227 );
2228 }
2229
2230 #[test]
2231 fn daemon_binary_config_refuses_a_relative_data_home() {
2232 let _env_lock = ENV_LOCK.lock().unwrap();
2233 let root = unique_temp_dir("daemon-binary-relative-data");
2234 let _data = EnvGuard::set_str("XDG_DATA_HOME", "relative-data-home");
2235 let _config = EnvGuard::set("XDG_CONFIG_HOME", &root.join("config"));
2236 let _port = EnvGuard::unset(SUBC_PORT_ENV);
2237
2238 let error = BootstrapConfig::from_env_for_daemon_binary()
2239 .expect_err("a relative data home must refuse the daemon binary's config");
2240 assert!(
2241 matches!(error, BootstrapError::RunDir(_)),
2242 "expected a run-directory refusal, got {error}"
2243 );
2244 assert!(error.to_string().contains("XDG_DATA_HOME"), "{error}");
2245 }
2246
2247 #[test]
2248 fn privileged_operator_prompt_is_loaded_by_both_bootstrap_config_paths() {
2249 let _env_lock = ENV_LOCK.lock().unwrap();
2250 let _port = EnvGuard::unset(SUBC_PORT_ENV);
2251 let (_dir, conn_path) = temp_connection_file_path("privileged-operator-prompt");
2252 let config_path = conn_path.with_file_name("subc.jsonc");
2253 for (doc, expected) in [
2254 (None, daemon_config::PrivilegedOperatorPrompt::Log),
2255 (
2256 Some(r#"{"version":1}"#),
2257 daemon_config::PrivilegedOperatorPrompt::Log,
2258 ),
2259 (
2260 Some(r#"{"version":1,"privileged_operator_prompt":"log"}"#),
2261 daemon_config::PrivilegedOperatorPrompt::Log,
2262 ),
2263 (
2264 Some(r#"{"version":1,"privileged_operator_prompt":"enforce"}"#),
2265 daemon_config::PrivilegedOperatorPrompt::Enforce,
2266 ),
2267 ] {
2268 if let Some(doc) = doc {
2269 fs::write(&config_path, doc).unwrap();
2270 }
2271 assert_eq!(
2272 BootstrapConfig::from_env_with_daemon_config_path(&config_path)
2273 .unwrap()
2274 .privileged_operator_prompt,
2275 expected
2276 );
2277 assert_eq!(
2278 BootstrapConfig::new(&conn_path, 0)
2279 .with_daemon_config_path(&config_path)
2280 .unwrap()
2281 .privileged_operator_prompt,
2282 expected
2283 );
2284 }
2285 }
2286
2287 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2288 async fn privileged_operator_prompt_is_snapshotted_by_running_daemon() {
2289 let dir = unique_temp_dir("privileged-operator-prompt-bootstrap");
2290 let connection_path = dir.join("connection.json");
2291 let config_path = dir.join("subc.jsonc");
2292 fs::write(
2293 &config_path,
2294 r#"{"version":1,"privileged_operator_prompt":"enforce"}"#,
2295 )
2296 .unwrap();
2297 let config = BootstrapConfig::new(&connection_path, 0)
2298 .with_daemon_config_path(&config_path)
2299 .unwrap();
2300 let daemon = AbortOnDrop::new(tokio::spawn(run_with_config(config)));
2301 tokio::time::timeout(Duration::from_secs(5), async {
2302 while !connection_path.exists() {
2303 assert!(
2304 !daemon.handle.is_finished(),
2305 "daemon exited before publishing"
2306 );
2307 tokio::task::yield_now().await;
2308 }
2309 })
2310 .await
2311 .unwrap();
2312 let info = connection_file::read(&connection_path).unwrap();
2313 let mut client = connect_from_info(&info).await.unwrap();
2314 authenticate_client(&mut client, &info, Duration::from_secs(5))
2315 .await
2316 .unwrap();
2317 for (correlation, mode, expected) in [
2318 (1, "enforce", Vec::new()),
2319 (2, "log", vec!["privileged_operator_prompt"]),
2320 (3, "log", vec!["privileged_operator_prompt"]),
2321 ] {
2322 fs::write(
2323 &config_path,
2324 serde_json::json!({"version":1,"privileged_operator_prompt":mode}).to_string(),
2325 )
2326 .unwrap();
2327 let frame = crate::Frame::build(
2328 subc_protocol::FrameType::Request,
2329 subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
2330 0,
2331 0,
2332 correlation,
2333 serde_json::to_vec(&subc_control::ClientControlRequest::SupervisorRescan {
2334 preview: true,
2335 })
2336 .unwrap(),
2337 )
2338 .unwrap();
2339 crate::write_frame(&mut client, &frame).await.unwrap();
2340 let reply =
2341 tokio::time::timeout(Duration::from_secs(5), crate::read_frame(&mut client))
2342 .await
2343 .unwrap()
2344 .unwrap()
2345 .unwrap();
2346 assert_eq!(reply.header.ty, subc_protocol::FrameType::Response);
2347 assert_eq!(reply.header.corr, correlation);
2348 let subc_control::ClientControlResponse::SupervisorRescan { result } =
2349 serde_json::from_slice(&reply.body).unwrap()
2350 else {
2351 panic!("expected a rescan response");
2352 };
2353 assert_eq!(result.restart_required, expected);
2354 }
2355 }
2356
2357 #[test]
2358 fn configured_port_uses_default_config_and_env_override() {
2359 let _env_lock = ENV_LOCK.lock().unwrap();
2360 let (_dir, conn_path) = temp_connection_file_path("daemon-config-port");
2361 let config_path = conn_path.with_file_name("subc.jsonc");
2362
2363 let _port = EnvGuard::unset(SUBC_PORT_ENV);
2364 assert_eq!(
2365 BootstrapConfig::from_env_with_daemon_config_path(&config_path)
2366 .unwrap()
2367 .port,
2368 DEFAULT_SUBC_PORT
2369 );
2370
2371 fs::write(&config_path, r#"{ "version": 1, "port": 8123 }"#).unwrap();
2372 assert_eq!(
2373 BootstrapConfig::from_env_with_daemon_config_path(&config_path)
2374 .unwrap()
2375 .port,
2376 8123
2377 );
2378
2379 let _port = EnvGuard::set_str(SUBC_PORT_ENV, "9012");
2380 assert_eq!(
2381 BootstrapConfig::from_env_with_daemon_config_path(&config_path)
2382 .unwrap()
2383 .port,
2384 9012
2385 );
2386 }
2387
2388 #[tokio::test]
2389 async fn second_singleton_probe_against_served_tcp_daemon_reports_already_running() {
2390 let (_dir, path) = temp_connection_file_path("already-running");
2391
2392 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2393 let server = start_server(bound);
2394
2395 let second = ensure_singleton(&path, 0).await.unwrap();
2396 assert!(matches!(second, Outcome::AlreadyRunning));
2397
2398 server.abort();
2399 let _ = server.await;
2400 }
2401
2402 #[tokio::test]
2403 async fn daemon_connection_file_publishes_protocol_wire_version() {
2404 let (_dir, path) = temp_connection_file_path("wire-version");
2405 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2406 assert_eq!(bound.connection_info.wire_version, Some(PROTOCOL_VERSION));
2407 assert_eq!(
2408 connection_file::read(&path).unwrap().wire_version,
2409 Some(PROTOCOL_VERSION)
2410 );
2411
2412 drop(bound.listeners);
2413 }
2414
2415 #[tokio::test]
2416 async fn stale_unbound_connection_file_is_reclaimed() {
2417 let (_dir, path) = temp_connection_file_path("stale-reclaim");
2418 let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
2419 let stale_port = stale.local_addr().unwrap().port();
2420 drop(stale);
2421 let stale_info = make_connection_info(stale_port);
2422 write_atomic(&path, &stale_info).unwrap();
2423
2424 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2425 assert_ne!(bound.connection_info.key, stale_info.key);
2426 drop(bound.listeners);
2427 }
2428
2429 #[cfg(unix)]
2430 #[tokio::test]
2431 async fn ensure_singleton_reclaims_insecure_connection_file() {
2432 let (_dir, path) = temp_connection_file_path("insecure-reclaim");
2433 let stale = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
2434 let stale_port = stale.local_addr().unwrap().port();
2435 drop(stale);
2436 let stale_info = make_connection_info(stale_port);
2437 write_atomic(&path, &stale_info).unwrap();
2438 fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
2439
2440 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2441 assert_ne!(bound.connection_info.key, stale_info.key);
2442 assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
2443 assert_owner_only_connection_file(&path);
2444
2445 drop(bound.listeners);
2446 }
2447
2448 #[tokio::test]
2449 async fn ensure_singleton_reclaims_non_loopback_connection_file() {
2450 let (_dir, path) = temp_connection_file_path("non-loopback-reclaim");
2451 let mut stale_info = make_connection_info(8757);
2452 stale_info.endpoints = vec![Endpoint {
2453 host: "192.0.2.10".to_owned(),
2454 port: 8757,
2455 }];
2456 write_atomic(&path, &stale_info).unwrap();
2457
2458 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2459 assert_ne!(bound.connection_info.key, stale_info.key);
2460 assert_ne!(bound.connection_info.daemon_id, stale_info.daemon_id);
2461 assert!(bound
2462 .connection_info
2463 .endpoints
2464 .iter()
2465 .all(|endpoint| endpoint.host.parse::<IpAddr>().unwrap().is_loopback()));
2466 assert_owner_only_connection_file(&path);
2467
2468 drop(bound.listeners);
2469 }
2470
2471 #[tokio::test]
2472 async fn ensure_singleton_reclaims_invalid_connection_file_shapes() {
2473 let mut unsupported_schema = make_connection_info(8757);
2474 unsupported_schema.schema = SCHEMA_VERSION + 1;
2475
2476 let mut empty_endpoints = make_connection_info(8757);
2477 empty_endpoints.endpoints.clear();
2478
2479 let mut short_key = make_connection_info(8757);
2480 short_key.key = vec![0x5A; MIN_KEY_LEN - 1];
2481
2482 let cases = vec![
2483 (
2484 "unsupported-schema",
2485 serde_json::to_vec(&unsupported_schema).unwrap(),
2486 Some(unsupported_schema),
2487 ),
2488 (
2489 "empty-endpoints",
2490 serde_json::to_vec(&empty_endpoints).unwrap(),
2491 Some(empty_endpoints),
2492 ),
2493 (
2494 "short-key",
2495 serde_json::to_vec(&short_key).unwrap(),
2496 Some(short_key),
2497 ),
2498 ("invalid-json", b"{not valid connection json".to_vec(), None),
2499 ];
2500
2501 for (label, contents, old_info) in cases {
2502 let (_dir, path) = temp_connection_file_path(label);
2503 write_raw_owner_only_connection_file(&path, &contents);
2504
2505 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2506 if let Some(old_info) = old_info {
2507 assert_ne!(bound.connection_info.key, old_info.key, "{label}");
2508 assert_ne!(
2509 bound.connection_info.daemon_id, old_info.daemon_id,
2510 "{label}"
2511 );
2512 }
2513 assert!(bound.connection_info.key.len() >= MIN_KEY_LEN, "{label}");
2514 assert_ne!(bound.connection_info.daemon_id, [0u8; 16], "{label}");
2515 assert_owner_only_connection_file(&path);
2516
2517 drop(bound.listeners);
2518 }
2519 }
2520
2521 #[tokio::test]
2522 async fn foreign_reused_port_connection_file_is_reclaimed_after_auth_probe_fails() {
2523 let (_dir, path) = temp_connection_file_path("foreign-reclaim");
2524 let foreign = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
2525 let foreign_port = foreign.local_addr().unwrap().port();
2526 write_atomic(&path, &make_connection_info(foreign_port)).unwrap();
2527 let foreign_task = tokio::spawn(async move {
2528 if let Ok((mut stream, _)) = foreign.accept().await {
2529 let mut buf = [0u8; 64];
2530 let _ = stream.read(&mut buf).await;
2531 }
2532 });
2533
2534 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2535 assert!(bound
2536 .connection_info
2537 .endpoints
2538 .iter()
2539 .all(|endpoint| endpoint.port != foreign_port));
2540
2541 drop(bound.listeners);
2542 let _ = foreign_task.await;
2543 }
2544
2545 #[tokio::test]
2546 async fn stale_start_lock_file_is_reclaimable() {
2547 let (_dir, path) = temp_connection_file_path("start-lock-stale-file");
2548 let lock_path = start_lock_path(&path);
2549 drop(open_owner_only_lock(&lock_path).unwrap());
2550 assert!(lock_path.is_file());
2551
2552 let lock = StartLock::acquire(&path).await.unwrap();
2553 assert!(lock_path.is_file());
2554
2555 drop(lock);
2556 assert!(lock_path.is_file());
2557 }
2558
2559 #[tokio::test]
2560 async fn held_start_lock_blocks_second_acquire_until_release() {
2561 let (_dir, path) = temp_connection_file_path("start-lock-held");
2562 let lock_path = start_lock_path(&path);
2563 let first = StartLock::acquire(&path).await.unwrap();
2564
2565 let err = match StartLock::acquire(&path).await {
2566 Ok(_) => panic!("second acquire while held must stay busy"),
2567 Err(err) => err,
2568 };
2569 assert!(matches!(
2570 err,
2571 BootstrapError::StartLockBusy {
2572 ref path,
2573 attempts: START_LOCK_RETRIES,
2574 } if path == &lock_path
2575 ));
2576
2577 drop(first);
2578
2579 let second = StartLock::acquire(&path)
2580 .await
2581 .expect("released advisory lock should be reclaimable");
2582 drop(second);
2583 }
2584
2585 #[tokio::test]
2586 async fn bind_conflict_on_fixed_port_fails_loud_without_reselecting() {
2587 let (_dir, path) = temp_connection_file_path("bind-conflict");
2588 let occupied = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
2589 let occupied_port = occupied.local_addr().unwrap().port();
2590
2591 let err = ensure_singleton(&path, occupied_port).await.unwrap_err();
2592 assert!(matches!(
2593 err,
2594 BootstrapError::Bind { ref source, .. } if source.kind() == io::ErrorKind::AddrInUse
2595 ));
2596 assert!(err.to_string().contains("set the port in config"));
2597
2598 drop(occupied);
2599 }
2600
2601 #[tokio::test]
2602 async fn ephemeral_ipv6_collision_still_serves_ipv4() {
2603 let (listeners, endpoints) = bind_loopback_with(0, |port| async move {
2604 let occupied = TcpListener::bind((Ipv6Addr::LOCALHOST, port)).await?;
2605 let result = TcpListener::bind((Ipv6Addr::LOCALHOST, port)).await;
2606 drop(occupied);
2607 result
2608 })
2609 .await
2610 .expect("an incidental IPv6 collision must not prevent an ephemeral daemon from starting");
2611 assert_eq!(endpoints.len(), 1);
2612 assert_eq!(endpoints[0].host, "127.0.0.1");
2613 TcpStream::connect((Ipv4Addr::LOCALHOST, endpoints[0].port))
2614 .await
2615 .unwrap();
2616 drop(listeners);
2617 }
2618
2619 #[tokio::test]
2620 async fn unpublished_boot_holds_singleton_lock_until_publication() {
2621 let dir = ScratchDir::new("unpublished-singleton-lock");
2622 let path = dir.join("connection.json");
2623 let bound = expect_bound(
2624 ensure_singleton_inner(BootstrapConfig::new(&path, 0), false)
2625 .await
2626 .unwrap(),
2627 );
2628 assert!(!path.exists());
2629 let contender = open_owner_only_lock(&start_lock_path(&path)).unwrap();
2630 assert!(
2631 matches!(FileExt::try_lock(&contender), Err(TryLockError::WouldBlock)),
2632 "an unpublished boot must keep its singleton claim"
2633 );
2634 drop(bound);
2635 FileExt::try_lock(&contender).unwrap();
2636 }
2637
2638 #[tokio::test]
2639 async fn start_lock_drop_releases_claim_with_a_shared_file_description() {
2640 let dir = ScratchDir::new("shared-singleton-lock");
2641 let path = dir.join("connection.json");
2642 let bound = expect_bound(
2643 ensure_singleton_inner(BootstrapConfig::new(&path, 0), false)
2644 .await
2645 .unwrap(),
2646 );
2647 let inherited = bound
2650 .publication_lock
2651 .as_ref()
2652 .unwrap()
2653 ._file
2654 .try_clone()
2655 .unwrap();
2656 let contender = open_owner_only_lock(&start_lock_path(&path)).unwrap();
2657 assert!(matches!(
2658 FileExt::try_lock(&contender),
2659 Err(TryLockError::WouldBlock)
2660 ));
2661 drop(bound);
2662 FileExt::try_lock(&contender).expect("dropping bootstrap releases even an inherited lock");
2663 drop(inherited);
2664 }
2665
2666 #[tokio::test]
2667 async fn readiness_probe_requires_an_authenticating_server() {
2668 let dir = ScratchDir::new("unserved-readiness");
2669 let bound = expect_bound(
2670 ensure_singleton_inner(BootstrapConfig::new(dir.join("connection.json"), 0), false)
2671 .await
2672 .unwrap(),
2673 );
2674 assert!(matches!(
2675 verify_serving(&bound.connection_info).await,
2676 Err(BootstrapError::StartupNotServing)
2677 ));
2678 }
2679
2680 #[cfg(unix)]
2681 #[tokio::test]
2682 async fn orphan_sweep_finishes_before_connection_file_publication() {
2683 use crate::live_children::{ExecutableIdentity, LiveChild};
2684 let dir = ScratchDir::new("publish-after-sweep");
2685 let path = dir.join("connection.json");
2686 let record = dir.join("live-children.json");
2687 let ready = dir.join("ready");
2688 let mut child = std::process::Command::new("/bin/sh")
2689 .args([
2690 "-c",
2691 "trap '' TERM; : > \"$0\"; read -r _",
2692 ready.to_str().unwrap(),
2693 ])
2694 .stdin(std::process::Stdio::piped())
2695 .env("XDG_DATA_HOME", dir.path())
2696 .env("XDG_RUNTIME_DIR", dir.path())
2697 .env("XDG_CONFIG_HOME", dir.path())
2698 .spawn()
2699 .unwrap();
2700 timeout(Duration::from_secs(5), async {
2701 while !ready.exists() {
2702 sleep(Duration::from_millis(5)).await;
2703 }
2704 })
2705 .await
2706 .unwrap();
2707 let observed = subc_os::Process::open(child.id())
2708 .unwrap()
2709 .unwrap()
2710 .observe()
2711 .unwrap();
2712 crate::live_children::write_record(
2713 &record,
2714 &[LiveChild {
2715 module_id: "old-sleep".into(),
2716 pid: child.id(),
2717 protocol: subc_control::ModuleProtocol::None,
2718 start_time: Some(observed.start_time),
2719 executable: observed.executable.map(ExecutableIdentity::from),
2720 cgroup_name: None,
2721 }],
2722 )
2723 .unwrap();
2724 let config = BootstrapConfig::new(&path, 0).with_live_children_record(&record);
2725 let daemon = tokio::spawn(run_with_config(config));
2726 timeout(Duration::from_secs(5), async {
2727 while !path.exists() {
2728 sleep(Duration::from_millis(5)).await;
2729 }
2730 })
2731 .await
2732 .unwrap();
2733 assert!(path.exists());
2734 let ended = child.try_wait().unwrap().is_some();
2735 if !ended {
2736 child.kill().unwrap();
2737 }
2738 child.wait().unwrap();
2739 if ended {
2740 assert!(matches!(probe_existing(&path).await.unwrap(), Probe::Live));
2741 }
2742 daemon.abort();
2743 let _ = daemon.await;
2744 assert!(
2745 ended,
2746 "the published daemon must not still owe its orphan sweep"
2747 );
2748 }
2749
2750 #[tokio::test(flavor = "current_thread")]
2757 async fn connection_file_publication_leaves_the_async_runtime_free() {
2758 use std::sync::atomic::{AtomicBool, Ordering};
2759
2760 let (_dir, path) = temp_connection_file_path("publish-off-runtime");
2761 let write_started = Arc::new(AtomicBool::new(false));
2762 let (progress_tx, progress_rx) = std::sync::mpsc::channel::<()>();
2763 let (verdict_tx, verdict_rx) = std::sync::mpsc::channel::<bool>();
2764 let hook_started = Arc::clone(&write_started);
2765 connection_file_write_hook::install(&path, move || {
2766 hook_started.store(true, Ordering::SeqCst);
2767 let progressed = progress_rx.recv_timeout(Duration::from_secs(5)).is_ok();
2768 let _ = verdict_tx.send(progressed);
2769 });
2770 let ticker = tokio::spawn(async move {
2773 loop {
2774 if write_started.load(Ordering::SeqCst) {
2775 let _ = progress_tx.send(());
2776 return;
2777 }
2778 sleep(Duration::from_millis(5)).await;
2779 }
2780 });
2781
2782 let daemon = tokio::spawn(run_with_config(BootstrapConfig::new(&path, 0)));
2783 let published = timeout(Duration::from_secs(15), async {
2784 while !path.exists() && !daemon.is_finished() {
2785 sleep(Duration::from_millis(5)).await;
2786 }
2787 })
2788 .await;
2789 let daemon_exited = daemon.is_finished();
2790 daemon.abort();
2791 let daemon_result = daemon.await;
2792 ticker.abort();
2793
2794 assert!(
2795 published.is_ok() && !daemon_exited,
2796 "the daemon must start and publish its connection file: {daemon_result:?}"
2797 );
2798 match verdict_rx.try_recv() {
2799 Ok(true) => {}
2800 Ok(false) => panic!(
2801 "no other task on the runtime ran while the connection file was being written: the write is blocking the async worker thread"
2802 ),
2803 Err(_) => panic!("startup published the connection file without the hooked write"),
2804 }
2805 }
2806
2807 #[tokio::test]
2810 async fn a_panicking_connection_file_write_fails_startup() {
2811 let (_dir, path) = temp_connection_file_path("publish-panics");
2812 connection_file_write_hook::install(&path, || {
2813 panic!("deliberate panic inside the connection-file write")
2814 });
2815
2816 let error = timeout(
2817 Duration::from_secs(15),
2818 run_with_config(BootstrapConfig::new(&path, 0)),
2819 )
2820 .await
2821 .expect("startup must end once the write task fails")
2822 .expect_err("startup must fail when the connection-file write panics");
2823
2824 assert!(
2825 matches!(&error, BootstrapError::ConnectionFileWrite { path: failed, .. } if failed == &path),
2826 "expected a connection-file write error, got {error:?}"
2827 );
2828 let message = error.to_string();
2829 assert!(message.contains(&path.display().to_string()), "{message}");
2830 assert!(message.contains("panicked"), "{message}");
2831 assert!(!path.exists(), "no connection file may be published");
2832 }
2833
2834 #[cfg(target_os = "macos")]
2835 #[test]
2836 fn nofile_raise_worker() {
2837 let Some(path) = std::env::var_os("SUBC_NOFILE_TEST_FILE") else {
2838 return;
2839 };
2840 let (_, hard) = rlimit::Resource::NOFILE.get().unwrap();
2841 rlimit::Resource::NOFILE.set(256, hard).unwrap();
2842 raise_nofile_limit_with_ceiling(Some(10240));
2843 std::fs::write(path, rlimit::Resource::NOFILE.get().unwrap().0.to_string()).unwrap();
2844 }
2845
2846 #[cfg(target_os = "macos")]
2847 #[test]
2848 fn macos_nofile_raise_clamps_to_kernel_ceiling() {
2849 let dir = ScratchDir::new("nofile-ceiling");
2850 let result = dir.join("soft");
2851 let status = std::process::Command::new(std::env::current_exe().unwrap())
2852 .args(["--exact", "bootstrap::tests::nofile_raise_worker"])
2853 .env("SUBC_NOFILE_TEST_FILE", &result)
2854 .env("XDG_DATA_HOME", dir.path())
2855 .env("XDG_RUNTIME_DIR", dir.path())
2856 .env("XDG_CONFIG_HOME", dir.path())
2857 .status()
2858 .unwrap();
2859 assert!(status.success());
2860 let soft: u64 = std::fs::read_to_string(result).unwrap().parse().unwrap();
2861 assert!(
2862 soft > 256 && soft <= 10240,
2863 "the inherited limit must be raised within the kernel ceiling; got {soft}"
2864 );
2865 }
2866
2867 #[tokio::test]
2868 async fn key_rotation_republishes_new_material_and_old_file_fails_auth() {
2869 let (_dir, path) = temp_connection_file_path("key-rotation");
2870 let first = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2871 let old_info = first.connection_info.clone();
2872 let fixed_port = old_info.endpoints[0].port;
2873 drop(first.listeners);
2874
2875 let second = expect_bound(ensure_singleton(&path, fixed_port).await.unwrap());
2876 let new_info = second.connection_info.clone();
2877 assert_ne!(old_info.key, new_info.key);
2878 assert_ne!(old_info.daemon_id, new_info.daemon_id);
2879 let server = start_server(second);
2880
2881 let mut old_stream = connect_from_info(&old_info).await.unwrap();
2882 let old_auth = authenticate_client(&mut old_stream, &old_info, PROBE_AUTH_DEADLINE).await;
2883 assert!(
2884 old_auth.is_err(),
2885 "old key must not authenticate after restart"
2886 );
2887
2888 let reread = connection_file::read(&path).unwrap();
2889 let mut new_stream = connect_from_info(&reread).await.unwrap();
2890 authenticate_client(&mut new_stream, &reread, PROBE_AUTH_DEADLINE)
2891 .await
2892 .unwrap();
2893
2894 server.abort();
2895 let _ = server.await;
2896 }
2897
2898 #[cfg(unix)]
2899 #[tokio::test]
2900 async fn published_connection_file_permissions_are_owner_only() {
2901 let (_dir, path) = temp_connection_file_path("permissions");
2902 let bound = expect_bound(ensure_singleton(&path, 0).await.unwrap());
2903
2904 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
2905 assert_eq!(mode, 0o600);
2906
2907 drop(bound.listeners);
2908 }
2909}