agent-sandbox 0.3.0

A sandboxed execution environment for AI agents via WASM
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
use std::collections::HashMap;

use agent_sandbox::config::SandboxConfig;
use agent_sandbox::{DomainPattern, FetchPolicy, FetchRequest, Sandbox};

fn temp_sandbox() -> (tempfile::TempDir, Sandbox) {
    let tmp = tempfile::tempdir().unwrap();
    let config = SandboxConfig {
        work_dir: tmp.path().to_path_buf(),
        ..Default::default()
    };
    let sandbox = Sandbox::new(config).unwrap();
    (tmp, sandbox)
}

#[tokio::test]
async fn test_create_sandbox() {
    let (_tmp, sandbox) = temp_sandbox();
    // Sandbox created successfully
    sandbox.destroy().await.unwrap();
}

#[tokio::test]
async fn test_write_and_read_file() {
    let (_tmp, sandbox) = temp_sandbox();

    sandbox
        .write_file("test.txt", b"hello world")
        .await
        .unwrap();

    let content = sandbox.read_file("test.txt").await.unwrap();
    assert_eq!(content, b"hello world");
}

#[tokio::test]
async fn test_write_file_creates_parent_dirs() {
    let (_tmp, sandbox) = temp_sandbox();

    sandbox.write_file("a/b/c.txt", b"nested").await.unwrap();

    let content = sandbox.read_file("a/b/c.txt").await.unwrap();
    assert_eq!(content, b"nested");
}

#[tokio::test]
async fn test_list_dir() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("a.txt"), "a").unwrap();
    std::fs::write(tmp.path().join("b.txt"), "b").unwrap();
    std::fs::create_dir(tmp.path().join("subdir")).unwrap();

    let entries = sandbox.list_dir(".").await.unwrap();
    assert_eq!(entries.len(), 3);
    assert!(entries.iter().any(|e| e.name == "a.txt" && e.is_file));
    assert!(entries.iter().any(|e| e.name == "b.txt" && e.is_file));
    assert!(entries.iter().any(|e| e.name == "subdir" && e.is_dir));
}

#[tokio::test]
async fn test_exec_echo() {
    let (_tmp, sandbox) = temp_sandbox();

    let result = sandbox
        .exec("echo", &["hello".into(), "world".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    assert_eq!(
        String::from_utf8_lossy(&result.stdout).trim(),
        "hello world"
    );
}

#[tokio::test]
async fn test_exec_cat() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("hello.txt"), "hello sandbox").unwrap();

    let result = sandbox
        .exec("cat", &["/work/hello.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    assert!(String::from_utf8_lossy(&result.stdout).contains("hello sandbox"));
}

#[tokio::test]
async fn test_exec_ls() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("file1.txt"), "").unwrap();
    std::fs::write(tmp.path().join("file2.txt"), "").unwrap();

    let result = sandbox.exec("ls", &["/work".into()]).await.unwrap();

    assert_eq!(result.exit_code, 0);
    let output = String::from_utf8_lossy(&result.stdout);
    assert!(output.contains("file1.txt"));
    assert!(output.contains("file2.txt"));
}

#[tokio::test]
async fn test_exec_find() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::create_dir_all(tmp.path().join("a/b")).unwrap();
    std::fs::write(tmp.path().join("a/b/deep.txt"), "deep").unwrap();

    let result = sandbox
        .exec("find", &["/work".into(), "-name".into(), "*.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let output = String::from_utf8_lossy(&result.stdout);
    assert!(output.contains("deep.txt"));
}

#[tokio::test]
async fn test_exec_grep() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(
        tmp.path().join("code.rs"),
        "fn main() {\n    println!(\"hello\");\n}\n",
    )
    .unwrap();

    let result = sandbox
        .exec("grep", &["main".into(), "/work/code.rs".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let output = String::from_utf8_lossy(&result.stdout);
    assert!(output.contains("fn main()"));
}

#[tokio::test]
async fn test_exec_wc() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("lines.txt"), "one\ntwo\nthree\n").unwrap();

    let result = sandbox
        .exec("wc", &["-l".into(), "/work/lines.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let output = String::from_utf8_lossy(&result.stdout);
    assert!(output.contains("3"));
}

#[tokio::test]
async fn test_exec_mkdir_and_touch() {
    let (_tmp, sandbox) = temp_sandbox();

    let result = sandbox
        .exec("mkdir", &["-p".into(), "/work/newdir/sub".into()])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);

    let result = sandbox
        .exec("touch", &["/work/newdir/sub/file.txt".into()])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);

    let result = sandbox
        .exec("ls", &["/work/newdir/sub".into()])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    let output = String::from_utf8_lossy(&result.stdout);
    assert!(output.contains("file.txt"));
}

