mxc-sdk 1.0.1

Importable library for starting MXC sandboxes in-process, with streaming stdio.
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
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! `BaseContainerRunner` — executes scripts through the Windows BaseContainer APIs.
//!
//! The runner uses the PSEC / `CreateProcessSecurityEnvironment` two-phase
//! contract and attaches the resulting environment to `CreateProcessW`.

use std::ffi::c_void;
use std::fmt::Write;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::ptr;
use std::sync::Arc;

use crate::learning_mode_core::{capture_diagnostics::CaptureAnalysis, AnalyzeError};
use crate::learning_mode_windows::{
    EtlDenialAnalyzer, LearningModeApi, LearningModeError, LearningModeTraceSources,
};
use windows::Win32::Foundation::{
    CloseHandle, GetLastError, SetHandleInformation, ERROR_CALL_NOT_IMPLEMENTED, E_NOTIMPL, HANDLE,
    HANDLE_FLAG_INHERIT, WAIT_OBJECT_0, WAIT_TIMEOUT,
};
use windows::Win32::System::Console::{
    GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
};
use windows::Win32::System::Threading::{
    CreateProcessW, GetExitCodeProcess, TerminateProcess, WaitForSingleObject,
    EXTENDED_STARTUPINFO_PRESENT, PROCESS_CREATION_FLAGS, PROCESS_INFORMATION,
    STARTF_USESTDHANDLES, STARTUPINFOW,
};
use windows_core::{PCWSTR, PWSTR};

use crate::mxc_common::api_set::is_api_set_implemented;
use crate::mxc_common::audit::{
    sanitize_identity, AuditEvent, AuditEventName, KillMethod, OperationStatus, TeardownSkipReason,
    TeardownStatus,
};
use crate::mxc_common::error::WxcError;
use crate::mxc_common::log_symbols::EMOJI_SECTION;
use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{
    CaptureDenialsErrorOutput, CaptureDenialsOutput, ContainmentBackend, ExecutionRequest,
    FailurePhase, SandboxOutputMetadata, ScriptResponse,
};
use crate::mxc_common::process_util::{
    create_std_pipes, InterruptiblePipeReader, OwnedHandle, PipeReadCanceller, PipeWriter,
    SendOwnedHandle,
};
use crate::mxc_common::sandbox_process::{
    boxed_closer, cancel_and_join_discard, duplicate_and_take_native_stdio, spawn_discard,
    take_boxed_read, take_boxed_write, NativeStdio, SandboxBackend, SandboxProcess, StdioMode,
    StreamCloser,
};
use crate::mxc_common::script_runner::get_timeout_milliseconds;
use crate::mxc_common::string_util;
use crate::mxc_common::validator::{validate_network_policy_support, NetworkPolicySupport};
use crate::process_container_common::base_container_helpers::{
    build_psec_v1_security_environment_spec, has_conflicting_proxy_identity,
};
use crate::process_container_common::capture_output::{
    combine_capture_and_cleanup_results, combine_process_and_teardown_results,
    remove_internal_capture_file, unique_denials_output_paths, write_capture_denials_document,
    write_stderr_line_best_effort,
};
use crate::process_container_common::job_object::UiJobObject;
use crate::process_container_common::launch_diagnostics::{
    diagnose_create_process_failure, diagnose_missing_required_env, diagnose_process_exit,
    validate_required_child_env,
};
use crate::process_container_common::native_capture::CaptureSession;
use crate::process_container_common::proxy_coordinator::ProxyCoordinator;
use crate::process_container_common::secenv::{
    self, ProcessSecurityEnvironment, SecurityEnvironmentStartupInfo, SecurityEnvironmentSupport,
    SecurityEnvironmentVersion, PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE,
    SECURITY_ENVIRONMENT_API_SET,
};

use windows::Win32::System::Threading::{
    ResumeThread, CREATE_NO_WINDOW, CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT,
};

trait CaptureDenialAnalyzer {
    fn analyze_capture(&self, source_path: &Path) -> Result<CaptureAnalysis, AnalyzeError>;
}

impl CaptureDenialAnalyzer for EtlDenialAnalyzer {
    fn analyze_capture(&self, source_path: &Path) -> Result<CaptureAnalysis, AnalyzeError> {
        EtlDenialAnalyzer::analyze_capture(self, source_path)
    }
}

/// Build the environment block handed to the contained child.
///
/// Honors the three states of [`ExecutionRequest::env`]:
///
/// * `None` — no environment supplied. The child gets a clean default user
///   profile block (never the `wxc-exec` process's own variables).
/// * `Some(entries)` — the caller's environment, used **verbatim**. MXC adds
///   nothing to it, including when `entries` is empty: an explicitly empty
///   environment produces an empty block, not the default one. Proxy variables
///   are still injected, because the proxy is enforced policy rather than
///   inherited environment.
///
/// When `inherit_default_env` is set, `entries` is layered on top of the
/// default block instead of replacing it, which is the supported way to ask for
/// "the user's profile block plus these".
fn build_child_env_block(request: &ExecutionRequest) -> Result<Option<Vec<u16>>, WxcError> {
    let proxy_address = if request.policy.runtime_network_proxy_specified {
        request.policy.network_proxy.address.as_ref()
    } else {
        None
    };

    let entries = match request.env.as_deref() {
        None => {
            let mut entries =
                crate::process_container_common::appcontainer_runner::create_default_env_entries()?;
            if let Some(address) = proxy_address {
                crate::process_container_common::appcontainer_runner::inject_proxy_vars(
                    &mut entries,
                    address,
                );
            }
            entries
        }
        Some(supplied) if request.inherit_default_env => {
            crate::process_container_common::appcontainer_runner::build_inherited_entries(
                supplied,
                proxy_address,
            )?
        }
        Some(supplied) => {
            crate::process_container_common::appcontainer_runner::build_explicit_entries(
                supplied,
                proxy_address,
            )
        }
    };
    Ok(Some(
        crate::process_container_common::appcontainer_runner::encode_env_block(&entries),
    ))
}

const CAPTURE_API_AVAILABLE_LOG: &str =
    "captureDenials: learning-mode trace API available (processmodel.dll)";
const PSEC_ENUMERATE_PATHS_UNSUPPORTED_MSG: &str =
    "processContainer.filesystem.enumeratePaths requires Process Security Environment contract version 1.1 \
     and QueryProcessSecurityEnvironmentSupport to advertise PSE_SUPPORT_FS_ENUMERATE; this OS \
     build does not support that policy, and enumeration-only access cannot fall back to \
     AppContainer enforcement";
const CREATE_PROCESS_IN_SECURITY_ENVIRONMENT_API: &str =
    "CreateProcessW(PROC_THREAD_ATTRIBUTE_SECURITY_ENVIRONMENT)";

fn log_base_network_policy_audit(
    request: &ExecutionRequest,
    identity: &str,
    status: OperationStatus,
    logger: &mut Logger,
) {
    if logger.has_diagnostic_sink() {
        let record =
            crate::process_container_common::network_policy_helpers::network_policy_applied_record(
                &request.policy,
                sanitize_identity(identity),
                crate::process_container_common::fallback_detector::IsolationTier::BaseContainer
                    .as_str(),
                request.policy.network_proxy.address.as_ref(),
                status,
            );
        logger.log_audit_event(&record);
    }
}

#[derive(Debug)]
struct CaptureCleanupError {
    output: CaptureDenialsOutput,
    cleanup_message: String,
}

impl std::fmt::Display for CaptureCleanupError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.cleanup_message)
    }
}

impl std::error::Error for CaptureCleanupError {}

/// True when a Win32 error code signals the BaseContainer feature is not
/// enabled on this build (symbol present, capability gated off).
fn is_api_not_implemented(err: u32) -> bool {
    err == ERROR_CALL_NOT_IMPLEMENTED.0 || err == E_NOTIMPL.0 as u32
}

trait CaptureSessionOps {
    fn environment(&self) -> HANDLE;
    fn finish(
        self: Box<Self>,
        output_path: Option<&std::path::Path>,
    ) -> Result<(), crate::learning_mode_windows::LearningModeError>;
}

impl CaptureSessionOps for CaptureSession {
    fn environment(&self) -> HANDLE {
        self.environment()
    }

    fn finish(
        self: Box<Self>,
        output_path: Option<&std::path::Path>,
    ) -> Result<(), crate::learning_mode_windows::LearningModeError> {
        (*self).finish(output_path)
    }
}

trait CaptureSessionFactory: Send + Sync {
    fn trace_sources(
        &self,
    ) -> Result<LearningModeTraceSources, crate::learning_mode_windows::LearningModeError>;

    fn begin(
        &self,
        sandbox_specification: &[u8],
        flags: u32,
    ) -> Result<Box<dyn CaptureSessionOps>, crate::learning_mode_windows::LearningModeError>;
}

struct RealCaptureSessionFactory;

impl CaptureSessionFactory for RealCaptureSessionFactory {
    fn trace_sources(
        &self,
    ) -> Result<LearningModeTraceSources, crate::learning_mode_windows::LearningModeError> {
        LearningModeApi::load().map(|api| api.trace_sources())
    }

    fn begin(
        &self,
        sandbox_specification: &[u8],
        flags: u32,
    ) -> Result<Box<dyn CaptureSessionOps>, crate::learning_mode_windows::LearningModeError> {
        CaptureSession::begin(sandbox_specification, flags)
            .map(|session| Box::new(session) as Box<dyn CaptureSessionOps>)
    }
}

/// Request-level BaseContainer eligibility. This is the authoritative decision
/// consumed by tier selection; callers must not reconstruct eligibility from
/// individual host capability probes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BaseContainerRequestDecision {
    Serviceable,
    Unavailable,
    PolicyIncompatible,
    DeniedPathsUnsupported,
    EnumeratePathsUnsupported,
    NativeCaptureUnavailable,
}

impl BaseContainerRequestDecision {
    pub(crate) fn can_service_request(self) -> bool {
        self == Self::Serviceable
    }
}

/// Script runner that launches through a process security environment.
pub struct BaseContainerRunner {
    proxy_coordinator: ProxyCoordinator,
    capture_factory: Arc<dyn CaptureSessionFactory>,
    request_serviceability_confirmed: bool,
}

impl Default for BaseContainerRunner {
    fn default() -> Self {
        Self {
            proxy_coordinator: ProxyCoordinator::default(),
            capture_factory: Arc::new(RealCaptureSessionFactory),
            request_serviceability_confirmed: false,
        }
    }
}

impl BaseContainerRunner {
    pub fn new() -> Self {
        Self::default()
    }

    /// Construct the runner after [`Self::can_backend_service_request`] returned
    /// [`BaseContainerRequestDecision::Serviceable`] for the request that will
    /// be executed. The dispatcher owns that invariant and uses this constructor
    /// so validation does not repeat the OS capability decision.
    pub(crate) fn new_for_selected_request() -> Self {
        Self {
            request_serviceability_confirmed: true,
            ..Self::default()
        }
    }

    #[cfg(test)]
    fn with_capture_factory(capture_factory: Arc<dyn CaptureSessionFactory>) -> Self {
        Self {
            proxy_coordinator: ProxyCoordinator::default(),
            capture_factory,
            request_serviceability_confirmed: true,
        }
    }

    fn build_capture_aware_security_environment_spec(
        &self,
        request: &ExecutionRequest,
        version: SecurityEnvironmentVersion,
    ) -> Result<Vec<u8>, ScriptResponse> {
        let capture_network_decisions = match request.policy.capture_denials.as_ref() {
            Some(_) => self
                .capture_factory
                .trace_sources()
                .map_err(|error| {
                    ScriptResponse::error(&format!(
                        "captureDenials: failed to inspect learning-mode trace sources: {error}"
                    ))
                })?
                .includes_network(),
            None => false,
        };
        Ok(build_psec_v1_security_environment_spec(
            request,
            version,
            capture_network_decisions,
        ))
    }

    fn cleanup_capture_begin_failure(&mut self, logger: &mut Logger) {
        // CaptureSession owns and closes the PSEC environment. No legacy
        // identity/tracking state is created for this path.
        self.proxy_coordinator.stop(logger);
    }

    /// Whether the process security-environment API set is present.
    pub fn is_base_container_api_present() -> bool {
        #[cfg(test)]
        if let Ok(forced) = std::env::var("MXC_FORCE_BC_USABLE") {
            return forced == "1";
        }

        static PRESENT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
        *PRESENT.get_or_init(|| is_api_set_implemented(SECURITY_ENVIRONMENT_API_SET))
    }

    /// Whether native capture has both PSEC and a complete Learning Mode ABI.
    pub fn is_native_capture_available() -> bool {
        #[cfg(test)]
        if let Ok(forced) = std::env::var("MXC_FORCE_NATIVE_CAPTURE_USABLE") {
            return forced == "1";
        }

        Self::native_capture_available_with(Self::is_base_container_api_present(), || {
            LearningModeApi::load().is_ok()
        })
    }

    fn native_capture_available_with(
        base_container_available: bool,
        learning_mode_abi_available: impl FnOnce() -> bool,
    ) -> bool {
        base_container_available && learning_mode_abi_available()
    }

    /// Whether PSEC can enforce `filesystem.deniedPaths`.
    pub fn supports_native_denied_paths() -> bool {
        #[cfg(test)]
        if let Ok(forced) = std::env::var("MXC_FORCE_DENY_PATHS") {
            return forced == "1";
        }

        Self::is_base_container_api_present()
            && secenv::query_support(SecurityEnvironmentSupport::FileSystemDeny)
    }

    /// Whether PSEC can enforce `processContainer.filesystem.enumeratePaths`.
    pub fn supports_enumerate_paths() -> bool {
        Self::is_base_container_api_present()
            && secenv::query_support(SecurityEnvironmentSupport::FileSystemEnumerate)
    }

    /// Whether BaseContainer supports native bidirectional host-loopback ingress.
    pub fn supports_ingress_host_loopback_allow() -> bool {
        Self::is_base_container_api_present()
            && secenv::query_support(SecurityEnvironmentSupport::NetworkIngress)
    }

    /// Whether this host supports an identity-less proxy on loopback.
    /// This is not general host-loopback ingress support.
    pub(crate) fn supports_identityless_loopback_proxy() -> Result<bool, LearningModeError> {
        if !Self::is_base_container_api_present() {
            return Ok(false);
        }
        secenv::supports_version(SecurityEnvironmentVersion::V1_0)
    }

    /// The single PSEC version-selection point: start at 1.0 and raise it to
    /// the highest version required by any requested native feature.
    fn choose_min_required_psec_version_for_request(
        request: &ExecutionRequest,
    ) -> SecurityEnvironmentVersion {
        let mut version = SecurityEnvironmentVersion::V1_0;
        if !request.policy.denied_paths.is_empty() {
            version = version.max(SecurityEnvironmentSupport::FileSystemDeny.required_version());
        }
        if !request.policy.enumerate_paths.is_empty() {
            version =
                version.max(SecurityEnvironmentSupport::FileSystemEnumerate.required_version());
        }

        version
    }

