// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! `control.toml`: where control keeps its state, the routes repository, the files it writes //! for edge and Caddy, and the deployment facts both compilers need. Written by the NixOS //! module; never holds a secret (secrets are credential *names* in `$CREDENTIALS_DIRECTORY`). use std::net::SocketAddr; use std::path::{Path, PathBuf}; use ianitor_core::compile::CompileOptions; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Config { /// The API listens here. Only loopback addresses are accepted. #[serde(default = "default_listen")] pub listen: SocketAddr, /// Extra `Host` header values the API accepts (besides the listen address, `localhost` /// and `127.0.0.1` on its port), e.g. the admin host edge forwards to control in phase 3. #[serde(default)] pub allowed_hosts: Vec, /// Tokens, share links, apply records, the apply journal. pub state_dir: PathBuf, /// Overrides `$CREDENTIALS_DIRECTORY` (dev mode and tests only). pub credentials_dir: Option, /// The `git` binary. #[serde(default = "default_git")] pub git: PathBuf, /// How long the health watch after an apply lasts. #[serde(default = "default_watch")] pub watch_secs: u64, /// How often watched hosts are probed during the watch. #[serde(default = "default_every")] pub watch_every_secs: u64, /// Extra time edge waits for a confirmation after the watch before it reverts by itself. #[serde(default = "default_margin")] pub trial_margin_secs: u64, /// How often control reads health from edge for the overview. #[serde(default = "default_poll")] pub health_poll_secs: u64, pub routes: Routes, pub edge: Edge, pub caddy: Caddy, /// Deployment facts for both compilers. pub compile: Compile, /// Different facts for the Caddy output (only tests need this: both engines side by side). pub compile_caddy: Option, /// The Domi CA; without it `tls = "domi"` certificates are expected in `cert_dir` already /// and the certificate screens say the CA is not set up. #[serde(default)] pub pki: Option, /// The web UI behind edge (sign-in through Authelia, see docs/api.md). #[serde(default)] pub ui: Option, /// Switching between Pingora and the Caddy fallback at runtime. #[serde(default)] pub engine: Option, /// Branch previews for Fabrica (`POST /api/v1/previews`); off without it. #[serde(default)] pub previews: Option, } /// `[previews]`: where branch previews live and what they may point at. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PreviewsConfig { /// Previews are `--.`; a wildcard DNS record points here. pub domain: String, /// `domi` (the Domi CA, internal) or `letsencrypt` (public; one certificate per preview). #[serde(default = "default_preview_tls")] pub tls: String, /// `none` (anyone with the address) or `forward-auth` (behind the site's sign-in). #[serde(default = "default_preview_auth")] pub auth: String, /// Where previews may send traffic: `10.0.0.0/8`, `127.0.0.1:20000-29999`, `app.internal`, /// `*.svc.internal:8080`. Nothing else is accepted; control's own port and Caddy's admin /// port never are. Empty: every preview is refused. #[serde(default)] pub upstreams: Vec, #[serde(default = "default_preview_ttl")] pub default_ttl_secs: u64, #[serde(default = "default_preview_min_ttl")] pub min_ttl_secs: u64, #[serde(default = "default_preview_max_ttl")] pub max_ttl_secs: u64, #[serde(default = "default_preview_max")] pub max_previews: usize, /// How often expired previews are looked for. #[serde(default = "default_preview_sweep")] pub sweep_secs: u64, } fn default_preview_tls() -> String { "domi".into() } fn default_preview_auth() -> String { "none".into() } fn default_preview_ttl() -> u64 { 72 * 3600 } fn default_preview_min_ttl() -> u64 { 300 } fn default_preview_max_ttl() -> u64 { 30 * 86_400 } fn default_preview_max() -> usize { 100 } fn default_preview_sweep() -> u64 { 30 } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Routes { /// The routes repository (bare). Created with an empty `ianitor.toml` when missing. pub repo: PathBuf, #[serde(default = "default_branch")] pub branch: String, /// Where kept changes are pushed (a URL or a path); none means no push. pub remote: Option, /// Shown in the UI ("Last pushed to "). #[serde(default = "default_remote_name")] pub remote_name: String, /// User name for HTTPS pushes. #[serde(default = "default_push_user")] pub push_username: String, /// Credential (file name in `$CREDENTIALS_DIRECTORY`) holding the push password or token. pub push_credential: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Edge { /// The edge config file; only ever holds a config that passed its watch. pub config: PathBuf, /// The trial file edge loads during an apply (default `.trial`). pub trial: Option, /// Edge's admin socket; without it control applies without reload or health watch /// (dev mode without an edge). pub admin_socket: Option, /// The share-link revocation file edge reads. pub share_revocations: PathBuf, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Caddy { /// The Caddy JSON the caddy-fallback unit reads. pub config: PathBuf, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Compile { pub http_listen: SocketAddr, pub https_listen: SocketAddr, pub cert_dir: String, pub state_dir: String, pub access_log: String, pub caddy_credentials_dir: String, pub caddy_admin: Option, /// Caddy's admin API on a Unix socket: how control loads a change while Caddy serves. #[serde(default)] pub caddy_admin_socket: Option, /// Proxies in front whose X-Forwarded-For is believed (e.g. ["127.0.0.1"] beside Caddy). #[serde(default)] pub trusted_proxies: Vec, } impl Compile { pub fn options(&self) -> CompileOptions { use ianitor_core::compile::windows_path as w; CompileOptions { http_listen: self.http_listen, https_listen: self.https_listen, cert_dir: w(&self.cert_dir), state_dir: w(&self.state_dir), access_log: w(&self.access_log), caddy_credentials_dir: w(&self.caddy_credentials_dir), caddy_admin: self.caddy_admin, caddy_admin_socket: self.caddy_admin_socket.clone(), trusted_proxies: self.trusted_proxies.clone(), } } } fn default_listen() -> SocketAddr { SocketAddr::from(([127, 0, 0, 1], 7878)) } fn default_git() -> PathBuf { PathBuf::from("git") } fn default_watch() -> u64 { 60 } fn default_every() -> u64 { 5 } fn default_margin() -> u64 { 30 } fn default_poll() -> u64 { 2 } fn default_branch() -> String { "main".into() } fn default_remote_name() -> String { "Gitea".into() } fn default_push_user() -> String { "ianitor".into() } #[derive(Debug, thiserror::Error)] pub enum ConfigError { #[error("cannot read {path}: {source}")] Read { path: PathBuf, source: std::io::Error, }, #[error("{path} is not a valid control config: {message}")] Parse { path: PathBuf, message: String }, #[error("control config: {0}")] Invalid(String), } impl Config { pub fn load(path: &Path) -> Result { let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read { path: path.to_owned(), source, })?; let c: Config = toml::from_str(&text).map_err(|e| ConfigError::Parse { path: path.to_owned(), message: e.message().to_owned(), })?; c.check()?; Ok(c) } pub fn check(&self) -> Result<(), ConfigError> { if !self.listen.ip().is_loopback() { return Err(ConfigError::Invalid(format!( "listen = {} is not a loopback address; ianitor-control only listens on 127.0.0.1 or ::1", self.listen ))); } if !(1..=3600).contains(&self.watch_secs) { return Err(ConfigError::Invalid("watch_secs must be 1 to 3600".into())); } if !(1..=60).contains(&self.watch_every_secs) || !(1..=600).contains(&self.trial_margin_secs) { return Err(ConfigError::Invalid( "watch_every_secs must be 1 to 60 and trial_margin_secs 1 to 600".into(), )); } if self.routes.branch.is_empty() || !self .routes .branch .bytes() .all(|c| c.is_ascii_alphanumeric() || b"-_./".contains(&c)) || self.routes.branch.starts_with(['-', '.', '/']) || self.routes.branch.contains("..") { return Err(ConfigError::Invalid( "routes.branch is not a plain branch name".into(), )); } if let Some(r) = &self.routes.remote && (r.starts_with('-') || r.is_empty()) { return Err(ConfigError::Invalid("routes.remote is not usable".into())); } if let Some(c) = &self.routes.push_credential && !valid_credential_name(c) { return Err(ConfigError::Invalid( "routes.push_credential must be a plain credential name".into(), )); } // The keys at rest are only as strong as this; only test builds may lower it. if let Some(p) = &self.pki && p.kdf_iterations < MIN_KDF_ITERATIONS && !cfg!(feature = "test-hooks") { return Err(ConfigError::Invalid(format!( "pki.kdf_iterations must be at least {MIN_KDF_ITERATIONS}" ))); } if let Some(p) = &self.previews { crate::previews::check_config(p, self).map_err(ConfigError::Invalid)?; } if let Some(m) = empty_model() { for c in std::iter::once(&self.compile).chain(self.compile_caddy.as_ref()) { ianitor_core::compile::edge(&m, &c.options()) .map_err(|e| ConfigError::Invalid(e.to_string()))?; } } Ok(()) } pub fn trial_path(&self) -> PathBuf { self.edge .trial .clone() .unwrap_or_else(|| suffixed(&self.edge.config, ".trial")) } pub fn caddy_trial_path(&self) -> PathBuf { suffixed(&self.caddy.config, ".trial") } pub fn caddy_compile(&self) -> &Compile { self.compile_caddy.as_ref().unwrap_or(&self.compile) } pub fn credentials_dir(&self) -> Option { self.credentials_dir .clone() .or_else(|| std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from)) } /// Read a credential by name (trailing newline dropped). Never logged. pub fn credential(&self, name: &str) -> Option> { if !valid_credential_name(name) { return None; } let raw = std::fs::read(self.credentials_dir()?.join(name)).ok()?; let t = raw .strip_suffix(b"\r\n") .or_else(|| raw.strip_suffix(b"\n")) .unwrap_or(&raw); (!t.is_empty()).then(|| t.to_vec()) } } pub fn valid_credential_name(n: &str) -> bool { !n.is_empty() && n.len() <= 64 && n.bytes() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_' || c == b'-') } fn suffixed(p: &Path, suffix: &str) -> PathBuf { let mut name = p.file_name().unwrap_or_default().to_os_string(); name.push(suffix); p.with_file_name(name) } fn empty_model() -> Option { ianitor_core::load( &ianitor_core::SourceFile { name: "ianitor.toml", contents: "", }, &[], ) .ok() } /// The PBKDF2 floor for keys at rest (OWASP 2023 for PBKDF2-HMAC-SHA256). pub const MIN_KDF_ITERATIONS: u32 = 600_000; #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PkiConfig { /// The Domi root certificate (public; may be a Nix store path). The root key is never on /// the server. pub root_cert: PathBuf, /// Credential with the password that encrypts the intermediate and device keys at rest. #[serde(default = "default_pki_password")] pub password_credential: String, /// How requests are approved: `manual` (`ianitor-control pki approve ` on the /// server) until Custos can (docs/custos-ticket.md). #[serde(default = "default_approval")] pub approval: String, /// PBKDF2 iterations for the keys control encrypts (only tests lower it). #[serde(default = "default_kdf")] pub kdf_iterations: u32, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct UiConfig { /// The admin host edge serves the UI on (a host in the routes repository with /// `auth = "forward-auth"`, upstream this API, and the proof header rule). Added to /// `allowed_hosts`; used for device install links. pub hostname: Option, /// Credential holding the per-boot secret edge adds as `X-Ianitor-Proof` on the admin /// host. With it, a request carrying the proof is identified by its `Remote-User`. pub proof_credential: Option, /// The built web UI (served at `/`). pub static_dir: Option, /// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out". #[serde(default)] pub logout_url: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct EngineConfig { /// Which engine runs at boot: `pingora` or `caddy` (read by the engine-select unit). pub file: PathBuf, /// `systemctl` (through the polkit rule for exactly the two units) or `none`. #[serde(default = "default_units")] pub units: String, #[serde(default = "default_systemctl")] pub systemctl: PathBuf, #[serde(default = "default_edge_unit")] pub edge_unit: String, #[serde(default = "default_caddy_unit")] pub caddy_unit: String, } fn default_pki_password() -> String { "pki-password".into() } fn default_approval() -> String { "manual".into() } fn default_kdf() -> u32 { ianitor_core::pki::KEY_KDF_ITERATIONS } fn default_units() -> String { "systemctl".into() } fn default_systemctl() -> PathBuf { PathBuf::from("systemctl") } fn default_edge_unit() -> String { "ianitor-edge.service".into() } fn default_caddy_unit() -> String { "caddy-fallback.service".into() }