Skip to content

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

wasi-http p3: correctly enforce content-length for response bodies (#14822)

Pat Hickey5db2f0b01f92
diff --git a/crates/wasi-http/src/p3/body.rs b/crates/wasi-http/src/p3/body.rs
index ad14d1df52..5a71e0842c 100644
--- a/crates/wasi-http/src/p3/body.rs
+++ b/crates/wasi-http/src/p3/body.rs
@@ -702,21 +702,15 @@ where
#[inline]
fn is_end_stream(&self) -> bool {
- self.body.is_end_stream()
+ // Do not report end of stream before `limit` bytes were sent, otherwise
+ // the consumer might stop polling before a short write is detected in
+ // `poll_frame`.
+ self.sent == self.limit && self.body.is_end_stream()
}
#[inline]
fn size_hint(&self) -> http_body::SizeHint {
- let n = self.limit.saturating_sub(self.sent);
- let mut hint = self.body.size_hint();
- if hint.lower() >= n {
- hint.set_exact(n)
- } else if let Some(max) = hint.upper() {
- hint.set_upper(n.min(max))
- } else {
- hint.set_upper(n)
- }
- hint
+ http_body::SizeHint::with_exact(self.limit.saturating_sub(self.sent))
}
}
@@ -754,7 +748,94 @@ impl<T> BodyExt for T {}
#[cfg(test)]
mod tests {
- use super::channel_capacity;
+ use super::{BodyExt as _, channel_capacity};
+ use crate::Error;
+ use bytes::Bytes;
+ use core::pin::pin;
+ use core::task::{Context, Poll, Waker};
+ use http_body::Body as _;
+ use http_body_util::{BodyExt as _, Full};
+ use tokio::sync::oneshot;
+
+ /// A body shorter than its `Content-Length` must not report end of stream
+ /// or a size hint based on its actual length, otherwise a consumer like
+ /// `hyper` frames the message by the wrong length without ever observing
+ /// the short write.
+ #[test]
+ fn content_length_short_body() {
+ let (error_tx, mut error_rx) = oneshot::channel();
+ let body = Full::new(Bytes::from_static(b"hello"))
+ .map_err(|never| match never {})
+ .with_content_length(10, error_tx, Error::HttpResponseBodySize);
+ let mut body = pin!(body);
+ assert!(!body.is_end_stream());
+ assert_eq!(body.size_hint().exact(), Some(10));
+
+ let mut cx = Context::from_waker(Waker::noop());
+ match body.as_mut().poll_frame(&mut cx) {
+ Poll::Ready(Some(Ok(frame))) => assert_eq!(frame.into_data().unwrap(), "hello"),
+ other => panic!("unexpected poll result: {other:?}"),
+ }
+ assert!(!body.is_end_stream());
+ assert_eq!(body.size_hint().exact(), Some(5));
+
+ match body.as_mut().poll_frame(&mut cx) {
+ Poll::Ready(Some(Err(Error::HttpResponseBodySize(Some(5))))) => {}
+ other => panic!("unexpected poll result: {other:?}"),
+ }
+ assert!(matches!(
+ error_rx.try_recv(),
+ Ok(Error::HttpResponseBodySize(Some(5)))
+ ));
+ }
+
+ /// A body longer than its `Content-Length` must fail before any data
+ /// exceeding the limit is produced.
+ #[test]
+ fn content_length_long_body() {
+ let (error_tx, mut error_rx) = oneshot::channel();
+ let body = Full::new(Bytes::from_static(b"helloworld"))
+ .map_err(|never| match never {})
+ .with_content_length(3, error_tx, Error::HttpResponseBodySize);
+ let mut body = pin!(body);
+ assert!(!body.is_end_stream());
+ assert_eq!(body.size_hint().exact(), Some(3));
+
+ let mut cx = Context::from_waker(Waker::noop());
+ match body.as_mut().poll_frame(&mut cx) {
+ Poll::Ready(Some(Err(Error::HttpResponseBodySize(Some(10))))) => {}
+ other => panic!("unexpected poll result: {other:?}"),
+ }
+ assert!(matches!(
+ error_rx.try_recv(),
+ Ok(Error::HttpResponseBodySize(Some(10)))
+ ));
+ }
+
+ /// A body matching its `Content-Length` is passed through unchanged.
+ #[test]
+ fn content_length_exact_body() {
+ let (error_tx, mut error_rx) = oneshot::channel();
+ let body = Full::new(Bytes::from_static(b"hello"))
+ .map_err(|never| match never {})
+ .with_content_length(5, error_tx, Error::HttpResponseBodySize);
+ let mut body = pin!(body);
+ assert!(!body.is_end_stream());
+ assert_eq!(body.size_hint().exact(), Some(5));
+
+ let mut cx = Context::from_waker(Waker::noop());
+ match body.as_mut().poll_frame(&mut cx) {
+ Poll::Ready(Some(Ok(frame))) => assert_eq!(frame.into_data().unwrap(), "hello"),
+ other => panic!("unexpected poll result: {other:?}"),
+ }
+ assert!(body.is_end_stream());
+ assert_eq!(body.size_hint().exact(), Some(0));
+ assert!(matches!(
+ body.as_mut().poll_frame(&mut cx),
+ Poll::Ready(None)
+ ));
+ assert!(error_rx.try_recv().is_err());
+ }
/// `mpsc::channel` panics above `Semaphore::MAX_PERMITS` and at zero, so the
/// capacity handed to it must always be clamped - including for the huge
diff --git a/crates/wasi-http/src/p3/response.rs b/crates/wasi-http/src/p3/response.rs
index 5cd13174b2..6adf406bd2 100644
--- a/crates/wasi-http/src/p3/response.rs
+++ b/crates/wasi-http/src/p3/response.rs
@@ -1,10 +1,11 @@
use crate::p3::bindings::http::types::ErrorCode;
-use crate::p3::body::{Body, GuestBody};
+use crate::p3::body::{Body, BodyExt as _, GuestBody};
use crate::{Error, FieldMap, WasiHttpCtxView, WasiHttpHooks, WasiHttpView, get_content_length};
use bytes::Bytes;
use http::StatusCode;
use http_body_util::BodyExt as _;
use http_body_util::combinators::UnsyncBoxBody;
+use tokio::sync::oneshot;
use wasmtime::AsContextMut;
use wasmtime::error::Context as _;
@@ -59,30 +60,40 @@ impl Response {
) -> wasmtime::Result<http::Response<UnsyncBoxBody<Bytes, Error>>> {
let res = http::Response::try_from(self)?;
let (res, body) = res.into_parts();
+ // `Content-Length` header value is validated in `fields` implementation
+ let content_length =
+ get_content_length(&res.headers).context("failed to parse `content-length`")?;
let body = match body {
Body::Guest {
contents_rx,
trailers_rx,
result_tx,
- } => {
- // `Content-Length` header value is validated in `fields` implementation
- let content_length =
- get_content_length(&res.headers).context("failed to parse `content-length`")?;
- GuestBody::new(
- store,
- contents_rx,
- trailers_rx,
- result_tx,
- fut,
- content_length,
- ErrorCode::HttpResponseBodySize,
- getter,
- )?
- .boxed_unsync()
- }
+ } => GuestBody::new(
+ store,
+ contents_rx,
+ trailers_rx,
+ result_tx,
+ fut,
+ content_length,
+ ErrorCode::HttpResponseBodySize,
+ getter,
+ )?
+ .boxed_unsync(),
Body::Host { body, result_tx } => {
- _ = result_tx.send(Box::new(fut));
- body
+ if let Some(limit) = content_length {
+ let (http_result_tx, http_result_rx) = oneshot::channel();
+ _ = result_tx.send(Box::new(async move {
+ if let Ok(err) = http_result_rx.await {
+ return Err(err);
+ };
+ fut.await
+ }));
+ body.with_content_length(limit, http_result_tx, Error::HttpResponseBodySize)
+ .boxed_unsync()
+ } else {
+ _ = result_tx.send(Box::new(fut));
+ body
+ }
}
};
Ok(http::Response::from_parts(res, body))
diff --git a/crates/wasi-http/tests/all/p3/mod.rs b/crates/wasi-http/tests/all/p3/mod.rs
index 4f509b4cd7..cdefeb3d5f 100644
--- a/crates/wasi-http/tests/all/p3/mod.rs
+++ b/crates/wasi-http/tests/all/p3/mod.rs
@@ -365,6 +365,72 @@ async fn p3_http_echo_host_to_host() -> Result<()> {
test_http_echo(P3_HTTP_ECHO_COMPONENT, false, true).await
}
+/// A guest forwarding a host body as its response body must not be able to
+/// declare a `content-length` which does not match the body.
+#[test_log::test(tokio::test(flavor = "multi_thread"))]
+async fn p3_http_echo_host_to_host_content_length() -> Result<()> {
+ async fn echo(declared: &str, body: &'static [u8]) -> Result<Result<Bytes, Error>> {
+ let engine = test_programs_artifacts::engine(|config| {
+ config.wasm_component_model_async(true);
+ });
+ let component = Component::from_file(&engine, P3_HTTP_ECHO_COMPONENT)?;
+ let mut store = Store::new(&engine, Ctx::new(oneshot::channel().0));
+ let mut linker = Linker::new(&engine);
+ wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;
+ wasmtime_wasi::p3::add_to_linker(&mut linker)?;
+ wasmtime_wasi_http::p3::add_to_linker(&mut linker)?;
+ let service = Service::instantiate_async(&mut store, &component, &linker).await?;
+
+ // The echo service echoes the request headers, so the request's
+ // `content-length` becomes the response's. The request body is
+ // deliberately not checked against it here, to model a guest which
+ // sets a mismatched `content-length` on a forwarded host body.
+ let req = http::Request::builder()
+ .uri("http://localhost/")
+ .header("x-host-to-host", "true")
+ .header("content-length", declared)
+ .body(http_body_util::Full::new(Bytes::from_static(body)))?;
+ let (req, _io) = Request::from_http(&mut store.data_mut().hooks, req);
+ store
+ .run_concurrent(async |store| {
+ let res = service.handle(store, req).await?.unwrap();
+ let res = store.with(|store| res.into_http(store, async { Ok(()) }))?;
+ assert_eq!(res.headers()["content-length"], declared);
+ let body = res.into_body();
+ // `hyper` frames the response by the size hint and stops
+ // polling once the body reports end of stream, so these must
+ // match the declared length.
+ let declared = declared.parse::<u64>()?;
+ assert_eq!(body.size_hint().exact(), Some(declared));
+ let res = body.collect().await.map(|body| body.to_bytes());
+ Ok(res)
+ })
+ .await?
+ }
+
+ let body = echo("10", b"HELLOWORLD").await?.unwrap();
+ assert_eq!(body, "HELLOWORLD");
+
+ let err = echo("3", b"HELLOWORLD").await?.unwrap_err();
+ assert!(
+ matches!(err, Error::HttpResponseBodySize(Some(10))),
+ "{err:?}"
+ );
+
+ let err = echo("20", b"HELLOWORLD").await?.unwrap_err();
+ assert!(
+ matches!(err, Error::HttpResponseBodySize(Some(10))),
+ "{err:?}"
+ );
+
+ let err = echo("0", b"HTTP/1.1 302 Found\r\n\r\n").await?.unwrap_err();
+ assert!(
+ matches!(err, Error::HttpResponseBodySize(Some(_))),
+ "{err:?}"
+ );
+ Ok(())
+}
+
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_middleware() -> Result<()> {
test_http_middleware(false).await