diff --git a/Cargo.lock b/Cargo.lock index f4d900d..289dd35 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1042,6 +1042,7 @@ dependencies = [ "rustls-pki-types", "serde", "serde_json", + "thiserror 2.0.21", "tokio", "x509-parser 0.18.1", ] diff --git a/Cargo.toml b/Cargo.toml index b4cd1ea..2259be2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ url = "2.5.7" tokio = { version = "1.48", features = ["full"] } bytes = "1.10" http = "1.3" -log = "0.4.28" +log = { version = "0.4.28", features = ["std"] } async-trait = "0.1.89" rustls = { version = "0.23.31", default-features = false, features = ["ring", "std", "tls12", "logging"] } rustls-pki-types = "1.12" diff --git a/crates/edge/Cargo.toml b/crates/edge/Cargo.toml index 162a55d..f83f1f9 100644 --- a/crates/edge/Cargo.toml +++ b/crates/edge/Cargo.toml @@ -26,6 +26,7 @@ serde_json.workspace = true 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 [dev-dependencies] ianitor-testkit.workspace = true diff --git a/crates/edge/src/acme.rs b/crates/edge/src/acme.rs new file mode 100644 index 0000000..1febc10 --- /dev/null +++ b/crates/edge/src/acme.rs @@ -0,0 +1,289 @@ +// 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/. + +//! Let's Encrypt (any RFC 8555 directory) through `instant-acme`, HTTP-01 challenges answered +//! on the plain-HTTP listener. Certificates and the account live in `/acme` +//! (key files mode 0600) and are swapped into the SNI store without a restart. A certificate +//! is renewed when it has less than 30 days left; failures are retried with backoff. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; +use std::time::Duration; + +use async_trait::async_trait; +use instant_acme::{ + Account, AccountCredentials, AuthorizationStatus, ChallengeType, Identifier, NewAccount, + NewOrder, OrderStatus, RetryPolicy, +}; +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}; + +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); + +/// HTTP-01 tokens → key authorizations, shared with the HTTP listener. +#[derive(Default)] +pub struct Challenges(RwLock>); + +impl Challenges { + pub fn get(&self, token: &str) -> Option { + self.0.read().ok()?.get(token).cloned() + } + + fn insert(&self, token: String, key_auth: String) { + if let Ok(mut m) = self.0.write() { + m.insert(token, key_auth); + } + } + + fn remove(&self, token: &str) { + if let Ok(mut m) = self.0.write() { + m.remove(token); + } + } +} + +pub struct AcmeService { + pub rt: Arc, + pub certs: Arc, + pub challenges: Arc, + /// Extra trust root for the ACME directory (tests against Pebble only). + pub ca_root: Option, +} + +fn write_private(path: &Path, data: &[u8]) -> Result<(), String> { + let tmp = path.with_extension("tmp"); + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o600); + let mut f = opts + .open(&tmp) + .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; + std::io::Write::write_all(&mut f, data) + .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; + std::fs::rename(&tmp, path).map_err(|e| format!("cannot replace {}: {e}", path.display())) +} + +fn fnv(data: &[u8]) -> String { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for b in data { + h ^= u64::from(*b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + format!("{h:016x}") +} + +impl AcmeService { + fn dir(&self) -> PathBuf { + self.rt.acme_dir() + } + + fn paths(&self, host: &str) -> (PathBuf, PathBuf) { + ( + self.dir().join(format!("{host}.crt")), + self.dir().join(format!("{host}.key")), + ) + } + + /// Load a stored certificate into the SNI store; returns its expiry. + fn load_stored(&self, host: &str) -> Option { + let (crt, key) = self.paths(host); + let cert_pem = std::fs::read(&crt).ok()?; + let key_pem = std::fs::read(&key).ok()?; + let expiry = not_after(&cert_pem)?; + match certified_key(&cert_pem, &key_pem) { + Ok(ck) => { + self.certs.insert(host, ck); + Some(expiry) + } + Err(e) => { + log::warn!(target: "ianitor::acme", "{host}: stored certificate is not usable ({e}); ordering a new one"); + None + } + } + } + + fn builder(&self) -> Result { + match &self.ca_root { + Some(p) => Account::builder_with_root(p), + None => Account::builder(), + } + .map_err(|e| format!("cannot set up the ACME client: {e}")) + } + + async fn account(&self, directory: &str, email: Option<&str>) -> Result { + let file = self + .dir() + .join(format!("account-{}.json", fnv(directory.as_bytes()))); + if let Ok(text) = std::fs::read_to_string(&file) { + let creds: AccountCredentials = serde_json::from_str(&text) + .map_err(|e| format!("{} is damaged: {e}", file.display()))?; + return self + .builder()? + .from_credentials(creds) + .await + .map_err(|e| format!("cannot restore the ACME account: {e}")); + } + let contact = email.map(|e| format!("mailto:{e}")); + let contacts: Vec<&str> = contact.iter().map(String::as_str).collect(); + let (account, creds) = self + .builder()? + .create( + &NewAccount { + contact: &contacts, + terms_of_service_agreed: true, + only_return_existing: false, + }, + directory.to_owned(), + None, + ) + .await + .map_err(|e| format!("cannot create the ACME account: {e}"))?; + let text = serde_json::to_vec(&creds) + .map_err(|e| format!("cannot store the ACME account: {e}"))?; + write_private(&file, &text)?; + log::info!(target: "ianitor::acme", "created ACME account at {directory}"); + Ok(account) + } + + async fn issue(&self, account: &Account, host: &str) -> Result { + let ids = [Identifier::Dns(host.to_owned())]; + let mut order = account + .new_order(&NewOrder::new(&ids)) + .await + .map_err(|e| format!("new order: {e}"))?; + let mut tokens = Vec::new(); + let mut auths = order.authorizations(); + while let Some(result) = auths.next().await { + let mut authz = result.map_err(|e| format!("authorization: {e}"))?; + if authz.status == AuthorizationStatus::Valid { + continue; + } + if authz.status != AuthorizationStatus::Pending { + return Err(format!("authorization is {:?}", authz.status)); + } + let mut ch = authz + .challenge(ChallengeType::Http01) + .ok_or("the server offers no HTTP-01 challenge")?; + self.challenges + .insert(ch.token.clone(), ch.key_authorization().as_str().to_owned()); + tokens.push(ch.token.clone()); + ch.set_ready() + .await + .map_err(|e| format!("challenge ready: {e}"))?; + } + let policy = RetryPolicy::new().timeout(Duration::from_secs(90)); + let status = order + .poll_ready(&policy) + .await + .map_err(|e| format!("order: {e}")); + for t in &tokens { + self.challenges.remove(t); + } + match status? { + OrderStatus::Ready => {} + other => return Err(format!("order ended as {other:?}")), + } + let key_pem = order + .finalize() + .await + .map_err(|e| format!("finalize: {e}"))?; + let chain_pem = order + .poll_certificate(&policy) + .await + .map_err(|e| format!("certificate: {e}"))?; + let ck = certified_key(chain_pem.as_bytes(), key_pem.as_bytes())?; + let expiry = + not_after(chain_pem.as_bytes()).ok_or("cannot read the new certificate's expiry")?; + 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); + 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. + async fn round(&self, expiries: &mut HashMap) -> bool { + let Some(acme) = &self.rt.cfg.acme else { + return true; + }; + let due: Vec = self + .rt + .acme_hosts() + .into_iter() + .filter(|h| { + expiries + .get(h) + .is_none_or(|e| (*e as f64) - now_secs() < RENEW_BEFORE_SECS) + }) + .collect(); + if due.is_empty() { + return true; + } + let account = match self.account(&acme.directory, acme.email.as_deref()).await { + Ok(a) => a, + Err(e) => { + log::error!(target: "ianitor::acme", "{e}"); + return false; + } + }; + let mut ok = true; + for host in due { + match self.issue(&account, &host).await { + Ok(exp) => { + expiries.insert(host, exp); + } + Err(e) => { + log::error!(target: "ianitor::acme", "{host}: could not obtain a certificate: {e}"); + ok = false; + } + } + } + ok + } +} + +#[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; + 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 + }; + tokio::select! { + _ = tokio::time::sleep(wait) => {} + _ = shutdown.changed() => return, + } + } + } +} diff --git a/crates/edge/src/error.rs b/crates/edge/src/error.rs new file mode 100644 index 0000000..32d774c --- /dev/null +++ b/crates/edge/src/error.rs @@ -0,0 +1,37 @@ +// 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/. + +//! Startup errors. None of them ever carries a secret value. + +use std::path::PathBuf; + +#[derive(Debug, thiserror::Error)] +pub enum EdgeError { + #[error("cannot read {path}: {source}")] + Read { + path: PathBuf, + source: std::io::Error, + }, + #[error("cannot write {path}: {source}")] + Write { + path: PathBuf, + source: std::io::Error, + }, + #[error("{path} is not a valid edge config: {message}")] + Config { path: PathBuf, message: String }, + #[error("edge config version {found} is not supported (this build reads version {expected})")] + Version { found: u32, expected: u32 }, + #[error("secret `{name}`: {reason}")] + Secret { name: String, reason: &'static str }, + #[error("certificate for {host}: {reason}")] + Cert { host: String, reason: String }, + #[error("upstream {address}: {reason}")] + Upstream { address: String, reason: String }, + #[error("header `{name}`: {reason}")] + Header { name: String, reason: &'static str }, + #[error("listener {address}: {reason}")] + Listen { address: String, reason: String }, + #[error("command line: {0}")] + Usage(String), +} diff --git a/crates/edge/src/fetch.rs b/crates/edge/src/fetch.rs new file mode 100644 index 0000000..f0172eb --- /dev/null +++ b/crates/edge/src/fetch.rs @@ -0,0 +1,63 @@ +// 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 HTTP client on Pingora's connector, for forward-auth subrequests and health checks. + +use std::time::Duration; + +use bytes::{Bytes, BytesMut}; +use pingora::connectors::http::Connector; +use pingora::http::{RequestHeader, ResponseHeader}; +use pingora::upstreams::peer::HttpPeer; +use pingora::{Error, ErrorType, Result}; + +use crate::runtime::UpstreamRt; + +pub struct Fetched { + pub header: ResponseHeader, + pub body: Bytes, +} + +/// Dial timeout, matching Caddy's reverse_proxy default. +pub const DIAL_TIMEOUT: Duration = Duration::from_secs(3); + +pub fn peer(u: &UpstreamRt) -> HttpPeer { + let mut p = HttpPeer::new(u.addr, u.tls, u.sni.clone()); + p.options.connection_timeout = Some(DIAL_TIMEOUT); + p +} + +/// Send `req` without a body; read the whole response, at most `max_body` bytes of body. +pub async fn fetch( + connector: &Connector, + u: &UpstreamRt, + req: RequestHeader, + max_body: usize, + timeout: Duration, +) -> Result { + let mut p = peer(u); + p.options.read_timeout = Some(timeout); + p.options.write_timeout = Some(timeout); + p.options.total_connection_timeout = Some(timeout); + let (mut http, _reused) = connector.get_http_session(&p).await?; + http.write_request_header(Box::new(req)).await?; + http.finish_request_body().await?; + http.read_response_header().await?; + let header = http + .response_header() + .cloned() + .ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?; + let mut body = BytesMut::new(); + while let Some(chunk) = http.read_response_body().await? { + if body.len() + chunk.len() > max_body { + return Error::e_explain(ErrorType::InvalidHTTPHeader, "response body too large"); + } + body.extend_from_slice(&chunk); + } + // Not returned to the pool: these calls are rare and a fresh connection is simplest. + Ok(Fetched { + header, + body: body.freeze(), + }) +} diff --git a/crates/edge/src/forward_auth.rs b/crates/edge/src/forward_auth.rs new file mode 100644 index 0000000..6f7b0a5 --- /dev/null +++ b/crates/edge/src/forward_auth.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/. + +//! Forward-auth compatible with Authelia's ForwardAuth implementation +//! (`GET /api/authz/forward-auth`) and with Caddy's `forward_auth` directive: +//! +//! - The subrequest is a `GET` to the configured path, carrying the client's request headers +//! (minus hop-by-hop and framing headers, never a body) plus `X-Forwarded-Method`, +//! `X-Forwarded-Proto`, `X-Forwarded-Host`, `X-Forwarded-Uri` and `X-Forwarded-For`, which +//! edge always sets itself (client-supplied values are replaced). +//! - A 2xx answer allows the request: each configured identity header is removed from the +//! client request and, when the auth answer has a non-empty value, set from it. +//! - Any other answer is returned to the client as it is (status, headers, body), and the +//! request never reaches the upstream. +//! - If the auth server cannot be reached, the request fails closed with 502. + +use std::time::Duration; + +use bytes::Bytes; +use http::header::{self, HeaderName, HeaderValue}; +use pingora::Result; +use pingora::connectors::http::Connector; +use pingora::http::{RequestHeader, ResponseHeader}; +use pingora::proxy::Session; + +use crate::fetch::fetch; +use crate::runtime::ForwardAuthRt; + +const MAX_AUTH_BODY: usize = 1 << 20; +const AUTH_TIMEOUT: Duration = Duration::from_secs(10); + +pub enum Outcome { + Allow(Vec<(HeaderName, Option)>), + Deny(Box, Bytes), +} + +/// Request headers never copied to a subrequest or a passed-through response. +pub fn hop_by_hop(name: &HeaderName) -> bool { + matches!( + name.as_str(), + "connection" + | "keep-alive" + | "proxy-connection" + | "te" + | "trailer" + | "transfer-encoding" + | "upgrade" + | "content-length" + | "proxy-authenticate" + | "proxy-authorization" + ) +} + +fn forwarded(name: &HeaderName) -> bool { + name.as_str().starts_with("x-forwarded-") +} + +pub async fn check( + connector: &Connector, + fa: &ForwardAuthRt, + session: &Session, + host_header: &str, + client_ip: Option, +) -> Result { + let req = session.req_header(); + let mut sub = RequestHeader::build("GET", fa.path_and_query.as_bytes(), None)?; + for (name, value) in req.headers.iter() { + if !hop_by_hop(name) && !forwarded(name) && name != header::HOST { + sub.append_header(name.clone(), value.clone())?; + } + } + let uri = req.uri.path_and_query().map(|p| p.as_str()).unwrap_or("/"); + sub.insert_header(header::HOST, host_header)?; + sub.insert_header("X-Forwarded-Method", req.method.as_str())?; + sub.insert_header("X-Forwarded-Proto", "https")?; + sub.insert_header("X-Forwarded-Host", host_header)?; + sub.insert_header("X-Forwarded-Uri", uri)?; + if let Some(ip) = client_ip { + sub.insert_header("X-Forwarded-For", ip)?; + } + + let got = fetch(connector, &fa.upstream, sub, MAX_AUTH_BODY, AUTH_TIMEOUT).await?; + let status = got.header.status.as_u16(); + if (200..300).contains(&status) { + let copy = fa + .copy_headers + .iter() + .map(|n| { + let v = got.header.headers.get(n).filter(|v| !v.is_empty()).cloned(); + (n.clone(), v) + }) + .collect(); + return Ok(Outcome::Allow(copy)); + } + + let mut resp = ResponseHeader::build(got.header.status, None)?; + for (name, value) in got.header.headers.iter() { + if !hop_by_hop(name) { + resp.append_header(name.clone(), value.clone())?; + } + } + resp.insert_header(header::CONTENT_LENGTH, got.body.len().to_string())?; + Ok(Outcome::Deny(Box::new(resp), got.body)) +} diff --git a/crates/edge/src/health.rs b/crates/edge/src/health.rs new file mode 100644 index 0000000..648a53d --- /dev/null +++ b/crates/edge/src/health.rs @@ -0,0 +1,76 @@ +// 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/. + +//! 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. + +use std::sync::Arc; +use std::sync::atomic::Ordering; +use std::time::Duration; + +use async_trait::async_trait; +use pingora::connectors::http::Connector; +use pingora::http::RequestHeader; +use pingora::server::ShutdownWatch; +use pingora::services::background::BackgroundService; + +use crate::fetch::fetch; +use crate::runtime::{HostRt, Runtime, UpstreamRt}; + +const TIMEOUT: Duration = Duration::from_secs(5); + +pub struct HealthChecks { + pub rt: 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; + }; + if req + .insert_header(http::header::HOST, u.authority.as_str()) + .is_err() + { + return false; + } + match tokio::time::timeout(TIMEOUT, fetch(connector, u, req, 64 * 1024, TIMEOUT)).await { + Ok(Ok(f)) => f.header.status.is_success(), + _ => false, + } +} + +async fn watch(host: Arc, path: String, every: Duration) { + let connector = Connector::new(None); + loop { + for u in &host.upstreams { + let ok = probe(&connector, u, &path).await; + if u.healthy.swap(ok, Ordering::Relaxed) != ok { + if ok { + log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority); + } else { + log::warn!(target: "ianitor::health", "{}: upstream {} failed its health check", host.cfg.hostname, u.authority); + } + } + } + tokio::time::sleep(every).await; + } +} + +#[async_trait] +impl BackgroundService for HealthChecks { + async fn start(&self, mut shutdown: ShutdownWatch) { + let mut tasks = Vec::new(); + for host in self.rt.hosts.values() { + if let Some(hc) = &host.cfg.health_check { + let every = Duration::from_secs(u64::from(hc.interval_secs.max(1))); + tasks.push(tokio::spawn(watch(host.clone(), hc.path.clone(), every))); + } + } + let _ = shutdown.changed().await; + for t in tasks { + t.abort(); + } + } +} diff --git a/crates/edge/src/http_app.rs b/crates/edge/src/http_app.rs new file mode 100644 index 0000000..bae8e31 --- /dev/null +++ b/crates/edge/src/http_app.rs @@ -0,0 +1,90 @@ +// 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 plain-HTTP listener: answers ACME HTTP-01 challenges, redirects known hosts to HTTPS +//! with 308 (like Caddy), and answers 404 for anything else. + +use std::sync::Arc; +use std::time::Instant; + +use async_trait::async_trait; +use http::{Response, StatusCode, header}; +use pingora::apps::http_app::ServeHttp; +use pingora::protocols::http::ServerSession; + +use crate::acme::Challenges; +use crate::logging::{AccessRecord, now_secs, truncate_ip}; +use crate::proxy::{host_header, hostname}; +use crate::runtime::Runtime; + +pub struct HttpApp { + pub rt: Arc, + pub challenges: Arc, +} + +fn empty(status: StatusCode) -> Response> { + let mut r = Response::new(Vec::new()); + *r.status_mut() = status; + r.headers_mut() + .insert(header::CONTENT_LENGTH, http::HeaderValue::from_static("0")); + r +} + +#[async_trait] +impl ServeHttp for HttpApp { + async fn response(&self, session: &mut ServerSession) -> Response> { + let start = Instant::now(); + let req = session.req_header(); + let hh = host_header(req); + let name = hostname(&hh); + let path = req.uri.path().to_owned(); + + if let Some(token) = path.strip_prefix("/.well-known/acme-challenge/") + && let Some(key_auth) = self.challenges.get(token) + { + log::info!(target: "ianitor::acme", "answered HTTP-01 challenge for {name}"); + let mut r = Response::new(key_auth.into_bytes()); + r.headers_mut().insert( + header::CONTENT_TYPE, + http::HeaderValue::from_static("text/plain"), + ); + return r; + } + + let Some(host) = self.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 location = if port == 443 { + format!("https://{name}{uri}") + } else { + format!("https://{name}:{port}{uri}") + }; + let mut r = empty(StatusCode::PERMANENT_REDIRECT); + match http::HeaderValue::from_str(&location) { + Ok(v) => { + r.headers_mut().insert(header::LOCATION, v); + } + Err(_) => return empty(StatusCode::BAD_REQUEST), + } + if host.cfg.access_log + && let Some(log) = &self.rt.access_log + { + log.write(&AccessRecord { + ts: now_secs(), + host: &host.cfg.hostname, + method: req.method.as_str(), + path: &path, + status: 308, + remote_ip: session + .client_addr() + .and_then(|a| a.as_inet()) + .map(|a| truncate_ip(a.ip()).to_string()), + duration_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX), + }); + } + r + } +} diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index 117b823..1b42089 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -2,4 +2,128 @@ // 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: the Pingora data plane. +//! 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. + +pub mod acme; +pub mod error; +pub mod fetch; +pub mod forward_auth; +pub mod health; +pub mod http_app; +pub mod logging; +pub mod proxy; +pub mod runtime; +pub mod secrets; +pub mod tls; + +use std::path::PathBuf; +use std::sync::Arc; + +use pingora::connectors::http::Connector; +use pingora::listeners::tls::TlsSettings; +use pingora::proxy::http_proxy_service; +use pingora::server::Server; +use pingora::server::configuration::ServerConf; +use pingora::services::background::background_service; +use pingora::services::listening::Service; + +pub use error::EdgeError; +pub use runtime::Runtime; + +#[derive(Debug, Clone, Default)] +pub struct Options { + /// The compiled edge config (`ianitor-core` edge compiler output). + pub config: PathBuf, + /// Extra trust root for the ACME directory's TLS (Pebble in tests). + pub acme_root: Option, +} + +/// 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) +} + +/// Assemble the Pingora server with all services. Listeners bind when it runs. +pub fn server(rt: Arc, opts: &Options) -> Result { + pingora::tls::install_default_crypto_provider(); + let conf = ServerConf { + threads: 2, + grace_period_seconds: Some(5), + graceful_shutdown_timeout_seconds: Some(10), + ..ServerConf::default() + }; + let mut server = Server::new_with_opt_and_conf(None, conf); + server.bootstrap(); + + let challenges = Arc::new(acme::Challenges::default()); + + let mut https = http_proxy_service( + &server.configuration, + proxy::EdgeProxy { + rt: rt.clone(), + connector: Connector::new(None), + }, + ); + let mut tls = TlsSettings::intermediate("", "").map_err(|e| EdgeError::Listen { + address: rt.cfg.https_listen.clone(), + reason: e.to_string(), + })?; + tls.set_cert_resolver(rt.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(), + challenges: challenges.clone(), + }, + ); + http.add_tcp(&rt.cfg.http_listen); + + server.add_service(https); + server.add_service(http); + server.add_service(background_service( + "ianitor health checks", + health::HealthChecks { rt: rt.clone() }, + )); + server.add_service(background_service( + "ianitor acme", + acme::AcmeService { + rt: rt.clone(), + certs: rt.certs.clone(), + challenges, + ca_root: opts.acme_root.clone(), + }, + )); + Ok(server) +} + +/// Run until `stop` resolves (or is dropped). For running edge inside a test process. +#[cfg(unix)] +pub fn run_until(server: Server, stop: tokio::sync::oneshot::Receiver<()>) { + use pingora::server::{RunArgs, ShutdownSignal, ShutdownSignalWatch}; + + struct Stop(tokio::sync::Mutex>>); + + #[async_trait::async_trait] + impl ShutdownSignalWatch for Stop { + async fn recv(&self) -> ShutdownSignal { + if let Some(rx) = self.0.lock().await.take() { + let _ = rx.await; + } + ShutdownSignal::FastShutdown + } + } + + server.run(RunArgs { + shutdown_signal: Box::new(Stop(tokio::sync::Mutex::new(Some(stop)))), + }); +} diff --git a/crates/edge/src/logging.rs b/crates/edge/src/logging.rs new file mode 100644 index 0000000..0b89808 --- /dev/null +++ b/crates/edge/src/logging.rs @@ -0,0 +1,171 @@ +// 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 (stderr, always on; journald under systemd) and the per-host access log +//! (JSON lines in a local file, client IP truncated to /24 or /48, no query strings). +//! +//! Library crates (Pingora, rustls, h2, ...) are capped at `info` whatever `IANITOR_LOG` says: +//! their debug output can include raw request and response headers. + +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +use std::path::Path; +use std::sync::Mutex; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use log::{Level, LevelFilter, Log, Metadata, Record}; +use serde::Serialize; + +use crate::error::EdgeError; + +struct StderrLogger { + own: LevelFilter, +} + +const LIBRARY_MAX: LevelFilter = LevelFilter::Info; + +impl Log for StderrLogger { + fn enabled(&self, m: &Metadata<'_>) -> bool { + let limit = if m.target().starts_with("ianitor") { + self.own + } else { + self.own.min(LIBRARY_MAX) + }; + 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 mut err = std::io::stderr().lock(); + let _ = writeln!(err, "{lvl} {}: {}", r.target(), r.args()); + } + } + + fn flush(&self) { + let _ = std::io::stderr().flush(); + } +} + +/// Install the stderr logger. `level` is `error`, `warn`, `info` (default), `debug` or `trace`. +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(StderrLogger { own })).is_ok() { + log::set_max_level(own); + } +} + +/// IPv4 → /24, IPv6 → /48 (IPv4-mapped IPv6 is treated as IPv4). +pub fn truncate_ip(ip: IpAddr) -> IpAddr { + match ip { + IpAddr::V4(v4) => { + let [a, b, c, _] = v4.octets(); + IpAddr::V4(Ipv4Addr::new(a, b, c, 0)) + } + IpAddr::V6(v6) => match v6.to_ipv4_mapped() { + Some(v4) => truncate_ip(IpAddr::V4(v4)), + None => { + let s = v6.segments(); + IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], 0, 0, 0, 0, 0)) + } + }, + } +} + +#[derive(Serialize)] +pub struct AccessRecord<'a> { + pub ts: f64, + pub host: &'a str, + pub method: &'a str, + /// Path only: query strings can carry tokens. + pub path: &'a str, + pub status: u16, + pub remote_ip: Option, + pub duration_ms: u64, +} + +pub fn now_secs() -> f64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or(Duration::ZERO) + .as_secs_f64() +} + +pub struct AccessLog { + file: Mutex, +} + +impl AccessLog { + pub fn open(path: &Path) -> Result { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|source| EdgeError::Write { + path: dir.to_owned(), + source, + })?; + } + let mut opts = OpenOptions::new(); + opts.create(true).append(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o640); + let file = opts.open(path).map_err(|source| EdgeError::Write { + path: path.to_owned(), + source, + })?; + Ok(AccessLog { + file: Mutex::new(file), + }) + } + + pub fn write(&self, rec: &AccessRecord<'_>) { + let Ok(mut line) = serde_json::to_vec(rec) else { + return; + }; + line.push(b'\n'); + if let Ok(mut f) = self.file.lock() + && let Err(e) = f.write_all(&line) + { + log::error!(target: "ianitor::access", "cannot write the access log: {e}"); + } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + fn t(s: &str) -> String { + truncate_ip(s.parse().unwrap()).to_string() + } + + #[test] + fn ipv4_is_truncated_to_24() { + assert_eq!(t("192.168.17.42"), "192.168.17.0"); + assert_eq!(t("127.0.0.1"), "127.0.0.0"); + } + + #[test] + fn ipv6_is_truncated_to_48() { + assert_eq!(t("2001:db8:abcd:12:3456::1"), "2001:db8:abcd::"); + assert_eq!(t("::1"), "::"); + } + + #[test] + fn mapped_ipv4_is_treated_as_ipv4() { + assert_eq!(t("::ffff:10.1.2.3"), "10.1.2.0"); + } +} diff --git a/crates/edge/src/main.rs b/crates/edge/src/main.rs index f2ceb6d..08210f3 100644 --- a/crates/edge/src/main.rs +++ b/crates/edge/src/main.rs @@ -2,9 +2,61 @@ // 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 binary (not implemented yet). +//! `ianitor-edge --config [--check] [--acme-root ]` +//! +//! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG` +//! (error, warn, info, debug, trace; libraries are capped at info). -fn main() -> std::process::ExitCode { - eprintln!("ianitor-edge: not implemented yet"); - std::process::ExitCode::from(2) +use std::path::PathBuf; +use std::process::ExitCode; + +use ianitor_edge::{EdgeError, Options}; + +fn parse_args() -> Result<(Options, bool), EdgeError> { + let mut opts = Options::default(); + let mut check = false; + let mut config = None; + let mut args = std::env::args_os().skip(1); + while let Some(a) = args.next() { + match a.to_str() { + Some("--config") => config = args.next().map(PathBuf::from), + Some("--acme-root") => opts.acme_root = args.next().map(PathBuf::from), + Some("--check") => check = true, + Some("--help" | "-h") => { + println!( + "usage: ianitor-edge --config [--check] [--acme-root ]" + ); + std::process::exit(0); + } + _ => { + return Err(EdgeError::Usage(format!( + "unknown argument {}", + a.to_string_lossy() + ))); + } + } + } + opts.config = + config.ok_or_else(|| EdgeError::Usage("--config is required".into()))?; + Ok((opts, check)) +} + +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()); + if check { + return Ok(None); + } + ianitor_edge::server(rt, &opts).map(Some) + }); + match started { + Ok(None) => ExitCode::SUCCESS, + Ok(Some(server)) => server.run_forever(), + Err(e) => { + log::error!(target: "ianitor::edge", "{e}"); + ExitCode::FAILURE + } + } } diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs new file mode 100644 index 0000000..9016b7f --- /dev/null +++ b/crates/edge/src/proxy.rs @@ -0,0 +1,332 @@ +// 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 HTTPS reverse proxy. Order per request (same as the Caddy compiler emits): +//! host lookup (unknown → 404) → forward-auth → websocket refusal → upstream with header rules. + +use std::net::IpAddr; +use std::sync::Arc; +use std::sync::atomic::Ordering; +use std::time::Instant; + +use async_trait::async_trait; +use http::header; +use pingora::connectors::http::Connector; +use pingora::http::{RequestHeader, ResponseHeader}; +use pingora::proxy::{FailToProxy, ProxyHttp, Session}; +use pingora::upstreams::peer::HttpPeer; +use pingora::{Error, ErrorSource, ErrorType, Result}; + +use crate::fetch; +use crate::forward_auth::{self, Outcome}; +use crate::logging::{AccessRecord, now_secs, truncate_ip}; +use crate::runtime::{HostRt, Op, Runtime}; + +pub struct EdgeProxy { + pub rt: Arc, + pub connector: Connector, +} + +pub struct Ctx { + host: Option>, + /// The Host header as the client sent it (with port, if any). + host_header: String, + start: Instant, +} + +/// Host header (HTTP/1) or :authority (HTTP/2). +pub fn host_header(req: &RequestHeader) -> String { + req.headers + .get(header::HOST) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned) + .or_else(|| req.uri.authority().map(|a| a.as_str().to_owned())) + .unwrap_or_default() +} + +/// Host without port, lowercase. `[v6]:port` keeps the brackets off. +pub fn hostname(host_header: &str) -> String { + let h = host_header.trim(); + let name = if let Some(rest) = h.strip_prefix('[') { + rest.split(']').next().unwrap_or("") + } else { + h.rsplit_once(':').map_or(h, |(n, port)| { + if port.bytes().all(|c| c.is_ascii_digit()) { + n + } else { + h + } + }) + }; + name.to_ascii_lowercase() +} + +pub fn client_ip(session: &Session) -> Option { + session + .client_addr() + .and_then(|a| a.as_inet()) + .map(|a| a.ip()) +} + +/// A response with an empty body, like Caddy's `static_response` and error responses. +pub async fn respond_empty(session: &mut Session, code: u16) -> Result<()> { + let mut resp = ResponseHeader::build(code, Some(1))?; + resp.insert_header(header::CONTENT_LENGTH, "0")?; + session.write_response_header(Box::new(resp), true).await +} + +fn apply( + ops: &[Op], + mut set: impl FnMut(&http::HeaderName, Option<&http::HeaderValue>) -> Result<()>, +) -> Result<()> { + for op in ops { + match op { + Op::Set(n, v) => set(n, Some(v))?, + Op::Remove(n) => set(n, None)?, + } + } + Ok(()) +} + +fn is_websocket_upgrade(req: &RequestHeader) -> bool { + req.headers + .get(header::UPGRADE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.trim().eq_ignore_ascii_case("websocket")) +} + +#[async_trait] +impl ProxyHttp for EdgeProxy { + type CTX = Ctx; + + fn new_ctx(&self) -> Ctx { + Ctx { + host: None, + host_header: String::new(), + start: Instant::now(), + } + } + + async fn request_filter(&self, session: &mut Session, ctx: &mut Ctx) -> Result { + ctx.host_header = host_header(session.req_header()); + let Some(host) = self.rt.host(&hostname(&ctx.host_header)).cloned() else { + respond_empty(session, 404).await?; + return Ok(true); + }; + ctx.host = Some(host.clone()); + + if host.cfg.forward_auth { + let fa = self.rt.forward_auth.as_ref().ok_or_else(|| { + Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured") + })?; + let ip = client_ip(session).map(|i| i.to_string()); + let outcome = match forward_auth::check( + &self.connector, + fa, + session, + &ctx.host_header, + ip, + ) + .await + { + Ok(o) => o, + Err(e) => { + log::error!(target: "ianitor::auth", "forward-auth for {} failed, denying: {e}", host.cfg.hostname); + return Err(Error::explain( + ErrorType::HTTPStatus(502), + "forward-auth unreachable", + )); + } + }; + match outcome { + Outcome::Deny(resp, body) => { + let head = session.req_header().method == http::Method::HEAD; + let end = head || body.is_empty(); + session.write_response_header(resp, end).await?; + if !end { + session.write_response_body(Some(body), true).await?; + } + return Ok(true); + } + Outcome::Allow(copy) => { + let req = session.req_header_mut(); + for (name, value) in copy { + req.remove_header(&name); + if let Some(v) = value { + req.insert_header(name, v)?; + } + } + } + } + } + + if !host.cfg.websockets && is_websocket_upgrade(session.req_header()) { + respond_empty(session, 403).await?; + return Ok(true); + } + Ok(false) + } + + async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result> { + let host = ctx + .host + .as_ref() + .ok_or_else(|| Error::explain(ErrorType::HTTPStatus(500), "no host"))?; + let n = host.upstreams.len(); + let first = host.next.fetch_add(1, Ordering::Relaxed); + let chosen = (0..n) + .map(|i| &host.upstreams[(first + i) % n]) + .find(|u| u.healthy.load(Ordering::Relaxed)) + .ok_or_else(|| Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream"))?; + log::debug!(target: "ianitor::proxy", "{}: upstream {}", host.cfg.hostname, chosen.authority); + Ok(Box::new(fetch::peer(chosen))) + } + + fn fail_to_connect( + &self, + _s: &mut Session, + _p: &HttpPeer, + _c: &mut Ctx, + mut e: Box, + ) -> Box { + // Like Caddy's default (no lb_try_duration): one attempt, then 502. + e.set_retry(false); + e + } + + async fn upstream_request_filter( + &self, + session: &mut Session, + req: &mut RequestHeader, + ctx: &mut Ctx, + ) -> Result<()> { + // Forwarding headers are always edge's own; client-supplied values are replaced. + match client_ip(session) { + Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?, + None => { + req.remove_header("X-Forwarded-For"); + } + } + req.insert_header("X-Forwarded-Proto", "https")?; + req.insert_header("X-Forwarded-Host", ctx.host_header.as_str())?; + if let Some(host) = &ctx.host { + apply(&host.request_ops, |n, v| { + match v { + Some(v) => req.insert_header(n.clone(), v.clone())?, + None => { + req.remove_header(n); + } + } + Ok(()) + })?; + } + Ok(()) + } + + async fn upstream_response_filter( + &self, + _s: &mut Session, + resp: &mut ResponseHeader, + ctx: &mut Ctx, + ) -> Result<()> { + let Some(host) = &ctx.host else { return Ok(()) }; + apply(&host.response_ops, |n, v| { + match v { + Some(v) => resp.insert_header(n.clone(), v.clone())?, + None => { + resp.remove_header(n); + } + } + Ok(()) + })?; + // Defence in depth: never hand a secret back to a client, even if the upstream echoes it. + if !host.secret_values.is_empty() { + let leaking: Vec = resp + .headers + .iter() + .filter(|(_, v)| host.secret_values.iter().any(|s| contains(v.as_bytes(), s))) + .map(|(n, _)| n.clone()) + .collect(); + for n in leaking { + log::warn!(target: "ianitor::secrets", "{}: dropped response header `{n}` because it contained a secret", host.cfg.hostname); + resp.remove_header(&n); + } + } + Ok(()) + } + + async fn fail_to_proxy(&self, session: &mut Session, e: &Error, _ctx: &mut Ctx) -> FailToProxy { + let code = match e.etype() { + ErrorType::HTTPStatus(c) => *c, + _ => match e.esource() { + ErrorSource::Upstream => 502, + ErrorSource::Downstream => match e.etype() { + ErrorType::WriteError | ErrorType::ReadError | ErrorType::ConnectionClosed => 0, + _ => 400, + }, + ErrorSource::Internal | ErrorSource::Unset => 500, + }, + }; + if code > 0 + && session.response_written().is_none() + && let Err(err) = respond_empty(session, code).await + { + log::debug!(target: "ianitor::proxy", "could not send the error response: {err}"); + } + FailToProxy { + error_code: code, + can_reuse_downstream: false, + } + } + + async fn logging(&self, session: &mut Session, _e: Option<&Error>, ctx: &mut Ctx) { + let Some(host) = &ctx.host else { return }; + if !host.cfg.access_log { + return; + } + let Some(log) = &self.rt.access_log else { + return; + }; + let req = session.req_header(); + log.write(&AccessRecord { + ts: now_secs(), + host: &host.cfg.hostname, + method: req.method.as_str(), + path: req.uri.path(), + status: session.response_written().map_or(0, |r| r.status.as_u16()), + remote_ip: client_ip(session).map(|i| truncate_ip(i).to_string()), + duration_ms: u64::try_from(ctx.start.elapsed().as_millis()).unwrap_or(u64::MAX), + }); + } + + fn request_summary(&self, session: &Session, ctx: &Ctx) -> String { + // Method, host and path only: no query string, no headers. + let req = session.req_header(); + format!("{} {}{}", req.method, ctx.host_header, req.uri.path()) + } +} + +pub fn contains(hay: &[u8], needle: &[u8]) -> bool { + !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hostname_strips_port_and_case() { + assert_eq!(hostname("App.Test:8443"), "app.test"); + assert_eq!(hostname("app.test"), "app.test"); + assert_eq!(hostname("[::1]:443"), "::1"); + assert_eq!(hostname(""), ""); + } + + #[test] + fn contains_finds_substrings() { + assert!(contains(b"abc-secret-def", b"secret")); + assert!(!contains(b"abc", b"")); + assert!(!contains(b"sec", b"secret")); + } +} diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs new file mode 100644 index 0000000..5661836 --- /dev/null +++ b/crates/edge/src/runtime.rs @@ -0,0 +1,251 @@ +// 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 compiled edge config turned into ready-to-serve state: resolved upstream addresses, +//! parsed header names, secrets loaded, certificates loaded. Built once at startup. + +use std::collections::{BTreeSet, HashMap}; +use std::net::{SocketAddr, ToSocketAddrs}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize}; + +use http::{HeaderName, HeaderValue}; +use ianitor_core::edge_config::{ + EDGE_CONFIG_VERSION, EdgeConfig, EdgeHeaderOp, EdgeHost, EdgeTls, EdgeUpstream, EdgeValue, +}; + +use crate::error::EdgeError; +use crate::logging::AccessLog; +use crate::secrets::Secrets; +use crate::tls::{CertStore, certified_key}; + +pub enum Op { + Set(HeaderName, HeaderValue), + Remove(HeaderName), +} + +pub struct UpstreamRt { + pub addr: SocketAddr, + /// `host:port` as configured; the Host header of health checks. + pub authority: String, + pub tls: bool, + pub sni: String, + pub healthy: AtomicBool, +} + +pub struct HostRt { + pub cfg: EdgeHost, + pub upstreams: Vec, + pub next: AtomicUsize, + pub request_ops: Vec, + pub response_ops: Vec, + /// Values of the secrets this host injects; a response header containing one is dropped. + pub secret_values: Vec>, +} + +pub struct ForwardAuthRt { + pub upstream: UpstreamRt, + pub path_and_query: String, + pub copy_headers: Vec, +} + +pub struct Runtime { + pub cfg: EdgeConfig, + pub hosts: HashMap>, + pub forward_auth: Option, + pub access_log: Option, + pub certs: Arc, +} + +impl Runtime { + pub fn host(&self, name: &str) -> Option<&Arc> { + self.hosts.get(name) + } + + pub fn acme_hosts(&self) -> Vec { + self.cfg + .hosts + .iter() + .filter(|h| h.tls == EdgeTls::Acme) + .map(|h| h.hostname.clone()) + .collect() + } + + pub fn acme_dir(&self) -> PathBuf { + Path::new(&self.cfg.state_dir).join("acme") + } +} + +pub fn read_config(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|source| EdgeError::Read { + path: path.to_owned(), + source, + })?; + let cfg: EdgeConfig = serde_json::from_str(&text).map_err(|e| EdgeError::Config { + path: path.to_owned(), + message: e.to_string(), + })?; + if cfg.version != EDGE_CONFIG_VERSION { + return Err(EdgeError::Version { + found: cfg.version, + expected: EDGE_CONFIG_VERSION, + }); + } + Ok(cfg) +} + +fn upstream(u: &EdgeUpstream) -> Result { + let err = |reason: String| EdgeError::Upstream { + address: u.address.clone(), + reason, + }; + // Resolved once at startup; Pingora peers need a socket address. + let addr = u + .address + .to_socket_addrs() + .map_err(|e| err(format!("cannot resolve: {e}")))? + .next() + .ok_or_else(|| err("resolves to no address".into()))?; + Ok(UpstreamRt { + addr, + authority: u.address.clone(), + tls: u.tls, + sni: u.sni.clone(), + healthy: AtomicBool::new(true), + }) +} + +fn header_name(name: &str) -> Result { + HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header { + name: name.to_owned(), + reason: "not a valid header name", + }) +} + +fn ops( + list: &[EdgeHeaderOp], + secrets: &Secrets, + values: &mut Vec>, +) -> Result, EdgeError> { + list.iter() + .map(|op| match op { + EdgeHeaderOp::Remove { name } => Ok(Op::Remove(header_name(name)?)), + EdgeHeaderOp::Set { name, value } => { + let v = match value { + EdgeValue::Literal { value } => { + HeaderValue::from_str(value).map_err(|_| EdgeError::Header { + name: name.clone(), + reason: "value is not a valid header value", + })? + } + EdgeValue::Secret { name: secret } => { + let s = secrets.get(secret).ok_or(EdgeError::Secret { + name: secret.clone(), + reason: "not loaded", + })?; + values.push(s.as_bytes().to_vec()); + s.header_value() + } + }; + Ok(Op::Set(header_name(name)?, v)) + } + }) + .collect() +} + +/// Load secrets and certificates and resolve upstreams. Fails on the first problem; edge never +/// starts half-configured. +pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result { + let names: BTreeSet = cfg + .hosts + .iter() + .flat_map(|h| h.request_headers.iter().chain(&h.response_headers)) + .filter_map(|op| match op { + EdgeHeaderOp::Set { + value: EdgeValue::Secret { name }, + .. + } => Some(name.clone()), + _ => None, + }) + .collect(); + let secrets = Secrets::load(&names, credentials_dir)?; + + let certs = Arc::new(CertStore::default()); + let mut hosts = HashMap::new(); + for h in &cfg.hosts { + if let EdgeTls::Files { cert, key } = &h.tls { + let read = |p: &str| { + std::fs::read(p).map_err(|source| EdgeError::Read { + path: PathBuf::from(p), + source, + }) + }; + let pair = + certified_key(&read(cert)?, &read(key)?).map_err(|reason| EdgeError::Cert { + host: h.hostname.clone(), + reason, + })?; + certs.insert(&h.hostname, pair); + } + let mut secret_values = Vec::new(); + let request_ops = ops(&h.request_headers, &secrets, &mut secret_values)?; + let response_ops = ops(&h.response_headers, &secrets, &mut secret_values)?; + let upstreams = h + .upstreams + .iter() + .map(upstream) + .collect::, _>>()?; + if upstreams.is_empty() { + return Err(EdgeError::Upstream { + address: h.hostname.clone(), + reason: "host has no upstream".into(), + }); + } + hosts.insert( + h.hostname.clone(), + Arc::new(HostRt { + cfg: h.clone(), + upstreams, + next: AtomicUsize::new(0), + request_ops, + response_ops, + secret_values, + }), + ); + } + + let forward_auth = match &cfg.forward_auth { + Some(fa) => Some(ForwardAuthRt { + upstream: upstream(&fa.upstream)?, + path_and_query: fa.path_and_query.clone(), + copy_headers: fa + .copy_headers + .iter() + .map(|h| header_name(h)) + .collect::>()?, + }), + None => None, + }; + if forward_auth.is_none() && cfg.hosts.iter().any(|h| h.forward_auth) { + return Err(EdgeError::Config { + path: PathBuf::from(""), + message: "a host uses forward-auth but no forward_auth endpoint is configured".into(), + }); + } + + let access_log = if cfg.hosts.iter().any(|h| h.access_log) { + Some(AccessLog::open(Path::new(&cfg.access_log))?) + } else { + None + }; + + Ok(Runtime { + cfg, + hosts, + forward_auth, + access_log, + certs, + }) +} diff --git a/crates/edge/src/secrets.rs b/crates/edge/src/secrets.rs new file mode 100644 index 0000000..52421f1 --- /dev/null +++ b/crates/edge/src/secrets.rs @@ -0,0 +1,163 @@ +// 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/. + +//! Secrets referenced by header rules, read once at startup from `$CREDENTIALS_DIRECTORY` +//! (systemd `LoadCredential=`). A [`Secret`] never prints its value: `Debug` and `Display` +//! are redacted, the header value is marked sensitive (HPACK never-index) and errors name +//! the secret, never its content. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; +use std::path::Path; + +use http::HeaderValue; + +use crate::error::EdgeError; + +/// Largest credential file accepted. +const MAX_LEN: u64 = 8192; + +#[derive(Clone)] +pub struct Secret { + value: HeaderValue, +} + +impl Secret { + pub fn header_value(&self) -> HeaderValue { + self.value.clone() + } + + pub fn as_bytes(&self) -> &[u8] { + self.value.as_bytes() + } +} + +impl fmt::Debug for Secret { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Secret()") + } +} + +impl fmt::Display for Secret { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("") + } +} + +/// Turn a credential file's bytes into a header value. One trailing newline (`\n` or `\r\n`) +/// is dropped, as Caddy's `{file.*}` placeholder does; anything else must be one line of +/// visible ASCII, spaces and tabs. +pub fn parse(name: &str, raw: &[u8]) -> Result { + let err = |reason| EdgeError::Secret { + name: name.to_owned(), + reason, + }; + let trimmed = raw + .strip_suffix(b"\r\n") + .or_else(|| raw.strip_suffix(b"\n")) + .unwrap_or(raw); + if trimmed.is_empty() { + return Err(err("the credential is empty")); + } + if !trimmed + .iter() + .all(|c| (0x20..0x7f).contains(c) || *c == b'\t') + { + return Err(err("the credential must be a single line of visible ASCII")); + } + let mut value = HeaderValue::from_bytes(trimmed) + .map_err(|_| err("the credential is not a valid header value"))?; + value.set_sensitive(true); + Ok(Secret { value }) +} + +pub struct Secrets(BTreeMap); + +impl Secrets { + pub fn get(&self, name: &str) -> Option<&Secret> { + self.0.get(name) + } + + /// Load every named secret from `dir` (the value of `$CREDENTIALS_DIRECTORY`). + pub fn load(names: &BTreeSet, dir: Option<&Path>) -> Result { + let mut out = BTreeMap::new(); + for name in names { + // Names are validated by core, but the edge config is input too. + if name.is_empty() + || !name + .bytes() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_' || c == b'-') + { + return Err(EdgeError::Secret { + name: name.clone(), + reason: "the name is not a valid credential name", + }); + } + let Some(dir) = dir else { + return Err(EdgeError::Secret { + name: name.clone(), + reason: "$CREDENTIALS_DIRECTORY is not set (use systemd LoadCredential=)", + }); + }; + let path = dir.join(name); + let meta = std::fs::metadata(&path).map_err(|_| EdgeError::Secret { + name: name.clone(), + reason: "no such credential in $CREDENTIALS_DIRECTORY", + })?; + if meta.len() > MAX_LEN { + return Err(EdgeError::Secret { + name: name.clone(), + reason: "the credential is larger than 8 KiB", + }); + } + let raw = std::fs::read(&path).map_err(|_| EdgeError::Secret { + name: name.clone(), + reason: "the credential cannot be read", + })?; + out.insert(name.clone(), parse(name, &raw)?); + } + Ok(Secrets(out)) + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::panic)] + use super::*; + + #[test] + fn trailing_newline_is_dropped_once() { + assert_eq!(parse("a", b"value\n").unwrap().as_bytes(), b"value"); + assert_eq!(parse("a", b"value\r\n").unwrap().as_bytes(), b"value"); + assert_eq!(parse("a", b"value").unwrap().as_bytes(), b"value"); + } + + #[test] + fn multi_line_and_control_bytes_are_refused() { + for bad in [ + &b"a\nb"[..], + b"a\n\n", + b"a\rb", + b"\0", + b"", + b"\n", + "ü".as_bytes(), + ] { + assert!(parse("a", bad).is_err(), "{bad:?}"); + } + } + + #[test] + fn debug_and_display_never_show_the_value() { + let s = parse("a", b"hunter2").unwrap(); + assert!(!format!("{s:?} {s}").contains("hunter2")); + assert!(s.header_value().is_sensitive()); + } + + #[test] + fn errors_never_contain_the_value() { + let e = parse("api", b"hunter2\nx").unwrap_err(); + assert!(!e.to_string().contains("hunter2")); + } +} diff --git a/crates/edge/src/tls.rs b/crates/edge/src/tls.rs new file mode 100644 index 0000000..35bd3d6 --- /dev/null +++ b/crates/edge/src/tls.rs @@ -0,0 +1,66 @@ +// 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/. + +//! Certificate selection by SNI. Certificates can be swapped at runtime (ACME renewals) +//! without touching connections in flight. + +use std::collections::HashMap; +use std::sync::Arc; + +use arc_swap::ArcSwap; +use rustls::server::{ClientHello, ResolvesServerCert}; +use rustls::sign::CertifiedKey; +use rustls_pki_types::pem::PemObject; +use rustls_pki_types::{CertificateDer, PrivateKeyDer}; + +#[derive(Debug, Default)] +pub struct CertStore { + certs: ArcSwap>>, +} + +impl CertStore { + pub fn insert(&self, host: &str, key: CertifiedKey) { + let key = Arc::new(key); + self.certs.rcu(|m| { + let mut m = HashMap::clone(m); + m.insert(host.to_owned(), key.clone()); + m + }); + } + + pub fn has(&self, host: &str) -> bool { + self.certs.load().contains_key(host) + } +} + +impl ResolvesServerCert for CertStore { + fn resolve(&self, hello: ClientHello<'_>) -> Option> { + // No SNI or an unknown name: no certificate, the handshake fails (as with Caddy). + let name = hello.server_name()?.to_ascii_lowercase(); + self.certs.load().get(&name).cloned() + } +} + +/// Parse a PEM chain and PEM private key into a rustls key pair, checking they match. +pub fn certified_key(cert_pem: &[u8], key_pem: &[u8]) -> Result { + let chain: Vec> = CertificateDer::pem_slice_iter(cert_pem) + .collect::>() + .map_err(|e| format!("cannot parse the certificate chain: {e}"))?; + if chain.is_empty() { + return Err("the certificate file has no certificate".into()); + } + // Never include key bytes in an error. + let key = PrivateKeyDer::from_pem_slice(key_pem) + .map_err(|_| "cannot parse the private key".to_owned())?; + let provider = rustls::crypto::ring::default_provider(); + CertifiedKey::from_der(chain, key, &provider) + .map_err(|e| format!("certificate and key do not form a usable pair: {e}")) +} + +/// `notAfter` of the first certificate in a PEM chain, as Unix seconds. +pub fn not_after(cert_pem: &[u8]) -> Option { + let first = CertificateDer::pem_slice_iter(cert_pem).next()?.ok()?; + let (_, cert) = x509_parser::parse_x509_certificate(first.as_ref()).ok()?; + Some(cert.validity().not_after.timestamp()) +} diff --git a/crates/edge/tests/common/mod.rs b/crates/edge/tests/common/mod.rs index b3cc2c1..ff7ccc6 100644 --- a/crates/edge/tests/common/mod.rs +++ b/crates/edge/tests/common/mod.rs @@ -13,8 +13,8 @@ use std::sync::Arc; use std::time::Duration; use ianitor_core::compile::{self, CompileOptions}; -use ianitor_core::{load, SourceFile, TlsMode}; -use ianitor_testkit::proc::{free_port, local, wait_for_port, ChildGuard, TempDir}; +use ianitor_core::{SourceFile, TlsMode, load}; +use ianitor_testkit::proc::{ChildGuard, TempDir, free_port, local, wait_for_port}; use ianitor_testkit::tls::TestCa; use rustls::RootCertStore; @@ -42,7 +42,12 @@ impl Edge { /// Everything edge wrote or was given, except the credentials themselves. pub fn all_output(&self) -> String { - format!("{}\n{}\n{}", self.stderr(), self.access_log(), self.config_text) + format!( + "{}\n{}\n{}", + self.stderr(), + self.access_log(), + self.config_text + ) } pub fn exited(&mut self) -> Option { @@ -60,7 +65,13 @@ pub struct EdgeSpec<'a> { impl Default for EdgeSpec<'_> { fn default() -> Self { - EdgeSpec { site: "", hosts: Vec::new(), secrets: Vec::new(), log_level: "info", extra_args: Vec::new() } + EdgeSpec { + site: "", + hosts: Vec::new(), + secrets: Vec::new(), + log_level: "info", + extra_args: Vec::new(), + } } } @@ -70,14 +81,32 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge { for d in ["certs", "state", "creds", "logs"] { std::fs::create_dir_all(dir.join(d)).unwrap(); } - let sources: Vec = spec.hosts.iter().map(|(n, c)| SourceFile { name: n, contents: c }).collect(); - let model = load(&SourceFile { name: "ianitor.toml", contents: spec.site }, &sources).expect("valid routes"); + let sources: Vec = spec + .hosts + .iter() + .map(|(n, c)| SourceFile { + name: n, + contents: c, + }) + .collect(); + let model = load( + &SourceFile { + name: "ianitor.toml", + contents: spec.site, + }, + &sources, + ) + .expect("valid routes"); let ca = TestCa::new("Ianitor Test CA"); for h in model.hosts() { if h.tls == TlsMode::Domi { let leaf = ca.issue(&[h.hostname.as_str()]); - std::fs::write(dir.join(&format!("certs/{}.crt", h.hostname)), leaf.cert_pem).unwrap(); + std::fs::write( + dir.join(&format!("certs/{}.crt", h.hostname)), + leaf.cert_pem, + ) + .unwrap(); std::fs::write(dir.join(&format!("certs/{}.key", h.hostname)), leaf.key_pem).unwrap(); } } @@ -105,15 +134,24 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge { cmd.args(&spec.extra_args); cmd.env("CREDENTIALS_DIRECTORY", dir.join("creds")); cmd.env("IANITOR_LOG", spec.log_level); - cmd.stdout(Stdio::from(stderr.try_clone().unwrap())).stderr(Stdio::from(stderr)); + cmd.stdout(Stdio::from(stderr.try_clone().unwrap())) + .stderr(Stdio::from(stderr)); let child = ChildGuard(cmd.spawn().expect("spawn ianitor-edge")); - Edge { child, http, https, dir, ca, config_text } + Edge { + child, + http, + https, + dir, + ca, + config_text, + } } /// Spawn and wait until both listeners accept connections. pub fn start(spec: EdgeSpec<'_>) -> Edge { let mut e = spawn(spec); - let ok = wait_for_port(e.https, Duration::from_secs(20)) && wait_for_port(e.http, Duration::from_secs(5)); + let ok = wait_for_port(e.https, Duration::from_secs(20)) + && wait_for_port(e.http, Duration::from_secs(5)); if !ok || e.exited().is_some() { panic!("ianitor-edge did not start:\n{}", e.stderr()); } @@ -121,5 +159,8 @@ pub fn start(spec: EdgeSpec<'_>) -> Edge { } pub fn host_file(hostname: &str, body: &str) -> (String, String) { - (format!("hosts/{hostname}.toml"), format!("hostname = \"{hostname}\"\ntls = \"domi\"\n{body}")) + ( + format!("hosts/{hostname}.toml"), + format!("hostname = \"{hostname}\"\ntls = \"domi\"\n{body}"), + ) } diff --git a/crates/edge/tests/forward_auth.rs b/crates/edge/tests/forward_auth.rs index 0f80807..85a7b78 100644 --- a/crates/edge/tests/forward_auth.rs +++ b/crates/edge/tests/forward_auth.rs @@ -11,10 +11,10 @@ mod common; -use common::{host_file, start, EdgeSpec}; +use common::{EdgeSpec, host_file, start}; use ianitor_testkit::authelia::MockAuthelia; use ianitor_testkit::client::{self, Req, WsOutcome}; -use ianitor_testkit::upstream::{closed_port, Echo, WsEcho}; +use ianitor_testkit::upstream::{Echo, WsEcho, closed_port}; fn site(auth_url: &str) -> String { format!("[forward_auth]\nurl = \"{auth_url}\"\n") @@ -29,8 +29,17 @@ async fn denial_never_reaches_the_upstream() { let edge = start(EdgeSpec { site: &site, hosts: vec![ - host_file("auth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url())), - host_file("wsauth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", ws.url())), + host_file( + "auth.test", + &format!( + "upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", + echo.url() + ), + ), + host_file( + "wsauth.test", + &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", ws.url()), + ), ], ..Default::default() }); @@ -48,7 +57,10 @@ async fn denial_never_reaches_the_upstream() { r.header("location"), Some("https://auth.test/?rd=https%3A%2F%2Fauth.test%2Fprivate%3Fx%3D1") ); - assert_eq!(r.header("set-cookie"), Some("authelia_flow=1; Path=/; HttpOnly")); + assert_eq!( + r.header("set-cookie"), + Some("authelia_flow=1; Path=/; HttpOnly") + ); assert!(r.text().contains("302 Found")); let r = go(Req::new("HEAD", "auth.test", "/")).await; @@ -60,7 +72,10 @@ async fn denial_never_reaches_the_upstream() { let r = go(Req::get("auth.test", "/").header("authorization", "Bearer wrong")).await; assert_eq!(r.status, 401); - assert_eq!(r.header("www-authenticate"), Some("Basic realm=\"Authorization Required\"")); + assert_eq!( + r.header("www-authenticate"), + Some("Basic realm=\"Authorization Required\"") + ); let r = go(Req::get("auth.test", "/").header("cookie", "authelia_session=forbidden")).await; assert_eq!(r.status, 403); @@ -74,16 +89,38 @@ async fn denial_never_reaches_the_upstream() { .header("x-forwarded-for", "10.0.0.1")) .await; assert_eq!(r.status, 302); - assert!(r.header("location").unwrap().contains("auth.test%2Fadmin"), "edge sends its own X-Forwarded-*"); + assert!( + r.header("location").unwrap().contains("auth.test%2Fadmin"), + "edge sends its own X-Forwarded-*" + ); // A websocket upgrade without a session is denied before any upgrade happens. - match client::websocket(edge.https, "wsauth.test", roots.clone(), "wsauth.test", "/socket", &[], "hi").await.unwrap() { + match client::websocket( + edge.https, + "wsauth.test", + roots.clone(), + "wsauth.test", + "/socket", + &[], + "hi", + ) + .await + .unwrap() + { WsOutcome::Refused(r) => assert_eq!(r.status, 302), WsOutcome::Upgraded { .. } => panic!("unauthenticated websocket was upgraded"), } - assert!(echo.proxied().is_empty(), "a denied request reached the upstream: {:?}", echo.proxied()); - assert_eq!(ws.connections(), 0, "a denied websocket reached the upstream"); + assert!( + echo.proxied().is_empty(), + "a denied request reached the upstream: {:?}", + echo.proxied() + ); + assert_eq!( + ws.connections(), + 0, + "a denied websocket reached the upstream" + ); // What Authelia was told, per its proxy-authorization guide. let asked = authelia.requests(); @@ -95,10 +132,22 @@ async fn denial_never_reaches_the_upstream() { assert_eq!(post.method, "GET", "the auth subrequest is a GET"); assert_eq!(post.path, "/api/authz/forward-auth"); assert_eq!(post.header("x-forwarded-proto"), Some(b"https".as_slice())); - assert_eq!(post.header("x-forwarded-host"), Some(b"auth.test".as_slice())); - assert_eq!(post.header("x-forwarded-uri"), Some(b"/submit?x=1".as_slice())); - assert_eq!(post.header("x-forwarded-for"), Some(b"127.0.0.1".as_slice())); - assert!(post.body.is_empty(), "the request body is not sent to the auth server"); + assert_eq!( + post.header("x-forwarded-host"), + Some(b"auth.test".as_slice()) + ); + assert_eq!( + post.header("x-forwarded-uri"), + Some(b"/submit?x=1".as_slice()) + ); + assert_eq!( + post.header("x-forwarded-for"), + Some(b"127.0.0.1".as_slice()) + ); + assert!( + post.body.is_empty(), + "the request body is not sent to the auth server" + ); } #[tokio::test(flavor = "multi_thread")] @@ -108,7 +157,13 @@ async fn allowed_request_carries_identity_from_the_auth_server_only() { let site = site(&authelia.url()); let edge = start(EdgeSpec { site: &site, - hosts: vec![host_file("auth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()))], + hosts: vec![host_file( + "auth.test", + &format!( + "upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", + echo.url() + ), + )], ..Default::default() }); let roots = edge.roots(); @@ -131,10 +186,19 @@ async fn allowed_request_carries_identity_from_the_auth_server_only() { let up = &seen[0]; assert_eq!(up.header("remote-user"), Some(b"alice".as_slice())); assert_eq!(up.header("remote-groups"), Some(b"admins,dev".as_slice())); - assert_eq!(up.header("remote-email"), Some(b"alice@example.org".as_slice())); + assert_eq!( + up.header("remote-email"), + Some(b"alice@example.org".as_slice()) + ); assert_eq!(up.header("remote-name"), Some(b"Alice Example".as_slice())); assert_eq!(up.body, b"form=data", "the body still reaches the upstream"); - assert_eq!(up.headers.iter().filter(|(n, _)| n == "remote-user").count(), 1); + assert_eq!( + up.headers + .iter() + .filter(|(n, _)| n == "remote-user") + .count(), + 1 + ); // Allowed without identity: the client's own Remote-* headers are removed, not passed on. echo.clear(); @@ -142,31 +206,52 @@ async fn allowed_request_carries_identity_from_the_auth_server_only() { edge.https, "auth.test", roots.clone(), - &Req::get("auth.test", "/").header("cookie", "authelia_session=nameless").header("remote-user", "mallory"), + &Req::get("auth.test", "/") + .header("cookie", "authelia_session=nameless") + .header("remote-user", "mallory"), ) .await .unwrap(); assert_eq!(r.status, 200); assert_eq!(echo.proxied()[0].header("remote-user"), None); - let r = client::https(edge.https, "auth.test", roots, &Req::get("auth.test", "/").header("authorization", "Bearer good")) - .await - .unwrap(); + let r = client::https( + edge.https, + "auth.test", + roots, + &Req::get("auth.test", "/").header("authorization", "Bearer good"), + ) + .await + .unwrap(); assert_eq!(r.status, 200); } #[tokio::test(flavor = "multi_thread")] async fn unreachable_auth_server_fails_closed() { let echo = Echo::start("app").await; - let site = site(&format!("http://127.0.0.1:{}/api/authz/forward-auth", closed_port())); + let site = site(&format!( + "http://127.0.0.1:{}/api/authz/forward-auth", + closed_port() + )); let edge = start(EdgeSpec { site: &site, - hosts: vec![host_file("auth.test", &format!("upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", echo.url()))], + hosts: vec![host_file( + "auth.test", + &format!( + "upstreams = [\"{}\"]\nauth = \"forward-auth\"\n", + echo.url() + ), + )], ..Default::default() }); - let r = client::https(edge.https, "auth.test", edge.roots(), &Req::get("auth.test", "/").header("cookie", "authelia_session=good")) - .await - .unwrap(); + let r = client::https( + edge.https, + "auth.test", + edge.roots(), + &Req::get("auth.test", "/").header("cookie", "authelia_session=good"), + ) + .await + .unwrap(); assert_eq!(r.status, 502); assert!(echo.proxied().is_empty()); } diff --git a/crates/edge/tests/secrets.rs b/crates/edge/tests/secrets.rs index 43f9593..addc881 100644 --- a/crates/edge/tests/secrets.rs +++ b/crates/edge/tests/secrets.rs @@ -10,12 +10,15 @@ mod common; -use common::{host_file, start, spawn, EdgeSpec}; +use common::{EdgeSpec, host_file, spawn, start}; use ianitor_testkit::client::{self, Req, Resp, WsOutcome}; -use ianitor_testkit::upstream::{closed_port, Echo, WsEcho}; +use ianitor_testkit::upstream::{Echo, WsEcho, closed_port}; fn unique_secret() -> String { - let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); format!("sekret-{}-{nanos:x}-tail", std::process::id()) } @@ -26,7 +29,11 @@ fn assert_clean(what: &str, haystack: &[u8], secret: &str) { fn assert_resp_clean(what: &str, r: &Resp, secret: &str) { for (n, v) in &r.headers { - assert_clean(&format!("{what}: response header {n}"), v.as_bytes(), secret); + assert_clean( + &format!("{what}: response header {n}"), + v.as_bytes(), + secret, + ); } assert_clean(&format!("{what}: response body"), &r.body, secret); } @@ -36,13 +43,32 @@ async fn injected_secret_never_appears_in_a_response_or_log() { let secret = unique_secret(); let echo = Echo::start("app").await; let ws = WsEcho::start().await; - let rule = "[[request_headers]]\naction = \"set\"\nname = \"X-Api-Key\"\nsecret = \"api_key\"\n"; + let rule = + "[[request_headers]]\naction = \"set\"\nname = \"X-Api-Key\"\nsecret = \"api_key\"\n"; let edge = start(EdgeSpec { site: "secrets = [\"api_key\"]\n", hosts: vec![ - host_file("app.test", &format!("upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}", echo.url())), - host_file("down.test", &format!("upstreams = [\"http://127.0.0.1:{}\"]\naccess_log = \"truncated\"\n{rule}", closed_port())), - host_file("ws.test", &format!("upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}", ws.url())), + host_file( + "app.test", + &format!( + "upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}", + echo.url() + ), + ), + host_file( + "down.test", + &format!( + "upstreams = [\"http://127.0.0.1:{}\"]\naccess_log = \"truncated\"\n{rule}", + closed_port() + ), + ), + host_file( + "ws.test", + &format!( + "upstreams = [\"{}\"]\naccess_log = \"truncated\"\n{rule}", + ws.url() + ), + ), ], // systemd credentials usually end with a newline; it is not part of the value. secrets: vec![("api_key".into(), format!("{secret}\n").into_bytes())], @@ -57,20 +83,45 @@ async fn injected_secret_never_appears_in_a_response_or_log() { }; let mut responses = Vec::new(); - responses.push(("plain GET", go("app.test", Req::get("app.test", "/hello?token=abc")).await)); - responses.push(("POST", go("app.test", Req::new("POST", "app.test", "/submit").body(b"payload")).await)); + responses.push(( + "plain GET", + go("app.test", Req::get("app.test", "/hello?token=abc")).await, + )); + responses.push(( + "POST", + go( + "app.test", + Req::new("POST", "app.test", "/submit").body(b"payload"), + ) + .await, + )); responses.push(( "client tries to set the header", - go("app.test", Req::get("app.test", "/").header("x-api-key", "attacker")).await, + go( + "app.test", + Req::get("app.test", "/").header("x-api-key", "attacker"), + ) + .await, + )); + responses.push(( + "upstream error status", + go("app.test", Req::get("app.test", "/status/500")).await, )); - responses.push(("upstream error status", go("app.test", Req::get("app.test", "/status/500")).await)); responses.push(( "upstream reflects the secret in a header", go("app.test", Req::get("app.test", "/reflect?h=x-api-key")).await, )); - responses.push(("upstream down", go("down.test", Req::get("down.test", "/")).await)); - responses.push(("unknown host", go("app.test", Req::get("nope.test", "/")).await)); - let plain = client::http(edge.http, &Req::get("app.test", "/x?y=1")).await.unwrap(); + responses.push(( + "upstream down", + go("down.test", Req::get("down.test", "/")).await, + )); + responses.push(( + "unknown host", + go("app.test", Req::get("nope.test", "/")).await, + )); + let plain = client::http(edge.http, &Req::get("app.test", "/x?y=1")) + .await + .unwrap(); responses.push(("plain HTTP redirect", plain)); for (what, r) in &responses { @@ -78,10 +129,24 @@ async fn injected_secret_never_appears_in_a_response_or_log() { } assert_eq!(responses[0].1.status, 200); assert_eq!(responses[4].1.status, 200); - assert!(responses[4].1.header("x-reflected").is_none(), "edge strips a response header carrying a secret"); + assert!( + responses[4].1.header("x-reflected").is_none(), + "edge strips a response header carrying a secret" + ); assert_eq!(responses[5].1.status, 502); - match client::websocket(edge.https, "ws.test", roots.clone(), "ws.test", "/socket", &[], "ping").await.unwrap() { + match client::websocket( + edge.https, + "ws.test", + roots.clone(), + "ws.test", + "/socket", + &[], + "ping", + ) + .await + .unwrap() + { WsOutcome::Upgraded { status, echo } => { assert_eq!(status, 101); assert_eq!(echo, "ping"); @@ -93,18 +158,38 @@ async fn injected_secret_never_appears_in_a_response_or_log() { let seen = echo.proxied(); assert!(seen.len() >= 5, "{seen:?}"); for r in &seen { - assert_eq!(r.header("x-api-key"), Some(secret.as_bytes()), "upstream request {}", r.path); + assert_eq!( + r.header("x-api-key"), + Some(secret.as_bytes()), + "upstream request {}", + r.path + ); } // Give the access log a moment to flush, then check every output channel. tokio::time::sleep(std::time::Duration::from_millis(300)).await; let access = edge.access_log(); - assert!(access.lines().count() >= 7, "access log has the requests:\n{access}"); - assert!(access.contains("\"127.0.0.0\""), "IPv4 truncated to /24:\n{access}"); - assert!(!access.contains("127.0.0.1"), "full client IP must not be logged:\n{access}"); - assert!(!access.contains("token=abc"), "query strings are not logged:\n{access}"); + assert!( + access.lines().count() >= 7, + "access log has the requests:\n{access}" + ); + assert!( + access.contains("\"127.0.0.0\""), + "IPv4 truncated to /24:\n{access}" + ); + assert!( + !access.contains("127.0.0.1"), + "full client IP must not be logged:\n{access}" + ); + assert!( + !access.contains("token=abc"), + "query strings are not logged:\n{access}" + ); let stderr = edge.stderr(); - assert!(stderr.len() > 100, "trace logging produced output:\n{stderr}"); + assert!( + stderr.len() > 100, + "trace logging produced output:\n{stderr}" + ); assert_clean("stderr (trace level)", stderr.as_bytes(), &secret); assert_clean("access log", access.as_bytes(), &secret); assert_clean("compiled edge config", edge.config_text.as_bytes(), &secret); @@ -143,15 +228,24 @@ async fn malformed_secret_is_rejected_without_echoing_it() { site: "secrets = [\"api_key\"]\n", hosts: vec![host_file( "app.test", - &format!("upstreams = [\"{}\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n", echo.url()), + &format!( + "upstreams = [\"{}\"]\n[[request_headers]]\naction = \"set\"\nname = \"X-A\"\nsecret = \"api_key\"\n", + echo.url() + ), )], // A newline inside the value would split the header: refused. - secrets: vec![("api_key".into(), format!("{secret}\ninjected: yes\n").into_bytes())], + secrets: vec![( + "api_key".into(), + format!("{secret}\ninjected: yes\n").into_bytes(), + )], log_level: "trace", ..Default::default() }); let status = wait_exit(&mut edge); - assert!(!status.success(), "edge must refuse a secret that is not a valid header value"); + assert!( + !status.success(), + "edge must refuse a secret that is not a valid header value" + ); assert_clean("stderr", edge.stderr().as_bytes(), &secret); } diff --git a/tests/support/src/authelia.rs b/tests/support/src/authelia.rs index 82da540..67fced0 100644 --- a/tests/support/src/authelia.rs +++ b/tests/support/src/authelia.rs @@ -41,18 +41,25 @@ pub struct MockAuthelia { impl MockAuthelia { pub async fn start() -> MockAuthelia { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let m = MockAuthelia { addr: listener.local_addr().unwrap(), requests: Arc::default() }; + let m = MockAuthelia { + addr: listener.local_addr().unwrap(), + requests: Arc::default(), + }; let mm = m.clone(); tokio::spawn(async move { loop { - let Ok((stream, _)) = listener.accept().await else { continue }; + let Ok((stream, _)) = listener.accept().await else { + continue; + }; let mm = mm.clone(); tokio::spawn(async move { let svc = service_fn(move |req| { let mm = mm.clone(); async move { Ok::<_, Infallible>(mm.handle(req).await) } }); - let _ = http1::Builder::new().serve_connection(TokioIo::new(stream), svc).await; + let _ = http1::Builder::new() + .serve_connection(TokioIo::new(stream), svc) + .await; }); } }); @@ -70,14 +77,28 @@ impl MockAuthelia { async fn handle(&self, req: Request) -> Response> { let (parts, body) = req.into_parts(); - let body = body.collect().await.map(|b| b.to_bytes()).unwrap_or_default(); + let body = body + .collect() + .await + .map(|b| b.to_bytes()) + .unwrap_or_default(); self.requests.lock().unwrap().push(Recorded { method: parts.method.to_string(), path: parts.uri.path().to_owned(), - headers: parts.headers.iter().map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec())).collect(), + headers: parts + .headers + .iter() + .map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec())) + .collect(), body: body.to_vec(), }); - let h = |name: &str| parts.headers.get(name).and_then(|v| v.to_str().ok()).map(str::to_owned); + let h = |name: &str| { + parts + .headers + .get(name) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned) + }; let text = |status: u16, body: &str| { Response::builder() .status(status) @@ -89,9 +110,12 @@ impl MockAuthelia { if parts.method != hyper::Method::GET || parts.uri.path() != PATH { return text(404, "404 page not found"); } - let (Some(method), Some(proto), Some(host), Some(uri)) = - (h("x-forwarded-method"), h("x-forwarded-proto"), h("x-forwarded-host"), h("x-forwarded-uri")) - else { + let (Some(method), Some(proto), Some(host), Some(uri)) = ( + h("x-forwarded-method"), + h("x-forwarded-proto"), + h("x-forwarded-host"), + h("x-forwarded-uri"), + ) else { return text(400, "missing X-Forwarded headers"); }; @@ -136,7 +160,9 @@ impl MockAuthelia { .header("location", location.clone()) .header("set-cookie", "authelia_flow=1; Path=/; HttpOnly") .header("content-type", "text/html; charset=utf-8") - .body(Full::new(Bytes::from(format!("302 Found")))) + .body(Full::new(Bytes::from(format!( + "302 Found" + )))) .unwrap() } _ => text(401, "401 Unauthorized"), diff --git a/tests/support/src/client.rs b/tests/support/src/client.rs index a006bd0..873d875 100644 --- a/tests/support/src/client.rs +++ b/tests/support/src/client.rs @@ -37,7 +37,12 @@ impl Req { } pub fn new(method: &str, host: &str, path: &str) -> Req { - Req { method: method.into(), path: path.into(), headers: vec![("host".into(), host.into())], body: Vec::new() } + Req { + method: method.into(), + path: path.into(), + headers: vec![("host".into(), host.into())], + body: Vec::new(), + } } pub fn header(mut self, name: &str, value: &str) -> Req { @@ -61,11 +66,18 @@ pub struct Resp { impl Resp { pub fn header(&self, name: &str) -> Option<&str> { - self.headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()) + self.headers + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) } pub fn header_all(&self, name: &str) -> Vec<&str> { - self.headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str()).collect() + self.headers + .iter() + .filter(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_str()) + .collect() } pub fn text(&self) -> String { @@ -81,7 +93,9 @@ fn other(e: impl std::fmt::Display) -> io::Error { pub fn tls_connector(roots: Arc) -> TlsConnector { crate::tls::install_crypto(); - let mut cfg = rustls::ClientConfig::builder().with_root_certificates(roots).with_no_client_auth(); + let mut cfg = rustls::ClientConfig::builder() + .with_root_certificates(roots) + .with_no_client_auth(); cfg.alpn_protocols = vec![b"http/1.1".to_vec()]; TlsConnector::from(Arc::new(cfg)) } @@ -96,29 +110,58 @@ async fn tls_stream( tls_connector(roots).connect(name, tcp).await } -async fn send(io: S, req: &Req) -> io::Result { - let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(io)).await.map_err(other)?; +async fn send( + io: S, + req: &Req, +) -> io::Result { + let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(io)) + .await + .map_err(other)?; tokio::spawn(async move { let _ = conn.await; }); - let mut b = hyper::Request::builder().method(req.method.as_str()).uri(req.path.as_str()); + let mut b = hyper::Request::builder() + .method(req.method.as_str()) + .uri(req.path.as_str()); for (n, v) in &req.headers { b = b.header(n.as_str(), v.as_str()); } - let request = b.body(Full::new(Bytes::from(req.body.clone()))).map_err(other)?; + let request = b + .body(Full::new(Bytes::from(req.body.clone()))) + .map_err(other)?; let resp = sender.send_request(request).await.map_err(other)?; let status = resp.status().as_u16(); let headers = resp .headers() .iter() - .map(|(n, v)| (n.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned())) + .map(|(n, v)| { + ( + n.as_str().to_owned(), + String::from_utf8_lossy(v.as_bytes()).into_owned(), + ) + }) .collect(); - let body = resp.into_body().collect().await.map_err(other)?.to_bytes().to_vec(); - Ok(Resp { status, headers, body }) + let body = resp + .into_body() + .collect() + .await + .map_err(other)? + .to_bytes() + .to_vec(); + Ok(Resp { + status, + headers, + body, + }) } /// One request over a fresh TLS connection to `addr` with the given SNI. -pub async fn https(addr: SocketAddr, sni: &str, roots: Arc, req: &Req) -> io::Result { +pub async fn https( + addr: SocketAddr, + sni: &str, + roots: Arc, + req: &Req, +) -> io::Result { tokio::time::timeout(TIMEOUT, async { let s = tls_stream(addr, sni, roots).await?; send(s, req).await @@ -157,7 +200,9 @@ pub async fn websocket( ) -> io::Result { tokio::time::timeout(TIMEOUT, async { let s = tls_stream(addr, sni, roots).await?; - let mut request = format!("wss://{host}{path}").into_client_request().map_err(other)?; + let mut request = format!("wss://{host}{path}") + .into_client_request() + .map_err(other)?; for (n, v) in extra { request.headers_mut().insert( http::HeaderName::from_bytes(n.as_bytes()).map_err(other)?, @@ -167,7 +212,9 @@ pub async fn websocket( match tokio_tungstenite::client_async(request, s).await { Ok((mut ws, resp)) => { let status = resp.status().as_u16(); - ws.send(tungstenite::Message::text(message)).await.map_err(other)?; + ws.send(tungstenite::Message::text(message)) + .await + .map_err(other)?; let echo = match ws.next().await { Some(Ok(m)) => m.into_text().map_err(other)?.to_string(), other_msg => return Err(other(format!("no echo: {other_msg:?}"))), @@ -180,10 +227,19 @@ pub async fn websocket( let headers = resp .headers() .iter() - .map(|(n, v)| (n.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned())) + .map(|(n, v)| { + ( + n.as_str().to_owned(), + String::from_utf8_lossy(v.as_bytes()).into_owned(), + ) + }) .collect(); let body = resp.body().clone().unwrap_or_default(); - Ok(WsOutcome::Refused(Resp { status, headers, body })) + Ok(WsOutcome::Refused(Resp { + status, + headers, + body, + })) } Err(e) => Err(other(e)), } diff --git a/tests/support/src/proc.rs b/tests/support/src/proc.rs index dd04640..8e8eb6a 100644 --- a/tests/support/src/proc.rs +++ b/tests/support/src/proc.rs @@ -12,7 +12,11 @@ use std::time::{Duration, Instant}; /// A port on 127.0.0.1 that was free a moment ago. pub fn free_port() -> u16 { - std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() + std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port() } pub fn local(port: u16) -> SocketAddr { @@ -70,12 +74,17 @@ impl Drop for TempDir { /// Locate an external tool: `$IANITOR__BIN`, then `$PATH`. pub fn find_binary(name: &str) -> Option { - let var = format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_")); + let var = format!( + "IANITOR_{}_BIN", + name.to_ascii_uppercase().replace('-', "_") + ); if let Some(p) = std::env::var_os(&var) { return Some(PathBuf::from(p)); } let path = std::env::var_os("PATH")?; - std::env::split_paths(&path).map(|d| d.join(name)).find(|p| p.is_file()) + std::env::split_paths(&path) + .map(|d| d.join(name)) + .find(|p| p.is_file()) } /// Like [`find_binary`], but a missing tool fails the test, unless `IANITOR_ALLOW_SKIP=1`, @@ -87,11 +96,13 @@ pub fn require_binary(name: &str) -> Option { eprintln!("SKIPPED: `{name}` not found (IANITOR_ALLOW_SKIP=1)"); None } - None => panic!( - "`{name}` is needed for this test but was not found on PATH (or ${}). \ - In WSL: nix profile add nixpkgs#{name}. Set IANITOR_ALLOW_SKIP=1 to skip instead.", - format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_")) - ), + None => { + let var = format!("IANITOR_{}_BIN", name.to_ascii_uppercase().replace('-', "_")); + panic!( + "`{name}` is needed for this test but was not found on PATH (or ${var}). \ + In WSL: nix profile add nixpkgs#{name}. Set IANITOR_ALLOW_SKIP=1 to skip instead." + ) + } } } diff --git a/tests/support/src/tls.rs b/tests/support/src/tls.rs index 5674595..f82b196 100644 --- a/tests/support/src/tls.rs +++ b/tests/support/src/tls.rs @@ -32,15 +32,24 @@ impl TestCa { dn.push(DnType::CommonName, common_name); params.distinguished_name = dn; params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0)); - params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign, KeyUsagePurpose::DigitalSignature]; + params.key_usages = vec![ + KeyUsagePurpose::KeyCertSign, + KeyUsagePurpose::CrlSign, + KeyUsagePurpose::DigitalSignature, + ]; let cert = params.self_signed(&key).unwrap(); - TestCa { cert_pem: cert.pem(), issuer: Issuer::new(params, key) } + TestCa { + cert_pem: cert.pem(), + issuer: Issuer::new(params, key), + } } /// A server certificate for the given DNS names (or IP literals). pub fn issue(&self, names: &[&str]) -> Leaf { let key = KeyPair::generate().unwrap(); - let mut params = CertificateParams::new(names.iter().map(|s| (*s).to_owned()).collect::>()).unwrap(); + let mut params = + CertificateParams::new(names.iter().map(|s| (*s).to_owned()).collect::>()) + .unwrap(); let mut dn = DistinguishedName::new(); dn.push(DnType::CommonName, names.first().copied().unwrap_or("test")); params.distinguished_name = dn; @@ -48,7 +57,10 @@ impl TestCa { params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; params.key_usages = vec![KeyUsagePurpose::DigitalSignature]; let cert = params.signed_by(&key, &self.issuer).unwrap(); - Leaf { cert_pem: cert.pem(), key_pem: key.serialize_pem() } + Leaf { + cert_pem: cert.pem(), + key_pem: key.serialize_pem(), + } } pub fn roots(&self) -> Arc { diff --git a/tests/support/src/upstream.rs b/tests/support/src/upstream.rs index e9c0427..75b4897 100644 --- a/tests/support/src/upstream.rs +++ b/tests/support/src/upstream.rs @@ -49,7 +49,10 @@ pub struct Recorded { impl Recorded { pub fn header(&self, name: &str) -> Option<&[u8]> { - self.headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_slice()) + self.headers + .iter() + .find(|(n, _)| n.eq_ignore_ascii_case(name)) + .map(|(_, v)| v.as_slice()) } } @@ -80,14 +83,18 @@ impl Echo { let e = echo.clone(); tokio::spawn(async move { loop { - let Ok((stream, _)) = listener.accept().await else { continue }; + let Ok((stream, _)) = listener.accept().await else { + continue; + }; let e = e.clone(); tokio::spawn(async move { let svc = service_fn(move |req| { let e = e.clone(); async move { Ok::<_, Infallible>(e.handle(req).await) } }); - let _ = http1::Builder::new().serve_connection(TokioIo::new(stream), svc).await; + let _ = http1::Builder::new() + .serve_connection(TokioIo::new(stream), svc) + .await; }); } }); @@ -104,7 +111,10 @@ impl Echo { /// Requests other than health checks. pub fn proxied(&self) -> Vec { - self.requests().into_iter().filter(|r| r.path != "/healthz").collect() + self.requests() + .into_iter() + .filter(|r| r.path != "/healthz") + .collect() } pub fn clear(&self) { @@ -113,13 +123,21 @@ impl Echo { async fn handle(&self, req: Request) -> Response { let (parts, body) = req.into_parts(); - let body = body.collect().await.map(|b| b.to_bytes()).unwrap_or_default(); + let body = body + .collect() + .await + .map(|b| b.to_bytes()) + .unwrap_or_default(); let path = parts.uri.path().to_owned(); let query = parts.uri.query().unwrap_or("").to_owned(); self.requests.lock().unwrap().push(Recorded { method: parts.method.to_string(), path: path.clone(), - headers: parts.headers.iter().map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec())).collect(), + headers: parts + .headers + .iter() + .map(|(n, v)| (n.as_str().to_owned(), v.as_bytes().to_vec())) + .collect(), body: body.to_vec(), }); let base = |status: u16| { @@ -133,19 +151,35 @@ impl Echo { let s = self.health.load(Ordering::SeqCst); return base(s).body(full(format!("health {s}"))).unwrap(); } - if let Some(code) = path.strip_prefix("/status/").and_then(|c| c.parse::().ok()) { - return base(code).header("content-type", "text/plain").body(full(format!("status {code}"))).unwrap(); + if let Some(code) = path + .strip_prefix("/status/") + .and_then(|c| c.parse::().ok()) + { + return base(code) + .header("content-type", "text/plain") + .body(full(format!("status {code}"))) + .unwrap(); } if path == "/big" { - let n: usize = query.strip_prefix("n=").and_then(|n| n.parse().ok()).unwrap_or(1024).min(10 << 20); - return base(200).header("content-type", "application/octet-stream").body(full(vec![b'x'; n])).unwrap(); + let n: usize = query + .strip_prefix("n=") + .and_then(|n| n.parse().ok()) + .unwrap_or(1024) + .min(10 << 20); + return base(200) + .header("content-type", "application/octet-stream") + .body(full(vec![b'x'; n])) + .unwrap(); } if path == "/chunked" { let chunks = ["first,", "second,", "third"] .into_iter() .map(|c| Ok::<_, Infallible>(Frame::data(Bytes::from_static(c.as_bytes())))); let stream = futures_util::stream::iter(chunks); - return base(200).header("content-type", "text/plain").body(BodyExt::boxed(StreamBody::new(stream))).unwrap(); + return base(200) + .header("content-type", "text/plain") + .body(BodyExt::boxed(StreamBody::new(stream))) + .unwrap(); } if path == "/set-cookie" { return base(200) @@ -167,7 +201,10 @@ impl Echo { let mut headers = serde_json::Map::new(); for h in ECHO_HEADERS { if let Some(v) = parts.headers.get(h) { - headers.insert(h.to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned().into()); + headers.insert( + h.to_owned(), + String::from_utf8_lossy(v.as_bytes()).into_owned().into(), + ); } } for h in HASHED_HEADERS { @@ -184,7 +221,10 @@ impl Echo { "body_fnv": fnv64(&body), "headers": headers, }); - base(200).header("content-type", "application/json").body(full(json.to_string())).unwrap() + base(200) + .header("content-type", "application/json") + .body(full(json.to_string())) + .unwrap() } } @@ -198,14 +238,21 @@ pub struct WsEcho { impl WsEcho { pub async fn start() -> WsEcho { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let ws = WsEcho { addr: listener.local_addr().unwrap(), connections: Arc::default() }; + let ws = WsEcho { + addr: listener.local_addr().unwrap(), + connections: Arc::default(), + }; let conns = ws.connections.clone(); tokio::spawn(async move { loop { - let Ok((stream, _)) = listener.accept().await else { continue }; + let Ok((stream, _)) = listener.accept().await else { + continue; + }; let conns = conns.clone(); tokio::spawn(async move { - let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await else { return }; + let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await else { + return; + }; conns.fetch_add(1, Ordering::SeqCst); while let Some(Ok(msg)) = ws.next().await { if msg.is_text() || msg.is_binary() {