diff --git a/.githooks/test-pre-commit.sh b/.githooks/test-pre-commit.sh index a7a239c..771e14a 100755 --- a/.githooks/test-pre-commit.sh +++ b/.githooks/test-pre-commit.sh @@ -65,8 +65,11 @@ expect_staged() { B='-----BEGIN' E='-----END' -mkdir -p "$WORK/../ianitor-hook-src.$$" && SRC="$WORK/../ianitor-hook-src.$$" -trap 'rm -rf "$WORK" "$SRC"' EXIT INT TERM +# An absolute path next to $WORK (not "$WORK/..", which no longer resolves once $WORK is gone), +# removed first. +SRC="$(dirname "$WORK")/ianitor-hook-src.$$" +mkdir -p "$SRC" || exit 2 +trap 'rm -rf "$SRC" "$WORK"' EXIT INT TERM printf '%s RSA PRIVATE KEY-----\nMIIBOgIBAAJBAK\n%s RSA PRIVATE KEY-----\n' "$B" "$E" > "$SRC/pem" head -c 6291456 /dev/zero | tr '\000' 'a' > "$SRC/six-mb" diff --git a/Cargo.lock b/Cargo.lock index be5f6ae..76ea7d2 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" @@ -1005,15 +1055,37 @@ dependencies = [ [[package]] name = "ianitor-control" version = "0.1.0" +dependencies = [ + "axum", + "base64 0.22.1", + "bytes", + "http", + "ianitor-core", + "ianitor-edge", + "ianitor-testkit", + "log", + "rcgen", + "ring", + "rustls", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio", + "toml", + "utoipa", +] [[package]] name = "ianitor-core" version = "0.1.0" dependencies = [ + "base64 0.22.1", + "ring", "serde", "serde_json", "thiserror 2.0.21", "toml", + "unicode-normalization", "url", ] @@ -1021,6 +1093,7 @@ dependencies = [ name = "ianitor-diff" version = "0.1.0" dependencies = [ + "ianitor-control", "ianitor-core", "ianitor-edge", "ianitor-testkit", @@ -1036,12 +1109,17 @@ dependencies = [ "arc-swap", "async-trait", "bytes", + "form_urlencoded", "http", + "http-body-util", + "hyper", + "hyper-util", "ianitor-core", "ianitor-testkit", "instant-acme", "log", "pingora", + "ring", "rustls", "rustls-pki-types", "serde", @@ -1192,6 +1270,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", + "serde", + "serde_core", ] [[package]] @@ -1343,6 +1423,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" @@ -1358,6 +1444,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" @@ -2311,6 +2403,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" @@ -2320,6 +2423,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" @@ -2488,6 +2603,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" @@ -2608,6 +2729,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.54.1" @@ -2733,6 +2860,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" @@ -2798,6 +2946,15 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "unsafe-libyaml" version = "0.2.11" @@ -2843,6 +3000,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/Cargo.toml b/Cargo.toml index 2259be2..2df601d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/ [workspace.package] version = "0.1.0" edition = "2024" -rust-version = "1.88" +rust-version = "1.89" license = "MPL-2.0" publish = false @@ -18,6 +18,8 @@ serde_json = "1.0.145" toml = "1.2.1" thiserror = "2.0.17" url = "2.5.7" +ring = "0.17.14" +base64 = "0.22.1" tokio = { version = "1.48", features = ["full"] } bytes = "1.10" http = "1.3" diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 8b31672..3929d18 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -1,15 +1,41 @@ [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" +[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 mode only: a throw-away CA for the dev hosts (the Domi CA arrives in phase 3). +rcgen.workspace = true + +[dev-dependencies] +ianitor-testkit.workspace = true +ianitor-edge.workspace = true +rustls.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..a6d12fe --- /dev/null +++ b/crates/control/src/api/handlers.rs @@ -0,0 +1,1296 @@ +// 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'-') + { + // Not a hostname: say so without repeating what was sent. + let mut e = ApiError::new(StatusCode::NOT_FOUND, "host.not_found", Params::new()); + e.body.message = "There is no such host.".into(); + return Err(e); + } + 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_begin(k, &fp)? + { + return Ok(replay(st, stored)); + } + let rec = match st.ctl.submit(change, base_rev, &actor.name) { + Ok(r) => r, + Err(f) => { + if let Some(k) = &key { + st.idem_finish(k, &fp, None); + } + return Err(f.into()); + } + }; + if let Some(k) = &key { + st.idem_finish(k, &fp, Some(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), + Stored::Pending => { + ApiError::new(StatusCode::CONFLICT, "request.in_progress", Params::new()) + .retry(1) + .into_response() + } + } +} + +// ---------------------------------------------------------------- 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_begin(k, &fp)? + { + return Ok(replay(&st, s)); + } + // In its own task: a client that goes away mid-request neither cancels the mint nor + // leaves its Idempotency-Key reserved. + let task = tokio::spawn({ + let (st, actor, key, fp) = (st.clone(), actor.clone(), key.clone(), fp.clone()); + let value = body.value; + async move { + let out = mint_inner(&st, &actor, &hostname, value).await; + if let Some(k) = &key { + st.idem_finish( + k, + &fp, + out.as_ref().ok().map(|v| Stored::Json(201, v.clone())), + ); + } + out + } + }); + let out = match task.await { + Ok(out) => out, + Err(e) => { + if let Some(k) = &key { + st.idem_finish(k, &fp, None); + } + Err(ApiError::internal(e.to_string())) + } + }; + out.map(|v| json(StatusCode::CREATED, &v)) +} + +async fn mint_inner( + st: &AppState, + actor: &Actor, + hostname: &str, + b: MintBody, +) -> Result { + let hostname = hostname.to_owned(); + 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 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::TooMany => { + ApiError::new(StatusCode::CONFLICT, "share.too_many", Params::new()) + } + 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())]), + ), + }), + }; + serde_json::to_value(&out).map_err(|e| ApiError::internal(e.to_string())) +} + +/// 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..6edfd46 --- /dev/null +++ b/crates/control/src/api/mod.rs @@ -0,0 +1,521 @@ +// 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 { + /// The first request with this key is still being handled. + Pending, + Apply(String), + Json(u16, serde_json::Value), +} + +/// Most Idempotency-Keys held at once (each for 24 h). +const MAX_IDEM_KEYS: usize = 2000; + +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(()) + } + + /// Start a request with an Idempotency-Key, atomically: `Ok(Some)` replays an earlier + /// answer, `Ok(None)` reserves the key (finish with [`AppState::idem_finish`]), `Err` when + /// the key was used for another request, is still in progress, or no key can be held. + pub fn idem_begin(&self, key: &str, fingerprint: &str) -> Result, ApiError> { + let mut m = self + .idem + .lock() + .map_err(|_| ApiError::internal("idempotency store"))?; + let t = now(); + match m.get(key) { + Some((fp, _, at)) if t.saturating_sub(*at) < 86_400 && fp != fingerprint => { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "request.idempotency", + Params::new(), + )); + } + Some((_, Stored::Pending, at)) if t.saturating_sub(*at) < 86_400 => { + return Err(ApiError::new( + StatusCode::CONFLICT, + "request.in_progress", + Params::new(), + ) + .retry(1)); + } + Some((_, Stored::Apply(id), at)) if t.saturating_sub(*at) < 86_400 => { + return Ok(Some(Stored::Apply(id.clone()))); + } + Some((_, Stored::Json(s, v), at)) if t.saturating_sub(*at) < 86_400 => { + return Ok(Some(Stored::Json(*s, v.clone()))); + } + _ => {} + } + if m.len() >= MAX_IDEM_KEYS { + m.retain(|_, (_, _, at)| t.saturating_sub(*at) < 86_400); + } + if m.len() >= MAX_IDEM_KEYS { + return Err(ApiError::new( + StatusCode::TOO_MANY_REQUESTS, + "rate.limited", + Params::new(), + ) + .retry(60)); + } + m.insert(key.to_owned(), (fingerprint.to_owned(), Stored::Pending, t)); + Ok(None) + } + + /// Finish a reserved key: remember the answer, or (on `None`, a refusal) free the key. + pub fn idem_finish(&self, key: &str, fingerprint: &str, s: Option) { + if let Ok(mut m) = self.idem.lock() { + match s { + Some(s) => { + m.insert(key.to_owned(), (fingerprint.to_owned(), s, now())); + } + None => { + m.remove(key); + } + } + } + } +} + +// ---------------------------------------------------------------- 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 `") { + // The name is the sender's: repeat it only if it is a plain field name. + let plain = !f.is_empty() + && f.len() <= 64 + && f.bytes() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_'); + let shown = if plain { + f + } else { + "(a field name)".to_owned() + }; + let mut err = ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "request.body_unknown_field", + messages::params([("field", shown.clone())]), + ); + err.body.field = plain.then_some(shown); + 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()) + .map(str::to_owned); + // The token store takes a file lock: off the async threads. + let ctl = st.ctl.clone(); + let checked = tokio::task::spawn_blocking(move || ctl.tokens.check(auth.as_deref())) + .await + .unwrap_or(Err(Refusal::Unknown)); + let tok = checked.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..b85bbe4 --- /dev/null +++ b/crates/control/src/crash.rs @@ -0,0 +1,44 @@ +// 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. +//! +//! `IANITOR_TEST_FAIL_WRITE=` makes every write of a state file with that name +//! fail, as on a full disk (fault injection for the same tests). + +/// 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(); + } +} + +/// Fail a state-file write when `IANITOR_TEST_FAIL_WRITE` names this file. +pub fn fail_write(path: &std::path::Path) -> Result<(), String> { + match ( + std::env::var_os("IANITOR_TEST_FAIL_WRITE"), + path.file_name(), + ) { + (Some(want), Some(name)) if want == name => Err(format!( + "cannot write {}: IANITOR_TEST_FAIL_WRITE (injected)", + path.display() + )), + _ => Ok(()), + } +} diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs new file mode 100644 index 0000000..70930e6 --- /dev/null +++ b/crates/control/src/dev.rs @@ -0,0 +1,237 @@ +// 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}; + +/// Hosts that get a certificate from the dev CA, so `tls = "domi"` works for them. +const DEV_HOSTS: [&str; 3] = ["app.dev.test", "wiki.dev.test", "photos.dev.test"]; + +/// A throw-away CA and certificates for [`DEV_HOSTS`] in `certs/`; the CA as `dev-ca.crt`. +fn dev_certs(dir: &Path) -> Result<(), String> { + use rcgen::{ + BasicConstraints, CertificateParams, DnType, IsCa, Issuer, KeyPair, KeyUsagePurpose, + }; + let e = |x: rcgen::Error| x.to_string(); + let ca_key = KeyPair::generate().map_err(e)?; + let mut ca = CertificateParams::new(Vec::::new()).map_err(e)?; + ca.distinguished_name + .push(DnType::CommonName, "Ianitor dev CA"); + ca.is_ca = IsCa::Ca(BasicConstraints::Constrained(0)); + ca.key_usages = vec![ + KeyUsagePurpose::KeyCertSign, + KeyUsagePurpose::DigitalSignature, + ]; + let ca_cert = ca.self_signed(&ca_key).map_err(e)?; + std::fs::write(dir.join("certs/dev-ca.crt"), ca_cert.pem()).map_err(|x| x.to_string())?; + let issuer = Issuer::new(ca, ca_key); + for h in DEV_HOSTS { + let key = KeyPair::generate().map_err(e)?; + let mut p = CertificateParams::new(vec![h.to_owned()]).map_err(e)?; + p.distinguished_name.push(DnType::CommonName, h); + let cert = p.signed_by(&key, &issuer).map_err(e)?; + std::fs::write(dir.join(format!("certs/{h}.crt")), cert.pem()) + .map_err(|x| x.to_string())?; + write_atomic( + &dir.join(format!("certs/{h}.key")), + key.serialize_pem().as_bytes(), + 0o600, + ) + .map_err(|x| x.to_string())?; + } + Ok(()) +} + +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())?; + } + dev_certs(&dir)?; + 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). tls = \"domi\" works for {}; CA: {}", + b.display(), + DEV_HOSTS.join(", "), + dir.join("certs/dev-ca.crt").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..19ccbeb --- /dev/null +++ b/crates/control/src/engine.rs @@ -0,0 +1,1877 @@ +// 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>, + /// False while the pause is only in memory (paused.json could not be written). + pause_saved: std::sync::atomic::AtomicBool, + /// 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), + pause_saved: std::sync::atomic::AtomicBool::new(true), + 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()) + } + + /// Pause changes. Always in memory; `Err` when it could not be saved, and then the + /// caller must keep the journal so a restart still knows. + fn pause(&self, r: Reason) -> Result<(), String> { + let saved = write_json(&self.cfg.state_dir.join("paused.json"), &r); + self.pause_saved + .store(saved.is_ok(), std::sync::atomic::Ordering::SeqCst); + if let Ok(mut p) = self.paused.lock() { + *p = Some(r); + } + saved + } + + /// Is the current pause on disk? If not, try to write it now. + fn pause_durable(&self) -> bool { + use std::sync::atomic::Ordering; + let Some(p) = self.paused() else { + return true; + }; + if self.pause_saved.load(Ordering::SeqCst) { + return true; + } + match write_json(&self.cfg.state_dir.join("paused.json"), &p) { + Ok(()) => { + self.pause_saved.store(true, Ordering::SeqCst); + log::info!(target: "ianitor::apply", "the pause is saved now"); + true + } + Err(e) => { + log::error!(target: "ianitor::apply", "the pause still cannot be saved: {e}"); + false + } + } + } + + /// The way out of `control.files_unwritten`. Runs only in the apply worker, under the + /// apply lock, so no apply is in flight: write both files from the branch head, make edge + /// run exactly that (reload and compare its hash), and drop the journal only if it is the + /// `confirmed` journal of the apply that caused the pause. + async fn retry_files(&self) -> bool { + let Some(p) = self + .paused() + .filter(|p| p.code == "control.files_unwritten") + else { + return false; + }; + let written = self + .head_model() + .map_err(|f| f.reason.message) + .and_then(|(_, _, m)| { + let (e, c) = self.compile(&m).map_err(|f| f.reason.message)?; + write_atomic(&self.cfg.edge.config, e.as_bytes(), 0o644) + .and_then(|_| write_atomic(&self.cfg.caddy.config, c.as_bytes(), 0o644)) + .map_err(|e| e.to_string())?; + Ok(crate::util::sha256_hex(e.as_bytes())) + }); + let want = match written { + Ok(w) => w, + Err(e) => { + log::error!(target: "ianitor::apply", "the config files still cannot be written: {e}"); + return false; + } + }; + if self.edge.attached() { + match self.edge.reload().await { + Ok(got) if got == want => {} + Ok(got) => { + log::error!(target: "ianitor::apply", "edge reloaded to {got}, not to the files just written ({want}); still paused"); + return false; + } + Err(e) => { + log::error!(target: "ianitor::apply", "the files are written, but edge did not reload them ({e}); still paused"); + return false; + } + } + } + let cause = p.params.get("apply_id").cloned(); + match read_json::(&self.journal_path()) { + Ok(Some(j)) if Some(&j.apply_id) == cause.as_ref() && j.stage == "confirmed" => { + for t in [self.cfg.trial_path(), self.cfg.caddy_trial_path()] { + if let Err(e) = remove_if_exists(&t) { + log::warn!(target: "ianitor::apply", "cannot remove {}: {e}", t.display()); + } + } + self.clear_journal(); + } + Ok(Some(j)) => { + log::warn!(target: "ianitor::apply", "leaving the journal of apply {} (stage {}) alone", j.apply_id, j.stage); + } + Ok(None) => {} + Err(e) => log::error!(target: "ianitor::apply", "{e}"), + } + log::info!(target: "ianitor::apply", "the config files are written and edge runs them; changes resume"); + self.unpause(); + true + } + + fn unpause(&self) { + if let Err(e) = remove_if_exists(&self.cfg.state_dir.join("paused.json")) { + log::error!(target: "ianitor::apply", "cannot remove paused.json ({e}); the next start re-checks it"); + } + if let Ok(mut p) = self.paused.lock() { + *p = None; + } + } + + /// While paused, only a Restore of a kept version may run: it is the way out of + /// `needs_attention` (docs/ui-api.md §3.2). + /// + /// A Restore runs only once the pause is saved: until then the `reverting` journal is the + /// only record of it on disk, and a Restore would replace that journal with its own. + /// `in_worker` is false when a request is first checked: a change that the worker may + /// still let through (after it retried the files) is queued rather than refused. + fn paused_for(&self, change: &Change, in_worker: bool) -> Option { + let p = self.paused()?; + if !in_worker && p.code == "control.files_unwritten" { + return None; + } + let restorable = matches!( + p.code.as_str(), + "apply.needs_attention" | "control.files_unwritten" + ); + if !(matches!(change, Change::Restore { .. }) && restorable) { + return Some(p); + } + if self.pause_durable() { + return None; + } + Some(Reason { + message: format!( + "{} Ianitor cannot save this pause to disk, so even Restore waits until it can.", + p.message + ), + ..p + }) + } + + 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_for(&change, false) { + 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"); + }); + self.retry_files().await; + if let Some(p) = self.paused_for(&job.change, true) { + 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) { + // The journal still says `prepared` with this commit, which recovery also reverts. + return self + .revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed") + .await; + } + 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; + } + let push_step = self.push_step(); + self.update(&id, |r| { + r.step("write", "done"); + r.step("reload", "skipped"); + r.step("watch", "skipped"); + r.step("push", push_step); + }); + 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(); + if let Err(e) = self.journal(&j) { + return self + .revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed") + .await; + } + 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 want = crate::util::sha256_hex(edge_text.as_bytes()); + if sha != want { + let r = reason( + "apply.failed.reload", + messages::params([("engine", "Pingora".into())]), + ); + let detail = format!( + "edge loaded a trial with SHA-256 {sha}, not the one control wrote ({want})" + ); + return self + .revert( + &id, + &j, + Reason { + detail: Some(detail), + ..r + }, + "failed", + ) + .await; + } + if let Err(e) = self.journal(&j) { + return self + .revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed") + .await; + } + 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(); + if let Err(e) = self.journal(&j) { + // Without a `confirmed` journal a crash would revert a kept change; so revert now + // (the revert also brings edge back to edge.json). + return self + .revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed") + .await; + } + crash::point("confirmed"); + let promoted = self.promote().or_else(|e| { + log::error!(target: "ianitor::apply", "cannot promote the trial files ({e}); writing them again"); + write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644) + .and_then(|_| write_atomic(&self.cfg.caddy.config, caddy_text.as_bytes(), 0o644)) + }); + if let Err(e) = promoted { + // Edge serves the change and the repository has it, but the files do not: keep + // the journal at `confirmed` (recovery promotes) and pause so nothing overwrites it. + log::error!(target: "ianitor::apply", "cannot write the config files: {e}"); + let mut p = reason("control.files_unwritten", Params::new()); + p.detail = Some(e.to_string()); + p.params.insert("apply_id".into(), id.clone()); + if let Err(pe) = self.pause(p) { + log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it"); + } + let push_step = self.push_step(); + self.update(&id, |r| r.step("push", push_step)); + self.finish(&id, "kept", Some(kept_reason), Vec::new()); + return; + } + j.stage = "promoted".into(); + if let Err(e) = self.journal(&j) { + // Files are promoted; a stale `confirmed` journal only makes recovery promote again. + log::error!(target: "ianitor::apply", "{e}"); + } + crash::point("promoted"); + // Record first, journal last: a crash in between is finished again by recovery. + let push_step = self.push_step(); + self.update(&id, |r| r.step("push", push_step)); + self.finish(&id, "kept", Some(kept_reason), Vec::new()); + self.clear_journal(); + if self.paused().is_some() && matches!(job.change, Change::Restore { .. }) { + log::info!(target: "ianitor::apply", "a kept Restore ends the pause"); + self.unpause(); + } + self.push_wake.notify_one(); + } + + /// The push step of a kept apply: pending, or skipped when there is no remote. + fn push_step(&self) -> &'static str { + if self.cfg.routes.remote.is_some() { + "pending" + } else { + "skipped" + } + } + + 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()); + if let Err(e) = self.journal(&j) { + // The earlier stage stays on disk; recovery reverts from it too. + log::error!(target: "ianitor::apply", "{e}"); + } + crash::point("reverting"); + match self.finish_revert(&j).await { + Ok(rev) => { + self.update(id, |r| r.revert_commit = rev.or(r.revert_commit.clone())); + self.finish(id, state, Some(why), Vec::new()); + self.clear_journal(); + } + 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)); + // The journal stays at `reverting`: a restart retries the revert, and even + // if the pause below cannot be saved, it never loads the unverified head. + if let Err(pe) = self.pause(r.clone()) { + log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it"); + } + 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())?; + } + // Edge must now run edge.json, the last good config. If it confirmed the trial after + // all (an answer lost on the way) it does not: reload it. If edge cannot be asked, + // this is not a finished revert (a restart asks again). + if self.edge.attached() { + let disk = std::fs::read(&self.cfg.edge.config) + .map_err(|e| format!("cannot read {}: {e}", self.cfg.edge.config.display()))?; + let want = crate::util::sha256_hex(&disk); + let mut status = self.edge.status().await; + for _ in 0..5 { + if status.is_ok() { + break; + } + tokio::time::sleep(Duration::from_secs(1)).await; + status = self.edge.status().await; + } + let st = status.map_err(|e| format!("cannot see which config edge runs: {e}"))?; + if st.trial.is_some() || st.config_sha256 != want { + log::warn!(target: "ianitor::apply", "edge does not run edge.json; reloading it"); + if st.trial.is_some() + && let Err(e) = self.edge.abort().await + { + log::warn!(target: "ianitor::apply", "edge did not abort its trial: {e}"); + } + let got = self + .edge + .reload() + .await + .map_err(|e| format!("edge did not reload edge.json: {e}"))?; + if got != want { + return Err("edge reloaded, but not to edge.json".into()); + } + } + } + Ok(rev) + } + + // ------------------------------------------------------------ recovery + + async fn recover(&self) -> Result<(), String> { + let _lock = self.apply_lock.lock().await; + let journal: Option = read_json(&self.journal_path())?; + let mut keep_paused = false; + 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.finish( + &j.apply_id, + "failed", + Some(reason("apply.interrupted.queued", Params::new())), + Vec::new(), + ); + self.clear_journal(); + } + "confirmed" | "promoted" => { + if let Err(e) = self.promote() { + // Start anyway, paused: edge serves the change, the files lag behind. + log::error!(target: "ianitor::apply", "cannot promote the trial files at start: {e}"); + let mut p = reason("control.files_unwritten", Params::new()); + p.detail = Some(e.to_string()); + p.params.insert("apply_id".into(), j.apply_id.clone()); + if let Err(pe) = self.pause(p) { + log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it"); + } + keep_paused = true; + self.finish(&j.apply_id, "kept", None, Vec::new()); + } else { + let push_step = self.push_step(); + self.update(&j.apply_id, |r| r.step("push", push_step)); + let kept = self + .record(&j.apply_id) + .and_then(|r| r.reason.filter(|x| x.code.starts_with("apply.kept"))); + self.finish(&j.apply_id, "kept", kept, Vec::new()); + self.clear_journal(); + } + } + _ => { + 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.or(r.revert_commit.clone()); + }); + // 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()); + self.clear_journal(); + if self + .paused() + .is_some_and(|p| p.code == "apply.needs_attention") + { + log::info!(target: "ianitor::apply", "the interrupted revert is done; changes resume"); + self.unpause(); + } + } + Err(e) => { + // Journal kept: the next start tries again. + let mut r = reason("apply.needs_attention", Params::new()); + r.detail = Some(e); + if let Err(pe) = self.pause(r.clone()) { + log::error!(target: "ianitor::apply", "cannot save the pause: {pe}"); + } + 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 Err(e) = self.edge.abort().await + { + log::warn!(target: "ianitor::control", "edge did not abort a leftover trial: {e}"); + } + // An apply whose revert failed left an unverified commit at the branch head: edge keeps + // the last good config until a Restore. Any other pause is re-checked now. + if self + .paused() + .is_some_and(|p| p.code == "apply.needs_attention") + { + log::warn!(target: "ianitor::control", "changes are paused (needs attention); edge keeps the last good config until a Restore"); + } else if keep_paused { + log::warn!(target: "ianitor::control", "changes are paused until the config files can be written"); + } else { + self.unpause(); + 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. Only at start, under + /// the apply lock (from `recover`). The files and the journal are written only by the apply + /// worker (`run`, `revert`, `retry_files`) and by `recover`, all under that lock. + 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); + if let Err(e) = self.pause(f.reason) { + log::error!(target: "ianitor::control", "cannot save the pause: {e}"); + } + 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()); + if let Err(e) = self.pause(r) { + log::error!(target: "ianitor::control", "cannot save the pause: {e}"); + } + 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..063e2b3 100644 --- a/crates/control/src/main.rs +++ b/crates/control/src/main.rs @@ -2,11 +2,241 @@ // 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; + } + // Answer only the password prompt; anything else (a passphrase, a host key question) + // gets no answer, so the push fails instead of handing out the token. + if !prompt.starts_with("Password for") { + eprintln!("ianitor-control askpass: not answering {prompt:?}"); + return ExitCode::FAILURE; + } + 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()) +} + +/// The token files must stay owned by the user control runs as: refuse to touch them as +/// anyone else (typically root), instead of leaving root-owned files control cannot open. +#[cfg(unix)] +fn same_owner(dir: &std::path::Path) -> Result<(), String> { + use std::os::unix::fs::MetadataExt; + let existing = dir + .ancestors() + .find(|p| p.is_dir()) + .ok_or_else(|| format!("no part of {} exists", dir.display()))?; + let owner = std::fs::metadata(existing) + .map_err(|e| format!("cannot read {}: {e}", existing.display()))? + .uid(); + // Who we are, without libc: the owner of a file we create (in the temp dir, so nothing is + // created in the state dir by the wrong user). + let probe = std::env::temp_dir().join(format!(".ianitor-owner-probe-{}", std::process::id())); + // create_new: never follows or reuses a file someone else put there. + let me = std::fs::File::create_new(&probe) + .and_then(|f| f.metadata()) + .map(|m| m.uid()); + if me.is_ok() { + let _ = std::fs::remove_file(&probe); + } + let me = me.map_err(|e| format!("cannot create a probe file to learn who runs this: {e}"))?; + if me == 0 && !dir.is_dir() { + return Err(format!( + "{} does not exist; create it as the user control runs as (or run this as that user), not as root", + dir.display() + )); + } + if me != owner { + return Err(format!( + "{} belongs to uid {owner}, but this runs as uid {me}; run it as that user (e.g. sudo -u ianitor ianitor-control token ...)", + existing.display() + )); + } + Ok(()) +} + +#[cfg(not(unix))] +fn same_owner(_: &std::path::Path) -> Result<(), String> { + Ok(()) +} + +fn token(args: &[String]) -> Result<(), String> { + let dir = state_dir(args)?; + // Check the owner before creating anything: the nearest existing ancestor must belong to + // whoever runs this (so root does not create a state dir control cannot use). + same_owner(&dir)?; + 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..945f222 --- /dev/null +++ b/crates/control/src/messages.rs @@ -0,0 +1,283 @@ +// 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.too_many" => { + "There are 2,000 active share links already. Stop some, or stop all, then try again." + } + "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.files_unwritten" => { + "The change is live, but Ianitor could not save the proxy settings to disk. Changes are paused until Ianitor restarts and saves them." + } + "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.in_progress" => { + "The first request with this Idempotency-Key is still being handled. Try again in a moment." + } + "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..73122a5 --- /dev/null +++ b/crates/control/src/repo.rs @@ -0,0 +1,561 @@ +// 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 + } + + 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..bcea803 --- /dev/null +++ b/crates/control/src/shares.rs @@ -0,0 +1,309 @@ +// 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::collections::BTreeSet; +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; +/// Most active links at once. +pub const MAX_ACTIVE: usize = 2000; +/// Most ids edge takes on its deny list (edge refuses 10,000 and more). +const MAX_DENY: usize = 9_999; + +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, + /// More active links than [`MAX_ACTIVE`]. + TooMany, + 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()) + } + + /// The revocation file as edge has it now, if it can be read. + fn published(&self) -> Option<(u32, BTreeSet)> { + #[derive(Deserialize)] + struct Published { + epoch: u32, + deny: Vec, + } + let p: Published = serde_json::from_slice(&std::fs::read(&self.revocations).ok()?).ok()?; + Some((p.epoch, p.deny.into_iter().collect())) + } + + /// The records, with the epoch never below the published one (records lost or restored + /// from an older backup must not bring stopped links back). + fn load_reconciled(&self) -> Result { + let mut f = self.load()?; + if let Some((epoch, _)) = self.published() + && epoch > f.epoch + { + log::warn!(target: "ianitor::share", "share-link records are behind the published revocations (epoch {} < {epoch}); continuing from {epoch}", f.epoch); + f.epoch = epoch; + } + Ok(f) + } + + fn save(&self, f: &mut ShareFile) -> Result<(), String> { + let t = now(); + // Kept at least until they expire: a stopped link must stay on the deny list as long + // as its token would otherwise work. + f.links + .retain(|l| t < l.expires_at.saturating_add(KEEP_SECS)); + let deny = self.reconcile(f); + write_json(&self.path, f)?; + self.publish(f.epoch, deny) + } + + /// The deny list for `f`, raising `f.epoch` when the list cannot be kept whole: + /// - a published id that the records cannot account for (stopped link lost from the + /// records) is never just dropped: the epoch goes up, which stops every older link; + /// - a list longer than edge accepts also raises the epoch, instead of being cut short. + fn reconcile(&self, f: &mut ShareFile) -> Vec { + let t = now(); + let published = self.published(); + if let Some((epoch, _)) = &published { + f.epoch = f.epoch.max(*epoch); + } + let deny_for = |f: &ShareFile| -> Vec { + let mut d: 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(); + d.sort(); + d + }; + let mut deny = deny_for(f); + if let Some((epoch, old)) = published + && epoch == f.epoch + { + let accounted = |id: &String| { + deny.binary_search(id).is_ok() + || f.links + .iter() + .any(|l| &l.id == id && (l.expires_at <= t || l.epoch < f.epoch)) + }; + if !old.iter().all(accounted) { + log::warn!(target: "ianitor::share", "stopped links are missing from the records; raising the epoch, which stops every earlier link"); + f.epoch = f.epoch.saturating_add(1); + deny = deny_for(f); + } + } + if deny.len() > MAX_DENY { + log::warn!(target: "ianitor::share", "more than {MAX_DENY} stopped links; raising the epoch, which stops every earlier link"); + f.epoch = f.epoch.saturating_add(1); + deny = deny_for(f); + } + deny + } + + /// Write the revocation file edge reads. + fn publish(&self, epoch: u32, deny: Vec) -> Result<(), String> { + // Readable by edge (another user); it holds only random link ids. + let text = + serde_json::to_vec(&RevocationFile { 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 mut f = self.load()?; + self.save(&mut 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_reconciled().map_err(MintError::Store)?; + let t0 = now(); + if f.links + .iter() + .filter(|l| l.stopped_at.is_none() && l.expires_at > t0) + .count() + >= MAX_ACTIVE + { + return Err(MintError::TooMany); + } + 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()); + } + // Settle the epoch first (lost records, an overflowing deny list): a link minted + // below the epoch that is about to be published would be dead on arrival. + let _ = self.reconcile(&mut f); + 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_reconciled()?; + 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_reconciled()?; + 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..1bde3ea --- /dev/null +++ b/crates/control/src/tokens.rs @@ -0,0 +1,263 @@ +// 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<()>, +} + +struct StoreGuard<'a> { + _m: std::sync::MutexGuard<'a, ()>, + _f: std::fs::File, +} + +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(()), + } + } + + /// Exclusive access to `tokens.json` for one read-modify-write: a mutex inside this + /// process and an advisory lock on `tokens.lock` across processes (the CLI and the + /// server), released when the guard is dropped, also if the process dies. + fn guard(&self) -> Result, String> { + let m = self + .lock + .lock() + .map_err(|_| "token store unavailable".to_owned())?; + let path = self.path.with_file_name("tokens.lock"); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir) + .map_err(|e| format!("cannot create {}: {e}", dir.display()))?; + } + let f = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(&path) + .map_err(|e| format!("cannot open {}: {e}", path.display()))?; + f.lock() + .map_err(|e| format!("cannot lock {}: {e}", path.display()))?; + Ok(StoreGuard { _m: m, _f: f }) + } + + 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.guard()?; + 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> { + let _g = self.guard()?; + Ok(self.load()?.tokens) + } + + pub fn revoke(&self, id: &str) -> Result, String> { + let _g = self.guard()?; + 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.guard()?; + 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.guard().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..12759c1 --- /dev/null +++ b/crates/control/src/util.rs @@ -0,0 +1,170 @@ +// 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<()> { + crate::crash::fail_write(path).map_err(std::io::Error::other)?; + 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(); + // Unique per write (process, counter, random), so two writers of the same file never + // share a temporary file. + static WRITES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = WRITES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let r = random::<4>().map(|b| hex(&b))?; + name.push(format!(".tmp-{}-{n}-{r}", 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<()> { + crate::crash::fail_write(to).map_err(std::io::Error::other)?; + 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 concurrent_atomic_writes_of_one_file_all_succeed() { + let d = std::env::temp_dir().join(format!("ianitor-util-c-{}", std::process::id())); + let p = d.join("paused.json"); + let threads: Vec<_> = (0..16) + .map(|i| { + let p = p.clone(); + std::thread::spawn(move || { + (0..50).all(|_| write_atomic(&p, format!("{i}").as_bytes(), 0o600).is_ok()) + }) + }) + .collect(); + for t in threads { + assert!(t.join().unwrap(), "a write failed"); + } + let left: Vec<_> = std::fs::read_dir(&d).unwrap().collect(); + assert_eq!(left.len(), 1, "no temporary files left"); + let _ = std::fs::remove_dir_all(&d); + } + + #[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); + } +} diff --git a/crates/control/tests/api.rs b/crates/control/tests/api.rs new file mode 100644 index 0000000..2d45a8c --- /dev/null +++ b/crates/control/tests/api.rs @@ -0,0 +1,543 @@ +// 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 API's edges (ROADMAP §6 phase 2, tests first): requests without a valid token are +//! rejected on every route and tokens never reach a log, an error or a state file; request +//! bodies are hostile input; the routes repository holds only host files; control only +//! listens on loopback; the OpenAPI document covers the API. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[cfg(unix)] +mod common; + +#[cfg(not(unix))] +#[test] +fn skipped_on_windows() { + eprintln!( + "SKIPPED on Windows: {} needs Linux (edge admin socket); run it in WSL2", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use std::time::Duration; + + use crate::common::{Env, EnvSpec, host}; + use ianitor_testkit::more::tcp_raw; + use ianitor_testkit::upstream::Echo; + use serde_json::{Value, json}; + + /// Every (method, path) in the OpenAPI document, with path parameters filled in. + fn routes(doc: &Value) -> Vec<(String, String)> { + let mut out = Vec::new(); + for (path, item) in doc["paths"].as_object().unwrap() { + for method in ["get", "post", "put", "patch", "delete"] { + if item.get(method).is_some() { + let p = path + .replace("{hostname}", "a.test") + .replace("{id}", "x") + .replace("{change_id}", "x"); + out.push((method.to_uppercase(), p)); + } + } + } + out + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn requests_without_a_valid_token_are_rejected_and_tokens_are_never_logged() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + let doc = env.call("GET", "/api/v1/openapi.json", None).await; + assert_eq!(doc.status, 200, "{}", doc.text); + let routes = routes(&doc.json); + assert!(routes.len() >= 25, "{routes:?}"); + + // Make a second token through the API and revoke it, to test a revoked one too. + let made = env + .call("POST", "/api/v1/tokens", Some(json!({ "name": "script" }))) + .await; + assert_eq!(made.status, 201, "{}", made.text); + let revoked = made.json["token"].as_str().unwrap().to_owned(); + let rid = made.json["id"].as_str().unwrap().to_owned(); + assert_eq!( + env.call("DELETE", &format!("/api/v1/tokens/{rid}"), None) + .await + .status, + 204 + ); + // A listing never shows values or hashes. + let list = env.call("GET", "/api/v1/tokens", None).await; + assert!( + !list.text.contains(&revoked) && !list.text.contains("sha256"), + "{}", + list.text + ); + assert!(!list.text.contains(&env.token)); + + let mut wrong = env.token.clone(); + wrong.pop(); + wrong.push(if env.token.ends_with('A') { 'B' } else { 'A' }); + type Case = (String, Vec<(String, String)>, &'static str); + let cases: Vec = vec![ + ("no header".into(), vec![], "token.missing"), + ( + "not bearer".into(), + vec![("Authorization".into(), env.token.clone())], + "token.unknown", + ), + ( + "basic".into(), + vec![("Authorization".into(), "Basic YWRtaW46YWRtaW4=".into())], + "token.unknown", + ), + ( + "one char off".into(), + vec![("Authorization".into(), format!("Bearer {wrong}"))], + "token.unknown", + ), + ( + "made up".into(), + vec![( + "Authorization".into(), + "Bearer ian_0000000000000000_xxxxxxxx".into(), + )], + "token.unknown", + ), + ( + "revoked".into(), + vec![("Authorization".into(), format!("Bearer {revoked}"))], + "token.revoked", + ), + ( + "empty bearer".into(), + vec![("Authorization".into(), "Bearer ".into())], + "token.unknown", + ), + // Identity headers do not authenticate (docs/ui-api.md G14). + ( + "remote-user".into(), + vec![ + ("Remote-User".into(), "mark".into()), + ("Remote-Groups".into(), "admins".into()), + ], + "token.missing", + ), + ]; + for (what, headers, code) in &cases { + let hs: Vec<(&str, &str)> = headers + .iter() + .map(|(a, b)| (a.as_str(), b.as_str())) + .collect(); + for (method, path) in &routes { + let body = (method != "GET" && method != "DELETE").then(|| json!({})); + let r = env.call_with(method, path, &hs, body).await; + assert_eq!(r.status, 401, "{what}: {method} {path}: {}", r.text); + assert_eq!(r.json["error"]["code"], *code, "{what}: {method} {path}"); + assert!(r.json["error"]["message"].as_str().unwrap().len() > 10); + assert!(r.json["request_id"].is_string() && r.json["server_time"].is_string()); + } + } + // Unknown paths are refused the same way, before anything else. + assert_eq!( + env.call_with("GET", "/api/v1/nope", &[], None).await.status, + 401 + ); + assert_eq!(env.call_with("GET", "/", &[], None).await.status, 401); + + // A wrong Host header (DNS rebinding) is refused even with a good token. + let auth = format!("Bearer {}", env.token); + let raw = format!( + "GET /api/v1/overview HTTP/1.1\r\nHost: evil.example\r\nAuthorization: {auth}\r\nConnection: close\r\n\r\n" + ); + let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap(); + assert_eq!(r.status, 403, "{}", r.text()); + // A browser write without the UI header is refused (CSRF). + let r = env + .call_with( + "POST", + "/api/v1/hosts", + &[("Authorization", &auth), ("Origin", "https://evil.example")], + Some(json!({ "host": host("a.test", &good.url(), false) })), + ) + .await; + assert_eq!(r.status, 403, "{}", r.text); + assert_eq!(r.json["error"]["code"], "request.csrf"); + let r = env + .call_with( + "POST", + "/api/v1/hosts", + &[ + ("Authorization", &auth), + ("Origin", "http://127.0.0.1"), + ("X-Ianitor-UI", "1"), + ], + Some(json!({ "host": host("a.test", &good.url(), false) })), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + env.wait_apply(r.json["apply"]["id"].as_str().unwrap()) + .await; + + // Exercise the rest with the good token, then look for any token anywhere. + for (method, path) in &routes { + if method == "GET" { + env.call(method, path, None).await; + } + } + tokio::time::sleep(Duration::from_millis(300)).await; + env.kill_control(); + let mut everything = env.control_log(); + for f in [ + "applies.json", + "push.json", + "share-links.json", + "journal.json", + ] { + everything.push_str(&env.file(&format!("state/{f}"))); + } + everything.push_str(&env.file("edge/edge.json")); + everything.push_str(&env.git(&["log", "-p", "--all"])); + // `ian_<16 hex>_`; the secret itself may contain '_'. + let secret_part = |t: &str| { + assert!(t.starts_with("ian_") && t.as_bytes()[20] == b'_'); + t[21..].to_owned() + }; + for t in [&env.token, &revoked] { + assert!( + !everything.contains(secret_part(t).as_str()), + "a token leaked" + ); + } + let stored = env.file("state/tokens.json"); + for t in [&env.token, &revoked] { + assert!( + !stored.contains(secret_part(t).as_str()), + "tokens.json holds a value, not a hash" + ); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(env.dir.join("state/tokens.json")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o077, 0, "tokens.json is private"); + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn bodies_are_hostile_input() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + let auth = format!("Bearer {}", env.token); + + // Unknown fields, at the top and inside the host. + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("a.test", &good.url(), false), "colour": 1 })), + ) + .await; + assert_eq!(r.status, 422, "{}", r.text); + assert_eq!(r.json["error"]["code"], "request.body_unknown_field"); + assert_eq!(r.json["error"]["field"], "colour"); + let mut h = host("a.test", &good.url(), false); + h["upstream"] = json!("typo"); + let r = env + .call("POST", "/api/v1/hosts", Some(json!({ "host": h }))) + .await; + assert_eq!( + r.json["error"]["code"], "request.body_unknown_field", + "{}", + r.text + ); + // Wrong types never echo the value sent. + let r = env + .call( + "POST", + "/api/v1/tokens", + Some(json!({ "name": ["secret-ish-value"] })), + ) + .await; + assert_eq!(r.status, 400, "{}", r.text); + assert!(!r.text.contains("secret-ish-value"), "{}", r.text); + // Nor do odd field names, path parameters or credentials in an upstream URL. + let r = env + .call("POST", "/api/v1/tokens", Some(json!({ "pass:hunter2": 1 }))) + .await; + assert_eq!(r.status, 422, "{}", r.text); + assert!(!r.text.contains("hunter2"), "{}", r.text); + let r = env.call("GET", "/api/v1/hosts/x%3Chunter2%3E", None).await; + assert_eq!(r.status, 404, "{}", r.text); + assert!(!r.text.contains("hunter2"), "{}", r.text); + let mut leaky = host("a.test", "http://admin:hunter2@10.0.0.2:3000", false); + leaky["upstreams"] = json!(["http://admin:hunter2@10.0.0.2:3000", "ftp://u:hunter2@x"]); + let r = env + .call("POST", "/api/v1/hosts", Some(json!({ "host": leaky }))) + .await; + assert_eq!(r.status, 422, "{}", r.text); + assert!(!r.text.contains("hunter2"), "{}", r.text); + // Not JSON, wrong content type, too large. + let raw = format!( + "POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: application/json\r\nContent-Length: 5\r\nConnection: close\r\n\r\n{{{{{{{{{{", + env.api + ); + let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap(); + assert_eq!(r.status, 400, "{}", r.text()); + let raw = format!( + "POST /api/v1/hosts HTTP/1.1\r\nHost: {}\r\nAuthorization: {auth}\r\nContent-Type: text/plain\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}", + env.api + ); + let r = tcp_raw(env.api, raw.as_bytes()).await.unwrap(); + assert_eq!(r.status, 415, "{}", r.text()); + let big = "x".repeat(70 * 1024); + let r = env + .call("POST", "/api/v1/tokens", Some(json!({ "name": big }))) + .await; + assert_eq!(r.status, 413, "{}", &r.text[..r.text.len().min(300)]); + + // Field errors come back as one envelope with codes and field paths. + let mut bad = host("a.test", "ftp://x", true); + bad["health_check"]["interval_secs"] = json!(0); + let r = env + .call("POST", "/api/v1/hosts", Some(json!({ "host": bad }))) + .await; + assert_eq!(r.status, 422, "{}", r.text); + let fields: Vec<&str> = r.json["errors"] + .as_array() + .unwrap() + .iter() + .filter_map(|e| e["field"].as_str()) + .collect(); + assert!(fields.contains(&"upstreams[0]"), "{fields:?}"); + assert!(fields.contains(&"health_check.interval_secs"), "{fields:?}"); + assert_eq!(r.json["error"]["code"], "apply.failed.validation"); + let codes: Vec<&str> = r.json["errors"] + .as_array() + .unwrap() + .iter() + .filter_map(|e| e["code"].as_str()) + .collect(); + assert!(codes.contains(&"host.upstream.scheme"), "{codes:?}"); + let msg = r.json["errors"][0]["message"].as_str().unwrap(); + assert!( + !msg.contains("TOML") && !msg.contains("hosts/"), + "plain English: {msg}" + ); + // Validate without applying. + let r = env + .call( + "POST", + "/api/v1/hosts/validate?mode=create", + Some(host("a.test", &good.url(), false)), + ) + .await; + assert_eq!(r.status, 200, "{}", r.text); + // A hostname that does not match the path, a host that does not exist. + let r = env + .call( + "PUT", + "/api/v1/hosts/b.test", + Some(json!({ "host": host("a.test", &good.url(), false) })), + ) + .await; + assert_eq!( + r.json["error"]["code"], "host.hostname.mismatch", + "{}", + r.text + ); + let r = env.call("DELETE", "/api/v1/hosts/nope.test", None).await; + assert_eq!(r.status, 404); + let r = env.call("GET", "/api/v1/hosts/..%2f..%2fetc", None).await; + assert_eq!(r.status, 404); + // base_rev must be a commit of the history. + let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "0".repeat(40) }))).await; + assert_eq!(r.json["error"]["code"], "request.base_rev", "{}", r.text); + let r = env.call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &good.url(), false), "base_rev": "--upload-pack=touch /tmp/x" }))).await; + assert_eq!(r.status, 422, "{}", r.text); + + // Idempotency-Key: a retry returns the same apply; another body with it is refused. + let body = json!({ "host": host("a.test", &good.url(), false) }); + let k = [ + ("Authorization", auth.as_str()), + ("Idempotency-Key", "click-1"), + ]; + let first = env + .call_with("POST", "/api/v1/hosts", &k, Some(body.clone())) + .await; + assert_eq!(first.status, 202, "{}", first.text); + let again = env.call_with("POST", "/api/v1/hosts", &k, Some(body)).await; + assert_eq!(again.status, 202, "{}", again.text); + assert_eq!(again.json["apply"]["id"], first.json["apply"]["id"]); + let other = env + .call_with( + "POST", + "/api/v1/hosts", + &k, + Some(json!({ "host": host("b.test", &good.url(), false) })), + ) + .await; + assert_eq!(other.status, 422); + assert_eq!(other.json["error"]["code"], "request.idempotency"); + env.wait_apply(first.json["apply"]["id"].as_str().unwrap()) + .await; + // Taken hostname. + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("a.test", &good.url(), false) })), + ) + .await; + assert_eq!(r.json["error"]["code"], "host.hostname.taken", "{}", r.text); + assert_eq!(r.json["error"]["field"], "hostname"); + // The overview answers 304 to its own ETag. + let o = env.call("GET", "/api/v1/overview", None).await; + let etag = o.header("etag").unwrap().to_owned(); + let r = env + .call_with( + "GET", + "/api/v1/overview", + &[("Authorization", &auth), ("If-None-Match", &etag)], + None, + ) + .await; + assert_eq!(r.status, 304); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn the_routes_repository_holds_only_host_files() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + assert_eq!( + env.add_host(host("a.test", &good.url(), false)).await["state"], + "kept" + ); + let good_edge = env.file("edge/edge.json"); + env.kill_control(); + // Someone pushes a stray file and a nested folder straight into the repository. + let work = env.dir.join("work"); + let git = |args: &[&str], cwd: &std::path::Path| { + let o = std::process::Command::new("git") + .args(["-c", "user.name=t", "-c", "user.email=t@t"]) + .args(args) + .current_dir(cwd) + .output() + .unwrap(); + assert!( + o.status.success(), + "{args:?} {}", + String::from_utf8_lossy(&o.stderr) + ); + }; + git( + &[ + "clone", + "--quiet", + &env.repo().to_string_lossy(), + &work.to_string_lossy(), + ], + &env.dir.join("."), + ); + std::fs::create_dir_all(work.join("hosts/sub")).unwrap(); + std::fs::write(work.join("README.md"), "hello").unwrap(); + std::fs::write( + work.join("hosts/sub/b.test.toml"), + "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", + ) + .unwrap(); + git(&["add", "-A"], &work); + git(&["commit", "--quiet", "-m", "stray"], &work); + git(&["push", "--quiet", "origin", "HEAD:main"], &work); + + env.start_control(None); + let o = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text); + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("c.test", &good.url(), false) })), + ) + .await; + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "control.paused"); + // Edge keeps the last good config; nothing stray was compiled. + assert_eq!(env.file("edge/edge.json"), good_edge); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn control_only_listens_on_loopback() { + let env = Env::new(EnvSpec::default()).await; + let text = std::fs::read_to_string(env.config_path()).unwrap(); + let open = text.replace( + &format!("listen = \"{}\"", env.api), + "listen = \"0.0.0.0:7979\"", + ); + std::fs::write(env.config_path(), open).unwrap(); + let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control")) + .arg("--config") + .arg(env.config_path()) + .output() + .unwrap(); + assert!(!out.status.success()); + assert!( + String::from_utf8_lossy(&out.stderr).contains("loopback"), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!(std::net::TcpStream::connect("127.0.0.1:7979").is_err()); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn the_overview_has_everything_the_main_screen_needs() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + env.add_host(host("a.test", &good.url(), true)).await; + tokio::time::sleep(Duration::from_secs(2)).await; + let o = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(o.status, 200, "{}", o.text); + for k in [ + "counts", + "hosts", + "engine", + "last_apply", + "undo", + "repo", + "site", + "server_time", + "rev", + ] { + assert!(o.json.get(k).is_some(), "{k} missing: {}", o.text); + } + assert_eq!(o.json["counts"]["hosts"], 1); + assert_eq!(o.json["counts"]["healthy"], 1, "{}", o.text); + let h = &o.json["hosts"][0]; + assert_eq!(h["health"]["state"], "healthy"); + assert!(h["health"]["latency_ms"].is_u64()); + assert_eq!(h["certificate"]["state"], "ok"); + assert_eq!(o.json["engine"]["running"], "pingora"); + assert_eq!(o.json["engine"]["state"], "running"); + assert_eq!(o.json["last_apply"]["state"], "kept"); + assert_eq!(o.json["undo"]["available"], true); + assert!(o.json["intermediate"].is_null()); + // The CLI lists tokens without values. + let out = std::process::Command::new(env!("CARGO_BIN_EXE_ianitor-control")) + .args(["token", "list", "--config"]) + .arg(env.config_path()) + .output() + .unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + assert!(text.contains("test") && !text.contains(&env.token[21..])); + } +} diff --git a/crates/control/tests/apply.rs b/crates/control/tests/apply.rs new file mode 100644 index 0000000..fef8c46 --- /dev/null +++ b/crates/control/tests/apply.rs @@ -0,0 +1,1243 @@ +// 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 §6 phase 2, tests first): a failed health check reverts the +//! commit and restores the previous edge config; a control crash at any stage leaves edge on +//! the last good config and recovery makes repository, files and edge agree; concurrent +//! applies are serialised; Undo names its target; kept changes are pushed, and a failed push +//! keeps the change. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[cfg(unix)] +mod common; + +#[cfg(not(unix))] +#[test] +fn skipped_on_windows() { + eprintln!( + "SKIPPED on Windows: {} needs Linux (edge admin socket); run it in WSL2", + file!() + ); +} + +#[cfg(unix)] +mod unix { + use std::time::Duration; + + use crate::common::{Env, EnvSpec, host, sha256}; + use ianitor_testkit::client::{self, Req}; + use ianitor_testkit::upstream::Echo; + use serde_json::json; + + async fn get(env: &Env, hostname: &str) -> ianitor_testkit::client::Resp { + client::https( + env.opts.https_listen, + hostname, + env.roots(), + &Req::get(hostname, "/"), + ) + .await + .unwrap() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_failed_health_check_reverts_the_commit_and_restores_the_previous_edge_config() { + let good = Echo::start("good").await; + let sick = Echo::start("sick").await; + sick.health.store(500, std::sync::atomic::Ordering::SeqCst); + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + + let r = env.add_host(host("a.test", &good.url(), true)).await; + assert_eq!(r["state"], "kept", "{r}"); + assert_eq!(r["reason"]["code"], "apply.kept"); + let kept_head = env.head(); + let kept_edge = env.file("edge/edge.json"); + assert_eq!(env.edge_status().await["config_sha256"], sha256(&kept_edge)); + let body: serde_json::Value = + serde_json::from_slice(&get(&env, "a.test").await.body).unwrap(); + assert_eq!(body["upstream"], "good"); + + // Point it at an upstream whose health check fails: reverted, with the reason. + let r = env + .apply( + "PUT", + "/api/v1/hosts/a.test", + Some(json!({ "host": host("a.test", &sick.url(), true), "base_rev": kept_head })), + ) + .await; + assert_eq!(r["state"], "reverted", "{r}"); + assert_eq!(r["reason"]["code"], "apply.reverted.server_error", "{r}"); + assert_eq!(r["reason"]["hostname"], "a.test"); + assert!( + r["reason"]["message"] + .as_str() + .unwrap() + .contains("a.test was not changed") + ); + assert_eq!(r["attempted_host"]["upstreams"][0], sick.url()); + + // The commit is reverted in git (history keeps both), and the tree is the kept one. + let log = env.git(&["log", "--format=%s", "refs/heads/main"]); + let subjects: Vec<&str> = log.lines().collect(); + assert!( + subjects[0].starts_with("Revert \"Changed a.test\""), + "{log}" + ); + assert_eq!(subjects[1], "Changed a.test"); + assert_eq!( + env.git(&["rev-parse", "refs/heads/main^{tree}"]), + env.git(&["rev-parse", &format!("{kept_head}^{{tree}}")]) + ); + // Edge serves the previous config again; the files never left it. + assert_eq!(env.file("edge/edge.json"), kept_edge); + env.assert_consistent().await; + let body: serde_json::Value = + serde_json::from_slice(&get(&env, "a.test").await.body).unwrap(); + assert_eq!(body["upstream"], "good"); + + // History shows the attempt as one entry. + let h = env.call("GET", "/api/v1/history", None).await; + let entries = h.json["entries"].as_array().unwrap(); + assert_eq!(entries.len(), 2, "{}", h.text); + assert_eq!(entries[0]["state"], "reverted"); + assert_eq!(entries[1]["state"], "kept"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn only_touched_hosts_are_judged_and_a_host_already_down_never_reverts() { + let good = Echo::start("good").await; + let flaky = Echo::start("flaky").await; + let sick = Echo::start("sick").await; + sick.health.store(503, std::sync::atomic::Ordering::SeqCst); + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + // Without a health check, the watch only checks that the host answers. + let r = env.add_host(host("b.test", &good.url(), false)).await; + assert_eq!(r["state"], "kept", "{r}"); + assert_eq!(r["reason"]["code"], "apply.kept.no_watch", "{r}"); + // A host that is up when added and goes down later... + assert_eq!( + env.add_host(host("c.test", &flaky.url(), true)).await["state"], + "kept" + ); + flaky.health.store(500, std::sync::atomic::Ordering::SeqCst); + tokio::time::sleep(Duration::from_secs(3)).await; + let o = env.call("GET", "/api/v1/overview", None).await; + let c = o.json["hosts"] + .as_array() + .unwrap() + .iter() + .find(|h| h["hostname"] == "c.test") + .unwrap() + .clone(); + assert_eq!(c["health"]["state"], "down", "{}", o.text); + assert_eq!(c["health"]["failure"]["kind"], "server_error"); + // ...does not stop other changes (only touched hosts are judged), + assert_eq!( + env.add_host(host("d.test", &good.url(), true)).await["state"], + "kept" + ); + // and an edit of the host that was already down is not reverted for it. + let mut edited = host("c.test", &flaky.url(), true); + edited["websockets"] = json!(false); + let r = env + .apply( + "PUT", + "/api/v1/hosts/c.test", + Some(json!({ "host": edited })), + ) + .await; + assert_eq!(r["state"], "kept", "{r}"); + // A new host that fails its check is reverted. + let r = env.add_host(host("e.test", &sick.url(), true)).await; + assert_eq!(r["state"], "reverted", "{r}"); + // Removing a host has nothing to watch and is kept. + let r = env.apply("DELETE", "/api/v1/hosts/b.test", None).await; + assert_eq!(r["state"], "kept", "{r}"); + assert_eq!(r["steps"][4]["state"], "skipped"); + env.assert_consistent().await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn edge_refusing_a_config_fails_the_apply_and_nothing_changes() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + assert_eq!( + env.add_host(host("a.test", &good.url(), false)).await["state"], + "kept" + ); + let before = env.head(); + // No certificate for this name: edge refuses the config. + std::fs::remove_file(env.dir.join("certs/d.test.crt")).unwrap(); + let r = env.add_host(host("d.test", &good.url(), false)).await; + assert_eq!(r["state"], "failed", "{r}"); + assert_eq!(r["reason"]["code"], "apply.failed.reload"); + assert!( + r["reason"]["detail"].as_str().unwrap().contains("d.test"), + "{r}" + ); + assert_eq!( + env.git(&["rev-parse", "refs/heads/main^{tree}"]), + env.git(&["rev-parse", &format!("{before}^{{tree}}")]) + ); + env.assert_consistent().await; + assert_eq!(get(&env, "a.test").await.status, 200); + } + + // ------------------------------------------------------------ crash safety + + /// Kill control at `stage` during an apply; edge must be on the last good config, and a + /// restarted control must bring repository, files and edge back in line. + async fn crash_at(stage: &str) { + let good = Echo::start("good").await; + let sick = Echo::start("sick").await; + sick.health.store(500, std::sync::atomic::Ordering::SeqCst); + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + assert_eq!( + env.add_host(host("a.test", &good.url(), true)).await["state"], + "kept" + ); + let good_edge = env.file("edge/edge.json"); + let good_head = env.head(); + env.kill_control(); + + env.start_control(Some(stage)); + // The reverting stage is reached by a change that fails its watch. + let upstream = if stage == "reverting" { + sick.url() + } else { + good.url() + }; + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("b.test", &upstream, true) })), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + let exit = env.wait_control_exit(Duration::from_secs(30)); + assert!( + exit.is_some(), + "control did not stop at {stage}:\n{}", + env.control_log() + ); + + let confirmed = matches!(stage, "confirmed" | "promoted"); + // edge.json on disk is always the last good config: the old one, unless edge had + // already confirmed the new one. + if !confirmed { + assert_eq!( + env.file("edge/edge.json"), + good_edge, + "{stage}: edge.json untouched" + ); + } + // A trial edge was serving reverts by itself at its deadline (watch 2 s + margin 2 s). + tokio::time::sleep(Duration::from_secs(5)).await; + let st = env.edge_status().await; + assert!(st["trial"].is_null(), "{stage}: trial still running: {st}"); + if !confirmed { + assert_eq!( + st["config_sha256"], + sha256(&good_edge), + "{stage}: edge back on the last good config" + ); + assert_eq!(get(&env, "a.test").await.status, 200); + } + + // Recovery. + env.start_control(None); + let rec = env + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await; + assert_eq!(rec.status, 200, "{}", rec.text); + if confirmed { + assert_eq!(rec.json["state"], "kept", "{stage}: {}", rec.text); + } else if stage == "prepared" { + assert_eq!(rec.json["state"], "failed", "{stage}: {}", rec.text); + assert_eq!(env.head(), good_head, "{stage}: branch never moved"); + } else { + assert_eq!(rec.json["state"], "reverted", "{stage}: {}", rec.text); + assert_eq!( + rec.json["reason"]["code"], + if stage == "reverting" { + "apply.reverted.server_error" + } else { + "apply.interrupted" + }, + "{stage}: {}", + rec.text + ); + assert_eq!( + env.git(&["rev-parse", "refs/heads/main^{tree}"]), + env.git(&["rev-parse", &format!("{good_head}^{{tree}}")]), + "{stage}: the change is reverted in git" + ); + } + env.assert_consistent().await; + // And applies work again afterwards. + let r = env.add_host(host("c.test", &good.url(), false)).await; + assert_eq!(r["state"], "kept", "{stage}: {r}"); + env.assert_consistent().await; + } + + macro_rules! crash_tests { + ($($name:ident => $stage:literal),* $(,)?) => {$( + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn $name() { + crash_at($stage).await; + } + )*}; + } + + crash_tests! { + crash_after_the_commit_object_is_made => "prepared", + crash_after_the_branch_moved => "committed", + crash_after_the_trial_files_are_written => "trial_written", + crash_after_edge_loaded_the_trial => "trial_loaded", + crash_during_the_watch => "watching", + crash_after_the_watch => "watched", + crash_after_edge_confirmed => "confirmed", + crash_after_the_files_were_promoted => "promoted", + crash_while_reverting => "reverting", + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn an_edge_restart_during_the_watch_reverts_and_edge_starts_from_the_last_good_config() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec { + watch_secs: 6, + ..Default::default() + }) + .await; + env.start_control(None); + assert_eq!( + env.add_host(host("a.test", &good.url(), true)).await["state"], + "kept" + ); + let good_edge = env.file("edge/edge.json"); + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("b.test", &good.url(), true) })), + ) + .await; + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + tokio::time::sleep(Duration::from_secs(2)).await; + env.stop_edge(); + env.start_edge(); + assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge)); + let rec = env.wait_apply(&id).await; + assert_eq!(rec["state"], "reverted", "{rec}"); + assert_eq!(rec["reason"]["code"], "apply.reverted.edge_lost"); + env.assert_consistent().await; + } + + // ------------------------------------------------------------ serialisation + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn concurrent_applies_are_serialised() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec { + watch_secs: 1, + ..Default::default() + }) + .await; + env.start_control(None); + let names = ["a.test", "b.test", "c.test", "d.test", "e.test"]; + let env_ref = &env; + let posts = names.iter().map(|n| { + let body = json!({ "host": host(n, &good.url(), true) }); + async move { env_ref.call("POST", "/api/v1/hosts", Some(body)).await } + }); + let answers = futures_join(posts).await; + let mut ids = Vec::new(); + for a in &answers { + assert_eq!(a.status, 202, "{}", a.text); + ids.push(a.json["apply"]["id"].as_str().unwrap().to_owned()); + } + // While one runs, the others say they are queued behind it. + let queued = env + .call("GET", &format!("/api/v1/applies/{}", ids[4]), None) + .await; + let st = queued.json["state"].as_str().unwrap().to_owned(); + if st == "queued" { + assert!( + queued.json["queue"]["position"].as_u64().unwrap() >= 1, + "{}", + queued.text + ); + } + let mut spans = Vec::new(); + for id in &ids { + let r = env.wait_apply(id).await; + assert_eq!(r["state"], "kept", "{r}"); + spans.push(( + r["started_at"].as_str().unwrap().to_owned(), + r["finished_at"].as_str().unwrap().to_owned(), + r["commit"].as_str().unwrap().to_owned(), + )); + } + // One after another: the five commits form one linear chain at the head (nothing + // lost, nothing interleaved). Timestamps have one-second resolution, so they are not + // compared. + let commits: Vec = spans.iter().map(|s| s.2.clone()).collect(); + let mut chain = Vec::new(); + let mut c = env.head(); + for _ in 0..commits.len() { + chain.push(c.clone()); + c = env.git(&["rev-parse", &format!("{c}^")]); + } + let mut sorted_chain = chain.clone(); + sorted_chain.sort(); + let mut sorted_commits = commits.clone(); + sorted_commits.sort(); + assert_eq!( + sorted_chain, sorted_commits, + "a linear chain of the five commits" + ); + let files = env.head_files(); + for n in names { + assert!( + files.iter().any(|(p, _)| p == &format!("hosts/{n}.toml")), + "{n} missing" + ); + } + env.assert_consistent().await; + } + + async fn futures_join(fs: impl Iterator) -> Vec { + let mut out = Vec::new(); + let handles: Vec<_> = fs.collect(); + // Start all at once: poll them together. + let mut pinned: Vec>> = handles.into_iter().map(Box::pin).collect(); + let mut results: Vec> = (0..pinned.len()).map(|_| None).collect(); + std::future::poll_fn(|cx| { + let mut pending = false; + for (i, f) in pinned.iter_mut().enumerate() { + if results[i].is_none() { + match f.as_mut().poll(cx) { + std::task::Poll::Ready(v) => results[i] = Some(v), + std::task::Poll::Pending => pending = true, + } + } + } + if pending { + std::task::Poll::Pending + } else { + std::task::Poll::Ready(()) + } + }) + .await; + for r in results { + out.push(r.unwrap()); + } + out + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_queued_apply_can_be_cancelled() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec { + watch_secs: 3, + ..Default::default() + }) + .await; + env.start_control(None); + let a = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("a.test", &good.url(), true) })), + ) + .await; + let b = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("b.test", &good.url(), true) })), + ) + .await; + let bid = b.json["apply"]["id"].as_str().unwrap().to_owned(); + let r = env + .call("DELETE", &format!("/api/v1/applies/{bid}"), None) + .await; + assert_eq!(r.status, 204, "{}", r.text); + let rb = env.wait_apply(&bid).await; + assert_eq!(rb["state"], "failed"); + assert_eq!(rb["reason"]["code"], "apply.cancelled"); + let ra = env + .wait_apply(a.json["apply"]["id"].as_str().unwrap()) + .await; + assert_eq!(ra["state"], "kept"); + // A running or finished apply cannot be cancelled. + let r = env + .call( + "DELETE", + &format!("/api/v1/applies/{}", ra["id"].as_str().unwrap()), + None, + ) + .await; + assert_eq!(r.status, 409); + assert!( + !env.head_files() + .iter() + .any(|(p, _)| p == "hosts/b.test.toml") + ); + env.assert_consistent().await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_revert_that_fails_pauses_changes_until_a_restore() { + let good = Echo::start("good").await; + let sick = Echo::start("sick").await; + sick.health.store(500, std::sync::atomic::Ordering::SeqCst); + let mut env = Env::new(EnvSpec { + watch_secs: 3, + ..Default::default() + }) + .await; + env.start_control(None); + let kept = env.add_host(host("a.test", &good.url(), true)).await; + let good_edge = env.file("edge/edge.json"); + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("b.test", &sick.url(), true) })), + ) + .await; + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + // While it is being watched, lock the branch so the revert commit cannot land. + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while env + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await + .json["commit"] + .is_null() + { + assert!(std::time::Instant::now() < deadline); + tokio::time::sleep(Duration::from_millis(20)).await; + } + let lock = env.repo().join("refs/heads/main.lock"); + std::fs::write(&lock, "").unwrap(); + let rec = env.wait_apply(&id).await; + assert_eq!(rec["state"], "needs_attention", "{rec}"); + // Edge was still told to drop the trial: visitors get the last good config. + let st = env.edge_status().await; + assert_eq!(st["config_sha256"], sha256(&good_edge)); + assert_eq!(env.file("edge/edge.json"), good_edge); + let o = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text); + assert_eq!(o.json["undo"]["blocked"]["code"], "undo.paused"); + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("c.test", &good.url(), false) })), + ) + .await; + assert_eq!(r.status, 409); + // A control restart (the branch still locked) retries the revert, fails again, and + // does not push the unverified head to edge. + env.kill_control(); + env.start_control(None); + assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge)); + let o = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text); + std::fs::remove_file(&lock).unwrap(); + // Restore the last kept version: the way out. + let r = env + .apply( + "POST", + "/api/v1/restore", + Some(json!({ "change_id": kept["id"] })), + ) + .await; + assert_eq!(r["state"], "kept", "{r}"); + let o = env.call("GET", "/api/v1/overview", None).await; + assert!(o.json["paused"].is_null(), "{}", o.text); + env.assert_consistent().await; + } + + /// QC fix round 2 (M3 reopened): a Restore while the pause is not saved must not take the + /// `reverting` journal with it, or a restart loads the unverified head. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_restore_while_the_pause_is_unsaved_never_drops_it() { + let good = Echo::start("good").await; + let sick = Echo::start("sick").await; + sick.health.store(500, std::sync::atomic::Ordering::SeqCst); + let mut env = Env::new(EnvSpec { + watch_secs: 3, + ..Default::default() + }) + .await; + env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "paused.json")]); + let kept = env.add_host(host("a.test", &good.url(), true)).await; + let good_edge = env.file("edge/edge.json"); + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("b.test", &sick.url(), true) })), + ) + .await; + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while env + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await + .json["commit"] + .is_null() + { + assert!(std::time::Instant::now() < deadline); + tokio::time::sleep(Duration::from_millis(20)).await; + } + let lock = env.repo().join("refs/heads/main.lock"); + std::fs::write(&lock, "").unwrap(); + let rec = env.wait_apply(&id).await; + assert_eq!(rec["state"], "needs_attention", "{rec}"); + // Restore (the way out) while the pause still cannot be saved: refused, journal kept. + let r = env + .call( + "POST", + "/api/v1/restore", + Some(json!({ "change_id": kept["id"] })), + ) + .await; + if r.status == 202 { + env.wait_apply(r.json["apply"]["id"].as_str().unwrap()) + .await; + } else { + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "control.paused", "{}", r.text); + } + let j: serde_json::Value = serde_json::from_str(&env.file("state/journal.json")) + .expect("the reverting journal is kept"); + assert_eq!(j["stage"], "reverting", "{j}"); + // The cause goes away; control restarts and finishes the revert, never loading the + // unverified head. + env.kill_control(); + std::fs::remove_file(&lock).unwrap(); + env.start_control(None); + tokio::time::sleep(Duration::from_secs(1)).await; + assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge)); + env.assert_consistent().await; + } + + /// QC fix round 2: when the config files cannot be written after a confirmed apply, + /// control pauses with the journal kept, still starts (paused) if they cannot be written + /// at the next start either, and resumes once they can. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn unwritable_config_files_pause_and_never_stop_control_from_starting() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + assert_eq!( + env.add_host(host("a.test", &good.url(), false)).await["state"], + "kept" + ); + env.kill_control(); + env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "edge.json")]); + let r = env.add_host(host("b.test", &good.url(), false)).await; + assert_eq!(r["state"], "kept", "{r}"); + let j: serde_json::Value = + serde_json::from_str(&env.file("state/journal.json")).expect("journal kept"); + assert_eq!(j["stage"], "confirmed", "{j}"); + let o = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text); + // Restart while the file still cannot be written: control starts, paused. + env.kill_control(); + env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "edge.json")]); + let o = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(o.status, 200); + assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text); + // Once it can be written, a restart finishes the promotion and changes resume. + env.kill_control(); + env.start_control(None); + let o = env.call("GET", "/api/v1/overview", None).await; + assert!(o.json["paused"].is_null(), "{}", o.text); + assert!( + env.head_files() + .iter() + .any(|(p, _)| p == "hosts/b.test.toml") + ); + env.assert_consistent().await; + } + + /// QC fix round 3: a request during a Restore's watch must not write the unverified head + /// to edge.json (or drop the Restore's journal); after the Restore is reverted, edge serves + /// what it served before. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_request_during_a_restore_watch_never_writes_the_unverified_head() { + async fn upstream_of(env: &Env) -> String { + let r = client::https( + env.opts.https_listen, + "a.test", + env.roots(), + &Req::get("a.test", "/"), + ) + .await + .unwrap(); + let v: serde_json::Value = serde_json::from_slice(&r.body).unwrap_or_default(); + format!("{} {}", r.status, v["upstream"].as_str().unwrap_or("?")) + } + let one = Echo::start("one").await; + let two = Echo::start("two").await; + let mut env = Env::new(EnvSpec { + watch_secs: 4, + ..Default::default() + }) + .await; + env.start_control(None); + let kept1 = env.add_host(host("a.test", &one.url(), true)).await; + assert_eq!(kept1["state"], "kept"); + // edge.json cannot be replaced (a non-empty directory in its place): promote fails. + let ej = env.dir.join("edge/edge.json"); + std::fs::remove_file(&ej).unwrap(); + std::fs::create_dir(&ej).unwrap(); + std::fs::write(ej.join("x"), "x").unwrap(); + let r = env + .apply( + "PUT", + "/api/v1/hosts/a.test", + Some(json!({ "host": host("a.test", &two.url(), true) })), + ) + .await; + assert_eq!(r["state"], "kept", "{r}"); + assert_eq!(upstream_of(&env).await, "200 two"); + // Restore the first version; its upstream is sick now, so its watch will fail. + one.health.store(500, std::sync::atomic::Ordering::SeqCst); + let r = env + .call( + "POST", + "/api/v1/restore", + Some(json!({ "change_id": kept1["id"] })), + ) + .await; + assert_eq!(r.status, 202, "{}", r.text); + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + let deadline = std::time::Instant::now() + Duration::from_secs(20); + loop { + let s = env + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await; + if s.json["state"] == "watching" { + break; + } + assert!( + std::time::Instant::now() < deadline, + "never watched: {}", + s.text + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + // The disk problem goes away; a write request arrives during the watch. + std::fs::remove_dir_all(&ej).unwrap(); + let _ = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("a.test", &two.url(), true) })), + ) + .await; + assert!( + env.dir.join("state/journal.json").exists(), + "the Restore's journal is still there" + ); + assert!( + !ej.exists() || env.file("edge/edge.json").contains(&two.url()), + "edge.json not written from the head under watch" + ); + let rec = env.wait_apply(&id).await; + assert_ne!(rec["state"], "kept", "{rec}"); + let now = upstream_of(&env).await; + assert_eq!( + now, "200 two", + "after the Restore was undone, edge serves the failed Restore's config ({now})" + ); + } + + /// Edge gone while a revert runs: control cannot see what edge serves, so it does not + /// claim `reverted`; it pauses, and a restart with edge back finishes the job. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_revert_that_cannot_see_edge_ends_as_needs_attention() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec { + watch_secs: 3, + ..Default::default() + }) + .await; + env.start_control(None); + assert_eq!( + env.add_host(host("a.test", &good.url(), true)).await["state"], + "kept" + ); + let good_edge = env.file("edge/edge.json"); + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("b.test", &good.url(), true) })), + ) + .await; + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + tokio::time::sleep(Duration::from_millis(1500)).await; + env.stop_edge(); + let rec = env.wait_apply(&id).await; + assert_eq!(rec["state"], "needs_attention", "{rec}"); + env.start_edge(); + env.kill_control(); + env.start_control(None); + let rec = env + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await; + assert_eq!(rec.json["state"], "reverted", "{}", rec.text); + assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge)); + env.assert_consistent().await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn a_pause_that_cannot_be_saved_keeps_the_journal_and_a_restart_finishes_the_revert() { + let good = Echo::start("good").await; + let sick = Echo::start("sick").await; + sick.health.store(500, std::sync::atomic::Ordering::SeqCst); + let mut env = Env::new(EnvSpec { + watch_secs: 3, + ..Default::default() + }) + .await; + // A full disk, as far as paused.json is concerned. + env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "paused.json")]); + let kept = env.add_host(host("a.test", &good.url(), true)).await; + let good_edge = env.file("edge/edge.json"); + let good_tree = env.git(&["rev-parse", "refs/heads/main^{tree}"]); + let r = env + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("b.test", &sick.url(), true) })), + ) + .await; + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while env + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await + .json["commit"] + .is_null() + { + assert!(std::time::Instant::now() < deadline); + tokio::time::sleep(Duration::from_millis(20)).await; + } + let lock = env.repo().join("refs/heads/main.lock"); + std::fs::write(&lock, "").unwrap(); + let rec = env.wait_apply(&id).await; + assert_eq!(rec["state"], "needs_attention", "{rec}"); + // The pause is not on disk, so the journal must stay, at `reverting`. + assert!(!env.dir.join("state/paused.json").exists()); + let j: serde_json::Value = + serde_json::from_str(&env.file("state/journal.json")).expect("journal kept"); + assert_eq!(j["stage"], "reverting", "{j}"); + + // Restart while the branch is still locked: still no unverified config for edge. + env.kill_control(); + env.start_control(None); + assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge)); + assert_eq!(env.file("edge/edge.json"), good_edge); + let o = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text); + + // Restart once the lock is gone: recovery finishes the revert and resumes. + env.kill_control(); + std::fs::remove_file(&lock).unwrap(); + env.start_control(None); + let rec = env + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await; + assert_eq!(rec.json["state"], "reverted", "{}", rec.text); + assert_eq!(env.git(&["rev-parse", "refs/heads/main^{tree}"]), good_tree); + let o = env.call("GET", "/api/v1/overview", None).await; + assert!(o.json["paused"].is_null(), "{}", o.text); + assert_eq!(o.json["undo"]["target"]["change_id"], kept["id"]); + env.assert_consistent().await; + } + + // ------------------------------------------------------------ undo, restore, conflicts + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn undo_names_its_target_and_undo_after_undo_is_a_redo() { + let good = Echo::start("good").await; + let sick = Echo::start("sick").await; + sick.health.store(500, std::sync::atomic::Ordering::SeqCst); + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + let u = env.call("GET", "/api/v1/undo", None).await; + assert_eq!(u.json["blocked"]["code"], "undo.nothing", "{}", u.text); + + let a = env.add_host(host("a.test", &good.url(), false)).await; + let b = env.add_host(host("b.test", &good.url(), false)).await; + // A reverted attempt does not become the Undo target. + let failed = env.add_host(host("c.test", &sick.url(), true)).await; + assert_eq!(failed["state"], "reverted"); + let u = env.call("GET", "/api/v1/undo", None).await; + assert_eq!(u.json["target"]["change_id"], b["id"], "{}", u.text); + assert_eq!(u.json["target"]["summary"], "Added b.test"); + assert_eq!(u.json["effect"], "Removes b.test"); + + // Undo refuses a target that is not the latest kept change. + let r = env + .call( + "POST", + "/api/v1/undo", + Some(json!({ "target_change_id": a["id"] })), + ) + .await; + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "undo.target_moved"); + assert!( + r.json["error"]["message"] + .as_str() + .unwrap() + .contains("Added b.test") + ); + + let undo = env + .apply( + "POST", + "/api/v1/undo", + Some(json!({ "target_change_id": b["id"] })), + ) + .await; + assert_eq!(undo["state"], "kept", "{undo}"); + assert_eq!(undo["summary"], "Undid: Added b.test"); + assert_eq!(undo["undo_of"], b["id"]); + assert!( + !env.head_files() + .iter() + .any(|(p, _)| p == "hosts/b.test.toml") + ); + + // Undo again: a redo, and it says so. + let u = env.call("GET", "/api/v1/undo", None).await; + assert_eq!(u.json["target"]["change_id"], undo["id"]); + assert_eq!(u.json["effect"], "Adds b.test back", "{}", u.text); + let redo = env + .apply( + "POST", + "/api/v1/undo", + Some(json!({ "target_change_id": undo["id"] })), + ) + .await; + assert_eq!(redo["state"], "kept"); + assert!( + env.head_files() + .iter() + .any(|(p, _)| p == "hosts/b.test.toml") + ); + + // Restore the version after the first change, as a new change. + let p = env + .call( + "GET", + &format!( + "/api/v1/history/{}/restore-preview", + a["id"].as_str().unwrap() + ), + None, + ) + .await; + assert_eq!(p.json["restorable"], true, "{}", p.text); + assert_eq!(p.json["changes"][0]["hostname"], "b.test"); + assert_eq!(p.json["changes"][0]["effect"], "removed"); + let head = env.head(); + let r = env + .apply( + "POST", + "/api/v1/restore", + Some(json!({ "change_id": a["id"], "base_rev": head })), + ) + .await; + assert_eq!(r["state"], "kept", "{r}"); + assert_eq!(r["kind"], "restore"); + assert_eq!(r["restore_of"], a["id"]); + let names: Vec = env.head_files().into_iter().map(|(p, _)| p).collect(); + assert_eq!(names, ["hosts/a.test.toml", "ianitor.toml"]); + // Restoring the same version again: nothing to do. + let r = env + .call( + "POST", + "/api/v1/restore", + Some(json!({ "change_id": r["id"] })), + ) + .await; + assert_eq!(r.json["error"]["code"], "restore.same", "{}", r.text); + // A reverted change cannot be restored. + let r = env + .call( + "POST", + "/api/v1/restore", + Some(json!({ "change_id": failed["id"] })), + ) + .await; + assert_eq!(r.json["error"]["code"], "restore.not_kept", "{}", r.text); + env.assert_consistent().await; + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn an_edit_from_an_old_form_is_refused_only_if_the_same_host_changed() { + let good = Echo::start("good").await; + let mut env = Env::new(EnvSpec::default()).await; + env.start_control(None); + env.add_host(host("a.test", &good.url(), false)).await; + let form = env.call("GET", "/api/v1/hosts/a.test", None).await; + let rev = form.json["rev"].as_str().unwrap().to_owned(); + // Another host changes: no conflict. + env.add_host(host("b.test", &good.url(), false)).await; + let mut edited = host("a.test", &good.url(), false); + edited["websockets"] = json!(false); + let r = env + .apply( + "PUT", + "/api/v1/hosts/a.test", + Some(json!({ "host": edited.clone(), "base_rev": rev })), + ) + .await; + assert_eq!(r["state"], "kept", "{r}"); + // The same host changed since the form was loaded: refused, with who and when. + edited["access_log"] = json!("truncated"); + let r = env + .call( + "PUT", + "/api/v1/hosts/a.test", + Some(json!({ "host": edited, "base_rev": rev })), + ) + .await; + assert_eq!(r.status, 409, "{}", r.text); + assert_eq!(r.json["error"]["code"], "change.conflict"); + assert_eq!(r.json["error"]["params"]["summary"], "Changed a.test"); + } + + // ------------------------------------------------------------ push + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn kept_changes_are_pushed_and_a_failed_push_keeps_the_change() { + let good = Echo::start("good").await; + let remote_dir = ianitor_testkit::proc::TempDir::new("remote"); + let remote = remote_dir.join("routes-remote.git"); + let mut env = Env::new(EnvSpec { + remote: Some(remote.to_string_lossy().into_owned()), + ..Default::default() + }) + .await; + // The remote does not exist yet: the push fails, the change is still kept. + env.start_control(None); + let r = env.add_host(host("a.test", &good.url(), false)).await; + assert_eq!(r["state"], "kept", "{r}"); + tokio::time::sleep(Duration::from_secs(1)).await; + let o = env.call("GET", "/api/v1/overview", None).await; + assert_eq!( + o.json["repo"]["push_error_code"], "push.failed.unreachable", + "{}", + o.text + ); + assert!(o.json["repo"]["unpushed"].as_u64().unwrap() >= 1); + assert!( + env.head_files() + .iter() + .any(|(p, _)| p == "hosts/a.test.toml") + ); + env.assert_consistent().await; + + // Create the remote and push now. + let st = std::process::Command::new("git") + .args(["init", "--bare", "--quiet"]) + .arg(&remote) + .status() + .unwrap(); + assert!(st.success()); + let r = env.call("POST", "/api/v1/repo/push", None).await; + assert_eq!(r.status, 200, "{}", r.text); + assert!(r.json["push_error_code"].is_null(), "{}", r.text); + assert_eq!(r.json["unpushed"], 0); + let remote_head = std::process::Command::new("git") + .env("GIT_DIR", &remote) + .args(["rev-parse", "refs/heads/main"]) + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&remote_head.stdout).trim(), + env.head() + ); + // The next kept change is pushed by itself. + env.add_host(host("b.test", &good.url(), false)).await; + tokio::time::sleep(Duration::from_secs(2)).await; + let remote_head = std::process::Command::new("git") + .env("GIT_DIR", &remote) + .args(["rev-parse", "refs/heads/main"]) + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&remote_head.stdout).trim(), + env.head() + ); + } + + // ------------------------------------------------------------ share links end to end + + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn share_links_end_to_end() { + let good = Echo::start("good").await; + let auth = ianitor_testkit::authelia::MockAuthelia::start().await; + let site = format!("[forward_auth]\nurl = \"{}\"\n", auth.url()); + let mut env = Env::new(EnvSpec { + site, + ..Default::default() + }) + .await; + env.start_control(None); + let mut h = host("share.test", &good.url(), false); + h["auth"] = json!("forward-auth"); + assert_eq!(env.add_host(h).await["state"], "kept"); + // Links off: refused with the plain-English reason. + let r = env + .call( + "POST", + "/api/v1/hosts/share.test/share-links", + Some(json!({})), + ) + .await; + assert_eq!(r.status, 409); + assert_eq!(r.json["error"]["code"], "share.disabled"); + let r = env + .apply( + "PATCH", + "/api/v1/hosts/share.test", + Some(json!({ "share_links": true })), + ) + .await; + assert_eq!(r["state"], "kept", "{r}"); + assert_eq!(r["kind"], "share_links"); + + let r = env + .call( + "POST", + "/api/v1/hosts/share.test/share-links", + Some(json!({ "path_prefix": "/albums", "expires_in_s": 3600 })), + ) + .await; + assert_eq!(r.status, 201, "{}", r.text); + let url = r.json["url"].as_str().unwrap().to_owned(); + let id = r.json["id"].as_str().unwrap().to_owned(); + assert!( + url.starts_with(&format!( + "https://share.test:{}/albums?share=ish1.", + env.opts.https_listen.port() + )), + "{url}" + ); + let path = url + .split_once(&format!(":{}", env.opts.https_listen.port())) + .unwrap() + .1 + .to_owned(); + + let visit = |p: String, cookie: Option| { + let mut req = Req::get("share.test", &p); + if let Some(c) = cookie { + req = req.header("cookie", &c); + } + let (addr, roots) = (env.opts.https_listen, env.roots()); + async move { + client::https(addr, "share.test", roots, &req) + .await + .unwrap() + } + }; + let r = visit(path.clone(), None).await; + assert_eq!(r.status, 303, "{}", r.text()); + let cookie = r + .header("set-cookie") + .unwrap() + .split(';') + .next() + .unwrap() + .to_owned(); + assert_eq!( + visit("/albums/x".into(), Some(cookie.clone())).await.status, + 200 + ); + assert_eq!( + visit("/private".into(), Some(cookie.clone())).await.status, + 302, + "outside the prefix: sign-in" + ); + + let list = env.call("GET", "/api/v1/share-links", None).await; + assert_eq!(list.json["items"][0]["state"], "active"); + assert!(!list.text.contains("ish1."), "no tokens in the list"); + + // Stop: refused within seconds. + let r = env + .call("DELETE", &format!("/api/v1/share-links/{id}"), None) + .await; + assert_eq!(r.status, 204); + assert_eq!( + visit("/albums/x".into(), Some(cookie.clone())).await.status, + 302 + ); + let r = visit(path.clone(), None).await; + assert_eq!(r.status, 403); + + // replaces: the new link works, the replaced one stops. + let r1 = env + .call( + "POST", + "/api/v1/hosts/share.test/share-links", + Some(json!({})), + ) + .await; + let p1 = r1.json["url"] + .as_str() + .unwrap() + .split_once(&format!(":{}", env.opts.https_listen.port())) + .unwrap() + .1 + .to_owned(); + let r2 = env + .call( + "POST", + "/api/v1/hosts/share.test/share-links", + Some(json!({ "replaces": r1.json["id"], "password": "correct horse" })), + ) + .await; + assert_eq!(r2.status, 201, "{}", r2.text); + assert_eq!(r2.json["has_password"], true); + assert_eq!(visit(p1, None).await.status, 403, "replaced link stopped"); + // Stop all. + let r = env.call("POST", "/api/v1/share-links/stop-all", None).await; + assert_eq!(r.status, 200); + let p2 = r2.json["url"] + .as_str() + .unwrap() + .split_once(&format!(":{}", env.opts.https_listen.port())) + .unwrap() + .1 + .to_owned(); + let r = visit(p2, None).await; + // A password link shows its page before anything is proven; the POST is refused. + assert_eq!(r.status, 401); + // Tokens and passwords are not in control's log. + let log = env.control_log(); + assert!(!log.contains("ish1."), "token in the control log"); + assert!(!log.contains("correct horse")); + } +} diff --git a/crates/control/tests/common/mod.rs b/crates/control/tests/common/mod.rs new file mode 100644 index 0000000..7e5d1a9 --- /dev/null +++ b/crates/control/tests/common/mod.rs @@ -0,0 +1,565 @@ +// 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/. + +//! A control-plane test environment on 127.0.0.1: an edge running in this process (with its +//! admin socket), the real `ianitor-control` binary as a child process (so a test can kill it +//! or make it abort at a crash point), a bare routes repository, test upstreams and a test CA. +//! The first API token comes from `ianitor-control token create`, as in production. + +#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use ianitor_core::compile::{self, CompileOptions}; +use ianitor_core::{SourceFile, load}; +use ianitor_testkit::more::{JsonResp, tcp_json, unix_json}; +use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port}; +use ianitor_testkit::tls::TestCa; +use rustls::RootCertStore; +use serde_json::{Value, json}; + +pub const HOSTS: [&str; 7] = [ + "a.test", + "b.test", + "c.test", + "d.test", + "e.test", + "f.test", + "share.test", +]; +pub const SHARE_KEY: &str = "control-test-share-key-0123456789abcdef0123456789"; + +pub struct Edge { + stop: Option>, + pub http: SocketAddr, + pub https: SocketAddr, + pub admin: PathBuf, +} + +impl Drop for Edge { + fn drop(&mut self) { + if let Some(s) = self.stop.take() { + let _ = s.send(()); + } + } +} + +pub struct Env { + pub dir: TempDir, + pub ca: TestCa, + pub edge: Option, + pub control: Option, + pub api: SocketAddr, + pub token: String, + pub opts: CompileOptions, + pub watch_secs: u64, + pub remote: Option, + log_n: u32, +} + +pub struct EnvSpec { + pub watch_secs: u64, + pub site: String, + pub remote: Option, +} + +impl Default for EnvSpec { + fn default() -> Self { + EnvSpec { + watch_secs: 2, + site: String::new(), + remote: None, + } + } +} + +fn s(p: &Path) -> String { + p.to_string_lossy().into_owned() +} + +impl Env { + pub async fn new(spec: EnvSpec) -> Env { + let dir = TempDir::new("ctl"); + for d in [ + "state", + "edge", + "caddy", + "certs", + "creds", + "logs", + "edge-state", + ] { + std::fs::create_dir_all(dir.join(d)).unwrap(); + } + let ca = TestCa::new("Ianitor Control Test CA"); + for h in HOSTS { + let leaf = ca.issue(&[h]); + std::fs::write(dir.join(&format!("certs/{h}.crt")), leaf.cert_pem).unwrap(); + std::fs::write(dir.join(&format!("certs/{h}.key")), leaf.key_pem).unwrap(); + } + std::fs::write(dir.join("creds/share-link-key"), SHARE_KEY).unwrap(); + let opts = CompileOptions { + http_listen: local(free_port()), + https_listen: local(free_port()), + cert_dir: dir.str("certs"), + state_dir: dir.str("edge-state"), + access_log: dir.str("logs/access.log"), + caddy_credentials_dir: dir.str("creds"), + caddy_admin: None, + }; + // Edge starts from an empty config; control brings it in line on its first start. + let empty = load( + &SourceFile { + name: "ianitor.toml", + contents: "", + }, + &[], + ) + .unwrap(); + std::fs::write( + dir.join("edge/edge.json"), + compile::edge(&empty, &opts).unwrap(), + ) + .unwrap(); + std::fs::write( + dir.join("edge/share-revocations.json"), + "{\"epoch\":0,\"deny\":[]}", + ) + .unwrap(); + + let api = local(free_port()); + let mut env = Env { + edge: None, + control: None, + api, + token: String::new(), + opts, + watch_secs: spec.watch_secs, + remote: spec.remote.clone(), + ca, + dir, + log_n: 0, + }; + env.write_config(&spec); + env.start_edge(); + // Seed the routes repository with the site file, then make the first token. + if !spec.site.is_empty() { + env.seed_site(&spec.site); + } + env.token = env.cli_token("test"); + env + } + + fn write_config(&self, spec: &EnvSpec) { + let d = |p: &str| s(&self.dir.join(p)); + let remote = spec + .remote + .as_ref() + .map(|r| format!("remote = \"{r}\"\n")) + .unwrap_or_default(); + let text = format!( + r#"listen = "{api}" +state_dir = "{state}" +credentials_dir = "{creds}" +watch_secs = {watch} +watch_every_secs = 1 +trial_margin_secs = 2 +health_poll_secs = 1 + +[routes] +repo = "{repo}" +{remote} +[edge] +config = "{edge}/edge.json" +admin_socket = "{edge}/admin.sock" +share_revocations = "{edge}/share-revocations.json" + +[caddy] +config = "{caddy}/caddy.json" + +[compile] +http_listen = "{http}" +https_listen = "{https}" +cert_dir = "{certs}" +state_dir = "{edge_state}" +access_log = "{log}" +caddy_credentials_dir = "{creds}" +"#, + api = self.api, + state = d("state"), + creds = d("creds"), + watch = spec.watch_secs, + repo = d("routes.git"), + edge = d("edge"), + caddy = d("caddy"), + http = self.opts.http_listen, + https = self.opts.https_listen, + certs = d("certs"), + edge_state = d("edge-state"), + log = d("logs/access.log"), + ); + std::fs::write(self.dir.join("control.toml"), text).unwrap(); + } + + pub fn config_path(&self) -> PathBuf { + self.dir.join("control.toml") + } + + pub fn repo(&self) -> PathBuf { + self.dir.join("routes.git") + } + + pub fn start_edge(&mut self) { + let opts = ianitor_edge::Options { + config: self.dir.join("edge/edge.json"), + admin_socket: Some(self.dir.join("edge/admin.sock")), + share_revocations: Some(self.dir.join("edge/share-revocations.json")), + credentials_dir: Some(self.dir.join("creds")), + ..Default::default() + }; + let shared = ianitor_edge::prepare(&opts).expect("edge config"); + let server = ianitor_edge::server(shared, &opts).expect("edge server"); + let (tx, rx) = tokio::sync::oneshot::channel(); + std::thread::spawn(move || ianitor_edge::run_until(server, rx)); + assert!(wait_for_port( + self.opts.https_listen, + Duration::from_secs(20) + )); + let deadline = Instant::now() + Duration::from_secs(5); + while !self.dir.join("edge/admin.sock").exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + self.edge = Some(Edge { + stop: Some(tx), + http: self.opts.http_listen, + https: self.opts.https_listen, + admin: self.dir.join("edge/admin.sock"), + }); + } + + /// Stop the in-process edge (and wait until its listeners are gone). + pub fn stop_edge(&mut self) { + self.edge = None; + let deadline = Instant::now() + Duration::from_secs(15); + while std::net::TcpStream::connect(self.opts.https_listen).is_ok() + && Instant::now() < deadline + { + std::thread::sleep(Duration::from_millis(50)); + } + std::thread::sleep(Duration::from_millis(200)); + } + + fn command(&self) -> Command { + let mut c = Command::new(env!("CARGO_BIN_EXE_ianitor-control")); + c.env_remove("IANITOR_TEST_CRASH_AT"); + c.env_remove("IANITOR_TEST_FAIL_WRITE"); + c + } + + pub fn cli_token(&self, name: &str) -> String { + let out = self + .command() + .args(["token", "create", "--name", name, "--config"]) + .arg(self.config_path()) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let t = String::from_utf8_lossy(&out.stdout).trim().to_owned(); + assert!(t.starts_with("ian_"), "{t}"); + t + } + + /// Put an `ianitor.toml` into a fresh repository (before control first starts). + fn seed_site(&self, site: &str) { + let work = self.dir.join("seed"); + std::fs::create_dir_all(&work).unwrap(); + let git = |args: &[&str], cwd: &Path| { + let o = Command::new("git") + .args([ + "-c", + "user.name=test", + "-c", + "user.email=t@t", + "-c", + "init.defaultBranch=main", + ]) + .args(args) + .current_dir(cwd) + .output() + .unwrap(); + assert!( + o.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&o.stderr) + ); + }; + git( + &["init", "--bare", "--quiet", &s(&self.repo())], + &self.dir.join("."), + ); + git(&["init", "--quiet"], &work); + std::fs::write(work.join("ianitor.toml"), site).unwrap(); + git(&["add", "ianitor.toml"], &work); + git(&["commit", "--quiet", "-m", "Site settings"], &work); + git( + &["push", "--quiet", &s(&self.repo()), "HEAD:refs/heads/main"], + &work, + ); + let _ = std::fs::remove_dir_all(&work); + } + + pub fn control_log(&self) -> String { + let mut out = String::new(); + for i in 0..=self.log_n { + out.push_str( + &std::fs::read_to_string(self.dir.join(&format!("logs/control-{i}.log"))) + .unwrap_or_default(), + ); + } + out + } + + /// Start the control binary; with `crash_at`, it aborts when an apply reaches that stage. + pub fn start_control(&mut self, crash_at: Option<&str>) { + self.start_control_env(crash_at, &[]); + } + + /// Like [`Env::start_control`], with extra environment (fault injection). + pub fn start_control_env(&mut self, crash_at: Option<&str>, envs: &[(&str, &str)]) { + self.log_n += 1; + let log = std::fs::File::create(self.dir.join(&format!("logs/control-{}.log", self.log_n))) + .unwrap(); + let mut c = self.command(); + c.arg("--config").arg(self.config_path()); + c.env("IANITOR_LOG", "debug"); + if let Some(stage) = crash_at { + c.env("IANITOR_TEST_CRASH_AT", stage); + } + for (k, v) in envs { + c.env(k, v); + } + c.stdout(Stdio::from(log.try_clone().unwrap())) + .stderr(Stdio::from(log)); + self.control = Some(ChildGuard(c.spawn().unwrap())); + if !wait_for_port(self.api, Duration::from_secs(30)) { + panic!("control did not start:\n{}", self.control_log()); + } + } + + pub fn kill_control(&mut self) { + self.control = None; + let deadline = Instant::now() + Duration::from_secs(10); + while std::net::TcpStream::connect(self.api).is_ok() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + } + + /// Wait for control to exit by itself (a crash point). + pub fn wait_control_exit(&mut self, timeout: Duration) -> Option { + let deadline = Instant::now() + timeout; + while Instant::now() < deadline { + if let Some(c) = &mut self.control + && let Some(st) = c.0.try_wait().unwrap() + { + self.control = None; + return Some(st); + } + std::thread::sleep(Duration::from_millis(50)); + } + None + } + + pub async fn call(&self, method: &str, path: &str, body: Option) -> JsonResp { + let auth = format!("Bearer {}", self.token); + self.call_with(method, path, &[("Authorization", &auth)], body) + .await + } + + pub async fn call_with( + &self, + method: &str, + path: &str, + headers: &[(&str, &str)], + body: Option, + ) -> JsonResp { + tcp_json(self.api, method, path, headers, body.as_ref()) + .await + .unwrap_or_else(|e| panic!("{method} {path}: {e}\n{}", self.control_log())) + } + + /// Wait for an apply to end; returns its record. + pub async fn wait_apply(&self, id: &str) -> Value { + let deadline = Instant::now() + Duration::from_secs(90); + loop { + let r = self + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await; + assert_eq!(r.status, 200, "{}", r.text); + let st = r.json["state"].as_str().unwrap_or("").to_owned(); + if ["kept", "reverted", "failed", "needs_attention"].contains(&st.as_str()) { + return r.json; + } + if Instant::now() > deadline { + panic!("apply {id} still {st}:\n{}", self.control_log()); + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + } + + /// Submit and wait. + pub async fn apply(&self, method: &str, path: &str, body: Option) -> Value { + let r = self.call(method, path, body).await; + assert_eq!(r.status, 202, "{method} {path}: {}", r.text); + let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); + self.wait_apply(&id).await + } + + pub async fn add_host(&self, host: Value) -> Value { + self.apply("POST", "/api/v1/hosts", Some(json!({ "host": host }))) + .await + } + + pub async fn edge_status(&self) -> Value { + let r = unix_json(&self.dir.join("edge/admin.sock"), "GET", "/v1/status", None) + .await + .unwrap(); + r.json + } + + pub fn roots(&self) -> Arc { + self.ca.roots() + } + + pub fn git(&self, args: &[&str]) -> String { + let o = Command::new("git") + .env("GIT_DIR", self.repo()) + .args(args) + .output() + .unwrap(); + assert!( + o.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&o.stderr) + ); + String::from_utf8_lossy(&o.stdout).trim().to_owned() + } + + pub fn head(&self) -> String { + self.git(&["rev-parse", "refs/heads/main"]) + } + + /// The routes files at the branch head. + pub fn head_files(&self) -> Vec<(String, String)> { + let list = self.git(&["ls-tree", "-r", "--name-only", "refs/heads/main"]); + list.lines() + .map(|p| { + ( + p.to_owned(), + self.git(&["show", &format!("refs/heads/main:{p}")]) + "\n", + ) + }) + .collect() + } + + /// What edge.json and caddy.json must hold for the branch head. + pub fn expected_configs(&self) -> (String, String) { + let files = self.head_files(); + let site = files + .iter() + .find(|(p, _)| p == "ianitor.toml") + .map(|(_, c)| c.clone()) + .unwrap_or_default(); + let hosts: Vec = files + .iter() + .filter(|(p, _)| p != "ianitor.toml") + .map(|(p, c)| SourceFile { + name: p, + contents: c, + }) + .collect(); + let model = load( + &SourceFile { + name: "ianitor.toml", + contents: &site, + }, + &hosts, + ) + .expect("head validates"); + ( + compile::edge(&model, &self.opts).unwrap(), + compile::caddy(&model, &self.opts).unwrap(), + ) + } + + pub fn file(&self, p: &str) -> String { + std::fs::read_to_string(self.dir.join(p)).unwrap_or_default() + } + + /// The repository, both files and edge agree, and nothing is left half done. + pub async fn assert_consistent(&self) { + let (edge_text, caddy_text) = self.expected_configs(); + assert_eq!( + self.file("edge/edge.json"), + edge_text, + "edge.json matches the branch head" + ); + assert_eq!( + self.file("caddy/caddy.json"), + caddy_text, + "caddy.json matches the branch head" + ); + let st = self.edge_status().await; + assert!(st["trial"].is_null(), "no trial left running: {st}"); + assert_eq!( + st["config_sha256"], + sha256(&edge_text), + "edge runs edge.json" + ); + assert!( + !self.dir.join("edge/edge.json.trial").exists(), + "no trial file left" + ); + assert!( + !self.dir.join("caddy/caddy.json.trial").exists(), + "no Caddy trial file left" + ); + assert!( + !self.dir.join("state/journal.json").exists(), + "no journal left" + ); + } +} + +pub fn sha256(text: &str) -> String { + ring::digest::digest(&ring::digest::SHA256, text.as_bytes()) + .as_ref() + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// A host body for the API. +pub fn host(name: &str, upstream: &str, health: bool) -> Value { + let mut h = json!({ + "hostname": name, + "upstreams": [upstream], + "tls": "domi", + "auth": "none", + "websockets": true, + "share_links": false, + "access_log": "off", + }); + if health { + h["health_check"] = json!({ "path": "/healthz", "interval_secs": 1 }); + } + h +} diff --git a/crates/control/tests/stores.rs b/crates/control/tests/stores.rs new file mode 100644 index 0000000..716880b --- /dev/null +++ b/crates/control/tests/stores.rs @@ -0,0 +1,198 @@ +// 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/. + +//! Token and share-link stores (QC fix round 1, M2 and M4): a CLI revoke is never lost to the +//! server recording token use at the same time, and losing `share-links.json` never revives a +//! stopped link. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use ianitor_control::shares::Shares; +use ianitor_control::tokens::{Refusal, Tokens}; +use ianitor_core::share::ShareKey; +use ianitor_testkit::proc::TempDir; +use serde_json::Value; + +fn revocations(p: &std::path::Path) -> Value { + serde_json::from_slice(&std::fs::read(p).unwrap()).unwrap() +} + +#[test] +fn a_cli_revoke_is_not_lost_while_the_server_records_token_use() { + let bin = env!("CARGO_BIN_EXE_ianitor-control"); + let rounds = 20; + let mut lost = 0; + for _ in 0..rounds { + let d = TempDir::new("tok-race"); + let server = Tokens::new(d.path()); + let values: Vec<_> = (0..150) + .map(|i| server.create(&format!("t{i}"), None).unwrap()) + .collect(); + let victim = values[75].0.id.clone(); + let mut cli = std::process::Command::new(bin) + .args(["token", "revoke", &victim, "--state-dir"]) + .arg(d.path()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap(); + for (_, v) in &values { + let _ = server.check(Some(&format!("Bearer {v}"))); + } + assert!(cli.wait().unwrap().success()); + if !matches!( + server.check(Some(&format!("Bearer {}", values[75].1))), + Err(Refusal::Revoked(_)) + ) { + lost += 1; + } + } + assert_eq!( + lost, 0, + "the CLI said revoked but the token still worked in {lost}/{rounds} rounds" + ); +} + +#[test] +fn concurrent_creates_from_the_cli_and_the_server_all_survive() { + let bin = env!("CARGO_BIN_EXE_ianitor-control"); + let d = TempDir::new("tok-create"); + let server = Tokens::new(d.path()); + let mut clis: Vec<_> = (0..8) + .map(|i| { + std::process::Command::new(bin) + .args([ + "token", + "create", + "--name", + &format!("cli{i}"), + "--state-dir", + ]) + .arg(d.path()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap() + }) + .collect(); + for i in 0..40 { + server.create(&format!("srv{i}"), None).unwrap(); + } + for c in &mut clis { + assert!(c.wait().unwrap().success()); + } + assert_eq!(server.list().unwrap().len(), 48); +} + +#[test] +fn losing_share_links_json_never_lowers_the_revocation_epoch() { + let d = TempDir::new("epoch"); + let rev = d.join("share-revocations.json"); + let s = Shares::new(d.path(), &rev); + let key = ShareKey::new(&[9u8; 32]).unwrap(); + let m = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap(); + s.stop(&m.record.id).unwrap(); + s.stop_all().unwrap(); + s.stop_all().unwrap(); + assert_eq!(revocations(&rev)["epoch"], 2); + std::fs::remove_file(d.join("share-links.json")).unwrap(); + Shares::new(d.path(), &rev) + .ensure_revocation_file() + .unwrap(); + assert!( + revocations(&rev)["epoch"].as_u64().unwrap() >= 2, + "{}", + revocations(&rev) + ); + // Minting after the loss continues from there. + let m2 = Shares::new(d.path(), &rev) + .mint(&key, "a.test", "/", 3600, None, None, "t") + .unwrap(); + assert!(m2.record.epoch >= 2); +} + +#[test] +fn a_lost_deny_list_raises_the_epoch_instead_of_shrinking() { + let d = TempDir::new("deny"); + let rev = d.join("share-revocations.json"); + let s = Shares::new(d.path(), &rev); + let key = ShareKey::new(&[9u8; 32]).unwrap(); + let a = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap(); + let _b = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap(); + s.stop(&a.record.id).unwrap(); + let before = revocations(&rev); + assert_eq!(before["deny"][0], a.record.id); + assert_eq!(before["epoch"], 0); + // The records are gone (or an older backup without the stop is restored). + std::fs::remove_file(d.join("share-links.json")).unwrap(); + Shares::new(d.path(), &rev) + .ensure_revocation_file() + .unwrap(); + let after = revocations(&rev); + let still_denied = after["deny"] + .as_array() + .unwrap() + .iter() + .any(|x| x == &before["deny"][0]); + assert!( + still_denied || after["epoch"].as_u64().unwrap() > 0, + "stopped link {} works again: {after}", + a.record.id + ); +} + +#[test] +fn a_deny_list_that_would_overflow_raises_the_epoch() { + let d = TempDir::new("overflow"); + let rev = d.join("share-revocations.json"); + let s = Shares::new(d.path(), &rev); + let t = ianitor_control::util::now(); + let links: Vec = (0..10_050u32) + .map(|i| { + serde_json::json!({ + "id": format!("{:032x}", i + 1), "hostname": "a.test", "path_prefix": "/", "epoch": 0, + "created_at": t, "expires_at": t + 3600, "has_password": false, "created_by": "t", + "stopped_at": t + }) + }) + .collect(); + std::fs::write( + d.join("share-links.json"), + serde_json::json!({ "epoch": 0, "links": links }).to_string(), + ) + .unwrap(); + s.ensure_revocation_file().unwrap(); + let r = revocations(&rev); + assert!( + r["epoch"].as_u64().unwrap() >= 1, + "an overflowing deny list must raise the epoch: {}", + r["epoch"] + ); + assert!(r["deny"].as_array().unwrap().len() < 10_000); +} + +#[test] +fn a_link_minted_after_the_records_were_lost_works() { + let d = TempDir::new("doa"); + let rev = d.join("share-revocations.json"); + let s = Shares::new(d.path(), &rev); + let key = ShareKey::new(&[9u8; 32]).unwrap(); + let a = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap(); + s.stop(&a.record.id).unwrap(); + std::fs::remove_file(d.join("share-links.json")).unwrap(); + let b = s.mint(&key, "a.test", "/", 3600, None, None, "t").unwrap(); + let published = revocations(&rev); + assert!( + u64::from(b.record.epoch) >= published["epoch"].as_u64().unwrap(), + "dead on arrival: link epoch {} < published {}", + b.record.epoch, + published["epoch"] + ); + let list = s.load().unwrap(); + let rec = list.links.iter().find(|l| l.id == b.record.id).unwrap(); + assert_eq!( + rec.state(list.epoch, ianitor_control::util::now()), + "active" + ); +} diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 51de11d..4c526bc 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -13,6 +13,9 @@ serde_json.workspace = true toml.workspace = true thiserror.workspace = true url.workspace = true +ring.workspace = true +base64.workspace = true +unicode-normalization = "0.1.24" [lints] workspace = true diff --git a/crates/core/src/compile/edge.rs b/crates/core/src/compile/edge.rs index e6d7e13..65a80c3 100644 --- a/crates/core/src/compile/edge.rs +++ b/crates/core/src/compile/edge.rs @@ -54,6 +54,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig { interval_secs: hc.interval_secs, }), access_log: h.access_log == AccessLog::Truncated, + share_links: h.share_links, }) .collect(), } diff --git a/crates/core/src/edge_config.rs b/crates/core/src/edge_config.rs index a50d8c9..fdece67 100644 --- a/crates/core/src/edge_config.rs +++ b/crates/core/src/edge_config.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; /// Bumped on any incompatible change; edge refuses other versions. -pub const EDGE_CONFIG_VERSION: u32 = 1; +pub const EDGE_CONFIG_VERSION: u32 = 2; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -103,4 +103,7 @@ pub struct EdgeHost { pub response_headers: Vec, pub health_check: Option, pub access_log: bool, + /// Share-link tokens (see `ianitor_core::share`) let visitors in on this host without + /// forward-auth. Checked against the key credential and the revocation file. + pub share_links: bool, } diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index ed088dd..a371155 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -2,11 +2,67 @@ // 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/. -//! Typed validation errors. Every message names the file and says what is wrong in plain English, -//! so the UI can show it as is. +//! Typed validation errors. Every message names the file and says what is wrong in plain English. +//! +//! Each error also has a stable [`ValidationError::code`], the form field it is about +//! ([`ValidationError::field`], e.g. `upstreams[1]`) and the values the UI shows in bold +//! ([`ValidationError::params`]). The control API maps the code to the UI's copy +//! (docs/ui-api.md §3.1) and keeps the `Display` text below as the technical detail. +use std::collections::BTreeMap; use std::fmt; +/// The reasons carried in `&'static str` fields. [`ValidationError::code`] compares them by +/// value, so every reason is written once, here. +pub(crate) mod reason { + pub const HOST_EMPTY: &str = "it is empty"; + pub const HOST_TOO_LONG: &str = "it is longer than 253 characters"; + pub const HOST_IP: &str = "IP addresses are not hostnames"; + pub const HOST_WILDCARD: &str = "wildcards are not supported"; + pub const HOST_TRAILING_DOT: &str = "it must not end with a dot"; + pub const HOST_UPPERCASE: &str = "it must be lowercase"; + pub const HOST_SPACES: &str = "it must not contain spaces"; + pub const HOST_EMPTY_LABEL: &str = "it has an empty label"; + pub const HOST_LABEL_LONG: &str = "a label is longer than 63 characters"; + pub const HOST_CHARACTERS: &str = "only a-z, 0-9, '-' and '.' are allowed"; + pub const HOST_LABEL_DASH: &str = "a label must not start or end with '-'"; + pub const HOST_NUMERIC: &str = "the last label must not be numeric"; + + pub const URL_ASCII: &str = "it must be plain ASCII without spaces"; + pub const URL_NOT_URL: &str = "it is not a URL like http://127.0.0.1:8080"; + pub const URL_SCHEME: &str = "only http:// and https:// are supported"; + pub const URL_CREDENTIALS: &str = "credentials in the URL are not allowed"; + pub const URL_FRAGMENT: &str = "a #fragment is not allowed"; + pub const URL_NO_HOST: &str = "it has no host"; + pub const URL_HOST_NAME: &str = "the host name is not valid"; + pub const URL_NO_PORT: &str = "it has no port"; + pub const URL_PORT_ZERO: &str = "port 0 is not usable"; + pub const URL_PATH: &str = "a path is not allowed; requests keep their own path"; + pub const URL_QUERY: &str = "a ?query is not allowed"; + pub const URL_BRACES: &str = "'{' and '}' are not allowed"; + pub const URL_MIXED: &str = "all upstreams of a host must use the same scheme"; + + pub const VALUE_EMPTY: &str = "an empty value is not allowed; use action = \"remove\""; + pub const VALUE_LONG: &str = "it is longer than 4096 characters"; + pub const VALUE_ASCII: &str = "only visible ASCII characters and spaces are allowed"; + pub const VALUE_BRACES: &str = "'{' and '}' are not allowed (they are placeholders in Caddy)"; + pub const VALUE_EDGE_SPACE: &str = "it must not start or end with a space"; + + pub const RULE_REMOVE_VALUE: &str = "remove takes no value or secret"; + pub const RULE_BOTH: &str = "give either value or secret, not both"; + pub const RULE_NEITHER: &str = "set needs a value or a secret"; + + pub const HEALTH_PATH: &str = + "path must start with '/' and contain only visible ASCII without '{', '}' or '#'"; + pub const HEALTH_INTERVAL: &str = "interval_secs must be between 1 and 3600"; + + pub const PATH_LAYOUT: &str = + "only ianitor.toml and hosts/.toml belong in the routes repository"; + pub const PATH_SUBDIR: &str = "folders inside hosts/ are not allowed"; + pub const PATH_NAME: &str = "the file name must be a lowercase hostname followed by .toml"; + pub const PATH_KIND: &str = "symbolic links, executables and submodules are not allowed"; +} + /// One problem found in the route files. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum ValidationError { @@ -26,8 +82,10 @@ pub enum ValidationError { DuplicateFile { file: String }, #[error("{file} is larger than {max} bytes")] FileTooLarge { file: String, max: usize }, - #[error("{file} must be named after its hostname: {hostname}.toml")] + #[error("{file} must be named after its hostname: hosts/{hostname}.toml")] FileNameMismatch { file: String, hostname: String }, + #[error("{file}: {reason}")] + UnexpectedFile { file: String, reason: &'static str }, #[error("{file}: at most {max} upstreams per host")] TooManyUpstreams { file: String, max: usize }, #[error("{file}: `{hostname}` is not a valid hostname: {reason}")] @@ -49,36 +107,64 @@ pub enum ValidationError { file: String, url: String, reason: &'static str, + /// Position in `upstreams`; `None` when the problem is about the list as a whole. + index: Option, }, #[error("{file}: upstream `{url}` is listed twice")] - DuplicateUpstream { file: String, url: String }, + DuplicateUpstream { + file: String, + url: String, + index: usize, + }, #[error("{file}: secret `{secret}` is used but not declared in the site file")] - UndefinedSecret { file: String, secret: String }, + UndefinedSecret { + file: String, + secret: String, + field: String, + }, #[error( "{file}: response header `{header}` may not use a secret; secrets only go to upstreams" )] - SecretInResponseHeader { file: String, header: String }, + SecretInResponseHeader { + file: String, + header: String, + field: String, + }, #[error( "{file}: `{name}` is not a valid secret name (use a-z, 0-9, '_' and '-', at most 64 characters)" )] InvalidSecretName { file: String, name: String }, #[error("{file}: `{name}` is not a valid header name")] - InvalidHeaderName { file: String, name: String }, + InvalidHeaderName { + file: String, + name: String, + field: String, + }, #[error("{file}: value for header `{header}` is not allowed: {reason}")] InvalidHeaderValue { file: String, header: String, reason: &'static str, + field: String, }, #[error("{file}: header `{header}` is managed by the proxy and cannot be changed by a rule")] - ProtectedHeader { file: String, header: String }, + ProtectedHeader { + file: String, + header: String, + field: String, + }, #[error("{file}: header `{header}` has more than one rule in the same list")] - DuplicateHeaderRule { file: String, header: String }, + DuplicateHeaderRule { + file: String, + header: String, + field: String, + }, #[error("{file}: rule for header `{header}` is incomplete: {reason}")] BadHeaderRule { file: String, header: String, reason: &'static str, + field: String, }, #[error("{file}: health check is not usable: {reason}")] BadHealthCheck { file: String, reason: &'static str }, @@ -97,6 +183,220 @@ fn line_suffix(line: Option) -> String { } } +impl ValidationError { + /// The file the problem is in (for a duplicate hostname: the second file). + pub fn file(&self) -> &str { + use ValidationError as E; + match self { + E::Syntax { file, .. } + | E::UnknownField { file, .. } + | E::MissingField { file, .. } + | E::InvalidValue { file, .. } + | E::DuplicateFile { file } + | E::FileTooLarge { file, .. } + | E::FileNameMismatch { file, .. } + | E::UnexpectedFile { file, .. } + | E::TooManyUpstreams { file, .. } + | E::InvalidHostname { file, .. } + | E::NoUpstreams { file } + | E::BadUpstreamUrl { file, .. } + | E::DuplicateUpstream { file, .. } + | E::UndefinedSecret { file, .. } + | E::SecretInResponseHeader { file, .. } + | E::InvalidSecretName { file, .. } + | E::InvalidHeaderName { file, .. } + | E::InvalidHeaderValue { file, .. } + | E::ProtectedHeader { file, .. } + | E::DuplicateHeaderRule { file, .. } + | E::BadHeaderRule { file, .. } + | E::BadHealthCheck { file, .. } + | E::ForwardAuthNotConfigured { file } + | E::BadForwardAuth { file, .. } + | E::BadAcme { file, .. } => file, + E::DuplicateHostname { second, .. } => second, + } + } + + /// True when the problem is in the site file (or a stray file), not in a host file. + pub fn in_site_file(&self) -> bool { + !self.file().starts_with("hosts/") + } + + /// A stable code the UI switches on, e.g. `host.upstream.no_port` (docs/ui-api.md §3.1). + pub fn code(&self) -> &'static str { + use ValidationError as E; + use reason as r; + let site = self.in_site_file(); + match self { + E::Syntax { .. } => "file.syntax", + E::UnknownField { .. } if site => "site.field.unknown", + E::UnknownField { .. } => "host.field.unknown", + E::MissingField { field, .. } if !site && field == "hostname" => { + "host.hostname.missing" + } + E::MissingField { field, .. } if !site && field == "upstreams" => { + "host.upstreams.missing" + } + E::MissingField { .. } => "file.field.missing", + E::InvalidValue { .. } => "file.field.invalid", + E::DuplicateFile { .. } => "repo.duplicate_file", + E::FileTooLarge { .. } => "file.too_large", + E::FileNameMismatch { .. } => "host.file_name", + E::UnexpectedFile { .. } => "repo.unexpected_file", + E::TooManyUpstreams { .. } => "host.upstream.too_many", + E::InvalidHostname { reason, .. } => match *reason { + x if x == r::HOST_EMPTY => "host.hostname.missing", + x if x == r::HOST_TOO_LONG => "host.hostname.too_long", + x if x == r::HOST_IP || x == r::HOST_NUMERIC => "host.hostname.numeric", + x if x == r::HOST_WILDCARD => "host.hostname.wildcard", + x if x == r::HOST_TRAILING_DOT => "host.hostname.trailing_dot", + x if x == r::HOST_UPPERCASE => "host.hostname.uppercase", + x if x == r::HOST_SPACES => "host.hostname.spaces", + x if x == r::HOST_EMPTY_LABEL => "host.hostname.empty_label", + x if x == r::HOST_LABEL_LONG => "host.hostname.label_long", + x if x == r::HOST_LABEL_DASH => "host.hostname.label_dash", + _ => "host.hostname.characters", + }, + E::DuplicateHostname { .. } => "host.hostname.taken", + E::NoUpstreams { .. } => "host.upstreams.missing", + E::BadUpstreamUrl { reason, .. } => match *reason { + x if x == r::URL_SCHEME => "host.upstream.scheme", + x if x == r::URL_CREDENTIALS => "host.upstream.credentials", + x if x == r::URL_FRAGMENT => "host.upstream.fragment", + x if x == r::URL_NO_HOST => "host.upstream.no_host", + x if x == r::URL_HOST_NAME => "host.upstream.host_name", + x if x == r::URL_NO_PORT => "host.upstream.no_port", + x if x == r::URL_PORT_ZERO => "host.upstream.port_zero", + x if x == r::URL_PATH => "host.upstream.path", + x if x == r::URL_QUERY => "host.upstream.query", + x if x == r::URL_MIXED => "host.upstream.mixed_schemes", + _ => "host.upstream.not_url", + }, + E::DuplicateUpstream { .. } => "host.upstream.duplicate", + E::UndefinedSecret { .. } => "host.header.secret_unknown", + E::SecretInResponseHeader { .. } => "host.header.secret_response", + E::InvalidSecretName { .. } => "site.secret.name", + E::InvalidHeaderName { .. } | E::ProtectedHeader { .. } if site => { + "site.forward_auth.header" + } + E::InvalidHeaderName { .. } => "host.header.name", + E::InvalidHeaderValue { reason, .. } if *reason == r::VALUE_EMPTY => { + "host.header.empty" + } + E::InvalidHeaderValue { .. } => "host.header.value", + E::ProtectedHeader { .. } => "host.header.protected", + E::DuplicateHeaderRule { .. } => "host.header.duplicate", + E::BadHeaderRule { reason, .. } => match *reason { + x if x == r::RULE_BOTH => "host.header.both", + x if x == r::RULE_REMOVE_VALUE => "host.header.remove_value", + _ => "host.header.empty", + }, + E::BadHealthCheck { reason, .. } if *reason == r::HEALTH_INTERVAL => { + "host.health.interval" + } + E::BadHealthCheck { .. } => "host.health.path", + E::ForwardAuthNotConfigured { .. } => "host.auth.not_configured", + E::BadForwardAuth { .. } => "site.forward_auth", + E::BadAcme { .. } => "site.acme", + } + } + + /// The form field the problem is about, as a path into the host body (`hostname`, + /// `upstreams[0]`, `request_headers[2].name`, `health_check.path`), or `None`. + pub fn field(&self) -> Option { + use ValidationError as E; + if self.in_site_file() { + return None; + } + match self { + E::UnknownField { field, .. } | E::MissingField { field, .. } => Some(field.clone()), + E::FileNameMismatch { .. } + | E::InvalidHostname { .. } + | E::DuplicateHostname { .. } => Some("hostname".into()), + E::TooManyUpstreams { .. } | E::NoUpstreams { .. } => Some("upstreams".into()), + E::BadUpstreamUrl { index, .. } => Some(match index { + Some(i) => format!("upstreams[{i}]"), + None => "upstreams".into(), + }), + E::DuplicateUpstream { index, .. } => Some(format!("upstreams[{index}]")), + E::UndefinedSecret { field, .. } + | E::SecretInResponseHeader { field, .. } + | E::InvalidHeaderName { field, .. } + | E::InvalidHeaderValue { field, .. } + | E::ProtectedHeader { field, .. } + | E::DuplicateHeaderRule { field, .. } + | E::BadHeaderRule { field, .. } => Some(field.clone()), + E::BadHealthCheck { reason, .. } if *reason == reason::HEALTH_INTERVAL => { + Some("health_check.interval_secs".into()) + } + E::BadHealthCheck { .. } => Some("health_check.path".into()), + E::ForwardAuthNotConfigured { .. } => Some("auth".into()), + _ => None, + } + } + + /// The values a message shows: always `file`, plus `line`, `field`, `max`, `hostname`, + /// `suggestion`, `url`, `name` or `secret` where they apply. + pub fn params(&self) -> BTreeMap<&'static str, String> { + use ValidationError as E; + let mut p = BTreeMap::new(); + p.insert("file", self.file().to_owned()); + match self { + E::Syntax { line: Some(l), .. } => { + p.insert("line", l.to_string()); + } + E::UnknownField { field, .. } | E::MissingField { field, .. } => { + p.insert("field", field.clone()); + } + E::FileTooLarge { max, .. } | E::TooManyUpstreams { max, .. } => { + p.insert("max", max.to_string()); + } + E::FileNameMismatch { hostname, .. } | E::DuplicateHostname { hostname, .. } => { + p.insert("hostname", hostname.clone()); + } + E::InvalidHostname { + hostname, reason, .. + } => { + p.insert("hostname", hostname.clone()); + if *reason == reason::HOST_UPPERCASE || *reason == reason::HOST_TRAILING_DOT { + p.insert( + "suggestion", + hostname.trim_end_matches('.').to_ascii_lowercase(), + ); + } + } + E::BadUpstreamUrl { url, reason, .. } => { + p.insert("url", url.clone()); + if [reason::URL_PATH, reason::URL_QUERY, reason::URL_FRAGMENT].contains(reason) + && let Ok(u) = url::Url::parse(url) + && let Some(host) = u.host_str() + { + let port = u.port().map(|p| format!(":{p}")).unwrap_or_default(); + p.insert("suggestion", format!("{}://{host}{port}", u.scheme())); + } + } + E::DuplicateUpstream { url, .. } => { + p.insert("url", url.clone()); + } + E::UndefinedSecret { secret, .. } => { + p.insert("secret", secret.clone()); + } + E::InvalidSecretName { name, .. } | E::InvalidHeaderName { name, .. } => { + p.insert("name", name.clone()); + } + E::SecretInResponseHeader { header, .. } + | E::InvalidHeaderValue { header, .. } + | E::ProtectedHeader { header, .. } + | E::DuplicateHeaderRule { header, .. } + | E::BadHeaderRule { header, .. } => { + p.insert("name", header.clone()); + } + _ => {} + } + p + } +} + /// All problems found in one load, in a stable order (file by file, then hostname checks). #[derive(Debug, Clone, PartialEq, Eq)] pub struct ValidationErrors(pub(crate) Vec); @@ -109,6 +409,11 @@ impl ValidationErrors { pub fn into_errors(self) -> Vec { self.0 } + + /// Wrap errors found outside [`crate::load`] (e.g. by [`crate::routes::check_path`]). + pub fn from_errors(errors: Vec) -> ValidationErrors { + ValidationErrors(errors) + } } impl fmt::Display for ValidationErrors { diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index eda6c33..c3536b0 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -12,12 +12,15 @@ pub mod compile; pub mod edge_config; mod error; mod model; +pub mod routes; +pub mod share; +pub mod time; mod validate; pub use error::{ValidationError, ValidationErrors}; pub use model::{ AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, - HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, Model, Scheme, - SecretName, Site, TlsMode, Upstream, UpstreamHost, + HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, LETSENCRYPT_STAGING, MAX_FILE_BYTES, + MAX_UPSTREAMS, Model, Scheme, SecretName, Site, TlsMode, Upstream, UpstreamHost, }; pub use validate::{SourceFile, load}; diff --git a/crates/core/src/routes.rs b/crates/core/src/routes.rs new file mode 100644 index 0000000..9ca5430 --- /dev/null +++ b/crates/core/src/routes.rs @@ -0,0 +1,105 @@ +// 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 shape of the routes repository: exactly `ianitor.toml` and `hosts/.toml`, +//! regular files only. Anything else (other names, folders inside `hosts/`, symbolic links, +//! submodules, executables) is refused, so the repository can never hold something the +//! compilers do not read. + +use crate::error::{ValidationError, reason}; +use crate::validate::check_hostname; + +/// The site file at the root of the repository. +pub const SITE_FILE: &str = "ianitor.toml"; +/// The folder holding one file per host. +pub const HOSTS_DIR: &str = "hosts"; +/// Most host files one repository may hold. +pub const MAX_HOST_FILES: usize = 1000; + +/// What a tree entry is, as git reports it (`git ls-tree` modes). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EntryKind { + /// Mode 100644. + File, + /// Mode 100755. + Executable, + /// Mode 120000. + Symlink, + /// Mode 160000. + Submodule, +} + +/// A path the repository may hold. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RoutePath { + Site, + Host { hostname: String }, +} + +/// The path of the file for `hostname`. +pub fn host_path(hostname: &str) -> String { + format!("{HOSTS_DIR}/{hostname}.toml") +} + +/// Check one path of the repository tree (as listed recursively, `/`-separated). +pub fn check_path(path: &str, kind: EntryKind) -> Result { + let bad = |reason| ValidationError::UnexpectedFile { + file: path.to_owned(), + reason, + }; + if kind != EntryKind::File { + return Err(bad(reason::PATH_KIND)); + } + if path == SITE_FILE { + return Ok(RoutePath::Site); + } + let Some(rest) = path.strip_prefix("hosts/") else { + return Err(bad(reason::PATH_LAYOUT)); + }; + if rest.contains(['/', '\\']) { + return Err(bad(reason::PATH_SUBDIR)); + } + let Some(hostname) = rest.strip_suffix(".toml") else { + return Err(bad(reason::PATH_NAME)); + }; + if check_hostname(hostname).is_err() { + return Err(bad(reason::PATH_NAME)); + } + Ok(RoutePath::Host { + hostname: hostname.to_owned(), + }) +} + +/// Check a whole tree listing. Returns every problem; at most [`MAX_HOST_FILES`] host files. +pub fn check_tree<'a>( + entries: impl IntoIterator, +) -> Result<(), Vec> { + let mut errors = Vec::new(); + let mut hosts = 0usize; + let mut site = false; + for (path, kind) in entries { + match check_path(path, kind) { + Ok(RoutePath::Site) => site = true, + Ok(RoutePath::Host { .. }) => hosts += 1, + Err(e) => errors.push(e), + } + } + if !site { + errors.push(ValidationError::MissingField { + file: SITE_FILE.into(), + field: "(the file itself)".into(), + }); + } + if hosts > MAX_HOST_FILES { + errors.push(ValidationError::UnexpectedFile { + file: HOSTS_DIR.into(), + reason: "more than 1000 host files", + }); + } + if errors.is_empty() { + Ok(()) + } else { + Err(errors) + } +} diff --git a/crates/core/src/share.rs b/crates/core/src/share.rs new file mode 100644 index 0000000..5466a69 --- /dev/null +++ b/crates/core/src/share.rs @@ -0,0 +1,554 @@ +// 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: stateless tokens minted by control and checked by edge. +//! +//! A link token is `ish1.` + base64url(payload ‖ mac): +//! +//! ```text +//! payload = version (1) ‖ id (16) ‖ epoch (u32 BE) ‖ expires_at (u64 BE, Unix s) ‖ flags (1) ‖ path prefix +//! mac = HMAC-SHA256(key, "ianitor share link v1" 0 host 0 payload [0 HMAC-SHA256(key, "ianitor share password v1" 0 id password)]) +//! ``` +//! +//! - The host is not in the token but in the MAC, so a token for one host fails on another. +//! - With a password (flag bit 0), the MAC can only be checked by someone who has both the key +//! and the password: the token carries no password hash, so holding a link does not allow +//! guessing its password offline. Edge rate-limits guesses. +//! - The session cookie edge sets after a successful check is `iss1.` + base64url(payload ‖ +//! HMAC(key, "ianitor share session v1" 0 host 0 payload)): a different domain, so a link +//! token is never accepted as a cookie and a cookie never as a link (and a cookie for a +//! password link proves the password was given). +//! - Revocation: every token carries the epoch it was minted in; edge refuses tokens from an +//! older epoch ("stop all") and ids on the deny list ("stop this link"). +//! +//! [`path_within`] decides whether a raw request path lies under a link's prefix. It refuses +//! anything an upstream might read differently from a plain byte comparison. + +use std::collections::BTreeSet; +use std::fmt; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use ring::hmac; + +/// Name of the credential (`$CREDENTIALS_DIRECTORY/`) holding the share-link key, read by +/// both edge and control. +pub const KEY_CREDENTIAL: &str = "share-link-key"; +/// Shortest key accepted, in bytes. +pub const MIN_KEY_LEN: usize = 32; +/// Query parameter carrying a link token. Edge only takes values that start with +/// [`LINK_PREFIX`]; anything else is left to the upstream. +pub const QUERY_PARAM: &str = "share"; +/// Start of every link token. +pub const LINK_PREFIX: &str = "ish1."; +/// Start of every session cookie value. +pub const SESSION_PREFIX: &str = "iss1."; +/// Session cookie name (`__Secure-`: browsers only accept it with `Secure`). +pub const COOKIE_NAME: &str = "__Secure-ianitor-share"; +/// Path the password form posts to, on hosts with share links. +pub const PASSWORD_PATH: &str = "/.well-known/ianitor/share"; +/// Longest path prefix. +pub const MAX_PREFIX_LEN: usize = 256; +/// Password length limits, in characters. +pub const MIN_PASSWORD_CHARS: usize = 8; +pub const MAX_PASSWORD_CHARS: usize = 128; + +const VERSION: u8 = 1; +const FLAG_PASSWORD: u8 = 1; +const FIXED_LEN: usize = 1 + 16 + 4 + 8 + 1; +const MAC_LEN: usize = 32; +/// Longest token or cookie accepted before decoding. +const MAX_ENCODED_LEN: usize = 1024; + +/// A link id: 16 random bytes, written as 32 lowercase hex digits. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ShareId(pub [u8; 16]); + +impl ShareId { + pub fn to_hex(&self) -> String { + self.0.iter().map(|b| format!("{b:02x}")).collect() + } + + pub fn from_hex(s: &str) -> Option { + if s.len() != 32 + || !s + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) + { + return None; + } + let mut out = [0u8; 16]; + for (i, o) in out.iter_mut().enumerate() { + *o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?; + } + Some(ShareId(out)) + } +} + +impl fmt::Display for ShareId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.to_hex()) + } +} + +/// The HMAC key. Never printed. +pub struct ShareKey(hmac::Key); + +impl fmt::Debug for ShareKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ShareKey()") + } +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ShareError { + #[error("the share-link key must be at least {MIN_KEY_LEN} bytes")] + KeyTooShort, + #[error("the path prefix is not usable: {0}")] + Prefix(&'static str), + #[error("the password must be {MIN_PASSWORD_CHARS} to {MAX_PASSWORD_CHARS} characters")] + Password, +} + +impl ShareKey { + pub fn new(bytes: &[u8]) -> Result { + if bytes.len() < MIN_KEY_LEN { + return Err(ShareError::KeyTooShort); + } + Ok(ShareKey(hmac::Key::new(hmac::HMAC_SHA256, bytes))) + } +} + +/// What a token says. For a token checked with [`verify_link`] or [`verify_session`], all of +/// it is proven by the MAC; from [`peek`], none of it is. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Claims { + pub id: ShareId, + pub epoch: u32, + pub expires_at: u64, + pub password: bool, + pub prefix: String, +} + +/// What to mint. +#[derive(Debug, Clone)] +pub struct LinkSpec<'a> { + pub id: ShareId, + pub epoch: u32, + pub expires_at: u64, + /// Already checked with [`check_prefix`]. + pub prefix: &'a str, + pub password: Option<&'a str>, +} + +/// Why a token was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Rejection { + /// Not a token at all (bad encoding, wrong version, too long). + Malformed, + /// The MAC does not match: altered, minted for another host, made with another key, or + /// (for a password link) the wrong password. + Invalid, + /// The link needs a password and none was given. + PasswordRequired, + /// Proven genuine, but past its expiry. + Expired { expires_at: u64 }, + /// Proven genuine, but stopped (deny list or an older epoch). + Revoked, +} + +/// The revocation state edge checks against (from the deny-list file control writes). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Revocations { + /// Tokens minted in an older epoch are refused ("stop all"). + pub epoch: u32, + /// Stopped links. + pub deny: BTreeSet, +} + +impl Revocations { + pub fn is_revoked(&self, c: &Claims) -> bool { + c.epoch < self.epoch || self.deny.contains(&c.id) + } +} + +fn payload(spec: &LinkSpec<'_>) -> Vec { + let mut p = Vec::with_capacity(FIXED_LEN + spec.prefix.len()); + p.push(VERSION); + p.extend_from_slice(&spec.id.0); + p.extend_from_slice(&spec.epoch.to_be_bytes()); + p.extend_from_slice(&spec.expires_at.to_be_bytes()); + p.push(if spec.password.is_some() { + FLAG_PASSWORD + } else { + 0 + }); + p.extend_from_slice(spec.prefix.as_bytes()); + p +} + +fn password_tag(key: &ShareKey, id: &ShareId, password: &str) -> hmac::Tag { + let mut ctx = hmac::Context::with_key(&key.0); + ctx.update(b"ianitor share password v1\0"); + ctx.update(&id.0); + ctx.update(password.as_bytes()); + ctx.sign() +} + +fn link_message( + key: &ShareKey, + host: &str, + payload: &[u8], + id: &ShareId, + password: Option<&str>, +) -> Vec { + let mut m = Vec::with_capacity(64 + host.len() + payload.len()); + m.extend_from_slice(b"ianitor share link v1\0"); + m.extend_from_slice(host.as_bytes()); + m.push(0); + m.extend_from_slice(payload); + if let Some(pw) = password { + m.push(0); + m.extend_from_slice(password_tag(key, id, pw).as_ref()); + } + m +} + +fn session_message(host: &str, payload: &[u8]) -> Vec { + let mut m = Vec::with_capacity(64 + host.len() + payload.len()); + m.extend_from_slice(b"ianitor share session v1\0"); + m.extend_from_slice(host.as_bytes()); + m.push(0); + m.extend_from_slice(payload); + m +} + +fn check_password(pw: &str) -> Result<(), ShareError> { + let n = pw.chars().count(); + if (MIN_PASSWORD_CHARS..=MAX_PASSWORD_CHARS).contains(&n) { + Ok(()) + } else { + Err(ShareError::Password) + } +} + +/// Mint a link token for `host` (a validated hostname). +pub fn mint(key: &ShareKey, host: &str, spec: &LinkSpec<'_>) -> Result { + let prefix = check_prefix(spec.prefix).map_err(ShareError::Prefix)?; + if prefix != spec.prefix { + return Err(ShareError::Prefix("it is not in its normal form")); + } + if let Some(pw) = spec.password { + check_password(pw)?; + } + let p = payload(spec); + let tag = hmac::sign( + &key.0, + &link_message(key, host, &p, &spec.id, spec.password), + ); + let mut raw = p; + raw.extend_from_slice(tag.as_ref()); + Ok(format!("{LINK_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw))) +} + +/// Split and decode without checking the MAC. Only for showing a password page. +fn decode(token: &str, prefix: &str) -> Result<(Claims, Vec, Vec), Rejection> { + if token.len() > MAX_ENCODED_LEN { + return Err(Rejection::Malformed); + } + let body = token.strip_prefix(prefix).ok_or(Rejection::Malformed)?; + let raw = URL_SAFE_NO_PAD + .decode(body) + .map_err(|_| Rejection::Malformed)?; + if raw.len() < FIXED_LEN + MAC_LEN + 1 { + return Err(Rejection::Malformed); + } + let (p, mac) = raw.split_at(raw.len() - MAC_LEN); + if p[0] != VERSION || p[FIXED_LEN - 1] & !FLAG_PASSWORD != 0 { + return Err(Rejection::Malformed); + } + let mut id = [0u8; 16]; + id.copy_from_slice(&p[1..17]); + let mut e = [0u8; 4]; + e.copy_from_slice(&p[17..21]); + let mut x = [0u8; 8]; + x.copy_from_slice(&p[21..29]); + let prefix = std::str::from_utf8(&p[FIXED_LEN..]).map_err(|_| Rejection::Malformed)?; + // A token whose prefix is not in normal form was never minted. + if check_prefix(prefix).ok().as_deref() != Some(prefix) { + return Err(Rejection::Malformed); + } + Ok(( + Claims { + id: ShareId(id), + epoch: u32::from_be_bytes(e), + expires_at: u64::from_be_bytes(x), + password: p[FIXED_LEN - 1] & FLAG_PASSWORD != 0, + prefix: prefix.to_owned(), + }, + p.to_vec(), + mac.to_vec(), + )) +} + +/// What a link token claims, unchecked (for the password page: is a password needed, and +/// until when does it claim to work). Never grant anything on this alone. +pub fn peek(token: &str) -> Result { + decode(token, LINK_PREFIX).map(|(c, _, _)| c) +} + +/// Check a link token for `host`. The order of checks fixes what a visitor learns: a password +/// is asked for before anything else is proven; expiry and revocation are reported only for +/// tokens proven genuine. +pub fn verify_link( + key: &ShareKey, + host: &str, + token: &str, + password: Option<&str>, + now: u64, + revocations: &Revocations, +) -> Result { + let (claims, p, mac) = decode(token, LINK_PREFIX)?; + let password = match (claims.password, password) { + (true, None) => return Err(Rejection::PasswordRequired), + (true, Some(pw)) => Some(pw), + (false, _) => None, + }; + let msg = link_message(key, host, &p, &claims.id, password); + hmac::verify(&key.0, &msg, &mac).map_err(|_| Rejection::Invalid)?; + finish(claims, now, revocations) +} + +fn finish(claims: Claims, now: u64, revocations: &Revocations) -> Result { + if now >= claims.expires_at { + return Err(Rejection::Expired { + expires_at: claims.expires_at, + }); + } + if revocations.is_revoked(&claims) { + return Err(Rejection::Revoked); + } + Ok(claims) +} + +/// The session cookie value for claims proven by [`verify_link`]. +pub fn session_value(key: &ShareKey, host: &str, claims: &Claims) -> String { + let spec = LinkSpec { + id: claims.id, + epoch: claims.epoch, + expires_at: claims.expires_at, + prefix: &claims.prefix, + password: claims.password.then_some(""), + }; + let p = payload(&spec); + let tag = hmac::sign(&key.0, &session_message(host, &p)); + let mut raw = p; + raw.extend_from_slice(tag.as_ref()); + format!("{SESSION_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw)) +} + +/// Check a session cookie value for `host`. +pub fn verify_session( + key: &ShareKey, + host: &str, + value: &str, + now: u64, + revocations: &Revocations, +) -> Result { + let (claims, p, mac) = decode(value, SESSION_PREFIX)?; + hmac::verify(&key.0, &session_message(host, &p), &mac).map_err(|_| Rejection::Invalid)?; + finish(claims, now, revocations) +} + +/// Normalise and check a path prefix: starts with `/`, at most [`MAX_PREFIX_LEN`] bytes, only +/// unreserved characters and `!$&'()*+,=:@-._~`, no `%`, `;`, backslash, empty segment or dot +/// segment. A trailing `/` is dropped (except for `/` itself). +pub fn check_prefix(prefix: &str) -> Result { + if !prefix.starts_with('/') { + return Err("it must start with /"); + } + if prefix.len() > MAX_PREFIX_LEN { + return Err("it is longer than 256 characters"); + } + let ok = |c: u8| c.is_ascii_alphanumeric() || b"/!$&'()*+,=:@-._~".contains(&c); + if !prefix.bytes().all(ok) { + return Err("only letters, digits, / and -._~!$&'()*+,=:@ are allowed"); + } + if prefix.contains("//") { + return Err("it has an empty segment (//)"); + } + let trimmed = if prefix.len() > 1 { + prefix.strip_suffix('/').unwrap_or(prefix) + } else { + prefix + }; + if trimmed == "/" { + return Ok("/".into()); + } + for seg in trimmed[1..].split('/') { + if seg.is_empty() { + return Err("it has an empty segment (//)"); + } + if seg.bytes().all(|c| c == b'.') { + return Err("it has a . or .. segment"); + } + } + Ok(trimmed.to_owned()) +} + +/// Percent-encodings no plain path needs (lowercased before matching): `.`, `/`, `\`, `%` +/// itself (double encoding), NUL, and IIS `%u` escapes. +pub const REFUSED_ENCODINGS: &[&str] = &["%2e", "%2f", "%5c", "%25", "%00", "%u"]; + +/// ASCII characters a look-alike must not stand for after NFKC normalisation. +/// ASCII characters a non-ASCII character must not turn into under NFKC. +const STRUCTURAL: &[char] = &['/', '\\', ';', '?', '#', '%']; + +/// Slash and backslash look-alikes NFKC leaves alone (some upstreams still treat them as +/// separators): division slash, fraction slash, big solidus, big reverse solidus, set minus, +/// reverse solidus operator, box-drawing diagonals. +const SLASH_LOOKALIKES: &[char] = &[ + '\u{2215}', '\u{2044}', '\u{29F8}', '\u{29F9}', '\u{2216}', '\u{29F5}', '\u{2571}', '\u{2572}', +]; + +/// Unicode's Default_Ignorable_Code_Point (DerivedCoreProperties.txt, Unicode 15). +fn default_ignorable(c: char) -> bool { + matches!( + c as u32, + 0x00AD + | 0x034F + | 0x061C + | 0x115F..=0x1160 + | 0x17B4..=0x17B5 + | 0x180B..=0x180F + | 0x200B..=0x200F + | 0x202A..=0x202E + | 0x2060..=0x206F + | 0x3164 + | 0xFE00..=0xFE0F + | 0xFEFF + | 0xFFA0 + | 0xFFF0..=0xFFF8 + | 0x1BCA0..=0x1BCA3 + | 0x1D173..=0x1D17A + | 0xE0000..=0xE0FFF + ) +} + +/// Decode `%xx` escapes once. `None` for a broken escape. +fn percent_decode(raw: &str) -> Option> { + let b = raw.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + if b[i] == b'%' { + let hex = raw.get(i + 1..i + 3)?; + // from_str_radix would also take "+f". + if !hex.bytes().all(|c| c.is_ascii_hexdigit()) { + return None; + } + out.push(u8::from_str_radix(hex, 16).ok()?); + i += 3; + } else { + out.push(b[i]); + i += 1; + } + } + Some(out) +} + +/// Is `raw_path` (the request path exactly as sent, still percent-encoded) under `prefix`? +/// +/// Refused outright, whatever the prefix: +/// - anything but visible ASCII, a backslash, an empty segment (`//`); +/// - the encodings in [`REFUSED_ENCODINGS`] and broken `%` escapes; +/// - escapes that do not decode to valid UTF-8 (this refuses every overlong form, such as +/// `%c0%ae`); +/// - any encoded character that NFKC normalisation turns into something containing `/`, `\`, +/// `;`, `?`, `#`, `%` or a control character (fullwidth and small forms), and the slash +/// look-alikes NFKC leaves alone ([`SLASH_LOOKALIKES`]); +/// - a segment that NFKC turns into only dots or nothing, after dropping default-ignorable +/// characters and combining marks and trimming whitespace (two-dot +/// leaders, ellipses, fullwidth dots, look-alike spaces); look-alike dots and spaces inside a +/// name with other characters (`Wait….pdf`, an ideographic space) are fine; +/// - a segment of only dots, also with `;params` (`..;x`, `..%3b`), and any segment that is +/// one or more dots followed by a percent-encoded byte (`..%20`, `..%3f`, `..%23`), since +/// some servers trim or decode that into a dot segment. +/// +/// Other paths match on whole segments, case-sensitively: prefix `/a` covers `/a` and `/a/x`, +/// not `/ab` or `/A`. +pub fn path_within(prefix: &str, raw_path: &str) -> bool { + use unicode_normalization::UnicodeNormalization; + if !raw_path.starts_with('/') + || !raw_path.bytes().all(|c| c.is_ascii_graphic()) + || raw_path.contains('\\') + { + return false; + } + let lower = raw_path.to_ascii_lowercase(); + if REFUSED_ENCODINGS.iter().any(|bad| lower.contains(bad)) { + return false; + } + // An empty segment anywhere but at the end (a trailing slash) is `//`. + if raw_path.contains("//") { + return false; + } + let Some(decoded) = percent_decode(raw_path) else { + return false; + }; + let Ok(decoded) = String::from_utf8(decoded) else { + return false; + }; + let looks_structural = decoded.chars().filter(|c| !c.is_ascii()).any(|c| { + SLASH_LOOKALIKES.contains(&c) + || std::iter::once(c) + .nfkc() + .any(|n| STRUCTURAL.contains(&n) || n.is_control()) + }); + if looks_structural { + return false; + } + // Dot segments as an upstream that normalises (NFKC) and trims whitespace would see them. + let segments: Vec<&str> = decoded[1..].split('/').collect(); + for (i, seg) in segments.iter().enumerate() { + if seg.is_empty() && i + 1 == segments.len() { + continue; // trailing slash + } + if seg.is_ascii() { + continue; // the raw checks below cover ASCII segments + } + // Invisible characters (default-ignorable code points, combining marks) do not count: + // `\u{200B}..` is `..` to a server that drops them. + let n: String = seg.nfkc().collect(); + let visible: String = n + .split(';') + .next() + .unwrap_or("") + .chars() + .filter(|c| { + !default_ignorable(*c) && !unicode_normalization::char::is_combining_mark(*c) + }) + .collect(); + if visible.trim().chars().all(|c| c == '.') { + return false; + } + } + for seg in lower[1..].split('/') { + // `..;x` is `..` to Tomcat and friends; `..%3b` is `..;` to servers that decode + // before splitting. + let seg = seg.replace("%3b", ";"); + let name = seg.split(';').next().unwrap_or(""); + let after_dots = name.trim_start_matches('.'); + if name.starts_with('.') && (after_dots.is_empty() || after_dots.starts_with('%')) { + return false; + } + } + if prefix == "/" { + return true; + } + match raw_path.strip_prefix(prefix) { + Some(rest) => rest.is_empty() || rest.starts_with('/'), + None => false, + } +} diff --git a/crates/core/src/time.rs b/crates/core/src/time.rs new file mode 100644 index 0000000..56eee7c --- /dev/null +++ b/crates/core/src/time.rs @@ -0,0 +1,73 @@ +// 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/. + +//! Unix seconds to calendar dates (UTC), for API timestamps and visitor pages. Pure: the +//! caller passes the time in. + +/// Days since 1970-01-01 → (year, month 1–12, day 1–31). Howard Hinnant's `civil_from_days`. +fn civil_from_days(days: i64) -> (i64, u32, u32) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +/// `2026-11-14T14:20:00Z`. +pub fn rfc3339(unix: u64) -> String { + let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2); + let (y, m, d) = civil_from_days(secs.div_euclid(86_400)); + let s = secs.rem_euclid(86_400); + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", + s / 3600, + (s / 60) % 60, + s % 60 + ) +} + +const MONTHS: [&str; 12] = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", +]; + +/// `14 November 2026` (UTC). +pub fn long_date(unix: u64) -> String { + let secs = i64::try_from(unix).unwrap_or(i64::MAX / 2); + let (y, m, d) = civil_from_days(secs.div_euclid(86_400)); + let month = MONTHS + .get(m.saturating_sub(1) as usize) + .copied() + .unwrap_or("?"); + format!("{d} {month} {y}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_dates() { + assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z"); + assert_eq!(rfc3339(951_782_400), "2000-02-29T00:00:00Z"); + assert_eq!(rfc3339(1_794_666_000), "2026-11-14T14:20:00Z"); + assert_eq!(long_date(1_794_666_000), "14 November 2026"); + assert_eq!(long_date(4_133_980_799), "31 December 2100"); + } +} diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs index f86c154..d00e3f3 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -11,7 +11,7 @@ use std::net::IpAddr; use serde::Deserialize; use serde::de::DeserializeOwned; -use crate::error::{ValidationError as E, ValidationErrors}; +use crate::error::{ValidationError as E, ValidationErrors, reason as r}; use crate::model::{ AUTHELIA_COPY_HEADERS, AccessLog, Acme, AuthMode, ForwardAuth, HeaderRule, HeaderValue, HealthCheck, Host, Hostname, LETSENCRYPT_PRODUCTION, MAX_FILE_BYTES, MAX_UPSTREAMS, Model, @@ -274,11 +274,13 @@ fn check_site(file: &str, raw: RawSite, errors: &mut Vec) -> Option { errors.push(E::InvalidHeaderName { file: file.to_owned(), name: h.clone(), + field: "forward_auth.copy_headers".into(), }); } else if is_protected(h) { errors.push(E::ProtectedHeader { file: file.to_owned(), header: h.clone(), + field: "forward_auth.copy_headers".into(), }); } else if !seen.insert(h.to_ascii_lowercase()) { errors.push(bad("copy_headers lists a header twice")); @@ -375,9 +377,8 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec reason, }), Ok(()) => { - // One TOML per host, named after it: `hosts/.toml`. - let base = file.rsplit(['/', '\\']).next().unwrap_or(file); - if base != format!("{}.toml", raw.hostname) { + // One TOML per host, named after it: exactly `hosts/.toml`. + if file != format!("hosts/{}.toml", raw.hostname) { errors.push(E::FileNameMismatch { file: f(), hostname: raw.hostname.clone(), @@ -397,7 +398,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec } let mut upstreams: Vec = Vec::new(); let mut seen_upstreams = BTreeSet::new(); - for u in raw.upstreams.iter().take(MAX_UPSTREAMS) { + for (index, u) in raw.upstreams.iter().take(MAX_UPSTREAMS).enumerate() { match parse_url(u, false) { Ok((up, _)) => { if seen_upstreams.insert(up.clone()) { @@ -405,14 +406,16 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec } else { errors.push(E::DuplicateUpstream { file: f(), - url: u.clone(), + url: shown_url(u), + index, }); } } Err(reason) => errors.push(E::BadUpstreamUrl { file: f(), - url: u.clone(), + url: shown_url(u), reason, + index: Some(index), }), } } @@ -420,8 +423,14 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec if upstreams.windows(2).any(|w| w[0].scheme != w[1].scheme) { errors.push(E::BadUpstreamUrl { file: f(), - url: raw.upstreams.join(", "), - reason: "all upstreams of a host must use the same scheme", + url: raw + .upstreams + .iter() + .map(|u| shown_url(u)) + .collect::>() + .join(", "), + reason: r::URL_MIXED, + index: None, }); } @@ -450,8 +459,22 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec } AuthMode::None => Vec::new(), }; - let request_headers = check_rules(file, raw.request_headers, true, &identity, site, errors); - let response_headers = check_rules(file, raw.response_headers, false, &[], site, errors); + let request_headers = check_rules( + file, + "request_headers", + raw.request_headers, + &identity, + site, + errors, + ); + let response_headers = check_rules( + file, + "response_headers", + raw.response_headers, + &[], + site, + errors, + ); let health_check = raw.health_check.and_then(|hc| { let bad = |reason| E::BadHealthCheck { file: f(), reason }; @@ -462,9 +485,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec .bytes() .all(|c| c.is_ascii_graphic() && !b"{}#".contains(&c)); if !ok_path { - errors.push(bad( - "path must start with '/' and contain only visible ASCII without '{', '}' or '#'", - )); + errors.push(bad(r::HEALTH_PATH)); return None; } match u32::try_from(hc.interval_secs) { @@ -473,7 +494,7 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec interval_secs: i, }), _ => { - errors.push(bad("interval_secs must be between 1 and 3600")); + errors.push(bad(r::HEALTH_INTERVAL)); None } } @@ -527,45 +548,65 @@ fn is_protected(name: &str) -> bool { fn check_rules( file: &str, + list: &str, raw: Vec, - request: bool, identity: &[String], site: Option<&Site>, errors: &mut Vec, ) -> Vec { + let request = list == "request_headers"; let f = || file.to_owned(); let mut out = Vec::new(); let mut seen = BTreeSet::new(); - for r in raw { + for (i, r) in raw.into_iter().enumerate() { + let at = |part: &str| { + if part.is_empty() { + format!("{list}[{i}]") + } else { + format!("{list}[{i}].{part}") + } + }; let header = r.name.clone(); if !valid_header_name(&r.name) { errors.push(E::InvalidHeaderName { file: f(), name: r.name, + field: at("name"), }); continue; } let lower = r.name.to_ascii_lowercase(); if is_protected(&r.name) || identity.contains(&lower) { - errors.push(E::ProtectedHeader { file: f(), header }); + errors.push(E::ProtectedHeader { + file: f(), + header, + field: at("name"), + }); continue; } if !seen.insert(lower) { - errors.push(E::DuplicateHeaderRule { file: f(), header }); + errors.push(E::DuplicateHeaderRule { + file: f(), + header, + field: at("name"), + }); continue; } let bad = |reason| E::BadHeaderRule { file: f(), header: header.clone(), reason, + field: at(if reason == r::RULE_NEITHER { + "value" + } else { + "" + }), }; match (r.action, r.value, r.secret) { (RawAction::Remove, None, None) => out.push(HeaderRule::Remove { name: r.name }), - (RawAction::Remove, _, _) => errors.push(bad("remove takes no value or secret")), - (RawAction::Set, Some(_), Some(_)) => { - errors.push(bad("give either value or secret, not both")) - } - (RawAction::Set, None, None) => errors.push(bad("set needs a value or a secret")), + (RawAction::Remove, _, _) => errors.push(bad(r::RULE_REMOVE_VALUE)), + (RawAction::Set, Some(_), Some(_)) => errors.push(bad(r::RULE_BOTH)), + (RawAction::Set, None, None) => errors.push(bad(r::RULE_NEITHER)), (RawAction::Set, Some(v), None) => match check_header_value(&v) { Ok(()) => out.push(HeaderRule::Set { name: r.name, @@ -575,15 +616,21 @@ fn check_rules( file: f(), header, reason, + field: at("value"), }), }, (RawAction::Set, None, Some(s)) => { if !request { - errors.push(E::SecretInResponseHeader { file: f(), header }); + errors.push(E::SecretInResponseHeader { + file: f(), + header, + field: at(""), + }); } else if site.is_some_and(|site| !site.secrets.contains(&SecretName(s.clone()))) { errors.push(E::UndefinedSecret { file: f(), secret: s, + field: at("secret"), }); } else { out.push(HeaderRule::Set { @@ -608,19 +655,19 @@ fn valid_header_name(n: &str) -> bool { fn check_header_value(v: &str) -> Result<(), &'static str> { if v.is_empty() { - return Err("an empty value is not allowed; use action = \"remove\""); + return Err(r::VALUE_EMPTY); } if v.len() > 4096 { - return Err("it is longer than 4096 characters"); + return Err(r::VALUE_LONG); } if !v.bytes().all(|c| (0x20..0x7f).contains(&c)) { - return Err("only visible ASCII characters and spaces are allowed"); + return Err(r::VALUE_ASCII); } if v.contains(['{', '}']) { - return Err("'{' and '}' are not allowed (they are placeholders in Caddy)"); + return Err(r::VALUE_BRACES); } if v.starts_with(' ') || v.ends_with(' ') { - return Err("it must not start or end with a space"); + return Err(r::VALUE_EDGE_SPACE); } Ok(()) } @@ -629,44 +676,47 @@ fn check_header_value(v: &str) -> Result<(), &'static str> { pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> { if h.is_empty() { - return Err("it is empty"); + return Err(r::HOST_EMPTY); } if h.len() > 253 { - return Err("it is longer than 253 characters"); + return Err(r::HOST_TOO_LONG); } if h.parse::().is_ok() || h.starts_with('[') { - return Err("IP addresses are not hostnames"); + return Err(r::HOST_IP); } if h.contains('*') { - return Err("wildcards are not supported"); + return Err(r::HOST_WILDCARD); + } + if h.contains(char::is_whitespace) { + return Err(r::HOST_SPACES); } if h.ends_with('.') { - return Err("it must not end with a dot"); + return Err(r::HOST_TRAILING_DOT); } if h.bytes().any(|c| c.is_ascii_uppercase()) { - return Err("it must be lowercase"); + return Err(r::HOST_UPPERCASE); } let mut last = ""; for label in h.split('.') { if label.is_empty() { - return Err("it has an empty label"); + return Err(r::HOST_EMPTY_LABEL); } if label.len() > 63 { - return Err("a label is longer than 63 characters"); + return Err(r::HOST_LABEL_LONG); } if !label .bytes() .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-') { - return Err("only a-z, 0-9, '-' and '.' are allowed"); + return Err(r::HOST_CHARACTERS); } if label.starts_with('-') || label.ends_with('-') { - return Err("a label must not start or end with '-'"); + return Err(r::HOST_LABEL_DASH); } last = label; } if last.bytes().all(|c| c.is_ascii_digit()) { - return Err("the last label must not be numeric"); + return Err(r::HOST_NUMERIC); } Ok(()) } @@ -675,42 +725,42 @@ pub(crate) fn check_hostname(h: &str) -> Result<(), &'static str> { /// (for the forward-auth endpoint); otherwise any path other than `/` is rejected. fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static str> { if !raw.bytes().all(|c| c.is_ascii_graphic()) { - return Err("it must be plain ASCII without spaces"); + return Err(r::URL_ASCII); } - let u = url::Url::parse(raw).map_err(|_| "it is not a URL like http://127.0.0.1:8080")?; + let u = url::Url::parse(raw).map_err(|_| r::URL_NOT_URL)?; let scheme = match u.scheme() { "http" => Scheme::Http, "https" => Scheme::Https, - _ => return Err("only http:// and https:// are supported"), + _ => return Err(r::URL_SCHEME), }; if !u.username().is_empty() || u.password().is_some() { - return Err("credentials in the URL are not allowed"); + return Err(r::URL_CREDENTIALS); } if u.fragment().is_some() { - return Err("a #fragment is not allowed"); + return Err(r::URL_FRAGMENT); } let host = match u.host() { - None => return Err("it has no host"), + None => return Err(r::URL_NO_HOST), Some(url::Host::Ipv4(ip)) => UpstreamHost::Ip(IpAddr::V4(ip)), Some(url::Host::Ipv6(ip)) => UpstreamHost::Ip(IpAddr::V6(ip)), Some(url::Host::Domain(d)) => { if check_hostname(d).is_err() { - return Err("the host name is not valid"); + return Err(r::URL_HOST_NAME); } UpstreamHost::Name(d.to_owned()) } }; - let port = u.port_or_known_default().ok_or("it has no port")?; + let port = u.port_or_known_default().ok_or(r::URL_NO_PORT)?; if port == 0 { - return Err("port 0 is not usable"); + return Err(r::URL_PORT_ZERO); } let mut path = u.path().to_owned(); if !allow_path { if path != "/" && !path.is_empty() { - return Err("a path is not allowed; requests keep their own path"); + return Err(r::URL_PATH); } if u.query().is_some() { - return Err("a ?query is not allowed"); + return Err(r::URL_QUERY); } } else { if let Some(q) = u.query() { @@ -718,8 +768,50 @@ fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static path.push_str(q); } if path.contains(['{', '}']) { - return Err("'{' and '}' are not allowed"); + return Err(r::URL_BRACES); } } Ok((Upstream { scheme, host, port }, path)) } + +/// A URL as an error may show it: everything before the last `@` (after the scheme) is +/// replaced by `…`, so a user name or password, even one containing `/`, `?` or `#`, never +/// reaches a message, a log or the API. A URL with no `@` is shown as it is. +pub(crate) fn shown_url(raw: &str) -> String { + let (scheme, rest) = match raw.find("://") { + Some(i) => (&raw[..i + 3], &raw[i + 3..]), + None => ("", raw), + }; + match rest.rfind('@') { + Some(at) => format!("{scheme}\u{2026}@{}", &rest[at + 1..]), + None => raw.to_owned(), + } +} + +#[cfg(test)] +mod shown_tests { + use super::shown_url; + + #[test] + fn userinfo_is_hidden() { + assert_eq!( + shown_url("http://user:hunter2@10.0.0.1:80/x"), + "http://\u{2026}@10.0.0.1:80/x" + ); + assert_eq!(shown_url("user:hunter2@host:80"), "\u{2026}@host:80"); + assert_eq!(shown_url("http://10.0.0.1:80"), "http://10.0.0.1:80"); + assert_eq!(shown_url("http://h/a@b"), "http://\u{2026}@b"); + assert_eq!( + shown_url("http://admin:hunter/2@10.0.0.1:80"), + "http://\u{2026}@10.0.0.1:80" + ); + assert_eq!( + shown_url("http://admin:hunter?2@10.0.0.1:80"), + "http://\u{2026}@10.0.0.1:80" + ); + assert_eq!( + shown_url("http://admin:hunter#2@10.0.0.1:80"), + "http://\u{2026}@10.0.0.1:80" + ); + } +} diff --git a/crates/core/tests/golden/edge.json b/crates/core/tests/golden/edge.json index f7bb580..d673595 100644 --- a/crates/core/tests/golden/edge.json +++ b/crates/core/tests/golden/edge.json @@ -1,5 +1,5 @@ { - "version": 1, + "version": 2, "http_listen": "0.0.0.0:80", "https_listen": "0.0.0.0:443", "https_port": 443, @@ -82,7 +82,8 @@ "path": "/api/v1/status", "interval_secs": 15 }, - "access_log": true + "access_log": true, + "share_links": false }, { "hostname": "status.example.org", @@ -101,7 +102,8 @@ "request_headers": [], "response_headers": [], "health_check": null, - "access_log": false + "access_log": false, + "share_links": false }, { "hostname": "wiki.home.test", @@ -131,7 +133,8 @@ ], "response_headers": [], "health_check": null, - "access_log": false + "access_log": false, + "share_links": false } ] } diff --git a/crates/core/tests/routes.rs b/crates/core/tests/routes.rs new file mode 100644 index 0000000..de57b3c --- /dev/null +++ b/crates/core/tests/routes.rs @@ -0,0 +1,276 @@ +// 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 holds exactly `ianitor.toml` and `hosts/.toml`, and the +//! loader requires the exact path (ROADMAP §10: the check used to look at the base name only). +//! Validation errors carry a stable code, a field path and params for the UI (docs/ui-api.md §3.1). + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use ianitor_core::routes::{EntryKind, RoutePath, check_path, check_tree}; +use ianitor_core::{SourceFile, ValidationError, load}; + +#[test] +fn only_the_site_file_and_host_files_are_allowed() { + assert_eq!( + check_path("ianitor.toml", EntryKind::File).unwrap(), + RoutePath::Site + ); + assert_eq!( + check_path("hosts/wiki.home.test.toml", EntryKind::File).unwrap(), + RoutePath::Host { + hostname: "wiki.home.test".into() + } + ); + for bad in [ + "README.md", + ".gitattributes", + "hosts.toml", + "other/wiki.home.test.toml", + "hosts/sub/wiki.home.test.toml", + "hosts/wiki.home.test.toml/x", + "hosts/Wiki.home.test.toml", + "hosts/wiki.home.test.TOML", + "hosts/wiki.home.test", + "hosts/.toml", + "hosts/*.home.test.toml", + "hosts/wiki..test.toml", + "hosts/10.0.0.1.toml", + "hosts/wiki home.toml", + "hosts\\wiki.home.test.toml", + "hosts/wiki\\x.toml", + "IANITOR.toml", + "./ianitor.toml", + ] { + let e = check_path(bad, EntryKind::File).unwrap_err(); + assert!( + matches!(e, ValidationError::UnexpectedFile { ref file, .. } if file == bad), + "{bad}: {e:?}" + ); + assert_eq!(e.code(), "repo.unexpected_file"); + } +} + +#[test] +fn links_executables_and_submodules_are_refused() { + for kind in [ + EntryKind::Symlink, + EntryKind::Submodule, + EntryKind::Executable, + ] { + assert!(check_path("hosts/a.test.toml", kind).is_err(), "{kind:?}"); + assert!(check_path("ianitor.toml", kind).is_err(), "{kind:?}"); + } +} + +#[test] +fn a_tree_needs_the_site_file_and_reports_every_stray_file() { + let ok = [ + ("ianitor.toml", EntryKind::File), + ("hosts/a.test.toml", EntryKind::File), + ]; + assert!(check_tree(ok).is_ok()); + let errs = check_tree([ + ("hosts/a.test.toml", EntryKind::File), + ("notes.txt", EntryKind::File), + ("hosts/b/c.toml", EntryKind::File), + ]) + .unwrap_err(); + assert_eq!(errs.len(), 3, "{errs:?}"); +} + +#[test] +fn the_loader_requires_the_exact_path() { + let site = SourceFile { + name: "ianitor.toml", + contents: "", + }; + let body = "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n"; + for name in [ + "app.test.toml", + "other/app.test.toml", + "hosts/x/app.test.toml", + "hosts\\app.test.toml", + "./hosts/app.test.toml", + ] { + let errs = load( + &site, + &[SourceFile { + name, + contents: body, + }], + ) + .unwrap_err(); + assert!( + errs.errors() + .iter() + .any(|e| matches!(e, ValidationError::FileNameMismatch { .. })), + "{name}: {errs:?}" + ); + } + assert!( + load( + &site, + &[SourceFile { + name: "hosts/app.test.toml", + contents: body + }] + ) + .is_ok() + ); +} + +fn errors_for(body: &str) -> Vec { + let site = SourceFile { + name: "ianitor.toml", + contents: "secrets = [\"api_key\"]\n", + }; + load( + &site, + &[SourceFile { + name: "hosts/app.test.toml", + contents: body, + }], + ) + .unwrap_err() + .into_errors() +} + +#[test] +fn errors_have_codes_fields_and_params_for_the_ui() { + let cases: &[(&str, &str, Option<&str>)] = &[ + ( + "upstreams = [\"http://127.0.0.1:1\"]\n", + "host.hostname.missing", + Some("hostname"), + ), + ( + "hostname = \"app.test\"\n", + "host.upstreams.missing", + Some("upstreams"), + ), + ( + "hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", + "host.hostname.uppercase", + Some("hostname"), + ), + ( + "hostname = \"app test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", + "host.hostname.spaces", + Some("hostname"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"ftp://x\"]\n", + "host.upstream.scheme", + Some("upstreams[1]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1/x\"]\n", + "host.upstream.path", + Some("upstreams[0]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"http://127.0.0.1:1\"]\n", + "host.upstream.duplicate", + Some("upstreams[1]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\", \"https://127.0.0.1:2\"]\n", + "host.upstream.mixed_schemes", + Some("upstreams"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\ncolour = 1\n", + "host.field.unknown", + Some("colour"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nvalue = \"1\"\n[[request_headers]]\naction = \"set\"\nname = \"Host\"\nvalue = \"x\"\n", + "host.header.protected", + Some("request_headers[1].name"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[response_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n", + "host.header.secret_response", + Some("response_headers[0]"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"nope\"\n", + "host.header.secret_unknown", + Some("request_headers[0].secret"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n[health_check]\npath = \"/x\"\ninterval_secs = 0\n", + "host.health.interval", + Some("health_check.interval_secs"), + ), + ( + "hostname = \"app.test\"\nupstreams = [\"http://127.0.0.1:1\"]\nauth = \"forward-auth\"\n", + "host.auth.not_configured", + Some("auth"), + ), + ]; + for (body, code, field) in cases { + let errs = errors_for(body); + let e = errs + .iter() + .find(|e| e.code() == *code) + .unwrap_or_else(|| panic!("no {code} for {body:?}: {errs:?}")); + assert_eq!(e.field().as_deref(), *field, "{code}"); + assert_eq!(e.params()["file"], "hosts/app.test.toml"); + } +} + +#[test] +fn params_carry_suggestions() { + let errs = errors_for("hostname = \"App.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n"); + let e = errs + .iter() + .find(|e| e.code() == "host.hostname.uppercase") + .unwrap(); + assert_eq!(e.params()["suggestion"], "app.test"); + let errs = errors_for("hostname = \"app.test\"\nupstreams = [\"http://10.0.0.2:3000/app\"]\n"); + let e = errs + .iter() + .find(|e| e.code() == "host.upstream.path") + .unwrap(); + assert_eq!(e.params()["suggestion"], "http://10.0.0.2:3000"); + assert_eq!(e.params()["url"], "http://10.0.0.2:3000/app"); +} + +#[test] +fn a_password_in_an_upstream_url_is_never_repeated() { + let errs = errors_for( + "hostname = \"app.test\"\nupstreams = [\"http://admin:hunter2@10.0.0.2:3000\", \"ftp://u:hunter2@x\", \"http://admin:hunter2@10.0.0.2:3000\"]\n", + ); + assert!(!errs.is_empty()); + for e in &errs { + let all = format!("{e} {:?} {:?}", e.params(), e.field()); + assert!(!all.contains("hunter2"), "{all}"); + } + let e = errs + .iter() + .find(|e| e.code() == "host.upstream.credentials") + .unwrap(); + assert_eq!(e.params()["url"], "http://\u{2026}@10.0.0.2:3000"); +} + +#[test] +fn credentials_with_slash_query_or_hash_are_never_repeated() { + for url in [ + "http://admin:hunter/2@10.0.0.1:80", + "http://admin:hunter?2@10.0.0.1:80", + "http://admin:hunter#2@10.0.0.1:80", + "ftp://admin:hunter2@10.0.0.1", + ] { + let errs = errors_for(&format!( + "hostname = \"app.test\"\nupstreams = [\"{url}\"]\n" + )); + assert!(!errs.is_empty(), "{url} accepted"); + for e in &errs { + let all = format!("{e} {:?}", e.params()); + assert!(!all.contains("hunter"), "{url}: {all}"); + } + } +} diff --git a/crates/core/tests/schema.rs b/crates/core/tests/schema.rs index bcd4845..53636d1 100644 --- a/crates/core/tests/schema.rs +++ b/crates/core/tests/schema.rs @@ -148,11 +148,11 @@ value = "max-age=31536000" #[test] fn hosts_are_sorted_by_hostname_whatever_the_file_order() { let a = SourceFile { - name: "b.test.toml", + name: "hosts/b.test.toml", contents: "hostname = \"b.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }; let b = SourceFile { - name: "a.test.toml", + name: "hosts/a.test.toml", contents: "hostname = \"a.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }; let m1 = load(&site(), &[a, b]).unwrap(); @@ -175,7 +175,7 @@ fn empty_site_file_is_allowed() { contents: "", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -236,7 +236,7 @@ fn rejects_unknown_field_in_site_file() { contents: "secrets = []\nsecret_values = { a = \"b\" }\n", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -348,10 +348,11 @@ fn accepts_good_hostnames() { } #[test] -fn rejects_duplicate_hostnames_across_files() { - let r = load( - &site(), - &[ +fn a_second_file_for_the_same_host_is_refused_by_its_path() { + // With the exact `hosts/.toml` rule, two files can never hold one hostname: + // the second one is in the wrong place, whatever the file order. + for order in [false, true] { + let mut files = vec![ SourceFile { name: "hosts/app.test.toml", contents: MINIMAL, @@ -360,38 +361,19 @@ fn rejects_duplicate_hostnames_across_files() { name: "other/app.test.toml", contents: MINIMAL, }, - ], - ); - let errs = r.unwrap_err(); - assert_eq!( - errs.errors(), - [ValidationError::DuplicateHostname { - hostname: "app.test".into(), - first: "hosts/app.test.toml".into(), - second: "other/app.test.toml".into() - }] - ); -} - -#[test] -fn duplicate_detection_is_independent_of_file_order() { - let r = load( - &site(), - &[ - SourceFile { - name: "other/app.test.toml", - contents: MINIMAL, - }, - SourceFile { - name: "hosts/app.test.toml", - contents: MINIMAL, - }, - ], - ); - let errs = r.unwrap_err(); - assert!( - matches!(&errs.errors()[0], ValidationError::DuplicateHostname { first, second, .. } if first == "hosts/app.test.toml" && second == "other/app.test.toml") - ); + ]; + if order { + files.reverse(); + } + let errs = load(&site(), &files).unwrap_err(); + assert_eq!( + errs.errors(), + [ValidationError::FileNameMismatch { + file: "other/app.test.toml".into(), + hostname: "app.test".into() + }] + ); + } } #[test] @@ -400,11 +382,11 @@ fn rejects_duplicate_source_file_names() { &site(), &[ SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }, SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }, ], @@ -440,7 +422,9 @@ fn rejects_bad_upstream_urls() { ] { let e = single_error(&format!("hostname = \"app.test\"\nupstreams = [{bad:?}]\n")); assert!( - matches!(e, ValidationError::BadUpstreamUrl { ref url, .. } if url == bad), + // Credentials are never repeated in an error. + matches!(e, ValidationError::BadUpstreamUrl { ref url, .. } + if url == bad || (bad.contains('@') && url == "http://\u{2026}@127.0.0.1:8080")), "upstream {bad:?} gave {e:?}" ); } @@ -485,7 +469,8 @@ fn rejects_undefined_secret_reference() { e, ValidationError::UndefinedSecret { file: "hosts/app.test.toml".into(), - secret: "nope".into() + secret: "nope".into(), + field: "request_headers[0].secret".into() } ); } @@ -498,7 +483,7 @@ fn undefined_secret_is_reported_when_site_declares_none() { contents: "", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: &format!( "{MINIMAL}[[request_headers]]\naction = \"set\"\nname = \"X-K\"\nsecret = \"api_key\"\n" ), @@ -532,7 +517,7 @@ fn rejects_bad_secret_names_in_site_file() { contents: &format!("secrets = [{bad:?}]\n"), }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -678,7 +663,7 @@ fn forward_auth_requires_site_configuration() { contents: "", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: &format!("{MINIMAL}auth = \"forward-auth\"\n"), }], ); @@ -704,7 +689,7 @@ fn rejects_bad_forward_auth_site_config() { contents: &format!("[forward_auth]\nurl = {bad:?}\n"), }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -743,15 +728,15 @@ fn collects_errors_from_every_file() { &site(), &[ SourceFile { - name: "a.test.toml", + name: "hosts/a.test.toml", contents: "hostname = \"a.test\"\nupstreams = [\"ftp://x\"]\n", }, SourceFile { - name: "B.test.toml", + name: "hosts/B.test.toml", contents: "hostname = \"B.test\"\nupstreams = [\"http://127.0.0.1:1\"]\n", }, SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }, ], @@ -830,7 +815,7 @@ fn rejects_wildcards_in_copy_headers() { contents: "[forward_auth]\nurl = \"http://127.0.0.1:9091/x\"\ncopy_headers = [\"Remote-*\"]\n", }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); @@ -861,7 +846,7 @@ fn rejects_oversized_route_files() { contents: &big, }, &[SourceFile { - name: "app.test.toml", + name: "hosts/app.test.toml", contents: MINIMAL, }], ); diff --git a/crates/core/tests/share.rs b/crates/core/tests/share.rs new file mode 100644 index 0000000..f6acff0 --- /dev/null +++ b/crates/core/tests/share.rs @@ -0,0 +1,487 @@ +// 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-link tokens (ROADMAP §6 phase 2, tests first): a token is refused when expired, for +//! the wrong path, for the wrong host, tampered, without its password or with a wrong one, +//! and no path trick lets it escape its prefix. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::BTreeSet; + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use ianitor_core::share::{ + Claims, LinkSpec, Rejection, Revocations, ShareId, ShareKey, check_prefix, mint, path_within, + peek, session_value, verify_link, verify_session, +}; + +const NOW: u64 = 1_800_000_000; +const HOST: &str = "photos.home.test"; + +fn key() -> ShareKey { + ShareKey::new(b"0123456789abcdef0123456789abcdef-test-key").unwrap() +} + +fn other_key() -> ShareKey { + ShareKey::new(b"fedcba9876543210fedcba9876543210-test-key").unwrap() +} + +fn id(n: u8) -> ShareId { + ShareId([n; 16]) +} + +fn spec<'a>(prefix: &'a str, password: Option<&'a str>) -> LinkSpec<'a> { + LinkSpec { + id: id(7), + epoch: 3, + expires_at: NOW + 3600, + prefix, + password, + } +} + +fn none() -> Revocations { + Revocations { + epoch: 3, + deny: BTreeSet::new(), + } +} + +fn token(prefix: &str, password: Option<&str>) -> String { + mint(&key(), HOST, &spec(prefix, password)).unwrap() +} + +#[test] +fn a_fresh_token_is_accepted_and_says_what_it_covers() { + let t = token("/albums/summer", None); + assert!(t.starts_with("ish1."), "{t}"); + let c = verify_link(&key(), HOST, &t, None, NOW, &none()).unwrap(); + assert_eq!( + c, + Claims { + id: id(7), + epoch: 3, + expires_at: NOW + 3600, + password: false, + prefix: "/albums/summer".into() + } + ); +} + +#[test] +fn an_expired_token_is_refused_as_expired() { + let t = token("/", None); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW + 3600, &none()), + Err(Rejection::Expired { + expires_at: NOW + 3600 + }) + ); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW + 99_999, &none()), + Err(Rejection::Expired { + expires_at: NOW + 3600 + }) + ); +} + +#[test] +fn a_token_for_another_host_is_refused() { + let t = token("/", None); + for host in [ + "other.home.test", + "PHOTOS.home.test", + "photos.home.test.", + "photos.home", + ] { + assert_eq!( + verify_link(&key(), host, &t, None, NOW, &none()), + Err(Rejection::Invalid), + "{host}" + ); + } +} + +#[test] +fn a_token_made_with_another_key_is_refused() { + let t = mint(&other_key(), HOST, &spec("/", None)).unwrap(); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &none()), + Err(Rejection::Invalid) + ); +} + +#[test] +fn every_single_bit_flip_is_refused() { + let t = token("/albums", None); + let raw = URL_SAFE_NO_PAD + .decode(t.strip_prefix("ish1.").unwrap()) + .unwrap(); + for i in 0..raw.len() { + for bit in 0..8 { + let mut r = raw.clone(); + r[i] ^= 1 << bit; + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&r)); + let got = verify_link(&key(), HOST, &forged, None, NOW, &none()); + assert!( + matches!( + got, + Err(Rejection::Invalid | Rejection::Malformed | Rejection::PasswordRequired) + ), + "byte {i} bit {bit}: {got:?}" + ); + } + } +} + +#[test] +fn a_longer_expiry_or_wider_prefix_cannot_be_spliced_in() { + let t = token("/albums/summer", None); + let raw = URL_SAFE_NO_PAD + .decode(t.strip_prefix("ish1.").unwrap()) + .unwrap(); + let (payload, mac) = raw.split_at(raw.len() - 32); + // Same MAC, prefix cut down to "/albums". + let mut p = payload[..30].to_vec(); + p.extend_from_slice(b"/albums"); + p.extend_from_slice(mac); + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p)); + assert_eq!( + verify_link(&key(), HOST, &forged, None, NOW, &none()), + Err(Rejection::Invalid) + ); + // Same MAC, expiry pushed out. + let mut p = payload.to_vec(); + p[21..29].copy_from_slice(&(NOW + 10 * 3600).to_be_bytes()); + p.extend_from_slice(mac); + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&p)); + assert_eq!( + verify_link(&key(), HOST, &forged, None, NOW, &none()), + Err(Rejection::Invalid) + ); +} + +#[test] +fn garbage_is_malformed_never_a_panic() { + for bad in [ + "", + "ish1.", + "ish1.!!!!", + "ish2.AAAA", + "iss1.AAAA", + "ish1.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + &"ish1.".repeat(400), + "ish1.\u{0}", + ] { + assert_eq!( + verify_link(&key(), HOST, bad, None, NOW, &none()), + Err(Rejection::Malformed), + "{bad:?}" + ); + } +} + +#[test] +fn a_password_link_needs_its_password() { + let t = token("/", Some("correct horse")); + assert!(peek(&t).unwrap().password); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &none()), + Err(Rejection::PasswordRequired) + ); + for wrong in ["", "correct hors", "correct horse ", "Correct horse", "x"] { + assert_eq!( + verify_link(&key(), HOST, &t, Some(wrong), NOW, &none()), + Err(Rejection::Invalid), + "{wrong:?}" + ); + } + let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap(); + assert!(c.password); +} + +#[test] +fn the_token_carries_no_password_hash() { + // Two links that differ only in the password have the same payload; only the MAC differs. + let a = token("/", Some("password-one")); + let b = token("/", Some("password-two")); + let ra = URL_SAFE_NO_PAD + .decode(a.strip_prefix("ish1.").unwrap()) + .unwrap(); + let rb = URL_SAFE_NO_PAD + .decode(b.strip_prefix("ish1.").unwrap()) + .unwrap(); + assert_eq!(ra.len(), rb.len()); + assert_eq!(ra[..ra.len() - 32], rb[..rb.len() - 32]); + assert_ne!(ra[ra.len() - 32..], rb[rb.len() - 32..]); +} + +#[test] +fn a_dropped_password_flag_does_not_open_the_link() { + let t = token("/", Some("correct horse")); + let mut raw = URL_SAFE_NO_PAD + .decode(t.strip_prefix("ish1.").unwrap()) + .unwrap(); + raw[29] = 0; + let forged = format!("ish1.{}", URL_SAFE_NO_PAD.encode(&raw)); + assert_eq!( + verify_link(&key(), HOST, &forged, None, NOW, &none()), + Err(Rejection::Invalid) + ); +} + +#[test] +fn passwords_are_8_to_128_characters() { + assert!(mint(&key(), HOST, &spec("/", Some("short"))).is_err()); + assert!(mint(&key(), HOST, &spec("/", Some(&"x".repeat(129)))).is_err()); + assert!(mint(&key(), HOST, &spec("/", Some("12345678"))).is_ok()); +} + +#[test] +fn stopped_links_and_older_epochs_are_revoked() { + let t = token("/", None); + let mut r = none(); + r.deny.insert(id(7)); + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &r), + Err(Rejection::Revoked) + ); + let r = Revocations { + epoch: 4, + deny: BTreeSet::new(), + }; + assert_eq!( + verify_link(&key(), HOST, &t, None, NOW, &r), + Err(Rejection::Revoked) + ); + // Another link on the deny list does not matter. + let mut r = none(); + r.deny.insert(id(8)); + assert!(verify_link(&key(), HOST, &t, None, NOW, &r).is_ok()); +} + +#[test] +fn session_cookies_and_link_tokens_are_not_interchangeable() { + let t = token("/albums", Some("correct horse")); + let c = verify_link(&key(), HOST, &t, Some("correct horse"), NOW, &none()).unwrap(); + let s = session_value(&key(), HOST, &c); + assert!(s.starts_with("iss1.")); + assert_eq!(verify_session(&key(), HOST, &s, NOW, &none()).unwrap(), c); + // A cookie is not a link, a link is not a cookie, even with the prefix swapped. + assert!(verify_link(&key(), HOST, &s, None, NOW, &none()).is_err()); + assert!(verify_session(&key(), HOST, &t, NOW, &none()).is_err()); + let swapped = s.replacen("iss1.", "ish1.", 1); + assert!(verify_link(&key(), HOST, &swapped, Some("correct horse"), NOW, &none()).is_err()); + let swapped = t.replacen("ish1.", "iss1.", 1); + assert!(verify_session(&key(), HOST, &swapped, NOW, &none()).is_err()); + // Cookies are host-bound, expire and are revoked like links. + assert_eq!( + verify_session(&key(), "other.home.test", &s, NOW, &none()), + Err(Rejection::Invalid) + ); + assert!(matches!( + verify_session(&key(), HOST, &s, NOW + 3600, &none()), + Err(Rejection::Expired { .. }) + )); + let mut r = none(); + r.deny.insert(id(7)); + assert_eq!( + verify_session(&key(), HOST, &s, NOW, &r), + Err(Rejection::Revoked) + ); +} + +#[test] +fn short_keys_are_refused() { + assert!(ShareKey::new(b"short").is_err()); + assert!(ShareKey::new(&[0u8; 31]).is_err()); + assert!(ShareKey::new(&[0u8; 32]).is_ok()); + assert!(!format!("{:?}", key()).contains("0123")); +} + +#[test] +fn prefixes_are_normalised_or_refused() { + assert_eq!(check_prefix("/").unwrap(), "/"); + assert_eq!(check_prefix("/a/").unwrap(), "/a"); + assert_eq!( + check_prefix("/albums/summer-2026").unwrap(), + "/albums/summer-2026" + ); + for bad in [ + "", "a", "//", "/a//b", "/a/../b", "/..", "/.", "/a/./b", "/a%2fb", "/a\\b", "/a b", + "/a;b", "/ä", "/a?b", "/a#b", + ] { + assert!(check_prefix(bad).is_err(), "{bad:?} accepted"); + } + assert!(check_prefix(&format!("/{}", "a".repeat(256))).is_err()); + // A prefix that is not in normal form is not minted. + assert!(mint(&key(), HOST, &spec("/a/", None)).is_err()); +} + +#[test] +fn ids_round_trip_as_hex() { + let i = ShareId([0xab; 16]); + assert_eq!(i.to_hex(), "ab".repeat(16)); + assert_eq!(ShareId::from_hex(&i.to_hex()), Some(i)); + for bad in [ + "", + "ab", + &"AB".repeat(16), + &"zz".repeat(16), + &"a".repeat(33), + ] { + assert_eq!(ShareId::from_hex(bad), None, "{bad:?}"); + } +} + +// ------------------------------------------------------------------ prefix escapes + +#[test] +fn paths_under_the_prefix_are_within() { + for (prefix, path) in [ + ("/a", "/a"), + ("/a", "/a/"), + ("/a", "/a/b"), + ("/a", "/a/b/c.jpg"), + ("/a", "/a/b%20c"), + ("/a", "/a/%E2%9C%93"), + ("/", "/"), + ("/", "/anything/at/all"), + ("/a/b", "/a/b/c"), + ("/a", "/a/b;v=1"), + ("/a", "/a/.well"), + ("/a", "/a/%C3%A9t%C3%A9.jpg"), + ("/a", "/a/%e2%9c%93"), + ("/a", "/a/a%20b"), + // QC fix round 3: ordinary names with look-alike dots or spaces inside. + ("/a", "/a/Wait%E2%80%A6.pdf"), + ("/a", "/a/%E3%80%80photo"), + ("/a", "/a/my%C2%A0file.pdf"), + ("/a", "/a/dokumenty/p%C5%99ehled"), + ("/a", "/a/my%20file.pdf"), + ("/a", "/a/a+b"), + ("/a", "/a/caf%C3%A9"), + ("/a", "/a/cafe%CC%81"), + ("/a", "/a/%E3%80%80photo%E3%80%80album"), + ("/a", "/a/e%CC%81"), + ("/a", "/a/%E2%80%93"), + ("/a", "/a/%E6%97%85%E8%A1%8C"), + ("/a", "/a/.well-known/x"), + ("/a", "/a/%C2%BD.txt"), + ("/a", "/a/x%3Fy"), + ] { + assert!(path_within(prefix, path), "{prefix} should cover {path}"); + } +} + +#[test] +fn no_path_trick_escapes_the_prefix() { + let cases = [ + ("/a", "/ab"), + ("/a", "/abc/d"), + ("/a", "/A"), + ("/a", "/A/b"), + ("/a/b", "/a"), + ("/a/b", "/a/bc"), + ("/a", "/b"), + ("/a", "/a/../b"), + ("/a", "/a/.."), + ("/a", "/a/./../b"), + ("/a", "/a/%2e%2e/b"), + ("/a", "/a/%2E%2E/b"), + ("/a", "/a/.%2e/b"), + ("/a", "/a/%2e./b"), + ("/a", "/a/%252e%252e/b"), + ("/a", "/a/%25252e/b"), + ("/a", "/a%2f..%2fb"), + ("/a", "/a%2F..%2Fb"), + ("/a", "/a/..%2fb"), + ("/a", "/a//b"), + ("/a", "//a/b"), + ("/a", "/a\\..\\b"), + ("/a", "/a/..\\b"), + ("/a", "/a%5c..%5cb"), + ("/a", "/a/..;/b"), + ("/a", "/a/.;/b"), + ("/a", "/a/%00/b"), + ("/a", "/a/b c"), + ("/a", "/a/\tb"), + ("/a", "a/b"), + ("/a", ""), + ("/a", "/a/ä"), + ("/", "/../etc/passwd"), + ("/", "//evil"), + ("/", "/%2e%2e/x"), + // QC fix round 1: overlong UTF-8, IIS %u, fullwidth dots, Windows-trimmed and + // encoded-semicolon dot segments. + ("/a", "/a/%c0%ae%c0%ae/b"), + ("/a", "/a/%C0%AE%C0%AE/secret"), + ("/a", "/a/..%c0%afb"), + ("/a", "/a/%e0%80%ae%e0%80%ae/b"), + ("/a", "/a/%f0%80%80%ae/b"), + ("/a", "/a/%u002e%u002e/b"), + ("/a", "/a/%u002E%u002E/b"), + ("/a", "/a/..%u2215b"), + ("/a", "/a/%ef%bc%8e%ef%bc%8e/b"), + ("/a", "/a/..%ef%bc%8fb"), + ("/a", "/a/..%e2%88%95b"), + ("/a", "/a/..%20/b"), + ("/a", "/a/.%20/b"), + ("/a", "/a/..%09/b"), + ("/a", "/a/..%3b/b"), + ("/a", "/a/..%3B/b"), + ("/a", "/a/..%3bx/b"), + ("/a", "/a/.;x/b"), + ("/a", "/a;/../b"), + ("/a", "/a/%2E./b"), + // QC fix round 2: NFKC look-alikes and dots before an encoded byte. + ("/a", "/a/%e2%80%a5/b"), + ("/a", "/a/%E2%80%A5/b"), + ("/a", "/a/%ef%b8%b0/b"), + ("/a", "/a/..%ef%b9%a8secret"), + ("/a", "/a/..%3f/b"), + ("/a", "/a/..%3F"), + ("/a", "/a/..%23/b"), + ("/a", "/a/%e3%80%80/b"), + ("/a", "/a/%zz/b"), + ("/a", "/a/%e2%9c"), + // QC fix round 3: a segment that is only an ellipsis or a look-alike space, slash + // look-alikes, and a broken escape that from_str_radix would take. + ("/a", "/a/%E2%80%A6/b"), + ("/a", "/a/%E2%80%A6"), + ("/a", "/a/%E3%80%80/b"), + ("/a", "/a/%C2%A0%C2%A0/b"), + ("/a", "/a/..%e2%88%95b"), + ("/a", "/a/..%e2%81%84b"), + ("/a", "/a/..%e2%a7%b8b"), + ("/a", "/a/x%e2%88%95y"), + ("/a", "/a/x%e2%81%84y"), + ("/a", "/a/%+f/b"), + ("/a", "/a/%-1/b"), + // QC fix round 4: dot-only segments hidden by invisible characters. + ("/a", "/a/%e2%80%8b../b"), + ("/a", "/a/%ef%bb%bf../b"), + ("/a", "/a/%c2%ad../b"), + ("/a", "/a/%cc%81../b"), + ("/a", "/a/%e2%80%a4.%e2%80%8b/b"), + ("/a", "/a/%e2%81%a0%e2%80%a5/b"), + ("/a", "/a/..%cc%81/b"), + ("/a", "/a/%e3%80%80../b"), + ("/a", "/a/%ef%bc%8e%ef%bc%8e/b"), + ("/a", "/a/%e2%80%a5%3bx/b"), + ("/a", "/a/%ef%bc%85/b"), + ("/a", "/a/x%ef%bc%8fy"), + ("/a", "/a/%e2%80%a4%09/b"), + ("/a", "/a/%ef%b9%a8"), + ("/a", "/a/%e2%88%96"), + ("/a", "/a/%e2%80%8b/b"), + ]; + for (prefix, path) in cases { + assert!( + !path_within(prefix, path), + "{prefix} must not cover {path:?}" + ); + } +} diff --git a/crates/edge/Cargo.toml b/crates/edge/Cargo.toml index f83f1f9..2b7e192 100644 --- a/crates/edge/Cargo.toml +++ b/crates/edge/Cargo.toml @@ -27,9 +27,15 @@ arc-swap = "1.7" instant-acme = { version = "0.8.5", default-features = false, features = ["ring", "hyper-rustls", "rcgen"] } x509-parser = "0.18" thiserror.workspace = true +ring.workspace = true +hyper.workspace = true +hyper-util.workspace = true +http-body-util.workspace = true +form_urlencoded = "1.2" [dev-dependencies] ianitor-testkit.workspace = true +ring.workspace = true [lints] workspace = true diff --git a/crates/edge/src/acme.rs b/crates/edge/src/acme.rs index 1febc10..580b9c4 100644 --- a/crates/edge/src/acme.rs +++ b/crates/edge/src/acme.rs @@ -21,13 +21,14 @@ use pingora::server::ShutdownWatch; use pingora::services::background::BackgroundService; use crate::logging::now_secs; -use crate::runtime::Runtime; -use crate::tls::{CertStore, certified_key, not_after}; +use crate::shared::{CertState, Shared}; +use crate::tls::{certified_key, not_after}; const RENEW_BEFORE_SECS: f64 = 30.0 * 86_400.0; const CHECK_EVERY: Duration = Duration::from_secs(12 * 3600); const FIRST_RETRY: Duration = Duration::from_secs(30); const MAX_RETRY: Duration = Duration::from_secs(3600); +const MIN_GAP: Duration = Duration::from_secs(5); /// HTTP-01 tokens → key authorizations, shared with the HTTP listener. #[derive(Default)] @@ -52,8 +53,7 @@ impl Challenges { } pub struct AcmeService { - pub rt: Arc, - pub certs: Arc, + pub shared: Arc, pub challenges: Arc, /// Extra trust root for the ACME directory (tests against Pebble only). pub ca_root: Option, @@ -84,7 +84,7 @@ fn fnv(data: &[u8]) -> String { impl AcmeService { fn dir(&self) -> PathBuf { - self.rt.acme_dir() + self.shared.current().acme_dir() } fn paths(&self, host: &str) -> (PathBuf, PathBuf) { @@ -102,7 +102,8 @@ impl AcmeService { let expiry = not_after(&cert_pem)?; match certified_key(&cert_pem, &key_pem) { Ok(ck) => { - self.certs.insert(host, ck); + self.shared.certs.insert(host, ck); + self.ok(host, expiry); Some(expiry) } Err(e) => { @@ -207,18 +208,30 @@ impl AcmeService { let (crt, key) = self.paths(host); write_private(&key, key_pem.as_bytes())?; write_private(&crt, chain_pem.as_bytes())?; - self.certs.insert(host, ck); + self.shared.certs.insert(host, ck); + self.ok(host, expiry); log::info!(target: "ianitor::acme", "{host}: certificate issued, valid until {expiry}"); Ok(expiry) } /// One pass over every ACME host. Returns false if any host failed. + fn ok(&self, host: &str, expiry: i64) { + self.shared.set_cert_state( + host, + CertState { + state: "ok", + not_after: Some(expiry), + error: None, + }, + ); + } + async fn round(&self, expiries: &mut HashMap) -> bool { - let Some(acme) = &self.rt.cfg.acme else { + let rt = self.shared.current(); + let Some(acme) = &rt.cfg.acme else { return true; }; - let due: Vec = self - .rt + let due: Vec = rt .acme_hosts() .into_iter() .filter(|h| { @@ -230,10 +243,25 @@ impl AcmeService { if due.is_empty() { return true; } + for h in &due { + if !expiries.contains_key(h) { + self.shared.set_cert_state( + h, + CertState { + state: "pending", + not_after: None, + error: None, + }, + ); + } + } let account = match self.account(&acme.directory, acme.email.as_deref()).await { Ok(a) => a, Err(e) => { log::error!(target: "ianitor::acme", "{e}"); + for h in &due { + self.failed(h, expiries.get(h).copied(), &e); + } return false; } }; @@ -245,43 +273,73 @@ impl AcmeService { } Err(e) => { log::error!(target: "ianitor::acme", "{host}: could not obtain a certificate: {e}"); + self.failed(&host, expiries.get(&host).copied(), &e); ok = false; } } } ok } + + /// A host that still has a valid certificate stays `ok` while renewal retries. + fn failed(&self, host: &str, expiry: Option, error: &str) { + let still_valid = expiry.is_some_and(|e| (e as f64) > now_secs()); + self.shared.set_cert_state( + host, + CertState { + state: if still_valid { "ok" } else { "failed" }, + not_after: expiry, + error: Some(error.chars().take(300).collect()), + }, + ); + } } #[async_trait] impl BackgroundService for AcmeService { async fn start(&self, mut shutdown: ShutdownWatch) { - if self.rt.acme_hosts().is_empty() { - return; - } - let dir = self.dir(); - if let Err(e) = std::fs::create_dir_all(&dir) { - log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display()); - return; - } let mut expiries = HashMap::new(); - for h in self.rt.acme_hosts() { - if let Some(e) = self.load_stored(&h) { - expiries.insert(h, e); - } - } let mut retry = FIRST_RETRY; + let mut last: Option = None; loop { - let wait = if self.round(&mut expiries).await { - retry = FIRST_RETRY; - CHECK_EVERY - } else { - let w = retry; - retry = (retry * 2).min(MAX_RETRY); - w - }; + // Reloads can come many times a second; ACME rounds at most every 5 s. + if let Some(l) = last + && l.elapsed() < MIN_GAP + { + tokio::select! { + _ = tokio::time::sleep(MIN_GAP - l.elapsed()) => {} + _ = shutdown.changed() => return, + } + } + last = Some(std::time::Instant::now()); + let hosts = self.shared.current().acme_hosts(); + let mut wait = CHECK_EVERY; + if !hosts.is_empty() { + let dir = self.dir(); + if let Err(e) = std::fs::create_dir_all(&dir) { + log::error!(target: "ianitor::acme", "cannot create {}: {e}", dir.display()); + } else { + for h in hosts { + if !expiries.contains_key(&h) + && let Some(e) = self.load_stored(&h) + { + expiries.insert(h, e); + } + } + wait = if self.round(&mut expiries).await { + retry = FIRST_RETRY; + CHECK_EVERY + } else { + let w = retry; + retry = (retry * 2).min(MAX_RETRY); + w + }; + } + } + // Woken early by a reload (new hosts) or a "try again" from control. tokio::select! { _ = tokio::time::sleep(wait) => {} + _ = self.shared.acme_wake.notified() => {} _ = shutdown.changed() => return, } } diff --git a/crates/edge/src/admin.rs b/crates/edge/src/admin.rs new file mode 100644 index 0000000..9ffd085 --- /dev/null +++ b/crates/edge/src/admin.rs @@ -0,0 +1,338 @@ +// 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 admin socket: a Unix socket (mode 0660, so only edge's user and group, i.e. control, +//! can connect; never a TCP port) speaking small JSON over HTTP/1.1. +//! +//! | Request | Does | +//! |:--|:--| +//! | `GET /v1/status` | config hash, trial, revocations, health per host and upstream, certificates | +//! | `POST /v1/reload` | reload the config file (refused while a trial runs) | +//! | `POST /v1/trial {confirm_within_secs, watch_hosts?, watch_every_secs?}` | serve the trial file until confirmed | +//! | `POST /v1/confirm {config_sha256}` | keep the running trial | +//! | `POST /v1/abort` | back to the config before the trial (idempotent) | +//! | `POST /v1/share-revocations/reload` | re-read the share-link revocation file | +//! | `POST /v1/acme/retry` | try Let's Encrypt again now | +//! +//! Bodies are at most 4 KiB with no unknown fields. Answers never carry a secret. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use async_trait::async_trait; +use bytes::Bytes; +use http_body_util::{BodyExt, Full, Limited}; +use hyper::body::Incoming; +use hyper::server::conn::http1; +use hyper::service::service_fn; +use hyper::{Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use pingora::server::ShutdownWatch; +use pingora::services::background::BackgroundService; +use serde::Deserialize; +use serde_json::{Value, json}; + +use crate::shared::{AdminError, Shared, WatchSpec}; + +const MAX_BODY: usize = 4096; +/// Longest trial the admin socket accepts. +const MAX_TRIAL_SECS: u64 = 3600; + +pub struct AdminSocket { + pub shared: Arc, + pub path: PathBuf, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct TrialBody { + confirm_within_secs: u64, + #[serde(default)] + watch_hosts: Vec, + watch_every_secs: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct ConfirmBody { + config_sha256: String, +} + +type Resp = Response>; + +fn reply(status: StatusCode, v: Value) -> Resp { + let mut r = Response::new(Full::new(Bytes::from(v.to_string()))); + *r.status_mut() = status; + r.headers_mut().insert( + http::header::CONTENT_TYPE, + http::HeaderValue::from_static("application/json"), + ); + r +} + +fn error(status: StatusCode, message: impl std::fmt::Display) -> Resp { + reply(status, json!({ "error": message.to_string() })) +} + +fn admin_error(e: AdminError) -> Resp { + match e { + AdminError::Refused(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e), + AdminError::Conflict(m) => error(StatusCode::CONFLICT, m), + } +} + +/// The status document. +pub fn status(shared: &Shared) -> Value { + let rt = shared.current(); + let mut hosts: Vec<&String> = rt.hosts.keys().collect(); + hosts.sort(); + let hosts: Vec = hosts + .into_iter() + .filter_map(|name| rt.hosts.get(name)) + .map(|h| { + let name = &h.cfg.hostname; + let cert = match &h.cfg.tls { + ianitor_core::edge_config::EdgeTls::Files { .. } => json!({ + "state": "ok", + "not_after": rt.file_cert_expiry.get(name), + "error": null, + }), + ianitor_core::edge_config::EdgeTls::Acme => match shared.cert_state(name) { + Some(c) => { + json!({ "state": c.state, "not_after": c.not_after, "error": c.error }) + } + None => json!({ "state": "pending", "not_after": null, "error": null }), + }, + }; + json!({ + "hostname": name, + "health_check": h.cfg.health_check.is_some(), + "upstreams": h.upstreams.iter().map(|u| json!({ + "address": u.authority, + "healthy": u.healthy.load(std::sync::atomic::Ordering::Relaxed), + "checks": u.health.checks(), + })).collect::>(), + "certificate": cert, + }) + }) + .collect(); + let rev = shared.revocations(); + json!({ + "generation": shared.generation(), + "config_sha256": rt.sha256, + "started_at": shared.started_at, + "trial": shared.trial_info().map(|(sha, left, prev)| json!({ + "config_sha256": sha, + "seconds_left": left, + "previous_sha256": prev, + })), + "share_revocations": { + "loaded": rev.loaded, + "epoch": rev.revocations.epoch, + "stopped": rev.revocations.deny.len(), + "error": rev.error, + }, + "hosts": hosts, + }) +} + +async fn body Deserialize<'de>>( + req: Request, +) -> Result, Box> { + let bytes = Limited::new(req.into_body(), MAX_BODY) + .collect() + .await + .map_err(|_| { + error( + StatusCode::PAYLOAD_TOO_LARGE, + "the body is larger than 4 KiB", + ) + })? + .to_bytes(); + if bytes.is_empty() { + return Ok(None); + } + serde_json::from_slice(&bytes) + .map(Some) + .map_err(|e| Box::new(error(StatusCode::BAD_REQUEST, format!("bad body: {e}")))) +} + +async fn handle(shared: Arc, req: Request) -> Resp { + let method = req.method().clone(); + let path = req.uri().path().to_owned(); + match (method.as_str(), path.as_str()) { + ("GET", "/v1/status") => reply(StatusCode::OK, status(&shared)), + ("POST", "/v1/reload") => { + let r = tokio::task::spawn_blocking({ + let s = shared.clone(); + move || s.reload() + }) + .await; + match r { + Ok(Ok(rt)) => reply( + StatusCode::OK, + json!({ "config_sha256": rt.sha256, "generation": shared.generation() }), + ), + Ok(Err(e)) => admin_error(e), + Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e), + } + } + ("POST", "/v1/trial") => { + let b: TrialBody = match body(req).await { + Ok(Some(b)) => b, + Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"), + Err(r) => return *r, + }; + if !(1..=MAX_TRIAL_SECS).contains(&b.confirm_within_secs) { + return error( + StatusCode::BAD_REQUEST, + "confirm_within_secs must be between 1 and 3600", + ); + } + let every = b.watch_every_secs.unwrap_or(5); + if !(1..=60).contains(&every) || b.watch_hosts.len() > 1000 { + return error(StatusCode::BAD_REQUEST, "watch_every_secs must be 1 to 60"); + } + let watch = (!b.watch_hosts.is_empty()).then(|| WatchSpec { + hosts: b.watch_hosts, + every: Duration::from_secs(every), + }); + let within = Duration::from_secs(b.confirm_within_secs); + let r = tokio::task::spawn_blocking({ + let s = shared.clone(); + move || s.start_trial(within, watch) + }) + .await; + match r { + Ok(Ok((id, rt))) => { + let s = shared.clone(); + tokio::spawn(async move { + if let Some(deadline) = s.trial_deadline(id) { + tokio::time::sleep_until(deadline.into()).await; + s.expire_trial(id); + } + }); + reply( + StatusCode::OK, + json!({ "config_sha256": rt.sha256, "generation": shared.generation() }), + ) + } + Ok(Err(e)) => admin_error(e), + Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e), + } + } + ("POST", "/v1/confirm") => { + let b: ConfirmBody = match body(req).await { + Ok(Some(b)) => b, + Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"), + Err(r) => return *r, + }; + match shared.confirm(&b.config_sha256) { + Ok(()) => reply(StatusCode::OK, json!({ "confirmed": true })), + Err(e) => admin_error(e), + } + } + ("POST", "/v1/abort") => reply(StatusCode::OK, json!({ "reverted": shared.abort() })), + ("POST", "/v1/share-revocations/reload") => match shared.reload_revocations() { + Ok(()) => { + let r = shared.revocations(); + reply( + StatusCode::OK, + json!({ "epoch": r.revocations.epoch, "stopped": r.revocations.deny.len() }), + ) + } + Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e), + }, + ("POST", "/v1/acme/retry") => { + shared.acme_wake.notify_one(); + reply(StatusCode::OK, json!({ "retrying": true })) + } + (_, "/v1/status" | "/v1/reload" | "/v1/trial" | "/v1/confirm" | "/v1/abort") => { + error(StatusCode::METHOD_NOT_ALLOWED, "method not allowed") + } + _ => error(StatusCode::NOT_FOUND, "no such admin request"), + } +} + +fn bind(path: &Path) -> std::io::Result { + use std::os::unix::fs::{FileTypeExt, PermissionsExt}; + // A socket left over from a previous run is removed; anything else at the path is not. + if let Ok(meta) = std::fs::symlink_metadata(path) { + if meta.file_type().is_socket() { + std::fs::remove_file(path)?; + } else { + return Err(std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + format!("{} exists and is not a socket", path.display()), + )); + } + } + // Bind inside a fresh 0700 directory, set the mode, then move the socket into place, so + // there is no moment in which the socket exists with the process umask's permissions. + use std::os::unix::fs::DirBuilderExt; + let parent = path.parent().unwrap_or(Path::new(".")); + let private = parent.join(format!(".ianitor-admin-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&private); + std::fs::DirBuilder::new().mode(0o700).create(&private)?; + let staged = private.join("admin.sock"); + let bound = tokio::net::UnixListener::bind(&staged).and_then(|l| { + std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o660))?; + std::fs::rename(&staged, path)?; + Ok(l) + }); + let _ = std::fs::remove_dir_all(&private); + bound +} + +#[async_trait] +impl BackgroundService for AdminSocket { + async fn start(&self, mut shutdown: ShutdownWatch) { + let listener = match bind(&self.path) { + Ok(l) => l, + Err(e) => { + log::error!(target: "ianitor::admin", "cannot listen on {}: {e}; control cannot reach edge", self.path.display()); + return; + } + }; + log::info!(target: "ianitor::admin", "admin socket at {}", self.path.display()); + loop { + tokio::select! { + _ = shutdown.changed() => break, + a = listener.accept() => { + let Ok((stream, _)) = a else { continue }; + let shared = self.shared.clone(); + tokio::spawn(async move { + let svc = service_fn(move |req| { + let shared = shared.clone(); + async move { Ok::<_, std::convert::Infallible>(handle(shared, req).await) } + }); + let _ = http1::Builder::new() + .serve_connection(TokioIo::new(stream), svc) + .await; + }); + } + } + } + let _ = std::fs::remove_file(&self.path); + } +} + +/// Re-reads the share-link revocation file when it changes (every 5 s), so a stopped link +/// stops even if control's reload request was lost. +pub struct RevocationPoller { + pub shared: Arc, +} + +#[async_trait] +impl BackgroundService for RevocationPoller { + async fn start(&self, mut shutdown: ShutdownWatch) { + loop { + tokio::select! { + _ = shutdown.changed() => return, + _ = tokio::time::sleep(Duration::from_secs(5)) => self.shared.poll_revocations(), + } + } + } +} diff --git a/crates/edge/src/health.rs b/crates/edge/src/health.rs index 0195d99..bba150d 100644 --- a/crates/edge/src/health.rs +++ b/crates/edge/src/health.rs @@ -4,57 +4,153 @@ //! Active health checks, like Caddy's `health_checks.active`: `GET ` with the upstream //! address as Host, healthy on 2xx, 5 s timeout, one result flips the state. The first round -//! runs at startup; upstreams start healthy. +//! runs when a config is loaded; upstreams start healthy. +//! +//! Every result is also recorded (time, latency, why it failed) for the admin socket. +//! During a trial, the watched hosts are probed at least every `every` seconds; a watched +//! host without a health check gets `GET /` with its own hostname as Host, and any answer +//! below 500 counts as alive (docs/ui-api.md G3). Those watch probes never change routing. use std::sync::Arc; use std::sync::atomic::Ordering; -use std::time::Duration; +use std::time::{Duration, Instant}; use async_trait::async_trait; use pingora::connectors::http::Connector; use pingora::http::RequestHeader; use pingora::server::ShutdownWatch; use pingora::services::background::BackgroundService; +use pingora::{Error, ErrorType}; use crate::fetch::fetch; -use crate::runtime::{HostRt, Runtime, UpstreamRt}; +use crate::logging::now_secs; +use crate::runtime::{Check, HostRt, UpstreamRt}; +use crate::shared::Shared; const TIMEOUT: Duration = Duration::from_secs(5); pub struct HealthChecks { - pub rt: Arc, + pub shared: Arc, } -async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool { - let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else { - return false; +/// Why a probe failed, in the words of docs/ui-api.md §3.3. +pub fn failure_kind(e: &Error) -> &'static str { + match e.etype() { + ErrorType::ConnectRefused | ErrorType::ConnectError | ErrorType::ConnectionClosed => { + "refused" + } + ErrorType::ConnectTimedout + | ErrorType::ReadTimedout + | ErrorType::WriteTimedout + | ErrorType::TLSHandshakeTimedout => "timeout", + ErrorType::ConnectNoRoute => "name", + ErrorType::TLSHandshakeFailure | ErrorType::InvalidCert | ErrorType::HandshakeError => { + "tls" + } + _ => "bad_answer", + } +} + +fn status_kind(status: u16) -> &'static str { + match status { + 300..=399 => "redirect", + 401 | 403 => "sign_in", + 404 => "not_found", + 500..=599 => "server_error", + _ => "bad_answer", + } +} + +/// One probe. `watch` probes count any answer below 500 as alive. +async fn probe( + connector: &Connector, + u: &UpstreamRt, + path: &str, + host: &str, + watch: bool, +) -> Check { + let started = Instant::now(); + let at = now_secs() as u64; + let source = if watch { "watch" } else { "health_check" }; + let fail = |kind: &'static str, status: Option, latency: Option| Check { + seq: 0, + at, + ok: false, + source, + kind: Some(kind), + status, + latency_ms: latency, }; - if req - .insert_header(http::header::HOST, u.authority.as_str()) - .is_err() - { - return false; + let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else { + return fail("bad_answer", None, None); + }; + if req.insert_header(http::header::HOST, host).is_err() { + return fail("bad_answer", None, None); } match fetch(connector, u, req, 64 * 1024, TIMEOUT).await { - Ok(f) => f.header.status.is_success(), - Err(_) => false, + Ok(f) => { + let status = f.header.status.as_u16(); + let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + let ok = if watch { + (100..500).contains(&status) + } else { + f.header.status.is_success() + }; + if ok { + Check { + seq: 0, + at, + ok: true, + source, + kind: None, + status: Some(status), + latency_ms: Some(latency), + } + } else { + fail(status_kind(status), Some(status), Some(latency)) + } + } + Err(e) => fail(failure_kind(&e), None, None), } } /// One round over a host's upstreams. Each probe runs in its own task, so a panic inside a /// probe (e.g. a library bug on an odd answer) marks that upstream unhealthy instead of /// ending health checks. -async fn round(host: &Arc, path: &str, connector: &Arc) { +async fn round(host: &Arc, path: &str, connector: &Arc, watch: bool) { for i in 0..host.upstreams.len() { let (h, p, c) = (host.clone(), path.to_owned(), connector.clone()); - let ok = match tokio::spawn(async move { probe(&c, &h.upstreams[i], &p).await }).await { - Ok(ok) => ok, + let probe_host = if watch { + host.cfg.hostname.clone() + } else { + host.upstreams[i].authority.clone() + }; + let check = match tokio::spawn(async move { + probe(&c, &h.upstreams[i], &p, &probe_host, watch).await + }) + .await + { + Ok(c) => c, Err(e) => { log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority); - false + Check { + seq: 0, + at: now_secs() as u64, + ok: false, + source: if watch { "watch" } else { "health_check" }, + kind: Some("bad_answer"), + status: None, + latency_ms: None, + } } }; let u = &host.upstreams[i]; + let ok = check.ok; + u.health.record(check); + if watch { + // Watch probes only report; routing follows the host's own health check. + continue; + } if u.healthy.swap(ok, Ordering::Relaxed) != ok { if ok { log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority); @@ -65,50 +161,93 @@ async fn round(host: &Arc, path: &str, connector: &Arc) { } } -async fn watch(host: Arc, path: String, every: Duration) { +async fn watcher(host: Arc, path: String, every: Duration, watch: bool) { let connector = Arc::new(Connector::new(None)); loop { - round(&host, &path, &connector).await; + round(&host, &path, &connector, watch).await; tokio::time::sleep(every).await; } } +struct Job { + host: Arc, + path: String, + every: Duration, + watch: bool, +} + +fn jobs(shared: &Shared) -> Vec { + let rt = shared.current(); + let spec = shared.watch_spec(); + let watched = |h: &str| { + spec.as_ref() + .is_some_and(|s| s.hosts.iter().any(|w| w == h)) + }; + let every = spec.as_ref().map(|s| s.every); + let mut out = Vec::new(); + for h in rt.hosts.values() { + let name = &h.cfg.hostname; + match &h.cfg.health_check { + Some(hc) => { + let mut interval = Duration::from_secs(u64::from(hc.interval_secs.max(1))); + if watched(name) + && let Some(e) = every + { + interval = interval.min(e); + } + out.push(Job { + host: h.clone(), + path: hc.path.clone(), + every: interval, + watch: false, + }); + } + None if watched(name) => out.push(Job { + host: h.clone(), + path: "/".into(), + every: every.unwrap_or(Duration::from_secs(5)), + watch: true, + }), + None => {} + } + } + out +} + #[async_trait] impl BackgroundService for HealthChecks { async fn start(&self, mut shutdown: ShutdownWatch) { - let checked: Vec<(Arc, String, Duration)> = self - .rt - .hosts - .values() - .filter_map(|h| { - h.cfg.health_check.as_ref().map(|hc| { - ( - h.clone(), - hc.path.clone(), - Duration::from_secs(u64::from(hc.interval_secs.max(1))), - ) - }) - }) - .collect(); - let mut tasks = tokio::task::JoinSet::new(); - let mut which = std::collections::HashMap::new(); - for (i, (h, p, every)) in checked.iter().enumerate() { - which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i); - } - // A watcher never returns; if one ends anyway, say so and start it again. + let mut changes = self.shared.subscribe(); loop { - tokio::select! { - _ = shutdown.changed() => break, - Some(done) = tasks.join_next_with_id() => { - let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() }; - if let Some(i) = which.remove(&id) { - let (h, p, every) = &checked[i]; - log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", h.cfg.hostname); - which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i); + let jobs = jobs(&self.shared); + let mut tasks = tokio::task::JoinSet::new(); + let mut which = std::collections::HashMap::new(); + for (i, j) in jobs.iter().enumerate() { + let id = tasks + .spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch)) + .id(); + which.insert(id, i); + } + // Run until the config or the watch changes; a watcher never returns, and if one + // ends anyway, say so and start it again. + let stop = loop { + tokio::select! { + _ = shutdown.changed() => break true, + r = changes.changed() => break r.is_err(), + Some(done) = tasks.join_next_with_id() => { + let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() }; + if let Some(i) = which.remove(&id) { + let j = &jobs[i]; + log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", j.host.cfg.hostname); + which.insert(tasks.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch)).id(), i); + } } } + }; + tasks.abort_all(); + if stop { + return; } } - tasks.abort_all(); } } diff --git a/crates/edge/src/http_app.rs b/crates/edge/src/http_app.rs index 82c0492..5b83bbf 100644 --- a/crates/edge/src/http_app.rs +++ b/crates/edge/src/http_app.rs @@ -19,10 +19,10 @@ use pingora::server::ShutdownWatch; use crate::acme::Challenges; use crate::logging::{AccessRecord, now_secs, truncate_ip}; use crate::proxy::{host_header, hostname}; -use crate::runtime::Runtime; +use crate::shared::Shared; pub struct HttpApp { - pub rt: Arc, + pub shared: Arc, pub challenges: Arc, } @@ -75,6 +75,7 @@ impl HttpServerApp for HttpApp { impl HttpApp { async fn response(&self, session: &mut ServerSession) -> Response> { let start = Instant::now(); + let rt = self.shared.current(); let req = session.req_header(); let hh = host_header(req); let name = hostname(&hh); @@ -92,11 +93,11 @@ impl HttpApp { return r; } - let Some(host) = self.rt.host(&name) else { + let Some(host) = rt.host(&name) else { return empty(StatusCode::NOT_FOUND); }; let uri = req.uri.path_and_query().map_or("/", |p| p.as_str()); - let port = self.rt.cfg.https_port; + let port = rt.cfg.https_port; let location = if port == 443 { format!("https://{name}{uri}") } else { @@ -110,7 +111,7 @@ impl HttpApp { Err(_) => return empty(StatusCode::BAD_REQUEST), } if host.cfg.access_log - && let Some(log) = &self.rt.access_log + && let Some(log) = &rt.access_log { log.write(&AccessRecord { ts: now_secs(), diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index 1b42089..66d4ea5 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -5,23 +5,29 @@ //! Ianitor edge: the Pingora data plane. It reads the config compiled by `ianitor-core` //! and serves it; it never decides policy. //! -//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, websockets, header rules, -//! round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and redirects), -//! health checks, ACME issuance and renewal. +//! Services: HTTPS reverse proxy (SNI certificates, forward-auth, share links, websockets, +//! header rules, round-robin over healthy upstreams), plain-HTTP listener (ACME HTTP-01 and +//! redirects), health checks, ACME issuance and renewal, and the admin socket through which +//! control reloads the config in process (see `shared`). pub mod acme; +#[cfg(unix)] +pub mod admin; pub mod error; pub mod fetch; pub mod forward_auth; pub mod health; pub mod http_app; pub mod logging; +pub mod pages; pub mod proxy; pub mod runtime; pub mod secrets; +pub mod share; +pub mod shared; pub mod tls; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; use pingora::connectors::http::Connector; @@ -34,24 +40,67 @@ use pingora::services::listening::Service; pub use error::EdgeError; pub use runtime::Runtime; +pub use shared::Shared; #[derive(Debug, Clone, Default)] pub struct Options { /// The compiled edge config (`ianitor-core` edge compiler output). pub config: PathBuf, + /// The trial config control writes before an apply; default `.trial`. + pub trial_config: Option, + /// Admin socket for control (Unix only); none when `None`. + pub admin_socket: Option, + /// The share-link revocation file control writes; without it, share links are refused. + pub share_revocations: Option, /// Extra trust root for the ACME directory's TLS (Pebble in tests). pub acme_root: Option, + /// Overrides `$CREDENTIALS_DIRECTORY` (tests running several edges in one process). + pub credentials_dir: Option, +} + +impl Options { + pub fn trial_path(&self) -> PathBuf { + self.trial_config + .clone() + .unwrap_or_else(|| default_trial_path(&self.config)) + } +} + +/// `.trial`, next to the config. +pub fn default_trial_path(config: &Path) -> PathBuf { + let mut name = config.file_name().unwrap_or_default().to_os_string(); + name.push(".trial"); + config.with_file_name(name) +} + +fn credentials_dir(opts: &Options) -> Option { + opts.credentials_dir + .clone() + .or_else(|| std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from)) } /// Read the config, load secrets from `$CREDENTIALS_DIRECTORY`, load certificates. -pub fn prepare(opts: &Options) -> Result, EdgeError> { - let cfg = runtime::read_config(&opts.config)?; - let creds = std::env::var_os("CREDENTIALS_DIRECTORY").map(PathBuf::from); - runtime::build(cfg, creds.as_deref()).map(Arc::new) +pub fn prepare(opts: &Options) -> Result, EdgeError> { + let creds = credentials_dir(opts); + let rt = runtime::build_file(&opts.config, creds.as_deref())?; + Ok(shared_for(rt, opts)) +} + +/// Wrap an already built runtime (tests run edge in process this way). +pub fn shared_for(rt: Runtime, opts: &Options) -> Arc { + Shared::new( + rt, + shared::Paths { + config: opts.config.clone(), + trial: opts.trial_path(), + revocations: opts.share_revocations.clone(), + }, + credentials_dir(opts), + ) } /// Assemble the Pingora server with all services. Listeners bind when it runs. -pub fn server(rt: Arc, opts: &Options) -> Result { +pub fn server(shared: Arc, opts: &Options) -> Result { pingora::tls::install_default_crypto_provider(); let conf = ServerConf { threads: 2, @@ -63,11 +112,12 @@ pub fn server(rt: Arc, opts: &Options) -> Result { server.bootstrap(); let challenges = Arc::new(acme::Challenges::default()); + let rt = shared.current(); let mut https = http_proxy_service( &server.configuration, proxy::EdgeProxy { - rt: rt.clone(), + shared: shared.clone(), connector: Connector::new(None), }, ); @@ -75,14 +125,14 @@ pub fn server(rt: Arc, opts: &Options) -> Result { address: rt.cfg.https_listen.clone(), reason: e.to_string(), })?; - tls.set_cert_resolver(rt.certs.clone()); + tls.set_cert_resolver(shared.certs.clone()); tls.enable_h2(); https.add_tls_with_settings(&rt.cfg.https_listen, None, tls); let mut http = Service::new( "ianitor http".to_owned(), http_app::HttpApp { - rt: rt.clone(), + shared: shared.clone(), challenges: challenges.clone(), }, ); @@ -92,17 +142,36 @@ pub fn server(rt: Arc, opts: &Options) -> Result { server.add_service(http); server.add_service(background_service( "ianitor health checks", - health::HealthChecks { rt: rt.clone() }, + health::HealthChecks { + shared: shared.clone(), + }, )); server.add_service(background_service( "ianitor acme", acme::AcmeService { - rt: rt.clone(), - certs: rt.certs.clone(), + shared: shared.clone(), challenges, ca_root: opts.acme_root.clone(), }, )); + #[cfg(unix)] + { + server.add_service(background_service( + "ianitor share revocations", + admin::RevocationPoller { + shared: shared.clone(), + }, + )); + if let Some(path) = &opts.admin_socket { + server.add_service(background_service( + "ianitor admin socket", + admin::AdminSocket { + shared: shared.clone(), + path: path.clone(), + }, + )); + } + } Ok(server) } diff --git a/crates/edge/src/main.rs b/crates/edge/src/main.rs index 08210f3..e65a403 100644 --- a/crates/edge/src/main.rs +++ b/crates/edge/src/main.rs @@ -2,7 +2,8 @@ // 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-edge --config [--check] [--acme-root ]` +//! `ianitor-edge --config [--check] [--admin-socket ] [--trial-config ] +//! [--share-revocations ] [--acme-root ]` //! //! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG` //! (error, warn, info, debug, trace; libraries are capped at info). @@ -21,10 +22,14 @@ fn parse_args() -> Result<(Options, bool), EdgeError> { match a.to_str() { Some("--config") => config = args.next().map(PathBuf::from), Some("--acme-root") => opts.acme_root = args.next().map(PathBuf::from), + Some("--admin-socket") => opts.admin_socket = args.next().map(PathBuf::from), + Some("--trial-config") => opts.trial_config = args.next().map(PathBuf::from), + Some("--share-revocations") => opts.share_revocations = args.next().map(PathBuf::from), Some("--check") => check = true, Some("--help" | "-h") => { println!( - "usage: ianitor-edge --config [--check] [--acme-root ]" + "usage: ianitor-edge --config [--check] [--admin-socket ] \ + [--trial-config ] [--share-revocations ] [--acme-root ]" ); std::process::exit(0); } @@ -44,12 +49,12 @@ fn parse_args() -> Result<(Options, bool), EdgeError> { fn main() -> ExitCode { ianitor_edge::logging::init(std::env::var("IANITOR_LOG").ok().as_deref()); let started = parse_args().and_then(|(opts, check)| { - let rt = ianitor_edge::prepare(&opts)?; - log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), rt.hosts.len()); + let shared = ianitor_edge::prepare(&opts)?; + log::info!(target: "ianitor::edge", "config {} loaded: {} hosts", opts.config.display(), shared.current().hosts.len()); if check { return Ok(None); } - ianitor_edge::server(rt, &opts).map(Some) + ianitor_edge::server(shared, &opts).map(Some) }); match started { Ok(None) => ExitCode::SUCCESS, diff --git a/crates/edge/src/pages.rs b/crates/edge/src/pages.rs new file mode 100644 index 0000000..484f927 --- /dev/null +++ b/crates/edge/src/pages.rs @@ -0,0 +1,211 @@ +// 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 share-link visitor pages (docs/ui-api.md §4): one self-contained HTML page each, inline +//! CSS, no JavaScript, no external requests, under 8 KB. Only the hostname and a date come +//! from the request side, both escaped; the token is echoed only into the password form's +//! hidden field (it is already in the visitor's address bar at that point), escaped too. + +use ianitor_core::share::PASSWORD_PATH; +use ianitor_core::time::long_date; + +pub enum Problem { + WrongPassword, + TooMany, +} + +pub enum Page<'a> { + Password { + host: &'a str, + token: &'a str, + until: u64, + problem: Option, + }, + Expired { + host: &'a str, + until: u64, + }, + Invalid { + host: &'a str, + }, +} + +impl Page<'_> { + pub fn status(&self) -> u16 { + match self { + Page::Password { + problem: Some(Problem::TooMany), + .. + } => 429, + Page::Password { .. } => 401, + Page::Expired { .. } => 410, + Page::Invalid { .. } => 403, + } + } +} + +pub fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c if c.is_control() => {} + c => out.push(c), + } + } + out +} + +const STYLE: &str = "\ +*{box-sizing:border-box}\ +body{margin:0;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;\ +background:#0c0b0f;color:#f1edf3;font-family:system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif;padding:16px}\ +.card{width:100%;max-width:420px;padding:32px;background:#18151d;border:1px solid #3c3445;border-radius:18px}\ +@media (max-width:480px){.card{padding:24px}}\ +.host{color:#cfc6d4;font-size:.95rem;font-weight:600;margin:0 0 16px;overflow-wrap:anywhere}\ +svg{display:block;margin:0 0 12px}\ +h1{font-size:1.5rem;font-weight:700;color:#f1edf3;margin:0 0 8px}\ +p{font-size:1rem;line-height:1.5;color:#cfc6d4;margin:0 0 16px}\ +label{display:block;color:#cfc6d4;font-size:.9rem;margin:0 0 6px}\ +input[type=password]{width:100%;height:48px;background:#0c0b0f;border:1px solid #7d7189;border-radius:10px;\ +color:#f1edf3;font-size:1rem;padding:0 12px}\ +input[type=password]:focus{outline:none;border-color:#e0a3dc;box-shadow:0 0 0 4px rgba(224,163,220,.16)}\ +.err{color:#e2683a;font-size:.92rem;margin:8px 0 0;display:flex;gap:6px;align-items:center}\ +button{margin-top:16px;width:100%;height:48px;border-radius:12px;border:1px solid #c77cc1;color:#fff;font-weight:700;\ +font-size:1rem;background:linear-gradient(#8d3b89,#76306f 55%,#5c2257)}\ +button:focus{outline:2px solid #f2c9ee;outline-offset:2px}\ +button:disabled{opacity:.5}\ +.small{font-size:.92rem;margin:16px 0 0}\ +a{color:#e0a3dc;display:inline-flex;align-items:center;min-height:44px}\ +footer{color:#a99eb1;font-size:.72rem;letter-spacing:.2em;text-transform:uppercase;margin-top:16px}"; + +fn icon(kind: &str) -> String { + let (colour, body) = match kind { + // lock + "lock" => ( + "#e0a3dc", + "", + ), + // clock + "clock" => ( + "#d99a35", + "", + ), + // broken link + _ => ( + "#d99a35", + "", + ), + }; + format!( + "{body}" + ) +} + +const RING: &str = ""; + +fn shell(host: &str, inner: &str, title: &str) -> String { + format!( + "\ + \ + \ + {title}
\ +

{}

{inner}
Ianitor Domi
", + escape(host) + ) +} + +pub fn render(p: &Page<'_>) -> String { + match p { + Page::Password { + host, + token, + until, + problem, + } => { + let h = escape(host); + let (msg, disabled) = match problem { + Some(Problem::WrongPassword) => ( + format!( + "

{RING}That password is not right. Check it with the person who sent the link.

" + ), + "", + ), + Some(Problem::TooMany) => ( + format!( + "

{RING}Too many tries. Wait a minute, then try again.

" + ), + " disabled", + ), + None => (String::new(), ""), + }; + let inner = format!( + "{}

This link is protected

\ +

Someone shared {h} with you. Enter the password they gave you.

\ +
\ + \ + \ + \ + {msg}
\ +

The link works until {}.

", + icon("lock"), + escape(token), + long_date(*until) + ); + shell(host, &inner, "This link is protected") + } + Page::Expired { host, until } => { + let inner = format!( + "{}

This link has expired

\ +

It worked until {}. Ask the person who sent it for a new one.

\ + Have an account? Sign in", + icon("clock"), + long_date(*until) + ); + shell(host, &inner, "This link has expired") + } + Page::Invalid { host } => { + let inner = format!( + "{}

This link no longer works

\ +

It may have been stopped, or not copied in full. Ask the person who sent it for a new one.

\ + Have an account? Sign in", + icon("broken") + ); + shell(host, &inner, "This link no longer works") + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pages_are_small_and_escaped() { + for p in [ + Page::Password { + host: "x", + token: "\">