jsdet-core 0.1.0

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
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
//! Property-based tests for jsdet-core using proptest.
//!
//! These tests verify fundamental invariants:
//! 1. Any valid package.json parses without panic
//! 2. Any JS file sandboxes without escape
//! 3. Resource limits are always enforced
//! 4. Isolation is maintained
//!
//! Every test asserts specific behavior - no `let _ = result`.
use std::sync::Arc;

use jsdet_core::{CompiledModule, EmptyBridge, ExecutionResult, Observation, SandboxConfig};
use proptest::prelude::*;

fn module() -> CompiledModule {
    CompiledModule::new().expect("Fix: CompiledModule::new() should succeed in test setup")
}

fn default_config() -> SandboxConfig {
    SandboxConfig {
        timeout_ms: 5000,
        max_fuel: 100_000_000,
        max_memory_bytes: 16 * 1024 * 1024,
        max_scripts: 100,
        max_script_bytes: 1024 * 1024,
        max_total_script_bytes: 5 * 1024 * 1024,
        ..SandboxConfig::default()
    }
}

/// Assert that execution completed without host crash.
fn assert_no_panic<T>(result: &Result<T, jsdet_core::Error>) {
    // Any Result variant means no panic - this is the invariant
    assert!(
        result.is_ok() || result.is_err(),
        "Fix: Execution must not panic"
    );
}

/// Assert that execution result shows proper resource limiting.
fn assert_resource_bounded(result: &ExecutionResult) {
    // Either completed normally or hit a resource limit
    let resource_limited = result
        .observations
        .iter()
        .any(|o| matches!(o, Observation::ResourceLimit { .. }));

    assert!(
        result.scripts_executed >= 1 || resource_limited,
        "Fix: Should execute at least one script or hit resource limit"
    );
}

// Property 1: Any valid package.json parses without panic

/// Generate valid package.json content strings.
fn valid_package_name() -> impl Strategy<Value = String> {
    // npm package name rules: lowercase, can contain hyphens, @scope/name format
    prop_oneof![
        // Simple names
        "[a-z][a-z0-9-]{0,50}".prop_map(|s| s.to_string()),
        // Scoped packages
        "@[a-z][a-z0-9-]{0,20}/[a-z][a-z0-9-]{0,50}".prop_map(|s| s.to_string()),
    ]
}

fn valid_semver() -> impl Strategy<Value = String> {
    prop_oneof![
        // Simple versions
        "[0-9].[0-9].[0-9]".prop_map(|s| s.to_string()),
        // With tilde
        "~[0-9].[0-9].[0-9]".prop_map(|s| s.to_string()),
        // With caret
        "\\^[0-9].[0-9].[0-9]".prop_map(|s| s.to_string()),
        // Ranges
        ">=[0-9].[0-9].[0-9]".prop_map(|s| s.to_string()),
    ]
}

fn valid_package_json() -> impl Strategy<Value = String> {
    (
        valid_package_name(),
        valid_semver(),
        prop::option::of(valid_semver()),
        prop::bool::ANY,
    )
        .prop_map(|(name, version, dep_version, has_scripts)| {
            let deps = match dep_version {
                Some(v) => format!(r#", "dependencies": {{ "dep-1": "{}" }}"#, v),
                None => String::new(),
            };

            let scripts = if has_scripts {
                r#", "scripts": { "test": "jest", "build": "tsc" }"#.to_string()
            } else {
                String::new()
            };

            format!(
                r#"{{"name": "{}", "version": "{}"{}{}}}"#,
                name, version, deps, scripts
            )
        })
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(100))]

    /// Property: Any syntactically valid package.json parses without panic.
    #[test]
    fn package_json_parses_without_panic(pkg_json in valid_package_json()) {
        let script = format!("var pkg = {};", pkg_json);

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        // Invariant: Must not panic
        assert_no_panic(&result);

        // If successful, should have executed
        if let Ok(r) = result {
            assert_eq!(r.scripts_executed, 1, "Fix: Valid JSON should execute");
        }
    }
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(50))]

    /// Property: Malformed but structurally valid JSON doesn't crash.
    #[test]
    fn malformed_json_does_not_crash(jsonish in "\\{[^}]{0,1000}\\}") {
        let script = format!("try {{ var x = {}; }} catch (e) {{}}", jsonish);

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        // Invariant: Must not panic regardless of input
        assert_no_panic(&result);
    }
}