#[tokio::test]
async fn test_path_traversal_blocked() {
    let (_tmp, sandbox) = temp_sandbox();

    let result = sandbox.read_file("../../../etc/passwd").await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("traversal"));
}

#[tokio::test]
async fn test_command_not_found() {
    let (_tmp, sandbox) = temp_sandbox();

    let result = sandbox.exec("nonexistent_cmd", &[]).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("not found"));
}

#[tokio::test]
async fn test_fuel_exhaustion_timeout() {
    let tmp = tempfile::tempdir().unwrap();
    let config = SandboxConfig {
        work_dir: tmp.path().to_path_buf(),
        fuel_limit: 1000, // Very low fuel to trigger exhaustion
        ..Default::default()
    };
    let sandbox = Sandbox::new(config).unwrap();

    // Even a simple echo should exhaust 1000 fuel units
    let result = sandbox.exec("echo", &["hello".into()]).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("timed out") || err.contains("fuel"),
        "Expected timeout/fuel error, got: {}",
        err
    );
}

#[tokio::test]
async fn test_diff_reports_changes() {
    let (tmp, _sandbox) = temp_sandbox();

    // Write initial file
    std::fs::write(tmp.path().join("existing.txt"), "original").unwrap();

    // Create a new sandbox to snapshot current state
    let config = SandboxConfig {
        work_dir: tmp.path().to_path_buf(),
        ..Default::default()
    };
    let sandbox = Sandbox::new(config).unwrap();

    // Create a new file
    std::fs::write(tmp.path().join("new.txt"), "new content").unwrap();

    // Modify existing file
    std::fs::write(tmp.path().join("existing.txt"), "modified").unwrap();

    let changes = sandbox.diff().await.unwrap();
    assert!(
        changes.iter().any(|c| c.path == "new.txt"),
        "Expected 'new.txt' in changes: {:?}",
        changes.iter().map(|c| &c.path).collect::<Vec<_>>()
    );
    assert!(
        changes.iter().any(|c| c.path == "existing.txt"),
        "Expected 'existing.txt' in changes: {:?}",
        changes.iter().map(|c| &c.path).collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_destroy_prevents_operations() {
    let (_tmp, sandbox) = temp_sandbox();

    sandbox.destroy().await.unwrap();

    let result = sandbox.read_file("anything.txt").await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("destroyed"));
}

#[tokio::test]
async fn test_exec_sed() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("input.txt"), "hello world\n").unwrap();

    let result = sandbox
        .exec("sed", &["s/world/rust/g".into(), "/work/input.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let output = String::from_utf8_lossy(&result.stdout);
    assert!(output.contains("hello rust"));
}

#[tokio::test]
async fn test_exec_basename_dirname() {
    let (_tmp, sandbox) = temp_sandbox();

    let result = sandbox
        .exec("basename", &["/work/path/to/file.txt".into()])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), "file.txt");

    let result = sandbox
        .exec("dirname", &["/work/path/to/file.txt".into()])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(
        String::from_utf8_lossy(&result.stdout).trim(),
        "/work/path/to"
    );
}

// --- Additional tool exec tests ---

