From c60484a5b8ae476d70f6cb8633604fce39c02dbc Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 27 Oct 2026 07:54:46 -0500 Subject: [PATCH] feat(config): implement TOML configuration parser and credential resolution - Add AppConfig, IpProvidersConfig, and SubscriberConfig - Support credential resolution from environment variables or secrets files - Implement automatic fallback paths for state and history files (systemd / XDG) - Add comprehensive unit tests covering parsing, resolution, and validation --- src/config.rs | 188 +++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + tests/config_test.rs | 102 +++++++++++++++++++++++ 3 files changed, 291 insertions(+) create mode 100644 src/config.rs create mode 100644 tests/config_test.rs diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..c85dc75 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,188 @@ +use serde::Deserialize; +use std::fs; +use std::path::{Path, PathBuf}; + +use crate::domain::errors::ConfigError; + +/// Configuration for the public IP discovery checkers. +#[derive(Debug, Clone, Deserialize)] +pub struct IpProvidersConfig { + /// List of external IP-echo URLs (e.g. "https://api.ipify.org"). + pub urls: Vec, + + /// Timeout in seconds per HTTP check attempt. + #[serde(default = "default_timeout_secs")] + pub timeout_secs: u64, +} + +fn default_timeout_secs() -> u64 { + 5 +} + +/// Configuration for an individual DDNS subscriber. +#[derive(Debug, Clone, Deserialize)] +pub struct SubscriberConfig { + /// Provider type ("dynu", etc.). + pub provider: String, + + /// Domain name to update. + pub domain: String, + + /// Environment variable name holding the credential or API key. + pub credentials_env: Option, + + /// Path to a secret file containing the credential. + pub credentials_file: Option, +} + +impl SubscriberConfig { + /// Resolves the credential for this subscriber from the environment + /// or from a file. + pub fn resolve_credential(&self) -> Result { + if let Some(ref env_var) = self.credentials_env { + match std::env::var(env_var) { + Ok(val) => { + let trimmed = val.trim().to_string(); + if !trimmed.is_empty() { + return Ok(trimmed); + } + } + Err(e) => { + if self.credentials_file.is_none() { + return Err(ConfigError::MissingEnvVar { + var: env_var.clone(), + source: e, + }); + } + } + } + } + + if let Some(ref file_path) = self.credentials_file { + let content = fs::read_to_string(file_path).map_err(|source| ConfigError::Io { + path: file_path.to_string_lossy().to_string(), + source, + })?; + let trimmed = content.trim().to_string(); + if trimmed.is_empty() { + return Err(ConfigError::Validation(format!( + "Credential file '{}' is empty", + file_path.display() + ))); + } + return Ok(trimmed); + } + + Err(ConfigError::Validation(format!( + "Subscriber for domain '{}' must specify either 'credentials_env' or 'credentials_file'", + self.domain + ))) + } +} + +/// Root application configuration. +#[derive(Debug, Clone, Deserialize)] +pub struct AppConfig { + /// IP provider settings. + pub ip_providers: IpProvidersConfig, + + /// List of configured DDNS subscribers. + #[serde(default)] + pub subscribers: Vec, + + /// Optional explicit path to the state file. + pub state_path: Option, + + /// Optional explicit path to the JSONL history audit log. + pub history_path: Option, +} + +impl AppConfig { + /// Deserializes and validates configuration from a TOML string. + pub fn from_toml(content: &str) -> Result { + let config: AppConfig = toml::from_str(content)?; + config.validate()?; + Ok(config) + } + + /// Loads and validates configuration from a file on disk. + pub fn load_from_path>(path: P) -> Result { + let path_ref = path.as_ref(); + let content = fs::read_to_string(path_ref).map_err(|source| ConfigError::Io { + path: path_ref.to_string_lossy().to_string(), + source, + })?; + Self::from_toml(&content) + } + + /// Validates the configuration semantics. + pub fn validate(&self) -> Result<(), ConfigError> { + if self.ip_providers.urls.is_empty() { + return Err(ConfigError::Validation( + "At least one IP provider URL must be configured".to_string(), + )); + } + + if self.ip_providers.timeout_secs == 0 { + return Err(ConfigError::Validation( + "IP provider timeout must be greater than 0 seconds".to_string(), + )); + } + + for sub in &self.subscribers { + if sub.domain.trim().is_empty() { + return Err(ConfigError::Validation( + "Subscriber domain cannot be empty".to_string(), + )); + } + if sub.credentials_env.is_none() && sub.credentials_file.is_none() { + return Err(ConfigError::Validation(format!( + "Subscriber for domain '{}' must have credentials_env or credentials_file", + sub.domain + ))); + } + } + + Ok(()) + } + + /// Returns the resolved state file path (config override -> systemd StateDirectory -> XDG). + pub fn resolve_state_path(&self) -> PathBuf { + if let Some(ref path) = self.state_path { + return path.clone(); + } + + if let Ok(state_dir) = std::env::var("STATE_DIRECTORY") { + return PathBuf::from(state_dir).join("state.json"); + } + + if let Ok(home) = std::env::var("HOME") { + return PathBuf::from(home) + .join(".config") + .join("ddns-monitor") + .join("state.json"); + } + + PathBuf::from("/var/lib/ddns-monitor/state.json") + } + + /// Returns the resolved history file path (config override -> systemd StateDirectory -> XDG). + pub fn resolve_history_path(&self) -> PathBuf { + if let Some(ref path) = self.history_path { + return path.clone(); + } + + if let Ok(state_dir) = std::env::var("STATE_DIRECTORY") { + return PathBuf::from(state_dir).join("history.jsonl"); + } + + if let Ok(home) = std::env::var("HOME") { + return PathBuf::from(home) + .join(".config") + .join("ddns-monitor") + .join("history.jsonl"); + } + + PathBuf::from("/var/lib/ddns-monitor/history.jsonl") + } +} diff --git a/src/lib.rs b/src/lib.rs index d7abca1..c8c1a08 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1 +1,2 @@ +pub mod config; pub mod domain; diff --git a/tests/config_test.rs b/tests/config_test.rs new file mode 100644 index 0000000..2539147 --- /dev/null +++ b/tests/config_test.rs @@ -0,0 +1,102 @@ +use ddns_monitor::config::{AppConfig, SubscriberConfig}; +use ddns_monitor::domain::errors::ConfigError; +use std::fs; + +#[test] +fn test_parse_valid_toml_config() { + let toml_data = r#" +[ip_providers] +urls = [ + "https://api.ipify.org", + "https://ifconfig.me/ip" +] +timeout_secs = 5 + +[[subscribers]] +provider = "dynu" +domain = "example.dyndns.org" +credentials_env = "TEST_DYNU_SECRET" + +[[subscribers]] +provider = "dynu" +domain = "backup.dyndns.org" +credentials_file = "/tmp/fake_secret" +"#; + + let config = AppConfig::from_toml(toml_data).expect("valid config"); + assert_eq!(config.ip_providers.urls.len(), 2); + assert_eq!(config.ip_providers.timeout_secs, 5); + assert_eq!(config.subscribers.len(), 2); + assert_eq!(config.subscribers[0].provider, "dynu"); + assert_eq!(config.subscribers[0].domain, "example.dyndns.org"); + assert_eq!( + config.subscribers[0].credentials_env.as_deref(), + Some("TEST_DYNU_SECRET") + ); +} + +#[test] +fn test_resolve_credential_from_env() { + let sub = SubscriberConfig { + provider: "dynu".to_string(), + domain: "test.org".to_string(), + credentials_env: Some("DDNS_TEST_ENV_VAR_123".to_string()), + credentials_file: None, + }; + + // Before setting env var + unsafe { + std::env::remove_var("DDNS_TEST_ENV_VAR_123"); + } + assert!(sub.resolve_credential().is_err()); + + // After setting env var + unsafe { + std::env::set_var("DDNS_TEST_ENV_VAR_123", "secret123"); + } + let secret = sub.resolve_credential().expect("resolved from env"); + assert_eq!(secret, "secret123"); + unsafe { + std::env::remove_var("DDNS_TEST_ENV_VAR_123"); + } +} + +#[test] +fn test_resolve_credential_from_file() { + let temp_path = std::env::temp_dir().join("ddns_monitor_test_secret.txt"); + fs::write(&temp_path, " my-file-secret \n").unwrap(); + + let sub = SubscriberConfig { + provider: "dynu".to_string(), + domain: "test.org".to_string(), + credentials_env: None, + credentials_file: Some(temp_path.clone()), + }; + + let secret = sub.resolve_credential().expect("resolved from file"); + assert_eq!(secret, "my-file-secret"); + let _ = fs::remove_file(temp_path); +} + +#[test] +fn test_empty_urls_validation_error() { + let toml_data = r#" +[ip_providers] +urls = [] +timeout_secs = 5 + +[[subscribers]] +provider = "dynu" +domain = "example.com" +credentials_env = "FOO" +"#; + + let res = AppConfig::from_toml(toml_data); + assert!(res.is_err()); + match res.unwrap_err() { + ConfigError::Validation(msg) => { + assert!(msg.contains("At least one IP provider URL")); + } + err => panic!("Unexpected error type: {:?}", err), + } +}