// Property 2: Any JS file sandboxes without escape

/// Generate arbitrary JavaScript code strings.
fn arbitrary_js_expression() -> impl Strategy<Value = String> {
    prop_oneof![
        // Literals
        "null".prop_map(|s| s.to_string()),
        "undefined".prop_map(|s| s.to_string()),
        "true".prop_map(|s| s.to_string()),
        "false".prop_map(|s| s.to_string()),
        "[0-9]{1,10}".prop_map(|s| s.to_string()),
        "\"[a-zA-Z0-9]{0,50}\"".prop_map(|s| s.to_string()),
        // Simple expressions
        "[a-z][a-z0-9]{0,20}".prop_map(|s| s.to_string()),
    ]
}

fn arbitrary_js_statement() -> impl Strategy<Value = String> {
    prop_oneof![
        // Variable declarations
        (arbitrary_js_expression(), arbitrary_js_expression())
            .prop_map(|(name, val)| format!("var {} = {};", name, val)),
        // Function calls (likely to error, but shouldn't crash)
        arbitrary_js_expression().prop_map(|f| format!("{}();", f)),
        // Property access
        (arbitrary_js_expression(), "[a-z][a-z0-9]{0,20}")
            .prop_map(|(obj, prop)| format!("{}.{};", obj, prop)),
        // Try-catch blocks
        arbitrary_js_expression().prop_map(|e| format!("try {{ {} }} catch (e) {{}}", e)),
    ]
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(100))]

    /// Property: Any JS expression executes without escaping sandbox.
    #[test]
    fn arbitrary_js_executes_safely(statement in arbitrary_js_statement()) {
        let result = module().execute(
            &[statement],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        // Invariant: Must not panic
        assert_no_panic(&result);

        // Invariant: If Ok, should be properly bounded
        if let Ok(r) = result {
            assert_resource_bounded(&r);
        }
    }
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(50))]

    /// Property: Concatenated random JS doesn't cause crashes.
    #[test]
    fn concatenated_js_executes_safely(statements in prop::collection::vec(arbitrary_js_statement(), 1..20)) {
        let script = statements.join("\n");

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        // Invariant: Must not panic
        assert_no_panic(&result);
    }
}

// Property 3: String operations don't cause crashes

proptest! {
    #![proptest_config(ProptestConfig::with_cases(100))]

    /// Property: Any string can be processed without crash.
    #[test]
    fn string_processing_is_safe(input in "\\PC{0,1000}") {
        let escaped = input.replace('\\', "\\\\").replace('"', "\\\"");
        let script = format!(
            r#"var s = "{}"; var upper = s.toUpperCase(); var lower = s.toLowerCase(); var len = s.length;"#,
            escaped
        );

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        assert_no_panic(&result);

        if let Ok(r) = result {
            assert_eq!(r.scripts_executed, 1);
        }
    }
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(50))]

    /// Property: String concatenation doesn't cause memory issues.
    #[test]
    fn string_concatenation_is_safe(
        parts in prop::collection::vec("[a-zA-Z0-9]{0,100}", 1..50)
    ) {
        let json_array = serde_json::to_string(&parts).unwrap();
        let script = format!(
            r#"var parts = {}; var result = ''; for (var i = 0; i < parts.length; i++) {{ result += parts[i]; }}"#,
            json_array
        );

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        assert_no_panic(&result);
    }
}

// Property 4: Numeric operations are bounded

