Files
ianitor/crates/control/src/config.rs
T

405 lines
14 KiB
Rust

// 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<String>,
/// Tokens, share links, apply records, the apply journal.
pub state_dir: PathBuf,
/// Overrides `$CREDENTIALS_DIRECTORY` (dev mode and tests only).
pub credentials_dir: Option<PathBuf>,
/// 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<Compile>,
/// 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<PkiConfig>,
/// The web UI behind edge (sign-in through Authelia, see docs/api.md).
#[serde(default)]
pub ui: Option<UiConfig>,
/// Switching between Pingora and the Caddy fallback at runtime.
#[serde(default)]
pub engine: Option<EngineConfig>,
}
#[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<String>,
/// Shown in the UI ("Last pushed to <name>").
#[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<String>,
}
#[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 `<config>.trial`).
pub trial: Option<PathBuf>,
/// Edge's admin socket; without it control applies without reload or health watch
/// (dev mode without an edge).
pub admin_socket: Option<PathBuf>,
/// 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<SocketAddr>,
/// Caddy's admin API on a Unix socket: how control loads a change while Caddy serves.
#[serde(default)]
pub caddy_admin_socket: Option<String>,
/// Proxies in front whose X-Forwarded-For is believed (e.g. ["127.0.0.1"] beside Caddy).
#[serde(default)]
pub trusted_proxies: Vec<std::net::IpAddr>,
/// The front proxy's Unix socket (beside Caddy): both engines serve the HTTPS hosts on it
/// and believe its X-Forwarded-For.
#[serde(default)]
pub proxy_socket: Option<String>,
}
impl Compile {
pub fn options(&self) -> CompileOptions {
CompileOptions {
http_listen: self.http_listen,
https_listen: self.https_listen,
cert_dir: self.cert_dir.clone(),
state_dir: self.state_dir.clone(),
access_log: self.access_log.clone(),
caddy_credentials_dir: self.caddy_credentials_dir.clone(),
caddy_admin: self.caddy_admin,
caddy_admin_socket: self.caddy_admin_socket.clone(),
trusted_proxies: self.trusted_proxies.clone(),
proxy_socket: self.proxy_socket.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<Config, ConfigError> {
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 let Some(s) = self.ui.as_ref().and_then(|u| u.socket.as_ref())
&& (!s.is_absolute() || s.as_os_str().len() > 100)
{
return Err(ConfigError::Invalid(
"ui.socket must be an absolute path of at most 100 characters".into(),
));
}
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(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<PathBuf> {
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<Vec<u8>> {
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::Model> {
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 <code>` 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<String>,
/// 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<String>,
/// The built web UI (served at `/`).
pub static_dir: Option<PathBuf>,
/// A Unix socket (mode 0660; its directory only for the ianitor group) on which control
/// also serves the API for the admin host (G14 option b). With it, the proof signs in only
/// on this socket; over the loopback port, which any local process can reach (or take while
/// control restarts), only API tokens work. The admin host's upstream is then
/// `unix:<this path>`.
#[serde(default)]
pub socket: Option<PathBuf>,
/// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out".
#[serde(default)]
pub logout_url: Option<String>,
}
#[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()
}