Skip to main content

dekopon_provider_http/
lib.rs

1#![forbid(unsafe_code)]
2#![cfg_attr(test, allow(clippy::unwrap_used))]
3#![cfg_attr(
4    test,
5    allow(
6        clippy::disallowed_methods,
7        clippy::disallowed_types,
8        reason = "tests spawn, join and drain freely; production sites carry their own expectation"
9    )
10)]
11use std::{error::Error, fmt};
12
13use dekopon_provider_sdk::asset::{Encoding, Handle};
14
15pub const HTTP_WIT: &str = include_str!("../wit/deps/http.wit");
16
17pub mod method {
18    pub const CONNECT: &str = "CONNECT";
19    pub const DELETE: &str = "DELETE";
20    pub const GET: &str = "GET";
21    pub const HEAD: &str = "HEAD";
22    pub const OPTIONS: &str = "OPTIONS";
23    pub const PATCH: &str = "PATCH";
24    pub const POST: &str = "POST";
25    pub const PUT: &str = "PUT";
26    pub const TRACE: &str = "TRACE";
27}
28
29mod bindings {
30    wit_bindgen::generate!({
31        path: "wit",
32        world: "http-client",
33        with: {
34            "dekopon:asset/asset@0.1.0": dekopon_provider_sdk::asset::bindings::dekopon::asset::asset,
35        },
36        generate_all,
37    });
38}
39
40#[derive(Clone, Debug, Eq, PartialEq)]
41pub struct Header {
42    pub name: String,
43    pub value: Vec<u8>,
44}
45
46impl Header {
47    pub fn new(name: impl Into<String>, value: impl Into<Vec<u8>>) -> Result<Self, BuildError> {
48        let name = name.into();
49        if !is_token(&name) {
50            return Err(BuildError::InvalidHeaderName(name));
51        }
52        let value = value.into();
53        if !is_field_value(&value) {
54            return Err(BuildError::InvalidHeaderValue(name));
55        }
56        Ok(Self { name, value })
57    }
58
59    pub fn text(name: impl Into<String>, value: impl Into<String>) -> Result<Self, BuildError> {
60        Self::new(name, value.into().into_bytes())
61    }
62}
63
64#[derive(Clone, Debug, Eq, PartialEq)]
65pub struct Request {
66    pub method: String,
67    /// Absolute request URI. The broker performs authoritative URI and policy validation.
68    pub uri: String,
69    pub headers: Vec<Header>,
70    pub body: Vec<u8>,
71}
72
73impl Request {
74    pub fn new(method: impl Into<String>, uri: impl Into<String>) -> Result<Self, BuildError> {
75        let method = method.into();
76        if !is_token(&method) {
77            return Err(BuildError::InvalidMethod(method));
78        }
79        let uri = uri.into();
80        if uri.is_empty() {
81            return Err(BuildError::EmptyUri);
82        }
83        Ok(Self {
84            method,
85            uri,
86            headers: Vec::new(),
87            body: Vec::new(),
88        })
89    }
90
91    #[must_use]
92    pub fn with_header(mut self, header: Header) -> Self {
93        self.headers.push(header);
94        self
95    }
96
97    #[must_use]
98    pub fn with_body(mut self, body: impl Into<Vec<u8>>) -> Self {
99        self.body = body.into();
100        self
101    }
102}
103
104#[derive(Clone, Debug, Eq, PartialEq)]
105pub struct Response {
106    pub status: u16,
107    pub headers: Vec<Header>,
108    pub body: Vec<u8>,
109}
110
111#[derive(Debug)]
112pub enum Part<'a> {
113    Literal(Vec<u8>),
114    Asset {
115        handle: &'a Handle,
116        encoding: Encoding,
117    },
118}
119
120impl<'a> Part<'a> {
121    pub fn literal(bytes: impl Into<Vec<u8>>) -> Self {
122        Self::Literal(bytes.into())
123    }
124
125    pub fn asset(handle: &'a Handle, encoding: Encoding) -> Self {
126        Self::Asset { handle, encoding }
127    }
128}
129
130#[derive(Debug)]
131pub struct StreamedRequest<'a> {
132    pub method: String,
133    pub uri: String,
134    pub headers: Vec<Header>,
135    pub body: Vec<Part<'a>>,
136}
137
138impl<'a> StreamedRequest<'a> {
139    pub fn new(method: impl Into<String>, uri: impl Into<String>) -> Result<Self, BuildError> {
140        let request = Request::new(method, uri)?;
141        Ok(Self {
142            method: request.method,
143            uri: request.uri,
144            headers: request.headers,
145            body: Vec::new(),
146        })
147    }
148
149    #[must_use]
150    pub fn with_header(mut self, header: Header) -> Self {
151        self.headers.push(header);
152        self
153    }
154
155    #[must_use]
156    pub fn with_body(mut self, body: Vec<Part<'a>>) -> Self {
157        self.body = body;
158        self
159    }
160}
161
162#[derive(Debug)]
163pub struct StreamedResponse {
164    pub status: u16,
165    pub headers: Vec<Header>,
166    pub body: Handle,
167}
168
169#[derive(Clone, Copy, Debug, Eq, PartialEq)]
170pub enum HttpErrorCode {
171    InvalidMethod,
172    InvalidUri,
173    InvalidHeader,
174    RequestTooLarge,
175    Denied,
176    HostCallLimit,
177    Dns,
178    Connect,
179    Tls,
180    Timeout,
181    Protocol,
182    ResponseTooLarge,
183    Internal,
184}
185
186impl HttpErrorCode {
187    /// Returns the WIT contract's stable error-code name rather than the Rust variant name, since a
188    /// provider's stringified error must match the wire contract, not this crate's naming.
189    #[must_use]
190    pub const fn as_str(self) -> &'static str {
191        match self {
192            Self::InvalidMethod => "invalid-method",
193            Self::InvalidUri => "invalid-uri",
194            Self::InvalidHeader => "invalid-header",
195            Self::RequestTooLarge => "request-too-large",
196            Self::Denied => "denied",
197            Self::HostCallLimit => "host-call-limit",
198            Self::Dns => "dns",
199            Self::Connect => "connect",
200            Self::Tls => "tls",
201            Self::Timeout => "timeout",
202            Self::Protocol => "protocol",
203            Self::ResponseTooLarge => "response-too-large",
204            Self::Internal => "internal",
205        }
206    }
207}
208
209impl fmt::Display for HttpErrorCode {
210    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
211        formatter.write_str(self.as_str())
212    }
213}
214
215#[derive(Clone, Debug, Eq, PartialEq)]
216pub struct HttpError {
217    pub code: HttpErrorCode,
218    pub message: String,
219}
220
221impl fmt::Display for HttpError {
222    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
223        write!(formatter, "{}: {}", self.code.as_str(), self.message)
224    }
225}
226
227impl Error for HttpError {}
228
229#[derive(Clone, Debug, Eq, PartialEq)]
230pub enum BuildError {
231    InvalidMethod(String),
232    EmptyUri,
233    InvalidHeaderName(String),
234    InvalidHeaderValue(String),
235}
236
237impl fmt::Display for BuildError {
238    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
239        match self {
240            Self::InvalidMethod(method) => write!(formatter, "invalid HTTP method {method:?}"),
241            Self::EmptyUri => formatter.write_str("HTTP URI must not be empty"),
242            Self::InvalidHeaderName(name) => write!(formatter, "invalid HTTP header name {name:?}"),
243            Self::InvalidHeaderValue(name) => {
244                write!(formatter, "HTTP header {name:?} contains a prohibited byte")
245            }
246        }
247    }
248}
249
250impl Error for BuildError {}
251
252/// Calling this confers no authority; the host validates the request against the current authorized
253/// invocation and may refuse it with Denied.
254pub fn send(request: Request) -> Result<Response, HttpError> {
255    let request = bindings::dekopon::http::client::Request {
256        method: request.method,
257        uri: request.uri,
258        headers: request
259            .headers
260            .into_iter()
261            .map(|header| bindings::dekopon::http::client::Header {
262                name: header.name,
263                value: header.value,
264            })
265            .collect(),
266        body: request.body,
267    };
268
269    bindings::dekopon::http::client::send(&request)
270        .map(|response| Response {
271            status: response.status,
272            headers: response
273                .headers
274                .into_iter()
275                .map(|header| Header {
276                    name: header.name,
277                    value: header.value,
278                })
279                .collect(),
280            body: response.body,
281        })
282        .map_err(|error| HttpError {
283            code: map_error_code(error.code),
284            message: error.message,
285        })
286}
287
288/// Grants no authority; the broker enforces HTTP and asset bounds and must have its asset directory
289/// configured before it will spool a response.
290pub fn stream(request: StreamedRequest<'_>) -> Result<StreamedResponse, HttpError> {
291    use bindings::dekopon::http::client as wit;
292    let request = wit::StreamedRequest {
293        method: request.method,
294        uri: request.uri,
295        headers: request
296            .headers
297            .into_iter()
298            .map(|header| wit::Header {
299                name: header.name,
300                value: header.value,
301            })
302            .collect(),
303        body: request
304            .body
305            .into_iter()
306            .map(|part| match part {
307                Part::Literal(bytes) => wit::Part::Literal(bytes),
308                Part::Asset { handle, encoding } => wit::Part::Asset(wit::AssetPart {
309                    handle: handle.as_inner(),
310                    encoding,
311                }),
312            })
313            .collect(),
314    };
315    wit::stream(&request)
316        .map(|response| StreamedResponse {
317            status: response.status,
318            headers: response
319                .headers
320                .into_iter()
321                .map(|header| Header {
322                    name: header.name,
323                    value: header.value,
324                })
325                .collect(),
326            body: Handle::from_inner(response.body),
327        })
328        .map_err(|error| HttpError {
329            code: map_error_code(error.code),
330            message: error.message,
331        })
332}
333
334fn map_error_code(code: bindings::dekopon::http::client::ErrorCode) -> HttpErrorCode {
335    use bindings::dekopon::http::client::ErrorCode as Wit;
336    match code {
337        Wit::InvalidMethod => HttpErrorCode::InvalidMethod,
338        Wit::InvalidUri => HttpErrorCode::InvalidUri,
339        Wit::InvalidHeader => HttpErrorCode::InvalidHeader,
340        Wit::RequestTooLarge => HttpErrorCode::RequestTooLarge,
341        Wit::Denied => HttpErrorCode::Denied,
342        Wit::HostCallLimit => HttpErrorCode::HostCallLimit,
343        Wit::Dns => HttpErrorCode::Dns,
344        Wit::Connect => HttpErrorCode::Connect,
345        Wit::Tls => HttpErrorCode::Tls,
346        Wit::Timeout => HttpErrorCode::Timeout,
347        Wit::Protocol => HttpErrorCode::Protocol,
348        Wit::ResponseTooLarge => HttpErrorCode::ResponseTooLarge,
349        Wit::Internal => HttpErrorCode::Internal,
350    }
351}
352
353fn is_token(value: &str) -> bool {
354    !value.is_empty()
355        && value.bytes().all(|byte| {
356            byte.is_ascii_alphanumeric()
357                || matches!(
358                    byte,
359                    b'!' | b'#'
360                        | b'$'
361                        | b'%'
362                        | b'&'
363                        | b'\''
364                        | b'*'
365                        | b'+'
366                        | b'-'
367                        | b'.'
368                        | b'^'
369                        | b'_'
370                        | b'`'
371                        | b'|'
372                        | b'~'
373                )
374        })
375}
376
377fn is_field_value(value: &[u8]) -> bool {
378    value
379        .iter()
380        .all(|byte| *byte == b'\t' || (*byte >= 0x20 && *byte != 0x7f))
381}
382
383#[cfg(test)]
384mod tests {
385    use super::{
386        HTTP_WIT, Header, HttpError, HttpErrorCode, Part, Request, StreamedRequest, method,
387    };
388
389    #[test]
390    fn streamed_builder_validates_and_preserves_part_and_header_order() {
391        assert!(StreamedRequest::new("BAD METHOD", "https://example.test/").is_err());
392        assert!(StreamedRequest::new(method::POST, "").is_err());
393        let request = StreamedRequest::new(method::POST, "https://example.test/")
394            .unwrap()
395            .with_header(Header::text("x-example", "first").unwrap())
396            .with_header(Header::text("x-example", "second").unwrap())
397            .with_body(vec![
398                Part::literal(b"head".to_vec()),
399                Part::literal(b"tail".to_vec()),
400            ]);
401        assert_eq!(request.headers[0].value, b"first");
402        assert_eq!(request.headers[1].value, b"second");
403        assert!(matches!(&request.body[0], Part::Literal(bytes) if bytes == b"head"));
404        assert!(matches!(&request.body[1], Part::Literal(bytes) if bytes == b"tail"));
405    }
406
407    const ALL_CODES: [HttpErrorCode; 13] = [
408        HttpErrorCode::InvalidMethod,
409        HttpErrorCode::InvalidUri,
410        HttpErrorCode::InvalidHeader,
411        HttpErrorCode::RequestTooLarge,
412        HttpErrorCode::Denied,
413        HttpErrorCode::HostCallLimit,
414        HttpErrorCode::Dns,
415        HttpErrorCode::Connect,
416        HttpErrorCode::Tls,
417        HttpErrorCode::Timeout,
418        HttpErrorCode::Protocol,
419        HttpErrorCode::ResponseTooLarge,
420        HttpErrorCode::Internal,
421    ];
422
423    #[test]
424    fn accepts_standard_and_extension_methods() {
425        assert!(Request::new(method::PATCH, "https://example.test/items/1").is_ok());
426        assert!(Request::new("PROPFIND", "https://example.test/").is_ok());
427    }
428
429    #[test]
430    fn rejects_non_token_methods_and_header_names() {
431        assert!(Request::new("BAD METHOD", "https://example.test/").is_err());
432        assert!(Header::text("bad header", "value").is_err());
433    }
434
435    #[test]
436    fn rejects_header_line_injection() {
437        assert!(Header::text("x-example", "safe\r\ninjected: value").is_err());
438    }
439
440    #[test]
441    fn error_codes_render_the_wit_names() {
442        let block = HTTP_WIT
443            .split_once("enum error-code {")
444            .expect("the contract declares error-code")
445            .1
446            .split_once('}')
447            .expect("the enum is closed")
448            .0;
449        let declared = block
450            .lines()
451            .map(str::trim)
452            .filter_map(|line| line.strip_suffix(','))
453            .collect::<Vec<_>>();
454
455        assert_eq!(
456            declared,
457            ALL_CODES
458                .iter()
459                .map(|code| code.as_str())
460                .collect::<Vec<_>>()
461        );
462
463        for code in ALL_CODES {
464            assert_eq!(code.to_string(), code.as_str());
465        }
466
467        let error = HttpError {
468            code: HttpErrorCode::ResponseTooLarge,
469            message: "body exceeded the authorized bound".to_owned(),
470        };
471        assert_eq!(
472            error.to_string(),
473            "response-too-large: body exceeded the authorized bound"
474        );
475    }
476}