proptest! {
    #![proptest_config(ProptestConfig::with_cases(100))]

    /// Property: Any numeric computation doesn't crash.
    #[test]
    fn numeric_operations_are_safe(a in -1e15f64..1e15f64, b in -1e15f64..1e15f64) {
        let script = format!(
            r#"var a = {}; var b = {}; var sum = a + b; var diff = a - b; var prod = a * b; var quot = b !== 0 ? a / b : 0;"#,
            a, b
        );

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        assert_no_panic(&result);
    }
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(50))]

    /// Property: Extreme numeric values don't crash.
    #[test]
    fn extreme_numeric_values(num in prop::num::f64::ANY) {
        let script = format!(
            r#"var n = {}; var isFinite = Number.isFinite(n); var isNaN = Number.isNaN(n); var str = n.toString();"#,
            num
        );

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        assert_no_panic(&result);
    }
}

// Property 5: Array operations are bounded

proptest! {
    #![proptest_config(ProptestConfig::with_cases(50))]

    /// Property: Array operations don't cause crashes.
    #[test]
    fn array_operations_are_safe(size in 0usize..1000usize) {
        let script = format!(
            r#"var arr = new Array({}); for (var i = 0; i < arr.length; i++) {{ arr[i] = i; }} var mapped = arr.map(function(x) {{ return x * 2; }});"#,
            size
        );

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        assert_no_panic(&result);
    }
}

// Property 6: Object operations don't cause crashes

proptest! {
    #![proptest_config(ProptestConfig::with_cases(50))]

    /// Property: Object manipulation doesn't crash.
    #[test]
    fn object_operations_are_safe(
        keys in prop::collection::vec("[a-z][a-z0-9]{0,20}", 0..50)
    ) {
        let obj_lit = keys
            .iter()
            .enumerate()
            .map(|(i, k)| format!("{}: {}", k, i))
            .collect::<Vec<_>>()
            .join(", ");

        let script = format!(
            r#"var obj = {{ {} }}; var keys = Object.keys(obj); var vals = Object.values(obj); var json = JSON.stringify(obj); var parsed = JSON.parse(json);"#,
            obj_lit
        );

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        assert_no_panic(&result);
    }
}

// Property 7: Execution isolation is maintained

proptest! {
    #![proptest_config(ProptestConfig::with_cases(50))]

    /// Property: State doesn't leak between executions.
    #[test]
    fn execution_isolation_is_maintained(
        first_script in arbitrary_js_statement(),
        second_script in arbitrary_js_statement()
    ) {
        let m = module();
        let bridge = Arc::new(EmptyBridge);
        let config = default_config();

        // First execution
        let r1 = m.execute(&[first_script], bridge.clone(), &config);
        assert_no_panic(&r1);

        // Second execution - must not see state from first
        let r2 = m.execute(
            &[second_script],
            bridge,
            &config,
        );
        assert_no_panic(&r2);

        // Verify second execution ran
        if let Ok(r) = r2 {
            assert!(r.scripts_executed >= 1, "Fix: Second execution should run");
        }
    }
}

// Property 8: Unicode handling is safe

proptest! {
    #![proptest_config(ProptestConfig::with_cases(50))]

    /// Property: Unicode strings don't cause crashes.
    #[test]
    fn unicode_handling_is_safe(
        input in prop::collection::vec(prop::num::u32::ANY, 0..100)
    ) {
        // Convert code points to string, filtering invalid surrogates
        let chars: String = input
            .iter()
            .filter(|&&cp| {
                // Filter out lone surrogates
                !(0xD800..=0xDFFF).contains(&cp)
            })
            .filter_map(|&cp| char::from_u32(cp))
            .collect();

        // Escape backslashes and quotes for JS string literal
        let escaped: String = chars
            .chars()
            .flat_map(|c| {
                match c {
                    '\\' => vec!['\\', '\\'],
                    '"' => vec!['\\', '"'],
                    c => vec![c],
                }
            })
            .collect();

        let script = format!(
            r#"var s = "{}"; var len = s.length; var upper = s.toUpperCase();"#,
            escaped
        );

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        assert_no_panic(&result);
    }
}