    /// The single BaseContainer serviceability decision point: return the first
    /// reason the request cannot be enforced, or
    /// [`BaseContainerRequestDecision::Serviceable`] when every check passes.
    pub(crate) fn can_backend_service_request(
        request: &ExecutionRequest,
    ) -> BaseContainerRequestDecision {
        if !Self::is_base_container_api_present() {
            return BaseContainerRequestDecision::Unavailable;
        }
        if request.policy.least_privilege_mode
            || (request.policy.network_proxy.is_enabled()
                && !request.policy.runtime_network_proxy_specified)
        {
            return BaseContainerRequestDecision::PolicyIncompatible;
        }
        let capture_denials = request.policy.capture_denials.is_some();
        #[cfg(test)]
        let native_capture_available = if capture_denials {
            std::env::var("MXC_FORCE_NATIVE_CAPTURE_USABLE").map_or_else(
                |_| Self::is_native_capture_available(),
                |forced| forced == "1",
            )
        } else {
            true
        };
        #[cfg(not(test))]
        let native_capture_available = !capture_denials || Self::is_native_capture_available();
        if !native_capture_available {
            return BaseContainerRequestDecision::NativeCaptureUnavailable;
        }
        if !request.policy.enumerate_paths.is_empty() && !Self::supports_enumerate_paths() {
            return BaseContainerRequestDecision::EnumeratePathsUnsupported;
        }
        if !request.policy.denied_paths.is_empty() && !Self::supports_native_denied_paths() {
            return BaseContainerRequestDecision::DeniedPathsUnsupported;
        }

        BaseContainerRequestDecision::Serviceable
    }
}

impl BaseContainerRunner {
    /// Set up and launch the BaseContainer child, returning a [`BaseChild`] the
    /// caller runs to completion (blocking) or wraps in a streaming handle. When
    /// `capture` is set the child's stdio is wired to pipes the caller drives
    /// (the streaming path); otherwise the child inherits the parent's std
    /// handles / console (the run-to-completion path).
    fn spawn_base(
        &mut self,
        request: &ExecutionRequest,
        logger: &mut Logger,
        capture: bool,
    ) -> Result<BaseChild, ScriptResponse> {
        let _ = writeln!(
            logger,
            "{EMOJI_SECTION} SECTION: Backend runner 'BaseContainer'"
        );

        // --- Learning-mode capabilities (parity with AppContainerScriptRunner) ---
        // Emit per-capability diagnostics (informational for `learningModeLogging`,
        // a security warning for `permissiveLearningMode`).
        crate::process_container_common::appcontainer_runner::log_learning_mode_capability_diagnostics(
            &request.policy.capabilities,
            logger,
        );

        let psec_version = Self::choose_min_required_psec_version_for_request(request);
        let version_supported =
            secenv::supports_version(psec_version).map_err(|error| ScriptResponse {
                failure_phase: FailurePhase::BackendUnavailable,
                ..ScriptResponse::error(&format!(
                    "failed to query Process Security Environment contract support: {error}"
                ))
            })?;
        if !version_supported {
            return Err(ScriptResponse::rejected(
                if !request.policy.enumerate_paths.is_empty() {
                    PSEC_ENUMERATE_PATHS_UNSUPPORTED_MSG
                } else {
                    "the required Process Security Environment schema version is not supported"
                },
            ));
        }

        if let Some(addr) = request.policy.network_proxy.address.as_ref() {
            let _ = writeln!(logger, "effective proxy: {}", addr.to_url());
            let _ = writeln!(
                logger,
                "warning: proxy support on Windows is best-effort -- only scripts that use \
                 the WinHTTP stack will be proxied; other HTTP stacks may bypass it.",
            );
        }
        let _ = writeln!(logger, "{EMOJI_SECTION} SECTION: Build sandbox spec");
        let capture_denials = request.policy.capture_denials.clone();
        if capture_denials.is_some() {
            let _ = writeln!(logger, "{EMOJI_SECTION} SECTION: captureDenials");
        }

        let process_security_environment_spec =
            self.build_capture_aware_security_environment_spec(request, psec_version)?;
        let _ = writeln!(
            logger,
            "process security environment spec built (PSEC {}.{}, {} bytes)",
            psec_version.major,
            psec_version.minor,
            process_security_environment_spec.len()
        );

        // Resolve two paths for the capture:
        //   * `capture_etl_path` — a runner-managed `.etl` in a protected
        //     per-run directory for native V2 capture. Guarded WPR analyzes
        //     its ETL while elevated and returns only a bounded process-scoped
        //     result.
        //   * `capture_output_path` — the JSON denials deliverable that consuming
        //     apps read: caller-specified via `captureDenials.outputPath` when
        //     provided, else a managed per-run temp `.json` file.
        let mut managed_capture = capture_denials
            .as_ref()
            .map(|config| managed_capture_output_path(config.retain_etl))
            .transpose()?;
        let capture_output_paths = capture_denials
            .as_ref()
            .map(|config| unique_denials_output_paths(config.output_path.as_deref(), false))
            .transpose()
            .map_err(|error| ScriptResponse::error(&error))?;
        let capture_output_path = match capture_output_paths {
            Some(paths) => Some(paths.denials),
            None => None,
        };

        let _ = writeln!(logger, "{EMOJI_SECTION} SECTION: Load API");

        let _ = writeln!(logger, "{EMOJI_SECTION} SECTION: Launch process");

        // 3. Build the command line (passed directly, same as AppContainerScriptRunner).
        let mut cmd_wide = string_util::to_wide(&request.script_code);

        // Resolved via the shared helper so both Windows launch paths agree and
        // neither can pass a NULL cwd (see `working_directory`).
        let working_directory =
            crate::process_container_common::working_directory::launch_working_directory(request);
        let _ = writeln!(
            logger,
            "working directory: {}",
            working_directory.describe()
        );
        let cwd_wide = string_util::to_wide(&working_directory.path);
        let cwd_ptr = cwd_wide.as_ptr();

        let identity = "<process-security-environment>".to_string();

        // --- Determine STDIO mode ---
        // If wxc-exec's stdout or stderr is not a terminal (i.e., piped by the SDK),
        // we forward our own std handles to the child via STARTF_USESTDHANDLES so the
        // child's output streams directly to the SDK in real time.
        //
        // In capture mode (`StdioMode::Pipes`) we always take the pipe
        // path and wire the child to capture pipes that the streaming handle
        // reads from.
        let pipe_mode =
            capture || !std::io::stdout().is_terminal() || !std::io::stderr().is_terminal();

        if pipe_mode {
            if capture {
                let _ = writeln!(
                    logger,
                    "STDIO mode: capture (piping child output to the streaming handle)"
                );
            } else {
                let _ = writeln!(
                    logger,
                    "STDIO mode: passthrough (forwarding parent handles to child)"
                );
            }
        }

        // --- Retrieve / create std handles (pipe mode only) ---
        let mut h_stdin = HANDLE::default();
        let mut h_stdout = HANDLE::default();
        let mut h_stderr = HANDLE::default();

        // Capture pipe read-ends (parent side) kept alive until after the wait;
        // child-side ends kept alive until after process creation.
        let mut capture_reads: Option<(OwnedHandle, OwnedHandle)> = None;
        let mut capture_child_ends: Vec<OwnedHandle> = Vec::new();
        // Parent's stdin write-end; in capture mode it is handed to the caller
        // so they can write to the child.
        let mut captured_stdin_write: Option<OwnedHandle> = None;

        if pipe_mode {
            if capture {
                let (stdin_read, stdin_write) = match create_std_pipes(false) {
                    Ok(p) => p,
                    Err(e) => return Err(ScriptResponse::error(&format!("stdin pipe: {e}"))),
                };
                let (stdout_read, stdout_write) = match create_std_pipes(true) {
                    Ok(p) => p,
                    Err(e) => return Err(ScriptResponse::error(&format!("stdout pipe: {e}"))),
                };
                let (stderr_read, stderr_write) = match create_std_pipes(true) {
                    Ok(p) => p,
                    Err(e) => return Err(ScriptResponse::error(&format!("stderr pipe: {e}"))),
                };

                h_stdin = stdin_read.get();
                h_stdout = stdout_write.get();
                h_stderr = stderr_write.get();

                capture_child_ends.push(stdin_read);
                capture_child_ends.push(stdout_write);
                capture_child_ends.push(stderr_write);
                captured_stdin_write = Some(stdin_write);
                capture_reads = Some((stdout_read, stderr_read));
            } else {
                h_stdin = match unsafe { GetStdHandle(STD_INPUT_HANDLE) } {
                    Ok(h) => h,
                    Err(e) => {
                        return Err(ScriptResponse::error(&format!("GetStdHandle(STDIN): {e}")))
                    }
                };
                h_stdout = match unsafe { GetStdHandle(STD_OUTPUT_HANDLE) } {
                    Ok(h) => h,
                    Err(e) => {
                        return Err(ScriptResponse::error(&format!("GetStdHandle(STDOUT): {e}")))
                    }
                };
                h_stderr = match unsafe { GetStdHandle(STD_ERROR_HANDLE) } {
                    Ok(h) => h,
                    Err(e) => {
                        return Err(ScriptResponse::error(&format!("GetStdHandle(STDERR): {e}")))
                    }
                };

                if h_stdin.is_invalid() || h_stdin == HANDLE::default() {
                    return Err(ScriptResponse::error(
                        "GetStdHandle(STDIN) returned null/invalid handle",
                    ));
                }
                if h_stdout.is_invalid() || h_stdout == HANDLE::default() {
                    return Err(ScriptResponse::error(
                        "GetStdHandle(STDOUT) returned null/invalid handle",
                    ));
                }
                if h_stderr.is_invalid() || h_stderr == HANDLE::default() {
                    return Err(ScriptResponse::error(
                        "GetStdHandle(STDERR) returned null/invalid handle",
                    ));
                }

                // Ensure the handles are inheritable.
                unsafe {
                    if let Err(e) =
                        SetHandleInformation(h_stdin, HANDLE_FLAG_INHERIT.0, HANDLE_FLAG_INHERIT)
                    {
                        return Err(ScriptResponse::error(&format!(
                            "SetHandleInformation(STDIN): {e}"
                        )));
                    }
                    if let Err(e) =
                        SetHandleInformation(h_stdout, HANDLE_FLAG_INHERIT.0, HANDLE_FLAG_INHERIT)
                    {
                        return Err(ScriptResponse::error(&format!(
                            "SetHandleInformation(STDOUT): {e}"
                        )));
                    }
                    if let Err(e) =
                        SetHandleInformation(h_stderr, HANDLE_FLAG_INHERIT.0, HANDLE_FLAG_INHERIT)
                    {
                        return Err(ScriptResponse::error(&format!(
                            "SetHandleInformation(STDERR): {e}"
                        )));
                    }
                }
            }
        }

        // STARTUPINFOW -- in pipe mode, pass parent handles via STARTF_USESTDHANDLES
        // so child output streams directly to the SDK caller.
        let si = STARTUPINFOW {
            cb: std::mem::size_of::<STARTUPINFOW>() as u32,
            dwFlags: if pipe_mode {
                STARTF_USESTDHANDLES
            } else {
                Default::default()
            },
            hStdInput: h_stdin,
            hStdOutput: h_stdout,
            hStdError: h_stderr,
            ..unsafe { std::mem::zeroed() }
        };
        #[allow(unused_assignments)]
        let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };

        // Environment block for the sandboxed child.
        // Explicit variables are always isolated from the parent environment.
        // CreateProcessW must receive an explicit clean block or it would
        // inherit all wxc-exec process variables.
        let env_block = build_child_env_block(request).map_err(|error| {
            ScriptResponse::error(&format!(
                "failed to create a clean child environment: {error}"
            ))
        })?;

        let env_ptr = env_block
            .as_ref()
            .map(|b| b.as_ptr() as *const c_void)
            .unwrap_or(ptr::null());
        // Suppress the empty console window for console-subsystem children when
        // stdio is piped (no console is shared). In console-sharing mode (ConPTY)
        // the child inherits the parent's live console for interactive I/O, so
        // CREATE_NO_WINDOW must not be set there.
        let no_window_flag = if pipe_mode { CREATE_NO_WINDOW.0 } else { 0 };
        // Create the child suspended so its main thread cannot spawn any
        // descendant before we've assigned it to the job object below.
        let creation_flags = CREATE_SUSPENDED.0
            | no_window_flag
            | if env_block.is_some() {
                CREATE_UNICODE_ENVIRONMENT.0
            } else {
                0
            };

        let _ = writeln!(logger, "launching: {}", request.script_code);
        let _ = writeln!(logger, "identity: {identity}");

        let current_env_ptr = env_ptr;
        let current_creation_flags = creation_flags;

        let mut capture_session: Option<Box<dyn CaptureSessionOps>> = None;
        let mut security_environment: Option<ProcessSecurityEnvironment> = None;
        {
            let psec_spec = process_security_environment_spec.as_slice();
            if capture_denials.is_some() {
                match self
                    .capture_factory
                    .begin(psec_spec, PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE)
                {
                    Ok(session) => {
                        let _ = writeln!(
                            logger,
                            "{CAPTURE_API_AVAILABLE_LOG}; security environment and trace started"
                        );
                        capture_session = Some(session);
                    }
                    Err(e) => {
                        let msg =
                            format!("captureDenials: failed to start learning-mode capture: {e}");
                        let _ = writeln!(logger, "Error: {msg}");
                        log_base_network_policy_audit(
                            request,
                            &identity,
                            OperationStatus::Failure,
                            logger,
                        );
                        let failure_phase = if e.is_api_unavailable() {
                            FailurePhase::BackendUnavailable
                        } else {
                            FailurePhase::LaunchFailed
                        };
                        self.cleanup_capture_begin_failure(logger);
                        return Err(ScriptResponse {
                            exit_code: -1,
                            error_message: msg.clone(),
                            standard_err: msg,
                            failure_phase,
                            ..Default::default()
                        });
                    }
                }
            } else {
                let result = secenv::create(psec_spec, PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE);
                match result {
                    Ok(environment) => {
                        let _ = writeln!(
                            logger,
                            "process security environment created (processmodel.dll)"
                        );
                        security_environment = Some(environment);
                    }
                    Err(error) => {
                        let msg =
                            format!("failed to create the process security environment: {error}");
                        let _ = writeln!(logger, "Error: {msg}");
                        log_base_network_policy_audit(
                            request,
                            &identity,
                            OperationStatus::Failure,
                            logger,
                        );
                        let failure_phase = if error.is_api_unavailable() {
                            FailurePhase::BackendUnavailable
                        } else {
                            FailurePhase::LaunchFailed
                        };
                        return Err(ScriptResponse {
                            exit_code: -1,
                            error_message: msg.clone(),
                            standard_err: msg,
                            failure_phase,
                            ..Default::default()
                        });
                    }
                }
            }
        }

