Skip to content

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

51.4 KB
Raw Blame
use crate::http_server::Server;
use bytes::Bytes;
use flate2::Compression;
use flate2::write::{DeflateDecoder, DeflateEncoder};
use futures::SinkExt;
use futures::channel::oneshot;
use http::HeaderValue;
use http_body::Body;
use http_body_util::{BodyExt as _, Collected, Empty};
use std::io::Write;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use test_programs_artifacts::*;
use tokio::{fs, try_join};
use wasm_compose::composer::ComponentComposer;
use wasm_compose::config::{Config, Dependency, Instantiation, InstantiationArg};
use wasmtime::component::{Component, Linker, ResourceTable};
use wasmtime::{Result, Store, ToWasmtimeResult as _, error::Context as _, format_err};
use wasmtime_wasi::p3::bindings::Command;
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
use wasmtime_wasi_http::p3::Request;
use wasmtime_wasi_http::p3::bindings::Service;
use wasmtime_wasi_http::p3::bindings::http::types::ErrorCode;
use wasmtime_wasi_http::{
    DEFAULT_FORBIDDEN_HEADERS, Error, ForbiddenHeaderFilter, RequestOptions, WasiBody, WasiHttpCtx,
    WasiHttpCtxView, WasiHttpHooks, WasiHttpView, default_send_request,
};

foreach_p3_http!(assert_test_exists);

/// Channel over which a request forwarded to one of the `p3-test*` endpoints is
/// sent once its body has been collected, or the error encountered while
/// collecting it.
type ForwardedRequestTx = oneshot::Sender<Result<http::Request<Collected<Bytes>>, Error>>;

/// An extension the host attaches to a request passed to the guest.
#[derive(Clone, Debug, PartialEq)]
struct RequestMarker(&'static str);

/// An extension `TestHooks::send_request` attaches to the response for
/// `p3-test-extensions`.
#[derive(Clone, Debug, PartialEq)]
struct ResponseMarker(&'static str);

#[derive(Default)]
struct TestHooks {
    request_tx: Option<ForwardedRequestTx>,
    io_dropped_tx: Option<oneshot::Sender<()>>,
}

impl TestHooks {
    fn new(request_tx: Option<ForwardedRequestTx>) -> Self {
        Self {
            request_tx,
            ..Self::default()
        }
    }
}

/// Collects the body of `request`, and then sends it, or the error encountered
/// while collecting it, over the channel if present.
async fn collect_request(
    request: http::Request<WasiBody>,
    request_tx: Option<ForwardedRequestTx>,
) -> Result<(), Error> {
    let (parts, body) = request.into_parts();
    let result = body.collect().await;
    let Some(request_tx) = request_tx else {
        return result.map(|_body| ());
    };
    match result {
        Ok(body) => {
            _ = request_tx.send(Ok(http::Request::from_parts(parts, body)));
        }
        Err(err) => {
            _ = request_tx.send(Err(err));
        }
    }
    Ok(())
}

impl WasiHttpHooks for TestHooks {
    fn forbidden_header_filter(&mut self) -> ForbiddenHeaderFilter {
        Arc::new(|name| {
            name.as_str() == "custom-forbidden-header" || DEFAULT_FORBIDDEN_HEADERS.contains(name)
        })
    }

    fn send_request(
        &mut self,
        request: http::Request<WasiBody>,
        options: Option<RequestOptions>,
        fut: Box<dyn Future<Output = Result<(), Error>> + Send>,
    ) -> Box<
        dyn Future<
                Output = Result<
                    (
                        http::Response<WasiBody>,
                        Box<dyn Future<Output = Result<(), Error>> + Send>,
                    ),
                    Error,
                >,
            > + Send,
    > {
        _ = fut;
        if let Some("p3-test") = request.uri().authority().map(|v| v.as_str()) {
            // The default test case reads the entire request before responding.
            let request_tx = self.request_tx.take();
            Box::new(async move {
                collect_request(request, request_tx).await?;
                Ok((
                    http::Response::new(Default::default()),
                    Box::new(async { Ok(()) }) as Box<dyn Future<Output = _> + Send>,
                ))
            })
        } else if let Some("p3-test-immediate-response") =
            request.uri().authority().map(|v| v.as_str())
        {
            // Respond immediately, collecting the request body in the
            // background after the response is returned.
            let request_tx = self.request_tx.take();
            tokio::spawn(collect_request(request, request_tx));
            Box::new(async {
                Ok((
                    http::Response::new(Default::default()),
                    Box::new(async { Ok(()) }) as Box<dyn Future<Output = _> + Send>,
                ))
            })
        } else if let Some("p3-test-keep-open") = request.uri().authority().map(|v| v.as_str()) {
            // Simulate a long-running connection by returning an `io` future
            // that owns the request and never resolves. `io_dropped_tx` is
            // dropped along with it, which the test observes to tell whether
            // the I/O was cancelled.
            let io_dropped_tx = self.io_dropped_tx.take();
            Box::new(async {
                Ok((
                    http::Response::new(Default::default()),
                    Box::new(async move {
                        let _request = request;
                        let _io_dropped_tx = io_dropped_tx;
                        std::future::pending::<()>().await;
                        Ok(())
                    }) as Box<dyn Future<Output = _> + Send>,
                ))
            })
        } else if let Some("p3-test-extensions") = request.uri().authority().map(|v| v.as_str()) {
            // Like `p3-test`, but the response carries an extension, for
            // checking that extensions survive a trip through the guest.
            let request_tx = self.request_tx.take();
            Box::new(async move {
                collect_request(request, request_tx).await?;
                let mut response = http::Response::new(Default::default());
                response
                    .extensions_mut()
                    .insert(ResponseMarker("from send_request"));
                Ok((
                    response,
                    Box::new(async { Ok(()) }) as Box<dyn Future<Output = _> + Send>,
                ))
            })
        } else if let Some("p3-test-trailers") = request.uri().authority().map(|v| v.as_str()) {
            let request_tx = self.request_tx.take();
            let body = http_body_util::StreamBody::new(futures::stream::iter([
                Ok(http_body::Frame::data(Bytes::from_static(b"response"))),
                Ok(http_body::Frame::trailers(forbidden_trailers())),
            ]));
            Box::new(async move {
                collect_request(request, request_tx).await?;
                Ok((
                    http::Response::new(body.boxed_unsync()),
                    Box::new(async { Ok(()) }) as Box<dyn Future<Output = _> + Send>,
                ))
            })
        } else {
            Box::new(async move {
                use http_body_util::BodyExt;

                let (res, io) = default_send_request(request, options).await?;
                Ok((
                    res.map(BodyExt::boxed_unsync),
                    Box::new(io) as Box<dyn Future<Output = _> + Send>,
                ))
            })
        }
    }
}

struct Ctx {
    table: ResourceTable,
    wasi: WasiCtx,
    http: WasiHttpCtx,
    hooks: TestHooks,
}

impl Ctx {
    fn new() -> Self {
        Self::with_hooks(TestHooks::new(None))
    }

    fn with_hooks(hooks: TestHooks) -> Self {
        Self {
            table: ResourceTable::default(),
            wasi: WasiCtxBuilder::new().inherit_stdio().build(),
            http: WasiHttpCtx::new(),
            hooks,
        }
    }
}

impl WasiView for Ctx {
    fn ctx(&mut self) -> WasiCtxView<'_> {
        WasiCtxView {
            ctx: &mut self.wasi,
            table: &mut self.table,
        }
    }
}

impl WasiHttpView for Ctx {
    fn http(&mut self) -> WasiHttpCtxView<'_> {
        WasiHttpCtxView {
            ctx: &mut self.http,
            table: &mut self.table,
            hooks: &mut self.hooks,
        }
    }
}

