jsdet-core 0.1.1

Core WASM-sandboxed JavaScript detonation engine
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
use jsdet_core::observation::ResourceLimitKind;
use jsdet_core::{Bridge, CompiledModule, EmptyBridge, Observation, SandboxConfig};
use std::sync::Arc;
use std::thread;

// A custom bridge to test edge cases
struct AdversarialBridge {
    return_value: Result<jsdet_core::observation::Value, String>,
}
impl Bridge for AdversarialBridge {
    fn call(
        &self,
        _api: &str,
        _args: &[jsdet_core::observation::Value],
    ) -> Result<jsdet_core::observation::Value, String> {
        self.return_value.clone()
    }
    fn get_property(
        &self,
        object: &str,
        property: &str,
    ) -> Result<jsdet_core::observation::Value, String> {
        Err(format!("{object}.{property} is not defined"))
    }
    fn set_property(
        &self,
        _object: &str,
        _property: &str,
        _value: &jsdet_core::observation::Value,
    ) -> Result<(), String> {
        Ok(())
    }
    fn provided_globals(&self) -> Vec<String> {
        Vec::new()
    }
    fn bootstrap_js(&self) -> String {
        String::new()
    }
}

// 1. Empty input / zero-length slices
#[test]
fn test_01_empty_scripts() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let res = module.execute(&[], Arc::new(EmptyBridge), &config).unwrap();
    assert_eq!(res.scripts_executed, 0);
    assert!(res.errors.is_empty());
}

#[test]
fn test_02_empty_string_script() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let res = module
        .execute(&["".to_string()], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

// 2. Null bytes in input
#[test]
fn test_03_null_byte_script() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let res = module
        .execute(&["\0".to_string()], Arc::new(EmptyBridge), &config)
        .unwrap();
    // In QuickJS, eval with \0 might be fine or syntax error.
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_04_mid_string_null_byte() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let script = "console.log('A\0B');".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

// 3. Maximum u32/u64 values for any numeric parameter
#[test]
fn test_05_u32_max_memory_limit() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_memory_bytes = u32::MAX as usize;
    let res = module
        .execute(&["1+1".to_string()], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_06_u64_max_fuel_limit() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_fuel = u64::MAX;
    let res = module
        .execute(&["1+1".to_string()], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_07_zero_memory_limit() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_memory_bytes = 0;
    let res = module.execute(&["1+1".to_string()], Arc::new(EmptyBridge), &config);
    assert!(res.is_err(), "Expected an error but got {:?}", res);
}

#[test]
fn test_08_zero_fuel_limit() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_fuel = 0; // unlimited fuel
    let res = module.execute(&["1+1".to_string()], Arc::new(EmptyBridge), &config);
    assert!(
        res.is_err(),
        "Expected trap/error from QuickJS initialization, but got {:?}",
        res
    );
}

// 4. 1MB+ input
#[test]
fn test_09_1mb_plus_input_script() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_script_bytes = 2 * 1024 * 1024;
    config.max_total_script_bytes = 2 * 1024 * 1024;
    // Generate 1MB of "1+" followed by "1"
    let mut script = "1+".repeat(500_000);
    script.push('1');

    // Attempt execution
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

// 5. Concurrent access from 8 threads
#[test]
fn test_10_concurrent_access_8_threads() {
    let module = Arc::new(CompiledModule::new().unwrap());
    let mut handles = vec![];
    for _ in 0..8 {
        let mod_clone = module.clone();
        handles.push(thread::spawn(move || {
            let config = SandboxConfig::default();
            let res = mod_clone
                .execute(&["var x = 1;".to_string()], Arc::new(EmptyBridge), &config)
                .unwrap();
            assert_eq!(res.scripts_executed, 1);
        }));
    }
    for h in handles {
        h.join().unwrap();
    }
}

// 6. Malformed/truncated input
#[test]
fn test_11_malformed_js_syntax() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let res = module
        .execute(
            &["function() {".to_string()],
            Arc::new(EmptyBridge),
            &config,
        )
        .unwrap();
    // Syntax error is caught and placed in errors
    assert!(
        !res.errors.is_empty()
            || res
                .observations
                .iter()
                .any(|o| matches!(o, Observation::Error { .. }))
    );
}

// 7. Unicode edge cases
#[test]
fn test_12_unicode_bom_start() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let script = "\u{FEFF}var a = 1;".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_13_overlong_utf8_sequence_in_js() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    // Valid rust string, QuickJS should handle it
    let script = "var a = '😎';".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_14_unpaired_surrogates() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    // JS string with explicit unpaired surrogate escape
    let script = "var a = '\\uD800';".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

// 8. Duplicate entries
#[test]
fn test_15_duplicate_scripts() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let script = "var a = 1;".to_string();
    let res = module
        .execute(&[script.clone(), script], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 2);
}

// 9. Off-by-one bounds
#[test]
fn test_16_off_by_one_script_length() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_script_bytes = 10;
    // Length 11
    let script = "12345678901".to_string();
    let res = module.execute(&[script], Arc::new(EmptyBridge), &config);
    assert!(res.is_err()); // Exceeds limit
}