        pi = unsafe { std::mem::zeroed() };
        let inherited_handles = if pipe_mode {
            vec![h_stdin, h_stdout, h_stderr]
        } else {
            Vec::new()
        };
        let environment_handle = capture_session
            .as_ref()
            .map(|session| session.environment())
            .or_else(|| {
                security_environment
                    .as_ref()
                    .map(ProcessSecurityEnvironment::raw)
            })
            .expect("PSEC environment owner is initialized before launch");
        let extended_startup =
            match SecurityEnvironmentStartupInfo::new(si, environment_handle, &inherited_handles) {
                Ok(startup) => startup,
                Err(primary) => {
                    let cleanup_error = capture_session
                        .take()
                        .map(|session| session.finish(None))
                        .unwrap_or(Ok(()))
                        .err();
                    let mut msg =
                        format!("failed to attach the process security environment: {primary}");
                    if let Some(cleanup_error) = &cleanup_error {
                        let _ = write!(
                        msg,
                        "; additionally failed to discard the learning-mode trace: {cleanup_error}"
                    );
                    }
                    let _ = writeln!(logger, "Error: {msg}");
                    log_base_network_policy_audit(
                        request,
                        &identity,
                        OperationStatus::Failure,
                        logger,
                    );
                    let failure_phase = if primary.is_api_unavailable()
                        || cleanup_error.as_ref().is_some_and(
                            crate::learning_mode_windows::LearningModeError::is_api_unavailable,
                        ) {
                        FailurePhase::BackendUnavailable
                    } else {
                        FailurePhase::LaunchFailed
                    };
                    if capture_denials.is_some() {
                        self.cleanup_capture_begin_failure(logger);
                    }
                    return Err(ScriptResponse {
                        exit_code: -1,
                        error_message: msg.clone(),
                        standard_err: msg,
                        failure_phase,
                        ..Default::default()
                    });
                }
            };
        let environment = (!current_env_ptr.is_null()).then_some(current_env_ptr);
        let result = unsafe {
            CreateProcessW(
                PCWSTR::null(),
                Some(PWSTR(cmd_wide.as_mut_ptr())),
                None,
                None,
                !inherited_handles.is_empty(),
                PROCESS_CREATION_FLAGS(current_creation_flags | EXTENDED_STARTUPINFO_PRESENT.0),
                environment,
                PCWSTR(cwd_ptr),
                &extended_startup.startup_info().StartupInfo,
                &mut pi,
            )
        };
        let (success, last_error) = if result.is_ok() {
            (1, None)
        } else {
            (0, Some(unsafe { GetLastError() }))
        };

        if success == 0 {
            let err = last_error.unwrap_or_else(|| unsafe { GetLastError() });
            // Clean up any partially-populated handles from the failed API call.
            unsafe {
                if !pi.hProcess.is_invalid() {
                    let _ = CloseHandle(pi.hProcess);
                }
                if !pi.hThread.is_invalid() {
                    let _ = CloseHandle(pi.hThread);
                }
            }
            let capture_cleanup_error = capture_session
                .take()
                .and_then(|session| session.finish(None).err());
            if capture_denials.is_some() {
                self.cleanup_capture_begin_failure(logger);
            }

            //
            // Diagnose the launch failure (FailurePhase::LaunchFailed).
            //
            let diagnostic_env = if request.inherit_default_env {
                None
            } else {
                request.env.as_deref()
            };
            let diag = diagnose_missing_required_env(err.0, diagnostic_env).unwrap_or_else(|| {
                diagnose_create_process_failure(
                    err.0,
                    &request.script_code,
                    &request.policy.readonly_paths,
                )
            });

            let mut extended_error = format!(
                "{CREATE_PROCESS_IN_SECURITY_ENVIRONMENT_API} failed: {err:?} (working directory: {})",
                working_directory.describe()
            );
            if let Some(cleanup_error) = capture_cleanup_error {
                let _ = write!(
                    extended_error,
                    "; capture teardown also failed: {cleanup_error}"
                );
            }
            let _ = writeln!(logger, "Error: {extended_error}");

            let _ = writeln!(
                logger,
                "Error: Launch diagnostic [{}]: {}",
                diag.kind, diag.message
            );

            // Classify a disabled-feature error as BackendUnavailable; any
            // other launch error stays LaunchFailed.
            let failure_phase = if is_api_not_implemented(err.0) {
                FailurePhase::BackendUnavailable
            } else {
                FailurePhase::LaunchFailed
            };

            return Err(ScriptResponse {
                exit_code: -1,
                error_message: diag.message.clone(),
                standard_err: diag.message,
                extended_error,
                failure_phase,
                ..Default::default()
            });
        }

        let _ = writeln!(logger, "process created (PID: {})", pi.dwProcessId);

        // Child has inherited the pipe handles; close the parent's child-side
        // ends so the read-ends observe EOF when the child exits.
        capture_child_ends.clear();

        let (stdout_read, stderr_read) = match capture_reads {
            Some((out, err)) => (Some(out), Some(err)),
            None => (None, None),
        };

        // Assign the child to a job object so the streaming handle's `kill()`
        // (and the timeout / `Drop` paths) can tree-kill it — the child plus
        // every descendant it spawns after assignment. This backend *is* a
        // security boundary, so fail **closed**: if the job cannot be created
        // or the process cannot be assigned, terminate the just-launched child
        // and reject the spawn rather than run a sandbox that cannot be
        // reliably torn down. (Previously this was best-effort: a failed
        // assignment left `job = None`, after which `kill()`/timeout/`Drop`
        // could only `TerminateProcess` the root and no descendant was
        // tree-killed at all.)
        //
        // The child was created suspended (CREATE_SUSPENDED) and is resumed only
        // after this assignment, so no descendant it spawns can escape the job.
        let job = match UiJobObject::new().and_then(|job| {
            // Pass the raw handle — `assign_process` borrows it and does not
            // take ownership. Wrapping it in a temporary `OwnedHandle` here
            // would close `pi.hProcess` when the temporary dropped, leaving the
            // owned handle on the `BaseChild` below pointing at a closed (and
            // possibly reused) handle. Sole ownership stays with that field.
            job.assign_process(pi.hProcess)?;
            Ok(job)
        }) {
            Ok(job) => job,
            Err(e) => {
                let _ = writeln!(
                    logger,
                    "Error: BaseContainer job-object setup failed ({e}); terminating \
                     the child and failing closed — a sandbox that cannot be \
                     tree-killed must not run."
                );
                // The child is already running and there is no job to tree-kill
                // through, so terminate the root directly and reap it before
                // tearing down sandbox / proxy state, upholding the same
                // "enforcement never outlives a live child" invariant as the
                // normal teardown paths.
                unsafe {
                    let _ = TerminateProcess(pi.hProcess, u32::MAX);
                    let _ = WaitForSingleObject(pi.hProcess, u32::MAX);
                    let _ = CloseHandle(pi.hProcess);
                    let _ = CloseHandle(pi.hThread);
                }
                let capture_cleanup_error = capture_session
                    .take()
                    .and_then(|session| session.finish(None).err());
                if capture_denials.is_some() {
                    self.cleanup_capture_begin_failure(logger);
                }
                self.proxy_coordinator.stop(logger);

                const JOB_SETUP_FAILED_MSG: &str =
                    "BaseContainer sandbox could not be placed in a job object, so it \
                     could not be reliably terminated; the launch was rejected to \
                     avoid running an uncontainable sandbox.";
                let mut extended_error = format!("BaseContainer job-object setup failed: {e}");
                if let Some(cleanup_error) = capture_cleanup_error {
                    let _ = write!(
                        extended_error,
                        "; capture teardown also failed: {cleanup_error}"
                    );
                }
                return Err(ScriptResponse {
                    exit_code: -1,
                    error_message: JOB_SETUP_FAILED_MSG.to_string(),
                    standard_err: JOB_SETUP_FAILED_MSG.to_string(),
                    extended_error,
                    failure_phase: FailurePhase::LaunchFailed,
                    ..Default::default()
                });
            }
        };

        // The child was created suspended; now that it is in the job object (so
        // every descendant it spawns is captured), resume its main thread.
        // SAFETY: `pi.hThread` is the just-created, still-owned main-thread
        // handle; `ResumeThread` only adjusts its suspend count.
        let previous_suspend_count = unsafe { ResumeThread(pi.hThread) };
        if previous_suspend_count == u32::MAX {
            let mut message = format!(
                "ResumeThread failed for the BaseContainer child: {:?}",
                unsafe { GetLastError() }
            );
            if let Err(error) = job.terminate_and_wait(u32::MAX) {
                let _ = write!(
                    message,
                    "; additionally failed to terminate the sandbox process tree: {error}"
                );
            }
            unsafe {
                let _ = CloseHandle(pi.hProcess);
                let _ = CloseHandle(pi.hThread);
            }
            if let Some(error) = capture_session
                .take()
                .and_then(|session| session.finish(None).err())
            {
                let _ = write!(
                    message,
                    "; additionally failed to discard the learning-mode trace: {error}"
                );
            }
            self.proxy_coordinator.stop(logger);
            return Err(ScriptResponse {
                failure_phase: FailurePhase::LaunchFailed,
                ..ScriptResponse::error(&message)
            });
        }

        crate::mxc_common::telemetry::log_network_policy_applied(
            sanitize_identity(&identity),
            crate::process_container_common::network_policy_helpers::CAPABILITIES_ENFORCEMENT_MODE,
            crate::process_container_common::network_policy_helpers::audit_egress_default(
                &request.policy,
            ),
            request
                .policy
                .network_proxy
                .address
                .as_ref()
                .map(|address| address.port as u64)
                .unwrap_or(0),
        );
        log_base_network_policy_audit(request, &identity, OperationStatus::Success, logger);

        // Hand ownership to the caller via `BaseChild`, which performs
        // sandbox/proxy teardown after the child exits. `job` is always present
        // here (we failed closed above); the `Option` and the root-only fallback
        // in `kill()` remain purely as defense-in-depth.
        Ok(BaseChild {
            process: OwnedHandle::new(pi.hProcess),
            thread: OwnedHandle::new(pi.hThread),
            pid: pi.dwProcessId,
            job: Some(job),
            stdin_write: captured_stdin_write,
            stdout_read,
            stderr_read,
            timeout_ms: get_timeout_milliseconds(request.script_timeout),
            preserve_policy: request.lifecycle.preserve_policy,
            identity,
            proxy_coordinator: std::mem::take(&mut self.proxy_coordinator),
            capture_session,
            security_environment,
            managed_capture: managed_capture.take(),
            capture_output_path,
            retain_capture_etl: capture_denials
                .as_ref()
                .is_some_and(|config| config.retain_etl),
        })
    }
}

/// A BaseContainer child launched by [`BaseContainerRunner::spawn_base`].
/// `spawn_base` resumes it only after job assignment. This owns the process
/// handle, parent-side pipe ends, and per-run state it tears down once the
/// child exits.
struct BaseChild {
    process: OwnedHandle,
    thread: OwnedHandle,
    pid: u32,
    /// Job object the child is assigned to, used to tree-kill it. Always
    /// `Some` on a successfully spawned child (`spawn_base` fails closed when
    /// the job cannot be set up); the `Option` is retained so `kill()` can keep
    /// a root-only fallback as defense-in-depth.
    job: Option<UiJobObject>,
    stdin_write: Option<OwnedHandle>,
    stdout_read: Option<OwnedHandle>,
    stderr_read: Option<OwnedHandle>,
    timeout_ms: u32,
    preserve_policy: bool,
    identity: String,
    proxy_coordinator: ProxyCoordinator,
    /// Live learning-mode capture session (`Some` only when `captureDenials`
    /// is configured and the OS API is available). Sealed in `run_teardown`
    /// after the child exits.
    capture_session: Option<Box<dyn CaptureSessionOps>>,
    /// Non-capture PSEC environment retained until the child exits so policy
    /// enforcement outlives the process tree.
    security_environment: Option<ProcessSecurityEnvironment>,
    /// Protected per-run ETL path and its cleanup guard.
    managed_capture: Option<ManagedCapturePath>,
    /// Resolved JSON denials deliverable path (caller-specified or a managed
    /// per-run temp file). `Some` iff `capture_session` is `Some`.
    capture_output_path: Option<PathBuf>,
    /// Whether the sealed ETL is retained after analysis.
    retain_capture_etl: bool,
}

impl SandboxBackend for BaseContainerRunner {
    fn network_policy_support(&self) -> NetworkPolicySupport {
        NetworkPolicySupport::ALL
    }

    fn validate(&self, request: &ExecutionRequest) -> Result<(), ScriptResponse> {
        validate_required_child_env(request)?;
        validate_network_policy_support(request, self.network_policy_support())?;
        if has_conflicting_proxy_identity(&request.policy) {
            return Err(ScriptResponse::rejected(
                "processContainer.network.allowedProxyPeer grants loopback access only to the \
                 specified peer and cannot be combined with \
                 network.ingress.hostLoopback='allow', which grants unrestricted host-loopback \
                 access",
            ));
        }
        // Dry-run validates the schema and policy shape without selecting or
        // probing a host capture provider.
        if request.dry_run {
            return Ok(());
        }
        if !self.request_serviceability_confirmed
            && !Self::can_backend_service_request(request).can_service_request()
        {
            return Err(ScriptResponse {
                failure_phase: FailurePhase::BackendUnavailable,
                ..ScriptResponse::error(
                    "the request cannot be represented by the process security environment \
                     available on this host",
                )
            });
        }
        if request.policy.least_privilege_mode {
            return Err(ScriptResponse::rejected(
                "the process-security-environment path cannot be combined with \
                 processContainer.leastPrivilege because it does not support LPAC tokens",
            ));
        }
        Ok(())
    }

    fn spawn(
        &mut self,
        request: &ExecutionRequest,
        logger: &mut Logger,
        stdio: StdioMode,
    ) -> Result<Box<dyn SandboxProcess>, ScriptResponse> {
        use crate::mxc_common::validator::validate_common;

        crate::process_container_common::validate_process_container_stdio(stdio)?;
        validate_common(request)?;
        self.validate(request)?;

        // Pipes → capture pipes the caller drives; Inherit → the child inherits
        // the binary's own std handles / console (a TTY when the binary has one).
        let capture = stdio == StdioMode::Pipes;
        let child = self.spawn_base(request, logger, capture)?;
        Ok(Box::new(BaseContainerSandboxProcess::from_child(
            child, logger,
        )))
    }

    fn diagnose_exit(&self, request: &ExecutionRequest, exit_code: i32) -> Option<String> {
        diagnose_process_exit(
            &request.script_code,
            &request.policy.readonly_paths,
            &request.policy.readwrite_paths,
            exit_code as u32,
        )
        .map(|diag| diag.message)
    }
}

/// A running BaseContainer-sandboxed process exposed as a [`SandboxProcess`].
/// Owns the process handle, the parent-side pipes, and the per-run proxy /
/// sandbox state, which it tears down once the child exits.
struct BaseContainerSandboxProcess {
    process: SendOwnedHandle,
    _thread: SendOwnedHandle,
    job: Option<UiJobObject>,
    pid: u32,
    stdin: Option<PipeWriter>,
    stdout: Option<InterruptiblePipeReader>,
    stderr: Option<InterruptiblePipeReader>,
    /// Cancellers for the stdout/stderr reads, kept so the `SandboxProcess`
    /// closers can mint a [`StreamCloser`] even after the stream is taken.
    stdout_canceller: Option<PipeReadCanceller>,
    stderr_canceller: Option<PipeReadCanceller>,
    timeout_ms: u32,
    // Retained here, in addition to the optional engine telemetry wrapper, so
    // callers still receive timeout classification when telemetry is disabled.
    timeout_requested: bool,
    preserve_policy: bool,
    identity: String,
    proxy_coordinator: ProxyCoordinator,
    /// Cached teardown outcome so repeated terminal waits cannot hide a
    /// capture failure after the session has been consumed.
    teardown_result: Option<Result<(), String>>,
    /// Live learning-mode capture session, moved from the `BaseChild`. Sealed
    /// in `run_teardown` once the child has exited and been reaped.
    capture_session: Option<Box<dyn CaptureSessionOps>>,
    /// Non-capture PSEC environment, closed after the child exits and is reaped.
    security_environment: Option<ProcessSecurityEnvironment>,
    /// Protected per-run ETL path and its cleanup guard.
    managed_capture: Option<ManagedCapturePath>,
    /// Resolved JSON denials deliverable path.
    capture_output_path: Option<PathBuf>,
    /// Whether the sealed ETL is retained after analysis.
    retain_capture_etl: bool,
    /// Exit code of the child, recorded by `wait` before teardown so the
    /// denials summary can carry it. `None` on the `Drop`/early-exit path.
    last_exit_code: Option<i32>,
    /// Structured output published after capture teardown succeeds.
    output_metadata: Option<SandboxOutputMetadata>,
    audit_logger: Logger,
}

