From 39dd8f0f472a44edf20ead4376406cac98624089 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 10 Nov 2026 20:46:28 +0100 Subject: [PATCH] [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() + ); } }