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 PrivilegedOperatorPrompt,
56}
57
58impl RestartRequiredSection {
59 pub const ALL: [Self; 6] = [
60 Self::Port,
61 Self::Storage,
62 Self::AdmissionFactsCarrierModuleId,
63 Self::AdmissionFactsTargets,
64 Self::ScopeAuthorityOwners,
65 Self::PrivilegedOperatorPrompt,
66 ];
67
68 pub const fn label(self) -> &'static str {
69 match self {
70 Self::Port => "port",
71 Self::Storage => "storage",
72 Self::AdmissionFactsCarrierModuleId => "admission_facts_carrier_module_id",
73 Self::AdmissionFactsTargets => "admission_facts_targets",
74 Self::ScopeAuthorityOwners => "scope_authority_owners",
75 Self::PrivilegedOperatorPrompt => "privileged_operator_prompt",
76 }
77 }
78}
79
80#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
82#[serde(rename_all = "lowercase")]
83pub enum PrivilegedOperatorPrompt {
84 #[default]
85 Log,
86 Enforce,
87}
88
89pub fn default_scope_authority_owners() -> Vec<String> {
92 vec!["prefrontal-core".to_string()]
93}
94
95const 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)";
106
107const 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)";
114
115#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct LoggingConfig {
123 pub level: String,
124 pub tags: BTreeMap<String, String>,
129 pub retention: Retention,
130 pub alarm_segment_mb: u32,
132}
133
134impl LoggingConfig {
135 pub fn filter_spec(&self, module_id: &str) -> String {
144 let mut directives = vec![self.level.clone()];
145 directives.extend(self.tags.iter().map(|(logger, level)| {
146 if logger == module_id || logger.contains('.') {
147 format!("{logger}={level}")
148 } else {
149 format!("{module_id}.{logger}={level}")
150 }
151 }));
152 directives.join(",")
153 }
154
155 pub fn segment_retention(&self) -> cortexkit_log::SegmentRetention {
156 cortexkit_log::SegmentRetention {
157 max_age_days: self.retention.max_age_days,
158 alarm_segment_mb: self.alarm_segment_mb,
159 }
160 }
161}
162
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct DaemonConfig {
165 pub path: PathBuf,
166 pub port: Option<u16>,
167 pub privileged_operator_prompt: PrivilegedOperatorPrompt,
169 pub drain_timeout_ms: Option<u64>,
173 pub route_bind_relay_timeout_ms: Option<u64>,
182 pub modules: Vec<ConfiguredModule>,
183 pub storage: Option<StorageConfig>,
186 pub admission_facts_carrier_module_id: Option<String>,
188 pub admission_facts_targets: Option<Vec<String>>,
190 pub scope_authority_owners: Vec<String>,
196 pub reserved_capabilities: BTreeMap<String, String>,
200}
201
202#[derive(Debug, Clone, PartialEq, Eq)]
206pub enum StorageConfig {
207 Sqlite { data_home: PathBuf },
209}
210
211impl StorageConfig {
212 pub fn descriptor_for(&self, module_id: &str) -> serde_json::Value {
238 match self {
239 StorageConfig::Sqlite { data_home } => {
248 let data_home = data_home.to_string_lossy();
249 let path = format!(
250 "{}/cortexkit/{module_id}/store.db",
251 data_home.trim_end_matches('/')
252 );
253 serde_json::json!({
254 "module_id": module_id,
255 "storage_namespace": "default",
256 "isolation": { "kind": "module" },
257 "backend": { "backend": "sqlite", "path": path },
258 })
259 }
260 }
261 }
262}
263
264#[derive(Debug, Clone, PartialEq, Eq)]
265pub struct ConfiguredModule {
266 pub module_id: String,
267 pub program: PathBuf,
268 pub args: Vec<String>,
269 pub env: Vec<(String, String)>,
270 pub log: Option<LoggingConfig>,
274 pub enabled: bool,
275 pub reserved: bool,
281 pub reserved_prefixes: Vec<String>,
285 pub protocol: ModuleProtocol,
288 pub overlap: ModuleOverlap,
291 pub health: HealthConfig,
292 pub drain_timeout_ms: Option<u64>,
295 pub register_timeout: Duration,
298 pub route_bind_relay_timeout_ms: Option<u64>,
303 pub restart: RestartPolicy,
314}
315
316impl ConfiguredModule {
317 pub fn module_spec(&self) -> ModuleSpec {
318 let mut env = self.env.clone();
319 if let Some(log) = &self.log {
320 env.retain(|(key, _)| {
321 key != CK_LOG_ENV
322 && key != CAPTURE_MAX_FILE_MB_ENV
323 && key != CAPTURE_KEEP_ENV
324 && key != CAPTURE_MAX_AGE_DAYS_ENV
325 });
326 env.retain(|(key, _)| {
327 key != CHILD_LOG_MAX_AGE_DAYS_ENV && key != CHILD_LOG_ALARM_SEGMENT_MB_ENV
328 });
329 env.push((CK_LOG_ENV.to_string(), log.filter_spec(&self.module_id)));
330 env.push((
331 CHILD_LOG_MAX_AGE_DAYS_ENV.to_string(),
332 log.retention.max_age_days.to_string(),
333 ));
334 env.push((
335 CHILD_LOG_ALARM_SEGMENT_MB_ENV.to_string(),
336 log.alarm_segment_mb.to_string(),
337 ));
338 env.push((
342 CAPTURE_MAX_FILE_MB_ENV.to_string(),
343 log.retention.max_file_mb.to_string(),
344 ));
345 env.push((CAPTURE_KEEP_ENV.to_string(), log.retention.keep.to_string()));
346 env.push((
347 CAPTURE_MAX_AGE_DAYS_ENV.to_string(),
348 log.retention.max_age_days.to_string(),
349 ));
350 }
351 ModuleSpec {
352 module_id: self.module_id.clone(),
353 program: self.program.clone(),
354 args: self.args.clone(),
355 env,
356 reserved: self.reserved,
357 reserved_prefixes: self.reserved_prefixes.clone(),
358 protocol: self.protocol,
359 overlap: self.overlap,
360 }
361 }
362}
363
364#[derive(Debug)]
365pub enum DaemonConfigError {
366 Read {
367 path: PathBuf,
368 source: io::Error,
369 },
370 InvalidJsonc {
371 path: PathBuf,
372 message: String,
373 },
374 InvalidJson {
375 path: PathBuf,
376 source: serde_json::Error,
377 },
378 UnsupportedVersion {
379 path: PathBuf,
380 version: u32,
381 },
382 InvalidValue {
383 path: PathBuf,
384 message: String,
385 },
386}
387
388#[derive(Debug, Deserialize)]
389struct RawDaemonConfig {
390 version: u32,
391 #[serde(default)]
392 activity: ActivityConfig,
393 #[serde(default)]
394 port: Option<u16>,
395 #[serde(default)]
396 privileged_operator_prompt: PrivilegedOperatorPrompt,
397 #[serde(default)]
398 drain_timeout_ms: Option<u64>,
399 #[serde(default)]
400 route_bind_relay_timeout_ms: Option<u64>,
401 #[serde(default)]
402 log: Option<RawLoggingConfig>,
403 #[serde(default)]
404 modules: BTreeMap<String, RawModuleConfig>,
405 #[serde(default)]
406 storage: Option<RawStorageConfig>,
407 #[serde(default)]
408 admission_facts_carrier_module_id: Option<String>,
409 #[serde(default)]
410 admission_facts_targets: Option<Vec<String>>,
411 #[serde(default)]
412 scope_authority_owners: Option<Vec<String>>,
413 #[serde(default)]
414 reserved_capabilities: BTreeMap<String, String>,
415}
416
417#[derive(Debug, Deserialize)]
418#[serde(tag = "backend", rename_all = "snake_case")]
419enum RawStorageConfig {
420 Sqlite {
421 #[serde(default)]
424 data_home: Option<PathBuf>,
425 },
426}
427
428#[derive(Debug, Deserialize)]
429struct RawModuleConfig {
430 program: PathBuf,
431 #[serde(default)]
432 args: Vec<String>,
433 #[serde(default)]
434 env: BTreeMap<String, String>,
435 #[serde(default)]
436 log: Option<RawLoggingConfig>,
437 #[serde(default = "default_enabled")]
438 enabled: bool,
439 #[serde(default)]
440 reserved: bool,
441 #[serde(flatten)]
444 ignored: BTreeMap<String, serde_json::Value>,
445 #[serde(default)]
446 reserved_prefixes: Vec<String>,
447 #[serde(default)]
451 protocol: Option<String>,
452 #[serde(default)]
454 overlap: Option<String>,
455 #[serde(default)]
456 health: Option<RawHealthConfig>,
457 #[serde(default)]
458 drain_timeout_ms: Option<u64>,
459 #[serde(default)]
460 register_timeout_s: Option<u64>,
461 #[serde(default)]
462 route_bind_relay_timeout_ms: Option<u64>,
463 #[serde(default)]
464 restart: Option<RawRestartConfig>,
465}
466
467#[derive(Debug, Clone, Deserialize)]
468struct RawLoggingConfig {
469 #[serde(default)]
470 level: Option<String>,
471 #[serde(default)]
472 tags: BTreeMap<String, String>,
473 #[serde(default)]
474 alarm_segment_mb: Option<u32>,
475 #[serde(default)]
476 max_file_mb: Option<u32>,
477 #[serde(default)]
478 keep: Option<u8>,
479 #[serde(default)]
480 max_age_days: Option<u32>,
481}
482
483#[derive(Debug, Deserialize)]
484struct RawRestartConfig {
485 #[serde(default)]
486 max_restarts: Option<u32>,
487 #[serde(default)]
488 window_secs: Option<u64>,
489 #[serde(default)]
490 backoff_ms: Option<u64>,
491 #[serde(default)]
492 max_backoff_ms: Option<u64>,
493}
494
495#[derive(Debug, Deserialize)]
496struct RawHealthConfig {
497 #[serde(default)]
498 http: Option<String>,
499 #[serde(default)]
500 cadence_ms: Option<u64>,
501 #[serde(default)]
502 deadline_ms: Option<u64>,
503 #[serde(default)]
504 failure_threshold: Option<u32>,
505 #[serde(default)]
506 on_degraded: Option<RawHealthAction>,
507 #[serde(default)]
508 on_failing: Option<RawHealthAction>,
509 #[serde(default)]
510 critical: bool,
511}
512
513#[derive(Debug, Deserialize)]
514#[serde(rename_all = "snake_case")]
515enum RawHealthAction {
516 Report,
517 Restart,
518 Alert,
519}
520
521pub fn default_config_path() -> PathBuf {
522 default_config_home().join(DAEMON_CONFIG_RELATIVE_PATH)
523}
524
525pub fn default_config_home() -> PathBuf {
547 if let Some(config_home) = non_empty_os_var("XDG_CONFIG_HOME") {
548 return PathBuf::from(config_home);
549 }
550
551 #[cfg(windows)]
552 {
553 if let Some(app_data) = non_empty_os_var("APPDATA") {
554 return PathBuf::from(app_data);
555 }
556 if let Some(user_profile) = non_empty_os_var("USERPROFILE") {
557 return PathBuf::from(user_profile).join("AppData").join("Roaming");
558 }
559 }
560
561 if let Some(home) = non_empty_os_var("HOME") {
562 return PathBuf::from(home).join(".config");
563 }
564
565 PathBuf::from(".config")
566}
567
568pub fn load(path: impl AsRef<Path>) -> Result<Option<DaemonConfig>, DaemonConfigError> {
569 let path = path.as_ref();
570 let Some(doc) = read_config_doc(path)? else {
571 return Ok(None);
572 };
573 parse_doc(&doc, path).map(Some)
574}
575
576pub fn load_with_activity(
580 path: impl AsRef<Path>,
581) -> Result<Option<(DaemonConfig, ActivityConfig)>, DaemonConfigError> {
582 let path = path.as_ref();
583 let Some(doc) = read_config_doc(path)? else {
584 return Ok(None);
585 };
586 parse_doc_with_activity(&doc, path).map(Some)
587}
588
589pub fn parse_with_activity(
594 doc: &str,
595 path: impl AsRef<Path>,
596) -> Result<(DaemonConfig, ActivityConfig), DaemonConfigError> {
597 parse_doc_with_activity(doc, path.as_ref())
598}
599
600pub fn load_logging(path: impl AsRef<Path>) -> Result<Option<LoggingConfig>, DaemonConfigError> {
606 let path = path.as_ref();
607 let Some(doc) = read_config_doc(path)? else {
608 return Ok(None);
609 };
610 let json = jsonc_to_json(&doc).map_err(|message| DaemonConfigError::InvalidJsonc {
611 path: path.to_path_buf(),
612 message,
613 })?;
614 let raw: RawDaemonConfig =
615 serde_json::from_str(&json).map_err(|source| DaemonConfigError::InvalidJson {
616 path: path.to_path_buf(),
617 source,
618 })?;
619 if raw.version != SUPPORTED_CONFIG_VERSION {
620 return Err(DaemonConfigError::UnsupportedVersion {
621 path: path.to_path_buf(),
622 version: raw.version,
623 });
624 }
625 raw.log
626 .map(|log| parse_logging_config(log, path, "daemon log"))
627 .transpose()
628}
629
630pub fn ensure_daemon_run_dir_private() -> Result<PathBuf, io::Error> {
656 let path = daemon_run_dir()
657 .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error.to_string()))?;
658 ensure_directory_private(&path)?;
659 Ok(path)
660}
661
662#[cfg(unix)]
667fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
668 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
669
670 if !path.exists() {
671 fs::DirBuilder::new()
672 .recursive(true)
673 .mode(0o700)
674 .create(path)?;
675 return Ok(());
676 }
677 let mode = fs::metadata(path)?.permissions().mode() & 0o777;
678 if mode & 0o077 != 0 {
679 fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
680 }
681 Ok(())
682}
683
684#[cfg(windows)]
687fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
688 subc_os::windows_acl::create_private_dir(path)
689}
690
691#[cfg(not(any(unix, windows)))]
692fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
693 if !path.exists() {
694 fs::create_dir_all(path)?;
695 }
696 Ok(())
697}
698
699pub fn daemon_run_dir() -> Result<PathBuf, DaemonRunDirError> {
709 daemon_run_dir_from(default_data_home())
710}
711
712fn daemon_run_dir_from(data_home: PathBuf) -> Result<PathBuf, DaemonRunDirError> {
715 if !data_home.is_absolute() {
716 return Err(DaemonRunDirError::RelativeDataHome { data_home });
717 }
718 Ok(data_home.join("cortexkit").join("run"))
719}
720
721#[derive(Debug, Clone, PartialEq, Eq)]
723pub enum DaemonRunDirError {
724 RelativeDataHome { data_home: PathBuf },
727}
728
729impl fmt::Display for DaemonRunDirError {
730 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
731 match self {
732 Self::RelativeDataHome { data_home } => write!(
733 f,
734 "cannot resolve the daemon run directory: the data home `{}` is relative, \
735 so it would land under the current working directory; {}",
736 data_home.display(),
737 DATA_HOME_REMEDY
738 ),
739 }
740 }
741}
742
743impl std::error::Error for DaemonRunDirError {}
744
745#[cfg(windows)]
747const DATA_HOME_REMEDY: &str =
748 "set XDG_DATA_HOME to an absolute path, or set APPDATA, USERPROFILE or HOME";
749#[cfg(not(windows))]
750const DATA_HOME_REMEDY: &str = "set XDG_DATA_HOME to an absolute path, or set HOME";
751
752fn read_config_doc(path: &Path) -> Result<Option<String>, DaemonConfigError> {
753 match fs::read_to_string(path) {
754 Ok(doc) => Ok(Some(doc)),
755 Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None),
756 Err(source) => Err(DaemonConfigError::Read {
757 path: path.to_path_buf(),
758 source,
759 }),
760 }
761}
762
763fn parse_doc(doc: &str, path: &Path) -> Result<DaemonConfig, DaemonConfigError> {
764 parse_doc_with_activity(doc, path).map(|(config, _)| config)
765}
766
767fn parse_doc_with_activity(
768 doc: &str,
769 path: &Path,
770) -> Result<(DaemonConfig, ActivityConfig), DaemonConfigError> {
771 let json = jsonc_to_json(doc).map_err(|message| DaemonConfigError::InvalidJsonc {
772 path: path.to_path_buf(),
773 message,
774 })?;
775 let raw: RawDaemonConfig =
776 serde_json::from_str(&json).map_err(|source| DaemonConfigError::InvalidJson {
777 path: path.to_path_buf(),
778 source,
779 })?;
780
781 if raw.version != SUPPORTED_CONFIG_VERSION {
782 return Err(DaemonConfigError::UnsupportedVersion {
783 path: path.to_path_buf(),
784 version: raw.version,
785 });
786 }
787
788 let daemon_logging = raw
789 .log
790 .map(|log| parse_logging_config(log, path, "daemon log"))
791 .transpose()?;
792 let default_drain_timeout_ms = raw.drain_timeout_ms;
793 let default_route_bind_relay_timeout_ms = match raw.route_bind_relay_timeout_ms {
799 Some(0) => {
800 return Err(DaemonConfigError::InvalidValue {
801 path: path.to_path_buf(),
802 message: ROUTE_BIND_RELAY_ZERO_MESSAGE.to_string(),
803 });
804 }
805 Some(value) => Some(value),
806 None => None,
807 };
808 let modules = raw
809 .modules
810 .into_iter()
811 .map(|(module_id, module)| {
812 let protocol = parse_module_protocol(module.protocol.as_deref(), path, &module_id)?;
813 let health = module
814 .health
815 .map(|health| parse_health_config(health, path, &module_id, protocol))
816 .transpose()?
817 .unwrap_or_default();
818 if let Err(reason) = crate::registry::module_id_path_hazard(&module_id) {
819 return Err(DaemonConfigError::InvalidValue {
820 path: path.to_path_buf(),
821 message: format!(
822 "module id '{}' is not usable as a path component ({reason}): \
823 the daemon derives each module's store path from its id",
824 module_id.escape_debug()
825 ),
826 });
827 }
828 let per_module_route_bind_relay_timeout_ms = match module.route_bind_relay_timeout_ms {
833 Some(0) => {
834 return Err(DaemonConfigError::InvalidValue {
835 path: path.to_path_buf(),
836 message: format!(
837 "module '{module_id}' {ROUTE_BIND_RELAY_ZERO_MESSAGE}",
838 module_id = module_id.escape_debug()
839 ),
840 });
841 }
842 Some(value) => Some(value),
843 None => default_route_bind_relay_timeout_ms,
844 };
845 if module.ignored.contains_key("launch_nonce_env") {
850 tracing::warn!(
851 module_id = %module_id.escape_debug(),
852 "launch_nonce_env is deprecated and ignored; nonce delivery is determined by the platform"
853 );
854 }
855 let overlap = parse_module_overlap(module.overlap.as_deref(), path, &module_id)?;
856 if module.env.contains_key(SUBC_SPAWN_ROLE_ENV) {
860 return Err(DaemonConfigError::InvalidValue {
861 path: path.to_path_buf(),
862 message: format!(
863 "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",
864 module_id = module_id.escape_debug()
865 ),
866 });
867 }
868 if protocol == ModuleProtocol::None && module.reserved {
875 return Err(DaemonConfigError::InvalidValue {
876 path: path.to_path_buf(),
877 message: format!(
878 "module '{module_id}' sets reserved: true with protocol: \"none\"; \
879 reserved is enforced on the module's HELLO and a protocol: \"none\" \
880 module never registers, so the reservation could never be checked",
881 module_id = module_id.escape_debug()
882 ),
883 });
884 }
885 let restart = parse_restart_config(module.restart, path, &module_id)?;
886 let register_timeout_s = module
887 .register_timeout_s
888 .unwrap_or(crate::supervise::DEFAULT_REGISTER_TIMEOUT.as_secs());
889 if !(10..=3600).contains(®ister_timeout_s) {
890 return Err(DaemonConfigError::InvalidValue {
891 path: path.to_path_buf(),
892 message: format!(
893 "module '{module_id}' register_timeout_s must be an integer from 10 to 3600"
894 ),
895 });
896 }
897 let log = module
898 .log
899 .map(|log| parse_logging_config(log, path, &format!("module '{module_id}' log")))
900 .transpose()?
901 .or_else(|| daemon_logging.clone());
902 Ok(ConfiguredModule {
903 module_id,
904 program: module.program,
905 args: module.args,
906 env: module.env.into_iter().collect(),
907 log,
908 enabled: module.enabled,
909 reserved: module.reserved,
910 reserved_prefixes: module.reserved_prefixes,
911 protocol,
912 overlap,
913 health,
914 drain_timeout_ms: module.drain_timeout_ms.or(default_drain_timeout_ms),
917 register_timeout: Duration::from_secs(register_timeout_s),
918 route_bind_relay_timeout_ms: per_module_route_bind_relay_timeout_ms,
923 restart,
924 })
925 })
926 .collect::<Result<Vec<_>, DaemonConfigError>>()?;
927
928 validate_reserved_prefixes(&modules, path)?;
929 validate_reserved_capabilities(&raw.reserved_capabilities, path)?;
930 validate_admission_facts_config(
931 &modules,
932 raw.admission_facts_carrier_module_id.as_deref(),
933 raw.admission_facts_targets.as_deref(),
934 path,
935 )?;
936 let scope_authority_owners = raw
937 .scope_authority_owners
938 .unwrap_or_else(default_scope_authority_owners);
939 if scope_authority_owners.iter().any(|owner| owner.is_empty()) {
940 return Err(DaemonConfigError::InvalidValue {
941 path: path.to_path_buf(),
942 message: "scope_authority_owners must not contain empty module ids".to_string(),
943 });
944 }
945
946 let storage = raw
947 .storage
948 .map(|s| match s {
949 RawStorageConfig::Sqlite { data_home } => {
950 let data_home = data_home.unwrap_or_else(default_data_home);
951 if !data_home.is_absolute() {
960 return Err(DaemonConfigError::InvalidValue {
961 path: path.to_path_buf(),
962 message: format!(
963 "storage data home resolved to the relative path {} \
964 (no absolute XDG_DATA_HOME, APPDATA, USERPROFILE, or HOME \
965 in the daemon's environment); refusing to serve a \
966 cwd-relative storage descriptor to modules. Set \
967 XDG_DATA_HOME or HOME to an absolute path, or set \
968 storage.data_home in this file.",
969 data_home.display()
970 ),
971 });
972 }
973 Ok(StorageConfig::Sqlite { data_home })
974 }
975 })
976 .transpose()?;
977
978 if raw.activity.max_age_days == 0 || raw.activity.max_total_mb == 0 {
979 return Err(DaemonConfigError::InvalidValue {
980 path: path.to_path_buf(),
981 message: "activity.max_age_days and activity.max_total_mb must be positive".into(),
982 });
983 }
984 Ok((
985 DaemonConfig {
986 path: path.to_path_buf(),
987 port: raw.port,
988 privileged_operator_prompt: raw.privileged_operator_prompt,
989 drain_timeout_ms: default_drain_timeout_ms,
990 route_bind_relay_timeout_ms: default_route_bind_relay_timeout_ms,
991 modules,
992 storage,
993 admission_facts_carrier_module_id: raw.admission_facts_carrier_module_id,
994 admission_facts_targets: raw.admission_facts_targets,
995 scope_authority_owners,
996 reserved_capabilities: raw.reserved_capabilities,
997 },
998 raw.activity,
999 ))
1000}
1001
1002fn parse_logging_config(
1003 raw: RawLoggingConfig,
1004 path: &Path,
1005 owner: &str,
1006) -> Result<LoggingConfig, DaemonConfigError> {
1007 fn valid_level(level: &str) -> bool {
1008 matches!(level, "off" | "error" | "warn" | "info" | "debug" | "trace")
1009 }
1010
1011 let level = raw.level.unwrap_or_else(|| "info".to_string());
1012 if !valid_level(&level) {
1013 return Err(DaemonConfigError::InvalidValue {
1014 path: path.to_path_buf(),
1015 message: format!(
1016 "{owner}.level must be one of off, error, warn, info, debug, trace; got {level:?}"
1017 ),
1018 });
1019 }
1020 for (tag, tag_level) in &raw.tags {
1021 let well_formed = !tag.is_empty()
1026 && tag.split('.').all(|segment| {
1027 let mut chars = segment.chars();
1028 matches!(chars.next(), Some('a'..='z'))
1029 && chars.all(|c| matches!(c, 'a'..='z' | '0'..='9' | '-'))
1030 });
1031 if !well_formed {
1032 return Err(DaemonConfigError::InvalidValue {
1033 path: path.to_path_buf(),
1034 message: format!(
1035 "{owner}.tags key {tag:?} is not a logger name (dotted segments of [a-z][a-z0-9-]*)"
1036 ),
1037 });
1038 }
1039 if !valid_level(tag_level) {
1040 return Err(DaemonConfigError::InvalidValue {
1041 path: path.to_path_buf(),
1042 message: format!(
1043 "{owner}.tags.{tag} must be one of off, error, warn, info, debug, trace; got {tag_level:?}"
1044 ),
1045 });
1046 }
1047 }
1048
1049 let defaults = Retention::default();
1050 let retention = Retention {
1051 max_file_mb: raw.max_file_mb.unwrap_or(defaults.max_file_mb),
1052 keep: raw.keep.unwrap_or(defaults.keep),
1053 max_age_days: raw.max_age_days.unwrap_or(defaults.max_age_days),
1054 };
1055 if retention.max_file_mb == 0 {
1056 return Err(DaemonConfigError::InvalidValue {
1057 path: path.to_path_buf(),
1058 message: format!("{owner}.max_file_mb must be greater than 0"),
1059 });
1060 }
1061
1062 let alarm_segment_mb = raw
1063 .alarm_segment_mb
1064 .unwrap_or(cortexkit_log::SegmentRetention::default().alarm_segment_mb);
1065 if alarm_segment_mb == 0 {
1066 return Err(DaemonConfigError::InvalidValue {
1067 path: path.to_path_buf(),
1068 message: format!("{owner}.alarm_segment_mb must be greater than 0"),
1069 });
1070 }
1071
1072 Ok(LoggingConfig {
1073 level,
1074 tags: raw.tags,
1075 retention,
1076 alarm_segment_mb,
1077 })
1078}
1079
1080fn parse_module_protocol(
1089 raw: Option<&str>,
1090 path: &Path,
1091 module_id: &str,
1092) -> Result<ModuleProtocol, DaemonConfigError> {
1093 match raw {
1094 None | Some("subc") => Ok(ModuleProtocol::Subc),
1095 Some("none") => Ok(ModuleProtocol::None),
1096 Some(other) => Err(DaemonConfigError::InvalidValue {
1100 path: path.to_path_buf(),
1101 message: format!(
1102 "module '{module_id}' declares protocol {other:?}; supported values are \
1103 \"subc\" (the default when the key is absent) and \"none\"",
1104 module_id = module_id.escape_debug(),
1105 ),
1106 }),
1107 }
1108}
1109
1110fn parse_module_overlap(
1114 raw: Option<&str>,
1115 path: &Path,
1116 module_id: &str,
1117) -> Result<ModuleOverlap, DaemonConfigError> {
1118 match raw {
1119 None | Some("exclusive") => Ok(ModuleOverlap::Exclusive),
1120 Some("safe") => Ok(ModuleOverlap::Safe),
1121 Some(other) => Err(DaemonConfigError::InvalidValue {
1122 path: path.to_path_buf(),
1123 message: format!(
1124 "module '{module_id}' declares overlap {other:?}; supported values are \
1125 \"exclusive\" (the default when the key is absent) and \"safe\"",
1126 module_id = module_id.escape_debug(),
1127 ),
1128 }),
1129 }
1130}
1131
1132fn validate_reserved_capabilities(
1133 bindings: &BTreeMap<String, String>,
1134 path: &Path,
1135) -> Result<(), DaemonConfigError> {
1136 for (capability, module_id) in bindings {
1137 if !is_valid_capability_identifier(capability) {
1138 return Err(DaemonConfigError::InvalidValue {
1139 path: path.to_path_buf(),
1140 message: format!(
1141 "reserved_capabilities key {:?} is not a valid capability identifier",
1142 capability
1143 ),
1144 });
1145 }
1146 if module_id.trim().is_empty() {
1147 return Err(DaemonConfigError::InvalidValue {
1148 path: path.to_path_buf(),
1149 message: format!(
1150 "reserved_capabilities binding for {:?} has an empty module id",
1151 capability
1152 ),
1153 });
1154 }
1155 if let Err(reason) = crate::registry::module_id_path_hazard(module_id) {
1156 return Err(DaemonConfigError::InvalidValue {
1157 path: path.to_path_buf(),
1158 message: format!(
1159 "reserved_capabilities binding for {:?} has an unusable module id {:?}: {reason}",
1160 capability, module_id
1161 ),
1162 });
1163 }
1164 }
1165 Ok(())
1166}
1167
1168fn validate_admission_facts_config(
1169 modules: &[ConfiguredModule],
1170 carrier_module_id: Option<&str>,
1171 targets: Option<&[String]>,
1172 path: &Path,
1173) -> Result<(), DaemonConfigError> {
1174 let Some(carrier_module_id) = carrier_module_id else {
1175 return Ok(());
1176 };
1177
1178 let Some(carrier) = modules
1179 .iter()
1180 .find(|module| module.module_id == carrier_module_id)
1181 else {
1182 return Err(DaemonConfigError::InvalidValue {
1183 path: path.to_path_buf(),
1184 message: format!(
1185 "admission_facts_carrier_module_id '{carrier_module_id}' must name a configured module"
1186 ),
1187 });
1188 };
1189 if !carrier.enabled || !carrier.reserved {
1190 return Err(DaemonConfigError::InvalidValue {
1191 path: path.to_path_buf(),
1192 message: format!(
1193 "admission_facts_carrier_module_id '{carrier_module_id}' must name an enabled reserved module"
1194 ),
1195 });
1196 }
1197
1198 let Some(targets) = targets else {
1199 return Err(DaemonConfigError::InvalidValue {
1200 path: path.to_path_buf(),
1201 message: "admission_facts_targets must be present when an admission facts carrier is configured".to_string(),
1202 });
1203 };
1204 if targets.is_empty() || targets.iter().any(String::is_empty) {
1205 return Err(DaemonConfigError::InvalidValue {
1206 path: path.to_path_buf(),
1207 message:
1208 "admission_facts_targets must be non-empty and must not contain empty module ids"
1209 .to_string(),
1210 });
1211 }
1212
1213 Ok(())
1214}
1215
1216fn default_enabled() -> bool {
1217 true
1218}
1219
1220fn validate_reserved_prefixes(
1221 modules: &[ConfiguredModule],
1222 path: &Path,
1223) -> Result<(), DaemonConfigError> {
1224 for module in modules {
1225 if module.reserved_prefixes.is_empty() {
1226 continue;
1227 }
1228 if !module.reserved {
1229 return Err(DaemonConfigError::InvalidValue {
1230 path: path.to_path_buf(),
1231 message: format!(
1232 "module '{}' reserved_prefixes require reserved=true so the owner is spawn-nonce protected",
1233 module.module_id
1234 ),
1235 });
1236 }
1237 for prefix in &module.reserved_prefixes {
1238 if !prefix.ends_with(':') {
1239 return Err(DaemonConfigError::InvalidValue {
1240 path: path.to_path_buf(),
1241 message: format!(
1242 "module '{}' reserved prefix '{}' must end with ':'",
1243 module.module_id, prefix
1244 ),
1245 });
1246 }
1247 }
1248 }
1249
1250 for module in modules {
1251 for prefix in &module.reserved_prefixes {
1252 if let Some(colliding) = modules
1253 .iter()
1254 .find(|candidate| candidate.module_id.starts_with(prefix))
1255 {
1256 return Err(DaemonConfigError::InvalidValue {
1257 path: path.to_path_buf(),
1258 message: format!(
1259 "reserved prefix '{}' owned by '{}' collides with configured module id '{}'",
1260 prefix, module.module_id, colliding.module_id
1261 ),
1262 });
1263 }
1264 }
1265 }
1266
1267 for (left_index, left) in modules.iter().enumerate() {
1268 for right in modules.iter().skip(left_index + 1) {
1269 if left.module_id == right.module_id {
1270 continue;
1271 }
1272 for left_prefix in &left.reserved_prefixes {
1273 for right_prefix in &right.reserved_prefixes {
1274 if left_prefix.starts_with(right_prefix)
1275 || right_prefix.starts_with(left_prefix)
1276 {
1277 return Err(DaemonConfigError::InvalidValue {
1278 path: path.to_path_buf(),
1279 message: format!(
1280 "reserved prefixes '{}' owned by '{}' and '{}' owned by '{}' overlap",
1281 left_prefix, left.module_id, right_prefix, right.module_id
1282 ),
1283 });
1284 }
1285 }
1286 }
1287 }
1288 }
1289
1290 Ok(())
1291}
1292
1293fn parse_health_config(
1294 raw: RawHealthConfig,
1295 path: &Path,
1296 module_id: &str,
1297 protocol: ModuleProtocol,
1298) -> Result<HealthConfig, DaemonConfigError> {
1299 if let Some(url) = raw.http.as_deref() {
1300 let reason = if protocol != ModuleProtocol::None {
1301 Some("is valid only for protocol: \"none\" modules".to_string())
1302 } else {
1303 crate::supervise::parse_http_probe_url(url).err()
1304 };
1305 if let Some(reason) = reason {
1306 return Err(DaemonConfigError::InvalidValue {
1307 path: path.to_path_buf(),
1308 message: format!("module '{module_id}' health.http {reason}"),
1309 });
1310 }
1311 }
1312 let defaults = HealthConfig::default();
1313 let cadence = positive_millis(
1314 raw.cadence_ms,
1315 defaults.cadence,
1316 path,
1317 module_id,
1318 "cadence_ms",
1319 )?;
1320 let deadline = positive_millis(
1321 raw.deadline_ms,
1322 defaults.deadline,
1323 path,
1324 module_id,
1325 "deadline_ms",
1326 )?;
1327 let failure_threshold = match raw.failure_threshold {
1328 Some(0) => {
1329 return Err(DaemonConfigError::InvalidValue {
1330 path: path.to_path_buf(),
1331 message: format!("module '{module_id}' health.failure_threshold must be positive"),
1332 })
1333 }
1334 Some(value) => value,
1335 None => defaults.failure_threshold,
1336 };
1337
1338 Ok(HealthConfig {
1339 http: raw.http,
1340 cadence,
1341 deadline,
1342 failure_threshold,
1343 on_degraded: match raw.on_degraded {
1344 Some(RawHealthAction::Restart) => {
1345 return Err(DaemonConfigError::InvalidValue {
1346 path: path.to_path_buf(),
1347 message: format!(
1348 "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)."
1349 ),
1350 });
1351 }
1352 Some(action) => health_action(action),
1353 None => defaults.on_degraded,
1354 },
1355 on_failing: raw
1356 .on_failing
1357 .map(health_action)
1358 .unwrap_or(defaults.on_failing),
1359 critical: raw.critical,
1360 })
1361}
1362
1363fn parse_restart_config(
1370 raw: Option<RawRestartConfig>,
1371 path: &Path,
1372 module_id: &str,
1373) -> Result<RestartPolicy, DaemonConfigError> {
1374 let defaults = RestartPolicy::default();
1375 let Some(raw) = raw else {
1376 return Ok(defaults);
1377 };
1378
1379 let window = match raw.window_secs {
1380 Some(0) => {
1381 return Err(DaemonConfigError::InvalidValue {
1382 path: path.to_path_buf(),
1383 message: format!(
1384 "module '{module_id}' {RESTART_WINDOW_ZERO_MESSAGE}",
1385 module_id = module_id.escape_debug()
1386 ),
1387 });
1388 }
1389 Some(secs) => Duration::from_secs(secs),
1390 None => defaults.window,
1391 };
1392 let backoff = raw
1393 .backoff_ms
1394 .map(Duration::from_millis)
1395 .unwrap_or(defaults.backoff);
1396 let max_backoff = raw
1397 .max_backoff_ms
1398 .map(Duration::from_millis)
1399 .unwrap_or(defaults.max_backoff);
1400 if max_backoff < backoff {
1401 return Err(DaemonConfigError::InvalidValue {
1402 path: path.to_path_buf(),
1403 message: format!(
1404 "module '{}' restart.max_backoff_ms must be greater than or equal to restart.backoff_ms (max_backoff_ms={max_backoff:?}, backoff_ms={backoff:?})",
1405 module_id.escape_debug()
1406 ),
1407 });
1408 }
1409
1410 Ok(RestartPolicy {
1411 max_restarts: raw.max_restarts.unwrap_or(defaults.max_restarts),
1414 backoff,
1415 max_backoff,
1416 window,
1417 })
1418}
1419
1420fn positive_millis(
1421 value: Option<u64>,
1422 default: std::time::Duration,
1423 path: &Path,
1424 module_id: &str,
1425 field: &str,
1426) -> Result<std::time::Duration, DaemonConfigError> {
1427 match value {
1428 Some(0) => Err(DaemonConfigError::InvalidValue {
1429 path: path.to_path_buf(),
1430 message: format!("module '{module_id}' health.{field} must be positive"),
1431 }),
1432 Some(value) => Ok(std::time::Duration::from_millis(value)),
1433 None => Ok(default),
1434 }
1435}
1436
1437fn health_action(action: RawHealthAction) -> HealthAction {
1438 match action {
1439 RawHealthAction::Report => HealthAction::Report,
1440 RawHealthAction::Restart => HealthAction::Restart,
1441 RawHealthAction::Alert => HealthAction::Alert,
1442 }
1443}
1444
1445pub(crate) fn default_data_home() -> PathBuf {
1448 if let Some(data_home) = non_empty_os_var("XDG_DATA_HOME") {
1449 return PathBuf::from(data_home);
1450 }
1451
1452 #[cfg(windows)]
1453 {
1454 if let Some(app_data) = non_empty_os_var("APPDATA") {
1455 return PathBuf::from(app_data);
1456 }
1457 if let Some(user_profile) = non_empty_os_var("USERPROFILE") {
1458 return PathBuf::from(user_profile).join("AppData").join("Roaming");
1459 }
1460 }
1461
1462 if let Some(home) = non_empty_os_var("HOME") {
1463 return PathBuf::from(home).join(".local").join("share");
1464 }
1465
1466 PathBuf::from(".local").join("share")
1467}
1468
1469fn non_empty_os_var(key: &str) -> Option<OsString> {
1470 let value = env::var_os(key)?;
1471 if value.is_empty() {
1472 None
1473 } else {
1474 Some(value)
1475 }
1476}
1477
1478impl fmt::Display for DaemonConfigError {
1479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1480 match self {
1481 Self::Read { path, source } => {
1482 write!(f, "failed to read daemon config {}: {source}", path.display())
1483 }
1484 Self::InvalidJsonc { path, message } => {
1485 write!(f, "invalid JSONC in daemon config {}: {message}", path.display())
1486 }
1487 Self::InvalidJson { path, source } => {
1488 write!(f, "invalid daemon config {}: {source}", path.display())
1489 }
1490 Self::UnsupportedVersion { path, version } => write!(
1491 f,
1492 "invalid daemon config {}: version {version} is unsupported (expected {SUPPORTED_CONFIG_VERSION})",
1493 path.display()
1494 ),
1495 Self::InvalidValue { path, message } => {
1496 write!(f, "invalid daemon config {}: {message}", path.display())
1497 }
1498 }
1499 }
1500}
1501
1502impl Error for DaemonConfigError {
1503 fn source(&self) -> Option<&(dyn Error + 'static)> {
1504 match self {
1505 Self::Read { source, .. } => Some(source),
1506 Self::InvalidJson { source, .. } => Some(source),
1507 Self::InvalidJsonc { .. }
1508 | Self::UnsupportedVersion { .. }
1509 | Self::InvalidValue { .. } => None,
1510 }
1511 }
1512}
1513
1514#[cfg(all(test, windows))]
1515mod windows_run_dir_privacy_tests {
1516 use super::ensure_directory_private;
1517 use cortexkit_test_support::ScratchDir;
1518 use subc_os::windows_acl::test_support::{
1519 assert_dacl_owner_only, assert_owner_only, grant_everyone,
1520 };
1521
1522 #[test]
1523 fn windows_run_dir_has_exact_protected_dacl_at_creation() {
1524 let root = ScratchDir::new("windows-run-dir-create");
1525 grant_everyone(root.path());
1526 let path = root.join("run");
1527 ensure_directory_private(&path).unwrap();
1528 assert_owner_only(&path, true, true);
1529 }
1530
1531 #[test]
1532 fn windows_run_dir_narrows_existing_inherited_descendants() {
1533 let root = ScratchDir::new("windows-run-dir-existing");
1534 grant_everyone(root.path());
1535 let path = root.join("run");
1536 std::fs::create_dir(&path).unwrap();
1537 let child = path.join("old.log");
1538 std::fs::write(&child, b"old log").unwrap();
1539 ensure_directory_private(&path).unwrap();
1540 assert_dacl_owner_only(&path, true, true);
1543 assert_dacl_owner_only(&child, false, false);
1544 }
1545}
1546
1547#[cfg(all(test, unix))]
1548mod run_dir_privacy_tests {
1549 use cortexkit_test_support::ScratchDir;
1550 use std::fs;
1551 use std::os::unix::fs::PermissionsExt;
1552
1553 #[test]
1559 fn run_dir_is_created_private_and_an_inherited_wide_one_is_tightened() {
1560 let temp = ScratchDir::new("subc-run-dir-privacy");
1561 let created = temp.path().join("cortexkit").join("run");
1562 super::ensure_directory_private(&created).expect("create run dir");
1563 let mode = fs::metadata(&created)
1564 .expect("stat created")
1565 .permissions()
1566 .mode()
1567 & 0o777;
1568 assert_eq!(
1569 mode, 0o700,
1570 "observable a run directory this code creates must be 0700, got {mode:o}"
1571 );
1572
1573 fs::set_permissions(&created, fs::Permissions::from_mode(0o755)).expect("widen");
1575 let widened = fs::metadata(&created)
1576 .expect("stat widened")
1577 .permissions()
1578 .mode()
1579 & 0o777;
1580 assert_eq!(
1581 widened, 0o755,
1582 "observable the fixture must actually be wide before the tighten"
1583 );
1584
1585 super::ensure_directory_private(&created).expect("tighten run dir");
1586 let mode = fs::metadata(&created)
1587 .expect("stat tightened")
1588 .permissions()
1589 .mode()
1590 & 0o777;
1591 assert_eq!(
1592 mode, 0o700,
1593 "observable an inherited group- or world-readable run directory must be tightened to 0700, got {mode:o}"
1594 );
1595 }
1596}
1597
1598#[cfg(test)]
1599mod tests {
1600 use super::*;
1601
1602 static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1611
1612 fn abs(posix: &str) -> PathBuf {
1617 if cfg!(windows) {
1618 PathBuf::from(format!("C:{}", posix.replace('/', "\\")))
1619 } else {
1620 PathBuf::from(posix)
1621 }
1622 }
1623
1624 #[test]
1625 fn default_data_home_matches_golden_fixture() {
1626 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1627 let doc: serde_json::Value =
1628 serde_json::from_str(include_str!("../tests/golden/data_home_resolution.json"))
1629 .expect("golden parses");
1630 let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1631 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1632 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1633 let platform_matches =
1634 |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1635
1636 let mut ran = 0usize;
1637 for case in doc["cases"].as_array().expect("cases array") {
1638 let name = case["name"].as_str().expect("name");
1639 if !platform_matches(case["platform"].as_str().expect("platform")) {
1640 continue;
1641 }
1642 for v in vars {
1643 env::remove_var(v);
1644 }
1645 for (k, v) in case["env"].as_object().expect("env map") {
1646 env::set_var(k, v.as_str().expect("env value"));
1647 }
1648 let got = default_data_home();
1649 assert_eq!(
1650 got.to_string_lossy(),
1651 case["expect"].as_str().expect("expect"),
1652 "golden case '{name}' diverged"
1653 );
1654 ran += 1;
1655 }
1656 assert!(
1658 ran >= 6,
1659 "only {ran} golden cases ran; fixture or filter broken"
1660 );
1661
1662 for (k, v) in saved {
1663 match v {
1664 Some(val) => env::set_var(k, val),
1665 None => env::remove_var(k),
1666 }
1667 }
1668 }
1669
1670 #[test]
1675 fn daemon_run_dir_refuses_a_relative_data_home_and_names_the_variables() {
1676 for data_home in [PathBuf::from(".local/share"), PathBuf::from("relative-xdg")] {
1677 let error = daemon_run_dir_from(data_home.clone())
1678 .expect_err("a relative data home must be refused");
1679 assert_eq!(
1680 error,
1681 DaemonRunDirError::RelativeDataHome {
1682 data_home: data_home.clone()
1683 }
1684 );
1685 let message = error.to_string();
1686 assert!(
1687 message.contains("XDG_DATA_HOME") && message.contains("HOME"),
1688 "the refusal must name the variables to set: {message}"
1689 );
1690 }
1691 }
1692
1693 #[test]
1694 fn daemon_run_dir_under_an_absolute_data_home_is_cortexkit_run() {
1695 let data_home = env::temp_dir().join("subc-run-dir-probe").join("data");
1696 assert!(data_home.is_absolute());
1697 assert_eq!(
1698 daemon_run_dir_from(data_home.clone()),
1699 Ok(data_home.join("cortexkit").join("run"))
1700 );
1701 }
1702
1703 #[test]
1709 fn default_config_home_matches_golden_fixture() {
1710 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1711 let doc: serde_json::Value =
1712 serde_json::from_str(include_str!("../tests/golden/config_home_resolution.json"))
1713 .expect("golden parses");
1714 let vars = ["XDG_CONFIG_HOME", "APPDATA", "USERPROFILE", "HOME"];
1715 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1716 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1717 let platform_matches =
1718 |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1719
1720 let mut ran = 0usize;
1721 for case in doc["cases"].as_array().expect("cases array") {
1722 let name = case["name"].as_str().expect("name");
1723 if !platform_matches(case["platform"].as_str().expect("platform")) {
1724 continue;
1725 }
1726 for v in vars {
1727 env::remove_var(v);
1728 }
1729 for (k, v) in case["env"].as_object().expect("env map") {
1730 env::set_var(k, v.as_str().expect("env value"));
1731 }
1732 let got = default_config_home();
1733 assert_eq!(
1734 got.to_string_lossy(),
1735 case["expect"].as_str().expect("expect"),
1736 "golden case '{name}' diverged"
1737 );
1738 ran += 1;
1739 }
1740 assert!(
1741 ran >= 6,
1742 "only {ran} golden cases ran; fixture or filter broken"
1743 );
1744
1745 for (k, v) in saved {
1746 match v {
1747 Some(val) => env::set_var(k, val),
1748 None => env::remove_var(k),
1749 }
1750 }
1751 }
1752
1753 #[test]
1760 fn relative_storage_data_home_is_refused_at_parse() {
1761 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1762 let path = Path::new("/golden/subc.jsonc");
1763
1764 let doc =
1766 r#"{ "version": 1, "storage": { "backend": "sqlite", "data_home": "relative/home" } }"#;
1767 let err = parse_doc(doc, path).expect_err("relative data_home must refuse");
1768 assert!(
1769 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1770 if message.contains("relative path relative/home")),
1771 "wrong refusal: {err:?}"
1772 );
1773
1774 let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1776 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1777 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1778 for v in vars {
1779 env::remove_var(v);
1780 }
1781 let doc = r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#;
1782 let err = parse_doc(doc, path).expect_err("no home in env must refuse");
1783 assert!(
1784 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1785 if message.contains("no absolute XDG_DATA_HOME")),
1786 "wrong refusal: {err:?}"
1787 );
1788
1789 let want = abs("/abs/home");
1793 let doc = format!(
1794 r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
1795 serde_json::to_string(&want).expect("json path")
1796 );
1797 let cfg = parse_doc(&doc, path).expect("absolute data_home parses");
1798 assert!(matches!(
1799 cfg.storage,
1800 Some(StorageConfig::Sqlite { ref data_home }) if *data_home == want
1801 ));
1802
1803 for (k, v) in saved {
1804 match v {
1805 Some(val) => env::set_var(k, val),
1806 None => env::remove_var(k),
1807 }
1808 }
1809 }
1810
1811 #[test]
1812 fn restart_required_sections_are_the_rescan_cannot_apply_set() {
1813 assert_eq!(
1814 RestartRequiredSection::ALL.map(RestartRequiredSection::label),
1815 [
1816 "port",
1817 "storage",
1818 "admission_facts_carrier_module_id",
1819 "admission_facts_targets",
1820 "scope_authority_owners",
1821 "privileged_operator_prompt",
1822 ]
1823 );
1824 }
1825
1826 #[test]
1827 fn privileged_operator_prompt_defaults_to_log_and_accepts_both_modes() {
1828 let path = Path::new("/tmp/subc.jsonc");
1829 let config = parse_doc(r#"{"version":1}"#, path).unwrap();
1830 assert_eq!(
1831 config.privileged_operator_prompt,
1832 PrivilegedOperatorPrompt::Log
1833 );
1834 for (value, expected) in [
1835 ("log", PrivilegedOperatorPrompt::Log),
1836 ("enforce", PrivilegedOperatorPrompt::Enforce),
1837 ] {
1838 let config = parse_doc(
1839 &format!(r#"{{"version":1,"privileged_operator_prompt":"{value}"}}"#),
1840 path,
1841 )
1842 .unwrap();
1843 assert_eq!(config.privileged_operator_prompt, expected);
1844 }
1845 }
1846
1847 #[test]
1848 fn privileged_operator_prompt_refuses_unknown_values_and_wrong_types() {
1849 let path = Path::new("/tmp/subc.jsonc");
1850 for value in [r#""unknown""#, r#""Enforce""#, "null", "true", "1", "{}"] {
1851 let error = parse_doc(
1852 &format!(r#"{{"version":1,"privileged_operator_prompt":{value}}}"#),
1853 path,
1854 )
1855 .unwrap_err();
1856 assert!(matches!(error, DaemonConfigError::InvalidJson { .. }));
1857 }
1858 }
1859
1860 #[test]
1861 fn scope_authority_owners_defaults_to_the_session_runtime() {
1862 let config = parse_doc(r#"{ "version": 1 }"#, Path::new("/tmp/subc.jsonc")).unwrap();
1863 assert_eq!(config.scope_authority_owners, vec!["prefrontal-core"]);
1864 }
1865
1866 #[test]
1867 fn scope_authority_owners_is_read_when_set_and_refuses_an_empty_id() {
1868 let config = parse_doc(
1869 r#"{ "version": 1, "scope_authority_owners": ["a", "b"] }"#,
1870 Path::new("/tmp/subc.jsonc"),
1871 )
1872 .unwrap();
1873 assert_eq!(config.scope_authority_owners, vec!["a", "b"]);
1874 let config = parse_doc(
1877 r#"{ "version": 1, "scope_authority_owners": [] }"#,
1878 Path::new("/tmp/subc.jsonc"),
1879 )
1880 .unwrap();
1881 assert!(config.scope_authority_owners.is_empty());
1882 let error = parse_doc(
1883 r#"{ "version": 1, "scope_authority_owners": [""] }"#,
1884 Path::new("/tmp/subc.jsonc"),
1885 )
1886 .expect_err("an empty module id is refused");
1887 assert!(
1888 error.to_string().contains("scope_authority_owners"),
1889 "{error}"
1890 );
1891 }
1892
1893 #[test]
1894 fn no_storage_section_yields_none() {
1895 let config = parse_doc(
1896 r#"{ "version": 1, "modules": {} }"#,
1897 Path::new("/tmp/subc.jsonc"),
1898 )
1899 .expect("parse");
1900 assert_eq!(config.storage, None);
1901 }
1902
1903 #[test]
1904 fn sqlite_storage_parses_with_explicit_data_home() {
1905 let config = parse_doc(
1906 &format!(
1907 r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
1908 serde_json::to_string(&abs("/data")).expect("json path")
1909 ),
1910 Path::new("/tmp/subc.jsonc"),
1911 )
1912 .expect("parse");
1913 assert_eq!(
1914 config.storage,
1915 Some(StorageConfig::Sqlite {
1916 data_home: abs("/data")
1917 })
1918 );
1919 }
1920
1921 #[test]
1922 fn sqlite_storage_defaults_data_home_when_omitted() {
1923 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1929 std::env::set_var("XDG_DATA_HOME", abs("/forced/data/home"));
1930 let config = parse_doc(
1931 r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#,
1932 Path::new("/tmp/subc.jsonc"),
1933 )
1934 .expect("parse");
1935 std::env::remove_var("XDG_DATA_HOME");
1936 assert_eq!(
1937 config.storage,
1938 Some(StorageConfig::Sqlite {
1939 data_home: abs("/forced/data/home")
1940 })
1941 );
1942 }
1943
1944 #[test]
1945 fn descriptor_for_matches_store_types_shape() {
1946 let cfg = StorageConfig::Sqlite {
1950 data_home: PathBuf::from("/data"),
1951 };
1952 let descriptor = cfg.descriptor_for("alfonso-routing");
1953 assert_eq!(
1954 descriptor,
1955 serde_json::json!({
1956 "module_id": "alfonso-routing",
1957 "storage_namespace": "default",
1958 "isolation": { "kind": "module" },
1959 "backend": {
1960 "backend": "sqlite",
1961 "path": "/data/cortexkit/alfonso-routing/store.db"
1962 }
1963 })
1964 );
1965 }
1966
1967 #[test]
1968 fn path_hazard_module_id_refuses_config_parse() {
1969 let path = Path::new("/tmp/subc.jsonc");
1970 let err = parse_doc(
1971 r#"{ "version": 1, "modules": { "../escape": { "program": "x" } } }"#,
1972 path,
1973 )
1974 .expect_err("separator-bearing module id must refuse");
1975 let text = format!("{err}");
1976 assert!(
1977 text.contains("not usable as a path component"),
1978 "refusal must name the hazard: {text}"
1979 );
1980 }
1981
1982 #[test]
1983 fn drain_timeout_resolves_module_over_daemon_over_absent() {
1984 let path = Path::new("/tmp/subc.jsonc");
1985 let config = parse_doc(
1986 r#"
1987 {
1988 "version": 1,
1989 "drain_timeout_ms": 45000,
1990 "modules": {
1991 "fast": { "program": "fast", "drain_timeout_ms": 0 },
1992 "slow": { "program": "slow", "drain_timeout_ms": 120000 },
1993 "inherits": { "program": "inherits" }
1994 }
1995 }
1996 "#,
1997 path,
1998 )
1999 .unwrap();
2000 let by_id = |id: &str| {
2001 config
2002 .modules
2003 .iter()
2004 .find(|m| m.module_id == id)
2005 .unwrap()
2006 .drain_timeout_ms
2007 };
2008 assert_eq!(by_id("fast"), Some(0));
2011 assert_eq!(by_id("slow"), Some(120_000));
2012 assert_eq!(by_id("inherits"), Some(45_000));
2014 assert_eq!(config.drain_timeout_ms, Some(45_000));
2015 }
2016
2017 #[test]
2018 fn drain_timeout_absent_everywhere_stays_none_for_builtin_default() {
2019 let path = Path::new("/tmp/subc.jsonc");
2020 let config = parse_doc(
2021 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2022 path,
2023 )
2024 .unwrap();
2025 assert_eq!(config.modules[0].drain_timeout_ms, None);
2029 assert_eq!(config.drain_timeout_ms, None);
2030 }
2031
2032 #[test]
2033 fn route_bind_relay_timeout_resolves_module_over_daemon_over_absent() {
2034 let path = Path::new("/tmp/subc.jsonc");
2040 let config = parse_doc(
2041 r#"
2042 {
2043 "version": 1,
2044 "route_bind_relay_timeout_ms": 30000,
2045 "modules": {
2046 "tight": { "program": "tight", "route_bind_relay_timeout_ms": 5000 },
2047 "loose": { "program": "loose", "route_bind_relay_timeout_ms": 60000 },
2048 "inherits": { "program": "inherits" }
2049 }
2050 }
2051 "#,
2052 path,
2053 )
2054 .unwrap();
2055 let by_id = |id: &str| {
2056 config
2057 .modules
2058 .iter()
2059 .find(|m| m.module_id == id)
2060 .unwrap()
2061 .route_bind_relay_timeout_ms
2062 };
2063 assert_eq!(by_id("tight"), Some(5_000));
2065 assert_eq!(by_id("loose"), Some(60_000));
2066 assert_eq!(by_id("inherits"), Some(30_000));
2068 assert_eq!(config.route_bind_relay_timeout_ms, Some(30_000));
2069 }
2070
2071 #[test]
2072 fn log_tag_keys_must_be_logger_names_and_the_error_names_the_key() {
2073 let path = Path::new("/tmp/subc.jsonc");
2074 for bad in ["Perf", "a b", "perf.", ".perf", "gc..walk", "a=b"] {
2075 let doc = format!(
2076 r#"{{ "version": 1, "modules": {{ "m": {{ "program": "m", "log": {{ "tags": {{ "{bad}": "debug" }} }} }} }} }}"#
2077 );
2078 let err = parse_doc(&doc, path).expect_err(bad);
2079 let text = format!("{err}");
2080 assert!(
2081 text.contains(&format!("{bad:?}")),
2082 "must name the key: {text}"
2083 );
2084 assert!(
2085 text.contains("logger name"),
2086 "must say what a key is: {text}"
2087 );
2088 }
2089 let ok = parse_doc(
2091 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "tags": { "perf": "debug", "gc.walk": "trace", "m": "error", "a-b": "info" } } } } }"#,
2092 path,
2093 );
2094 assert!(ok.is_ok(), "{ok:?}");
2095 }
2096
2097 #[test]
2098 fn log_filter_spec_prefixes_bare_keys_with_the_module_and_passes_absolute_ones() {
2099 let path = Path::new("/tmp/subc.jsonc");
2100 let config = parse_doc(
2101 r#"{ "version": 1, "modules": { "synapse": { "program": "s", "log": { "level": "warn", "tags": { "perf": "debug", "gc.walk": "trace", "synapse": "error", "other.x": "info" } } } } }"#,
2102 path,
2103 )
2104 .unwrap();
2105 let log = config.modules[0].log.as_ref().unwrap();
2106 assert_eq!(
2108 log.filter_spec("synapse"),
2109 "warn,gc.walk=trace,other.x=info,synapse.perf=debug,synapse=error"
2110 );
2111 }
2112
2113 #[test]
2114 fn log_alarm_segment_mb_defaults_to_the_crate_default_and_refuses_zero() {
2115 let path = Path::new("/tmp/subc.jsonc");
2116 let config = parse_doc(
2117 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "level": "info" } } } }"#,
2118 path,
2119 )
2120 .unwrap();
2121 assert_eq!(
2122 config.modules[0].log.as_ref().unwrap().alarm_segment_mb,
2123 cortexkit_log::SegmentRetention::default().alarm_segment_mb
2124 );
2125 let err = parse_doc(
2126 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "alarm_segment_mb": 0 } } } }"#,
2127 path,
2128 )
2129 .expect_err("zero alarm must refuse");
2130 assert!(format!("{err}").contains("alarm_segment_mb"));
2131 }
2132
2133 #[test]
2134 fn route_bind_relay_timeout_zero_at_daemon_layer_is_refused() {
2135 let path = Path::new("/tmp/subc.jsonc");
2136 let err = parse_doc(
2137 r#"
2138 {
2139 "version": 1,
2140 "route_bind_relay_timeout_ms": 0,
2141 "modules": { "m": { "program": "m" } }
2142 }
2143 "#,
2144 path,
2145 )
2146 .expect_err("a daemon-wide zero budget must refuse parse");
2147 let text = format!("{err}");
2148 assert!(
2149 text.contains("route_bind_relay_timeout_ms"),
2150 "error must name the offending key: {text}"
2151 );
2152 assert!(
2153 text.contains("enabled: false"),
2154 "error must name the remedy (enable false): {text}"
2155 );
2156 }
2157
2158 #[test]
2159 fn route_bind_relay_timeout_zero_at_module_layer_is_refused() {
2160 let path = Path::new("/tmp/subc.jsonc");
2161 let err = parse_doc(
2162 r#"
2163 {
2164 "version": 1,
2165 "modules": {
2166 "good": { "program": "good" },
2167 "broken": { "program": "broken", "route_bind_relay_timeout_ms": 0 }
2168 }
2169 }
2170 "#,
2171 path,
2172 )
2173 .expect_err("a per-module zero budget must refuse parse");
2174 let text = format!("{err}");
2175 assert!(
2176 text.contains("route_bind_relay_timeout_ms"),
2177 "error must name the offending key: {text}"
2178 );
2179 assert!(
2180 text.contains("broken"),
2181 "error must name the offending module id: {text}"
2182 );
2183 assert!(
2184 text.contains("enabled: false"),
2185 "error must name the remedy (enable false): {text}"
2186 );
2187 }
2188
2189 #[test]
2190 fn drain_timeout_zero_still_parses_for_wedge_bounces() {
2191 let path = Path::new("/tmp/subc.jsonc");
2197 let config = parse_doc(
2198 r#"
2199 {
2200 "version": 1,
2201 "drain_timeout_ms": 0,
2202 "modules": {
2203 "wedge": { "program": "wedge", "drain_timeout_ms": 0 }
2204 }
2205 }
2206 "#,
2207 path,
2208 )
2209 .expect("drain_timeout_ms: 0 must still parse; wedge-bounce uses it");
2210 let wedge = config
2211 .modules
2212 .iter()
2213 .find(|m| m.module_id == "wedge")
2214 .unwrap();
2215 assert_eq!(wedge.drain_timeout_ms, Some(0));
2216 assert_eq!(config.drain_timeout_ms, Some(0));
2217 }
2218
2219 #[test]
2220 fn route_bind_relay_timeout_absent_everywhere_stays_none_for_builtin_default() {
2221 let path = Path::new("/tmp/subc.jsonc");
2226 let config = parse_doc(
2227 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2228 path,
2229 )
2230 .unwrap();
2231 assert_eq!(config.modules[0].route_bind_relay_timeout_ms, None);
2232 assert_eq!(config.route_bind_relay_timeout_ms, None);
2233 }
2234
2235 #[test]
2241 fn a_config_without_a_restart_block_keeps_the_supervisor_defaults() {
2242 let path = Path::new("/tmp/subc.jsonc");
2243 let config = parse_doc(
2244 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2245 path,
2246 )
2247 .unwrap();
2248 assert_eq!(config.modules[0].restart.max_restarts, 3);
2249 assert_eq!(config.modules[0].restart.window, Duration::from_secs(600));
2250 assert_eq!(
2251 config.modules[0].restart.backoff,
2252 Duration::from_millis(100)
2253 );
2254 assert_eq!(
2255 config.modules[0].restart.max_backoff,
2256 Duration::from_secs(30)
2257 );
2258 }
2259
2260 #[test]
2261 fn register_timeout_config_accepts_bounds_and_rejects_outside_them() {
2262 let path = Path::new("subc.jsonc");
2263 for seconds in [10, 3600] {
2264 let doc = format!(
2265 r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{seconds}}}}}}}"#
2266 );
2267 let config = parse_doc(&doc, path).unwrap();
2268 assert_eq!(
2269 config.modules[0].register_timeout,
2270 Duration::from_secs(seconds)
2271 );
2272 }
2273 for value in ["9", "3601"] {
2274 let doc = format!(
2275 r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{value}}}}}}}"#
2276 );
2277 let error = parse_doc(&doc, path).unwrap_err().to_string();
2278 assert!(error.contains("register_timeout_s"), "{value}: {error}");
2279 }
2280 let config = parse_doc(r#"{"version":1,"modules":{"m":{"program":"m"}}}"#, path).unwrap();
2281 assert_eq!(config.modules[0].register_timeout, Duration::from_secs(120));
2282 }
2283
2284 #[test]
2285 fn a_restart_block_resolves_each_key_independently() {
2286 let path = Path::new("/tmp/subc.jsonc");
2287 let config = parse_doc(
2288 r#"
2289 {
2290 "version": 1,
2291 "modules": {
2292 "all": {
2293 "program": "all",
2294 "restart": { "max_restarts": 5, "window_secs": 60, "backoff_ms": 250, "max_backoff_ms": 5000 }
2295 },
2296 "window-only": {
2297 "program": "window-only",
2298 "restart": { "window_secs": 7200 }
2299 },
2300 "never": {
2301 "program": "never",
2302 "restart": { "max_restarts": 0 }
2303 }
2304 }
2305 }
2306 "#,
2307 path,
2308 )
2309 .unwrap();
2310 let by_id = |id: &str| {
2311 config
2312 .modules
2313 .iter()
2314 .find(|m| m.module_id == id)
2315 .unwrap()
2316 .restart
2317 };
2318
2319 let all = by_id("all");
2320 assert_eq!(all.max_restarts, 5);
2321 assert_eq!(all.window, Duration::from_secs(60));
2322 assert_eq!(all.backoff, Duration::from_millis(250));
2323 assert_eq!(all.max_backoff, Duration::from_secs(5));
2324
2325 let window_only = by_id("window-only");
2328 assert_eq!(window_only.max_restarts, 3);
2329 assert_eq!(window_only.window, Duration::from_secs(7_200));
2330 assert_eq!(window_only.backoff, Duration::from_millis(100));
2331 assert_eq!(window_only.max_backoff, Duration::from_secs(30));
2332
2333 assert_eq!(by_id("never").max_restarts, 0);
2336 }
2337
2338 #[test]
2342 fn restart_window_zero_is_refused_by_name() {
2343 let path = Path::new("/tmp/subc.jsonc");
2344 let err = parse_doc(
2345 r#"
2346 {
2347 "version": 1,
2348 "modules": {
2349 "good": { "program": "good" },
2350 "broken": { "program": "broken", "restart": { "window_secs": 0 } }
2351 }
2352 }
2353 "#,
2354 path,
2355 )
2356 .expect_err("a zero crash window must refuse parse");
2357 assert!(
2358 matches!(err, DaemonConfigError::InvalidValue { .. }),
2359 "a zero window is an invalid value, not a parse failure: {err:?}"
2360 );
2361 let text = format!("{err}");
2362 assert!(
2363 text.contains("restart.window_secs"),
2364 "error must name the offending key: {text}"
2365 );
2366 assert!(
2367 text.contains("broken"),
2368 "error must name the offending module id: {text}"
2369 );
2370 assert!(
2371 text.contains("max_restarts: 0"),
2372 "error must name the setting that actually stops restarts: {text}"
2373 );
2374 }
2375
2376 #[test]
2377 fn restart_max_backoff_below_backoff_is_refused_by_name() {
2378 let path = Path::new("/tmp/subc.jsonc");
2379 let err = parse_doc(
2380 r#"
2381 {
2382 "version": 1,
2383 "modules": {
2384 "broken": {
2385 "program": "broken",
2386 "restart": { "backoff_ms": 1000, "max_backoff_ms": 999 }
2387 }
2388 }
2389 }
2390 "#,
2391 path,
2392 )
2393 .expect_err("a maximum below the base backoff must refuse parse");
2394 assert!(
2395 matches!(err, DaemonConfigError::InvalidValue { .. }),
2396 "an invalid restart bound must be an InvalidValue: {err:?}"
2397 );
2398 let text = format!("{err}");
2399 assert!(
2400 text.contains("restart.max_backoff_ms"),
2401 "error must name max_backoff_ms: {text}"
2402 );
2403 assert!(
2404 text.contains("restart.backoff_ms"),
2405 "error must name backoff_ms: {text}"
2406 );
2407 assert!(
2408 text.contains("broken"),
2409 "error must name the offending module id: {text}"
2410 );
2411 }
2412
2413 #[test]
2414 fn parse_jsonc_defaults_and_ignores_unknown_fields() {
2415 let path = Path::new("/tmp/subc.jsonc");
2416 let config = parse_doc(
2417 r#"
2418 {
2419 // forward-compatible root field
2420 "version": 1,
2421 "unknown": { "ignored": true },
2422 "modules": {
2423 "aft": {
2424 "program": "aft",
2425 "args": ["module",],
2426 "env": { "A": "B", },
2427 "future": 42,
2428 },
2429 "disabled": { "program": "disabled", "enabled": false }
2430 },
2431 }
2432 "#,
2433 path,
2434 )
2435 .unwrap();
2436
2437 assert_eq!(config.port, None);
2438 assert_eq!(config.modules.len(), 2);
2439 assert_eq!(config.modules[0].module_id, "aft");
2440 assert_eq!(config.modules[0].program, PathBuf::from("aft"));
2441 assert_eq!(config.modules[0].args, ["module"]);
2442 assert_eq!(config.modules[0].env, [("A".to_string(), "B".to_string())]);
2443 assert!(config.modules[0].enabled);
2444 assert!(config.modules[0].reserved_prefixes.is_empty());
2445 assert_eq!(config.modules[0].health, HealthConfig::default());
2446 assert!(!config.modules[1].enabled);
2447 }
2448
2449 #[test]
2450 fn reserved_capabilities_accept_unknown_bound_modules_and_refuse_bad_identifiers() {
2451 let path = Path::new("/tmp/subc.jsonc");
2452 let config = parse_doc(
2453 r#"{
2454 "version": 1,
2455 "reserved_capabilities": {
2456 "credentials-provider/v1": "future-vault"
2457 },
2458 "modules": {}
2459 }"#,
2460 path,
2461 )
2462 .expect("a binding may predate its provider installation");
2463 assert_eq!(
2464 config.reserved_capabilities,
2465 BTreeMap::from([(
2466 "credentials-provider/v1".to_string(),
2467 "future-vault".to_string()
2468 )])
2469 );
2470
2471 let error = parse_doc(
2472 r#"{
2473 "version": 1,
2474 "reserved_capabilities": { "Credentials/v1": "vault" },
2475 "modules": {}
2476 }"#,
2477 path,
2478 )
2479 .expect_err("reserved capabilities use the capability identifier grammar");
2480 assert!(error.to_string().contains("reserved_capabilities key"));
2481 }
2482
2483 #[test]
2484 fn retired_launch_nonce_env_is_ignored_for_any_value() {
2485 let parse = |field: &str| {
2486 parse_doc(
2487 &format!(r#"{{"version":1,"modules":{{"probe":{{"program":"probe"{field}}}}}}}"#),
2488 Path::new("subc.jsonc"),
2489 )
2490 .unwrap()
2491 .modules
2492 .remove(0)
2493 .module_spec()
2494 };
2495 for value in ["true", "false", "null", "0", "\"false\"", "[]", "{}"] {
2496 assert_eq!(
2497 parse(""),
2498 parse(&format!(",\"launch_nonce_env\":{value}")),
2499 "the retired key must not change the launch spec or require a restart"
2500 );
2501 }
2502 }
2503
2504 #[test]
2507 fn an_absent_protocol_key_and_an_explicit_subc_are_the_same_module() {
2508 let parse = |module_body: &str| {
2509 parse_doc(
2510 &format!(
2511 r#"{{
2512 "version": 1,
2513 "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2514 }}"#
2515 ),
2516 Path::new("subc.jsonc"),
2517 )
2518 .expect("module parses")
2519 .modules
2520 .remove(0)
2521 };
2522
2523 let absent = parse("");
2524 let explicit = parse(r#", "protocol": "subc""#);
2525 let none = parse(r#", "protocol": "none""#);
2526
2527 assert_eq!(absent.protocol, ModuleProtocol::Subc);
2528 assert_eq!(explicit.protocol, ModuleProtocol::Subc);
2529 assert_eq!(
2530 absent, explicit,
2531 "an absent protocol key must produce exactly the module an explicit subc does"
2532 );
2533 assert_eq!(none.protocol, ModuleProtocol::None);
2534 assert_eq!(none.module_spec().protocol, ModuleProtocol::None);
2538 }
2539
2540 #[test]
2544 fn overlap_defaults_to_exclusive_and_only_safe_opts_in() {
2545 let parse = |module_body: &str| {
2546 parse_doc(
2547 &format!(
2548 r#"{{
2549 "version": 1,
2550 "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2551 }}"#
2552 ),
2553 Path::new("subc.jsonc"),
2554 )
2555 };
2556
2557 let absent = parse("").unwrap().modules.remove(0);
2558 assert_eq!(absent.overlap, ModuleOverlap::Exclusive);
2559 assert_eq!(absent.module_spec().overlap, ModuleOverlap::Exclusive);
2560 let safe = parse(r#", "overlap": "safe""#).unwrap().modules.remove(0);
2561 assert_eq!(safe.module_spec().overlap, ModuleOverlap::Safe);
2562 let typo = parse(r#", "overlap": "sfae""#).expect_err("an unknown overlap is refused");
2563 assert!(typo.to_string().contains("sfae"), "{typo}");
2564 }
2565
2566 #[test]
2570 fn the_spawn_role_is_refused_as_a_configured_env_key() {
2571 let error = parse_doc(
2572 r#"{
2573 "version": 1,
2574 "modules": { "aft": { "program": "aft", "env": { "SUBC_SPAWN_ROLE": "swap_candidate" } } }
2575 }"#,
2576 Path::new("subc.jsonc"),
2577 )
2578 .expect_err("SUBC_SPAWN_ROLE must not be configurable");
2579 assert!(
2580 matches!(error, DaemonConfigError::InvalidValue { .. }),
2581 "expected InvalidValue, got {error:?}"
2582 );
2583 assert!(error.to_string().contains("SUBC_SPAWN_ROLE"), "{error}");
2584 }
2585
2586 #[test]
2592 fn an_unsupported_protocol_value_is_refused_by_name() {
2593 let error = parse_doc(
2594 r#"{
2595 "version": 1,
2596 "modules": { "nats": { "program": "nats-server", "protocol": "grpc" } }
2597 }"#,
2598 Path::new("subc.jsonc"),
2599 )
2600 .expect_err("an unknown protocol must not fall back to a default");
2601
2602 assert!(
2603 matches!(error, DaemonConfigError::InvalidValue { .. }),
2604 "expected InvalidValue, got {error:?}"
2605 );
2606 let message = error.to_string();
2607 assert!(
2608 message.contains("grpc"),
2609 "the refusal must name the offending value: {message}"
2610 );
2611 assert!(
2612 message.contains("nats"),
2613 "the refusal must name the module so it can be found in the file: {message}"
2614 );
2615 }
2616
2617 #[test]
2621 fn reserved_true_with_protocol_none_is_refused_with_the_reason() {
2622 let error = parse_doc(
2623 r#"{
2624 "version": 1,
2625 "modules": {
2626 "nats": { "program": "nats-server", "protocol": "none", "reserved": true }
2627 }
2628 }"#,
2629 Path::new("subc.jsonc"),
2630 )
2631 .expect_err("a reservation that can never be checked must not parse");
2632
2633 assert!(
2634 matches!(error, DaemonConfigError::InvalidValue { .. }),
2635 "expected InvalidValue, got {error:?}"
2636 );
2637 let message = error.to_string();
2638 assert!(
2639 message.contains("nats") && message.contains("reserved"),
2640 "the refusal must name the module and the offending key: {message}"
2641 );
2642 assert!(
2643 message.contains("HELLO") || message.contains("never registers"),
2644 "the refusal must say WHY the pair cannot work: {message}"
2645 );
2646 }
2647
2648 #[test]
2649 fn reserved_prefixes_parse_for_reserved_modules() {
2650 let config = parse_doc(
2651 r#"
2652 {
2653 "version": 1,
2654 "modules": {
2655 "federation": {
2656 "program": "fed",
2657 "reserved": true,
2658 "reserved_prefixes": ["fed:"]
2659 }
2660 }
2661 }
2662 "#,
2663 Path::new("subc.jsonc"),
2664 )
2665 .unwrap();
2666
2667 assert_eq!(config.modules[0].reserved_prefixes, ["fed:".to_string()]);
2668 }
2669
2670 #[test]
2671 fn reserved_prefixes_reject_bad_boundaries_and_owners() {
2672 let missing_delimiter = parse_doc(
2673 r#"{
2674 "version": 1,
2675 "modules": {
2676 "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed"] }
2677 }
2678 }"#,
2679 Path::new("subc.jsonc"),
2680 )
2681 .unwrap_err();
2682 assert!(matches!(
2683 missing_delimiter,
2684 DaemonConfigError::InvalidValue { .. }
2685 ));
2686
2687 let non_reserved_owner = parse_doc(
2688 r#"{
2689 "version": 1,
2690 "modules": {
2691 "federation": { "program": "fed", "reserved_prefixes": ["fed:"] }
2692 }
2693 }"#,
2694 Path::new("subc.jsonc"),
2695 )
2696 .unwrap_err();
2697 assert!(matches!(
2698 non_reserved_owner,
2699 DaemonConfigError::InvalidValue { .. }
2700 ));
2701 }
2702
2703 #[test]
2704 fn reserved_prefixes_reject_cross_owner_overlap_and_exact_id_collisions() {
2705 let overlap = parse_doc(
2706 r#"{
2707 "version": 1,
2708 "modules": {
2709 "fed-owner": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2710 "sub-owner": { "program": "fed-sub", "reserved": true, "reserved_prefixes": ["fed:sub:"] }
2711 }
2712 }"#,
2713 Path::new("subc.jsonc"),
2714 )
2715 .unwrap_err();
2716 assert!(matches!(overlap, DaemonConfigError::InvalidValue { .. }));
2717
2718 let exact_collision = parse_doc(
2719 r#"{
2720 "version": 1,
2721 "modules": {
2722 "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2723 "fed:special": { "program": "special" }
2724 }
2725 }"#,
2726 Path::new("subc.jsonc"),
2727 )
2728 .unwrap_err();
2729 assert!(matches!(
2730 exact_collision,
2731 DaemonConfigError::InvalidValue { .. }
2732 ));
2733 }
2734
2735 #[test]
2736 fn health_config_parses_and_ignores_unknown_fields() {
2737 let config = parse_doc(
2738 r#"
2739 {
2740 "version": 1,
2741 "modules": {
2742 "aft": {
2743 "program": "aft",
2744 "health": {
2745 "cadence_ms": 100,
2746 "deadline_ms": 20,
2747 "failure_threshold": 2,
2748 "on_degraded": "report",
2749 "on_failing": "restart",
2750 "critical": true,
2751 "future": "ignored"
2752 }
2753 }
2754 }
2755 }
2756 "#,
2757 Path::new("subc.jsonc"),
2758 )
2759 .unwrap();
2760
2761 let health = &config.modules[0].health;
2762 assert_eq!(health.cadence, std::time::Duration::from_millis(100));
2763 assert_eq!(health.deadline, std::time::Duration::from_millis(20));
2764 assert_eq!(health.failure_threshold, 2);
2765 assert_eq!(health.on_degraded, HealthAction::Report);
2766 assert_eq!(health.on_failing, HealthAction::Restart);
2767 assert!(health.critical);
2768 }
2769
2770 #[test]
2771 fn http_health_refuses_non_loopback_https_and_wire_modules() {
2772 for (protocol, url) in [
2773 ("none", "http://example.com/healthz"),
2774 ("none", "https://127.0.0.1/healthz"),
2775 ("subc", "http://127.0.0.1/healthz"),
2776 ] {
2777 let doc = serde_json::json!({"version": 1, "modules": {"bus": {
2778 "program": "nats-server", "protocol": protocol, "health": {"http": url}
2779 }}})
2780 .to_string();
2781 let error = parse_doc(&doc, Path::new("test.jsonc"))
2782 .unwrap_err()
2783 .to_string();
2784 assert!(
2785 error.contains("bus") && error.contains("health.http"),
2786 "{error}"
2787 );
2788 }
2789 }
2790
2791 #[test]
2792 fn health_config_rejects_bad_enum_and_non_positive_numbers() {
2793 let bad_enum = parse_doc(
2794 r#"{
2795 "version": 1,
2796 "modules": { "aft": { "program": "aft", "health": { "on_failing": "page" } } }
2797 }"#,
2798 Path::new("subc.jsonc"),
2799 )
2800 .unwrap_err();
2801 assert!(matches!(bad_enum, DaemonConfigError::InvalidJson { .. }));
2802
2803 let zero = parse_doc(
2804 r#"{
2805 "version": 1,
2806 "modules": { "aft": { "program": "aft", "health": { "cadence_ms": 0 } } }
2807 }"#,
2808 Path::new("subc.jsonc"),
2809 )
2810 .unwrap_err();
2811 assert!(matches!(zero, DaemonConfigError::InvalidValue { .. }));
2812 }
2813
2814 #[test]
2815 fn admission_facts_carrier_requires_non_empty_targets() {
2816 let missing_targets = parse_doc(
2817 r#"{
2818 "version": 1,
2819 "admission_facts_carrier_module_id": "fed",
2820 "modules": { "fed": { "program": "fed", "reserved": true } }
2821 }"#,
2822 Path::new("subc.jsonc"),
2823 )
2824 .unwrap_err();
2825 assert!(
2831 matches!(&missing_targets, DaemonConfigError::InvalidValue { message, .. }
2832 if message.contains("must be present")),
2833 "expected the presence rule, got: {missing_targets:?}"
2834 );
2835
2836 let empty_targets = parse_doc(
2837 r#"{
2838 "version": 1,
2839 "admission_facts_carrier_module_id": "fed",
2840 "admission_facts_targets": [""],
2841 "modules": { "fed": { "program": "fed", "reserved": true } }
2842 }"#,
2843 Path::new("subc.jsonc"),
2844 )
2845 .unwrap_err();
2846 assert!(
2847 matches!(&empty_targets, DaemonConfigError::InvalidValue { message, .. }
2848 if message.contains("must be non-empty")),
2849 "expected the non-empty rule, got: {empty_targets:?}"
2850 );
2851 }
2852
2853 #[test]
2854 fn admission_facts_carrier_must_be_enabled_reserved_and_configured() {
2855 for module in [
2856 r#"{ "program": "fed", "enabled": false, "reserved": true }"#,
2857 r#"{ "program": "fed", "enabled": true, "reserved": false }"#,
2858 ] {
2859 let doc = format!(
2860 r#"{{
2861 "version": 1,
2862 "admission_facts_carrier_module_id": "fed",
2863 "admission_facts_targets": ["target"],
2864 "modules": {{ "fed": {module}, "target": {{ "program": "target" }} }}
2865 }}"#
2866 );
2867 let err = parse_doc(&doc, Path::new("subc.jsonc")).unwrap_err();
2868 assert!(
2872 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
2873 if message.contains("enabled reserved module")),
2874 "expected the enabled-and-reserved rule, got: {err:?}"
2875 );
2876 }
2877
2878 let absent = parse_doc(
2879 r#"{
2880 "version": 1,
2881 "admission_facts_carrier_module_id": "missing",
2882 "admission_facts_targets": ["target"],
2883 "modules": { "target": { "program": "target" } }
2884 }"#,
2885 Path::new("subc.jsonc"),
2886 )
2887 .unwrap_err();
2888 assert!(
2889 matches!(&absent, DaemonConfigError::InvalidValue { message, .. }
2890 if message.contains("must name a configured module")),
2891 "expected the configured-module rule, got: {absent:?}"
2892 );
2893 }
2894
2895 #[test]
2896 fn reject_unsupported_version() {
2897 let err = parse_doc(
2898 r#"{ "version": 2, "modules": {} }"#,
2899 Path::new("subc.jsonc"),
2900 )
2901 .unwrap_err();
2902 assert!(matches!(
2903 err,
2904 DaemonConfigError::UnsupportedVersion { version: 2, .. }
2905 ));
2906 }
2907
2908 #[test]
2909 fn reject_unterminated_block_comment() {
2910 let err = parse_doc(r#"{ "version": 1, /*"#, Path::new("subc.jsonc")).unwrap_err();
2911 assert!(matches!(err, DaemonConfigError::InvalidJsonc { .. }));
2912 }
2913}
2914
2915#[cfg(test)]
2916mod activity_config_tests {
2917 use super::*;
2918
2919 #[test]
2920 fn activity_config_defaults_partial_overrides_and_positive_bounds() {
2921 let path = Path::new("subc.jsonc");
2922 let default = parse_doc_with_activity(r#"{"version":1,"modules":{}}"#, path).unwrap();
2923 assert_eq!(
2924 default.1,
2925 ActivityConfig {
2926 max_age_days: 30,
2927 max_total_mb: 64
2928 }
2929 );
2930 let changed = parse_doc_with_activity(
2931 r#"{"version":1,"activity":{"max_age_days":7,"max_total_mb":8}}"#,
2932 path,
2933 )
2934 .unwrap();
2935 assert_eq!(
2936 changed.1,
2937 ActivityConfig {
2938 max_age_days: 7,
2939 max_total_mb: 8
2940 }
2941 );
2942 let partial =
2943 parse_doc_with_activity(r#"{"version":1,"activity":{"max_age_days":7}}"#, path)
2944 .unwrap();
2945 assert_eq!(
2946 partial.1,
2947 ActivityConfig {
2948 max_age_days: 7,
2949 max_total_mb: 64
2950 }
2951 );
2952 for doc in [
2953 r#"{"version":1,"activity":{"max_age_days":0}}"#,
2954 r#"{"version":1,"activity":{"max_total_mb":0}}"#,
2955 ] {
2956 assert!(parse_doc(doc, path).is_err());
2957 }
2958 assert!(!RestartRequiredSection::ALL
2959 .iter()
2960 .any(|section| section.label() == "activity"));
2961 }
2962}