wasmsh-browser 0.7.0

Browser Web Worker integration for wasmsh
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
//! Security tests for the network allowlist.
//!
//! Verifies that `curl` and `wget` can only reach hosts explicitly listed
//! in the `allowed_hosts` configuration.  Uses real HTTP requests to
//! mayflower.de as the allowed host.
//!
//! These tests require network access and will be skipped if
//! `mayflower.de` is unreachable.

use std::io::Read;

use wasmsh_browser::WorkerRuntime;
use wasmsh_protocol::{HostCommand, WorkerEvent};
use wasmsh_utils::net_types::{
    HostAllowlist, HttpRequest, HttpResponse, NetworkBackend, NetworkError,
};

/// Native network backend using `ureq` for integration testing.
/// Validates URLs against a `HostAllowlist` before making real HTTP requests.
struct NativeNetworkBackend {
    allowlist: HostAllowlist,
}

impl NativeNetworkBackend {
    fn new(allowed_hosts: Vec<String>) -> Self {
        Self {
            allowlist: HostAllowlist::new(allowed_hosts),
        }
    }
}

impl NetworkBackend for NativeNetworkBackend {
    fn check_url(&self, url: &str) -> Result<(), NetworkError> {
        self.allowlist.check(url)
    }

    fn fetch(&self, request: &HttpRequest) -> Result<HttpResponse, NetworkError> {
        self.allowlist.check(&request.url)?;

        let ureq_req = ureq::request(&request.method, &request.url);
        let mut req = ureq_req;
        for (key, value) in &request.headers {
            req = req.set(key, value);
        }

        let result = if let Some(ref body) = request.body {
            req.send_bytes(body)
        } else {
            req.call()
        };

        match result {
            Ok(resp) => {
                let status = resp.status();
                let mut headers = Vec::new();
                for name in resp.headers_names() {
                    if let Some(value) = resp.header(&name) {
                        headers.push((name, value.to_string()));
                    }
                }
                let mut body = Vec::new();
                resp.into_reader()
                    .take(10 * 1024 * 1024) // 10 MB limit
                    .read_to_end(&mut body)
                    .unwrap_or(0);
                Ok(HttpResponse {
                    status,
                    headers,
                    body,
                })
            }
            Err(ureq::Error::Status(status, resp)) => {
                let mut body = Vec::new();
                resp.into_reader()
                    .take(1024 * 1024)
                    .read_to_end(&mut body)
                    .unwrap_or(0);
                Ok(HttpResponse {
                    status,
                    headers: vec![],
                    body,
                })
            }
            Err(e) => Err(NetworkError::ConnectionFailed(e.to_string())),
        }
    }
}

fn extract_stdout(events: &[WorkerEvent]) -> String {
    let mut out = Vec::new();
    for event in events {
        if let WorkerEvent::Stdout(data) = event {
            out.extend_from_slice(data);
        }
    }
    String::from_utf8_lossy(&out).to_string()
}

fn extract_stderr(events: &[WorkerEvent]) -> String {
    let mut out = Vec::new();
    for event in events {
        if let WorkerEvent::Stderr(data) = event {
            out.extend_from_slice(data);
        }
    }
    String::from_utf8_lossy(&out).to_string()
}

fn extract_exit_code(events: &[WorkerEvent]) -> Option<i32> {
    for event in events {
        if let WorkerEvent::Exit(code) = event {
            return Some(*code);
        }
    }
    None
}

/// Check if mayflower.de is reachable (skip tests if offline).
fn mayflower_reachable() -> bool {
    ureq::get("https://mayflower.de")
        .set("User-Agent", "wasmsh-test/1.0")
        .call()
        .is_ok()
}

fn init_runtime_with_network(allowed_hosts: Vec<String>) -> WorkerRuntime {
    let mut rt = WorkerRuntime::new();
    let backend = NativeNetworkBackend::new(allowed_hosts.clone());
    rt.set_network_backend(Box::new(backend));
    rt.handle_command(HostCommand::Init {
        step_budget: 0,
        allowed_hosts,
    });
    rt
}

// ── Allowed host tests ──────────────────────────────────────────

#[test]
fn curl_allowed_host_succeeds() {
    if !mayflower_reachable() {
        return; // mayflower.de unreachable — skip
    }

    let mut rt = init_runtime_with_network(vec!["mayflower.de".into()]);
    let events = rt.handle_command(HostCommand::Run {
        input: "curl -sL https://mayflower.de".into(),
    });

    let stdout = extract_stdout(&events);
    let exit_code = extract_exit_code(&events).unwrap();

    assert_eq!(exit_code, 0, "curl to allowed host should succeed");
    assert!(
        !stdout.is_empty(),
        "curl to allowed host should return content"
    );
    assert!(
        stdout.contains("<!") || stdout.contains("<html") || stdout.contains("<HTML"),
        "expected HTML from mayflower.de, got: {}...",
        &stdout[..stdout.len().min(200)]
    );
}