// SAFETY: the fields are Windows HANDLEs / handle-owning managers and owned
// strings. HANDLEs are process-global and safe to use from any single thread;
// this handle is owned exclusively by the caller, so moving it across threads
// is sound.
unsafe impl Send for BaseContainerSandboxProcess {}

impl BaseContainerSandboxProcess {
    fn from_child(mut child: BaseChild, logger: &Logger) -> Self {
        let process = SendOwnedHandle::take(&mut child.process);
        let thread = SendOwnedHandle::take(&mut child.thread);
        let stdin = child.stdin_write.take().map(PipeWriter::new);
        let stdout = child.stdout_read.take().map(InterruptiblePipeReader::new);
        let stderr = child.stderr_read.take().map(InterruptiblePipeReader::new);
        let stdout_canceller = stdout.as_ref().map(InterruptiblePipeReader::canceller);
        let stderr_canceller = stderr.as_ref().map(InterruptiblePipeReader::canceller);
        Self {
            process,
            _thread: thread,
            job: child.job.take(),
            pid: child.pid,
            stdin,
            stdout,
            stderr,
            stdout_canceller,
            stderr_canceller,
            timeout_ms: child.timeout_ms,
            timeout_requested: false,
            preserve_policy: child.preserve_policy,
            identity: sanitize_identity(&std::mem::take(&mut child.identity)).to_string(),
            proxy_coordinator: std::mem::take(&mut child.proxy_coordinator),
            teardown_result: None,
            capture_session: child.capture_session.take(),
            security_environment: child.security_environment.take(),
            managed_capture: child.managed_capture.take(),
            capture_output_path: child.capture_output_path.take(),
            retain_capture_etl: child.retain_capture_etl,
            last_exit_code: None,
            output_metadata: None,
            audit_logger: logger.clone_diagnostic_sink(),
        }
    }

    fn audit(&self, name: AuditEventName) -> AuditEvent {
        AuditEvent::new(name)
            .str("backend", ContainmentBackend::ProcessContainer.wire_name())
            .str("identity", &self.identity)
            .str(
                "tier",
                crate::process_container_common::fallback_detector::IsolationTier::BaseContainer
                    .as_str(),
            )
            .u64("pid", self.pid as u64)
    }

    fn audit_enabled(&self) -> bool {
        self.audit_logger.has_diagnostic_sink()
    }

    fn run_teardown(&mut self, allow_retention: bool) -> std::io::Result<()> {
        if let Some(result) = &self.teardown_result {
            return result.clone().map_err(std::io::Error::other);
        }
        let mut logger = self.audit_logger.clone_diagnostic_sink();

        // Seal the learning-mode ETL trace now that the child has exited and
        // been reaped (both `wait` and `Drop` kill + reap before calling this).
        // Seal the ETL, decode it into the JSON denials deliverable, and either
        // delete it or report its retained path according to the request. Any
        // seal/decode/write failure is returned through `wait()`.
        let capture_result = if let Some(session) = self.capture_session.take() {
            let managed_capture = self.managed_capture.take();
            if !allow_retention {
                let result = discard_abandoned_capture(session, managed_capture);
                self.capture_output_path.take();
                result.map(|_| None)
            } else {
                let etl_path = managed_capture
                    .as_ref()
                    .map(|capture| capture.etl_path.as_path());
                let output_path = self.capture_output_path.take();
                let exit_code = self.last_exit_code.unwrap_or(-1);
                let retain_etl = allow_retention && self.retain_capture_etl;
                let finish_result = session.finish(etl_path);
                let (mut etl_path, mut etl_directory) = managed_capture
                    .map(ManagedCapturePath::disarm)
                    .map(|(path, directory)| (Some(path), Some(directory)))
                    .unwrap_or((None, None));
                let promotion_error = if finish_result.is_ok() && retain_etl {
                    match (&etl_path, &etl_directory) {
                        (Some(etl), Some(directory)) => {
                            match promote_capture_for_retention(etl, directory) {
                                Ok((retained_etl, retained_directory)) => {
                                    etl_path = Some(retained_etl);
                                    etl_directory = Some(retained_directory);
                                    None
                                }
                                Err(error) => Some(error),
                            }
                        }
                        _ => None,
                    }
                } else {
                    None
                };
                let (capture_result, etl_was_sealed) = match finish_result {
                    Ok(()) => (
                        match (&etl_path, &output_path) {
                            (Some(etl), Some(output)) => Self::decode_write_and_finalize(
                                &EtlDenialAnalyzer,
                                etl,
                                etl_directory.as_deref(),
                                output,
                                exit_code,
                                retain_etl,
                            )
                            .map(Some),
                            _ => finalize_capture_result(
                                Err(std::io::Error::other(
                                    "captureDenials internal output paths were not initialized",
                                )),
                                etl_path.as_deref(),
                                etl_directory.as_deref(),
                                retain_etl,
                            )
                            .map(Some),
                        },
                        true,
                    ),
                    Err(error) => (
                        finalize_capture_seal_failure(
                            std::io::Error::other(format!(
                                "captureDenials failed to finalize the denial capture: {error}"
                            )),
                            etl_path.as_deref(),
                            etl_directory.as_deref(),
                        )
                        .map(Some),
                        false,
                    ),
                };
                let result = match (capture_result, promotion_error) {
                    (Ok(Some(metadata)), Some(error)) => {
                        self.output_metadata = Some(SandboxOutputMetadata {
                            capture_denials: Some(metadata),
                            capture_denials_error: Some(CaptureDenialsErrorOutput {
                                message: error.to_string(),
                                etl_path: etl_path
                                    .as_deref()
                                    .map(|path| path.to_string_lossy().into_owned())
                                    .unwrap_or_default(),
                            }),
                        });
                        Err(error)
                    }
                    (Err(capture_error), Some(promotion_error)) => {
                        let error = std::io::Error::other(format!(
                            "{capture_error}; additionally {promotion_error}"
                        ));
                        if let Some(etl_path) = etl_path.as_deref() {
                            self.output_metadata = Some(SandboxOutputMetadata {
                                capture_denials: None,
                                capture_denials_error: Some(CaptureDenialsErrorOutput {
                                    message: error.to_string(),
                                    etl_path: etl_path.to_string_lossy().into_owned(),
                                }),
                            });
                        }
                        Err(error)
                    }
                    (Ok(Some(metadata)), None) => {
                        self.output_metadata = Some(SandboxOutputMetadata {
                            capture_denials: Some(metadata.clone()),
                            capture_denials_error: None,
                        });
                        Ok(Some(metadata))
                    }
                    (Err(error), None) => {
                        if let Some(metadata) = capture_output_from_cleanup_error(&error) {
                            self.output_metadata = Some(SandboxOutputMetadata {
                                capture_denials: Some(metadata.clone()),
                                capture_denials_error: None,
                            });
                        } else if retain_etl && etl_was_sealed {
                            if let Some(etl_path) = etl_path.as_deref() {
                                self.output_metadata = Some(SandboxOutputMetadata {
                                    capture_denials: None,
                                    capture_denials_error: Some(CaptureDenialsErrorOutput {
                                        message: error.to_string(),
                                        etl_path: etl_path.to_string_lossy().into_owned(),
                                    }),
                                });
                            }
                        }
                        Err(error)
                    }
                    (Ok(None), promotion_error) => promotion_error.map_or(Ok(None), Err),
                };
                result
            }
        } else {
            self.managed_capture.take();
            Ok(None)
        };
        self.security_environment.take();
        let proxy_stopped = self.proxy_coordinator.stop(&mut logger);
        let result = capture_result
            .map(|_| ())
            .map_err(|error| error.to_string());
        self.log_teardown(&result, proxy_stopped);
        self.teardown_result = Some(result.clone());
        result.map_err(std::io::Error::other)
    }

    fn log_teardown(&mut self, capture_result: &Result<(), String>, proxy_stopped: bool) {
        if !self.audit_enabled() && !crate::mxc_common::telemetry::is_active() {
            return;
        }
        let (status, skip_reason) =
            base_container_teardown_status(capture_result.is_err(), false, self.preserve_policy);
        crate::mxc_common::telemetry::log_sandbox_torn_down(
            &self.identity,
            status.as_str(),
            &format!(
                "firewall_rules_removed=0,bfs_removed=false,proxy_stopped={proxy_stopped},\
                 container_released=false"
            ),
        );
        if self.audit_enabled() {
            let mut record = self
                .audit(AuditEventName::SandboxTornDown)
                .str("status", status.as_str())
                .u64("firewall_rules_removed", 0)
                .bool("firewall_removal_ok", true)
                .bool("bfs_removed", false)
                .bool("proxy_stopped", proxy_stopped)
                .bool("preserve_policy", self.preserve_policy)
                .bool("container_released", false);
            if let Some(reason) = skip_reason {
                record = record.str("skip_reason", reason.as_str());
            }
            self.audit_logger.log_audit_event(&record);
        }
    }

    fn kill_process_tree(&mut self) -> std::io::Result<()> {
        if let Some(job) = &self.job {
            if let Err(error) = job.terminate_raw(u32::MAX) {
                self.record_kill_failure(KillMethod::TerminateJobObject, &error);
                return Err(std::io::Error::other(format!(
                    "TerminateJobObject: {error}"
                )));
            }
            if let Err(drain_warning) = job.wait_for_empty() {
                write_stderr_line_best_effort(format_args!(
                    "sandbox job did not fully drain within the teardown window \
                     (continuing): {drain_warning}"
                ));
            }
        } else if let Err(error) = unsafe { TerminateProcess(self.process.get(), u32::MAX) } {
            self.record_kill_failure(KillMethod::TerminateProcess, &error);
            return Err(std::io::Error::other(format!("TerminateProcess: {error}")));
        }
        Ok(())
    }

    fn record_kill_failure(&mut self, method: KillMethod, error: &windows::core::Error) {
        crate::mxc_common::telemetry::log_process_event(
            &self.identity,
            self.pid,
            crate::mxc_common::telemetry::ProcessEvent::KillFailed(method.as_str(), error.code().0),
        );
        if self.audit_enabled() {
            let record = self
                .audit(AuditEventName::ProcessKillFailed)
                .str("kill_method", method.as_str())
                .i64("error_code", error.code().0 as i64);
            self.audit_logger.log_audit_event(&record);
        }
    }

    fn timeout_result(&mut self) -> std::io::Result<i32> {
        crate::mxc_common::telemetry::log_process_event(
            &self.identity,
            self.pid,
            crate::mxc_common::telemetry::ProcessEvent::TimedOut(self.timeout_ms as u64),
        );
        if self.audit_enabled() {
            let record = self
                .audit(AuditEventName::ProcessTimedOut)
                .u64("timeout_ms", self.timeout_ms as u64);
            self.audit_logger.log_audit_event(&record);
        }
        Err(std::io::Error::new(
            std::io::ErrorKind::TimedOut,
            format!("script timed out after {}ms", self.timeout_ms),
        ))
    }

    fn terminate_and_reap(&mut self) -> std::io::Result<()> {
        self.kill_process_tree()?;
        unsafe {
            match WaitForSingleObject(self.process.get(), u32::MAX) {
                WAIT_OBJECT_0 => Ok(()),
                status => Err(std::io::Error::other(format!(
                    "WaitForSingleObject(process) returned {status:?}"
                ))),
            }
        }
    }

    /// Decodes a sealed capture into the JSON denials document at `output_path`.
    fn decode_and_write_denials(
        analyzer: &dyn CaptureDenialAnalyzer,
        etl_path: &std::path::Path,
        output_path: &std::path::Path,
        exit_code: i32,
    ) -> std::io::Result<CaptureDenialsOutput> {
        let analysis = analyzer.analyze_capture(etl_path).map_err(|error| {
            std::io::Error::other(format!(
                "captureDenials failed to decode denials ETL: {error}"
            ))
        })?;
        write_capture_denials_document(analysis, exit_code, output_path)
    }

    fn decode_write_and_finalize(
        analyzer: &dyn CaptureDenialAnalyzer,
        etl_path: &Path,
        etl_directory: Option<&Path>,
        output_path: &Path,
        exit_code: i32,
        retain_etl: bool,
    ) -> std::io::Result<CaptureDenialsOutput> {
        finalize_capture_result(
            Self::decode_and_write_denials(analyzer, etl_path, output_path, exit_code),
            Some(etl_path),
            etl_directory,
            retain_etl,
        )
    }
}

fn finalize_capture_result(
    capture_result: std::io::Result<CaptureDenialsOutput>,
    etl_path: Option<&Path>,
    etl_directory: Option<&Path>,
    retain_etl: bool,
) -> std::io::Result<CaptureDenialsOutput> {
    if retain_etl {
        let Some(etl_path) = etl_path else {
            return capture_result;
        };
        let retained_path = etl_path.to_string_lossy().into_owned();
        return capture_result
            .map(|mut output| {
                output.etl_path = Some(retained_path);
                output
            })
            .map_err(|error| {
                std::io::Error::other(format!(
                    "{error}; retained ETL file at {}",
                    etl_path.display()
                ))
            });
    }

    combine_capture_output_and_cleanup_results(
        capture_result,
        etl_path
            .map(|path| remove_managed_capture_path(path, etl_directory))
            .unwrap_or(Ok(())),
    )
}

fn combine_capture_output_and_cleanup_results(
    capture_result: std::io::Result<CaptureDenialsOutput>,
    cleanup_result: std::io::Result<()>,
) -> std::io::Result<CaptureDenialsOutput> {
    match (capture_result, cleanup_result) {
        (Ok(output), Ok(())) => Ok(output),
        (Ok(output), Err(cleanup_error)) => Err(std::io::Error::other(CaptureCleanupError {
            output,
            cleanup_message: cleanup_error.to_string(),
        })),
        (Err(capture_error), Ok(())) => Err(capture_error),
        (Err(capture_error), Err(cleanup_error)) => Err(std::io::Error::other(format!(
            "{capture_error}; additionally failed to clean up the internal ETL: {cleanup_error}"
        ))),
    }
}

fn capture_output_from_cleanup_error(error: &std::io::Error) -> Option<&CaptureDenialsOutput> {
    error
        .get_ref()
        .and_then(|source| source.downcast_ref::<CaptureCleanupError>())
        .map(|error| &error.output)
}

fn finalize_capture_seal_failure<T>(
    capture_error: std::io::Error,
    etl_path: Option<&Path>,
    etl_directory: Option<&Path>,
) -> std::io::Result<T> {
    combine_capture_and_cleanup_results(
        Err(capture_error),
        etl_path
            .map(|path| remove_managed_capture_path(path, etl_directory))
            .unwrap_or(Ok(())),
    )
}

fn discard_abandoned_capture(
    session: Box<dyn CaptureSessionOps>,
    managed_capture: Option<ManagedCapturePath>,
) -> std::io::Result<()> {
    let result = session.finish(None).map_err(|error| {
        std::io::Error::other(format!(
            "captureDenials failed to discard the abandoned denial capture: {error}"
        ))
    });
    drop(managed_capture);
    result
}

