Land the shared peer contracts: types, error mapping, transport trait, fake transport and fixtures, registry/proxy/health skeletons, the AppState.peers and Config.peers seams, the ping and peers route stubs, and unit plus integration tests. No loops, no network, feature off by default.
495 lines
15 KiB
Rust
495 lines
15 KiB
Rust
//! Layered configuration.
|
|
//!
|
|
//! Precedence, lowest to highest: built-in defaults, TOML file, `SKYG_*`
|
|
//! environment variables (`__` separates nesting, e.g. `SKYG_SERVER__PORT`),
|
|
//! CLI overrides.
|
|
//!
|
|
//! No field is an `Option` so the effective config serializes to TOML.
|
|
//! An empty string or empty list means "unset".
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::net::{IpAddr, Ipv4Addr};
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use figment::providers::{Env, Format, Serialized, Toml};
|
|
use figment::Figment;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::peers::PeersConfig;
|
|
|
|
/// Default config file location, used only when it exists and `--config` is absent.
|
|
pub const DEFAULT_CONFIG_PATH: &str = "/etc/skyg-linux-tracker.toml";
|
|
/// Environment variable prefix.
|
|
pub const ENV_PREFIX: &str = "SKYG_";
|
|
|
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct Config {
|
|
pub server: ServerConfig,
|
|
pub auth: AuthConfig,
|
|
pub otel: OtelConfig,
|
|
pub sources: SourcesConfig,
|
|
pub limits: LimitsConfig,
|
|
pub peers: PeersConfig,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct ServerConfig {
|
|
/// Listen address. Non-loopback requires `auth.enabled = true`.
|
|
pub bind: IpAddr,
|
|
pub port: u16,
|
|
/// Extra `Host` header values accepted on `/mcp`, added to the defaults
|
|
/// (loopback names plus `bind`).
|
|
pub allowed_hosts: Vec<String>,
|
|
/// Extra `Origin` values accepted on `/mcp`, added to the defaults
|
|
/// (loopback origins plus `bind`). Entries include a scheme.
|
|
pub allowed_origins: Vec<String>,
|
|
/// Optional native TLS (off by default).
|
|
pub tls: TlsConfig,
|
|
}
|
|
|
|
/// Native TLS for REST and `/mcp`. Optional: when `enabled` is false the
|
|
/// paths are ignored and never read.
|
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct TlsConfig {
|
|
pub enabled: bool,
|
|
/// PEM certificate chain (leaf first).
|
|
pub cert_file: PathBuf,
|
|
/// PEM private key (PKCS#8, PKCS#1 or SEC1).
|
|
pub key_file: PathBuf,
|
|
}
|
|
|
|
impl ServerConfig {
|
|
/// Host names always accepted: loopback plus `bind` (unless unspecified).
|
|
pub fn default_hosts(&self) -> Vec<String> {
|
|
let mut v: Vec<String> = ["localhost", "127.0.0.1", "::1"]
|
|
.into_iter()
|
|
.map(String::from)
|
|
.collect();
|
|
if !self.bind.is_unspecified() {
|
|
v.push(self.bind.to_string());
|
|
}
|
|
v
|
|
}
|
|
}
|
|
|
|
impl Default for ServerConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
bind: IpAddr::V4(Ipv4Addr::LOCALHOST),
|
|
port: 1984,
|
|
allowed_hosts: Vec::new(),
|
|
allowed_origins: Vec::new(),
|
|
tls: TlsConfig::default(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct AuthConfig {
|
|
pub enabled: bool,
|
|
pub db_path: PathBuf,
|
|
}
|
|
|
|
impl Default for AuthConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
enabled: true,
|
|
db_path: PathBuf::from("/var/lib/skyg-linux-tracker/db.sqlite"),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
|
pub enum OtelProtocol {
|
|
#[default]
|
|
#[serde(rename = "grpc")]
|
|
Grpc,
|
|
#[serde(rename = "http/protobuf")]
|
|
HttpProtobuf,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct OtelConfig {
|
|
pub enabled: bool,
|
|
pub endpoint: String,
|
|
pub protocol: OtelProtocol,
|
|
pub service_name: String,
|
|
/// Extra OTLP headers or gRPC metadata (for example `authorization`).
|
|
pub headers: BTreeMap<String, String>,
|
|
pub export_unit_metrics: bool,
|
|
pub export_logs: bool,
|
|
pub metrics_interval_secs: u64,
|
|
pub logs: OtelLogsConfig,
|
|
pub metrics: OtelMetricsConfig,
|
|
}
|
|
|
|
impl Default for OtelConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
enabled: false,
|
|
endpoint: "http://localhost:4317".into(),
|
|
protocol: OtelProtocol::Grpc,
|
|
service_name: "skyg-linux-tracker".into(),
|
|
headers: BTreeMap::new(),
|
|
export_unit_metrics: true,
|
|
export_logs: false,
|
|
metrics_interval_secs: 30,
|
|
logs: OtelLogsConfig::default(),
|
|
metrics: OtelMetricsConfig::default(),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Which journal units / containers feed OTel logs. Empty means all.
|
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct OtelLogsConfig {
|
|
pub journal_units: Vec<String>,
|
|
pub docker_containers: Vec<String>,
|
|
}
|
|
|
|
/// Glob allowlists for exported metrics.
|
|
///
|
|
/// Empty `units` means `*.service` and `*.timer`. Empty `containers`
|
|
/// means all containers.
|
|
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct OtelMetricsConfig {
|
|
pub units: Vec<String>,
|
|
pub containers: Vec<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct SourcesConfig {
|
|
pub docker_socket: PathBuf,
|
|
/// Journal namespace. Empty means the default journal.
|
|
pub journal_namespace: String,
|
|
}
|
|
|
|
impl Default for SourcesConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
docker_socket: PathBuf::from("/var/run/docker.sock"),
|
|
journal_namespace: String::new(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
#[serde(default)]
|
|
pub struct LimitsConfig {
|
|
/// Maximum journal lines per snapshot or MCP call.
|
|
pub max_lines: usize,
|
|
/// Maximum container log lines (`tail`).
|
|
pub max_tail: usize,
|
|
/// Maximum duration of a bounded follow, in seconds.
|
|
pub max_follow_secs: u64,
|
|
}
|
|
|
|
impl Default for LimitsConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
max_lines: 1000,
|
|
max_tail: 1000,
|
|
max_follow_secs: 60,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
pub enum ConfigError {
|
|
#[error("config file not found: {0}")]
|
|
MissingFile(PathBuf),
|
|
#[error("invalid configuration: {0}")]
|
|
Load(Box<figment::Error>),
|
|
#[error("invalid configuration: {0}")]
|
|
Invalid(String),
|
|
}
|
|
|
|
impl From<figment::Error> for ConfigError {
|
|
fn from(e: figment::Error) -> Self {
|
|
Self::Load(Box::new(e))
|
|
}
|
|
}
|
|
|
|
/// Highest-precedence layer. Only `Some` fields are applied.
|
|
#[derive(Debug, Clone, Default)]
|
|
pub struct CliOverrides {
|
|
pub bind: Option<IpAddr>,
|
|
pub port: Option<u16>,
|
|
pub auth_enabled: Option<bool>,
|
|
pub db_path: Option<PathBuf>,
|
|
pub docker_socket: Option<PathBuf>,
|
|
pub journal_namespace: Option<String>,
|
|
pub otel_enabled: Option<bool>,
|
|
pub otel_endpoint: Option<String>,
|
|
}
|
|
|
|
impl CliOverrides {
|
|
fn apply(&self, mut fig: Figment) -> Figment {
|
|
fn put<T: Serialize>(fig: Figment, key: &str, v: &Option<T>) -> Figment {
|
|
match v {
|
|
Some(v) => fig.merge(Serialized::default(key, v)),
|
|
None => fig,
|
|
}
|
|
}
|
|
fig = put(fig, "server.bind", &self.bind);
|
|
fig = put(fig, "server.port", &self.port);
|
|
fig = put(fig, "auth.enabled", &self.auth_enabled);
|
|
fig = put(fig, "auth.db_path", &self.db_path);
|
|
fig = put(fig, "sources.docker_socket", &self.docker_socket);
|
|
fig = put(fig, "sources.journal_namespace", &self.journal_namespace);
|
|
fig = put(fig, "otel.enabled", &self.otel_enabled);
|
|
fig = put(fig, "otel.endpoint", &self.otel_endpoint);
|
|
fig
|
|
}
|
|
}
|
|
|
|
impl Config {
|
|
/// Build the merged config.
|
|
///
|
|
/// `file`: explicit `--config` path (must exist). When `None`, the default
|
|
/// path is read only if present.
|
|
pub fn load(file: Option<&Path>, cli: &CliOverrides) -> Result<Self, ConfigError> {
|
|
let mut fig = Figment::from(Serialized::defaults(Config::default()));
|
|
match file {
|
|
Some(p) => {
|
|
if !p.exists() {
|
|
return Err(ConfigError::MissingFile(p.to_path_buf()));
|
|
}
|
|
fig = fig.merge(Toml::file(p));
|
|
}
|
|
None => {
|
|
let p = Path::new(DEFAULT_CONFIG_PATH);
|
|
if p.exists() {
|
|
fig = fig.merge(Toml::file(p));
|
|
}
|
|
}
|
|
}
|
|
fig = fig.merge(Env::prefixed(ENV_PREFIX).split("__"));
|
|
fig = cli.apply(fig);
|
|
let cfg: Config = fig.extract()?;
|
|
cfg.validate()?;
|
|
Ok(cfg)
|
|
}
|
|
|
|
/// Cross-field validation.
|
|
pub fn validate(&self) -> Result<(), ConfigError> {
|
|
if self.server.port == 0 {
|
|
return Err(ConfigError::Invalid(
|
|
"server.port must be greater than zero".into(),
|
|
));
|
|
}
|
|
let tls = &self.server.tls;
|
|
if tls.enabled
|
|
&& (tls.cert_file.as_os_str().is_empty() || tls.key_file.as_os_str().is_empty())
|
|
{
|
|
return Err(ConfigError::Invalid(
|
|
"server.tls.enabled = true requires both server.tls.cert_file and server.tls.key_file"
|
|
.into(),
|
|
));
|
|
}
|
|
if !self.auth.enabled && !self.server.bind.is_loopback() {
|
|
return Err(ConfigError::Invalid(format!(
|
|
"auth.enabled = false is only allowed on a loopback bind address (server.bind = {})",
|
|
self.server.bind
|
|
)));
|
|
}
|
|
if self.limits.max_lines == 0
|
|
|| self.limits.max_tail == 0
|
|
|| self.limits.max_follow_secs == 0
|
|
{
|
|
return Err(ConfigError::Invalid(
|
|
"limits.* must be greater than zero".into(),
|
|
));
|
|
}
|
|
if self.otel.metrics_interval_secs == 0 {
|
|
return Err(ConfigError::Invalid(
|
|
"otel.metrics_interval_secs must be greater than zero".into(),
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Effective config as TOML, with OTLP header values redacted.
|
|
pub fn to_toml_redacted(&self) -> Result<String, toml::ser::Error> {
|
|
let mut c = self.clone();
|
|
for v in c.otel.headers.values_mut() {
|
|
*v = "***".into();
|
|
}
|
|
toml::to_string_pretty(&c)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[allow(clippy::result_large_err)] // figment::Jail closures return figment::Error
|
|
mod tests {
|
|
use super::*;
|
|
use figment::Jail;
|
|
|
|
fn load(file: Option<&str>, cli: &CliOverrides) -> Result<Config, ConfigError> {
|
|
Config::load(file.map(Path::new), cli)
|
|
}
|
|
|
|
#[test]
|
|
fn port_zero_rejected() {
|
|
Jail::expect_with(|_| {
|
|
let cli = CliOverrides {
|
|
port: Some(0),
|
|
..Default::default()
|
|
};
|
|
assert!(load(None, &cli).is_err());
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn defaults_only() {
|
|
Jail::expect_with(|jail| {
|
|
// An explicit empty file keeps the test independent of the host's /etc config.
|
|
jail.create_file("empty.toml", "")?;
|
|
let c = load(Some("empty.toml"), &CliOverrides::default()).unwrap();
|
|
assert_eq!(c, Config::default());
|
|
assert_eq!(c.server.port, 1984);
|
|
assert!(c.auth.enabled);
|
|
assert_eq!(c.limits.max_lines, 1000);
|
|
assert_eq!(c.limits.max_follow_secs, 60);
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn file_overrides_defaults() {
|
|
Jail::expect_with(|jail| {
|
|
jail.create_file(
|
|
"c.toml",
|
|
r#"
|
|
[server]
|
|
port = 8000
|
|
[otel.headers]
|
|
authorization = "Bearer x"
|
|
[otel.metrics]
|
|
units = ["nginx.service"]
|
|
[limits]
|
|
max_lines = 50
|
|
"#,
|
|
)?;
|
|
let c = load(Some("c.toml"), &CliOverrides::default()).unwrap();
|
|
assert_eq!(c.server.port, 8000);
|
|
assert_eq!(c.otel.headers["authorization"], "Bearer x");
|
|
assert_eq!(c.otel.metrics.units, vec!["nginx.service"]);
|
|
assert_eq!(c.limits.max_lines, 50);
|
|
assert_eq!(c.limits.max_tail, 1000);
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn env_overrides_file() {
|
|
Jail::expect_with(|jail| {
|
|
jail.create_file("c.toml", "[server]\nport = 8000\n")?;
|
|
jail.set_env("SKYG_SERVER__PORT", "8100");
|
|
jail.set_env("SKYG_LIMITS__MAX_TAIL", "7");
|
|
let c = load(Some("c.toml"), &CliOverrides::default()).unwrap();
|
|
assert_eq!(c.server.port, 8100);
|
|
assert_eq!(c.limits.max_tail, 7);
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn cli_overrides_env() {
|
|
Jail::expect_with(|jail| {
|
|
jail.create_file("c.toml", "[server]\nport = 8000\n")?;
|
|
jail.set_env("SKYG_SERVER__PORT", "8100");
|
|
let cli = CliOverrides {
|
|
port: Some(8200),
|
|
..Default::default()
|
|
};
|
|
let c = load(Some("c.toml"), &cli).unwrap();
|
|
assert_eq!(c.server.port, 8200);
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn auth_off_with_public_bind_is_rejected() {
|
|
Jail::expect_with(|jail| {
|
|
jail.set_env("SKYG_AUTH__ENABLED", "false");
|
|
jail.set_env("SKYG_SERVER__BIND", "0.0.0.0");
|
|
assert!(matches!(
|
|
load(None, &CliOverrides::default()),
|
|
Err(ConfigError::Invalid(_))
|
|
));
|
|
jail.set_env("SKYG_SERVER__BIND", "127.0.0.1");
|
|
assert!(load(None, &CliOverrides::default()).is_ok());
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn missing_explicit_file_is_error() {
|
|
Jail::expect_with(|_| {
|
|
assert!(matches!(
|
|
load(Some("nope.toml"), &CliOverrides::default()),
|
|
Err(ConfigError::MissingFile(_))
|
|
));
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn tls_enabled_requires_both_paths() {
|
|
let mut c = Config::default();
|
|
assert!(!c.server.tls.enabled);
|
|
c.validate().unwrap();
|
|
c.server.tls.enabled = true;
|
|
assert!(c.validate().is_err());
|
|
c.server.tls.cert_file = "/c.pem".into();
|
|
assert!(c.validate().is_err());
|
|
c.server.tls.key_file = "/k.pem".into();
|
|
c.validate().unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn tls_disabled_ignores_paths_and_env_overrides() {
|
|
let mut c = Config::default();
|
|
c.server.tls.cert_file = "/nonexistent/c.pem".into();
|
|
c.server.tls.key_file = "/nonexistent/k.pem".into();
|
|
c.validate().unwrap();
|
|
Jail::expect_with(|jail| {
|
|
jail.set_env("SKYG_SERVER__TLS__ENABLED", "true");
|
|
jail.set_env("SKYG_SERVER__TLS__CERT_FILE", "/c.pem");
|
|
jail.set_env("SKYG_SERVER__TLS__KEY_FILE", "/k.pem");
|
|
let c = load(None, &CliOverrides::default()).unwrap();
|
|
assert!(c.server.tls.enabled);
|
|
assert_eq!(c.server.tls.cert_file, Path::new("/c.pem"));
|
|
assert!(c.to_toml_redacted().unwrap().contains("[server.tls]"));
|
|
Ok(())
|
|
});
|
|
}
|
|
|
|
#[test]
|
|
fn example_file_matches_defaults() {
|
|
let c: Config = toml::from_str(include_str!("../config.example.toml")).unwrap();
|
|
assert_eq!(c, Config::default());
|
|
}
|
|
|
|
#[test]
|
|
fn toml_roundtrip_and_redaction() {
|
|
let mut c = Config::default();
|
|
c.otel
|
|
.headers
|
|
.insert("authorization".into(), "secret".into());
|
|
let s = c.to_toml_redacted().unwrap();
|
|
assert!(!s.contains("secret"));
|
|
assert!(s.contains("port = 1984"));
|
|
}
|
|
}
|