#[tokio::test]
async fn test_exec_head() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(
        tmp.path().join("data.txt"),
        "line1\nline2\nline3\nline4\nline5\n",
    )
    .unwrap();

    let result = sandbox
        .exec("head", &["-n".into(), "2".into(), "/work/data.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let output = String::from_utf8_lossy(&result.stdout);
    assert!(output.contains("line1"));
    assert!(output.contains("line2"));
    assert!(!output.contains("line3"));
}

#[tokio::test]
async fn test_exec_tail() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(
        tmp.path().join("data.txt"),
        "line1\nline2\nline3\nline4\nline5\n",
    )
    .unwrap();

    let result = sandbox
        .exec("tail", &["-n".into(), "2".into(), "/work/data.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let output = String::from_utf8_lossy(&result.stdout);
    assert!(!output.contains("line3"));
    assert!(output.contains("line4"));
    assert!(output.contains("line5"));
}

#[tokio::test]
async fn test_exec_sort() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("unsorted.txt"), "banana\napple\ncherry\n").unwrap();

    let result = sandbox
        .exec("sort", &["/work/unsorted.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    assert_eq!(
        String::from_utf8_lossy(&result.stdout).trim(),
        "apple\nbanana\ncherry"
    );
}

#[tokio::test]
async fn test_exec_uniq() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("dups.txt"), "a\na\nb\nb\nb\nc\n").unwrap();

    let result = sandbox
        .exec("uniq", &["/work/dups.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), "a\nb\nc");
}

#[tokio::test]
async fn test_exec_cp() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("src.txt"), "copy me").unwrap();

    let result = sandbox
        .exec("cp", &["/work/src.txt".into(), "/work/dst.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let content = std::fs::read_to_string(tmp.path().join("dst.txt")).unwrap();
    assert_eq!(content, "copy me");
}

#[tokio::test]
async fn test_exec_mv() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("old.txt"), "move me").unwrap();

    let result = sandbox
        .exec("mv", &["/work/old.txt".into(), "/work/new.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    assert!(!tmp.path().join("old.txt").exists());
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("new.txt")).unwrap(),
        "move me"
    );
}

#[tokio::test]
async fn test_exec_rm() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("delete.txt"), "bye").unwrap();
    assert!(tmp.path().join("delete.txt").exists());

    let result = sandbox
        .exec("rm", &["/work/delete.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    assert!(!tmp.path().join("delete.txt").exists());
}

#[tokio::test]
async fn test_exec_base64() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("plain.txt"), "hello").unwrap();

    let result = sandbox
        .exec("base64", &["/work/plain.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), "aGVsbG8=");
}

#[tokio::test]
async fn test_exec_sha256sum() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("hash.txt"), "hello").unwrap();

    let result = sandbox
        .exec("sha256sum", &["/work/hash.txt".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let output = String::from_utf8_lossy(&result.stdout);
    // sha256("hello") = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
    assert!(output.contains("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"));
}

#[tokio::test]
async fn test_exec_diff() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("a.txt"), "line1\nline2\nline3\n").unwrap();
    std::fs::write(tmp.path().join("b.txt"), "line1\nmodified\nline3\n").unwrap();

    let result = sandbox
        .exec("diff", &["/work/a.txt".into(), "/work/b.txt".into()])
        .await
        .unwrap();

    // diff returns exit code 1 when files differ
    assert_eq!(result.exit_code, 1);
    let output = String::from_utf8_lossy(&result.stdout);
    assert!(output.contains("line2") || output.contains("modified"));
}

#[tokio::test]
async fn test_exec_cut() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("csv.txt"), "a,b,c\n1,2,3\n").unwrap();

    let result = sandbox
        .exec(
            "cut",
            &[
                "-d".into(),
                ",".into(),
                "-f".into(),
                "2".into(),
                "/work/csv.txt".into(),
            ],
        )
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), "b\n2");
}

#[tokio::test]
async fn test_exec_env() {
    let (_tmp, sandbox) = temp_sandbox();

    let result = sandbox.exec("env", &[]).await.unwrap();

    assert_eq!(result.exit_code, 0);
    let output = String::from_utf8_lossy(&result.stdout);
    assert!(output.contains("TOOLBOX_CMD=env"));
}

// --- Security tests ---

#[tokio::test]
async fn test_security_path_traversal_variants() {
    let (_tmp, sandbox) = temp_sandbox();

    // Various traversal attempts via readFile
    let traversals = [
        "../../../etc/passwd",
        "../../etc/shadow",
        "foo/../../..",
        "./../../etc/hosts",
        "foo/../../../etc/passwd",
    ];

    for path in traversals {
        let result = sandbox.read_file(path).await;
        assert!(
            result.is_err(),
            "Path '{}' should be blocked but was allowed",
            path
        );
        assert!(
            result.unwrap_err().to_string().contains("traversal"),
            "Path '{}' should return traversal error",
            path
        );
    }
}

#[tokio::test]
async fn test_security_write_file_traversal() {
    let (_tmp, sandbox) = temp_sandbox();

    // Attempt to write outside the sandbox
    let result = sandbox
        .write_file("../../../tmp/escape.txt", b"pwned")
        .await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("traversal"));
}

