Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use std::time::Duration;

use anyhow::{Context, Result};
use isola::{
    host::NoopOutputSink,
    sandbox::{Arg, CallOutput, Sandbox, SandboxOptions, args},
};
use wiremock::{
    Mock, MockServer, ResponseTemplate,
    matchers::{body_string, header, method, path},
};

use super::common::{TestHost, build_module};

async fn call_with_timeout<I>(
    sandbox: &mut Sandbox<TestHost>,
    function: &str,
    args: I,
    timeout: Duration,
) -> Result<CallOutput>
where
    I: IntoIterator<Item = Arg>,
{
    tokio::time::timeout(timeout, sandbox.call(function, args))
        .await
        .map_or_else(
            |_| {
                Err(anyhow::anyhow!(
                    "sandbox call timed out after {}ms",
                    timeout.as_millis()
                ))
            },
            |result| result.map_err(Into::into),
        )
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_js_http_client_roundtrip() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };

    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/echo"))
        .and(header("content-type", "application/json"))
        .and(body_string(r#"{"hello":"world"}"#))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(r#"{"ok":true}"#),
        )
        .expect(1)
        .mount(&server)
        .await;

    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    let script = r#"
async function main(url) {
    let resp = await fetch(url + "/echo", {
        method: "POST",
        headers: {"content-type": "application/json"},
        body: '{"hello":"world"}'
    });
    return resp.text();
}
"#;
    sandbox
        .eval_script(script, NoopOutputSink::shared())
        .await
        .context("failed to evaluate http fetch script")?;

    let url_arg = server.uri();
    let output = call_with_timeout(
        &mut sandbox,
        "main",
        args![url_arg]?,
        Duration::from_secs(5),
    )
    .await
    .context("failed to call http fetch function")?;

    assert!(output.items.is_empty(), "expected no partial outputs");

    let value: String = output
        .result
        .as_ref()
        .context("expected exactly one end output")?
        .to_serde()
        .context("failed to decode response body")?;
    assert_eq!(value, r#"{"ok":true}"#);

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_js_http_status_errors_surface() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/status/503"))
        .respond_with(ResponseTemplate::new(503))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/status/500"))
        .and(header("content-type", "application/json"))
        .and(body_string(r#"{"value":"test"}"#))
        .respond_with(ResponseTemplate::new(500))
        .expect(1)
        .mount(&server)
        .await;

    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    let script = r#"
async function main(url) {
    let first = await fetch(url + "/status/503");
    let second = await fetch(url + "/status/500", {
        method: "POST",
        body: {value: "test"}
    });
    return [first.status, second.status];
}
"#;
    sandbox
        .eval_script(script, NoopOutputSink::shared())
        .await
        .context("failed to evaluate status script")?;

    let url_arg = server.uri();
    let output = call_with_timeout(
        &mut sandbox,
        "main",
        args![url_arg]?,
        Duration::from_secs(5),
    )
    .await
    .context("failed to call status function")?;

    assert!(output.items.is_empty(), "expected no partial outputs");
    let value: (i64, i64) = output
        .result
        .as_ref()
        .context("expected exactly one end output")?
        .to_serde()
        .context("failed to decode status tuple")?;
    assert_eq!(value, (503, 500));

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_js_http_concurrent_requests() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/a"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(r#"{"name":"a"}"#),
        )
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/b"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(r#"{"name":"b"}"#),
        )
        .expect(1)
        .mount(&server)
        .await;

    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    // Use Promise.all to verify concurrent requests work
    let script = r#"
async function main(url) {
    let [a, b] = await Promise.all([
        fetch(url + "/a"),
        fetch(url + "/b")
    ]);
    return Promise.all([a.json(), b.json()]);
}
"#;
    sandbox
        .eval_script(script, NoopOutputSink::shared())
        .await
        .context("failed to evaluate concurrent fetch script")?;

    let url_arg = server.uri();
    let output = call_with_timeout(
        &mut sandbox,
        "main",
        args![url_arg]?,
        Duration::from_secs(5),
    )
    .await
    .context("failed to call concurrent fetch function")?;

    assert!(output.items.is_empty(), "expected no partial outputs");
    let value: Vec<serde_json::Value> = output
        .result
        .as_ref()
        .context("expected end output")?
        .to_serde()
        .context("failed to decode concurrent result")?;
    assert_eq!(value.len(), 2);
    assert_eq!(value[0]["name"], "a");
    assert_eq!(value[1]["name"], "b");

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_js_http_json_body() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };

    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/json"))
        .and(header("content-type", "application/json"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(r#"{"received":true}"#),
        )
        .expect(1)
        .mount(&server)
        .await;

    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    let script = r#"
async function main(url) {
    let resp = await fetch(url + "/json", {
        method: "POST",
        body: {key: "value"}
    });
    return resp.json();
}
"#;
    sandbox
        .eval_script(script, NoopOutputSink::shared())
        .await
        .context("failed to evaluate json body script")?;

    let url_arg = server.uri();
    let output = call_with_timeout(
        &mut sandbox,
        "main",
        args![url_arg]?,
        Duration::from_secs(5),
    )
    .await
    .context("failed to call json body function")?;

    let value: serde_json::Value = output
        .result
        .as_ref()
        .context("expected end output")?
        .to_serde()
        .context("failed to decode json response")?;
    assert_eq!(value["received"], true);

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_js_http_delayed_concurrent() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };

    let server = MockServer::start().await;
    // Slow endpoint: 500ms delay
    Mock::given(method("GET"))
        .and(path("/slow"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string("slow")
                .set_body_string("slow-response")
                .insert_header("content-type", "text/plain"),
        )
        .expect(1)
        .mount(&server)
        .await;
    // Fast endpoint: immediate
    Mock::given(method("GET"))
        .and(path("/fast"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_string("fast-response")
                .insert_header("content-type", "text/plain"),
        )
        .expect(1)
        .mount(&server)
        .await;

    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    // Both requests should complete via Promise.all with the poll-based event loop
    let script = r#"
async function main(url) {
    let [slow, fast] = await Promise.all([
        fetch(url + "/slow").then(r => r.text()),
        fetch(url + "/fast").then(r => r.text())
    ]);
    return {slow, fast};
}
"#;
    sandbox
        .eval_script(script, NoopOutputSink::shared())
        .await
        .context("failed to evaluate delayed concurrent script")?;

    let url_arg = server.uri();
    let output = call_with_timeout(
        &mut sandbox,
        "main",
        args![url_arg]?,
        Duration::from_secs(10),
    )
    .await
    .context("failed to call delayed concurrent function")?;

    let value: serde_json::Value = output
        .result
        .as_ref()
        .context("expected end output")?
        .to_serde()
        .context("failed to decode delayed concurrent result")?;
    assert_eq!(value["slow"], "slow-response");
    assert_eq!(value["fast"], "fast-response");

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_js_http_headers_and_request_input() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };

    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/headers"))
        .and(header("content-type", "application/json"))
        .and(body_string(r#"{"hello":"world"}"#))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(r#"{"ok":true}"#),
        )
        .expect(1)
        .mount(&server)
        .await;

    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    let script = r#"
async function main(url) {
    const headers = new Headers([["X-Dup", "a"]]);
    headers.append("x-dup", "b");
    headers.set("content-type", "application/json");
    const req = new Request(url + "/headers", {
        method: "POST",
        headers,
        body: {hello: "world"},
    });

    const resp = await fetch(req);
    return {
        status: resp.status,
        ok: resp.ok,
        header: req.headers.get("x-dup"),
        body: await resp.json(),
    };
}
"#;
    sandbox
        .eval_script(script, NoopOutputSink::shared())
        .await
        .context("failed to evaluate headers/request script")?;

    let url_arg = server.uri();
    let output = call_with_timeout(
        &mut sandbox,
        "main",
        args![url_arg]?,
        Duration::from_secs(5),
    )
    .await
    .context("failed to call headers/request function")?;

    let value: serde_json::Value = output
        .result
        .as_ref()
        .context("expected end output")?
        .to_serde()
        .context("failed to decode headers/request result")?;
    assert_eq!(value["status"], 200);
    assert_eq!(value["ok"], true);
    assert_eq!(value["header"], "a, b");
    assert_eq!(value["body"]["ok"], true);

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_js_http_body_used_enforced() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/read-once"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("content-type", "application/json")
                .set_body_string(r#"{"ok":true}"#),
        )
        .expect(1)
        .mount(&server)
        .await;

    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    let script = r#"
async function main(url) {
    const resp = await fetch(url + "/read-once");
    const first = await resp.text();
    let secondError = "";
    try {
        await resp.json();
    } catch (e) {
        secondError = String(e.message || e);
    }
    return {first, secondError, bodyUsed: resp.bodyUsed};
}
"#;
    sandbox
        .eval_script(script, NoopOutputSink::shared())
        .await
        .context("failed to evaluate bodyUsed script")?;

    let url_arg = server.uri();
    let output = call_with_timeout(
        &mut sandbox,
        "main",
        args![url_arg]?,
        Duration::from_secs(5),
    )
    .await
    .context("failed to call bodyUsed function")?;

    let value: serde_json::Value = output
        .result
        .as_ref()
        .context("expected end output")?
        .to_serde()
        .context("failed to decode bodyUsed result")?;
    assert_eq!(value["first"], r#"{"ok":true}"#);
    assert_eq!(value["bodyUsed"], true);
    let second_error = value["secondError"]
        .as_str()
        .context("expected secondError as string")?;
    assert!(
        second_error.contains("Body has already been"),
        "unexpected bodyUsed second-read error: {second_error}",
    );

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_js_http_abort_pre_aborted_rejects() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };

    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    let script = r#"
async function main(url) {
    const controller = new AbortController();
    controller.abort("stop");
    try {
        await fetch(url + "/never", {signal: controller.signal});
        return "expected-abort";
    } catch (e) {
        return String(e.name || e);
    }
}
"#;
    sandbox
        .eval_script(script, NoopOutputSink::shared())
        .await
        .context("failed to evaluate abort script")?;

    let output = call_with_timeout(
        &mut sandbox,
        "main",
        args!["http://example.com"]?,
        Duration::from_secs(5),
    )
    .await
    .context("failed to call abort function")?;

    let value: String = output
        .result
        .as_ref()
        .context("expected end output")?
        .to_serde()
        .context("failed to decode abort result")?;
    assert_eq!(value, "AbortError");

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_js_http_get_with_body_rejected() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };

    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    let script = r#"
function main(url) {
    try {
        new Request(url + "/invalid", {method: "GET", body: "x"});
        return "expected-get-body-error";
    } catch (e) {
        return String(e.message || e);
    }
}
"#;
    sandbox
        .eval_script(script, NoopOutputSink::shared())
        .await
        .context("failed to evaluate GET body script")?;

    let output = call_with_timeout(
        &mut sandbox,
        "main",
        args!["http://example.com"]?,
        Duration::from_secs(5),
    )
    .await
    .context("failed to call GET body function")?;

    let value: String = output
        .result
        .as_ref()
        .context("expected end output")?
        .to_serde()
        .context("failed to decode GET body result")?;
    assert!(
        value.contains("GET/HEAD"),
        "unexpected GET body error message: {value}",
    );

    Ok(())
}

#[tokio::test]
#[cfg_attr(debug_assertions, ignore = "integration tests run in release mode")]
async fn integration_js_http_url_search_params_body() -> Result<()> {
    let Some(module) = build_module().await? else {
        return Ok(());
    };

    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/form"))
        .and(header(
            "content-type",
            "application/x-www-form-urlencoded;charset=UTF-8",
        ))
        .and(body_string("a=1&b=two"))
        .respond_with(ResponseTemplate::new(200).set_body_string("ok"))
        .expect(1)
        .mount(&server)
        .await;

    let mut sandbox = module
        .instantiate(TestHost::default(), SandboxOptions::default())
        .await
        .context("failed to instantiate sandbox")?;

    let script = r#"
async function main(url) {
    const params = new URLSearchParams({a: "1", b: "two"});
    const resp = await fetch(url + "/form", {
        method: "POST",
        body: params,
    });
    return [resp.status, await resp.text()];
}
"#;
    sandbox
        .eval_script(script, NoopOutputSink::shared())
        .await
        .context("failed to evaluate URLSearchParams script")?;

    let output = call_with_timeout(
        &mut sandbox,
        "main",
        args![server.uri()]?,
        Duration::from_secs(5),
    )
    .await
    .context("failed to call URLSearchParams function")?;

    let value: (i64, String) = output
        .result
        .as_ref()
        .context("expected end output")?
        .to_serde()
        .context("failed to decode URLSearchParams result")?;
    assert_eq!(value.0, 200);
    assert_eq!(value.1, "ok");

    Ok(())
}