From 6ce1fe9d2bc9ac8a653058710c172f5839c5a100 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 17:49:53 +0100 Subject: [PATCH] [edge] Reload and share links: in-process config swap with self-reverting trials, admin socket with health and certificate status, share-link cookies, visitor pages and throttle --- Cargo.lock | 4 + crates/edge/Cargo.toml | 5 + crates/edge/src/acme.rs | 120 ++++++--- crates/edge/src/admin.rs | 326 +++++++++++++++++++++++ crates/edge/src/health.rs | 237 +++++++++++++---- crates/edge/src/http_app.rs | 11 +- crates/edge/src/lib.rs | 95 +++++-- crates/edge/src/main.rs | 15 +- crates/edge/src/pages.rs | 211 +++++++++++++++ crates/edge/src/proxy.rs | 56 +++- crates/edge/src/runtime.rs | 181 +++++++++++-- crates/edge/src/share.rs | 428 +++++++++++++++++++++++++++++++ crates/edge/src/shared.rs | 403 +++++++++++++++++++++++++++++ crates/edge/src/tls.rs | 15 +- crates/edge/tests/reload.rs | 111 ++++++-- crates/edge/tests/share_links.rs | 86 +++++-- tests/diff/src/lib.rs | 8 +- tests/support/src/more.rs | 11 +- 18 files changed, 2137 insertions(+), 186 deletions(-) create mode 100644 crates/edge/src/admin.rs create mode 100644 crates/edge/src/pages.rs create mode 100644 crates/edge/src/share.rs create mode 100644 crates/edge/src/shared.rs diff --git a/Cargo.lock b/Cargo.lock index cdd8120..baa1c57 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1038,7 +1038,11 @@ dependencies = [ "arc-swap", "async-trait", "bytes", + "form_urlencoded", "http", + "http-body-util", + "hyper", + "hyper-util", "ianitor-core", "ianitor-testkit", "instant-acme", diff --git a/crates/edge/Cargo.toml b/crates/edge/Cargo.toml index 3eb54e9..2b7e192 100644 --- a/crates/edge/Cargo.toml +++ b/crates/edge/Cargo.toml @@ -27,6 +27,11 @@ 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 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..09fa478 --- /dev/null +++ b/crates/edge/src/admin.rs @@ -0,0 +1,326 @@ +// 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()), + )); + } + } + let l = tokio::net::UnixListener::bind(path)?; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o660))?; + Ok(l) +} + +#[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..23a3ee5 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,63 @@ 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, } +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() -> Option { + 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(); + 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(), + ) } /// 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 +108,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 +121,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 +138,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: "\">