#[tokio::test]
async fn test_security_list_dir_traversal() {
    let (_tmp, sandbox) = temp_sandbox();

    let result = sandbox.list_dir("../../../etc").await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("traversal"));
}

#[tokio::test]
async fn test_security_symlink_escape() {
    let (tmp, sandbox) = temp_sandbox();

    // Create a symlink inside work dir that points outside
    let link_path = tmp.path().join("escape_link");
    std::os::unix::fs::symlink("/etc", &link_path).unwrap();

    // Reading via the symlink should fail — the resolved path is outside the sandbox
    let result = sandbox.read_file("escape_link/passwd").await;
    assert!(
        result.is_err(),
        "Symlink escape to /etc/passwd should be blocked"
    );
}

#[tokio::test]
async fn test_security_cat_cannot_read_host_files() {
    let (_tmp, sandbox) = temp_sandbox();

    // WASM sandbox should not have access to /etc/passwd via cat
    let result = sandbox.exec("cat", &["/etc/passwd".into()]).await.unwrap();

    // Should fail since /etc is not mounted
    assert_ne!(result.exit_code, 0);
    assert!(String::from_utf8_lossy(&result.stdout).is_empty());
}

#[tokio::test]
async fn test_security_find_confined_to_sandbox() {
    let (_tmp, sandbox) = temp_sandbox();

    // find should not be able to traverse outside /work
    let result = sandbox
        .exec("find", &["/".into(), "-name".into(), "passwd".into()])
        .await
        .unwrap();

    let output = String::from_utf8_lossy(&result.stdout);
    // Should not find /etc/passwd — only /work is mounted
    assert!(
        !output.contains("/etc/passwd"),
        "find should not see /etc/passwd, got: {}",
        output
    );
}

#[tokio::test]
async fn test_security_cp_cannot_write_outside_sandbox() {
    let (tmp, sandbox) = temp_sandbox();

    std::fs::write(tmp.path().join("secret.txt"), "data").unwrap();

    // Attempt to copy to a path outside /work
    let result = sandbox
        .exec("cp", &["/work/secret.txt".into(), "/tmp/escape.txt".into()])
        .await
        .unwrap();

    // Should fail — /tmp is not writable/mounted
    assert_ne!(result.exit_code, 0);
    assert!(!std::path::Path::new("/tmp/escape.txt").exists());
}

#[tokio::test]
async fn test_security_env_vars_isolated() {
    let tmp = tempfile::tempdir().unwrap();
    let config = SandboxConfig {
        work_dir: tmp.path().to_path_buf(),
        env_vars: [("SECRET_KEY".into(), "s3cret".into())]
            .into_iter()
            .collect(),
        ..Default::default()
    };
    let sandbox = Sandbox::new(config).unwrap();

    let result = sandbox.exec("env", &[]).await.unwrap();
    let output = String::from_utf8_lossy(&result.stdout);

    // Configured env vars should be visible
    assert!(output.contains("SECRET_KEY=s3cret"));

    // Host env vars like HOME, USER, PATH should NOT leak into the sandbox
    assert!(
        !output.contains("HOME="),
        "Host HOME should not leak into sandbox"
    );
    assert!(
        !output.contains("USER="),
        "Host USER should not leak into sandbox"
    );
}

#[tokio::test]
async fn test_security_fuel_limit_prevents_infinite_loop() {
    let tmp = tempfile::tempdir().unwrap();
    let config = SandboxConfig {
        work_dir: tmp.path().to_path_buf(),
        fuel_limit: 100_000, // Low enough to stop runaway but enough to start
        ..Default::default()
    };
    let sandbox = Sandbox::new(config).unwrap();

    // Try running a command — with limited fuel it should error, not hang
    let result = sandbox.exec("echo", &["test".into()]).await;
    // Either succeeds quickly or fails with timeout/fuel — should NOT hang
    assert!(
        result.is_ok() || result.unwrap_err().to_string().contains("timed out"),
        "Low fuel should either complete or timeout, not hang"
    );
}

