// 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 { 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 { 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() ); } }