1use std::{
2 collections::BTreeMap,
3 env,
4 error::Error,
5 ffi::OsString,
6 fmt, fs, io,
7 path::{Path, PathBuf},
8 time::Duration,
9};
10
11pub use crate::activity::ActivityConfig;
12use cortexkit_log::Retention;
13use serde::Deserialize;
14use subc_control::ModuleProtocol;
15use subc_jsonc::jsonc_to_json;
16use subc_protocol::manifest::is_valid_capability_identifier;
17
18use crate::{
19 supervise::{ModuleOverlap, SUBC_SPAWN_ROLE_ENV},
20 HealthAction, HealthConfig, ModuleSpec, RestartPolicy,
21};
22
23const DAEMON_CONFIG_RELATIVE_PATH: &str = "cortexkit/subc.jsonc";
24const SUPPORTED_CONFIG_VERSION: u32 = 1;
25pub(crate) const CK_LOG_ENV: &str = "CK_LOG";
26pub(crate) const CAPTURE_MAX_FILE_MB_ENV: &str = "__SUBC_CAPTURE_LOG_MAX_FILE_MB";
27pub(crate) const CAPTURE_KEEP_ENV: &str = "__SUBC_CAPTURE_LOG_KEEP";
28pub(crate) const CAPTURE_MAX_AGE_DAYS_ENV: &str = "__SUBC_CAPTURE_LOG_MAX_AGE_DAYS";
29pub(crate) const CHILD_LOG_MAX_AGE_DAYS_ENV: &str = "CK_LOG_MAX_AGE_DAYS";
33pub(crate) const CHILD_LOG_ALARM_SEGMENT_MB_ENV: &str = "CK_LOG_ALARM_SEGMENT_MB";
34
35#[derive(Clone, Copy, Debug, Eq, PartialEq)]
49pub enum RestartRequiredSection {
50 Port,
51 Storage,
52 AdmissionFactsCarrierModuleId,
53 AdmissionFactsTargets,
54 ScopeAuthorityOwners,
55 FederatedScopeOwner,
56 PrivilegedOperatorPrompt,
57}
58
59impl RestartRequiredSection {
60 pub const ALL: [Self; 7] = [
61 Self::Port,
62 Self::Storage,
63 Self::AdmissionFactsCarrierModuleId,
64 Self::AdmissionFactsTargets,
65 Self::ScopeAuthorityOwners,
66 Self::FederatedScopeOwner,
67 Self::PrivilegedOperatorPrompt,
68 ];
69
70 pub const fn label(self) -> &'static str {
71 match self {
72 Self::Port => "port",
73 Self::Storage => "storage",
74 Self::AdmissionFactsCarrierModuleId => "admission_facts_carrier_module_id",
75 Self::AdmissionFactsTargets => "admission_facts_targets",
76 Self::ScopeAuthorityOwners => "scope_authority_owners",
77 Self::FederatedScopeOwner => "federated_scope_owner",
78 Self::PrivilegedOperatorPrompt => "privileged_operator_prompt",
79 }
80 }
81}
82
83#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
85#[serde(rename_all = "lowercase")]
86pub enum PrivilegedOperatorPrompt {
87 #[default]
88 Log,
89 Enforce,
90}
91
92pub fn default_scope_authority_owners() -> Vec<String> {
95 vec!["prefrontal-core".to_string()]
96}
97
98pub fn default_federated_scope_owner() -> String {
99 "callosum".to_string()
100}
101
102const ROUTE_BIND_RELAY_ZERO_MESSAGE: &str = "route_bind_relay_timeout_ms must be greater than 0 (a zero budget fails every bind to the module; to make a module unreachable use enabled: false)";
113
114const RESTART_WINDOW_ZERO_MESSAGE: &str = "restart.window_secs must be greater than 0 (a zero window holds no crash, so the budget can never be spent; for effectively unlimited restarts set a deliberately large window_secs, and to stop restarting entirely set restart.max_restarts: 0)";
121
122#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct LoggingConfig {
130 pub level: String,
131 pub tags: BTreeMap<String, String>,
136 pub retention: Retention,
137 pub alarm_segment_mb: u32,
139}
140
141impl LoggingConfig {
142 pub fn filter_spec(&self, module_id: &str) -> String {
151 let mut directives = vec![self.level.clone()];
152 directives.extend(self.tags.iter().map(|(logger, level)| {
153 if logger == module_id || logger.contains('.') {
154 format!("{logger}={level}")
155 } else {
156 format!("{module_id}.{logger}={level}")
157 }
158 }));
159 directives.join(",")
160 }
161
162 pub fn segment_retention(&self) -> cortexkit_log::SegmentRetention {
163 cortexkit_log::SegmentRetention {
164 max_age_days: self.retention.max_age_days,
165 alarm_segment_mb: self.alarm_segment_mb,
166 }
167 }
168}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct DaemonConfig {
172 pub path: PathBuf,
173 pub port: Option<u16>,
174 pub privileged_operator_prompt: PrivilegedOperatorPrompt,
176 pub drain_timeout_ms: Option<u64>,
180 pub route_bind_relay_timeout_ms: Option<u64>,
189 pub modules: Vec<ConfiguredModule>,
190 pub storage: Option<StorageConfig>,
193 pub admission_facts_carrier_module_id: Option<String>,
195 pub admission_facts_targets: Option<Vec<String>>,
197 pub scope_authority_owners: Vec<String>,
203 pub federated_scope_owner: String,
205 pub reserved_capabilities: BTreeMap<String, String>,
209}
210
211#[derive(Debug, Clone, PartialEq, Eq)]
215pub enum StorageConfig {
216 Sqlite { data_home: PathBuf },
218}
219
220impl StorageConfig {
221 pub fn descriptor_for(&self, module_id: &str) -> serde_json::Value {
247 match self {
248 StorageConfig::Sqlite { data_home } => {
257 let data_home = data_home.to_string_lossy();
258 let path = format!(
259 "{}/cortexkit/{module_id}/store.db",
260 data_home.trim_end_matches('/')
261 );
262 serde_json::json!({
263 "module_id": module_id,
264 "storage_namespace": "default",
265 "isolation": { "kind": "module" },
266 "backend": { "backend": "sqlite", "path": path },
267 })
268 }
269 }
270 }
271}
272
273#[derive(Debug, Clone, PartialEq, Eq)]
274pub struct ConfiguredModule {
275 pub module_id: String,
276 pub program: PathBuf,
277 pub args: Vec<String>,
278 pub env: Vec<(String, String)>,
279 pub log: Option<LoggingConfig>,
283 pub enabled: bool,
284 pub reserved: bool,
290 pub reserved_prefixes: Vec<String>,
294 pub protocol: ModuleProtocol,
297 pub overlap: ModuleOverlap,
300 pub carry_containment: bool,
303 pub health: HealthConfig,
304 pub drain_timeout_ms: Option<u64>,
307 pub register_timeout: Duration,
310 pub route_bind_relay_timeout_ms: Option<u64>,
315 pub restart: RestartPolicy,
326}
327
328impl ConfiguredModule {
329 pub fn module_spec(&self) -> ModuleSpec {
330 let mut env = self.env.clone();
331 if let Some(log) = &self.log {
332 env.retain(|(key, _)| {
333 key != CK_LOG_ENV
334 && key != CAPTURE_MAX_FILE_MB_ENV
335 && key != CAPTURE_KEEP_ENV
336 && key != CAPTURE_MAX_AGE_DAYS_ENV
337 });
338 env.retain(|(key, _)| {
339 key != CHILD_LOG_MAX_AGE_DAYS_ENV && key != CHILD_LOG_ALARM_SEGMENT_MB_ENV
340 });
341 env.push((CK_LOG_ENV.to_string(), log.filter_spec(&self.module_id)));
342 env.push((
343 CHILD_LOG_MAX_AGE_DAYS_ENV.to_string(),
344 log.retention.max_age_days.to_string(),
345 ));
346 env.push((
347 CHILD_LOG_ALARM_SEGMENT_MB_ENV.to_string(),
348 log.alarm_segment_mb.to_string(),
349 ));
350 env.push((
354 CAPTURE_MAX_FILE_MB_ENV.to_string(),
355 log.retention.max_file_mb.to_string(),
356 ));
357 env.push((CAPTURE_KEEP_ENV.to_string(), log.retention.keep.to_string()));
358 env.push((
359 CAPTURE_MAX_AGE_DAYS_ENV.to_string(),
360 log.retention.max_age_days.to_string(),
361 ));
362 }
363 ModuleSpec {
364 module_id: self.module_id.clone(),
365 program: self.program.clone(),
366 args: self.args.clone(),
367 env,
368 reserved: self.reserved,
369 reserved_prefixes: self.reserved_prefixes.clone(),
370 protocol: self.protocol,
371 overlap: self.overlap,
372 carry_containment: self.carry_containment,
373 }
374 }
375}
376
377#[derive(Debug)]
378pub enum DaemonConfigError {
379 Read {
380 path: PathBuf,
381 source: io::Error,
382 },
383 InvalidJsonc {
384 path: PathBuf,
385 message: String,
386 },
387 InvalidJson {
388 path: PathBuf,
389 source: serde_json::Error,
390 },
391 UnsupportedVersion {
392 path: PathBuf,
393 version: u32,
394 },
395 InvalidValue {
396 path: PathBuf,
397 message: String,
398 },
399}
400
401#[derive(Debug, Deserialize)]
402struct RawDaemonConfig {
403 version: u32,
404 #[serde(default)]
405 activity: ActivityConfig,
406 #[serde(default)]
407 port: Option<u16>,
408 #[serde(default)]
409 privileged_operator_prompt: PrivilegedOperatorPrompt,
410 #[serde(default)]
411 drain_timeout_ms: Option<u64>,
412 #[serde(default)]
413 route_bind_relay_timeout_ms: Option<u64>,
414 #[serde(default)]
415 log: Option<RawLoggingConfig>,
416 #[serde(default)]
417 modules: BTreeMap<String, RawModuleConfig>,
418 #[serde(default)]
419 storage: Option<RawStorageConfig>,
420 #[serde(default)]
421 admission_facts_carrier_module_id: Option<String>,
422 #[serde(default)]
423 admission_facts_targets: Option<Vec<String>>,
424 #[serde(default)]
425 scope_authority_owners: Option<Vec<String>>,
426 #[serde(default = "default_federated_scope_owner")]
427 federated_scope_owner: String,
428 #[serde(default)]
429 reserved_capabilities: BTreeMap<String, String>,
430}
431
432#[derive(Debug, Deserialize)]
433#[serde(tag = "backend", rename_all = "snake_case")]
434enum RawStorageConfig {
435 Sqlite {
436 #[serde(default)]
439 data_home: Option<PathBuf>,
440 },
441}
442
443#[derive(Debug, Deserialize)]
444struct RawModuleConfig {
445 program: PathBuf,
446 #[serde(default)]
447 args: Vec<String>,
448 #[serde(default)]
449 env: BTreeMap<String, String>,
450 #[serde(default)]
451 log: Option<RawLoggingConfig>,
452 #[serde(default = "default_enabled")]
453 enabled: bool,
454 #[serde(default)]
455 reserved: bool,
456 #[serde(flatten)]
459 ignored: BTreeMap<String, serde_json::Value>,
460 #[serde(default)]
461 reserved_prefixes: Vec<String>,
462 #[serde(default)]
466 protocol: Option<String>,
467 #[serde(default)]
469 overlap: Option<String>,
470 #[serde(default)]
471 carry_containment: bool,
472 #[serde(default)]
473 health: Option<RawHealthConfig>,
474 #[serde(default)]
475 drain_timeout_ms: Option<u64>,
476 #[serde(default)]
477 register_timeout_s: Option<u64>,
478 #[serde(default)]
479 route_bind_relay_timeout_ms: Option<u64>,
480 #[serde(default)]
481 restart: Option<RawRestartConfig>,
482}
483
484#[derive(Debug, Clone, Deserialize)]
485struct RawLoggingConfig {
486 #[serde(default)]
487 level: Option<String>,
488 #[serde(default)]
489 tags: BTreeMap<String, String>,
490 #[serde(default)]
491 alarm_segment_mb: Option<u32>,
492 #[serde(default)]
493 max_file_mb: Option<u32>,
494 #[serde(default)]
495 keep: Option<u8>,
496 #[serde(default)]
497 max_age_days: Option<u32>,
498}
499
500#[derive(Debug, Deserialize)]
501struct RawRestartConfig {
502 #[serde(default)]
503 max_restarts: Option<u32>,
504 #[serde(default)]
505 window_secs: Option<u64>,
506 #[serde(default)]
507 backoff_ms: Option<u64>,
508 #[serde(default)]
509 max_backoff_ms: Option<u64>,
510}
511
512#[derive(Debug, Deserialize)]
513struct RawHealthConfig {
514 #[serde(default)]
515 http: Option<String>,
516 #[serde(default)]
517 cadence_ms: Option<u64>,
518 #[serde(default)]
519 deadline_ms: Option<u64>,
520 #[serde(default)]
521 failure_threshold: Option<u32>,
522 #[serde(default)]
523 on_degraded: Option<RawHealthAction>,
524 #[serde(default)]
525 on_failing: Option<RawHealthAction>,
526 #[serde(default)]
527 critical: bool,
528}
529
530#[derive(Debug, Deserialize)]
531#[serde(rename_all = "snake_case")]
532enum RawHealthAction {
533 Report,
534 Restart,
535 Alert,
536}
537
538pub fn default_config_path() -> PathBuf {
539 default_config_home().join(DAEMON_CONFIG_RELATIVE_PATH)
540}
541
542pub fn default_config_home() -> PathBuf {
564 if let Some(config_home) = non_empty_os_var("XDG_CONFIG_HOME") {
565 return PathBuf::from(config_home);
566 }
567
568 #[cfg(windows)]
569 {
570 if let Some(app_data) = non_empty_os_var("APPDATA") {
571 return PathBuf::from(app_data);
572 }
573 if let Some(user_profile) = non_empty_os_var("USERPROFILE") {
574 return PathBuf::from(user_profile).join("AppData").join("Roaming");
575 }
576 }
577
578 if let Some(home) = non_empty_os_var("HOME") {
579 return PathBuf::from(home).join(".config");
580 }
581
582 PathBuf::from(".config")
583}
584
585pub fn load(path: impl AsRef<Path>) -> Result<Option<DaemonConfig>, DaemonConfigError> {
586 let path = path.as_ref();
587 let Some(doc) = read_config_doc(path)? else {
588 return Ok(None);
589 };
590 parse_doc(&doc, path).map(Some)
591}
592
593pub fn load_with_activity(
597 path: impl AsRef<Path>,
598) -> Result<Option<(DaemonConfig, ActivityConfig)>, DaemonConfigError> {
599 let path = path.as_ref();
600 let Some(doc) = read_config_doc(path)? else {
601 return Ok(None);
602 };
603 parse_doc_with_activity(&doc, path).map(Some)
604}
605
606pub fn parse_with_activity(
611 doc: &str,
612 path: impl AsRef<Path>,
613) -> Result<(DaemonConfig, ActivityConfig), DaemonConfigError> {
614 parse_doc_with_activity(doc, path.as_ref())
615}
616
617pub fn load_logging(path: impl AsRef<Path>) -> Result<Option<LoggingConfig>, DaemonConfigError> {
623 let path = path.as_ref();
624 let Some(doc) = read_config_doc(path)? else {
625 return Ok(None);
626 };
627 let json = jsonc_to_json(&doc).map_err(|message| DaemonConfigError::InvalidJsonc {
628 path: path.to_path_buf(),
629 message,
630 })?;
631 let raw: RawDaemonConfig =
632 serde_json::from_str(&json).map_err(|source| DaemonConfigError::InvalidJson {
633 path: path.to_path_buf(),
634 source,
635 })?;
636 if raw.version != SUPPORTED_CONFIG_VERSION {
637 return Err(DaemonConfigError::UnsupportedVersion {
638 path: path.to_path_buf(),
639 version: raw.version,
640 });
641 }
642 raw.log
643 .map(|log| parse_logging_config(log, path, "daemon log"))
644 .transpose()
645}
646
647pub fn ensure_daemon_run_dir_private() -> Result<PathBuf, io::Error> {
673 let path = daemon_run_dir()
674 .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error.to_string()))?;
675 ensure_directory_private(&path)?;
676 Ok(path)
677}
678
679#[cfg(unix)]
684fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
685 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
686
687 if !path.exists() {
688 fs::DirBuilder::new()
689 .recursive(true)
690 .mode(0o700)
691 .create(path)?;
692 return Ok(());
693 }
694 let mode = fs::metadata(path)?.permissions().mode() & 0o777;
695 if mode & 0o077 != 0 {
696 fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
697 }
698 Ok(())
699}
700
701#[cfg(windows)]
704fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
705 subc_os::windows_acl::create_private_dir(path)
706}
707
708#[cfg(not(any(unix, windows)))]
709fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
710 if !path.exists() {
711 fs::create_dir_all(path)?;
712 }
713 Ok(())
714}
715
716pub fn daemon_run_dir() -> Result<PathBuf, DaemonRunDirError> {
726 daemon_run_dir_from(default_data_home())
727}
728
729fn daemon_run_dir_from(data_home: PathBuf) -> Result<PathBuf, DaemonRunDirError> {
732 if !data_home.is_absolute() {
733 return Err(DaemonRunDirError::RelativeDataHome { data_home });
734 }
735 Ok(data_home.join("cortexkit").join("run"))
736}
737
738#[derive(Debug, Clone, PartialEq, Eq)]
740pub enum DaemonRunDirError {
741 RelativeDataHome { data_home: PathBuf },
744}
745
746impl fmt::Display for DaemonRunDirError {
747 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
748 match self {
749 Self::RelativeDataHome { data_home } => write!(
750 f,
751 "cannot resolve the daemon run directory: the data home `{}` is relative, \
752 so it would land under the current working directory; {}",
753 data_home.display(),
754 DATA_HOME_REMEDY
755 ),
756 }
757 }
758}
759
760impl std::error::Error for DaemonRunDirError {}
761
762#[cfg(windows)]
764const DATA_HOME_REMEDY: &str =
765 "set XDG_DATA_HOME to an absolute path, or set APPDATA, USERPROFILE or HOME";
766#[cfg(not(windows))]
767const DATA_HOME_REMEDY: &str = "set XDG_DATA_HOME to an absolute path, or set HOME";
768
769fn read_config_doc(path: &Path) -> Result<Option<String>, DaemonConfigError> {
770 match fs::read_to_string(path) {
771 Ok(doc) => Ok(Some(doc)),
772 Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None),
773 Err(source) => Err(DaemonConfigError::Read {
774 path: path.to_path_buf(),
775 source,
776 }),
777 }
778}
779
780fn parse_doc(doc: &str, path: &Path) -> Result<DaemonConfig, DaemonConfigError> {
781 parse_doc_with_activity(doc, path).map(|(config, _)| config)
782}
783
784fn parse_doc_with_activity(
785 doc: &str,
786 path: &Path,
787) -> Result<(DaemonConfig, ActivityConfig), DaemonConfigError> {
788 let json = jsonc_to_json(doc).map_err(|message| DaemonConfigError::InvalidJsonc {
789 path: path.to_path_buf(),
790 message,
791 })?;
792 let raw: RawDaemonConfig =
793 serde_json::from_str(&json).map_err(|source| DaemonConfigError::InvalidJson {
794 path: path.to_path_buf(),
795 source,
796 })?;
797
798 if raw.version != SUPPORTED_CONFIG_VERSION {
799 return Err(DaemonConfigError::UnsupportedVersion {
800 path: path.to_path_buf(),
801 version: raw.version,
802 });
803 }
804
805 let daemon_logging = raw
806 .log
807 .map(|log| parse_logging_config(log, path, "daemon log"))
808 .transpose()?;
809 let default_drain_timeout_ms = raw.drain_timeout_ms;
810 let default_route_bind_relay_timeout_ms = match raw.route_bind_relay_timeout_ms {
816 Some(0) => {
817 return Err(DaemonConfigError::InvalidValue {
818 path: path.to_path_buf(),
819 message: ROUTE_BIND_RELAY_ZERO_MESSAGE.to_string(),
820 });
821 }
822 Some(value) => Some(value),
823 None => None,
824 };
825 let modules = raw
826 .modules
827 .into_iter()
828 .map(|(module_id, module)| {
829 let protocol = parse_module_protocol(module.protocol.as_deref(), path, &module_id)?;
830 let health = module
831 .health
832 .map(|health| parse_health_config(health, path, &module_id, protocol))
833 .transpose()?
834 .unwrap_or_default();
835 if let Err(reason) = crate::registry::module_id_path_hazard(&module_id) {
836 return Err(DaemonConfigError::InvalidValue {
837 path: path.to_path_buf(),
838 message: format!(
839 "module id '{}' is not usable as a path component ({reason}): \
840 the daemon derives each module's store path from its id",
841 module_id.escape_debug()
842 ),
843 });
844 }
845 let per_module_route_bind_relay_timeout_ms = match module.route_bind_relay_timeout_ms {
850 Some(0) => {
851 return Err(DaemonConfigError::InvalidValue {
852 path: path.to_path_buf(),
853 message: format!(
854 "module '{module_id}' {ROUTE_BIND_RELAY_ZERO_MESSAGE}",
855 module_id = module_id.escape_debug()
856 ),
857 });
858 }
859 Some(value) => Some(value),
860 None => default_route_bind_relay_timeout_ms,
861 };
862 if module.ignored.contains_key("launch_nonce_env") {
867 tracing::warn!(
868 module_id = %module_id.escape_debug(),
869 "launch_nonce_env is deprecated and ignored; nonce delivery is determined by the platform"
870 );
871 }
872 let overlap = parse_module_overlap(module.overlap.as_deref(), path, &module_id)?;
873 if module.carry_containment && overlap == ModuleOverlap::Safe {
874 return Err(DaemonConfigError::InvalidValue {
875 path: path.to_path_buf(),
876 message: format!(
877 "module '{}' sets carry_containment: true with overlap: \"safe\"; carried containment does not support overlapping instances",
878 module_id.escape_debug()
879 ),
880 });
881 }
882 if module.env.contains_key(SUBC_SPAWN_ROLE_ENV) {
886 return Err(DaemonConfigError::InvalidValue {
887 path: path.to_path_buf(),
888 message: format!(
889 "module '{module_id}' sets {SUBC_SPAWN_ROLE_ENV} in env; that variable is set by the supervisor on a swap candidate only and cannot be configured",
890 module_id = module_id.escape_debug()
891 ),
892 });
893 }
894 if protocol == ModuleProtocol::None && module.reserved {
901 return Err(DaemonConfigError::InvalidValue {
902 path: path.to_path_buf(),
903 message: format!(
904 "module '{module_id}' sets reserved: true with protocol: \"none\"; \
905 reserved is enforced on the module's HELLO and a protocol: \"none\" \
906 module never registers, so the reservation could never be checked",
907 module_id = module_id.escape_debug()
908 ),
909 });
910 }
911 let restart = parse_restart_config(module.restart, path, &module_id)?;
912 let register_timeout_s = module
913 .register_timeout_s
914 .unwrap_or(crate::supervise::DEFAULT_REGISTER_TIMEOUT.as_secs());
915 if !(10..=3600).contains(®ister_timeout_s) {
916 return Err(DaemonConfigError::InvalidValue {
917 path: path.to_path_buf(),
918 message: format!(
919 "module '{module_id}' register_timeout_s must be an integer from 10 to 3600"
920 ),
921 });
922 }
923 let log = module
924 .log
925 .map(|log| parse_logging_config(log, path, &format!("module '{module_id}' log")))
926 .transpose()?
927 .or_else(|| daemon_logging.clone());
928 Ok(ConfiguredModule {
929 module_id,
930 program: module.program,
931 args: module.args,
932 env: module.env.into_iter().collect(),
933 log,
934 enabled: module.enabled,
935 reserved: module.reserved,
936 reserved_prefixes: module.reserved_prefixes,
937 protocol,
938 overlap,
939 carry_containment: module.carry_containment,
940 health,
941 drain_timeout_ms: module.drain_timeout_ms.or(default_drain_timeout_ms),
944 register_timeout: Duration::from_secs(register_timeout_s),
945 route_bind_relay_timeout_ms: per_module_route_bind_relay_timeout_ms,
950 restart,
951 })
952 })
953 .collect::<Result<Vec<_>, DaemonConfigError>>()?;
954
955 validate_reserved_prefixes(&modules, path)?;
956 validate_reserved_capabilities(&raw.reserved_capabilities, path)?;
957 validate_admission_facts_config(
958 &modules,
959 raw.admission_facts_carrier_module_id.as_deref(),
960 raw.admission_facts_targets.as_deref(),
961 path,
962 )?;
963 let scope_authority_owners = raw
964 .scope_authority_owners
965 .unwrap_or_else(default_scope_authority_owners);
966 subc_protocol::manifest::validate_module_id(&raw.federated_scope_owner).map_err(|error| {
967 DaemonConfigError::InvalidValue {
968 path: path.to_path_buf(),
969 message: format!("federated_scope_owner: {error}"),
970 }
971 })?;
972 if scope_authority_owners.iter().any(|owner| owner.is_empty()) {
973 return Err(DaemonConfigError::InvalidValue {
974 path: path.to_path_buf(),
975 message: "scope_authority_owners must not contain empty module ids".to_string(),
976 });
977 }
978
979 let storage = raw
980 .storage
981 .map(|s| match s {
982 RawStorageConfig::Sqlite { data_home } => {
983 let data_home = data_home.unwrap_or_else(default_data_home);
984 if !data_home.is_absolute() {
993 return Err(DaemonConfigError::InvalidValue {
994 path: path.to_path_buf(),
995 message: format!(
996 "storage data home resolved to the relative path {} \
997 (no absolute XDG_DATA_HOME, APPDATA, USERPROFILE, or HOME \
998 in the daemon's environment); refusing to serve a \
999 cwd-relative storage descriptor to modules. Set \
1000 XDG_DATA_HOME or HOME to an absolute path, or set \
1001 storage.data_home in this file.",
1002 data_home.display()
1003 ),
1004 });
1005 }
1006 Ok(StorageConfig::Sqlite { data_home })
1007 }
1008 })
1009 .transpose()?;
1010
1011 if raw.activity.max_age_days == 0 || raw.activity.max_total_mb == 0 {
1012 return Err(DaemonConfigError::InvalidValue {
1013 path: path.to_path_buf(),
1014 message: "activity.max_age_days and activity.max_total_mb must be positive".into(),
1015 });
1016 }
1017 Ok((
1018 DaemonConfig {
1019 path: path.to_path_buf(),
1020 port: raw.port,
1021 privileged_operator_prompt: raw.privileged_operator_prompt,
1022 drain_timeout_ms: default_drain_timeout_ms,
1023 route_bind_relay_timeout_ms: default_route_bind_relay_timeout_ms,
1024 modules,
1025 storage,
1026 admission_facts_carrier_module_id: raw.admission_facts_carrier_module_id,
1027 admission_facts_targets: raw.admission_facts_targets,
1028 scope_authority_owners,
1029 federated_scope_owner: raw.federated_scope_owner,
1030 reserved_capabilities: raw.reserved_capabilities,
1031 },
1032 raw.activity,
1033 ))
1034}
1035
1036fn parse_logging_config(
1037 raw: RawLoggingConfig,
1038 path: &Path,
1039 owner: &str,
1040) -> Result<LoggingConfig, DaemonConfigError> {
1041 fn valid_level(level: &str) -> bool {
1042 matches!(level, "off" | "error" | "warn" | "info" | "debug" | "trace")
1043 }
1044
1045 let level = raw.level.unwrap_or_else(|| "info".to_string());
1046 if !valid_level(&level) {
1047 return Err(DaemonConfigError::InvalidValue {
1048 path: path.to_path_buf(),
1049 message: format!(
1050 "{owner}.level must be one of off, error, warn, info, debug, trace; got {level:?}"
1051 ),
1052 });
1053 }
1054 for (tag, tag_level) in &raw.tags {
1055 let well_formed = !tag.is_empty()
1060 && tag.split('.').all(|segment| {
1061 let mut chars = segment.chars();
1062 matches!(chars.next(), Some('a'..='z'))
1063 && chars.all(|c| matches!(c, 'a'..='z' | '0'..='9' | '-'))
1064 });
1065 if !well_formed {
1066 return Err(DaemonConfigError::InvalidValue {
1067 path: path.to_path_buf(),
1068 message: format!(
1069 "{owner}.tags key {tag:?} is not a logger name (dotted segments of [a-z][a-z0-9-]*)"
1070 ),
1071 });
1072 }
1073 if !valid_level(tag_level) {
1074 return Err(DaemonConfigError::InvalidValue {
1075 path: path.to_path_buf(),
1076 message: format!(
1077 "{owner}.tags.{tag} must be one of off, error, warn, info, debug, trace; got {tag_level:?}"
1078 ),
1079 });
1080 }
1081 }
1082
1083 let defaults = Retention::default();
1084 let retention = Retention {
1085 max_file_mb: raw.max_file_mb.unwrap_or(defaults.max_file_mb),
1086 keep: raw.keep.unwrap_or(defaults.keep),
1087 max_age_days: raw.max_age_days.unwrap_or(defaults.max_age_days),
1088 };
1089 if retention.max_file_mb == 0 {
1090 return Err(DaemonConfigError::InvalidValue {
1091 path: path.to_path_buf(),
1092 message: format!("{owner}.max_file_mb must be greater than 0"),
1093 });
1094 }
1095
1096 let alarm_segment_mb = raw
1097 .alarm_segment_mb
1098 .unwrap_or(cortexkit_log::SegmentRetention::default().alarm_segment_mb);
1099 if alarm_segment_mb == 0 {
1100 return Err(DaemonConfigError::InvalidValue {
1101 path: path.to_path_buf(),
1102 message: format!("{owner}.alarm_segment_mb must be greater than 0"),
1103 });
1104 }
1105
1106 Ok(LoggingConfig {
1107 level,
1108 tags: raw.tags,
1109 retention,
1110 alarm_segment_mb,
1111 })
1112}
1113
1114fn parse_module_protocol(
1123 raw: Option<&str>,
1124 path: &Path,
1125 module_id: &str,
1126) -> Result<ModuleProtocol, DaemonConfigError> {
1127 match raw {
1128 None | Some("subc") => Ok(ModuleProtocol::Subc),
1129 Some("none") => Ok(ModuleProtocol::None),
1130 Some(other) => Err(DaemonConfigError::InvalidValue {
1134 path: path.to_path_buf(),
1135 message: format!(
1136 "module '{module_id}' declares protocol {other:?}; supported values are \
1137 \"subc\" (the default when the key is absent) and \"none\"",
1138 module_id = module_id.escape_debug(),
1139 ),
1140 }),
1141 }
1142}
1143
1144fn parse_module_overlap(
1148 raw: Option<&str>,
1149 path: &Path,
1150 module_id: &str,
1151) -> Result<ModuleOverlap, DaemonConfigError> {
1152 match raw {
1153 None | Some("exclusive") => Ok(ModuleOverlap::Exclusive),
1154 Some("safe") => Ok(ModuleOverlap::Safe),
1155 Some(other) => Err(DaemonConfigError::InvalidValue {
1156 path: path.to_path_buf(),
1157 message: format!(
1158 "module '{module_id}' declares overlap {other:?}; supported values are \
1159 \"exclusive\" (the default when the key is absent) and \"safe\"",
1160 module_id = module_id.escape_debug(),
1161 ),
1162 }),
1163 }
1164}
1165
1166fn validate_reserved_capabilities(
1167 bindings: &BTreeMap<String, String>,
1168 path: &Path,
1169) -> Result<(), DaemonConfigError> {
1170 for (capability, module_id) in bindings {
1171 if !is_valid_capability_identifier(capability) {
1172 return Err(DaemonConfigError::InvalidValue {
1173 path: path.to_path_buf(),
1174 message: format!(
1175 "reserved_capabilities key {:?} is not a valid capability identifier",
1176 capability
1177 ),
1178 });
1179 }
1180 if module_id.trim().is_empty() {
1181 return Err(DaemonConfigError::InvalidValue {
1182 path: path.to_path_buf(),
1183 message: format!(
1184 "reserved_capabilities binding for {:?} has an empty module id",
1185 capability
1186 ),
1187 });
1188 }
1189 if let Err(reason) = crate::registry::module_id_path_hazard(module_id) {
1190 return Err(DaemonConfigError::InvalidValue {
1191 path: path.to_path_buf(),
1192 message: format!(
1193 "reserved_capabilities binding for {:?} has an unusable module id {:?}: {reason}",
1194 capability, module_id
1195 ),
1196 });
1197 }
1198 }
1199 Ok(())
1200}
1201
1202fn validate_admission_facts_config(
1203 modules: &[ConfiguredModule],
1204 carrier_module_id: Option<&str>,
1205 targets: Option<&[String]>,
1206 path: &Path,
1207) -> Result<(), DaemonConfigError> {
1208 let Some(carrier_module_id) = carrier_module_id else {
1209 return Ok(());
1210 };
1211
1212 let Some(carrier) = modules
1213 .iter()
1214 .find(|module| module.module_id == carrier_module_id)
1215 else {
1216 return Err(DaemonConfigError::InvalidValue {
1217 path: path.to_path_buf(),
1218 message: format!(
1219 "admission_facts_carrier_module_id '{carrier_module_id}' must name a configured module"
1220 ),
1221 });
1222 };
1223 if !carrier.enabled || !carrier.reserved {
1224 return Err(DaemonConfigError::InvalidValue {
1225 path: path.to_path_buf(),
1226 message: format!(
1227 "admission_facts_carrier_module_id '{carrier_module_id}' must name an enabled reserved module"
1228 ),
1229 });
1230 }
1231
1232 let Some(targets) = targets else {
1233 return Err(DaemonConfigError::InvalidValue {
1234 path: path.to_path_buf(),
1235 message: "admission_facts_targets must be present when an admission facts carrier is configured".to_string(),
1236 });
1237 };
1238 if targets.is_empty() || targets.iter().any(String::is_empty) {
1239 return Err(DaemonConfigError::InvalidValue {
1240 path: path.to_path_buf(),
1241 message:
1242 "admission_facts_targets must be non-empty and must not contain empty module ids"
1243 .to_string(),
1244 });
1245 }
1246
1247 Ok(())
1248}
1249
1250fn default_enabled() -> bool {
1251 true
1252}
1253
1254fn validate_reserved_prefixes(
1255 modules: &[ConfiguredModule],
1256 path: &Path,
1257) -> Result<(), DaemonConfigError> {
1258 for module in modules {
1259 if module.reserved_prefixes.is_empty() {
1260 continue;
1261 }
1262 if !module.reserved {
1263 return Err(DaemonConfigError::InvalidValue {
1264 path: path.to_path_buf(),
1265 message: format!(
1266 "module '{}' reserved_prefixes require reserved=true so the owner is spawn-nonce protected",
1267 module.module_id
1268 ),
1269 });
1270 }
1271 for prefix in &module.reserved_prefixes {
1272 if !prefix.ends_with(':') {
1273 return Err(DaemonConfigError::InvalidValue {
1274 path: path.to_path_buf(),
1275 message: format!(
1276 "module '{}' reserved prefix '{}' must end with ':'",
1277 module.module_id, prefix
1278 ),
1279 });
1280 }
1281 }
1282 }
1283
1284 for module in modules {
1285 for prefix in &module.reserved_prefixes {
1286 if let Some(colliding) = modules
1287 .iter()
1288 .find(|candidate| candidate.module_id.starts_with(prefix))
1289 {
1290 return Err(DaemonConfigError::InvalidValue {
1291 path: path.to_path_buf(),
1292 message: format!(
1293 "reserved prefix '{}' owned by '{}' collides with configured module id '{}'",
1294 prefix, module.module_id, colliding.module_id
1295 ),
1296 });
1297 }
1298 }
1299 }
1300
1301 for (left_index, left) in modules.iter().enumerate() {
1302 for right in modules.iter().skip(left_index + 1) {
1303 if left.module_id == right.module_id {
1304 continue;
1305 }
1306 for left_prefix in &left.reserved_prefixes {
1307 for right_prefix in &right.reserved_prefixes {
1308 if left_prefix.starts_with(right_prefix)
1309 || right_prefix.starts_with(left_prefix)
1310 {
1311 return Err(DaemonConfigError::InvalidValue {
1312 path: path.to_path_buf(),
1313 message: format!(
1314 "reserved prefixes '{}' owned by '{}' and '{}' owned by '{}' overlap",
1315 left_prefix, left.module_id, right_prefix, right.module_id
1316 ),
1317 });
1318 }
1319 }
1320 }
1321 }
1322 }
1323
1324 Ok(())
1325}
1326
1327fn parse_health_config(
1328 raw: RawHealthConfig,
1329 path: &Path,
1330 module_id: &str,
1331 protocol: ModuleProtocol,
1332) -> Result<HealthConfig, DaemonConfigError> {
1333 if let Some(url) = raw.http.as_deref() {
1334 let reason = if protocol != ModuleProtocol::None {
1335 Some("is valid only for protocol: \"none\" modules".to_string())
1336 } else {
1337 crate::supervise::parse_http_probe_url(url).err()
1338 };
1339 if let Some(reason) = reason {
1340 return Err(DaemonConfigError::InvalidValue {
1341 path: path.to_path_buf(),
1342 message: format!("module '{module_id}' health.http {reason}"),
1343 });
1344 }
1345 }
1346 let defaults = HealthConfig::default();
1347 let cadence = positive_millis(
1348 raw.cadence_ms,
1349 defaults.cadence,
1350 path,
1351 module_id,
1352 "cadence_ms",
1353 )?;
1354 let deadline = positive_millis(
1355 raw.deadline_ms,
1356 defaults.deadline,
1357 path,
1358 module_id,
1359 "deadline_ms",
1360 )?;
1361 let failure_threshold = match raw.failure_threshold {
1362 Some(0) => {
1363 return Err(DaemonConfigError::InvalidValue {
1364 path: path.to_path_buf(),
1365 message: format!("module '{module_id}' health.failure_threshold must be positive"),
1366 })
1367 }
1368 Some(value) => value,
1369 None => defaults.failure_threshold,
1370 };
1371
1372 Ok(HealthConfig {
1373 http: raw.http,
1374 cadence,
1375 deadline,
1376 failure_threshold,
1377 on_degraded: match raw.on_degraded {
1378 Some(RawHealthAction::Restart) => {
1379 return Err(DaemonConfigError::InvalidValue {
1380 path: path.to_path_buf(),
1381 message: format!(
1382 "module '{module_id}' health.on_degraded may not be 'restart': a degraded module is slow-but-moving, so restarting it converts transient load into an outage. Use 'report' or 'alert' (Health-Path v2: only total wreckage or reported-unresponsiveness restarts)."
1383 ),
1384 });
1385 }
1386 Some(action) => health_action(action),
1387 None => defaults.on_degraded,
1388 },
1389 on_failing: raw
1390 .on_failing
1391 .map(health_action)
1392 .unwrap_or(defaults.on_failing),
1393 critical: raw.critical,
1394 })
1395}
1396
1397fn parse_restart_config(
1404 raw: Option<RawRestartConfig>,
1405 path: &Path,
1406 module_id: &str,
1407) -> Result<RestartPolicy, DaemonConfigError> {
1408 let defaults = RestartPolicy::default();
1409 let Some(raw) = raw else {
1410 return Ok(defaults);
1411 };
1412
1413 let window = match raw.window_secs {
1414 Some(0) => {
1415 return Err(DaemonConfigError::InvalidValue {
1416 path: path.to_path_buf(),
1417 message: format!(
1418 "module '{module_id}' {RESTART_WINDOW_ZERO_MESSAGE}",
1419 module_id = module_id.escape_debug()
1420 ),
1421 });
1422 }
1423 Some(secs) => Duration::from_secs(secs),
1424 None => defaults.window,
1425 };
1426 let backoff = raw
1427 .backoff_ms
1428 .map(Duration::from_millis)
1429 .unwrap_or(defaults.backoff);
1430 let max_backoff = raw
1431 .max_backoff_ms
1432 .map(Duration::from_millis)
1433 .unwrap_or(defaults.max_backoff);
1434 if max_backoff < backoff {
1435 return Err(DaemonConfigError::InvalidValue {
1436 path: path.to_path_buf(),
1437 message: format!(
1438 "module '{}' restart.max_backoff_ms must be greater than or equal to restart.backoff_ms (max_backoff_ms={max_backoff:?}, backoff_ms={backoff:?})",
1439 module_id.escape_debug()
1440 ),
1441 });
1442 }
1443
1444 Ok(RestartPolicy {
1445 max_restarts: raw.max_restarts.unwrap_or(defaults.max_restarts),
1448 backoff,
1449 max_backoff,
1450 window,
1451 })
1452}
1453
1454fn positive_millis(
1455 value: Option<u64>,
1456 default: std::time::Duration,
1457 path: &Path,
1458 module_id: &str,
1459 field: &str,
1460) -> Result<std::time::Duration, DaemonConfigError> {
1461 match value {
1462 Some(0) => Err(DaemonConfigError::InvalidValue {
1463 path: path.to_path_buf(),
1464 message: format!("module '{module_id}' health.{field} must be positive"),
1465 }),
1466 Some(value) => Ok(std::time::Duration::from_millis(value)),
1467 None => Ok(default),
1468 }
1469}
1470
1471fn health_action(action: RawHealthAction) -> HealthAction {
1472 match action {
1473 RawHealthAction::Report => HealthAction::Report,
1474 RawHealthAction::Restart => HealthAction::Restart,
1475 RawHealthAction::Alert => HealthAction::Alert,
1476 }
1477}
1478
1479pub(crate) fn default_data_home() -> PathBuf {
1482 if let Some(data_home) = non_empty_os_var("XDG_DATA_HOME") {
1483 return PathBuf::from(data_home);
1484 }
1485
1486 #[cfg(windows)]
1487 {
1488 if let Some(app_data) = non_empty_os_var("APPDATA") {
1489 return PathBuf::from(app_data);
1490 }
1491 if let Some(user_profile) = non_empty_os_var("USERPROFILE") {
1492 return PathBuf::from(user_profile).join("AppData").join("Roaming");
1493 }
1494 }
1495
1496 if let Some(home) = non_empty_os_var("HOME") {
1497 return PathBuf::from(home).join(".local").join("share");
1498 }
1499
1500 PathBuf::from(".local").join("share")
1501}
1502
1503fn non_empty_os_var(key: &str) -> Option<OsString> {
1504 let value = env::var_os(key)?;
1505 if value.is_empty() {
1506 None
1507 } else {
1508 Some(value)
1509 }
1510}
1511
1512impl fmt::Display for DaemonConfigError {
1513 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1514 match self {
1515 Self::Read { path, source } => {
1516 write!(f, "failed to read daemon config {}: {source}", path.display())
1517 }
1518 Self::InvalidJsonc { path, message } => {
1519 write!(f, "invalid JSONC in daemon config {}: {message}", path.display())
1520 }
1521 Self::InvalidJson { path, source } => {
1522 write!(f, "invalid daemon config {}: {source}", path.display())
1523 }
1524 Self::UnsupportedVersion { path, version } => write!(
1525 f,
1526 "invalid daemon config {}: version {version} is unsupported (expected {SUPPORTED_CONFIG_VERSION})",
1527 path.display()
1528 ),
1529 Self::InvalidValue { path, message } => {
1530 write!(f, "invalid daemon config {}: {message}", path.display())
1531 }
1532 }
1533 }
1534}
1535
1536impl Error for DaemonConfigError {
1537 fn source(&self) -> Option<&(dyn Error + 'static)> {
1538 match self {
1539 Self::Read { source, .. } => Some(source),
1540 Self::InvalidJson { source, .. } => Some(source),
1541 Self::InvalidJsonc { .. }
1542 | Self::UnsupportedVersion { .. }
1543 | Self::InvalidValue { .. } => None,
1544 }
1545 }
1546}
1547
1548#[cfg(all(test, windows))]
1549mod windows_run_dir_privacy_tests {
1550 use super::ensure_directory_private;
1551 use cortexkit_test_support::ScratchDir;
1552 use subc_os::windows_acl::test_support::{
1553 assert_dacl_owner_only, assert_owner_only, grant_everyone,
1554 };
1555
1556 #[test]
1557 fn windows_run_dir_has_exact_protected_dacl_at_creation() {
1558 let root = ScratchDir::new("windows-run-dir-create");
1559 grant_everyone(root.path());
1560 let path = root.join("run");
1561 ensure_directory_private(&path).unwrap();
1562 assert_owner_only(&path, true, true);
1563 }
1564
1565 #[test]
1566 fn windows_run_dir_narrows_existing_inherited_descendants() {
1567 let root = ScratchDir::new("windows-run-dir-existing");
1568 grant_everyone(root.path());
1569 let path = root.join("run");
1570 std::fs::create_dir(&path).unwrap();
1571 let child = path.join("old.log");
1572 std::fs::write(&child, b"old log").unwrap();
1573 ensure_directory_private(&path).unwrap();
1574 assert_dacl_owner_only(&path, true, true);
1577 assert_dacl_owner_only(&child, false, false);
1578 }
1579}
1580
1581#[cfg(all(test, unix))]
1582mod run_dir_privacy_tests {
1583 use cortexkit_test_support::ScratchDir;
1584 use std::fs;
1585 use std::os::unix::fs::PermissionsExt;
1586
1587 #[test]
1593 fn run_dir_is_created_private_and_an_inherited_wide_one_is_tightened() {
1594 let temp = ScratchDir::new("subc-run-dir-privacy");
1595 let created = temp.path().join("cortexkit").join("run");
1596 super::ensure_directory_private(&created).expect("create run dir");
1597 let mode = fs::metadata(&created)
1598 .expect("stat created")
1599 .permissions()
1600 .mode()
1601 & 0o777;
1602 assert_eq!(
1603 mode, 0o700,
1604 "observable a run directory this code creates must be 0700, got {mode:o}"
1605 );
1606
1607 fs::set_permissions(&created, fs::Permissions::from_mode(0o755)).expect("widen");
1609 let widened = fs::metadata(&created)
1610 .expect("stat widened")
1611 .permissions()
1612 .mode()
1613 & 0o777;
1614 assert_eq!(
1615 widened, 0o755,
1616 "observable the fixture must actually be wide before the tighten"
1617 );
1618
1619 super::ensure_directory_private(&created).expect("tighten run dir");
1620 let mode = fs::metadata(&created)
1621 .expect("stat tightened")
1622 .permissions()
1623 .mode()
1624 & 0o777;
1625 assert_eq!(
1626 mode, 0o700,
1627 "observable an inherited group- or world-readable run directory must be tightened to 0700, got {mode:o}"
1628 );
1629 }
1630}
1631
1632#[cfg(test)]
1633mod tests {
1634 use super::*;
1635
1636 static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1645
1646 fn abs(posix: &str) -> PathBuf {
1651 if cfg!(windows) {
1652 PathBuf::from(format!("C:{}", posix.replace('/', "\\")))
1653 } else {
1654 PathBuf::from(posix)
1655 }
1656 }
1657
1658 #[test]
1659 fn default_data_home_matches_golden_fixture() {
1660 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1661 let doc: serde_json::Value =
1662 serde_json::from_str(include_str!("../tests/golden/data_home_resolution.json"))
1663 .expect("golden parses");
1664 let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1665 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1666 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1667 let platform_matches =
1668 |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1669
1670 let mut ran = 0usize;
1671 for case in doc["cases"].as_array().expect("cases array") {
1672 let name = case["name"].as_str().expect("name");
1673 if !platform_matches(case["platform"].as_str().expect("platform")) {
1674 continue;
1675 }
1676 for v in vars {
1677 env::remove_var(v);
1678 }
1679 for (k, v) in case["env"].as_object().expect("env map") {
1680 env::set_var(k, v.as_str().expect("env value"));
1681 }
1682 let got = default_data_home();
1683 assert_eq!(
1684 got.to_string_lossy(),
1685 case["expect"].as_str().expect("expect"),
1686 "golden case '{name}' diverged"
1687 );
1688 ran += 1;
1689 }
1690 assert!(
1692 ran >= 6,
1693 "only {ran} golden cases ran; fixture or filter broken"
1694 );
1695
1696 for (k, v) in saved {
1697 match v {
1698 Some(val) => env::set_var(k, val),
1699 None => env::remove_var(k),
1700 }
1701 }
1702 }
1703
1704 #[test]
1709 fn daemon_run_dir_refuses_a_relative_data_home_and_names_the_variables() {
1710 for data_home in [PathBuf::from(".local/share"), PathBuf::from("relative-xdg")] {
1711 let error = daemon_run_dir_from(data_home.clone())
1712 .expect_err("a relative data home must be refused");
1713 assert_eq!(
1714 error,
1715 DaemonRunDirError::RelativeDataHome {
1716 data_home: data_home.clone()
1717 }
1718 );
1719 let message = error.to_string();
1720 assert!(
1721 message.contains("XDG_DATA_HOME") && message.contains("HOME"),
1722 "the refusal must name the variables to set: {message}"
1723 );
1724 }
1725 }
1726
1727 #[test]
1728 fn daemon_run_dir_under_an_absolute_data_home_is_cortexkit_run() {
1729 let data_home = env::temp_dir().join("subc-run-dir-probe").join("data");
1730 assert!(data_home.is_absolute());
1731 assert_eq!(
1732 daemon_run_dir_from(data_home.clone()),
1733 Ok(data_home.join("cortexkit").join("run"))
1734 );
1735 }
1736
1737 #[test]
1743 fn default_config_home_matches_golden_fixture() {
1744 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1745 let doc: serde_json::Value =
1746 serde_json::from_str(include_str!("../tests/golden/config_home_resolution.json"))
1747 .expect("golden parses");
1748 let vars = ["XDG_CONFIG_HOME", "APPDATA", "USERPROFILE", "HOME"];
1749 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1750 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1751 let platform_matches =
1752 |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1753
1754 let mut ran = 0usize;
1755 for case in doc["cases"].as_array().expect("cases array") {
1756 let name = case["name"].as_str().expect("name");
1757 if !platform_matches(case["platform"].as_str().expect("platform")) {
1758 continue;
1759 }
1760 for v in vars {
1761 env::remove_var(v);
1762 }
1763 for (k, v) in case["env"].as_object().expect("env map") {
1764 env::set_var(k, v.as_str().expect("env value"));
1765 }
1766 let got = default_config_home();
1767 assert_eq!(
1768 got.to_string_lossy(),
1769 case["expect"].as_str().expect("expect"),
1770 "golden case '{name}' diverged"
1771 );
1772 ran += 1;
1773 }
1774 assert!(
1775 ran >= 6,
1776 "only {ran} golden cases ran; fixture or filter broken"
1777 );
1778
1779 for (k, v) in saved {
1780 match v {
1781 Some(val) => env::set_var(k, val),
1782 None => env::remove_var(k),
1783 }
1784 }
1785 }
1786
1787 #[test]
1794 fn relative_storage_data_home_is_refused_at_parse() {
1795 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1796 let path = Path::new("/golden/subc.jsonc");
1797
1798 let doc =
1800 r#"{ "version": 1, "storage": { "backend": "sqlite", "data_home": "relative/home" } }"#;
1801 let err = parse_doc(doc, path).expect_err("relative data_home must refuse");
1802 assert!(
1803 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1804 if message.contains("relative path relative/home")),
1805 "wrong refusal: {err:?}"
1806 );
1807
1808 let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1810 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1811 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1812 for v in vars {
1813 env::remove_var(v);
1814 }
1815 let doc = r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#;
1816 let err = parse_doc(doc, path).expect_err("no home in env must refuse");
1817 assert!(
1818 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1819 if message.contains("no absolute XDG_DATA_HOME")),
1820 "wrong refusal: {err:?}"
1821 );
1822
1823 let want = abs("/abs/home");
1827 let doc = format!(
1828 r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
1829 serde_json::to_string(&want).expect("json path")
1830 );
1831 let cfg = parse_doc(&doc, path).expect("absolute data_home parses");
1832 assert!(matches!(
1833 cfg.storage,
1834 Some(StorageConfig::Sqlite { ref data_home }) if *data_home == want
1835 ));
1836
1837 for (k, v) in saved {
1838 match v {
1839 Some(val) => env::set_var(k, val),
1840 None => env::remove_var(k),
1841 }
1842 }
1843 }
1844
1845 #[test]
1846 fn restart_required_sections_are_the_rescan_cannot_apply_set() {
1847 assert_eq!(
1848 RestartRequiredSection::ALL.map(RestartRequiredSection::label),
1849 [
1850 "port",
1851 "storage",
1852 "admission_facts_carrier_module_id",
1853 "admission_facts_targets",
1854 "scope_authority_owners",
1855 "federated_scope_owner",
1856 "privileged_operator_prompt",
1857 ]
1858 );
1859 }
1860
1861 #[test]
1862 fn privileged_operator_prompt_defaults_to_log_and_accepts_both_modes() {
1863 let path = Path::new("/tmp/subc.jsonc");
1864 let config = parse_doc(r#"{"version":1}"#, path).unwrap();
1865 assert_eq!(
1866 config.privileged_operator_prompt,
1867 PrivilegedOperatorPrompt::Log
1868 );
1869 for (value, expected) in [
1870 ("log", PrivilegedOperatorPrompt::Log),
1871 ("enforce", PrivilegedOperatorPrompt::Enforce),
1872 ] {
1873 let config = parse_doc(
1874 &format!(r#"{{"version":1,"privileged_operator_prompt":"{value}"}}"#),
1875 path,
1876 )
1877 .unwrap();
1878 assert_eq!(config.privileged_operator_prompt, expected);
1879 }
1880 }
1881
1882 #[test]
1883 fn privileged_operator_prompt_refuses_unknown_values_and_wrong_types() {
1884 let path = Path::new("/tmp/subc.jsonc");
1885 for value in [r#""unknown""#, r#""Enforce""#, "null", "true", "1", "{}"] {
1886 let error = parse_doc(
1887 &format!(r#"{{"version":1,"privileged_operator_prompt":{value}}}"#),
1888 path,
1889 )
1890 .unwrap_err();
1891 assert!(matches!(error, DaemonConfigError::InvalidJson { .. }));
1892 }
1893 }
1894
1895 #[test]
1896 fn scope_authority_owners_defaults_to_the_session_runtime() {
1897 let config = parse_doc(r#"{ "version": 1 }"#, Path::new("/tmp/subc.jsonc")).unwrap();
1898 assert_eq!(config.scope_authority_owners, vec!["prefrontal-core"]);
1899 }
1900
1901 #[test]
1902 fn federated_scope_owner_defaults_and_is_validated_and_restart_required() {
1903 let config = parse_doc(r#"{ "version": 1 }"#, Path::new("/fixture/subc.jsonc")).unwrap();
1904 assert_eq!(config.federated_scope_owner, "callosum");
1905 assert!(!config
1906 .scope_authority_owners
1907 .contains(&config.federated_scope_owner));
1908 let configured = parse_doc(
1909 r#"{ "version": 1, "federated_scope_owner": "peer-carrier" }"#,
1910 Path::new("/fixture/subc.jsonc"),
1911 )
1912 .unwrap();
1913 assert_eq!(configured.federated_scope_owner, "peer-carrier");
1914 assert!(RestartRequiredSection::ALL.contains(&RestartRequiredSection::FederatedScopeOwner));
1915 for invalid in ["", "..", "a/b", "a\\b"] {
1916 let body = serde_json::json!({"version": 1, "federated_scope_owner": invalid});
1917 assert!(
1918 parse_doc(&body.to_string(), Path::new("/fixture/subc.jsonc"))
1919 .unwrap_err()
1920 .to_string()
1921 .contains("federated_scope_owner")
1922 );
1923 }
1924 }
1925
1926 #[test]
1927 fn scope_authority_owners_is_read_when_set_and_refuses_an_empty_id() {
1928 let config = parse_doc(
1929 r#"{ "version": 1, "scope_authority_owners": ["a", "b"] }"#,
1930 Path::new("/tmp/subc.jsonc"),
1931 )
1932 .unwrap();
1933 assert_eq!(config.scope_authority_owners, vec!["a", "b"]);
1934 let config = parse_doc(
1937 r#"{ "version": 1, "scope_authority_owners": [] }"#,
1938 Path::new("/tmp/subc.jsonc"),
1939 )
1940 .unwrap();
1941 assert!(config.scope_authority_owners.is_empty());
1942 let error = parse_doc(
1943 r#"{ "version": 1, "scope_authority_owners": [""] }"#,
1944 Path::new("/tmp/subc.jsonc"),
1945 )
1946 .expect_err("an empty module id is refused");
1947 assert!(
1948 error.to_string().contains("scope_authority_owners"),
1949 "{error}"
1950 );
1951 }
1952
1953 #[test]
1954 fn no_storage_section_yields_none() {
1955 let config = parse_doc(
1956 r#"{ "version": 1, "modules": {} }"#,
1957 Path::new("/tmp/subc.jsonc"),
1958 )
1959 .expect("parse");
1960 assert_eq!(config.storage, None);
1961 }
1962
1963 #[test]
1964 fn sqlite_storage_parses_with_explicit_data_home() {
1965 let config = parse_doc(
1966 &format!(
1967 r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
1968 serde_json::to_string(&abs("/data")).expect("json path")
1969 ),
1970 Path::new("/tmp/subc.jsonc"),
1971 )
1972 .expect("parse");
1973 assert_eq!(
1974 config.storage,
1975 Some(StorageConfig::Sqlite {
1976 data_home: abs("/data")
1977 })
1978 );
1979 }
1980
1981 #[test]
1982 fn sqlite_storage_defaults_data_home_when_omitted() {
1983 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1989 std::env::set_var("XDG_DATA_HOME", abs("/forced/data/home"));
1990 let config = parse_doc(
1991 r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#,
1992 Path::new("/tmp/subc.jsonc"),
1993 )
1994 .expect("parse");
1995 std::env::remove_var("XDG_DATA_HOME");
1996 assert_eq!(
1997 config.storage,
1998 Some(StorageConfig::Sqlite {
1999 data_home: abs("/forced/data/home")
2000 })
2001 );
2002 }
2003
2004 #[test]
2005 fn descriptor_for_matches_store_types_shape() {
2006 let cfg = StorageConfig::Sqlite {
2010 data_home: PathBuf::from("/data"),
2011 };
2012 let descriptor = cfg.descriptor_for("alfonso-routing");
2013 assert_eq!(
2014 descriptor,
2015 serde_json::json!({
2016 "module_id": "alfonso-routing",
2017 "storage_namespace": "default",
2018 "isolation": { "kind": "module" },
2019 "backend": {
2020 "backend": "sqlite",
2021 "path": "/data/cortexkit/alfonso-routing/store.db"
2022 }
2023 })
2024 );
2025 }
2026
2027 #[test]
2028 fn path_hazard_module_id_refuses_config_parse() {
2029 let path = Path::new("/tmp/subc.jsonc");
2030 let err = parse_doc(
2031 r#"{ "version": 1, "modules": { "../escape": { "program": "x" } } }"#,
2032 path,
2033 )
2034 .expect_err("separator-bearing module id must refuse");
2035 let text = format!("{err}");
2036 assert!(
2037 text.contains("not usable as a path component"),
2038 "refusal must name the hazard: {text}"
2039 );
2040 }
2041
2042 #[test]
2043 fn drain_timeout_resolves_module_over_daemon_over_absent() {
2044 let path = Path::new("/tmp/subc.jsonc");
2045 let config = parse_doc(
2046 r#"
2047 {
2048 "version": 1,
2049 "drain_timeout_ms": 45000,
2050 "modules": {
2051 "fast": { "program": "fast", "drain_timeout_ms": 0 },
2052 "slow": { "program": "slow", "drain_timeout_ms": 120000 },
2053 "inherits": { "program": "inherits" }
2054 }
2055 }
2056 "#,
2057 path,
2058 )
2059 .unwrap();
2060 let by_id = |id: &str| {
2061 config
2062 .modules
2063 .iter()
2064 .find(|m| m.module_id == id)
2065 .unwrap()
2066 .drain_timeout_ms
2067 };
2068 assert_eq!(by_id("fast"), Some(0));
2071 assert_eq!(by_id("slow"), Some(120_000));
2072 assert_eq!(by_id("inherits"), Some(45_000));
2074 assert_eq!(config.drain_timeout_ms, Some(45_000));
2075 }
2076
2077 #[test]
2078 fn drain_timeout_absent_everywhere_stays_none_for_builtin_default() {
2079 let path = Path::new("/tmp/subc.jsonc");
2080 let config = parse_doc(
2081 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2082 path,
2083 )
2084 .unwrap();
2085 assert_eq!(config.modules[0].drain_timeout_ms, None);
2089 assert_eq!(config.drain_timeout_ms, None);
2090 }
2091
2092 #[test]
2093 fn route_bind_relay_timeout_resolves_module_over_daemon_over_absent() {
2094 let path = Path::new("/tmp/subc.jsonc");
2100 let config = parse_doc(
2101 r#"
2102 {
2103 "version": 1,
2104 "route_bind_relay_timeout_ms": 30000,
2105 "modules": {
2106 "tight": { "program": "tight", "route_bind_relay_timeout_ms": 5000 },
2107 "loose": { "program": "loose", "route_bind_relay_timeout_ms": 60000 },
2108 "inherits": { "program": "inherits" }
2109 }
2110 }
2111 "#,
2112 path,
2113 )
2114 .unwrap();
2115 let by_id = |id: &str| {
2116 config
2117 .modules
2118 .iter()
2119 .find(|m| m.module_id == id)
2120 .unwrap()
2121 .route_bind_relay_timeout_ms
2122 };
2123 assert_eq!(by_id("tight"), Some(5_000));
2125 assert_eq!(by_id("loose"), Some(60_000));
2126 assert_eq!(by_id("inherits"), Some(30_000));
2128 assert_eq!(config.route_bind_relay_timeout_ms, Some(30_000));
2129 }
2130
2131 #[test]
2132 fn log_tag_keys_must_be_logger_names_and_the_error_names_the_key() {
2133 let path = Path::new("/tmp/subc.jsonc");
2134 for bad in ["Perf", "a b", "perf.", ".perf", "gc..walk", "a=b"] {
2135 let doc = format!(
2136 r#"{{ "version": 1, "modules": {{ "m": {{ "program": "m", "log": {{ "tags": {{ "{bad}": "debug" }} }} }} }} }}"#
2137 );
2138 let err = parse_doc(&doc, path).expect_err(bad);
2139 let text = format!("{err}");
2140 assert!(
2141 text.contains(&format!("{bad:?}")),
2142 "must name the key: {text}"
2143 );
2144 assert!(
2145 text.contains("logger name"),
2146 "must say what a key is: {text}"
2147 );
2148 }
2149 let ok = parse_doc(
2151 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "tags": { "perf": "debug", "gc.walk": "trace", "m": "error", "a-b": "info" } } } } }"#,
2152 path,
2153 );
2154 assert!(ok.is_ok(), "{ok:?}");
2155 }
2156
2157 #[test]
2158 fn log_filter_spec_prefixes_bare_keys_with_the_module_and_passes_absolute_ones() {
2159 let path = Path::new("/tmp/subc.jsonc");
2160 let config = parse_doc(
2161 r#"{ "version": 1, "modules": { "synapse": { "program": "s", "log": { "level": "warn", "tags": { "perf": "debug", "gc.walk": "trace", "synapse": "error", "other.x": "info" } } } } }"#,
2162 path,
2163 )
2164 .unwrap();
2165 let log = config.modules[0].log.as_ref().unwrap();
2166 assert_eq!(
2168 log.filter_spec("synapse"),
2169 "warn,gc.walk=trace,other.x=info,synapse.perf=debug,synapse=error"
2170 );
2171 }
2172
2173 #[test]
2174 fn log_alarm_segment_mb_defaults_to_the_crate_default_and_refuses_zero() {
2175 let path = Path::new("/tmp/subc.jsonc");
2176 let config = parse_doc(
2177 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "level": "info" } } } }"#,
2178 path,
2179 )
2180 .unwrap();
2181 assert_eq!(
2182 config.modules[0].log.as_ref().unwrap().alarm_segment_mb,
2183 cortexkit_log::SegmentRetention::default().alarm_segment_mb
2184 );
2185 let err = parse_doc(
2186 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "alarm_segment_mb": 0 } } } }"#,
2187 path,
2188 )
2189 .expect_err("zero alarm must refuse");
2190 assert!(format!("{err}").contains("alarm_segment_mb"));
2191 }
2192
2193 #[test]
2194 fn route_bind_relay_timeout_zero_at_daemon_layer_is_refused() {
2195 let path = Path::new("/tmp/subc.jsonc");
2196 let err = parse_doc(
2197 r#"
2198 {
2199 "version": 1,
2200 "route_bind_relay_timeout_ms": 0,
2201 "modules": { "m": { "program": "m" } }
2202 }
2203 "#,
2204 path,
2205 )
2206 .expect_err("a daemon-wide zero budget must refuse parse");
2207 let text = format!("{err}");
2208 assert!(
2209 text.contains("route_bind_relay_timeout_ms"),
2210 "error must name the offending key: {text}"
2211 );
2212 assert!(
2213 text.contains("enabled: false"),
2214 "error must name the remedy (enable false): {text}"
2215 );
2216 }
2217
2218 #[test]
2219 fn route_bind_relay_timeout_zero_at_module_layer_is_refused() {
2220 let path = Path::new("/tmp/subc.jsonc");
2221 let err = parse_doc(
2222 r#"
2223 {
2224 "version": 1,
2225 "modules": {
2226 "good": { "program": "good" },
2227 "broken": { "program": "broken", "route_bind_relay_timeout_ms": 0 }
2228 }
2229 }
2230 "#,
2231 path,
2232 )
2233 .expect_err("a per-module zero budget must refuse parse");
2234 let text = format!("{err}");
2235 assert!(
2236 text.contains("route_bind_relay_timeout_ms"),
2237 "error must name the offending key: {text}"
2238 );
2239 assert!(
2240 text.contains("broken"),
2241 "error must name the offending module id: {text}"
2242 );
2243 assert!(
2244 text.contains("enabled: false"),
2245 "error must name the remedy (enable false): {text}"
2246 );
2247 }
2248
2249 #[test]
2250 fn drain_timeout_zero_still_parses_for_wedge_bounces() {
2251 let path = Path::new("/tmp/subc.jsonc");
2257 let config = parse_doc(
2258 r#"
2259 {
2260 "version": 1,
2261 "drain_timeout_ms": 0,
2262 "modules": {
2263 "wedge": { "program": "wedge", "drain_timeout_ms": 0 }
2264 }
2265 }
2266 "#,
2267 path,
2268 )
2269 .expect("drain_timeout_ms: 0 must still parse; wedge-bounce uses it");
2270 let wedge = config
2271 .modules
2272 .iter()
2273 .find(|m| m.module_id == "wedge")
2274 .unwrap();
2275 assert_eq!(wedge.drain_timeout_ms, Some(0));
2276 assert_eq!(config.drain_timeout_ms, Some(0));
2277 }
2278
2279 #[test]
2280 fn route_bind_relay_timeout_absent_everywhere_stays_none_for_builtin_default() {
2281 let path = Path::new("/tmp/subc.jsonc");
2286 let config = parse_doc(
2287 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2288 path,
2289 )
2290 .unwrap();
2291 assert_eq!(config.modules[0].route_bind_relay_timeout_ms, None);
2292 assert_eq!(config.route_bind_relay_timeout_ms, None);
2293 }
2294
2295 #[test]
2301 fn a_config_without_a_restart_block_keeps_the_supervisor_defaults() {
2302 let path = Path::new("/tmp/subc.jsonc");
2303 let config = parse_doc(
2304 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2305 path,
2306 )
2307 .unwrap();
2308 assert_eq!(config.modules[0].restart.max_restarts, 3);
2309 assert_eq!(config.modules[0].restart.window, Duration::from_secs(600));
2310 assert_eq!(
2311 config.modules[0].restart.backoff,
2312 Duration::from_millis(100)
2313 );
2314 assert_eq!(
2315 config.modules[0].restart.max_backoff,
2316 Duration::from_secs(30)
2317 );
2318 }
2319
2320 #[test]
2321 fn register_timeout_config_accepts_bounds_and_rejects_outside_them() {
2322 let path = Path::new("subc.jsonc");
2323 for seconds in [10, 3600] {
2324 let doc = format!(
2325 r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{seconds}}}}}}}"#
2326 );
2327 let config = parse_doc(&doc, path).unwrap();
2328 assert_eq!(
2329 config.modules[0].register_timeout,
2330 Duration::from_secs(seconds)
2331 );
2332 }
2333 for value in ["9", "3601"] {
2334 let doc = format!(
2335 r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{value}}}}}}}"#
2336 );
2337 let error = parse_doc(&doc, path).unwrap_err().to_string();
2338 assert!(error.contains("register_timeout_s"), "{value}: {error}");
2339 }
2340 let config = parse_doc(r#"{"version":1,"modules":{"m":{"program":"m"}}}"#, path).unwrap();
2341 assert_eq!(config.modules[0].register_timeout, Duration::from_secs(120));
2342 }
2343
2344 #[test]
2345 fn a_restart_block_resolves_each_key_independently() {
2346 let path = Path::new("/tmp/subc.jsonc");
2347 let config = parse_doc(
2348 r#"
2349 {
2350 "version": 1,
2351 "modules": {
2352 "all": {
2353 "program": "all",
2354 "restart": { "max_restarts": 5, "window_secs": 60, "backoff_ms": 250, "max_backoff_ms": 5000 }
2355 },
2356 "window-only": {
2357 "program": "window-only",
2358 "restart": { "window_secs": 7200 }
2359 },
2360 "never": {
2361 "program": "never",
2362 "restart": { "max_restarts": 0 }
2363 }
2364 }
2365 }
2366 "#,
2367 path,
2368 )
2369 .unwrap();
2370 let by_id = |id: &str| {
2371 config
2372 .modules
2373 .iter()
2374 .find(|m| m.module_id == id)
2375 .unwrap()
2376 .restart
2377 };
2378
2379 let all = by_id("all");
2380 assert_eq!(all.max_restarts, 5);
2381 assert_eq!(all.window, Duration::from_secs(60));
2382 assert_eq!(all.backoff, Duration::from_millis(250));
2383 assert_eq!(all.max_backoff, Duration::from_secs(5));
2384
2385 let window_only = by_id("window-only");
2388 assert_eq!(window_only.max_restarts, 3);
2389 assert_eq!(window_only.window, Duration::from_secs(7_200));
2390 assert_eq!(window_only.backoff, Duration::from_millis(100));
2391 assert_eq!(window_only.max_backoff, Duration::from_secs(30));
2392
2393 assert_eq!(by_id("never").max_restarts, 0);
2396 }
2397
2398 #[test]
2402 fn restart_window_zero_is_refused_by_name() {
2403 let path = Path::new("/tmp/subc.jsonc");
2404 let err = parse_doc(
2405 r#"
2406 {
2407 "version": 1,
2408 "modules": {
2409 "good": { "program": "good" },
2410 "broken": { "program": "broken", "restart": { "window_secs": 0 } }
2411 }
2412 }
2413 "#,
2414 path,
2415 )
2416 .expect_err("a zero crash window must refuse parse");
2417 assert!(
2418 matches!(err, DaemonConfigError::InvalidValue { .. }),
2419 "a zero window is an invalid value, not a parse failure: {err:?}"
2420 );
2421 let text = format!("{err}");
2422 assert!(
2423 text.contains("restart.window_secs"),
2424 "error must name the offending key: {text}"
2425 );
2426 assert!(
2427 text.contains("broken"),
2428 "error must name the offending module id: {text}"
2429 );
2430 assert!(
2431 text.contains("max_restarts: 0"),
2432 "error must name the setting that actually stops restarts: {text}"
2433 );
2434 }
2435
2436 #[test]
2437 fn restart_max_backoff_below_backoff_is_refused_by_name() {
2438 let path = Path::new("/tmp/subc.jsonc");
2439 let err = parse_doc(
2440 r#"
2441 {
2442 "version": 1,
2443 "modules": {
2444 "broken": {
2445 "program": "broken",
2446 "restart": { "backoff_ms": 1000, "max_backoff_ms": 999 }
2447 }
2448 }
2449 }
2450 "#,
2451 path,
2452 )
2453 .expect_err("a maximum below the base backoff must refuse parse");
2454 assert!(
2455 matches!(err, DaemonConfigError::InvalidValue { .. }),
2456 "an invalid restart bound must be an InvalidValue: {err:?}"
2457 );
2458 let text = format!("{err}");
2459 assert!(
2460 text.contains("restart.max_backoff_ms"),
2461 "error must name max_backoff_ms: {text}"
2462 );
2463 assert!(
2464 text.contains("restart.backoff_ms"),
2465 "error must name backoff_ms: {text}"
2466 );
2467 assert!(
2468 text.contains("broken"),
2469 "error must name the offending module id: {text}"
2470 );
2471 }
2472
2473 #[test]
2474 fn parse_jsonc_defaults_and_ignores_unknown_fields() {
2475 let path = Path::new("/tmp/subc.jsonc");
2476 let config = parse_doc(
2477 r#"
2478 {
2479 // forward-compatible root field
2480 "version": 1,
2481 "unknown": { "ignored": true },
2482 "modules": {
2483 "aft": {
2484 "program": "aft",
2485 "args": ["module",],
2486 "env": { "A": "B", },
2487 "future": 42,
2488 },
2489 "disabled": { "program": "disabled", "enabled": false }
2490 },
2491 }
2492 "#,
2493 path,
2494 )
2495 .unwrap();
2496
2497 assert_eq!(config.port, None);
2498 assert_eq!(config.modules.len(), 2);
2499 assert_eq!(config.modules[0].module_id, "aft");
2500 assert_eq!(config.modules[0].program, PathBuf::from("aft"));
2501 assert_eq!(config.modules[0].args, ["module"]);
2502 assert_eq!(config.modules[0].env, [("A".to_string(), "B".to_string())]);
2503 assert!(config.modules[0].enabled);
2504 assert!(config.modules[0].reserved_prefixes.is_empty());
2505 assert_eq!(config.modules[0].health, HealthConfig::default());
2506 assert!(!config.modules[1].enabled);
2507 }
2508
2509 #[test]
2510 fn reserved_capabilities_accept_unknown_bound_modules_and_refuse_bad_identifiers() {
2511 let path = Path::new("/tmp/subc.jsonc");
2512 let config = parse_doc(
2513 r#"{
2514 "version": 1,
2515 "reserved_capabilities": {
2516 "credentials-provider/v1": "future-vault"
2517 },
2518 "modules": {}
2519 }"#,
2520 path,
2521 )
2522 .expect("a binding may predate its provider installation");
2523 assert_eq!(
2524 config.reserved_capabilities,
2525 BTreeMap::from([(
2526 "credentials-provider/v1".to_string(),
2527 "future-vault".to_string()
2528 )])
2529 );
2530
2531 let error = parse_doc(
2532 r#"{
2533 "version": 1,
2534 "reserved_capabilities": { "Credentials/v1": "vault" },
2535 "modules": {}
2536 }"#,
2537 path,
2538 )
2539 .expect_err("reserved capabilities use the capability identifier grammar");
2540 assert!(error.to_string().contains("reserved_capabilities key"));
2541 }
2542
2543 #[test]
2544 fn retired_launch_nonce_env_is_ignored_for_any_value() {
2545 let parse = |field: &str| {
2546 parse_doc(
2547 &format!(r#"{{"version":1,"modules":{{"probe":{{"program":"probe"{field}}}}}}}"#),
2548 Path::new("subc.jsonc"),
2549 )
2550 .unwrap()
2551 .modules
2552 .remove(0)
2553 .module_spec()
2554 };
2555 for value in ["true", "false", "null", "0", "\"false\"", "[]", "{}"] {
2556 assert_eq!(
2557 parse(""),
2558 parse(&format!(",\"launch_nonce_env\":{value}")),
2559 "the retired key must not change the launch spec or require a restart"
2560 );
2561 }
2562 }
2563
2564 #[test]
2567 fn an_absent_protocol_key_and_an_explicit_subc_are_the_same_module() {
2568 let parse = |module_body: &str| {
2569 parse_doc(
2570 &format!(
2571 r#"{{
2572 "version": 1,
2573 "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2574 }}"#
2575 ),
2576 Path::new("subc.jsonc"),
2577 )
2578 .expect("module parses")
2579 .modules
2580 .remove(0)
2581 };
2582
2583 let absent = parse("");
2584 let explicit = parse(r#", "protocol": "subc""#);
2585 let none = parse(r#", "protocol": "none""#);
2586
2587 assert_eq!(absent.protocol, ModuleProtocol::Subc);
2588 assert_eq!(explicit.protocol, ModuleProtocol::Subc);
2589 assert_eq!(
2590 absent, explicit,
2591 "an absent protocol key must produce exactly the module an explicit subc does"
2592 );
2593 assert_eq!(none.protocol, ModuleProtocol::None);
2594 assert_eq!(none.module_spec().protocol, ModuleProtocol::None);
2598 }
2599
2600 #[test]
2604 fn overlap_defaults_to_exclusive_and_only_safe_opts_in() {
2605 let parse = |module_body: &str| {
2606 parse_doc(
2607 &format!(
2608 r#"{{
2609 "version": 1,
2610 "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2611 }}"#
2612 ),
2613 Path::new("subc.jsonc"),
2614 )
2615 };
2616
2617 let absent = parse("").unwrap().modules.remove(0);
2618 assert_eq!(absent.overlap, ModuleOverlap::Exclusive);
2619 assert_eq!(absent.module_spec().overlap, ModuleOverlap::Exclusive);
2620 let safe = parse(r#", "overlap": "safe""#).unwrap().modules.remove(0);
2621 assert_eq!(safe.module_spec().overlap, ModuleOverlap::Safe);
2622 let typo = parse(r#", "overlap": "sfae""#).expect_err("an unknown overlap is refused");
2623 assert!(typo.to_string().contains("sfae"), "{typo}");
2624 }
2625
2626 #[test]
2627 fn carry_containment_defaults_off_and_refuses_overlap() {
2628 let parse = |module_body: &str| {
2629 parse_doc(
2630 &format!(
2631 r#"{{
2632 "version": 1,
2633 "modules": {{ "worker": {{ "program": "worker"{module_body} }} }}
2634 }}"#
2635 ),
2636 Path::new("subc.jsonc"),
2637 )
2638 };
2639
2640 let absent = parse("").unwrap().modules.remove(0);
2641 let explicit_off = parse(r#", "carry_containment": false"#)
2642 .unwrap()
2643 .modules
2644 .remove(0);
2645 assert_eq!(absent, explicit_off);
2646 assert!(!absent.module_spec().carry_containment);
2647 let carried = parse(r#", "carry_containment": true"#)
2648 .unwrap()
2649 .modules
2650 .remove(0);
2651 assert!(carried.module_spec().carry_containment);
2652 let error = parse(r#", "carry_containment": true, "overlap": "safe""#)
2653 .expect_err("a carried container cannot have overlapping leaders");
2654 let message = error.to_string();
2655 assert!(message.contains("worker"), "{message}");
2656 assert!(message.contains("carry_containment"), "{message}");
2657 assert!(message.contains("overlap"), "{message}");
2658 }
2659
2660 #[test]
2664 fn the_spawn_role_is_refused_as_a_configured_env_key() {
2665 let error = parse_doc(
2666 r#"{
2667 "version": 1,
2668 "modules": { "aft": { "program": "aft", "env": { "SUBC_SPAWN_ROLE": "swap_candidate" } } }
2669 }"#,
2670 Path::new("subc.jsonc"),
2671 )
2672 .expect_err("SUBC_SPAWN_ROLE must not be configurable");
2673 assert!(
2674 matches!(error, DaemonConfigError::InvalidValue { .. }),
2675 "expected InvalidValue, got {error:?}"
2676 );
2677 assert!(error.to_string().contains("SUBC_SPAWN_ROLE"), "{error}");
2678 }
2679
2680 #[test]
2686 fn an_unsupported_protocol_value_is_refused_by_name() {
2687 let error = parse_doc(
2688 r#"{
2689 "version": 1,
2690 "modules": { "nats": { "program": "nats-server", "protocol": "grpc" } }
2691 }"#,
2692 Path::new("subc.jsonc"),
2693 )
2694 .expect_err("an unknown protocol must not fall back to a default");
2695
2696 assert!(
2697 matches!(error, DaemonConfigError::InvalidValue { .. }),
2698 "expected InvalidValue, got {error:?}"
2699 );
2700 let message = error.to_string();
2701 assert!(
2702 message.contains("grpc"),
2703 "the refusal must name the offending value: {message}"
2704 );
2705 assert!(
2706 message.contains("nats"),
2707 "the refusal must name the module so it can be found in the file: {message}"
2708 );
2709 }
2710
2711 #[test]
2715 fn reserved_true_with_protocol_none_is_refused_with_the_reason() {
2716 let error = parse_doc(
2717 r#"{
2718 "version": 1,
2719 "modules": {
2720 "nats": { "program": "nats-server", "protocol": "none", "reserved": true }
2721 }
2722 }"#,
2723 Path::new("subc.jsonc"),
2724 )
2725 .expect_err("a reservation that can never be checked must not parse");
2726
2727 assert!(
2728 matches!(error, DaemonConfigError::InvalidValue { .. }),
2729 "expected InvalidValue, got {error:?}"
2730 );
2731 let message = error.to_string();
2732 assert!(
2733 message.contains("nats") && message.contains("reserved"),
2734 "the refusal must name the module and the offending key: {message}"
2735 );
2736 assert!(
2737 message.contains("HELLO") || message.contains("never registers"),
2738 "the refusal must say WHY the pair cannot work: {message}"
2739 );
2740 }
2741
2742 #[test]
2743 fn reserved_prefixes_parse_for_reserved_modules() {
2744 let config = parse_doc(
2745 r#"
2746 {
2747 "version": 1,
2748 "modules": {
2749 "federation": {
2750 "program": "fed",
2751 "reserved": true,
2752 "reserved_prefixes": ["fed:"]
2753 }
2754 }
2755 }
2756 "#,
2757 Path::new("subc.jsonc"),
2758 )
2759 .unwrap();
2760
2761 assert_eq!(config.modules[0].reserved_prefixes, ["fed:".to_string()]);
2762 }
2763
2764 #[test]
2765 fn reserved_prefixes_reject_bad_boundaries_and_owners() {
2766 let missing_delimiter = parse_doc(
2767 r#"{
2768 "version": 1,
2769 "modules": {
2770 "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed"] }
2771 }
2772 }"#,
2773 Path::new("subc.jsonc"),
2774 )
2775 .unwrap_err();
2776 assert!(matches!(
2777 missing_delimiter,
2778 DaemonConfigError::InvalidValue { .. }
2779 ));
2780
2781 let non_reserved_owner = parse_doc(
2782 r#"{
2783 "version": 1,
2784 "modules": {
2785 "federation": { "program": "fed", "reserved_prefixes": ["fed:"] }
2786 }
2787 }"#,
2788 Path::new("subc.jsonc"),
2789 )
2790 .unwrap_err();
2791 assert!(matches!(
2792 non_reserved_owner,
2793 DaemonConfigError::InvalidValue { .. }
2794 ));
2795 }
2796
2797 #[test]
2798 fn reserved_prefixes_reject_cross_owner_overlap_and_exact_id_collisions() {
2799 let overlap = parse_doc(
2800 r#"{
2801 "version": 1,
2802 "modules": {
2803 "fed-owner": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2804 "sub-owner": { "program": "fed-sub", "reserved": true, "reserved_prefixes": ["fed:sub:"] }
2805 }
2806 }"#,
2807 Path::new("subc.jsonc"),
2808 )
2809 .unwrap_err();
2810 assert!(matches!(overlap, DaemonConfigError::InvalidValue { .. }));
2811
2812 let exact_collision = parse_doc(
2813 r#"{
2814 "version": 1,
2815 "modules": {
2816 "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2817 "fed:special": { "program": "special" }
2818 }
2819 }"#,
2820 Path::new("subc.jsonc"),
2821 )
2822 .unwrap_err();
2823 assert!(matches!(
2824 exact_collision,
2825 DaemonConfigError::InvalidValue { .. }
2826 ));
2827 }
2828
2829 #[test]
2830 fn health_config_parses_and_ignores_unknown_fields() {
2831 let config = parse_doc(
2832 r#"
2833 {
2834 "version": 1,
2835 "modules": {
2836 "aft": {
2837 "program": "aft",
2838 "health": {
2839 "cadence_ms": 100,
2840 "deadline_ms": 20,
2841 "failure_threshold": 2,
2842 "on_degraded": "report",
2843 "on_failing": "restart",
2844 "critical": true,
2845 "future": "ignored"
2846 }
2847 }
2848 }
2849 }
2850 "#,
2851 Path::new("subc.jsonc"),
2852 )
2853 .unwrap();
2854
2855 let health = &config.modules[0].health;
2856 assert_eq!(health.cadence, std::time::Duration::from_millis(100));
2857 assert_eq!(health.deadline, std::time::Duration::from_millis(20));
2858 assert_eq!(health.failure_threshold, 2);
2859 assert_eq!(health.on_degraded, HealthAction::Report);
2860 assert_eq!(health.on_failing, HealthAction::Restart);
2861 assert!(health.critical);
2862 }
2863
2864 #[test]
2865 fn http_health_refuses_non_loopback_https_and_wire_modules() {
2866 for (protocol, url) in [
2867 ("none", "http://example.com/healthz"),
2868 ("none", "https://127.0.0.1/healthz"),
2869 ("subc", "http://127.0.0.1/healthz"),
2870 ] {
2871 let doc = serde_json::json!({"version": 1, "modules": {"bus": {
2872 "program": "nats-server", "protocol": protocol, "health": {"http": url}
2873 }}})
2874 .to_string();
2875 let error = parse_doc(&doc, Path::new("test.jsonc"))
2876 .unwrap_err()
2877 .to_string();
2878 assert!(
2879 error.contains("bus") && error.contains("health.http"),
2880 "{error}"
2881 );
2882 }
2883 }
2884
2885 #[test]
2886 fn health_config_rejects_bad_enum_and_non_positive_numbers() {
2887 let bad_enum = parse_doc(
2888 r#"{
2889 "version": 1,
2890 "modules": { "aft": { "program": "aft", "health": { "on_failing": "page" } } }
2891 }"#,
2892 Path::new("subc.jsonc"),
2893 )
2894 .unwrap_err();
2895 assert!(matches!(bad_enum, DaemonConfigError::InvalidJson { .. }));
2896
2897 let zero = parse_doc(
2898 r#"{
2899 "version": 1,
2900 "modules": { "aft": { "program": "aft", "health": { "cadence_ms": 0 } } }
2901 }"#,
2902 Path::new("subc.jsonc"),
2903 )
2904 .unwrap_err();
2905 assert!(matches!(zero, DaemonConfigError::InvalidValue { .. }));
2906 }
2907
2908 #[test]
2909 fn admission_facts_carrier_requires_non_empty_targets() {
2910 let missing_targets = parse_doc(
2911 r#"{
2912 "version": 1,
2913 "admission_facts_carrier_module_id": "fed",
2914 "modules": { "fed": { "program": "fed", "reserved": true } }
2915 }"#,
2916 Path::new("subc.jsonc"),
2917 )
2918 .unwrap_err();
2919 assert!(
2925 matches!(&missing_targets, DaemonConfigError::InvalidValue { message, .. }
2926 if message.contains("must be present")),
2927 "expected the presence rule, got: {missing_targets:?}"
2928 );
2929
2930 let empty_targets = parse_doc(
2931 r#"{
2932 "version": 1,
2933 "admission_facts_carrier_module_id": "fed",
2934 "admission_facts_targets": [""],
2935 "modules": { "fed": { "program": "fed", "reserved": true } }
2936 }"#,
2937 Path::new("subc.jsonc"),
2938 )
2939 .unwrap_err();
2940 assert!(
2941 matches!(&empty_targets, DaemonConfigError::InvalidValue { message, .. }
2942 if message.contains("must be non-empty")),
2943 "expected the non-empty rule, got: {empty_targets:?}"
2944 );
2945 }
2946
2947 #[test]
2948 fn admission_facts_carrier_must_be_enabled_reserved_and_configured() {
2949 for module in [
2950 r#"{ "program": "fed", "enabled": false, "reserved": true }"#,
2951 r#"{ "program": "fed", "enabled": true, "reserved": false }"#,
2952 ] {
2953 let doc = format!(
2954 r#"{{
2955 "version": 1,
2956 "admission_facts_carrier_module_id": "fed",
2957 "admission_facts_targets": ["target"],
2958 "modules": {{ "fed": {module}, "target": {{ "program": "target" }} }}
2959 }}"#
2960 );
2961 let err = parse_doc(&doc, Path::new("subc.jsonc")).unwrap_err();
2962 assert!(
2966 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
2967 if message.contains("enabled reserved module")),
2968 "expected the enabled-and-reserved rule, got: {err:?}"
2969 );
2970 }
2971
2972 let absent = parse_doc(
2973 r#"{
2974 "version": 1,
2975 "admission_facts_carrier_module_id": "missing",
2976 "admission_facts_targets": ["target"],
2977 "modules": { "target": { "program": "target" } }
2978 }"#,
2979 Path::new("subc.jsonc"),
2980 )
2981 .unwrap_err();
2982 assert!(
2983 matches!(&absent, DaemonConfigError::InvalidValue { message, .. }
2984 if message.contains("must name a configured module")),
2985 "expected the configured-module rule, got: {absent:?}"
2986 );
2987 }
2988
2989 #[test]
2990 fn reject_unsupported_version() {
2991 let err = parse_doc(
2992 r#"{ "version": 2, "modules": {} }"#,
2993 Path::new("subc.jsonc"),
2994 )
2995 .unwrap_err();
2996 assert!(matches!(
2997 err,
2998 DaemonConfigError::UnsupportedVersion { version: 2, .. }
2999 ));
3000 }
3001
3002 #[test]
3003 fn reject_unterminated_block_comment() {
3004 let err = parse_doc(r#"{ "version": 1, /*"#, Path::new("subc.jsonc")).unwrap_err();
3005 assert!(matches!(err, DaemonConfigError::InvalidJsonc { .. }));
3006 }
3007}
3008
3009#[cfg(test)]
3010mod activity_config_tests {
3011 use super::*;
3012
3013 #[test]
3014 fn activity_config_defaults_partial_overrides_and_positive_bounds() {
3015 let path = Path::new("subc.jsonc");
3016 let default = parse_doc_with_activity(r#"{"version":1,"modules":{}}"#, path).unwrap();
3017 assert_eq!(
3018 default.1,
3019 ActivityConfig {
3020 max_age_days: 30,
3021 max_total_mb: 64
3022 }
3023 );
3024 let changed = parse_doc_with_activity(
3025 r#"{"version":1,"activity":{"max_age_days":7,"max_total_mb":8}}"#,
3026 path,
3027 )
3028 .unwrap();
3029 assert_eq!(
3030 changed.1,
3031 ActivityConfig {
3032 max_age_days: 7,
3033 max_total_mb: 8
3034 }
3035 );
3036 let partial =
3037 parse_doc_with_activity(r#"{"version":1,"activity":{"max_age_days":7}}"#, path)
3038 .unwrap();
3039 assert_eq!(
3040 partial.1,
3041 ActivityConfig {
3042 max_age_days: 7,
3043 max_total_mb: 64
3044 }
3045 );
3046 for doc in [
3047 r#"{"version":1,"activity":{"max_age_days":0}}"#,
3048 r#"{"version":1,"activity":{"max_total_mb":0}}"#,
3049 ] {
3050 assert!(parse_doc(doc, path).is_err());
3051 }
3052 assert!(!RestartRequiredSection::ALL
3053 .iter()
3054 .any(|section| section.label() == "activity"));
3055 }
3056}