Skip to main content

fetchlet_web/
dispatch.rs

1use bytes::Bytes;
2use serde_json::{Value, json};
3
4use crate::protocol::PROTOCOL_VERSION;
5use crate::{Error, WebLimits, WebState};
6
7/// The embedder's byte store for the current invocation, which carries
8/// binary data between the guest and the host by handle.
9pub trait ByteHandles {
10    /// The embedder's error, which also represents this crate's errors.
11    type Error: From<Error>;
12
13    /// Store bytes for the guest to take, returning their handle.
14    fn put(&mut self, bytes: Bytes) -> Result<u64, Self::Error>;
15
16    /// Take the bytes the guest stored under `handle`.
17    fn take(&mut self, handle: u64) -> Result<Bytes, Self::Error>;
18}
19
20/// The current invocation: its Web API state and its byte store.
21pub struct Invocation<'a, B> {
22    pub state: &'a mut WebState,
23    pub bytes: &'a mut B,
24}
25
26/// The Web APIs this build implements, reported by the `web.capabilities`
27/// operation so the guest runtime installs only those globals.
28pub fn capabilities() -> Value {
29    let mut apis = Vec::new();
30    if cfg!(feature = "url") {
31        apis.push("url");
32    }
33    if cfg!(feature = "url-pattern") {
34        apis.push("url-pattern");
35    }
36    if cfg!(feature = "compression") {
37        apis.push("compression");
38    }
39    if cfg!(feature = "web-crypto") {
40        apis.push("crypto");
41    }
42    if cfg!(feature = "node-crypto") {
43        apis.push("node-crypto");
44    }
45    json!({ "protocol": PROTOCOL_VERSION, "apis": apis })
46}
47
48/// Run a Web API operation, or return `None` when `operation` is not one,
49/// so the embedder can route its own operations.
50///
51/// Stateless operations, such as URL parsing, also run without an
52/// invocation, for example while a module is evaluated.
53pub fn dispatch<B: ByteHandles>(
54    operation: &str,
55    input: &str,
56    limits: &WebLimits,
57    invocation: Option<Invocation<'_, B>>,
58) -> Option<Result<Value, B::Error>> {
59    let _ = (input, limits, &invocation);
60    let result = match operation {
61        "web.capabilities" => Ok(capabilities()),
62        #[cfg(feature = "url")]
63        "url.parse" | "url.set" => crate::url::dispatch(operation, input),
64        #[cfg(feature = "url-pattern")]
65        "urlpattern.parse" | "urlpattern.match" => crate::url_pattern::dispatch(operation, input),
66        #[cfg(feature = "web-crypto")]
67        "crypto.random" | "crypto.digest" | "crypto.generateKey" | "crypto.importKey"
68        | "crypto.exportKey" | "crypto.sign" | "crypto.verify" | "crypto.encrypt"
69        | "crypto.decrypt" | "crypto.deriveBits" => {
70            crate::crypto::dispatch(operation, input, limits)
71        }
72        #[cfg(feature = "node-crypto")]
73        "nodeCrypto.hash" | "nodeCrypto.hmac" | "nodeCrypto.pbkdf2" | "nodeCrypto.hkdf"
74        | "nodeCrypto.scrypt" => crate::node_crypto::dispatch(operation, input, limits),
75        #[cfg(feature = "compression")]
76        "compression.open" | "compression.write" | "compression.finish" | "compression.read"
77        | "compression.close" => {
78            let Some(invocation) = invocation else {
79                return Some(Err(Error::NoInvocation.into()));
80            };
81            return Some(crate::compression::dispatch(
82                operation, input, limits, invocation,
83            ));
84        }
85        _ => return None,
86    };
87    Some(result.map_err(B::Error::from))
88}
89
90#[cfg(test)]
91mod tests {
92    use std::collections::BTreeMap;
93
94    use super::*;
95
96    #[derive(Default)]
97    struct Store {
98        next: u64,
99        entries: BTreeMap<u64, Bytes>,
100    }
101
102    impl ByteHandles for Store {
103        type Error = Error;
104
105        fn put(&mut self, bytes: Bytes) -> Result<u64, Error> {
106            self.next += 1;
107            self.entries.insert(self.next, bytes);
108            Ok(self.next)
109        }
110
111        fn take(&mut self, handle: u64) -> Result<Bytes, Error> {
112            self.entries
113                .remove(&handle)
114                .ok_or_else(|| Error::InvalidRequest("unknown handle".into()))
115        }
116    }
117
118    fn run(operation: &str, input: &str, invocation: Option<Invocation<'_, Store>>) -> Value {
119        dispatch(operation, input, &WebLimits::default(), invocation)
120            .expect("a Web API operation")
121            .expect("a successful operation")
122    }
123
124    #[test]
125    fn reports_the_protocol_and_leaves_other_operations_to_the_embedder() {
126        let reply = run("web.capabilities", "null", None);
127        assert_eq!(reply["protocol"], PROTOCOL_VERSION);
128        assert!(dispatch::<Store>("fetch.start", "{}", &WebLimits::default(), None).is_none());
129    }
130
131    /// The operations protocol.json lists are served exactly when their API
132    /// is reported, so the guest, built from the same file, finds them.
133    #[test]
134    fn serves_the_listed_operations_of_each_reported_api() {
135        let reported = capabilities()["apis"].clone();
136        for (api, operations) in crate::protocol::OPERATIONS {
137            let served = *api == "web" || reported.as_array().unwrap().contains(&json!(api));
138            for operation in *operations {
139                let reply = dispatch::<Store>(operation, "null", &WebLimits::default(), None);
140                assert_eq!(reply.is_some(), served, "{operation}");
141            }
142        }
143        for api in reported.as_array().unwrap() {
144            assert!(
145                crate::protocol::OPERATIONS
146                    .iter()
147                    .any(|(listed, _)| api == listed),
148                "{api} is reported but not listed in protocol.json"
149            );
150        }
151    }
152
153    /// Every operation name `dispatch` matches is listed in protocol.json,
154    /// so that renaming one without the file, and its version, fails here.
155    #[test]
156    fn dispatches_only_listed_operations() {
157        let source = include_str!("dispatch.rs");
158        let body =
159            &source[source.find("pub fn dispatch").unwrap()..source.find("#[cfg(test)]").unwrap()];
160        let listed: Vec<&str> = crate::protocol::OPERATIONS
161            .iter()
162            .flat_map(|(_, operations)| operations.iter().copied())
163            .collect();
164        let names = body
165            .split('"')
166            .skip(1)
167            .step_by(2)
168            .filter(|literal| literal.contains('.'));
169        let mut count = 0;
170        for name in names {
171            assert!(
172                listed.contains(&name),
173                "{name} is not listed in protocol.json"
174            );
175            count += 1;
176        }
177        assert_eq!(count, listed.len());
178    }
179
180    #[cfg(not(any(
181        feature = "url",
182        feature = "url-pattern",
183        feature = "compression",
184        feature = "web-crypto"
185    )))]
186    #[test]
187    fn omitted_apis_are_neither_reported_nor_served() {
188        assert_eq!(capabilities()["apis"], json!([]));
189        for operation in [
190            "url.parse",
191            "urlpattern.parse",
192            "compression.open",
193            "crypto.random",
194        ] {
195            assert!(dispatch::<Store>(operation, "null", &WebLimits::default(), None).is_none());
196        }
197    }
198
199    #[cfg(feature = "url")]
200    #[test]
201    fn stateless_operations_run_without_an_invocation() {
202        assert_eq!(capabilities()["apis"][0], "url");
203        let reply = run("url.parse", r#"["https://a.test/x", null]"#, None);
204        assert_eq!(reply[0], "https://a.test/x");
205    }
206
207    #[cfg(feature = "compression")]
208    #[test]
209    fn stateful_operations_need_an_invocation_and_keep_its_state() {
210        assert!(matches!(
211            dispatch::<Store>(
212                "compression.open",
213                r#"["gzip", false]"#,
214                &WebLimits::default(),
215                None
216            ),
217            Some(Err(Error::NoInvocation))
218        ));
219        let mut state = WebState::default();
220        let mut store = Store::default();
221        let mut step = |operation: &str, input: &str| {
222            run(
223                operation,
224                input,
225                Some(Invocation {
226                    state: &mut state,
227                    bytes: &mut store,
228                }),
229            )
230        };
231        let id = step("compression.open", r#"["gzip", false]"#).to_string();
232        step("compression.finish", &id);
233        let handle = step("compression.read", &id);
234        let piece = store.take(handle.as_u64().unwrap()).unwrap();
235        assert_eq!(&piece[..2], &[0x1f, 0x8b]);
236        let mut step = |operation: &str, input: &str| {
237            run(
238                operation,
239                input,
240                Some(Invocation {
241                    state: &mut state,
242                    bytes: &mut store,
243                }),
244            )
245        };
246        step("compression.close", &id);
247        // A fresh state, as for the next invocation, has no codec under that id.
248        let mut next = WebState::default();
249        let reply = dispatch(
250            "compression.finish",
251            &id,
252            &WebLimits::default(),
253            Some(Invocation {
254                state: &mut next,
255                bytes: &mut store,
256            }),
257        );
258        assert!(matches!(reply, Some(Err(Error::InvalidRequest(_)))));
259    }
260
261    #[cfg(feature = "compression")]
262    #[test]
263    fn output_the_guest_did_not_take_is_dropped_and_stops_the_stream() {
264        let mut state = WebState::default();
265        let mut store = Store::default();
266        let mut step = |store: &mut Store, operation: &str, input: &str| {
267            dispatch(
268                operation,
269                input,
270                &WebLimits::default(),
271                Some(Invocation {
272                    state: &mut state,
273                    bytes: store,
274                }),
275            )
276            .expect("a Web API operation")
277        };
278        let id = step(&mut store, "compression.open", r#"["deflate-raw", false]"#)
279            .unwrap()
280            .to_string();
281        // Input that does not compress gives several pieces of output.
282        let mut state32 = 0x9e37_79b9u32;
283        let input: Vec<u8> = (0..300_000)
284            .map(|_| {
285                state32 ^= state32 << 13;
286                state32 ^= state32 >> 17;
287                state32 ^= state32 << 5;
288                state32 as u8
289            })
290            .collect();
291        let handle = store.put(Bytes::from(input)).unwrap();
292        step(
293            &mut store,
294            "compression.write",
295            &format!("[{id}, {handle}]"),
296        )
297        .unwrap();
298        let first = step(&mut store, "compression.read", &id).unwrap();
299        assert!(first.is_u64());
300        assert!(matches!(
301            step(&mut store, "compression.read", &id),
302            Err(Error::InvalidRequest(_))
303        ));
304        assert!(store.take(first.as_u64().unwrap()).is_err());
305    }
306}