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, ScriptEntry, ScriptRuntime, 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> {
96 vec!["prefrontal-core".to_string(), "prefrontal".to_string()]
97}
98
99pub fn default_federated_scope_owner() -> String {
100 "callosum".to_string()
101}
102
103const 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)";
114
115const 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)";
122
123#[derive(Debug, Clone, PartialEq, Eq)]
130pub struct LoggingConfig {
131 pub level: String,
132 pub tags: BTreeMap<String, String>,
137 pub retention: Retention,
138 pub alarm_segment_mb: u32,
140}
141
142impl LoggingConfig {
143 pub fn filter_spec(&self, module_id: &str) -> String {
152 let mut directives = vec![self.level.clone()];
153 directives.extend(self.tags.iter().map(|(logger, level)| {
154 if logger == module_id || logger.contains('.') {
155 format!("{logger}={level}")
156 } else {
157 format!("{module_id}.{logger}={level}")
158 }
159 }));
160 directives.join(",")
161 }
162
163 pub fn segment_retention(&self) -> cortexkit_log::SegmentRetention {
164 cortexkit_log::SegmentRetention {
165 max_age_days: self.retention.max_age_days,
166 alarm_segment_mb: self.alarm_segment_mb,
167 }
168 }
169}
170
171#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct DaemonConfig {
173 pub path: PathBuf,
174 pub port: Option<u16>,
175 pub privileged_operator_prompt: PrivilegedOperatorPrompt,
177 pub drain_timeout_ms: Option<u64>,
181 pub route_bind_relay_timeout_ms: Option<u64>,
190 pub modules: Vec<ConfiguredModule>,
191 pub storage: Option<StorageConfig>,
194 pub admission_facts_carrier_module_id: Option<String>,
196 pub admission_facts_targets: Option<Vec<String>>,
198 pub scope_authority_owners: Vec<String>,
204 pub federated_scope_owner: String,
206 pub reserved_capabilities: BTreeMap<String, String>,
210 pub(crate) agent_policy_root: crate::policy_root::Section,
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
217pub enum StorageConfig {
218 Sqlite { data_home: PathBuf },
220}
221
222impl StorageConfig {
223 pub fn descriptor_for(&self, module_id: &str) -> serde_json::Value {
249 match self {
250 StorageConfig::Sqlite { data_home } => {
259 let data_home = data_home.to_string_lossy();
260 let path = format!(
261 "{}/cortexkit/{module_id}/store.db",
262 data_home.trim_end_matches('/')
263 );
264 serde_json::json!({
265 "module_id": module_id,
266 "storage_namespace": "default",
267 "isolation": { "kind": "module" },
268 "backend": { "backend": "sqlite", "path": path },
269 })
270 }
271 }
272 }
273}
274
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub struct ConfiguredModule {
277 pub module_id: String,
278 pub program: PathBuf,
279 pub script: Option<ScriptEntry>,
281 pub args: Vec<String>,
282 pub env: Vec<(String, String)>,
283 pub log: Option<LoggingConfig>,
287 pub enabled: bool,
288 pub registration_channel: bool,
291 pub reserved: bool,
297 pub reserved_prefixes: Vec<String>,
301 pub protocol: ModuleProtocol,
304 pub overlap: ModuleOverlap,
307 pub carry_containment: bool,
310 pub health: HealthConfig,
311 pub drain_timeout_ms: Option<u64>,
314 pub register_timeout: Duration,
317 pub route_bind_relay_timeout_ms: Option<u64>,
322 pub restart: RestartPolicy,
334}
335
336impl ConfiguredModule {
337 pub fn module_spec(&self) -> ModuleSpec {
338 let mut env = self.env.clone();
339 if let Some(log) = &self.log {
340 env.retain(|(key, _)| {
341 key != CK_LOG_ENV
342 && key != CAPTURE_MAX_FILE_MB_ENV
343 && key != CAPTURE_KEEP_ENV
344 && key != CAPTURE_MAX_AGE_DAYS_ENV
345 });
346 env.retain(|(key, _)| {
347 key != CHILD_LOG_MAX_AGE_DAYS_ENV && key != CHILD_LOG_ALARM_SEGMENT_MB_ENV
348 });
349 env.push((CK_LOG_ENV.to_string(), log.filter_spec(&self.module_id)));
350 env.push((
351 CHILD_LOG_MAX_AGE_DAYS_ENV.to_string(),
352 log.retention.max_age_days.to_string(),
353 ));
354 env.push((
355 CHILD_LOG_ALARM_SEGMENT_MB_ENV.to_string(),
356 log.alarm_segment_mb.to_string(),
357 ));
358 env.push((
362 CAPTURE_MAX_FILE_MB_ENV.to_string(),
363 log.retention.max_file_mb.to_string(),
364 ));
365 env.push((CAPTURE_KEEP_ENV.to_string(), log.retention.keep.to_string()));
366 env.push((
367 CAPTURE_MAX_AGE_DAYS_ENV.to_string(),
368 log.retention.max_age_days.to_string(),
369 ));
370 }
371 ModuleSpec {
372 script: self.script.clone(),
373 module_id: self.module_id.clone(),
374 program: self.program.clone(),
375 args: self.args.clone(),
376 env,
377 reserved: self.reserved,
378 reserved_prefixes: self.reserved_prefixes.clone(),
379 protocol: self.protocol,
380 overlap: self.overlap,
381 carry_containment: self.carry_containment,
382 }
383 }
384}
385
386#[derive(Debug)]
387pub enum DaemonConfigError {
388 Read {
389 path: PathBuf,
390 source: io::Error,
391 },
392 InvalidJsonc {
393 path: PathBuf,
394 message: String,
395 },
396 InvalidJson {
397 path: PathBuf,
398 source: serde_json::Error,
399 },
400 UnsupportedVersion {
401 path: PathBuf,
402 version: u32,
403 },
404 InvalidValue {
405 path: PathBuf,
406 message: String,
407 },
408}
409
410#[derive(Debug, Deserialize)]
411struct RawDaemonConfig {
412 version: u32,
413 #[serde(default)]
414 activity: ActivityConfig,
415 #[serde(default)]
416 port: Option<u16>,
417 #[serde(default)]
418 privileged_operator_prompt: PrivilegedOperatorPrompt,
419 #[serde(default)]
420 drain_timeout_ms: Option<u64>,
421 #[serde(default)]
422 route_bind_relay_timeout_ms: Option<u64>,
423 #[serde(default)]
424 log: Option<RawLoggingConfig>,
425 #[serde(default)]
426 modules: BTreeMap<String, RawModuleConfig>,
427 #[serde(default)]
428 storage: Option<RawStorageConfig>,
429 #[serde(default)]
430 admission_facts_carrier_module_id: Option<String>,
431 #[serde(default)]
432 admission_facts_targets: Option<Vec<String>>,
433 #[serde(default)]
434 scope_authority_owners: Option<Vec<String>>,
435 #[serde(default = "default_federated_scope_owner")]
436 federated_scope_owner: String,
437 #[serde(default)]
438 reserved_capabilities: BTreeMap<String, String>,
439 #[serde(default, deserialize_with = "crate::policy_root::present_section")]
440 agent_policy_root: Option<serde_json::Value>,
441}
442
443#[derive(Debug, Deserialize)]
444#[serde(tag = "backend", rename_all = "snake_case")]
445enum RawStorageConfig {
446 Sqlite {
447 #[serde(default)]
450 data_home: Option<PathBuf>,
451 },
452}
453
454#[derive(Debug, Deserialize)]
455struct RawModuleConfig {
456 #[serde(default, deserialize_with = "present_value")]
457 program: Option<PathBuf>,
458 #[serde(default, deserialize_with = "present_value")]
459 script: Option<RawScriptConfig>,
460 #[serde(default)]
461 args: Vec<String>,
462 #[serde(default)]
463 env: BTreeMap<String, String>,
464 #[serde(default)]
465 log: Option<RawLoggingConfig>,
466 #[serde(default = "default_enabled")]
467 enabled: bool,
468 #[serde(default)]
469 registration_channel: bool,
470 #[serde(default)]
471 reserved: bool,
472 #[serde(flatten)]
475 ignored: BTreeMap<String, serde_json::Value>,
476 #[serde(default)]
477 reserved_prefixes: Vec<String>,
478 #[serde(default)]
482 protocol: Option<String>,
483 #[serde(default)]
485 overlap: Option<String>,
486 #[serde(default)]
487 carry_containment: bool,
488 #[serde(default)]
489 health: Option<RawHealthConfig>,
490 #[serde(default)]
491 drain_timeout_ms: Option<u64>,
492 #[serde(default)]
493 register_timeout_s: Option<u64>,
494 #[serde(default)]
495 route_bind_relay_timeout_ms: Option<u64>,
496 #[serde(default)]
497 restart: Option<RawRestartConfig>,
498}
499
500#[derive(Debug, Deserialize)]
501#[serde(deny_unknown_fields)]
502struct RawScriptConfig {
503 runtime: String,
504 path: PathBuf,
505}
506
507fn present_value<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
508where
509 D: serde::Deserializer<'de>,
510 T: Deserialize<'de>,
511{
512 T::deserialize(deserializer).map(Some)
513}
514
515#[cfg(test)]
516mod script_config_tests {
517 use super::*;
518
519 fn parse(entry: serde_json::Value) -> Result<DaemonConfig, DaemonConfigError> {
520 parse_doc(
521 &serde_json::json!({"version":1,"modules":{"example":entry}}).to_string(),
522 Path::new("subc.jsonc"),
523 )
524 }
525
526 #[test]
527 fn script_config_accepts_bun_and_resolves_only_the_installed_runner() {
528 let config =
529 parse(serde_json::json!({"script":{"runtime":"bun","path":"bundle.js"}})).unwrap();
530 assert_eq!(
531 config.modules[0].program,
532 crate::supervise::script::runner_path(ScriptRuntime::Bun).unwrap()
533 );
534 assert_eq!(
535 config.modules[0].module_spec().script,
536 Some(ScriptEntry::new(
537 ScriptRuntime::Bun,
538 std::path::absolute("bundle.js").unwrap()
539 ))
540 );
541 }
542
543 #[test]
544 fn script_config_accepts_python_and_resolves_only_the_installed_runner() {
545 let config =
546 parse(serde_json::json!({"script":{"runtime":"python","path":"bundle.py"}})).unwrap();
547 assert_eq!(
548 config.modules[0].program,
549 crate::supervise::script::runner_path(ScriptRuntime::Python).unwrap()
550 );
551 assert_ne!(
552 config.modules[0].program,
553 crate::supervise::script::runner_path(ScriptRuntime::Bun).unwrap()
554 );
555 assert_eq!(
556 config.modules[0].module_spec().script,
557 Some(ScriptEntry::new(
558 ScriptRuntime::Python,
559 std::path::absolute("bundle.py").unwrap()
560 ))
561 );
562 }
563
564 #[test]
565 fn script_config_refuses_conflicting_missing_null_and_unknown_runtime_entries() {
566 for entry in [
567 serde_json::json!({}),
568 serde_json::json!({"program":"node","script":{"runtime":"bun","path":"bundle.js"}}),
569 serde_json::json!({"program":null,"script":{"runtime":"bun","path":"bundle.js"}}),
570 serde_json::json!({"program":"node","script":null}),
571 serde_json::json!({"script":{"runtime":"node","path":"bundle.js"}}),
572 ] {
573 assert!(parse(entry.clone()).is_err(), "accepted {entry}");
574 }
575 let error = parse(serde_json::json!({"script":{"runtime":"node","path":"bundle.js"}}))
576 .unwrap_err()
577 .to_string();
578 assert!(
579 error.contains("example") && error.contains("node"),
580 "{error}"
581 );
582 }
583
584 #[test]
585 fn script_config_refuses_explicit_runtime_preload_environment() {
586 for key in [
587 "NODE_OPTIONS",
588 "BUN_OPTIONS",
589 "BUN_INSTALL",
590 "NODE_PATH",
591 "BUN_CONFIG_PRELOAD",
592 "BUN_CONFIG_any",
593 "PYTHONPATH",
594 "PYTHONHOME",
595 "PYTHONSTARTUP",
596 "PYTHON_any",
597 ] {
598 let env = BTreeMap::from([(key, "unapproved")]);
599 for runtime in ["bun", "python"] {
600 let error = parse(
601 serde_json::json!({"script":{"runtime":runtime,"path":"bundle.js"},"env":env}),
602 )
603 .unwrap_err()
604 .to_string();
605 assert!(error.contains(key) && error.contains("example"), "{error}");
606 }
607 assert!(parse(serde_json::json!({"program":"legacy-interpreter","env":env})).is_ok());
608 }
609 }
610}
611
612#[derive(Debug, Clone, Deserialize)]
613struct RawLoggingConfig {
614 #[serde(default)]
615 level: Option<String>,
616 #[serde(default)]
617 tags: BTreeMap<String, String>,
618 #[serde(default)]
619 alarm_segment_mb: Option<u32>,
620 #[serde(default)]
621 max_file_mb: Option<u32>,
622 #[serde(default)]
623 keep: Option<u8>,
624 #[serde(default)]
625 max_age_days: Option<u32>,
626}
627
628#[derive(Debug, Deserialize)]
629struct RawRestartConfig {
630 #[serde(default)]
631 max_restarts: Option<u32>,
632 #[serde(default)]
633 window_secs: Option<u64>,
634 #[serde(default)]
635 backoff_ms: Option<u64>,
636 #[serde(default)]
637 max_backoff_ms: Option<u64>,
638}
639
640#[derive(Debug, Deserialize)]
641struct RawHealthConfig {
642 #[serde(default)]
643 http: Option<String>,
644 #[serde(default)]
645 cadence_ms: Option<u64>,
646 #[serde(default)]
647 deadline_ms: Option<u64>,
648 #[serde(default)]
649 failure_threshold: Option<u32>,
650 #[serde(default)]
651 on_degraded: Option<RawHealthAction>,
652 #[serde(default)]
653 on_failing: Option<RawHealthAction>,
654 #[serde(default)]
655 critical: bool,
656}
657
658#[derive(Debug, Deserialize)]
659#[serde(rename_all = "snake_case")]
660enum RawHealthAction {
661 Report,
662 Restart,
663 Alert,
664}
665
666pub fn default_config_path() -> PathBuf {
667 default_config_home().join(DAEMON_CONFIG_RELATIVE_PATH)
668}
669
670pub fn default_config_home() -> PathBuf {
692 if let Some(config_home) = non_empty_os_var("XDG_CONFIG_HOME") {
693 return PathBuf::from(config_home);
694 }
695
696 #[cfg(windows)]
697 {
698 if let Some(app_data) = non_empty_os_var("APPDATA") {
699 return PathBuf::from(app_data);
700 }
701 if let Some(user_profile) = non_empty_os_var("USERPROFILE") {
702 return PathBuf::from(user_profile).join("AppData").join("Roaming");
703 }
704 }
705
706 if let Some(home) = non_empty_os_var("HOME") {
707 return PathBuf::from(home).join(".config");
708 }
709
710 PathBuf::from(".config")
711}
712
713pub fn load(path: impl AsRef<Path>) -> Result<Option<DaemonConfig>, DaemonConfigError> {
714 let path = path.as_ref();
715 let Some(doc) = read_config_doc(path)? else {
716 return Ok(None);
717 };
718 parse_doc(&doc, path).map(Some)
719}
720
721pub fn load_with_activity(
725 path: impl AsRef<Path>,
726) -> Result<Option<(DaemonConfig, ActivityConfig)>, DaemonConfigError> {
727 let path = path.as_ref();
728 let Some(doc) = read_config_doc(path)? else {
729 return Ok(None);
730 };
731 parse_doc_with_activity(&doc, path).map(Some)
732}
733
734pub fn parse_with_activity(
739 doc: &str,
740 path: impl AsRef<Path>,
741) -> Result<(DaemonConfig, ActivityConfig), DaemonConfigError> {
742 parse_doc_with_activity(doc, path.as_ref())
743}
744
745pub fn load_logging(path: impl AsRef<Path>) -> Result<Option<LoggingConfig>, DaemonConfigError> {
751 let path = path.as_ref();
752 let Some(doc) = read_config_doc(path)? else {
753 return Ok(None);
754 };
755 let json = jsonc_to_json(&doc).map_err(|message| DaemonConfigError::InvalidJsonc {
756 path: path.to_path_buf(),
757 message,
758 })?;
759 let raw: RawDaemonConfig =
760 serde_json::from_str(&json).map_err(|source| DaemonConfigError::InvalidJson {
761 path: path.to_path_buf(),
762 source,
763 })?;
764 if raw.version != SUPPORTED_CONFIG_VERSION {
765 return Err(DaemonConfigError::UnsupportedVersion {
766 path: path.to_path_buf(),
767 version: raw.version,
768 });
769 }
770 raw.log
771 .map(|log| parse_logging_config(log, path, "daemon log"))
772 .transpose()
773}
774
775pub fn ensure_daemon_run_dir_private() -> Result<PathBuf, io::Error> {
801 let path = daemon_run_dir()
802 .map_err(|error| io::Error::new(io::ErrorKind::InvalidInput, error.to_string()))?;
803 ensure_directory_private(&path)?;
804 Ok(path)
805}
806
807#[cfg(unix)]
812pub(crate) fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
813 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
814
815 if !path.exists() {
816 fs::DirBuilder::new()
817 .recursive(true)
818 .mode(0o700)
819 .create(path)?;
820 return Ok(());
821 }
822 let mode = fs::metadata(path)?.permissions().mode() & 0o777;
823 if mode & 0o077 != 0 {
824 fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
825 }
826 Ok(())
827}
828
829#[cfg(windows)]
832fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
833 subc_os::windows_acl::create_private_dir(path)
834}
835
836#[cfg(not(any(unix, windows)))]
837fn ensure_directory_private(path: &Path) -> Result<(), io::Error> {
838 if !path.exists() {
839 fs::create_dir_all(path)?;
840 }
841 Ok(())
842}
843
844pub fn daemon_run_dir() -> Result<PathBuf, DaemonRunDirError> {
854 daemon_run_dir_from(default_data_home())
855}
856
857pub(crate) fn daemon_run_dir_from(data_home: PathBuf) -> Result<PathBuf, DaemonRunDirError> {
860 if !data_home.is_absolute() {
861 return Err(DaemonRunDirError::RelativeDataHome { data_home });
862 }
863 Ok(data_home.join("cortexkit").join("run"))
864}
865
866#[derive(Debug, Clone, PartialEq, Eq)]
868pub enum DaemonRunDirError {
869 RelativeDataHome { data_home: PathBuf },
872}
873
874impl fmt::Display for DaemonRunDirError {
875 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
876 match self {
877 Self::RelativeDataHome { data_home } => write!(
878 f,
879 "cannot resolve the daemon run directory: the data home `{}` is relative, \
880 so it would land under the current working directory; {}",
881 data_home.display(),
882 DATA_HOME_REMEDY
883 ),
884 }
885 }
886}
887
888impl std::error::Error for DaemonRunDirError {}
889
890#[cfg(windows)]
892const DATA_HOME_REMEDY: &str =
893 "set XDG_DATA_HOME to an absolute path, or set APPDATA, USERPROFILE or HOME";
894#[cfg(not(windows))]
895const DATA_HOME_REMEDY: &str = "set XDG_DATA_HOME to an absolute path, or set HOME";
896
897fn read_config_doc(path: &Path) -> Result<Option<String>, DaemonConfigError> {
898 match fs::read_to_string(path) {
899 Ok(doc) => Ok(Some(doc)),
900 Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None),
901 Err(source) => Err(DaemonConfigError::Read {
902 path: path.to_path_buf(),
903 source,
904 }),
905 }
906}
907
908fn parse_doc(doc: &str, path: &Path) -> Result<DaemonConfig, DaemonConfigError> {
909 parse_doc_with_activity(doc, path).map(|(config, _)| config)
910}
911
912fn parse_doc_with_activity(
913 doc: &str,
914 path: &Path,
915) -> Result<(DaemonConfig, ActivityConfig), DaemonConfigError> {
916 let json = jsonc_to_json(doc).map_err(|message| DaemonConfigError::InvalidJsonc {
917 path: path.to_path_buf(),
918 message,
919 })?;
920 let raw: RawDaemonConfig =
921 serde_json::from_str(&json).map_err(|source| DaemonConfigError::InvalidJson {
922 path: path.to_path_buf(),
923 source,
924 })?;
925
926 if raw.version != SUPPORTED_CONFIG_VERSION {
927 return Err(DaemonConfigError::UnsupportedVersion {
928 path: path.to_path_buf(),
929 version: raw.version,
930 });
931 }
932
933 let daemon_logging = raw
934 .log
935 .map(|log| parse_logging_config(log, path, "daemon log"))
936 .transpose()?;
937 let default_drain_timeout_ms = raw.drain_timeout_ms;
938 let default_route_bind_relay_timeout_ms = match raw.route_bind_relay_timeout_ms {
944 Some(0) => {
945 return Err(DaemonConfigError::InvalidValue {
946 path: path.to_path_buf(),
947 message: ROUTE_BIND_RELAY_ZERO_MESSAGE.to_string(),
948 });
949 }
950 Some(value) => Some(value),
951 None => None,
952 };
953 let modules = raw
954 .modules
955 .into_iter()
956 .map(|(module_id, module)| {
957 if module_id == "subc" {
958 return Err(DaemonConfigError::InvalidValue {
959 path: path.to_path_buf(),
960 message: "module id 'subc' is reserved for the daemon".to_owned(),
961 });
962 }
963 let (program, script) = match (module.program, module.script) {
964 (Some(program), None) => (program, None),
965 (None, Some(script)) if matches!(script.runtime.as_str(), "bun" | "python") => {
966 let runtime = match script.runtime.as_str() {
967 "python" => ScriptRuntime::Python,
968 _ => ScriptRuntime::Bun,
969 };
970 let script_path = crate::supervise::script::resolve_script_path(&script.path)
971 .map_err(|error| DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}': {error}") })?;
972 let runner = crate::supervise::script::runner_path(runtime)
973 .map_err(|error| DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}': {error}") })?;
974 (runner, Some(ScriptEntry::new(runtime, script_path)))
975 }
976 (None, Some(script)) => return Err(DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}' script runtime '{}' is unsupported; expected bun or python", script.runtime.escape_debug()) }),
977 _ => return Err(DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}' must name exactly one of program or script") }),
978 };
979 if script.is_some() {
980 if let Some(key) = module.env.keys().find(|key| crate::supervise::script::forbidden_env(key)) {
981 return Err(DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}' script env '{key}' is refused: runtime options can execute code before script verification") });
982 }
983 }
984 let protocol = parse_module_protocol(module.protocol.as_deref(), path, &module_id)?;
985 let health = module
986 .health
987 .map(|health| parse_health_config(health, path, &module_id, protocol))
988 .transpose()?
989 .unwrap_or_default();
990 if let Err(reason) = crate::registry::module_id_path_hazard(&module_id) {
991 return Err(DaemonConfigError::InvalidValue {
992 path: path.to_path_buf(),
993 message: format!(
994 "module id '{}' is not usable as a path component ({reason}): \
995 the daemon derives each module's store path from its id",
996 module_id.escape_debug()
997 ),
998 });
999 }
1000 let per_module_route_bind_relay_timeout_ms = match module.route_bind_relay_timeout_ms {
1005 Some(0) => {
1006 return Err(DaemonConfigError::InvalidValue {
1007 path: path.to_path_buf(),
1008 message: format!(
1009 "module '{module_id}' {ROUTE_BIND_RELAY_ZERO_MESSAGE}",
1010 module_id = module_id.escape_debug()
1011 ),
1012 });
1013 }
1014 Some(value) => Some(value),
1015 None => default_route_bind_relay_timeout_ms,
1016 };
1017 if module.ignored.contains_key("launch_nonce_env") {
1022 tracing::warn!(
1023 module_id = %module_id.escape_debug(),
1024 "launch_nonce_env is deprecated and ignored; nonce delivery is determined by the platform"
1025 );
1026 }
1027 let overlap = parse_module_overlap(module.overlap.as_deref(), path, &module_id)?;
1028 if module.carry_containment && overlap == ModuleOverlap::Safe {
1029 return Err(DaemonConfigError::InvalidValue {
1030 path: path.to_path_buf(),
1031 message: format!(
1032 "module '{}' sets carry_containment: true with overlap: \"safe\"; carried containment does not support overlapping instances",
1033 module_id.escape_debug()
1034 ),
1035 });
1036 }
1037 if module.env.contains_key(SUBC_SPAWN_ROLE_ENV) {
1041 return Err(DaemonConfigError::InvalidValue {
1042 path: path.to_path_buf(),
1043 message: format!(
1044 "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",
1045 module_id = module_id.escape_debug()
1046 ),
1047 });
1048 }
1049 if protocol == ModuleProtocol::None && module.reserved {
1056 return Err(DaemonConfigError::InvalidValue {
1057 path: path.to_path_buf(),
1058 message: format!(
1059 "module '{module_id}' sets reserved: true with protocol: \"none\"; \
1060 reserved is enforced on the module's HELLO and a protocol: \"none\" \
1061 module never registers, so the reservation could never be checked",
1062 module_id = module_id.escape_debug()
1063 ),
1064 });
1065 }
1066 let restart = parse_restart_config(module.restart, path, &module_id)?;
1067 let register_timeout_s = module
1068 .register_timeout_s
1069 .unwrap_or(crate::supervise::DEFAULT_REGISTER_TIMEOUT.as_secs());
1070 if !(10..=3600).contains(®ister_timeout_s) {
1071 return Err(DaemonConfigError::InvalidValue {
1072 path: path.to_path_buf(),
1073 message: format!(
1074 "module '{module_id}' register_timeout_s must be an integer from 10 to 3600"
1075 ),
1076 });
1077 }
1078 let log = module
1079 .log
1080 .map(|log| parse_logging_config(log, path, &format!("module '{module_id}' log")))
1081 .transpose()?
1082 .or_else(|| daemon_logging.clone());
1083 Ok(ConfiguredModule { module_id,
1084 program,
1085 script,
1086 args: module.args,
1087 env: module.env.into_iter().collect(),
1088 log,
1089 enabled: module.enabled,
1090 registration_channel: module.registration_channel,
1091 reserved: module.reserved,
1092 reserved_prefixes: module.reserved_prefixes,
1093 protocol,
1094 overlap,
1095 carry_containment: module.carry_containment,
1096 health,
1097 drain_timeout_ms: module.drain_timeout_ms.or(default_drain_timeout_ms),
1100 register_timeout: Duration::from_secs(register_timeout_s),
1101 route_bind_relay_timeout_ms: per_module_route_bind_relay_timeout_ms,
1106 restart, })
1107 })
1108 .collect::<Result<Vec<_>, DaemonConfigError>>()?;
1109
1110 validate_reserved_prefixes(&modules, path)?;
1111 validate_reserved_capabilities(&raw.reserved_capabilities, path)?;
1112 validate_admission_facts_config(
1113 &modules,
1114 raw.admission_facts_carrier_module_id.as_deref(),
1115 raw.admission_facts_targets.as_deref(),
1116 path,
1117 )?;
1118 let scope_authority_owners = raw
1119 .scope_authority_owners
1120 .unwrap_or_else(default_scope_authority_owners);
1121 subc_protocol::manifest::validate_module_id(&raw.federated_scope_owner).map_err(|error| {
1122 DaemonConfigError::InvalidValue {
1123 path: path.to_path_buf(),
1124 message: format!("federated_scope_owner: {error}"),
1125 }
1126 })?;
1127 if scope_authority_owners.iter().any(|owner| owner.is_empty()) {
1128 return Err(DaemonConfigError::InvalidValue {
1129 path: path.to_path_buf(),
1130 message: "scope_authority_owners must not contain empty module ids".to_string(),
1131 });
1132 }
1133
1134 let storage = raw
1135 .storage
1136 .map(|s| match s {
1137 RawStorageConfig::Sqlite { data_home } => {
1138 let data_home = data_home.unwrap_or_else(default_data_home);
1139 if !data_home.is_absolute() {
1148 return Err(DaemonConfigError::InvalidValue {
1149 path: path.to_path_buf(),
1150 message: format!(
1151 "storage data home resolved to the relative path {} \
1152 (no absolute XDG_DATA_HOME, APPDATA, USERPROFILE, or HOME \
1153 in the daemon's environment); refusing to serve a \
1154 cwd-relative storage descriptor to modules. Set \
1155 XDG_DATA_HOME or HOME to an absolute path, or set \
1156 storage.data_home in this file.",
1157 data_home.display()
1158 ),
1159 });
1160 }
1161 Ok(StorageConfig::Sqlite { data_home })
1162 }
1163 })
1164 .transpose()?;
1165
1166 if raw.activity.max_age_days == 0 || raw.activity.max_total_mb == 0 {
1167 return Err(DaemonConfigError::InvalidValue {
1168 path: path.to_path_buf(),
1169 message: "activity.max_age_days and activity.max_total_mb must be positive".into(),
1170 });
1171 }
1172 Ok((
1173 DaemonConfig {
1174 path: path.to_path_buf(),
1175 port: raw.port,
1176 privileged_operator_prompt: raw.privileged_operator_prompt,
1177 drain_timeout_ms: default_drain_timeout_ms,
1178 route_bind_relay_timeout_ms: default_route_bind_relay_timeout_ms,
1179 modules,
1180 storage,
1181 admission_facts_carrier_module_id: raw.admission_facts_carrier_module_id,
1182 admission_facts_targets: raw.admission_facts_targets,
1183 scope_authority_owners,
1184 federated_scope_owner: raw.federated_scope_owner,
1185 reserved_capabilities: raw.reserved_capabilities,
1186 agent_policy_root: crate::policy_root::parse_section(raw.agent_policy_root),
1187 },
1188 raw.activity,
1189 ))
1190}
1191
1192fn parse_logging_config(
1193 raw: RawLoggingConfig,
1194 path: &Path,
1195 owner: &str,
1196) -> Result<LoggingConfig, DaemonConfigError> {
1197 fn valid_level(level: &str) -> bool {
1198 matches!(level, "off" | "error" | "warn" | "info" | "debug" | "trace")
1199 }
1200
1201 let level = raw.level.unwrap_or_else(|| "info".to_string());
1202 if !valid_level(&level) {
1203 return Err(DaemonConfigError::InvalidValue {
1204 path: path.to_path_buf(),
1205 message: format!(
1206 "{owner}.level must be one of off, error, warn, info, debug, trace; got {level:?}"
1207 ),
1208 });
1209 }
1210 for (tag, tag_level) in &raw.tags {
1211 let well_formed = !tag.is_empty()
1216 && tag.split('.').all(|segment| {
1217 let mut chars = segment.chars();
1218 matches!(chars.next(), Some('a'..='z'))
1219 && chars.all(|c| matches!(c, 'a'..='z' | '0'..='9' | '-'))
1220 });
1221 if !well_formed {
1222 return Err(DaemonConfigError::InvalidValue {
1223 path: path.to_path_buf(),
1224 message: format!(
1225 "{owner}.tags key {tag:?} is not a logger name (dotted segments of [a-z][a-z0-9-]*)"
1226 ),
1227 });
1228 }
1229 if !valid_level(tag_level) {
1230 return Err(DaemonConfigError::InvalidValue {
1231 path: path.to_path_buf(),
1232 message: format!(
1233 "{owner}.tags.{tag} must be one of off, error, warn, info, debug, trace; got {tag_level:?}"
1234 ),
1235 });
1236 }
1237 }
1238
1239 let defaults = Retention::default();
1240 let retention = Retention {
1241 max_file_mb: raw.max_file_mb.unwrap_or(defaults.max_file_mb),
1242 keep: raw.keep.unwrap_or(defaults.keep),
1243 max_age_days: raw.max_age_days.unwrap_or(defaults.max_age_days),
1244 };
1245 if retention.max_file_mb == 0 {
1246 return Err(DaemonConfigError::InvalidValue {
1247 path: path.to_path_buf(),
1248 message: format!("{owner}.max_file_mb must be greater than 0"),
1249 });
1250 }
1251
1252 let alarm_segment_mb = raw
1253 .alarm_segment_mb
1254 .unwrap_or(cortexkit_log::SegmentRetention::default().alarm_segment_mb);
1255 if alarm_segment_mb == 0 {
1256 return Err(DaemonConfigError::InvalidValue {
1257 path: path.to_path_buf(),
1258 message: format!("{owner}.alarm_segment_mb must be greater than 0"),
1259 });
1260 }
1261
1262 Ok(LoggingConfig {
1263 level,
1264 tags: raw.tags,
1265 retention,
1266 alarm_segment_mb,
1267 })
1268}
1269
1270fn parse_module_protocol(
1279 raw: Option<&str>,
1280 path: &Path,
1281 module_id: &str,
1282) -> Result<ModuleProtocol, DaemonConfigError> {
1283 match raw {
1284 None | Some("subc") => Ok(ModuleProtocol::Subc),
1285 Some("none") => Ok(ModuleProtocol::None),
1286 Some(other) => Err(DaemonConfigError::InvalidValue {
1290 path: path.to_path_buf(),
1291 message: format!(
1292 "module '{module_id}' declares protocol {other:?}; supported values are \
1293 \"subc\" (the default when the key is absent) and \"none\"",
1294 module_id = module_id.escape_debug(),
1295 ),
1296 }),
1297 }
1298}
1299
1300fn parse_module_overlap(
1304 raw: Option<&str>,
1305 path: &Path,
1306 module_id: &str,
1307) -> Result<ModuleOverlap, DaemonConfigError> {
1308 match raw {
1309 None | Some("exclusive") => Ok(ModuleOverlap::Exclusive),
1310 Some("safe") => Ok(ModuleOverlap::Safe),
1311 Some(other) => Err(DaemonConfigError::InvalidValue {
1312 path: path.to_path_buf(),
1313 message: format!(
1314 "module '{module_id}' declares overlap {other:?}; supported values are \
1315 \"exclusive\" (the default when the key is absent) and \"safe\"",
1316 module_id = module_id.escape_debug(),
1317 ),
1318 }),
1319 }
1320}
1321
1322fn validate_reserved_capabilities(
1323 bindings: &BTreeMap<String, String>,
1324 path: &Path,
1325) -> Result<(), DaemonConfigError> {
1326 for (capability, module_id) in bindings {
1327 if !is_valid_capability_identifier(capability) {
1328 return Err(DaemonConfigError::InvalidValue {
1329 path: path.to_path_buf(),
1330 message: format!(
1331 "reserved_capabilities key {:?} is not a valid capability identifier",
1332 capability
1333 ),
1334 });
1335 }
1336 if module_id.trim().is_empty() {
1337 return Err(DaemonConfigError::InvalidValue {
1338 path: path.to_path_buf(),
1339 message: format!(
1340 "reserved_capabilities binding for {:?} has an empty module id",
1341 capability
1342 ),
1343 });
1344 }
1345 if let Err(reason) = crate::registry::module_id_path_hazard(module_id) {
1346 return Err(DaemonConfigError::InvalidValue {
1347 path: path.to_path_buf(),
1348 message: format!(
1349 "reserved_capabilities binding for {:?} has an unusable module id {:?}: {reason}",
1350 capability, module_id
1351 ),
1352 });
1353 }
1354 }
1355 Ok(())
1356}
1357
1358fn validate_admission_facts_config(
1359 modules: &[ConfiguredModule],
1360 carrier_module_id: Option<&str>,
1361 targets: Option<&[String]>,
1362 path: &Path,
1363) -> Result<(), DaemonConfigError> {
1364 let Some(carrier_module_id) = carrier_module_id else {
1365 return Ok(());
1366 };
1367
1368 let Some(carrier) = modules
1369 .iter()
1370 .find(|module| module.module_id == carrier_module_id)
1371 else {
1372 return Err(DaemonConfigError::InvalidValue {
1373 path: path.to_path_buf(),
1374 message: format!(
1375 "admission_facts_carrier_module_id '{carrier_module_id}' must name a configured module"
1376 ),
1377 });
1378 };
1379 if !carrier.enabled || !carrier.reserved {
1380 return Err(DaemonConfigError::InvalidValue {
1381 path: path.to_path_buf(),
1382 message: format!(
1383 "admission_facts_carrier_module_id '{carrier_module_id}' must name an enabled reserved module"
1384 ),
1385 });
1386 }
1387
1388 let Some(targets) = targets else {
1389 return Err(DaemonConfigError::InvalidValue {
1390 path: path.to_path_buf(),
1391 message: "admission_facts_targets must be present when an admission facts carrier is configured".to_string(),
1392 });
1393 };
1394 if targets.is_empty() || targets.iter().any(String::is_empty) {
1395 return Err(DaemonConfigError::InvalidValue {
1396 path: path.to_path_buf(),
1397 message:
1398 "admission_facts_targets must be non-empty and must not contain empty module ids"
1399 .to_string(),
1400 });
1401 }
1402
1403 Ok(())
1404}
1405
1406fn default_enabled() -> bool {
1407 true
1408}
1409
1410fn validate_reserved_prefixes(
1411 modules: &[ConfiguredModule],
1412 path: &Path,
1413) -> Result<(), DaemonConfigError> {
1414 for module in modules {
1415 if module.reserved_prefixes.is_empty() {
1416 continue;
1417 }
1418 if !module.reserved {
1419 return Err(DaemonConfigError::InvalidValue {
1420 path: path.to_path_buf(),
1421 message: format!(
1422 "module '{}' reserved_prefixes require reserved=true so the owner is spawn-nonce protected",
1423 module.module_id
1424 ),
1425 });
1426 }
1427 for prefix in &module.reserved_prefixes {
1428 if !prefix.ends_with(':') {
1429 return Err(DaemonConfigError::InvalidValue {
1430 path: path.to_path_buf(),
1431 message: format!(
1432 "module '{}' reserved prefix '{}' must end with ':'",
1433 module.module_id, prefix
1434 ),
1435 });
1436 }
1437 }
1438 }
1439
1440 for module in modules {
1441 for prefix in &module.reserved_prefixes {
1442 if let Some(colliding) = modules
1443 .iter()
1444 .find(|candidate| candidate.module_id.starts_with(prefix))
1445 {
1446 return Err(DaemonConfigError::InvalidValue {
1447 path: path.to_path_buf(),
1448 message: format!(
1449 "reserved prefix '{}' owned by '{}' collides with configured module id '{}'",
1450 prefix, module.module_id, colliding.module_id
1451 ),
1452 });
1453 }
1454 }
1455 }
1456
1457 for (left_index, left) in modules.iter().enumerate() {
1458 for right in modules.iter().skip(left_index + 1) {
1459 if left.module_id == right.module_id {
1460 continue;
1461 }
1462 for left_prefix in &left.reserved_prefixes {
1463 for right_prefix in &right.reserved_prefixes {
1464 if left_prefix.starts_with(right_prefix)
1465 || right_prefix.starts_with(left_prefix)
1466 {
1467 return Err(DaemonConfigError::InvalidValue {
1468 path: path.to_path_buf(),
1469 message: format!(
1470 "reserved prefixes '{}' owned by '{}' and '{}' owned by '{}' overlap",
1471 left_prefix, left.module_id, right_prefix, right.module_id
1472 ),
1473 });
1474 }
1475 }
1476 }
1477 }
1478 }
1479
1480 Ok(())
1481}
1482
1483fn parse_health_config(
1484 raw: RawHealthConfig,
1485 path: &Path,
1486 module_id: &str,
1487 protocol: ModuleProtocol,
1488) -> Result<HealthConfig, DaemonConfigError> {
1489 if let Some(url) = raw.http.as_deref() {
1490 let reason = if protocol != ModuleProtocol::None {
1491 Some("is valid only for protocol: \"none\" modules".to_string())
1492 } else {
1493 crate::supervise::parse_http_probe_url(url).err()
1494 };
1495 if let Some(reason) = reason {
1496 return Err(DaemonConfigError::InvalidValue {
1497 path: path.to_path_buf(),
1498 message: format!("module '{module_id}' health.http {reason}"),
1499 });
1500 }
1501 }
1502 let defaults = HealthConfig::default();
1503 let cadence = positive_millis(
1504 raw.cadence_ms,
1505 defaults.cadence,
1506 path,
1507 module_id,
1508 "cadence_ms",
1509 )?;
1510 let deadline = positive_millis(
1511 raw.deadline_ms,
1512 defaults.deadline,
1513 path,
1514 module_id,
1515 "deadline_ms",
1516 )?;
1517 let failure_threshold = match raw.failure_threshold {
1518 Some(0) => {
1519 return Err(DaemonConfigError::InvalidValue {
1520 path: path.to_path_buf(),
1521 message: format!("module '{module_id}' health.failure_threshold must be positive"),
1522 })
1523 }
1524 Some(value) => value,
1525 None => defaults.failure_threshold,
1526 };
1527
1528 Ok(HealthConfig {
1529 http: raw.http,
1530 cadence,
1531 deadline,
1532 failure_threshold,
1533 on_degraded: match raw.on_degraded {
1534 Some(RawHealthAction::Restart) => {
1535 return Err(DaemonConfigError::InvalidValue {
1536 path: path.to_path_buf(),
1537 message: format!(
1538 "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)."
1539 ),
1540 });
1541 }
1542 Some(action) => health_action(action),
1543 None => defaults.on_degraded,
1544 },
1545 on_failing: raw
1546 .on_failing
1547 .map(health_action)
1548 .unwrap_or(defaults.on_failing),
1549 critical: raw.critical,
1550 })
1551}
1552
1553fn parse_restart_config(
1560 raw: Option<RawRestartConfig>,
1561 path: &Path,
1562 module_id: &str,
1563) -> Result<RestartPolicy, DaemonConfigError> {
1564 let defaults = RestartPolicy::default();
1565 let Some(raw) = raw else {
1566 return Ok(defaults);
1567 };
1568
1569 let window = match raw.window_secs {
1570 Some(0) => {
1571 return Err(DaemonConfigError::InvalidValue {
1572 path: path.to_path_buf(),
1573 message: format!(
1574 "module '{module_id}' {RESTART_WINDOW_ZERO_MESSAGE}",
1575 module_id = module_id.escape_debug()
1576 ),
1577 });
1578 }
1579 Some(secs) => Duration::from_secs(secs),
1580 None => defaults.window,
1581 };
1582 let backoff = raw
1583 .backoff_ms
1584 .map(Duration::from_millis)
1585 .unwrap_or(defaults.backoff);
1586 let max_backoff = raw
1587 .max_backoff_ms
1588 .map(Duration::from_millis)
1589 .unwrap_or(defaults.max_backoff);
1590 if max_backoff < backoff {
1591 return Err(DaemonConfigError::InvalidValue {
1592 path: path.to_path_buf(),
1593 message: format!(
1594 "module '{}' restart.max_backoff_ms must be greater than or equal to restart.backoff_ms (max_backoff_ms={max_backoff:?}, backoff_ms={backoff:?})",
1595 module_id.escape_debug()
1596 ),
1597 });
1598 }
1599
1600 Ok(RestartPolicy {
1601 max_restarts: raw.max_restarts.unwrap_or(defaults.max_restarts),
1604 backoff,
1605 max_backoff,
1606 window,
1607 })
1608}
1609
1610fn positive_millis(
1611 value: Option<u64>,
1612 default: std::time::Duration,
1613 path: &Path,
1614 module_id: &str,
1615 field: &str,
1616) -> Result<std::time::Duration, DaemonConfigError> {
1617 match value {
1618 Some(0) => Err(DaemonConfigError::InvalidValue {
1619 path: path.to_path_buf(),
1620 message: format!("module '{module_id}' health.{field} must be positive"),
1621 }),
1622 Some(value) => Ok(std::time::Duration::from_millis(value)),
1623 None => Ok(default),
1624 }
1625}
1626
1627fn health_action(action: RawHealthAction) -> HealthAction {
1628 match action {
1629 RawHealthAction::Report => HealthAction::Report,
1630 RawHealthAction::Restart => HealthAction::Restart,
1631 RawHealthAction::Alert => HealthAction::Alert,
1632 }
1633}
1634
1635pub(crate) fn default_data_home() -> PathBuf {
1638 if let Some(data_home) = non_empty_os_var("XDG_DATA_HOME") {
1639 return PathBuf::from(data_home);
1640 }
1641
1642 #[cfg(windows)]
1643 {
1644 if let Some(app_data) = non_empty_os_var("APPDATA") {
1645 return PathBuf::from(app_data);
1646 }
1647 if let Some(user_profile) = non_empty_os_var("USERPROFILE") {
1648 return PathBuf::from(user_profile).join("AppData").join("Roaming");
1649 }
1650 }
1651
1652 if let Some(home) = non_empty_os_var("HOME") {
1653 return PathBuf::from(home).join(".local").join("share");
1654 }
1655
1656 PathBuf::from(".local").join("share")
1657}
1658
1659fn non_empty_os_var(key: &str) -> Option<OsString> {
1660 let value = env::var_os(key)?;
1661 if value.is_empty() {
1662 None
1663 } else {
1664 Some(value)
1665 }
1666}
1667
1668impl fmt::Display for DaemonConfigError {
1669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1670 match self {
1671 Self::Read { path, source } => {
1672 write!(f, "failed to read daemon config {}: {source}", path.display())
1673 }
1674 Self::InvalidJsonc { path, message } => {
1675 write!(f, "invalid JSONC in daemon config {}: {message}", path.display())
1676 }
1677 Self::InvalidJson { path, source } => {
1678 write!(f, "invalid daemon config {}: {source}", path.display())
1679 }
1680 Self::UnsupportedVersion { path, version } => write!(
1681 f,
1682 "invalid daemon config {}: version {version} is unsupported (expected {SUPPORTED_CONFIG_VERSION})",
1683 path.display()
1684 ),
1685 Self::InvalidValue { path, message } => {
1686 write!(f, "invalid daemon config {}: {message}", path.display())
1687 }
1688 }
1689 }
1690}
1691
1692impl Error for DaemonConfigError {
1693 fn source(&self) -> Option<&(dyn Error + 'static)> {
1694 match self {
1695 Self::Read { source, .. } => Some(source),
1696 Self::InvalidJson { source, .. } => Some(source),
1697 Self::InvalidJsonc { .. }
1698 | Self::UnsupportedVersion { .. }
1699 | Self::InvalidValue { .. } => None,
1700 }
1701 }
1702}
1703
1704#[cfg(all(test, windows))]
1705mod windows_run_dir_privacy_tests {
1706 use super::ensure_directory_private;
1707 use cortexkit_test_support::ScratchDir;
1708 use subc_os::windows_acl::test_support::{
1709 assert_dacl_owner_only, assert_owner_only, grant_everyone,
1710 };
1711
1712 #[test]
1713 fn windows_run_dir_has_exact_protected_dacl_at_creation() {
1714 let root = ScratchDir::new("windows-run-dir-create");
1715 grant_everyone(root.path());
1716 let path = root.join("run");
1717 ensure_directory_private(&path).unwrap();
1718 assert_owner_only(&path, true, true);
1719 }
1720
1721 #[test]
1722 fn windows_run_dir_narrows_existing_inherited_descendants() {
1723 let root = ScratchDir::new("windows-run-dir-existing");
1724 grant_everyone(root.path());
1725 let path = root.join("run");
1726 std::fs::create_dir(&path).unwrap();
1727 let child = path.join("old.log");
1728 std::fs::write(&child, b"old log").unwrap();
1729 ensure_directory_private(&path).unwrap();
1730 assert_dacl_owner_only(&path, true, true);
1733 assert_dacl_owner_only(&child, false, false);
1734 }
1735}
1736
1737#[cfg(all(test, unix))]
1738mod run_dir_privacy_tests {
1739 use cortexkit_test_support::ScratchDir;
1740 use std::fs;
1741 use std::os::unix::fs::PermissionsExt;
1742
1743 #[test]
1749 fn run_dir_is_created_private_and_an_inherited_wide_one_is_tightened() {
1750 let temp = ScratchDir::new("subc-run-dir-privacy");
1751 let created = temp.path().join("cortexkit").join("run");
1752 super::ensure_directory_private(&created).expect("create run dir");
1753 let mode = fs::metadata(&created)
1754 .expect("stat created")
1755 .permissions()
1756 .mode()
1757 & 0o777;
1758 assert_eq!(
1759 mode, 0o700,
1760 "observable a run directory this code creates must be 0700, got {mode:o}"
1761 );
1762
1763 fs::set_permissions(&created, fs::Permissions::from_mode(0o755)).expect("widen");
1765 let widened = fs::metadata(&created)
1766 .expect("stat widened")
1767 .permissions()
1768 .mode()
1769 & 0o777;
1770 assert_eq!(
1771 widened, 0o755,
1772 "observable the fixture must actually be wide before the tighten"
1773 );
1774
1775 super::ensure_directory_private(&created).expect("tighten run dir");
1776 let mode = fs::metadata(&created)
1777 .expect("stat tightened")
1778 .permissions()
1779 .mode()
1780 & 0o777;
1781 assert_eq!(
1782 mode, 0o700,
1783 "observable an inherited group- or world-readable run directory must be tightened to 0700, got {mode:o}"
1784 );
1785 }
1786}
1787
1788#[cfg(test)]
1789mod tests {
1790 use super::*;
1791
1792 static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1801
1802 fn abs(posix: &str) -> PathBuf {
1807 if cfg!(windows) {
1808 PathBuf::from(format!("C:{}", posix.replace('/', "\\")))
1809 } else {
1810 PathBuf::from(posix)
1811 }
1812 }
1813
1814 #[test]
1815 fn default_data_home_matches_golden_fixture() {
1816 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1817 let doc: serde_json::Value =
1818 serde_json::from_str(include_str!("../tests/golden/data_home_resolution.json"))
1819 .expect("golden parses");
1820 let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1821 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1822 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1823 let platform_matches =
1824 |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1825
1826 let mut ran = 0usize;
1827 for case in doc["cases"].as_array().expect("cases array") {
1828 let name = case["name"].as_str().expect("name");
1829 if !platform_matches(case["platform"].as_str().expect("platform")) {
1830 continue;
1831 }
1832 for v in vars {
1833 env::remove_var(v);
1834 }
1835 for (k, v) in case["env"].as_object().expect("env map") {
1836 env::set_var(k, v.as_str().expect("env value"));
1837 }
1838 let got = default_data_home();
1839 assert_eq!(
1840 got.to_string_lossy(),
1841 case["expect"].as_str().expect("expect"),
1842 "golden case '{name}' diverged"
1843 );
1844 ran += 1;
1845 }
1846 assert!(
1848 ran >= 6,
1849 "only {ran} golden cases ran; fixture or filter broken"
1850 );
1851
1852 for (k, v) in saved {
1853 match v {
1854 Some(val) => env::set_var(k, val),
1855 None => env::remove_var(k),
1856 }
1857 }
1858 }
1859
1860 #[test]
1865 fn daemon_run_dir_refuses_a_relative_data_home_and_names_the_variables() {
1866 for data_home in [PathBuf::from(".local/share"), PathBuf::from("relative-xdg")] {
1867 let error = daemon_run_dir_from(data_home.clone())
1868 .expect_err("a relative data home must be refused");
1869 assert_eq!(
1870 error,
1871 DaemonRunDirError::RelativeDataHome {
1872 data_home: data_home.clone()
1873 }
1874 );
1875 let message = error.to_string();
1876 assert!(
1877 message.contains("XDG_DATA_HOME") && message.contains("HOME"),
1878 "the refusal must name the variables to set: {message}"
1879 );
1880 }
1881 }
1882
1883 #[test]
1884 fn daemon_run_dir_under_an_absolute_data_home_is_cortexkit_run() {
1885 let data_home = env::temp_dir().join("subc-run-dir-probe").join("data");
1886 assert!(data_home.is_absolute());
1887 assert_eq!(
1888 daemon_run_dir_from(data_home.clone()),
1889 Ok(data_home.join("cortexkit").join("run"))
1890 );
1891 }
1892
1893 #[test]
1899 fn default_config_home_matches_golden_fixture() {
1900 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1901 let doc: serde_json::Value =
1902 serde_json::from_str(include_str!("../tests/golden/config_home_resolution.json"))
1903 .expect("golden parses");
1904 let vars = ["XDG_CONFIG_HOME", "APPDATA", "USERPROFILE", "HOME"];
1905 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1906 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1907 let platform_matches =
1908 |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1909
1910 let mut ran = 0usize;
1911 for case in doc["cases"].as_array().expect("cases array") {
1912 let name = case["name"].as_str().expect("name");
1913 if !platform_matches(case["platform"].as_str().expect("platform")) {
1914 continue;
1915 }
1916 for v in vars {
1917 env::remove_var(v);
1918 }
1919 for (k, v) in case["env"].as_object().expect("env map") {
1920 env::set_var(k, v.as_str().expect("env value"));
1921 }
1922 let got = default_config_home();
1923 assert_eq!(
1924 got.to_string_lossy(),
1925 case["expect"].as_str().expect("expect"),
1926 "golden case '{name}' diverged"
1927 );
1928 ran += 1;
1929 }
1930 assert!(
1931 ran >= 6,
1932 "only {ran} golden cases ran; fixture or filter broken"
1933 );
1934
1935 for (k, v) in saved {
1936 match v {
1937 Some(val) => env::set_var(k, val),
1938 None => env::remove_var(k),
1939 }
1940 }
1941 }
1942
1943 #[test]
1950 fn relative_storage_data_home_is_refused_at_parse() {
1951 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1952 let path = Path::new("/golden/subc.jsonc");
1953
1954 let doc =
1956 r#"{ "version": 1, "storage": { "backend": "sqlite", "data_home": "relative/home" } }"#;
1957 let err = parse_doc(doc, path).expect_err("relative data_home must refuse");
1958 assert!(
1959 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1960 if message.contains("relative path relative/home")),
1961 "wrong refusal: {err:?}"
1962 );
1963
1964 let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1966 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1967 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1968 for v in vars {
1969 env::remove_var(v);
1970 }
1971 let doc = r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#;
1972 let err = parse_doc(doc, path).expect_err("no home in env must refuse");
1973 assert!(
1974 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1975 if message.contains("no absolute XDG_DATA_HOME")),
1976 "wrong refusal: {err:?}"
1977 );
1978
1979 let want = abs("/abs/home");
1983 let doc = format!(
1984 r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
1985 serde_json::to_string(&want).expect("json path")
1986 );
1987 let cfg = parse_doc(&doc, path).expect("absolute data_home parses");
1988 assert!(matches!(
1989 cfg.storage,
1990 Some(StorageConfig::Sqlite { ref data_home }) if *data_home == want
1991 ));
1992
1993 for (k, v) in saved {
1994 match v {
1995 Some(val) => env::set_var(k, val),
1996 None => env::remove_var(k),
1997 }
1998 }
1999 }
2000
2001 #[test]
2002 fn restart_required_sections_are_the_rescan_cannot_apply_set() {
2003 assert_eq!(
2004 RestartRequiredSection::ALL.map(RestartRequiredSection::label),
2005 [
2006 "port",
2007 "storage",
2008 "admission_facts_carrier_module_id",
2009 "admission_facts_targets",
2010 "scope_authority_owners",
2011 "federated_scope_owner",
2012 "privileged_operator_prompt",
2013 ]
2014 );
2015 }
2016
2017 #[test]
2018 fn privileged_operator_prompt_defaults_to_log_and_accepts_both_modes() {
2019 let path = Path::new("/tmp/subc.jsonc");
2020 let config = parse_doc(r#"{"version":1}"#, path).unwrap();
2021 assert_eq!(
2022 config.privileged_operator_prompt,
2023 PrivilegedOperatorPrompt::Log
2024 );
2025 for (value, expected) in [
2026 ("log", PrivilegedOperatorPrompt::Log),
2027 ("enforce", PrivilegedOperatorPrompt::Enforce),
2028 ] {
2029 let config = parse_doc(
2030 &format!(r#"{{"version":1,"privileged_operator_prompt":"{value}"}}"#),
2031 path,
2032 )
2033 .unwrap();
2034 assert_eq!(config.privileged_operator_prompt, expected);
2035 }
2036 }
2037
2038 #[test]
2039 fn privileged_operator_prompt_refuses_unknown_values_and_wrong_types() {
2040 let path = Path::new("/tmp/subc.jsonc");
2041 for value in [r#""unknown""#, r#""Enforce""#, "null", "true", "1", "{}"] {
2042 let error = parse_doc(
2043 &format!(r#"{{"version":1,"privileged_operator_prompt":{value}}}"#),
2044 path,
2045 )
2046 .unwrap_err();
2047 assert!(matches!(error, DaemonConfigError::InvalidJson { .. }));
2048 }
2049 }
2050
2051 #[test]
2052 fn scope_authority_owners_defaults_to_the_session_runtime() {
2053 let config = parse_doc(r#"{ "version": 1 }"#, Path::new("/tmp/subc.jsonc")).unwrap();
2054 assert_eq!(
2055 config.scope_authority_owners,
2056 vec!["prefrontal-core", "prefrontal"]
2057 );
2058 }
2059
2060 #[test]
2061 fn federated_scope_owner_defaults_and_is_validated_and_restart_required() {
2062 let config = parse_doc(r#"{ "version": 1 }"#, Path::new("/fixture/subc.jsonc")).unwrap();
2063 assert_eq!(config.federated_scope_owner, "callosum");
2064 assert!(!config
2065 .scope_authority_owners
2066 .contains(&config.federated_scope_owner));
2067 let configured = parse_doc(
2068 r#"{ "version": 1, "federated_scope_owner": "peer-carrier" }"#,
2069 Path::new("/fixture/subc.jsonc"),
2070 )
2071 .unwrap();
2072 assert_eq!(configured.federated_scope_owner, "peer-carrier");
2073 assert!(RestartRequiredSection::ALL.contains(&RestartRequiredSection::FederatedScopeOwner));
2074 for invalid in ["", "..", "a/b", "a\\b"] {
2075 let body = serde_json::json!({"version": 1, "federated_scope_owner": invalid});
2076 assert!(
2077 parse_doc(&body.to_string(), Path::new("/fixture/subc.jsonc"))
2078 .unwrap_err()
2079 .to_string()
2080 .contains("federated_scope_owner")
2081 );
2082 }
2083 }
2084
2085 #[test]
2086 fn scope_authority_owners_is_read_when_set_and_refuses_an_empty_id() {
2087 let config = parse_doc(
2088 r#"{ "version": 1, "scope_authority_owners": ["a", "b"] }"#,
2089 Path::new("/tmp/subc.jsonc"),
2090 )
2091 .unwrap();
2092 assert_eq!(config.scope_authority_owners, vec!["a", "b"]);
2093 let config = parse_doc(
2096 r#"{ "version": 1, "scope_authority_owners": [] }"#,
2097 Path::new("/tmp/subc.jsonc"),
2098 )
2099 .unwrap();
2100 assert!(config.scope_authority_owners.is_empty());
2101 let error = parse_doc(
2102 r#"{ "version": 1, "scope_authority_owners": [""] }"#,
2103 Path::new("/tmp/subc.jsonc"),
2104 )
2105 .expect_err("an empty module id is refused");
2106 assert!(
2107 error.to_string().contains("scope_authority_owners"),
2108 "{error}"
2109 );
2110 }
2111
2112 #[test]
2113 fn no_storage_section_yields_none() {
2114 let config = parse_doc(
2115 r#"{ "version": 1, "modules": {} }"#,
2116 Path::new("/tmp/subc.jsonc"),
2117 )
2118 .expect("parse");
2119 assert_eq!(config.storage, None);
2120 }
2121
2122 #[test]
2123 fn sqlite_storage_parses_with_explicit_data_home() {
2124 let config = parse_doc(
2125 &format!(
2126 r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
2127 serde_json::to_string(&abs("/data")).expect("json path")
2128 ),
2129 Path::new("/tmp/subc.jsonc"),
2130 )
2131 .expect("parse");
2132 assert_eq!(
2133 config.storage,
2134 Some(StorageConfig::Sqlite {
2135 data_home: abs("/data")
2136 })
2137 );
2138 }
2139
2140 #[test]
2141 fn sqlite_storage_defaults_data_home_when_omitted() {
2142 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
2148 std::env::set_var("XDG_DATA_HOME", abs("/forced/data/home"));
2149 let config = parse_doc(
2150 r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#,
2151 Path::new("/tmp/subc.jsonc"),
2152 )
2153 .expect("parse");
2154 std::env::remove_var("XDG_DATA_HOME");
2155 assert_eq!(
2156 config.storage,
2157 Some(StorageConfig::Sqlite {
2158 data_home: abs("/forced/data/home")
2159 })
2160 );
2161 }
2162
2163 #[test]
2164 fn descriptor_for_matches_store_types_shape() {
2165 let cfg = StorageConfig::Sqlite {
2169 data_home: PathBuf::from("/data"),
2170 };
2171 let descriptor = cfg.descriptor_for("alfonso-routing");
2172 assert_eq!(
2173 descriptor,
2174 serde_json::json!({
2175 "module_id": "alfonso-routing",
2176 "storage_namespace": "default",
2177 "isolation": { "kind": "module" },
2178 "backend": {
2179 "backend": "sqlite",
2180 "path": "/data/cortexkit/alfonso-routing/store.db"
2181 }
2182 })
2183 );
2184 }
2185
2186 #[test]
2187 fn path_hazard_module_id_refuses_config_parse() {
2188 let path = Path::new("/tmp/subc.jsonc");
2189 let err = parse_doc(
2190 r#"{ "version": 1, "modules": { "../escape": { "program": "x" } } }"#,
2191 path,
2192 )
2193 .expect_err("separator-bearing module id must refuse");
2194 let text = format!("{err}");
2195 assert!(
2196 text.contains("not usable as a path component"),
2197 "refusal must name the hazard: {text}"
2198 );
2199 }
2200
2201 #[test]
2202 fn daemon_module_id_is_reserved() {
2203 let path = Path::new("/tmp/subc.jsonc");
2204 let err = parse_doc(
2205 r#"{ "version": 1, "modules": { "subc": { "program": "x" } } }"#,
2206 path,
2207 )
2208 .expect_err("a configured module must not take the daemon's id");
2209 assert!(
2210 matches!(err, DaemonConfigError::InvalidValue { message, .. }
2211 if message == "module id 'subc' is reserved for the daemon")
2212 );
2213
2214 parse_doc(
2215 r#"{ "version": 1, "modules": { "subc-helper": { "program": "x" } } }"#,
2216 path,
2217 )
2218 .expect("only the exact daemon id is reserved");
2219 }
2220
2221 #[test]
2222 fn drain_timeout_resolves_module_over_daemon_over_absent() {
2223 let path = Path::new("/tmp/subc.jsonc");
2224 let config = parse_doc(
2225 r#"
2226 {
2227 "version": 1,
2228 "drain_timeout_ms": 45000,
2229 "modules": {
2230 "fast": { "program": "fast", "drain_timeout_ms": 0 },
2231 "slow": { "program": "slow", "drain_timeout_ms": 120000 },
2232 "inherits": { "program": "inherits" }
2233 }
2234 }
2235 "#,
2236 path,
2237 )
2238 .unwrap();
2239 let by_id = |id: &str| {
2240 config
2241 .modules
2242 .iter()
2243 .find(|m| m.module_id == id)
2244 .unwrap()
2245 .drain_timeout_ms
2246 };
2247 assert_eq!(by_id("fast"), Some(0));
2250 assert_eq!(by_id("slow"), Some(120_000));
2251 assert_eq!(by_id("inherits"), Some(45_000));
2253 assert_eq!(config.drain_timeout_ms, Some(45_000));
2254 }
2255
2256 #[test]
2257 fn drain_timeout_absent_everywhere_stays_none_for_builtin_default() {
2258 let path = Path::new("/tmp/subc.jsonc");
2259 let config = parse_doc(
2260 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2261 path,
2262 )
2263 .unwrap();
2264 assert_eq!(config.modules[0].drain_timeout_ms, None);
2268 assert_eq!(config.drain_timeout_ms, None);
2269 }
2270
2271 #[test]
2272 fn route_bind_relay_timeout_resolves_module_over_daemon_over_absent() {
2273 let path = Path::new("/tmp/subc.jsonc");
2279 let config = parse_doc(
2280 r#"
2281 {
2282 "version": 1,
2283 "route_bind_relay_timeout_ms": 30000,
2284 "modules": {
2285 "tight": { "program": "tight", "route_bind_relay_timeout_ms": 5000 },
2286 "loose": { "program": "loose", "route_bind_relay_timeout_ms": 60000 },
2287 "inherits": { "program": "inherits" }
2288 }
2289 }
2290 "#,
2291 path,
2292 )
2293 .unwrap();
2294 let by_id = |id: &str| {
2295 config
2296 .modules
2297 .iter()
2298 .find(|m| m.module_id == id)
2299 .unwrap()
2300 .route_bind_relay_timeout_ms
2301 };
2302 assert_eq!(by_id("tight"), Some(5_000));
2304 assert_eq!(by_id("loose"), Some(60_000));
2305 assert_eq!(by_id("inherits"), Some(30_000));
2307 assert_eq!(config.route_bind_relay_timeout_ms, Some(30_000));
2308 }
2309
2310 #[test]
2311 fn log_tag_keys_must_be_logger_names_and_the_error_names_the_key() {
2312 let path = Path::new("/tmp/subc.jsonc");
2313 for bad in ["Perf", "a b", "perf.", ".perf", "gc..walk", "a=b"] {
2314 let doc = format!(
2315 r#"{{ "version": 1, "modules": {{ "m": {{ "program": "m", "log": {{ "tags": {{ "{bad}": "debug" }} }} }} }} }}"#
2316 );
2317 let err = parse_doc(&doc, path).expect_err(bad);
2318 let text = format!("{err}");
2319 assert!(
2320 text.contains(&format!("{bad:?}")),
2321 "must name the key: {text}"
2322 );
2323 assert!(
2324 text.contains("logger name"),
2325 "must say what a key is: {text}"
2326 );
2327 }
2328 let ok = parse_doc(
2330 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "tags": { "perf": "debug", "gc.walk": "trace", "m": "error", "a-b": "info" } } } } }"#,
2331 path,
2332 );
2333 assert!(ok.is_ok(), "{ok:?}");
2334 }
2335
2336 #[test]
2337 fn log_filter_spec_prefixes_bare_keys_with_the_module_and_passes_absolute_ones() {
2338 let path = Path::new("/tmp/subc.jsonc");
2339 let config = parse_doc(
2340 r#"{ "version": 1, "modules": { "synapse": { "program": "s", "log": { "level": "warn", "tags": { "perf": "debug", "gc.walk": "trace", "synapse": "error", "other.x": "info" } } } } }"#,
2341 path,
2342 )
2343 .unwrap();
2344 let log = config.modules[0].log.as_ref().unwrap();
2345 assert_eq!(
2347 log.filter_spec("synapse"),
2348 "warn,gc.walk=trace,other.x=info,synapse.perf=debug,synapse=error"
2349 );
2350 }
2351
2352 #[test]
2353 fn log_alarm_segment_mb_defaults_to_the_crate_default_and_refuses_zero() {
2354 let path = Path::new("/tmp/subc.jsonc");
2355 let config = parse_doc(
2356 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "level": "info" } } } }"#,
2357 path,
2358 )
2359 .unwrap();
2360 assert_eq!(
2361 config.modules[0].log.as_ref().unwrap().alarm_segment_mb,
2362 cortexkit_log::SegmentRetention::default().alarm_segment_mb
2363 );
2364 let err = parse_doc(
2365 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "alarm_segment_mb": 0 } } } }"#,
2366 path,
2367 )
2368 .expect_err("zero alarm must refuse");
2369 assert!(format!("{err}").contains("alarm_segment_mb"));
2370 }
2371
2372 #[test]
2373 fn route_bind_relay_timeout_zero_at_daemon_layer_is_refused() {
2374 let path = Path::new("/tmp/subc.jsonc");
2375 let err = parse_doc(
2376 r#"
2377 {
2378 "version": 1,
2379 "route_bind_relay_timeout_ms": 0,
2380 "modules": { "m": { "program": "m" } }
2381 }
2382 "#,
2383 path,
2384 )
2385 .expect_err("a daemon-wide zero budget must refuse parse");
2386 let text = format!("{err}");
2387 assert!(
2388 text.contains("route_bind_relay_timeout_ms"),
2389 "error must name the offending key: {text}"
2390 );
2391 assert!(
2392 text.contains("enabled: false"),
2393 "error must name the remedy (enable false): {text}"
2394 );
2395 }
2396
2397 #[test]
2398 fn route_bind_relay_timeout_zero_at_module_layer_is_refused() {
2399 let path = Path::new("/tmp/subc.jsonc");
2400 let err = parse_doc(
2401 r#"
2402 {
2403 "version": 1,
2404 "modules": {
2405 "good": { "program": "good" },
2406 "broken": { "program": "broken", "route_bind_relay_timeout_ms": 0 }
2407 }
2408 }
2409 "#,
2410 path,
2411 )
2412 .expect_err("a per-module zero budget must refuse parse");
2413 let text = format!("{err}");
2414 assert!(
2415 text.contains("route_bind_relay_timeout_ms"),
2416 "error must name the offending key: {text}"
2417 );
2418 assert!(
2419 text.contains("broken"),
2420 "error must name the offending module id: {text}"
2421 );
2422 assert!(
2423 text.contains("enabled: false"),
2424 "error must name the remedy (enable false): {text}"
2425 );
2426 }
2427
2428 #[test]
2429 fn drain_timeout_zero_still_parses_for_wedge_bounces() {
2430 let path = Path::new("/tmp/subc.jsonc");
2436 let config = parse_doc(
2437 r#"
2438 {
2439 "version": 1,
2440 "drain_timeout_ms": 0,
2441 "modules": {
2442 "wedge": { "program": "wedge", "drain_timeout_ms": 0 }
2443 }
2444 }
2445 "#,
2446 path,
2447 )
2448 .expect("drain_timeout_ms: 0 must still parse; wedge-bounce uses it");
2449 let wedge = config
2450 .modules
2451 .iter()
2452 .find(|m| m.module_id == "wedge")
2453 .unwrap();
2454 assert_eq!(wedge.drain_timeout_ms, Some(0));
2455 assert_eq!(config.drain_timeout_ms, Some(0));
2456 }
2457
2458 #[test]
2459 fn route_bind_relay_timeout_absent_everywhere_stays_none_for_builtin_default() {
2460 let path = Path::new("/tmp/subc.jsonc");
2465 let config = parse_doc(
2466 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2467 path,
2468 )
2469 .unwrap();
2470 assert_eq!(config.modules[0].route_bind_relay_timeout_ms, None);
2471 assert_eq!(config.route_bind_relay_timeout_ms, None);
2472 }
2473
2474 #[test]
2480 fn a_config_without_a_restart_block_keeps_the_supervisor_defaults() {
2481 let path = Path::new("/tmp/subc.jsonc");
2482 let config = parse_doc(
2483 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2484 path,
2485 )
2486 .unwrap();
2487 assert_eq!(config.modules[0].restart.max_restarts, 3);
2488 assert_eq!(config.modules[0].restart.window, Duration::from_secs(600));
2489 assert_eq!(
2490 config.modules[0].restart.backoff,
2491 Duration::from_millis(100)
2492 );
2493 assert_eq!(
2494 config.modules[0].restart.max_backoff,
2495 Duration::from_secs(30)
2496 );
2497 }
2498
2499 #[test]
2500 fn register_timeout_config_accepts_bounds_and_rejects_outside_them() {
2501 let path = Path::new("subc.jsonc");
2502 for seconds in [10, 3600] {
2503 let doc = format!(
2504 r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{seconds}}}}}}}"#
2505 );
2506 let config = parse_doc(&doc, path).unwrap();
2507 assert_eq!(
2508 config.modules[0].register_timeout,
2509 Duration::from_secs(seconds)
2510 );
2511 }
2512 for value in ["9", "3601"] {
2513 let doc = format!(
2514 r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{value}}}}}}}"#
2515 );
2516 let error = parse_doc(&doc, path).unwrap_err().to_string();
2517 assert!(error.contains("register_timeout_s"), "{value}: {error}");
2518 }
2519 let config = parse_doc(r#"{"version":1,"modules":{"m":{"program":"m"}}}"#, path).unwrap();
2520 assert_eq!(config.modules[0].register_timeout, Duration::from_secs(120));
2521 }
2522
2523 #[test]
2524 fn a_restart_block_resolves_each_key_independently() {
2525 let path = Path::new("/tmp/subc.jsonc");
2526 let config = parse_doc(
2527 r#"
2528 {
2529 "version": 1,
2530 "modules": {
2531 "all": {
2532 "program": "all",
2533 "restart": { "max_restarts": 5, "window_secs": 60, "backoff_ms": 250, "max_backoff_ms": 5000 }
2534 },
2535 "window-only": {
2536 "program": "window-only",
2537 "restart": { "window_secs": 7200 }
2538 },
2539 "never": {
2540 "program": "never",
2541 "restart": { "max_restarts": 0 }
2542 }
2543 }
2544 }
2545 "#,
2546 path,
2547 )
2548 .unwrap();
2549 let by_id = |id: &str| {
2550 config
2551 .modules
2552 .iter()
2553 .find(|m| m.module_id == id)
2554 .unwrap()
2555 .restart
2556 };
2557
2558 let all = by_id("all");
2559 assert_eq!(all.max_restarts, 5);
2560 assert_eq!(all.window, Duration::from_secs(60));
2561 assert_eq!(all.backoff, Duration::from_millis(250));
2562 assert_eq!(all.max_backoff, Duration::from_secs(5));
2563
2564 let window_only = by_id("window-only");
2567 assert_eq!(window_only.max_restarts, 3);
2568 assert_eq!(window_only.window, Duration::from_secs(7_200));
2569 assert_eq!(window_only.backoff, Duration::from_millis(100));
2570 assert_eq!(window_only.max_backoff, Duration::from_secs(30));
2571
2572 assert_eq!(by_id("never").max_restarts, 0);
2575 }
2576
2577 #[test]
2581 fn restart_window_zero_is_refused_by_name() {
2582 let path = Path::new("/tmp/subc.jsonc");
2583 let err = parse_doc(
2584 r#"
2585 {
2586 "version": 1,
2587 "modules": {
2588 "good": { "program": "good" },
2589 "broken": { "program": "broken", "restart": { "window_secs": 0 } }
2590 }
2591 }
2592 "#,
2593 path,
2594 )
2595 .expect_err("a zero crash window must refuse parse");
2596 assert!(
2597 matches!(err, DaemonConfigError::InvalidValue { .. }),
2598 "a zero window is an invalid value, not a parse failure: {err:?}"
2599 );
2600 let text = format!("{err}");
2601 assert!(
2602 text.contains("restart.window_secs"),
2603 "error must name the offending key: {text}"
2604 );
2605 assert!(
2606 text.contains("broken"),
2607 "error must name the offending module id: {text}"
2608 );
2609 assert!(
2610 text.contains("max_restarts: 0"),
2611 "error must name the setting that actually stops restarts: {text}"
2612 );
2613 }
2614
2615 #[test]
2616 fn restart_max_backoff_below_backoff_is_refused_by_name() {
2617 let path = Path::new("/tmp/subc.jsonc");
2618 let err = parse_doc(
2619 r#"
2620 {
2621 "version": 1,
2622 "modules": {
2623 "broken": {
2624 "program": "broken",
2625 "restart": { "backoff_ms": 1000, "max_backoff_ms": 999 }
2626 }
2627 }
2628 }
2629 "#,
2630 path,
2631 )
2632 .expect_err("a maximum below the base backoff must refuse parse");
2633 assert!(
2634 matches!(err, DaemonConfigError::InvalidValue { .. }),
2635 "an invalid restart bound must be an InvalidValue: {err:?}"
2636 );
2637 let text = format!("{err}");
2638 assert!(
2639 text.contains("restart.max_backoff_ms"),
2640 "error must name max_backoff_ms: {text}"
2641 );
2642 assert!(
2643 text.contains("restart.backoff_ms"),
2644 "error must name backoff_ms: {text}"
2645 );
2646 assert!(
2647 text.contains("broken"),
2648 "error must name the offending module id: {text}"
2649 );
2650 }
2651
2652 #[test]
2653 fn parse_jsonc_defaults_and_ignores_unknown_fields() {
2654 let path = Path::new("/tmp/subc.jsonc");
2655 let config = parse_doc(
2656 r#"
2657 {
2658 // forward-compatible root field
2659 "version": 1,
2660 "unknown": { "ignored": true },
2661 "modules": {
2662 "aft": {
2663 "program": "aft",
2664 "args": ["module",],
2665 "env": { "A": "B", },
2666 "future": 42,
2667 },
2668 "disabled": { "program": "disabled", "enabled": false }
2669 },
2670 }
2671 "#,
2672 path,
2673 )
2674 .unwrap();
2675
2676 assert_eq!(config.port, None);
2677 assert_eq!(config.modules.len(), 2);
2678 assert_eq!(config.modules[0].module_id, "aft");
2679 assert_eq!(config.modules[0].program, PathBuf::from("aft"));
2680 assert_eq!(config.modules[0].args, ["module"]);
2681 assert_eq!(config.modules[0].env, [("A".to_string(), "B".to_string())]);
2682 assert!(config.modules[0].enabled);
2683 assert!(config.modules[0].reserved_prefixes.is_empty());
2684 assert_eq!(config.modules[0].health, HealthConfig::default());
2685 assert!(!config.modules[1].enabled);
2686 }
2687
2688 #[test]
2689 fn reserved_capabilities_accept_unknown_bound_modules_and_refuse_bad_identifiers() {
2690 let path = Path::new("/tmp/subc.jsonc");
2691 let config = parse_doc(
2692 r#"{
2693 "version": 1,
2694 "reserved_capabilities": {
2695 "credentials-provider/v1": "future-vault"
2696 },
2697 "modules": {}
2698 }"#,
2699 path,
2700 )
2701 .expect("a binding may predate its provider installation");
2702 assert_eq!(
2703 config.reserved_capabilities,
2704 BTreeMap::from([(
2705 "credentials-provider/v1".to_string(),
2706 "future-vault".to_string()
2707 )])
2708 );
2709
2710 let error = parse_doc(
2711 r#"{
2712 "version": 1,
2713 "reserved_capabilities": { "Credentials/v1": "vault" },
2714 "modules": {}
2715 }"#,
2716 path,
2717 )
2718 .expect_err("reserved capabilities use the capability identifier grammar");
2719 assert!(error.to_string().contains("reserved_capabilities key"));
2720 }
2721
2722 #[test]
2723 fn retired_launch_nonce_env_is_ignored_for_any_value() {
2724 let parse = |field: &str| {
2725 parse_doc(
2726 &format!(r#"{{"version":1,"modules":{{"probe":{{"program":"probe"{field}}}}}}}"#),
2727 Path::new("subc.jsonc"),
2728 )
2729 .unwrap()
2730 .modules
2731 .remove(0)
2732 .module_spec()
2733 };
2734 for value in ["true", "false", "null", "0", "\"false\"", "[]", "{}"] {
2735 assert_eq!(
2736 parse(""),
2737 parse(&format!(",\"launch_nonce_env\":{value}")),
2738 "the retired key must not change the launch spec or require a restart"
2739 );
2740 }
2741 }
2742
2743 #[test]
2746 fn an_absent_protocol_key_and_an_explicit_subc_are_the_same_module() {
2747 let parse = |module_body: &str| {
2748 parse_doc(
2749 &format!(
2750 r#"{{
2751 "version": 1,
2752 "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2753 }}"#
2754 ),
2755 Path::new("subc.jsonc"),
2756 )
2757 .expect("module parses")
2758 .modules
2759 .remove(0)
2760 };
2761
2762 let absent = parse("");
2763 let explicit = parse(r#", "protocol": "subc""#);
2764 let none = parse(r#", "protocol": "none""#);
2765
2766 assert_eq!(absent.protocol, ModuleProtocol::Subc);
2767 assert_eq!(explicit.protocol, ModuleProtocol::Subc);
2768 assert_eq!(
2769 absent, explicit,
2770 "an absent protocol key must produce exactly the module an explicit subc does"
2771 );
2772 assert_eq!(none.protocol, ModuleProtocol::None);
2773 assert_eq!(none.module_spec().protocol, ModuleProtocol::None);
2777 }
2778
2779 #[test]
2783 fn overlap_defaults_to_exclusive_and_only_safe_opts_in() {
2784 let parse = |module_body: &str| {
2785 parse_doc(
2786 &format!(
2787 r#"{{
2788 "version": 1,
2789 "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2790 }}"#
2791 ),
2792 Path::new("subc.jsonc"),
2793 )
2794 };
2795
2796 let absent = parse("").unwrap().modules.remove(0);
2797 assert_eq!(absent.overlap, ModuleOverlap::Exclusive);
2798 assert_eq!(absent.module_spec().overlap, ModuleOverlap::Exclusive);
2799 let safe = parse(r#", "overlap": "safe""#).unwrap().modules.remove(0);
2800 assert_eq!(safe.module_spec().overlap, ModuleOverlap::Safe);
2801 let typo = parse(r#", "overlap": "sfae""#).expect_err("an unknown overlap is refused");
2802 assert!(typo.to_string().contains("sfae"), "{typo}");
2803 }
2804
2805 #[test]
2806 fn carry_containment_defaults_off_and_refuses_overlap() {
2807 let parse = |module_body: &str| {
2808 parse_doc(
2809 &format!(
2810 r#"{{
2811 "version": 1,
2812 "modules": {{ "worker": {{ "program": "worker"{module_body} }} }}
2813 }}"#
2814 ),
2815 Path::new("subc.jsonc"),
2816 )
2817 };
2818
2819 let absent = parse("").unwrap().modules.remove(0);
2820 let explicit_off = parse(r#", "carry_containment": false"#)
2821 .unwrap()
2822 .modules
2823 .remove(0);
2824 assert_eq!(absent, explicit_off);
2825 assert!(!absent.module_spec().carry_containment);
2826 let carried = parse(r#", "carry_containment": true"#)
2827 .unwrap()
2828 .modules
2829 .remove(0);
2830 assert!(carried.module_spec().carry_containment);
2831 let error = parse(r#", "carry_containment": true, "overlap": "safe""#)
2832 .expect_err("a carried container cannot have overlapping leaders");
2833 let message = error.to_string();
2834 assert!(message.contains("worker"), "{message}");
2835 assert!(message.contains("carry_containment"), "{message}");
2836 assert!(message.contains("overlap"), "{message}");
2837 }
2838
2839 #[test]
2843 fn the_spawn_role_is_refused_as_a_configured_env_key() {
2844 let error = parse_doc(
2845 r#"{
2846 "version": 1,
2847 "modules": { "aft": { "program": "aft", "env": { "SUBC_SPAWN_ROLE": "swap_candidate" } } }
2848 }"#,
2849 Path::new("subc.jsonc"),
2850 )
2851 .expect_err("SUBC_SPAWN_ROLE must not be configurable");
2852 assert!(
2853 matches!(error, DaemonConfigError::InvalidValue { .. }),
2854 "expected InvalidValue, got {error:?}"
2855 );
2856 assert!(error.to_string().contains("SUBC_SPAWN_ROLE"), "{error}");
2857 }
2858
2859 #[test]
2865 fn an_unsupported_protocol_value_is_refused_by_name() {
2866 let error = parse_doc(
2867 r#"{
2868 "version": 1,
2869 "modules": { "nats": { "program": "nats-server", "protocol": "grpc" } }
2870 }"#,
2871 Path::new("subc.jsonc"),
2872 )
2873 .expect_err("an unknown protocol must not fall back to a default");
2874
2875 assert!(
2876 matches!(error, DaemonConfigError::InvalidValue { .. }),
2877 "expected InvalidValue, got {error:?}"
2878 );
2879 let message = error.to_string();
2880 assert!(
2881 message.contains("grpc"),
2882 "the refusal must name the offending value: {message}"
2883 );
2884 assert!(
2885 message.contains("nats"),
2886 "the refusal must name the module so it can be found in the file: {message}"
2887 );
2888 }
2889
2890 #[test]
2894 fn reserved_true_with_protocol_none_is_refused_with_the_reason() {
2895 let error = parse_doc(
2896 r#"{
2897 "version": 1,
2898 "modules": {
2899 "nats": { "program": "nats-server", "protocol": "none", "reserved": true }
2900 }
2901 }"#,
2902 Path::new("subc.jsonc"),
2903 )
2904 .expect_err("a reservation that can never be checked must not parse");
2905
2906 assert!(
2907 matches!(error, DaemonConfigError::InvalidValue { .. }),
2908 "expected InvalidValue, got {error:?}"
2909 );
2910 let message = error.to_string();
2911 assert!(
2912 message.contains("nats") && message.contains("reserved"),
2913 "the refusal must name the module and the offending key: {message}"
2914 );
2915 assert!(
2916 message.contains("HELLO") || message.contains("never registers"),
2917 "the refusal must say WHY the pair cannot work: {message}"
2918 );
2919 }
2920
2921 #[test]
2922 fn reserved_prefixes_parse_for_reserved_modules() {
2923 let config = parse_doc(
2924 r#"
2925 {
2926 "version": 1,
2927 "modules": {
2928 "federation": {
2929 "program": "fed",
2930 "reserved": true,
2931 "reserved_prefixes": ["fed:"]
2932 }
2933 }
2934 }
2935 "#,
2936 Path::new("subc.jsonc"),
2937 )
2938 .unwrap();
2939
2940 assert_eq!(config.modules[0].reserved_prefixes, ["fed:".to_string()]);
2941 }
2942
2943 #[test]
2944 fn reserved_prefixes_reject_bad_boundaries_and_owners() {
2945 let missing_delimiter = parse_doc(
2946 r#"{
2947 "version": 1,
2948 "modules": {
2949 "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed"] }
2950 }
2951 }"#,
2952 Path::new("subc.jsonc"),
2953 )
2954 .unwrap_err();
2955 assert!(matches!(
2956 missing_delimiter,
2957 DaemonConfigError::InvalidValue { .. }
2958 ));
2959
2960 let non_reserved_owner = parse_doc(
2961 r#"{
2962 "version": 1,
2963 "modules": {
2964 "federation": { "program": "fed", "reserved_prefixes": ["fed:"] }
2965 }
2966 }"#,
2967 Path::new("subc.jsonc"),
2968 )
2969 .unwrap_err();
2970 assert!(matches!(
2971 non_reserved_owner,
2972 DaemonConfigError::InvalidValue { .. }
2973 ));
2974 }
2975
2976 #[test]
2977 fn reserved_prefixes_reject_cross_owner_overlap_and_exact_id_collisions() {
2978 let overlap = parse_doc(
2979 r#"{
2980 "version": 1,
2981 "modules": {
2982 "fed-owner": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2983 "sub-owner": { "program": "fed-sub", "reserved": true, "reserved_prefixes": ["fed:sub:"] }
2984 }
2985 }"#,
2986 Path::new("subc.jsonc"),
2987 )
2988 .unwrap_err();
2989 assert!(matches!(overlap, DaemonConfigError::InvalidValue { .. }));
2990
2991 let exact_collision = parse_doc(
2992 r#"{
2993 "version": 1,
2994 "modules": {
2995 "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2996 "fed:special": { "program": "special" }
2997 }
2998 }"#,
2999 Path::new("subc.jsonc"),
3000 )
3001 .unwrap_err();
3002 assert!(matches!(
3003 exact_collision,
3004 DaemonConfigError::InvalidValue { .. }
3005 ));
3006 }
3007
3008 #[test]
3009 fn health_config_parses_and_ignores_unknown_fields() {
3010 let config = parse_doc(
3011 r#"
3012 {
3013 "version": 1,
3014 "modules": {
3015 "aft": {
3016 "program": "aft",
3017 "health": {
3018 "cadence_ms": 100,
3019 "deadline_ms": 20,
3020 "failure_threshold": 2,
3021 "on_degraded": "report",
3022 "on_failing": "restart",
3023 "critical": true,
3024 "future": "ignored"
3025 }
3026 }
3027 }
3028 }
3029 "#,
3030 Path::new("subc.jsonc"),
3031 )
3032 .unwrap();
3033
3034 let health = &config.modules[0].health;
3035 assert_eq!(health.cadence, std::time::Duration::from_millis(100));
3036 assert_eq!(health.deadline, std::time::Duration::from_millis(20));
3037 assert_eq!(health.failure_threshold, 2);
3038 assert_eq!(health.on_degraded, HealthAction::Report);
3039 assert_eq!(health.on_failing, HealthAction::Restart);
3040 assert!(health.critical);
3041 }
3042
3043 #[test]
3044 fn http_health_refuses_non_loopback_https_and_wire_modules() {
3045 for (protocol, url) in [
3046 ("none", "http://example.com/healthz"),
3047 ("none", "https://127.0.0.1/healthz"),
3048 ("subc", "http://127.0.0.1/healthz"),
3049 ] {
3050 let doc = serde_json::json!({"version": 1, "modules": {"bus": {
3051 "program": "nats-server", "protocol": protocol, "health": {"http": url}
3052 }}})
3053 .to_string();
3054 let error = parse_doc(&doc, Path::new("test.jsonc"))
3055 .unwrap_err()
3056 .to_string();
3057 assert!(
3058 error.contains("bus") && error.contains("health.http"),
3059 "{error}"
3060 );
3061 }
3062 }
3063
3064 #[test]
3065 fn health_config_rejects_bad_enum_and_non_positive_numbers() {
3066 let bad_enum = parse_doc(
3067 r#"{
3068 "version": 1,
3069 "modules": { "aft": { "program": "aft", "health": { "on_failing": "page" } } }
3070 }"#,
3071 Path::new("subc.jsonc"),
3072 )
3073 .unwrap_err();
3074 assert!(matches!(bad_enum, DaemonConfigError::InvalidJson { .. }));
3075
3076 let zero = parse_doc(
3077 r#"{
3078 "version": 1,
3079 "modules": { "aft": { "program": "aft", "health": { "cadence_ms": 0 } } }
3080 }"#,
3081 Path::new("subc.jsonc"),
3082 )
3083 .unwrap_err();
3084 assert!(matches!(zero, DaemonConfigError::InvalidValue { .. }));
3085 }
3086
3087 #[test]
3088 fn admission_facts_carrier_requires_non_empty_targets() {
3089 let missing_targets = parse_doc(
3090 r#"{
3091 "version": 1,
3092 "admission_facts_carrier_module_id": "fed",
3093 "modules": { "fed": { "program": "fed", "reserved": true } }
3094 }"#,
3095 Path::new("subc.jsonc"),
3096 )
3097 .unwrap_err();
3098 assert!(
3104 matches!(&missing_targets, DaemonConfigError::InvalidValue { message, .. }
3105 if message.contains("must be present")),
3106 "expected the presence rule, got: {missing_targets:?}"
3107 );
3108
3109 let empty_targets = parse_doc(
3110 r#"{
3111 "version": 1,
3112 "admission_facts_carrier_module_id": "fed",
3113 "admission_facts_targets": [""],
3114 "modules": { "fed": { "program": "fed", "reserved": true } }
3115 }"#,
3116 Path::new("subc.jsonc"),
3117 )
3118 .unwrap_err();
3119 assert!(
3120 matches!(&empty_targets, DaemonConfigError::InvalidValue { message, .. }
3121 if message.contains("must be non-empty")),
3122 "expected the non-empty rule, got: {empty_targets:?}"
3123 );
3124 }
3125
3126 #[test]
3127 fn admission_facts_carrier_must_be_enabled_reserved_and_configured() {
3128 for module in [
3129 r#"{ "program": "fed", "enabled": false, "reserved": true }"#,
3130 r#"{ "program": "fed", "enabled": true, "reserved": false }"#,
3131 ] {
3132 let doc = format!(
3133 r#"{{
3134 "version": 1,
3135 "admission_facts_carrier_module_id": "fed",
3136 "admission_facts_targets": ["target"],
3137 "modules": {{ "fed": {module}, "target": {{ "program": "target" }} }}
3138 }}"#
3139 );
3140 let err = parse_doc(&doc, Path::new("subc.jsonc")).unwrap_err();
3141 assert!(
3145 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
3146 if message.contains("enabled reserved module")),
3147 "expected the enabled-and-reserved rule, got: {err:?}"
3148 );
3149 }
3150
3151 let absent = parse_doc(
3152 r#"{
3153 "version": 1,
3154 "admission_facts_carrier_module_id": "missing",
3155 "admission_facts_targets": ["target"],
3156 "modules": { "target": { "program": "target" } }
3157 }"#,
3158 Path::new("subc.jsonc"),
3159 )
3160 .unwrap_err();
3161 assert!(
3162 matches!(&absent, DaemonConfigError::InvalidValue { message, .. }
3163 if message.contains("must name a configured module")),
3164 "expected the configured-module rule, got: {absent:?}"
3165 );
3166 }
3167
3168 #[test]
3169 fn reject_unsupported_version() {
3170 let err = parse_doc(
3171 r#"{ "version": 2, "modules": {} }"#,
3172 Path::new("subc.jsonc"),
3173 )
3174 .unwrap_err();
3175 assert!(matches!(
3176 err,
3177 DaemonConfigError::UnsupportedVersion { version: 2, .. }
3178 ));
3179 }
3180
3181 #[test]
3182 fn reject_unterminated_block_comment() {
3183 let err = parse_doc(r#"{ "version": 1, /*"#, Path::new("subc.jsonc")).unwrap_err();
3184 assert!(matches!(err, DaemonConfigError::InvalidJsonc { .. }));
3185 }
3186}
3187
3188#[cfg(test)]
3189mod activity_config_tests {
3190 use super::*;
3191
3192 #[test]
3193 fn activity_config_defaults_partial_overrides_and_positive_bounds() {
3194 let path = Path::new("subc.jsonc");
3195 let default = parse_doc_with_activity(r#"{"version":1,"modules":{}}"#, path).unwrap();
3196 assert_eq!(
3197 default.1,
3198 ActivityConfig {
3199 max_age_days: 30,
3200 max_total_mb: 64
3201 }
3202 );
3203 let changed = parse_doc_with_activity(
3204 r#"{"version":1,"activity":{"max_age_days":7,"max_total_mb":8}}"#,
3205 path,
3206 )
3207 .unwrap();
3208 assert_eq!(
3209 changed.1,
3210 ActivityConfig {
3211 max_age_days: 7,
3212 max_total_mb: 8
3213 }
3214 );
3215 let partial =
3216 parse_doc_with_activity(r#"{"version":1,"activity":{"max_age_days":7}}"#, path)
3217 .unwrap();
3218 assert_eq!(
3219 partial.1,
3220 ActivityConfig {
3221 max_age_days: 7,
3222 max_total_mb: 64
3223 }
3224 );
3225 for doc in [
3226 r#"{"version":1,"activity":{"max_age_days":0}}"#,
3227 r#"{"version":1,"activity":{"max_total_mb":0}}"#,
3228 ] {
3229 assert!(parse_doc(doc, path).is_err());
3230 }
3231 assert!(!RestartRequiredSection::ALL
3232 .iter()
3233 .any(|section| section.label() == "activity"));
3234 }
3235}
3236
3237#[cfg(test)]
3238mod registration_declaration_tests {
3239 use super::*;
3240 #[test]
3241 fn registration_declaration_config_bool_is_optional_and_typed() {
3242 let parse = |field: &str| {
3243 parse_doc(
3244 &format!(r#"{{"version":1,"modules":{{"worker":{{"program":"worker"{field}}}}}}}"#),
3245 Path::new("subc.jsonc"),
3246 )
3247 };
3248 assert!(!parse("").unwrap().modules[0].registration_channel);
3249 assert!(
3250 !parse(r#", "registration_channel":false"#).unwrap().modules[0].registration_channel
3251 );
3252 assert!(parse(r#", "registration_channel":true"#).unwrap().modules[0].registration_channel);
3253 assert!(parse(r#", "registration_channel":"true""#).is_err());
3254 }
3255}