Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Fix for #12903 (#12904)

karthik-phl92bfb73ca83c
diff --git a/crates/wasi-http/src/p3/body.rs b/crates/wasi-http/src/p3/body.rs
index 0d2da68dac..37f96c0579 100644
--- a/crates/wasi-http/src/p3/body.rs
+++ b/crates/wasi-http/src/p3/body.rs
@@ -484,57 +484,67 @@ where
if self.body.is_end_stream() {
break 'result Ok(None);
} else {
- return Poll::Ready(Ok(StreamResult::Completed));
+ // Destination has zero capacity but the body could still have data. Cannot return
+ // `Completed` (nothing was produced — violates the StreamProducer contract). Fall
+ // through to poll the body with `cap = None` so it buffers the frame.
+ None
}
}
None => None,
};
- match Pin::new(&mut self.body).poll_frame(cx) {
- Poll::Ready(Some(Ok(frame))) => {
- match frame.into_data().map_err(http_body::Frame::into_trailers) {
- Ok(mut frame) => {
- // Libraries like `Reqwest` generate a 0-length frame after sensing end-of-stream,
- // so we have to check for the body's end-of-stream indicator here too
- if frame.len() == 0 && self.body.is_end_stream() {
- break 'result Ok(None);
- }
+ loop {
+ match Pin::new(&mut self.body).poll_frame(cx) {
+ Poll::Ready(Some(Ok(frame))) => {
+ match frame.into_data().map_err(http_body::Frame::into_trailers) {
+ Ok(mut frame) => {
+ if frame.len() == 0 {
+ // Zero-length data frames are valid per the http_body::Body
+ // trait contract and RFC 9113 §6.1 — skip and re-poll
+ // directly rather than using `wake_by_ref()` + Pending, which
+ // would just re-enter this function via the task queue
+ if self.body.is_end_stream() {
+ break 'result Ok(None);
+ }
+ continue;
+ }
- if let Some(cap) = cap {
- let n = frame.len();
- let cap = cap.into();
- if n > cap {
- // data frame does not fit in destination, fill it and buffer the rest
- dst.set_buffer(Cursor::new(frame.split_off(cap)));
- let mut dst = dst.as_direct(store, cap);
- dst.remaining().copy_from_slice(&frame);
- dst.mark_written(cap);
+ if let Some(cap) = cap {
+ let n = frame.len();
+ let cap = cap.into();
+ if n > cap {
+ // data frame does not fit in destination, fill it and buffer the rest
+ dst.set_buffer(Cursor::new(frame.split_off(cap)));
+ let mut dst = dst.as_direct(store, cap);
+ dst.remaining().copy_from_slice(&frame);
+ dst.mark_written(cap);
+ } else {
+ // copy the whole frame into the destination
+ let mut dst = dst.as_direct(store, n);
+ dst.remaining()[..n].copy_from_slice(&frame);
+ dst.mark_written(n);
+ }
} else {
- // copy the whole frame into the destination
- let mut dst = dst.as_direct(store, n);
- dst.remaining()[..n].copy_from_slice(&frame);
- dst.mark_written(n);
+ dst.set_buffer(Cursor::new(frame));
}
- } else {
- dst.set_buffer(Cursor::new(frame));
+ return Poll::Ready(Ok(StreamResult::Completed));
}
- return Poll::Ready(Ok(StreamResult::Completed));
- }
- Err(Ok(trailers)) => {
- let view = (self.getter)(store.data_mut());
- let trailers = FieldMap::new_immutable(trailers);
- let trailers = view
- .table
- .push(trailers)
- .context("failed to push trailers to table")?;
- break 'result Ok(Some(trailers));
+ Err(Ok(trailers)) => {
+ let view = (self.getter)(store.data_mut());
+ let trailers = FieldMap::new_immutable(trailers);
+ let trailers = view
+ .table
+ .push(trailers)
+ .context("failed to push trailers to table")?;
+ break 'result Ok(Some(trailers));
+ }
+ Err(Err(..)) => break 'result Err(ErrorCode::HttpProtocolError),
}
- Err(Err(..)) => break 'result Err(ErrorCode::HttpProtocolError),
}
+ Poll::Ready(Some(Err(err))) => break 'result Err(err),
+ Poll::Ready(None) => break 'result Ok(None),
+ Poll::Pending if finish => return Poll::Ready(Ok(StreamResult::Cancelled)),
+ Poll::Pending => return Poll::Pending,
}
- Poll::Ready(Some(Err(err))) => break 'result Err(err),
- Poll::Ready(None) => break 'result Ok(None),
- Poll::Pending if finish => return Poll::Ready(Ok(StreamResult::Cancelled)),
- Poll::Pending => return Poll::Pending,
}
};
self.close(res);
diff --git a/crates/wasi-http/tests/all/p3/mod.rs b/crates/wasi-http/tests/all/p3/mod.rs
index d46bd157a0..af3fdb0b9f 100644
--- a/crates/wasi-http/tests/all/p3/mod.rs
+++ b/crates/wasi-http/tests/all/p3/mod.rs
@@ -731,3 +731,93 @@ async fn p3_http_data_frame_at_end_of_stream() -> Result<()> {
assert_eq!(collected_body, expected.as_slice());
Ok(())
}
+
+/// Body wrapper that interleaves zero-length data frames with real data.
+///
+/// Zero-length data frames are valid per the `http_body::Body` trait contract and
+/// RFC 9113 §6.1. This wrapper injects `empty_per_frame` empty frames before each
+/// real frame from the inner body, testing that `HostBodyStreamProducer` tolerates them.
+struct BodyWithEmptyFrames {
+ inner: http_body_util::StreamBody<
+ futures::channel::mpsc::Receiver<Result<http_body::Frame<Bytes>, ErrorCode>>,
+ >,
+ /// Number of empty frames to inject before each real frame
+ empty_per_frame: usize,
+ /// Number of empty frames left to inject before the next real frame
+ empty_remaining: usize,
+}
+
+impl http_body::Body for BodyWithEmptyFrames {
+ type Data = Bytes;
+ type Error = ErrorCode;
+
+ fn poll_frame(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ ) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
+ if self.empty_remaining > 0 {
+ self.empty_remaining -= 1;
+ return Poll::Ready(Some(Ok(http_body::Frame::data(Bytes::new()))));
+ }
+ let this = &mut *self;
+ let result = Pin::new(&mut this.inner).poll_frame(cx);
+ if matches!(&result, Poll::Ready(Some(Ok(_)))) {
+ // Reset counter so empty frames are injected before the next real frame
+ this.empty_remaining = this.empty_per_frame;
+ }
+ result
+ }
+
+ fn is_end_stream(&self) -> bool {
+ false
+ }
+}
+
+#[test_log::test(tokio::test(flavor = "multi_thread"))]
+async fn p3_http_empty_frames_interleaved() -> Result<()> {
+ _ = env_logger::try_init();
+
+ // Verifies that zero-length data frames interleaved with real data do not cause
+ // poll_produce to return Completed with 0 items produced.
+ // Pattern: empty, empty, data("hello "), empty, empty, data("world")
+
+ let (mut body_tx, body_rx) = futures::channel::mpsc::channel::<Result<_, ErrorCode>>(2);
+
+ let wrapped_body = BodyWithEmptyFrames {
+ inner: http_body_util::StreamBody::new(body_rx),
+ empty_per_frame: 2,
+ empty_remaining: 2,
+ };
+
+ let request = http::Request::builder()
+ .uri("http://localhost/")
+ .method(http::Method::GET);
+
+ let response = futures::join!(
+ run_http(
+ P3_HTTP_ECHO_COMPONENT,
+ request.body(wrapped_body)?,
+ oneshot::channel().0
+ ),
+ async {
+ body_tx
+ .send(Ok(http_body::Frame::data(Bytes::from_static(b"hello "))))
+ .await
+ .unwrap();
+ body_tx
+ .send(Ok(http_body::Frame::data(Bytes::from_static(b"world"))))
+ .await
+ .unwrap();
+ drop(body_tx);
+ }
+ )
+ .0?
+ .unwrap();
+
+ assert_eq!(response.status().as_u16(), 200);
+
+ let (_, collected_body) = response.into_parts();
+ let collected_body = collected_body.to_bytes();
+ assert_eq!(collected_body, b"hello world".as_slice());
+ Ok(())
+}