#[tokio::test]
async fn test_security_timeout_prevents_hang() {
    let tmp = tempfile::tempdir().unwrap();
    let config = SandboxConfig {
        work_dir: tmp.path().to_path_buf(),
        timeout: std::time::Duration::from_secs(2), // 2 second timeout
        fuel_limit: u64::MAX,                       // Effectively unlimited fuel
        ..Default::default()
    };
    let sandbox = Sandbox::new(config).unwrap();

    let start = std::time::Instant::now();
    // Even with unlimited fuel, we should not wait longer than timeout + margin
    let _result = sandbox.exec("echo", &["hello".into()]).await;
    let elapsed = start.elapsed();

    assert!(
        elapsed < std::time::Duration::from_secs(10),
        "Execution should respect timeout, took {:?}",
        elapsed
    );
}

#[tokio::test]
async fn test_security_destroyed_sandbox_blocks_all_ops() {
    let (_tmp, sandbox) = temp_sandbox();

    sandbox.destroy().await.unwrap();

    // All operations should fail with "destroyed"
    assert!(sandbox.read_file("any.txt").await.is_err());
    assert!(sandbox.write_file("any.txt", b"data").await.is_err());
    assert!(sandbox.list_dir(".").await.is_err());
    assert!(sandbox.exec("echo", &["hello".into()]).await.is_err());
    assert!(sandbox.diff().await.is_err());
}

#[tokio::test]
async fn test_security_grep_cannot_read_host_files() {
    let (_tmp, sandbox) = temp_sandbox();

    let result = sandbox
        .exec("grep", &["root".into(), "/etc/passwd".into()])
        .await
        .unwrap();

    // grep should fail because /etc is not mounted
    assert_ne!(result.exit_code, 0);
}

#[tokio::test]
async fn test_security_rm_cannot_delete_outside_sandbox() {
    let (_tmp, sandbox) = temp_sandbox();

    let result = sandbox.exec("rm", &["/etc/hostname".into()]).await.unwrap();

    // rm outside /work should fail
    assert_ne!(result.exit_code, 0);
}

#[tokio::test]
async fn test_security_multiple_sandboxes_isolated() {
    let tmp1 = tempfile::tempdir().unwrap();
    let tmp2 = tempfile::tempdir().unwrap();

    let sandbox1 = Sandbox::new(SandboxConfig {
        work_dir: tmp1.path().to_path_buf(),
        ..Default::default()
    })
    .unwrap();

    let sandbox2 = Sandbox::new(SandboxConfig {
        work_dir: tmp2.path().to_path_buf(),
        ..Default::default()
    })
    .unwrap();

    // Write a file in sandbox1
    std::fs::write(tmp1.path().join("secret.txt"), "sandbox1 secret").unwrap();

    // Sandbox2 should not see sandbox1's files
    let result = sandbox2
        .exec("cat", &["/work/secret.txt".into()])
        .await
        .unwrap();
    assert_ne!(
        result.exit_code, 0,
        "Sandbox2 should not see sandbox1's files"
    );

    // Sandbox1 should see its own file
    let result = sandbox1
        .exec("cat", &["/work/secret.txt".into()])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert!(String::from_utf8_lossy(&result.stdout).contains("sandbox1 secret"));
}

// --- Node.js / JavaScript runtime tests ---

#[tokio::test]
async fn test_node_version() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox.exec("node", &["--version".into()]).await.unwrap();
    assert_eq!(result.exit_code, 0);
    let output = String::from_utf8_lossy(&result.stdout);
    assert!(output.contains("node v0.1.0"));
}

#[tokio::test]
async fn test_node_eval_console_log() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec(
            "node",
            &["-e".into(), "console.log('hello from js')".into()],
        )
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(
        stdout.contains("hello from js"),
        "Expected 'hello from js' in stdout: {stdout}"
    );
}

#[tokio::test]
async fn test_node_eval_arithmetic() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec("node", &["-p".into(), "2 + 3 * 4".into()])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), "14");
}

#[tokio::test]
async fn test_node_eval_string_operations() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec(
            "node",
            &["-p".into(), "'hello'.toUpperCase() + ' WORLD'".into()],
        )
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(
        String::from_utf8_lossy(&result.stdout).trim(),
        "HELLO WORLD"
    );
}

#[tokio::test]
async fn test_node_eval_json_parse() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec(
            "node",
            &[
                "-p".into(),
                r#"JSON.stringify(JSON.parse('{"a":1,"b":2}'))"#.into(),
            ],
        )
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(
        String::from_utf8_lossy(&result.stdout).trim(),
        r#"{"a":1,"b":2}"#
    );
}

