Skip to main content

wasmtime_wasi_http/p3/
request.rs

1use crate::p3::bindings::http::types::ErrorCode;
2use crate::p3::body::{Body, BodyExt as _, GuestBody};
3use crate::p3::{HttpError, HttpResult};
4use crate::{
5    Error, FieldMap, RequestOptions, WasiHttpCtxView, WasiHttpHooks, WasiHttpView,
6    get_content_length,
7};
8use bytes::Bytes;
9use http::header::HOST;
10use http::uri::{Authority, PathAndQuery, Scheme};
11use http::{HeaderValue, Method, Uri};
12use http_body_util::BodyExt as _;
13use http_body_util::combinators::UnsyncBoxBody;
14use std::sync::Arc;
15use tokio::sync::oneshot;
16use tracing::debug;
17use wasmtime::AsContextMut;
18
19/// The concrete type behind a `wasi:http/types.request` resource.
20pub struct Request {
21    /// The method of the request.
22    pub method: Method,
23    /// The scheme of the request.
24    pub scheme: Option<Scheme>,
25    /// The authority of the request.
26    pub authority: Option<Authority>,
27    /// The path and query of the request.
28    pub path_with_query: Option<PathAndQuery>,
29    /// The request headers.
30    pub headers: FieldMap,
31    /// Request options.
32    pub options: Option<Arc<RequestOptions>>,
33    /// Data associated with this request. Cannot be read by the guest, but can
34    /// be forwarded by the guest.
35    pub extensions: http::Extensions,
36    /// Request body.
37    pub(crate) body: Body,
38}
39
40impl Request {
41    /// Construct a new [Request]
42    ///
43    /// This returns a [Future] that the will be used to communicate
44    /// a request processing error, if any.
45    ///
46    /// Requests constructed this way will not perform any `Content-Length` validation.
47    pub fn new<B>(
48        method: Method,
49        scheme: Option<Scheme>,
50        authority: Option<Authority>,
51        path_with_query: Option<PathAndQuery>,
52        headers: impl Into<FieldMap>,
53        options: Option<Arc<RequestOptions>>,
54        body: B,
55    ) -> (
56        Self,
57        impl Future<Output = Result<(), Error>> + Send + 'static,
58    )
59    where
60        B: http_body::Body<Data = Bytes> + Send + 'static,
61        B::Error: Into<Error>,
62    {
63        let (tx, rx) = oneshot::channel();
64        (
65            Self {
66                method,
67                scheme,
68                authority,
69                path_with_query,
70                headers: headers.into(),
71                options,
72                extensions: http::Extensions::new(),
73                body: Body::Host {
74                    body: body.map_err(Into::into).boxed_unsync(),
75                    result_tx: tx,
76                },
77            },
78            async {
79                let Ok(fut) = rx.await else { return Ok(()) };
80                Box::into_pin(fut).await
81            },
82        )
83    }
84
85    /// Construct a new [Request] from [http::Request].
86    ///
87    /// This returns a [Future] that will be used to communicate
88    /// a request processing error, if any.
89    ///
90    /// Requests constructed this way will not perform any `Content-Length` validation.
91    pub fn from_http<T>(
92        hooks: &mut dyn WasiHttpHooks,
93        req: http::Request<T>,
94    ) -> (
95        Self,
96        impl Future<Output = Result<(), Error>> + Send + 'static + use<T>,
97    )
98    where
99        T: http_body::Body<Data = Bytes> + Send + 'static,
100        T::Error: Into<Error>,
101    {
102        let (
103            http::request::Parts {
104                method,
105                uri,
106                headers,
107                extensions,
108                ..
109            },
110            body,
111        ) = req.into_parts();
112        let http::uri::Parts {
113            scheme,
114            authority,
115            path_and_query,
116            ..
117        } = uri.into_parts();
118        let (mut req, fut) = Self::new(
119            method,
120            scheme,
121            authority,
122            path_and_query,
123            FieldMap::new_immutable(hooks, headers),
124            None,
125            body,
126        );
127        req.extensions = extensions;
128        (req, fut)
129    }
130
131    /// Convert this [`Request`] into an [`http::Request<UnsyncBoxBody<Bytes, ErrorCode>>`].
132    ///
133    /// The specified future `fut` can be used to communicate a request processing
134    /// error, if any, back to the caller (e.g., if this request was constructed
135    /// through `wasi:http/types.request#new`).
136    pub fn into_http<T: WasiHttpView + 'static>(
137        self,
138        store: impl AsContextMut<Data = T>,
139        fut: impl Future<Output = Result<(), Error>> + Send + 'static,
140    ) -> HttpResult<(
141        http::Request<UnsyncBoxBody<Bytes, Error>>,
142        Option<Arc<RequestOptions>>,
143    )> {
144        self.into_http_with_getter(store, fut, T::http)
145    }
146
147    /// Like [`Self::into_http`], but uses a custom getter for obtaining the [`WasiHttpCtxView`].
148    pub fn into_http_with_getter<T: 'static>(
149        self,
150        mut store: impl AsContextMut<Data = T>,
151        fut: impl Future<Output = Result<(), Error>> + Send + 'static,
152        mut getter: impl FnMut(&mut T) -> WasiHttpCtxView<'_> + Clone + Unpin + Send + 'static,
153    ) -> HttpResult<(
154        http::Request<UnsyncBoxBody<Bytes, Error>>,
155        Option<Arc<RequestOptions>>,
156    )> {
157        let Request {
158            method,
159            scheme,
160            authority,
161            path_with_query,
162            mut headers,
163            options,
164            extensions,
165            body,
166        } = self;
167        // `Content-Length` header value is validated in `fields` implementation
168        let content_length = match get_content_length(&headers) {
169            Ok(content_length) => content_length,
170            Err(err) => {
171                body.drop(&mut store).map_err(HttpError::trap)?;
172                return Err(ErrorCode::InternalError(Some(format!("{err:#}"))).into());
173            }
174        };
175        // This match must appear before any potential errors handled with '?'
176        // (or errors have to explicitly be addressed and drop the body, as above),
177        // as otherwise the Body::Guest resources will not be cleaned up when dropped.
178        // see: https://github.com/bytecodealliance/wasmtime/pull/11440#discussion_r2326139381
179        // for additional context.
180        let body = match body {
181            Body::Guest {
182                contents_rx,
183                trailers_rx,
184                result_tx,
185            } => GuestBody::new(
186                &mut store,
187                contents_rx,
188                trailers_rx,
189                result_tx,
190                fut,
191                content_length,
192                ErrorCode::HttpRequestBodySize,
193                getter.clone(),
194            )
195            .map_err(HttpError::trap)?
196            .boxed_unsync(),
197            Body::Host { body, result_tx } => {
198                let is_forbidden = getter(store.as_context_mut().data_mut())
199                    .hooks
200                    .forbidden_header_filter();
201                let body = body.with_filtered_trailers(is_forbidden).boxed_unsync();
202                if let Some(limit) = content_length {
203                    let (http_result_tx, http_result_rx) = oneshot::channel();
204                    _ = result_tx.send(Box::new(async move {
205                        if let Ok(err) = http_result_rx.await {
206                            return Err(err);
207                        };
208                        fut.await
209                    }));
210                    body.with_content_length(limit, http_result_tx, Error::HttpRequestBodySize)
211                        .boxed_unsync()
212                } else {
213                    _ = result_tx.send(Box::new(fut));
214                    body
215                }
216            }
217        };
218        let mut store = store.as_context_mut();
219        let WasiHttpCtxView { hooks, ctx, .. } = getter(store.data_mut());
220        headers.set_mutable(ctx.field_size_limit);
221        if hooks.set_host_header() {
222            let host = if let Some(authority) = authority.as_ref() {
223                HeaderValue::try_from(authority.as_str())
224                    .map_err(|err| ErrorCode::InternalError(Some(err.to_string())))?
225            } else {
226                HeaderValue::from_static("")
227            };
228            headers.append_raw(HOST, host).map_err(HttpError::trap)?;
229        }
230        let scheme = match scheme {
231            None => hooks.default_scheme().ok_or(ErrorCode::HttpProtocolError)?,
232            Some(scheme) if hooks.is_supported_scheme(&scheme) => scheme,
233            Some(..) => return Err(ErrorCode::HttpProtocolError.into()),
234        };
235        let mut uri = Uri::builder().scheme(scheme);
236        if let Some(authority) = authority {
237            uri = uri.authority(authority)
238        };
239        if let Some(path_with_query) = path_with_query {
240            uri = uri.path_and_query(path_with_query)
241        };
242        let uri = uri.build().map_err(|err| {
243            debug!(?err, "failed to build request URI");
244            ErrorCode::HttpRequestUriInvalid
245        })?;
246        let mut req = http::Request::builder();
247        *req.headers_mut().unwrap() = headers.into();
248        *req.extensions_mut().unwrap() = extensions;
249        let req = req
250            .method(method)
251            .uri(uri)
252            .body(body)
253            .map_err(|err| ErrorCode::InternalError(Some(err.to_string())))?;
254        Ok((req, options))
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261    use crate::WasiHttpCtx;
262    use core::future::Future;
263    use core::pin::pin;
264    use core::str::FromStr;
265    use core::task::{Context, Poll, Waker};
266    use http_body_util::{BodyExt, Empty, Full};
267    use wasmtime::Result;
268    use wasmtime::{Engine, Store};
269    use wasmtime_wasi::{ResourceTable, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
270
271    struct TestCtx {
272        table: ResourceTable,
273        wasi: WasiCtx,
274        http: WasiHttpCtx,
275    }
276
277    impl TestCtx {
278        fn new() -> Self {
279            Self {
280                table: ResourceTable::default(),
281                wasi: WasiCtxBuilder::new().build(),
282                http: Default::default(),
283            }
284        }
285    }
286
287    impl WasiView for TestCtx {
288        fn ctx(&mut self) -> WasiCtxView<'_> {
289            WasiCtxView {
290                ctx: &mut self.wasi,
291                table: &mut self.table,
292            }
293        }
294    }
295
296    impl WasiHttpView for TestCtx {
297        fn http(&mut self) -> WasiHttpCtxView<'_> {
298            WasiHttpCtxView {
299                ctx: &mut self.http,
300                table: &mut self.table,
301                hooks: crate::default_hooks(),
302            }
303        }
304    }
305
306    #[tokio::test]
307    async fn test_request_into_http_schemes() -> Result<()> {
308        let schemes = vec![Some(Scheme::HTTP), Some(Scheme::HTTPS), None];
309        let engine = Engine::default();
310
311        for scheme in schemes {
312            let (req, fut) = Request::new(
313                Method::POST,
314                scheme.clone(),
315                Some(Authority::from_static("example.com")),
316                Some(PathAndQuery::from_static("/path?query=1")),
317                FieldMap::default(),
318                None,
319                Full::new(Bytes::from_static(b"body")).boxed_unsync(),
320            );
321            let mut store = Store::new(&engine, TestCtx::new());
322            let (http_req, options) = req.into_http(&mut store, async { Ok(()) }).unwrap();
323            assert_eq!(options, None);
324            assert_eq!(http_req.method(), Method::POST);
325            let expected_scheme = scheme.unwrap_or(Scheme::HTTPS); // default scheme
326            assert_eq!(
327                http_req.uri(),
328                &http::Uri::from_str(&format!(
329                    "{}://example.com/path?query=1",
330                    expected_scheme.as_str()
331                ))
332                .unwrap()
333            );
334            let body_bytes = http_req.into_body().collect().await?;
335            assert_eq!(body_bytes.to_bytes(), b"body".as_slice());
336            let mut cx = Context::from_waker(Waker::noop());
337            let result = pin!(fut).poll(&mut cx);
338            assert!(matches!(result, Poll::Ready(Ok(()))));
339        }
340
341        Ok(())
342    }
343
344    #[tokio::test]
345    async fn test_request_into_http_uri_error() -> Result<()> {
346        let (req, fut) = Request::new(
347            Method::GET,
348            Some(Scheme::HTTP),
349            Some(Authority::from_static("example.com")),
350            None, // <-- should fail, must be Some(_) when authority is set
351            FieldMap::default(),
352            None,
353            Empty::new().boxed_unsync(),
354        );
355        let mut store = Store::new(&Engine::default(), TestCtx::new());
356        let result = req
357            .into_http(&mut store, async {
358                Err(Error::InternalError(Some("uh oh".to_string())))
359            })
360            .unwrap_err();
361        assert!(matches!(
362            result.downcast()?,
363            ErrorCode::HttpRequestUriInvalid,
364        ));
365        let mut cx = Context::from_waker(Waker::noop());
366        let result = pin!(fut).poll(&mut cx);
367        assert!(matches!(
368            result,
369            Poll::Ready(Err(Error::InternalError(Some(_))))
370        ));
371
372        Ok(())
373    }
374}