async fn run_cli(path: &str, server: &Server) -> wasmtime::Result<()> {
    let engine = test_programs_artifacts::engine(|config| {
        config.wasm_backtrace_details(wasmtime::WasmBacktraceDetails::Enable);
        config.wasm_component_model_async(true);
    });
    let component = Component::from_file(&engine, path)?;
    let mut store = Store::new(
        &engine,
        Ctx {
            wasi: wasmtime_wasi::WasiCtx::builder()
                .env("HTTP_SERVER", server.addr())
                .inherit_stdio()
                .build(),
            ..Ctx::new()
        },
    );
    let mut linker = Linker::new(&engine);
    wasmtime_wasi::p2::add_to_linker_async(&mut linker)
        .context("failed to link `wasi:[email protected]`")?;
    wasmtime_wasi::p3::add_to_linker(&mut linker).context("failed to link `wasi:[email protected]`")?;
    wasmtime_wasi_http::p3::add_to_linker(&mut linker)
        .context("failed to link `wasi:[email protected]`")?;
    let command = Command::instantiate_async(&mut store, &component, &linker).await?;
    store
        .run_concurrent(async |store| command.wasi_cli_run().call_run(store).await)
        .await
        .context("failed to call `wasi:cli/run#run`")?
        .context("guest trapped")?
        .map_err(|()| format_err!("`wasi:cli/run#run` failed"))
}

/// Run the `p3_http_api_bench` guest for a single iteration of each API to
/// make sure it keeps working.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_api_bench() -> Result<()> {
    let engine = test_programs_artifacts::engine(|config| {
        config.wasm_backtrace_details(wasmtime::WasmBacktraceDetails::Enable);
        config.wasm_component_model_async(true);
    });
    let component = Component::from_file(&engine, P3_HTTP_API_BENCH_COMPONENT)?;
    let mut linker = Linker::new(&engine);
    wasmtime_wasi::p2::add_to_linker_async(&mut linker)
        .context("failed to link `wasi:[email protected]`")?;
    wasmtime_wasi::p3::add_to_linker(&mut linker).context("failed to link `wasi:[email protected]`")?;
    wasmtime_wasi_http::p3::add_to_linker(&mut linker)
        .context("failed to link `wasi:[email protected]`")?;

    for api in ["request.new", "response.consume-body", "client.send"] {
        // `TestHooks` only accepts a single request to `p3-test*`, so use a
        // fresh store and a single iteration for each API.
        let mut store = Store::new(
            &engine,
            Ctx {
                wasi: WasiCtxBuilder::new()
                    .args(&["p3_http_api_bench", api, "1"])
                    .inherit_stdio()
                    .build(),
                ..Ctx::new()
            },
        );
        let command = Command::instantiate_async(&mut store, &component, &linker).await?;
        store
            .run_concurrent(async |store| command.wasi_cli_run().call_run(store).await)
            .await
            .context("failed to call `wasi:cli/run#run`")?
            .context("guest trapped")?
            .map_err(|()| format_err!("`{api}` failed"))?;
    }
    Ok(())
}