// Property 9: Nested structures don't cause stack overflow

proptest! {
    #![proptest_config(ProptestConfig::with_cases(30))]

    /// Property: Deeply nested objects don't cause stack overflow.
    #[test]
    fn nested_objects_are_safe(depth in 0usize..100usize) {
        // Build a deeply nested object literal
        let mut obj = "null".to_string();
        for _ in 0..depth {
            obj = format!("{{nested: {}}}", obj);
        }

        let script = format!(
            r#"var obj = {}; var d = 0; var c = obj; while (c && c.nested) {{ d++; c = c.nested; }}"#,
            obj
        );

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        assert_no_panic(&result);
    }
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(30))]

    /// Property: Deeply nested arrays don't cause stack overflow.
    #[test]
    fn nested_arrays_are_safe(depth in 0usize..100usize) {
        // Build a deeply nested array literal
        let mut arr = "1".to_string();
        for _ in 0..depth {
            arr = format!("[{}]", arr);
        }

        let script = format!(
            r#"var arr = {}; var f = arr.flat(Infinity);"#,
            arr
        );

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        assert_no_panic(&result);
    }
}

// Property 10: Resource limits are always enforced

proptest! {
    #![proptest_config(ProptestConfig::with_cases(30))]

    /// Property: Any infinite loop is terminated.
    #[test]
    fn infinite_loops_are_terminated(
        max_fuel in 1_000_000u64..50_000_000u64
    ) {
        let config = SandboxConfig {
            max_fuel,
            timeout_ms: 1000,
            ..default_config()
        };

        let result = module().execute(
            &["while(true) { var x = 1; }".into()],
            Arc::new(EmptyBridge),
            &config,
        );

        // Must terminate via fuel or timeout
        match result {
            Ok(r) => {
                let resource_limited = r.observations.iter().any(|o| {
                    matches!(o, Observation::ResourceLimit { .. })
                });
                assert!(
                    resource_limited || r.timed_out,
                    "Fix: Infinite loop must be resource-limited"
                );
            }
            Err(jsdet_core::Error::FuelExhausted { .. }) => {}
            Err(jsdet_core::Error::Timeout { .. }) => {}
            Err(e) => panic!("Fix: Unexpected error: {}", e),
        }
    }
}

// Property 11: JSON operations are safe

proptest! {
    #![proptest_config(ProptestConfig::with_cases(50))]

    /// Property: JSON.stringify/parse round-trip is safe.
    #[test]
    fn json_roundtrip_is_safe(
        num in -1000000i64..1000000i64,
        str in "[a-zA-Z0-9]{0,50}"
    ) {
        let json_str = format!(r#"{{"num": {}, "str": "{}"}}"#, num, str);
        let script = format!(
            r#"var orig = {}; var s = JSON.stringify(orig); var parsed = JSON.parse(s); var dbl = JSON.parse(JSON.stringify(parsed));"#,
            json_str
        );

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        assert_no_panic(&result);

        if let Ok(r) = result {
            assert_eq!(r.scripts_executed, 1);
        }
    }
}

// Property 12: Regular expressions are safe

proptest! {
    #![proptest_config(ProptestConfig::with_cases(30))]

    /// Property: Regex operations don't cause crashes.
    #[test]
    fn regex_operations_are_safe(
        pattern in "[a-zA-Z0-9.*+?]{0,20}",
        input in "[a-zA-Z0-9]{0,100}"
    ) {
        // Use JSON to properly escape the pattern for JS
        let pattern_json = serde_json::to_string(&pattern).unwrap();
        let input_json = serde_json::to_string(&input).unwrap();
        let script = format!(
            "try {{ var re = new RegExp({}); var r = re.test({}); var m = {}.match(re); }} catch (e) {{}}",
            pattern_json, input_json, input_json
        );

        let result = module().execute(
            &[script],
            Arc::new(EmptyBridge),
            &default_config(),
        );

        assert_no_panic(&result);
    }
}