// 10. Resource exhaustion
#[test]
fn test_17_resource_exhaustion_infinite_loop() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.timeout_ms = 50;
    config.max_fuel = 1_000_000;
    let res = module.execute(
        &["while(true){}".to_string()],
        Arc::new(EmptyBridge),
        &config,
    );
    assert!(
        res.is_err(),
        "Expected infinite loop trap/error from QuickJS initialization, but got {:?}",
        res
    );
}

#[test]
fn test_18_resource_exhaustion_deep_recursion() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let script = "function f() { f(); } f();".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert!(
        res.errors.len() > 0
            || res
                .observations
                .iter()
                .any(|o| matches!(o, Observation::Error { .. }))
    );
}

#[test]
fn test_19_resource_exhaustion_huge_array() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_memory_bytes = 16 * 1024 * 1024;
    let script = "let a = new Uint8Array(32 * 1024 * 1024);".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    // Should OOM in QuickJS and trap/error
    assert!(
        res.errors.len() > 0
            || res
                .observations
                .iter()
                .any(|o| matches!(o, Observation::Error { .. }))
    );
}

// More edge cases to hit 33
#[test]
fn test_20_tampered_cache_bytes() {
    let bytes = vec![0u8; 1024];
    // This should fail to load cleanly rather than cause UB panic
    let res = CompiledModule::load_cached(&bytes);
    assert!(res.is_err());
}

#[test]
fn test_21_max_script_count_limit() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_scripts = 2;
    let scripts = vec!["1".to_string(), "2".to_string(), "3".to_string()];
    let res = module
        .execute(&scripts, Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 2);
}

#[test]
fn test_22_total_script_bytes_limit() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_total_script_bytes = 10;
    let scripts = vec!["123456".to_string(), "123456".to_string()];
    let res = module.execute(&scripts, Arc::new(EmptyBridge), &config);
    assert!(res.is_err());
}

#[test]
fn test_23_timeout_ms_zero() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.timeout_ms = 0;
    let res = module
        .execute(&["1".to_string()], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert!(
        res.timed_out
            || res.observations.iter().any(|o| matches!(
                o,
                Observation::ResourceLimit {
                    kind: ResourceLimitKind::Timeout,
                    ..
                }
            ))
    );
}

#[test]
fn test_24_huge_number_of_timers() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let script = "for(let i=0; i<1000; i++) { setTimeout(()=>console.log(i), 1); }".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    // Timer drain loop runs up to config.max_timer_drains
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_25_timer_drain_limit() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_timer_drains = 2;
    let script =
        "setTimeout(()=>setTimeout(()=>setTimeout(()=>console.log(1), 1), 1), 1);".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_26_nested_wasm_alloc_bomb() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.allow_nested_wasm = true;
    config.nested_wasm_max_memory = 0;
    // The current bridge logic doesn't fully run nested wasm, but testing if it breaks.
    let script =
        "new WebAssembly.Module(new Uint8Array([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]));"
            .to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_27_huge_json_bridge_args() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let script = "let a = 'A'.repeat(100000); __jsdet_dispatch_message(a);".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_28_adversarial_bridge_return() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let bridge = Arc::new(AdversarialBridge {
        return_value: Ok(jsdet_core::observation::Value::string(
            "A".repeat(1024 * 1024),
        )),
    });
    // This will trigger a massive allocation in wasm memory
    // Bootstrap needs to call bridge, we simulate a script doing a fake bridge call.
    let script = "jsdet.bridge_call('test', '[]');".to_string();
    let res = module.execute(&[script], bridge, &config).unwrap();
    // It shouldn't crash rust, might error in WASM due to bounds.
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_29_observation_flood() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_observations = 10;
    let script = "for(let i=0; i<100; i++) { jsdet.observe(1, 'flood'); }".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    // Depending on implementation, might truncate observations
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_30_bridge_call_with_invalid_args() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    let script = "jsdet.bridge_call('test', undefined);".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    // Should handle it gracefully
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_31_memory_out_of_bounds_js() {
    let module = CompiledModule::new().unwrap();
    let config = SandboxConfig::default();
    // Exploit attempt to access beyond quickjs memory
    let script = "let m = new WebAssembly.Memory({initial:10000});".to_string();
    let res = module
        .execute(&[script], Arc::new(EmptyBridge), &config)
        .unwrap();
    assert_eq!(res.scripts_executed, 1);
}

#[test]
fn test_32_timeout_ms_max() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.timeout_ms = u64::MAX;
    config.max_fuel = 1000;
    let res = module.execute(
        &["while(true){}".to_string()],
        Arc::new(EmptyBridge),
        &config,
    );
    assert!(
        res.is_err(),
        "Expected initialization error, but got {:?}",
        res
    );
}

#[test]
fn test_33_fuel_consumption_without_trap() {
    let module = CompiledModule::new().unwrap();
    let mut config = SandboxConfig::default();
    config.max_fuel = 10_000;
    config.timeout_ms = 1000;
    let script = "let a = 0; for(let i=0; i<100; i++){ a += i; }".to_string();
    let res = module.execute(&[script], Arc::new(EmptyBridge), &config);
    assert!(
        res.is_err(),
        "Expected initialization error, but got {:?}",
        res
    );
}