A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
wasi-http: report body errors from future-trailers (#14656)
Xia Chaod0c68084d84a
diff --git a/crates/test-programs/src/bin/p2_cli_serve_trailers_result.rs b/crates/test-programs/src/bin/p2_cli_serve_trailers_result.rsnew file mode 100644index 0000000000..636ce91952--- /dev/null+++ b/crates/test-programs/src/bin/p2_cli_serve_trailers_result.rs@@ -0,0 +1,64 @@+use test_programs::proxy;+use test_programs::wasi::http::types::{+ Fields, IncomingBody, IncomingRequest, OutgoingBody, OutgoingResponse, ResponseOutparam,+};+use test_programs::wasi::io::streams::StreamError;++struct T;++proxy::export!(T);++impl proxy::exports::wasi::http::incoming_handler::Guest for T {+ fn handle(request: IncomingRequest, outparam: ResponseOutparam) {+ // Reports what the body stream saw and what `future-trailers` said,+ // so one request can assert both together.+ let (read, trailers) = match request.consume() {+ Err(e) => (format!("consume-error={e:?}"), String::from("not-reached")),+ Ok(body) => {+ let read = match body.stream() {+ Err(e) => format!("stream-error={e:?}"),+ Ok(stream) => {+ let mut bytes = 0usize;+ let note = loop {+ match stream.blocking_read(4096) {+ Ok(buf) if buf.is_empty() => break format!("eof bytes={bytes}"),+ Ok(buf) => bytes += buf.len(),+ Err(StreamError::Closed) => break format!("closed bytes={bytes}"),+ Err(StreamError::LastOperationFailed(e)) => {+ break format!(+ "failed bytes={bytes} code={:?}",+ test_programs::wasi::http::types::http_error_code(&e)+ );+ }+ }+ };+ drop(stream);+ note+ }+ };++ let future = IncomingBody::finish(body);+ future.subscribe().block();+ let trailers = match future.get() {+ Some(Ok(Ok(Some(fields)))) => format!("field-count={}", fields.entries().len()),+ Some(Ok(Ok(None))) => String::from("none"),+ Some(Ok(Err(code))) => format!("error-code={code:?}"),+ Some(Err(())) => String::from("outer-error"),+ None => String::from("pending"),+ };+ (read, trailers)+ }+ };++ let resp = OutgoingResponse::new(Fields::new());+ let body = resp.body().expect("outgoing response");+ ResponseOutparam::set(outparam, Ok(resp));+ let out = body.write().expect("outgoing stream");+ out.blocking_write_and_flush(format!("read={read} trailers={trailers}").as_bytes())+ .expect("writing response");+ drop(out);+ OutgoingBody::finish(body, None).expect("outgoing-body.finish");+ }+}++fn main() {}diff --git a/crates/wasi-http/src/p2/body.rs b/crates/wasi-http/src/p2/body.rsindex 2f28ac83a5..994af093da 100644--- a/crates/wasi-http/src/p2/body.rs+++ b/crates/wasi-http/src/p2/body.rs@@ -94,6 +94,10 @@ enum StreamEnd {/// Body was completely read and trailers were read. Here are the trailers./// Note that `None` means that the body finished without trailers.Trailers(Option<http::HeaderMap>),++ /// The body finished with an error. `future-trailers` reports it as well,+ /// so a guest that only reads the trailers still sees the failure.+ Error(Arc<Error>),}/// The concrete type behind the `wasi:io/streams.input-stream` resource returned@@ -102,7 +106,7 @@ enum StreamEnd {pub struct HostIncomingBodyStream {state: IncomingBodyStreamState,buffer: Bytes,- error: Option<Error>,+ error: Option<Arc<Error>>,}impl HostIncomingBodyStream {@@ -136,8 +140,17 @@ impl HostIncomingBodyStream {// Destroy the body to terminate the stream while enqueueing the// error to get returned from the next call to `read`.Some(Err(e)) => {+ // Also tell `future-trailers`. Both paths report the real+ // error, so it's shared rather than replaced by an error-code.+ let tx = match mem::replace(&mut self.state, IncomingBodyStreamState::Closed) {+ IncomingBodyStreamState::Open { tx, .. } => Some(tx),+ IncomingBodyStreamState::Closed => None,+ };+ let e = Arc::new(e);+ if let Some(tx) = tx {+ let _ = tx.send(StreamEnd::Error(Arc::clone(&e)));+ }self.error = Some(e);- self.state = IncomingBodyStreamState::Closed;}// No more frames are going to be received again, so drop the `body`@@ -256,7 +269,7 @@ pub enum HostFutureTrailers {////// Note that `Ok(None)` means that there were no trailers for this request/// while `Ok(Some(_))` means that trailers were found in the request.- Done(Result<Option<http::HeaderMap>, Error>),+ Done(Result<Option<http::HeaderMap>, Arc<Error>>),/// Trailers have been consumed by `future-trailers.get`.Consumed,@@ -284,6 +297,12 @@ impl Pollable for HostFutureTrailers {// were reached. It's up to us now to complete the body.Ok(StreamEnd::Remaining(b)) => body.body = IncomingBodyState::Start(b),+ // The body itself errored out, so report that through this+ // future as its contract requires.+ Ok(StreamEnd::Error(e)) => {+ *self = HostFutureTrailers::Done(Err(e));+ }+// This means there were no trailers present.Ok(StreamEnd::Trailers(None)) | Err(_) => {*self = HostFutureTrailers::Done(Ok(None));@@ -305,7 +324,7 @@ impl Pollable for HostFutureTrailers {let result = loop {match hyper_body.frame().await {None => break Ok(None),- Some(Err(e)) => break Err(e),+ Some(Err(e)) => break Err(Arc::new(e)),Some(Ok(frame)) => {// If this frame is a data frame ignore it as we're only// interested in trailers.diff --git a/crates/wasi-http/src/p2/types_impl.rs b/crates/wasi-http/src/p2/types_impl.rsindex 7e968f469a..d436160498 100644--- a/crates/wasi-http/src/p2/types_impl.rs+++ b/crates/wasi-http/src/p2/types_impl.rs@@ -31,6 +31,9 @@ impl types::Host for WasiHttpCtxView<'_> {if let Some(e) = e.downcast_ref::<crate::Error>() {return Ok(Some(self.hooks.error_to_p2(e)));}+ if let Some(e) = e.downcast_ref::<std::sync::Arc<crate::Error>>() {+ return Ok(Some(self.hooks.error_to_p2(e)));+ }Ok(e.downcast_ref::<types::ErrorCode>().cloned())}}diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rsindex cfadc273c3..368ead3431 100644--- a/tests/all/cli_tests.rs+++ b/tests/all/cli_tests.rs@@ -2176,6 +2176,77 @@ start a print 1234Ok(())}+ // A body can fail to parse after the guest read part of it.+ // `future-trailers` must report an error, not a successful body.+ #[tokio::test]+ async fn p2_cli_serve_trailers_result() -> Result<()> {+ let server = WasmtimeServe::new(P2_CLI_SERVE_TRAILERS_RESULT_COMPONENT, |cmd| {+ cmd.arg("-Scli");+ })?;++ async fn request(server: &WasmtimeServe, raw: &[u8]) -> Result<String> {+ let mut stream = TcpStream::connect(server.first_addr()).await?;+ stream.write_all(raw).await?;+ let mut response = Vec::new();+ let mut buf = [0; 1024];+ loop {+ let n = tokio::time::timeout(Duration::from_secs(10), stream.read(&mut buf))+ .await+ .expect("timed out waiting for a response")?;+ if n == 0 {+ break;+ }+ response.extend_from_slice(&buf[..n]);+ }+ String::from_utf8(response).map_err(Into::into)+ }++ let malformed: &[(&str, &[u8])] = &[+ (+ "empty trailer name",+ b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n: v\r\n\r\n",+ ),+ (+ "trailer without a colon",+ b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nBadTrailer\r\n\r\n",+ ),+ (+ "trailer with a NUL",+ b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nX-T: a\x00b\r\n\r\n",+ ),+ (+ "extra zero chunk",+ b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n0\r\n\r\n",+ ),+ ];+ for (name, raw) in malformed {+ let response = request(&server, raw).await?;+ assert!(+ response.contains("trailers=error-code=ErrorCode::HttpProtocolError"),+ "{name}: {response:?}",+ );+ }++ // A well-formed body still reports success: once without trailers and+ // once with a single trailer.+ let response = request(+ &server,+ b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n",+ )+ .await?;+ assert!(response.contains("trailers=none"), "{response:?}");++ let response = request(+ &server,+ b"POST / HTTP/1.1\r\nHost: a\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nX-T: v\r\n\r\n",+ )+ .await?;+ assert!(response.contains("trailers=field-count=1"), "{response:?}");++ server.finish()?;+ Ok(())+ }+#[test]fn p2_cli_argv0() -> Result<()> {run_wasmtime(&["run", "--argv0=a", P2_CLI_ARGV0, "a"])?;