[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:
@@ -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<AtomicBool>;
|
||||
}
|
||||
|
||||
/// 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<A> {
|
||||
inner: Arc<A>,
|
||||
timeout: Duration,
|
||||
options: HttpServerOptions,
|
||||
}
|
||||
|
||||
impl<A> HeaderDeadline<A> {
|
||||
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<A> {
|
||||
&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<A> HttpServerApp for HeaderDeadline<A>
|
||||
where
|
||||
A: HttpServerApp + Send + Sync + 'static,
|
||||
{
|
||||
async fn process_new_http(
|
||||
self: &Arc<Self>,
|
||||
session: ServerSession,
|
||||
shutdown: &ShutdownWatch,
|
||||
) -> Option<ReusedHttpStream> {
|
||||
// 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<pingora::protocols::http::v2::server::H2Options> {
|
||||
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<Self>,
|
||||
mut http: ServerSession,
|
||||
_shutdown: &ShutdownWatch,
|
||||
) -> Option<ReusedHttpStream> {
|
||||
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()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ impl HttpServerApp for HttpApp {
|
||||
shutdown: &ShutdownWatch,
|
||||
) -> Option<ReusedHttpStream> {
|
||||
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) {
|
||||
|
||||
+24
-11
@@ -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<PathBuf>,
|
||||
/// Overrides `$CREDENTIALS_DIRECTORY` (tests running several edges in one process).
|
||||
pub credentials_dir: Option<PathBuf>,
|
||||
/// The overall deadline for a request header; default [`deadline::HEADER_TIMEOUT`].
|
||||
pub header_timeout: Option<std::time::Duration>,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
@@ -114,12 +117,19 @@ pub fn server(shared: Arc<Shared>, opts: &Options) -> Result<Server, EdgeError>
|
||||
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<Shared>, opts: &Options) -> Result<Server, EdgeError>
|
||||
|
||||
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);
|
||||
|
||||
|
||||
+13
-2
@@ -3,7 +3,7 @@
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
//! `ianitor-edge --config <edge.json> [--check] [--admin-socket <path>] [--trial-config <path>]
|
||||
//! [--share-revocations <path>] [--acme-root <ca.pem>]`
|
||||
//! [--share-revocations <path>] [--acme-root <ca.pem>] [--header-timeout <secs>]`
|
||||
//!
|
||||
//! 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::<u64>().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 <edge.json> [--check] [--admin-socket <path>] \
|
||||
[--trial-config <path>] [--share-revocations <path>] [--acme-root <ca.pem>]"
|
||||
[--trial-config <path>] [--share-revocations <path>] [--acme-root <ca.pem>] \
|
||||
[--header-timeout <secs>]"
|
||||
);
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
@@ -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<bool> {
|
||||
let rt = self.shared.current();
|
||||
ctx.rt = Some(rt.clone());
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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<u8> {
|
||||
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<usize> {
|
||||
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<Option<(Resp, usize)>> {
|
||||
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<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
mut io: S,
|
||||
reqs: &[Req],
|
||||
idle: Duration,
|
||||
) -> io::Result<Vec<Resp>> {
|
||||
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<Vec<Resp>> {
|
||||
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<RootCertStore>,
|
||||
reqs: &[Req],
|
||||
) -> io::Result<Vec<Resp>> {
|
||||
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<Resp> {
|
||||
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"))?
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user