#[test]
fn wget_allowed_host_succeeds() {
    if !mayflower_reachable() {
        return; // mayflower.de unreachable — skip
    }

    let mut rt = init_runtime_with_network(vec!["mayflower.de".into()]);
    let events = rt.handle_command(HostCommand::Run {
        input: "wget -qO - https://mayflower.de".into(),
    });

    let stdout = extract_stdout(&events);
    let exit_code = extract_exit_code(&events).unwrap();

    assert_eq!(exit_code, 0, "wget to allowed host should succeed");
    assert!(
        !stdout.is_empty(),
        "wget to allowed host should return content"
    );
}

// ── Denied host tests ───────────────────────────────────────────

#[test]
fn curl_denied_host_blocked() {
    let mut rt = init_runtime_with_network(vec!["mayflower.de".into()]);
    let events = rt.handle_command(HostCommand::Run {
        input: "curl https://example.com".into(),
    });

    let stderr = extract_stderr(&events);
    let exit_code = extract_exit_code(&events).unwrap();

    assert_ne!(exit_code, 0, "curl to denied host must fail");
    assert!(
        stderr.contains("denied"),
        "stderr should mention 'denied', got: {stderr}"
    );
}

#[test]
fn wget_denied_host_blocked() {
    let mut rt = init_runtime_with_network(vec!["mayflower.de".into()]);
    let events = rt.handle_command(HostCommand::Run {
        input: "wget -qO - https://example.com".into(),
    });

    let stderr = extract_stderr(&events);
    let exit_code = extract_exit_code(&events).unwrap();

    assert_ne!(exit_code, 0, "wget to denied host must fail");
    assert!(
        stderr.contains("denied"),
        "stderr should mention 'denied', got: {stderr}"
    );
}

#[test]
fn curl_denied_host_with_subdomain() {
    // Only mayflower.de is allowed, not subdomains
    let mut rt = init_runtime_with_network(vec!["mayflower.de".into()]);
    let events = rt.handle_command(HostCommand::Run {
        input: "curl https://evil.mayflower.de".into(),
    });

    let exit_code = extract_exit_code(&events).unwrap();
    assert_ne!(
        exit_code, 0,
        "curl to subdomain of allowed host must fail (exact match only)"
    );
}

#[test]
fn curl_denied_similar_hostname() {
    let mut rt = init_runtime_with_network(vec!["mayflower.de".into()]);

    for host in [
        "https://notmayflower.de",
        "https://mayflower.de.evil.com",
        "https://mayflower.com",
    ] {
        let events = rt.handle_command(HostCommand::Run {
            input: format!("curl {host}"),
        });
        let exit_code = extract_exit_code(&events).unwrap();
        assert_ne!(exit_code, 0, "curl to '{host}' must be blocked");
    }
}

// ── Wildcard pattern tests ──────────────────────────────────────

#[test]
fn curl_wildcard_allows_subdomains_but_not_apex() {
    if !mayflower_reachable() {
        return; // mayflower.de unreachable — skip
    }

    // `*.mayflower.de` matches strict subdomains only; the apex
    // `mayflower.de` is NOT covered. See docs/reference/sandbox-and-capabilities.md
    // and the matching e2e tests in e2e/pyodide-node/tests/network-security.test.mjs.
    let mut rt = init_runtime_with_network(vec!["*.mayflower.de".into()]);

    // www subdomain: must succeed. NOTE: no `-L` here — many sites
    // redirect www → apex, and B3's per-hop allowlist re-check
    // correctly denies the apex (which `*.mayflower.de` does not
    // cover). The test asserts initial host policy, so we stop at the
    // first hop.
    let events = rt.handle_command(HostCommand::Run {
        input: "curl -s -o /dev/null -w '%{http_code}' https://www.mayflower.de".into(),
    });
    assert_eq!(
        extract_exit_code(&events).unwrap(),
        0,
        "www.mayflower.de should be allowed by *.mayflower.de"
    );

    // Apex: must be denied.
    let events = rt.handle_command(HostCommand::Run {
        input: "curl https://mayflower.de".into(),
    });
    assert_ne!(
        extract_exit_code(&events).unwrap(),
        0,
        "apex mayflower.de must NOT be covered by *.mayflower.de"
    );

    // Unrelated host: still blocked.
    let events = rt.handle_command(HostCommand::Run {
        input: "curl https://example.com".into(),
    });
    assert_ne!(
        extract_exit_code(&events).unwrap(),
        0,
        "example.com must still be blocked"
    );
}

