[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)

This commit is contained in:
2026-11-10 20:43:50 +01:00
parent 0e9c2a7bc9
commit 7a2aee20eb
7 changed files with 722 additions and 14 deletions
+237
View File
@@ -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<S: AsyncRead + AsyncWrite + Unpin>(mut s: S) -> (Duration, Vec<u8>) {
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<String>) -> 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<u16> = 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<u16> = got.iter().map(|r| r.status).collect();
assert_eq!(statuses, vec![200, 200, 200], "{}", edge.stderr());
let paths: Vec<String> = 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());
}
}