fn remove_managed_capture_path(path: &Path, directory: Option<&Path>) -> std::io::Result<()> {
    let file_result = remove_internal_capture_file(path);
    let directory_result = match directory {
        Some(directory) => match std::fs::remove_dir(directory) {
            Ok(()) => Ok(()),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(error) => Err(std::io::Error::other(format!(
                "captureDenials failed to remove internal ETL directory {}: {error}",
                directory.display()
            ))),
        },
        None => Ok(()),
    };
    match (file_result, directory_result) {
        (Ok(()), Ok(())) => Ok(()),
        (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
        (Err(file_error), Err(directory_error)) => Err(std::io::Error::other(format!(
            "{file_error}; additionally {directory_error}"
        ))),
    }
}

fn base_container_teardown_status(
    capture_failed: bool,
    destroy_on_exit: bool,
    preserve_policy: bool,
) -> (TeardownStatus, Option<TeardownSkipReason>) {
    if capture_failed {
        (TeardownStatus::Failure, None)
    } else if preserve_policy {
        (
            TeardownStatus::Skipped,
            Some(TeardownSkipReason::PreservePolicy),
        )
    } else if destroy_on_exit {
        (
            TeardownStatus::Skipped,
            Some(TeardownSkipReason::CleanupNotImplemented),
        )
    } else {
        (TeardownStatus::Success, None)
    }
}

impl SandboxProcess for BaseContainerSandboxProcess {
    fn output_metadata(&self) -> Option<&SandboxOutputMetadata> {
        self.output_metadata.as_ref()
    }

    fn take_native_stdio(&mut self) -> std::io::Result<Option<NativeStdio>> {
        let stdio = duplicate_and_take_native_stdio(
            &mut self.stdin,
            &mut self.stdout,
            &mut self.stderr,
            |stream| stream.try_clone_owned_handle(),
            |stream| stream.try_clone_owned_handle(),
            |stream| stream.try_clone_owned_handle(),
        )?;
        if stdio.is_some() {
            self.stdout_canceller.take();
            self.stderr_canceller.take();
        }
        Ok(stdio)
    }

    fn take_stdin(&mut self) -> Option<Box<dyn std::io::Write + Send>> {
        take_boxed_write(&mut self.stdin)
    }

    fn take_stdout(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
        take_boxed_read(&mut self.stdout)
    }

    fn take_stderr(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
        take_boxed_read(&mut self.stderr)
    }

    fn stdout_closer(&self) -> Option<Box<dyn StreamCloser>> {
        boxed_closer(&self.stdout_canceller)
    }

    fn stderr_closer(&self) -> Option<Box<dyn StreamCloser>> {
        boxed_closer(&self.stderr_canceller)
    }

    fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
        match unsafe { WaitForSingleObject(self.process.get(), 0) } {
            WAIT_OBJECT_0 => {
                let mut code: u32 = 0;
                if unsafe { GetExitCodeProcess(self.process.get(), &mut code) }.is_err() {
                    return Err(std::io::Error::other("GetExitCodeProcess failed"));
                }
                // Keep polling non-blocking and independent of captureDenials.
                // `wait()` or `Drop` owns descendant termination and capture
                // finalization after the root exit becomes observable.
                if self.timeout_requested {
                    Err(std::io::Error::new(
                        std::io::ErrorKind::TimedOut,
                        "sandbox execution timed out",
                    ))
                } else {
                    Ok(Some(code as i32))
                }
            }
            WAIT_TIMEOUT => Ok(None),
            _ => Err(std::io::Error::other("WaitForSingleObject failed")),
        }
    }

    fn id(&self) -> u32 {
        self.pid
    }

    fn kill(&mut self) -> std::io::Result<()> {
        // Tree-kill via the job object when the child was successfully assigned
        // to one; otherwise fall back to terminating the root process.
        self.kill_process_tree()
    }

    fn kill_for_timeout(&mut self) -> std::io::Result<()> {
        self.timeout_requested = true;
        self.kill_process_tree()
    }

    fn wait(&mut self) -> std::io::Result<i32> {
        // Close our copy of any not-taken stdin so the child sees EOF and can
        // exit reliably (an interactive command would otherwise block waiting
        // for input).
        self.stdin.take();

        // Drain (and discard) any not-taken streams concurrently to avoid the
        // child blocking on a full pipe buffer.
        let stdout_thread = spawn_discard(self.stdout.take());
        let stderr_thread = spawn_discard(self.stderr.take());

        let result = match unsafe { WaitForSingleObject(self.process.get(), self.timeout_ms) } {
            WAIT_OBJECT_0 => {
                let mut code: u32 = 0;
                if unsafe { GetExitCodeProcess(self.process.get(), &mut code) }.is_err() {
                    Err(std::io::Error::other("GetExitCodeProcess failed"))
                } else if self.timeout_requested {
                    self.timeout_result()
                } else {
                    let exit_code = code as i32;
                    crate::mxc_common::telemetry::log_process_event(
                        &self.identity,
                        self.pid,
                        crate::mxc_common::telemetry::ProcessEvent::Exited(exit_code),
                    );
                    if self.audit_enabled() {
                        let record = self
                            .audit(AuditEventName::ProcessExited)
                            .i64("exit_code", exit_code as i64);
                        self.audit_logger.log_audit_event(&record);
                    }
                    Ok(exit_code)
                }
            }
            WAIT_TIMEOUT => self.timeout_result(),
            _ => Err(std::io::Error::other("WaitForSingleObject failed")),
        };

        // Tree-kill (the job when assigned, else the root) so any backgrounded
        // descendant dies *before* `run_teardown()` stops the proxy / sandbox
        // enforcement — upholding the same invariant as `Drop`. The foreground
        // child has already exited on the success path; on a timeout or wait
        // failure this also terminates it. Then reap the root before releasing
        // the pipe drains — and killing the tree closes the descendant's pipe
        // write-ends, so the drains can finish.
        let termination_result = self.terminate_and_reap();
        cancel_and_join_discard(stdout_thread, &self.stdout_canceller);
        cancel_and_join_discard(stderr_thread, &self.stderr_canceller);
        termination_result?;
        // Record the child's exit code so `run_teardown` can stamp it into the
        // denials summary. On a timeout / wait failure there is no exit code.
        self.last_exit_code = result.as_ref().ok().copied();
        let teardown_result = self.run_teardown(true);
        combine_process_and_teardown_results(result, teardown_result)
    }
}

impl Drop for BaseContainerSandboxProcess {
    fn drop(&mut self) {
        // Kill and reap before tearing down proxy / sandbox state, so an
        // abandoned-but-running sandbox cannot outlive its enforcement (or
        // leak as an orphan).
        if let Err(error) = self.terminate_and_reap() {
            write_stderr_line_best_effort(format_args!(
                "failed to terminate sandbox process tree during drop: {error}"
            ));
            return;
        }
        // A dropped handle has no observer for output metadata, so retaining
        // its ETL would leave a sensitive artifact with no discoverable owner.
        // If wait already attempted teardown, it already reported any failure.
        if self.teardown_result.is_none() {
            if let Err(error) = self.run_teardown(false) {
                write_stderr_line_best_effort(format_args!(
                    "captureDenials teardown failed during drop: {error}"
                ));
            }
        }
    }
}

struct ManagedCapturePath {
    directory: PathBuf,
    etl_path: PathBuf,
    armed: bool,
}

impl ManagedCapturePath {
    fn disarm(mut self) -> (PathBuf, PathBuf) {
        self.armed = false;
        (
            std::mem::take(&mut self.etl_path),
            std::mem::take(&mut self.directory),
        )
    }
}

impl Drop for ManagedCapturePath {
    fn drop(&mut self) {
        if self.armed {
            let _ = remove_managed_capture_path(&self.etl_path, Some(&self.directory));
        }
    }
}

fn managed_capture_output_path(retain_etl: bool) -> Result<ManagedCapturePath, ScriptResponse> {
    if !retain_etl {
        return managed_capture_output_path_in(
            &std::env::temp_dir(),
            "mxc_capture_denials_",
            false,
        );
    }

    let local_app_data = std::env::var_os("LOCALAPPDATA")
        .map(PathBuf::from)
        .or_else(|| {
            std::env::var_os("USERPROFILE")
                .map(PathBuf::from)
                .map(|profile| profile.join("AppData").join("Local"))
        })
        .ok_or_else(|| {
            ScriptResponse::error(
                "captureDenials could not resolve LOCALAPPDATA for protected ETL storage",
            )
        })?;
    let root = local_app_data
        .join("Microsoft")
        .join("MXC")
        .join("capture-denials")
        .join("working");
    managed_capture_output_path_in(&root, "", true)
}

fn promote_capture_for_retention(
    etl_path: &Path,
    directory: &Path,
) -> std::io::Result<(PathBuf, PathBuf)> {
    let working_root = directory
        .parent()
        .ok_or_else(|| std::io::Error::other("captureDenials working directory has no parent"))?;
    let capture_root = working_root
        .parent()
        .ok_or_else(|| std::io::Error::other("captureDenials working root has no parent"))?;
    let retained_root = capture_root
        .join(crate::process_container_common::capture_output::RETAINED_CAPTURE_DIR_NAME);
    std::fs::create_dir_all(&retained_root)?;
    crate::mxc_common::filesystem_dacl::set_owner_only_dacl(&retained_root, true)
        .map_err(std::io::Error::other)?;
    let directory_name = directory.file_name().ok_or_else(|| {
        std::io::Error::other("captureDenials working directory has no file name")
    })?;
    let retained_directory = retained_root.join(directory_name);
    std::fs::rename(directory, &retained_directory).map_err(|error| {
        std::io::Error::other(format!(
            "captureDenials failed to move sealed ETL into retained storage: {error}; retained ETL file remains at {}",
            etl_path.display()
        ))
    })?;
    Ok((
        retained_directory.join(
            etl_path
                .file_name()
                .unwrap_or_else(|| std::ffi::OsStr::new("capture.etl")),
        ),
        retained_directory,
    ))
}

