[bug] Downstream HTTP/2 response-body writes have no deadline: a never-reading client parks the stream forever
Describe the bug
A downstream HTTP/2 stream parks permanently in the response-body write. A client can send a complete request, keep the stream open, and stop reading; the proxy then waits for flow-control capacity that the client never grants and that no deadline bounds. For HTTP/2 this wait happens in h2's capacity reservation, and it ends only when the peer reads, resets the stream, or closes the connection.
The stalled stream stays active, so the connection-level h2_idle_timeout does not apply: the accept loop starts its idle timer only after the active-stream count reaches zero. One stalled stream therefore pins the request task, the HTTP/2 stream, the connection, and the upstream session that the duplex loop holds until the downstream half returns.
The client sends no RST_STREAM and keeps its connection open, so no event can end the wait. The same state arises from a slow reader or from a client that crashes while its TCP connection stays open. Two listener configurations are affected: plaintext with h2c: true, and TLS with ALPN h2. No credentials and no malformed input are required.
Root cause
1. The proxy writes the response through write_response_tasks
The response path (process_upstream_tasks_h2, and the cache branch at pingora-proxy/src/proxy_h2.rs:721) hands every response task to Session::write_response_tasks, which forwards the batch to the downstream session.
// pingora-proxy/src/proxy_h2.rs:478-483
if !serve_from_cache.should_send_to_downstream() {
// TODO: need to derive response_done from filtered_tasks in case downstream failed already
return Ok(None);
}
let response_done = session.write_response_tasks(filtered_tasks).await?;// pingora-proxy/src/lib.rs:886-894
pub async fn write_response_tasks(&mut self, mut tasks: Vec<HttpTask>) -> Result<bool> {
let mut seen_upgraded = self.downstream_task_seen_upgraded || self.was_upgraded();
for task in tasks.iter_mut() {
self.downstream_response_task_filter(task, &mut seen_upgraded)
.await?;
}
self.downstream_task_seen_upgraded = seen_upgraded;
self.downstream_session.response_duplex_vec(tasks).await
}2. response_duplex_vec calls write_body for every body task
// pingora-core/src/protocols/http/v2/server.rs:753-772
pub async fn response_duplex_vec(&mut self, tasks: Vec<HttpTask>) -> Result<bool> {
let mut end_stream = false;
for task in tasks.into_iter() {
end_stream = match task {
HttpTask::Header(header, end) => {
self.write_response_header(header, end)
.map_err(|e| e.into_down())?;
end
}
HttpTask::Body(data, end) => match data {
Some(d) => {
if !d.is_empty() {
self.write_body(d, end).await.map_err(|e| e.into_down())?;
}
end
}
None => end,
},3. write_body applies a deadline only when write_timeout is set
// pingora-core/src/protocols/http/v2/server.rs:666-677
pub async fn write_body(&mut self, data: Bytes, end: bool) -> Result<()> {
match self.write_timeout {
Some(t) => match timeout(t, self.do_write_body(data, end)).await {
Ok(res) => res,
Err(_) => Error::e_explain(
ErrorType::WriteTimedout,
format!("writing body, timeout: {t:?}"),
),
},
None => self.do_write_body(data, end).await,
}
}do_write_body forwards the same optional value to the bottom-level helper (super::write_body(writer, data, end, self.write_timeout), :693).
4. The blocking point is the capacity reservation, and the bottom-level helper has the same None branch
// pingora-core/src/protocols/http/v2/mod.rs:28-49
async fn reserve_and_send(
writer: &mut SendStream<Bytes>,
remaining: &mut Bytes,
end: bool,
) -> Result<()> {
// reserve remaining bytes then wait
writer.reserve_capacity(remaining.len());
let res = std::future::poll_fn(|cx| writer.poll_capacity(cx)).await;
match res {
None => Error::e_explain(H2Error, "cannot reserve capacity"),
Some(ready) => {
let n = ready.or_err(H2Error, "while waiting for capacity")?;
let remaining_size = remaining.len();
let data_to_send = remaining.split_to(std::cmp::min(remaining_size, n));
writer
.send_data(data_to_send, remaining.is_empty() && end)
.or_err(WriteError, "while writing h2 request body")?;
Ok(())
}
}
}// pingora-core/src/protocols/http/v2/mod.rs:52-82
pub async fn write_body(
writer: &mut SendStream<Bytes>,
data: Bytes,
end: bool,
write_timeout: Option<Duration>,
) -> Result<()> {
let mut remaining = data;
// Cannot poll 0 capacity, so send it directly.
if remaining.is_empty() {
writer
.send_data(remaining, end)
.or_err(WriteError, "while writing h2 request body")?;
return Ok(());
}
loop {
match write_timeout {
Some(t) => match timeout(t, reserve_and_send(writer, &mut remaining, end)).await {
Ok(res) => res?,
Err(_) => Error::e_explain(
WriteTimedout,
format!("while writing h2 request body, timeout: {t:?}"),
)?,
},
None => {
reserve_and_send(writer, &mut remaining, end).await?;
}
}
if remaining.is_empty() {
return Ok(());
}
}
}writer.poll_capacity(cx) resolves only when the peer frees stream or connection window credit. A client that never reads never sends WINDOW_UPDATE, so the None branch stays pending for the whole response body.
5. write_timeout defaults to None
The field is public and honored when set, but every constructed session leaves it unset.
// pingora-core/src/protocols/http/v2/server.rs:288-293
/// The write timeout which will be applied to writing response body.
/// The timeout is reset on every write. This is not a timeout on the overall duration of the
/// response.
pub write_timeout: Option<Duration>,
// How long to wait when draining (discarding) request body
total_drain_timeout: Option<Duration>,// pingora-core/src/protocols/http/v2/server.rs:489-502
Ok(Some(H2Accept::Session(HttpSession {
request_header,
request_body_reader,
send_response,
send_response_body: None,
response_written: None,
ended: false,
body_read: 0,
body_sent: 0,
retry_buffer: None,
digest,
write_timeout: None,
total_drain_timeout: None,
})))default_h2_options() (:69-74) sets a header-list limit and a concurrent-stream limit, and does not set a write deadline.
6. The per-stream guard is moved into the task and held for its whole lifetime
// pingora-core/src/apps/mod.rs:346-356
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;
// Note, `PersistentSettings` not currently relevant for h2
app.process_new_http(
ServerSession::<DS>::new_http2_with_custom_session(h2_stream),
&shutdown,
)
.await;
});7. The guard keeps the active-stream count above zero
// pingora-core/src/protocols/http/v2/server.rs:206-214
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();
}
}
}8. The connection idle timer starts only after every active stream finishes
// pingora-core/src/protocols/http/v2/server.rs:171-179
// Any accepted stream cancels this future. The next iteration
// waits for all active streams to finish before starting a fresh
// idle period.
_ = wait_for_idle_timeout(&active, idle_timeout.unwrap_or_default()), if idle_timeout.is_some() => {
// Idle with nothing in flight: drop `conn` to close the
// socket now (no graceful GOAWAY wait that could hang on
// a dead peer).
return;
}// pingora-core/src/protocols/http/v2/server.rs:241-246
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;
}
}With one parked stream the count never returns to zero (:229-238), so the sleep never starts and a configured h2_idle_timeout never fires.
9. The upstream half is held until the downstream half returns
// pingora-proxy/src/proxy_h2.rs:306-319
let ret = tokio::try_join!(
self.bidirection_down_to_up(
session,
&mut client_body,
rx,
ctx,
write_timeout,
&mut downstream_custom_message_writer,
&mut downstream_custom_message_reader,
pipe_state.clone(),
),
pipe_up_to_down_response(client_session, tx, pipe_state)
);The downstream half does not return, so the upstream Http2Session or HTTP/1 connection is not released back to the pool.
10. Other bounds do not apply
| Bound | Why it does not end the wait |
|---|---|
write_timeout (v2/server.rs:666-677) |
Defaults to None; when set, it covers a single write, not the whole response |
h2_idle_timeout |
The active-stream count stays above zero, so wait_for_idle_timeout never starts |
HTTP/1 downstream read_timeout (default 60s, v1/server.rs:189) |
Covers the read direction only; the HTTP/2 session has no counterpart field |
total_drain_timeout |
Wraps drain_request_body only (v2/server.rs:576-588) and defaults to None |
Upstream read_timeout |
Defaults to None (upstreams/peer.rs:579); even when set it ends the upstream read, not the downstream write |
| TCP keepalive | Optional on listeners and disabled by default; the connection is not idle at the application layer |
Runtime::shutdown_timeout |
Reclaims these tasks only when the process receives a shutdown signal |
The HTTP/1 downstream write has the same shape: write_body applies a deadline only when write_timeout is set, and it defaults to None (v1/server.rs:190, :972-981).
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 (the 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/pingora_f3_h2_downstream_write_stall.rs and run:
cargo +nightly-2026-03-21 test -p pingora-core --test pingora_f3_h2_downstream_write_stall -- --nocaptureOn the current tree both tests fail after the 5-second bound. That failure is the reproduction.
pingora-core/tests/pingora_f3_h2_downstream_write_stall.rs (runnable test file)//! F3: a downstream HTTP/2 client that completes its request and never reads
//! parks the proxy in the response-body write; the stream stays active, so
//! `h2_idle_timeout` never reclaims the connection.
//!
//! Integration: `pingora-core/tests/pingora_f3_h2_downstream_write_stall.rs`
//! Run: cargo +nightly-2026-03-21 test -p pingora-core --test pingora_f3_h2_downstream_write_stall -- --nocapture
//! On the audited tree both tests fail with VULNERABILITY REPRODUCED.
//! Audited commit: 4487f7b2ab50f159e4a2cf4f6a6b813f61bb6e19
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 pingora_error::BError;
use pingora_http::ResponseHeader;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::time::timeout;
const BOUND: Duration = Duration::from_secs(5);
const IDLE: Duration = Duration::from_secs(1);
// Larger than any default H2 flow-control window, so the write can only
// complete if the peer reads.
const BODY_CHUNK: usize = 32 * 1024;
const BODY_CHUNKS: usize = 256;
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 },
))))
}
/// Client: complete POST, then hold the response stream without reading it,
/// sending no RST_STREAM and keeping the connection open.
async fn spawn_write_stalled_client(io: tokio::io::DuplexStream) -> tokio::task::JoinHandle<()> {
let (send_req, conn) = h2::client::handshake(io).await.unwrap();
let conn_task = 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", "4")
.body(())
.unwrap();
let (resp, mut body) = send_req.send_request(req, false).unwrap();
body.send_data(bytes::Bytes::from_static(b"ping"), true)
.unwrap();
tokio::spawn(async move {
let _keep_alive = (send_req, resp, body);
std::future::pending::<()>().await;
});
conn_task
}
/// `H2Connection` is private to the crate, so name the concrete h2 type here.
async fn accept_one_session(
conn: &mut h2::server::Connection<Stream, bytes::Bytes>,
) -> HttpSession {
loop {
match HttpSession::from_h2_conn(conn, Arc::new(Digest::default()))
.await
.expect("accept failed")
{
Some(H2Accept::Session(session)) => return session,
Some(H2Accept::Rejected) => continue,
None => panic!("connection closed before a stream was accepted"),
}
}
}
/// Production write path with `write_timeout` left at its default `None`.
#[tokio::test]
async fn h2_response_body_write_must_not_park_forever_on_a_read_stalling_client() {
let (server_io, client_io) = tokio::io::duplex(64 * 1024);
let client = spawn_write_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 mut session = timeout(BOUND, accept_one_session(&mut conn))
.await
.expect("stream accept timed out");
let mut header = ResponseHeader::build(200, None).unwrap();
header
.append_header("content-length", (BODY_CHUNK * BODY_CHUNKS).to_string())
.unwrap();
session
.write_response_header(Box::new(header), false)
.unwrap();
let write = timeout(BOUND, async {
for _ in 0..BODY_CHUNKS {
session
.write_body(bytes::Bytes::from(vec![b'x'; BODY_CHUNK]), false)
.await?;
}
Ok::<_, BError>(())
})
.await;
client.abort();
assert!(
write.is_ok(),
"VULNERABILITY REPRODUCED: the downstream HTTP/2 response-body write \
was still pending after {BOUND:?}. `write_body()` applies no deadline \
when `write_timeout` is `None` (v2/server.rs:666-677), so \
`h2::SendStream::send_data()` waits forever for a client that keeps the \
stream open, completes the request and never reads the response."
);
}
struct WriteStallApp {
options: HttpServerOptions,
entered: Arc<AtomicBool>,
returned: Arc<AtomicBool>,
}
#[async_trait]
impl HttpServerApp for WriteStallApp {
async fn process_new_http(
self: &Arc<Self>,
mut session: ServerSession,
_shutdown: &ShutdownWatch,
) -> Option<ReusedHttpStream> {
let _ = session.read_body_or_idle(false).await;
let mut header = ResponseHeader::build(200, None).unwrap();
let _ = header.append_header("content-length", (BODY_CHUNK * BODY_CHUNKS).to_string());
let _ = session.write_response_header(Box::new(header)).await;
self.entered.store(true, Ordering::SeqCst);
for _ in 0..BODY_CHUNKS {
if session
.write_response_body(bytes::Bytes::from(vec![b'x'; BODY_CHUNK]), false)
.await
.is_err()
{
break;
}
}
self.returned.store(true, Ordering::SeqCst);
None
}
fn server_options(&self) -> Option<&HttpServerOptions> {
Some(&self.options)
}
}
/// Production accept path with `h2_idle_timeout = 1s`: the parked stream keeps
/// `ActiveSessions` non-zero, so the idle branch never runs.
#[tokio::test]
async fn h2_idle_timeout_must_reclaim_a_stream_stalled_on_a_response_write() {
let mut options = HttpServerOptions::default();
options.h2c = true;
options.h2_idle_timeout = Some(IDLE);
let app = Arc::new(WriteStallApp {
options,
entered: Arc::new(AtomicBool::new(false)),
returned: Arc::new(AtomicBool::new(false)),
});
let (server_io, client_io) = tokio::io::duplex(64 * 1024);
let client = spawn_write_stalled_client(client_io).await;
let (_shutdown_tx, shutdown) = tokio::sync::watch::channel(falsSource: cloudflare/pingora