#[tokio::test]
async fn test_node_eval_array_methods() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec(
            "node",
            &[
                "-p".into(),
                "[3,1,4,1,5].filter(x => x > 2).sort().join(',')".into(),
            ],
        )
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), "3,4,5");
}

#[tokio::test]
async fn test_node_eval_error_handling() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec("node", &["-e".into(), "throw new Error('oops')".into()])
        .await
        .unwrap();
    assert_ne!(result.exit_code, 0);
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("oops"),
        "Expected 'oops' in stderr: {stderr}"
    );
}

#[tokio::test]
async fn test_node_eval_syntax_error() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec("node", &["-e".into(), "function {".into()])
        .await
        .unwrap();
    assert_ne!(result.exit_code, 0);
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(!stderr.is_empty(), "Expected error output for syntax error");
}

#[tokio::test]
async fn test_node_run_file() {
    let (tmp, sandbox) = temp_sandbox();
    std::fs::write(
        tmp.path().join("script.js"),
        "var x = 10;\nvar y = 20;\nconsole.log(x + y);\n",
    )
    .unwrap();

    let result = sandbox
        .exec("node", &["/work/script.js".into()])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(stdout.contains("30"), "Expected '30' in stdout: {stdout}");
}

#[tokio::test]
async fn test_node_file_not_found() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec("node", &["/work/nonexistent.js".into()])
        .await
        .unwrap();
    assert_ne!(result.exit_code, 0);
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("cannot open"),
        "Expected file not found error in stderr: {stderr}"
    );
}

#[tokio::test]
async fn test_node_multiline_script() {
    let (tmp, sandbox) = temp_sandbox();
    std::fs::write(
        tmp.path().join("multi.js"),
        r#"
function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(10));
"#,
    )
    .unwrap();

    let result = sandbox
        .exec("node", &["/work/multi.js".into()])
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(
        stdout.contains("55"),
        "Expected fibonacci(10)=55 in stdout: {stdout}"
    );
}

#[tokio::test]
async fn test_exec_js_convenience_method() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec_js("console.log('exec_js works')")
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(
        stdout.contains("exec_js works"),
        "Expected 'exec_js works' in stdout: {stdout}"
    );
}

#[tokio::test]
async fn test_node_eval_object_destructuring() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec(
            "node",
            &[
                "-e".into(),
                "const {a, b} = {a: 1, b: 2}; console.log(a + b)".into(),
            ],
        )
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(stdout.contains("3"), "Expected '3' in stdout: {stdout}");
}

#[tokio::test]
async fn test_node_eval_template_literals() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec(
            "node",
            &[
                "-e".into(),
                "const name = 'World'; console.log(`Hello ${name}!`)".into(),
            ],
        )
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(
        stdout.contains("Hello World!"),
        "Expected 'Hello World!' in stdout: {stdout}"
    );
}

#[tokio::test]
async fn test_node_eval_map_reduce() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec(
            "node",
            &[
                "-p".into(),
                "[1,2,3,4,5].map(x => x * x).reduce((a, b) => a + b, 0)".into(),
            ],
        )
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), "55");
}

#[tokio::test]
async fn test_node_no_args_shows_usage() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox.exec("node", &[]).await.unwrap();
    assert_ne!(result.exit_code, 0);
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("Usage"),
        "Expected usage message in stderr: {stderr}"
    );
}

#[tokio::test]
async fn test_node_eval_promises_basic() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec(
            "node",
            &[
                "-e".into(),
                "Promise.resolve(42).then(v => console.log('resolved: ' + v))".into(),
            ],
        )
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    // Note: boa may or may not flush microtasks; check if output appears
    // This test validates that Promise constructor works without crashing
}

#[tokio::test]
async fn test_node_eval_math_functions() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec(
            "node",
            &["-p".into(), "Math.max(1, 5, 3) + Math.min(1, 5, 3)".into()],
        )
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), "6");
}

#[tokio::test]
async fn test_node_eval_regex() {
    let (_tmp, sandbox) = temp_sandbox();
    let result = sandbox
        .exec(
            "node",
            &["-p".into(), "'hello world 123'.match(/\\d+/)[0]".into()],
        )
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), "123");
}

