From 7a2aee20ebaaf22f045779f93d7a2a34dcfa0946 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 20:43:50 +0100 Subject: [PATCH 01/45] [edge] Listeners, tests first: an overall header deadline (slowloris), pipelined requests answered in order on both listeners, a proxy socket whose X-Forwarded-For is believed (red: the deadline is a pass-through) --- crates/edge/src/deadline.rs | 257 +++++++++++++++++++++++++++++++++ crates/edge/src/http_app.rs | 2 +- crates/edge/src/lib.rs | 35 +++-- crates/edge/src/main.rs | 15 +- crates/edge/src/proxy.rs | 6 + crates/edge/tests/listeners.rs | 237 ++++++++++++++++++++++++++++++ tests/support/src/client.rs | 184 +++++++++++++++++++++++ 7 files changed, 722 insertions(+), 14 deletions(-) create mode 100644 crates/edge/src/deadline.rs create mode 100644 crates/edge/tests/listeners.rs diff --git a/crates/edge/src/deadline.rs b/crates/edge/src/deadline.rs new file mode 100644 index 0000000..27b6671 --- /dev/null +++ b/crates/edge/src/deadline.rs @@ -0,0 +1,257 @@ +// 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/. + +//! An overall deadline for reading a request header (slowloris). +//! +//! Pingora times out each *read* of a request header (60 s), not the header as a whole, so a +//! client that sends one byte every 59 s holds a connection open for as long as it likes. +//! Caddy (Go's `ReadHeaderTimeout`, 1 minute by default in Caddy 2) closes such a connection +//! after a minute. [`HeaderDeadline`] wraps an HTTP app and does the same: a request whose +//! header is not complete within the deadline has its connection closed, without an answer +//! (Go does not answer either). +//! +//! The app under it says "the header is in" by calling [`header_read`] (edge's proxy does it in +//! its first filter, the plain-HTTP listener right after parsing), which reaches this +//! request's deadline through a task-local. A request whose header is in is never cut by it, +//! however long its body or its upstream takes. +//! +//! On a reused keep-alive connection the deadline starts when the previous answer was sent, so +//! it also covers the idle wait (Pingora's keep-alive timeout, 60 s): such a request gets the +//! keep-alive timeout plus the header deadline. The first request on a connection is told +//! apart by the reuse budget the wrapper sets (`keepalive_request_limit`, effectively +//! unlimited): only the first request sees it whole. + +use std::future::pending; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use async_trait::async_trait; +use pingora::apps::{HttpServerApp, HttpServerOptions, ReusedHttpStream}; +use pingora::protocols::http::ServerSession; +use pingora::server::ShutdownWatch; + +/// Caddy's default `read_header` timeout. +pub const HEADER_TIMEOUT: Duration = Duration::from_secs(60); + +/// Pingora's keep-alive timeout between requests on one connection (`process_new` sets 60 s). +pub const KEEPALIVE_IDLE: Duration = Duration::from_secs(60); + +/// The reuse budget that marks a connection's first request (Pingora counts it down by one on +/// every reuse; four billion requests on one connection is not a limit anyone meets). +const FIRST_REQUEST_BUDGET: u32 = u32::MAX; + +tokio::task_local! { + static HEADER_IN: Arc; +} + +/// The request header has been read: the deadline no longer applies to this request. +/// Outside a [`HeaderDeadline`] it does nothing. +pub fn header_read() { + let _ = HEADER_IN.try_with(|f| f.store(true, Ordering::Release)); +} + +/// Wraps an HTTP app (edge's proxy, the plain-HTTP listener) with the header deadline. +pub struct HeaderDeadline { + inner: Arc, + timeout: Duration, + options: HttpServerOptions, +} + +impl HeaderDeadline { + pub fn new(inner: A, timeout: Duration) -> Self { + let mut options = HttpServerOptions::default(); + options.keepalive_request_limit = Some(FIRST_REQUEST_BUDGET); + HeaderDeadline { + inner: Arc::new(inner), + timeout, + options, + } + } + + pub fn inner(&self) -> &Arc { + &self.inner + } + + /// The deadline for this session: the header timeout, plus the keep-alive idle time on a + /// reused connection. HTTP/2 streams arrive with their header already read. + fn deadline_for(&self, session: &ServerSession) -> Duration { + let first = session.is_http2() + || session.get_keepalive_reuses_remaining() == Some(FIRST_REQUEST_BUDGET); + if first { + self.timeout + } else { + self.timeout + KEEPALIVE_IDLE + } + } +} + +#[async_trait] +impl HttpServerApp for HeaderDeadline +where + A: HttpServerApp + Send + Sync + 'static, +{ + async fn process_new_http( + self: &Arc, + session: ServerSession, + shutdown: &ShutdownWatch, + ) -> Option { + // Not built yet: no deadline (the red commit of the slowloris fix). + let _ = self.deadline_for(&session); + self.inner.process_new_http(session, shutdown).await + } + + fn h2_options(&self) -> Option { + self.inner.h2_options() + } + + fn server_options(&self) -> Option<&HttpServerOptions> { + Some(&self.options) + } + + async fn http_cleanup(&self) { + self.inner.http_cleanup().await; + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + use pingora::apps::ServerApp; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + /// Reads the header, says so, then answers 204 after `work` (a slow upstream). + struct App { + work: Duration, + } + + #[async_trait] + impl HttpServerApp for App { + async fn process_new_http( + self: &Arc, + mut http: ServerSession, + _shutdown: &ShutdownWatch, + ) -> Option { + if !matches!(http.read_request().await, Ok(true)) { + return None; + } + header_read(); + tokio::time::sleep(self.work).await; + let mut resp = pingora::http::ResponseHeader::build(204, None).unwrap(); + resp.insert_header("content-length", "0").unwrap(); + http.write_response_header(Box::new(resp)).await.ok()?; + let settings = pingora::apps::HttpPersistentSettings::for_session(&http); + http.finish() + .await + .ok() + .flatten() + .map(|s| ReusedHttpStream::from_reusable_stream(s, settings)) + } + } + + fn shutdown() -> ShutdownWatch { + let (tx, rx) = tokio::sync::watch::channel(false); + std::mem::forget(tx); + rx + } + + /// Serve one connection (the in-memory pipe) with the deadline; returns the client end. + fn serve(work: Duration, timeout: Duration) -> tokio::io::DuplexStream { + let (client, server) = tokio::io::duplex(64 * 1024); + let app = Arc::new(HeaderDeadline::new(App { work }, timeout)); + tokio::spawn(async move { + let sd = shutdown(); + let _ = app.process_new(Box::new(server), &sd).await; + }); + client + } + + /// Read until the server closes the pipe or `limit` passes; what was read, and whether the + /// pipe closed. + async fn read_all(c: &mut tokio::io::DuplexStream, limit: Duration) -> (String, bool) { + let mut out = Vec::new(); + let mut buf = [0u8; 1024]; + let end = tokio::time::Instant::now() + limit; + loop { + match tokio::time::timeout_at(end, c.read(&mut buf)).await { + Ok(Ok(0)) | Ok(Err(_)) => return (String::from_utf8_lossy(&out).into(), true), + Ok(Ok(n)) => out.extend_from_slice(&buf[..n]), + Err(_) => return (String::from_utf8_lossy(&out).into(), false), + } + } + } + + #[tokio::test(start_paused = true)] + async fn a_header_trickled_past_the_deadline_is_cut() { + let mut c = serve(Duration::ZERO, HEADER_TIMEOUT); + let start = tokio::time::Instant::now(); + // One byte every 30 s: each read is well inside Pingora's own 60 s read timeout. + let header = b"GET / HTTP/1.1\r\nHost: a.test\r\nX-Slow: 1\r\n"; + let mut closed_at = None; + for b in header { + if c.write_all(&[*b]).await.is_err() { + closed_at = Some(start.elapsed()); + break; + } + let (got, closed) = read_all(&mut c, Duration::from_secs(30)).await; + assert!(got.is_empty(), "no answer to a half header: {got}"); + if closed { + closed_at = Some(start.elapsed()); + break; + } + } + let at = closed_at.expect("the connection was closed"); + assert!( + at >= HEADER_TIMEOUT && at <= HEADER_TIMEOUT + Duration::from_secs(30), + "closed after {at:?}" + ); + } + + #[tokio::test(start_paused = true)] + async fn a_slow_answer_after_a_complete_header_is_not_cut() { + let mut c = serve(Duration::from_secs(300), HEADER_TIMEOUT); + c.write_all(b"GET / HTTP/1.1\r\nHost: a.test\r\n\r\n") + .await + .unwrap(); + let (got, _) = read_all(&mut c, Duration::from_secs(400)).await; + assert!(got.starts_with("HTTP/1.1 204"), "{got}"); + } + + #[tokio::test(start_paused = true)] + async fn a_reused_connection_gets_the_idle_time_on_top() { + let mut c = serve(Duration::ZERO, HEADER_TIMEOUT); + c.write_all(b"GET / HTTP/1.1\r\nHost: a.test\r\n\r\n") + .await + .unwrap(); + let (got, closed) = read_all(&mut c, Duration::from_secs(1)).await; + assert!(got.starts_with("HTTP/1.1 204") && !closed, "{got}"); + // Idle for 50 s, then a header that takes another 50 s: 100 s in all, inside the + // keep-alive idle time plus the deadline. + tokio::time::sleep(Duration::from_secs(50)).await; + c.write_all(b"GET /2 HTTP/1.1\r\n").await.unwrap(); + tokio::time::sleep(Duration::from_secs(50)).await; + c.write_all(b"Host: a.test\r\n\r\n").await.unwrap(); + let (got, _) = read_all(&mut c, Duration::from_secs(1)).await; + assert!(got.starts_with("HTTP/1.1 204"), "second answer: {got}"); + // A third request that never completes is cut at idle + deadline. + let start = tokio::time::Instant::now(); + c.write_all(b"GET /3 HTTP/1.1\r\n").await.unwrap(); + let mut closed = false; + while start.elapsed() < Duration::from_secs(200) { + let _ = c.write_all(b"X").await; + let (_, cl) = read_all(&mut c, Duration::from_secs(20)).await; + if cl { + closed = true; + break; + } + } + assert!(closed, "the third request was cut"); + assert!( + start.elapsed() <= HEADER_TIMEOUT + KEEPALIVE_IDLE + Duration::from_secs(20), + "{:?}", + start.elapsed() + ); + } +} diff --git a/crates/edge/src/http_app.rs b/crates/edge/src/http_app.rs index 5b83bbf..799801e 100644 --- a/crates/edge/src/http_app.rs +++ b/crates/edge/src/http_app.rs @@ -45,7 +45,7 @@ impl HttpServerApp for HttpApp { shutdown: &ShutdownWatch, ) -> Option { match http.read_request().await { - Ok(true) => {} + Ok(true) => crate::deadline::header_read(), Ok(false) => return None, Err(e) => { if matches!(e.etype(), ErrorType::InvalidHTTPHeader) { diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index a7292bb..13ad7ed 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -13,6 +13,7 @@ pub mod acme; #[cfg(unix)] pub mod admin; +pub mod deadline; pub mod error; pub mod fetch; pub mod forward_auth; @@ -32,7 +33,7 @@ use std::sync::Arc; use pingora::connectors::http::Connector; use pingora::listeners::tls::TlsSettings; -use pingora::proxy::http_proxy_service; +use pingora::proxy::http_proxy; use pingora::server::Server; use pingora::server::configuration::ServerConf; use pingora::services::background::background_service; @@ -56,6 +57,8 @@ pub struct Options { pub acme_root: Option, /// Overrides `$CREDENTIALS_DIRECTORY` (tests running several edges in one process). pub credentials_dir: Option, + /// The overall deadline for a request header; default [`deadline::HEADER_TIMEOUT`]. + pub header_timeout: Option, } impl Options { @@ -114,12 +117,19 @@ pub fn server(shared: Arc, opts: &Options) -> Result let challenges = Arc::new(acme::Challenges::default()); let rt = shared.current(); - let mut https = http_proxy_service( - &server.configuration, - proxy::EdgeProxy { - shared: shared.clone(), - connector: Connector::new(None), - }, + let header_timeout = opts.header_timeout.unwrap_or(deadline::HEADER_TIMEOUT); + let mut https = Service::new( + "ianitor https".to_owned(), + deadline::HeaderDeadline::new( + http_proxy( + &server.configuration, + proxy::EdgeProxy { + shared: shared.clone(), + connector: Connector::new(None), + }, + ), + header_timeout, + ), ); let mut tls = TlsSettings::with_callbacks(Box::new(tls::SniRecorder)).map_err(|e| EdgeError::Listen { @@ -136,10 +146,13 @@ pub fn server(shared: Arc, opts: &Options) -> Result let mut http = Service::new( "ianitor http".to_owned(), - http_app::HttpApp { - shared: shared.clone(), - challenges: challenges.clone(), - }, + deadline::HeaderDeadline::new( + http_app::HttpApp { + shared: shared.clone(), + challenges: challenges.clone(), + }, + header_timeout, + ), ); http.add_tcp(&rt.cfg.http_listen); diff --git a/crates/edge/src/main.rs b/crates/edge/src/main.rs index e65a403..2dc6025 100644 --- a/crates/edge/src/main.rs +++ b/crates/edge/src/main.rs @@ -3,7 +3,7 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! `ianitor-edge --config [--check] [--admin-socket ] [--trial-config ] -//! [--share-revocations ] [--acme-root ]` +//! [--share-revocations ] [--acme-root ] [--header-timeout ]` //! //! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG` //! (error, warn, info, debug, trace; libraries are capped at info). @@ -25,11 +25,22 @@ fn parse_args() -> Result<(Options, bool), EdgeError> { 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("--header-timeout") => { + let secs = args + .next() + .and_then(|s| s.to_str().and_then(|s| s.parse::().ok())) + .filter(|s| (1..=3600).contains(s)) + .ok_or_else(|| { + EdgeError::Usage("--header-timeout takes 1 to 3600 seconds".into()) + })?; + opts.header_timeout = Some(std::time::Duration::from_secs(secs)); + } Some("--check") => check = true, Some("--help" | "-h") => { println!( "usage: ianitor-edge --config [--check] [--admin-socket ] \ - [--trial-config ] [--share-revocations ] [--acme-root ]" + [--trial-config ] [--share-revocations ] [--acme-root ] \ + [--header-timeout ]" ); std::process::exit(0); } diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index f79e8cd..fd9b685 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -162,6 +162,12 @@ impl ProxyHttp for EdgeProxy { } } + async fn early_request_filter(&self, session: &mut Session, _ctx: &mut Ctx) -> Result<()> { + // The header is in: the header deadline (slowloris) no longer applies. + crate::deadline::header_read(); + Ok(()) + } + async fn request_filter(&self, session: &mut Session, ctx: &mut Ctx) -> Result { let rt = self.shared.current(); ctx.rt = Some(rt.clone()); diff --git a/crates/edge/tests/listeners.rs b/crates/edge/tests/listeners.rs new file mode 100644 index 0000000..4b44fbe --- /dev/null +++ b/crates/edge/tests/listeners.rs @@ -0,0 +1,237 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Listener hardening (phase 4, tests first): an overall deadline for a request header +//! (slowloris), pipelined requests answered in order on both listeners, and the proxy socket a +//! front proxy (Caddy beside Ianitor) reaches edge through, whose X-Forwarded-For is believed +//! because only that proxy can connect to it. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +#[cfg(unix)] +mod common; + +#[cfg(not(unix))] +#[test] +#[ignore = "needs Linux (the Pingora runner): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} + +#[cfg(unix)] +mod unix { + use std::time::{Duration, Instant}; + + use crate::common::{Edge, EdgeSpec, host_file, start}; + use ianitor_testkit::client::{self, Req}; + use ianitor_testkit::upstream::Echo; + use rustls_pki_types::ServerName; + use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; + + /// Trickle a header that never ends, one byte every 300 ms; how long until edge closes the + /// connection, and whatever it sent. + async fn trickle(mut s: S) -> (Duration, Vec) { + let start = Instant::now(); + let header = b"GET / HTTP/1.1\r\nHost: app.test\r\nX-Slow: "; + let mut got = Vec::new(); + let mut i = 0usize; + while start.elapsed() < Duration::from_secs(20) { + let b = header.get(i).copied().unwrap_or(b'a'); + i += 1; + if s.write_all(&[b]).await.is_err() || s.flush().await.is_err() { + return (start.elapsed(), got); + } + let mut buf = [0u8; 512]; + match tokio::time::timeout(Duration::from_millis(300), s.read(&mut buf)).await { + Ok(Ok(0)) | Ok(Err(_)) => return (start.elapsed(), got), + Ok(Ok(n)) => got.extend_from_slice(&buf[..n]), + Err(_) => {} + } + } + panic!("edge kept a trickling header open for 20 s"); + } + + fn app_edge(echo: &Echo, extra: Vec) -> Edge { + start(EdgeSpec { + hosts: vec![host_file( + "app.test", + &format!("upstreams = [\"{}\"]\n", echo.url()), + )], + extra_args: extra, + ..Default::default() + }) + } + + #[tokio::test(flavor = "multi_thread")] + async fn a_trickled_header_is_cut_at_the_deadline_on_both_listeners() { + let echo = Echo::start("app").await; + let edge = app_edge(&echo, vec!["--header-timeout".into(), "2".into()]); + + let tcp = tokio::net::TcpStream::connect(edge.http).await.unwrap(); + let (took, got) = trickle(tcp).await; + assert!( + took >= Duration::from_millis(1800) && took < Duration::from_secs(6), + "plain HTTP closed after {took:?}" + ); + assert!(got.is_empty(), "no answer to half a header: {got:?}"); + + let tcp = tokio::net::TcpStream::connect(edge.https).await.unwrap(); + let name = ServerName::try_from("app.test").unwrap(); + let tls = client::tls_connector(edge.roots()) + .connect(name, tcp) + .await + .unwrap(); + let (took, got) = trickle(tls).await; + assert!( + took >= Duration::from_millis(1800) && took < Duration::from_secs(6), + "HTTPS closed after {took:?}" + ); + assert!(got.is_empty(), "no answer to half a header: {got:?}"); + assert!(echo.proxied().is_empty()); + + // A complete header still gets through. + let r = client::https( + edge.https, + "app.test", + edge.roots(), + &Req::get("app.test", "/"), + ) + .await + .unwrap(); + assert_eq!(r.status, 200, "{}", edge.stderr()); + } + + #[tokio::test(flavor = "multi_thread")] + async fn pipelined_requests_are_answered_in_order_on_both_listeners() { + let echo = Echo::start("app").await; + let edge = app_edge(&echo, vec![]); + + // Plain HTTP: a redirect, a 404 for an unknown host, a redirect. + let got = client::http_pipelined( + edge.http, + &[ + Req::get("app.test", "/one"), + Req::get("nobody.test", "/"), + Req::get("app.test", "/three"), + ], + ) + .await + .unwrap(); + let statuses: Vec = got.iter().map(|r| r.status).collect(); + assert_eq!(statuses, vec![308, 404, 308], "{}", edge.stderr()); + assert!(got[2].header("location").unwrap().ends_with("/three")); + + // HTTPS: three requests, one with a body, each proxied in order. + let got = client::https_pipelined( + edge.https, + "app.test", + edge.roots(), + &[ + Req::get("app.test", "/a"), + Req::new("POST", "app.test", "/b").body(b"hello"), + Req::get("app.test", "/c"), + ], + ) + .await + .unwrap(); + let statuses: Vec = got.iter().map(|r| r.status).collect(); + assert_eq!(statuses, vec![200, 200, 200], "{}", edge.stderr()); + let paths: Vec = echo.proxied().iter().map(|r| r.path.clone()).collect(); + assert_eq!(paths, vec!["/a", "/b", "/c"]); + } + + #[tokio::test(flavor = "multi_thread")] + async fn the_proxy_socket_believes_its_forwarded_for_and_tcp_does_not() { + use std::os::unix::fs::PermissionsExt; + let echo = Echo::start("app").await; + let dir = ianitor_testkit::proc::TempDir::new("proxy-sock"); + let sock = dir.join("proxy.sock"); + let edge = app_edge( + &echo, + vec!["--proxy-socket".into(), sock.to_string_lossy().into()], + ); + for _ in 0..100 { + if sock.exists() { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + let mode = std::fs::metadata(&sock).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o660, "only the socket's owner and group may connect"); + + // Through the socket (Caddy appends the visitor it saw to X-Forwarded-For). + let r = client::unix( + &sock, + &Req::get("app.test", "/via-socket") + .header("x-forwarded-for", "198.51.100.9, 203.0.113.7"), + ) + .await + .unwrap(); + assert_eq!(r.status, 200, "{}", edge.stderr()); + // Over loopback TCP with the same claim: not believed. + let r = client::https( + edge.https, + "app.test", + edge.roots(), + &Req::get("app.test", "/via-tcp").header("x-forwarded-for", "203.0.113.7"), + ) + .await + .unwrap(); + assert_eq!(r.status, 200); + + let seen = echo.proxied(); + let header = |path: &str, name: &str| { + let r = seen.iter().find(|r| r.path == path).unwrap(); + String::from_utf8(r.header(name).unwrap().to_vec()).unwrap() + }; + assert_eq!( + header("/via-socket", "x-forwarded-for"), + "203.0.113.7", + "the rightmost entry: the visitor the front proxy saw" + ); + assert_eq!(header("/via-tcp", "x-forwarded-for"), "127.0.0.1"); + assert_eq!( + header("/via-socket", "x-forwarded-proto"), + "https", + "the front proxy terminated TLS" + ); + } + + /// A device-certificate host asks for the certificate in the TLS handshake; the socket has + /// none, so the host is refused there (403), never served without one. + #[tokio::test(flavor = "multi_thread")] + async fn a_device_host_is_refused_through_the_proxy_socket() { + let echo = Echo::start("dev").await; + let dir = ianitor_testkit::proc::TempDir::new("proxy-sock-dev"); + let sock = dir.join("proxy.sock"); + let devices_ca = ianitor_testkit::tls::TestCa::new("Devices Test CA"); + let edge = start(EdgeSpec { + hosts: vec![host_file( + "device.test", + &format!("upstreams = [\"{}\"]\ndevice_certs = true\n", echo.url()), + )], + files: vec![ + ( + "certs/domi-devices-ca.pem".into(), + devices_ca.cert_pem.clone().into_bytes(), + ), + ( + "certs/domi-devices.pem".into(), + devices_ca.issue(&["a-device"]).cert_pem.into_bytes(), + ), + ], + extra_args: vec!["--proxy-socket".into(), sock.to_string_lossy().into()], + ..Default::default() + }); + for _ in 0..100 { + if sock.exists() { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + let r = client::unix(&sock, &Req::get("device.test", "/")) + .await + .unwrap(); + assert_eq!(r.status, 403, "{}", edge.stderr()); + assert!(echo.proxied().is_empty()); + } +} diff --git a/tests/support/src/client.rs b/tests/support/src/client.rs index acc2914..26f2121 100644 --- a/tests/support/src/client.rs +++ b/tests/support/src/client.rs @@ -311,3 +311,187 @@ pub async fn https_with_cert( .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? } + +// ------------------------------------------------------------------ pipelining + +/// The request as bytes: request line, the headers as given, `content-length` for a body. +pub fn encode(req: &Req) -> Vec { + let mut out = format!("{} {} HTTP/1.1\r\n", req.method, req.path).into_bytes(); + for (n, v) in &req.headers { + out.extend_from_slice(format!("{n}: {v}\r\n").as_bytes()); + } + if !req.body.is_empty() { + out.extend_from_slice(format!("content-length: {}\r\n", req.body.len()).as_bytes()); + } + out.extend_from_slice(b"\r\n"); + out.extend_from_slice(&req.body); + out +} + +fn find(hay: &[u8], needle: &[u8]) -> Option { + hay.windows(needle.len()).position(|w| w == needle) +} + +/// Parse one response from the front of `buf` (`head`: the request was a HEAD). `Ok(None)`: +/// not complete yet; with `eof`, a body without a length ends at the end of the data. +fn parse_one(buf: &[u8], head: bool, eof: bool) -> io::Result> { + let Some(end) = find(buf, b"\r\n\r\n") else { + return Ok(None); + }; + let text = String::from_utf8_lossy(&buf[..end]).into_owned(); + let mut lines = text.split("\r\n"); + let status_line = lines.next().unwrap_or_default(); + let status: u16 = status_line + .split(' ') + .nth(1) + .and_then(|s| s.parse().ok()) + .ok_or_else(|| other(format!("bad status line: {status_line}")))?; + let headers: Vec<(String, String)> = lines + .filter_map(|l| l.split_once(':')) + .map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().to_owned())) + .collect(); + let get = |n: &str| headers.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone()); + let start = end + 4; + let no_body = head || status < 200 || status == 204 || status == 304; + let (body, used) = if no_body { + (Vec::new(), start) + } else if get("transfer-encoding").is_some_and(|t| t.eq_ignore_ascii_case("chunked")) { + let mut at = start; + let mut body = Vec::new(); + loop { + let Some(nl) = find(&buf[at..], b"\r\n") else { + return Ok(None); + }; + let size_text = String::from_utf8_lossy(&buf[at..at + nl]).into_owned(); + let size = usize::from_str_radix(size_text.split(';').next().unwrap_or("").trim(), 16) + .map_err(|_| other(format!("bad chunk size: {size_text}")))?; + at += nl + 2; + if size == 0 { + // No trailers expected: the empty line ends the message. + if buf.len() < at + 2 { + return Ok(None); + } + at += 2; + break; + } + if buf.len() < at + size + 2 { + return Ok(None); + } + body.extend_from_slice(&buf[at..at + size]); + at += size + 2; + } + (body, at) + } else if let Some(len) = get("content-length") { + let len: usize = len + .parse() + .map_err(|_| other(format!("bad content-length: {len}")))?; + if buf.len() < start + len { + return Ok(None); + } + (buf[start..start + len].to_vec(), start + len) + } else if eof { + (buf[start..].to_vec(), buf.len()) + } else { + return Ok(None); + }; + Ok(Some(( + Resp { + status, + headers, + body, + }, + used, + ))) +} + +/// Send every request back to back in one write on one connection (HTTP/1.1 pipelining), then +/// read the answers in order until the server closes or `idle` passes without data. Interim +/// (1xx) answers are skipped. +pub async fn pipelined_on( + mut io: S, + reqs: &[Req], + idle: Duration, +) -> io::Result> { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut all = Vec::new(); + for r in reqs { + all.extend(encode(r)); + } + io.write_all(&all).await?; + io.flush().await?; + let mut buf = Vec::new(); + let mut out = Vec::new(); + let mut chunk = [0u8; 16 * 1024]; + let mut eof = false; + while out.len() < reqs.len() { + let head = reqs[out.len()].method.eq_ignore_ascii_case("HEAD"); + if let Some((resp, used)) = parse_one(&buf, head, eof)? { + buf.drain(..used); + if resp.status >= 200 { + out.push(resp); + } + continue; + } + if eof { + break; + } + match tokio::time::timeout(idle, io.read(&mut chunk)).await { + Ok(Ok(0)) | Ok(Err(_)) => eof = true, + Ok(Ok(n)) => buf.extend_from_slice(&chunk[..n]), + Err(_) => break, + } + } + Ok(out) +} + +/// [`pipelined_on`] over a fresh plain TCP connection. +pub async fn http_pipelined(addr: SocketAddr, reqs: &[Req]) -> io::Result> { + let s = TcpStream::connect(addr).await?; + pipelined_on(s, reqs, Duration::from_secs(3)).await +} + +/// [`pipelined_on`] over a fresh TLS connection with the given SNI. +pub async fn https_pipelined( + addr: SocketAddr, + sni: &str, + roots: Arc, + reqs: &[Req], +) -> io::Result> { + let s = tls_stream(addr, sni, roots).await?; + pipelined_on(s, reqs, Duration::from_secs(3)).await +} + +#[cfg(test)] +mod pipeline_tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn responses_are_split_by_length_and_chunks() { + let raw = b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nhiHTTP/1.1 404 Not Found\r\n\ + transfer-encoding: chunked\r\n\r\n3\r\nabc\r\n0\r\n\r\nHTTP/1.1 308 x\r\n\ + location: /\r\ncontent-length: 0\r\n\r\n"; + let (a, used) = parse_one(raw, false, false).unwrap().unwrap(); + assert_eq!((a.status, a.text().as_str()), (200, "hi")); + let rest = &raw[used..]; + let (b, used2) = parse_one(rest, false, false).unwrap().unwrap(); + assert_eq!((b.status, b.text().as_str()), (404, "abc")); + let (c, _) = parse_one(&rest[used2..], false, false).unwrap().unwrap(); + assert_eq!(c.status, 308); + assert!(parse_one(b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nab", false, false) + .unwrap() + .is_none()); + } +} + +/// One request over a fresh connection to a Unix socket (edge's proxy socket, control's UI +/// socket). +#[cfg(unix)] +pub async fn unix(path: &std::path::Path, req: &Req) -> io::Result { + tokio::time::timeout(TIMEOUT, async { + let s = tokio::net::UnixStream::connect(path).await?; + send(s, req).await + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? +} From 39dd8f0f472a44edf20ead4376406cac98624089 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 20:46:28 +0100 Subject: [PATCH 02/45] [edge] Listeners: a request header must be complete within 60 s (--header-timeout), pipelined requests are answered in order, and --proxy-socket serves the front proxy on a 0660 Unix socket whose X-Forwarded-For is believed --- crates/edge/src/deadline.rs | 23 ++++++++++++++++++++--- crates/edge/src/http_app.rs | 3 +++ crates/edge/src/lib.rs | 27 +++++++++++++++++++++++++++ crates/edge/src/main.rs | 6 ++++-- crates/edge/src/proxy.rs | 35 ++++++++++++++++++++--------------- tests/support/src/client.rs | 10 ++++++++-- 6 files changed, 82 insertions(+), 22 deletions(-) diff --git a/crates/edge/src/deadline.rs b/crates/edge/src/deadline.rs index 27b6671..3a2b12b 100644 --- a/crates/edge/src/deadline.rs +++ b/crates/edge/src/deadline.rs @@ -97,9 +97,26 @@ where session: ServerSession, shutdown: &ShutdownWatch, ) -> Option { - // Not built yet: no deadline (the red commit of the slowloris fix). - let _ = self.deadline_for(&session); - self.inner.process_new_http(session, shutdown).await + let deadline = self.deadline_for(&session); + let flag = Arc::new(AtomicBool::new(false)); + let watch = flag.clone(); + let inner = self.inner.clone(); + HEADER_IN + .scope(flag, async move { + tokio::select! { + r = inner.process_new_http(session, shutdown) => r, + () = async { + tokio::time::sleep(deadline).await; + if watch.load(Ordering::Acquire) { + pending::<()>().await; + } + } => { + log::debug!(target: "ianitor::http", "request header not complete after {deadline:?}; connection closed"); + None + } + } + }) + .await } fn h2_options(&self) -> Option { diff --git a/crates/edge/src/http_app.rs b/crates/edge/src/http_app.rs index 799801e..6671ae2 100644 --- a/crates/edge/src/http_app.rs +++ b/crates/edge/src/http_app.rs @@ -44,6 +44,9 @@ impl HttpServerApp for HttpApp { mut http: ServerSession, shutdown: &ShutdownWatch, ) -> Option { + // Pipelined requests are answered in order, as Caddy does (RFC 9112 §9.3.2); without + // this Pingora answers the first and closes the connection. + http.set_pipelining_enabled(true); match http.read_request().await { Ok(true) => crate::deadline::header_read(), Ok(false) => return None, diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index 13ad7ed..64d66f5 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -59,6 +59,10 @@ pub struct Options { pub credentials_dir: Option, /// The overall deadline for a request header; default [`deadline::HEADER_TIMEOUT`]. pub header_timeout: Option, + /// A Unix socket (mode 0660) on which edge serves the HTTPS hosts in plain HTTP to a front + /// proxy that terminated TLS (Caddy beside Ianitor). Only the socket's owner and group can + /// connect, so its `X-Forwarded-For` is believed (Unix only). + pub proxy_socket: Option, } impl Options { @@ -143,6 +147,9 @@ pub fn server(shared: Arc, opts: &Options) -> Result https .endpoints() .set_pre_tls_callback(Arc::new(tls::HandshakeStart)); + if let Some(path) = &opts.proxy_socket { + add_proxy_socket(&mut https, path)?; + } let mut http = Service::new( "ianitor http".to_owned(), @@ -193,6 +200,26 @@ pub fn server(shared: Arc, opts: &Options) -> Result Ok(server) } +/// The front proxy's socket on the HTTPS service: plain HTTP, mode 0660. +#[cfg(unix)] +fn add_proxy_socket(svc: &mut Service, path: &Path) -> Result<(), EdgeError> { + use std::os::unix::fs::PermissionsExt; + let p = path.to_str().ok_or_else(|| EdgeError::Listen { + address: path.display().to_string(), + reason: "the proxy socket path is not UTF-8".into(), + })?; + svc.add_uds(p, Some(std::fs::Permissions::from_mode(0o660))); + Ok(()) +} + +#[cfg(not(unix))] +fn add_proxy_socket(_svc: &mut Service, path: &Path) -> Result<(), EdgeError> { + Err(EdgeError::Listen { + address: path.display().to_string(), + reason: "a proxy socket needs a Unix system".into(), + }) +} + /// 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<()>) { diff --git a/crates/edge/src/main.rs b/crates/edge/src/main.rs index 2dc6025..4c4ef08 100644 --- a/crates/edge/src/main.rs +++ b/crates/edge/src/main.rs @@ -3,7 +3,8 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! `ianitor-edge --config [--check] [--admin-socket ] [--trial-config ] -//! [--share-revocations ] [--acme-root ] [--header-timeout ]` +//! [--share-revocations ] [--acme-root ] [--header-timeout ] +//! [--proxy-socket ]` //! //! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG` //! (error, warn, info, debug, trace; libraries are capped at info). @@ -23,6 +24,7 @@ fn parse_args() -> Result<(Options, bool), EdgeError> { 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("--proxy-socket") => opts.proxy_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("--header-timeout") => { @@ -40,7 +42,7 @@ fn parse_args() -> Result<(Options, bool), EdgeError> { println!( "usage: ianitor-edge --config [--check] [--admin-socket ] \ [--trial-config ] [--share-revocations ] [--acme-root ] \ - [--header-timeout ]" + [--header-timeout ] [--proxy-socket ]" ); std::process::exit(0); } diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index fd9b685..8b1ba07 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -75,9 +75,6 @@ pub fn hostname(host_header: &str) -> String { name.to_ascii_lowercase() } -/// The client's address: the peer, or, when the peer is a trusted proxy, the rightmost -/// `X-Forwarded-For` entry that is not itself trusted (the same right-to-left rule as Caddy's -/// `trusted_proxies_strict`). Anything a client could forge to the left is ignored. /// An IPv4 address carried as IPv6 (`::ffff:127.0.0.1`) is the IPv4 address. fn canonical(ip: IpAddr) -> IpAddr { match ip { @@ -86,16 +83,21 @@ fn canonical(ip: IpAddr) -> IpAddr { } } +/// The client's address: the peer, or, when the peer is a trusted proxy, the rightmost +/// `X-Forwarded-For` entry that is not itself trusted (the same right-to-left rule as Caddy's +/// `trusted_proxies_strict`). Anything a client could forge to the left is ignored. +/// +/// A request on the proxy socket (`--proxy-socket`) comes from the front proxy by +/// construction: only the socket's owner and group can connect to it, so its peer is trusted +/// and its `X-Forwarded-For` names the client. With no usable entry there is no address. pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option { - let peer = canonical( - session - .client_addr() - .and_then(|a| a.as_inet()) - .map(|a| a.ip())?, - ); + let addr = session.client_addr()?; + let peer = addr.as_inet().map(|a| canonical(a.ip())); let trusted_ip = |ip: &IpAddr| trusted.iter().any(|t| canonical(*t) == *ip); - if !trusted_ip(&peer) { - return Some(peer); + if let Some(p) = peer + && !trusted_ip(&p) + { + return Some(p); } let mut last = peer; for v in session @@ -105,16 +107,16 @@ pub fn client_ip(session: &Session, trusted: &[IpAddr]) -> Option { .iter() .rev() { - let Ok(s) = v.to_str() else { return Some(last) }; + let Ok(s) = v.to_str() else { return last }; for part in s.rsplit(',') { match part.trim().parse::().map(canonical) { - Ok(ip) if trusted_ip(&ip) => last = ip, + Ok(ip) if trusted_ip(&ip) => last = Some(ip), Ok(ip) => return Some(ip), - Err(_) => return Some(last), + Err(_) => return last, } } } - Some(last) + last } /// A response with an empty body, like Caddy's `static_response` and error responses. @@ -165,6 +167,9 @@ impl ProxyHttp for EdgeProxy { async fn early_request_filter(&self, session: &mut Session, _ctx: &mut Ctx) -> Result<()> { // The header is in: the header deadline (slowloris) no longer applies. crate::deadline::header_read(); + // Pipelined requests are answered in order, as Caddy does (RFC 9112 §9.3.2); without + // this Pingora answers the first and closes the connection. + session.downstream_session.set_pipelining_enabled(true); Ok(()) } diff --git a/tests/support/src/client.rs b/tests/support/src/client.rs index 26f2121..ca1e42d 100644 --- a/tests/support/src/client.rs +++ b/tests/support/src/client.rs @@ -478,9 +478,15 @@ mod pipeline_tests { assert_eq!((b.status, b.text().as_str()), (404, "abc")); let (c, _) = parse_one(&rest[used2..], false, false).unwrap().unwrap(); assert_eq!(c.status, 308); - assert!(parse_one(b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nab", false, false) + assert!( + parse_one( + b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nab", + false, + false + ) .unwrap() - .is_none()); + .is_none() + ); } } From 66dcf75fea9c2d2a0d66d5457f71f4767e92bc81 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 20:50:26 +0100 Subject: [PATCH 03/45] [edge] Resolver, tests first: hung name lookups pin at most a bounded number of their own threads, concurrent lookups of one name share one, and the rest fail at once (red: one blocking-pool task per request, as before) --- crates/edge/src/lib.rs | 1 + crates/edge/src/resolver.rs | 251 ++++++++++++++++++++++++++++++++++++ crates/edge/src/runtime.rs | 87 +------------ 3 files changed, 258 insertions(+), 81 deletions(-) create mode 100644 crates/edge/src/resolver.rs diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index 64d66f5..e6b9e76 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -22,6 +22,7 @@ pub mod http_app; pub mod logging; pub mod pages; pub mod proxy; +pub mod resolver; pub mod runtime; pub mod secrets; pub mod share; diff --git a/crates/edge/src/resolver.rs b/crates/edge/src/resolver.rs new file mode 100644 index 0000000..a044538 --- /dev/null +++ b/crates/edge/src/resolver.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/. + +//! Upstream name lookups with a bounded cost. +//! +//! The system resolver (`getaddrinfo`, which honours nsswitch and /etc/hosts like every other +//! program on the machine) blocks a thread, and a lookup cannot be cancelled: when a request +//! gives up after [`crate::runtime::RESOLVE_TIMEOUT`], the thread stays busy until glibc gives +//! up (by default 5 s × 2 attempts × each name server). Through tokio's blocking pool, a dead +//! name server and enough requests would pin every thread of that pool, which the rest of edge +//! shares (file reads, the admin socket). +//! +//! So lookups run on their own threads, at most [`MAX_LOOKUP_THREADS`] at a time, never on +//! tokio's pool; concurrent requests for one name share one lookup; and a request that would +//! need a thread past the limit fails at once (a 502, like a lookup that timed out) instead of +//! queueing. Nothing is cached: like Caddy, every connect resolves again. + +use std::collections::HashMap; +use std::io; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::Duration; + +use tokio::sync::{OwnedSemaphorePermit, Semaphore, watch}; + +/// How many lookups may hold a thread at once. +pub const MAX_LOOKUP_THREADS: usize = 8; + +type Lookup = dyn Fn(&str, u16) -> io::Result> + Send + Sync; +type Answer = Result>, (io::ErrorKind, String)>; +type Inflight = Mutex>>>; + +pub struct Resolver { + permits: Arc, + inflight: Arc, + lookup: Arc, +} + +fn lock(m: &Inflight) -> MutexGuard<'_, HashMap<(String, u16), watch::Receiver>>> { + m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// The process-wide resolver over the system's `getaddrinfo`. +pub fn system() -> &'static Resolver { + static SYSTEM: std::sync::LazyLock = std::sync::LazyLock::new(|| { + Resolver::new(MAX_LOOKUP_THREADS, |host, port| { + use std::net::ToSocketAddrs; + (host, port).to_socket_addrs().map(Iterator::collect) + }) + }); + &SYSTEM +} + +impl Resolver { + pub fn new( + threads: usize, + lookup: impl Fn(&str, u16) -> io::Result> + Send + Sync + 'static, + ) -> Resolver { + Resolver { + permits: Arc::new(Semaphore::new(threads)), + inflight: Arc::default(), + lookup: Arc::new(lookup), + } + } + + /// Addresses for `host:port` in resolver order, within `deadline`. IP literals are not + /// looked up. Errors: `TimedOut` (the lookup may go on in the background, holding its + /// thread), `ResourceBusy` (every lookup thread is taken), `NotFound` (no address), or the + /// resolver's own error. + pub async fn resolve( + &self, + host: &str, + port: u16, + deadline: Duration, + ) -> io::Result> { + if let Ok(ip) = host.parse::() { + return Ok(vec![SocketAddr::new(ip, port)]); + } + let mut rx = self.start_or_join(host, port)?; + let answer = match tokio::time::timeout(deadline, rx.wait_for(Option::is_some)).await { + Ok(Ok(v)) => v.clone(), + Ok(Err(_)) => { + return Err(io::Error::other( + "the name lookup thread ended without an answer", + )); + } + Err(_) => { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + format!("name lookup took longer than {deadline:?}"), + )); + } + }; + match answer { + Some(Ok(addrs)) if addrs.is_empty() => Err(io::Error::new( + io::ErrorKind::NotFound, + "name resolves to no address", + )), + Some(Ok(addrs)) => Ok(addrs.as_ref().clone()), + Some(Err((kind, msg))) => Err(io::Error::new(kind, msg)), + None => Err(io::Error::other("no answer")), + } + } + + /// The lookup in flight for this name, or a new one on its own thread. + fn start_or_join(&self, host: &str, port: u16) -> io::Result>> { + // Not built yet (the red commit): one blocking-pool task per request, as before. + let _ = (&self.permits, &self.inflight); + let (tx, rx) = watch::channel(None); + let lookup = self.lookup.clone(); + let host = host.to_owned(); + tokio::task::spawn_blocking(move || { + let answer = lookup(&host, port) + .map(Arc::new) + .map_err(|e| (e.kind(), e.to_string())); + let _ = tx.send(Some(answer)); + }); + Ok(rx) + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + use std::sync::Condvar; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::Instant; + + /// A resolver whose lookups hang until the gate opens; counts the lookups started. + struct Hung { + started: Arc, + gate: Arc<(Mutex, Condvar)>, + } + + impl Hung { + fn resolver(threads: usize) -> (Resolver, Hung) { + let started = Arc::new(AtomicUsize::new(0)); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let (s, g) = (started.clone(), gate.clone()); + let r = Resolver::new(threads, move |_, port| { + s.fetch_add(1, Ordering::SeqCst); + let (m, cv) = &*g; + let mut open = m.lock().unwrap(); + while !*open { + open = cv.wait(open).unwrap(); + } + Ok(vec![SocketAddr::from(([127, 0, 0, 1], port))]) + }); + (r, Hung { started, gate }) + } + + fn open(&self) { + let (m, cv) = &*self.gate; + *m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = true; + cv.notify_all(); + } + } + + /// A failed assertion must not leave lookups hung (the runtime waits for them on drop). + impl Drop for Hung { + fn drop(&mut self) { + self.open(); + } + } + + const SHORT: Duration = Duration::from_millis(100); + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn hung_lookups_pin_at_most_the_limit_and_the_rest_fail_at_once() { + let (r, hung) = Hung::resolver(2); + for name in ["a.test", "b.test"] { + let e = r.resolve(name, 80, SHORT).await.unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::TimedOut, "{e}"); + } + // Both threads are still stuck in the resolver: a third name fails without waiting. + let t = Instant::now(); + let e = r + .resolve("c.test", 80, Duration::from_secs(5)) + .await + .unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::ResourceBusy, "{e}"); + assert!(t.elapsed() < Duration::from_secs(1), "{:?}", t.elapsed()); + // A name already being looked up joins that lookup instead of taking a thread. + let e = r.resolve("A.test", 80, SHORT).await.unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::TimedOut); + assert_eq!(hung.started.load(Ordering::SeqCst), 2); + + // Once the resolver answers, the threads come back. + hung.open(); + let mut ok = None; + for _ in 0..100 { + match r.resolve("c.test", 81, SHORT).await { + Ok(a) => { + ok = Some(a); + break; + } + Err(e) if e.kind() == io::ErrorKind::ResourceBusy => { + tokio::time::sleep(Duration::from_millis(20)).await; + } + Err(e) => panic!("{e}"), + } + } + assert_eq!(ok.unwrap(), vec![SocketAddr::from(([127, 0, 0, 1], 81))]); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn concurrent_requests_for_one_name_share_one_lookup() { + let started = Arc::new(AtomicUsize::new(0)); + let s = started.clone(); + let r = Arc::new(Resolver::new(2, move |_, port| { + s.fetch_add(1, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(200)); + Ok(vec![SocketAddr::from(([192, 0, 2, 1], port))]) + })); + let mut tasks = Vec::new(); + for _ in 0..20 { + let r = r.clone(); + tasks.push(tokio::spawn(async move { + r.resolve("shared.test", 443, Duration::from_secs(5)).await + })); + } + for t in tasks { + assert_eq!( + t.await.unwrap().unwrap(), + vec![SocketAddr::from(([192, 0, 2, 1], 443))] + ); + } + assert_eq!(started.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn literals_empty_answers_and_errors() { + let r = Resolver::new(1, |host, _| match host { + "empty.test" => Ok(vec![]), + _ => Err(io::Error::new(io::ErrorKind::NotFound, "no such host")), + }); + assert_eq!( + r.resolve("::1", 8080, SHORT).await.unwrap(), + vec!["[::1]:8080".parse().unwrap()] + ); + assert_eq!( + r.resolve("empty.test", 80, SHORT).await.unwrap_err().kind(), + io::ErrorKind::NotFound + ); + let e = r.resolve("gone.test", 80, SHORT).await.unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::NotFound); + assert!(e.to_string().contains("no such host")); + } +} diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs index c6e0416..1c5ca57 100644 --- a/crates/edge/src/runtime.rs +++ b/crates/edge/src/runtime.rs @@ -235,54 +235,15 @@ pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(3); impl UpstreamRt { /// Addresses to try, in resolver order. Names are resolved at connect time (like Caddy's /// dialer), so DNS changes and unresolvable names only affect requests, not startup. - /// A lookup that takes longer than [`RESOLVE_TIMEOUT`] is an error. + /// A lookup that takes longer than [`RESOLVE_TIMEOUT`] is an error; lookups run on their + /// own bounded threads ([`crate::resolver`]). pub async fn resolve(&self) -> std::io::Result> { - resolve_with( - &self.host, - self.port, - RESOLVE_TIMEOUT, - |host, port| async move { - tokio::net::lookup_host((host.as_str(), port)) - .await - .map(Iterator::collect) - }, - ) - .await + crate::resolver::system() + .resolve(&self.host, self.port, RESOLVE_TIMEOUT) + .await } } -/// [`UpstreamRt::resolve`] with the lookup passed in, so the deadline can be tested. -pub async fn resolve_with( - host: &str, - port: u16, - deadline: Duration, - lookup: F, -) -> std::io::Result> -where - F: FnOnce(String, u16) -> Fut, - Fut: Future>>, -{ - if let Ok(ip) = host.parse::() { - return Ok(vec![SocketAddr::new(ip, port)]); - } - let addrs = match tokio::time::timeout(deadline, lookup(host.to_owned(), port)).await { - Ok(r) => r?, - Err(_) => { - return Err(std::io::Error::new( - std::io::ErrorKind::TimedOut, - format!("name lookup took longer than {deadline:?}"), - )); - } - }; - if addrs.is_empty() { - return Err(std::io::Error::new( - std::io::ErrorKind::NotFound, - "name resolves to no address", - )); - } - Ok(addrs) -} - fn header_name(name: &str) -> Result { HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header { name: name.to_owned(), @@ -498,46 +459,10 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result Date: Tue, 10 Nov 2026 20:50:52 +0100 Subject: [PATCH 04/45] [edge] Resolver: upstream names are looked up on at most 8 threads of their own, never on tokio's blocking pool; one lookup per name at a time; a lookup past the limit fails at once with 502 --- crates/edge/src/resolver.rs | 50 +++++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 11 deletions(-) diff --git a/crates/edge/src/resolver.rs b/crates/edge/src/resolver.rs index a044538..6abde8f 100644 --- a/crates/edge/src/resolver.rs +++ b/crates/edge/src/resolver.rs @@ -29,7 +29,8 @@ pub const MAX_LOOKUP_THREADS: usize = 8; type Lookup = dyn Fn(&str, u16) -> io::Result> + Send + Sync; type Answer = Result>, (io::ErrorKind, String)>; -type Inflight = Mutex>>>; +type Waiters = HashMap<(String, u16), watch::Receiver>>; +type Inflight = Mutex; pub struct Resolver { permits: Arc, @@ -37,7 +38,7 @@ pub struct Resolver { lookup: Arc, } -fn lock(m: &Inflight) -> MutexGuard<'_, HashMap<(String, u16), watch::Receiver>>> { +fn lock(m: &Inflight) -> MutexGuard<'_, Waiters> { m.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } @@ -105,17 +106,44 @@ impl Resolver { /// The lookup in flight for this name, or a new one on its own thread. fn start_or_join(&self, host: &str, port: u16) -> io::Result>> { - // Not built yet (the red commit): one blocking-pool task per request, as before. - let _ = (&self.permits, &self.inflight); + let key = (host.to_ascii_lowercase(), port); + let mut map = lock(&self.inflight); + if let Some(rx) = map.get(&key) { + return Ok(rx.clone()); + } + let permit: OwnedSemaphorePermit = + self.permits.clone().try_acquire_owned().map_err(|_| { + io::Error::new( + io::ErrorKind::ResourceBusy, + format!( + "{MAX_LOOKUP_THREADS} name lookups are already waiting on the resolver" + ), + ) + })?; let (tx, rx) = watch::channel(None); + map.insert(key.clone(), rx.clone()); + drop(map); let lookup = self.lookup.clone(); - let host = host.to_owned(); - tokio::task::spawn_blocking(move || { - let answer = lookup(&host, port) - .map(Arc::new) - .map_err(|e| (e.kind(), e.to_string())); - let _ = tx.send(Some(answer)); - }); + let inflight = self.inflight.clone(); + let spawned = std::thread::Builder::new() + .name("ianitor-dns".into()) + .spawn({ + let key = key.clone(); + move || { + let answer = lookup(&key.0, key.1) + .map(Arc::new) + .map_err(|e| (e.kind(), e.to_string())); + let _ = tx.send(Some(answer)); + lock(&inflight).remove(&key); + drop(permit); + } + }); + if let Err(e) = spawned { + lock(&self.inflight).remove(&key); + return Err(io::Error::other(format!( + "cannot start a name lookup thread: {e}" + ))); + } Ok(rx) } } From a278ef3b232f861581b989f841cd7e82f1e7d61b Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 20:53:40 +0100 Subject: [PATCH 05/45] [tests] Windows: a Linux-only test target shows as one ignored test, not as a pass --- crates/control/tests/api.rs | 10 ++++------ crates/control/tests/apply.rs | 10 ++++------ crates/control/tests/engine_switch.rs | 10 ++++------ crates/control/tests/pki.rs | 10 ++++------ crates/control/tests/ui_auth.rs | 10 ++++------ crates/edge/tests/acme_pebble.rs | 10 ++++------ crates/edge/tests/device_certs.rs | 10 ++++------ crates/edge/tests/forward_auth.rs | 10 ++++------ crates/edge/tests/listeners.rs | 4 +++- crates/edge/tests/reload.rs | 10 ++++------ crates/edge/tests/secrets.rs | 10 ++++------ crates/edge/tests/share_links.rs | 10 ++++------ crates/edge/tests/trusted_proxies.rs | 10 ++++------ crates/edge/tests/upstreams.rs | 10 ++++------ tests/diff/tests/apply_sequence.rs | 10 ++++------ tests/diff/tests/diff.rs | 10 ++++------ 16 files changed, 63 insertions(+), 91 deletions(-) diff --git a/crates/control/tests/api.rs b/crates/control/tests/api.rs index c41f05c..4f74181 100644 --- a/crates/control/tests/api.rs +++ b/crates/control/tests/api.rs @@ -12,14 +12,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (edge admin socket); run it in WSL2", - file!() - ); -} +#[ignore = "needs Linux (edge admin socket): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/control/tests/apply.rs b/crates/control/tests/apply.rs index fef8c46..5bfdac3 100644 --- a/crates/control/tests/apply.rs +++ b/crates/control/tests/apply.rs @@ -13,14 +13,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (edge admin socket); run it in WSL2", - file!() - ); -} +#[ignore = "needs Linux (edge admin socket): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/control/tests/engine_switch.rs b/crates/control/tests/engine_switch.rs index 42ddf4a..7f20c22 100644 --- a/crates/control/tests/engine_switch.rs +++ b/crates/control/tests/engine_switch.rs @@ -11,14 +11,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux; run it in WSL2", - file!() - ); -} +#[ignore = "needs Linux: run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/control/tests/pki.rs b/crates/control/tests/pki.rs index 0b998f2..e2e5d8f 100644 --- a/crates/control/tests/pki.rs +++ b/crates/control/tests/pki.rs @@ -13,14 +13,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux; run it in WSL2", - file!() - ); -} +#[ignore = "needs Linux: run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/control/tests/ui_auth.rs b/crates/control/tests/ui_auth.rs index 431c975..f9794ef 100644 --- a/crates/control/tests/ui_auth.rs +++ b/crates/control/tests/ui_auth.rs @@ -13,14 +13,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux; run it in WSL2", - file!() - ); -} +#[ignore = "needs Linux: run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/edge/tests/acme_pebble.rs b/crates/edge/tests/acme_pebble.rs index 9af257d..e4beec9 100644 --- a/crates/edge/tests/acme_pebble.rs +++ b/crates/edge/tests/acme_pebble.rs @@ -15,14 +15,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md", - file!() - ); -} +#[ignore = "needs Linux (Pingora runner, Caddy, Pebble): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/edge/tests/device_certs.rs b/crates/edge/tests/device_certs.rs index 28db0a9..f1543ea 100644 --- a/crates/edge/tests/device_certs.rs +++ b/crates/edge/tests/device_certs.rs @@ -12,14 +12,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (Pingora runner); run it in WSL2, see CLAUDE.md", - file!() - ); -} +#[ignore = "needs Linux (Pingora runner): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/edge/tests/forward_auth.rs b/crates/edge/tests/forward_auth.rs index 093678e..219209e 100644 --- a/crates/edge/tests/forward_auth.rs +++ b/crates/edge/tests/forward_auth.rs @@ -11,14 +11,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md", - file!() - ); -} +#[ignore = "needs Linux (Pingora runner, Caddy, Pebble): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/edge/tests/listeners.rs b/crates/edge/tests/listeners.rs index 4b44fbe..eca2319 100644 --- a/crates/edge/tests/listeners.rs +++ b/crates/edge/tests/listeners.rs @@ -12,9 +12,11 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -#[ignore = "needs Linux (the Pingora runner): run it in WSL2, see CLAUDE.md"] +#[ignore = "needs Linux (Pingora runner): run it in WSL2, see CLAUDE.md"] fn needs_linux() {} #[cfg(unix)] diff --git a/crates/edge/tests/reload.rs b/crates/edge/tests/reload.rs index c0b7ce8..2640cc1 100644 --- a/crates/edge/tests/reload.rs +++ b/crates/edge/tests/reload.rs @@ -12,14 +12,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md", - file!() - ); -} +#[ignore = "needs Linux (Pingora runner, Caddy, Pebble): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/edge/tests/secrets.rs b/crates/edge/tests/secrets.rs index 2775f18..fadecd0 100644 --- a/crates/edge/tests/secrets.rs +++ b/crates/edge/tests/secrets.rs @@ -10,14 +10,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md", - file!() - ); -} +#[ignore = "needs Linux (Pingora runner, Caddy, Pebble): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/edge/tests/share_links.rs b/crates/edge/tests/share_links.rs index cd94938..9088783 100644 --- a/crates/edge/tests/share_links.rs +++ b/crates/edge/tests/share_links.rs @@ -13,14 +13,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md", - file!() - ); -} +#[ignore = "needs Linux (Pingora runner, Caddy, Pebble): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/edge/tests/trusted_proxies.rs b/crates/edge/tests/trusted_proxies.rs index 51782be..dc6424f 100644 --- a/crates/edge/tests/trusted_proxies.rs +++ b/crates/edge/tests/trusted_proxies.rs @@ -11,14 +11,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (Pingora runner); run it in WSL2, see CLAUDE.md", - file!() - ); -} +#[ignore = "needs Linux (Pingora runner): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/crates/edge/tests/upstreams.rs b/crates/edge/tests/upstreams.rs index dabb165..3c96bc9 100644 --- a/crates/edge/tests/upstreams.rs +++ b/crates/edge/tests/upstreams.rs @@ -10,14 +10,12 @@ #[cfg(unix)] mod common; +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md", - file!() - ); -} +#[ignore = "needs Linux (Pingora runner, Caddy, Pebble): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/tests/diff/tests/apply_sequence.rs b/tests/diff/tests/apply_sequence.rs index 37c3f93..1a2e179 100644 --- a/tests/diff/tests/apply_sequence.rs +++ b/tests/diff/tests/apply_sequence.rs @@ -9,14 +9,12 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy); run it in WSL2", - file!() - ); -} +#[ignore = "needs Linux (Pingora runner, Caddy): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { diff --git a/tests/diff/tests/diff.rs b/tests/diff/tests/diff.rs index 9e4d5f3..1b7adf2 100644 --- a/tests/diff/tests/diff.rs +++ b/tests/diff/tests/diff.rs @@ -7,14 +7,12 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +// On Windows this target has nothing to run: it shows as one *ignored* test, never as a +// pass (ROADMAP §8.3; run it in WSL2, see CLAUDE.md). #[cfg(not(unix))] #[test] -fn skipped_on_windows() { - eprintln!( - "SKIPPED on Windows: {} needs Linux (Pingora runner, Caddy, Pebble); run it in WSL2, see CLAUDE.md", - file!() - ); -} +#[ignore = "needs Linux (Pingora runner, Caddy, Pebble): run it in WSL2, see CLAUDE.md"] +fn needs_linux() {} #[cfg(unix)] mod unix { From 4150848842c962ae4be3832a03c45d2f05a28af5 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 20:54:46 +0100 Subject: [PATCH 06/45] [diff] Pipelining: two pipelined cases (plain HTTP and HTTPS), every answer's status, location and body compared in order --- tests/diff/src/lib.rs | 70 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/tests/diff/src/lib.rs b/tests/diff/src/lib.rs index 6d7446c..ced0787 100644 --- a/tests/diff/src/lib.rs +++ b/tests/diff/src/lib.rs @@ -325,6 +325,13 @@ pub enum Action { host: &'static str, headers: Vec<(&'static str, &'static str)>, }, + /// Several requests written back to back on one connection (HTTP/1.1 pipelining); HTTPS + /// with this SNI, plain HTTP without. Every answer's status, `location` and body are + /// compared, in order. + Pipelined { + sni: Option<&'static str>, + reqs: Vec, + }, } /// One request of the corpus. Status, every response header (except [`IGNORED_HEADERS`]) @@ -446,6 +453,28 @@ pub fn corpus() -> Vec { ), http("HTTP redirects to HTTPS", Req::get(p, "/a/b?c=d")), http("HTTP unknown host", Req::get("unknown.test", "/")), + Case { + name: "HTTP pipelined: redirect, unknown host, redirect", + action: Action::Pipelined { + sni: None, + reqs: vec![ + Req::get(p, "/one"), + Req::get("unknown.test", "/"), + Req::get(p, "/three?x=1"), + ], + }, + }, + Case { + name: "HTTPS pipelined: GET, POST with body, GET", + action: Action::Pipelined { + sni: Some(p), + reqs: vec![ + Req::get(p, "/first"), + Req::new("POST", p, "/second").body(b"pipelined body"), + Req::get(p, "/third"), + ], + }, + }, http( "HTTP unknown ACME token", Req::get(p, "/.well-known/acme-challenge/nope"), @@ -714,6 +743,41 @@ pub async fn run_case(case: &Case, t: &Target, roots: Arc) -> Obs Action::Http { req } => client::http(t.http, req) .await .map_or_else(failed, |r| observe(&r, t)), + Action::Pipelined { sni, reqs } => { + let answers = match sni { + Some(sni) => client::https_pipelined(t.https, sni, roots, reqs).await, + None => client::http_pipelined(t.http, reqs).await, + }; + match answers { + Ok(list) => { + let mut headers = BTreeMap::new(); + let mut body = String::new(); + for (i, r) in list.iter().enumerate() { + let o = observe(r, t); + headers.insert(format!("answer-{i}-status"), o.status.to_string()); + if let Some(l) = o.headers.get("location") { + headers.insert(format!("answer-{i}-location"), l.clone()); + } + let _ = writeln!( + body, + "--- answer {i} +{}", + o.body + ); + } + Observation { + status: list.first().map_or(0, |r| r.status), + headers, + body: format!( + "{} answers +{body}", + list.len() + ), + } + } + Err(e) => failed(e), + } + } Action::Websocket { sni, host, headers } => { match client::websocket(t.https, sni, roots, host, "/socket", headers, "ping").await { Ok(WsOutcome::Upgraded { @@ -984,6 +1048,12 @@ pub fn case_host(case: &Case) -> String { .find(|(n, _)| n == "host") .map(|(_, v)| v.to_ascii_lowercase()) .unwrap_or_default(), + Action::Pipelined { sni: Some(sni), .. } => (*sni).to_owned(), + Action::Pipelined { sni: None, reqs } => reqs + .first() + .and_then(|r| r.headers.iter().find(|(n, _)| n == "host")) + .map(|(_, v)| v.to_ascii_lowercase()) + .unwrap_or_default(), } } From ffffa62999a1cb5ac935c4c609c7f3023d9e19ed Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 20:59:57 +0100 Subject: [PATCH 07/45] [core] Proxy socket: compile option proxy_socket gives both engines a 0660 Unix socket for the front proxy (edge in its config, Caddy a third server with trusted_proxies_unix); listeners change only with a restart --- crates/control/src/config.rs | 5 ++++ crates/control/src/dev.rs | 1 + crates/control/tests/common/mod.rs | 1 + crates/core/src/compile/caddy.rs | 30 ++++++++++++++++++++--- crates/core/src/compile/edge.rs | 1 + crates/core/src/compile/mod.rs | 17 +++++++++++++ crates/core/src/edge_config.rs | 4 +++ crates/core/tests/compile.rs | 39 ++++++++++++++++++++++++++++++ crates/edge/src/lib.rs | 8 ++---- crates/edge/src/main.rs | 6 ++--- crates/edge/src/shared.rs | 5 +++- crates/edge/tests/common/mod.rs | 4 +++ crates/edge/tests/listeners.rs | 14 +++++++---- tests/diff/src/lib.rs | 1 + tests/diff/tests/apply_sequence.rs | 1 + 15 files changed, 117 insertions(+), 20 deletions(-) diff --git a/crates/control/src/config.rs b/crates/control/src/config.rs index ac2736e..04a4af6 100644 --- a/crates/control/src/config.rs +++ b/crates/control/src/config.rs @@ -116,6 +116,10 @@ pub struct Compile { /// Proxies in front whose X-Forwarded-For is believed (e.g. ["127.0.0.1"] beside Caddy). #[serde(default)] pub trusted_proxies: Vec, + /// The front proxy's Unix socket (beside Caddy): both engines serve the HTTPS hosts on it + /// and believe its X-Forwarded-For. + #[serde(default)] + pub proxy_socket: Option, } impl Compile { @@ -130,6 +134,7 @@ impl Compile { caddy_admin: self.caddy_admin, caddy_admin_socket: self.caddy_admin_socket.clone(), trusted_proxies: self.trusted_proxies.clone(), + proxy_socket: self.proxy_socket.clone(), } } } diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs index 2b59ad6..0c157dd 100644 --- a/crates/control/src/dev.rs +++ b/crates/control/src/dev.rs @@ -150,6 +150,7 @@ pub async fn run(args: &[String]) -> Result<(), String> { caddy_admin: None, caddy_admin_socket: None, trusted_proxies: Vec::new(), + proxy_socket: None, }, compile_caddy: None, pki: Some(ianitor_control::config::PkiConfig { diff --git a/crates/control/tests/common/mod.rs b/crates/control/tests/common/mod.rs index 041db6f..218a0c6 100644 --- a/crates/control/tests/common/mod.rs +++ b/crates/control/tests/common/mod.rs @@ -116,6 +116,7 @@ impl Env { caddy_admin: None, caddy_admin_socket: None, trusted_proxies: Vec::new(), + proxy_socket: None, }; // Edge starts from an empty config; control brings it in line on its first start. let empty = load( diff --git a/crates/core/src/compile/caddy.rs b/crates/core/src/compile/caddy.rs index 3a34071..74b1de8 100644 --- a/crates/core/src/compile/caddy.rs +++ b/crates/core/src/compile/caddy.rs @@ -19,6 +19,7 @@ use crate::{ const ACCESS_LOGGER: &str = "ianitor_access"; const HTTPS_SERVER: &str = "ianitor_https"; const HTTP_SERVER: &str = "ianitor_http"; +const PROXY_SERVER: &str = "ianitor_proxy"; pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value { let hosts = model.hosts(); @@ -77,6 +78,23 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value { .collect(); policies.push(json!({})); + // ---- The front proxy's socket: the same routes in plain HTTP, its peer trusted (edge: + // `client_ip` on the socket). No TLS here, so no certificates are managed for it. + let mut proxy = o.proxy_socket.as_ref().map(|sock| { + let mut p = Map::new(); + p.insert( + "listen".into(), + json!([format!("unix//{}|0660", sock.trim_start_matches('/'))]), + ); + p.insert("routes".into(), Value::Array(routes.clone())); + p.insert("automatic_https".into(), json!({ "disable": true })); + p.insert("protocols".into(), json!(["h1"])); + p.insert("trusted_proxies_unix".into(), json!(true)); + p.insert("client_ip_headers".into(), json!(["X-Forwarded-For"])); + p.insert("trusted_proxies_strict".into(), json!(1)); + p + }); + let mut https = Map::new(); https.insert("listen".into(), json!([o.https_listen.to_string()])); https.insert("routes".into(), Value::Array(routes)); @@ -106,10 +124,11 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value { .iter() .map(|h| (h.hostname.to_string(), json!([ACCESS_LOGGER]))) .collect(); - https.insert( - "logs".into(), - json!({ "logger_names": names, "skip_unmapped_hosts": true }), - ); + let logs = json!({ "logger_names": names, "skip_unmapped_hosts": true }); + if let Some(p) = proxy.as_mut() { + p.insert("logs".into(), logs.clone()); + } + https.insert("logs".into(), logs); } // ---- HTTP server: redirect known hosts to HTTPS (ACME HTTP-01 is answered by Caddy itself). @@ -142,6 +161,9 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> Value { let mut servers = Map::new(); servers.insert(HTTPS_SERVER.into(), Value::Object(https)); servers.insert(HTTP_SERVER.into(), http); + if let Some(p) = proxy { + servers.insert(PROXY_SERVER.into(), Value::Object(p)); + } let mut tls = Map::new(); if !domi.is_empty() { diff --git a/crates/core/src/compile/edge.rs b/crates/core/src/compile/edge.rs index a486c44..40d3a78 100644 --- a/crates/core/src/compile/edge.rs +++ b/crates/core/src/compile/edge.rs @@ -35,6 +35,7 @@ pub(super) fn compile(model: &Model, o: &CompileOptions) -> EdgeConfig { allow: join(&o.cert_dir, DEVICE_ALLOW_FILE), }), trusted_proxies: o.trusted_proxies.iter().map(ToString::to_string).collect(), + proxy_socket: o.proxy_socket.clone(), forward_auth: site.forward_auth.as_ref().map(|fa| EdgeForwardAuth { upstream: upstream(&fa.upstream), path_and_query: fa.path_and_query.clone(), diff --git a/crates/core/src/compile/mod.rs b/crates/core/src/compile/mod.rs index c03b71c..a62e08d 100644 --- a/crates/core/src/compile/mod.rs +++ b/crates/core/src/compile/mod.rs @@ -48,6 +48,10 @@ pub struct CompileOptions { /// Ianitor on loopback): the share-link throttle and the access log then see the real /// client. Empty (the default): only the connection's own address counts. pub trusted_proxies: Vec, + /// A Unix socket (mode 0660) on which the engine also serves the HTTPS hosts, in plain HTTP, + /// to a front proxy that terminated TLS (Caddy beside Ianitor). Only the socket's owner and + /// group can connect, so its peer is trusted and its `X-Forwarded-For` names the client. + pub proxy_socket: Option, } #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] @@ -80,6 +84,19 @@ pub fn caddy(model: &Model, options: &CompileOptions) -> Result Result<(), CompileError> { + if let Some(s) = &o.proxy_socket { + check_path(s).map_err(|reason| CompileError::BadOption { + option: "proxy_socket", + reason, + })?; + // sun_path holds 108 bytes on Linux, the terminating NUL included. + if s.len() > 100 { + return Err(CompileError::BadOption { + option: "proxy_socket", + reason: "a socket path is at most 100 characters", + }); + } + } if let Some(s) = &o.caddy_admin_socket { check_path(s).map_err(|reason| CompileError::BadOption { option: "caddy_admin_socket", diff --git a/crates/core/src/edge_config.rs b/crates/core/src/edge_config.rs index b8d6869..6f853aa 100644 --- a/crates/core/src/edge_config.rs +++ b/crates/core/src/edge_config.rs @@ -34,6 +34,10 @@ pub struct EdgeConfig { /// Peers whose `X-Forwarded-For` is believed (IP addresses); empty: none. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub trusted_proxies: Vec, + /// A Unix socket (mode 0660) serving the HTTPS hosts in plain HTTP to a front proxy that + /// terminated TLS; its peer is trusted (`X-Forwarded-For` names the client). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub proxy_socket: Option, /// Sorted by hostname. pub hosts: Vec, } diff --git a/crates/core/tests/compile.rs b/crates/core/tests/compile.rs index 584cd5d..1d57b56 100644 --- a/crates/core/tests/compile.rs +++ b/crates/core/tests/compile.rs @@ -74,6 +74,7 @@ fn options() -> CompileOptions { caddy_admin: None, caddy_admin_socket: None, trusted_proxies: Vec::new(), + proxy_socket: None, } } @@ -174,6 +175,44 @@ fn trusted_proxies_reach_both_engines_only_when_set() { assert_eq!(https["trusted_proxies_strict"], serde_json::json!(1)); } +#[test] +fn the_proxy_socket_reaches_both_engines_only_when_set() { + let edge = compile::edge(&model(false), &options()).unwrap(); + let caddy = compile::caddy(&model(false), &options()).unwrap(); + assert!(!edge.contains("proxy_socket") && !caddy.contains("ianitor_proxy")); + let mut o = options(); + o.proxy_socket = Some("/run/ianitor-proxy/edge.sock".into()); + let cfg: EdgeConfig = serde_json::from_str(&compile::edge(&model(false), &o).unwrap()).unwrap(); + assert_eq!( + cfg.proxy_socket.as_deref(), + Some("/run/ianitor-proxy/edge.sock") + ); + let v: serde_json::Value = + serde_json::from_str(&compile::caddy(&model(false), &o).unwrap()).unwrap(); + let servers = &v["apps"]["http"]["servers"]; + let proxy = &servers["ianitor_proxy"]; + assert_eq!( + proxy["listen"], + serde_json::json!(["unix//run/ianitor-proxy/edge.sock|0660"]) + ); + // The same routes as the HTTPS server, no TLS, the socket's peer trusted. + assert_eq!(proxy["routes"], servers["ianitor_https"]["routes"]); + assert_eq!( + proxy["automatic_https"], + serde_json::json!({"disable": true}) + ); + assert_eq!(proxy["trusted_proxies_unix"], serde_json::json!(true)); + assert!(proxy.get("tls_connection_policies").is_none()); + + let long = format!("/{}", "a".repeat(120)); + for bad in ["relative.sock", "/run/{env.HOME}.sock", long.as_str()] { + let mut o = options(); + o.proxy_socket = Some(bad.to_owned()); + assert!(compile::edge(&model(false), &o).is_err(), "{bad}"); + assert!(compile::caddy(&model(false), &o).is_err(), "{bad}"); + } +} + #[test] fn outputs_reference_secrets_by_name_only() { let edge = compile::edge(&model(false), &options()).unwrap(); diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index e6b9e76..b070706 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -60,10 +60,6 @@ pub struct Options { pub credentials_dir: Option, /// The overall deadline for a request header; default [`deadline::HEADER_TIMEOUT`]. pub header_timeout: Option, - /// A Unix socket (mode 0660) on which edge serves the HTTPS hosts in plain HTTP to a front - /// proxy that terminated TLS (Caddy beside Ianitor). Only the socket's owner and group can - /// connect, so its `X-Forwarded-For` is believed (Unix only). - pub proxy_socket: Option, } impl Options { @@ -148,8 +144,8 @@ pub fn server(shared: Arc, opts: &Options) -> Result https .endpoints() .set_pre_tls_callback(Arc::new(tls::HandshakeStart)); - if let Some(path) = &opts.proxy_socket { - add_proxy_socket(&mut https, path)?; + if let Some(path) = &rt.cfg.proxy_socket { + add_proxy_socket(&mut https, Path::new(path))?; } let mut http = Service::new( diff --git a/crates/edge/src/main.rs b/crates/edge/src/main.rs index 4c4ef08..2dc6025 100644 --- a/crates/edge/src/main.rs +++ b/crates/edge/src/main.rs @@ -3,8 +3,7 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! `ianitor-edge --config [--check] [--admin-socket ] [--trial-config ] -//! [--share-revocations ] [--acme-root ] [--header-timeout ] -//! [--proxy-socket ]` +//! [--share-revocations ] [--acme-root ] [--header-timeout ]` //! //! Secrets come from `$CREDENTIALS_DIRECTORY`; the log level from `$IANITOR_LOG` //! (error, warn, info, debug, trace; libraries are capped at info). @@ -24,7 +23,6 @@ fn parse_args() -> Result<(Options, bool), EdgeError> { 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("--proxy-socket") => opts.proxy_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("--header-timeout") => { @@ -42,7 +40,7 @@ fn parse_args() -> Result<(Options, bool), EdgeError> { println!( "usage: ianitor-edge --config [--check] [--admin-socket ] \ [--trial-config ] [--share-revocations ] [--acme-root ] \ - [--header-timeout ] [--proxy-socket ]" + [--header-timeout ]" ); std::process::exit(0); } diff --git a/crates/edge/src/shared.rs b/crates/edge/src/shared.rs index fb3a787..8d247d1 100644 --- a/crates/edge/src/shared.rs +++ b/crates/edge/src/shared.rs @@ -119,7 +119,10 @@ pub struct Shared { } fn same_listeners(a: &Runtime, b: &Runtime) -> Result<(), EdgeError> { - if a.cfg.http_listen != b.cfg.http_listen || a.cfg.https_listen != b.cfg.https_listen { + if a.cfg.http_listen != b.cfg.http_listen + || a.cfg.https_listen != b.cfg.https_listen + || a.cfg.proxy_socket != b.cfg.proxy_socket + { return Err(EdgeError::Config { path: PathBuf::from(""), message: "the listen addresses can only change with a restart".into(), diff --git a/crates/edge/tests/common/mod.rs b/crates/edge/tests/common/mod.rs index e4cf978..6220f05 100644 --- a/crates/edge/tests/common/mod.rs +++ b/crates/edge/tests/common/mod.rs @@ -112,6 +112,8 @@ pub struct EdgeSpec<'a> { pub files: Vec<(String, Vec)>, /// Peers whose X-Forwarded-For edge believes. pub trusted_proxies: Vec, + /// The front proxy's Unix socket. + pub proxy_socket: Option, } impl Default for EdgeSpec<'_> { @@ -125,6 +127,7 @@ impl Default for EdgeSpec<'_> { http_port: None, files: Vec::new(), trusted_proxies: Vec::new(), + proxy_socket: None, } } } @@ -195,6 +198,7 @@ pub fn spawn(spec: EdgeSpec<'_>) -> Edge { caddy_admin: None, caddy_admin_socket: None, trusted_proxies: spec.trusted_proxies.clone(), + proxy_socket: spec.proxy_socket.clone(), }; let config_text = compile_with(&dir, &ca, &opts, spec.site, &spec.hosts); std::fs::write(dir.join("edge.json"), &config_text).unwrap(); diff --git a/crates/edge/tests/listeners.rs b/crates/edge/tests/listeners.rs index eca2319..fcda72e 100644 --- a/crates/edge/tests/listeners.rs +++ b/crates/edge/tests/listeners.rs @@ -147,10 +147,14 @@ mod unix { let echo = Echo::start("app").await; let dir = ianitor_testkit::proc::TempDir::new("proxy-sock"); let sock = dir.join("proxy.sock"); - let edge = app_edge( - &echo, - vec!["--proxy-socket".into(), sock.to_string_lossy().into()], - ); + let edge = start(EdgeSpec { + hosts: vec![host_file( + "app.test", + &format!("upstreams = [\"{}\"]\n", echo.url()), + )], + proxy_socket: Some(sock.to_string_lossy().into()), + ..Default::default() + }); for _ in 0..100 { if sock.exists() { break; @@ -221,7 +225,7 @@ mod unix { devices_ca.issue(&["a-device"]).cert_pem.into_bytes(), ), ], - extra_args: vec!["--proxy-socket".into(), sock.to_string_lossy().into()], + proxy_socket: Some(sock.to_string_lossy().into()), ..Default::default() }); for _ in 0..100 { diff --git a/tests/diff/src/lib.rs b/tests/diff/src/lib.rs index ced0787..c64293b 100644 --- a/tests/diff/src/lib.rs +++ b/tests/diff/src/lib.rs @@ -181,6 +181,7 @@ impl Env { caddy_admin: None, caddy_admin_socket: None, trusted_proxies: Vec::new(), + proxy_socket: None, } } diff --git a/tests/diff/tests/apply_sequence.rs b/tests/diff/tests/apply_sequence.rs index 1a2e179..dd66c02 100644 --- a/tests/diff/tests/apply_sequence.rs +++ b/tests/diff/tests/apply_sequence.rs @@ -40,6 +40,7 @@ mod unix { caddy_admin: o.caddy_admin, caddy_admin_socket: o.caddy_admin_socket.clone(), trusted_proxies: o.trusted_proxies.clone(), + proxy_socket: o.proxy_socket.clone(), } } From 84c1c819067b0a4de17f92f9f1f9806db708a553 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 21:02:41 +0100 Subject: [PATCH 08/45] [core] Unix upstreams, tests first: unix:/path reaches both engines (edge address, Caddy dial), the path is strict, forward-auth never goes to a socket (red: not parsed yet) --- crates/control/src/messages.rs | 6 ++ crates/core/src/model.rs | 26 +++++- crates/core/tests/unix_upstreams.rs | 118 ++++++++++++++++++++++++++++ 3 files changed, 147 insertions(+), 3 deletions(-) create mode 100644 crates/core/tests/unix_upstreams.rs diff --git a/crates/control/src/messages.rs b/crates/control/src/messages.rs index fe01126..c01794f 100644 --- a/crates/control/src/messages.rs +++ b/crates/control/src/messages.rs @@ -37,6 +37,12 @@ fn template(code: &str) -> &'static str { } "host.upstream.not_url" => "Write it as a full address, like http://10.0.0.23:3000.", "host.upstream.scheme" => "Start the address with http:// or https://.", + "host.upstream.unix_path" => { + "Write a socket as unix:/absolute/path.sock, with letters, digits, dots, dashes and underscores only." + } + "host.upstream.unix_socket" => { + "Only the web UI's admin host can use a socket, and only control's own ([ui] socket in control.toml)." + } "host.upstream.no_host" => "Add the server's name or IP address after http://.", "host.upstream.host_name" => { "The server name is not usable. Use letters a–z, digits, dots and dashes, or an IP address." diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs index b4822af..8bd9a5c 100644 --- a/crates/core/src/model.rs +++ b/crates/core/src/model.rs @@ -64,11 +64,13 @@ impl Scheme { } } -/// Where the upstream host is: a DNS name or an IP literal (IPv6 without brackets). +/// Where the upstream host is: a DNS name, an IP literal (IPv6 without brackets), or a Unix +/// socket path (`unix:/abs/path`, plain HTTP; which socket a host may use is control's call). #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum UpstreamHost { Name(String), Ip(std::net::IpAddr), + Unix(String), } /// A validated upstream: scheme, host and explicit port. No path, query, fragment or userinfo. @@ -81,26 +83,44 @@ pub struct Upstream { } impl Upstream { - /// `host:port` as used for dialing, with IPv6 in brackets. + /// `host:port` as used for dialing, with IPv6 in brackets; `unix:` for a socket. pub fn authority(&self) -> String { match &self.host { UpstreamHost::Name(n) => format!("{n}:{}", self.port), UpstreamHost::Ip(std::net::IpAddr::V6(ip)) => format!("[{ip}]:{}", self.port), UpstreamHost::Ip(ip) => format!("{ip}:{}", self.port), + UpstreamHost::Unix(p) => format!("unix:{p}"), } } - /// The host part for TLS SNI and certificate verification. + /// The host part for TLS SNI and certificate verification (empty for a socket, which is + /// always plain HTTP). pub fn host_str(&self) -> String { match &self.host { UpstreamHost::Name(n) => n.clone(), UpstreamHost::Ip(ip) => ip.to_string(), + UpstreamHost::Unix(_) => String::new(), } } + + /// The socket path of a `unix:` upstream. + pub fn unix_path(&self) -> Option<&str> { + match &self.host { + UpstreamHost::Unix(p) => Some(p), + _ => None, + } + } + + pub fn is_unix(&self) -> bool { + self.unix_path().is_some() + } } impl fmt::Display for Upstream { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.is_unix() { + return f.write_str(&self.authority()); + } write!(f, "{}://{}", self.scheme.as_str(), self.authority()) } } diff --git a/crates/core/tests/unix_upstreams.rs b/crates/core/tests/unix_upstreams.rs new file mode 100644 index 0000000..a92232b --- /dev/null +++ b/crates/core/tests/unix_upstreams.rs @@ -0,0 +1,118 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Unix-socket upstreams (G14 option b, tests first): the admin host reaches control on a +//! Unix socket in a directory only the ianitor group can use, so no local process can take +//! control's place while it restarts. Route files are hostile input: the path is strict, and +//! which socket a host may use is control's decision (its `[ui] socket`), not core's. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use ianitor_core::compile::{self, CompileOptions}; +use ianitor_core::edge_config::EdgeConfig; +use ianitor_core::{Model, SourceFile, ValidationError, load}; + +const SOCKET: &str = "/run/ianitor-control/ui.sock"; + +fn load_host(upstreams: &str) -> Result> { + let body = format!("hostname = \"ui.test\"\ntls = \"domi\"\nupstreams = [{upstreams}]\n"); + load( + &SourceFile { + name: "ianitor.toml", + contents: "", + }, + &[SourceFile { + name: "hosts/ui.test.toml", + contents: &body, + }], + ) + .map_err(ianitor_core::ValidationErrors::into_errors) +} + +fn options() -> CompileOptions { + CompileOptions { + http_listen: "0.0.0.0:80".parse().unwrap(), + https_listen: "0.0.0.0:443".parse().unwrap(), + cert_dir: "/var/lib/ianitor/certs".into(), + state_dir: "/var/lib/ianitor".into(), + access_log: "/var/log/ianitor/access.log".into(), + caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(), + caddy_admin: None, + caddy_admin_socket: None, + trusted_proxies: Vec::new(), + proxy_socket: None, + } +} + +#[test] +fn a_unix_socket_upstream_reaches_both_engines() { + let model = load_host(&format!("\"unix:{SOCKET}\"")).unwrap(); + let up = &model.hosts()[0].upstreams[0]; + assert!(up.is_unix()); + assert_eq!(up.to_string(), format!("unix:{SOCKET}")); + + let edge: EdgeConfig = + serde_json::from_str(&compile::edge(&model, &options()).unwrap()).unwrap(); + let u = &edge.hosts[0].upstreams[0]; + assert_eq!(u.address, format!("unix:{SOCKET}")); + assert!(!u.tls); + + let caddy: serde_json::Value = + serde_json::from_str(&compile::caddy(&model, &options()).unwrap()).unwrap(); + let text = caddy.to_string(); + assert!( + text.contains("\"dial\":\"unix//run/ianitor-control/ui.sock\""), + "{text}" + ); +} + +#[test] +fn a_unix_socket_path_is_strict() { + let long = format!("unix:/run/{}.sock", "a".repeat(100)); + for bad in [ + "unix:relative.sock", + "unix:", + "unix:/", + "unix:/run/", + "unix://run/x.sock", + "unix:/run//x.sock", + "unix:/run/../etc/x.sock", + "unix:/run/./x.sock", + "unix:/run/x y.sock", + "unix:/run/{env.HOME}.sock", + "unix:/run/x.sock?q=1", + "unix:/run/x\\y.sock", + "unix:/run/ü.sock", + long.as_str(), + ] { + let errs = load_host(&format!("{:?}", bad)) + .err() + .unwrap_or_else(|| panic!("{bad} was accepted")); + assert!( + errs.iter().any(|e| e.code() == "host.upstream.unix_path"), + "{bad}: {errs:?}" + ); + } +} + +#[test] +fn forward_auth_never_goes_to_a_socket() { + let errs = load( + &SourceFile { + name: "ianitor.toml", + contents: "[forward_auth]\nurl = \"unix:/run/authelia.sock\"\n", + }, + &[], + ) + .unwrap_err(); + assert!(!errs.errors().is_empty()); +} + +#[test] +fn a_unix_upstream_and_a_tcp_one_are_both_kept() { + let model = load_host(&format!("\"unix:{SOCKET}\", \"http://127.0.0.1:7878\"")).unwrap(); + assert_eq!(model.hosts()[0].upstreams.len(), 2); + let dup = load_host(&format!("\"unix:{SOCKET}\", \"unix:{SOCKET}\"")).unwrap_err(); + assert!(dup.iter().any(|e| e.code() == "host.upstream.duplicate")); +} From d74079c66dda345a03d2f84f721bfee9df551603 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 21:04:24 +0100 Subject: [PATCH 09/45] [core] Unix upstreams: unix:/path parses strictly into a socket upstream; edge proxies and health-checks it in plain HTTP over the socket, Caddy dials unix/ --- crates/core/src/compile/caddy.rs | 6 ++- crates/core/src/error.rs | 2 + crates/core/src/validate.rs | 31 ++++++++++- crates/edge/src/fetch.rs | 39 +++++++++++--- crates/edge/src/health.rs | 3 ++ crates/edge/src/proxy.rs | 5 ++ crates/edge/src/runtime.rs | 18 +++++++ crates/edge/tests/listeners.rs | 89 ++++++++++++++++++++++++++++++++ 8 files changed, 183 insertions(+), 10 deletions(-) diff --git a/crates/core/src/compile/caddy.rs b/crates/core/src/compile/caddy.rs index 74b1de8..1bf147a 100644 --- a/crates/core/src/compile/caddy.rs +++ b/crates/core/src/compile/caddy.rs @@ -281,7 +281,11 @@ fn host_route(h: &Host, fa: Option<&ForwardAuth>, o: &CompileOptions) -> Value { fn upstreams(list: &[&Upstream]) -> Value { Value::Array( list.iter() - .map(|u| json!({ "dial": u.authority() })) + .map(|u| match u.unix_path() { + // Caddy's network address: `unix/` then the absolute path. + Some(p) => json!({ "dial": format!("unix/{p}") }), + None => json!({ "dial": u.authority() }), + }) .collect(), ) } diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs index e4dbc84..c4011d7 100644 --- a/crates/core/src/error.rs +++ b/crates/core/src/error.rs @@ -34,6 +34,7 @@ pub(crate) mod reason { pub const URL_CREDENTIALS: &str = "credentials in the URL are not allowed"; pub const URL_FRAGMENT: &str = "a #fragment is not allowed"; pub const URL_NO_HOST: &str = "it has no host"; + pub const URL_UNIX_PATH: &str = "a socket upstream is unix:/absolute/path: letters, digits, '.', '_', '-' and single '/' only, no '.' or '..' parts, at most 100 characters"; pub const URL_HOST_NAME: &str = "the host name is not valid"; pub const URL_NO_PORT: &str = "it has no port"; pub const URL_PORT_ZERO: &str = "port 0 is not usable"; @@ -275,6 +276,7 @@ impl ValidationError { x if x == r::URL_PATH => "host.upstream.path", x if x == r::URL_QUERY => "host.upstream.query", x if x == r::URL_MIXED => "host.upstream.mixed_schemes", + x if x == r::URL_UNIX_PATH => "host.upstream.unix_path", _ => "host.upstream.not_url", }, E::DuplicateUpstream { .. } => "host.upstream.duplicate", diff --git a/crates/core/src/validate.rs b/crates/core/src/validate.rs index d9fb9ac..47a16ac 100644 --- a/crates/core/src/validate.rs +++ b/crates/core/src/validate.rs @@ -401,7 +401,11 @@ fn check_host(file: &str, raw: RawHost, site: Option<&Site>, errors: &mut Vec let mut upstreams: Vec = Vec::new(); let mut seen_upstreams = BTreeSet::new(); for (index, u) in raw.upstreams.iter().take(MAX_UPSTREAMS).enumerate() { - match parse_url(u, false) { + let parsed = match u.strip_prefix("unix:") { + Some(path) => parse_unix(path).map(|up| (up, String::new())), + None => parse_url(u, false), + }; + match parsed { Ok((up, _)) => { if seen_upstreams.insert(up.clone()) { upstreams.push(up); @@ -786,6 +790,31 @@ fn parse_url(raw: &str, allow_path: bool) -> Result<(Upstream, String), &'static Ok((Upstream { scheme, host, port }, path)) } +/// The path of a `unix:` upstream. It ends up in JSON strings and in Caddy's dial address +/// (where `{...}` would be a placeholder), so it is plain: absolute, `[A-Za-z0-9._-]` parts +/// joined by single `/`, no `.` or `..` part, at most 100 bytes (sun_path is 108 on Linux). +fn parse_unix(path: &str) -> Result { + let ok = path.len() <= 100 + && path.len() > 1 + && path.starts_with('/') + && path[1..].split('/').all(|part| { + !part.is_empty() + && part != "." + && part != ".." + && part + .bytes() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-')) + }); + if !ok { + return Err(r::URL_UNIX_PATH); + } + Ok(Upstream { + scheme: Scheme::Http, + host: UpstreamHost::Unix(path.to_owned()), + port: 0, + }) +} + /// A URL as an error may show it: everything before the last `@` (after the scheme) is /// replaced by `…`, so a user name or password, even one containing `/`, `?` or `#`, never /// reaches a message, a log or the API. A URL with no `@` is shown as it is. diff --git a/crates/edge/src/fetch.rs b/crates/edge/src/fetch.rs index c6700eb..9407ab8 100644 --- a/crates/edge/src/fetch.rs +++ b/crates/edge/src/fetch.rs @@ -39,6 +39,36 @@ pub fn peer(addr: SocketAddr, u: &UpstreamRt) -> HttpPeer { p } +/// The peer of a `unix:` upstream (plain HTTP over the socket). +#[cfg(unix)] +pub fn unix_peer(path: &str) -> Result { + let mut p = HttpPeer::new_uds(path, false, String::new())?; + p.options.connection_timeout = Some(DIAL_TIMEOUT); + Ok(p) +} + +#[cfg(not(unix))] +pub fn unix_peer(path: &str) -> Result { + Error::e_explain( + ErrorType::SocketError, + format!("{path}: Unix sockets need a Unix system"), + ) +} + +/// Every peer to try for `u`, in order: its socket, or each address its name resolves to. +pub async fn peers(u: &UpstreamRt) -> Result> { + if let Some(path) = &u.unix { + return Ok(vec![unix_peer(path)?]); + } + let addrs = u.resolve().await.map_err(|e| { + Error::explain( + ErrorType::ConnectNoRoute, + format!("cannot resolve {}: {e}", u.authority), + ) + })?; + Ok(addrs.into_iter().map(|a| peer(a, u)).collect()) +} + /// Send `req` without a body; read the whole response, at most `max_body` bytes of body, /// all within `timeout`. pub async fn fetch( @@ -64,16 +94,9 @@ async fn exchange( max_body: usize, timeout: Duration, ) -> Result { - let addrs = u.resolve().await.map_err(|e| { - Error::explain( - ErrorType::ConnectNoRoute, - format!("cannot resolve {}: {e}", u.authority), - ) - })?; let mut last = None; let mut session = None; - for addr in addrs { - let mut p = peer(addr, u); + for mut p in peers(u).await? { p.options.total_connection_timeout = Some(timeout); match connector.get_http_session(&p).await { Ok((s, _reused)) => { diff --git a/crates/edge/src/health.rs b/crates/edge/src/health.rs index bba150d..68b74f2 100644 --- a/crates/edge/src/health.rs +++ b/crates/edge/src/health.rs @@ -122,6 +122,9 @@ async fn round(host: &Arc, path: &str, connector: &Arc, watch let (h, p, c) = (host.clone(), path.to_owned(), connector.clone()); let probe_host = if watch { host.cfg.hostname.clone() + } else if host.upstreams[i].unix.is_some() { + // A socket has no authority to name; the probe asks as a local client would. + "localhost".to_owned() } else { host.upstreams[i].authority.clone() }; diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index 8b1ba07..a13ea89 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -306,6 +306,11 @@ impl ProxyHttp for EdgeProxy { Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream") })?; let up = &host.upstreams[i]; + if let Some(path) = &up.unix { + // A socket: one peer, nothing to resolve and no other address to try. + log::debug!(target: "ianitor::proxy", "{}: upstream {}", host.cfg.hostname, up.authority); + return Ok(Box::new(fetch::unix_peer(path)?)); + } ctx.addrs = match up.resolve().await { Ok(a) => a, Err(e) => { diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs index 1c5ca57..ae15f9b 100644 --- a/crates/edge/src/runtime.rs +++ b/crates/edge/src/runtime.rs @@ -85,6 +85,8 @@ pub struct UpstreamRt { pub authority: String, pub tls: bool, pub sni: String, + /// A `unix:` upstream's socket path (plain HTTP); `host` and `port` are then unused. + pub unix: Option, pub healthy: AtomicBool, pub health: HealthRecord, } @@ -205,6 +207,21 @@ fn upstream(u: &EdgeUpstream) -> Result { address: u.address.clone(), reason: reason.to_owned(), }; + if let Some(path) = u.address.strip_prefix("unix:") { + if !path.starts_with('/') || u.tls { + return Err(err("expected unix:/absolute/path, plain HTTP")); + } + return Ok(UpstreamRt { + host: String::new(), + port: 0, + authority: u.address.clone(), + tls: false, + sni: String::new(), + unix: Some(path.to_owned()), + healthy: AtomicBool::new(true), + health: HealthRecord::default(), + }); + } let (host, port) = u .address .rsplit_once(':') @@ -223,6 +240,7 @@ fn upstream(u: &EdgeUpstream) -> Result { authority: u.address.clone(), tls: u.tls, sni: u.sni.clone(), + unix: None, healthy: AtomicBool::new(true), health: HealthRecord::default(), }) diff --git a/crates/edge/tests/listeners.rs b/crates/edge/tests/listeners.rs index fcda72e..30db818 100644 --- a/crates/edge/tests/listeners.rs +++ b/crates/edge/tests/listeners.rs @@ -240,4 +240,93 @@ mod unix { assert_eq!(r.status, 403, "{}", edge.stderr()); assert!(echo.proxied().is_empty()); } + + /// A `unix:` upstream (G14 option b: the admin host reaches control on its socket): + /// requests and health checks go over the socket, in plain HTTP. + #[tokio::test(flavor = "multi_thread")] + async fn a_unix_socket_upstream_is_proxied_and_health_checked() { + use http_body_util::Full; + use hyper::server::conn::http1; + use hyper::service::service_fn; + use hyper_util::rt::TokioIo; + use std::sync::{Arc, Mutex}; + + let dir = ianitor_testkit::proc::TempDir::new("unix-upstream"); + let sock = dir.join("app.sock"); + let listener = tokio::net::UnixListener::bind(&sock).unwrap(); + let seen: Arc>> = Arc::default(); + let s = seen.clone(); + tokio::spawn(async move { + loop { + let Ok((stream, _)) = listener.accept().await else { + continue; + }; + let s = s.clone(); + tokio::spawn(async move { + let svc = service_fn(move |req: hyper::Request| { + let host = req + .headers() + .get("host") + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_owned(); + s.lock().unwrap().push((req.uri().path().to_owned(), host)); + async move { + Ok::<_, std::convert::Infallible>(hyper::Response::new(Full::new( + bytes::Bytes::from_static(b"via the socket"), + ))) + } + }); + let _ = http1::Builder::new() + .serve_connection(TokioIo::new(stream), svc) + .await; + }); + } + }); + + let edge = start(EdgeSpec { + hosts: vec![host_file( + "ui.test", + &format!( + "upstreams = [\"unix:{}\"] +[health_check] +path = \"/healthz\" +interval_secs = 1 +", + sock.display() + ), + )], + ..Default::default() + }); + let r = client::https( + edge.https, + "ui.test", + edge.roots(), + &Req::get("ui.test", "/x"), + ) + .await + .unwrap(); + assert_eq!( + (r.status, r.text().as_str()), + (200, "via the socket"), + "{}", + edge.stderr() + ); + for _ in 0..50 { + if seen.lock().unwrap().iter().any(|(p, _)| p == "/healthz") { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + let seen = seen.lock().unwrap().clone(); + assert!( + seen.contains(&("/x".to_owned(), "ui.test".to_owned())), + "{seen:?}" + ); + assert!( + seen.iter() + .any(|(p, h)| p == "/healthz" && h == "localhost"), + "{seen:?}" + ); + } } From 1f5e4a59a0e645df9efb112f9683ffce5e65e02d Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 21:04:59 +0100 Subject: [PATCH 10/45] [control] UI socket, tests first: with [ui] socket the proof signs in only over the 0660 socket (refused over TCP even when right), and a route may name a socket only for the admin host and only control's own (red: no socket yet) --- crates/control/tests/ui_auth.rs | 147 ++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) diff --git a/crates/control/tests/ui_auth.rs b/crates/control/tests/ui_auth.rs index f9794ef..17a6979 100644 --- a/crates/control/tests/ui_auth.rs +++ b/crates/control/tests/ui_auth.rs @@ -238,6 +238,153 @@ mod unix { ); } + // ---------------------------------------------------------------- G14 option b (phase 4) + + /// Control with `[ui] socket`: the UI comes in on a Unix socket in a directory only the + /// ianitor group can use; the loopback port stays for API tokens (scripts, the CLI). + async fn socket_env(site: String, ui_host: &str) -> (Env, std::path::PathBuf) { + let mut env = Env::new(EnvSpec { + site, + ..Default::default() + }) + .await; + std::fs::write( + env.dir.join("creds/ui-proof"), + format!( + "{PROOF} +" + ), + ) + .unwrap(); + let sock = env.dir.join("ui.sock"); + let text = std::fs::read_to_string(env.config_path()).unwrap() + + &format!( + " +[ui] +hostname = \"{ui_host}\" +proof_credential = \"ui-proof\" +socket = \"{}\" +", + sock.display() + ); + std::fs::write(env.config_path(), text).unwrap(); + env.start_control(None); + for _ in 0..100 { + if sock.exists() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + assert!( + sock.exists(), + "no UI socket: +{}", + env.control_log() + ); + (env, sock) + } + + async fn over_socket(sock: &std::path::Path, headers: &[(&str, &str)]) -> (u16, String) { + let mut req = Req::get("ui.test", "/api/v1/overview"); + for (n, v) in headers { + req = req.header(n, v); + } + let r = client::unix(sock, &req).await.unwrap(); + (r.status, r.text()) + } + + /// The per-boot proof alone no longer signs anyone in: off the socket it is refused even + /// when it is right, so a local process that learned it (say, by listening on control's + /// port while control restarted) gets nothing; on the socket, which only edge and Caddy + /// (group ianitor) can open, it works as before. + #[tokio::test(flavor = "multi_thread")] + async fn with_a_ui_socket_the_proof_counts_only_on_the_socket() { + use std::os::unix::fs::PermissionsExt; + let (env, sock) = socket_env(String::new(), "ui.test").await; + let mode = std::fs::metadata(&sock).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o660, "owner and group only"); + + let signed = [("Remote-User", "mark"), ("X-Ianitor-Proof", PROOF)]; + let r = env + .call_with("GET", "/api/v1/overview", &signed, None) + .await; + assert_eq!(r.status, 401, "the right proof over TCP: {}", r.text); + assert_eq!(r.json["error"]["code"], "ui.no_proof", "{}", r.text); + assert!(!env.control_log().contains("by mark")); + + let (status, text) = over_socket(&sock, &signed).await; + assert_eq!(status, 200, "{text}"); + // The socket does not replace the proof: without it, a Remote-User is still refused. + let (status, text) = over_socket(&sock, &[("Remote-User", "mark")]).await; + assert_eq!(status, 401, "{text}"); + let (status, text) = over_socket( + &sock, + &[("Remote-User", "mark"), ("X-Ianitor-Proof", "guess")], + ) + .await; + assert_eq!(status, 401, "{text}"); + + // API tokens keep working on the loopback port. + let r = env.call("GET", "/api/v1/overview", None).await; + assert_eq!(r.status, 200, "{}", r.text); + } + + /// A route file may name a socket only for the admin host, and only control's own. + #[tokio::test(flavor = "multi_thread")] + async fn a_socket_upstream_is_only_for_the_admin_host_and_controls_own_socket() { + let auth = MockAuthelia::start().await; + let site = format!( + "secrets = [\"ui-proof\"] +[forward_auth] +url = \"{}\" +", + auth.url() + ); + let (env, sock) = socket_env(site, "a.test").await; + for (hostname, upstream) in [ + ("b.test", format!("unix:{}", sock.display())), + ("a.test", "unix:/run/docker.sock".to_owned()), + ] { + let host = json!({"host": { + "hostname": hostname, "upstreams": [upstream], + "tls": "domi", "auth": "forward-auth", + }}); + let r = env.call("POST", "/api/v1/hosts", Some(host)).await; + assert_eq!(r.status, 422, "{hostname} {upstream}: {}", r.text); + assert_eq!( + r.json["errors"][0]["code"], "host.upstream.unix_socket", + "{}", + r.text + ); + } + + // The admin host on control's socket: through edge, Authelia decides, the UI gets in. + let host = json!({"host": { + "hostname": "a.test", "upstreams": [format!("unix:{}", sock.display())], + "tls": "domi", "auth": "forward-auth", + "request_headers": [{"action": "set", "name": "X-Ianitor-Proof", "secret": "ui-proof"}] + }}); + let rec = env.apply("POST", "/api/v1/hosts", Some(host)).await; + assert_eq!( + rec["state"], + "kept", + "{rec} +{}", + env.control_log() + ); + let edge = env.edge.as_ref().unwrap(); + let r = client::https( + edge.https, + "a.test", + env.ca.roots(), + &Req::get("a.test", "/api/v1/overview").header("cookie", "authelia_session=good"), + ) + .await + .unwrap(); + assert_eq!(r.status, 200, "{}", r.text()); + assert!(r.text().contains("\"hosts\""), "{}", r.text()); + } + /// QC: signed in at Authelia (alice) but the client also sends a proof guess: edge must /// replace, not append, the proof; and Remote-User must be Authelia's. #[tokio::test(flavor = "multi_thread")] From d249bcf9f2c086a0e2dafdc3172fef8e328aeb79 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 21:06:56 +0100 Subject: [PATCH 11/45] [control] UI socket: with [ui] socket control also serves the API on a 0660 Unix socket and trusts the proof only there; a socket upstream is refused unless it is the admin host on control's own socket; probes under Caddy reach it too --- crates/control/src/api/mod.rs | 15 ++++- crates/control/src/caddy_link.rs | 15 +++++ crates/control/src/config.rs | 14 ++++ crates/control/src/dev.rs | 1 + crates/control/src/engine.rs | 35 ++++++++++ crates/control/src/engine/caddy_apply.rs | 5 +- crates/control/src/lib.rs | 83 ++++++++++++++++++++++-- 7 files changed, 160 insertions(+), 8 deletions(-) diff --git a/crates/control/src/api/mod.rs b/crates/control/src/api/mod.rs index c63c84f..7391503 100644 --- a/crates/control/src/api/mod.rs +++ b/crates/control/src/api/mod.rs @@ -345,6 +345,10 @@ pub(crate) fn host_allowed(ctl: &Control, headers: &HeaderMap) -> bool { .any(|a| a.eq_ignore_ascii_case(host)) } +/// Marks a request that came in on control's UI socket (`[ui] socket`). +#[derive(Debug, Clone, Copy)] +pub struct ViaUiSocket; + enum UiIdentity { /// No sign-in headers: an API-token request. None, @@ -356,7 +360,7 @@ enum UiIdentity { User(String, String), } -fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity { +fn ui_identity(ctl: &Control, headers: &HeaderMap, via_socket: bool) -> UiIdentity { let names_user = headers.keys().any(|k| k.as_str().starts_with("remote-")); let proof = headers.get("x-ianitor-proof"); if !names_user && proof.is_none() { @@ -366,7 +370,11 @@ fn ui_identity(ctl: &Control, headers: &HeaderMap) -> UiIdentity { (Some(p), Some(want)) => crate::util::ct_eq(p.as_bytes(), want), _ => false, }; - if !ok { + // With a UI socket (G14 option b) the proof counts only there: the loopback port is open + // to every local process, and one that learned the proof (say, by taking control's port + // while it restarted and reading what edge sent) must not be able to use it. + let socket_only = ctl.cfg.ui.as_ref().is_some_and(|u| u.socket.is_some()); + if !ok || (socket_only && !via_socket) { return UiIdentity::Forged; } let users: Vec<&HeaderValue> = headers.get_all("remote-user").iter().collect(); @@ -428,7 +436,8 @@ async fn guard(State(st): State>, mut req: Request, next: Next) -> // The web UI, through edge on the admin host (docs/api.md, "Sign-in"): only a request // with the per-boot proof edge adds is identified by its Remote-User. Any other // request that names a user is refused, so a local process cannot claim to be one. - match ui_identity(&st.ctl, req.headers()) { + let via_socket = req.extensions().get::().is_some(); + match ui_identity(&st.ctl, req.headers(), via_socket) { UiIdentity::None => {} UiIdentity::Forged => { return Err(ApiError::new( diff --git a/crates/control/src/caddy_link.rs b/crates/control/src/caddy_link.rs index 4dcc777..3598194 100644 --- a/crates/control/src/caddy_link.rs +++ b/crates/control/src/caddy_link.rs @@ -315,6 +315,21 @@ pub async fn probe_upstream( "GET {path} HTTP/1.1\r\nHost: {host_header}\r\nUser-Agent: ianitor-health\r\nConnection: close\r\n\r\n" ); let run = async { + if let Some(path) = u.unix_path() { + // A socket upstream (the admin host on control's own UI socket): plain HTTP. + #[cfg(unix)] + { + let s = tokio::net::UnixStream::connect(path) + .await + .map_err(|e| io_kind(&e))?; + return ask(s, req.as_bytes()).await.map_err(|e| io_kind(&e)); + } + #[cfg(not(unix))] + { + let _ = path; + return Err("refused"); + } + } let tcp = match tokio::net::TcpStream::connect(u.authority()).await { Ok(t) => t, Err(e) => return Err(io_kind(&e)), diff --git a/crates/control/src/config.rs b/crates/control/src/config.rs index 04a4af6..8167c98 100644 --- a/crates/control/src/config.rs +++ b/crates/control/src/config.rs @@ -195,6 +195,13 @@ impl Config { } pub fn check(&self) -> Result<(), ConfigError> { + if let Some(s) = self.ui.as_ref().and_then(|u| u.socket.as_ref()) + && (!s.is_absolute() || s.as_os_str().len() > 100) + { + return Err(ConfigError::Invalid( + "ui.socket must be an absolute path of at most 100 characters".into(), + )); + } if !self.listen.ip().is_loopback() { return Err(ConfigError::Invalid(format!( "listen = {} is not a loopback address; ianitor-control only listens on 127.0.0.1 or ::1", @@ -346,6 +353,13 @@ pub struct UiConfig { pub proof_credential: Option, /// The built web UI (served at `/`). pub static_dir: Option, + /// A Unix socket (mode 0660; its directory only for the ianitor group) on which control + /// also serves the API for the admin host (G14 option b). With it, the proof signs in only + /// on this socket; over the loopback port, which any local process can reach (or take while + /// control restarts), only API tokens work. The admin host's upstream is then + /// `unix:`. + #[serde(default)] + pub socket: Option, /// Authelia's logout address (e.g. `https://auth.example/logout`), shown as "Sign out". #[serde(default)] pub logout_url: Option, diff --git a/crates/control/src/dev.rs b/crates/control/src/dev.rs index 0c157dd..1ae10c2 100644 --- a/crates/control/src/dev.rs +++ b/crates/control/src/dev.rs @@ -169,6 +169,7 @@ pub async fn run(args: &[String]) -> Result<(), String> { proof_credential: None, static_dir: Some(PathBuf::from(d)), logout_url: None, + socket: None, }), engine: None, }; diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs index e49bf61..2949a36 100644 --- a/crates/control/src/engine.rs +++ b/crates/control/src/engine.rs @@ -680,6 +680,41 @@ impl Control { })?; // The UI proof belongs to the [ui] host only (core already demands forward-auth for it). let ui_host = self.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref()); + // A socket upstream likewise: only the [ui] host, and only control's own UI socket (a + // route file must not point edge at any other socket on the machine). + let ui_socket = self + .cfg + .ui + .as_ref() + .and_then(|u| u.socket.as_deref()) + .and_then(|p| p.to_str()); + for h in model.hosts() { + for (i, u) in h.upstreams.iter().enumerate() { + let Some(path) = u.unix_path() else { continue }; + if ui_host == Some(h.hostname.as_str()) && ui_socket == Some(path) { + continue; + } + let p = messages::params([ + ("hostname", h.hostname.to_string()), + ("url", u.to_string()), + ]); + let fe = FieldError { + code: "host.upstream.unix_socket".into(), + message: message("host.upstream.unix_socket", &p), + field: Some(format!("upstreams[{i}]")), + params: p.clone(), + detail: None, + }; + return Err(Fail { + status: 422, + reason: reason( + "apply.failed.validation", + messages::params([("first_error", fe.message.clone())]), + ), + errors: vec![fe], + }); + } + } for h in model.hosts() { let proof = h.request_headers.iter().any(|r| { matches!(r, ianitor_core::HeaderRule::Set { value: ianitor_core::HeaderValue::Secret(s), .. } if s.as_str() == ianitor_core::UI_PROOF_SECRET) diff --git a/crates/control/src/engine/caddy_apply.rs b/crates/control/src/engine/caddy_apply.rs index 9b61bee..cbdeb2f 100644 --- a/crates/control/src/engine/caddy_apply.rs +++ b/crates/control/src/engine/caddy_apply.rs @@ -123,7 +123,10 @@ impl Control { async fn probe_host(hostname: &str, r: &Rule) -> Vec<(String, caddy_link::UpstreamProbe)> { let mut out = Vec::new(); for u in &r.upstreams { - let host_header = if r.has_check { + let host_header = if r.has_check && u.is_unix() { + // As edge: a socket has no authority to name. + "localhost".to_owned() + } else if r.has_check { u.authority() } else { hostname.to_owned() diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 65d3279..cc841b7 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -37,6 +37,7 @@ pub async fn serve( ) -> Result<(), String> { cfg.check().map_err(|e| e.to_string())?; let listen = cfg.listen; + let ui_socket = cfg.ui.as_ref().and_then(|u| u.socket.clone()); let ctl = Control::open(cfg).await?; tokio::spawn(ctl.clone().worker()); tokio::spawn(ctl.clone().health_poller()); @@ -50,14 +51,88 @@ pub async fn serve( .await .map_err(|e| format!("cannot listen on {listen}: {e}"))?; log::info!(target: "ianitor::control", "API on http://{listen}/api/v1"); - axum::serve(listener, app) - .with_graceful_shutdown(shutdown) - .await - .map_err(|e| e.to_string())?; + + // One shutdown for both listeners. + let (stop_tx, stop_rx) = tokio::sync::watch::channel(false); + tokio::spawn(async move { + shutdown.await; + let _ = stop_tx.send(true); + }); + let stopped = |mut rx: tokio::sync::watch::Receiver| async move { + let _ = rx.wait_for(|s| *s).await; + }; + let tcp = axum::serve(listener, app.clone()).with_graceful_shutdown(stopped(stop_rx.clone())); + match ui_socket { + None => tcp.await.map_err(|e| e.to_string())?, + Some(path) => { + let ui = ui_listener(&path)?; + log::info!(target: "ianitor::control", "UI API on unix:{}", path.display()); + let ui_app = app.layer(axum::Extension(api::ViaUiSocket)); + let ui = serve_ui(ui, ui_app, stopped(stop_rx)); + let (a, b) = tokio::join!(std::future::IntoFuture::into_future(tcp), ui); + a.map_err(|e| e.to_string())?; + b?; + } + } drop(ctl); Ok(()) } +/// Control's UI socket: a stale socket file from an earlier run is replaced; the new one is +/// 0660 (owner and group: edge and Caddy are in the ianitor group). Its directory is the +/// real fence: only the ianitor group may enter it, so no other user can connect or put a +/// socket of their own in its place. +#[cfg(unix)] +fn ui_listener(path: &std::path::Path) -> Result { + use std::os::unix::fs::{FileTypeExt, PermissionsExt}; + if let Ok(m) = std::fs::symlink_metadata(path) { + if !m.file_type().is_socket() { + return Err(format!( + "{} exists and is not a socket; not replacing it", + path.display() + )); + } + std::fs::remove_file(path).map_err(|e| format!("cannot remove {}: {e}", path.display()))?; + } + let l = tokio::net::UnixListener::bind(path) + .map_err(|e| format!("cannot listen on {}: {e}", path.display()))?; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o660)) + .map_err(|e| format!("cannot set the mode of {}: {e}", path.display()))?; + Ok(l) +} + +#[cfg(unix)] +async fn serve_ui( + l: tokio::net::UnixListener, + app: axum::Router, + stop: impl std::future::Future + Send + 'static, +) -> Result<(), String> { + axum::serve(l, app) + .with_graceful_shutdown(stop) + .await + .map_err(|e| e.to_string()) +} + +#[cfg(not(unix))] +struct NoUnixListener; + +#[cfg(not(unix))] +fn ui_listener(path: &std::path::Path) -> Result { + Err(format!( + "ui.socket {}: a Unix socket needs a Unix system", + path.display() + )) +} + +#[cfg(not(unix))] +async fn serve_ui( + _l: NoUnixListener, + _app: axum::Router, + _stop: impl std::future::Future + Send + 'static, +) -> Result<(), String> { + Ok(()) +} + /// Wait for Ctrl-C or SIGTERM. pub async fn stop_signal() { #[cfg(unix)] From 1358649550cc0042ead01507acd1a08f0462f9a4 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 21:09:24 +0100 Subject: [PATCH 12/45] [deploy] Sockets: services.ianitor.edge.proxySocket (Caddy beside Ianitor reaches edge on a 0660 socket of the ianitor-proxy group) and ui.socket (control's UI socket, the proof trusted only there); the Configuration_Server patch, beside-caddy.md and api.md follow; a VM test for both --- deploy/nixos/module.nix | 61 +++++++++++++++++++++++--- deploy/nixos/tests/default.nix | 50 +++++++++++++++++++++ docs/api.md | 17 ++++--- docs/deploy/beside-caddy.md | 28 ++++++------ docs/deploy/configuration-server.patch | 30 ++++++------- 5 files changed, 146 insertions(+), 40 deletions(-) diff --git a/deploy/nixos/module.nix b/deploy/nixos/module.nix index 34699d1..c10a36a 100644 --- a/deploy/nixos/module.nix +++ b/deploy/nixos/module.nix @@ -20,6 +20,14 @@ let pkg = cfg.package; stateRoot = "/var/lib/ianitor"; runProof = "/run/ianitor-proof"; + # Control's UI socket (G14 option b): its directory is control's RuntimeDirectory, 0750 + # ianitor-control:ianitor, so only the ianitor group (edge, Caddy) can reach it and no other + # user can put a socket there while control restarts. + uiSocket = "/run/ianitor-control/ui.sock"; + # The front proxy's socket (Caddy beside Ianitor): its directory is setgid ianitor-proxy, so + # the socket either engine makes there belongs to that group. + proxyDir = "/run/ianitor-proxy"; + proxySocket = "${proxyDir}/edge.sock"; toml = pkgs.formats.toml { }; isStore = p: lib.hasPrefix builtins.storeDir (toString p); @@ -42,7 +50,7 @@ let access_log = "/var/log/ianitor/access.log"; caddy_credentials_dir = "/run/credentials/caddy-fallback.service"; trusted_proxies = cfg.edge.trustedProxies; - }; + } // lib.optionalAttrs cfg.edge.proxySocket.enable { proxy_socket = proxySocket; }; controlToml = toml.generate "control.toml" ( { @@ -78,6 +86,7 @@ let static_dir = "${pkg}/share/ianitor/web"; } // lib.optionalAttrs (cfg.ui.hostname != null) { hostname = cfg.ui.hostname; } + // lib.optionalAttrs cfg.ui.socket { socket = uiSocket; } // lib.optionalAttrs (cfg.ui.logoutUrl != null) { logout_url = cfg.ui.logoutUrl; }; engine = { file = "${stateRoot}/engine"; @@ -147,11 +156,24 @@ in default = false; description = "Open edge's two ports in the firewall."; }; + proxySocket = { + enable = mkEnableOption '' + a Unix socket (${proxySocket}, 0660, group ianitor-proxy) on which edge (or the Caddy + fallback) serves the HTTPS hosts in plain HTTP to a front proxy that terminated TLS, + such as Caddy beside Ianitor. Only that group can connect, so its X-Forwarded-For is + believed; no loopback TCP port is involved''; + users = mkOption { + type = types.listOf types.str; + default = [ ]; + example = [ "caddy" ]; + description = "The front proxy's users, added to the ianitor-proxy group so they can connect."; + }; + }; trustedProxies = mkOption { type = types.listOf types.str; default = [ ]; example = [ "127.0.0.1" ]; - description = "Proxies in front of edge whose X-Forwarded-For names the client (beside Caddy: 127.0.0.1), for the share-link throttle and the access log. Off by default: on a loopback listener any local process could then claim any address (docs/deploy/beside-caddy.md)."; + description = "Proxies in front of edge whose X-Forwarded-For names the client, for the share-link throttle and the access log. Off by default: on a loopback listener any local process could then claim any address. Beside Caddy, use edge.proxySocket instead (docs/deploy/beside-caddy.md)."; }; }; @@ -229,6 +251,15 @@ in example = "ianitor.example"; description = "The admin host edge serves the UI on (a host in the routes repository with forward-auth and the X-Ianitor-Proof rule, docs/api.md)."; }; + socket = mkOption { + type = types.bool; + default = true; + description = '' + Serve the API for the admin host on ${uiSocket} as well, and trust the UI proof only + there (G14 option b): the admin host's upstream is then `unix:${uiSocket}`. Over the + loopback port, which every local process can reach, only API tokens work. + ''; + }; logoutUrl = mkOption { type = types.nullOr types.str; default = null; @@ -255,8 +286,19 @@ in # Only control (and Caddy itself) may reach Caddy's admin socket; edge is not in it. users.groups.ianitor-caddy-admin = { }; users.users.ianitor-control = { isSystemUser = true; group = "ianitor"; extraGroups = [ "ianitor-caddy-admin" ]; home = "${stateRoot}/control"; }; - users.users.ianitor-edge = { isSystemUser = true; group = "ianitor"; }; - users.users.caddy-fallback = { isSystemUser = true; group = "ianitor"; }; + users.users.ianitor-edge = { + isSystemUser = true; + group = "ianitor"; + extraGroups = lib.optional cfg.edge.proxySocket.enable "ianitor-proxy"; + }; + users.users.caddy-fallback = { + isSystemUser = true; + group = "ianitor"; + extraGroups = lib.optional cfg.edge.proxySocket.enable "ianitor-proxy"; + }; + users.groups.ianitor-proxy = mkIf cfg.edge.proxySocket.enable { + members = cfg.edge.proxySocket.users; + }; systemd.tmpfiles.rules = [ "d ${stateRoot} 0755 ianitor-control ianitor - -" @@ -268,7 +310,7 @@ in "d ${stateRoot}/caddy-state 0700 caddy-fallback ianitor - -" "f ${stateRoot}/engine 0644 ianitor-control ianitor - ${cfg.defaultEngine}" "d /var/log/ianitor 0770 ianitor-edge ianitor - -" - ]; + ] ++ lib.optional cfg.edge.proxySocket.enable "d ${proxyDir} 2770 root ianitor-proxy - -"; environment.systemPackages = [ pkg ]; # The non-secret config, so the CLI (token, pki) finds it: --config /etc/ianitor/control.toml. @@ -308,6 +350,9 @@ in ExecStopPost = "${pkg}/bin/ianitor-control caddy-revert --config ${controlToml}"; LoadCredential = loadCreds controlCreds ++ [ "ui-proof:${runProof}/ui-proof" ]; ReadWritePaths = [ stateRoot ]; + # The UI socket's directory: 0750, so the ianitor group may connect and nobody else. + RuntimeDirectory = "ianitor-control"; + RuntimeDirectoryMode = "0750"; Restart = "on-failure"; RestartSec = 2; }; @@ -334,7 +379,8 @@ in LoadCredential = loadCreds edgeCreds ++ [ "ui-proof:${runProof}/ui-proof" ]; RuntimeDirectory = "ianitor-edge"; RuntimeDirectoryMode = "0750"; - ReadWritePaths = [ "${stateRoot}/edge-state" "/var/log/ianitor" ]; + ReadWritePaths = [ "${stateRoot}/edge-state" "/var/log/ianitor" ] + ++ lib.optional cfg.edge.proxySocket.enable proxyDir; AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ]; CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ]; # The first start may come before control has written edge.json. @@ -366,7 +412,8 @@ in LoadCredential = loadCreds cfg.credentials ++ [ "ui-proof:${runProof}/ui-proof" ]; RuntimeDirectory = "caddy-fallback"; RuntimeDirectoryMode = "0750"; - ReadWritePaths = [ "${stateRoot}/caddy-state" "/var/log/ianitor" ]; + ReadWritePaths = [ "${stateRoot}/caddy-state" "/var/log/ianitor" ] + ++ lib.optional cfg.edge.proxySocket.enable proxyDir; AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ]; CapabilityBoundingSet = [ "CAP_NET_BIND_SERVICE" ]; # Go needs W^X for its runtime on some platforms. diff --git a/deploy/nixos/tests/default.nix b/deploy/nixos/tests/default.nix index f239d08..c0e06c8 100644 --- a/deploy/nixos/tests/default.nix +++ b/deploy/nixos/tests/default.nix @@ -226,6 +226,56 @@ in server.fail("find /var/lib/ianitor -name 'domi-root.key' | grep -q .") ''; + # G14 option b and the proxy socket (phase 4): another local user can neither open control's + # UI socket nor use the proof over the loopback port; the front proxy's socket is for the + # ianitor-proxy group only. + vm-sockets = pkgs.testers.runNixOSTest { + name = "ianitor-sockets"; + nodes.server = { + imports = [ server ]; + services.ianitor.edge.proxySocket = { enable = true; users = [ "front" ]; }; + services.ianitor.ui.hostname = "ui.test"; + users.users.front.isNormalUser = true; + users.users.mallory.isNormalUser = true; + }; + testScript = helpers + '' + start_all() + t = setup(server) + install_intermediate(server, t) + server.succeed("test -S /run/ianitor-control/ui.sock") + assert server.succeed("stat -c %a /run/ianitor-control/ui.sock").strip() == "660" + assert server.succeed("stat -c %a /run/ianitor-control").strip() == "750" + # Another local user cannot reach the UI socket ... + server.fail("runuser -u mallory -- curl -sf -m 5 --unix-socket /run/ianitor-control/ui.sock http://localhost/api/v1/overview") + # ... nor sign in over the loopback port, even with the real proof (read here as root). + proof = server.succeed("cat /run/ianitor-proof/ui-proof").strip() + code = server.succeed( + "runuser -u mallory -- curl -s -o /dev/null -w '%{http_code}' -H 'Remote-User: mallory' " + + "-H 'X-Ianitor-Proof: " + proof + "' http://127.0.0.1:7878/api/v1/overview" + ).strip() + assert code == "401", code + # The same over the socket, as edge (group ianitor): signed in. + code = server.succeed( + "runuser -u ianitor-edge -- curl -s -o /dev/null -w '%{http_code}' -H 'Host: ui.test' " + + "-H 'Remote-User: mark' -H 'X-Ianitor-Proof: " + proof + "' " + + "--unix-socket /run/ianitor-control/ui.sock http://ui.test/api/v1/overview" + ).strip() + assert code == "200", code + + # The front proxy's socket: the front user may connect, mallory may not. + r = api(server, t, "POST", "/hosts", {"host": { + "hostname": "app.test", "upstreams": ["http://127.0.0.1:8000"], "tls": "domi", "auth": "none"}}) + assert wait_apply(server, t, r["apply"]["id"])["state"] == "kept" + server.wait_until_succeeds("test -S /run/ianitor-proxy/edge.sock") + assert server.succeed("stat -c '%a %G' /run/ianitor-proxy/edge.sock").strip() == "660 ianitor-proxy" + code = server.succeed( + "runuser -u front -- curl -s -o /dev/null -w '%{http_code}' --unix-socket /run/ianitor-proxy/edge.sock http://app.test/" + ).strip() + assert code == "200", code + server.fail("runuser -u mallory -- curl -sf -m 5 --unix-socket /run/ianitor-proxy/edge.sock http://app.test/") + ''; + }; + vm-control-loopback = pkgs.testers.runNixOSTest { name = "ianitor-control-loopback"; nodes.server = server; diff --git a/docs/api.md b/docs/api.md index 8674ae6..a5751cb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -243,7 +243,7 @@ a host in the routes repository with forward-auth to Authelia and one header rul ```toml # hosts/ianitor.example.toml hostname = "ianitor.example" -upstreams = ["http://127.0.0.1:7878"] +upstreams = ["unix:/run/ianitor-control/ui.sock"] # [ui] socket (the NixOS module's default) tls = "domi" auth = "forward-auth" @@ -266,11 +266,18 @@ secret = "ui-proof" # listed in ianitor.toml: secrets = ["ui-proof"] - Any request with a `Remote-*` header but without the proof is `401 ui.no_proof`, so a local process on loopback cannot claim a user; the proof without `Remote-User` is `401 ui.no_user`. Tested in `crates/control/tests/ui_auth.rs`, including end to end through edge and a mock Authelia. +- **The UI socket (G14 option b, phase 4).** With `[ui] socket = "/run/ianitor-control/ui.sock"` + (the NixOS module sets it; `services.ianitor.ui.socket`, default on), control also serves the API + on that Unix socket, mode 0660, in its runtime directory (0750, ianitor-control:ianitor): only + the ianitor group (edge, caddy-fallback) can connect, and no other user can create a socket + there. The proof then counts **only on the socket**: over the loopback port it is + `401 ui.no_proof` even when it is right. Why: any local process can reach 127.0.0.1:7878, and + one that took that port while control restarted would receive edge's requests, proof and all. + The admin host's upstream is `unix:/run/ianitor-control/ui.sock`; control refuses a socket + upstream on any other host, and any socket other than its own (`host.upstream.unix_socket`). + The loopback port stays for API tokens (scripts, the CLI, the trial's SSH tunnel). - `[ui] logout_url` (Authelia's logout address) becomes `overview.site.auth_logout_url`, the UI's - "Sign out". A Unix socket only edge can reach is Phase 4 hardening (decision Q2). - -Why not the Unix socket now: edge's upstreams are `host:port` in the schema; a socket upstream is a -schema and compiler change in both engines, and the proof header needs neither. + "Sign out". ## Certificates (the Domi CA) diff --git a/docs/deploy/beside-caddy.md b/docs/deploy/beside-caddy.md index 1aa6e03..e0949a7 100644 --- a/docs/deploy/beside-caddy.md +++ b/docs/deploy/beside-caddy.md @@ -24,22 +24,24 @@ cut-over. This is **prepared, not applied**: Mark runs every command below himse ## The shape ```text -visitor ── Caddy :443 (as today) ── https://127.0.0.1:18443 Ianitor edge ── the app +visitor ── Caddy :443 (as today) ── unix:/run/ianitor-proxy/edge.sock ── Ianitor edge ── the app ``` -- Ianitor edge listens on **loopback only** (127.0.0.1:18080 and :18443), so D-21a holds: - nothing new is reachable from the LAN. Control is on 127.0.0.1:7878. -- Caddy keeps the public side for the two names and hands them to Ianitor over TLS; Ianitor - serves them with Domi certificates, which Caddy checks against the Domi root (a public file). +- Caddy reaches edge on edge's **proxy socket** (`services.ianitor.edge.proxySocket`, phase 4): + `/run/ianitor-proxy/edge.sock`, mode 0660, in a setgid directory of the group `ianitor-proxy`, + whose only members are edge, the Caddy fallback and Caddy (`proxySocket.users = [ "caddy" ]`). + Edge serves the HTTPS hosts there in plain HTTP (Caddy terminated TLS) and **believes the + X-Forwarded-For Caddy sends**, so the visit log and the share-link throttle see the visitor. + No other local user can connect, so none can claim an address; no loopback TCP port is + involved, and `trustedProxies` stays off. The Caddy fallback listens on the same socket + (compile option `proxy_socket`, a third Caddy server with `trusted_proxies_unix`), so an engine + switch keeps the two hosts reachable through Caddy. +- Edge's TCP listeners stay on **loopback only** (127.0.0.1:18080 and :18443), so D-21a holds: + nothing new is reachable from the LAN. Control is on 127.0.0.1:7878 (API tokens) and on its UI + socket `/run/ianitor-control/ui.sock` (the admin host, [../api.md](../api.md), "Sign-in"). - Every other host is untouched. Rollback: revert the patch and switch (below). -- Visitor addresses: Ianitor sees every visit coming from 127.0.0.1 (Caddy), so the share-link - throttle counts all visitors together and the visit log shows 127.0.0.0. The option - `services.ianitor.edge.trustedProxies = [ "127.0.0.1" ]` would make edge believe Caddy's - `X-Forwarded-For` instead, but edge listens on a TCP port on loopback that **any local user or - process can reach**, and any of them could then claim any address. It stays **off** for the - trial (the two hosts have no share links and no visit log); turn it on only on a machine where - every local account is trusted. (A Unix-socket listener for edge, which Caddy alone could reach, - is the proper fix; not built yet.) +- Until phase 4 this hop was TLS to 127.0.0.1:18443 with Domi certificates, and edge saw every + visitor as 127.0.0.1. The socket replaces it; the Domi root is no longer needed by Caddy. ## The patch diff --git a/docs/deploy/configuration-server.patch b/docs/deploy/configuration-server.patch index a003568..bf6c8e1 100644 --- a/docs/deploy/configuration-server.patch +++ b/docs/deploy/configuration-server.patch @@ -27,29 +27,26 @@ diff --git a/hyperv-infra/modules/caddy.nix b/hyperv-infra/modules/caddy.nix index e79f6b2..6fb5a49 100644 --- a/hyperv-infra/modules/caddy.nix +++ b/hyperv-infra/modules/caddy.nix -@@ -225,6 +225,21 @@ in +@@ -225,6 +225,18 @@ in Referrer-Policy "strict-origin-when-cross-origin" } ''; + # The Ianitor trial (modules/ianitor.nix): Caddy keeps the public side and hands the request -+ # to Ianitor edge on loopback, over TLS with a Domi certificate it checks against the Domi -+ # root. Host and SNI are the visitor's name. ++ # to Ianitor edge on its proxy socket, /run/ianitor-proxy/edge.sock (0660, group ++ # ianitor-proxy, which Caddy joins and no other local user is in). Edge believes the ++ # X-Forwarded-For Caddy sends there, so the visit log and the share-link throttle see the ++ # visitor; no loopback TCP port is involved. Host is the visitor's name. + viaIanitor = host: { + extraConfig = '' + tls internal + ${secureHeaders "SAMEORIGIN"} -+ reverse_proxy https://127.0.0.1:18443 { -+ transport http { -+ tls_server_name ${host} -+ tls_trusted_ca_certs ${../ianitor/domi-root.crt} -+ } -+ } ++ reverse_proxy unix//run/ianitor-proxy/edge.sock + ''; + }; simple = { frame ? "SAMEORIGIN", upstream }: { extraConfig = '' tls internal -@@ -252,7 +267,11 @@ in +@@ -252,7 +264,11 @@ in # flowers - was `localhost:8085`, which is PRODUCTION's port. On the mirror the app is # published on 127.0.0.1:8092 and fronted by nginx on 8091, matching production's topology # (nginx in front, not Caddy straight to the container). Proxying to 8085 reached nothing. @@ -67,7 +64,7 @@ new file mode 100644 index 0000000..cd23016 --- /dev/null +++ b/hyperv-infra/modules/ianitor.nix -@@ -0,0 +1,49 @@ +@@ -0,0 +1,52 @@ +{ config, lib, inputs, ... }: + +# Ianitor beside Caddy (Ianitor ROADMAP §1.12, Phase 3): two low-risk hosts, flowers and esp32, @@ -76,11 +73,12 @@ index 0000000..cd23016 +# Shape, chosen to keep decision D-21a ("Caddy is the only thing on 80/443 and the only service +# exposed beyond loopback"): +# -+# visitor -> Caddy :443 (tls as today) -> https://127.0.0.1:18443 Ianitor edge -> the app ++# visitor -> Caddy :443 (tls as today) -> unix socket /run/ianitor-proxy/edge.sock -> Ianitor edge -> the app +# -+# Ianitor edge listens on loopback only (18080/18443) and terminates TLS with a Domi certificate; -+# Caddy trusts the Domi root (a public certificate, ianitor/domi-root.crt) for that hop. Control -+# listens on 127.0.0.1:7878. Nothing new is reachable from the LAN. ++# Ianitor edge serves Caddy on its proxy socket (group ianitor-proxy: Caddy is the only member), ++# and believes the X-Forwarded-For Caddy sends there. Its TCP listeners stay on loopback only ++# (18080/18443, Domi certificates). Control listens on 127.0.0.1:7878 for API tokens and on its ++# UI socket for the admin host. Nothing new is reachable from the LAN. +# +# Secrets come from sops-nix (paths under /run/secrets, never the store); the module asserts it. +# Rollback: remove this import and the two `viaIanitor` lines in caddy.nix, nixos-rebuild switch. @@ -100,6 +98,8 @@ index 0000000..cd23016 + httpListen = "127.0.0.1:18080"; + httpsListen = "127.0.0.1:18443"; + openFirewall = false; ++ # Caddy reaches edge here; only Caddy joins the socket's group. ++ proxySocket = { enable = true; users = [ "caddy" ]; }; + }; + control.listen = "127.0.0.1:7878"; + shareLinkKeyFile = config.sops.secrets."ianitor/share-link-key".path; From 08e24e5d40f1bd026219464b6f7f217a0ea9afb6 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 21:17:29 +0100 Subject: [PATCH 13/45] [tests] Fuzz: cargo-fuzz targets for route files, header rules, share tokens, path_within and the CA's PEM/CSR parsing (tests/fuzz), a bounded run script that saves any crash as a hex regression, and every seed and saved crash replayed in cargo test --- Cargo.lock | 9 + Cargo.toml | 11 +- tests/fuzz/Cargo.toml | 16 ++ tests/fuzz/fuzz/Cargo.toml | 58 ++++ tests/fuzz/fuzz/fuzz_targets/header_rules.rs | 9 + tests/fuzz/fuzz/fuzz_targets/path_within.rs | 9 + tests/fuzz/fuzz/fuzz_targets/pki_pem.rs | 9 + tests/fuzz/fuzz/fuzz_targets/routes.rs | 9 + tests/fuzz/fuzz/fuzz_targets/share_token.rs | 9 + tests/fuzz/run.sh | 66 +++++ tests/fuzz/seeds/header_rules/proof | 5 + tests/fuzz/seeds/header_rules/set-and-remove | 7 + tests/fuzz/seeds/header_rules/values | 8 + tests/fuzz/seeds/path_within/dots | 1 + tests/fuzz/seeds/path_within/encoded | 1 + tests/fuzz/seeds/path_within/lookalike | 1 + tests/fuzz/seeds/path_within/plain | 1 + tests/fuzz/seeds/pki_pem/cert | 11 + tests/fuzz/seeds/pki_pem/csr | 7 + tests/fuzz/seeds/pki_pem/truncated | 4 + tests/fuzz/seeds/pki_pem/two-certs | 22 ++ tests/fuzz/seeds/routes/bad-path | 2 + tests/fuzz/seeds/routes/everything | 18 ++ tests/fuzz/seeds/routes/forward-auth | 11 + tests/fuzz/seeds/routes/plain | 4 + tests/fuzz/seeds/share_token/garbage-token | 1 + .../seeds/share_token/prefix-and-password | 1 + tests/fuzz/seeds/share_token/root | 1 + tests/fuzz/src/lib.rs | 263 ++++++++++++++++++ tests/fuzz/tests/regressions.rs | 100 +++++++ 30 files changed, 673 insertions(+), 1 deletion(-) create mode 100644 tests/fuzz/Cargo.toml create mode 100644 tests/fuzz/fuzz/Cargo.toml create mode 100644 tests/fuzz/fuzz/fuzz_targets/header_rules.rs create mode 100644 tests/fuzz/fuzz/fuzz_targets/path_within.rs create mode 100644 tests/fuzz/fuzz/fuzz_targets/pki_pem.rs create mode 100644 tests/fuzz/fuzz/fuzz_targets/routes.rs create mode 100644 tests/fuzz/fuzz/fuzz_targets/share_token.rs create mode 100755 tests/fuzz/run.sh create mode 100644 tests/fuzz/seeds/header_rules/proof create mode 100644 tests/fuzz/seeds/header_rules/set-and-remove create mode 100644 tests/fuzz/seeds/header_rules/values create mode 100644 tests/fuzz/seeds/path_within/dots create mode 100644 tests/fuzz/seeds/path_within/encoded create mode 100644 tests/fuzz/seeds/path_within/lookalike create mode 100644 tests/fuzz/seeds/path_within/plain create mode 100644 tests/fuzz/seeds/pki_pem/cert create mode 100644 tests/fuzz/seeds/pki_pem/csr create mode 100644 tests/fuzz/seeds/pki_pem/truncated create mode 100644 tests/fuzz/seeds/pki_pem/two-certs create mode 100644 tests/fuzz/seeds/routes/bad-path create mode 100644 tests/fuzz/seeds/routes/everything create mode 100644 tests/fuzz/seeds/routes/forward-auth create mode 100644 tests/fuzz/seeds/routes/plain create mode 100644 tests/fuzz/seeds/share_token/garbage-token create mode 100644 tests/fuzz/seeds/share_token/prefix-and-password create mode 100644 tests/fuzz/seeds/share_token/root create mode 100644 tests/fuzz/src/lib.rs create mode 100644 tests/fuzz/tests/regressions.rs diff --git a/Cargo.lock b/Cargo.lock index cabd477..6f37130 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1375,6 +1375,15 @@ dependencies = [ "x509-parser 0.18.1", ] +[[package]] +name = "ianitor-fuzz" +version = "0.1.0" +dependencies = [ + "ianitor-core", + "ianitor-edge", + "serde_json", +] + [[package]] name = "ianitor-testkit" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 2df601d..e479f4e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,15 @@ [workspace] resolver = "3" -members = ["crates/core", "crates/edge", "crates/control", "tests/diff", "tests/support"] +members = [ + "crates/core", + "crates/edge", + "crates/control", + "tests/diff", + "tests/fuzz", + "tests/support", +] +# cargo-fuzz's own workspace (libFuzzer flags): tests/fuzz/fuzz. +exclude = ["tests/fuzz/fuzz"] [workspace.package] version = "0.1.0" diff --git a/tests/fuzz/Cargo.toml b/tests/fuzz/Cargo.toml new file mode 100644 index 0000000..6a71e8b --- /dev/null +++ b/tests/fuzz/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "ianitor-fuzz" +description = "Fuzz target bodies (cargo-fuzz in fuzz/) and the replay of every saved input as a regression test." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +ianitor-core.workspace = true +ianitor-edge.workspace = true +serde_json.workspace = true + +[lints] +workspace = true diff --git a/tests/fuzz/fuzz/Cargo.toml b/tests/fuzz/fuzz/Cargo.toml new file mode 100644 index 0000000..52aa028 --- /dev/null +++ b/tests/fuzz/fuzz/Cargo.toml @@ -0,0 +1,58 @@ +# cargo-fuzz project (libFuzzer). Its own workspace: libfuzzer-sys needs the fuzzer flags, which +# the main workspace must not get. The target bodies live in ../src/lib.rs (crate ianitor-fuzz). +# Run: tests/fuzz/run.sh (bounded; any crash fails and is saved as a regression). +[package] +name = "ianitor-fuzz-targets" +version = "0.0.0" +publish = false +edition = "2024" +license = "MPL-2.0" + +[package.metadata] +cargo-fuzz = true + +[dependencies] +libfuzzer-sys = "0.4" +ianitor-fuzz = { path = ".." } + +[workspace] +members = ["."] + +[profile.release] +debug = 1 + +[[bin]] +name = "routes" +path = "fuzz_targets/routes.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "header_rules" +path = "fuzz_targets/header_rules.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "share_token" +path = "fuzz_targets/share_token.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "path_within" +path = "fuzz_targets/path_within.rs" +test = false +doc = false +bench = false + +[[bin]] +name = "pki_pem" +path = "fuzz_targets/pki_pem.rs" +test = false +doc = false +bench = false + diff --git a/tests/fuzz/fuzz/fuzz_targets/header_rules.rs b/tests/fuzz/fuzz/fuzz_targets/header_rules.rs new file mode 100644 index 0000000..e631326 --- /dev/null +++ b/tests/fuzz/fuzz/fuzz_targets/header_rules.rs @@ -0,0 +1,9 @@ +// 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/. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| ianitor_fuzz::header_rules(data)); diff --git a/tests/fuzz/fuzz/fuzz_targets/path_within.rs b/tests/fuzz/fuzz/fuzz_targets/path_within.rs new file mode 100644 index 0000000..d3966e1 --- /dev/null +++ b/tests/fuzz/fuzz/fuzz_targets/path_within.rs @@ -0,0 +1,9 @@ +// 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/. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| ianitor_fuzz::path_within(data)); diff --git a/tests/fuzz/fuzz/fuzz_targets/pki_pem.rs b/tests/fuzz/fuzz/fuzz_targets/pki_pem.rs new file mode 100644 index 0000000..1f4e7e8 --- /dev/null +++ b/tests/fuzz/fuzz/fuzz_targets/pki_pem.rs @@ -0,0 +1,9 @@ +// 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/. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| ianitor_fuzz::pki_pem(data)); diff --git a/tests/fuzz/fuzz/fuzz_targets/routes.rs b/tests/fuzz/fuzz/fuzz_targets/routes.rs new file mode 100644 index 0000000..ef51296 --- /dev/null +++ b/tests/fuzz/fuzz/fuzz_targets/routes.rs @@ -0,0 +1,9 @@ +// 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/. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| ianitor_fuzz::routes_toml(data)); diff --git a/tests/fuzz/fuzz/fuzz_targets/share_token.rs b/tests/fuzz/fuzz/fuzz_targets/share_token.rs new file mode 100644 index 0000000..d6415ce --- /dev/null +++ b/tests/fuzz/fuzz/fuzz_targets/share_token.rs @@ -0,0 +1,9 @@ +// 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/. + +#![no_main] + +use libfuzzer_sys::fuzz_target; + +fuzz_target!(|data: &[u8]| ianitor_fuzz::share_token(data)); diff --git a/tests/fuzz/run.sh b/tests/fuzz/run.sh new file mode 100755 index 0000000..ef7451d --- /dev/null +++ b/tests/fuzz/run.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# 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/. +# +# ROADMAP §5 layer 3: a bounded cargo-fuzz run of every target. Any crash fails the run, and the +# crashing input is copied to tests/fuzz/regressions//, where `cargo test` replays it +# (tests/fuzz/tests/regressions.rs) until it is fixed; commit it with the fix. +# +# tests/fuzz/run.sh [seconds per target, default 60] [target ...] +# +# Needs cargo-fuzz (`cargo install cargo-fuzz`, or nixpkgs#cargo-fuzz). With no nightly toolchain, +# RUSTC_BOOTSTRAP=1 lets a stable rustc take cargo-fuzz's flags. SANITIZER=address (default none) +# turns on ASan where the toolchain ships its runtime (rustup's x86_64 Linux does). The growing +# corpus lives outside the repository: $IANITOR_FUZZ_CORPUS (default ~/.cache/ianitor-fuzz). +# Linux only (libFuzzer); output and logs go to $CARGO_TARGET_DIR or tests/fuzz/fuzz/target. +set -euo pipefail + +secs=${1:-60} +shift || true +here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +targets=("$@") +if [ ${#targets[@]} -eq 0 ]; then + targets=(routes header_rules share_token path_within pki_pem) +fi +corpus_root=${IANITOR_FUZZ_CORPUS:-$HOME/.cache/ianitor-fuzz} +sanitizer=${SANITIZER:-none} +logs=${CARGO_TARGET_DIR:-$here/fuzz/target}/fuzz-logs +mkdir -p "$logs" + +toolchain=() +if cargo +nightly --version >/dev/null 2>&1; then + toolchain=(+nightly) +else + export RUSTC_BOOTSTRAP=1 +fi +cargo "${toolchain[@]}" fuzz --version >/dev/null + +cd "$here/fuzz" +status=0 +printf '%-14s %10s %8s %s\n' target runs seconds result +for t in "${targets[@]}"; do + corpus="$corpus_root/$t" + artifacts="$logs/artifacts/$t/" + mkdir -p "$corpus" "$artifacts" + log="$logs/$t.log" + if cargo "${toolchain[@]}" fuzz run --sanitizer "$sanitizer" "$t" "$corpus" "$here/seeds/$t" -- \ + -max_total_time="$secs" -timeout=10 -rss_limit_mb=2048 -print_final_stats=1 \ + -artifact_prefix="$artifacts" >"$log" 2>&1; then + result=ok + else + result=CRASH + status=1 + mkdir -p "$here/regressions/$t" + for a in "$artifacts"*; do + [ -f "$a" ] || continue + # Hex text: a crash input may hold NUL bytes, which the pre-commit hook refuses. + od -An -tx1 -v "$a" | tr -d ' \n' >"$here/regressions/$t/$(basename "$a").hex" + echo " saved $(basename "$a").hex to tests/fuzz/regressions/$t/" >&2 + done + tail -40 "$log" >&2 + fi + runs=$(grep -Eo 'stat::number_of_executed_units: *[0-9]+' "$log" | grep -Eo '[0-9]+$' | tail -1 || true) + printf '%-14s %10s %8s %s\n' "$t" "${runs:-?}" "$secs" "$result" +done +exit $status diff --git a/tests/fuzz/seeds/header_rules/proof b/tests/fuzz/seeds/header_rules/proof new file mode 100644 index 0000000..1827ce1 --- /dev/null +++ b/tests/fuzz/seeds/header_rules/proof @@ -0,0 +1,5 @@ +auth = "forward-auth" +[[request_headers]] +action = "set" +name = "X-Ianitor-Proof" +secret = "ui-proof" diff --git a/tests/fuzz/seeds/header_rules/set-and-remove b/tests/fuzz/seeds/header_rules/set-and-remove new file mode 100644 index 0000000..886aba1 --- /dev/null +++ b/tests/fuzz/seeds/header_rules/set-and-remove @@ -0,0 +1,7 @@ +[[request_headers]] +action = "set" +name = "X-Api-Key" +secret = "api_key" +[[response_headers]] +action = "remove" +name = "X-Powered-By" diff --git a/tests/fuzz/seeds/header_rules/values b/tests/fuzz/seeds/header_rules/values new file mode 100644 index 0000000..e5ab83f --- /dev/null +++ b/tests/fuzz/seeds/header_rules/values @@ -0,0 +1,8 @@ +[[request_headers]] +action = "set" +name = "X-A" +value = "a b\tc" +[[request_headers]] +action = "set" +name = "Host" +value = "x" diff --git a/tests/fuzz/seeds/path_within/dots b/tests/fuzz/seeds/path_within/dots new file mode 100644 index 0000000..56b571b --- /dev/null +++ b/tests/fuzz/seeds/path_within/dots @@ -0,0 +1 @@ +/docs/docs/../secret \ No newline at end of file diff --git a/tests/fuzz/seeds/path_within/encoded b/tests/fuzz/seeds/path_within/encoded new file mode 100644 index 0000000..2a4ae8a --- /dev/null +++ b/tests/fuzz/seeds/path_within/encoded @@ -0,0 +1 @@ +/a/a/%2e%2e/b \ No newline at end of file diff --git a/tests/fuzz/seeds/path_within/lookalike b/tests/fuzz/seeds/path_within/lookalike new file mode 100644 index 0000000..8ba2661 --- /dev/null +++ b/tests/fuzz/seeds/path_within/lookalike @@ -0,0 +1 @@ +/a/a/‥/b \ No newline at end of file diff --git a/tests/fuzz/seeds/path_within/plain b/tests/fuzz/seeds/path_within/plain new file mode 100644 index 0000000..65ed1c8 --- /dev/null +++ b/tests/fuzz/seeds/path_within/plain @@ -0,0 +1 @@ +/a/b/a/b/c.pdf \ No newline at end of file diff --git a/tests/fuzz/seeds/pki_pem/cert b/tests/fuzz/seeds/pki_pem/cert new file mode 100644 index 0000000..46df837 --- /dev/null +++ b/tests/fuzz/seeds/pki_pem/cert @@ -0,0 +1,11 @@ +-----BEGIN CERTIFICATE----- +MIIBljCCAT2gAwIBAgIUX1lbpmyTvnNF1T88oCzWlkJjimowCgYIKoZIzj0EAwIw +ITEfMB0GA1UEAwwWRnV6eiBTZWVkIEludGVybWVkaWF0ZTAeFw0yNjExMTAyMDE2 +NDZaFw0yNjEyMTAyMDE2NDZaMCExHzAdBgNVBAMMFkZ1enogU2VlZCBJbnRlcm1l +ZGlhdGUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASR07B1zm9jchpPxrFhVANE +opzcnaKpjZLi2NANOs/GO2rLFXj7rT2nkFhZcT1s8jebF9+ijPoNurXFEtyLAk/8 +o1MwUTAdBgNVHQ4EFgQUiDYADaKex6pvmQqH2pZPzFQL1IQwHwYDVR0jBBgwFoAU +iDYADaKex6pvmQqH2pZPzFQL1IQwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQD +AgNHADBEAiBsBb9NFAx5zJr/3DKmNqRnYInjf3NNpFxaQQX+bt8cxQIgIMr3auAS +Y4cr/K5PatZGUTXY6Yx8ljbAD6JEh9wnQ50= +-----END CERTIFICATE----- diff --git a/tests/fuzz/seeds/pki_pem/csr b/tests/fuzz/seeds/pki_pem/csr new file mode 100644 index 0000000..8cc83ec --- /dev/null +++ b/tests/fuzz/seeds/pki_pem/csr @@ -0,0 +1,7 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIHbMIGDAgEAMCExHzAdBgNVBAMMFkZ1enogU2VlZCBJbnRlcm1lZGlhdGUwWTAT +BgcqhkjOPQIBBggqhkjOPQMBBwNCAASR07B1zm9jchpPxrFhVANEopzcnaKpjZLi +2NANOs/GO2rLFXj7rT2nkFhZcT1s8jebF9+ijPoNurXFEtyLAk/8oAAwCgYIKoZI +zj0EAwIDRwAwRAIgOeNFc5Gs6sKwxgorIKYWPGiZggG/n1FMBHPbOvL/M8ECIDJB +ThJT2HWLs3qCmMJ5ElwMb8vh21I7AO0V4peZEx1d +-----END CERTIFICATE REQUEST----- diff --git a/tests/fuzz/seeds/pki_pem/truncated b/tests/fuzz/seeds/pki_pem/truncated new file mode 100644 index 0000000..4cf05c7 --- /dev/null +++ b/tests/fuzz/seeds/pki_pem/truncated @@ -0,0 +1,4 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIHbMIGDAgEAMCExHzAdBgNVBAMMFkZ1enogU2VlZCBJbnRlcm1lZGlhdGUwWTAT +BgcqhkjOPQIBBggqhkjOPQMBBwNCAASR07B1zm9jchpPxrFhVANEopzcnaKpjZLi +2NANOs/GO2rLFXj7rT2nkFhZcT1s8jebF9 \ No newline at end of file diff --git a/tests/fuzz/seeds/pki_pem/two-certs b/tests/fuzz/seeds/pki_pem/two-certs new file mode 100644 index 0000000..7f7bed6 --- /dev/null +++ b/tests/fuzz/seeds/pki_pem/two-certs @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIBljCCAT2gAwIBAgIUX1lbpmyTvnNF1T88oCzWlkJjimowCgYIKoZIzj0EAwIw +ITEfMB0GA1UEAwwWRnV6eiBTZWVkIEludGVybWVkaWF0ZTAeFw0yNjExMTAyMDE2 +NDZaFw0yNjEyMTAyMDE2NDZaMCExHzAdBgNVBAMMFkZ1enogU2VlZCBJbnRlcm1l +ZGlhdGUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASR07B1zm9jchpPxrFhVANE +opzcnaKpjZLi2NANOs/GO2rLFXj7rT2nkFhZcT1s8jebF9+ijPoNurXFEtyLAk/8 +o1MwUTAdBgNVHQ4EFgQUiDYADaKex6pvmQqH2pZPzFQL1IQwHwYDVR0jBBgwFoAU +iDYADaKex6pvmQqH2pZPzFQL1IQwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQD +AgNHADBEAiBsBb9NFAx5zJr/3DKmNqRnYInjf3NNpFxaQQX+bt8cxQIgIMr3auAS +Y4cr/K5PatZGUTXY6Yx8ljbAD6JEh9wnQ50= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIBljCCAT2gAwIBAgIUX1lbpmyTvnNF1T88oCzWlkJjimowCgYIKoZIzj0EAwIw +ITEfMB0GA1UEAwwWRnV6eiBTZWVkIEludGVybWVkaWF0ZTAeFw0yNjExMTAyMDE2 +NDZaFw0yNjEyMTAyMDE2NDZaMCExHzAdBgNVBAMMFkZ1enogU2VlZCBJbnRlcm1l +ZGlhdGUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASR07B1zm9jchpPxrFhVANE +opzcnaKpjZLi2NANOs/GO2rLFXj7rT2nkFhZcT1s8jebF9+ijPoNurXFEtyLAk/8 +o1MwUTAdBgNVHQ4EFgQUiDYADaKex6pvmQqH2pZPzFQL1IQwHwYDVR0jBBgwFoAU +iDYADaKex6pvmQqH2pZPzFQL1IQwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQD +AgNHADBEAiBsBb9NFAx5zJr/3DKmNqRnYInjf3NNpFxaQQX+bt8cxQIgIMr3auAS +Y4cr/K5PatZGUTXY6Yx8ljbAD6JEh9wnQ50= +-----END CERTIFICATE----- diff --git a/tests/fuzz/seeds/routes/bad-path b/tests/fuzz/seeds/routes/bad-path new file mode 100644 index 0000000..1550587 --- /dev/null +++ b/tests/fuzz/seeds/routes/bad-path @@ -0,0 +1,2 @@ +hosts/../x.tomlhostname = "A..test" +upstreams = ["ftp://x"] diff --git a/tests/fuzz/seeds/routes/everything b/tests/fuzz/seeds/routes/everything new file mode 100644 index 0000000..272406a --- /dev/null +++ b/tests/fuzz/seeds/routes/everything @@ -0,0 +1,18 @@ +secrets = ["api_key", "ui-proof"] +[forward_auth] +url = "http://127.0.0.1:9091/api/authz/forward-auth" +[acme] +directory = "https://acme.test/dir" +email = "a@b.test" +hostname = "b.test" +upstreams = ["https://[::1]:8443", "https://app.test:8443"] +tls = "letsencrypt" +websockets = true +share_links = true +access_log = "truncated" +[health_check] +path = "/healthz" +interval_secs = 5 +[[response_headers]] +action = "remove" +name = "Server" diff --git a/tests/fuzz/seeds/routes/forward-auth b/tests/fuzz/seeds/routes/forward-auth new file mode 100644 index 0000000..afd7b73 --- /dev/null +++ b/tests/fuzz/seeds/routes/forward-auth @@ -0,0 +1,11 @@ +secrets = ["api_key", "ui-proof"] +[forward_auth] +url = "http://127.0.0.1:9091/api/authz/forward-auth" +hostname = "ui.test" +upstreams = ["unix:/run/ianitor-control/ui.sock"] +tls = "domi" +auth = "forward-auth" +[[request_headers]] +action = "set" +name = "X-Ianitor-Proof" +secret = "ui-proof" diff --git a/tests/fuzz/seeds/routes/plain b/tests/fuzz/seeds/routes/plain new file mode 100644 index 0000000..ca54602 --- /dev/null +++ b/tests/fuzz/seeds/routes/plain @@ -0,0 +1,4 @@ +secrets = [] +hostname = "a.test" +upstreams = ["http://127.0.0.1:3000"] +tls = "domi" diff --git a/tests/fuzz/seeds/share_token/garbage-token b/tests/fuzz/seeds/share_token/garbage-token new file mode 100644 index 0000000..02fcc19 --- /dev/null +++ b/tests/fuzz/seeds/share_token/garbage-token @@ -0,0 +1 @@ +isl1.AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA \ No newline at end of file diff --git a/tests/fuzz/seeds/share_token/prefix-and-password b/tests/fuzz/seeds/share_token/prefix-and-password new file mode 100644 index 0000000..ce59616 --- /dev/null +++ b/tests/fuzz/seeds/share_token/prefix-and-password @@ -0,0 +1 @@ +/docs/reporthunter2 \ No newline at end of file diff --git a/tests/fuzz/seeds/share_token/root b/tests/fuzz/seeds/share_token/root new file mode 100644 index 0000000..3b8f576 --- /dev/null +++ b/tests/fuzz/seeds/share_token/root @@ -0,0 +1 @@ +/ \ No newline at end of file diff --git a/tests/fuzz/src/lib.rs b/tests/fuzz/src/lib.rs new file mode 100644 index 0000000..912b4d6 --- /dev/null +++ b/tests/fuzz/src/lib.rs @@ -0,0 +1,263 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! The fuzz targets' bodies (ROADMAP §5 layer 3), as plain functions: cargo-fuzz calls them +//! from `fuzz/fuzz_targets/*` (libFuzzer), and `tests/regressions.rs` replays every saved input +//! under `regressions//` in the ordinary `cargo test`, so a crash once found stays a +//! test. A target must never panic on any input; where a property is cheap, it is asserted +//! (a panic is how libFuzzer learns about it). +//! +//! Everything here is hostile input in production: route files (the routes repository), the +//! header rules in them, share tokens and paths from visitors, CSRs and PEM files handed to the +//! CA. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::PathBuf; +use std::sync::OnceLock; + +use ianitor_core::compile::{self, CompileOptions}; +use ianitor_core::edge_config::{EdgeConfig, EdgeTls}; +use ianitor_core::share::{self, LinkSpec, Revocations, ShareId, ShareKey}; +use ianitor_core::{SourceFile, load, pki, routes}; + +/// Every target, by the name its directories use. +pub const TARGETS: &[(&str, fn(&[u8]))] = &[ + ("routes", routes_toml), + ("header_rules", header_rules), + ("share_token", share_token), + ("path_within", path_within), + ("pki_pem", pki_pem), +]; + +fn text(data: &[u8]) -> String { + String::from_utf8_lossy(data).into_owned() +} + +/// The byte that splits one input into two (ASCII unit separator; not NUL, so seeds stay text +/// files the pre-commit hook accepts). +pub const SEP: u8 = 0x1f; + +/// Split at the first [`SEP`]: two independent inputs from one. +fn split2(data: &[u8]) -> (&[u8], &[u8]) { + match data.iter().position(|b| *b == SEP) { + Some(i) => (&data[..i], &data[i + 1..]), + None => (data, &[]), + } +} + +fn options() -> CompileOptions { + CompileOptions { + http_listen: "127.0.0.1:8080".parse().unwrap(), + https_listen: "127.0.0.1:8443".parse().unwrap(), + cert_dir: "/var/lib/ianitor/certs".into(), + state_dir: "/var/lib/ianitor/state".into(), + access_log: "/var/log/ianitor/access.log".into(), + caddy_credentials_dir: "/run/credentials/caddy-fallback.service".into(), + caddy_admin: None, + caddy_admin_socket: Some("/run/caddy-fallback/admin.sock".into()), + trusted_proxies: vec!["127.0.0.1".parse().unwrap()], + proxy_socket: Some("/run/ianitor-proxy/edge.sock".into()), + } +} + +/// Load, then: both compilers succeed, are deterministic, and the edge config reads back. +fn compile_checked(site: &str, hosts: &[(String, String)]) { + let sources: Vec> = hosts + .iter() + .map(|(n, c)| SourceFile { + name: n, + contents: c, + }) + .collect(); + let Ok(model) = load( + &SourceFile { + name: "ianitor.toml", + contents: site, + }, + &sources, + ) else { + return; + }; + let o = options(); + let edge = compile::edge(&model, &o).expect("a valid model compiles for edge"); + let caddy = compile::caddy(&model, &o).expect("a valid model compiles for Caddy"); + assert_eq!( + edge, + compile::edge(&model, &o).unwrap(), + "edge output is deterministic" + ); + assert_eq!( + caddy, + compile::caddy(&model, &o).unwrap(), + "Caddy output is deterministic" + ); + let cfg: EdgeConfig = serde_json::from_str(&edge).expect("edge reads what core writes"); + let _: serde_json::Value = serde_json::from_str(&caddy).expect("the Caddy JSON is JSON"); + build_edge_runtime(cfg); +} + +/// The credentials directory the edge runtime reads secrets from (fixed test values). +fn creds_dir() -> &'static PathBuf { + static DIR: OnceLock = OnceLock::new(); + DIR.get_or_init(|| { + let d = std::env::temp_dir().join(format!("ianitor-fuzz-creds-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + std::fs::write(d.join("api_key"), b"fuzz-secret-value\n").unwrap(); + std::fs::write(d.join("ui-proof"), b"fuzz-proof-value\n").unwrap(); + std::fs::write( + d.join("share-link-key"), + b"fuzz-share-link-key-0123456789abcdef0123456789", + ) + .unwrap(); + d + }) +} + +/// Edge builds its runtime (header names and values, upstream addresses) from a compiled +/// config. Files are kept out of it: no certificates to read, no access log to open, no device +/// lists; what is left must build, since core validated it. +fn build_edge_runtime(mut cfg: EdgeConfig) { + cfg.device_certs = None; + for h in &mut cfg.hosts { + h.tls = EdgeTls::Acme; + h.access_log = false; + h.device_certs = false; + } + if let Err(e) = ianitor_edge::runtime::build(cfg, Some(creds_dir())) { + panic!("edge refused a config core compiled: {e}"); + } +} + +/// Route files: a site file and one host file, split at the first SEP. Also the repository +/// path check on the host file's first line. +pub fn routes_toml(data: &[u8]) { + let (site, host) = split2(data); + let (site, host) = (text(site), text(host)); + let path = host.lines().next().unwrap_or_default(); + let _ = routes::check_path(path, routes::EntryKind::File); + // Name the host file after the hostname it claims, so a valid file can get through. + let name = host + .lines() + .find_map(|l| l.trim().strip_prefix("hostname")) + .and_then(|r| r.split('"').nth(1)) + .unwrap_or("x.test") + .to_owned(); + compile_checked(&site, &[(format!("hosts/{name}.toml"), host)]); +} + +/// Header rules: the input is appended to a host file that is otherwise valid, so the fuzzer +/// spends its time on `[[request_headers]]` / `[[response_headers]]` (names, values, secrets, +/// the protected list), through both compilers and edge's runtime. +pub fn header_rules(data: &[u8]) { + let site = "secrets = [\"api_key\", \"ui-proof\"]\n"; + let host = format!( + "hostname = \"h.test\"\nupstreams = [\"http://127.0.0.1:9000\"]\ntls = \"domi\"\n{}", + text(data) + ); + compile_checked(site, &[("hosts/h.test.toml".to_owned(), host)]); +} + +fn key() -> &'static ShareKey { + static KEY: OnceLock = OnceLock::new(); + KEY.get_or_init(|| ShareKey::new(b"fuzz-share-link-key-0123456789abcdef0123456789").unwrap()) +} + +/// Share tokens from visitors: a token and a password (split at SEP) checked as a link and as +/// a session; then a link minted from the input's bytes verifies for its own host and password +/// only. +pub fn share_token(data: &[u8]) { + let (token, password) = split2(data); + let (token, password) = (text(token), text(password)); + let revs = Revocations::default(); + let _ = share::peek(&token); + let pw = (!password.is_empty()).then_some(password.as_str()); + let _ = share::verify_link(key(), "h.test", &token, pw, 1_000, &revs); + let _ = share::verify_session(key(), "h.test", &token, 1_000, &revs); + + // Round trip with input-derived claims. + let Ok(prefix) = share::check_prefix(&token) else { + return; + }; + let mut id = [0u8; 16]; + for (i, b) in data.iter().take(16).enumerate() { + id[i] = *b; + } + let spec = LinkSpec { + id: ShareId(id), + epoch: u32::from(data.first().copied().unwrap_or(0)), + expires_at: 2_000, + prefix: &prefix, + password: pw, + }; + let Ok(t) = share::mint(key(), "h.test", &spec) else { + return; + }; + let c = share::verify_link(key(), "h.test", &t, pw, 1_000, &revs) + .expect("a minted link verifies for its host"); + assert_eq!(c.prefix, prefix); + assert!( + share::path_within(&prefix, &prefix), + "a prefix covers itself" + ); + assert!( + share::verify_link(key(), "other.test", &t, pw, 1_000, &revs).is_err(), + "a link is bound to its host" + ); + if pw.is_some() { + assert!( + share::verify_link(key(), "h.test", &t, Some("not the password"), 1_000, &revs) + .is_err() + || password == "not the password", + "a password link needs its password" + ); + } + let s = share::session_value(key(), "h.test", &c); + assert!(share::verify_session(key(), "h.test", &s, 1_000, &revs).is_ok()); + assert!( + share::verify_link(key(), "h.test", &t, pw, 2_000, &revs).is_err(), + "expired" + ); +} + +/// Visitor paths against a share link's prefix: never a panic; a checked prefix covers itself; +/// a dot segment never escapes it. +pub fn path_within(data: &[u8]) { + let (prefix, path) = split2(data); + let (prefix, path) = (text(prefix), text(path)); + let _ = share::path_within(&prefix, &path); + if let Ok(p) = share::check_prefix(&prefix) { + assert!(share::path_within(&p, &p)); + let escape = format!("{}/../outside", p.trim_end_matches('/')); + assert!(!share::path_within(&p, &escape), "{escape} escaped {p}"); + } +} + +/// The root the CA target signs with (made once; the fuzzer never sees its key). +fn test_root() -> &'static (String, pki::KeyPair) { + static ROOT: OnceLock<(String, pki::KeyPair)> = OnceLock::new(); + ROOT.get_or_init(|| pki::create_root(1_700_000_000).unwrap()) +} + +/// PEM and CSRs handed to the CA: parsers never panic, and a CSR the root signs gives an +/// intermediate the root issued. +pub fn pki_pem(data: &[u8]) { + let (a, _) = split2(data); + let pem = text(a); + let _ = pki::inspect(&pem); + let _ = pki::inspect_der(a); + let _ = pki::chain_der(&pem); + let _ = pki::first_pem(&pem); + let _ = pki::public_key_der(&pem); + let _ = pki::csr_der(&pem); + let _ = pki::csr_public_key_der(&pem); + let _ = pki::KeyPair::from_pem(&pem); + let _ = pki::KeyPair::from_der(a); + let (root_pem, root_key) = test_root(); + let _ = pki::intermediate_problem(&pem, root_pem, 1_700_000_100); + let _ = pki::issued_by(&pem, root_pem); + if let Ok(cert) = pki::sign_intermediate(root_pem, root_key, &pem, 1_700_000_100) { + assert_eq!(pki::issued_by(&cert, root_pem).ok(), Some(true)); + } +} diff --git a/tests/fuzz/tests/regressions.rs b/tests/fuzz/tests/regressions.rs new file mode 100644 index 0000000..27dfbd3 --- /dev/null +++ b/tests/fuzz/tests/regressions.rs @@ -0,0 +1,100 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Every saved fuzz input, replayed in the ordinary `cargo test`: the seeds (`seeds//`, +//! the starting corpus) and every input that once crashed a target (`regressions//`, +//! copied there by `tests/fuzz/run.sh` as `.hex`, hex text, since a crash input may hold +//! NUL bytes the pre-commit hook refuses). A crash found once stays a failing test until fixed. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::Path; + +fn from_hex(raw: &[u8]) -> Option> { + let digits: Vec = raw + .iter() + .copied() + .filter(|c| !c.is_ascii_whitespace()) + .collect(); + if digits.len() % 2 != 0 { + return None; + } + digits + .chunks(2) + .map(|p| u8::from_str_radix(std::str::from_utf8(p).ok()?, 16).ok()) + .collect() +} + +fn replay(dir: &str) -> usize { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join(dir); + let mut n = 0; + for (name, target) in ianitor_fuzz::TARGETS { + let d = root.join(name); + let Ok(entries) = std::fs::read_dir(&d) else { + continue; + }; + let mut files: Vec<_> = entries.filter_map(Result::ok).map(|e| e.path()).collect(); + files.sort(); + for f in files.iter().filter(|f| f.is_file()) { + let raw = std::fs::read(f).unwrap(); + let data = if f.extension().is_some_and(|e| e == "hex") { + from_hex(&raw).unwrap_or_else(|| panic!("{}: not hex", f.display())) + } else { + raw + }; + let r = std::panic::catch_unwind(|| target(&data)); + assert!(r.is_ok(), "{name}: {} panics", f.display()); + n += 1; + } + } + n +} + +#[test] +fn every_seed_runs_clean() { + let n = replay("seeds"); + assert!(n >= 10, "the seed corpus has inputs for every target ({n})"); +} + +#[test] +fn every_saved_crash_stays_fixed() { + replay("regressions"); +} + +#[test] +fn every_target_has_seeds() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("seeds"); + for (name, _) in ianitor_fuzz::TARGETS { + let n = std::fs::read_dir(root.join(name)) + .map(|d| d.count()) + .unwrap_or(0); + assert!(n > 0, "no seeds for {name}"); + } +} + +/// The route seeds meant to be valid are: otherwise the fuzzer would start from refusals only +/// and seldom reach the compilers and edge's runtime. +#[test] +fn the_valid_route_seeds_load() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("seeds/routes"); + for name in ["plain", "forward-auth", "everything"] { + let data = std::fs::read(root.join(name)).unwrap(); + let i = data.iter().position(|b| *b == ianitor_fuzz::SEP).unwrap(); + let site = String::from_utf8(data[..i].to_vec()).unwrap(); + let host = String::from_utf8(data[i + 1..].to_vec()).unwrap(); + let hostname = host.lines().next().unwrap().split('"').nth(1).unwrap(); + let file = format!("hosts/{hostname}.toml"); + let r = ianitor_core::load( + &ianitor_core::SourceFile { + name: "ianitor.toml", + contents: &site, + }, + &[ianitor_core::SourceFile { + name: &file, + contents: &host, + }], + ); + assert!(r.is_ok(), "{name}: {:?}", r.err()); + } +} From 46920440996fa6baf2710ca4cc7df9418f666b62 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 21:19:44 +0100 Subject: [PATCH 14/45] [diff] Pair: ianitor-pair runs edge and two Caddys (all cores, GOMAXPROCS=2) on the same compiled routes for the conformance and load scripts --- Cargo.lock | 4 + tests/diff/Cargo.toml | 8 ++ tests/diff/src/bin/pair.rs | 191 +++++++++++++++++++++++++++++++++++++ tests/diff/src/lib.rs | 37 +++++-- 4 files changed, 231 insertions(+), 9 deletions(-) create mode 100644 tests/diff/src/bin/pair.rs diff --git a/Cargo.lock b/Cargo.lock index 6f37130..68ea429 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1337,6 +1337,10 @@ dependencies = [ name = "ianitor-diff" version = "0.1.0" dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", "ianitor-control", "ianitor-core", "ianitor-edge", diff --git a/tests/diff/Cargo.toml b/tests/diff/Cargo.toml index be876f6..538cef9 100644 --- a/tests/diff/Cargo.toml +++ b/tests/diff/Cargo.toml @@ -15,6 +15,14 @@ tokio.workspace = true serde_json.workspace = true rustls.workspace = true rcgen.workspace = true +bytes.workspace = true +hyper.workspace = true +hyper-util.workspace = true +http-body-util.workspace = true + +[[bin]] +name = "ianitor-pair" +path = "src/bin/pair.rs" [dev-dependencies] ianitor-control = { path = "../../crates/control" } diff --git a/tests/diff/src/bin/pair.rs b/tests/diff/src/bin/pair.rs new file mode 100644 index 0000000..46f586a --- /dev/null +++ b/tests/diff/src/bin/pair.rs @@ -0,0 +1,191 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! `ianitor-pair`: Ianitor (edge, in this process) and Caddy side by side on 127.0.0.1, +//! serving the same routes compiled by core, for the conformance and load scripts +//! (scripts/conformance.sh, scripts/bench.sh; ROADMAP §5 layers 2 and 5). +//! +//! One host, `localhost` (a Domi-style certificate from a throwaway test CA), proxied to a +//! small upstream that answers `200 ok` and records nothing; it runs as a child process +//! (`ianitor-pair --upstream`), so this process's memory is edge's (plus a small runtime). Two Caddys run: +//! one as Go starts it (every core) and one with `GOMAXPROCS=2`, since edge runs Pingora with +//! two worker threads (crates/edge/src/lib.rs). Prints one JSON line with the addresses and the +//! CA file, then serves until SIGTERM or SIGINT. +//! +//! `ianitor-pair [--caddy ]` (default: `caddy` on PATH or `$IANITOR_CADDY_BIN`). + +#[cfg(not(unix))] +fn main() { + eprintln!("ianitor-pair needs Linux (the Pingora runner and Caddy); run it in WSL2"); + std::process::exit(2); +} + +#[cfg(unix)] +fn main() { + #[allow(clippy::expect_used)] + let rt = tokio::runtime::Runtime::new().expect("a tokio runtime"); + rt.block_on(unix::main()); +} + +#[cfg(unix)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod unix { + use std::convert::Infallible; + use std::net::SocketAddr; + + use http_body_util::Full; + use hyper::server::conn::http1; + use hyper::service::service_fn; + use hyper_util::rt::TokioIo; + use ianitor_core::compile::{self, CompileOptions}; + use ianitor_core::{SourceFile, load}; + use ianitor_diff::{Target, start_caddy_in, start_edge_in}; + use ianitor_testkit::proc::{ChildGuard, TempDir, find_binary, free_port, local}; + use ianitor_testkit::tls::TestCa; + use serde_json::json; + + /// `--upstream`: serve `200 ok` on a free loopback port, print it, run until killed. + async fn serve_upstream() { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + println!("{}", l.local_addr().unwrap()); + loop { + let Ok((s, _)) = l.accept().await else { + continue; + }; + tokio::spawn(async move { + let svc = service_fn(|_req| async { + Ok::<_, Infallible>(hyper::Response::new(Full::new(bytes::Bytes::from_static( + b"ok\n", + )))) + }); + let _ = http1::Builder::new() + .serve_connection(TokioIo::new(s), svc) + .await; + }); + } + } + + /// The upstream as a child process; its address. + fn upstream() -> (ChildGuard, SocketAddr) { + use std::io::BufRead; + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .arg("--upstream") + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let out = child.stdout.take().unwrap(); + let mut line = String::new(); + std::io::BufReader::new(out).read_line(&mut line).unwrap(); + (ChildGuard(child), line.trim().parse().unwrap()) + } + + fn options(dir: &TempDir, engine: &str) -> CompileOptions { + CompileOptions { + http_listen: local(free_port()), + https_listen: local(free_port()), + cert_dir: dir.str("certs"), + state_dir: dir.str(&format!("state-{engine}")), + access_log: dir.str(&format!("logs/{engine}-access.log")), + caddy_credentials_dir: dir.str("creds"), + caddy_admin: None, + caddy_admin_socket: None, + trusted_proxies: Vec::new(), + proxy_socket: None, + } + } + + fn addrs(t: &Target) -> serde_json::Value { + json!({ "http": t.http.to_string(), "https": t.https.to_string() }) + } + + pub async fn main() { + let args: Vec = std::env::args().collect(); + if args.iter().any(|a| a == "--upstream") { + serve_upstream().await; + return; + } + let caddy = args + .iter() + .position(|a| a == "--caddy") + .and_then(|i| args.get(i + 1)) + .map(std::path::PathBuf::from) + .or_else(|| find_binary("caddy")) + .unwrap_or_else(|| panic!("no caddy: pass --caddy or put it on PATH")); + + let (upstream_child, up) = upstream(); + let dir = TempDir::new("pair"); + for d in [ + "certs", + "creds", + "logs", + "state-edge", + "state-caddy", + "state-caddy2", + "xdg", + ] { + std::fs::create_dir_all(dir.join(d)).unwrap(); + } + let ca = TestCa::new("Ianitor Pair Test CA"); + let leaf = ca.issue(&["localhost"]); + std::fs::write(dir.join("certs/localhost.crt"), leaf.cert_pem).unwrap(); + std::fs::write(dir.join("certs/localhost.key"), leaf.key_pem).unwrap(); + std::fs::write(dir.join("ca.pem"), &ca.cert_pem).unwrap(); + + let host = + format!("hostname = \"localhost\"\ntls = \"domi\"\nupstreams = [\"http://{up}\"]\n"); + let model = load( + &SourceFile { + name: "ianitor.toml", + contents: "", + }, + &[SourceFile { + name: "hosts/localhost.toml", + contents: &host, + }], + ) + .expect("valid routes"); + + let edge_cfg = compile::edge(&model, &options(&dir, "edge")).unwrap(); + let caddy_cfg = compile::caddy(&model, &options(&dir, "caddy")).unwrap(); + let caddy2_cfg = compile::caddy(&model, &options(&dir, "caddy2")).unwrap(); + let ianitor = start_edge_in(dir.path(), "ianitor", &edge_cfg); + let caddy_all = start_caddy_in(dir.path(), "caddy", &caddy, &caddy_cfg, &[]); + let caddy_two = start_caddy_in( + dir.path(), + "caddy2", + &caddy, + &caddy2_cfg, + &[("GOMAXPROCS", "2")], + ); + let caddy_version = std::process::Command::new(&caddy) + .arg("version") + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()) + .unwrap_or_default(); + + println!( + "{}", + json!({ + "host": "localhost", + "ca": dir.join("ca.pem"), + "dir": dir.path(), + "upstream": up.to_string(), + "ianitor": addrs(&ianitor), + "caddy": addrs(&caddy_all), + "caddy_gomaxprocs2": addrs(&caddy_two), + "edge_threads": 2, + "build": if cfg!(debug_assertions) { "debug" } else { "release" }, + "caddy_version": caddy_version, + }) + ); + + use tokio::signal::unix::{SignalKind, signal}; + let mut term = signal(SignalKind::terminate()).unwrap(); + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + _ = term.recv() => {} + } + drop((ianitor, caddy_all, caddy_two, upstream_child)); + } +} diff --git a/tests/diff/src/lib.rs b/tests/diff/src/lib.rs index c64293b..77b3061 100644 --- a/tests/diff/src/lib.rs +++ b/tests/diff/src/lib.rs @@ -215,12 +215,17 @@ impl Drop for Target { /// Start Ianitor edge in this process from an edge config text. pub fn start_edge(env: &Env, name: &'static str, config_text: &str) -> Target { + start_edge_in(env.dir.path(), name, config_text) +} + +/// [`start_edge`] with the credentials in `/creds`. +pub fn start_edge_in(dir: &std::path::Path, name: &'static str, config_text: &str) -> Target { let cfg: ianitor_core::edge_config::EdgeConfig = serde_json::from_str(config_text).unwrap(); let (http, https) = ( cfg.http_listen.parse().unwrap(), cfg.https_listen.parse().unwrap(), ); - let rt = ianitor_edge::runtime::build(cfg, Some(&env.dir.join("creds"))).expect("edge runtime"); + let rt = ianitor_edge::runtime::build(cfg, Some(&dir.join("creds"))).expect("edge runtime"); let opts = ianitor_edge::Options::default(); let shared = ianitor_edge::shared_for(rt, &opts); let server = ianitor_edge::server(shared, &opts).expect("edge server"); @@ -245,9 +250,21 @@ pub fn start_edge(env: &Env, name: &'static str, config_text: &str) -> Target { /// Start `caddy run` on a generated Caddy JSON; a start that does not come up is retried /// (twice), since a port can be briefly unavailable right after the previous server on it. pub fn start_caddy(env: &Env, name: &'static str, caddy: &std::path::Path, json: &str) -> Target { + start_caddy_in(env.dir.path(), name, caddy, json, &[]) +} + +/// [`start_caddy`] in `dir` (its files, `/xdg` as home), with extra environment variables +/// (the benchmark sets `GOMAXPROCS`). +pub fn start_caddy_in( + dir: &std::path::Path, + name: &'static str, + caddy: &std::path::Path, + json: &str, + envs: &[(&str, &str)], +) -> Target { let mut last = String::new(); for _ in 0..3 { - match try_start_caddy(env, name, caddy, json) { + match try_start_caddy(dir, name, caddy, json, envs) { Ok(t) => return t, Err(e) => { last = e; @@ -259,10 +276,11 @@ pub fn start_caddy(env: &Env, name: &'static str, caddy: &std::path::Path, json: } fn try_start_caddy( - env: &Env, + dir: &std::path::Path, name: &'static str, caddy: &std::path::Path, json: &str, + envs: &[(&str, &str)], ) -> Result { let v: serde_json::Value = serde_json::from_str(json).unwrap(); let servers = &v["apps"]["http"]["servers"]; @@ -276,16 +294,17 @@ fn try_start_caddy( .unwrap() .parse() .unwrap(); - let file = env.dir.join(&format!("{name}.json")); + let file = dir.join(format!("{name}.json")); std::fs::write(&file, json).unwrap(); - let log = std::fs::File::create(env.dir.join(&format!("{name}.log"))).unwrap(); + let log = std::fs::File::create(dir.join(format!("{name}.log"))).unwrap(); let child = Command::new(caddy) .arg("run") .arg("--config") .arg(&file) - .env("HOME", env.dir.join("xdg")) - .env("XDG_CONFIG_HOME", env.dir.join("xdg")) - .env("XDG_DATA_HOME", env.dir.join("xdg")) + .env("HOME", dir.join("xdg")) + .env("XDG_CONFIG_HOME", dir.join("xdg")) + .env("XDG_DATA_HOME", dir.join("xdg")) + .envs(envs.iter().copied()) .stdout(Stdio::from(log.try_clone().unwrap())) .stderr(Stdio::from(log)) .spawn() @@ -296,7 +315,7 @@ fn try_start_caddy( { let _ = guard.0.kill(); let _ = guard.0.wait(); - let out = std::fs::read_to_string(env.dir.join(&format!("{name}.log"))).unwrap_or_default(); + let out = std::fs::read_to_string(dir.join(format!("{name}.log"))).unwrap_or_default(); return Err(format!("caddy did not listen on {https} / {http}:\n{out}")); } Ok(Target { From 9ae721b79fc7b50fce99431d41ffcc376d105293 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 21:23:16 +0100 Subject: [PATCH 15/45] [fabrica] Layers and the verifiable build: the layers pipeline runs all five test layers on a NixOS runner with KVM, verify-nix rebuilds a tag and compares with its pin, the release publishes the Nix pin (ianitor-nix.json) under the signed SHA256SUMS; scripts for conformance, load and the pin; docs/verify.md --- .fabrica/artifex/layers.yaml | 39 +++++++++++ .fabrica/artifex/release.yaml | 10 ++- .fabrica/artifex/verify-nix.yaml | 17 +++++ deploy/nixos/package.nix | 5 +- deploy/nixos/web.nix | 2 +- docs/domi-release.pub | 2 + docs/verify.md | 78 +++++++++++++++++++++ flake.nix | 25 +++++++ scripts/bench.sh | 115 +++++++++++++++++++++++++++++++ scripts/conformance.sh | 79 +++++++++++++++++++++ scripts/nix-pin.sh | 59 ++++++++++++++++ scripts/release-pin.mjs | 57 +++++++++++++++ 12 files changed, 485 insertions(+), 3 deletions(-) create mode 100644 .fabrica/artifex/layers.yaml create mode 100644 .fabrica/artifex/verify-nix.yaml create mode 100644 docs/domi-release.pub create mode 100644 docs/verify.md create mode 100755 scripts/bench.sh create mode 100755 scripts/conformance.sh create mode 100755 scripts/nix-pin.sh create mode 100644 scripts/release-pin.mjs diff --git a/.fabrica/artifex/layers.yaml b/.fabrica/artifex/layers.yaml new file mode 100644 index 0000000..18564ff --- /dev/null +++ b/.fabrica/artifex/layers.yaml @@ -0,0 +1,39 @@ +# Ianitor Domi: the five test layers (ROADMAP §5) on a push to main, or by hand. Layer 1 (the differential +# suite against Caddy) runs inside the workspace tests; layer 2 is scripts/conformance.sh (h2spec, testssl.sh); +# layer 3 tests/fuzz/run.sh (cargo-fuzz, 2 minutes a target; any crash fails); layer 4 the NixOS VM tests; +# layer 5 scripts/bench.sh (load and a 5-minute soak against Caddy; results kept as artifacts). +# Runner: label `nixos`, on a host with /dev/kvm and Nix's `kvm` system feature (the VM tests; on Hyper-V, +# nested virtualisation on), outbound HTTPS (crates.io, cache.nixos.org) and about 20 GB free. Every tool comes +# from the flake's `ci` shell, so the runner needs only Nix with flakes. +name: layers +on: + push: [main] + manual: true +runner: nixos +env: + CARGO_TERM_COLOR: "never" + CARGO_BUILD_JOBS: "8" +steps: + - id: workspace-tests + run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c cargo test --workspace --no-fail-fast + - id: conformance + needs: [workspace-tests] + run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c scripts/conformance.sh + artifacts: ["bench/conformance/*"] + - id: fuzz + needs: [workspace-tests] + run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c tests/fuzz/run.sh 120 + - id: vm-apply-reverts + nix: .#checks.x86_64-linux.vm-apply-reverts + - id: vm-engine-switch + nix: .#checks.x86_64-linux.vm-engine-switch + - id: vm-intermediate-renewal + nix: .#checks.x86_64-linux.vm-intermediate-renewal + - id: vm-control-loopback + nix: .#checks.x86_64-linux.vm-control-loopback + - id: vm-sockets + nix: .#checks.x86_64-linux.vm-sockets + - id: load + needs: [conformance, fuzz] + run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c scripts/bench.sh fabrica-runner + artifacts: ["bench/results/**"] diff --git a/.fabrica/artifex/release.yaml b/.fabrica/artifex/release.yaml index e05263b..748ab88 100644 --- a/.fabrica/artifex/release.yaml +++ b/.fabrica/artifex/release.yaml @@ -6,6 +6,9 @@ # `notes` is Fabrica's release notes since the previous v* tag (Fabrica docs/12_release_kit.md); `shots` takes the # same files as `fabrica aula shots` (core docs/FORMATS.md, "Fabrica: the Aula page") from the built web UI against # the demo control plane with invented data, in headless Edge. No landing page while app.yaml has no `aula: true`. +# `pin` publishes the Nix build's NAR hashes (.fabrica/nix/pin.json, written by scripts/nix-pin.sh on Linux and +# committed before the tag) with the tag's commit as ianitor-nix.json, so SHA256SUMS also vouches for the build +# anyone can repeat (docs/verify.md); the `verify-nix` pipeline rebuilds the tag on the NixOS runner and compares. name: release on: tag: "v*" @@ -29,8 +32,12 @@ steps: needs: [check, test] run: node apps/web/scripts/shots.mjs artifacts: ["target/aula/aula-*.png", "target/aula/aula.json"] + - id: pin + needs: [version] + run: node scripts/release-pin.mjs ${{ version }} ${{ tag }} ${{ commit }} + artifacts: ["target/nix/ianitor-nix.json"] - id: approve - needs: [version, notes, shots] + needs: [version, notes, shots, pin] approve: "Publish Ianitor ${{ tag }}: its notes and screenshots?" - id: publish needs: [approve] @@ -41,4 +48,5 @@ steps: - "**/release-notes.json" - "**/aula-*.png" - "**/aula.json" + - "**/ianitor-nix.json" sums: domi-release diff --git a/.fabrica/artifex/verify-nix.yaml b/.fabrica/artifex/verify-nix.yaml new file mode 100644 index 0000000..1203a17 --- /dev/null +++ b/.fabrica/artifex/verify-nix.yaml @@ -0,0 +1,17 @@ +# Ianitor Domi: the verifiable build (docs/verify.md). On a v* tag the NixOS runner builds .#ianitor and +# .#ianitor-web from the tag (the run record keeps each output's store path and NAR hash), builds them again +# from scratch, and compares with the pin the release publishes (.fabrica/nix/pin.json at the tag); any +# difference fails the run. Runner: label `nixos`, Nix with flakes; no KVM needed. +name: verify-nix +on: + tag: "v*" + manual: true +runner: nixos +steps: + - id: ianitor + nix: .#ianitor + - id: web + nix: .#ianitor-web + - id: pin + needs: [ianitor, web] + run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c scripts/nix-pin.sh --check diff --git a/deploy/nixos/package.nix b/deploy/nixos/package.nix index 65aae88..5874f2b 100644 --- a/deploy/nixos/package.nix +++ b/deploy/nixos/package.nix @@ -9,7 +9,8 @@ rustPlatform.buildRustPackage { pname = "ianitor"; - version = "0.1.0"; + # One version, the workspace's (scripts/check-version.mjs checks the rest). + version = (lib.importTOML ../../Cargo.toml).workspace.package.version; src = lib.fileset.toSource { root = ../..; @@ -19,6 +20,8 @@ rustPlatform.buildRustPackage { ../../crates ../../tests/diff ../../tests/support + # The fuzz crate is a workspace member; its cargo-fuzz project is not (own workspace). + (lib.fileset.difference ../../tests/fuzz ../../tests/fuzz/fuzz) ]; }; diff --git a/deploy/nixos/web.nix b/deploy/nixos/web.nix index f42e8a5..b82e185 100644 --- a/deploy/nixos/web.nix +++ b/deploy/nixos/web.nix @@ -8,7 +8,7 @@ stdenv.mkDerivation (finalAttrs: { pname = "ianitor-web"; - version = "0.1.0"; + version = (lib.importJSON ../../apps/web/package.json).version; src = lib.fileset.toSource { root = ../..; diff --git a/docs/domi-release.pub b/docs/domi-release.pub new file mode 100644 index 0000000..4bea412 --- /dev/null +++ b/docs/domi-release.pub @@ -0,0 +1,2 @@ +untrusted comment: minisign public key ABD87B469ADF4BE4 +RWTkS9+aRnvYq1si0VvyJFeEJf7oQ3Dsadl0/fI64nuVIaz286PGiyPe diff --git a/docs/verify.md b/docs/verify.md new file mode 100644 index 0000000..c43f5ae --- /dev/null +++ b/docs/verify.md @@ -0,0 +1,78 @@ +# Verifying a release + +Every Ianitor release on Gitea (`vX.Y.Z`) carries `SHA256SUMS` and `SHA256SUMS.minisig`, signed through Custos by +the `domi-release` key, and among the files that `SHA256SUMS` lists, `ianitor-nix.json`: the tag's commit and the +NAR hash of every Nix output (`.#ianitor`, the two binaries; `.#ianitor-web`, the built UI). Ianitor ships no +binary download: you build the tag yourself (or your server does, through the NixOS module) and check that you got +exactly the bytes the release vouches for. The build is reproducible: `scripts/nix-pin.sh` builds each output twice +from scratch and refuses to pin one whose bytes differ, and the `verify-nix` pipeline rebuilds every tag on the +NixOS runner and compares. + +## 1. The signature + +The `domi-release` public key, key id `ABD87B469ADF4BE4` (also in [domi-release.pub](domi-release.pub)): + +```text +untrusted comment: minisign public key ABD87B469ADF4BE4 +RWTkS9+aRnvYq1si0VvyJFeEJf7oQ3Dsadl0/fI64nuVIaz286PGiyPe +``` + +Take it from a source you trust more than the release page itself (Custos → *Signing keys* → *Copy minisign.pub*, +or a clone of this repository you already had). Then, in a folder with the release's files: + +```sh +minisign -Vm SHA256SUMS -p domi-release.pub # "Signature and comment signature verified" +sha256sum -c --ignore-missing SHA256SUMS # every downloaded file: OK +``` + +(`nix shell nixpkgs#minisign` if you have no minisign. Custos signs prehashed; minisign 0.10 and later verify it.) + +## 2. The build + +`ianitor-nix.json` names the commit and the hashes: + +```json +{ "version": "1.0.0", "commit": "<40 hex>", "system": "x86_64-linux", + "outputs": { "ianitor": { "storePath": "/nix/store/…-ianitor-1.0.0", "narHash": "sha256-…" }, … } } +``` + +Build that commit and compare (Linux with Nix and flakes; nothing from Ianitor's own caches is needed): + +```sh +c=$(jq -r .commit ianitor-nix.json) +for a in ianitor ianitor-web; do + p=$(nix build "git+https://gitea.marek-novak.cz/mnovak/Ianitor.git?rev=$c#$a" --no-link --print-out-paths) + got=$(nix path-info --json "$p" | jq -r 'if type == "array" then .[0].narHash else .[].narHash end') + want=$(jq -r ".outputs[\"$a\"].narHash" ianitor-nix.json) + [ "$got" = "$want" ] && echo "$a: $got matches" || echo "$a: MISMATCH (got $got, release says $want)" +done +``` + +The store path matches too (it depends only on the derivation, so it tells you the inputs were the same); the NAR +hash is the content. `nix build --rebuild` builds once more locally and fails if your own two builds differ. + +On a server that uses the NixOS module, the running build is `services.ianitor.package`, normally +`ianitor.packages.x86_64-linux.ianitor` from the flake input pinned in the server's `flake.lock`: if that input's +`rev` is the release's commit, `nix path-info --json $(readlink -f /run/current-system/sw/bin/ianitor-edge | sed 's#/bin/.*##')` +gives the same NAR hash. + +## What this does and does not prove + +- **Proves:** the release's notes, screenshots and pin are the ones Mark approved and Custos signed; the code at the + pinned commit builds to exactly the pinned bytes, on any machine with the same nixpkgs (the flake.lock is part of + the commit). +- **Does not prove:** that the code is good (that is the five test layers' job, ROADMAP §5), nor anything about the + Nix binary cache you build with: a substituted dependency is trusted as Nix trusts it. `nix build --rebuild` and + `--option substitute false` narrow that, at the cost of building everything. + +## For Mark: making the pin before a tag + +On a Linux machine with Nix (WSL2 Debian works), at the commit to be tagged: + +```sh +scripts/nix-pin.sh # builds twice, writes .fabrica/nix/pin.json +git add .fabrica/nix/pin.json && git commit -m "[repo] Release: the Nix pin of X.Y.Z" +``` + +The pin lies outside every package's source, so the commit does not change what it pins. The `release` pipeline's +`pin` step refuses a pin of another version, so a forgotten pin stops the release before anything is published. diff --git a/flake.nix b/flake.nix index c64e23a..2d55a42 100644 --- a/flake.nix +++ b/flake.nix @@ -28,6 +28,31 @@ inherit self; }; + # The tools of the five test layers (ROADMAP §5), for scripts/*.sh, tests/fuzz/run.sh and the + # `layers` pipeline: `nix develop .#ci -c `. + devShells = forAll (pkgs: { + ci = pkgs.mkShell { + packages = with pkgs; [ + cargo + rustc + clippy + rustfmt + cargo-fuzz + cmake + pkg-config + git + jq + caddy + pebble + h2spec + testssl + oha + nodejs_22 + pnpm_11 + ]; + }; + }); + formatter = forAll (pkgs: pkgs.nixfmt-rfc-style); }; } diff --git a/scripts/bench.sh b/scripts/bench.sh new file mode 100755 index 0000000..3a9068c --- /dev/null +++ b/scripts/bench.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +# 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/. +# +# ROADMAP §5 layer 5: load and soak against Caddy, reproducible. Ianitor and two Caddys (as Go +# starts it, and GOMAXPROCS=2 to match edge's two Pingora worker threads) serve the same route +# (tests/diff/src/bin/pair.rs) to the same upstream; oha drives each in turn. Results are +# committed as data: bench/results/-