diff --git a/Cargo.lock b/Cargo.lock index 09ac86f..4e5a097 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -219,6 +219,56 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + [[package]] name = "base64" version = "0.22.1" @@ -1006,13 +1056,22 @@ dependencies = [ name = "ianitor-control" version = "0.1.0" dependencies = [ + "axum", + "base64 0.22.1", + "bytes", + "http", "ianitor-core", "ianitor-edge", "ianitor-testkit", + "log", "ring", "rustls", + "serde", "serde_json", + "thiserror 2.0.21", "tokio", + "toml", + "utoipa", ] [[package]] @@ -1032,6 +1091,7 @@ dependencies = [ name = "ianitor-diff" version = "0.1.0" dependencies = [ + "ianitor-control", "ianitor-core", "ianitor-edge", "ianitor-testkit", @@ -1208,6 +1268,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", + "serde", + "serde_core", ] [[package]] @@ -1359,6 +1421,12 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "memchr" version = "2.8.3" @@ -1374,6 +1442,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -2327,6 +2401,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_spanned" version = "1.1.3" @@ -2336,6 +2421,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "serde_yaml" version = "0.9.34+deprecated" @@ -2504,6 +2601,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + [[package]] name = "synstructure" version = "0.13.2" @@ -2749,6 +2852,27 @@ version = "1.2.0+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + [[package]] name = "tower-service" version = "0.3.3" @@ -2859,6 +2983,29 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" +[[package]] +name = "utoipa" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bde15df68e80b16c7d16b9616e80770ad158988daa56a27dccd1e55558b0160" +dependencies = [ + "indexmap 2.14.2", + "serde", + "serde_json", + "utoipa-gen", +] + +[[package]] +name = "utoipa-gen" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba0b99ee52df3028635d93840c797102da61f8a7bb3cf751032455895b52ef8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "version_check" version = "0.9.5" diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 1b60032..bd59d3a 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -1,24 +1,39 @@ [package] name = "ianitor-control" -description = "Ianitor Domi control plane (API, routes repo, apply/rollback). Placeholder until phase 2." +description = "Ianitor Domi control plane: routes repo, apply with automatic rollback, share links, API tokens, REST API on loopback." version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true publish.workspace = true +[lib] +name = "ianitor_control" +path = "src/lib.rs" + [[bin]] name = "ianitor-control" path = "src/main.rs" -[lints] -workspace = true +[dependencies] +ianitor-core.workspace = true +axum = { version = "0.8.9", default-features = false, features = ["http1", "json", "query", "tokio", "matched-path"] } +utoipa = "5" +tokio.workspace = true +serde.workspace = true +serde_json.workspace = true +toml.workspace = true +thiserror.workspace = true +log.workspace = true +ring.workspace = true +base64.workspace = true +http.workspace = true +bytes.workspace = true [dev-dependencies] -ianitor-core.workspace = true -ianitor-edge.workspace = true ianitor-testkit.workspace = true -tokio.workspace = true -serde_json.workspace = true +ianitor-edge.workspace = true rustls.workspace = true -ring.workspace = true + +[lints] +workspace = true diff --git a/crates/control/src/api/handlers.rs b/crates/control/src/api/handlers.rs new file mode 100644 index 0000000..336207f --- /dev/null +++ b/crates/control/src/api/handlers.rs @@ -0,0 +1,1250 @@ +// 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/. + +//! The handlers, each annotated for the OpenAPI document. + +// An error answer is built once per failed request; boxing it buys nothing. +#![allow(clippy::result_large_err)] + +use std::sync::Arc; + +use axum::Extension; +use axum::extract::{Path, Query, State}; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use axum::response::{IntoResponse, Response}; +use serde::Deserialize; +use utoipa::{IntoParams, Modify, OpenApi, ToSchema}; + +use super::views::*; +use super::{Actor, ApiError, AppState, Body, Stored, fingerprint}; +use crate::engine::Change; +use crate::hostspec::{HeaderRuleSpec, HealthCheckSpec, HostSpec}; +use crate::messages::{self, Params, message}; +use crate::records::{FieldError, Reason, Step, WatchHost}; +use crate::shares::MintError; +use crate::util::{now, rfc3339, sha256_hex}; + +type Shared = State>; + +fn json(status: StatusCode, v: &T) -> Response { + (status, axum::Json(v)).into_response() +} + +fn check_hostname_param(h: &str) -> Result<(), ApiError> { + if h.is_empty() + || h.len() > 253 + || !h + .bytes() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'.' || c == b'-') + { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "host.not_found", + messages::params([("hostname", h.chars().take(253).collect())]), + )); + } + Ok(()) +} + +fn idem_key(headers: &HeaderMap) -> Result, ApiError> { + match headers.get("idempotency-key") { + None => Ok(None), + Some(v) => { + let s = v.to_str().unwrap_or(""); + if s.is_empty() || s.len() > 128 || !s.bytes().all(|c| c.is_ascii_graphic()) { + return Err(ApiError::new( + StatusCode::BAD_REQUEST, + "request.body", + messages::params([( + "problem", + "the Idempotency-Key header must be 1 to 128 visible characters.".into(), + )]), + )); + } + Ok(Some(s.to_owned())) + } + } +} + +/// Queue a change, answering 202 with the apply; a retried request with the same +/// Idempotency-Key gets the same apply back instead of a second one. +fn submit( + st: &AppState, + headers: &HeaderMap, + fp: String, + actor: &Actor, + change: Change, + base_rev: Option, +) -> Result { + let key = idem_key(headers)?.map(|k| format!("{}:{k}", actor.token_id)); + if let Some(k) = &key + && let Some(stored) = st.idem_get(k, &fp)? + { + return Ok(replay(st, stored)); + } + let rec = st.ctl.submit(change, base_rev, &actor.name)?; + if let Some(k) = &key { + st.idem_put(k, &fp, Stored::Apply(rec.id.clone())); + } + Ok(json( + StatusCode::ACCEPTED, + &ApplyAccepted { + apply: apply_view(&st.ctl, &rec), + }, + )) +} + +fn replay(st: &AppState, s: Stored) -> Response { + match s { + Stored::Apply(id) => match st.ctl.record(&id) { + Some(r) => json( + StatusCode::ACCEPTED, + &ApplyAccepted { + apply: apply_view(&st.ctl, &r), + }, + ), + None => ApiError::internal("the remembered apply is gone").into_response(), + }, + Stored::Json(status, v) => json(StatusCode::from_u16(status).unwrap_or(StatusCode::OK), &v), + } +} + +// ---------------------------------------------------------------- overview and hosts + +/// Everything the main screen shows, in one call. Answers 304 to a matching If-None-Match. +#[utoipa::path(get, path = "/api/v1/overview", tag = "overview", + responses((status = 200, body = Overview), (status = 304, description = "Unchanged since the ETag"), (status = 401, body = ErrorEnvelope)), + security(("bearer" = [])))] +pub async fn overview(State(st): Shared, headers: HeaderMap) -> Result { + let c = &st.ctl; + let (status, error, since) = { + let h = c + .health + .lock() + .map_err(|_| ApiError::internal("health cache"))?; + (h.status.clone(), h.error.clone(), h.since.clone()) + }; + let head = c + .repo + .head_required() + .map_err(|e| ApiError::internal(e.to_string()))?; + let tree = c.repo.tree(&head).ok(); + let hosts = tree + .as_ref() + .map(|t| host_rows(c, t, status.as_ref(), &since)) + .unwrap_or_default(); + let mut counts = Counts { + hosts: hosts.len(), + ..Counts::default() + }; + for h in &hosts { + match h.health.state.as_str() { + "healthy" => counts.healthy += 1, + "degraded" => counts.degraded += 1, + "down" => counts.down += 1, + _ => counts.unknown += 1, + } + } + let recs = c.records(); + let last_apply = recs.last().map(|r| apply_view(c, r)); + let active = recs + .iter() + .rev() + .find(|r| r.is_running()) + .map(|r| ActiveApply { + id: r.id.clone(), + state: r.state.clone(), + summary: r.summary.clone(), + seconds_left: r.watch.as_ref().map(|w| w.ends.saturating_sub(now())), + queued: c.queued_count(), + }); + let site = tree + .as_ref() + .and_then(|t| t.model().ok()) + .map(|m| SiteView { + forward_auth_configured: m.site().forward_auth.is_some(), + acme_configured: true, + secrets: m.site().secrets.iter().map(|s| s.to_string()).collect(), + watch_seconds: c.cfg.watch_secs, + share_links_available: c.share_key.is_some(), + }); + let ov = Overview { + counts, + hosts, + engine: EngineView { + running: "pingora".into(), + state: if status.is_some() && error.is_none() { + "running" + } else { + "stopped" + } + .into(), + since: status.as_ref().map(|s| rfc3339(s.started_at)), + fallback_ready: None, + }, + last_apply, + undo: undo_view(c), + active_apply: active, + repo: Some(repo_view(c, &head)), + intermediate: None, + site, + paused: c.paused().map(|p| Blocked { + code: "control.paused".into(), + message: message("control.paused", &messages::params([("reason", p.message)])), + }), + health_error: error.filter(|_| c.edge.attached()).map(|_| Blocked { + code: "health.unavailable".into(), + message: message( + "health.unavailable", + &messages::params([("engine", "Pingora".into())]), + ), + }), + rev: Some(head), + }; + let body = serde_json::to_vec(&ov).map_err(|e| ApiError::internal(e.to_string()))?; + let etag = format!("\"{}\"", &sha256_hex(&body)[..32]); + let mut resp = if headers + .get(header::IF_NONE_MATCH) + .is_some_and(|v| v.as_bytes() == etag.as_bytes()) + { + StatusCode::NOT_MODIFIED.into_response() + } else { + json(StatusCode::OK, &ov) + }; + if let Ok(v) = HeaderValue::from_str(&etag) { + resp.headers_mut().insert(header::ETAG, v); + } + Ok(resp) +} + +fn repo_view(c: &crate::engine::Control, head: &str) -> RepoView { + let p = c.push_state(); + RepoView { + name: c.cfg.routes.remote_name.clone(), + last_push_at: p.last_push_at.map(rfc3339), + unpushed: if c.cfg.routes.remote.is_some() { + c.repo.count_between(p.pushed.as_deref(), head).unwrap_or(0) + } else { + 0 + }, + push_error_code: p.error_code, + remote_configured: c.cfg.routes.remote.is_some(), + } +} + +/// Every host with its health. +#[utoipa::path(get, path = "/api/v1/hosts", tag = "hosts", + responses((status = 200, body = HostList), (status = 401, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn list_hosts(State(st): Shared) -> Result { + let c = &st.ctl; + let head = c + .repo + .head_required() + .map_err(|e| ApiError::internal(e.to_string()))?; + let tree = c + .repo + .tree(&head) + .map_err(|e| ApiError::internal(e.to_string()))?; + let (status, since) = { + let h = c + .health + .lock() + .map_err(|_| ApiError::internal("health cache"))?; + (h.status.clone(), h.since.clone()) + }; + Ok(json( + StatusCode::OK, + &HostList { + hosts: host_rows(c, &tree, status.as_ref(), &since), + rev: head, + }, + )) +} + +/// One host: every field, its file, its health, and `rev` to send back as `base_rev`. +#[utoipa::path(get, path = "/api/v1/hosts/{hostname}", tag = "hosts", + params(("hostname" = String, Path)), + responses((status = 200, body = HostDetail), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn get_host( + State(st): Shared, + Path(hostname): Path, +) -> Result { + check_hostname_param(&hostname)?; + let c = &st.ctl; + let head = c + .repo + .head_required() + .map_err(|e| ApiError::internal(e.to_string()))?; + let tree = c + .repo + .tree(&head) + .map_err(|e| ApiError::internal(e.to_string()))?; + let Some(text) = tree.host(&hostname) else { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "host.not_found", + messages::params([("hostname", hostname)]), + )); + }; + let spec = HostSpec::from_toml(text).map_err(|e| { + let mut err = ApiError::new( + StatusCode::CONFLICT, + "repo.unreadable", + messages::params([("file", ianitor_core::routes::host_path(&hostname))]), + ); + err.body.detail = Some(e); + err + })?; + let (status, since) = { + let h = c + .health + .lock() + .map_err(|_| ApiError::internal("health cache"))?; + (h.status.clone(), h.since.clone()) + }; + let hs = status + .as_ref() + .and_then(|s| s.hosts.iter().find(|x| x.hostname == hostname)); + Ok(json( + StatusCode::OK, + &HostDetail { + health: health_view(hs, Some(&spec), since.get(&hostname).copied()), + certificate: cert_view(hs, Some(&spec)), + host: spec, + rev: head, + toml: text.to_owned(), + }, + )) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct HostWrite { + pub host: HostSpec, + /// The routes commit the form was loaded from (`rev`). + pub base_rev: Option, +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct HostPatch { + pub share_links: bool, + pub base_rev: Option, +} + +#[derive(Debug, Deserialize, IntoParams)] +#[serde(deny_unknown_fields)] +pub struct ValidateQuery { + /// `create` (the hostname must be new) or `edit`. + pub mode: Option, +} + +#[derive(Debug, Deserialize, IntoParams)] +#[serde(deny_unknown_fields)] +pub struct BaseRevQuery { + pub base_rev: Option, +} + +/// Check a host body without applying it (field blur in the form). +#[utoipa::path(post, path = "/api/v1/hosts/validate", tag = "hosts", params(ValidateQuery), request_body = HostSpec, + responses((status = 200, body = Done), (status = 422, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn validate_host( + State(st): Shared, + Query(q): Query, + body: Body, +) -> Result { + let create = match q.mode.as_deref() { + None | Some("create") => true, + Some("edit") => false, + Some(_) => { + return Err(ApiError::new( + StatusCode::BAD_REQUEST, + "request.body", + messages::params([("problem", "mode must be create or edit.".into())]), + )); + } + }; + st.ctl.validate(&body.value, create)?; + Ok(json( + StatusCode::OK, + &Done { + message: "This host can be applied.".into(), + }, + )) +} + +/// Add a host. Answers 202 with the apply; poll `GET /applies/{id}`. +#[utoipa::path(post, path = "/api/v1/hosts", tag = "hosts", request_body = HostWrite, + params(("Idempotency-Key" = Option, Header, description = "One per click; a retry with the same key returns the same apply")), + responses((status = 202, body = ApplyAccepted), (status = 409, body = ErrorEnvelope), (status = 422, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn create_host( + State(st): Shared, + Extension(actor): Extension, + headers: HeaderMap, + body: Body, +) -> Result { + let fp = fingerprint("POST", "/api/v1/hosts", &body.raw); + let b = body.value; + submit( + &st, + &headers, + fp, + &actor, + Change::Put { + spec: b.host, + create: true, + }, + b.base_rev, + ) +} + +/// Change a host (all fields). The hostname in the body must be the one in the path. +#[utoipa::path(put, path = "/api/v1/hosts/{hostname}", tag = "hosts", request_body = HostWrite, + params(("hostname" = String, Path), ("Idempotency-Key" = Option, Header)), + responses((status = 202, body = ApplyAccepted), (status = 404, body = ErrorEnvelope), (status = 409, body = ErrorEnvelope), (status = 422, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn update_host( + State(st): Shared, + Extension(actor): Extension, + Path(hostname): Path, + headers: HeaderMap, + body: Body, +) -> Result { + check_hostname_param(&hostname)?; + let fp = fingerprint("PUT", &format!("/api/v1/hosts/{hostname}"), &body.raw); + let b = body.value; + if b.host.hostname != hostname { + let mut e = ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "host.hostname.mismatch", + messages::params([ + ("hostname", b.host.hostname.clone()), + ("path_hostname", hostname), + ]), + ); + e.body.field = Some("hostname".into()); + return Err(e); + } + submit( + &st, + &headers, + fp, + &actor, + Change::Put { + spec: b.host, + create: false, + }, + b.base_rev, + ) +} + +/// Turn share links on or off for a host (an apply like any other). +#[utoipa::path(patch, path = "/api/v1/hosts/{hostname}", tag = "hosts", request_body = HostPatch, + params(("hostname" = String, Path), ("Idempotency-Key" = Option, Header)), + responses((status = 202, body = ApplyAccepted), (status = 404, body = ErrorEnvelope), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn patch_host( + State(st): Shared, + Extension(actor): Extension, + Path(hostname): Path, + headers: HeaderMap, + body: Body, +) -> Result { + check_hostname_param(&hostname)?; + let fp = fingerprint("PATCH", &format!("/api/v1/hosts/{hostname}"), &body.raw); + let b = body.value; + submit( + &st, + &headers, + fp, + &actor, + Change::ShareLinks { + hostname, + on: b.share_links, + }, + b.base_rev, + ) +} + +/// Remove a host. No confirmation: Undo brings it back in one click. +#[utoipa::path(delete, path = "/api/v1/hosts/{hostname}", tag = "hosts", + params(("hostname" = String, Path), BaseRevQuery, ("Idempotency-Key" = Option, Header)), + responses((status = 202, body = ApplyAccepted), (status = 404, body = ErrorEnvelope), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn delete_host( + State(st): Shared, + Extension(actor): Extension, + Path(hostname): Path, + Query(q): Query, + headers: HeaderMap, +) -> Result { + check_hostname_param(&hostname)?; + let fp = fingerprint( + "DELETE", + &format!("/api/v1/hosts/{hostname}"), + q.base_rev.as_deref().unwrap_or("").as_bytes(), + ); + submit( + &st, + &headers, + fp, + &actor, + Change::Delete { hostname }, + q.base_rev, + ) +} + +/// Ask edge to try Let's Encrypt again now for this host. +#[utoipa::path(post, path = "/api/v1/hosts/{hostname}/certificate/retry", tag = "hosts", + params(("hostname" = String, Path)), + responses((status = 200, body = Done), (status = 503, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn retry_certificate( + State(st): Shared, + Path(hostname): Path, +) -> Result { + check_hostname_param(&hostname)?; + st.ctl.edge.acme_retry().await.map_err(|e| { + let mut err = ApiError::new( + StatusCode::SERVICE_UNAVAILABLE, + "apply.failed.edge_unreachable", + Params::new(), + ); + err.body.detail = Some(e.to_string()); + err + })?; + Ok(json( + StatusCode::OK, + &Done { + message: "Trying again now.".into(), + }, + )) +} + +// ---------------------------------------------------------------- applies, history, undo, restore + +#[derive(Debug, Deserialize, IntoParams)] +#[serde(deny_unknown_fields)] +pub struct ListQuery { + pub limit: Option, + /// A change id: entries older than it. + pub before: Option, + /// Only changes touching this host. + pub host: Option, +} + +#[derive(Debug, serde::Serialize, ToSchema)] +pub struct ApplyList { + pub items: Vec, +} + +/// Recent applies, newest first. +#[utoipa::path(get, path = "/api/v1/applies", tag = "applies", params(ListQuery), + responses((status = 200, body = ApplyList)), security(("bearer" = [])))] +pub async fn list_applies( + State(st): Shared, + Query(q): Query, +) -> Result { + let limit = q.limit.unwrap_or(20).clamp(1, 200); + let items = st + .ctl + .records() + .iter() + .rev() + .take(limit) + .map(|r| apply_view(&st.ctl, r)) + .collect(); + Ok(json(StatusCode::OK, &ApplyList { items })) +} + +/// One apply, with its steps and watch progress. Poll every second while it runs. +#[utoipa::path(get, path = "/api/v1/applies/{id}", tag = "applies", params(("id" = String, Path)), + responses((status = 200, body = ApplyView), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn get_apply(State(st): Shared, Path(id): Path) -> Result { + let r = st + .ctl + .record(&id) + .ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "change.not_found", Params::new()))?; + Ok(json(StatusCode::OK, &apply_view(&st.ctl, &r))) +} + +/// Cancel an apply that is still queued. +#[utoipa::path(delete, path = "/api/v1/applies/{id}", tag = "applies", params(("id" = String, Path)), + responses((status = 204), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn cancel_apply(State(st): Shared, Path(id): Path) -> Result { + if st.ctl.record(&id).is_none() { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "change.not_found", + Params::new(), + )); + } + if st.ctl.cancel(&id) { + Ok(StatusCode::NO_CONTENT.into_response()) + } else { + let mut e = ApiError::new(StatusCode::CONFLICT, "request.method", Params::new()); + e.body.message = "This change is not waiting any more, so it cannot be cancelled.".into(); + Err(e) + } +} + +/// One entry per user action, newest first. A reverted attempt is one entry. +#[utoipa::path(get, path = "/api/v1/history", tag = "history", params(ListQuery), + responses((status = 200, body = History)), security(("bearer" = [])))] +pub async fn history(State(st): Shared, Query(q): Query) -> Result { + let limit = q.limit.unwrap_or(50).clamp(1, 200); + let recs = st.ctl.records(); + let mut it: Box> = + Box::new(recs.iter().rev()); + if let Some(b) = &q.before { + it = Box::new(it.skip_while(move |r| &r.id != b).skip(1)); + } + let filtered: Vec = it + .filter(|r| q.host.as_ref().is_none_or(|h| r.hosts.contains(h))) + .take(limit + 1) + .map(history_row) + .collect(); + let next = (filtered.len() > limit).then(|| filtered[limit - 1].change_id.clone()); + let entries = filtered.into_iter().take(limit).collect(); + Ok(json( + StatusCode::OK, + &History { + entries, + next_before: next, + }, + )) +} + +/// One change in full, including what was tried (`attempted_host`). +#[utoipa::path(get, path = "/api/v1/history/{change_id}", tag = "history", params(("change_id" = String, Path)), + responses((status = 200, body = ApplyView), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn history_entry( + State(st): Shared, + Path(change_id): Path, +) -> Result { + get_apply(State(st), Path(change_id)).await +} + +/// What restoring this change's version would change now. +#[utoipa::path(get, path = "/api/v1/history/{change_id}/restore-preview", tag = "history", params(("change_id" = String, Path)), + responses((status = 200, body = RestorePreview), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn restore_preview( + State(st): Shared, + Path(change_id): Path, +) -> Result { + let c = &st.ctl; + let r = c + .record(&change_id) + .ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "change.not_found", Params::new()))?; + let head = c + .repo + .head_required() + .map_err(|e| ApiError::internal(e.to_string()))?; + let current = c + .repo + .tree(&head) + .map_err(|e| ApiError::internal(e.to_string()))?; + let Some(commit) = r.commit.clone().filter(|_| r.state == "kept") else { + return Ok(json( + StatusCode::OK, + &RestorePreview { + restorable: false, + same_as_current: false, + changes: Vec::new(), + blocked: Some(Blocked { + code: "restore.not_kept".into(), + message: message("restore.not_kept", &Params::new()), + }), + }, + )); + }; + let then = c + .repo + .tree(&commit) + .map_err(|e| ApiError::internal(e.to_string()))?; + let mut names: std::collections::BTreeSet = current.hostnames().into_iter().collect(); + names.extend(then.hostnames()); + let mut changes = Vec::new(); + for h in names { + let (a, b) = (current.host(&h), then.host(&h)); + if a == b { + continue; + } + let pa = a.and_then(|t| HostSpec::from_toml(t).ok()); + let pb = b.and_then(|t| HostSpec::from_toml(t).ok()); + let (effect, fields) = match (&pa, &pb) { + (None, Some(_)) => ("added", Vec::new()), + (Some(_), None) => ("removed", Vec::new()), + (Some(x), Some(y)) => ( + "changed", + x.diff(y) + .into_iter() + .map(|(field, from, to)| FieldChange { field, from, to }) + .collect(), + ), + (None, None) => continue, + }; + changes.push(HostChange { + hostname: h, + effect: effect.into(), + fields, + }); + } + let same = *then == *current; + Ok(json( + StatusCode::OK, + &RestorePreview { + restorable: !same, + same_as_current: same, + changes, + blocked: same.then(|| Blocked { + code: "restore.same".into(), + message: message("restore.same", &Params::new()), + }), + }, + )) +} + +/// What Undo would undo right now (also in the overview). +#[utoipa::path(get, path = "/api/v1/undo", tag = "history", + responses((status = 200, body = UndoView)), security(("bearer" = [])))] +pub async fn get_undo(State(st): Shared) -> Result { + Ok(json(StatusCode::OK, &undo_view(&st.ctl))) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct UndoBody { + /// The change Undo named (`undo.target.change_id`); refused if it is no longer the latest kept change. + pub target_change_id: String, +} + +/// Undo the latest kept change, through the same apply path. Undo after an Undo is a redo. +#[utoipa::path(post, path = "/api/v1/undo", tag = "history", request_body = UndoBody, + params(("Idempotency-Key" = Option, Header)), + responses((status = 202, body = ApplyAccepted), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn undo( + State(st): Shared, + Extension(actor): Extension, + headers: HeaderMap, + body: Body, +) -> Result { + let fp = fingerprint("POST", "/api/v1/undo", &body.raw); + submit( + &st, + &headers, + fp, + &actor, + Change::Undo { + target: body.value.target_change_id, + }, + None, + ) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct RestoreBody { + pub change_id: String, + pub base_rev: Option, +} + +/// Apply the routes as they were after a kept change, as a new change. +#[utoipa::path(post, path = "/api/v1/restore", tag = "history", request_body = RestoreBody, + params(("Idempotency-Key" = Option, Header)), + responses((status = 202, body = ApplyAccepted), (status = 404, body = ErrorEnvelope), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn restore( + State(st): Shared, + Extension(actor): Extension, + headers: HeaderMap, + body: Body, +) -> Result { + let fp = fingerprint("POST", "/api/v1/restore", &body.raw); + let b = body.value; + submit( + &st, + &headers, + fp, + &actor, + Change::Restore { + change_id: b.change_id, + }, + b.base_rev, + ) +} + +/// Push to the remote now instead of waiting for the next retry. +#[utoipa::path(post, path = "/api/v1/repo/push", tag = "repo", + responses((status = 200, body = RepoView), (status = 409, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn push_now(State(st): Shared) -> Result { + let c = &st.ctl; + let Some(remote) = c.cfg.routes.remote.clone() else { + return Err(ApiError::new( + StatusCode::CONFLICT, + "repo.no_remote", + Params::new(), + )); + }; + c.push_once(&remote).await; + let head = c + .repo + .head_required() + .map_err(|e| ApiError::internal(e.to_string()))?; + Ok(json(StatusCode::OK, &repo_view(c, &head))) +} + +/// Settings the UI shows (read-only in v1). +#[utoipa::path(get, path = "/api/v1/settings", tag = "settings", + responses((status = 200, body = Settings)), security(("bearer" = [])))] +pub async fn settings(State(st): Shared) -> Result { + let head = st + .ctl + .repo + .head_required() + .map_err(|e| ApiError::internal(e.to_string()))?; + Ok(json( + StatusCode::OK, + &Settings { + repo: repo_view(&st.ctl, &head), + watch_seconds: st.ctl.cfg.watch_secs, + }, + )) +} + +// ---------------------------------------------------------------- tokens + +/// API tokens, without values or hashes. +#[utoipa::path(get, path = "/api/v1/tokens", tag = "tokens", + responses((status = 200, body = TokenList)), security(("bearer" = [])))] +pub async fn list_tokens(State(st): Shared) -> Result { + let items = st.ctl.tokens.list().map_err(ApiError::internal)?; + Ok(json( + StatusCode::OK, + &TokenList { + items: items.iter().map(TokenView::from).collect(), + }, + )) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct TokenCreate { + pub name: Option, + /// Days until it expires (default 365); `null` with `never: true` for no expiry. + pub expires_in_days: Option, + #[serde(default)] + pub never_expires: bool, +} + +/// Make a token. Its value is in this response only. +#[utoipa::path(post, path = "/api/v1/tokens", tag = "tokens", request_body = TokenCreate, + responses((status = 201, body = CreatedToken), (status = 422, body = ErrorEnvelope), (status = 429, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn create_token( + State(st): Shared, + Extension(actor): Extension, + body: Body, +) -> Result { + st.limit(&format!("token-create:{}", actor.token_id), 10, 3600) + .map_err(|s| { + ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s) + })?; + let b = body.value; + let expires = if b.never_expires { + None + } else { + let days = b.expires_in_days.unwrap_or(365); + if !(1..=3650).contains(&days) { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "token.expiry", + Params::new(), + )); + } + Some(now() + days * 86_400) + }; + let name = b + .name + .unwrap_or_else(|| format!("Token {}", ianitor_core::time::long_date(now()))); + let (rec, value) = st.ctl.tokens.create(&name, expires).map_err(|e| { + if e == "token.name" { + let mut err = ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "token.name", + Params::new(), + ); + err.body.field = Some("name".into()); + err + } else { + ApiError::internal(e) + } + })?; + log::info!(target: "ianitor::tokens", "token {} ({}) created by token {}", rec.id, rec.name, actor.token_id); + Ok(json( + StatusCode::CREATED, + &CreatedToken { + id: rec.id, + name: rec.name, + token: value, + expires_at: rec.expires_at.map(rfc3339), + }, + )) +} + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct TokenRename { + pub name: String, +} + +/// Rename a token. +#[utoipa::path(patch, path = "/api/v1/tokens/{id}", tag = "tokens", request_body = TokenRename, params(("id" = String, Path)), + responses((status = 200, body = TokenView), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn rename_token( + State(st): Shared, + Path(id): Path, + body: Body, +) -> Result { + match st.ctl.tokens.rename(&id, &body.value.name) { + Ok(Some(r)) => Ok(json(StatusCode::OK, &TokenView::from(&r))), + Ok(None) => Err(ApiError::new( + StatusCode::NOT_FOUND, + "token.not_found", + Params::new(), + )), + Err(e) if e == "token.name" => Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "token.name", + Params::new(), + )), + Err(e) => Err(ApiError::internal(e)), + } +} + +/// Revoke a token. Anything using it stops working now. +#[utoipa::path(delete, path = "/api/v1/tokens/{id}", tag = "tokens", params(("id" = String, Path)), + responses((status = 204), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn revoke_token( + State(st): Shared, + Extension(actor): Extension, + Path(id): Path, +) -> Result { + match st.ctl.tokens.revoke(&id) { + Ok(Some(r)) => { + log::info!(target: "ianitor::tokens", "token {} revoked by token {}", r.id, actor.token_id); + Ok(StatusCode::NO_CONTENT.into_response()) + } + Ok(None) => Err(ApiError::new( + StatusCode::NOT_FOUND, + "token.not_found", + Params::new(), + )), + Err(e) => Err(ApiError::internal(e)), + } +} + +// ---------------------------------------------------------------- share links + +#[derive(Debug, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct MintBody { + #[serde(default = "root")] + pub path_prefix: String, + /// 1 hour to 90 days; default 7 days. + #[serde(default = "week")] + pub expires_in_s: u64, + /// At least 8 characters; never returned. + pub password: Option, + /// A link of this host to stop at the same time. + pub replaces: Option, +} + +fn root() -> String { + "/".into() +} +fn week() -> u64 { + 7 * 86_400 +} + +/// Make a share link for a host with share links on. The URL holds the token and is shown once. +#[utoipa::path(post, path = "/api/v1/hosts/{hostname}/share-links", tag = "share-links", request_body = MintBody, + params(("hostname" = String, Path), ("Idempotency-Key" = Option, Header)), + responses((status = 201, body = MintedLink), (status = 409, body = ErrorEnvelope), (status = 422, body = ErrorEnvelope), (status = 503, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn mint_share_link( + State(st): Shared, + Extension(actor): Extension, + Path(hostname): Path, + headers: HeaderMap, + body: Body, +) -> Result { + check_hostname_param(&hostname)?; + let fp = fingerprint( + "POST", + &format!("/api/v1/hosts/{hostname}/share-links"), + &body.raw, + ); + let key = idem_key(&headers)?.map(|k| format!("{}:{k}", actor.token_id)); + if let Some(k) = &key + && let Some(s) = st.idem_get(k, &fp)? + { + return Ok(replay(&st, s)); + } + st.limit(&format!("share-mint:{}", actor.token_id), 30, 60) + .map_err(|s| { + ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s) + })?; + let c = &st.ctl; + let (_, _, model) = c.head_model()?; + let Some(host) = model + .hosts() + .iter() + .find(|h| h.hostname.as_str() == hostname) + else { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "host.not_found", + messages::params([("hostname", hostname)]), + )); + }; + if !host.share_links { + return Err(ApiError::new( + StatusCode::CONFLICT, + "share.disabled", + messages::params([("hostname", hostname)]), + )); + } + let Some(share_key) = &c.share_key else { + return Err(ApiError::new( + StatusCode::SERVICE_UNAVAILABLE, + "share.unavailable", + Params::new(), + )); + }; + let b = body.value; + let field_err = |code: &str, field: &str| { + let mut e = ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + code, + messages::params([("hostname", hostname.clone())]), + ); + e.body.field = Some(field.into()); + e + }; + let minted = c + .shares + .mint( + share_key, + &hostname, + &b.path_prefix, + b.expires_in_s, + b.password.as_deref(), + b.replaces.as_deref(), + &actor.name, + ) + .map_err(|e| match e { + MintError::Prefix => field_err("share.prefix", "path_prefix"), + MintError::Expiry => field_err("share.expiry", "expires_in_s"), + MintError::PasswordShort => field_err("share.password_short", "password"), + MintError::PasswordLong => field_err("share.password_long", "password"), + MintError::Replaces => field_err("share.replaces", "replaces"), + MintError::Store(s) => ApiError::internal(s), + })?; + if b.replaces.is_some() { + c.revocations_changed().await; + } + let port = c.cfg.compile.https_listen.port(); + let authority = if port == 443 { + hostname.clone() + } else { + format!("{hostname}:{port}") + }; + let url = format!( + "https://{authority}{}?{}={}", + minted.record.path_prefix, + ianitor_core::share::QUERY_PARAM, + minted.token + ); + log::info!(target: "ianitor::share", "share link {} for {hostname} made by token {}", minted.record.id, actor.token_id); + let out = MintedLink { + id: minted.record.id, + url, + expires_at: rfc3339(minted.record.expires_at), + path_prefix: minted.record.path_prefix, + has_password: minted.record.has_password, + warning: (host.auth == ianitor_core::AuthMode::None).then(|| Blocked { + code: "host.share.no_signin".into(), + message: message( + "host.share.no_signin", + &messages::params([("hostname", hostname.clone())]), + ), + }), + }; + let v = serde_json::to_value(&out).map_err(|e| ApiError::internal(e.to_string()))?; + if let Some(k) = &key { + st.idem_put(k, &fp, Stored::Json(201, v.clone())); + } + Ok(json(StatusCode::CREATED, &v)) +} + +/// Every share link, newest first (without tokens). +#[utoipa::path(get, path = "/api/v1/share-links", tag = "share-links", + responses((status = 200, body = ShareLinkList)), security(("bearer" = [])))] +pub async fn list_share_links(State(st): Shared) -> Result { + let f = st.ctl.shares.load().map_err(ApiError::internal)?; + let t = now(); + let items = f + .links + .iter() + .rev() + .map(|l| ShareLinkView { + id: l.id.clone(), + hostname: l.hostname.clone(), + path_prefix: l.path_prefix.clone(), + created_at: rfc3339(l.created_at), + expires_at: rfc3339(l.expires_at), + has_password: l.has_password, + state: l.state(f.epoch, t).into(), + }) + .collect(); + Ok(json( + StatusCode::OK, + &ShareLinkList { + items, + epoch: f.epoch, + }, + )) +} + +/// Stop one link. Edge refuses it within seconds. +#[utoipa::path(delete, path = "/api/v1/share-links/{id}", tag = "share-links", params(("id" = String, Path)), + responses((status = 204), (status = 404, body = ErrorEnvelope)), security(("bearer" = [])))] +pub async fn stop_share_link( + State(st): Shared, + Path(id): Path, +) -> Result { + match st.ctl.shares.stop(&id).map_err(ApiError::internal)? { + Some(_) => { + st.ctl.revocations_changed().await; + Ok(StatusCode::NO_CONTENT.into_response()) + } + None => Err(ApiError::new( + StatusCode::NOT_FOUND, + "share.not_found", + Params::new(), + )), + } +} + +/// Stop every share link made so far. New ones work as usual. +#[utoipa::path(post, path = "/api/v1/share-links/stop-all", tag = "share-links", + responses((status = 200, body = StoppedAll)), security(("bearer" = [])))] +pub async fn stop_all_share_links(State(st): Shared) -> Result { + let epoch = st.ctl.shares.stop_all().map_err(ApiError::internal)?; + st.ctl.revocations_changed().await; + Ok(json( + StatusCode::OK, + &StoppedAll { + epoch, + message: message("share.stopped_all", &Params::new()), + }, + )) +} + +// ---------------------------------------------------------------- health, openapi + +/// Edge and control state, for scripts and checks. +#[utoipa::path(get, path = "/api/v1/health", tag = "overview", + responses((status = 200, body = HealthReport)), security(("bearer" = [])))] +pub async fn health(State(st): Shared) -> Result { + let c = &st.ctl; + let (status, error, read_at, since) = { + let h = c + .health + .lock() + .map_err(|_| ApiError::internal("health cache"))?; + ( + h.status.clone(), + h.error.clone(), + h.read_at, + h.since.clone(), + ) + }; + let head = c + .repo + .head_required() + .map_err(|e| ApiError::internal(e.to_string()))?; + let tree = c + .repo + .tree(&head) + .map_err(|e| ApiError::internal(e.to_string()))?; + Ok(json( + StatusCode::OK, + &HealthReport { + edge: EdgeHealth { + attached: c.edge.attached(), + reachable: status.is_some() && error.is_none(), + config_sha256: status.as_ref().map(|s| s.config_sha256.clone()), + trial_running: status.as_ref().is_some_and(|s| s.trial.is_some()), + error, + read_at: read_at.map(rfc3339), + }, + paused: c.paused().map(|p| Blocked { + code: "control.paused".into(), + message: p.message, + }), + queued: c.queued_count(), + hosts: host_rows(c, &tree, status.as_ref(), &since), + }, + )) +} + +/// This document. +#[utoipa::path(get, path = "/api/v1/openapi.json", tag = "overview", + responses((status = 200, description = "The OpenAPI document")), security(("bearer" = [])))] +pub async fn openapi() -> Response { + let mut r = super::openapi_json().into_response(); + r.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + r +} + +struct Bearer; + +impl Modify for Bearer { + fn modify(&self, api: &mut utoipa::openapi::OpenApi) { + use utoipa::openapi::security::{HttpAuthScheme, HttpBuilder, SecurityScheme}; + let components = api.components.get_or_insert_with(Default::default); + components.add_security_scheme( + "bearer", + SecurityScheme::Http(HttpBuilder::new().scheme(HttpAuthScheme::Bearer).build()), + ); + } +} + +#[derive(OpenApi)] +#[openapi( + info( + title = "Ianitor Domi control API", + description = "REST + JSON on loopback. Every call needs `Authorization: Bearer `. \ + Errors are `{error: {code, message, field, params, retry_after_s, detail}, errors: [...], request_id}`. \ + Every JSON object answer carries `server_time`. See docs/api.md and docs/ui-api.md.", + license(name = "MPL-2.0") + ), + paths( + overview, list_hosts, get_host, validate_host, create_host, update_host, patch_host, delete_host, + retry_certificate, list_applies, get_apply, cancel_apply, history, history_entry, restore_preview, + get_undo, undo, restore, push_now, settings, list_tokens, create_token, rename_token, revoke_token, + mint_share_link, list_share_links, stop_share_link, stop_all_share_links, health, openapi + ), + components(schemas( + HostSpec, HealthCheckSpec, HeaderRuleSpec, HostWrite, HostPatch, UndoBody, RestoreBody, TokenCreate, + TokenRename, MintBody, ErrorEnvelope, ErrorBody, ApplyAccepted, ApplyView, ApplyList, Step, WatchHost, + Reason, FieldError, Overview, HostList, HostDetail, History, RestorePreview, UndoView, TokenList, + TokenView, CreatedToken, ShareLinkList, ShareLinkView, MintedLink, StoppedAll, Settings, RepoView, + HealthReport, Done + )), + modifiers(&Bearer), + tags( + (name = "overview"), (name = "hosts"), (name = "applies"), (name = "history"), + (name = "repo"), (name = "settings"), (name = "tokens"), (name = "share-links") + ) +)] +pub struct ApiDoc; diff --git a/crates/control/src/api/mod.rs b/crates/control/src/api/mod.rs new file mode 100644 index 0000000..0502906 --- /dev/null +++ b/crates/control/src/api/mod.rs @@ -0,0 +1,467 @@ +// 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/. + +//! The REST + JSON API on loopback (`/api/v1`), with its OpenAPI document generated from the +//! handlers (utoipa). +//! +//! Every request: the `Host` header must name this server (against DNS rebinding); a browser +//! write without `X-Ianitor-UI: 1` is refused (CSRF); a valid `Authorization: Bearer` API +//! token is required (nothing else identifies the caller: control trusts no `Remote-*` +//! header); 120 requests a minute per token. Bodies are at most 64 KiB, JSON, with no +//! unknown fields. Errors are one typed envelope with a plain-English message. Logs show +//! method, route template, status and time only. + +// An error answer is built once per failed request; boxing it buys nothing. +#![allow(clippy::result_large_err)] + +pub mod handlers; +pub mod views; + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +use axum::Router; +use axum::body::{Body as AxumBody, Bytes}; +use axum::extract::{DefaultBodyLimit, FromRequest, MatchedPath, Request, State}; +use axum::http::{HeaderMap, HeaderValue, StatusCode, header}; +use axum::middleware::{self, Next}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{delete, get, post}; +use serde::de::DeserializeOwned; +use utoipa::OpenApi; + +pub use views::health_state; + +use crate::engine::{Control, Fail}; +use crate::messages::{self, Params, message}; +use crate::tokens::Refusal; +use crate::util::{hex, now, random, rfc3339, sha256_hex}; +use views::{ErrorBody, ErrorEnvelope}; + +pub const MAX_BODY: usize = 64 * 1024; +const RATE_PER_MINUTE: u32 = 120; + +/// Who is calling: the API token's id and name. +#[derive(Debug, Clone)] +pub struct Actor { + pub token_id: String, + pub name: String, +} + +pub enum Stored { + Apply(String), + Json(u16, serde_json::Value), +} + +pub struct AppState { + pub ctl: Arc, + idem: Mutex>, + rate: Mutex>, +} + +impl AppState { + pub fn new(ctl: Arc) -> Arc { + Arc::new(AppState { + ctl, + idem: Mutex::new(HashMap::new()), + rate: Mutex::new(HashMap::new()), + }) + } + + /// Count one request against `bucket`; `Err(seconds to wait)` over the limit. + pub fn limit(&self, bucket: &str, per_window: u32, window: u64) -> Result<(), u64> { + let Ok(mut m) = self.rate.lock() else { + return Ok(()); + }; + let t = now(); + let slot = t / window; + if m.len() > 10_000 { + m.retain(|_, (s, _)| *s + 1 >= slot); + } + let e = m.entry(bucket.to_owned()).or_insert((slot, 0)); + if e.0 != slot { + *e = (slot, 0); + } + if e.1 >= per_window { + return Err((slot + 1) * window - t); + } + e.1 += 1; + Ok(()) + } + + /// Look up an Idempotency-Key. `Ok(Some)` replays, `Err` when the key was used for + /// another request. + pub fn idem_get(&self, key: &str, fingerprint: &str) -> Result, ApiError> { + let Ok(m) = self.idem.lock() else { + return Ok(None); + }; + match m.get(key) { + Some((fp, _, _)) if fp != fingerprint => Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "request.idempotency", + Params::new(), + )), + Some((_, Stored::Apply(id), _)) => Ok(Some(Stored::Apply(id.clone()))), + Some((_, Stored::Json(s, v), _)) => Ok(Some(Stored::Json(*s, v.clone()))), + None => Ok(None), + } + } + + pub fn idem_put(&self, key: &str, fingerprint: &str, s: Stored) { + if let Ok(mut m) = self.idem.lock() { + let t = now(); + m.retain(|_, (_, _, at)| t.saturating_sub(*at) < 86_400); + if m.len() >= 2000 { + return; + } + m.insert(key.to_owned(), (fingerprint.to_owned(), s, t)); + } + } +} + +// ---------------------------------------------------------------- errors + +#[derive(Debug)] +pub struct ApiError { + pub status: StatusCode, + pub body: ErrorBody, + pub errors: Vec, +} + +impl ApiError { + pub fn new(status: StatusCode, code: &str, params: Params) -> ApiError { + ApiError { + status, + body: ErrorBody { + code: code.into(), + message: message(code, ¶ms), + field: params.get("field").cloned(), + params, + retry_after_s: None, + detail: None, + }, + errors: Vec::new(), + } + } + + pub fn internal(detail: impl Into) -> ApiError { + let mut e = ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", Params::new()); + e.body.detail = Some(detail.into()); + e + } + + pub fn retry(mut self, secs: u64) -> ApiError { + self.body.retry_after_s = Some(secs); + self.body.params.insert("seconds".into(), secs.to_string()); + self.body.message = message(&self.body.code, &self.body.params); + self + } +} + +impl From for ApiError { + fn from(f: Fail) -> ApiError { + ApiError { + status: StatusCode::from_u16(f.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR), + body: ErrorBody::from(&f.reason), + errors: f.errors.iter().map(ErrorBody::from).collect(), + } + } +} + +impl IntoResponse for ApiError { + fn into_response(self) -> Response { + let retry = self.body.retry_after_s; + let env = ErrorEnvelope { + error: self.body, + errors: self.errors, + request_id: String::new(), + }; + let mut r = (self.status, axum::Json(env)).into_response(); + if let Some(s) = retry + && let Ok(v) = HeaderValue::from_str(&s.to_string()) + { + r.headers_mut().insert(header::RETRY_AFTER, v); + } + r + } +} + +// ---------------------------------------------------------------- JSON bodies + +/// A JSON request body: at most 64 KiB, no unknown fields, errors that never echo values. +pub struct Body { + pub value: T, + pub raw: Bytes, +} + +impl FromRequest for Body { + type Rejection = ApiError; + + async fn from_request(req: Request, state: &S) -> Result { + let json_type = req + .headers() + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.starts_with("application/json")); + let raw = Bytes::from_request(req, state).await.map_err(|_| { + ApiError::new( + StatusCode::PAYLOAD_TOO_LARGE, + "request.too_large", + Params::new(), + ) + })?; + let text: &[u8] = if raw.is_empty() { b"{}" } else { &raw }; + if !raw.is_empty() && !json_type { + return Err(ApiError::new( + StatusCode::UNSUPPORTED_MEDIA_TYPE, + "request.body", + messages::params([("problem", "send it as application/json.".into())]), + )); + } + match serde_json::from_slice::(text) { + Ok(value) => Ok(Body { value, raw }), + Err(e) => Err(body_error(&e)), + } + } +} + +fn body_error(e: &serde_json::Error) -> ApiError { + let m = e.to_string(); + let quoted = |prefix: &str| -> Option { + let rest = m.split(prefix).nth(1)?; + Some(rest.split('`').next()?.to_owned()) + }; + if let Some(f) = quoted("unknown field `") { + let mut err = ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "request.body_unknown_field", + messages::params([("field", f.clone())]), + ); + err.body.field = Some(f); + return err; + } + if let Some(f) = quoted("missing field `") { + return ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "request.body", + messages::params([ + ("problem", format!("the field \"{f}\" is missing.")), + ("field", f), + ]), + ); + } + // Other serde messages can quote the value sent; say only where the problem is. + let what = match e.classify() { + serde_json::error::Category::Syntax | serde_json::error::Category::Eof => "it is not JSON", + _ => "a value has the wrong type or form", + }; + ApiError::new( + StatusCode::BAD_REQUEST, + "request.body", + messages::params([( + "problem", + format!("{what} (line {}, column {}).", e.line(), e.column()), + )]), + ) +} + +// ---------------------------------------------------------------- middleware + +fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool { + let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok()) else { + return false; + }; + let port = ctl.cfg.listen.port(); + let ok = [ + ctl.cfg.listen.to_string(), + format!("localhost:{port}"), + format!("127.0.0.1:{port}"), + format!("[::1]:{port}"), + ]; + ok.iter().any(|o| o.eq_ignore_ascii_case(host)) + || ctl + .cfg + .allowed_hosts + .iter() + .any(|a| a.eq_ignore_ascii_case(host)) +} + +/// Host check, CSRF check, token, rate limit; logs method, route template, status, time. +async fn guard(State(st): State>, mut req: Request, next: Next) -> Response { + let started = Instant::now(); + let method = req.method().clone(); + let route = req + .extensions() + .get::() + .map(|p| p.as_str().to_owned()) + .unwrap_or_else(|| "(no route)".into()); + let resp = async { + if !host_allowed(&st.ctl, req.headers()) { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "request.host", + Params::new(), + )); + } + let browser = req.headers().contains_key(header::ORIGIN) + || req.headers().contains_key("sec-fetch-site"); + let write = !matches!(method.as_str(), "GET" | "HEAD" | "OPTIONS"); + let ui = req + .headers() + .get("x-ianitor-ui") + .is_some_and(|v| v.as_bytes() == b"1"); + if browser && write && !ui { + return Err(ApiError::new( + StatusCode::FORBIDDEN, + "request.csrf", + Params::new(), + )); + } + let auth = req + .headers() + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()); + let tok = st.ctl.tokens.check(auth).map_err(|r| { + let (code, params) = match r { + Refusal::Missing => ("token.missing", Params::new()), + Refusal::Unknown => ("token.unknown", Params::new()), + Refusal::Expired(t) => ( + "token.expired", + messages::params([("date", ianitor_core::time::long_date(t))]), + ), + Refusal::Revoked(t) => ( + "token.revoked", + messages::params([("date", ianitor_core::time::long_date(t))]), + ), + }; + ApiError::new(StatusCode::UNAUTHORIZED, code, params) + })?; + st.limit(&format!("token:{}", tok.id), RATE_PER_MINUTE, 60) + .map_err(|s| { + ApiError::new(StatusCode::TOO_MANY_REQUESTS, "rate.limited", Params::new()).retry(s) + })?; + req.extensions_mut().insert(Actor { + token_id: tok.id, + name: tok.name, + }); + Ok(next.run(req).await) + } + .await; + let resp = resp.unwrap_or_else(IntoResponse::into_response); + log::info!(target: "ianitor::api", "{method} {route} {} {} ms", resp.status().as_u16(), started.elapsed().as_millis()); + resp +} + +/// Adds `server_time` to every JSON object answer and `request_id` to error envelopes. +async fn finish(req: Request, next: Next) -> Response { + let request_id = random::<8>().map(|b| hex(&b)).unwrap_or_default(); + let resp = next.run(req).await; + let json = resp + .headers() + .get(header::CONTENT_TYPE) + .is_some_and(|v| v.as_bytes().starts_with(b"application/json")); + let (mut parts, body) = resp.into_parts(); + if let Ok(v) = HeaderValue::from_str(&request_id) { + parts.headers.insert("x-request-id", v); + } + if !json { + return Response::from_parts(parts, body); + } + let Ok(bytes) = axum::body::to_bytes(body, 16 << 20).await else { + return Response::from_parts(parts, AxumBody::empty()); + }; + let out = match serde_json::from_slice::(&bytes) { + Ok(serde_json::Value::Object(mut m)) => { + m.insert("server_time".into(), rfc3339(now()).into()); + if m.contains_key("error") { + m.insert("request_id".into(), request_id.into()); + } + serde_json::to_vec(&m).unwrap_or_else(|_| bytes.to_vec()) + } + _ => bytes.to_vec(), + }; + parts.headers.remove(header::CONTENT_LENGTH); + Response::from_parts(parts, AxumBody::from(out)) +} + +async fn not_found() -> ApiError { + ApiError::new(StatusCode::NOT_FOUND, "request.not_found", Params::new()) +} + +async fn method_not_allowed() -> ApiError { + ApiError::new( + StatusCode::METHOD_NOT_ALLOWED, + "request.method", + Params::new(), + ) +} + +pub fn fingerprint(method: &str, path: &str, raw: &[u8]) -> String { + sha256_hex(format!("{method} {path} {}", sha256_hex(raw)).as_bytes()) +} + +pub fn router(st: Arc) -> Router { + use handlers as h; + let api = Router::new() + .route("/api/v1/overview", get(h::overview)) + .route("/api/v1/hosts", get(h::list_hosts).post(h::create_host)) + .route("/api/v1/hosts/validate", post(h::validate_host)) + .route( + "/api/v1/hosts/{hostname}", + get(h::get_host) + .put(h::update_host) + .patch(h::patch_host) + .delete(h::delete_host), + ) + .route( + "/api/v1/hosts/{hostname}/share-links", + post(h::mint_share_link), + ) + .route( + "/api/v1/hosts/{hostname}/certificate/retry", + post(h::retry_certificate), + ) + .route("/api/v1/applies", get(h::list_applies)) + .route( + "/api/v1/applies/{id}", + get(h::get_apply).delete(h::cancel_apply), + ) + .route("/api/v1/history", get(h::history)) + .route("/api/v1/history/{change_id}", get(h::history_entry)) + .route( + "/api/v1/history/{change_id}/restore-preview", + get(h::restore_preview), + ) + .route("/api/v1/undo", get(h::get_undo).post(h::undo)) + .route("/api/v1/restore", post(h::restore)) + .route("/api/v1/repo/push", post(h::push_now)) + .route("/api/v1/settings", get(h::settings)) + .route("/api/v1/tokens", get(h::list_tokens).post(h::create_token)) + .route( + "/api/v1/tokens/{id}", + delete(h::revoke_token).patch(h::rename_token), + ) + .route("/api/v1/share-links", get(h::list_share_links)) + .route( + "/api/v1/share-links/stop-all", + post(h::stop_all_share_links), + ) + .route("/api/v1/share-links/{id}", delete(h::stop_share_link)) + .route("/api/v1/health", get(h::health)) + .route("/api/v1/openapi.json", get(h::openapi)) + .method_not_allowed_fallback(method_not_allowed) + .fallback(not_found) + .layer(middleware::from_fn_with_state(st.clone(), guard)) + .layer(DefaultBodyLimit::max(MAX_BODY)) + .with_state(st); + api.layer(middleware::from_fn(finish)) +} + +/// The OpenAPI document. +pub fn openapi_json() -> String { + handlers::ApiDoc::openapi() + .to_pretty_json() + .unwrap_or_else(|_| "{}".into()) +} diff --git a/crates/control/src/api/views.rs b/crates/control/src/api/views.rs new file mode 100644 index 0000000..dfd5fc9 --- /dev/null +++ b/crates/control/src/api/views.rs @@ -0,0 +1,797 @@ +// 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/. + +//! Response shapes (docs/ui-api.md §1, §2), built from control's state. Times are RFC 3339 +//! UTC; every JSON object answer also gets `server_time` from the API layer. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use crate::edgelink::{EdgeStatus, HostStatus}; +use crate::engine::Control; +use crate::hostspec::HostSpec; +use crate::messages::{self, message}; +use crate::records::{ApplyRecord, FieldError, Reason, Step, WatchHost}; +use crate::util::{now, rfc3339}; + +fn t(x: Option) -> Option { + x.map(rfc3339) +} + +fn short(id: &Option) -> Option { + id.as_ref().map(|c| c.chars().take(7).collect()) +} + +/// One error, as the UI shows it (docs/ui-api.md §0). +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct ErrorBody { + /// Stable code, e.g. `host.upstream.no_port`. + pub code: String, + /// Plain English, shown as is. + pub message: String, + /// The form field, e.g. `upstreams[0]`. + pub field: Option, + pub params: BTreeMap, + pub retry_after_s: Option, + /// Technical detail, behind "Show details". Never a secret. + pub detail: Option, +} + +impl From<&FieldError> for ErrorBody { + fn from(e: &FieldError) -> Self { + ErrorBody { + code: e.code.clone(), + message: e.message.clone(), + field: e.field.clone(), + params: e.params.clone(), + retry_after_s: None, + detail: e.detail.clone(), + } + } +} + +impl From<&Reason> for ErrorBody { + fn from(r: &Reason) -> Self { + ErrorBody { + code: r.code.clone(), + message: r.message.clone(), + field: r.field.clone(), + params: r.params.clone(), + retry_after_s: None, + detail: r.detail.clone(), + } + } +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct ErrorEnvelope { + pub error: ErrorBody, + pub errors: Vec, + pub request_id: String, +} + +// ---------------------------------------------------------------- applies + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct WaitingFor { + pub apply_id: String, + pub summary: String, + pub seconds_left: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct QueueView { + pub position: usize, + pub waiting_for: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct WatchView { + pub ends_at: String, + pub seconds_left: u64, + pub hosts: Vec, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct PushView { + /// `pushed`, `pending` or `failed`. + pub state: String, + pub at: Option, + pub error_code: Option, + pub next_try_at: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct ApplyView { + pub id: String, + pub change_id: String, + /// `add`, `edit`, `remove`, `undo`, `restore` or `share_links`. + pub kind: String, + pub summary: String, + pub hosts: Vec, + /// `queued`, `validating`, `applying`, `watching`, `kept`, `reverted`, `failed` or + /// `needs_attention`. + pub state: String, + pub created_at: String, + pub started_at: Option, + pub finished_at: Option, + pub steps: Vec, + pub queue: Option, + pub watch: Option, + pub reason: Option, + pub errors: Vec, + pub commit_short: Option, + pub commit: Option, + pub push: Option, + pub undo_of: Option, + pub restore_of: Option, + pub effect: Option, + pub attempted_host: Option, + pub actor: String, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct ApplyAccepted { + pub apply: ApplyView, +} + +pub fn apply_view(c: &Control, r: &ApplyRecord) -> ApplyView { + let n = now(); + let queue = (r.state == "queued").then(|| { + let position = c.queue_position(&r.id).unwrap_or(1); + let running = c.records().into_iter().rev().find(|x| x.is_running()); + QueueView { + position, + waiting_for: running.map(|x| WaitingFor { + apply_id: x.id.clone(), + summary: x.summary.clone(), + seconds_left: x.watch.as_ref().map(|w| w.ends.saturating_sub(n)), + }), + } + }); + let push = (r.state == "kept" && r.commit.is_some()).then(|| { + let p = c.push_state(); + let step = r + .steps + .iter() + .find(|s| s.key == "push") + .map(|s| s.state.as_str()) + .unwrap_or("pending"); + PushView { + state: match step { + "done" => "pushed", + "failed" => "failed", + _ if c.cfg.routes.remote.is_none() => "pending", + _ if p.error_code.is_some() => "failed", + _ => "pending", + } + .into(), + at: t(p.last_push_at), + error_code: p.error_code.clone(), + next_try_at: t(p.next_try_at), + } + }); + ApplyView { + id: r.id.clone(), + change_id: r.id.clone(), + kind: r.kind.clone(), + summary: r.summary.clone(), + hosts: r.hosts.clone(), + state: r.state.clone(), + created_at: rfc3339(r.created), + started_at: t(r.started), + finished_at: t(r.finished), + steps: r.steps.clone(), + queue, + watch: r.watch.as_ref().map(|w| WatchView { + ends_at: rfc3339(w.ends), + seconds_left: if r.state == "watching" { + w.ends.saturating_sub(n) + } else { + 0 + }, + hosts: w.hosts.clone(), + }), + reason: r.reason.clone(), + errors: r.errors.iter().map(ErrorBody::from).collect(), + commit_short: short(&r.commit), + commit: r.commit.clone(), + push, + undo_of: r.undo_of.clone(), + restore_of: r.restore_of.clone(), + effect: r.effect.clone(), + attempted_host: r.attempted_host.clone(), + actor: r.actor.clone(), + } +} + +// ---------------------------------------------------------------- health + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct Failure { + pub kind: String, + pub upstream: String, + pub count: u32, + pub of: u32, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct UpstreamHealth { + pub url: String, + /// `healthy`, `down` or `pending`. + pub state: String, + pub last_check_at: Option, + pub latency_ms: Option, + pub failure_kind: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct HealthView { + /// `healthy`, `degraded`, `down`, `unknown` or `pending`. + pub state: String, + pub last_check_at: Option, + pub latency_ms: Option, + pub since: Option, + pub failure: Option, + pub upstreams: Vec, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct CertView { + /// `ok`, `pending` or `failed`. + pub state: String, + pub not_after: Option, + pub error_code: Option, +} + +/// The health word for a host (docs/ui-api.md §1.1): `unknown` without a health check, +/// `pending` before the first check, `healthy` when every upstream passed its last check and +/// its recent ones, `degraded` when some fail or results are mixed, `down` when none passed. +pub fn health_state(h: &HostStatus) -> &'static str { + if !h.health_check { + return "unknown"; + } + let checks: Vec> = h + .upstreams + .iter() + .map(|u| { + u.checks + .iter() + .filter(|c| c.source == "health_check") + .collect() + }) + .collect(); + if checks.iter().all(|c| c.is_empty()) { + return "pending"; + } + let last_ok: Vec = checks + .iter() + .map(|c| c.last().is_some_and(|x| x.ok)) + .collect(); + if !last_ok.iter().any(|x| *x) { + return "down"; + } + let mixed = checks + .iter() + .any(|c| c.iter().any(|x| x.ok) && c.iter().any(|x| !x.ok)); + if last_ok.iter().all(|x| *x) && !mixed { + "healthy" + } else { + "degraded" + } +} + +fn scheme_url(spec: Option<&HostSpec>, address: &str) -> String { + let scheme = spec + .and_then(|s| s.upstreams.first()) + .and_then(|u| u.split_once("://").map(|(s, _)| s.to_owned())) + .unwrap_or_else(|| "http".into()); + format!("{scheme}://{address}") +} + +pub fn health_view( + status: Option<&HostStatus>, + spec: Option<&HostSpec>, + since: Option<(&'static str, u64)>, +) -> HealthView { + let Some(h) = status else { + return HealthView { + state: if spec.is_some_and(|s| s.health_check.is_none()) { + "unknown" + } else { + "pending" + } + .into(), + last_check_at: None, + latency_ms: None, + since: None, + failure: None, + upstreams: Vec::new(), + }; + }; + let state = health_state(h); + let mut last_at = None; + let mut latency = None; + let mut failure: Option = None; + let ups = h + .upstreams + .iter() + .map(|u| { + let checks: Vec<_> = u + .checks + .iter() + .filter(|c| c.source == "health_check") + .collect(); + let last = checks.last(); + if let Some(l) = last { + last_at = last_at.max(Some(l.at)); + if l.ok { + latency = match (latency, l.latency_ms) { + (Some(a), Some(b)) => Some(u64::min(a, b)), + (a, b) => a.or(b), + }; + } else if failure.is_none() { + failure = Some(Failure { + kind: l.kind.clone().unwrap_or_else(|| "bad_answer".into()), + upstream: scheme_url(spec, &u.address), + count: checks.iter().filter(|c| !c.ok).count() as u32, + of: checks.len() as u32, + }); + } + } + UpstreamHealth { + url: scheme_url(spec, &u.address), + state: match last { + None => "pending", + Some(l) if l.ok => "healthy", + Some(_) => "down", + } + .into(), + last_check_at: last.map(|l| rfc3339(l.at)), + latency_ms: last.and_then(|l| l.latency_ms), + failure_kind: last.and_then(|l| l.kind.clone()), + } + }) + .collect(); + HealthView { + state: state.into(), + last_check_at: t(last_at), + latency_ms: latency, + since: since + .filter(|(s, _)| *s == state) + .map(|(_, at)| rfc3339(at)), + failure: if matches!(state, "down" | "degraded") { + failure + } else { + None + }, + upstreams: if h.health_check { ups } else { Vec::new() }, + } +} + +pub fn cert_view(status: Option<&HostStatus>, spec: Option<&HostSpec>) -> CertView { + match status { + Some(h) => CertView { + state: h.certificate.state.clone(), + not_after: h + .certificate + .not_after + .and_then(|x| u64::try_from(x).ok()) + .map(rfc3339), + error_code: (h.certificate.state == "failed").then(|| "cert.failed".into()), + }, + None => CertView { + state: if spec.is_some_and(|s| s.tls == "domi") { + "ok" + } else { + "pending" + } + .into(), + not_after: None, + error_code: None, + }, + } +} + +// ---------------------------------------------------------------- hosts and overview + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct HostRow { + pub hostname: String, + pub upstreams: Vec, + pub tls: String, + pub auth: String, + pub websockets: bool, + pub share_links: bool, + pub added_at: Option, + pub health: HealthView, + pub certificate: CertView, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct HostDetail { + pub host: HostSpec, + /// The routes commit this was read from; send it back as `base_rev`. + pub rev: String, + /// The host file as committed. + pub toml: String, + pub health: HealthView, + pub certificate: CertView, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct HostList { + pub rev: String, + pub hosts: Vec, +} + +#[derive(Debug, Clone, Default, Serialize, ToSchema)] +pub struct Counts { + pub hosts: usize, + pub healthy: usize, + pub degraded: usize, + pub down: usize, + pub unknown: usize, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct EngineView { + /// `pingora` (the Caddy switch waits on Mark, ROADMAP §10 (b)). + pub running: String, + /// `running` or `stopped` (control cannot reach it). + pub state: String, + pub since: Option, + #[schema(value_type = Option)] + pub fallback_ready: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct UndoTarget { + pub change_id: String, + pub summary: String, + pub kept_at: Option, + pub commit_short: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct Blocked { + pub code: String, + pub message: String, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct UndoView { + pub available: bool, + pub target: Option, + /// What Undo does, e.g. "Removes recipes.home.example". + pub effect: Option, + pub blocked: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct ActiveApply { + pub id: String, + pub state: String, + pub summary: String, + pub seconds_left: Option, + pub queued: usize, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct RepoView { + pub name: String, + pub last_push_at: Option, + pub unpushed: u64, + pub push_error_code: Option, + pub remote_configured: bool, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct SiteView { + pub forward_auth_configured: bool, + pub acme_configured: bool, + pub secrets: Vec, + pub watch_seconds: u64, + pub share_links_available: bool, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct Overview { + pub counts: Counts, + pub hosts: Vec, + pub engine: EngineView, + pub last_apply: Option, + pub undo: UndoView, + pub active_apply: Option, + pub repo: Option, + /// The Domi intermediate; arrives in phase 3. + #[schema(value_type = Option)] + pub intermediate: Option, + pub site: Option, + pub paused: Option, + /// Set when control cannot read health from edge (`health.unavailable`). + pub health_error: Option, + pub rev: Option, +} + +pub fn added_at(c: &Control, hostname: &str) -> Option { + c.records() + .iter() + .find(|r| r.kind == "add" && r.state == "kept" && r.hosts.iter().any(|h| h == hostname)) + .and_then(|r| r.finished) + .map(rfc3339) +} + +pub fn undo_view(c: &Control) -> UndoView { + let blocked = if let Some(p) = c.paused() { + Some(Blocked { + code: "undo.paused".into(), + message: message("undo.paused", &messages::Params::new()) + " " + &p.message, + }) + } else { + c.records() + .iter() + .rev() + .find(|r| r.is_running() && r.kind == "undo") + .map(|r| { + let left = r + .watch + .as_ref() + .map(|w| w.ends.saturating_sub(now())) + .unwrap_or(0); + Blocked { + code: "undo.watching".into(), + message: message( + "undo.watching", + &messages::params([("seconds", left.to_string())]), + ), + } + }) + }; + match c.undo_target() { + None => UndoView { + available: false, + target: None, + effect: None, + blocked: Some(blocked.unwrap_or(Blocked { + code: "undo.nothing".into(), + message: message("undo.nothing", &messages::Params::new()), + })), + }, + Some(t) => { + let effect = undo_effect(c, &t); + UndoView { + available: blocked.is_none(), + target: Some(UndoTarget { + change_id: t.id.clone(), + summary: t.summary.clone(), + kept_at: t.finished.map(rfc3339), + commit_short: short(&t.commit), + }), + effect, + blocked, + } + } + } +} + +/// What undoing `t` would do: from its tree back to the tree before it. +pub fn undo_effect(c: &Control, t: &ApplyRecord) -> Option { + let (commit, base) = (t.commit.as_ref()?, t.base.as_ref()?); + let from = c.repo.tree(commit).ok()?; + let to = c.repo.tree(base).ok()?; + let mut parts = Vec::new(); + let mut names: std::collections::BTreeSet = from.hostnames().into_iter().collect(); + names.extend(to.hostnames()); + for h in names { + match (from.host(&h), to.host(&h)) { + (Some(a), Some(b)) if a != b => parts.push(format!("Changes {h} back")), + (Some(_), None) => parts.push(format!("Removes {h}")), + (None, Some(_)) => parts.push(format!("Adds {h} back")), + _ => {} + } + } + Some(if parts.is_empty() { + "Changes the site settings back".into() + } else { + parts.join("; ") + }) +} + +pub fn host_rows( + c: &Control, + tree: &crate::repo::RouteTree, + status: Option<&EdgeStatus>, + since: &std::collections::HashMap, +) -> Vec { + tree.hostnames() + .into_iter() + .map(|h| { + let spec = tree.host(&h).and_then(|t| HostSpec::from_toml(t).ok()); + let st = status.and_then(|s| s.hosts.iter().find(|x| x.hostname == h)); + HostRow { + upstreams: spec + .as_ref() + .map(|s| s.upstreams.clone()) + .unwrap_or_default(), + tls: spec.as_ref().map(|s| s.tls.clone()).unwrap_or_default(), + auth: spec.as_ref().map(|s| s.auth.clone()).unwrap_or_default(), + websockets: spec.as_ref().is_none_or(|s| s.websockets), + share_links: spec.as_ref().is_some_and(|s| s.share_links), + added_at: added_at(c, &h), + health: health_view(st, spec.as_ref(), since.get(&h).copied()), + certificate: cert_view(st, spec.as_ref()), + hostname: h, + } + }) + .collect() +} + +// ---------------------------------------------------------------- history + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct HistoryEntry { + pub change_id: String, + pub summary: String, + pub kind: String, + pub state: String, + pub at: String, + pub commit_short: Option, + pub hosts: Vec, + pub reason_short: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct History { + pub entries: Vec, + /// Pass as `before` for older entries. + pub next_before: Option, +} + +pub fn history_row(r: &ApplyRecord) -> HistoryEntry { + HistoryEntry { + change_id: r.id.clone(), + summary: r.summary.clone(), + kind: r.kind.clone(), + state: r.state.clone(), + at: rfc3339(r.finished.unwrap_or(r.created)), + commit_short: short(&r.commit), + hosts: r.hosts.clone(), + reason_short: r.reason.as_ref().filter(|_| r.state != "kept").map(|x| { + x.params + .get("kind") + .cloned() + .unwrap_or_else(|| x.code.rsplit('.').next().unwrap_or("").replace('_', " ")) + }), + } +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct FieldChange { + pub field: String, + pub from: String, + pub to: String, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct HostChange { + pub hostname: String, + /// `added`, `removed` or `changed`. + pub effect: String, + pub fields: Vec, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct RestorePreview { + pub restorable: bool, + pub same_as_current: bool, + pub changes: Vec, + pub blocked: Option, +} + +// ---------------------------------------------------------------- tokens, shares, settings + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct TokenView { + pub id: String, + pub name: String, + pub created_at: String, + pub last_used_at: Option, + pub expires_at: Option, + pub revoked_at: Option, +} + +impl From<&crate::tokens::TokenRecord> for TokenView { + fn from(r: &crate::tokens::TokenRecord) -> Self { + TokenView { + id: r.id.clone(), + name: r.name.clone(), + created_at: rfc3339(r.created_at), + last_used_at: t(r.last_used_at), + expires_at: t(r.expires_at), + revoked_at: t(r.revoked_at), + } + } +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct TokenList { + pub items: Vec, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct CreatedToken { + pub id: String, + pub name: String, + /// Shown once; Ianitor keeps only its hash. + pub token: String, + pub expires_at: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct ShareLinkView { + pub id: String, + pub hostname: String, + pub path_prefix: String, + pub created_at: String, + pub expires_at: String, + pub has_password: bool, + /// `active`, `expired` or `stopped`. + pub state: String, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct ShareLinkList { + pub items: Vec, + pub epoch: u32, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct MintedLink { + pub id: String, + /// Contains the token; shown once. + pub url: String, + pub expires_at: String, + pub path_prefix: String, + pub has_password: bool, + /// `host.share.no_signin` when the host needs no sign-in anyway. + pub warning: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct StoppedAll { + pub epoch: u32, + pub message: String, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct Settings { + pub repo: RepoView, + pub watch_seconds: u64, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct EdgeHealth { + pub attached: bool, + pub reachable: bool, + pub config_sha256: Option, + pub trial_running: bool, + pub error: Option, + pub read_at: Option, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct HealthReport { + pub edge: EdgeHealth, + pub paused: Option, + pub queued: usize, + pub hosts: Vec, +} + +#[derive(Debug, Clone, Serialize, ToSchema)] +pub struct Done { + pub message: String, +} diff --git a/crates/control/src/config.rs b/crates/control/src/config.rs new file mode 100644 index 0000000..a35e23a --- /dev/null +++ b/crates/control/src/config.rs @@ -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, + /// 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, +} + +#[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, +} + +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 { + 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 { + 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() +} diff --git a/crates/control/src/crash.rs b/crates/control/src/crash.rs new file mode 100644 index 0000000..a39c2df --- /dev/null +++ b/crates/control/src/crash.rs @@ -0,0 +1,27 @@ +// 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/. + +//! Crash points for the crash-safety tests: with `IANITOR_TEST_CRASH_AT=` in its +//! environment, control aborts (no cleanup, like a kill -9) when an apply reaches that stage. +//! Without the variable this does nothing; the NixOS unit never sets it. + +/// The stages, in order. +pub const STAGES: [&str; 9] = [ + "prepared", + "committed", + "trial_written", + "trial_loaded", + "watching", + "watched", + "confirmed", + "promoted", + "reverting", +]; + +pub fn point(stage: &str) { + if std::env::var("IANITOR_TEST_CRASH_AT").as_deref() == Ok(stage) { + log::error!(target: "ianitor::crash", "IANITOR_TEST_CRASH_AT={stage}: aborting on purpose"); + std::process::abort(); + } +} diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs new file mode 100644 index 0000000..4a867f9 --- /dev/null +++ b/crates/control/src/dev.rs @@ -0,0 +1,197 @@ +// 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/. + +//! `ianitor-control --dev`: everything temporary, on 127.0.0.1. A fresh routes repository, a +//! state directory, a share-link key and one API token printed once. If an `ianitor-edge` +//! binary is found (`--edge-bin`, `$IANITOR_EDGE_BIN`, or next to this binary), it runs as +//! the dev proxy on 127.0.0.1:18080/18443 with an admin socket, so applies are loaded and +//! watched for real; otherwise applies are only written. Everything is removed on Ctrl-C. + +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::Duration; + +use ianitor_control::config::{Caddy, Compile, Config, Edge, Routes}; +use ianitor_control::repo::Repo; +use ianitor_control::tokens::Tokens; +use ianitor_control::util::{hex, random, write_atomic}; + +const SITE: &str = "# Dev site settings. Sign-in goes to an Authelia that may not run here.\n\ +[forward_auth]\nurl = \"http://127.0.0.1:9091/api/authz/forward-auth\"\n"; + +struct Cleanup { + dir: PathBuf, + edge: Option, +} + +impl Drop for Cleanup { + fn drop(&mut self) { + if let Some(c) = &mut self.edge { + let _ = c.kill(); + let _ = c.wait(); + } + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +fn find_edge(args: &[String]) -> Option { + let mut it = args.iter(); + while let Some(a) = it.next() { + if a == "--edge-bin" { + return it.next().map(PathBuf::from); + } + } + if let Some(p) = std::env::var_os("IANITOR_EDGE_BIN") { + return Some(PathBuf::from(p)); + } + let me = std::env::current_exe().ok()?; + let sibling = me.with_file_name(if cfg!(windows) { + "ianitor-edge.exe" + } else { + "ianitor-edge" + }); + sibling.is_file().then_some(sibling) +} + +fn arg(args: &[String], name: &str) -> Option { + let mut it = args.iter(); + while let Some(a) = it.next() { + if a == name { + return it.next().cloned(); + } + } + None +} + +pub async fn run(args: &[String]) -> Result<(), String> { + let listen: SocketAddr = arg(args, "--listen") + .unwrap_or_else(|| "127.0.0.1:7878".into()) + .parse() + .map_err(|_| "--listen must be an address like 127.0.0.1:7878")?; + if !listen.ip().is_loopback() { + return Err("--dev listens on loopback only".into()); + } + let dir = std::env::temp_dir().join(format!("ianitor-dev-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut cleanup = Cleanup { + dir: dir.clone(), + edge: None, + }; + for d in [ + "state", + "edge", + "caddy", + "certs", + "creds", + "logs", + "edge-state", + ] { + std::fs::create_dir_all(dir.join(d)).map_err(|e| e.to_string())?; + } + let key = hex(&random::<32>().map_err(|e| e.to_string())?); + write_atomic(&dir.join("creds/share-link-key"), key.as_bytes(), 0o600) + .map_err(|e| e.to_string())?; + + let edge_bin = if cfg!(unix) { find_edge(args) } else { None }; + let s = |p: &str| dir.join(p).to_string_lossy().into_owned(); + let cfg = Config { + listen, + allowed_hosts: Vec::new(), + state_dir: dir.join("state"), + credentials_dir: Some(dir.join("creds")), + git: PathBuf::from("git"), + watch_secs: arg(args, "--watch-secs") + .and_then(|v| v.parse().ok()) + .unwrap_or(10), + watch_every_secs: 2, + trial_margin_secs: 20, + health_poll_secs: 2, + routes: Routes { + repo: dir.join("routes.git"), + branch: "main".into(), + remote: None, + remote_name: "Gitea".into(), + push_username: "ianitor".into(), + push_credential: None, + }, + edge: Edge { + config: dir.join("edge/edge.json"), + trial: None, + admin_socket: edge_bin.as_ref().map(|_| dir.join("edge/admin.sock")), + share_revocations: dir.join("edge/share-revocations.json"), + }, + caddy: Caddy { + config: dir.join("caddy/caddy.json"), + }, + compile: Compile { + http_listen: "127.0.0.1:18080".parse().map_err(|_| "bad address")?, + https_listen: "127.0.0.1:18443".parse().map_err(|_| "bad address")?, + cert_dir: s("certs"), + state_dir: s("edge-state"), + access_log: s("logs/access.log"), + caddy_credentials_dir: s("creds"), + caddy_admin: None, + }, + compile_caddy: None, + }; + cfg.check().map_err(|e| e.to_string())?; + Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE) + .map_err(|e| e.to_string())?; + let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None)?; + + // Control writes edge.json first; then edge can start from it. + let ctl_cfg = cfg.clone(); + let opened = ianitor_control::Control::open(ctl_cfg).await?; + drop(opened); + if let Some(bin) = &edge_bin { + cleanup.edge = Some(start_edge(bin, &dir, &cfg)?); + } + + println!("Ianitor control (dev) on http://{listen}/api/v1"); + println!("Routes repository: {}", cfg.routes.repo.display()); + match &edge_bin { + Some(b) => println!( + "Dev proxy: {} on https://127.0.0.1:18443 (HTTP 18080); Domi hosts need certificates in {}", + b.display(), + dir.join("certs").display() + ), + None => println!( + "No ianitor-edge found: applies are written but not loaded or watched (use --edge-bin)." + ), + } + println!("API token (shown once): {token}"); + println!("Press Ctrl-C to stop and remove {}", dir.display()); + let r = ianitor_control::serve(cfg, ianitor_control::stop_signal()).await; + drop(cleanup); + r +} + +fn start_edge(bin: &Path, dir: &Path, cfg: &Config) -> Result { + let log = std::fs::File::create(dir.join("logs/edge.log")).map_err(|e| e.to_string())?; + let log2 = log.try_clone().map_err(|e| e.to_string())?; + let child = Command::new(bin) + .arg("--config") + .arg(&cfg.edge.config) + .arg("--admin-socket") + .arg(dir.join("edge/admin.sock")) + .arg("--share-revocations") + .arg(&cfg.edge.share_revocations) + .env("CREDENTIALS_DIRECTORY", dir.join("creds")) + .stdout(Stdio::from(log)) + .stderr(Stdio::from(log2)) + .spawn() + .map_err(|e| format!("cannot start {}: {e}", bin.display()))?; + let sock = dir.join("edge/admin.sock"); + for _ in 0..100 { + if sock.exists() { + return Ok(child); + } + std::thread::sleep(Duration::from_millis(50)); + } + Err(format!( + "the dev proxy did not start; see {}", + dir.join("logs/edge.log").display() + )) +} diff --git a/crates/control/src/edgelink.rs b/crates/control/src/edgelink.rs new file mode 100644 index 0000000..5485e57 --- /dev/null +++ b/crates/control/src/edgelink.rs @@ -0,0 +1,220 @@ +// 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's side of edge's admin socket (see `ianitor_edge::admin`). + +use std::path::PathBuf; +use std::time::Duration; + +use serde::Deserialize; +use serde_json::{Value, json}; + +#[derive(Debug, thiserror::Error)] +pub enum EdgeLinkError { + /// Edge did not answer (not running, socket missing, timeout). + #[error("edge cannot be reached: {0}")] + Unreachable(String), + /// Edge answered with an error. + #[error("{message}")] + Refused { status: u16, message: String }, +} + +/// One probe result as edge reports it. +#[derive(Debug, Clone, Deserialize, PartialEq, Eq)] +pub struct Check { + pub seq: u64, + pub at: u64, + pub ok: bool, + pub source: String, + pub kind: Option, + pub status: Option, + pub latency_ms: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct UpstreamStatus { + pub address: String, + pub healthy: bool, + pub checks: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct CertStatus { + pub state: String, + pub not_after: Option, + pub error: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct HostStatus { + pub hostname: String, + pub health_check: bool, + pub upstreams: Vec, + pub certificate: CertStatus, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct TrialStatus { + pub config_sha256: String, + pub seconds_left: u64, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct EdgeStatus { + pub generation: u64, + pub config_sha256: String, + pub started_at: u64, + pub trial: Option, + pub hosts: Vec, +} + +/// How control reaches edge. `None` in dev mode without an edge: applies are written but +/// not loaded or watched. +#[derive(Debug, Clone)] +pub enum EdgeLink { + Unix(PathBuf), + None, +} + +const TIMEOUT: Duration = Duration::from_secs(10); + +impl EdgeLink { + pub fn attached(&self) -> bool { + matches!(self, EdgeLink::Unix(_)) + } + + async fn call( + &self, + method: &str, + path: &str, + body: Option, + ) -> Result { + let EdgeLink::Unix(socket) = self else { + return Err(EdgeLinkError::Unreachable("no edge is attached".into())); + }; + #[cfg(unix)] + { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let body = body.map(|b| b.to_string()).unwrap_or_default(); + let req = format!( + "{method} {path} HTTP/1.1\r\nHost: edge\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + let exchange = async { + let mut s = tokio::net::UnixStream::connect(socket).await?; + s.write_all(req.as_bytes()).await?; + let mut buf = Vec::new(); + s.read_to_end(&mut buf).await?; + Ok::<_, std::io::Error>(buf) + }; + let buf = tokio::time::timeout(TIMEOUT, exchange) + .await + .map_err(|_| EdgeLinkError::Unreachable("no answer within 10 s".into()))? + .map_err(|e| EdgeLinkError::Unreachable(e.to_string()))?; + let (status, json) = parse(&buf).map_err(EdgeLinkError::Unreachable)?; + if (200..300).contains(&status) { + Ok(json) + } else { + Err(EdgeLinkError::Refused { + status, + message: json["error"].as_str().unwrap_or("edge refused").to_owned(), + }) + } + } + #[cfg(not(unix))] + { + let _ = (socket, method, path, body); + Err(EdgeLinkError::Unreachable( + "the admin socket needs Unix".into(), + )) + } + } + + pub async fn status(&self) -> Result { + let v = self.call("GET", "/v1/status", None).await?; + serde_json::from_value(v) + .map_err(|e| EdgeLinkError::Unreachable(format!("odd status: {e}"))) + } + + /// Load the trial file; returns its SHA-256 as edge computed it. + pub async fn trial( + &self, + confirm_within: u64, + watch_hosts: &[String], + every: u64, + ) -> Result { + let v = self + .call( + "POST", + "/v1/trial", + Some(json!({ + "confirm_within_secs": confirm_within, + "watch_hosts": watch_hosts, + "watch_every_secs": every, + })), + ) + .await?; + Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned()) + } + + pub async fn confirm(&self, sha: &str) -> Result<(), EdgeLinkError> { + self.call("POST", "/v1/confirm", Some(json!({ "config_sha256": sha }))) + .await + .map(|_| ()) + } + + pub async fn abort(&self) -> Result { + let v = self.call("POST", "/v1/abort", None).await?; + Ok(v["reverted"].as_bool().unwrap_or(false)) + } + + pub async fn reload(&self) -> Result { + let v = self.call("POST", "/v1/reload", None).await?; + Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned()) + } + + pub async fn reload_revocations(&self) -> Result<(), EdgeLinkError> { + self.call("POST", "/v1/share-revocations/reload", None) + .await + .map(|_| ()) + } + + pub async fn acme_retry(&self) -> Result<(), EdgeLinkError> { + self.call("POST", "/v1/acme/retry", None).await.map(|_| ()) + } +} + +fn parse(raw: &[u8]) -> Result<(u16, Value), String> { + let end = raw + .windows(4) + .position(|w| w == b"\r\n\r\n") + .ok_or("no complete answer from edge")?; + let head = String::from_utf8_lossy(&raw[..end]); + let status: u16 = head + .split(' ') + .nth(1) + .and_then(|s| s.parse().ok()) + .ok_or("no status from edge")?; + let chunked = head + .to_ascii_lowercase() + .contains("transfer-encoding: chunked"); + let mut body = raw[end + 4..].to_vec(); + if chunked { + let mut out = Vec::new(); + let mut rest = &body[..]; + while let Some(p) = rest.windows(2).position(|w| w == b"\r\n") { + let size = usize::from_str_radix(String::from_utf8_lossy(&rest[..p]).trim(), 16) + .map_err(|_| "odd chunk from edge")?; + rest = &rest[p + 2..]; + if size == 0 || rest.len() < size { + break; + } + out.extend_from_slice(&rest[..size]); + rest = &rest[(size + 2).min(rest.len())..]; + } + body = out; + } + let json = serde_json::from_slice(&body).unwrap_or(Value::Null); + Ok((status, json)) +} diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs new file mode 100644 index 0000000..9878cab --- /dev/null +++ b/crates/control/src/engine.rs @@ -0,0 +1,1587 @@ +// 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/. + +//! The apply pipeline (ROADMAP §3): validate → compile both outputs → commit → write the +//! trial files → edge loads the trial → watch the touched hosts → confirm and promote ("kept"), +//! or git-revert and abort ("reverted"). One worker runs applies one at a time, in the order +//! they were asked for; everything else waits in the queue. +//! +//! Crash safety: `edge.json` and `caddy.json` only ever hold configs that passed their +//! watch. The new config reaches edge as a *trial*, which edge drops by itself if control +//! does not confirm it in time; the journal (see `records`) tells a restarted control what +//! to finish or undo, so the repository, both files and edge agree again. + +// A refusal is built once per failed request or apply; boxing it buys nothing. +#![allow(clippy::result_large_err)] + +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use ianitor_core::compile; +use ianitor_core::share::ShareKey; +use tokio::sync::Notify; + +use crate::config::Config; +use crate::crash; +use crate::edgelink::{Check, EdgeLink, EdgeLinkError, EdgeStatus}; +use crate::hostspec::HostSpec; +use crate::messages::{self, Params, message}; +use crate::records::{ApplyRecord, FieldError, Journal, PushState, Reason, Watch, WatchHost}; +use crate::repo::{Repo, RepoError, RouteTree}; +use crate::shares::Shares; +use crate::tokens::Tokens; +use crate::util::{ + hex, now, random, read_json, remove_if_exists, rename_durable, rfc3339, write_atomic, + write_json, +}; + +/// What a user asked for. +#[derive(Debug, Clone)] +pub enum Change { + Put { spec: HostSpec, create: bool }, + ShareLinks { hostname: String, on: bool }, + Delete { hostname: String }, + Undo { target: String }, + Restore { change_id: String }, +} + +struct Job { + id: String, + change: Change, + base_rev: Option, +} + +/// A refusal, before or during an apply. +#[derive(Debug, Clone)] +pub struct Fail { + pub status: u16, + pub reason: Reason, + pub errors: Vec, +} + +impl Fail { + pub fn new(status: u16, code: &str, params: Params) -> Fail { + Fail { + status, + reason: reason(code, params), + errors: Vec::new(), + } + } + + pub fn detail(mut self, d: impl Into) -> Fail { + self.reason.detail = Some(d.into()); + self + } +} + +pub fn reason(code: &str, params: Params) -> Reason { + Reason { + code: code.into(), + message: message(code, ¶ms), + hostname: params.get("hostname").cloned(), + upstream: params.get("upstream").cloned(), + field: params.get("field").cloned(), + count: params.get("count").and_then(|c| c.parse().ok()), + of: params.get("of").and_then(|c| c.parse().ok()), + detail: None, + params, + } +} + +/// Core validation errors in the API's shape. +pub fn field_errors(errs: &ianitor_core::ValidationErrors) -> Vec { + errs.errors() + .iter() + .map(|e| { + let params: Params = e + .params() + .into_iter() + .map(|(k, v)| (k.to_owned(), v)) + .collect(); + FieldError { + code: e.code().into(), + message: message(e.code(), ¶ms), + field: e.field(), + params, + detail: Some(e.to_string()), + } + }) + .collect() +} + +struct Plan { + kind: &'static str, + summary: String, + verb: &'static str, + hosts: Vec, + target: RouteTree, + model: ianitor_core::Model, + attempted: Option, + undo_of: Option, + restore_of: Option, + effect: Option, +} + +/// Health as control last read it from edge. +#[derive(Debug, Clone, Default)] +pub struct HealthCache { + pub status: Option, + pub error: Option, + pub read_at: Option, + /// hostname → (state, since). + pub since: HashMap, +} + +pub struct Control { + pub cfg: Config, + pub repo: Repo, + pub edge: EdgeLink, + pub tokens: Tokens, + pub shares: Shares, + pub share_key: Option, + records: Mutex>, + queue: Mutex>, + wake: Notify, + pub health: Mutex, + push: Mutex, + pub push_wake: Notify, + paused: Mutex>, + /// Serialises applies with share-revocation writes and recovery. + apply_lock: tokio::sync::Mutex<()>, +} + +const MAX_RECORDS: usize = 1000; +const MAX_QUEUE: usize = 50; + +fn host_verb(kind: &str) -> &'static str { + match kind { + "add" => "added", + "remove" => "removed", + _ => "changed", + } +} + +fn repo_fail(e: RepoError) -> Fail { + match e { + RepoError::Shape(errs) => { + let file = errs + .first() + .map(|e| e.file().to_owned()) + .unwrap_or_default(); + let mut f = Fail::new(409, "repo.unreadable", messages::params([("file", file)])); + f.errors = field_errors(&ianitor_core::ValidationErrors::from_errors(errs)); + f + } + e => Fail::new(500, "internal", Params::new()).detail(e.to_string()), + } +} + +fn short(id: &str) -> String { + id.chars().take(10).collect() +} + +impl Control { + /// Open the stores and the repository, recover from an interrupted apply, and make the + /// files and edge agree with the repository. + pub async fn open(cfg: Config) -> Result, String> { + std::fs::create_dir_all(&cfg.state_dir) + .map_err(|e| format!("cannot create {}: {e}", cfg.state_dir.display()))?; + let repo = Repo::open( + &cfg.git, + &cfg.routes.repo, + &cfg.state_dir, + &cfg.routes.branch, + ) + .map_err(|e| e.to_string())?; + let edge = match &cfg.edge.admin_socket { + Some(p) => EdgeLink::Unix(p.clone()), + None => EdgeLink::None, + }; + let share_key = cfg + .credential(ianitor_core::share::KEY_CREDENTIAL) + .and_then(|k| ShareKey::new(&k).ok()); + if share_key.is_none() { + log::warn!(target: "ianitor::control", "no usable share-link-key credential: share links cannot be made"); + } + let records: Vec = + read_json(&cfg.state_dir.join("applies.json"))?.unwrap_or_default(); + let push: PushState = read_json(&cfg.state_dir.join("push.json"))?.unwrap_or_default(); + let paused: Option = read_json(&cfg.state_dir.join("paused.json"))?; + let c = Arc::new(Control { + tokens: Tokens::new(&cfg.state_dir), + shares: Shares::new(&cfg.state_dir, &cfg.edge.share_revocations), + repo, + edge, + share_key, + records: Mutex::new(records), + queue: Mutex::new(VecDeque::new()), + wake: Notify::new(), + health: Mutex::new(HealthCache::default()), + push: Mutex::new(push), + push_wake: Notify::new(), + paused: Mutex::new(paused), + apply_lock: tokio::sync::Mutex::new(()), + cfg, + }); + c.recover().await?; + Ok(c) + } + + // ------------------------------------------------------------ records + + fn save_records(&self, recs: &[ApplyRecord]) { + if let Err(e) = write_json(&self.cfg.state_dir.join("applies.json"), &recs) { + log::error!(target: "ianitor::control", "{e}"); + } + } + + fn update(&self, id: &str, f: F) { + if let Ok(mut recs) = self.records.lock() { + if let Some(r) = recs.iter_mut().find(|r| r.id == id) { + f(r); + } + self.save_records(&recs); + } + } + + pub fn record(&self, id: &str) -> Option { + self.records + .lock() + .ok()? + .iter() + .find(|r| r.id == id) + .cloned() + } + + pub fn records(&self) -> Vec { + self.records.lock().map(|r| r.clone()).unwrap_or_default() + } + + /// The latest kept change with a commit: the Undo target. + pub fn undo_target(&self) -> Option { + self.records + .lock() + .ok()? + .iter() + .rev() + .find(|r| r.is_kept_change()) + .cloned() + } + + pub fn paused(&self) -> Option { + self.paused.lock().ok().and_then(|p| p.clone()) + } + + fn pause(&self, r: Reason) { + let _ = write_json(&self.cfg.state_dir.join("paused.json"), &r); + if let Ok(mut p) = self.paused.lock() { + *p = Some(r); + } + } + + pub fn push_state(&self) -> PushState { + self.push.lock().map(|p| p.clone()).unwrap_or_default() + } + + /// Position (1-based) in the queue, and the running apply. + pub fn queue_position(&self, id: &str) -> Option { + let q = self.queue.lock().ok()?; + q.iter().position(|j| j.id == id).map(|p| p + 1) + } + + pub fn queued_count(&self) -> usize { + self.queue.lock().map(|q| q.len()).unwrap_or(0) + } + + // ------------------------------------------------------------ planning + + fn conflict( + &self, + base_rev: Option<&str>, + head: &str, + tree: &RouteTree, + hosts: &[String], + ) -> Result<(), Fail> { + let Some(base) = base_rev else { return Ok(()) }; + if base == head { + return Ok(()); + } + if !self.repo.in_history(base).map_err(repo_fail)? { + return Err(Fail::new(422, "request.base_rev", Params::new())); + } + let old = self.repo.tree(base).map_err(repo_fail)?; + for h in hosts { + if old.host(h) != tree.host(h) { + let last = self + .records() + .into_iter() + .rev() + .find(|r| r.is_kept_change() && r.hosts.contains(h)); + let (time, summary) = match last { + Some(r) => (rfc3339(r.finished.unwrap_or(r.created)), r.summary), + None => (String::new(), "a change outside Ianitor".into()), + }; + return Err(Fail::new( + 409, + "change.conflict", + messages::params([ + ("hostname", h.clone()), + ("time", time), + ("summary", summary), + ]), + )); + } + } + Ok(()) + } + + fn plan( + &self, + change: &Change, + head: &str, + tree: &RouteTree, + base_rev: Option<&str>, + ) -> Result { + let mut target = tree.clone(); + let (kind, summary, hosts, attempted, undo_of, restore_of, effect); + match change { + Change::Put { spec, create } => { + let h = spec.hostname.clone(); + let exists = tree.host(&h).is_some(); + if *create && exists { + let mut f = Fail::new( + 422, + "host.hostname.taken", + messages::params([("hostname", h.clone())]), + ); + f.reason.field = Some("hostname".into()); + f.errors.push(FieldError { + code: "host.hostname.taken".into(), + message: f.reason.message.clone(), + field: Some("hostname".into()), + params: f.reason.params.clone(), + detail: None, + }); + return Err(f); + } + if !*create && !exists { + return Err(Fail::new( + 404, + "host.not_found", + messages::params([("hostname", h)]), + )); + } + let text = spec.to_toml().map_err(|e| { + Fail::new(422, "request.body", messages::params([("problem", e)])) + })?; + target.set_host(&h, text); + kind = if *create { "add" } else { "edit" }; + summary = format!("{} {h}", if *create { "Added" } else { "Changed" }); + hosts = vec![h]; + attempted = Some(spec.clone()); + (undo_of, restore_of, effect) = (None, None, None); + } + Change::ShareLinks { hostname, on } => { + let Some(text) = tree.host(hostname) else { + return Err(Fail::new( + 404, + "host.not_found", + messages::params([("hostname", hostname.clone())]), + )); + }; + let mut spec = HostSpec::from_toml(text).map_err(|e| { + Fail::new( + 409, + "repo.unreadable", + messages::params([("file", ianitor_core::routes::host_path(hostname))]), + ) + .detail(e) + })?; + spec.share_links = *on; + let text = spec + .to_toml() + .map_err(|e| Fail::new(500, "internal", Params::new()).detail(e))?; + target.set_host(hostname, text); + kind = "share_links"; + summary = format!( + "Turned share links {} for {hostname}", + if *on { "on" } else { "off" } + ); + hosts = vec![hostname.clone()]; + attempted = Some(spec); + (undo_of, restore_of, effect) = (None, None, None); + } + Change::Delete { hostname } => { + if !target.remove_host(hostname) { + return Err(Fail::new( + 404, + "host.not_found", + messages::params([("hostname", hostname.clone())]), + )); + } + kind = "remove"; + summary = format!("Removed {hostname}"); + hosts = vec![hostname.clone()]; + (attempted, undo_of, restore_of, effect) = (None, None, None, None); + } + Change::Undo { target: wanted } => { + let Some(t) = self.undo_target() else { + return Err(Fail::new(409, "undo.nothing", Params::new())); + }; + let (Some(commit), Some(base)) = (t.commit.clone(), t.base.clone()) else { + return Err(Fail::new(409, "undo.nothing", Params::new())); + }; + if &t.id != wanted || self.repo.tree(&commit).map_err(repo_fail)?.as_ref() != tree { + return Err(Fail::new( + 409, + "undo.target_moved", + messages::params([("summary", t.summary.clone())]), + )); + } + target = (*self.repo.tree(&base).map_err(repo_fail)?).clone(); + kind = "undo"; + summary = format!("Undid: {}", t.summary); + hosts = changed_hosts(tree, &target); + effect = Some(effect_text(tree, &target)); + undo_of = Some(t.id.clone()); + (attempted, restore_of) = (None, None); + } + Change::Restore { change_id } => { + let Some(r) = self.record(change_id) else { + return Err(Fail::new(404, "change.not_found", Params::new())); + }; + let Some(commit) = r.commit.clone().filter(|_| r.state == "kept") else { + return Err(Fail::new(409, "restore.not_kept", Params::new())); + }; + target = (*self.repo.tree(&commit).map_err(repo_fail)?).clone(); + if &target == tree { + return Err(Fail::new(409, "restore.same", Params::new())); + } + kind = "restore"; + summary = format!( + "Restored the version of {}", + ianitor_core::time::long_date(r.finished.unwrap_or(r.created)) + ); + hosts = changed_hosts(tree, &target); + restore_of = Some(r.id.clone()); + (attempted, undo_of, effect) = (None, None, None); + } + } + if &target == tree { + return Err(Fail::new(409, "change.unchanged", Params::new())); + } + if !matches!(change, Change::Undo { .. }) { + self.conflict(base_rev, head, tree, &hosts)?; + } + let model = target.model().map_err(|errs| { + let fe = field_errors(&errs); + let first = fe.first().map(|e| e.message.clone()).unwrap_or_default(); + Fail { + status: 422, + reason: reason( + "apply.failed.validation", + messages::params([("first_error", first)]), + ), + errors: fe, + } + })?; + Ok(Plan { + kind, + verb: host_verb(kind), + summary, + hosts, + target, + model, + attempted, + undo_of, + restore_of, + effect, + }) + } + + fn compile(&self, model: &ianitor_core::Model) -> Result<(String, String), Fail> { + let e = compile::edge(model, &self.cfg.compile.options()); + let c = compile::caddy(model, &self.cfg.caddy_compile().options()); + match (e, c) { + (Ok(e), Ok(c)) => Ok((e, c)), + (Err(x), _) | (_, Err(x)) => { + Err(Fail::new(500, "apply.failed.build", Params::new()).detail(x.to_string())) + } + } + } + + fn head_and_tree(&self) -> Result<(String, Arc), Fail> { + let head = self.repo.head_required().map_err(repo_fail)?; + let tree = self.repo.tree(&head).map_err(repo_fail)?; + Ok((head, tree)) + } + + /// Check a change now (for the 422/409 answers) and queue it. Returns the queued record. + pub fn submit( + &self, + change: Change, + base_rev: Option, + actor: &str, + ) -> Result { + if let Some(p) = self.paused() { + return Err(Fail::new( + 409, + "control.paused", + messages::params([("reason", p.message)]), + )); + } + let (head, tree) = self.head_and_tree()?; + let plan = self.plan(&change, &head, &tree, base_rev.as_deref())?; + self.compile(&plan.model)?; + let id = format!( + "ch_{}", + hex(&random::<6>() + .map_err(|e| Fail::new(500, "internal", Params::new()).detail(e.to_string()))?) + ); + let mut rec = ApplyRecord::new( + id.clone(), + plan.kind, + plan.summary, + plan.hosts, + actor, + now(), + ); + rec.attempted_host = plan.attempted; + rec.undo_of = plan.undo_of; + rec.restore_of = plan.restore_of; + rec.effect = plan.effect; + { + let mut q = self + .queue + .lock() + .map_err(|_| Fail::new(500, "internal", Params::new()))?; + if q.len() >= MAX_QUEUE { + return Err(Fail::new( + 429, + "rate.limited", + messages::params([("seconds", "60".into())]), + )); + } + let mut recs = self + .records + .lock() + .map_err(|_| Fail::new(500, "internal", Params::new()))?; + recs.push(rec.clone()); + let excess = recs.len().saturating_sub(MAX_RECORDS); + recs.drain(..excess); + self.save_records(&recs); + q.push_back(Job { + id, + change, + base_rev, + }); + } + self.wake.notify_one(); + Ok(rec) + } + + /// Check a host body against the current routes without applying it. + pub fn validate(&self, spec: &HostSpec, create: bool) -> Result<(), Fail> { + let (head, tree) = self.head_and_tree()?; + let change = Change::Put { + spec: spec.clone(), + create, + }; + match self.plan(&change, &head, &tree, None) { + Ok(p) => self.compile(&p.model).map(|_| ()), + Err(f) if f.reason.code == "change.unchanged" => Ok(()), + Err(f) => Err(f), + } + } + + /// Cancel a queued apply. `Ok(false)` if it is not queued any more. + pub fn cancel(&self, id: &str) -> bool { + let removed = match self.queue.lock() { + Ok(mut q) => { + let before = q.len(); + q.retain(|j| j.id != id); + q.len() != before + } + Err(_) => false, + }; + if removed { + let t = now(); + self.update(id, |r| { + r.state = "failed".into(); + r.finished = Some(t); + r.reason = Some(reason("apply.cancelled", Params::new())); + for s in &mut r.steps { + s.state = "skipped".into(); + } + }); + } + removed + } + + // ------------------------------------------------------------ the worker + + /// Run queued applies one at a time, forever. + pub async fn worker(self: Arc) { + loop { + let job = self.queue.lock().ok().and_then(|mut q| q.pop_front()); + match job { + Some(j) => { + let me = self.clone(); + // Its own task: a panic in one apply does not stop the worker. + let id = j.id.clone(); + if let Err(e) = tokio::spawn(async move { me.run(j).await }).await { + log::error!(target: "ianitor::apply", "apply {id} crashed: {e}"); + let t = now(); + self.update(&id, |r| { + r.state = "failed".into(); + r.finished = Some(t); + r.reason = Some(reason("internal", Params::new())); + }); + } + } + None => self.wake.notified().await, + } + } + } + + fn finish(&self, id: &str, state: &str, r: Option, errors: Vec) { + let t = now(); + self.update(id, |rec| { + rec.state = state.into(); + rec.finished = Some(t); + rec.reason = r; + if !errors.is_empty() { + rec.errors = errors; + } + for s in &mut rec.steps { + if s.state == "running" { + s.state = if state == "kept" { + "done".into() + } else { + "failed".into() + }; + } else if s.state == "pending" && s.key != "push" { + s.state = "skipped".into(); + } + } + if state != "kept" { + rec.step("push", "skipped"); + } + }); + log::info!(target: "ianitor::apply", "apply {id}: {state}"); + } + + fn journal_path(&self) -> std::path::PathBuf { + self.cfg.state_dir.join("journal.json") + } + + fn journal(&self, j: &Journal) -> Result<(), String> { + write_json(&self.journal_path(), j) + } + + fn clear_journal(&self) { + if let Err(e) = remove_if_exists(&self.journal_path()) + .and_then(|_| crate::util::sync_dir(&self.cfg.state_dir)) + { + log::error!(target: "ianitor::apply", "cannot remove the journal: {e}"); + } + } + + async fn run(self: Arc, job: Job) { + let _lock = self.apply_lock.lock().await; + let id = job.id.clone(); + let t = now(); + self.update(&id, |r| { + r.state = "validating".into(); + r.started = Some(t); + r.step("validate", "running"); + }); + if let Some(p) = self.paused() { + return self.finish( + &id, + "failed", + Some(reason( + "control.paused", + messages::params([("reason", p.message)]), + )), + Vec::new(), + ); + } + let (head, tree) = match self.head_and_tree() { + Ok(x) => x, + Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors), + }; + let plan = match self.plan(&job.change, &head, &tree, job.base_rev.as_deref()) { + Ok(p) => p, + Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors), + }; + self.update(&id, |r| { + r.step("validate", "done"); + r.step("compile", "running"); + r.base = Some(head.clone()); + r.hosts = plan.hosts.clone(); + if plan.effect.is_some() { + r.effect = plan.effect.clone(); + } + }); + let (edge_text, caddy_text) = match self.compile(&plan.model) { + Ok(x) => x, + Err(f) => return self.finish(&id, "failed", Some(f.reason), Vec::new()), + }; + self.update(&id, |r| { + r.step("compile", "done"); + r.step("write", "running"); + r.state = "applying".into(); + }); + + let fail_internal = |e: String| { + Some(reason("internal", Params::new())).map(|mut r| { + r.detail = Some(e); + r + }) + }; + let tree_id = match self.repo.write_tree(&plan.target, None) { + Ok(t) => t, + Err(e) => return self.finish(&id, "failed", fail_internal(e.to_string()), Vec::new()), + }; + let rec = self.record(&id); + let actor = rec.as_ref().map(|r| r.actor.clone()).unwrap_or_default(); + let commit = match self.repo.commit(&tree_id, &[&head], &plan.summary, &actor) { + Ok(c) => c, + Err(e) => return self.finish(&id, "failed", fail_internal(e.to_string()), Vec::new()), + }; + let mut j = Journal { + apply_id: id.clone(), + stage: "prepared".into(), + base: head.clone(), + commit: commit.clone(), + edge_sha256: None, + reason: None, + }; + if let Err(e) = self.journal(&j) { + return self.finish(&id, "failed", fail_internal(e), Vec::new()); + } + crash::point("prepared"); + if let Err(e) = self.repo.update_ref(&commit, Some(&head)) { + self.clear_journal(); + return self.finish(&id, "failed", fail_internal(e.to_string()), Vec::new()); + } + self.update(&id, |r| r.commit = Some(commit.clone())); + j.stage = "committed".into(); + if let Err(e) = self.journal(&j) { + log::error!(target: "ianitor::apply", "{e}"); + } + crash::point("committed"); + + if !self.edge.attached() { + // Development without an edge: write the files directly, nothing to watch. + let r = write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644) + .and_then(|_| write_atomic(&self.cfg.caddy.config, caddy_text.as_bytes(), 0o644)); + self.clear_journal(); + if let Err(e) = r { + return self + .revert( + &id, + &j, + fail_internal(e.to_string()).unwrap_or_default(), + "failed", + ) + .await; + } + self.update(&id, |r| { + r.step("write", "done"); + r.step("reload", "skipped"); + r.step("watch", "skipped"); + r.step("push", "pending"); + }); + self.finish( + &id, + "kept", + Some(reason("apply.kept.no_edge", Params::new())), + Vec::new(), + ); + self.push_wake.notify_one(); + return; + } + + let trial = self.cfg.trial_path(); + let caddy_trial = self.cfg.caddy_trial_path(); + if let Err(e) = write_atomic(&trial, edge_text.as_bytes(), 0o644) + .and_then(|_| write_atomic(&caddy_trial, caddy_text.as_bytes(), 0o644)) + { + return self + .revert( + &id, + &j, + fail_internal(e.to_string()).unwrap_or_default(), + "failed", + ) + .await; + } + j.stage = "trial_written".into(); + let _ = self.journal(&j); + crash::point("trial_written"); + self.update(&id, |r| { + r.step("write", "done"); + r.step("reload", "running"); + }); + + // Which hosts to judge: those this change adds or changes, not those it removes. + let watch_hosts: Vec = plan + .hosts + .iter() + .filter(|h| plan.target.host(h).is_some()) + .cloned() + .collect(); + let was_down = self.down_hosts(); + let window = self.cfg.watch_secs; + let sha = match self + .edge + .trial( + window + self.cfg.trial_margin_secs, + &watch_hosts, + self.cfg.watch_every_secs, + ) + .await + { + Ok(s) => s, + Err(EdgeLinkError::Refused { message: m, .. }) => { + let r = reason( + "apply.failed.reload", + messages::params([("engine", "Pingora".into())]), + ); + return self + .revert( + &id, + &j, + Reason { + detail: Some(m), + ..r + }, + "failed", + ) + .await; + } + Err(EdgeLinkError::Unreachable(m)) => { + let r = reason("apply.failed.edge_unreachable", Params::new()); + return self + .revert( + &id, + &j, + Reason { + detail: Some(m), + ..r + }, + "failed", + ) + .await; + } + }; + j.stage = "trial_loaded".into(); + j.edge_sha256 = Some(sha.clone()); + let _ = self.journal(&j); + crash::point("trial_loaded"); + self.update(&id, |r| r.step("reload", "done")); + + let judged: Vec = watch_hosts + .iter() + .filter(|h| !was_down.contains(*h)) + .cloned() + .collect(); + let mut kept_reason = if watch_hosts.is_empty() { + reason( + "apply.kept.removed", + messages::params([("hostname", plan.hosts.join(", "))]), + ) + } else { + reason( + "apply.kept", + messages::params([ + ("hostname", watch_hosts.join(", ")), + ("seconds", window.to_string()), + ]), + ) + }; + if judged.is_empty() { + self.update(&id, |r| r.step("watch", "skipped")); + } else { + let ends = now() + window; + self.update(&id, |r| { + r.state = "watching".into(); + r.step("watch", "running"); + r.watch = Some(Watch { + ends, + hosts: judged + .iter() + .map(|h| WatchHost { + hostname: h.clone(), + ..Default::default() + }) + .collect(), + }); + }); + match self.watch(&id, &sha, &judged, &plan, ends).await { + Ok(no_check) => { + if !no_check.is_empty() && no_check.len() == judged.len() { + kept_reason = reason( + "apply.kept.no_watch", + messages::params([("hostname", no_check.join(", "))]), + ); + } + } + Err(r) => return self.revert(&id, &j, r, "reverted").await, + } + self.update(&id, |r| r.step("watch", "done")); + } + crash::point("watched"); + + if let Err(e) = self.edge.confirm(&sha).await { + let r = reason("apply.reverted.edge_lost", Params::new()); + return self + .revert( + &id, + &j, + Reason { + detail: Some(e.to_string()), + ..r + }, + "reverted", + ) + .await; + } + j.stage = "confirmed".into(); + let _ = self.journal(&j); + crash::point("confirmed"); + if let Err(e) = self.promote() { + // Edge serves the new config and the repository has it; the files catch up at + // the next start (recovery promotes again). + log::error!(target: "ianitor::apply", "cannot promote the trial files: {e}"); + } + j.stage = "promoted".into(); + let _ = self.journal(&j); + crash::point("promoted"); + self.clear_journal(); + self.update(&id, |r| r.step("push", "pending")); + self.finish(&id, "kept", Some(kept_reason), Vec::new()); + self.push_wake.notify_one(); + } + + fn promote(&self) -> std::io::Result<()> { + for (trial, fin) in [ + (self.cfg.trial_path(), self.cfg.edge.config.clone()), + (self.cfg.caddy_trial_path(), self.cfg.caddy.config.clone()), + ] { + if trial.exists() { + rename_durable(&trial, &fin)?; + } + } + Ok(()) + } + + /// Hosts that were down (every upstream failed its last check) before this apply. + fn down_hosts(&self) -> BTreeSet { + let Ok(h) = self.health.lock() else { + return BTreeSet::new(); + }; + h.since + .iter() + .filter(|(_, (s, _))| *s == "down") + .map(|(k, _)| k.clone()) + .collect() + } + + /// Watch the judged hosts until `ends`. `Ok(hosts that only had watch probes)`, or the + /// reason to revert. + async fn watch( + &self, + id: &str, + sha: &str, + hosts: &[String], + plan: &Plan, + ends: u64, + ) -> Result, Reason> { + let mut seen: HashMap<(String, String), BTreeMap> = HashMap::new(); + let mut unreachable_since: Option = None; + let mut first = true; + let health_path: HashMap = plan + .model + .hosts() + .iter() + .map(|h| { + ( + h.hostname.to_string(), + h.health_check + .as_ref() + .map_or("/".to_owned(), |c| c.path.clone()), + ) + }) + .collect(); + let mut watch_only = Vec::new(); + loop { + let st = match self.edge.status().await { + Ok(s) => { + unreachable_since = None; + s + } + Err(e) => { + let t = now(); + let since = *unreachable_since.get_or_insert(t); + if t.saturating_sub(since) > 10 || t >= ends { + let r = reason("apply.reverted.edge_lost", Params::new()); + return Err(Reason { + detail: Some(e.to_string()), + ..r + }); + } + tokio::time::sleep(Duration::from_secs(1)).await; + continue; + } + }; + if st.config_sha256 != sha || st.trial.is_none() { + return Err(reason("apply.reverted.edge_lost", Params::new())); + } + if first { + crash::point("watching"); + first = false; + } + let mut counts = Vec::new(); + watch_only.clear(); + for h in hosts { + let Some(hs) = st.hosts.iter().find(|x| &x.hostname == h) else { + continue; + }; + if !hs.health_check { + watch_only.push(h.clone()); + } + let (mut passed, mut failed) = (0u32, 0u32); + let mut all_failing = !hs.upstreams.is_empty(); + for u in &hs.upstreams { + let m = seen.entry((h.clone(), u.address.clone())).or_default(); + for c in &u.checks { + m.insert(c.seq, c.clone()); + } + passed += m.values().filter(|c| c.ok).count() as u32; + failed += m.values().filter(|c| !c.ok).count() as u32; + let tail_failures = m.values().rev().take_while(|c| !c.ok).count(); + if tail_failures < 3 { + all_failing = false; + } + } + counts.push(WatchHost { + hostname: h.clone(), + passed, + failed, + total: passed + failed, + }); + if all_failing { + return Err(self.revert_reason(h, plan, &seen, &health_path)); + } + } + self.update(id, |r| { + if let Some(w) = &mut r.watch { + w.hosts = counts; + } + }); + if now() >= ends { + break; + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + // At the end: every judged host needs an upstream whose last check passed. + for h in hosts { + let last_ok = seen + .iter() + .filter(|((host, _), _)| host == h) + .any(|(_, m)| m.values().next_back().is_some_and(|c| c.ok)); + let any = seen.iter().any(|((host, _), m)| host == h && !m.is_empty()); + if !any { + return Err(reason( + "apply.reverted.no_answer", + messages::params([ + ("hostname", h.clone()), + ("verb", plan.verb.into()), + ("seconds", self.cfg.watch_secs.to_string()), + ]), + )); + } + if !last_ok { + return Err(self.revert_reason(h, plan, &seen, &health_path)); + } + } + Ok(watch_only) + } + + fn revert_reason( + &self, + host: &str, + plan: &Plan, + seen: &HashMap<(String, String), BTreeMap>, + paths: &HashMap, + ) -> Reason { + let mut worst: Option<(&String, &BTreeMap)> = None; + for ((h, addr), m) in seen { + if h == host + && m.values().next_back().is_some_and(|c| !c.ok) + && worst.is_none_or(|(a, _)| addr < a) + { + worst = Some((addr, m)); + } + } + let Some((addr, m)) = worst else { + return reason( + "apply.reverted.no_answer", + messages::params([ + ("hostname", host.into()), + ("verb", plan.verb.into()), + ("seconds", self.cfg.watch_secs.to_string()), + ]), + ); + }; + let kind = m + .values() + .next_back() + .and_then(|c| c.kind.clone()) + .unwrap_or_else(|| "server_error".into()); + let code = match kind.as_str() { + "refused" | "timeout" | "name" | "tls" | "not_found" | "redirect" | "sign_in" => { + format!("apply.reverted.{kind}") + } + _ => "apply.reverted.server_error".into(), + }; + let count = m.values().filter(|c| !c.ok).count(); + let upstream_host = addr + .rsplit_once(':') + .map_or(addr.as_str(), |(h, _)| h) + .trim_start_matches('[') + .trim_end_matches(']') + .to_owned(); + reason( + &code, + messages::params([ + ("hostname", host.into()), + ("verb", plan.verb.into()), + ("upstream", addr.clone()), + ("upstream_host", upstream_host), + ( + "path", + paths.get(host).cloned().unwrap_or_else(|| "/".into()), + ), + ("count", count.to_string()), + ("of", m.len().to_string()), + ]), + ) + } + + /// Undo a commit that is on the branch: abort the trial, git-revert, drop the trial files. + async fn revert(&self, id: &str, j: &Journal, why: Reason, state: &str) { + let mut j = j.clone(); + j.stage = "reverting".into(); + j.reason = Some(why.clone()); + let _ = self.journal(&j); + crash::point("reverting"); + match self.finish_revert(&j).await { + Ok(rev) => { + self.update(id, |r| r.revert_commit = rev); + self.clear_journal(); + self.finish(id, state, Some(why), Vec::new()); + } + Err(e) => { + log::error!(target: "ianitor::apply", "apply {id}: the revert failed: {e}"); + let mut r = reason("apply.needs_attention", Params::new()); + r.detail = Some(format!("{}: {e}", why.message)); + self.pause(r.clone()); + self.clear_journal(); + self.finish(id, "needs_attention", Some(r), Vec::new()); + } + } + } + + /// The idempotent part of a revert. Returns the revert commit, if one was needed. + async fn finish_revert(&self, j: &Journal) -> Result, String> { + if self.edge.attached() { + match self.edge.abort().await { + Ok(_) => {} + // Edge down: it starts from edge.json, which is still the last good config. + Err(e) => { + log::warn!(target: "ianitor::apply", "could not tell edge to abort the trial: {e}") + } + } + } + let head = self.repo.head_required().map_err(|e| e.to_string())?; + let mut rev = None; + if head == j.commit { + let base_tree = self.repo.tree_id(&j.base).map_err(|e| e.to_string())?; + let subject = self + .repo + .info(&j.commit) + .map(|i| i.subject) + .unwrap_or_default(); + let why = j + .reason + .as_ref() + .map(|r| r.message.clone()) + .unwrap_or_default(); + let msg = format!("Revert \"{subject}\"\n\n{why}\n"); + let c = self + .repo + .commit(&base_tree, &[&j.commit], &msg, "Ianitor control") + .map_err(|e| e.to_string())?; + self.repo + .update_ref(&c, Some(&j.commit)) + .map_err(|e| e.to_string())?; + rev = Some(c); + } + for p in [self.cfg.trial_path(), self.cfg.caddy_trial_path()] { + remove_if_exists(&p).map_err(|e| e.to_string())?; + } + Ok(rev) + } + + // ------------------------------------------------------------ recovery + + async fn recover(&self) -> Result<(), String> { + let _lock = self.apply_lock.lock().await; + let journal: Option = read_json(&self.journal_path())?; + if let Some(j) = journal { + log::warn!(target: "ianitor::apply", "apply {} was interrupted at stage {}; recovering", j.apply_id, j.stage); + let head = self.repo.head_required().map_err(|e| e.to_string())?; + match j.stage.as_str() { + "prepared" if head != j.commit => { + self.clear_journal(); + self.finish( + &j.apply_id, + "failed", + Some(reason("apply.interrupted.queued", Params::new())), + Vec::new(), + ); + } + "confirmed" | "promoted" => { + self.promote().map_err(|e| e.to_string())?; + self.clear_journal(); + self.update(&j.apply_id, |r| r.step("push", "pending")); + self.finish(&j.apply_id, "kept", None, Vec::new()); + } + _ => { + let mut why = j + .reason + .clone() + .unwrap_or_else(|| reason("apply.interrupted", Params::new())); + if j.reason.is_none() { + why.detail = Some(format!("control stopped at stage {}", j.stage)); + } + let mut jj = j.clone(); + jj.reason = Some(why.clone()); + match self.finish_revert(&jj).await { + Ok(rev) => { + self.update(&j.apply_id, |r| { + r.commit = r.commit.clone().or(Some(j.commit.clone())); + r.revert_commit = rev; + }); + self.clear_journal(); + // A revert that was already under way keeps its own outcome. + let state = if why.code.starts_with("apply.failed") { + "failed" + } else { + "reverted" + }; + self.finish(&j.apply_id, state, Some(why), Vec::new()); + } + Err(e) => { + let mut r = reason("apply.needs_attention", Params::new()); + r.detail = Some(e); + self.pause(r.clone()); + self.finish(&j.apply_id, "needs_attention", Some(r), Vec::new()); + } + } + } + } + } + // Applies that were still queued never ran. + let stale: Vec = self + .records() + .iter() + .filter(|r| r.is_active()) + .map(|r| r.id.clone()) + .collect(); + for id in stale { + let code = if self.record(&id).is_some_and(|r| r.state == "queued") { + "apply.interrupted.queued" + } else { + "apply.interrupted" + }; + self.finish(&id, "failed", Some(reason(code, Params::new())), Vec::new()); + } + // A trial nobody owns any more. + if self.edge.attached() + && let Ok(st) = self.edge.status().await + && st.trial.is_some() + { + let _ = self.edge.abort().await; + } + self.sync_files().await; + if let Err(e) = self.shares.ensure_revocation_file() { + log::error!(target: "ianitor::share", "{e}"); + } + Ok(()) + } + + /// Make edge.json, caddy.json and edge agree with the branch head. + pub async fn sync_files(&self) { + let (_, tree) = match self.head_and_tree() { + Ok(x) => x, + Err(f) => { + log::error!(target: "ianitor::control", "{}", f.reason.message); + self.pause(f.reason); + return; + } + }; + let model = match tree.model() { + Ok(m) => m, + Err(errs) => { + let fe = field_errors(&errs); + let file = errs + .errors() + .first() + .map(|e| e.file().to_owned()) + .unwrap_or_default(); + let mut r = reason("repo.unreadable", messages::params([("file", file)])); + r.detail = fe.first().and_then(|e| e.detail.clone()); + log::error!(target: "ianitor::control", "the routes repository does not validate: {}", r.detail.clone().unwrap_or_default()); + self.pause(r); + return; + } + }; + let Ok((edge_text, caddy_text)) = self.compile(&model) else { + return; + }; + let mut changed = false; + for (path, text) in [ + (&self.cfg.edge.config, &edge_text), + (&self.cfg.caddy.config, &caddy_text), + ] { + if std::fs::read(path).ok().as_deref() != Some(text.as_bytes()) { + if let Err(e) = write_atomic(path, text.as_bytes(), 0o644) { + log::error!(target: "ianitor::control", "cannot write {}: {e}", path.display()); + } + changed = true; + } + } + if self.edge.attached() { + let want = crate::util::sha256_hex(edge_text.as_bytes()); + let running = self.edge.status().await.ok().map(|s| s.config_sha256); + if changed || running.as_deref().is_some_and(|r| r != want) { + match self.edge.reload().await { + Ok(_) => { + log::info!(target: "ianitor::control", "edge reloaded to match the routes repository") + } + Err(e) => { + log::warn!(target: "ianitor::control", "edge reload after recovery: {e}") + } + } + } + } + } + + // ------------------------------------------------------------ share links + + /// Tell edge the revocation file changed (it also notices by itself within 5 s). + pub async fn revocations_changed(&self) { + if self.edge.attached() + && let Err(e) = self.edge.reload_revocations().await + { + log::warn!(target: "ianitor::share", "edge did not reload the revocation file now ({e}); it will within 5 s"); + } + } + + /// The validated model at the branch head. + pub fn head_model(&self) -> Result<(String, Arc, ianitor_core::Model), Fail> { + let (head, tree) = self.head_and_tree()?; + let model = tree.model().map_err(|errs| { + let mut f = Fail::new( + 409, + "repo.unreadable", + messages::params([( + "file", + errs.errors() + .first() + .map(|e| e.file().to_owned()) + .unwrap_or_default(), + )]), + ); + f.errors = field_errors(&errs); + f + })?; + Ok((head, tree, model)) + } + + // ------------------------------------------------------------ background + + /// Read health from edge every few seconds for the overview. + pub async fn health_poller(self: Arc) { + loop { + let st = self.edge.status().await; + if let Ok(mut h) = self.health.lock() { + let t = now(); + h.read_at = Some(t); + match st { + Ok(s) => { + let mut since = HashMap::new(); + for host in &s.hosts { + let state = crate::api::health_state(host); + let prev = h.since.get(&host.hostname).copied(); + let start = match prev { + Some((p, at)) if p == state => at, + _ => t, + }; + since.insert(host.hostname.clone(), (state, start)); + } + h.since = since; + h.status = Some(s); + h.error = None; + } + Err(e) => { + h.error = Some(e.to_string()); + } + } + } + tokio::time::sleep(Duration::from_secs(self.cfg.health_poll_secs.max(1))).await; + } + } + + /// Push kept changes to the remote; retry with backoff on failure. + pub async fn pusher(self: Arc) { + let Some(remote) = self.cfg.routes.remote.clone() else { + return; + }; + loop { + let wait = self.push_once(&remote).await; + tokio::select! { + _ = self.push_wake.notified() => {} + _ = tokio::time::sleep(wait) => {} + } + } + } + + /// One push attempt. Returns how long to wait before the next. + pub async fn push_once(&self, remote: &str) -> Duration { + // Only push a settled head: never in the middle of an apply. + let head = { + let _lock = self.apply_lock.lock().await; + match self.repo.head_required() { + Ok(h) => h, + Err(_) => return Duration::from_secs(60), + } + }; + let state = self.push_state(); + if state.pushed.as_deref() == Some(head.as_str()) { + return Duration::from_secs(3600); + } + let askpass = self.cfg.routes.push_credential.as_ref().and_then(|c| { + let file = self.cfg.credentials_dir()?.join(c); + let exe = std::env::current_exe().ok()?; + Some((exe, self.cfg.routes.push_username.clone(), file)) + }); + let t = now(); + let result = self + .repo + .push(remote, &head, askpass, Duration::from_secs(60)) + .await; + let mut next = Duration::from_secs(3600); + if let Ok(mut p) = self.push.lock() { + p.last_attempt_at = Some(t); + match result { + Ok(()) => { + p.pushed = Some(head.clone()); + p.last_push_at = Some(now()); + p.error_code = None; + p.error_detail = None; + p.failures = 0; + p.next_try_at = None; + log::info!(target: "ianitor::push", "pushed {} to the remote", short(&head)); + } + Err(e) => { + let text = e.to_string(); + let low = text.to_ascii_lowercase(); + let code = if low.contains("rejected") + || low.contains("non-fast-forward") + || low.contains("fetch first") + { + "push.failed.rejected" + } else if low.contains("authentication failed") + || low.contains(" 401") + || low.contains(" 403") + || low.contains("permission denied (publickey") + || low.contains("could not read username") + || low.contains("could not read password") + { + "push.failed.auth" + } else { + "push.failed.unreachable" + }; + p.failures = p.failures.saturating_add(1); + let secs = (30u64 << p.failures.min(7)).min(3600); + next = Duration::from_secs(secs); + p.next_try_at = Some(now() + secs); + p.error_code = Some(code.into()); + p.error_detail = Some(text.chars().take(300).collect()); + log::warn!(target: "ianitor::push", "push failed ({code}); next try in {secs} s"); + } + } + let _ = write_json(&self.cfg.state_dir.join("push.json"), &*p); + } + // Mark records whose commit is now pushed. + let pushed = self.push_state().pushed; + if let Ok(mut recs) = self.records.lock() { + for r in recs + .iter_mut() + .rev() + .filter(|r| { + r.state == "kept" + && r.steps.iter().any(|s| s.key == "push" && s.state != "done") + }) + .take(50) + { + let s = match (&pushed, &r.commit) { + (Some(p), Some(c)) + if p == c || self.repo.count_between(Some(p), c).ok() == Some(0) => + { + "done" + } + _ if self.push_state().error_code.is_some() => "failed", + _ => "pending", + }; + r.step("push", s); + } + self.save_records(&recs); + } + next + } +} + +fn changed_hosts(a: &RouteTree, b: &RouteTree) -> Vec { + let mut names: BTreeSet = a.hostnames().into_iter().collect(); + names.extend(b.hostnames()); + names + .into_iter() + .filter(|h| a.host(h) != b.host(h)) + .collect() +} + +/// What going from `from` to `to` does, in the Undo bar's words. +fn effect_text(from: &RouteTree, to: &RouteTree) -> String { + let parts: Vec = changed_hosts(from, to) + .into_iter() + .map(|h| match (from.host(&h).is_some(), to.host(&h).is_some()) { + (true, false) => format!("Removes {h}"), + (false, true) => format!("Adds {h} back"), + _ => format!("Changes {h} back"), + }) + .collect(); + if parts.is_empty() { + "Changes the site settings back".into() + } else { + parts.join("; ") + } +} diff --git a/crates/control/src/hostspec.rs b/crates/control/src/hostspec.rs new file mode 100644 index 0000000..538a72c --- /dev/null +++ b/crates/control/src/hostspec.rs @@ -0,0 +1,187 @@ +// 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/. + +//! The host body of the API. It mirrors the host TOML file field for field (docs/ui-api.md +//! §1.2), so control writes exactly what Mark would write by hand. Core validates the TOML +//! control writes; this type only carries it. + +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct HostSpec { + /// Lowercase DNS name, e.g. `wiki.home.example`. + pub hostname: String, + /// Where traffic goes, e.g. `http://10.0.0.23:3000`. Same scheme for all. + pub upstreams: Vec, + /// `letsencrypt` or `domi`. + #[serde(default = "letsencrypt")] + pub tls: String, + /// `none` or `forward-auth`. + #[serde(default = "auth_none")] + pub auth: String, + #[serde(default = "yes")] + pub websockets: bool, + #[serde(default)] + pub share_links: bool, + /// `off` or `truncated`. + #[serde(default = "off")] + pub access_log: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub health_check: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub request_headers: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub response_headers: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct HealthCheckSpec { + pub path: String, + #[serde(default = "ten")] + pub interval_secs: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +#[serde(deny_unknown_fields)] +pub struct HeaderRuleSpec { + /// `set` or `remove`. + pub action: String, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub value: Option, + /// Name of a secret declared in `ianitor.toml`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub secret: Option, +} + +fn letsencrypt() -> String { + "letsencrypt".into() +} +fn auth_none() -> String { + "none".into() +} +fn off() -> String { + "off".into() +} +fn yes() -> bool { + true +} +fn ten() -> i64 { + 10 +} + +impl HostSpec { + /// The TOML file control commits for this host. Every field is written out, so the file + /// says exactly what the form said. + pub fn to_toml(&self) -> Result { + let body = toml::to_string(self).map_err(|e| e.to_string())?; + Ok(format!( + "# Written by Ianitor control. Edit through the web UI or the API.\n{body}" + )) + } + + pub fn from_toml(text: &str) -> Result { + toml::from_str(text).map_err(|e| e.message().to_owned()) + } + + /// Field-level differences, labelled for the restore preview (docs/ui-api.md §1.4). + pub fn diff(&self, to: &HostSpec) -> Vec<(String, String, String)> { + let mut out = Vec::new(); + let mut push = |f: &str, a: String, b: String| { + if a != b { + out.push((f.to_owned(), a, b)); + } + }; + push("hostname", self.hostname.clone(), to.hostname.clone()); + push( + "upstreams", + self.upstreams.join(", "), + to.upstreams.join(", "), + ); + push("tls", self.tls.clone(), to.tls.clone()); + push("auth", self.auth.clone(), to.auth.clone()); + push( + "websockets", + self.websockets.to_string(), + to.websockets.to_string(), + ); + push( + "share_links", + self.share_links.to_string(), + to.share_links.to_string(), + ); + push("access_log", self.access_log.clone(), to.access_log.clone()); + let hc = + |h: &Option| h.as_ref().map(|h| (h.path.clone(), h.interval_secs)); + let (a, b) = (hc(&self.health_check), hc(&to.health_check)); + push( + "health_check.path", + a.as_ref().map(|x| x.0.clone()).unwrap_or_default(), + b.as_ref().map(|x| x.0.clone()).unwrap_or_default(), + ); + push( + "health_check.interval_secs", + a.map(|x| x.1.to_string()).unwrap_or_default(), + b.map(|x| x.1.to_string()).unwrap_or_default(), + ); + let rules = + |r: &[HeaderRuleSpec], q: &[HeaderRuleSpec]| format!("{} rules", r.len() + q.len()); + if self.request_headers != to.request_headers + || self.response_headers != to.response_headers + { + out.push(( + "headers".into(), + rules(&self.request_headers, &self.response_headers), + rules(&to.request_headers, &to.response_headers), + )); + } + out + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn round_trips_and_core_accepts_it() { + let h = HostSpec { + hostname: "wiki.home.test".into(), + upstreams: vec!["http://10.0.0.2:3000".into()], + tls: "domi".into(), + auth: "none".into(), + websockets: false, + share_links: true, + access_log: "truncated".into(), + health_check: Some(HealthCheckSpec { + path: "/health".into(), + interval_secs: 15, + }), + request_headers: vec![HeaderRuleSpec { + action: "set".into(), + name: "X-A".into(), + value: Some("1".into()), + secret: None, + }], + response_headers: vec![], + }; + let text = h.to_toml().unwrap(); + assert_eq!(HostSpec::from_toml(&text).unwrap(), h); + let m = ianitor_core::load( + &ianitor_core::SourceFile { + name: "ianitor.toml", + contents: "", + }, + &[ianitor_core::SourceFile { + name: "hosts/wiki.home.test.toml", + contents: &text, + }], + ); + assert!(m.is_ok(), "{m:?}"); + } +} diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs new file mode 100644 index 0000000..683a167 --- /dev/null +++ b/crates/control/src/lib.rs @@ -0,0 +1,81 @@ +// 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/. + +//! Ianitor control: the routes repository, apply with automatic rollback, share links, API +//! tokens and the REST API, on loopback only. It never serves public traffic; if it stops, +//! edge keeps serving the last good config. + +pub mod api; +pub mod config; +pub mod crash; +pub mod edgelink; +pub mod engine; +pub mod hostspec; +pub mod logger; +pub mod messages; +pub mod records; +pub mod repo; +pub mod shares; +pub mod tokens; +pub mod util; + +use std::sync::Arc; + +pub use config::Config; +pub use engine::Control; + +/// Open control, start its background tasks and serve the API until `shutdown` resolves. +pub async fn serve( + cfg: Config, + shutdown: impl std::future::Future + Send + 'static, +) -> Result<(), String> { + cfg.check().map_err(|e| e.to_string())?; + let listen = cfg.listen; + let ctl = Control::open(cfg).await?; + tokio::spawn(ctl.clone().worker()); + tokio::spawn(ctl.clone().health_poller()); + tokio::spawn(ctl.clone().pusher()); + let app = api::router(api::AppState::new(ctl.clone())); + if !listen.ip().is_loopback() { + return Err("ianitor-control only listens on loopback".into()); + } + let listener = tokio::net::TcpListener::bind(listen) + .await + .map_err(|e| format!("cannot listen on {listen}: {e}"))?; + log::info!(target: "ianitor::control", "API on http://{listen}/api/v1"); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown) + .await + .map_err(|e| e.to_string())?; + drop(ctl); + Ok(()) +} + +/// Wait for Ctrl-C or SIGTERM. +pub async fn stop_signal() { + #[cfg(unix)] + { + use tokio::signal::unix::{SignalKind, signal}; + let mut term = match signal(SignalKind::terminate()) { + Ok(s) => s, + Err(_) => { + let _ = tokio::signal::ctrl_c().await; + return; + } + }; + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + _ = term.recv() => {} + } + } + #[cfg(not(unix))] + { + let _ = tokio::signal::ctrl_c().await; + } +} + +/// For tests: the router over an opened control. +pub fn app(ctl: Arc) -> axum::Router { + api::router(api::AppState::new(ctl)) +} diff --git a/crates/control/src/logger.rs b/crates/control/src/logger.rs new file mode 100644 index 0000000..89e01ea --- /dev/null +++ b/crates/control/src/logger.rs @@ -0,0 +1,61 @@ +// 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/. + +//! Error log on stderr (journald under systemd). Control never logs request headers, bodies, +//! query strings, tokens, passwords or share links: request lines are logged as method and +//! route only, by the API layer. + +use std::io::Write; + +use log::{Level, LevelFilter, Log, Metadata, Record}; + +struct Stderr { + own: LevelFilter, +} + +impl Log for Stderr { + fn enabled(&self, m: &Metadata<'_>) -> bool { + let limit = if m.target().starts_with("ianitor") { + self.own + } else { + self.own.min(LevelFilter::Info) + }; + m.level() <= limit + } + + fn log(&self, r: &Record<'_>) { + if self.enabled(r.metadata()) { + let lvl = match r.level() { + Level::Error => "ERROR", + Level::Warn => "WARN", + Level::Info => "INFO", + Level::Debug => "DEBUG", + Level::Trace => "TRACE", + }; + let _ = writeln!( + std::io::stderr().lock(), + "{lvl} {}: {}", + r.target(), + r.args() + ); + } + } + + fn flush(&self) { + let _ = std::io::stderr().flush(); + } +} + +pub fn init(level: Option<&str>) { + let own = match level.map(str::to_ascii_lowercase).as_deref() { + Some("error") => LevelFilter::Error, + Some("warn") => LevelFilter::Warn, + Some("debug") => LevelFilter::Debug, + Some("trace") => LevelFilter::Trace, + _ => LevelFilter::Info, + }; + if log::set_boxed_logger(Box::new(Stderr { own })).is_ok() { + log::set_max_level(own); + } +} diff --git a/crates/control/src/main.rs b/crates/control/src/main.rs index 47b4520..ec152e4 100644 --- a/crates/control/src/main.rs +++ b/crates/control/src/main.rs @@ -2,11 +2,189 @@ // 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/. -//! Placeholder for ianitor-control (ROADMAP phase 2). It deliberately opens no socket. +//! ```text +//! ianitor-control --config run the control plane +//! ianitor-control --dev [--edge-bin ] temporary everything on 127.0.0.1 +//! ianitor-control token create --name [--expires-days | --never] (--config | --state-dir ) +//! ianitor-control token list (--config | --state-dir ) +//! ianitor-control token revoke (--config | --state-dir ) +//! ianitor-control openapi print the OpenAPI document +//! ianitor-control check --config check the config and exit +//! ``` +//! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`), +//! the binary answers git's prompt from the push credential file. -fn main() { - println!( - "ianitor-control {}: placeholder. The control plane (API on 127.0.0.1) arrives in phase 2.", - env!("CARGO_PKG_VERSION") +use std::path::PathBuf; +use std::process::ExitCode; + +use ianitor_control::{Config, logger, tokens::Tokens}; + +mod dev; + +fn usage() -> ExitCode { + eprintln!( + "usage: ianitor-control --config | --dev [--edge-bin ] | \ + token create --name [--expires-days | --never] (--config | --state-dir ) | \ + token list (...) | token revoke (...) | openapi | check --config " ); + ExitCode::from(2) +} + +fn askpass() -> ExitCode { + // git asks "Username for 'https://…':" and "Password for 'https://…':". + let prompt = std::env::args().nth(1).unwrap_or_default(); + if prompt.starts_with("Username") { + println!( + "{}", + std::env::var("IANITOR_ASKPASS_USER").unwrap_or_default() + ); + return ExitCode::SUCCESS; + } + let Some(file) = std::env::var_os("IANITOR_ASKPASS_FILE") else { + return ExitCode::FAILURE; + }; + match std::fs::read_to_string(file) { + Ok(v) => { + println!("{}", v.trim_end_matches(['\r', '\n'])); + ExitCode::SUCCESS + } + Err(_) => ExitCode::FAILURE, + } +} + +fn state_dir(args: &[String]) -> Result { + let mut it = args.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--state-dir" => { + return it + .next() + .map(PathBuf::from) + .ok_or("--state-dir needs a path".into()); + } + "--config" => { + let p = it.next().ok_or("--config needs a path")?; + return Config::load(&PathBuf::from(p)) + .map(|c| c.state_dir) + .map_err(|e| e.to_string()); + } + _ => {} + } + } + Err("give --config or --state-dir ".into()) +} + +fn token(args: &[String]) -> Result<(), String> { + let dir = state_dir(args)?; + std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; + let tokens = Tokens::new(&dir); + match args.first().map(String::as_str) { + Some("create") => { + let mut name = None; + let mut expires = Some(ianitor_control::util::now() + 365 * 86_400); + let mut it = args.iter().skip(1); + while let Some(a) = it.next() { + match a.as_str() { + "--name" => name = it.next().cloned(), + "--never" => expires = None, + "--expires-days" => { + let d: u64 = it + .next() + .and_then(|d| d.parse().ok()) + .filter(|d| (1..=3650).contains(d)) + .ok_or("--expires-days must be 1 to 3650")?; + expires = Some(ianitor_control::util::now() + d * 86_400); + } + _ => {} + } + } + let name = name.ok_or("--name is required")?; + let (rec, value) = tokens.create(&name, expires).map_err(|e| { + if e == "token.name" { + "the name must be 1 to 64 letters, digits, spaces, dots, dashes or underscores" + .to_owned() + } else { + e + } + })?; + eprintln!( + "Token {} ({}) created. It is shown once; save it in Custos now:", + rec.id, rec.name + ); + println!("{value}"); + Ok(()) + } + Some("list") => { + for t in tokens.list()? { + println!( + "{} {} created {}{}{}", + t.id, + t.name, + ianitor_control::util::rfc3339(t.created_at), + t.expires_at + .map(|e| format!(" expires {}", ianitor_control::util::rfc3339(e))) + .unwrap_or_default(), + t.revoked_at + .map(|e| format!(" REVOKED {}", ianitor_control::util::rfc3339(e))) + .unwrap_or_default() + ); + } + Ok(()) + } + Some("revoke") => { + let id = args.get(1).ok_or("token revoke ")?; + match tokens.revoke(id)? { + Some(_) => { + eprintln!("Token {id} revoked."); + Ok(()) + } + None => Err(format!("there is no token {id}")), + } + } + _ => Err("token create | list | revoke".into()), + } +} + +fn main() -> ExitCode { + if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") { + return askpass(); + } + logger::init(std::env::var("IANITOR_LOG").ok().as_deref()); + let args: Vec = std::env::args().skip(1).collect(); + let rt = match tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + { + Ok(r) => r, + Err(e) => { + eprintln!("ianitor-control: cannot start: {e}"); + return ExitCode::FAILURE; + } + }; + let result = match args.first().map(String::as_str) { + Some("token") => token(&args[1..]), + Some("openapi") => { + println!("{}", ianitor_control::api::openapi_json()); + Ok(()) + } + Some("check") => state_dir(&args[1..]).map(|_| eprintln!("config is valid")), + Some("--dev") => rt.block_on(dev::run(&args[1..])), + Some("--config") => match args.get(1) { + Some(p) => match Config::load(&PathBuf::from(p)) { + Ok(cfg) => rt.block_on(ianitor_control::serve(cfg, ianitor_control::stop_signal())), + Err(e) => Err(e.to_string()), + }, + None => return usage(), + }, + Some("--help" | "-h") | None => return usage(), + Some(_) => return usage(), + }; + match result { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + log::error!(target: "ianitor::control", "{e}"); + eprintln!("ianitor-control: {e}"); + ExitCode::FAILURE + } + } } diff --git a/crates/control/src/messages.rs b/crates/control/src/messages.rs new file mode 100644 index 0000000..8cdfcc4 --- /dev/null +++ b/crates/control/src/messages.rs @@ -0,0 +1,274 @@ +// 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/. + +//! Every user-facing message, by code, in the words of docs/ui-api.md §3. `{x}` is filled from +//! the params; a missing param leaves a plain gap rather than a placeholder. + +use std::collections::BTreeMap; + +pub type Params = BTreeMap; + +fn template(code: &str) -> &'static str { + match code { + // 3.1 host form + "host.hostname.missing" => "Enter the address people will type, like wiki.home.example.", + "host.hostname.uppercase" => "Use lowercase letters only: {suggestion}.", + "host.hostname.characters" => "Use only letters a–z, digits, dots and dashes.", + "host.hostname.spaces" => "Remove the spaces from the address.", + "host.hostname.wildcard" => { + "Addresses with * are not supported yet. Add each name as its own host." + } + "host.hostname.trailing_dot" => "Remove the dot at the end.", + "host.hostname.empty_label" => "There are two dots in a row. Remove one.", + "host.hostname.label_dash" => "A part of the address cannot start or end with a dash.", + "host.hostname.label_long" => "Each part between dots can be at most 63 characters.", + "host.hostname.too_long" => "The address can be at most 253 characters.", + "host.hostname.numeric" => { + "That looks like an IP address. Use a name, like wiki.home.example." + } + "host.hostname.taken" => "{hostname} is already a host.", + "host.hostname.mismatch" => { + "The address in the form ({hostname}) is not the host you are editing ({path_hostname})." + } + "host.file_name" => "The address does not match the file it is stored in.", + "host.upstreams.missing" => { + "Enter where Ianitor should send traffic, like http://10.0.0.23:3000." + } + "host.upstream.not_url" => "Write it as a full address, like http://10.0.0.23:3000.", + "host.upstream.scheme" => "Start the address with http:// or https://.", + "host.upstream.no_host" => "Add the server's name or IP address after http://.", + "host.upstream.host_name" => { + "The server name is not usable. Use letters a–z, digits, dots and dashes, or an IP address." + } + "host.upstream.no_port" => "Add the port at the end, like :3000.", + "host.upstream.port_zero" => { + "Port 0 cannot be used. Enter the port the service listens on." + } + "host.upstream.path" => "Leave out the path after the port. Visitors keep their own path.", + "host.upstream.query" | "host.upstream.fragment" => "Leave out everything after ? or #.", + "host.upstream.credentials" => { + "Leave out the user name and password. Put them in a header rule with a secret instead." + } + "host.upstream.duplicate" => "This address is listed twice.", + "host.upstream.mixed_schemes" => { + "All addresses for one host must start the same way: all http:// or all https://." + } + "host.upstream.too_many" => "One host can send traffic to at most {max} addresses.", + "host.auth.not_configured" => { + "Sign-in is not set up on this server yet, so choose Anyone for now. To set it up, add the Authelia address to ianitor.toml in the routes repository." + } + "host.header.name" => "\"{name}\" cannot be a header name. Use letters, digits and dashes.", + "host.header.value" => { + "This value has characters a header cannot carry. Use visible characters and spaces only." + } + "host.header.empty" => "Enter a value, or choose Remove to drop the header.", + "host.header.protected" => "Ianitor sets {name} itself, so a rule cannot change it.", + "host.header.duplicate" => "{name} already has a rule in this list.", + "host.header.both" => "Choose a fixed value or a secret, not both.", + "host.header.remove_value" => "Remove needs only the header name.", + "host.header.secret_unknown" => { + "There is no secret named {secret}. Secrets are listed in ianitor.toml and loaded from the server's credentials." + } + "host.header.secret_response" => { + "Secrets can only be sent to your service, never back to visitors." + } + "host.health.path" => "Start with / and use plain characters, like /health.", + "host.health.interval" => "Check every 1 to 3600 seconds.", + "host.field.unknown" => "Ianitor does not know the setting \"{field}\".", + "host.field.invalid" | "file.field.invalid" => { + "One of the settings has a value Ianitor cannot use. Show details to see which." + } + "file.field.missing" => "The setting \"{field}\" is missing.", + "change.conflict" => { + "{hostname} was changed at {time} (\"{summary}\") after you opened it. Your edits are still here. Check them, then Apply again." + } + "change.unchanged" => "This is the same as what is live now, so nothing changed.", + "host.not_found" => "{hostname} is no longer a host.", + "host.share.no_signin" => { + "Anyone can already open {hostname}, so a share link changes nothing." + } + // 3.2 apply, undo, restore, repository + "apply.queued" => "Waiting for \"{summary}\" to finish, about {seconds} s.", + "apply.kept" => "{hostname} is live. Health checks passed for {seconds} s.", + "apply.kept.no_watch" => { + "{hostname} is live. It has no health check, so Ianitor only checked that it answers." + } + "apply.kept.removed" => "{hostname} is removed.", + "apply.kept.no_edge" => { + "Saved. No proxy is attached (development mode), so nothing was checked." + } + "apply.reverted.refused" => { + "{hostname} was not {verb}. {upstream} refused the connection on {count} of {of} checks. Ianitor undid the change; every other host kept running." + } + "apply.reverted.timeout" => { + "{hostname} was not {verb}. {upstream} did not answer within 5 seconds on {count} of {of} checks. Ianitor undid the change." + } + "apply.reverted.not_found" => { + "{hostname} was not {verb}. {upstream} says {path} does not exist. Check the health check address. Ianitor undid the change." + } + "apply.reverted.server_error" => { + "{hostname} was not {verb}. {upstream} answered with an error page on {count} of {of} checks. Ianitor undid the change." + } + "apply.reverted.redirect" => { + "{hostname} was not {verb}. {upstream} sent visitors elsewhere instead of answering {path}. Use an address that answers directly, like /health." + } + "apply.reverted.sign_in" => { + "{hostname} was not {verb}. {upstream} asked for a sign-in on {path}. Use an address that answers without signing in." + } + "apply.reverted.name" => { + "{hostname} was not {verb}. The name {upstream_host} could not be found on this network." + } + "apply.reverted.tls" => { + "{hostname} was not {verb}. {upstream} uses https://, but its certificate could not be checked." + } + "apply.reverted.no_answer" => { + "{hostname} was not {verb}. No health check finished within {seconds} s. Ianitor undid the change." + } + "apply.reverted.edge_lost" => { + "The proxy restarted during the check, so it went back to the last good settings. Ianitor undid the change to match." + } + "apply.failed.reload" => { + "{engine} did not take the new settings, so nothing changed. Every host kept running." + } + "apply.failed.build" => { + "Ianitor could not build the settings for this change, so nothing changed." + } + "apply.failed.validation" => { + "This change no longer fits with the routes: {first_error} Nothing changed." + } + "apply.failed.edge_unreachable" => { + "Ianitor cannot reach the proxy right now, so nothing changed. Traffic is not affected." + } + "apply.interrupted" => { + "Ianitor restarted during the check, so it undid the change to be safe." + } + "apply.interrupted.queued" => { + "Ianitor restarted before this change ran, so nothing changed. Try again." + } + "apply.cancelled" => "Cancelled before it started. Nothing changed.", + "apply.needs_attention" => { + "The change failed its check, and Ianitor could not undo it by itself. Visitors are served the last good settings, but the routes repository still has the change." + } + "push.failed.unreachable" => { + "Kept, but not yet saved to {remote}: {remote} did not answer. Ianitor tries again at {time}." + } + "push.failed.rejected" => { + "Kept, but {remote} has changes Ianitor does not have, so nothing was sent. Nothing is lost on this server." + } + "push.failed.auth" => { + "Kept, but {remote} refused Ianitor's access key. Check the key in Custos." + } + "undo.nothing" => "Nothing to undo yet.", + "undo.watching" => "Wait for the check to finish ({seconds} s).", + "undo.paused" => "Changes are paused, so Undo is not available.", + "undo.target_moved" => { + "The last change is now \"{summary}\", so Undo did nothing. Look again and choose." + } + "restore.same" => "This version is the same as the current one. Nothing to restore.", + "restore.not_kept" => { + "This change was undone at the time, so there is nothing to go back to." + } + "change.not_found" => "There is no change with that id.", + "repo.unreadable" => { + "{file} in the routes repository cannot be read. Changes are paused until it is fixed." + } + "repo.unexpected_file" => "{file} does not belong in the routes repository.", + "repo.no_remote" => "No place to push to is set up.", + // 3.4 share links + "share.disabled" => { + "Share links are off for {hostname}. Turning them on is a change to the host, checked like any other." + } + "share.prefix" => "Start with /, like /share/summer-2026. / shares the whole site.", + "share.expiry" => "Choose between 1 hour and 90 days.", + "share.password_short" => "Use at least 8 characters.", + "share.password_long" => "Use at most 128 characters.", + "share.stopped" => "Stopped. The link stops working within a few seconds.", + "share.stopped_all" => "All share links are stopped. New ones work as usual.", + "share.unavailable" => { + "Share links are not set up on this server: the share-link key is missing from the credentials." + } + "share.not_found" => "There is no share link with that id.", + "share.replaces" => "The link to replace is not a link for {hostname}.", + // 3.5 tokens, limits + "token.missing" => "This request needs an API token. Make one in Settings, API.", + "token.unknown" => { + "This API token is not one Ianitor issued, or it was copied incompletely." + } + "token.expired" => { + "This API token expired on {date}. Make a new one in Settings, API, then revoke this one." + } + "token.revoked" => "This API token was revoked on {date}.", + "token.not_found" => "There is no API token with that id.", + "token.name" => "Use 1 to 64 letters, digits, spaces, dots, dashes or underscores.", + "token.expiry" => "Choose between 1 and 3650 days, or never.", + "rate.limited" => "Too many requests in a short time. Try again in {seconds} s.", + "control.paused" => "Changes are paused: {reason} Traffic keeps flowing.", + // request shape + "request.body" => "The request body is not valid: {problem}", + "request.body_unknown_field" => "Ianitor does not know the field \"{field}\".", + "request.too_large" => "The request body is too large.", + "request.csrf" => { + "This request came from a browser page without Ianitor's UI header, so it was refused." + } + "request.host" => "This request was sent to an address Ianitor does not answer on.", + "request.not_found" => "There is no such API call.", + "request.method" => "This API call does not take that method.", + "request.idempotency" => "This Idempotency-Key was already used for a different request.", + "request.base_rev" => "base_rev is not a commit in the routes history.", + "health.unavailable" => { + "Ianitor cannot read health from {engine} right now. Traffic is not affected." + } + "internal" => "Something went wrong inside Ianitor control. Show details for more.", + _ => "Something went wrong.", + } +} + +/// The message for `code`, with params filled in. +pub fn message(code: &str, params: &Params) -> String { + let t = template(code); + let mut out = String::with_capacity(t.len() + 32); + let mut rest = t; + while let Some(start) = rest.find('{') { + out.push_str(&rest[..start]); + let after = &rest[start + 1..]; + match after.find('}') { + Some(end) => { + let key = &after[..end]; + if let Some(v) = params.get(key) { + out.push_str(v); + } + rest = &after[end + 1..]; + } + None => { + out.push_str(&rest[start..]); + rest = ""; + } + } + } + out.push_str(rest); + out +} + +pub fn params(pairs: [(&str, String); N]) -> Params { + pairs.into_iter().map(|(k, v)| (k.to_owned(), v)).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn placeholders_are_filled() { + let p = params([("hostname", "a.test".into()), ("max", "64".into())]); + assert_eq!( + message("host.hostname.taken", &p), + "a.test is already a host." + ); + assert_eq!( + message("host.upstream.too_many", &p), + "One host can send traffic to at most 64 addresses." + ); + assert!(!message("token.revoked", &Params::new()).contains('{')); + } +} diff --git a/crates/control/src/records.rs b/crates/control/src/records.rs new file mode 100644 index 0000000..ac80160 --- /dev/null +++ b/crates/control/src/records.rs @@ -0,0 +1,201 @@ +// 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/. + +//! Apply records (one per user action: the history the UI shows, docs/ui-api.md §2.1) and the +//! apply journal (what a crash interrupted). +//! +//! The journal (`journal.json`) is written, atomically and durably, before every step that +//! changes the outside world, so after a crash control knows how far an apply got: +//! +//! | stage | what has happened | recovery | +//! |:--|:--|:--| +//! | `prepared` | commit object made, branch not moved | branch at base: nothing to undo; at the commit: as `committed` | +//! | `committed` | branch moved to the commit | revert commit, abort trial, drop trial files | +//! | `trial_written` | trial files written | same | +//! | `trial_loaded` | edge serves the trial (and reverts by itself at its deadline) | same | +//! | `confirmed` | edge confirmed the trial | promote trial files, record kept | +//! | `promoted` | files promoted | record kept | +//! | `reverting` | revert started | finish the revert | +//! +//! Throughout, `edge.json` and `caddy.json` only ever hold a config that passed its watch. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use crate::hostspec::HostSpec; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)] +pub struct Step { + /// `validate`, `compile`, `write`, `reload`, `watch` or `push`. + pub key: String, + /// `pending`, `running`, `done`, `failed` or `skipped`. + pub state: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, ToSchema)] +pub struct WatchHost { + pub hostname: String, + pub passed: u32, + pub failed: u32, + pub total: u32, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)] +pub struct Watch { + /// Unix seconds. + pub ends: u64, + pub hosts: Vec, +} + +/// Why an apply did not stay (or a detail of why it did). +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default, ToSchema)] +pub struct Reason { + pub code: String, + /// Plain English, from `messages`. + pub message: String, + pub hostname: Option, + pub upstream: Option, + pub field: Option, + pub count: Option, + pub of: Option, + /// Technical detail (core's text, edge's error); never a secret. + pub detail: Option, + #[serde(default)] + pub params: BTreeMap, +} + +/// One field problem, in the API error shape. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)] +pub struct FieldError { + pub code: String, + pub message: String, + pub field: Option, + pub params: BTreeMap, + pub detail: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct ApplyRecord { + pub id: String, + /// `add`, `edit`, `remove`, `undo`, `restore` or `share_links`. + pub kind: String, + pub summary: String, + pub hosts: Vec, + /// `queued`, `validating`, `applying`, `watching`, `kept`, `reverted`, `failed` or + /// `needs_attention`. + pub state: String, + pub steps: Vec, + pub created: u64, + pub started: Option, + pub finished: Option, + pub watch: Option, + pub reason: Option, + #[serde(default)] + pub errors: Vec, + /// Branch head when the apply started. + pub base: Option, + /// The commit of this change (none if it never got one). + pub commit: Option, + /// The commit that undid it, for reverted applies. + pub revert_commit: Option, + pub undo_of: Option, + pub restore_of: Option, + /// Token name of whoever asked. + pub actor: String, + /// What was tried, for "Edit and try again". + pub attempted_host: Option, + /// For undo: what it does ("Removes x"). + pub effect: Option, +} + +pub const STEP_KEYS: [&str; 6] = ["validate", "compile", "write", "reload", "watch", "push"]; + +impl ApplyRecord { + pub fn new( + id: String, + kind: &str, + summary: String, + hosts: Vec, + actor: &str, + t: u64, + ) -> ApplyRecord { + ApplyRecord { + id, + kind: kind.into(), + summary, + hosts, + state: "queued".into(), + steps: STEP_KEYS + .iter() + .map(|k| Step { + key: (*k).into(), + state: "pending".into(), + }) + .collect(), + created: t, + started: None, + finished: None, + watch: None, + reason: None, + errors: Vec::new(), + base: None, + commit: None, + revert_commit: None, + undo_of: None, + restore_of: None, + actor: actor.into(), + attempted_host: None, + effect: None, + } + } + + pub fn step(&mut self, key: &str, state: &str) { + if let Some(s) = self.steps.iter_mut().find(|s| s.key == key) { + s.state = state.into(); + } + } + + pub fn is_active(&self) -> bool { + matches!( + self.state.as_str(), + "queued" | "validating" | "applying" | "watching" + ) + } + + pub fn is_running(&self) -> bool { + matches!(self.state.as_str(), "validating" | "applying" | "watching") + } + + /// A kept change with a commit: something Undo can target. + pub fn is_kept_change(&self) -> bool { + self.state == "kept" && self.commit.is_some() + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Journal { + pub apply_id: String, + pub stage: String, + pub base: String, + pub commit: String, + pub edge_sha256: Option, + pub reason: Option, +} + +/// Push state, in `push.json`. +#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct PushState { + pub pushed: Option, + pub last_push_at: Option, + pub last_attempt_at: Option, + pub next_try_at: Option, + pub error_code: Option, + pub error_detail: Option, + #[serde(default)] + pub failures: u32, +} diff --git a/crates/control/src/repo.rs b/crates/control/src/repo.rs new file mode 100644 index 0000000..87c80c5 --- /dev/null +++ b/crates/control/src/repo.rs @@ -0,0 +1,563 @@ +// 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/. + +//! The routes repository: a bare git repository driven through the `git` binary. +//! +//! Why the `git` binary (not git2 or gix): pushing to Gitea over HTTPS or SSH is required, +//! and gix cannot push yet; git2 would bring libgit2 plus OpenSSL/libssh2 as C dependencies +//! into the Nix build, while `git` is one store path Mark already uses, with the same +//! behaviour he sees by hand. Control only uses plumbing with fixed arguments: commit ids are +//! checked to be hex before they reach a command line, file content goes through stdin, the +//! environment is cleared (no user or system git config, no hooks, no prompts), and objects +//! and refs are fsync'ed so a crash cannot lose a commit edge already runs. +//! +//! Control never reads a working tree: trees are read from git objects, so symbolic links or +//! files outside the repository cannot be smuggled in. A tree must have exactly the shape +//! `ianitor_core::routes` allows. + +use std::collections::BTreeMap; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::{Arc, Mutex}; + +use ianitor_core::routes::{self, EntryKind, SITE_FILE}; +use ianitor_core::{MAX_FILE_BYTES, ValidationError}; + +#[derive(Debug, thiserror::Error)] +pub enum RepoError { + #[error("git {op} failed: {message}")] + Git { op: String, message: String }, + #[error("the routes repository has files that do not belong there")] + Shape(Vec), + #[error("{0} is not a commit in the routes history")] + UnknownCommit(String), + #[error("{0}")] + Other(String), +} + +/// A commit id: 40 (SHA-1) or 64 (SHA-256) lowercase hex digits. +pub fn is_commit_id(s: &str) -> bool { + (s.len() == 40 || s.len() == 64) + && s.bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) +} + +/// The files of one routes tree: path → content. Paths are exactly `ianitor.toml` and +/// `hosts/.toml`. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RouteTree { + pub files: BTreeMap, +} + +impl RouteTree { + pub fn site(&self) -> &str { + self.files.get(SITE_FILE).map_or("", String::as_str) + } + + pub fn host(&self, hostname: &str) -> Option<&str> { + self.files + .get(&routes::host_path(hostname)) + .map(String::as_str) + } + + pub fn hostnames(&self) -> Vec { + self.files + .keys() + .filter_map(|p| p.strip_prefix("hosts/")?.strip_suffix(".toml")) + .map(str::to_owned) + .collect() + } + + pub fn set_host(&mut self, hostname: &str, contents: String) { + self.files.insert(routes::host_path(hostname), contents); + } + + pub fn remove_host(&mut self, hostname: &str) -> bool { + self.files.remove(&routes::host_path(hostname)).is_some() + } + + /// Load and validate with core. + pub fn model(&self) -> Result { + let hosts: Vec = self + .files + .iter() + .filter(|(p, _)| p.as_str() != SITE_FILE) + .map(|(p, c)| ianitor_core::SourceFile { + name: p, + contents: c, + }) + .collect(); + ianitor_core::load( + &ianitor_core::SourceFile { + name: SITE_FILE, + contents: self.site(), + }, + &hosts, + ) + } +} + +/// Facts about one commit. +#[derive(Debug, Clone)] +pub struct CommitInfo { + pub id: String, + pub parents: Vec, + pub time: u64, + pub subject: String, +} + +pub struct Repo { + git: PathBuf, + dir: PathBuf, + home: PathBuf, + branch: String, + cache: Mutex)>>, +} + +fn null_device() -> &'static str { + if cfg!(windows) { "NUL" } else { "/dev/null" } +} + +impl Repo { + /// Open (or create, with an empty `ianitor.toml`) the bare repository at `dir`. + pub fn open(git: &Path, dir: &Path, home: &Path, branch: &str) -> Result { + Repo::open_seeded(git, dir, home, branch, "") + } + + /// Like [`Repo::open`]; a new repository starts with `site` as its `ianitor.toml`. + pub fn open_seeded( + git: &Path, + dir: &Path, + home: &Path, + branch: &str, + site: &str, + ) -> Result { + let repo = Repo { + git: git.to_owned(), + dir: dir.to_owned(), + home: home.to_owned(), + branch: branch.to_owned(), + cache: Mutex::new(None), + }; + if !dir.join("HEAD").exists() { + std::fs::create_dir_all(dir).map_err(|e| RepoError::Other(e.to_string()))?; + repo.run_in( + None, + &[ + "init", + "--bare", + "--quiet", + &format!("--initial-branch={branch}"), + ], + Some(dir), + None, + &[], + )?; + } + if repo.head()?.is_none() { + let mut t = RouteTree::default(); + t.files.insert(SITE_FILE.into(), site.to_owned()); + let tree = repo.write_tree(&t, None)?; + let c = repo.commit(&tree, &[], "Start the routes repository", "Ianitor control")?; + repo.update_ref(&c, None)?; + } + Ok(repo) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + fn command(&self) -> Command { + let mut c = Command::new(&self.git); + c.env_clear(); + if let Some(p) = std::env::var_os("PATH") { + c.env("PATH", p); + } + #[cfg(windows)] + for v in ["SYSTEMROOT", "TEMP", "TMP"] { + if let Some(x) = std::env::var_os(v) { + c.env(v, x); + } + } + c.env("HOME", &self.home) + .env("LC_ALL", "C") + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_GLOBAL", null_device()) + .env("GIT_TERMINAL_PROMPT", "0") + .args([ + "-c", + &format!("core.hooksPath={}", null_device()), + "-c", + "core.fsync=all", + "-c", + "core.fsyncMethod=fsync", + "-c", + "protocol.file.allow=always", + ]); + c + } + + fn run_in( + &self, + git_dir: Option<&Path>, + args: &[&str], + cwd: Option<&Path>, + stdin: Option<&[u8]>, + env: &[(&str, &str)], + ) -> Result, RepoError> { + let mut c = self.command(); + if let Some(d) = git_dir { + c.env("GIT_DIR", d); + } + if let Some(d) = cwd { + c.current_dir(d); + } + for (k, v) in env { + c.env(k, v); + } + c.args(args) + .stdin(if stdin.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let op = args.first().copied().unwrap_or("").to_owned(); + let mut child = c.spawn().map_err(|e| RepoError::Git { + op: op.clone(), + message: format!("cannot run {}: {e}", self.git.display()), + })?; + if let (Some(data), Some(mut si)) = (stdin, child.stdin.take()) { + si.write_all(data).map_err(|e| RepoError::Git { + op: op.clone(), + message: e.to_string(), + })?; + } + let out = child.wait_with_output().map_err(|e| RepoError::Git { + op: op.clone(), + message: e.to_string(), + })?; + if !out.status.success() { + return Err(RepoError::Git { + op, + message: String::from_utf8_lossy(&out.stderr) + .trim() + .chars() + .take(500) + .collect(), + }); + } + Ok(out.stdout) + } + + fn git(&self, args: &[&str], stdin: Option<&[u8]>) -> Result, RepoError> { + self.run_in(Some(&self.dir), args, None, stdin, &[]) + } + + fn git_str(&self, args: &[&str]) -> Result { + Ok(String::from_utf8_lossy(&self.git(args, None)?) + .trim() + .to_owned()) + } + + fn reference(&self) -> String { + format!("refs/heads/{}", self.branch) + } + + /// The current commit of the branch. + pub fn head(&self) -> Result, RepoError> { + match self.git( + &["rev-parse", "--verify", "--quiet", &self.reference()], + None, + ) { + Ok(out) => { + let s = String::from_utf8_lossy(&out).trim().to_owned(); + Ok(is_commit_id(&s).then_some(s)) + } + Err(RepoError::Git { .. }) => Ok(None), + Err(e) => Err(e), + } + } + + pub fn head_required(&self) -> Result { + self.head()? + .ok_or_else(|| RepoError::Other("the routes branch has no commit".into())) + } + + /// Is `id` a commit reachable from the branch head? + pub fn in_history(&self, id: &str) -> Result { + if !is_commit_id(id) { + return Ok(false); + } + let head = self.head_required()?; + let mut c = self.command(); + c.env("GIT_DIR", &self.dir) + .args(["merge-base", "--is-ancestor", id, &head]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + let st = c.status().map_err(|e| RepoError::Git { + op: "merge-base".into(), + message: e.to_string(), + })?; + Ok(st.success()) + } + + pub fn info(&self, id: &str) -> Result { + if !is_commit_id(id) { + return Err(RepoError::UnknownCommit(id.chars().take(64).collect())); + } + let out = self + .git( + &[ + "show", + "-s", + "--format=%H%x00%P%x00%at%x00%s", + "--end-of-options", + id, + ], + None, + ) + .map_err(|_| RepoError::UnknownCommit(id.to_owned()))?; + let text = String::from_utf8_lossy(&out); + let mut f = text.trim_end_matches('\n').split('\0'); + let (Some(h), Some(p), Some(t), Some(s)) = (f.next(), f.next(), f.next(), f.next()) else { + return Err(RepoError::UnknownCommit(id.to_owned())); + }; + Ok(CommitInfo { + id: h.to_owned(), + parents: p + .split(' ') + .filter(|x| !x.is_empty()) + .map(str::to_owned) + .collect(), + time: t.parse().unwrap_or(0), + subject: s.to_owned(), + }) + } + + /// Read the tree of a commit, checking its shape. Cached for the last commit read. + pub fn tree(&self, commit: &str) -> Result, RepoError> { + if !is_commit_id(commit) { + return Err(RepoError::UnknownCommit(commit.chars().take(64).collect())); + } + if let Ok(c) = self.cache.lock() + && let Some((id, t)) = c.as_ref() + && id == commit + { + return Ok(t.clone()); + } + let listing = self.git(&["ls-tree", "-r", "-z", "--full-tree", "-l", commit], None)?; + let mut entries = Vec::new(); + for rec in listing.split(|b| *b == 0).filter(|r| !r.is_empty()) { + let rec = String::from_utf8_lossy(rec); + let (meta, path) = rec + .split_once('\t') + .ok_or_else(|| RepoError::Other("unexpected ls-tree output".into()))?; + let mut m = meta.split_whitespace(); + let (mode, kind, sha, size) = (m.next(), m.next(), m.next(), m.next()); + let entry_kind = match (mode, kind) { + (Some("100644"), Some("blob")) => EntryKind::File, + (Some("100755"), Some("blob")) => EntryKind::Executable, + (Some("120000"), _) => EntryKind::Symlink, + _ => EntryKind::Submodule, + }; + let size: usize = size.and_then(|s| s.parse().ok()).unwrap_or(0); + entries.push(( + path.to_owned(), + entry_kind, + sha.unwrap_or("").to_owned(), + size, + )); + } + routes::check_tree(entries.iter().map(|(p, k, _, _)| (p.as_str(), *k))) + .map_err(RepoError::Shape)?; + let mut tree = RouteTree::default(); + for (path, _, sha, size) in entries { + if size > MAX_FILE_BYTES { + return Err(RepoError::Shape(vec![ValidationError::FileTooLarge { + file: path, + max: MAX_FILE_BYTES, + }])); + } + if !is_commit_id(&sha) { + return Err(RepoError::Other("unexpected object id".into())); + } + let blob = self.git(&["cat-file", "blob", &sha], None)?; + let text = String::from_utf8(blob).map_err(|_| { + RepoError::Shape(vec![ValidationError::Syntax { + file: path.clone(), + line: None, + message: "the file is not UTF-8 text".into(), + }]) + })?; + tree.files.insert(path, text); + } + let tree = Arc::new(tree); + if let Ok(mut c) = self.cache.lock() { + *c = Some((commit.to_owned(), tree.clone())); + } + Ok(tree) + } + + /// Write the tree objects for `tree`; returns the tree id. + pub fn write_tree(&self, tree: &RouteTree, _base: Option<&str>) -> Result { + let mut hosts = Vec::new(); + let mut root = Vec::new(); + for (path, content) in &tree.files { + let sha = self.git_str_in(&["hash-object", "-w", "--stdin"], content.as_bytes())?; + if let Some(name) = path.strip_prefix("hosts/") { + hosts.extend_from_slice(format!("100644 blob {sha}\t{name}\0").as_bytes()); + } else { + root.extend_from_slice(format!("100644 blob {sha}\t{path}\0").as_bytes()); + } + } + if !hosts.is_empty() { + let sub = self.git_str_in(&["mktree", "-z"], &hosts)?; + root.extend_from_slice(format!("040000 tree {sub}\thosts\0").as_bytes()); + } + self.git_str_in(&["mktree", "-z"], &root) + } + + fn git_str_in(&self, args: &[&str], stdin: &[u8]) -> Result { + let out = self.git(args, Some(stdin))?; + let s = String::from_utf8_lossy(&out).trim().to_owned(); + if !is_commit_id(&s) { + return Err(RepoError::Other(format!( + "git {} gave no object id", + args[0] + ))); + } + Ok(s) + } + + /// Create a commit object (not yet on the branch). + pub fn commit( + &self, + tree: &str, + parents: &[&str], + message: &str, + author: &str, + ) -> Result { + let mut args = vec!["commit-tree", tree]; + for p in parents { + args.push("-p"); + args.push(p); + } + args.extend(["-F", "-"]); + let author: String = author + .chars() + .filter(|c| !c.is_control() && !"<>".contains(*c)) + .take(64) + .collect(); + let author = if author.trim().is_empty() { + "Ianitor control".to_owned() + } else { + author + }; + let env = [ + ("GIT_AUTHOR_NAME", author.as_str()), + ("GIT_AUTHOR_EMAIL", "ianitor@localhost"), + ("GIT_COMMITTER_NAME", "Ianitor control"), + ("GIT_COMMITTER_EMAIL", "ianitor@localhost"), + ]; + let out = self.run_in(Some(&self.dir), &args, None, Some(message.as_bytes()), &env)?; + let s = String::from_utf8_lossy(&out).trim().to_owned(); + if !is_commit_id(&s) { + return Err(RepoError::Other("git commit-tree gave no commit id".into())); + } + Ok(s) + } + + pub fn tree_id(&self, commit: &str) -> Result { + if !is_commit_id(commit) { + return Err(RepoError::UnknownCommit(commit.to_owned())); + } + self.git_str(&["rev-parse", "--verify", &format!("{commit}^{{tree}}")]) + } + + /// Move the branch to `new` only if it is still at `old` (compare and swap). + pub fn update_ref(&self, new: &str, old: Option<&str>) -> Result<(), RepoError> { + let zero = "0".repeat(new.len()); + let old = old.unwrap_or(&zero); + self.git(&["update-ref", &self.reference(), new, old], None) + .map(|_| ()) + } + + /// Number of commits in `to` that are not in `from` (`from` none: all of `to`). + pub fn count_between(&self, from: Option<&str>, to: &str) -> Result { + let range = match from { + Some(f) if is_commit_id(f) => format!("{f}..{to}"), + _ => to.to_owned(), + }; + Ok(self + .git_str(&["rev-list", "--count", &range])? + .parse() + .unwrap_or(0)) + } + + /// Push `commit` to the branch on `remote`. Credentials come through `GIT_ASKPASS` + /// (this binary's `askpass` mode), never on a command line or in a file. + pub async fn push( + &self, + remote: &str, + commit: &str, + askpass: Option<(PathBuf, String, PathBuf)>, + timeout: std::time::Duration, + ) -> Result<(), RepoError> { + if !is_commit_id(commit) { + return Err(RepoError::UnknownCommit(commit.to_owned())); + } + let std_cmd = self.command(); + let mut c = tokio::process::Command::from(std_cmd); + c.env("GIT_DIR", &self.dir); + if let Some((exe, user, file)) = askpass { + c.env("GIT_ASKPASS", exe) + .env("IANITOR_ASKPASS", "1") + .env("IANITOR_ASKPASS_USER", user) + .env("IANITOR_ASKPASS_FILE", file); + } + c.args([ + "push", + "--porcelain", + "--", + remote, + &format!("{commit}:{}", self.reference()), + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + let child = c.spawn().map_err(|e| RepoError::Git { + op: "push".into(), + message: e.to_string(), + })?; + let out = tokio::time::timeout(timeout, child.wait_with_output()) + .await + .map_err(|_| RepoError::Git { + op: "push".into(), + message: format!("no answer within {} s", timeout.as_secs()), + })? + .map_err(|e| RepoError::Git { + op: "push".into(), + message: e.to_string(), + })?; + if out.status.success() { + Ok(()) + } else { + let text = format!( + "{} {}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + Err(RepoError::Git { + op: "push".into(), + message: text.trim().chars().take(500).collect(), + }) + } + } +} diff --git a/crates/control/src/shares.rs b/crates/control/src/shares.rs new file mode 100644 index 0000000..e160823 --- /dev/null +++ b/crates/control/src/shares.rs @@ -0,0 +1,233 @@ +// 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/. + +//! Share links on control's side: minting, the list, stopping. +//! +//! Control keeps what it minted in `share-links.json` (never the token itself) and writes +//! the revocation file edge reads (`{"epoch": n, "deny": [ids]}`): ids of stopped links that +//! have not expired yet, and the epoch below which every token is refused ("stop all"). +//! The file lives outside git, is written atomically, and edge re-reads it when control asks +//! and on its own every 5 s. When control is down nothing can be stopped, but edge keeps +//! refusing what is already on the list, also across its own restarts. + +use std::path::{Path, PathBuf}; + +use ianitor_core::share::{self, LinkSpec, ShareId, ShareKey}; +use serde::{Deserialize, Serialize}; + +use crate::util::{now, random, read_json, write_json}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LinkRecord { + pub id: String, + pub hostname: String, + pub path_prefix: String, + pub epoch: u32, + pub created_at: u64, + pub expires_at: u64, + pub has_password: bool, + pub created_by: String, + pub stopped_at: Option, +} + +impl LinkRecord { + pub fn state(&self, epoch: u32, t: u64) -> &'static str { + if self.stopped_at.is_some() || self.epoch < epoch { + "stopped" + } else if t >= self.expires_at { + "expired" + } else { + "active" + } + } +} + +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ShareFile { + pub epoch: u32, + pub links: Vec, +} + +#[derive(Serialize)] +struct RevocationFile { + epoch: u32, + deny: Vec, +} + +/// Kept in the list this long after expiry or stop. +const KEEP_SECS: u64 = 30 * 86_400; +pub const MIN_EXPIRY: u64 = 3600; +pub const MAX_EXPIRY: u64 = 90 * 86_400; + +pub struct Shares { + path: PathBuf, + revocations: PathBuf, + lock: std::sync::Mutex<()>, +} + +pub struct Minted { + pub record: LinkRecord, + pub token: String, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum MintError { + Prefix, + Expiry, + PasswordShort, + PasswordLong, + Replaces, + Store(String), +} + +impl Shares { + pub fn new(state_dir: &Path, revocations: &Path) -> Shares { + Shares { + path: state_dir.join("share-links.json"), + revocations: revocations.to_owned(), + lock: std::sync::Mutex::new(()), + } + } + + pub fn load(&self) -> Result { + Ok(read_json(&self.path)?.unwrap_or_default()) + } + + fn save(&self, f: &mut ShareFile) -> Result<(), String> { + let t = now(); + f.links.retain(|l| { + let end = l.stopped_at.unwrap_or(l.expires_at).min(l.expires_at); + t < end.saturating_add(KEEP_SECS) + }); + write_json(&self.path, f)?; + self.write_revocations(f) + } + + /// Write the revocation file edge reads. + pub fn write_revocations(&self, f: &ShareFile) -> Result<(), String> { + let t = now(); + let mut deny: Vec = f + .links + .iter() + .filter(|l| l.stopped_at.is_some() && l.expires_at > t && l.epoch >= f.epoch) + .map(|l| l.id.clone()) + .collect(); + deny.sort(); + deny.truncate(9_999); + // Readable by edge (another user); it holds only random link ids. + let text = serde_json::to_vec(&RevocationFile { + epoch: f.epoch, + deny, + }) + .map_err(|e| e.to_string())?; + crate::util::write_atomic(&self.revocations, &text, 0o644) + .map_err(|e| format!("cannot write {}: {e}", self.revocations.display())) + } + + pub fn ensure_revocation_file(&self) -> Result<(), String> { + let _g = self + .lock + .lock() + .map_err(|_| "share store unavailable".to_owned())?; + let f = self.load()?; + self.write_revocations(&f) + } + + #[allow(clippy::too_many_arguments)] + pub fn mint( + &self, + key: &ShareKey, + hostname: &str, + prefix: &str, + expires_in: u64, + password: Option<&str>, + replaces: Option<&str>, + actor: &str, + ) -> Result { + let prefix = share::check_prefix(prefix).map_err(|_| MintError::Prefix)?; + if !(MIN_EXPIRY..=MAX_EXPIRY).contains(&expires_in) { + return Err(MintError::Expiry); + } + if let Some(p) = password { + let n = p.chars().count(); + if n < share::MIN_PASSWORD_CHARS { + return Err(MintError::PasswordShort); + } + if n > share::MAX_PASSWORD_CHARS { + return Err(MintError::PasswordLong); + } + } + let _g = self + .lock + .lock() + .map_err(|_| MintError::Store("share store unavailable".into()))?; + let mut f = self.load().map_err(MintError::Store)?; + if let Some(r) = replaces { + let Some(old) = f + .links + .iter_mut() + .find(|l| l.id == r && l.hostname == hostname) + else { + return Err(MintError::Replaces); + }; + old.stopped_at.get_or_insert(now()); + } + let id = ShareId(random::<16>().map_err(|e| MintError::Store(e.to_string()))?); + let t = now(); + let spec = LinkSpec { + id, + epoch: f.epoch, + expires_at: t + expires_in, + prefix: &prefix, + password, + }; + let token = + share::mint(key, hostname, &spec).map_err(|e| MintError::Store(e.to_string()))?; + let record = LinkRecord { + id: id.to_hex(), + hostname: hostname.to_owned(), + path_prefix: prefix.clone(), + epoch: f.epoch, + created_at: t, + expires_at: t + expires_in, + has_password: password.is_some(), + created_by: actor.to_owned(), + stopped_at: None, + }; + f.links.push(record.clone()); + self.save(&mut f).map_err(MintError::Store)?; + Ok(Minted { record, token }) + } + + /// Stop one link. `Ok(None)` when there is no such link. + pub fn stop(&self, id: &str) -> Result, String> { + let _g = self + .lock + .lock() + .map_err(|_| "share store unavailable".to_owned())?; + let mut f = self.load()?; + let Some(l) = f.links.iter_mut().find(|l| l.id == id) else { + return Ok(None); + }; + l.stopped_at.get_or_insert(now()); + let r = l.clone(); + self.save(&mut f)?; + Ok(Some(r)) + } + + /// Stop every link minted so far by raising the epoch. + pub fn stop_all(&self) -> Result { + let _g = self + .lock + .lock() + .map_err(|_| "share store unavailable".to_owned())?; + let mut f = self.load()?; + f.epoch = f.epoch.saturating_add(1); + let e = f.epoch; + self.save(&mut f)?; + Ok(e) + } +} diff --git a/crates/control/src/tokens.rs b/crates/control/src/tokens.rs new file mode 100644 index 0000000..d2e1435 --- /dev/null +++ b/crates/control/src/tokens.rs @@ -0,0 +1,242 @@ +// 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/. + +//! API tokens. A token is `ian__`: a 16-hex-digit id (for listing and lookup) +//! and 32 random bytes. Control stores only SHA-256 of the whole token, in `tokens.json` +//! (mode 0600), and compares in constant time. +//! +//! A fast hash is enough here: the secret has 256 bits of entropy, so nobody can find a +//! preimage by guessing, slow or fast; slow password hashes only help low-entropy secrets +//! that people pick. The comparison is constant-time anyway (it compares hashes of the +//! presented value, so even a timing leak would say nothing about a stored hash's preimage). +//! +//! The value is shown once, in the response that creates it (or by `ianitor-control token +//! create`), and never logged. Revoked and expired tokens stay listed so a script gets a +//! precise message ("revoked on …"). + +use std::path::{Path, PathBuf}; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use serde::{Deserialize, Serialize}; + +use crate::util::{ct_eq, hex, now, random, read_json, sha256_hex, write_json}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TokenRecord { + pub id: String, + pub name: String, + pub sha256: String, + pub created_at: u64, + pub expires_at: Option, + pub last_used_at: Option, + pub revoked_at: Option, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct TokenFile { + tokens: Vec, +} + +/// Why a presented token was refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Refusal { + Missing, + Unknown, + Expired(u64), + Revoked(u64), +} + +pub const MAX_TOKENS: usize = 200; +const LAST_USED_GRANULARITY: u64 = 60; + +pub struct Tokens { + path: PathBuf, + /// Serialises read-modify-write of the file inside this process. + lock: std::sync::Mutex<()>, +} + +pub fn valid_name(n: &str) -> bool { + let n = n.trim(); + !n.is_empty() + && n.chars().count() <= 64 + && n.chars() + .all(|c| c.is_ascii_alphanumeric() || " ._-".contains(c)) +} + +impl Tokens { + pub fn new(state_dir: &Path) -> Tokens { + Tokens { + path: state_dir.join("tokens.json"), + lock: std::sync::Mutex::new(()), + } + } + + fn load(&self) -> Result { + Ok(read_json(&self.path)?.unwrap_or_default()) + } + + fn save(&self, f: &TokenFile) -> Result<(), String> { + write_json(&self.path, f) + } + + /// Create a token; returns the record and the value (shown once). + pub fn create( + &self, + name: &str, + expires_at: Option, + ) -> Result<(TokenRecord, String), String> { + let _g = self + .lock + .lock() + .map_err(|_| "token store unavailable".to_owned())?; + if !valid_name(name) { + return Err("token.name".into()); + } + let mut f = self.load()?; + if f.tokens.iter().filter(|t| t.revoked_at.is_none()).count() >= MAX_TOKENS { + return Err("too many tokens; revoke some first".into()); + } + let id = hex(&random::<8>().map_err(|e| e.to_string())?); + let secret = URL_SAFE_NO_PAD.encode(random::<32>().map_err(|e| e.to_string())?); + let value = format!("ian_{id}_{secret}"); + let rec = TokenRecord { + id, + name: name.trim().to_owned(), + sha256: sha256_hex(value.as_bytes()), + created_at: now(), + expires_at, + last_used_at: None, + revoked_at: None, + }; + f.tokens.push(rec.clone()); + self.save(&f)?; + Ok((rec, value)) + } + + pub fn list(&self) -> Result, String> { + Ok(self.load()?.tokens) + } + + pub fn revoke(&self, id: &str) -> Result, String> { + let _g = self + .lock + .lock() + .map_err(|_| "token store unavailable".to_owned())?; + let mut f = self.load()?; + let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else { + return Ok(None); + }; + if t.revoked_at.is_none() { + t.revoked_at = Some(now()); + } + let r = t.clone(); + self.save(&f)?; + Ok(Some(r)) + } + + pub fn rename(&self, id: &str, name: &str) -> Result, String> { + let _g = self + .lock + .lock() + .map_err(|_| "token store unavailable".to_owned())?; + if !valid_name(name) { + return Err("token.name".into()); + } + let mut f = self.load()?; + let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else { + return Ok(None); + }; + t.name = name.trim().to_owned(); + let r = t.clone(); + self.save(&f)?; + Ok(Some(r)) + } + + /// Check a presented `Authorization` value. The token never appears in an error. + pub fn check(&self, header: Option<&str>) -> Result { + let Some(h) = header else { + return Err(Refusal::Missing); + }; + let Some(value) = h.strip_prefix("Bearer ").map(str::trim) else { + return Err(Refusal::Unknown); + }; + let id = value + .strip_prefix("ian_") + .and_then(|r| r.split_once('_')) + .map(|(id, _)| id) + .filter(|id| id.len() == 16) + .ok_or(Refusal::Unknown)?; + let _g = self.lock.lock().map_err(|_| Refusal::Unknown)?; + let mut f = self.load().map_err(|_| Refusal::Unknown)?; + let presented = sha256_hex(value.as_bytes()); + let Some(t) = f.tokens.iter_mut().find(|t| t.id == id) else { + return Err(Refusal::Unknown); + }; + if !ct_eq(t.sha256.as_bytes(), presented.as_bytes()) { + return Err(Refusal::Unknown); + } + if let Some(r) = t.revoked_at { + return Err(Refusal::Revoked(r)); + } + let n = now(); + if let Some(e) = t.expires_at + && n >= e + { + return Err(Refusal::Expired(e)); + } + let rec = t.clone(); + if t.last_used_at + .is_none_or(|l| n.saturating_sub(l) >= LAST_USED_GRANULARITY) + { + t.last_used_at = Some(n); + if let Err(e) = self.save(&f) { + log::warn!(target: "ianitor::tokens", "cannot record token use: {e}"); + } + } + Ok(rec) + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn create_check_revoke() { + let d = std::env::temp_dir().join(format!("ianitor-tokens-{}", std::process::id())); + let t = Tokens::new(&d); + let (rec, value) = t.create("laptop", None).unwrap(); + assert!(value.starts_with("ian_")); + let stored = std::fs::read_to_string(d.join("tokens.json")).unwrap(); + assert!(!stored.contains(&value[21..]), "only the hash is stored"); + assert_eq!( + t.check(Some(&format!("Bearer {value}"))).unwrap().id, + rec.id + ); + assert_eq!(t.check(None).unwrap_err(), Refusal::Missing); + assert_eq!(t.check(Some(&value)).unwrap_err(), Refusal::Unknown); + let mut wrong = value.clone(); + wrong.pop(); + wrong.push('x'); + assert_eq!( + t.check(Some(&format!("Bearer {wrong}"))).unwrap_err(), + Refusal::Unknown + ); + t.revoke(&rec.id).unwrap(); + assert!(matches!( + t.check(Some(&format!("Bearer {value}"))).unwrap_err(), + Refusal::Revoked(_) + )); + let (_, v2) = t.create("old", Some(1)).unwrap(); + assert_eq!( + t.check(Some(&format!("Bearer {v2}"))).unwrap_err(), + Refusal::Expired(1) + ); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/control/src/util.rs b/crates/control/src/util.rs new file mode 100644 index 0000000..00870b7 --- /dev/null +++ b/crates/control/src/util.rs @@ -0,0 +1,143 @@ +// 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/. + +//! Small shared helpers: time, randomness, hashing, atomic file writes. + +use std::io::Write; +use std::path::Path; +use std::time::{SystemTime, UNIX_EPOCH}; + +use ring::rand::{SecureRandom, SystemRandom}; +use serde::Serialize; +use serde::de::DeserializeOwned; + +pub fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +pub fn rfc3339(t: u64) -> String { + ianitor_core::time::rfc3339(t) +} + +pub fn random() -> Result<[u8; N], std::io::Error> { + let mut b = [0u8; N]; + SystemRandom::new() + .fill(&mut b) + .map_err(|_| std::io::Error::other("the system random generator failed"))?; + Ok(b) +} + +pub fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +pub fn sha256_hex(data: &[u8]) -> String { + hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref()) +} + +/// Compare two byte strings in time that depends only on their length. +pub fn ct_eq(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + let mut d = 0u8; + for (x, y) in a.iter().zip(b) { + d |= x ^ y; + } + std::hint::black_box(d) == 0 +} + +/// Write `data` to `path` so that readers see the old or the new content, never a mix, and +/// the new content survives a crash once this returns: temporary file in the same directory, +/// fsync, rename, fsync of the directory. +pub fn write_atomic(path: &Path, data: &[u8], mode: u32) -> std::io::Result<()> { + let dir = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + std::fs::create_dir_all(dir)?; + let mut name = path.file_name().unwrap_or_default().to_os_string(); + name.push(format!(".tmp-{}", std::process::id())); + let tmp = dir.join(name); + { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut opts, mode); + #[cfg(not(unix))] + let _ = mode; + let mut f = opts.open(&tmp)?; + f.write_all(data)?; + f.sync_all()?; + } + std::fs::rename(&tmp, path)?; + sync_dir(dir) +} + +/// Rename `from` to `to` atomically and durably. +pub fn rename_durable(from: &Path, to: &Path) -> std::io::Result<()> { + std::fs::rename(from, to)?; + sync_dir(to.parent().unwrap_or(Path::new("."))) +} + +pub fn sync_dir(dir: &Path) -> std::io::Result<()> { + #[cfg(unix)] + { + std::fs::File::open(dir)?.sync_all()?; + } + #[cfg(not(unix))] + let _ = dir; + Ok(()) +} + +pub fn remove_if_exists(path: &Path) -> std::io::Result<()> { + match std::fs::remove_file(path) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e), + _ => Ok(()), + } +} + +/// Read a JSON state file; `Ok(None)` when it does not exist. +pub fn read_json(path: &Path) -> Result, String> { + match std::fs::read(path) { + Ok(b) => serde_json::from_slice(&b) + .map(Some) + .map_err(|e| format!("{} is damaged: {e}", path.display())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(format!("cannot read {}: {e}", path.display())), + } +} + +/// Write a JSON state file atomically, readable by its owner only. +pub fn write_json(path: &Path, value: &T) -> Result<(), String> { + let mut text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?; + text.push(b'\n'); + write_atomic(path, &text, 0o600).map_err(|e| format!("cannot write {}: {e}", path.display())) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn constant_time_compare() { + assert!(ct_eq(b"abc", b"abc")); + assert!(!ct_eq(b"abc", b"abd")); + assert!(!ct_eq(b"abc", b"ab")); + } + + #[test] + fn atomic_write_replaces() { + let d = std::env::temp_dir().join(format!("ianitor-util-{}", std::process::id())); + let p = d.join("f.json"); + write_atomic(&p, b"one", 0o600).unwrap(); + write_atomic(&p, b"two", 0o600).unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"two"); + let _ = std::fs::remove_dir_all(&d); + } +}