async fn run_http<E: Into<Error> + 'static>(
    component_filename: &str,
    req: http::Request<impl Body<Data = Bytes, Error = E> + Send + Sync + 'static>,
) -> wasmtime::Result<Result<http::Response<Collected<Bytes>>, Option<ErrorCode>>> {
    run_http_with_hooks(component_filename, req, TestHooks::new(None)).await
}

/// Like [`run_http`], but sends the request forwarded by the guest to one of
/// the `p3-test*` endpoints on `request_tx`, or the error encountered while
/// collecting its body.
async fn run_http_forwarded<E: Into<Error> + 'static>(
    component_filename: &str,
    req: http::Request<impl Body<Data = Bytes, Error = E> + Send + Sync + 'static>,
    request_tx: ForwardedRequestTx,
) -> wasmtime::Result<Result<http::Response<Collected<Bytes>>, Option<ErrorCode>>> {
    run_http_with_hooks(component_filename, req, TestHooks::new(Some(request_tx))).await
}

async fn run_http_with_hooks<E: Into<Error> + 'static>(
    component_filename: &str,
    req: http::Request<impl Body<Data = Bytes, Error = E> + Send + Sync + 'static>,
    hooks: TestHooks,
) -> wasmtime::Result<Result<http::Response<Collected<Bytes>>, Option<ErrorCode>>> {
    let engine = test_programs_artifacts::engine(|config| {
        config.wasm_backtrace_details(wasmtime::WasmBacktraceDetails::Enable);
        config.wasm_component_model_async(true);
    });
    let component = Component::from_file(&engine, component_filename)?;

    let mut store = Store::new(&engine, Ctx::with_hooks(hooks));

    let mut linker = Linker::new(&engine);
    wasmtime_wasi::p2::add_to_linker_async(&mut linker)
        .context("failed to link `wasi:[email protected]`")?;
    wasmtime_wasi::p3::add_to_linker(&mut linker).context("failed to link `wasi:[email protected]`")?;
    wasmtime_wasi_http::p3::add_to_linker(&mut linker)
        .context("failed to link `wasi:[email protected]`")?;
    let service = Service::instantiate_async(&mut store, &component, &linker).await?;
    let (req, io) = Request::from_http(&mut store.data_mut().hooks, req);
    store
        .run_concurrent(async |store| {
            let (res, ()) = try_join!(
                async {
                    let res = match service.handle(store, req).await? {
                        Ok(res) => res,
                        Err(err) => return Ok(Err(Some(err))),
                    };
                    let res = store.with(|store| res.into_http(store, async { Ok(()) }))?;
                    let (parts, body) = res.into_parts();
                    let body = body.collect().await.context("failed to collect body")?;
                    wasmtime::error::Ok(Ok(http::Response::from_parts(parts, body)))
                },
                async { io.await.context("failed to consume request body") }
            )?;
            Ok(res)
        })
        .await?
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_get() -> wasmtime::Result<()> {
    let server = Server::http1(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_GET_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_between_bytes_timeout() -> wasmtime::Result<()> {
    let server = Server::http1_stalled_body(1, std::time::Duration::from_secs(5))?;
    run_cli(
        P3_HTTP_OUTBOUND_REQUEST_BETWEEN_BYTES_TIMEOUT_COMPONENT,
        &server,
    )
    .await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_first_byte_timeout() -> wasmtime::Result<()> {
    let server = Server::http1_delayed(1, std::time::Duration::from_secs(5))?;
    run_cli(
        P3_HTTP_OUTBOUND_REQUEST_FIRST_BYTE_TIMEOUT_COMPONENT,
        &server,
    )
    .await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_timeout() -> wasmtime::Result<()> {
    let server = Server::http1(3)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_TIMEOUT_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_post() -> wasmtime::Result<()> {
    let server = Server::http1(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_POST_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_large_post() -> wasmtime::Result<()> {
    let server = Server::http1(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_LARGE_POST_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_long_path() -> wasmtime::Result<()> {
    let server = Server::http1(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_LONG_PATH_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_put() -> wasmtime::Result<()> {
    let server = Server::http1(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_PUT_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_invalid_version() -> wasmtime::Result<()> {
    let server = Server::http2(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_INVALID_VERSION_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_invalid_header() -> wasmtime::Result<()> {
    let server = Server::http2(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_INVALID_HEADER_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_unknown_method() -> wasmtime::Result<()> {
    let server = Server::http1(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_UNKNOWN_METHOD_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_unsupported_scheme() -> wasmtime::Result<()> {
    let server = Server::http1(1)?;
    run_cli(
        P3_HTTP_OUTBOUND_REQUEST_UNSUPPORTED_SCHEME_COMPONENT,
        &server,
    )
    .await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_invalid_port() -> wasmtime::Result<()> {
    let server = Server::http1(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_INVALID_PORT_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_invalid_dnsname() -> wasmtime::Result<()> {
    let server = Server::http1(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_INVALID_DNSNAME_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_response_build() -> wasmtime::Result<()> {
    let server = Server::http1(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_RESPONSE_BUILD_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_forward_duplicate_content_length() -> wasmtime::Result<()> {
    crate::shared::forward_duplicate_content_length(async |server| {
        run_cli(
            P3_HTTP_OUTBOUND_REQUEST_FORWARD_DUPLICATE_CONTENT_LENGTH_COMPONENT,
            server,
        )
        .await
    })
    .await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_content_length() -> wasmtime::Result<()> {
    let server = Server::http1(4)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_CONTENT_LENGTH_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_missing_path_and_query() -> wasmtime::Result<()> {
    let server = Server::http1(1)?;
    run_cli(
        P3_HTTP_OUTBOUND_REQUEST_MISSING_PATH_AND_QUERY_COMPONENT,
        &server,
    )
    .await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn wasi_http_proxy_tests() -> wasmtime::Result<()> {
    let req = http::Request::builder()
        .uri("http://example.com:8080/test-path")
        .method(http::Method::GET);

    let res = run_http(P3_API_PROXY_COMPONENT, req.body(Empty::new())?).await?;

    match res {
        Ok(res) => println!("response: {res:?}"),
        Err(err) => panic!("Error given in response: {err:?}"),
    };

    Ok(())
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_echo() -> Result<()> {
    test_http_echo(P3_HTTP_ECHO_COMPONENT, false, false).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
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());
        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
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_middleware_host_to_host() {
    let error = format!("{:?}", test_http_middleware(true).await.unwrap_err());

    let expected =
        "cannot read from and write to intra-component future/stream with non-numeric payload";

    assert!(
        error.contains(expected),
        "expected `{expected}`; got `{error}`"
    );
}

async fn test_http_middleware(host_to_host: bool) -> Result<()> {
    let tempdir = tempfile::tempdir()?;
    let echo = &fs::read(P3_HTTP_ECHO_COMPONENT).await?;
    let middleware = &fs::read(P3_HTTP_MIDDLEWARE_COMPONENT).await?;

    let path = tempdir.path().join("temp.wasm");
    fs::write(&path, compose(middleware, echo).await?).await?;
    test_http_echo(&path.to_str().unwrap(), true, host_to_host).await
}

async fn compose(a: &[u8], b: &[u8]) -> Result<Vec<u8>> {
    let dir = tempfile::tempdir()?;

    let a_file = dir.path().join("a.wasm");
    fs::write(&a_file, a).await?;

    let b_file = dir.path().join("b.wasm");
    fs::write(&b_file, b).await?;

    // The middleware imports `wasi:http/handler` which matches the echo's
    // `wasi:http/handler` export, so wasm-compose can link them automatically.
    ComponentComposer::new(
        &a_file,
        &wasm_compose::config::Config {
            dir: dir.path().to_owned(),
            definitions: vec![b_file.to_owned()],
            ..Default::default()
        },
    )
    .compose()
    .to_wasmtime_result()
}

/// Test that an error reported by `consume-body` is propagated up through
/// the middleware.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_middleware_error() -> Result<()> {
    _ = env_logger::try_init();

    let echo = &fs::read(P3_HTTP_ECHO_COMPONENT).await?;
    let middleware = &fs::read(P3_HTTP_MIDDLEWARE_COMPONENT).await?;
    let inner = compose(middleware, echo).await?;
    let composed = compose(middleware, &inner).await?;

    let tempdir = tempfile::tempdir()?;
    let path = tempdir.path().join("temp.wasm");
    fs::write(&path, &composed).await?;

    let (mut body_tx, body_rx) = futures::channel::mpsc::channel::<Result<_, ErrorCode>>(1);
    // Add a header which will trigger the echo service to record a transmission
    // error and never deliver a response.
    let request = http::Request::builder()
        .uri("http://localhost/")
        .method(http::Method::GET)
        .header("inject-transmission-error", "true");

    let response = futures::join!(
        async {
            let result = run_http(
                path.to_str().unwrap(),
                request.body(http_body_util::StreamBody::new(body_rx))?,
            )
            .await;
            result
        },
        async {
            body_tx
                .send(Ok(http_body::Frame::data(Bytes::from_static(
                    b"And the mome raths outgrabe",
                ))))
                .await
                .unwrap();
            body_tx
                .send(Ok(http_body::Frame::trailers({
                    let mut trailers = http::HeaderMap::new();
                    assert!(
                        trailers
                            .insert("fizz", http::HeaderValue::from_static("buzz"))
                            .is_none()
                    );
                    trailers
                })))
                .await
                .unwrap();
            drop(body_tx);
        }
    )
    .0;

    let err = response.unwrap_err();
    let expected_err = "Injected error by echo service";
    // Even though the echo service never replied, we can read the transmission
    // error on the future from `request.new`.
    assert!(
        format!("{err:#}").contains(expected_err),
        "Resulting error {err:#} does not contain expected message {expected_err}"
    );

    Ok(())
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_middleware_with_chain() -> Result<()> {
    test_http_middleware_with_chain(false).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_middleware_with_chain_host_to_host() -> Result<()> {
    test_http_middleware_with_chain(true).await
}

async fn test_http_middleware_with_chain(host_to_host: bool) -> Result<()> {
    let dir = tempfile::tempdir()?;
    let path = dir.path().join("temp.wasm");

    fs::copy(P3_HTTP_ECHO_COMPONENT, &dir.path().join("chain-http.wasm")).await?;

    let bytes = ComponentComposer::new(
        Path::new(P3_HTTP_MIDDLEWARE_WITH_CHAIN_COMPONENT),
        &Config {
            dir: dir.path().to_owned(),
            definitions: Vec::new(),
            search_paths: Vec::new(),
            skip_validation: false,
            import_components: false,
            disallow_imports: false,
            dependencies: [(
                "local:local/chain-http".to_owned(),
                Dependency {
                    path: P3_HTTP_ECHO_COMPONENT.into(),
                },
            )]
            .into_iter()
            .collect(),
            instantiations: [(
                "root".to_owned(),
                Instantiation {
                    dependency: Some("local:local/chain-http".to_owned()),
                    arguments: [(
                        "local:local/chain-http".to_owned(),
                        InstantiationArg {
                            instance: "local:local/chain-http".into(),
                            export: Some("wasi:http/[email protected]".into()),
                        },
                    )]
                    .into_iter()
                    .collect(),
                },
            )]
            .into_iter()
            .collect(),
        },
    )
    .compose()
    .to_wasmtime_result()?;
    fs::write(&path, &bytes).await?;

    test_http_echo(&path.to_str().unwrap(), true, host_to_host).await
}

async fn test_http_echo(component: &str, use_compression: bool, host_to_host: bool) -> Result<()> {
    _ = env_logger::try_init();

    let body = b"And the mome raths outgrabe";

    // Prepare the raw body, optionally compressed if that's what we're
    // testing.
    let raw_body = if use_compression {
        let mut encoder = DeflateEncoder::new(Vec::new(), Compression::fast());
        encoder.write_all(body).unwrap();
        Bytes::from(encoder.finish().unwrap())
    } else {
        Bytes::copy_from_slice(body)
    };

    // Prepare the http_body body, modeled here as a channel with the body
    // chunk above buffered up followed by some trailers. Note that trailers
    // are always here to test that code paths throughout the components.
    let (mut body_tx, body_rx) = futures::channel::mpsc::channel::<Result<_, ErrorCode>>(1);

    // Build the `http::Request`, optionally specifying compression-related
    // headers.
    let mut request = http::Request::builder()
        .uri("http://localhost/")
        .method(http::Method::GET)
        .header("foo", "bar");
    if use_compression {
        request = request
            .header("content-encoding", "deflate")
            .header("accept-encoding", "nonexistent-encoding, deflate");
    }
    if host_to_host {
        request = request.header("x-host-to-host", "true");
    }

    // Send this request to wasm and assert that success comes back.
    //
    // Note that this will read the entire body internally and wait for
    // everything to get collected before proceeding to below.
    let response = futures::join!(
        run_http(
            component,
            request.body(http_body_util::StreamBody::new(body_rx))?,
        ),
        async {
            body_tx
                .send(Ok(http_body::Frame::data(raw_body)))
                .await
                .unwrap();
            body_tx
                .send(Ok(http_body::Frame::trailers({
                    let mut trailers = http::HeaderMap::new();
                    assert!(
                        trailers
                            .insert("fizz", http::HeaderValue::from_static("buzz"))
                            .is_none()
                    );
                    trailers
                })))
                .await
                .unwrap();
            drop(body_tx);
        }
    )
    .0?
    .unwrap();
    assert!(response.status().as_u16() == 200);

    // Our input header should be echo'd back.
    assert_eq!(
        response.headers().get("foo"),
        Some(&HeaderValue::from_static("bar"))
    );

    // The compression headers should be set if `use_compression` was turned
    // on.
    if use_compression {
        assert_eq!(
            response.headers().get("content-encoding"),
            Some(&HeaderValue::from_static("deflate"))
        );
        assert!(response.headers().get("content-length").is_none());
    }

    // Trailers should be echo'd back as well.
    let trailers = response.body().trailers().expect("trailers missing");
    assert_eq!(
        trailers.get("fizz"),
        Some(&HeaderValue::from_static("buzz"))
    );

    // And our body should match our original input body as well.
    let (_, collected_body) = response.into_parts();
    let collected_body = collected_body.to_bytes();

    let response_body = if use_compression {
        let mut decoder = DeflateDecoder::new(Vec::new());
        decoder.write_all(&collected_body)?;
        decoder.finish()?
    } else {
        collected_body.to_vec()
    };
    assert_eq!(response_body, body.as_slice());
    Ok(())
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_proxy() -> Result<()> {
    let body = b"And the mome raths outgrabe";

    let raw_body = Bytes::copy_from_slice(body);

    let (mut body_tx, body_rx) = futures::channel::mpsc::channel::<Result<_, ErrorCode>>(1);

    // Tell the guest to forward the request to
    // `http://p3-test-immediate-response/`, which we handle specially in
    // `TestHooks::send_request` above by immediately returning a dummy response
    // and then collecting the request in the background before sending it to
    // the oneshot sender we specify below.  We won't start sending the request
    // body until after the guest has exited and we've dropped the store.

    let request = http::Request::builder()
        .uri("http://localhost/")
        .method(http::Method::GET)
        .header("url", "http://p3-test-immediate-response/");

    let (request_body_tx, request_body_rx) = oneshot::channel();
    let response = run_http_forwarded(
        P3_HTTP_PROXY_COMPONENT,
        request.body(http_body_util::StreamBody::new(body_rx))?,
        request_body_tx,
    )
    .await?
    .unwrap();
    assert!(response.status().as_u16() == 200);

    // The guest has exited and the store has been dropped; now we finally send
    // the request body and assert that it was all successfully passed to the
    // server on the other end.

    let ((), request_body) = futures::join!(
        async {
            body_tx
                .send(Ok(http_body::Frame::data(raw_body)))
                .await
                .unwrap();
            drop(body_tx);
        },
        async {
            request_body_rx
                .await
                .unwrap()
                .unwrap()
                .into_body()
                .to_bytes()
        }
    );

    assert_eq!(request_body, body.as_slice());
    Ok(())
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_proxy_store_drop_cancels_io() -> Result<()> {
    let (_body_tx, body_rx) = futures::channel::mpsc::channel::<Result<_, ErrorCode>>(1);

    // Tell the guest to forward the request to `http://p3-test-keep-open/`,
    // which we handle specially in `TestHooks::send_request` above by
    // immediately returning a response paired with an I/O future that never
    // resolves.
    let request = http::Request::builder()
        .uri("http://localhost/")
        .method(http::Method::GET)
        .header("url", "http://p3-test-keep-open/");

    let (io_dropped_tx, io_dropped_rx) = oneshot::channel();
    let response = run_http_with_hooks(
        P3_HTTP_PROXY_COMPONENT,
        request.body(http_body_util::StreamBody::new(body_rx))?,
        TestHooks {
            io_dropped_tx: Some(io_dropped_tx),
            ..TestHooks::default()
        },
    )
    .await?
    .unwrap();
    assert_eq!(response.status().as_u16(), 200);

    // The guest has exited, the response body has been consumed and the store
    // has been dropped, so nothing references the I/O task anymore and it
    // must be cancelled.
    let result = tokio::time::timeout(std::time::Duration::from_secs(10), io_dropped_rx).await;
    assert_eq!(
        result,
        Ok(Err(oneshot::Canceled)),
        "I/O task should have been cancelled"
    );
    Ok(())
}

/// Trailers containing both forbidden and allowed fields.
fn forbidden_trailers() -> http::HeaderMap {
    let mut trailers = http::HeaderMap::new();
    trailers.insert("connection", HeaderValue::from_static("x-hop"));
    trailers.insert(
        "proxy-authorization",
        HeaderValue::from_static("Basic c2VjcmV0OnNlY3JldA=="),
    );
    trailers.insert("upgrade", HeaderValue::from_static("h2c"));
    trailers.insert("custom-forbidden-header", HeaderValue::from_static("yes"));
    trailers.insert("x-ok", HeaderValue::from_static("1"));
    trailers
}

#[track_caller]
fn assert_trailers_filtered(trailers: Option<&http::HeaderMap>, what: &str) {
    let trailers = trailers.unwrap_or_else(|| panic!("{what}: trailers missing"));
    for name in [
        "connection",
        "proxy-authorization",
        "upgrade",
        "custom-forbidden-header",
    ] {
        assert!(
            trailers.get(name).is_none(),
            "{what}: forbidden trailer `{name}` leaked: {trailers:?}",
        );
    }
    assert_eq!(
        trailers.get("x-ok").map(|v| v.as_bytes()),
        Some(b"1".as_slice()),
        "{what}: allowed trailer missing: {trailers:?}",
    );
}

// A guest which forwards a host body as-is must not let forbidden trailers
// through, in either direction.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_forwarded_trailers_filtered() -> Result<()> {
    let request = http::Request::builder()
        .uri("http://localhost/")
        .method(http::Method::POST)
        .header("url", "http://p3-test-trailers/");
    let body = http_body_util::StreamBody::new(futures::stream::iter([
        Ok::<_, ErrorCode>(http_body::Frame::data(Bytes::from_static(b"request"))),
        Ok(http_body::Frame::trailers(forbidden_trailers())),
    ]));

    let (request_tx, request_rx) = oneshot::channel();
    let response = run_http_forwarded(P3_HTTP_PROXY_COMPONENT, request.body(body)?, request_tx)
        .await?
        .unwrap();
    assert_eq!(response.status().as_u16(), 200);
    let response = response.into_body();
    assert_trailers_filtered(response.trailers(), "response to client");
    assert_eq!(response.to_bytes(), b"response".as_slice());

    let upstream = request_rx.await.unwrap().unwrap().into_body();
    assert_trailers_filtered(upstream.trailers(), "request to upstream");
    assert_eq!(upstream.to_bytes(), b"request".as_slice());
    Ok(())
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_forbidden_headers() -> Result<()> {
    let request = http::Request::builder()
        .uri("http://localhost/")
        .method(http::Method::GET)
        .header("host", "victim.internal")
        .header("connection", "close")
        .header("custom-forbidden-header", "yes")
        .header("foo", "bar");

    let (request_tx, request_rx) = oneshot::channel();
    let response = run_http_forwarded(
        P3_HTTP_FORBIDDEN_HEADERS_COMPONENT,
        request.body(Empty::new())?,
        request_tx,
    )
    .await?
    .unwrap();
    assert_eq!(response.status().as_u16(), 200);

    // Grab the headers that actually reached the backend and assert that none
    // of the forbidden inbound headers leaked across the trust boundary.
    let outbound = request_rx.await.unwrap().unwrap();
    let headers = outbound.headers();

    // Forbidden headers shouldn't have gotten forwarded.
    assert!(
        !headers
            .get_all("host")
            .iter()
            .any(|v| v == "victim.internal"),
        "inbound `host` leaked to backend: {headers:?}",
    );
    assert!(
        headers.get("connection").is_none(),
        "inbound `connection` leaked to backend: {headers:?}",
    );
    assert!(
        headers.get("custom-forbidden-header").is_none(),
        "inbound `custom-forbidden-header` leaked to backend: {headers:?}",
    );

    // Other headers, however, get forwarded.
    assert_eq!(
        headers.get("foo").map(|v| v.as_bytes()),
        Some(b"bar".as_slice()),
    );

    Ok(())
}

/// Ensure that extensions survive a trip through the guest in both directions
/// when the guest forwards the HTTP request or response rather than making a
/// new one.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_extensions() -> Result<()> {
    let request = http::Request::builder()
        .uri("http://localhost/")
        .method(http::Method::GET)
        .extension(RequestMarker("from host"));

    let (request_tx, request_rx) = oneshot::channel();
    let response = run_http_forwarded(
        P3_HTTP_EXTENSIONS_COMPONENT,
        request.body(Empty::new())?,
        request_tx,
    )
    .await?
    .unwrap();
    assert_eq!(response.status().as_u16(), 200);
    assert_eq!(
        response.extensions().get::<ResponseMarker>(),
        Some(&ResponseMarker("from send_request")),
    );

    let outbound = request_rx.await.unwrap().unwrap();
    assert_eq!(
        outbound.extensions().get::<RequestMarker>(),
        Some(&RequestMarker("from host")),
    );

    Ok(())
}

/// A non-canonical http/1 reason phrase from the backend, which `hyper`'s
/// client records as a `ReasonPhrase` extension, survives the guest returning
/// the backend's response.
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_proxy_reason_phrase() -> Result<()> {
    let (server, _requests) = Server::raw(1, |_head| {
        b"HTTP/1.1 200 Quite Ok\r\ncontent-length: 0\r\n\r\n".to_vec()
    })?;

    let request = http::Request::builder()
        .uri("http://localhost/")
        .method(http::Method::GET)
        .header("url", format!("http://{}/", server.addr()));
    let response = run_http(P3_HTTP_PROXY_COMPONENT, request.body(Empty::new())?)
        .await?
        .unwrap();
    assert_eq!(response.status().as_u16(), 200);
    assert_eq!(
        response
            .extensions()
            .get::<hyper::ext::ReasonPhrase>()
            .map(|r| r.as_bytes()),
        Some(b"Quite Ok".as_slice()),
    );

    Ok(())
}

// Custom body wrapper that sends a configurable frame at EOS while reporting is_end_stream() = true
struct BodyWithFrameAtEos {
    inner: http_body_util::StreamBody<
        futures::channel::mpsc::Receiver<Result<http_body::Frame<Bytes>, ErrorCode>>,
    >,
    final_frame: Option<Bytes>,
    sent_final: bool,
    at_eos: bool,
}

impl http_body::Body for BodyWithFrameAtEos {
    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>>> {
        // First, poll the underlying body
        let this = &mut *self;
        match Pin::new(&mut this.inner).poll_frame(cx) {
            Poll::Ready(None) if !this.sent_final => {
                // When the underlying body ends, send the configured final frame
                // This simulates HTTP implementations that send frames at EOS
                this.sent_final = true;
                this.at_eos = true;
                if let Some(data) = this.final_frame.take() {
                    Poll::Ready(Some(Ok(http_body::Frame::data(data))))
                } else {
                    Poll::Ready(None)
                }
            }
            other => other,
        }
    }

    fn is_end_stream(&self) -> bool {
        // Report end of stream once we've reached it
        // This ensures is_end_stream() = true when we send the final frame
        self.at_eos
    }
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_empty_frame_at_end_of_stream() -> Result<()> {
    _ = env_logger::try_init();

    // This test verifies the fix which handles the case where a zero-length frame is
    // received when is_end_stream() is true. Without the fix, the StreamProducer would
    // crash when the WASM guest tries to read such a frame.

    let body = b"test";
    let raw_body = Bytes::copy_from_slice(body);

    let (mut body_tx, body_rx) = futures::channel::mpsc::channel::<Result<_, ErrorCode>>(1);

    let wrapped_body = BodyWithFrameAtEos {
        inner: http_body_util::StreamBody::new(body_rx),
        final_frame: Some(Bytes::new()), // Send empty frame at EOS
        sent_final: false,
        at_eos: false,
    };

    let request = http::Request::builder()
        .uri("http://localhost/")
        .method(http::Method::GET);

    // Use the echo component which actually reads from the stream
    let response = futures::join!(
        run_http(P3_HTTP_ECHO_COMPONENT, request.body(wrapped_body)?),
        async {
            body_tx
                .send(Ok(http_body::Frame::data(raw_body)))
                .await
                .unwrap();
            drop(body_tx);
        }
    )
    .0?
    .unwrap();

    assert_eq!(response.status().as_u16(), 200);

    // Verify the body was echoed correctly (empty frames should be filtered out by the fix)
    let (_, collected_body) = response.into_parts();
    let collected_body = collected_body.to_bytes();
    assert_eq!(collected_body, body.as_slice());
    Ok(())
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_data_frame_at_end_of_stream() -> Result<()> {
    _ = env_logger::try_init();

    // This test verifies that when is_end_stream() is true but the frame contains data,
    // we still process the data.

    let body = b"test";
    let final_data = b" final";
    let raw_body = Bytes::copy_from_slice(body);
    let final_frame = Bytes::copy_from_slice(final_data);

    let (mut body_tx, body_rx) = futures::channel::mpsc::channel::<Result<_, ErrorCode>>(1);

    let wrapped_body = BodyWithFrameAtEos {
        inner: http_body_util::StreamBody::new(body_rx),
        final_frame: Some(final_frame), // Send data frame at EOS with is_end_stream() = true
        sent_final: false,
        at_eos: false,
    };

    let request = http::Request::builder()
        .uri("http://localhost/")
        .method(http::Method::GET);

    // Use the echo component which actually reads from the stream
    let response = futures::join!(
        run_http(P3_HTTP_ECHO_COMPONENT, request.body(wrapped_body)?),
        async {
            body_tx
                .send(Ok(http_body::Frame::data(raw_body)))
                .await
                .unwrap();
            drop(body_tx);
        }
    )
    .0?
    .unwrap();

    assert_eq!(response.status().as_u16(), 200);

    // Verify the body was echoed correctly (the final frame's data should not be lost)
    let (_, collected_body) = response.into_parts();
    let collected_body = collected_body.to_bytes();
    let expected = [body.as_slice(), final_data.as_slice()].concat();
    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)?),
        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(())
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_outbound_request_chunk_size() -> Result<()> {
    let server = Server::http1(1)?;
    run_cli(P3_HTTP_OUTBOUND_REQUEST_CHUNK_SIZE_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_drop_transmit() -> Result<()> {
    let server = Server::http1(1)?;
    run_cli(P3_HTTP_DROP_TRANSMIT_COMPONENT, &server).await
}

#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_named_imports() -> Result<()> {
    crate::shared::run_named_imports_test(
        P3_HTTP_NAMED_IMPORTS_COMPONENT,
        wasmtime_wasi_http::p3::add_to_linker,
        wasmtime_wasi_http::p3::add_named_to_linker,
        async |store, component, linker| {
            let command = Command::instantiate_async(&mut *store, component, linker).await?;
            store
                .run_concurrent(async |store| command.wasi_cli_run().call_run(store).await)
                .await
                .context("failed to call `wasi:cli/run#run`")?
                .context("guest trapped")?
                .map_err(|()| format_err!("`wasi:cli/run#run` failed"))
        },
    )
    .await
}

/// A guest forwarding a host body it has partly read, or with its own
/// trailers, as its response body.
mod p3_http_forward_body {
    use super::*;

    async fn forward(mode: &str) -> Result<Collected<Bytes>> {
        let mut trailers = http::HeaderMap::new();
        trailers.insert("x-host", HeaderValue::from_static("host"));
        // Response body consists of "hello world" two frames followed by a
        // trailer.
        let frames = [
            http_body::Frame::data(Bytes::from_static(b"hello ")),
            http_body::Frame::data(Bytes::from_static(b"world")),
            http_body::Frame::trailers(trailers),
        ];
        let req = http::Request::builder()
            .uri("http://localhost/")
            .header("x-mode", mode)
            .body(http_body_util::StreamBody::new(futures::stream::iter(
                frames.map(Ok::<_, ErrorCode>),
            )))?;
        let res = run_http(P3_HTTP_FORWARD_BODY_COMPONENT, req)
            .await?
            .unwrap();
        Ok(res.into_body())
    }

    fn assert_host_trailers(body: &Collected<Bytes>) {
        let trailers = body.trailers().expect("missing trailers");
        assert_eq!(trailers.len(), 1, "{trailers:?}");
        assert_eq!(trailers["x-host"], "host");
    }

    #[test_log::test(tokio::test(flavor = "multi_thread"))]
    async fn read_0() -> Result<()> {
        let body = forward("read-0").await?;
        assert_host_trailers(&body);
        assert_eq!(body.to_bytes(), "hello world");
        Ok(())
    }

    #[test_log::test(tokio::test(flavor = "multi_thread"))]
    async fn read_1() -> Result<()> {
        let body = forward("read-1").await?;
        assert_host_trailers(&body);
        assert_eq!(body.to_bytes(), "ello world");
        Ok(())
    }

    #[ignore = "Enable when https://github.com/bytecodealliance/wasmtime/issues/15026 has been fixed."]
    #[test_log::test(tokio::test(flavor = "multi_thread"))]
    async fn trailers_error() -> Result<()> {
        let res = forward("trailers-error").await;
        assert!(res.is_err(), "{res:?}");
        Ok(())
    }
}