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)]
812fn 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
857fn 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 let (program, script) = match (module.program, module.script) {
958 (Some(program), None) => (program, None),
959 (None, Some(script)) if matches!(script.runtime.as_str(), "bun" | "python") => {
960 let runtime = match script.runtime.as_str() {
961 "python" => ScriptRuntime::Python,
962 _ => ScriptRuntime::Bun,
963 };
964 let script_path = crate::supervise::script::resolve_script_path(&script.path)
965 .map_err(|error| DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}': {error}") })?;
966 let runner = crate::supervise::script::runner_path(runtime)
967 .map_err(|error| DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}': {error}") })?;
968 (runner, Some(ScriptEntry::new(runtime, script_path)))
969 }
970 (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()) }),
971 _ => return Err(DaemonConfigError::InvalidValue { path: path.into(), message: format!("module '{module_id}' must name exactly one of program or script") }),
972 };
973 if script.is_some() {
974 if let Some(key) = module.env.keys().find(|key| crate::supervise::script::forbidden_env(key)) {
975 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") });
976 }
977 }
978 let protocol = parse_module_protocol(module.protocol.as_deref(), path, &module_id)?;
979 let health = module
980 .health
981 .map(|health| parse_health_config(health, path, &module_id, protocol))
982 .transpose()?
983 .unwrap_or_default();
984 if let Err(reason) = crate::registry::module_id_path_hazard(&module_id) {
985 return Err(DaemonConfigError::InvalidValue {
986 path: path.to_path_buf(),
987 message: format!(
988 "module id '{}' is not usable as a path component ({reason}): \
989 the daemon derives each module's store path from its id",
990 module_id.escape_debug()
991 ),
992 });
993 }
994 let per_module_route_bind_relay_timeout_ms = match module.route_bind_relay_timeout_ms {
999 Some(0) => {
1000 return Err(DaemonConfigError::InvalidValue {
1001 path: path.to_path_buf(),
1002 message: format!(
1003 "module '{module_id}' {ROUTE_BIND_RELAY_ZERO_MESSAGE}",
1004 module_id = module_id.escape_debug()
1005 ),
1006 });
1007 }
1008 Some(value) => Some(value),
1009 None => default_route_bind_relay_timeout_ms,
1010 };
1011 if module.ignored.contains_key("launch_nonce_env") {
1016 tracing::warn!(
1017 module_id = %module_id.escape_debug(),
1018 "launch_nonce_env is deprecated and ignored; nonce delivery is determined by the platform"
1019 );
1020 }
1021 let overlap = parse_module_overlap(module.overlap.as_deref(), path, &module_id)?;
1022 if module.carry_containment && overlap == ModuleOverlap::Safe {
1023 return Err(DaemonConfigError::InvalidValue {
1024 path: path.to_path_buf(),
1025 message: format!(
1026 "module '{}' sets carry_containment: true with overlap: \"safe\"; carried containment does not support overlapping instances",
1027 module_id.escape_debug()
1028 ),
1029 });
1030 }
1031 if module.env.contains_key(SUBC_SPAWN_ROLE_ENV) {
1035 return Err(DaemonConfigError::InvalidValue {
1036 path: path.to_path_buf(),
1037 message: format!(
1038 "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",
1039 module_id = module_id.escape_debug()
1040 ),
1041 });
1042 }
1043 if protocol == ModuleProtocol::None && module.reserved {
1050 return Err(DaemonConfigError::InvalidValue {
1051 path: path.to_path_buf(),
1052 message: format!(
1053 "module '{module_id}' sets reserved: true with protocol: \"none\"; \
1054 reserved is enforced on the module's HELLO and a protocol: \"none\" \
1055 module never registers, so the reservation could never be checked",
1056 module_id = module_id.escape_debug()
1057 ),
1058 });
1059 }
1060 let restart = parse_restart_config(module.restart, path, &module_id)?;
1061 let register_timeout_s = module
1062 .register_timeout_s
1063 .unwrap_or(crate::supervise::DEFAULT_REGISTER_TIMEOUT.as_secs());
1064 if !(10..=3600).contains(®ister_timeout_s) {
1065 return Err(DaemonConfigError::InvalidValue {
1066 path: path.to_path_buf(),
1067 message: format!(
1068 "module '{module_id}' register_timeout_s must be an integer from 10 to 3600"
1069 ),
1070 });
1071 }
1072 let log = module
1073 .log
1074 .map(|log| parse_logging_config(log, path, &format!("module '{module_id}' log")))
1075 .transpose()?
1076 .or_else(|| daemon_logging.clone());
1077 Ok(ConfiguredModule { module_id,
1078 program,
1079 script,
1080 args: module.args,
1081 env: module.env.into_iter().collect(),
1082 log,
1083 enabled: module.enabled,
1084 registration_channel: module.registration_channel,
1085 reserved: module.reserved,
1086 reserved_prefixes: module.reserved_prefixes,
1087 protocol,
1088 overlap,
1089 carry_containment: module.carry_containment,
1090 health,
1091 drain_timeout_ms: module.drain_timeout_ms.or(default_drain_timeout_ms),
1094 register_timeout: Duration::from_secs(register_timeout_s),
1095 route_bind_relay_timeout_ms: per_module_route_bind_relay_timeout_ms,
1100 restart, })
1101 })
1102 .collect::<Result<Vec<_>, DaemonConfigError>>()?;
1103
1104 validate_reserved_prefixes(&modules, path)?;
1105 validate_reserved_capabilities(&raw.reserved_capabilities, path)?;
1106 validate_admission_facts_config(
1107 &modules,
1108 raw.admission_facts_carrier_module_id.as_deref(),
1109 raw.admission_facts_targets.as_deref(),
1110 path,
1111 )?;
1112 let scope_authority_owners = raw
1113 .scope_authority_owners
1114 .unwrap_or_else(default_scope_authority_owners);
1115 subc_protocol::manifest::validate_module_id(&raw.federated_scope_owner).map_err(|error| {
1116 DaemonConfigError::InvalidValue {
1117 path: path.to_path_buf(),
1118 message: format!("federated_scope_owner: {error}"),
1119 }
1120 })?;
1121 if scope_authority_owners.iter().any(|owner| owner.is_empty()) {
1122 return Err(DaemonConfigError::InvalidValue {
1123 path: path.to_path_buf(),
1124 message: "scope_authority_owners must not contain empty module ids".to_string(),
1125 });
1126 }
1127
1128 let storage = raw
1129 .storage
1130 .map(|s| match s {
1131 RawStorageConfig::Sqlite { data_home } => {
1132 let data_home = data_home.unwrap_or_else(default_data_home);
1133 if !data_home.is_absolute() {
1142 return Err(DaemonConfigError::InvalidValue {
1143 path: path.to_path_buf(),
1144 message: format!(
1145 "storage data home resolved to the relative path {} \
1146 (no absolute XDG_DATA_HOME, APPDATA, USERPROFILE, or HOME \
1147 in the daemon's environment); refusing to serve a \
1148 cwd-relative storage descriptor to modules. Set \
1149 XDG_DATA_HOME or HOME to an absolute path, or set \
1150 storage.data_home in this file.",
1151 data_home.display()
1152 ),
1153 });
1154 }
1155 Ok(StorageConfig::Sqlite { data_home })
1156 }
1157 })
1158 .transpose()?;
1159
1160 if raw.activity.max_age_days == 0 || raw.activity.max_total_mb == 0 {
1161 return Err(DaemonConfigError::InvalidValue {
1162 path: path.to_path_buf(),
1163 message: "activity.max_age_days and activity.max_total_mb must be positive".into(),
1164 });
1165 }
1166 Ok((
1167 DaemonConfig {
1168 path: path.to_path_buf(),
1169 port: raw.port,
1170 privileged_operator_prompt: raw.privileged_operator_prompt,
1171 drain_timeout_ms: default_drain_timeout_ms,
1172 route_bind_relay_timeout_ms: default_route_bind_relay_timeout_ms,
1173 modules,
1174 storage,
1175 admission_facts_carrier_module_id: raw.admission_facts_carrier_module_id,
1176 admission_facts_targets: raw.admission_facts_targets,
1177 scope_authority_owners,
1178 federated_scope_owner: raw.federated_scope_owner,
1179 reserved_capabilities: raw.reserved_capabilities,
1180 agent_policy_root: crate::policy_root::parse_section(raw.agent_policy_root),
1181 },
1182 raw.activity,
1183 ))
1184}
1185
1186fn parse_logging_config(
1187 raw: RawLoggingConfig,
1188 path: &Path,
1189 owner: &str,
1190) -> Result<LoggingConfig, DaemonConfigError> {
1191 fn valid_level(level: &str) -> bool {
1192 matches!(level, "off" | "error" | "warn" | "info" | "debug" | "trace")
1193 }
1194
1195 let level = raw.level.unwrap_or_else(|| "info".to_string());
1196 if !valid_level(&level) {
1197 return Err(DaemonConfigError::InvalidValue {
1198 path: path.to_path_buf(),
1199 message: format!(
1200 "{owner}.level must be one of off, error, warn, info, debug, trace; got {level:?}"
1201 ),
1202 });
1203 }
1204 for (tag, tag_level) in &raw.tags {
1205 let well_formed = !tag.is_empty()
1210 && tag.split('.').all(|segment| {
1211 let mut chars = segment.chars();
1212 matches!(chars.next(), Some('a'..='z'))
1213 && chars.all(|c| matches!(c, 'a'..='z' | '0'..='9' | '-'))
1214 });
1215 if !well_formed {
1216 return Err(DaemonConfigError::InvalidValue {
1217 path: path.to_path_buf(),
1218 message: format!(
1219 "{owner}.tags key {tag:?} is not a logger name (dotted segments of [a-z][a-z0-9-]*)"
1220 ),
1221 });
1222 }
1223 if !valid_level(tag_level) {
1224 return Err(DaemonConfigError::InvalidValue {
1225 path: path.to_path_buf(),
1226 message: format!(
1227 "{owner}.tags.{tag} must be one of off, error, warn, info, debug, trace; got {tag_level:?}"
1228 ),
1229 });
1230 }
1231 }
1232
1233 let defaults = Retention::default();
1234 let retention = Retention {
1235 max_file_mb: raw.max_file_mb.unwrap_or(defaults.max_file_mb),
1236 keep: raw.keep.unwrap_or(defaults.keep),
1237 max_age_days: raw.max_age_days.unwrap_or(defaults.max_age_days),
1238 };
1239 if retention.max_file_mb == 0 {
1240 return Err(DaemonConfigError::InvalidValue {
1241 path: path.to_path_buf(),
1242 message: format!("{owner}.max_file_mb must be greater than 0"),
1243 });
1244 }
1245
1246 let alarm_segment_mb = raw
1247 .alarm_segment_mb
1248 .unwrap_or(cortexkit_log::SegmentRetention::default().alarm_segment_mb);
1249 if alarm_segment_mb == 0 {
1250 return Err(DaemonConfigError::InvalidValue {
1251 path: path.to_path_buf(),
1252 message: format!("{owner}.alarm_segment_mb must be greater than 0"),
1253 });
1254 }
1255
1256 Ok(LoggingConfig {
1257 level,
1258 tags: raw.tags,
1259 retention,
1260 alarm_segment_mb,
1261 })
1262}
1263
1264fn parse_module_protocol(
1273 raw: Option<&str>,
1274 path: &Path,
1275 module_id: &str,
1276) -> Result<ModuleProtocol, DaemonConfigError> {
1277 match raw {
1278 None | Some("subc") => Ok(ModuleProtocol::Subc),
1279 Some("none") => Ok(ModuleProtocol::None),
1280 Some(other) => Err(DaemonConfigError::InvalidValue {
1284 path: path.to_path_buf(),
1285 message: format!(
1286 "module '{module_id}' declares protocol {other:?}; supported values are \
1287 \"subc\" (the default when the key is absent) and \"none\"",
1288 module_id = module_id.escape_debug(),
1289 ),
1290 }),
1291 }
1292}
1293
1294fn parse_module_overlap(
1298 raw: Option<&str>,
1299 path: &Path,
1300 module_id: &str,
1301) -> Result<ModuleOverlap, DaemonConfigError> {
1302 match raw {
1303 None | Some("exclusive") => Ok(ModuleOverlap::Exclusive),
1304 Some("safe") => Ok(ModuleOverlap::Safe),
1305 Some(other) => Err(DaemonConfigError::InvalidValue {
1306 path: path.to_path_buf(),
1307 message: format!(
1308 "module '{module_id}' declares overlap {other:?}; supported values are \
1309 \"exclusive\" (the default when the key is absent) and \"safe\"",
1310 module_id = module_id.escape_debug(),
1311 ),
1312 }),
1313 }
1314}
1315
1316fn validate_reserved_capabilities(
1317 bindings: &BTreeMap<String, String>,
1318 path: &Path,
1319) -> Result<(), DaemonConfigError> {
1320 for (capability, module_id) in bindings {
1321 if !is_valid_capability_identifier(capability) {
1322 return Err(DaemonConfigError::InvalidValue {
1323 path: path.to_path_buf(),
1324 message: format!(
1325 "reserved_capabilities key {:?} is not a valid capability identifier",
1326 capability
1327 ),
1328 });
1329 }
1330 if module_id.trim().is_empty() {
1331 return Err(DaemonConfigError::InvalidValue {
1332 path: path.to_path_buf(),
1333 message: format!(
1334 "reserved_capabilities binding for {:?} has an empty module id",
1335 capability
1336 ),
1337 });
1338 }
1339 if let Err(reason) = crate::registry::module_id_path_hazard(module_id) {
1340 return Err(DaemonConfigError::InvalidValue {
1341 path: path.to_path_buf(),
1342 message: format!(
1343 "reserved_capabilities binding for {:?} has an unusable module id {:?}: {reason}",
1344 capability, module_id
1345 ),
1346 });
1347 }
1348 }
1349 Ok(())
1350}
1351
1352fn validate_admission_facts_config(
1353 modules: &[ConfiguredModule],
1354 carrier_module_id: Option<&str>,
1355 targets: Option<&[String]>,
1356 path: &Path,
1357) -> Result<(), DaemonConfigError> {
1358 let Some(carrier_module_id) = carrier_module_id else {
1359 return Ok(());
1360 };
1361
1362 let Some(carrier) = modules
1363 .iter()
1364 .find(|module| module.module_id == carrier_module_id)
1365 else {
1366 return Err(DaemonConfigError::InvalidValue {
1367 path: path.to_path_buf(),
1368 message: format!(
1369 "admission_facts_carrier_module_id '{carrier_module_id}' must name a configured module"
1370 ),
1371 });
1372 };
1373 if !carrier.enabled || !carrier.reserved {
1374 return Err(DaemonConfigError::InvalidValue {
1375 path: path.to_path_buf(),
1376 message: format!(
1377 "admission_facts_carrier_module_id '{carrier_module_id}' must name an enabled reserved module"
1378 ),
1379 });
1380 }
1381
1382 let Some(targets) = targets else {
1383 return Err(DaemonConfigError::InvalidValue {
1384 path: path.to_path_buf(),
1385 message: "admission_facts_targets must be present when an admission facts carrier is configured".to_string(),
1386 });
1387 };
1388 if targets.is_empty() || targets.iter().any(String::is_empty) {
1389 return Err(DaemonConfigError::InvalidValue {
1390 path: path.to_path_buf(),
1391 message:
1392 "admission_facts_targets must be non-empty and must not contain empty module ids"
1393 .to_string(),
1394 });
1395 }
1396
1397 Ok(())
1398}
1399
1400fn default_enabled() -> bool {
1401 true
1402}
1403
1404fn validate_reserved_prefixes(
1405 modules: &[ConfiguredModule],
1406 path: &Path,
1407) -> Result<(), DaemonConfigError> {
1408 for module in modules {
1409 if module.reserved_prefixes.is_empty() {
1410 continue;
1411 }
1412 if !module.reserved {
1413 return Err(DaemonConfigError::InvalidValue {
1414 path: path.to_path_buf(),
1415 message: format!(
1416 "module '{}' reserved_prefixes require reserved=true so the owner is spawn-nonce protected",
1417 module.module_id
1418 ),
1419 });
1420 }
1421 for prefix in &module.reserved_prefixes {
1422 if !prefix.ends_with(':') {
1423 return Err(DaemonConfigError::InvalidValue {
1424 path: path.to_path_buf(),
1425 message: format!(
1426 "module '{}' reserved prefix '{}' must end with ':'",
1427 module.module_id, prefix
1428 ),
1429 });
1430 }
1431 }
1432 }
1433
1434 for module in modules {
1435 for prefix in &module.reserved_prefixes {
1436 if let Some(colliding) = modules
1437 .iter()
1438 .find(|candidate| candidate.module_id.starts_with(prefix))
1439 {
1440 return Err(DaemonConfigError::InvalidValue {
1441 path: path.to_path_buf(),
1442 message: format!(
1443 "reserved prefix '{}' owned by '{}' collides with configured module id '{}'",
1444 prefix, module.module_id, colliding.module_id
1445 ),
1446 });
1447 }
1448 }
1449 }
1450
1451 for (left_index, left) in modules.iter().enumerate() {
1452 for right in modules.iter().skip(left_index + 1) {
1453 if left.module_id == right.module_id {
1454 continue;
1455 }
1456 for left_prefix in &left.reserved_prefixes {
1457 for right_prefix in &right.reserved_prefixes {
1458 if left_prefix.starts_with(right_prefix)
1459 || right_prefix.starts_with(left_prefix)
1460 {
1461 return Err(DaemonConfigError::InvalidValue {
1462 path: path.to_path_buf(),
1463 message: format!(
1464 "reserved prefixes '{}' owned by '{}' and '{}' owned by '{}' overlap",
1465 left_prefix, left.module_id, right_prefix, right.module_id
1466 ),
1467 });
1468 }
1469 }
1470 }
1471 }
1472 }
1473
1474 Ok(())
1475}
1476
1477fn parse_health_config(
1478 raw: RawHealthConfig,
1479 path: &Path,
1480 module_id: &str,
1481 protocol: ModuleProtocol,
1482) -> Result<HealthConfig, DaemonConfigError> {
1483 if let Some(url) = raw.http.as_deref() {
1484 let reason = if protocol != ModuleProtocol::None {
1485 Some("is valid only for protocol: \"none\" modules".to_string())
1486 } else {
1487 crate::supervise::parse_http_probe_url(url).err()
1488 };
1489 if let Some(reason) = reason {
1490 return Err(DaemonConfigError::InvalidValue {
1491 path: path.to_path_buf(),
1492 message: format!("module '{module_id}' health.http {reason}"),
1493 });
1494 }
1495 }
1496 let defaults = HealthConfig::default();
1497 let cadence = positive_millis(
1498 raw.cadence_ms,
1499 defaults.cadence,
1500 path,
1501 module_id,
1502 "cadence_ms",
1503 )?;
1504 let deadline = positive_millis(
1505 raw.deadline_ms,
1506 defaults.deadline,
1507 path,
1508 module_id,
1509 "deadline_ms",
1510 )?;
1511 let failure_threshold = match raw.failure_threshold {
1512 Some(0) => {
1513 return Err(DaemonConfigError::InvalidValue {
1514 path: path.to_path_buf(),
1515 message: format!("module '{module_id}' health.failure_threshold must be positive"),
1516 })
1517 }
1518 Some(value) => value,
1519 None => defaults.failure_threshold,
1520 };
1521
1522 Ok(HealthConfig {
1523 http: raw.http,
1524 cadence,
1525 deadline,
1526 failure_threshold,
1527 on_degraded: match raw.on_degraded {
1528 Some(RawHealthAction::Restart) => {
1529 return Err(DaemonConfigError::InvalidValue {
1530 path: path.to_path_buf(),
1531 message: format!(
1532 "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)."
1533 ),
1534 });
1535 }
1536 Some(action) => health_action(action),
1537 None => defaults.on_degraded,
1538 },
1539 on_failing: raw
1540 .on_failing
1541 .map(health_action)
1542 .unwrap_or(defaults.on_failing),
1543 critical: raw.critical,
1544 })
1545}
1546
1547fn parse_restart_config(
1554 raw: Option<RawRestartConfig>,
1555 path: &Path,
1556 module_id: &str,
1557) -> Result<RestartPolicy, DaemonConfigError> {
1558 let defaults = RestartPolicy::default();
1559 let Some(raw) = raw else {
1560 return Ok(defaults);
1561 };
1562
1563 let window = match raw.window_secs {
1564 Some(0) => {
1565 return Err(DaemonConfigError::InvalidValue {
1566 path: path.to_path_buf(),
1567 message: format!(
1568 "module '{module_id}' {RESTART_WINDOW_ZERO_MESSAGE}",
1569 module_id = module_id.escape_debug()
1570 ),
1571 });
1572 }
1573 Some(secs) => Duration::from_secs(secs),
1574 None => defaults.window,
1575 };
1576 let backoff = raw
1577 .backoff_ms
1578 .map(Duration::from_millis)
1579 .unwrap_or(defaults.backoff);
1580 let max_backoff = raw
1581 .max_backoff_ms
1582 .map(Duration::from_millis)
1583 .unwrap_or(defaults.max_backoff);
1584 if max_backoff < backoff {
1585 return Err(DaemonConfigError::InvalidValue {
1586 path: path.to_path_buf(),
1587 message: format!(
1588 "module '{}' restart.max_backoff_ms must be greater than or equal to restart.backoff_ms (max_backoff_ms={max_backoff:?}, backoff_ms={backoff:?})",
1589 module_id.escape_debug()
1590 ),
1591 });
1592 }
1593
1594 Ok(RestartPolicy {
1595 max_restarts: raw.max_restarts.unwrap_or(defaults.max_restarts),
1598 backoff,
1599 max_backoff,
1600 window,
1601 })
1602}
1603
1604fn positive_millis(
1605 value: Option<u64>,
1606 default: std::time::Duration,
1607 path: &Path,
1608 module_id: &str,
1609 field: &str,
1610) -> Result<std::time::Duration, DaemonConfigError> {
1611 match value {
1612 Some(0) => Err(DaemonConfigError::InvalidValue {
1613 path: path.to_path_buf(),
1614 message: format!("module '{module_id}' health.{field} must be positive"),
1615 }),
1616 Some(value) => Ok(std::time::Duration::from_millis(value)),
1617 None => Ok(default),
1618 }
1619}
1620
1621fn health_action(action: RawHealthAction) -> HealthAction {
1622 match action {
1623 RawHealthAction::Report => HealthAction::Report,
1624 RawHealthAction::Restart => HealthAction::Restart,
1625 RawHealthAction::Alert => HealthAction::Alert,
1626 }
1627}
1628
1629pub(crate) fn default_data_home() -> PathBuf {
1632 if let Some(data_home) = non_empty_os_var("XDG_DATA_HOME") {
1633 return PathBuf::from(data_home);
1634 }
1635
1636 #[cfg(windows)]
1637 {
1638 if let Some(app_data) = non_empty_os_var("APPDATA") {
1639 return PathBuf::from(app_data);
1640 }
1641 if let Some(user_profile) = non_empty_os_var("USERPROFILE") {
1642 return PathBuf::from(user_profile).join("AppData").join("Roaming");
1643 }
1644 }
1645
1646 if let Some(home) = non_empty_os_var("HOME") {
1647 return PathBuf::from(home).join(".local").join("share");
1648 }
1649
1650 PathBuf::from(".local").join("share")
1651}
1652
1653fn non_empty_os_var(key: &str) -> Option<OsString> {
1654 let value = env::var_os(key)?;
1655 if value.is_empty() {
1656 None
1657 } else {
1658 Some(value)
1659 }
1660}
1661
1662impl fmt::Display for DaemonConfigError {
1663 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1664 match self {
1665 Self::Read { path, source } => {
1666 write!(f, "failed to read daemon config {}: {source}", path.display())
1667 }
1668 Self::InvalidJsonc { path, message } => {
1669 write!(f, "invalid JSONC in daemon config {}: {message}", path.display())
1670 }
1671 Self::InvalidJson { path, source } => {
1672 write!(f, "invalid daemon config {}: {source}", path.display())
1673 }
1674 Self::UnsupportedVersion { path, version } => write!(
1675 f,
1676 "invalid daemon config {}: version {version} is unsupported (expected {SUPPORTED_CONFIG_VERSION})",
1677 path.display()
1678 ),
1679 Self::InvalidValue { path, message } => {
1680 write!(f, "invalid daemon config {}: {message}", path.display())
1681 }
1682 }
1683 }
1684}
1685
1686impl Error for DaemonConfigError {
1687 fn source(&self) -> Option<&(dyn Error + 'static)> {
1688 match self {
1689 Self::Read { source, .. } => Some(source),
1690 Self::InvalidJson { source, .. } => Some(source),
1691 Self::InvalidJsonc { .. }
1692 | Self::UnsupportedVersion { .. }
1693 | Self::InvalidValue { .. } => None,
1694 }
1695 }
1696}
1697
1698#[cfg(all(test, windows))]
1699mod windows_run_dir_privacy_tests {
1700 use super::ensure_directory_private;
1701 use cortexkit_test_support::ScratchDir;
1702 use subc_os::windows_acl::test_support::{
1703 assert_dacl_owner_only, assert_owner_only, grant_everyone,
1704 };
1705
1706 #[test]
1707 fn windows_run_dir_has_exact_protected_dacl_at_creation() {
1708 let root = ScratchDir::new("windows-run-dir-create");
1709 grant_everyone(root.path());
1710 let path = root.join("run");
1711 ensure_directory_private(&path).unwrap();
1712 assert_owner_only(&path, true, true);
1713 }
1714
1715 #[test]
1716 fn windows_run_dir_narrows_existing_inherited_descendants() {
1717 let root = ScratchDir::new("windows-run-dir-existing");
1718 grant_everyone(root.path());
1719 let path = root.join("run");
1720 std::fs::create_dir(&path).unwrap();
1721 let child = path.join("old.log");
1722 std::fs::write(&child, b"old log").unwrap();
1723 ensure_directory_private(&path).unwrap();
1724 assert_dacl_owner_only(&path, true, true);
1727 assert_dacl_owner_only(&child, false, false);
1728 }
1729}
1730
1731#[cfg(all(test, unix))]
1732mod run_dir_privacy_tests {
1733 use cortexkit_test_support::ScratchDir;
1734 use std::fs;
1735 use std::os::unix::fs::PermissionsExt;
1736
1737 #[test]
1743 fn run_dir_is_created_private_and_an_inherited_wide_one_is_tightened() {
1744 let temp = ScratchDir::new("subc-run-dir-privacy");
1745 let created = temp.path().join("cortexkit").join("run");
1746 super::ensure_directory_private(&created).expect("create run dir");
1747 let mode = fs::metadata(&created)
1748 .expect("stat created")
1749 .permissions()
1750 .mode()
1751 & 0o777;
1752 assert_eq!(
1753 mode, 0o700,
1754 "observable a run directory this code creates must be 0700, got {mode:o}"
1755 );
1756
1757 fs::set_permissions(&created, fs::Permissions::from_mode(0o755)).expect("widen");
1759 let widened = fs::metadata(&created)
1760 .expect("stat widened")
1761 .permissions()
1762 .mode()
1763 & 0o777;
1764 assert_eq!(
1765 widened, 0o755,
1766 "observable the fixture must actually be wide before the tighten"
1767 );
1768
1769 super::ensure_directory_private(&created).expect("tighten run dir");
1770 let mode = fs::metadata(&created)
1771 .expect("stat tightened")
1772 .permissions()
1773 .mode()
1774 & 0o777;
1775 assert_eq!(
1776 mode, 0o700,
1777 "observable an inherited group- or world-readable run directory must be tightened to 0700, got {mode:o}"
1778 );
1779 }
1780}
1781
1782#[cfg(test)]
1783mod tests {
1784 use super::*;
1785
1786 static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1795
1796 fn abs(posix: &str) -> PathBuf {
1801 if cfg!(windows) {
1802 PathBuf::from(format!("C:{}", posix.replace('/', "\\")))
1803 } else {
1804 PathBuf::from(posix)
1805 }
1806 }
1807
1808 #[test]
1809 fn default_data_home_matches_golden_fixture() {
1810 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1811 let doc: serde_json::Value =
1812 serde_json::from_str(include_str!("../tests/golden/data_home_resolution.json"))
1813 .expect("golden parses");
1814 let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1815 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1816 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1817 let platform_matches =
1818 |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1819
1820 let mut ran = 0usize;
1821 for case in doc["cases"].as_array().expect("cases array") {
1822 let name = case["name"].as_str().expect("name");
1823 if !platform_matches(case["platform"].as_str().expect("platform")) {
1824 continue;
1825 }
1826 for v in vars {
1827 env::remove_var(v);
1828 }
1829 for (k, v) in case["env"].as_object().expect("env map") {
1830 env::set_var(k, v.as_str().expect("env value"));
1831 }
1832 let got = default_data_home();
1833 assert_eq!(
1834 got.to_string_lossy(),
1835 case["expect"].as_str().expect("expect"),
1836 "golden case '{name}' diverged"
1837 );
1838 ran += 1;
1839 }
1840 assert!(
1842 ran >= 6,
1843 "only {ran} golden cases ran; fixture or filter broken"
1844 );
1845
1846 for (k, v) in saved {
1847 match v {
1848 Some(val) => env::set_var(k, val),
1849 None => env::remove_var(k),
1850 }
1851 }
1852 }
1853
1854 #[test]
1859 fn daemon_run_dir_refuses_a_relative_data_home_and_names_the_variables() {
1860 for data_home in [PathBuf::from(".local/share"), PathBuf::from("relative-xdg")] {
1861 let error = daemon_run_dir_from(data_home.clone())
1862 .expect_err("a relative data home must be refused");
1863 assert_eq!(
1864 error,
1865 DaemonRunDirError::RelativeDataHome {
1866 data_home: data_home.clone()
1867 }
1868 );
1869 let message = error.to_string();
1870 assert!(
1871 message.contains("XDG_DATA_HOME") && message.contains("HOME"),
1872 "the refusal must name the variables to set: {message}"
1873 );
1874 }
1875 }
1876
1877 #[test]
1878 fn daemon_run_dir_under_an_absolute_data_home_is_cortexkit_run() {
1879 let data_home = env::temp_dir().join("subc-run-dir-probe").join("data");
1880 assert!(data_home.is_absolute());
1881 assert_eq!(
1882 daemon_run_dir_from(data_home.clone()),
1883 Ok(data_home.join("cortexkit").join("run"))
1884 );
1885 }
1886
1887 #[test]
1893 fn default_config_home_matches_golden_fixture() {
1894 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1895 let doc: serde_json::Value =
1896 serde_json::from_str(include_str!("../tests/golden/config_home_resolution.json"))
1897 .expect("golden parses");
1898 let vars = ["XDG_CONFIG_HOME", "APPDATA", "USERPROFILE", "HOME"];
1899 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1900 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1901 let platform_matches =
1902 |p: &str| p == "any" || p == if cfg!(windows) { "windows" } else { "unix" };
1903
1904 let mut ran = 0usize;
1905 for case in doc["cases"].as_array().expect("cases array") {
1906 let name = case["name"].as_str().expect("name");
1907 if !platform_matches(case["platform"].as_str().expect("platform")) {
1908 continue;
1909 }
1910 for v in vars {
1911 env::remove_var(v);
1912 }
1913 for (k, v) in case["env"].as_object().expect("env map") {
1914 env::set_var(k, v.as_str().expect("env value"));
1915 }
1916 let got = default_config_home();
1917 assert_eq!(
1918 got.to_string_lossy(),
1919 case["expect"].as_str().expect("expect"),
1920 "golden case '{name}' diverged"
1921 );
1922 ran += 1;
1923 }
1924 assert!(
1925 ran >= 6,
1926 "only {ran} golden cases ran; fixture or filter broken"
1927 );
1928
1929 for (k, v) in saved {
1930 match v {
1931 Some(val) => env::set_var(k, val),
1932 None => env::remove_var(k),
1933 }
1934 }
1935 }
1936
1937 #[test]
1944 fn relative_storage_data_home_is_refused_at_parse() {
1945 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
1946 let path = Path::new("/golden/subc.jsonc");
1947
1948 let doc =
1950 r#"{ "version": 1, "storage": { "backend": "sqlite", "data_home": "relative/home" } }"#;
1951 let err = parse_doc(doc, path).expect_err("relative data_home must refuse");
1952 assert!(
1953 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1954 if message.contains("relative path relative/home")),
1955 "wrong refusal: {err:?}"
1956 );
1957
1958 let vars = ["XDG_DATA_HOME", "APPDATA", "USERPROFILE", "HOME"];
1960 let saved: Vec<(&str, Option<std::ffi::OsString>)> =
1961 vars.iter().map(|v| (*v, env::var_os(v))).collect();
1962 for v in vars {
1963 env::remove_var(v);
1964 }
1965 let doc = r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#;
1966 let err = parse_doc(doc, path).expect_err("no home in env must refuse");
1967 assert!(
1968 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
1969 if message.contains("no absolute XDG_DATA_HOME")),
1970 "wrong refusal: {err:?}"
1971 );
1972
1973 let want = abs("/abs/home");
1977 let doc = format!(
1978 r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
1979 serde_json::to_string(&want).expect("json path")
1980 );
1981 let cfg = parse_doc(&doc, path).expect("absolute data_home parses");
1982 assert!(matches!(
1983 cfg.storage,
1984 Some(StorageConfig::Sqlite { ref data_home }) if *data_home == want
1985 ));
1986
1987 for (k, v) in saved {
1988 match v {
1989 Some(val) => env::set_var(k, val),
1990 None => env::remove_var(k),
1991 }
1992 }
1993 }
1994
1995 #[test]
1996 fn restart_required_sections_are_the_rescan_cannot_apply_set() {
1997 assert_eq!(
1998 RestartRequiredSection::ALL.map(RestartRequiredSection::label),
1999 [
2000 "port",
2001 "storage",
2002 "admission_facts_carrier_module_id",
2003 "admission_facts_targets",
2004 "scope_authority_owners",
2005 "federated_scope_owner",
2006 "privileged_operator_prompt",
2007 ]
2008 );
2009 }
2010
2011 #[test]
2012 fn privileged_operator_prompt_defaults_to_log_and_accepts_both_modes() {
2013 let path = Path::new("/tmp/subc.jsonc");
2014 let config = parse_doc(r#"{"version":1}"#, path).unwrap();
2015 assert_eq!(
2016 config.privileged_operator_prompt,
2017 PrivilegedOperatorPrompt::Log
2018 );
2019 for (value, expected) in [
2020 ("log", PrivilegedOperatorPrompt::Log),
2021 ("enforce", PrivilegedOperatorPrompt::Enforce),
2022 ] {
2023 let config = parse_doc(
2024 &format!(r#"{{"version":1,"privileged_operator_prompt":"{value}"}}"#),
2025 path,
2026 )
2027 .unwrap();
2028 assert_eq!(config.privileged_operator_prompt, expected);
2029 }
2030 }
2031
2032 #[test]
2033 fn privileged_operator_prompt_refuses_unknown_values_and_wrong_types() {
2034 let path = Path::new("/tmp/subc.jsonc");
2035 for value in [r#""unknown""#, r#""Enforce""#, "null", "true", "1", "{}"] {
2036 let error = parse_doc(
2037 &format!(r#"{{"version":1,"privileged_operator_prompt":{value}}}"#),
2038 path,
2039 )
2040 .unwrap_err();
2041 assert!(matches!(error, DaemonConfigError::InvalidJson { .. }));
2042 }
2043 }
2044
2045 #[test]
2046 fn scope_authority_owners_defaults_to_the_session_runtime() {
2047 let config = parse_doc(r#"{ "version": 1 }"#, Path::new("/tmp/subc.jsonc")).unwrap();
2048 assert_eq!(
2049 config.scope_authority_owners,
2050 vec!["prefrontal-core", "prefrontal"]
2051 );
2052 }
2053
2054 #[test]
2055 fn federated_scope_owner_defaults_and_is_validated_and_restart_required() {
2056 let config = parse_doc(r#"{ "version": 1 }"#, Path::new("/fixture/subc.jsonc")).unwrap();
2057 assert_eq!(config.federated_scope_owner, "callosum");
2058 assert!(!config
2059 .scope_authority_owners
2060 .contains(&config.federated_scope_owner));
2061 let configured = parse_doc(
2062 r#"{ "version": 1, "federated_scope_owner": "peer-carrier" }"#,
2063 Path::new("/fixture/subc.jsonc"),
2064 )
2065 .unwrap();
2066 assert_eq!(configured.federated_scope_owner, "peer-carrier");
2067 assert!(RestartRequiredSection::ALL.contains(&RestartRequiredSection::FederatedScopeOwner));
2068 for invalid in ["", "..", "a/b", "a\\b"] {
2069 let body = serde_json::json!({"version": 1, "federated_scope_owner": invalid});
2070 assert!(
2071 parse_doc(&body.to_string(), Path::new("/fixture/subc.jsonc"))
2072 .unwrap_err()
2073 .to_string()
2074 .contains("federated_scope_owner")
2075 );
2076 }
2077 }
2078
2079 #[test]
2080 fn scope_authority_owners_is_read_when_set_and_refuses_an_empty_id() {
2081 let config = parse_doc(
2082 r#"{ "version": 1, "scope_authority_owners": ["a", "b"] }"#,
2083 Path::new("/tmp/subc.jsonc"),
2084 )
2085 .unwrap();
2086 assert_eq!(config.scope_authority_owners, vec!["a", "b"]);
2087 let config = parse_doc(
2090 r#"{ "version": 1, "scope_authority_owners": [] }"#,
2091 Path::new("/tmp/subc.jsonc"),
2092 )
2093 .unwrap();
2094 assert!(config.scope_authority_owners.is_empty());
2095 let error = parse_doc(
2096 r#"{ "version": 1, "scope_authority_owners": [""] }"#,
2097 Path::new("/tmp/subc.jsonc"),
2098 )
2099 .expect_err("an empty module id is refused");
2100 assert!(
2101 error.to_string().contains("scope_authority_owners"),
2102 "{error}"
2103 );
2104 }
2105
2106 #[test]
2107 fn no_storage_section_yields_none() {
2108 let config = parse_doc(
2109 r#"{ "version": 1, "modules": {} }"#,
2110 Path::new("/tmp/subc.jsonc"),
2111 )
2112 .expect("parse");
2113 assert_eq!(config.storage, None);
2114 }
2115
2116 #[test]
2117 fn sqlite_storage_parses_with_explicit_data_home() {
2118 let config = parse_doc(
2119 &format!(
2120 r#"{{ "version": 1, "storage": {{ "backend": "sqlite", "data_home": {} }} }}"#,
2121 serde_json::to_string(&abs("/data")).expect("json path")
2122 ),
2123 Path::new("/tmp/subc.jsonc"),
2124 )
2125 .expect("parse");
2126 assert_eq!(
2127 config.storage,
2128 Some(StorageConfig::Sqlite {
2129 data_home: abs("/data")
2130 })
2131 );
2132 }
2133
2134 #[test]
2135 fn sqlite_storage_defaults_data_home_when_omitted() {
2136 let _g = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
2142 std::env::set_var("XDG_DATA_HOME", abs("/forced/data/home"));
2143 let config = parse_doc(
2144 r#"{ "version": 1, "storage": { "backend": "sqlite" } }"#,
2145 Path::new("/tmp/subc.jsonc"),
2146 )
2147 .expect("parse");
2148 std::env::remove_var("XDG_DATA_HOME");
2149 assert_eq!(
2150 config.storage,
2151 Some(StorageConfig::Sqlite {
2152 data_home: abs("/forced/data/home")
2153 })
2154 );
2155 }
2156
2157 #[test]
2158 fn descriptor_for_matches_store_types_shape() {
2159 let cfg = StorageConfig::Sqlite {
2163 data_home: PathBuf::from("/data"),
2164 };
2165 let descriptor = cfg.descriptor_for("alfonso-routing");
2166 assert_eq!(
2167 descriptor,
2168 serde_json::json!({
2169 "module_id": "alfonso-routing",
2170 "storage_namespace": "default",
2171 "isolation": { "kind": "module" },
2172 "backend": {
2173 "backend": "sqlite",
2174 "path": "/data/cortexkit/alfonso-routing/store.db"
2175 }
2176 })
2177 );
2178 }
2179
2180 #[test]
2181 fn path_hazard_module_id_refuses_config_parse() {
2182 let path = Path::new("/tmp/subc.jsonc");
2183 let err = parse_doc(
2184 r#"{ "version": 1, "modules": { "../escape": { "program": "x" } } }"#,
2185 path,
2186 )
2187 .expect_err("separator-bearing module id must refuse");
2188 let text = format!("{err}");
2189 assert!(
2190 text.contains("not usable as a path component"),
2191 "refusal must name the hazard: {text}"
2192 );
2193 }
2194
2195 #[test]
2196 fn drain_timeout_resolves_module_over_daemon_over_absent() {
2197 let path = Path::new("/tmp/subc.jsonc");
2198 let config = parse_doc(
2199 r#"
2200 {
2201 "version": 1,
2202 "drain_timeout_ms": 45000,
2203 "modules": {
2204 "fast": { "program": "fast", "drain_timeout_ms": 0 },
2205 "slow": { "program": "slow", "drain_timeout_ms": 120000 },
2206 "inherits": { "program": "inherits" }
2207 }
2208 }
2209 "#,
2210 path,
2211 )
2212 .unwrap();
2213 let by_id = |id: &str| {
2214 config
2215 .modules
2216 .iter()
2217 .find(|m| m.module_id == id)
2218 .unwrap()
2219 .drain_timeout_ms
2220 };
2221 assert_eq!(by_id("fast"), Some(0));
2224 assert_eq!(by_id("slow"), Some(120_000));
2225 assert_eq!(by_id("inherits"), Some(45_000));
2227 assert_eq!(config.drain_timeout_ms, Some(45_000));
2228 }
2229
2230 #[test]
2231 fn drain_timeout_absent_everywhere_stays_none_for_builtin_default() {
2232 let path = Path::new("/tmp/subc.jsonc");
2233 let config = parse_doc(
2234 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2235 path,
2236 )
2237 .unwrap();
2238 assert_eq!(config.modules[0].drain_timeout_ms, None);
2242 assert_eq!(config.drain_timeout_ms, None);
2243 }
2244
2245 #[test]
2246 fn route_bind_relay_timeout_resolves_module_over_daemon_over_absent() {
2247 let path = Path::new("/tmp/subc.jsonc");
2253 let config = parse_doc(
2254 r#"
2255 {
2256 "version": 1,
2257 "route_bind_relay_timeout_ms": 30000,
2258 "modules": {
2259 "tight": { "program": "tight", "route_bind_relay_timeout_ms": 5000 },
2260 "loose": { "program": "loose", "route_bind_relay_timeout_ms": 60000 },
2261 "inherits": { "program": "inherits" }
2262 }
2263 }
2264 "#,
2265 path,
2266 )
2267 .unwrap();
2268 let by_id = |id: &str| {
2269 config
2270 .modules
2271 .iter()
2272 .find(|m| m.module_id == id)
2273 .unwrap()
2274 .route_bind_relay_timeout_ms
2275 };
2276 assert_eq!(by_id("tight"), Some(5_000));
2278 assert_eq!(by_id("loose"), Some(60_000));
2279 assert_eq!(by_id("inherits"), Some(30_000));
2281 assert_eq!(config.route_bind_relay_timeout_ms, Some(30_000));
2282 }
2283
2284 #[test]
2285 fn log_tag_keys_must_be_logger_names_and_the_error_names_the_key() {
2286 let path = Path::new("/tmp/subc.jsonc");
2287 for bad in ["Perf", "a b", "perf.", ".perf", "gc..walk", "a=b"] {
2288 let doc = format!(
2289 r#"{{ "version": 1, "modules": {{ "m": {{ "program": "m", "log": {{ "tags": {{ "{bad}": "debug" }} }} }} }} }}"#
2290 );
2291 let err = parse_doc(&doc, path).expect_err(bad);
2292 let text = format!("{err}");
2293 assert!(
2294 text.contains(&format!("{bad:?}")),
2295 "must name the key: {text}"
2296 );
2297 assert!(
2298 text.contains("logger name"),
2299 "must say what a key is: {text}"
2300 );
2301 }
2302 let ok = parse_doc(
2304 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "tags": { "perf": "debug", "gc.walk": "trace", "m": "error", "a-b": "info" } } } } }"#,
2305 path,
2306 );
2307 assert!(ok.is_ok(), "{ok:?}");
2308 }
2309
2310 #[test]
2311 fn log_filter_spec_prefixes_bare_keys_with_the_module_and_passes_absolute_ones() {
2312 let path = Path::new("/tmp/subc.jsonc");
2313 let config = parse_doc(
2314 r#"{ "version": 1, "modules": { "synapse": { "program": "s", "log": { "level": "warn", "tags": { "perf": "debug", "gc.walk": "trace", "synapse": "error", "other.x": "info" } } } } }"#,
2315 path,
2316 )
2317 .unwrap();
2318 let log = config.modules[0].log.as_ref().unwrap();
2319 assert_eq!(
2321 log.filter_spec("synapse"),
2322 "warn,gc.walk=trace,other.x=info,synapse.perf=debug,synapse=error"
2323 );
2324 }
2325
2326 #[test]
2327 fn log_alarm_segment_mb_defaults_to_the_crate_default_and_refuses_zero() {
2328 let path = Path::new("/tmp/subc.jsonc");
2329 let config = parse_doc(
2330 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "level": "info" } } } }"#,
2331 path,
2332 )
2333 .unwrap();
2334 assert_eq!(
2335 config.modules[0].log.as_ref().unwrap().alarm_segment_mb,
2336 cortexkit_log::SegmentRetention::default().alarm_segment_mb
2337 );
2338 let err = parse_doc(
2339 r#"{ "version": 1, "modules": { "m": { "program": "m", "log": { "alarm_segment_mb": 0 } } } }"#,
2340 path,
2341 )
2342 .expect_err("zero alarm must refuse");
2343 assert!(format!("{err}").contains("alarm_segment_mb"));
2344 }
2345
2346 #[test]
2347 fn route_bind_relay_timeout_zero_at_daemon_layer_is_refused() {
2348 let path = Path::new("/tmp/subc.jsonc");
2349 let err = parse_doc(
2350 r#"
2351 {
2352 "version": 1,
2353 "route_bind_relay_timeout_ms": 0,
2354 "modules": { "m": { "program": "m" } }
2355 }
2356 "#,
2357 path,
2358 )
2359 .expect_err("a daemon-wide zero budget must refuse parse");
2360 let text = format!("{err}");
2361 assert!(
2362 text.contains("route_bind_relay_timeout_ms"),
2363 "error must name the offending key: {text}"
2364 );
2365 assert!(
2366 text.contains("enabled: false"),
2367 "error must name the remedy (enable false): {text}"
2368 );
2369 }
2370
2371 #[test]
2372 fn route_bind_relay_timeout_zero_at_module_layer_is_refused() {
2373 let path = Path::new("/tmp/subc.jsonc");
2374 let err = parse_doc(
2375 r#"
2376 {
2377 "version": 1,
2378 "modules": {
2379 "good": { "program": "good" },
2380 "broken": { "program": "broken", "route_bind_relay_timeout_ms": 0 }
2381 }
2382 }
2383 "#,
2384 path,
2385 )
2386 .expect_err("a per-module zero budget must refuse parse");
2387 let text = format!("{err}");
2388 assert!(
2389 text.contains("route_bind_relay_timeout_ms"),
2390 "error must name the offending key: {text}"
2391 );
2392 assert!(
2393 text.contains("broken"),
2394 "error must name the offending module id: {text}"
2395 );
2396 assert!(
2397 text.contains("enabled: false"),
2398 "error must name the remedy (enable false): {text}"
2399 );
2400 }
2401
2402 #[test]
2403 fn drain_timeout_zero_still_parses_for_wedge_bounces() {
2404 let path = Path::new("/tmp/subc.jsonc");
2410 let config = parse_doc(
2411 r#"
2412 {
2413 "version": 1,
2414 "drain_timeout_ms": 0,
2415 "modules": {
2416 "wedge": { "program": "wedge", "drain_timeout_ms": 0 }
2417 }
2418 }
2419 "#,
2420 path,
2421 )
2422 .expect("drain_timeout_ms: 0 must still parse; wedge-bounce uses it");
2423 let wedge = config
2424 .modules
2425 .iter()
2426 .find(|m| m.module_id == "wedge")
2427 .unwrap();
2428 assert_eq!(wedge.drain_timeout_ms, Some(0));
2429 assert_eq!(config.drain_timeout_ms, Some(0));
2430 }
2431
2432 #[test]
2433 fn route_bind_relay_timeout_absent_everywhere_stays_none_for_builtin_default() {
2434 let path = Path::new("/tmp/subc.jsonc");
2439 let config = parse_doc(
2440 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2441 path,
2442 )
2443 .unwrap();
2444 assert_eq!(config.modules[0].route_bind_relay_timeout_ms, None);
2445 assert_eq!(config.route_bind_relay_timeout_ms, None);
2446 }
2447
2448 #[test]
2454 fn a_config_without_a_restart_block_keeps_the_supervisor_defaults() {
2455 let path = Path::new("/tmp/subc.jsonc");
2456 let config = parse_doc(
2457 r#"{ "version": 1, "modules": { "m": { "program": "m" } } }"#,
2458 path,
2459 )
2460 .unwrap();
2461 assert_eq!(config.modules[0].restart.max_restarts, 3);
2462 assert_eq!(config.modules[0].restart.window, Duration::from_secs(600));
2463 assert_eq!(
2464 config.modules[0].restart.backoff,
2465 Duration::from_millis(100)
2466 );
2467 assert_eq!(
2468 config.modules[0].restart.max_backoff,
2469 Duration::from_secs(30)
2470 );
2471 }
2472
2473 #[test]
2474 fn register_timeout_config_accepts_bounds_and_rejects_outside_them() {
2475 let path = Path::new("subc.jsonc");
2476 for seconds in [10, 3600] {
2477 let doc = format!(
2478 r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{seconds}}}}}}}"#
2479 );
2480 let config = parse_doc(&doc, path).unwrap();
2481 assert_eq!(
2482 config.modules[0].register_timeout,
2483 Duration::from_secs(seconds)
2484 );
2485 }
2486 for value in ["9", "3601"] {
2487 let doc = format!(
2488 r#"{{"version":1,"modules":{{"m":{{"program":"m","register_timeout_s":{value}}}}}}}"#
2489 );
2490 let error = parse_doc(&doc, path).unwrap_err().to_string();
2491 assert!(error.contains("register_timeout_s"), "{value}: {error}");
2492 }
2493 let config = parse_doc(r#"{"version":1,"modules":{"m":{"program":"m"}}}"#, path).unwrap();
2494 assert_eq!(config.modules[0].register_timeout, Duration::from_secs(120));
2495 }
2496
2497 #[test]
2498 fn a_restart_block_resolves_each_key_independently() {
2499 let path = Path::new("/tmp/subc.jsonc");
2500 let config = parse_doc(
2501 r#"
2502 {
2503 "version": 1,
2504 "modules": {
2505 "all": {
2506 "program": "all",
2507 "restart": { "max_restarts": 5, "window_secs": 60, "backoff_ms": 250, "max_backoff_ms": 5000 }
2508 },
2509 "window-only": {
2510 "program": "window-only",
2511 "restart": { "window_secs": 7200 }
2512 },
2513 "never": {
2514 "program": "never",
2515 "restart": { "max_restarts": 0 }
2516 }
2517 }
2518 }
2519 "#,
2520 path,
2521 )
2522 .unwrap();
2523 let by_id = |id: &str| {
2524 config
2525 .modules
2526 .iter()
2527 .find(|m| m.module_id == id)
2528 .unwrap()
2529 .restart
2530 };
2531
2532 let all = by_id("all");
2533 assert_eq!(all.max_restarts, 5);
2534 assert_eq!(all.window, Duration::from_secs(60));
2535 assert_eq!(all.backoff, Duration::from_millis(250));
2536 assert_eq!(all.max_backoff, Duration::from_secs(5));
2537
2538 let window_only = by_id("window-only");
2541 assert_eq!(window_only.max_restarts, 3);
2542 assert_eq!(window_only.window, Duration::from_secs(7_200));
2543 assert_eq!(window_only.backoff, Duration::from_millis(100));
2544 assert_eq!(window_only.max_backoff, Duration::from_secs(30));
2545
2546 assert_eq!(by_id("never").max_restarts, 0);
2549 }
2550
2551 #[test]
2555 fn restart_window_zero_is_refused_by_name() {
2556 let path = Path::new("/tmp/subc.jsonc");
2557 let err = parse_doc(
2558 r#"
2559 {
2560 "version": 1,
2561 "modules": {
2562 "good": { "program": "good" },
2563 "broken": { "program": "broken", "restart": { "window_secs": 0 } }
2564 }
2565 }
2566 "#,
2567 path,
2568 )
2569 .expect_err("a zero crash window must refuse parse");
2570 assert!(
2571 matches!(err, DaemonConfigError::InvalidValue { .. }),
2572 "a zero window is an invalid value, not a parse failure: {err:?}"
2573 );
2574 let text = format!("{err}");
2575 assert!(
2576 text.contains("restart.window_secs"),
2577 "error must name the offending key: {text}"
2578 );
2579 assert!(
2580 text.contains("broken"),
2581 "error must name the offending module id: {text}"
2582 );
2583 assert!(
2584 text.contains("max_restarts: 0"),
2585 "error must name the setting that actually stops restarts: {text}"
2586 );
2587 }
2588
2589 #[test]
2590 fn restart_max_backoff_below_backoff_is_refused_by_name() {
2591 let path = Path::new("/tmp/subc.jsonc");
2592 let err = parse_doc(
2593 r#"
2594 {
2595 "version": 1,
2596 "modules": {
2597 "broken": {
2598 "program": "broken",
2599 "restart": { "backoff_ms": 1000, "max_backoff_ms": 999 }
2600 }
2601 }
2602 }
2603 "#,
2604 path,
2605 )
2606 .expect_err("a maximum below the base backoff must refuse parse");
2607 assert!(
2608 matches!(err, DaemonConfigError::InvalidValue { .. }),
2609 "an invalid restart bound must be an InvalidValue: {err:?}"
2610 );
2611 let text = format!("{err}");
2612 assert!(
2613 text.contains("restart.max_backoff_ms"),
2614 "error must name max_backoff_ms: {text}"
2615 );
2616 assert!(
2617 text.contains("restart.backoff_ms"),
2618 "error must name backoff_ms: {text}"
2619 );
2620 assert!(
2621 text.contains("broken"),
2622 "error must name the offending module id: {text}"
2623 );
2624 }
2625
2626 #[test]
2627 fn parse_jsonc_defaults_and_ignores_unknown_fields() {
2628 let path = Path::new("/tmp/subc.jsonc");
2629 let config = parse_doc(
2630 r#"
2631 {
2632 // forward-compatible root field
2633 "version": 1,
2634 "unknown": { "ignored": true },
2635 "modules": {
2636 "aft": {
2637 "program": "aft",
2638 "args": ["module",],
2639 "env": { "A": "B", },
2640 "future": 42,
2641 },
2642 "disabled": { "program": "disabled", "enabled": false }
2643 },
2644 }
2645 "#,
2646 path,
2647 )
2648 .unwrap();
2649
2650 assert_eq!(config.port, None);
2651 assert_eq!(config.modules.len(), 2);
2652 assert_eq!(config.modules[0].module_id, "aft");
2653 assert_eq!(config.modules[0].program, PathBuf::from("aft"));
2654 assert_eq!(config.modules[0].args, ["module"]);
2655 assert_eq!(config.modules[0].env, [("A".to_string(), "B".to_string())]);
2656 assert!(config.modules[0].enabled);
2657 assert!(config.modules[0].reserved_prefixes.is_empty());
2658 assert_eq!(config.modules[0].health, HealthConfig::default());
2659 assert!(!config.modules[1].enabled);
2660 }
2661
2662 #[test]
2663 fn reserved_capabilities_accept_unknown_bound_modules_and_refuse_bad_identifiers() {
2664 let path = Path::new("/tmp/subc.jsonc");
2665 let config = parse_doc(
2666 r#"{
2667 "version": 1,
2668 "reserved_capabilities": {
2669 "credentials-provider/v1": "future-vault"
2670 },
2671 "modules": {}
2672 }"#,
2673 path,
2674 )
2675 .expect("a binding may predate its provider installation");
2676 assert_eq!(
2677 config.reserved_capabilities,
2678 BTreeMap::from([(
2679 "credentials-provider/v1".to_string(),
2680 "future-vault".to_string()
2681 )])
2682 );
2683
2684 let error = parse_doc(
2685 r#"{
2686 "version": 1,
2687 "reserved_capabilities": { "Credentials/v1": "vault" },
2688 "modules": {}
2689 }"#,
2690 path,
2691 )
2692 .expect_err("reserved capabilities use the capability identifier grammar");
2693 assert!(error.to_string().contains("reserved_capabilities key"));
2694 }
2695
2696 #[test]
2697 fn retired_launch_nonce_env_is_ignored_for_any_value() {
2698 let parse = |field: &str| {
2699 parse_doc(
2700 &format!(r#"{{"version":1,"modules":{{"probe":{{"program":"probe"{field}}}}}}}"#),
2701 Path::new("subc.jsonc"),
2702 )
2703 .unwrap()
2704 .modules
2705 .remove(0)
2706 .module_spec()
2707 };
2708 for value in ["true", "false", "null", "0", "\"false\"", "[]", "{}"] {
2709 assert_eq!(
2710 parse(""),
2711 parse(&format!(",\"launch_nonce_env\":{value}")),
2712 "the retired key must not change the launch spec or require a restart"
2713 );
2714 }
2715 }
2716
2717 #[test]
2720 fn an_absent_protocol_key_and_an_explicit_subc_are_the_same_module() {
2721 let parse = |module_body: &str| {
2722 parse_doc(
2723 &format!(
2724 r#"{{
2725 "version": 1,
2726 "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2727 }}"#
2728 ),
2729 Path::new("subc.jsonc"),
2730 )
2731 .expect("module parses")
2732 .modules
2733 .remove(0)
2734 };
2735
2736 let absent = parse("");
2737 let explicit = parse(r#", "protocol": "subc""#);
2738 let none = parse(r#", "protocol": "none""#);
2739
2740 assert_eq!(absent.protocol, ModuleProtocol::Subc);
2741 assert_eq!(explicit.protocol, ModuleProtocol::Subc);
2742 assert_eq!(
2743 absent, explicit,
2744 "an absent protocol key must produce exactly the module an explicit subc does"
2745 );
2746 assert_eq!(none.protocol, ModuleProtocol::None);
2747 assert_eq!(none.module_spec().protocol, ModuleProtocol::None);
2751 }
2752
2753 #[test]
2757 fn overlap_defaults_to_exclusive_and_only_safe_opts_in() {
2758 let parse = |module_body: &str| {
2759 parse_doc(
2760 &format!(
2761 r#"{{
2762 "version": 1,
2763 "modules": {{ "aft": {{ "program": "aft"{module_body} }} }}
2764 }}"#
2765 ),
2766 Path::new("subc.jsonc"),
2767 )
2768 };
2769
2770 let absent = parse("").unwrap().modules.remove(0);
2771 assert_eq!(absent.overlap, ModuleOverlap::Exclusive);
2772 assert_eq!(absent.module_spec().overlap, ModuleOverlap::Exclusive);
2773 let safe = parse(r#", "overlap": "safe""#).unwrap().modules.remove(0);
2774 assert_eq!(safe.module_spec().overlap, ModuleOverlap::Safe);
2775 let typo = parse(r#", "overlap": "sfae""#).expect_err("an unknown overlap is refused");
2776 assert!(typo.to_string().contains("sfae"), "{typo}");
2777 }
2778
2779 #[test]
2780 fn carry_containment_defaults_off_and_refuses_overlap() {
2781 let parse = |module_body: &str| {
2782 parse_doc(
2783 &format!(
2784 r#"{{
2785 "version": 1,
2786 "modules": {{ "worker": {{ "program": "worker"{module_body} }} }}
2787 }}"#
2788 ),
2789 Path::new("subc.jsonc"),
2790 )
2791 };
2792
2793 let absent = parse("").unwrap().modules.remove(0);
2794 let explicit_off = parse(r#", "carry_containment": false"#)
2795 .unwrap()
2796 .modules
2797 .remove(0);
2798 assert_eq!(absent, explicit_off);
2799 assert!(!absent.module_spec().carry_containment);
2800 let carried = parse(r#", "carry_containment": true"#)
2801 .unwrap()
2802 .modules
2803 .remove(0);
2804 assert!(carried.module_spec().carry_containment);
2805 let error = parse(r#", "carry_containment": true, "overlap": "safe""#)
2806 .expect_err("a carried container cannot have overlapping leaders");
2807 let message = error.to_string();
2808 assert!(message.contains("worker"), "{message}");
2809 assert!(message.contains("carry_containment"), "{message}");
2810 assert!(message.contains("overlap"), "{message}");
2811 }
2812
2813 #[test]
2817 fn the_spawn_role_is_refused_as_a_configured_env_key() {
2818 let error = parse_doc(
2819 r#"{
2820 "version": 1,
2821 "modules": { "aft": { "program": "aft", "env": { "SUBC_SPAWN_ROLE": "swap_candidate" } } }
2822 }"#,
2823 Path::new("subc.jsonc"),
2824 )
2825 .expect_err("SUBC_SPAWN_ROLE must not be configurable");
2826 assert!(
2827 matches!(error, DaemonConfigError::InvalidValue { .. }),
2828 "expected InvalidValue, got {error:?}"
2829 );
2830 assert!(error.to_string().contains("SUBC_SPAWN_ROLE"), "{error}");
2831 }
2832
2833 #[test]
2839 fn an_unsupported_protocol_value_is_refused_by_name() {
2840 let error = parse_doc(
2841 r#"{
2842 "version": 1,
2843 "modules": { "nats": { "program": "nats-server", "protocol": "grpc" } }
2844 }"#,
2845 Path::new("subc.jsonc"),
2846 )
2847 .expect_err("an unknown protocol must not fall back to a default");
2848
2849 assert!(
2850 matches!(error, DaemonConfigError::InvalidValue { .. }),
2851 "expected InvalidValue, got {error:?}"
2852 );
2853 let message = error.to_string();
2854 assert!(
2855 message.contains("grpc"),
2856 "the refusal must name the offending value: {message}"
2857 );
2858 assert!(
2859 message.contains("nats"),
2860 "the refusal must name the module so it can be found in the file: {message}"
2861 );
2862 }
2863
2864 #[test]
2868 fn reserved_true_with_protocol_none_is_refused_with_the_reason() {
2869 let error = parse_doc(
2870 r#"{
2871 "version": 1,
2872 "modules": {
2873 "nats": { "program": "nats-server", "protocol": "none", "reserved": true }
2874 }
2875 }"#,
2876 Path::new("subc.jsonc"),
2877 )
2878 .expect_err("a reservation that can never be checked must not parse");
2879
2880 assert!(
2881 matches!(error, DaemonConfigError::InvalidValue { .. }),
2882 "expected InvalidValue, got {error:?}"
2883 );
2884 let message = error.to_string();
2885 assert!(
2886 message.contains("nats") && message.contains("reserved"),
2887 "the refusal must name the module and the offending key: {message}"
2888 );
2889 assert!(
2890 message.contains("HELLO") || message.contains("never registers"),
2891 "the refusal must say WHY the pair cannot work: {message}"
2892 );
2893 }
2894
2895 #[test]
2896 fn reserved_prefixes_parse_for_reserved_modules() {
2897 let config = parse_doc(
2898 r#"
2899 {
2900 "version": 1,
2901 "modules": {
2902 "federation": {
2903 "program": "fed",
2904 "reserved": true,
2905 "reserved_prefixes": ["fed:"]
2906 }
2907 }
2908 }
2909 "#,
2910 Path::new("subc.jsonc"),
2911 )
2912 .unwrap();
2913
2914 assert_eq!(config.modules[0].reserved_prefixes, ["fed:".to_string()]);
2915 }
2916
2917 #[test]
2918 fn reserved_prefixes_reject_bad_boundaries_and_owners() {
2919 let missing_delimiter = parse_doc(
2920 r#"{
2921 "version": 1,
2922 "modules": {
2923 "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed"] }
2924 }
2925 }"#,
2926 Path::new("subc.jsonc"),
2927 )
2928 .unwrap_err();
2929 assert!(matches!(
2930 missing_delimiter,
2931 DaemonConfigError::InvalidValue { .. }
2932 ));
2933
2934 let non_reserved_owner = parse_doc(
2935 r#"{
2936 "version": 1,
2937 "modules": {
2938 "federation": { "program": "fed", "reserved_prefixes": ["fed:"] }
2939 }
2940 }"#,
2941 Path::new("subc.jsonc"),
2942 )
2943 .unwrap_err();
2944 assert!(matches!(
2945 non_reserved_owner,
2946 DaemonConfigError::InvalidValue { .. }
2947 ));
2948 }
2949
2950 #[test]
2951 fn reserved_prefixes_reject_cross_owner_overlap_and_exact_id_collisions() {
2952 let overlap = parse_doc(
2953 r#"{
2954 "version": 1,
2955 "modules": {
2956 "fed-owner": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2957 "sub-owner": { "program": "fed-sub", "reserved": true, "reserved_prefixes": ["fed:sub:"] }
2958 }
2959 }"#,
2960 Path::new("subc.jsonc"),
2961 )
2962 .unwrap_err();
2963 assert!(matches!(overlap, DaemonConfigError::InvalidValue { .. }));
2964
2965 let exact_collision = parse_doc(
2966 r#"{
2967 "version": 1,
2968 "modules": {
2969 "federation": { "program": "fed", "reserved": true, "reserved_prefixes": ["fed:"] },
2970 "fed:special": { "program": "special" }
2971 }
2972 }"#,
2973 Path::new("subc.jsonc"),
2974 )
2975 .unwrap_err();
2976 assert!(matches!(
2977 exact_collision,
2978 DaemonConfigError::InvalidValue { .. }
2979 ));
2980 }
2981
2982 #[test]
2983 fn health_config_parses_and_ignores_unknown_fields() {
2984 let config = parse_doc(
2985 r#"
2986 {
2987 "version": 1,
2988 "modules": {
2989 "aft": {
2990 "program": "aft",
2991 "health": {
2992 "cadence_ms": 100,
2993 "deadline_ms": 20,
2994 "failure_threshold": 2,
2995 "on_degraded": "report",
2996 "on_failing": "restart",
2997 "critical": true,
2998 "future": "ignored"
2999 }
3000 }
3001 }
3002 }
3003 "#,
3004 Path::new("subc.jsonc"),
3005 )
3006 .unwrap();
3007
3008 let health = &config.modules[0].health;
3009 assert_eq!(health.cadence, std::time::Duration::from_millis(100));
3010 assert_eq!(health.deadline, std::time::Duration::from_millis(20));
3011 assert_eq!(health.failure_threshold, 2);
3012 assert_eq!(health.on_degraded, HealthAction::Report);
3013 assert_eq!(health.on_failing, HealthAction::Restart);
3014 assert!(health.critical);
3015 }
3016
3017 #[test]
3018 fn http_health_refuses_non_loopback_https_and_wire_modules() {
3019 for (protocol, url) in [
3020 ("none", "http://example.com/healthz"),
3021 ("none", "https://127.0.0.1/healthz"),
3022 ("subc", "http://127.0.0.1/healthz"),
3023 ] {
3024 let doc = serde_json::json!({"version": 1, "modules": {"bus": {
3025 "program": "nats-server", "protocol": protocol, "health": {"http": url}
3026 }}})
3027 .to_string();
3028 let error = parse_doc(&doc, Path::new("test.jsonc"))
3029 .unwrap_err()
3030 .to_string();
3031 assert!(
3032 error.contains("bus") && error.contains("health.http"),
3033 "{error}"
3034 );
3035 }
3036 }
3037
3038 #[test]
3039 fn health_config_rejects_bad_enum_and_non_positive_numbers() {
3040 let bad_enum = parse_doc(
3041 r#"{
3042 "version": 1,
3043 "modules": { "aft": { "program": "aft", "health": { "on_failing": "page" } } }
3044 }"#,
3045 Path::new("subc.jsonc"),
3046 )
3047 .unwrap_err();
3048 assert!(matches!(bad_enum, DaemonConfigError::InvalidJson { .. }));
3049
3050 let zero = parse_doc(
3051 r#"{
3052 "version": 1,
3053 "modules": { "aft": { "program": "aft", "health": { "cadence_ms": 0 } } }
3054 }"#,
3055 Path::new("subc.jsonc"),
3056 )
3057 .unwrap_err();
3058 assert!(matches!(zero, DaemonConfigError::InvalidValue { .. }));
3059 }
3060
3061 #[test]
3062 fn admission_facts_carrier_requires_non_empty_targets() {
3063 let missing_targets = parse_doc(
3064 r#"{
3065 "version": 1,
3066 "admission_facts_carrier_module_id": "fed",
3067 "modules": { "fed": { "program": "fed", "reserved": true } }
3068 }"#,
3069 Path::new("subc.jsonc"),
3070 )
3071 .unwrap_err();
3072 assert!(
3078 matches!(&missing_targets, DaemonConfigError::InvalidValue { message, .. }
3079 if message.contains("must be present")),
3080 "expected the presence rule, got: {missing_targets:?}"
3081 );
3082
3083 let empty_targets = parse_doc(
3084 r#"{
3085 "version": 1,
3086 "admission_facts_carrier_module_id": "fed",
3087 "admission_facts_targets": [""],
3088 "modules": { "fed": { "program": "fed", "reserved": true } }
3089 }"#,
3090 Path::new("subc.jsonc"),
3091 )
3092 .unwrap_err();
3093 assert!(
3094 matches!(&empty_targets, DaemonConfigError::InvalidValue { message, .. }
3095 if message.contains("must be non-empty")),
3096 "expected the non-empty rule, got: {empty_targets:?}"
3097 );
3098 }
3099
3100 #[test]
3101 fn admission_facts_carrier_must_be_enabled_reserved_and_configured() {
3102 for module in [
3103 r#"{ "program": "fed", "enabled": false, "reserved": true }"#,
3104 r#"{ "program": "fed", "enabled": true, "reserved": false }"#,
3105 ] {
3106 let doc = format!(
3107 r#"{{
3108 "version": 1,
3109 "admission_facts_carrier_module_id": "fed",
3110 "admission_facts_targets": ["target"],
3111 "modules": {{ "fed": {module}, "target": {{ "program": "target" }} }}
3112 }}"#
3113 );
3114 let err = parse_doc(&doc, Path::new("subc.jsonc")).unwrap_err();
3115 assert!(
3119 matches!(&err, DaemonConfigError::InvalidValue { message, .. }
3120 if message.contains("enabled reserved module")),
3121 "expected the enabled-and-reserved rule, got: {err:?}"
3122 );
3123 }
3124
3125 let absent = parse_doc(
3126 r#"{
3127 "version": 1,
3128 "admission_facts_carrier_module_id": "missing",
3129 "admission_facts_targets": ["target"],
3130 "modules": { "target": { "program": "target" } }
3131 }"#,
3132 Path::new("subc.jsonc"),
3133 )
3134 .unwrap_err();
3135 assert!(
3136 matches!(&absent, DaemonConfigError::InvalidValue { message, .. }
3137 if message.contains("must name a configured module")),
3138 "expected the configured-module rule, got: {absent:?}"
3139 );
3140 }
3141
3142 #[test]
3143 fn reject_unsupported_version() {
3144 let err = parse_doc(
3145 r#"{ "version": 2, "modules": {} }"#,
3146 Path::new("subc.jsonc"),
3147 )
3148 .unwrap_err();
3149 assert!(matches!(
3150 err,
3151 DaemonConfigError::UnsupportedVersion { version: 2, .. }
3152 ));
3153 }
3154
3155 #[test]
3156 fn reject_unterminated_block_comment() {
3157 let err = parse_doc(r#"{ "version": 1, /*"#, Path::new("subc.jsonc")).unwrap_err();
3158 assert!(matches!(err, DaemonConfigError::InvalidJsonc { .. }));
3159 }
3160}
3161
3162#[cfg(test)]
3163mod activity_config_tests {
3164 use super::*;
3165
3166 #[test]
3167 fn activity_config_defaults_partial_overrides_and_positive_bounds() {
3168 let path = Path::new("subc.jsonc");
3169 let default = parse_doc_with_activity(r#"{"version":1,"modules":{}}"#, path).unwrap();
3170 assert_eq!(
3171 default.1,
3172 ActivityConfig {
3173 max_age_days: 30,
3174 max_total_mb: 64
3175 }
3176 );
3177 let changed = parse_doc_with_activity(
3178 r#"{"version":1,"activity":{"max_age_days":7,"max_total_mb":8}}"#,
3179 path,
3180 )
3181 .unwrap();
3182 assert_eq!(
3183 changed.1,
3184 ActivityConfig {
3185 max_age_days: 7,
3186 max_total_mb: 8
3187 }
3188 );
3189 let partial =
3190 parse_doc_with_activity(r#"{"version":1,"activity":{"max_age_days":7}}"#, path)
3191 .unwrap();
3192 assert_eq!(
3193 partial.1,
3194 ActivityConfig {
3195 max_age_days: 7,
3196 max_total_mb: 64
3197 }
3198 );
3199 for doc in [
3200 r#"{"version":1,"activity":{"max_age_days":0}}"#,
3201 r#"{"version":1,"activity":{"max_total_mb":0}}"#,
3202 ] {
3203 assert!(parse_doc(doc, path).is_err());
3204 }
3205 assert!(!RestartRequiredSection::ALL
3206 .iter()
3207 .any(|section| section.label() == "activity"));
3208 }
3209}
3210
3211#[cfg(test)]
3212mod registration_declaration_tests {
3213 use super::*;
3214 #[test]
3215 fn registration_declaration_config_bool_is_optional_and_typed() {
3216 let parse = |field: &str| {
3217 parse_doc(
3218 &format!(r#"{{"version":1,"modules":{{"worker":{{"program":"worker"{field}}}}}}}"#),
3219 Path::new("subc.jsonc"),
3220 )
3221 };
3222 assert!(!parse("").unwrap().modules[0].registration_channel);
3223 assert!(
3224 !parse(r#", "registration_channel":false"#).unwrap().modules[0].registration_channel
3225 );
3226 assert!(parse(r#", "registration_channel":true"#).unwrap().modules[0].registration_channel);
3227 assert!(parse(r#", "registration_channel":"true""#).is_err());
3228 }
3229}