#[test]
fn curl_explicit_apex_plus_wildcard_covers_both() {
    if !mayflower_reachable() {
        return;
    }
    let mut rt = init_runtime_with_network(vec!["mayflower.de".into(), "*.mayflower.de".into()]);
    let events = rt.handle_command(HostCommand::Run {
        input: "curl -sL https://mayflower.de".into(),
    });
    assert_eq!(
        extract_exit_code(&events).unwrap(),
        0,
        "explicit apex should be allowed"
    );
}

// ── Empty allowlist tests ───────────────────────────────────────

#[test]
fn curl_empty_allowlist_blocks_everything() {
    let mut rt = init_runtime_with_network(vec![]);
    let events = rt.handle_command(HostCommand::Run {
        input: "curl https://mayflower.de".into(),
    });

    let stderr = extract_stderr(&events);
    let exit_code = extract_exit_code(&events).unwrap();

    assert_ne!(exit_code, 0, "empty allowlist must block all requests");
    assert!(
        stderr.contains("denied") || stderr.contains("allowlist"),
        "stderr should mention denial: {stderr}"
    );
}

// ── No network backend tests ────────────────────────────────────

#[test]
fn curl_no_backend_returns_error() {
    let mut rt = WorkerRuntime::new();
    rt.handle_command(HostCommand::Init {
        step_budget: 0,
        allowed_hosts: vec![],
    });
    let events = rt.handle_command(HostCommand::Run {
        input: "curl https://mayflower.de".into(),
    });

    let stderr = extract_stderr(&events);
    let exit_code = extract_exit_code(&events).unwrap();

    assert_ne!(exit_code, 0);
    assert!(
        stderr.contains("network access not available"),
        "should report no network access: {stderr}"
    );
}

// ── curl output to file ─────────────────────────────────────────

#[test]
fn curl_output_to_file_allowed_host() {
    if !mayflower_reachable() {
        return; // mayflower.de unreachable — skip
    }

    let mut rt = init_runtime_with_network(vec!["mayflower.de".into()]);

    let events = rt.handle_command(HostCommand::Run {
        input: "curl -sLo /tmp/mayflower.html https://mayflower.de".into(),
    });
    let exit_code = extract_exit_code(&events).unwrap();
    assert_eq!(exit_code, 0, "curl -o to allowed host should succeed");

    let events = rt.handle_command(HostCommand::Run {
        input: "wc -c /tmp/mayflower.html".into(),
    });
    let stdout = extract_stdout(&events);
    let byte_count: usize = stdout
        .split_whitespace()
        .next()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0);
    assert!(
        byte_count > 100,
        "downloaded file should have substantial content, got {byte_count} bytes"
    );
}

// ── curl write-out ──────────────────────────────────────────────

#[test]
fn curl_write_out_http_code() {
    if !mayflower_reachable() {
        return; // mayflower.de unreachable — skip
    }

    let mut rt = init_runtime_with_network(vec!["mayflower.de".into()]);
    let events = rt.handle_command(HostCommand::Run {
        input: "curl -sL -o /dev/null -w '%{http_code}' https://mayflower.de".into(),
    });

    let stdout = extract_stdout(&events);
    let exit_code = extract_exit_code(&events).unwrap();

    assert_eq!(exit_code, 0);
    assert!(
        stdout.contains("200"),
        "expected HTTP 200 from mayflower.de, got: {stdout}"
    );
}

// ── Pipeline: curl | wc ─────────────────────────────────────────

#[test]
fn curl_pipe_to_shell_command() {
    if !mayflower_reachable() {
        return; // mayflower.de unreachable — skip
    }

    let mut rt = init_runtime_with_network(vec!["mayflower.de".into()]);

    let events = rt.handle_command(HostCommand::Run {
        input: "curl -sL https://mayflower.de | wc -l".into(),
    });

    let stdout = extract_stdout(&events);
    let exit_code = extract_exit_code(&events).unwrap();

    assert_eq!(exit_code, 0);
    let line_count: usize = stdout.trim().parse().unwrap_or(0);
    assert!(
        line_count > 5,
        "expected multiple lines from mayflower.de, got {line_count}"
    );
}