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