#[tokio::test]
async fn test_node_security_no_host_filesystem() {
    let (_tmp, sandbox) = temp_sandbox();
    // Node inside WASM sandbox should not be able to read /etc/passwd
    // The WASM runtime only mounts /work
    let result = sandbox.exec("node", &["/etc/passwd".into()]).await.unwrap();
    assert_ne!(result.exit_code, 0);
}

// --- Fetch / Networking tests ---

fn temp_sandbox_with_fetch(policy: FetchPolicy) -> (tempfile::TempDir, Sandbox) {
    let tmp = tempfile::tempdir().unwrap();
    let config = SandboxConfig {
        work_dir: tmp.path().to_path_buf(),
        fetch_policy: Some(policy),
        ..Default::default()
    };
    let sandbox = Sandbox::new(config).unwrap();
    (tmp, sandbox)
}

#[tokio::test]
async fn test_fetch_disabled_without_policy() {
    let (_tmp, sandbox) = temp_sandbox();

    let request = FetchRequest {
        url: "https://example.com".into(),
        method: "GET".into(),
        headers: HashMap::new(),
        body: None,
    };

    let result = sandbox.fetch(request).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("networking disabled"),
        "Expected 'networking disabled', got: {err}"
    );
}

#[tokio::test]
async fn test_fetch_basic_get() {
    let (_tmp, sandbox) = temp_sandbox_with_fetch(FetchPolicy::default());

    let request = FetchRequest {
        url: "https://example.com".into(),
        method: "GET".into(),
        headers: HashMap::new(),
        body: None,
    };

    let result = sandbox.fetch(request).await.unwrap();
    assert_eq!(result.status, 200);
    let body = String::from_utf8_lossy(&result.body);
    assert!(
        body.contains("Example Domain"),
        "Expected 'Example Domain' in body"
    );
}

#[tokio::test]
async fn test_fetch_blocked_domain() {
    let policy = FetchPolicy {
        blocked_domains: vec![DomainPattern("example.com".into())],
        ..Default::default()
    };
    let (_tmp, sandbox) = temp_sandbox_with_fetch(policy);

    let request = FetchRequest {
        url: "https://example.com".into(),
        method: "GET".into(),
        headers: HashMap::new(),
        body: None,
    };

    let result = sandbox.fetch(request).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.to_lowercase().contains("block") || err.to_lowercase().contains("denied"),
        "Expected domain blocked error, got: {err}"
    );
}

#[tokio::test]
async fn test_fetch_ssrf_private_ip_blocked() {
    let policy = FetchPolicy {
        deny_private_ips: true,
        ..Default::default()
    };
    let (_tmp, sandbox) = temp_sandbox_with_fetch(policy);

    let request = FetchRequest {
        url: "http://127.0.0.1".into(),
        method: "GET".into(),
        headers: HashMap::new(),
        body: None,
    };

    let result = sandbox.fetch(request).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.to_lowercase().contains("private") || err.to_lowercase().contains("block"),
        "Expected private IP blocked error, got: {err}"
    );
}

#[tokio::test]
async fn test_fetch_allowed_domains_only() {
    let policy = FetchPolicy {
        allowed_domains: Some(vec![DomainPattern("example.com".into())]),
        ..Default::default()
    };
    let (_tmp, sandbox) = temp_sandbox_with_fetch(policy);

    // Allowed domain should work
    let request = FetchRequest {
        url: "https://example.com".into(),
        method: "GET".into(),
        headers: HashMap::new(),
        body: None,
    };
    let result = sandbox.fetch(request).await.unwrap();
    assert_eq!(result.status, 200);

    // Non-allowed domain should fail
    let request2 = FetchRequest {
        url: "https://httpbin.org/get".into(),
        method: "GET".into(),
        headers: HashMap::new(),
        body: None,
    };
    let result2 = sandbox.fetch(request2).await;
    assert!(result2.is_err());
}

#[tokio::test]
async fn test_exec_curl_basic() {
    let (_tmp, sandbox) = temp_sandbox_with_fetch(FetchPolicy::default());

    let result = sandbox
        .exec("curl", &["https://example.com".into()])
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let body = String::from_utf8_lossy(&result.stdout);
    assert!(
        body.contains("Example Domain"),
        "Expected 'Example Domain' in curl output"
    );
    let stderr = String::from_utf8_lossy(&result.stderr);
    assert!(
        stderr.contains("HTTP 200"),
        "Expected 'HTTP 200' in stderr, got: {stderr}"
    );
}

