[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());
|
||||
|
||||
Reference in New Issue
Block a user