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