fn managed_capture_output_path_in(
    root: &Path,
    directory_prefix: &str,
    secure_root: bool,
) -> Result<ManagedCapturePath, ScriptResponse> {
    if secure_root {
        std::fs::create_dir_all(root).map_err(|error| {
            ScriptResponse::error(&format!(
                "captureDenials failed to create ETL root {}: {error}",
                root.display()
            ))
        })?;
        crate::mxc_common::filesystem_dacl::set_owner_only_dacl(root, true).map_err(|error| {
            ScriptResponse::error(&format!(
                "captureDenials failed to secure ETL root {}: {error}",
                root.display()
            ))
        })?;
    }

    for _ in 0..8 {
        let suffix = crate::process_container_common::capture_output::random_capture_suffix()
            .map_err(|error| ScriptResponse::error(&error))?;
        let directory = root.join(format!("{directory_prefix}{}_{suffix}", std::process::id()));
        match std::fs::create_dir(&directory) {
            Ok(()) => {
                if let Err(error) =
                    crate::mxc_common::filesystem_dacl::set_owner_only_dacl(&directory, true)
                {
                    let _ = std::fs::remove_dir(&directory);
                    return Err(ScriptResponse::error(&format!(
                        "captureDenials failed to secure ETL directory {}: {error}",
                        directory.display()
                    )));
                }
                return Ok(ManagedCapturePath {
                    etl_path: directory.join("capture.etl"),
                    directory,
                    armed: true,
                });
            }
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(error) => {
                return Err(ScriptResponse::error(&format!(
                    "captureDenials failed to create ETL directory {}: {error}",
                    directory.display()
                )));
            }
        }
    }

    Err(ScriptResponse::error(
        "captureDenials failed to allocate a unique protected ETL directory",
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::learning_mode_core::{
        capture_diagnostics::CaptureVerboseLoggingSummary, AccessType, AnalysisResult,
        AnalyzeError, DenialsDocument, DeniedResource, ResourceType,
    };
    use crate::mxc_common::models::{
        BaseProcessUiConfig, ClipboardPolicy, ContainerPolicy, ContainmentBackend, NetworkAction,
        NetworkCidr, NetworkEgressPolicy, NetworkIngressPolicy, NetworkPeer, NetworkPort,
        NetworkProtocol, NetworkRule, ProxyAddress, ProxyConfig, UiPolicy,
    };
    use crate::mxc_common::network_parser::{parse_network_policy, NetworkSections};
    use crate::mxc_common::ui_policy::EffectiveUiRestrictions;
    use crate::mxc_common::wire;
    use crate::process_container_common::job_object::to_job_object_uilimit_mask;
    use crate::process_security_environment_spec::process_security_environment_layout as psec_layout;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[test]
    fn native_capture_probe_requires_base_container_and_complete_learning_mode_abi() {
        assert!(!BaseContainerRunner::native_capture_available_with(
            false,
            || panic!("Learning Mode must not be probed when PSEC is unavailable")
        ));
        assert!(!BaseContainerRunner::native_capture_available_with(
            true,
            || false
        ));
        assert!(BaseContainerRunner::native_capture_available_with(
            true,
            || true
        ));
    }

    #[test]
    fn basecontainer_network_audit_records_proxyless_proxy_and_setup_failure() {
        for (default, proxy_port, status, expected_default) in [
            (NetworkAction::Deny, None, OperationStatus::Success, "block"),
            (
                NetworkAction::Allow,
                None,
                OperationStatus::Success,
                "allow",
            ),
            (
                NetworkAction::Deny,
                Some(8080),
                OperationStatus::Success,
                "block",
            ),
            (
                NetworkAction::Deny,
                Some(8080),
                OperationStatus::Failure,
                "block",
            ),
            (NetworkAction::Deny, None, OperationStatus::Failure, "block"),
        ] {
            let mut request = ExecutionRequest::default();
            request.policy.network_egress = Some(NetworkEgressPolicy {
                default,
                ..Default::default()
            });
            request.policy.network_proxy.address =
                proxy_port.map(|port| ProxyAddress::new("127.0.0.1".to_string(), port));
            let directory = tempfile::tempdir().expect("tempdir");
            let path = directory.path().join("network-audit.log");
            let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
            logger.enable_file_sink(&path).expect("diagnostic sink");

            log_base_network_policy_audit(
                &request,
                "<process-security-environment>",
                status,
                &mut logger,
            );
            drop(logger);

            let output = std::fs::read_to_string(&path).expect("read audit");
            let (_, json) = output
                .trim_end()
                .split_once("] ")
                .expect("timestamped audit record");
            let record: serde_json::Value = serde_json::from_str(json).expect("valid JSON");
            assert_eq!(output.lines().count(), 1);
            assert_eq!(
                record,
                serde_json::json!({
                    "event": "mxc.NetworkPolicyApplied",
                    "backend": "processcontainer",
                    "identity": "redacted",
                    "tier": "base-container",
                    "enforcement_mode": "capabilities",
                    "default_policy": expected_default,
                    "proxy_port": proxy_port.unwrap_or(0),
                    "firewall_rules_created": 0,
                    "firewall_applied": false,
                    "status": status.as_str(),
                })
            );
        }
    }

    fn enumerate_request() -> ExecutionRequest {
        let mut request = ExecutionRequest::default();
        request.policy.enumerate_paths = vec!["C:\\tools".to_string()];
        request.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy {
            default: NetworkAction::Deny,
            host_loopback: NetworkAction::Deny,
        });
        request
    }

    fn host_loopback_request() -> ExecutionRequest {
        let mut request = ExecutionRequest::default();
        request.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy {
            default: NetworkAction::Allow,
            host_loopback: NetworkAction::Allow,
        });
        request
    }

    struct FakeCaptureSession {
        finish_error: Option<(&'static str, i32)>,
        finish_calls: Arc<AtomicUsize>,
    }

    impl CaptureSessionOps for FakeCaptureSession {
        fn environment(&self) -> HANDLE {
            HANDLE(std::ptr::dangling_mut())
        }

        fn finish(
            self: Box<Self>,
            _output_path: Option<&std::path::Path>,
        ) -> Result<(), crate::learning_mode_windows::LearningModeError> {
            self.finish_calls.fetch_add(1, Ordering::SeqCst);
            match self.finish_error {
                Some((function, code)) => Err(
                    crate::learning_mode_windows::LearningModeError::HResultCall { function, code },
                ),
                None => Ok(()),
            }
        }
    }

    struct FakeCaptureFactory {
        trace_sources: LearningModeTraceSources,
        begin_error: Option<(&'static str, i32)>,
        finish_error: Option<(&'static str, i32)>,
        begin_calls: AtomicUsize,
        finish_calls: Arc<AtomicUsize>,
    }

    impl CaptureSessionFactory for FakeCaptureFactory {
        fn trace_sources(
            &self,
        ) -> Result<LearningModeTraceSources, crate::learning_mode_windows::LearningModeError>
        {
            Ok(self.trace_sources)
        }

        fn begin(
            &self,
            _sandbox_specification: &[u8],
            _flags: u32,
        ) -> Result<Box<dyn CaptureSessionOps>, crate::learning_mode_windows::LearningModeError>
        {
            self.begin_calls.fetch_add(1, Ordering::SeqCst);
            if let Some((function, code)) = self.begin_error {
                return Err(
                    crate::learning_mode_windows::LearningModeError::HResultCall { function, code },
                );
            }
            Ok(Box::new(FakeCaptureSession {
                finish_error: self.finish_error,
                finish_calls: Arc::clone(&self.finish_calls),
            }))
        }
    }

    fn fake_capture_factory() -> Arc<FakeCaptureFactory> {
        Arc::new(FakeCaptureFactory {
            trace_sources: LearningModeTraceSources::AccessAndNetwork,
            begin_error: None,
            finish_error: None,
            begin_calls: AtomicUsize::new(0),
            finish_calls: Arc::new(AtomicUsize::new(0)),
        })
    }

    impl BaseContainerRunner {
        fn build_process_security_environment_spec(request: &ExecutionRequest) -> Vec<u8> {
            let version = Self::choose_min_required_psec_version_for_request(request);
            Self::with_capture_factory(fake_capture_factory())
                .build_capture_aware_security_environment_spec(request, version)
                .unwrap()
        }
    }

    struct FakeAnalyzer {
        result: Result<AnalysisResult, &'static str>,
    }

    impl CaptureDenialAnalyzer for FakeAnalyzer {
        fn analyze_capture(&self, _source_path: &Path) -> Result<CaptureAnalysis, AnalyzeError> {
            match &self.result {
                Ok(result) => Ok(CaptureAnalysis {
                    denials: result.denials.clone(),
                    denied_resources_truncated: result.denied_resources_truncated,
                    verbose_logging: result.verbose_logging.clone(),
                    network_verbose_logging: CaptureVerboseLoggingSummary::default(),
                }),
                Err(message) => Err(AnalyzeError::Decode((*message).to_string())),
            }
        }
    }

    fn expected_mask(r: EffectiveUiRestrictions) -> u64 {
        to_job_object_uilimit_mask(&r) as u64
    }

    #[test]
    fn managed_capture_paths_are_unique_per_run() {
        let parent = tempfile::tempdir().expect("temp parent");
        let root = parent.path().join("capture-denials");
        let first = managed_capture_output_path_in(&root, "", true).expect("first path");
        let second = managed_capture_output_path_in(&root, "", true).expect("second path");
        let first_directory = first.directory.clone();
        let second_directory = second.directory.clone();

        assert_ne!(first.directory, second.directory);
        assert_eq!(first.etl_path.parent(), Some(first.directory.as_path()));
        assert_eq!(second.etl_path.parent(), Some(second.directory.as_path()));
        assert_eq!(
            first.etl_path.extension().and_then(|ext| ext.to_str()),
            Some("etl")
        );
        assert!(
            crate::mxc_common::filesystem_dacl::owner_is_self(&first.directory)
                .expect("read managed directory owner")
        );
        drop(first);
        drop(second);
        assert!(!first_directory.exists());
        assert!(!second_directory.exists());
    }

    #[test]
    fn retained_capture_moves_out_of_working_storage() {
        let parent = tempfile::tempdir().expect("temp parent");
        let working = parent.path().join("capture-denials").join("working");
        let directory = working.join("1234_abcd");
        std::fs::create_dir_all(&directory).expect("working directory");
        let etl_path = directory.join("capture.etl");
        std::fs::write(&etl_path, b"fake etl").expect("seed ETL");

        let (retained_etl, retained_directory) =
            promote_capture_for_retention(&etl_path, &directory).expect("promote capture");
        let retained_root = parent.path().join("capture-denials").join("retained");

        assert!(!directory.exists());
        assert_eq!(retained_directory.parent(), Some(retained_root.as_path()));
        assert_eq!(
            std::fs::read(retained_etl).expect("read retained ETL"),
            b"fake etl"
        );
    }

    #[test]
    fn cleanup_failure_preserves_successful_capture_output() {
        let output = CaptureDenialsOutput {
            kind: CaptureDenialsOutput::KIND.to_string(),
            output_path: "denials.json".to_string(),
            exit_code: 0,
            total_denials: 1,
            denied_resources_truncated: false,
            etl_path: None,
        };

        let error = combine_capture_output_and_cleanup_results(
            Ok(output.clone()),
            Err(std::io::Error::other("delete failed")),
        )
        .expect_err("cleanup failure should propagate");

        assert_eq!(capture_output_from_cleanup_error(&error), Some(&output));
        assert!(error.to_string().contains("delete failed"));
    }

    #[test]
    fn injected_analyzer_writes_document_and_returns_metadata() {
        let directory = tempfile::tempdir().expect("temp directory");
        let output_path = directory.path().join("denials.json");
        let analyzer = FakeAnalyzer {
            result: Ok(AnalysisResult::complete(vec![DeniedResource {
                resource: r"C:\blocked.txt".to_string(),
                resource_type: ResourceType::File,
                access_type: AccessType::Read,
                pid: 42,
                filetime: 99,
            }])),
        };

        let metadata = BaseContainerSandboxProcess::decode_and_write_denials(
            &analyzer,
            Path::new("ignored.etl"),
            &output_path,
            7,
        )
        .expect("decode succeeds");

        assert_eq!(metadata.kind, CaptureDenialsOutput::KIND);
        assert_eq!(metadata.exit_code, 7);
        assert_eq!(metadata.total_denials, 1);
        let document: DenialsDocument =
            serde_json::from_slice(&std::fs::read(&output_path).unwrap()).unwrap();
        assert_eq!(document.denials.len(), 1);
        let verbose_path =
            crate::learning_mode_core::verbose_logging_sibling_path(&output_path).unwrap();
        let verbose: serde_json::Value =
            serde_json::from_slice(&std::fs::read(verbose_path).unwrap()).unwrap();
        assert_eq!(
            verbose["version"],
            crate::learning_mode_core::capture_diagnostics::CAPTURE_VERBOSE_LOGGING_VERSION
        );
    }

    #[test]
    fn injected_analyzer_writes_empty_document() {
        let directory = tempfile::tempdir().expect("temp directory");
        let output_path = directory.path().join("denials.json");
        let analyzer = FakeAnalyzer {
            result: Ok(AnalysisResult::complete(Vec::new())),
        };

        let metadata = BaseContainerSandboxProcess::decode_and_write_denials(
            &analyzer,
            Path::new("ignored.etl"),
            &output_path,
            0,
        )
        .expect("decode succeeds");

        assert_eq!(metadata.total_denials, 0);
        assert!(output_path.exists());
    }

    #[test]
    fn injected_analyzer_failure_leaves_no_output_file() {
        let directory = tempfile::tempdir().expect("temp directory");
        let etl_path = directory.path().join("capture.etl");
        let output_path = directory.path().join("denials.json");
        std::fs::write(&etl_path, b"fake etl").expect("seed ETL");
        let analyzer = FakeAnalyzer {
            result: Err("simulated decode failure"),
        };

        let error = BaseContainerSandboxProcess::decode_write_and_finalize(
            &analyzer,
            &etl_path,
            None,
            &output_path,
            0,
            false,
        )
        .expect_err("decode should fail");

        assert!(error.to_string().contains("simulated decode failure"));
        assert!(!etl_path.exists());
        assert!(!output_path.exists());
    }

    #[test]
    fn default_etl_cleanup_removes_file_after_success() {
        let directory = tempfile::tempdir().expect("temp directory");
        let etl_path = directory.path().join("capture.etl");
        let output_path = directory.path().join("denials.json");
        std::fs::write(&etl_path, b"fake etl").expect("seed ETL");
        let analyzer = FakeAnalyzer {
            result: Ok(AnalysisResult::complete(Vec::new())),
        };

        let metadata = BaseContainerSandboxProcess::decode_write_and_finalize(
            &analyzer,
            &etl_path,
            None,
            &output_path,
            0,
            false,
        )
        .expect("decode should succeed");

        assert!(metadata.etl_path.is_none());
        assert!(!etl_path.exists());
        assert!(output_path.exists());
    }

    #[test]
    fn default_etl_cleanup_removes_managed_directory() {
        let parent = tempfile::tempdir().expect("temp parent");
        let directory = parent.path().join("managed");
        std::fs::create_dir(&directory).expect("managed directory");
        let etl_path = directory.join("capture.etl");
        let output_path = parent.path().join("denials.json");
        std::fs::write(&etl_path, b"fake etl").expect("seed ETL");
        let analyzer = FakeAnalyzer {
            result: Ok(AnalysisResult::complete(Vec::new())),
        };

        BaseContainerSandboxProcess::decode_write_and_finalize(
            &analyzer,
            &etl_path,
            Some(&directory),
            &output_path,
            0,
            false,
        )
        .expect("decode should succeed");

        assert!(!directory.exists());
        assert!(output_path.exists());
    }

    #[test]
    fn requested_etl_retention_reports_path_and_preserves_file() {
        let directory = tempfile::tempdir().expect("temp directory");
        let etl_path = directory.path().join("capture.etl");
        let output_path = directory.path().join("denials.json");
        std::fs::write(&etl_path, b"fake etl").expect("seed ETL");
        let analyzer = FakeAnalyzer {
            result: Ok(AnalysisResult::complete(Vec::new())),
        };

        let metadata = BaseContainerSandboxProcess::decode_write_and_finalize(
            &analyzer,
            &etl_path,
            None,
            &output_path,
            0,
            true,
        )
        .expect("decode should succeed");

        assert_eq!(
            metadata.etl_path.as_deref(),
            Some(etl_path.to_string_lossy().as_ref())
        );
        assert!(etl_path.exists());
        assert!(output_path.exists());
    }

    #[test]
    fn requested_etl_retention_preserves_file_when_analysis_fails() {
        let directory = tempfile::tempdir().expect("temp directory");
        let etl_path = directory.path().join("capture.etl");
        let output_path = directory.path().join("denials.json");
        std::fs::write(&etl_path, b"fake etl").expect("seed ETL");
        let analyzer = FakeAnalyzer {
            result: Err("simulated decode failure"),
        };

        let error = BaseContainerSandboxProcess::decode_write_and_finalize(
            &analyzer,
            &etl_path,
            None,
            &output_path,
            0,
            true,
        )
        .expect_err("decode should fail");

        let message = error.to_string();
        assert!(message.contains("simulated decode failure"));
        assert!(message.contains("retained ETL file at"));
        assert!(message.contains(&etl_path.to_string_lossy().into_owned()));
        assert!(etl_path.exists());
        assert!(!output_path.exists());
    }

    #[test]
    fn requested_etl_retention_cleans_directory_when_seal_fails() {
        let parent = tempfile::tempdir().expect("temp parent");
        let directory = parent.path().join("managed");
        std::fs::create_dir(&directory).expect("managed directory");
        let etl_path = directory.join("capture.etl");

        let error = finalize_capture_seal_failure::<CaptureDenialsOutput>(
            std::io::Error::other("simulated seal failure"),
            Some(&etl_path),
            Some(&directory),
        )
        .expect_err("seal failure should propagate");

        assert!(error.to_string().contains("simulated seal failure"));
        assert!(!error.to_string().contains("retained ETL file at"));
        assert!(!directory.exists());
    }

    #[test]
    fn abandoned_capture_discards_without_sealing_output() {
        struct DiscardRecordingSession {
            discarded: Arc<std::sync::atomic::AtomicBool>,
        }

        impl CaptureSessionOps for DiscardRecordingSession {
            fn environment(&self) -> HANDLE {
                HANDLE(std::ptr::dangling_mut())
            }

            fn finish(
                self: Box<Self>,
                output_path: Option<&Path>,
            ) -> Result<(), crate::learning_mode_windows::LearningModeError> {
                self.discarded
                    .store(output_path.is_none(), Ordering::SeqCst);
                Ok(())
            }
        }

        let parent = tempfile::tempdir().expect("temp parent");
        let directory = parent.path().join("managed");
        std::fs::create_dir(&directory).expect("managed directory");
        let managed_capture = ManagedCapturePath {
            etl_path: directory.join("capture.etl"),
            directory: directory.clone(),
            armed: true,
        };
        let discarded = Arc::new(std::sync::atomic::AtomicBool::new(false));

        discard_abandoned_capture(
            Box::new(DiscardRecordingSession {
                discarded: Arc::clone(&discarded),
            }),
            Some(managed_capture),
        )
        .expect("discard capture");

        assert!(discarded.load(Ordering::SeqCst));
        assert!(!directory.exists());
    }

    #[test]
    fn successful_process_reports_capture_teardown_failure() {
        let error =
            combine_process_and_teardown_results(Ok(0), Err(std::io::Error::other("seal failed")))
                .expect_err("capture failure must override successful process exit");

        assert!(error.to_string().contains("seal failed"));
    }

    #[test]
    fn wait_and_capture_failures_preserve_retained_etl_path() {
        let error = combine_process_and_teardown_results(
            Err(std::io::Error::new(
                std::io::ErrorKind::TimedOut,
                "script timed out after 1000ms",
            )),
            Err(std::io::Error::other(
                r"decode failed; retained ETL file at C:\Temp\capture.etl",
            )),
        )
        .expect_err("both failures should be reported");

        assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
        let message = error.to_string();
        assert!(message.contains("script timed out after 1000ms"));
        assert!(message.contains("decode failed"));
        assert!(message.contains(r"C:\Temp\capture.etl"));
    }

    #[test]
    fn is_api_not_implemented_classifies_disabled_feature() {
        assert!(is_api_not_implemented(ERROR_CALL_NOT_IMPLEMENTED.0));
        assert!(is_api_not_implemented(E_NOTIMPL.0 as u32));
        // ERROR_INVALID_PARAMETER and success are not disabled-feature failures.
        assert!(!is_api_not_implemented(87));
        assert!(!is_api_not_implemented(0));
    }

    #[test]
    fn capture_factory_injects_begin_failure() {
        let factory = Arc::new(FakeCaptureFactory {
            trace_sources: LearningModeTraceSources::AccessAndNetwork,
            begin_error: Some((
                "StartLearningModeTrace",
                windows::Win32::Foundation::E_FAIL.0,
            )),
            finish_error: None,
            begin_calls: AtomicUsize::new(0),
            finish_calls: Arc::new(AtomicUsize::new(0)),
        });
        let runner = BaseContainerRunner::with_capture_factory(factory.clone());

        let error = match runner
            .capture_factory
            .begin(&[], PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE)
        {
            Ok(_) => panic!("fake begin must fail"),
            Err(error) => error,
        };

        assert!(error.to_string().contains("StartLearningModeTrace"));
        assert_eq!(factory.begin_calls.load(Ordering::SeqCst), 1);
        assert_eq!(factory.finish_calls.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn capture_factory_injects_finish_failure_once() {
        let factory = Arc::new(FakeCaptureFactory {
            trace_sources: LearningModeTraceSources::AccessAndNetwork,
            begin_error: None,
            finish_error: Some((
                "StopLearningModeTrace",
                windows::Win32::Foundation::E_FAIL.0,
            )),
            begin_calls: AtomicUsize::new(0),
            finish_calls: Arc::new(AtomicUsize::new(0)),
        });
        let runner = BaseContainerRunner::with_capture_factory(factory.clone());
        let session = runner
            .capture_factory
            .begin(&[], PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE)
            .expect("fake begin");

        let error = session.finish(None).expect_err("fake finish must fail");

        assert!(matches!(
            error,
            crate::learning_mode_windows::LearningModeError::HResultCall {
                function: "StopLearningModeTrace",
                ..
            }
        ));
        assert_eq!(factory.begin_calls.load(Ordering::SeqCst), 1);
        assert_eq!(factory.finish_calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn validate_runner_rejects_a_sparse_verbatim_environment_before_host_probes() {
        let runner = BaseContainerRunner::new();
        let request = ExecutionRequest {
            env: Some(vec!["SystemRoot=C:\\Windows".to_string()]),
            ..Default::default()
        };

        let error = runner
            .validate(&request)
            .expect_err("BaseContainer must reject the environment before launch");
        assert_eq!(error.failure_phase, FailurePhase::Rejected);
        assert!(error.error_message.contains("LOCALAPPDATA"));
    }

    #[test]
    fn runtime_proxy_builds_psec_environment() {
        let mut request = ExecutionRequest::default();
        request.policy.runtime_network_proxy_specified = true;
        request.policy.network_proxy = ProxyConfig {
            address: Some(ProxyAddress::new("127.0.0.1".to_string(), 8080)),
        };
        request.env = Some(vec!["PATH=C:\\Windows".to_string()]);

        let environment = build_child_env_block(&request)
            .expect("environment")
            .expect("runtime proxy environment");
        let rendered = String::from_utf16_lossy(&environment);
        assert!(rendered.contains("PATH=C:\\Windows"));
        assert!(rendered.contains("HTTP_PROXY=http://127.0.0.1:8080"));
        assert!(rendered.contains("HTTPS_PROXY=http://127.0.0.1:8080"));
    }

    #[test]
    fn absent_env_yields_the_default_user_environment() {
        // No caller environment: the child must get a populated default block,
        // not an empty one.
        let request = ExecutionRequest::default();
        assert!(request.env.is_none());

        let environment = build_child_env_block(&request)
            .expect("environment")
            .expect("PSEC always needs an explicit block");
        let rendered = String::from_utf16_lossy(&environment);
        assert!(
            rendered.len() > 2,
            "default block should carry the user profile variables"
        );
    }

    #[test]
    fn explicitly_empty_env_yields_an_empty_block_not_the_default() {
        // `"env": []` is a request for an empty environment. It must not be
        // silently upgraded to the default profile block.
        let request = ExecutionRequest {
            env: Some(Vec::new()),
            ..Default::default()
        };

        let environment = build_child_env_block(&request)
            .expect("environment")
            .expect("an explicitly empty env must still produce a block");
        assert_eq!(
            environment.len(),
            2,
            "an empty block still requires two terminators"
        );
        assert_eq!(environment, vec![0u16, 0u16]);
    }

    #[test]
    fn supplied_env_is_used_verbatim() {
        // MXC adds nothing to a caller-supplied environment -- notably not the
        // variables Windows requires to be present. A caller that replaces the
        // block owns its contents; a missing requirement surfaces as an
        // actionable launch error instead.
        let request = ExecutionRequest {
            env: Some(vec!["MYVAR=hello".to_string()]),
            ..Default::default()
        };

        let environment = build_child_env_block(&request)
            .expect("environment")
            .expect("explicit block");
        let rendered = String::from_utf16_lossy(&environment);

        assert!(rendered.contains("MYVAR=hello"));
        assert!(!rendered.to_ascii_uppercase().contains("SYSTEMROOT"));
        assert!(!rendered.to_ascii_uppercase().contains("LOCALAPPDATA"));
    }

    #[test]
    fn inherit_default_env_layers_the_caller_entries_on_the_default_block() {
        // `inheritDefaultEnv` is how a caller asks for "the profile block plus
        // these": the defaults must survive, and a caller entry must replace
        // the same-named default rather than being appended alongside it.
        let request = ExecutionRequest {
            env: Some(vec![
                "MYVAR=hello".to_string(),
                "systemroot=C:\\Override".to_string(),
            ]),
            inherit_default_env: true,
            ..Default::default()
        };

        let environment = build_child_env_block(&request)
            .expect("environment")
            .expect("explicit block");
        let rendered = String::from_utf16_lossy(&environment);

        assert!(rendered.contains("MYVAR=hello"));
        assert!(rendered.to_ascii_uppercase().contains("LOCALAPPDATA"));
        assert!(rendered.contains("systemroot=C:\\Override"));
        assert_eq!(
            rendered.to_ascii_uppercase().matches("SYSTEMROOT=").count(),
            1,
            "a caller entry must replace the default, not duplicate it"
        );
    }

    #[test]
    fn build_process_security_environment_spec_produces_valid_psec() {
        let mut request = ExecutionRequest::default();
        request.policy.capabilities = vec!["internetClient".into(), "registryRead".into()];
        request.policy.readwrite_paths = vec!["C:\\temp".into()];
        request.policy.readonly_paths = vec!["C:\\Windows".into()];
        request.policy.denied_paths = vec!["C:\\secret".into()];

        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);

        assert!(psec_layout::process_security_environment_buffer_has_identifier(&bytes));
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
        let version = spec.version();
        assert_eq!(version.major(), 1);
        assert_eq!(version.minor(), 0);
        assert_eq!(spec.capabilities(), Some("internetClient,registryRead"));
        assert!(spec.disallow_win32k_system_calls());
        assert_eq!(
            spec.ui_restrictions(),
            expected_mask(EffectiveUiRestrictions {
                block_clipboard_read: true,
                block_clipboard_write: true,
                block_input_injection: true,
                block_input_method_changes: true,
                block_external_ui_objects: true,
                block_global_ui_namespace: true,
                block_desktop_switching: true,
                block_logoff_or_shutdown: true,
                block_system_parameter_changes: true,
                block_display_settings_changes: true,
            })
        );
        assert_eq!(
            spec.fs_read_write().unwrap().iter().collect::<Vec<_>>(),
            vec!["C:\\temp"]
        );
        assert_eq!(
            spec.fs_read_only().unwrap().iter().collect::<Vec<_>>(),
            vec!["C:\\Windows"]
        );
        assert_eq!(
            spec.fs_deny().unwrap().iter().collect::<Vec<_>>(),
            vec!["C:\\secret"]
        );
        let egress = spec
            .network_policy()
            .and_then(|policy| policy.egress())
            .expect("PSEC must carry an explicit egress default");
        assert_eq!(egress.default_action(), psec_layout::FilterAction::deny);
        assert!(egress.allow().is_none());
        assert!(egress.deny().is_none());
    }

    #[test]
    fn permissive_ui_policy_serializes_no_tier1_ui_restrictions() {
        let mut request = ExecutionRequest::default();
        request.policy.ui = UiPolicy {
            disable: false,
            clipboard: ClipboardPolicy::All,
            injection: true,
        };
        request.policy.base_process_ui = BaseProcessUiConfig {
            isolation: "desktop".to_string(),
            desktop_system_control: true,
            system_settings: "all".to_string(),
            ime: true,
        };

        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();

        assert!(!spec.disallow_win32k_system_calls());
        assert_eq!(spec.ui_restrictions(), 0);
    }

    #[test]
    fn build_process_security_environment_spec_serializes_enumerate_paths_as_v1_1() {
        let mut request = ExecutionRequest::default();
        request.policy.enumerate_paths = vec!["C:\\tools".into()];

        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();

        assert_eq!(spec.version().major(), 1);
        assert_eq!(spec.version().minor(), 1);
        assert_eq!(
            spec.fs_enumerate().unwrap().iter().collect::<Vec<_>>(),
            vec!["C:\\tools"]
        );
    }

    #[test]
    fn capture_denials_directional_default_deny_reaches_tessera_network_policy() {
        let mut request = ExecutionRequest::default();
        request.policy.capture_denials = Some(Default::default());
        request.policy.network_egress = Some(NetworkEgressPolicy {
            default: NetworkAction::Deny,
            ..Default::default()
        });

        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
        let egress = spec
            .network_policy()
            .and_then(|policy| policy.egress())
            .expect("PSEC must carry the Tessera egress policy");

        assert_eq!(spec.capabilities(), Some("internetClient"));
        assert_eq!(egress.default_action(), psec_layout::FilterAction::deny);
    }

    #[test]
    fn capture_capability_requires_a_network_aware_trace() {
        let mut request = ExecutionRequest::default();
        request.policy.capture_denials = Some(Default::default());
        request.policy.network_egress = Some(NetworkEgressPolicy {
            default: NetworkAction::Deny,
            ..Default::default()
        });

        for (trace_sources, capture_enabled, expected_capabilities) in [
            (LearningModeTraceSources::AccessOnly, true, None),
            (
                LearningModeTraceSources::AccessAndNetwork,
                true,
                Some("internetClient"),
            ),
            (LearningModeTraceSources::AccessOnly, false, None),
            (LearningModeTraceSources::AccessAndNetwork, false, None),
        ] {
            request.policy.capture_denials = capture_enabled.then(Default::default);
            let factory = Arc::new(FakeCaptureFactory {
                trace_sources,
                begin_error: None,
                finish_error: None,
                begin_calls: AtomicUsize::new(0),
                finish_calls: Arc::new(AtomicUsize::new(0)),
            });
            let runner = BaseContainerRunner::with_capture_factory(factory);
            let bytes = runner
                .build_capture_aware_security_environment_spec(
                    &request,
                    SecurityEnvironmentVersion::V1_0,
                )
                .unwrap();
            let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();

            assert_eq!(spec.capabilities(), expected_capabilities);
            let egress = spec.network_policy().unwrap().egress().unwrap();
            assert_eq!(egress.default_action(), psec_layout::FilterAction::deny);
            assert!(egress.allow().is_none());
            assert!(egress.deny().is_none());
        }
    }

    #[test]
    fn capture_capability_requires_an_explicit_direct_egress_section() {
        for (network, expected_capabilities) in [
            (None, None),
            (
                Some(wire::Network {
                    egress: None,
                    ingress: Some(wire::NetworkIngress {
                        default: Some(wire::NetworkAction::Deny),
                        host_loopback: Some(wire::NetworkAction::Deny),
                    }),
                }),
                None,
            ),
            (
                Some(wire::Network {
                    egress: Some(wire::NetworkEgress {
                        default: Some(wire::NetworkAction::Deny),
                        allow: None,
                        deny: None,
                    }),
                    ingress: None,
                }),
                Some("internetClient"),
            ),
        ] {
            let mut request = ExecutionRequest::default();
            request.policy.capture_denials = Some(Default::default());
            parse_network_policy(
                &mut request.policy,
                NetworkSections {
                    network,
                    runtime: None,
                    process_container: None,
                },
                &ContainmentBackend::ProcessContainer,
            )
            .unwrap();

            let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
            let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
            let egress = spec
                .network_policy()
                .and_then(|policy| policy.egress())
                .expect("PSEC must retain deny-default egress");

            assert_eq!(spec.capabilities(), expected_capabilities);
            assert_eq!(egress.default_action(), psec_layout::FilterAction::deny);
        }
    }

    #[test]
    fn directional_default_deny_without_capture_does_not_add_internet_capability() {
        let mut request = ExecutionRequest::default();
        request.policy.network_egress = Some(NetworkEgressPolicy {
            default: NetworkAction::Deny,
            ..Default::default()
        });

        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
        let egress = spec
            .network_policy()
            .and_then(|policy| policy.egress())
            .expect("PSEC must retain deny-default egress");

        assert!(spec.capabilities().is_none());
        assert_eq!(egress.default_action(), psec_layout::FilterAction::deny);
    }

    #[test]
    fn capture_denials_proxy_preserves_proxy_capability_posture() {
        let mut request = ExecutionRequest::default();
        request.policy.capture_denials = Some(Default::default());
        request.policy.runtime_network_proxy_specified = true;
        request.policy.network_proxy = ProxyConfig {
            address: Some(ProxyAddress::new("127.0.0.1".to_string(), 8080)),
        };
        request.policy.network_egress = Some(NetworkEgressPolicy {
            default: NetworkAction::Deny,
            ..Default::default()
        });
        request.policy.network_ingress = Some(NetworkIngressPolicy {
            default: NetworkAction::Allow,
            host_loopback: NetworkAction::Allow,
        });

        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();

        assert_eq!(
            spec.capabilities(),
            Some("privateNetworkClientServer,networkLoopback")
        );
        assert!(spec
            .capabilities()
            .is_none_or(|capabilities| !capabilities.contains("internetClient")));
        assert!(spec
            .network_policy()
            .and_then(|network| network.proxy())
            .is_some());
    }

    #[test]
    fn build_process_security_environment_spec_ignores_empty_capability() {
        let mut request = ExecutionRequest::default();
        request.policy.capabilities = vec![String::new()];
        request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: NetworkAction::Allow,
            ..Default::default()
        });

        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();

        assert_eq!(spec.capabilities(), Some("internetClient"));
    }

    #[test]
    fn build_process_security_environment_spec_preserves_implicit_deny_egress() {
        let request = ExecutionRequest::default();

        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
        let egress = spec
            .network_policy()
            .and_then(|policy| policy.egress())
            .expect("PSEC must carry an explicit egress default");

        assert_eq!(egress.default_action(), psec_layout::FilterAction::deny);
        assert!(spec.capabilities().is_none());
    }

    #[test]
    fn build_process_security_environment_spec_preserves_directional_allow_egress() {
        let mut request = ExecutionRequest::default();
        request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: NetworkAction::Allow,
            ..Default::default()
        });

        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
        let egress = spec
            .network_policy()
            .and_then(|policy| policy.egress())
            .expect("PSEC must carry an explicit egress default");

        assert_eq!(egress.default_action(), psec_layout::FilterAction::allow);
        assert_eq!(spec.capabilities(), Some("internetClient"));
    }

    #[test]
    fn psec_direct_host_loopback_encodes_capability_and_peer() {
        let mut request = host_loopback_request();
        request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: NetworkAction::Allow,
            ..Default::default()
        });

        for version in [
            SecurityEnvironmentVersion::V1_0,
            SecurityEnvironmentVersion::V1_1,
        ] {
            for (default, capabilities) in [
                (
                    NetworkAction::Allow,
                    "internetClient,privateNetworkClientServer,networkLoopback",
                ),
                (NetworkAction::Deny, "internetClient,networkLoopback"),
            ] {
                request.policy.network_ingress.as_mut().unwrap().default = default;
                request.policy.enumerate_paths = if version == SecurityEnvironmentVersion::V1_1 {
                    vec!["C:\\tools".to_string()]
                } else {
                    Vec::new()
                };
                let bytes = build_psec_v1_security_environment_spec(&request, version, false);
                let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
                let network = spec.network_policy().unwrap();

                assert_eq!(spec.version().minor(), version.minor);
                assert_eq!(spec.capabilities(), Some(capabilities));
                assert_eq!(
                network.allowed_appcontainer_peer(),
                Some(
                    crate::process_container_common::base_container_helpers::LOOPBACK_NETWORK_PEER
                )
            );
                assert_eq!(spec.fs_enumerate().is_some(), version.minor == 1);
                assert!(network.ingress().is_none());
                assert!(network.proxy().is_none());
                assert_eq!(
                    network.egress().unwrap().default_action(),
                    psec_layout::FilterAction::allow
                );
            }
        }
    }

    #[test]
    fn psec_direct_host_loopback_default_and_explicit_deny_do_not_grant_loopback() {
        for ingress in [
            None,
            Some(crate::mxc_common::models::NetworkIngressPolicy {
                default: NetworkAction::Allow,
                host_loopback: NetworkAction::Deny,
            }),
        ] {
            let mut request = ExecutionRequest::default();
            request.policy.network_ingress = ingress;
            for version in [
                SecurityEnvironmentVersion::V1_0,
                SecurityEnvironmentVersion::V1_1,
            ] {
                let bytes = build_psec_v1_security_environment_spec(&request, version, false);
                let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();

                assert!(!spec
                    .capabilities()
                    .unwrap_or_default()
                    .split(',')
                    .any(|capability| capability == "networkLoopback"));
                assert!(spec
                    .network_policy()
                    .unwrap()
                    .allowed_appcontainer_peer()
                    .is_none());
            }
        }
    }

    #[test]
    fn required_psec_contract_uses_v1_1_for_enumeration() {
        for mut request in [host_loopback_request(), identityless_proxy_request()] {
            request.policy.enumerate_paths = enumerate_request().policy.enumerate_paths;
            assert_eq!(
                BaseContainerRunner::choose_min_required_psec_version_for_request(&request),
                SecurityEnvironmentVersion::V1_1
            );
        }
    }

    #[test]
    fn loopback_and_proxy_do_not_raise_minimum_psec_version() {
        let _guard = crate::process_container_common::test_env::BcUsableGuard::set(true);
        for request in [host_loopback_request(), identityless_proxy_request()] {
            assert!(
                BaseContainerRunner::can_backend_service_request(&request).can_service_request()
            );
            assert_eq!(
                BaseContainerRunner::choose_min_required_psec_version_for_request(&request),
                SecurityEnvironmentVersion::V1_0
            );
        }
    }

    #[test]
    fn required_psec_contract_defaults_to_v1_0() {
        assert_eq!(
            BaseContainerRunner::choose_min_required_psec_version_for_request(
                &ExecutionRequest::default(),
            ),
            SecurityEnvironmentVersion::V1_0
        );
    }

    fn identityless_proxy_request() -> ExecutionRequest {
        let mut request = host_loopback_request();
        request.policy.runtime_network_proxy_specified = true;
        request.policy.network_proxy = ProxyConfig {
            address: Some(ProxyAddress::new("127.0.0.1".to_string(), 8080)),
        };
        request
    }

    #[test]
    fn identityless_loopback_proxy_requires_base_container_api() {
        let _guard = crate::process_container_common::test_env::BcUsableGuard::set(false);
        assert!(!BaseContainerRunner::supports_identityless_loopback_proxy().unwrap());
    }

    #[test]
    #[should_panic(
        expected = "build_psec_v1_security_environment_spec only supports PSEC major version 1"
    )]
    fn psec_v1_builder_rejects_other_major_versions() {
        build_psec_v1_security_environment_spec(
            &ExecutionRequest::default(),
            SecurityEnvironmentVersion { major: 2, minor: 0 },
            false,
        );
    }

    #[test]
    fn psec_enumeration_omits_ingress_table() {
        let request = enumerate_request();
        let bytes = build_psec_v1_security_environment_spec(
            &request,
            SecurityEnvironmentVersion::V1_1,
            false,
        );
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();

        assert_eq!(spec.version().minor(), 1);
        assert!(spec.network_policy().unwrap().ingress().is_none());
    }

    #[test]
    fn psec_ingress_default_allow_uses_private_network_capability() {
        let mut request = ExecutionRequest::default();
        request.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy {
            default: NetworkAction::Allow,
            host_loopback: NetworkAction::Deny,
        });
        request.policy.allowed_proxy_peer = Some("S-1-15-2-1".into());

        for version in [
            SecurityEnvironmentVersion::V1_0,
            SecurityEnvironmentVersion::V1_1,
        ] {
            let bytes = build_psec_v1_security_environment_spec(&request, version, false);
            let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
            let network = spec.network_policy().expect("network policy");

            assert_eq!(spec.version().minor(), version.minor);
            assert_eq!(
                spec.capabilities(),
                Some(
                    crate::process_container_common::network_policy_helpers::PRIVATE_NETWORK_CAPABILITY
                )
            );
            assert_eq!(network.allowed_appcontainer_peer(), Some("S-1-15-2-1"));
            assert!(network.ingress().is_none());
        }
    }

    #[test]
    fn psec_proxy_and_direct_egress_forms_are_mutually_exclusive() {
        for runtime_proxy_specified in [false, true] {
            let mut request = ExecutionRequest::default();
            request.policy.runtime_network_proxy_specified = runtime_proxy_specified;
            request.policy.network_proxy = ProxyConfig {
                address: Some(ProxyAddress::new("127.0.0.1".to_string(), 8080)),
            };
            request.policy.allowed_proxy_peer = Some("Contoso.Proxy_12345".to_string());

            let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
            let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
            let network = spec.network_policy().expect("network policy");
            assert_eq!(
                network.proxy().and_then(|proxy| proxy.url()),
                Some("http://127.0.0.1:8080")
            );
            assert_eq!(
                network.allowed_appcontainer_peer(),
                Some("Contoso.Proxy_12345")
            );
            assert!(network.egress().is_none());
        }

        let request = ExecutionRequest::default();
        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
        let network = spec.network_policy().expect("network policy");
        assert!(network.proxy().is_none());
        assert!(network.egress().is_some());
    }

    fn request_with_rich_network_rules() -> ExecutionRequest {
        let mut request = ExecutionRequest::default();
        request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: NetworkAction::Deny,
            allow: vec![NetworkRule {
                to: vec![
                    NetworkPeer {
                        cidr: NetworkCidr {
                            address: "10.0.0.0".parse().unwrap(),
                            prefix_length: 8,
                        },
                        except: vec![NetworkCidr {
                            address: "10.1.0.0".parse().unwrap(),
                            prefix_length: 16,
                        }],
                    },
                    NetworkPeer {
                        cidr: NetworkCidr {
                            address: "2001:db8::".parse().unwrap(),
                            prefix_length: 32,
                        },
                        except: Vec::new(),
                    },
                ],
                ports: vec![NetworkPort {
                    protocol: NetworkProtocol::Icmp,
                    port: None,
                    end_port: None,
                }],
            }],
            deny: vec![NetworkRule {
                to: Vec::new(),
                ports: vec![NetworkPort {
                    protocol: NetworkProtocol::Tcp,
                    port: Some(8000),
                    end_port: Some(8080),
                }],
            }],
        });
        request
    }

    #[test]
    fn build_process_security_environment_spec_preserves_rich_network_rules() {
        let request = request_with_rich_network_rules();
        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
        let egress = spec
            .network_policy()
            .and_then(|policy| policy.egress())
            .expect("egress policy");

        assert_eq!(spec.capabilities(), Some("internetClient"));
        let allow = egress.allow().expect("allow rules");
        assert_eq!(allow.len(), 2, "ICMP must expand by address family");
        assert_eq!(
            allow.get(0).ports().unwrap().get(0).protocol(),
            psec_layout::IpProtocol::icmpv4
        );
        let ipv4_destination = allow.get(0).destinations().unwrap().get(0);
        assert_eq!(
            ipv4_destination.subnet().unwrap().address(),
            Some("10.0.0.0")
        );
        assert_eq!(
            ipv4_destination.except().unwrap().get(0).address(),
            Some("10.1.0.0")
        );
        assert_eq!(
            allow.get(1).ports().unwrap().get(0).protocol(),
            psec_layout::IpProtocol::icmpv6
        );
        assert_eq!(
            allow
                .get(1)
                .destinations()
                .unwrap()
                .get(0)
                .subnet()
                .unwrap()
                .address(),
            Some("2001:db8::")
        );

        let denied_port = egress.deny().unwrap().get(0).ports().unwrap().get(0);
        assert_eq!(denied_port.protocol(), psec_layout::IpProtocol::tcp);
        assert_eq!(denied_port.port(), 8000);
        assert_eq!(denied_port.end_port(), 8080);
    }

    #[test]
    fn build_process_security_environment_spec_splits_mixed_icmp_rules() {
        let mut request = ExecutionRequest::default();
        request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: NetworkAction::Deny,
            allow: vec![NetworkRule {
                to: Vec::new(),
                ports: vec![
                    NetworkPort {
                        protocol: NetworkProtocol::Tcp,
                        port: Some(443),
                        end_port: None,
                    },
                    NetworkPort {
                        protocol: NetworkProtocol::Icmp,
                        port: None,
                        end_port: None,
                    },
                ],
            }],
            deny: Vec::new(),
        });

        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
        let allow = spec
            .network_policy()
            .and_then(|policy| policy.egress())
            .and_then(|egress| egress.allow())
            .expect("allow rules");

        assert_eq!(allow.len(), 3);
        assert_eq!(
            allow.get(0).ports().unwrap().get(0).protocol(),
            psec_layout::IpProtocol::tcp
        );
        assert_eq!(
            allow.get(1).ports().unwrap().get(0).protocol(),
            psec_layout::IpProtocol::icmpv4
        );
        assert_eq!(
            allow.get(2).ports().unwrap().get(0).protocol(),
            psec_layout::IpProtocol::icmpv6
        );
    }

    #[test]
    fn build_process_security_environment_spec_limits_icmp_to_destination_family() {
        for (cidr, expected_protocol) in [
            ("10.0.0.0/8", psec_layout::IpProtocol::icmpv4),
            ("2001:db8::/32", psec_layout::IpProtocol::icmpv6),
        ] {
            let (address, prefix_length) = cidr.split_once('/').unwrap();
            let mut request = ExecutionRequest::default();
            request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
                default: NetworkAction::Deny,
                allow: vec![NetworkRule {
                    to: vec![NetworkPeer {
                        cidr: NetworkCidr {
                            address: address.parse().unwrap(),
                            prefix_length: prefix_length.parse().unwrap(),
                        },
                        except: Vec::new(),
                    }],
                    ports: vec![NetworkPort {
                        protocol: NetworkProtocol::Icmp,
                        port: None,
                        end_port: None,
                    }],
                }],
                deny: Vec::new(),
            });

            let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
            let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
            let allow = spec
                .network_policy()
                .and_then(|policy| policy.egress())
                .and_then(|egress| egress.allow())
                .expect("allow rules");

            assert_eq!(allow.len(), 1, "{cidr} must emit one ICMP family");
            assert_eq!(
                allow.get(0).ports().unwrap().get(0).protocol(),
                expected_protocol
            );
        }
    }

    #[test]
    fn build_process_security_environment_spec_preserves_all_port_destinations() {
        let peer = NetworkPeer {
            cidr: NetworkCidr {
                address: "10.0.0.0".parse().unwrap(),
                prefix_length: 8,
            },
            except: Vec::new(),
        };
        let mut request = ExecutionRequest::default();
        request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: NetworkAction::Deny,
            allow: vec![NetworkRule {
                to: vec![peer.clone()],
                ports: Vec::new(),
            }],
            deny: vec![NetworkRule {
                to: vec![peer],
                ports: Vec::new(),
            }],
        });

        let bytes = BaseContainerRunner::build_process_security_environment_spec(&request);
        let spec = psec_layout::root_as_process_security_environment(&bytes).unwrap();
        let egress = spec
            .network_policy()
            .and_then(|policy| policy.egress())
            .expect("egress policy");

        for rule in [
            egress.allow().unwrap().get(0),
            egress.deny().unwrap().get(0),
        ] {
            assert!(rule.ports().is_none(), "empty ports means all ports");
            assert_eq!(
                rule.destinations()
                    .unwrap()
                    .get(0)
                    .subnet()
                    .unwrap()
                    .address(),
                Some("10.0.0.0")
            );
        }
    }

    #[test]
    fn conflicting_proxy_identity_table() {
        for allowed_proxy_peer in [false, true] {
            for host_loopback in [NetworkAction::Deny, NetworkAction::Allow] {
                let mut policy = ContainerPolicy {
                    network_ingress: Some(crate::mxc_common::models::NetworkIngressPolicy {
                        default: NetworkAction::Allow,
                        host_loopback,
                    }),
                    ..Default::default()
                };
                if allowed_proxy_peer {
                    policy.allowed_proxy_peer = Some("Contoso.Proxy_123".to_string());
                }

                assert_eq!(
                    has_conflicting_proxy_identity(&policy),
                    allowed_proxy_peer && host_loopback == NetworkAction::Allow
                );
            }
        }
    }

    #[test]
    fn validate_rejects_conflicting_proxy_identity_paths() {
        let runner = BaseContainerRunner::with_capture_factory(fake_capture_factory());
        let mut request = ExecutionRequest {
            dry_run: true,
            ..Default::default()
        };
        request.policy.allowed_proxy_peer = Some("Contoso.Proxy_123".to_string());
        request.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy {
            default: NetworkAction::Allow,
            host_loopback: NetworkAction::Allow,
        });

        let error = runner
            .validate(&request)
            .expect_err("proxy peer identity and host loopback are mutually exclusive");
        assert_eq!(
            error.error_message,
            "processContainer.network.allowedProxyPeer grants loopback access only to the \
             specified peer and cannot be combined with \
             network.ingress.hostLoopback='allow', which grants unrestricted host-loopback access"
        );
    }

    #[test]
    fn legacy_proxy_is_not_psec_compatible() {
        let mut request = ExecutionRequest::default();
        request.policy.network_proxy = ProxyConfig {
            address: Some(ProxyAddress::new("127.0.0.1".to_string(), 8080)),
        };

        assert!(
            !BaseContainerRunner::can_backend_service_request(&request).can_service_request(),
            "legacy proxy requests must fall through to an AppContainer tier"
        );
    }

    #[test]
    fn capture_runtime_proxy_uses_native_contract() {
        let _guard =
            crate::process_container_common::test_env::CaptureCapabilityGuard::set(true, true);
        let mut request = ExecutionRequest::default();
        request.policy.capture_denials = Some(Default::default());
        request.policy.runtime_network_proxy_specified = true;
        request.policy.network_proxy = ProxyConfig {
            address: Some(ProxyAddress::new("127.0.0.1".to_string(), 8080)),
        };
        assert!(BaseContainerRunner::can_backend_service_request(&request).can_service_request());
    }

    // ---- validate_runner: unsupported policy fields surface as errors. ----

    use crate::mxc_common::sandbox_process::SandboxBackend;

    #[test]
    fn validate_runner_accepts_empty_policy() {
        let runner = BaseContainerRunner::new();
        let request = ExecutionRequest::default();
        // validate_runner may still surface the host-API-unavailable error on
        // dev machines where BaseContainer isn't present; we only assert that
        // the policy-field checks above don't fire. Skip when the host doesn't
        // expose the API.
        if BaseContainerRunner::is_base_container_api_present() {
            assert!(runner.validate(&request).is_ok());
        }
    }

    // ETL-retention capability validation (the retainEtl gate, including the
    // BaseContainer native-PSEC exception) is exercised as a consolidated
    // matrix in `crate::guarded_capture`'s tests, so it is not duplicated here.
}