#[tokio::test]
async fn test_exec_curl_with_headers() {
    let (_tmp, sandbox) = temp_sandbox_with_fetch(FetchPolicy::default());

    let result = sandbox
        .exec(
            "curl",
            &[
                "-H".into(),
                "Accept: application/json".into(),
                "https://httpbin.org/headers".into(),
            ],
        )
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let body = String::from_utf8_lossy(&result.stdout);
    assert!(
        body.contains("Accept") || body.contains("accept"),
        "Expected headers in response body"
    );
}

#[tokio::test]
async fn test_exec_curl_disabled_without_policy() {
    let (_tmp, sandbox) = temp_sandbox();

    let result = sandbox.exec("curl", &["https://example.com".into()]).await;

    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("networking disabled"),
        "Expected 'networking disabled', got: {err}"
    );
}

#[tokio::test]
async fn test_exec_curl_output_file() {
    let (tmp, sandbox) = temp_sandbox_with_fetch(FetchPolicy::default());

    let result = sandbox
        .exec(
            "curl",
            &[
                "-o".into(),
                "output.html".into(),
                "https://example.com".into(),
            ],
        )
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);

    // Verify file was written
    let content = std::fs::read_to_string(tmp.path().join("output.html")).unwrap();
    assert!(
        content.contains("Example Domain"),
        "Expected 'Example Domain' in output file"
    );
}

#[tokio::test]
async fn test_exec_js_fetch() {
    let (_tmp, sandbox) = temp_sandbox_with_fetch(FetchPolicy::default());

    let result = sandbox
        .exec_js("var r = fetch('https://example.com'); console.log(r.status)")
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(stdout.contains("200"), "Expected '200' in stdout: {stdout}");
}

#[tokio::test]
async fn test_exec_js_fetch_with_options() {
    let (_tmp, sandbox) = temp_sandbox_with_fetch(FetchPolicy::default());

    let result = sandbox
        .exec_js(
            r#"var r = fetch('https://httpbin.org/post', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"key":"value"}' }); console.log(r.status)"#,
        )
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(stdout.contains("200"), "Expected '200' in stdout: {stdout}");
}

#[tokio::test]
async fn test_exec_js_fetch_response_body() {
    let (_tmp, sandbox) = temp_sandbox_with_fetch(FetchPolicy::default());

    let result = sandbox
        .exec_js("var r = fetch('https://example.com'); console.log(r.body.indexOf('Example Domain') >= 0)")
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(
        stdout.contains("true"),
        "Expected 'true' in stdout: {stdout}"
    );
}

#[tokio::test]
async fn test_exec_js_fetch_disabled() {
    let (_tmp, sandbox) = temp_sandbox();

    let result = sandbox
        .exec_js("try { fetch('https://example.com'); } catch(e) { console.log('error: ' + e.message); }")
        .await
        .unwrap();

    // Should either error or print error message
    let stdout = String::from_utf8_lossy(&result.stdout);
    let stderr = String::from_utf8_lossy(&result.stderr);
    let combined = format!("{stdout}{stderr}");
    assert!(
        combined.contains("disabled")
            || combined.contains("error")
            || combined.contains("networking")
            || result.exit_code != 0,
        "Expected fetch to fail when networking is disabled. stdout: {stdout}, stderr: {stderr}, exit: {}",
        result.exit_code
    );
}

#[tokio::test]
async fn test_exec_js_fetch_text_method() {
    let (_tmp, sandbox) = temp_sandbox_with_fetch(FetchPolicy::default());

    let result = sandbox
        .exec_js(
            "var r = fetch('https://example.com'); console.log(r.text().indexOf('Example') >= 0)",
        )
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(
        stdout.contains("true"),
        "Expected 'true' in stdout: {stdout}"
    );
}

#[tokio::test]
async fn test_exec_js_fetch_ok_property() {
    let (_tmp, sandbox) = temp_sandbox_with_fetch(FetchPolicy::default());

    let result = sandbox
        .exec_js("var r = fetch('https://example.com'); console.log(r.ok)")
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    let stdout = String::from_utf8_lossy(&result.stdout);
    assert!(
        stdout.contains("true"),
        "Expected 'true' in stdout: {stdout}"
    );
}