[control] Phase 2 control plane: routes repo via git, journaled apply with trial/watch/revert, undo and restore, push with retry, share links, API tokens, REST API with OpenAPI, --dev
This commit is contained in:
@@ -0,0 +1,282 @@
|
||||
// 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>,
|
||||
}
|
||||
|
||||
#[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>,
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 !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(),
|
||||
));
|
||||
}
|
||||
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()
|
||||
}
|
||||
Reference in New Issue
Block a user