mxc-sdk 1.2.0

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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Builder that converts an [`ExecutionRequest`] into a TinyScheme sandbox
//! profile string suitable for `sandbox_init()` or `sandbox-exec -p <profile>`.
//!
//! Pure profile generation, unit-tested on every host. Filesystem and environment
//! discovery happen before this module receives its inputs.
//!
//! # Profile shape
//!
//! The generated profile follows a deny-by-default baseline with explicit
//! allow rules layered on top, then explicit deny rules at the end so that
//! `deniedPaths` overrides any broader `readonly`/`readwrite` allow:
//!
//! ```text
//! (version 1)
//! (deny default)
//! ;; baseline allow rules required for any process to start ...
//! ;; policy-derived allow rules (filesystem readonly/readwrite, network) ...
//! ;; policy-derived deny rules (deniedPaths) ...
//! ```
//!
//! Apple's Seatbelt sandbox evaluates rules with last-match-wins semantics (within a given
//! operation), so trailing deny rules take precedence over earlier allow
//! rules — the behavior callers expect from MXC's `denied_paths`.
//!
//! With `seatbelt.captureDenials`, every deny rule carries the run's
//! `(with message "<tag>")` so its log entries can be attributed to this run.
//! Allow mode swaps `(deny default)` for `(allow default (with report) ...)`,
//! reports instead of enforcing the denies of settings the request omitted,
//! and makes the broad guiAccess grants report under `<tag>:grant`.

use crate::mxc_common::filesystem_resolve::{resolve_path_plan, FsIntent, ResolvedMount};
use crate::mxc_common::host_is_canonical_loopback;
use crate::mxc_common::models::{
    CaptureDenialsMode, ClipboardPolicy, ContainerPolicy, ExecutionRequest, ProxyAddress,
    SeatbeltCustomPosixShm, SeatbeltCustomRules, SeatbeltPosixShmAccess,
};
use crate::seatbelt_common::seatbelt_policy::{self, NamePattern};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};

/// Prepared filesystem grants for profile generation.
#[derive(Debug, Default)]
pub struct ProfileInputs {
    pub readonly_paths: Vec<String>,
    pub readwrite_paths: Vec<String>,
    pub denied_paths: Vec<String>,
    pub developer_dir: Option<String>,
    pub user_keychains: Option<String>,
    /// Per-run log tag; required when `seatbelt.captureDenials` is set.
    pub capture_tag: Option<String>,
}

/// Suffix on the capture tag for accesses allowed by a broad guiAccess grant.
pub const GRANT_TAG_SUFFIX: &str = ":grant";

/// Capture settings resolved for one profile build.
struct CaptureRules<'a> {
    tag: &'a str,
    allow_mode: bool,
}

impl CaptureRules<'_> {
    fn grant_modifier(&self) -> String {
        format!(
            " (with report) (with message {})",
            quote_scheme(&format!("{}{GRANT_TAG_SUFFIX}", self.tag))
        )
    }
}

fn capture_rules<'a>(
    request: &ExecutionRequest,
    inputs: &'a ProfileInputs,
) -> Result<Option<CaptureRules<'a>>, ProfileError> {
    let Some(config) = request
        .seatbelt
        .as_ref()
        .and_then(|c| c.capture_denials.as_ref())
    else {
        return Ok(None);
    };
    let tag = inputs.capture_tag.as_deref().ok_or_else(|| {
        ProfileError::Host("Seatbelt: captureDenials log tag was not prepared".to_string())
    })?;
    Ok(Some(CaptureRules {
        tag,
        allow_mode: config.mode == CaptureDenialsMode::Allow,
    }))
}

/// Why a profile could not be built: the request, or the executor's host.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProfileError {
    /// The request names something the profile cannot express.
    Policy(String),
    /// The executor's environment lacks something the profile needs.
    Host(String),
}

impl std::fmt::Display for ProfileError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Policy(message) | Self::Host(message) => f.write_str(message),
        }
    }
}

/// Build a complete Seatbelt sandbox profile, scoping cooperative proxy
/// reachability to the resolved address supplied by the runner.
///
/// Paths come from `inputs`; profile generation never inspects the host.
///
/// Public to keep profile generation reachable on hosts without the macOS runner.
pub fn build_profile_with_proxy(
    request: &ExecutionRequest,
    proxy_address: Option<&ProxyAddress>,
    inputs: &ProfileInputs,
) -> Result<String, ProfileError> {
    build_profile_with_terminals(request, proxy_address, inputs, &[])
}

/// Bind terminal paths discovered by the runner, never supplied by the workload.
pub(crate) fn build_profile_with_terminals(
    request: &ExecutionRequest,
    proxy_address: Option<&ProxyAddress>,
    inputs: &ProfileInputs,
    terminal_paths: &[PathBuf],
) -> Result<String, ProfileError> {
    let seatbelt = request.seatbelt.as_ref();
    if let Some(override_profile) = seatbelt.and_then(|c| c.profile_override.as_ref()) {
        if seatbelt.is_some_and(|c| c.capture_denials.is_some()) {
            return Err(ProfileError::Policy(
                "Seatbelt: captureDenials cannot tag a profileOverride profile".to_string(),
            ));
        }
        return Ok(override_profile.clone());
    }
    let capture = capture_rules(request, inputs)?;

    let mut out = String::with_capacity(2048);

    // Capture allow mode replaces the normal deny-default baseline.
    out.push_str("(version 1)\n");
    match &capture {
        Some(rules) if rules.allow_mode => {
            let _ = writeln!(
                out,
                "(allow default (with report) (with message {}))",
                quote_scheme(rules.tag)
            );
        }
        _ => out.push_str("(deny default)\n"),
    }

    // Minimum allow rules so a child process can actually run. These are
    // the same things Apple's own built-in profiles (e.g. no-internet)
    // include: dyld + system libraries, mach-lookup of the basic agents,
    // sysctl reads, and signaling processes in the same sandbox.
    out.push_str(BASELINE_ALLOW);

    // Filesystem — read-only system paths every process needs.
    out.push_str(SYSTEM_READ_ALLOW);
    write_developer_dir_rule(&mut out, inputs.developer_dir.as_deref());

    // Keep the controlling terminal usable without granting other host PTYs.
    out.push_str(TTY_ALLOW);
    for path in terminal_paths {
        let path = path.to_str().ok_or_else(|| {
            ProfileError::Host("Seatbelt: assigned terminal path is not valid UTF-8".into())
        })?;
        let _ = writeln!(
            out,
            "(allow file-read* file-write* file-ioctl (literal {}))",
            quote_scheme(path)
        );
    }

    // Policy-derived allow rules. Setting folder grants follow them, so a
    // read-only parent folder doesn't block them; policy entries at or inside
    // a granted folder are then repeated so they still apply there.
    let resolved = ResolvedPaths::from_inputs(inputs);
    let plan = resolve_path_plan(&resolved.readwrite, &resolved.readonly, &[]);
    write_filesystem_allow(&mut out, FS_ALLOW_SECTION, &plan);
    write_keychain_rules(&mut out, request, inputs.user_keychains.as_deref())?;
    write_gui_filesystem_rules(&mut out, request);
    let granted = setting_write_folders(request, inputs.user_keychains.as_deref());
    let within_grants: Vec<_> = plan
        .into_iter()
        .filter(|mount| {
            granted
                .iter()
                .any(|folder| Path::new(&mount.path).starts_with(folder))
        })
        .collect();
    write_filesystem_allow(&mut out, FS_WITHIN_GRANTS_SECTION, &within_grants);
    write_network_rules(
        &mut out,
        request,
        proxy_address,
        capture.as_ref().is_some_and(|rules| rules.allow_mode),
    );
    write_nested_pty_rules(&mut out, request);
    write_ui_rules(&mut out, request, capture.as_ref());
    write_custom_allows(&mut out, request, capture.as_ref());

    // Setting denies follow every allow so no grant reopens them, except that
    // V1 extraMachLookups entries still reach the Keychain servers.
    write_keychain_denies(&mut out, request, capture.as_ref());
    write_extra_seatbelt_rules(&mut out, request);
    write_ui_policy_denies(&mut out, request, capture.as_ref());
    write_nested_pty_denies(&mut out, request);
    write_custom_denies(&mut out, request);

    // Policy-derived deny rules go LAST so they win on conflict.
    write_filesystem_deny(&mut out, &resolved);

    match capture {
        Some(rules) => Ok(tag_deny_rules(&out, rules.tag)),
        None => Ok(out),
    }
}

/// Adds `(with message "<tag>")` to every rule that starts with `(deny `,
/// right after its operation names. Lines that continue a quoted string, such
/// as a name containing a newline, are left unchanged.
fn tag_deny_rules(profile: &str, tag: &str) -> String {
    let modifier = format!(" (with message {})", quote_scheme(tag));
    let mut out = String::with_capacity(profile.len() + 256);
    let mut in_string = false;
    for line in profile.split_inclusive('\n') {
        let starts_in_string = in_string;
        in_string = ends_in_string(line, in_string);
        let Some(rest) = line.strip_prefix("(deny ").filter(|_| !starts_in_string) else {
            out.push_str(line);
            continue;
        };
        let ops_end = rest.find(['(', ')', '\n']).unwrap_or(rest.len());
        let ops = rest[..ops_end].trim_end();
        out.push_str("(deny ");
        out.push_str(ops);
        out.push_str(&modifier);
        out.push_str(&rest[ops.len()..]);
    }
    out
}

/// Whether a quoted string is still open at the end of `line`.
fn ends_in_string(line: &str, mut in_string: bool) -> bool {
    let mut chars = line.chars();
    while let Some(c) = chars.next() {
        match c {
            '\\' if in_string => {
                chars.next();
            }
            '"' => in_string = !in_string,
            ';' if !in_string => break,
            _ => {}
        }
    }
    in_string
}

/// Baseline allow rules required for any sandboxed process to start.
///
/// The unfiltered `(allow file-read-metadata)` is what path resolution needs —
/// the kernel reads metadata on every ancestor directory. `deniedPaths` names
/// `file-read-metadata` explicitly so it outranks this grant.
const BASELINE_ALLOW: &str = "\
;; --- baseline (required for any process to start) ---
(allow process-fork)
(allow process-exec)
(allow signal (target same-sandbox))
(allow sysctl-read)
(allow file-read-metadata)
(allow mach-lookup
    (global-name \"com.apple.system.notification_center\")
    (global-name \"com.apple.system.logger\")
    (global-name \"com.apple.distributed_notifications@Uv3\")
    (global-name \"com.apple.CoreServices.coreservicesd\")
    (global-name \"com.apple.FSEvents\"))
";

/// Read-only access to system paths required by virtually every binary
/// (dynamic linker, system libraries, time-zone data, etc.).
const SYSTEM_READ_ALLOW: &str = "\
;; --- read-only access to system locations ---
;; `/` itself must be readable as data so the shell / loader can resolve
;; path lookups; without this the kernel kills the child during exec.
(allow file-read-data (literal \"/\"))
(allow file-read*
    (subpath \"/bin\")
    (subpath \"/sbin\")
    (subpath \"/usr/bin\")
    (subpath \"/usr/sbin\")
    (subpath \"/usr/lib\")
    (subpath \"/usr/libexec\")
    (subpath \"/usr/share\")
    (subpath \"/System\")
    (subpath \"/Library\")
    (subpath \"/private/var/db/timezone\")
    (subpath \"/private/var/db/dyld\")
    (subpath \"/private/var/select\")
    (subpath \"/private/etc\"))
;; Standard bit-bucket / entropy devices — read+write because shell
;; redirections (`>/dev/null`, `</dev/urandom`) need both directions.
;; Writes to /dev/null and /dev/zero are discarded; /dev/random and
;; /dev/urandom write to the entropy pool, which is harmless.
(allow file-read* file-write*
    (literal \"/dev/null\")
    (literal \"/dev/zero\")
    (literal \"/dev/random\")
    (literal \"/dev/urandom\"))
";

/// Emit the read-only grant for the prepared developer directory.
fn write_developer_dir_rule(out: &mut String, developer_dir: Option<&str>) {
    let Some(path) = developer_dir else {
        return;
    };
    out.push_str(";; --- active developer directory (xcrun shims in /usr/bin) ---\n");
    let _ = writeln!(out, "(allow file-read* (subpath {}))", quote_scheme(path));
}

/// Controlling-terminal access and kernel-scoped access to newly allocated PTYs.
const TTY_ALLOW: &str = "\
;; --- controlling terminal and sandbox-allocated pseudo-terminals ---
(allow file-read* file-write* file-ioctl (literal \"/dev/tty\"))
(allow file-read* file-write* file-ioctl
    (require-all
        (regex #\"^/dev/ttys[0-9]+$\")
        (extension \"com.apple.sandbox.pty\")))
(allow file-read* (subpath \"/dev/fd\"))
";

/// Prepared paths with `deny` > `readonly` > `readwrite` precedence applied.
struct ResolvedPaths {
    readonly: Vec<String>,
    readwrite: Vec<String>,
    denied: Vec<String>,
}

impl ResolvedPaths {
    fn from_inputs(inputs: &ProfileInputs) -> Self {
        let denied = inputs.denied_paths.clone();
        let mut readonly = inputs.readonly_paths.clone();
        let mut readwrite = inputs.readwrite_paths.clone();

        // `denied` is emitted last and would override either allow anyway, but
        // dropping the path keeps the emitted profile an honest description of
        // the effective policy.
        readonly.retain(|p| !denied.contains(p));
        readwrite.retain(|p| !denied.contains(p) && !readonly.contains(p));

        Self {
            readonly,
            readwrite,
            denied,
        }
    }
}

const FS_ALLOW_SECTION: &str = "policy.readonlyPaths / policy.readwritePaths (shallow-to-deep)";
const FS_WITHIN_GRANTS_SECTION: &str =
    "policy paths at or inside keychainAccess/guiAccess folders (shallow-to-deep)";

fn write_filesystem_allow(out: &mut String, section: &str, plan: &[ResolvedMount]) {
    if plan.is_empty() {
        return;
    }

    // Emit shallow-to-deep, one rule per path, using the same ordering the
    // Linux backends apply (`crate::mxc_common::filesystem_resolve`). Seatbelt is
    // last-match-wins between rules that carry a filter, so ordering by depth
    // makes the *deepest* intent win at every path — a `readonlyPaths` entry
    // nested inside a broader `readwritePaths` subtree stays read-only rather
    // than inheriting the parent's write grant. `deniedPaths` is deliberately
    // not part of this plan: it is emitted last so it outranks these filtered
    // allows regardless of depth.
    let _ = writeln!(out, ";; --- {section} ---");
    for mount in plan {
        let subpath = [mount.path.clone()];
        match mount.intent {
            FsIntent::ReadWrite => {
                // `network-bind` / `network-outbound` under a *path* filter
                // match only AF_UNIX sockets — Seatbelt matches IP sockets with
                // `(local ip)` / `(remote ip)` — so this widens nothing on the
                // IP side. Both halves are needed: Node toolchains (tsx, vite,
                // esbuild, jest) bind an IPC pipe and then connect to it.
                write_path_rule(
                    out,
                    "allow file-read* file-write* network-bind network-outbound",
                    &subpath,
                );
            }
            FsIntent::ReadOnly => {
                write_path_rule(out, "allow file-read*", &subpath);
                // The read allow names only `file-read*`, so it says nothing
                // about write or socket ops and cannot displace a shallower
                // read-write grant — the removal has to be explicit.
                //
                // This deny survives the unfiltered `(allow network-outbound)`
                // that `write_network_rules` emits below under
                // `egress.default: "allow"`: last-match-wins applies between
                // rules that carry a filter, and an unfiltered rule does not
                // override a path-filtered one. Pinned by
                // `readonly_socket_strip_survives_a_default_allow_outbound`.
                write_path_rule(
                    out,
                    "deny file-write* network-bind network-outbound",
                    &subpath,
                );
            }
            FsIntent::Denied => unreachable!("denied paths are not part of this plan"),
        }
    }
}

fn write_filesystem_deny(out: &mut String, paths: &ResolvedPaths) {
    if !paths.denied.is_empty() {
        // `network-outbound` is denied here for two reasons. A denied path can
        // sit inside a broader `readwritePaths` subtree, whose allow covers it;
        // and `write_outbound_allow_rules` emits an *unfiltered* `(allow
        // network-outbound)` under `egress.default: "allow"`. Either would otherwise let the sandbox
        // `connect()` to a UNIX socket inside a denied subtree and talk to
        // whatever listens there. A Docker / ssh-agent / gpg-agent socket is a
        // control plane, so that would be an escape.
        //
        // `file-read-metadata` is named explicitly even though `file-read*`
        // nominally spans it: the baseline emits an unfiltered `(allow
        // file-read-metadata)`, and a rule naming the operation outranks one
        // that only reaches it through the wildcard. Without it a denied path
        // still answers `stat()` with its real size and timestamps.
        out.push_str(";; --- policy.deniedPaths (override broader allow rules) ---\n");
        write_path_rule(
            out,
            "deny file-read* file-read-metadata file-write* network-bind network-outbound",
            &paths.denied,
        );
    }
}

/// Emit a single `(<ops> (subpath …)…)` rule over already-resolved paths.
fn write_path_rule(out: &mut String, ops: &str, paths: &[String]) {
    let _ = writeln!(out, "({ops}");
    for p in paths {
        let _ = writeln!(out, "    (subpath {})", quote_scheme(p));
    }
    out.push_str(")\n");
}

fn write_network_rules(
    out: &mut String,
    request: &ExecutionRequest,
    proxy_address: Option<&ProxyAddress>,
    allow_default: bool,
) {
    let policy = &request.policy;
    let allow_outbound = seatbelt_policy::egress_allowed(policy);
    match allow_outbound {
        false => {
            out.push_str(";; --- network: default-deny egress (no general outbound grant) ---\n");
        }
        true => {
            out.push_str(";; --- network: outbound allowed (any host) ---\n");
            write_outbound_allow_rules(out);
        }
    }

    write_host_loopback_rules(out, policy, allow_outbound, allow_default);

    // The proxy port must override the broader host-loopback deny.
    if !allow_outbound {
        if let Some(address) = proxy_address {
            write_proxy_reachability_rules(out, address);
        }
    }

    write_local_network_rules(out, seatbelt_policy::local_network_allowed(policy));
}

/// Apply `network.ingress.hostLoopback` to the container-to-host direction.
///
/// The posture is bidirectional per the 0.8 contract, but Seatbelt can only
/// enforce the outbound half: an inbound filter scoped to loopback is either a
/// no-op (`remote ip`) or kills `bind()` outright (`local ip`). The backend's
/// `validate` therefore refuses `hostLoopback: "allow"` under
/// `ingress.default: "deny"` — an inbound promise the profile cannot keep —
/// while permitting `hostLoopback: "deny"` under `ingress.default: "allow"`,
/// where this rule enforces the container-to-host half and the blanket
/// `network-inbound` grant over-permits the host-to-container half.
///
/// Capture allow mode needs an explicit deny even when authored egress is deny.
fn write_host_loopback_rules(
    out: &mut String,
    policy: &ContainerPolicy,
    allow_outbound: bool,
    allow_default: bool,
) {
    let loopback_allowed = seatbelt_policy::host_loopback_allowed(policy);

    match (loopback_allowed, allow_outbound) {
        (false, _) if allow_outbound || allow_default => {
            // `localhost` matches this machine on any of its addresses, so this
            // also closes the "reach the host via its LAN IP" path.
            out.push_str(";; --- network: ingress.hostLoopback=deny — close host loopback,\n");
            out.push_str(";;     including this host's own non-loopback addresses ---\n");
            out.push_str("(deny network-outbound (remote ip \"localhost:*\"))\n");
        }
        (true, false) => {
            // Same breadth in reverse: this opens every address bound to this
            // host, not just 127.0.0.1. Other machines stay blocked —
            // `localhost` means "this machine", not "this network" — and there
            // is no narrower primitive, since a literal `127.0.0.1` is a
            // profile syntax error ("host must be * or localhost").
            out.push_str(";; --- network: ingress.hostLoopback=allow — open host loopback\n");
            out.push_str(";;     under an otherwise-deny egress default. Covers every\n");
            out.push_str(";;     address bound to this host; other machines stay denied ---\n");
            out.push_str("(allow network-outbound (remote ip \"localhost:*\"))\n");
        }
        _ => {}
    }
}

fn write_outbound_allow_rules(out: &mut String) {
    out.push_str("(allow network-outbound)\n");
    out.push_str("(allow network-bind (local ip))\n");
    out.push_str("(allow system-socket)\n");
}

/// Grant proxy reachability under authored deny-egress, after any loopback deny.
/// `localhost:<port>` covers every host address; non-loopback proxies are rejected.
fn write_proxy_reachability_rules(out: &mut String, proxy_address: &ProxyAddress) {
    if host_is_canonical_loopback(proxy_address.host()) {
        let _ = writeln!(
            out,
            ";; --- network: proxy configured — allow reaching the loopback proxy on port {} ---",
            proxy_address.port()
        );
        let _ = writeln!(
            out,
            "(allow network-outbound (remote ip \"localhost:{}\"))",
            proxy_address.port()
        );
    } else {
        out.push_str(";; --- network: non-loopback proxy cannot be expressed as a Seatbelt\n");
        out.push_str(";;     reachability rule; no outbound allow emitted (fail closed) ---\n");
    }
}

/// Emit the `network-inbound` rule that lets the sandboxed process accept
/// incoming connections on its own listeners. Required for `server.listen()`
/// on macOS — the `network-bind` rule alone is not enough; the kernel rejects
/// `listen()` with EPERM without `network-inbound`. Scoped to `(local ip)` so
/// it only covers IP sockets, never UNIX-domain or Mach sockets.
fn write_local_network_rules(out: &mut String, allow_ingress: bool) {
    if !allow_ingress {
        return;
    }
    out.push_str(";; --- network: ingress.default=allow — accept inbound on local IPs ---\n");
    out.push_str("(allow network-inbound (local ip))\n");
}

fn write_ui_rules(out: &mut String, request: &ExecutionRequest, capture: Option<&CaptureRules>) {
    let ui = &request.policy.ui;
    let gui_access = seatbelt_policy::gui_access_effective(request);

    // The baseline profile uses `(deny default)`, so services are blocked
    // unless explicitly allowed. When UI is enabled, we allow the mach
    // services that gate window creation and launch services. When UI is
    // disabled we omit those allows (and add explicit denies for clarity).
    if !ui.disable {
        out.push_str(";; --- ui enabled: allow WindowServer + LaunchServices ---\n");
        write_global_names(out, "allow", seatbelt_policy::UI_SERVICE_NAMES);

        if gui_access {
            // GUI apps need a broad set of Mach services to draw windows —
            // WindowServer, CoreAnimation, fonts, Dock, accessibility,
            // preferences, and many XPC helpers that vary across macOS
            // versions. Rather than maintaining a fragile allowlist, we
            // permit all mach-lookup when guiAccess is on. Filesystem and
            // network policies still apply.
            // Under captureDenials, these grants also report each use.
            let report = capture
                .map(CaptureRules::grant_modifier)
                .unwrap_or_default();
            // Each custom block that is present replaces the grant for its names.
            let seatbelt = request.seatbelt.as_ref();
            let registers = seatbelt.and_then(|c| c.custom_mach_registers.as_ref());
            let custom_global = registers.is_some_and(|r| r.global.is_some());
            let custom_local = registers.is_some_and(|r| r.local.is_some());
            if seatbelt.is_none_or(|c| c.custom_mach_lookups.is_none()) {
                out.push_str(";; --- guiAccess: allow all Mach lookups for GUI applications ---\n");
                let _ = writeln!(out, "(allow mach-lookup{report})");
            }
            // GUI apps must register their own Mach services (XPC listeners)
            // to receive callbacks from WindowServer and other system agents.
            let register_scope = match (custom_global, custom_local) {
                (false, false) => Some(""),
                (false, true) => Some(" (global-name-prefix \"\")"),
                (true, false) => Some(" (local-name-prefix \"\")"),
                (true, true) => None,
            };
            if let Some(scope) = register_scope {
                out.push_str(
                    ";; --- guiAccess: allow Mach registration for GUI applications ---\n",
                );
                let _ = writeln!(out, "(allow mach-register{report}{scope})");
            }

            // IOKit user-client access for GPU / Metal rendering
            if seatbelt.is_none_or(|c| c.custom_io_kits.is_none()) {
                out.push_str(";; --- guiAccess: allow IOKit for GPU rendering ---\n");
                let _ = writeln!(out, "(allow iokit-open{report})");
            } else if ui.injection {
                // customIoKits replaces the grant above, which covered HID.
                out.push_str(";; --- ui.injection: allow HID input ---\n");
                let _ = writeln!(
                    out,
                    "(allow iokit-open{report} (iokit-user-client-class {}))",
                    quote_scheme(seatbelt_policy::HID_USER_CLIENT_CLASS)
                );
            }

            if seatbelt.is_none_or(|c| c.custom_posix_shm.is_none()) {
                out.push_str(";; --- guiAccess: allow POSIX shared memory ---\n");
                let _ = writeln!(out, "(allow {GUI_POSIX_SHM_OPERATIONS}{report})");
            }
        }
    }

    if !matches!(ui.clipboard, ClipboardPolicy::None) {
        out.push_str(";; --- clipboard enabled: allow pasteboard ---\n");
        let _ = writeln!(
            out,
            "(allow mach-lookup (global-name {}))",
            quote_scheme(seatbelt_policy::PASTEBOARD_SERVICE_NAME)
        );
    }
}

/// Per-user temp and cache directories that GUI apps write to (app temp
/// files, caches, GPU shader caches).
fn write_gui_filesystem_rules(out: &mut String, request: &ExecutionRequest) {
    if !seatbelt_policy::gui_access_effective(request) {
        return;
    }
    out.push_str(";; --- guiAccess: allow writing to per-user temp/cache ---\n");
    out.push_str("(allow file-read* file-write*\n");
    let _ = writeln!(out, "    (subpath {})", quote_scheme(SHARED_TEMP_DIR));
    let _ = writeln!(out, "    (subpath {}))", quote_scheme(PER_USER_TEMP_DIR));
}

const SHARED_TEMP_DIR: &str = "/private/tmp";
const PER_USER_TEMP_DIR: &str = "/private/var/folders";

/// Folders that `keychainAccess` and `guiAccess` grant read+write.
fn setting_write_folders<'a>(
    request: &ExecutionRequest,
    user_keychains: Option<&'a str>,
) -> Vec<&'a str> {
    let mut folders = Vec::new();
    if request.seatbelt.as_ref().is_some_and(|c| c.keychain_access) {
        folders.extend(user_keychains);
        folders.push(PER_USER_TEMP_DIR);
    }
    if seatbelt_policy::gui_access_effective(request) {
        folders.extend([SHARED_TEMP_DIR, PER_USER_TEMP_DIR]);
    }
    folders
}

/// Emit one `(<action> mach-lookup (global-name …)…)` rule.
fn write_global_names(out: &mut String, action: &str, names: &[&str]) {
    let _ = writeln!(out, "({action} mach-lookup");
    for name in names {
        let _ = writeln!(out, "    (global-name {})", quote_scheme(name));
    }
    out.push_str(")\n");
}

/// Opens the deny rule a setting adds for `operation`; the caller writes the
/// filters and closes it. In allow mode, a
/// setting the request omitted allows and reports each use instead, so the
/// report lists it even where a broader grant such as guiAccess covers it.
fn open_setting_rule(
    out: &mut String,
    field: &str,
    comment: &str,
    operation: &str,
    written: bool,
    capture: Option<&CaptureRules>,
) {
    match capture.filter(|rules| rules.allow_mode && !written) {
        Some(rules) => {
            let _ = writeln!(out, ";; --- {field} omitted: allow and report ---");
            let _ = write!(
                out,
                "(allow {operation} (with report) (with message {})",
                quote_scheme(rules.tag)
            );
        }
        None => {
            let _ = writeln!(out, ";; --- {comment} ---");
            let _ = write!(out, "(deny {operation}");
        }
    }
}

/// UI settings that remove access. Emitted after every allow rule.
fn write_ui_policy_denies(
    out: &mut String,
    request: &ExecutionRequest,
    capture: Option<&CaptureRules>,
) {
    let ui = &request.policy.ui;
    let written = request.policy.ui_fields_specified;
    if ui.disable {
        open_setting_rule(
            out,
            "ui.disable",
            "ui.disable: deny WindowServer + related",
            "mach-lookup",
            written.disable,
            capture,
        );
        for name in seatbelt_policy::UI_SERVICE_NAMES {
            let _ = write!(out, "\n    (global-name {})", quote_scheme(name));
        }
        out.push_str("\n)\n");
    }

    if matches!(ui.clipboard, ClipboardPolicy::None) {
        open_setting_rule(
            out,
            "ui.clipboard",
            "ui.clipboard=none: deny pasteboard servers",
            "mach-lookup",
            written.clipboard,
            capture,
        );
        let _ = writeln!(
            out,
            " (global-name-prefix {}))",
            quote_scheme(seatbelt_policy::PASTEBOARD_SERVICE_PREFIX)
        );
    }

    if !ui.injection {
        open_setting_rule(
            out,
            "ui.injection",
            "ui.injection=false: deny HID iokit access",
            "iokit-open",
            written.injection,
            capture,
        );
        let _ = writeln!(
            out,
            " (iokit-user-client-class {}))",
            quote_scheme(seatbelt_policy::HID_USER_CLIENT_CLASS)
        );
    }
}

/// Emit rules so the inner process can call `posix_openpt()` and allocate
/// its own pty.
fn write_nested_pty_rules(out: &mut String, request: &ExecutionRequest) {
    if !nested_pty_enabled(request) {
        return;
    }
    out.push_str(";; --- nestedPty: allow inner process to allocate its own pty ---\n");
    out.push_str("(allow pseudo-tty)\n");
    // TTY_ALLOW restricts secondary-device access to the kernel's PTY extension.
    out.push_str("(allow file-read* file-write* file-ioctl\n");
    out.push_str("    (literal \"/dev/ptmx\"))\n");
}

fn nested_pty_enabled(request: &ExecutionRequest) -> bool {
    request.seatbelt.as_ref().is_none_or(|c| c.nested_pty)
}

/// `nestedPty` defaults to true, so `false` is always written in the config
/// and stays denied even under captureDenials allow mode.
fn write_nested_pty_denies(out: &mut String, request: &ExecutionRequest) {
    if nested_pty_enabled(request) {
        return;
    }
    out.push_str(";; --- nestedPty=false: deny pty allocation ---\n");
    out.push_str("(deny pseudo-tty)\n");
    out.push_str("(deny file-read* file-write* file-ioctl (literal \"/dev/ptmx\"))\n");
}

/// Emit rules so `Security.framework` / `keytar` can reach `securityd`
/// and read/write the user's Keychain. Off by default — opt in via
/// `seatbelt.keychainAccess: true`.
///
/// Real-world Keychain access fans out across several daemons. At
/// minimum we need:
///
/// * `securityd` / `SecurityServer` — the actual Keychain server.
/// * `trustd` / `ocspd` — TLS trust evaluation; without them every
///   handshake logs "failed to copy trust settings".
/// * `cfprefsd.daemon` — `Security.framework` reads preferences for
///   trust settings, ACL prompts, etc.
/// * `xpcd` + `lsd.*` — XPC bootstrapper and LaunchServices, used to
///   resolve helper bundles when the keychain is unlocked.
///
/// On the filesystem side, the user's keychain DB lives under
/// `~/Library/Keychains` (read+write — keytar creates new entries),
/// `/private/var/db/mds` is Spotlight/MDS metadata that
/// `Security.framework` consults (read-only), and per-user XPC caches
/// live under `/private/var/folders` (read+write). The system keychain
/// stores under `/Library/Keychains` and `/System/Library/Keychains`
/// are already covered by the baseline `/Library` and `/System`
/// read-only allows, so we don't re-add them here.
fn write_keychain_rules(
    out: &mut String,
    request: &ExecutionRequest,
    user_keychains: Option<&str>,
) -> Result<(), ProfileError> {
    let enabled = request.seatbelt.as_ref().is_some_and(|c| c.keychain_access);
    if !enabled {
        return Ok(());
    }
    let user_keychains = user_keychains.ok_or_else(|| {
        ProfileError::Host(
            "User keychain directory was not prepared for keychainAccess".to_string(),
        )
    })?;

    out.push_str(";; --- keychainAccess: Mach IPC for Keychain (securityd, prefs, XPC, LS) ---\n");
    out.push_str("(allow mach-lookup");
    for name in seatbelt_policy::KEYCHAIN_GRANTED_NAMES {
        let _ = write!(out, "\n    (global-name {})", quote_scheme(name));
    }
    for prefix in seatbelt_policy::KEYCHAIN_GRANTED_PREFIXES {
        let _ = write!(
            out,
            "\n    (global-name-regex #\"^{}\")",
            prefix.replace('.', "\\.")
        );
    }
    out.push_str(")\n");

    out.push_str(";; --- keychainAccess: MDS keychain metadata + trustd protected store ---\n");
    out.push_str("(allow file-read*\n");
    // trustd's protected store of trust settings + revocation data.
    out.push_str("    (subpath \"/private/var/protected/trustd\")\n");
    out.push_str("    (subpath \"/private/var/db/mds\"))\n");

    out.push_str(";; --- keychainAccess: user keychain DB + XPC/folder caches (read+write) ---\n");
    out.push_str("(allow file-read* file-write*\n");
    let _ = writeln!(out, "    (subpath {})", quote_scheme(user_keychains));
    let _ = writeln!(out, "    (subpath {}))", quote_scheme(PER_USER_TEMP_DIR));
    Ok(())
}

/// Without `keychainAccess`, deny the Keychain servers after guiAccess and
/// custom grants. `extraMachLookups` follows, so its entries keep their V1 effect.
fn write_keychain_denies(
    out: &mut String,
    request: &ExecutionRequest,
    capture: Option<&CaptureRules>,
) {
    let seatbelt = request.seatbelt.as_ref();
    if seatbelt.is_some_and(|c| c.keychain_access) {
        return;
    }
    open_setting_rule(
        out,
        "keychainAccess",
        "keychainAccess=false: deny Keychain servers",
        "mach-lookup",
        seatbelt.is_some_and(|c| c.keychain_access_specified),
        capture,
    );
    for name in seatbelt_policy::KEYCHAIN_SERVER_NAMES {
        let _ = write!(out, "\n    (global-name {})", quote_scheme(name));
    }
    for prefix in seatbelt_policy::KEYCHAIN_SERVER_PREFIXES {
        let _ = write!(out, "\n    (global-name-prefix {})", quote_scheme(prefix));
    }
    out.push_str("\n)\n");
}

/// Emit caller-provided `extraMachLookups` rules: additional Mach service
/// global-names the inner process may resolve. No-op when the list is empty.
fn write_extra_seatbelt_rules(out: &mut String, request: &ExecutionRequest) {
    let Some(sb) = request.seatbelt.as_ref() else {
        return;
    };
    if sb.extra_mach_lookups.is_empty() {
        return;
    }

    out.push_str(";; --- extraMachLookups: caller-provided Mach services ---\n");
    out.push_str("(allow mach-lookup\n");
    for name in &sb.extra_mach_lookups {
        let _ = writeln!(out, "    (global-name {})", quote_scheme(name));
    }
    out.push_str(")\n");
}

/// The Seatbelt operation and name filters for one custom rule list.
struct CustomRuleTarget {
    field: &'static str,
    operation: &'static str,
    /// Filter for every name in scope; empty for the whole operation.
    scope: &'static str,
    exact: &'static str,
    prefix: &'static str,
}

const IOKIT_TARGET: CustomRuleTarget = CustomRuleTarget {
    field: "customIoKits",
    operation: "iokit-open",
    scope: "",
    exact: "iokit-user-client-class",
    prefix: "iokit-user-client-class-regex",
};
const LOOKUP_TARGET: CustomRuleTarget = CustomRuleTarget {
    field: "customMachLookups",
    operation: "mach-lookup",
    scope: "",
    exact: "global-name",
    prefix: "global-name-prefix",
};
const GLOBAL_REGISTER_TARGET: CustomRuleTarget = CustomRuleTarget {
    field: "customMachRegisters.global",
    operation: "mach-register",
    scope: " (global-name-prefix \"\")",
    exact: "global-name",
    prefix: "global-name-prefix",
};
const LOCAL_REGISTER_TARGET: CustomRuleTarget = CustomRuleTarget {
    field: "customMachRegisters.local",
    operation: "mach-register",
    scope: " (local-name-prefix \"\")",
    exact: "local-name",
    prefix: "local-name-prefix",
};

/// guiAccess's shared memory grant.
const GUI_POSIX_SHM_OPERATIONS: &str =
    "ipc-posix-shm-read-data ipc-posix-shm-write-data ipc-posix-shm-write-create";

/// Each shared memory operation and the lowest access level that grants it.
const POSIX_SHM_OPERATIONS: [(&str, SeatbeltPosixShmAccess); 5] = [
    ("ipc-posix-shm-read-data", SeatbeltPosixShmAccess::Read),
    ("ipc-posix-shm-read-metadata", SeatbeltPosixShmAccess::Read),
    (
        "ipc-posix-shm-write-data",
        SeatbeltPosixShmAccess::ReadWrite,
    ),
    ("ipc-posix-shm-write-create", SeatbeltPosixShmAccess::Create),
    ("ipc-posix-shm-write-unlink", SeatbeltPosixShmAccess::Own),
];

/// Shared memory operations whose level satisfies `include`.
fn posix_shm_operations(include: impl Fn(SeatbeltPosixShmAccess) -> bool) -> String {
    POSIX_SHM_OPERATIONS
        .iter()
        .filter(|(_, level)| include(*level))
        .map(|(operation, _)| *operation)
        .collect::<Vec<_>>()
        .join(" ")
}

const fn posix_shm_target(field: &'static str, operation: &'static str) -> CustomRuleTarget {
    CustomRuleTarget {
        field,
        operation,
        scope: "",
        exact: "ipc-posix-name",
        prefix: "ipc-posix-name-prefix",
    }
}

const SHM_LIST_TARGET: CustomRuleTarget = posix_shm_target("customPosixShm", "");
// Seatbelt prefers a rule that names an operation over a wildcard, so the
// deny names each one to win over every other shared memory rule.
const SHM_DENY_TARGET: CustomRuleTarget = posix_shm_target(
    "customPosixShm.deny",
    "ipc-posix-shm* ipc-posix-shm-read-data ipc-posix-shm-read-metadata \
     ipc-posix-shm-write-data ipc-posix-shm-write-create ipc-posix-shm-write-unlink",
);

fn custom_rule_targets(
    request: &ExecutionRequest,
) -> Vec<(&CustomRuleTarget, &SeatbeltCustomRules)> {
    let Some(config) = request.seatbelt.as_ref() else {
        return Vec::new();
    };
    let registers = config.custom_mach_registers.as_ref();
    [
        (&IOKIT_TARGET, config.custom_io_kits.as_ref()),
        (&LOOKUP_TARGET, config.custom_mach_lookups.as_ref()),
        (
            &GLOBAL_REGISTER_TARGET,
            registers.and_then(|r| r.global.as_ref()),
        ),
        (
            &LOCAL_REGISTER_TARGET,
            registers.and_then(|r| r.local.as_ref()),
        ),
    ]
    .into_iter()
    .filter_map(|(target, rules)| rules.map(|rules| (target, rules)))
    .collect()
}

/// Emit one `(<action> <operation> <filters>…)` rule for custom list entries.
fn write_custom_rule(
    out: &mut String,
    action: &str,
    target: &CustomRuleTarget,
    entries: &[String],
) {
    write_name_rule(out, action, target.operation, target, entries);
}

fn write_name_rule(
    out: &mut String,
    action: &str,
    operation: &str,
    target: &CustomRuleTarget,
    entries: &[String],
) {
    let _ = writeln!(out, "({action} {operation}");
    for entry in entries {
        let _ = match NamePattern::parse(entry) {
            NamePattern::Exact(name) => {
                writeln!(out, "    ({} {})", target.exact, quote_scheme(name))
            }
            // Validation limits IOKit class names to letters, digits, and '_'.
            NamePattern::Prefix(prefix) if target.prefix.ends_with("-regex") => {
                writeln!(out, "    ({} #\"^{prefix}\")", target.prefix)
            }
            NamePattern::Prefix(prefix) => {
                writeln!(out, "    ({} {})", target.prefix, quote_scheme(prefix))
            }
        };
    }
    out.push_str(")\n");
}

/// Emit custom `default` grants, `allow` lists, and the shared memory access
/// lists. Under captureDenials, a default grant reports each use like
/// guiAccess's grants.
fn write_custom_allows(
    out: &mut String,
    request: &ExecutionRequest,
    capture: Option<&CaptureRules>,
) {
    let report = capture
        .map(CaptureRules::grant_modifier)
        .unwrap_or_default();
    for (target, rules) in custom_rule_targets(request) {
        if seatbelt_policy::custom_default_allows(rules) {
            let _ = writeln!(out, ";; --- {}: default allow ---", target.field);
            let _ = writeln!(out, "(allow {}{report}{})", target.operation, target.scope);
        }
        if !rules.allow.is_empty() {
            let _ = writeln!(out, ";; --- {}.allow ---", target.field);
            write_custom_rule(out, "allow", target, &rules.allow);
        }
    }
    let Some(shm) = request
        .seatbelt
        .as_ref()
        .and_then(|c| c.custom_posix_shm.as_ref())
    else {
        return;
    };
    let default = seatbelt_policy::posix_shm_default(shm);
    if default != SeatbeltPosixShmAccess::Deny {
        out.push_str(";; --- customPosixShm: default grant ---\n");
        let operations = posix_shm_operations(|level| level <= default);
        let _ = writeln!(out, "(allow {operations}{report})");
    }
    write_posix_shm_access_lists(out, shm);
}

/// Give each listed shared memory name exactly its list's access. When two
/// rules name the same operations, Seatbelt applies the later one, so
/// broader prefixes go first and longer names override them.
fn write_posix_shm_access_lists(out: &mut String, shm: &SeatbeltCustomPosixShm) {
    let mut entries: Vec<_> = seatbelt_policy::posix_shm_access_lists(shm)
        .into_iter()
        .flat_map(|(list, level, entries)| entries.iter().map(move |e| (list, level, e)))
        .collect();
    entries.sort_by_key(|(_, _, entry)| match NamePattern::parse(entry) {
        NamePattern::Prefix(prefix) => (false, prefix.len()),
        NamePattern::Exact(_) => (true, 0),
    });
    for (list, level, entry) in entries {
        let entry = std::slice::from_ref(entry);
        let _ = writeln!(out, ";; --- customPosixShm.{list} ---");
        let granted = posix_shm_operations(|op| op <= level);
        write_name_rule(out, "allow", &granted, &SHM_LIST_TARGET, entry);
        let above = posix_shm_operations(|op| op > level);
        if !above.is_empty() {
            write_name_rule(out, "deny", &above, &SHM_LIST_TARGET, entry);
        }
    }
}

/// Emit custom `deny` lists after every allow, so they also remove MXC's
/// built-in grants.
fn write_custom_denies(out: &mut String, request: &ExecutionRequest) {
    for (target, rules) in custom_rule_targets(request) {
        if !rules.deny.is_empty() {
            let _ = writeln!(out, ";; --- {}.deny ---", target.field);
            write_custom_rule(out, "deny", target, &rules.deny);
        }
    }
    if let Some(shm) = request
        .seatbelt
        .as_ref()
        .and_then(|c| c.custom_posix_shm.as_ref())
        .filter(|shm| !shm.deny.is_empty())
    {
        let _ = writeln!(out, ";; --- {} ---", SHM_DENY_TARGET.field);
        write_custom_rule(out, "deny", &SHM_DENY_TARGET, &shm.deny);
    }
}

/// Quote a string for use as a TinyScheme string literal, escaping
/// embedded backslashes and double-quotes.
fn quote_scheme(s: &str) -> String {
    let mut q = String::with_capacity(s.len() + 2);
    q.push('"');
    q.push_str(&escape_for_quotes(s));
    q.push('"');
    q
}

fn escape_for_quotes(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            other => out.push(other),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::models::{
        NetworkAction, SeatbeltConfig, SeatbeltCustomDefault, SeatbeltCustomMachRegisters,
        SeatbeltCustomPosixShm, UiPolicy,
    };

    /// Whether some shared memory operation is granted for every name.
    fn grants_all_shm(p: &str) -> bool {
        p.lines()
            .any(|l| l.starts_with("(allow ipc-posix-shm") && l.ends_with(')'))
    }

    fn build_profile(request: &ExecutionRequest) -> Result<String, ProfileError> {
        build_profile_with_proxy(request, request.policy.network_proxy.address.as_ref())
    }

    fn build_profile_with_proxy(
        request: &ExecutionRequest,
        proxy_address: Option<&ProxyAddress>,
    ) -> Result<String, ProfileError> {
        let inputs = ProfileInputs {
            readonly_paths: request.policy.readonly_paths.clone(),
            readwrite_paths: request.policy.readwrite_paths.clone(),
            denied_paths: request.policy.denied_paths.clone(),
            user_keychains: request
                .seatbelt
                .as_ref()
                .is_some_and(|config| config.keychain_access)
                .then(|| "/Users/profile-test/Library/Keychains".into()),
            ..Default::default()
        };
        super::build_profile_with_proxy(request, proxy_address, &inputs)
    }

    fn req() -> ExecutionRequest {
        ExecutionRequest {
            script_code: "echo hi".to_string(),
            ..Default::default()
        }
    }

    #[test]
    fn baseline_profile_has_deny_default_and_baseline_allows() {
        let p = build_profile(&req()).unwrap();
        assert!(p.contains("(version 1)"));
        assert!(p.contains("(deny default)"));
        assert!(p.contains("(allow process-fork)"));
        assert!(p.contains("(allow process-exec)"));
        assert!(p.contains("(allow signal (target same-sandbox))"));
        assert!(p.contains("/usr/lib"));
        assert!(p.contains("/System"));
        assert!(p.contains("(subpath \"/bin\")"));
        assert!(p.contains("(subpath \"/usr/bin\")"));
        assert!(p.contains("(allow file-read-data (literal \"/\"))"));
    }

    #[test]
    fn readonly_paths_emit_subpath_allows() {
        let mut r = req();
        r.policy.readonly_paths = vec!["/opt/tools".into(), "/private/var/data".into()];
        let p = build_profile(&r).unwrap();
        assert!(p.contains("policy.readonlyPaths"));
        assert!(p.contains("(allow file-read*"));
        assert!(p.contains("(subpath \"/opt/tools\")"));
        assert!(p.contains("(subpath \"/private/var/data\")"));
        assert!(!p.contains("file-write* (subpath \"/opt/tools\")"));
    }

    #[test]
    fn readwrite_paths_emit_read_and_write_allows() {
        let mut r = req();
        r.policy.readwrite_paths = vec!["/private/tmp/output".into()];
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow file-read* file-write*"));
        assert!(p.contains("(subpath \"/private/tmp/output\")"));
    }

    #[test]
    fn denied_paths_appear_after_allows_to_override() {
        let mut r = req();
        r.policy.readwrite_paths = vec!["/private/tmp".into()];
        r.policy.denied_paths = vec!["/private/tmp/secret".into()];
        let p = build_profile(&r).unwrap();
        let allow_idx = p.find("(allow file-read* file-write*").unwrap();
        let deny_idx = p
            .find("(deny file-read* file-read-metadata file-write*")
            .unwrap();
        assert!(
            deny_idx > allow_idx,
            "deny rules must come after allow rules so they win on last-match"
        );
        assert!(p.contains("(subpath \"/private/tmp/secret\")"));
    }

    #[test]
    fn default_deny_network_emits_no_allow_network() {
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Deny));
        let p = build_profile(&r).unwrap();
        assert!(!p.contains("(allow network-outbound"));
        assert!(p.contains("network: default-deny"));
    }

    #[test]
    fn unsupported_directional_egress_rule_never_widens_to_allow_all() {
        // Backend validation rejects rules, and even a direct profile build
        // must not turn a denied default into allow-all.
        let mut r = req();
        r.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            allow: vec![crate::mxc_common::models::NetworkRule {
                to: vec![crate::mxc_common::models::NetworkPeer {
                    cidr: "192.0.2.1/32".parse().unwrap(),
                    except: Vec::new(),
                }],
                ..Default::default()
            }],
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        assert!(!p.contains("(allow network-outbound)"));
        assert!(p.contains("network: default-deny"));
        assert!(!p.contains("(remote"));
    }

    #[test]
    fn deny_with_loopback_proxy_keeps_port_scoped_reachability() {
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Deny));
        let address = ProxyAddress::new("127.0.0.1".into(), 8080);
        let p = build_profile_with_proxy(&r, Some(&address)).unwrap();
        assert!(!p.contains("(allow network-outbound)"));
        assert!(p.contains("8080"));
    }

    /// Regression test for the bracketed-IPv6 form, which the profile builder
    /// used to miss — it then fell through to the remote-proxy branch and
    /// emitted a bare `(allow network-outbound)` under a deny policy.
    #[test]
    fn every_loopback_proxy_spelling_stays_port_scoped_under_deny() {
        for host in [
            "127.0.0.1",
            "::1",
            "[::1]",
            "0:0:0:0:0:0:0:1",
            "[0:0:0:0:0:0:0:1]",
            "localhost",
            "LOCALHOST",
            "LocalHost",
        ] {
            let mut r = req();
            r.policy.network_egress = Some(egress(NetworkAction::Deny));
            let address = ProxyAddress::new(host.into(), 8080);
            let p = build_profile_with_proxy(&r, Some(&address)).unwrap();

            assert!(
                !p.contains("(allow network-outbound)"),
                "proxy host {host:?} widened egress to allow-all under default-deny; \
                 profile:\n{p}"
            );
            assert!(
                p.contains("(allow network-outbound (remote ip \"localhost:8080\"))"),
                "proxy host {host:?} did not emit port-scoped proxy reachability; \
                 profile:\n{p}"
            );
        }
    }

    /// Unreachable via real config (both upstream layers reject it), but if a
    /// loopback check ever diverges this must fail closed, not open.
    #[test]
    fn remote_proxy_under_deny_fails_closed() {
        for host in ["proxy.corp.example", "10.0.0.5", "[2001:db8::1]"] {
            let mut r = req();
            r.policy.network_egress = Some(egress(NetworkAction::Deny));
            let address = ProxyAddress::new(host.into(), 8080);
            let p = build_profile_with_proxy(&r, Some(&address)).unwrap();
            assert!(
                !p.contains("(allow network-outbound"),
                "remote proxy host {host:?} must not emit any outbound allow under \
                 default-deny; profile:\n{p}"
            );
        }
    }

    #[test]
    fn allow_outbound_no_hosts_emits_open_network_outbound() {
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Allow));
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow network-outbound)"));
    }

    #[test]
    fn directional_allow_outbound_still_closes_host_loopback() {
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Allow));
        r.policy.network_ingress = Some(ingress(NetworkAction::Deny));
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow network-outbound)"));
        assert!(p.contains("(deny network-outbound (remote ip \"localhost:*\"))"));
        assert!(!p.contains("(allow network-inbound"));
    }

    #[test]
    fn loopback_proxy_under_default_deny_scopes_outbound_to_proxy_port() {
        // A cooperative loopback proxy must be reachable even though outbound
        // is default-deny — but only the proxy's exact port, not all of
        // loopback and not the whole network.
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Deny));
        let addr = ProxyAddress::new("127.0.0.1".into(), 8080);
        let p = build_profile_with_proxy(&r, Some(&addr)).unwrap();
        assert!(p.contains("(allow network-outbound (remote ip \"localhost:8080\"))"));
        // Must NOT open outbound to all loopback ports or the whole network.
        assert!(!p.contains("localhost:*"));
        assert!(!p.contains("(allow network-outbound)\n"));
    }

    #[test]
    fn remote_proxy_under_default_deny_emits_no_outbound_allow() {
        // A remote proxy can't be expressed as a reachability rule, so it fails
        // closed. Rejected upstream, so this only pins the fallback behavior.
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Deny));
        let addr = ProxyAddress::from_url(
            "http://proxy.example.com:8080",
            "proxy.example.com".into(),
            8080,
        );
        let p = build_profile_with_proxy(&r, Some(&addr)).unwrap();
        assert!(p.contains("fail closed"));
        assert!(!p.contains("(allow network-outbound"));
    }

    #[test]
    fn proxy_under_default_allow_does_not_add_scoped_rule() {
        // When outbound is already open (egress.default allow), the proxy
        // reachability rule is redundant and must not be emitted.
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Allow));
        let addr = ProxyAddress::new("127.0.0.1".into(), 8080);
        let p = build_profile_with_proxy(&r, Some(&addr)).unwrap();
        assert!(p.contains("(allow network-outbound)\n"));
        assert!(!p.contains("(allow network-outbound (remote ip \"localhost:8080\"))"));
        assert!(p.contains("(deny network-outbound (remote ip \"localhost:*\"))"));
    }

    #[test]
    fn build_profile_wrapper_scopes_static_localhost_proxy() {
        // The convenience `build_profile` wrapper must honor a statically
        // configured proxy address (localhost:<port>), scoping the reachability
        // rule to that exact port under default-deny — not silently dropping it.
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Deny));
        r.policy.network_proxy = crate::mxc_common::models::ProxyConfig {
            address: Some(ProxyAddress::new("127.0.0.1".into(), 9091)),
        };
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow network-outbound (remote ip \"localhost:9091\"))"));
        assert!(!p.contains("localhost:*"));
    }

    #[test]
    fn directional_ingress_allow_emits_inbound_rule() {
        // server.listen() on macOS is governed by `network-inbound`, not
        // `network-bind` — with only `network-bind (local ip)` the bind()
        // succeeds and the kernel then rejects listen() with EPERM.
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Allow));
        r.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy {
            default: NetworkAction::Allow,
            host_loopback: NetworkAction::Deny,
        });
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow network-inbound (local ip))"));
        assert!(p.contains("ingress.default=allow"));
    }

    #[test]
    fn omitted_ingress_default_omits_inbound_rule() {
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Allow));
        let p = build_profile(&r).unwrap();
        assert!(!p.contains("network-inbound"));
    }

    #[test]
    fn ingress_allow_works_with_default_deny_outbound() {
        // Ingress is independent of outbound: a process can be
        // a pure server (no client traffic) and still accept local inbound.
        let mut r = req();
        r.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy {
            default: NetworkAction::Allow,
            host_loopback: NetworkAction::Deny,
        });
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow network-inbound (local ip))"));
        assert!(!p.contains("(allow network-outbound)"));
    }

    #[test]
    fn directional_egress_deny_emits_no_allow_network() {
        let mut r = req();
        r.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: NetworkAction::Deny,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        assert!(!p.contains("(allow network-outbound"));
        assert!(p.contains("network: default-deny"));
    }

    #[test]
    fn directional_egress_allow_emits_open_network_outbound() {
        let mut r = req();
        r.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: NetworkAction::Allow,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow network-outbound)"));
    }

    #[test]
    fn directional_ingress_default_allow_emits_inbound_rule() {
        // Seatbelt maps ingress.default (not hostLoopback) to the inbound rule.
        let mut r = req();
        r.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy {
            default: NetworkAction::Allow,
            host_loopback: NetworkAction::Allow,
        });
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow network-inbound (local ip))"));
    }

    #[test]
    fn directional_ingress_default_deny_omits_inbound_rule() {
        let mut r = req();
        r.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy {
            default: NetworkAction::Deny,
            host_loopback: NetworkAction::Deny,
        });
        let p = build_profile(&r).unwrap();
        assert!(!p.contains("network-inbound"));
    }

    #[test]
    fn ingress_allow_with_host_loopback_deny_grants_inbound_without_loopback_egress() {
        let mut r = req();
        r.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy {
            default: NetworkAction::Allow,
            host_loopback: NetworkAction::Deny,
        });
        let addr = ProxyAddress::new("127.0.0.1".into(), 9091);
        let p = build_profile_with_proxy(&r, Some(&addr)).unwrap();
        assert!(p.contains("(allow network-inbound (local ip))"));
        assert!(p.contains("(allow network-outbound (remote ip \"localhost:9091\"))"));
        // The bypass this posture exists to avoid: every other host port.
        assert!(!p.contains("(allow network-outbound (remote ip \"localhost:*\"))"));
        assert!(!p.contains("(allow network-outbound)"));
    }

    #[test]
    fn ingress_allow_with_host_loopback_deny_still_closes_loopback_under_egress_allow() {
        let mut r = req();
        r.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: NetworkAction::Allow,
            ..Default::default()
        });
        r.policy.network_ingress = Some(crate::mxc_common::models::NetworkIngressPolicy {
            default: NetworkAction::Allow,
            host_loopback: NetworkAction::Deny,
        });
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow network-inbound (local ip))"));
        assert!(p.contains("(allow network-outbound)"));
        assert!(
            p.find("(deny network-outbound (remote ip \"localhost:*\"))")
                > p.find("(allow network-outbound)"),
            "the localhost deny must follow the broad allow; profile:\n{p}"
        );
    }

    // --- network.ingress.hostLoopback -------------------------
    //
    // The posture only changes the profile in the two cells where it disagrees
    // with the egress default; the other two are already covered by the
    // baseline or by the blanket allow.

    fn ingress(action: NetworkAction) -> crate::mxc_common::models::NetworkIngressPolicy {
        crate::mxc_common::models::NetworkIngressPolicy {
            default: action,
            host_loopback: action,
        }
    }

    fn egress(action: NetworkAction) -> crate::mxc_common::models::NetworkEgressPolicy {
        crate::mxc_common::models::NetworkEgressPolicy {
            default: action,
            ..Default::default()
        }
    }

    #[test]
    fn host_loopback_deny_closes_loopback_under_open_egress() {
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Allow));
        r.policy.network_ingress = Some(ingress(NetworkAction::Deny));
        let p = build_profile(&r).unwrap();

        assert!(p.contains("(allow network-outbound)"));
        assert!(p.contains("(deny network-outbound (remote ip \"localhost:*\"))"));
        // Between two rules that both match, Seatbelt takes the last one.
        assert!(
            p.find("(deny network-outbound (remote ip \"localhost:*\"))")
                > p.find("(allow network-outbound)"),
            "the loopback deny must follow the blanket allow to take effect"
        );
    }

    #[test]
    fn host_loopback_allow_keeps_loopback_open_under_open_egress() {
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Allow));
        r.policy.network_ingress = Some(ingress(NetworkAction::Allow));
        let p = build_profile(&r).unwrap();

        assert!(p.contains("(allow network-outbound)"));
        assert!(!p.contains("localhost:*"));
    }

    #[test]
    fn host_loopback_allow_opens_loopback_under_deny_egress() {
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Deny));
        r.policy.network_ingress = Some(ingress(NetworkAction::Allow));
        let p = build_profile(&r).unwrap();

        assert!(p.contains("(allow network-outbound (remote ip \"localhost:*\"))"));
        assert!(!p.contains("(allow network-outbound)\n"));
    }

    #[test]
    fn host_loopback_deny_under_deny_egress_needs_no_rule() {
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Deny));
        r.policy.network_ingress = Some(ingress(NetworkAction::Deny));
        let p = build_profile(&r).unwrap();

        // `(deny default)` already covers it.
        assert!(!p.contains("localhost:*"));
        assert!(!p.contains("(allow network-outbound"));
    }

    #[test]
    fn omitted_ingress_under_open_egress_closes_host_loopback() {
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Allow));
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(deny network-outbound (remote ip \"localhost:*\"))"));
    }

    #[test]
    fn no_host_loopback_deny_can_swallow_the_proxy_allow() {
        // A proxy is only reachable under a deny egress default, and that arm
        // emits no `localhost:*` deny. Pin it: a deny reaching the profile
        // alongside the proxy allow would silently fail closed.
        for loopback in [NetworkAction::Allow, NetworkAction::Deny] {
            let mut r = req();
            r.policy.network_egress = Some(egress(NetworkAction::Deny));
            r.policy.network_ingress = Some(ingress(loopback));
            let addr = ProxyAddress::new("127.0.0.1".into(), 44444);
            let p = build_profile_with_proxy(&r, Some(&addr)).unwrap();

            assert!(
                p.contains("(allow network-outbound (remote ip \"localhost:44444\"))"),
                "hostLoopback={loopback:?}: the proxy allow must be emitted"
            );
            assert!(
                !p.contains("(deny network-outbound (remote ip \"localhost:*\"))"),
                "hostLoopback={loopback:?}: a loopback deny would swallow the proxy allow"
            );
        }
    }

    #[test]
    fn proxy_allow_is_emitted_after_the_host_loopback_allow() {
        // The only case where two `localhost` rules coexist. Both permit, so
        // order is harmless today — assert it anyway to keep the proxy
        // exception last if either rule ever becomes a deny.
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Deny));
        r.policy.network_ingress = Some(ingress(NetworkAction::Allow));
        let addr = ProxyAddress::new("127.0.0.1".into(), 44444);
        let p = build_profile_with_proxy(&r, Some(&addr)).unwrap();

        let loopback = p
            .find("(allow network-outbound (remote ip \"localhost:*\"))")
            .expect("hostLoopback=allow must emit the loopback allow");
        let proxy = p
            .find("(allow network-outbound (remote ip \"localhost:44444\"))")
            .expect("a loopback proxy must emit the port-scoped allow");
        assert!(proxy > loopback, "the proxy allow must be emitted last");
    }

    #[test]
    fn directional_deny_with_loopback_proxy_scopes_outbound_to_proxy_port() {
        // Deny + loopback proxy must grant only the selected proxy port.
        let mut r = req();
        r.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: NetworkAction::Deny,
            ..Default::default()
        });
        let addr = ProxyAddress::new("127.0.0.1".into(), 56159);
        let p = build_profile_with_proxy(&r, Some(&addr)).unwrap();
        assert!(p.contains("(allow network-outbound (remote ip \"localhost:56159\"))"));
        assert!(!p.contains("(allow network-outbound)\n"));
    }

    #[test]
    fn ui_disabled_blocks_windowserver() {
        let r = req();
        // Default UiPolicy has disable=true.
        assert!(r.policy.ui.disable);
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(deny mach-lookup"));
        assert!(p.contains("com.apple.windowserver.active"));
    }

    #[test]
    fn ui_enabled_allows_windowserver_and_clipboard() {
        let mut r = req();
        r.policy.ui = UiPolicy {
            disable: false,
            clipboard: ClipboardPolicy::All,
            injection: true,
        };
        let p = build_profile(&r).unwrap();
        // UI enabled → allow WindowServer
        assert!(p.contains("(allow mach-lookup"));
        assert!(p.contains("com.apple.windowserver.active"));
        // Clipboard=all → allow pasteboard
        assert!(p.contains("com.apple.pasteboard.1"));
        assert!(!p.contains("IOHIDLibUserClient"));
    }

    #[test]
    fn clipboard_none_blocks_pasteboard() {
        let r = req();
        // Default clipboard is None.
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(deny mach-lookup (global-name-prefix \"com.apple.pasteboard.\"))"));
        assert!(!p.contains("(global-name \"com.apple.pasteboard.1\")"));
    }

    /// Like the Keychain denies, the pasteboard deny follows every broader
    /// Mach grant, including custom allow lists.
    #[test]
    fn clipboard_deny_follows_custom_mach_grants() {
        let mut r = req();
        r.policy.ui.disable = false;
        r.seatbelt = Some(SeatbeltConfig {
            gui_access: true,
            custom_mach_lookups: Some(SeatbeltCustomRules {
                default: Some(SeatbeltCustomDefault::Allow),
                allow: vec!["com.apple.*".into()],
                deny: Vec::new(),
            }),
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        let deny = p.find("ui.clipboard=none: deny").expect("pasteboard deny");
        assert!(p.find("customMachLookups: default allow").unwrap() < deny);
        assert!(p.find("customMachLookups.allow").unwrap() < deny);
    }

    #[test]
    fn injection_false_blocks_hid_iokit() {
        let r = req();
        let p = build_profile(&r).unwrap();
        assert!(p.contains("IOHIDLibUserClient"));
    }

    #[test]
    fn profile_override_takes_precedence() {
        let mut r = req();
        r.policy.readonly_paths = vec!["/should/be/ignored".into()];
        r.seatbelt = Some(SeatbeltConfig {
            profile_override: Some("(version 1)(allow default)".into()),
            gui_access: false,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        assert_eq!(p, "(version 1)(allow default)");
    }

    #[test]
    fn paths_with_quotes_and_backslashes_are_escaped() {
        let mut r = req();
        // Hypothetical adversarial input — we never want a path to break out
        // of the quoted string and inject Scheme.
        r.policy.readonly_paths = vec!["/private/tmp/a\"b\\c".into()];
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(subpath \"/private/tmp/a\\\"b\\\\c\")"));
    }

    const FS_SECTION: &str =
        ";; --- policy.readonlyPaths / policy.readwritePaths (shallow-to-deep) ---";
    const RO_STRIP: &str = "(deny file-write* network-bind network-outbound\n";

    /// The policy-derived filesystem section, excluding the always-emitted
    /// baseline rules that also start with `(allow file-read*`.
    fn fs_section(profile: &str) -> &str {
        profile
            .find(FS_SECTION)
            .map(|i| &profile[i..])
            .unwrap_or("")
    }
    const RW_RULE: &str = "(allow file-read* file-write* network-bind network-outbound\n";
    const DENY_RULE: &str =
        "(deny file-read* file-read-metadata file-write* network-bind network-outbound\n";

    #[test]
    fn readwrite_paths_emit_unix_socket_ops() {
        let mut r = req();
        r.policy.readwrite_paths = vec!["/private/tmp/output".into()];
        let p = build_profile(&r).unwrap();
        let idx = p.find(RW_RULE).expect("readwrite rule");
        assert!(p[idx..].contains("(subpath \"/private/tmp/output\")"));
    }

    #[test]
    fn readwrite_unix_socket_ops_are_independent_of_network_policy() {
        // AF_UNIX bind/connect follow the filesystem policy, so a default-deny
        // network policy with denied ingress must still permit them.
        let mut r = req();
        r.policy.readwrite_paths = vec!["/private/tmp/output".into()];
        r.policy.network_egress = Some(egress(NetworkAction::Deny));
        let p = build_profile(&r).unwrap();
        assert!(p.contains(RW_RULE));
        assert!(!p.contains("network-inbound"));
        assert!(!p.contains("(allow network-outbound)"));
    }

    #[test]
    fn denied_paths_deny_outbound_under_default_allow() {
        // `egress.default: allow` emits a bare `(allow network-outbound)`, which
        // on its own grants AF_UNIX `connect()`. A denied subtree must still
        // deny it. Position relative to that unfiltered allow is deliberately
        // not asserted: an unfiltered rule cannot override a path-filtered one
        // in either direction, so pinning the order would encode a constraint
        // that does not exist. The orderings that *do* matter — deny after the
        // filtered read-write allows — are covered by
        // `denied_paths_appear_after_allows_to_override` and
        // `denied_paths_deny_unix_socket_ops_after_allows`.
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Allow));
        r.policy.denied_paths = vec!["/private/tmp/secret".into()];
        let p = build_profile(&r).unwrap();
        let deny_idx = p.find(DENY_RULE).expect("deny must cover network-outbound");
        assert!(p[deny_idx..].contains("(subpath \"/private/tmp/secret\")"));
    }

    #[test]
    fn readonly_paths_do_not_get_unix_socket_ops() {
        let mut r = req();
        r.policy.readonly_paths = vec!["/private/tmp/input".into()];
        let p = build_profile(&r).unwrap();
        assert!(!p.contains(RW_RULE));
        // The only socket mention for a read-only path is the explicit removal.
        assert!(!p.contains("allow network-bind"));
        assert!(fs_section(&p).contains(RO_STRIP));
    }

    #[test]
    fn denied_paths_deny_unix_socket_ops_after_allows() {
        let mut r = req();
        r.policy.readwrite_paths = vec!["/private/tmp".into()];
        r.policy.denied_paths = vec!["/private/tmp/secret".into()];
        let p = build_profile(&r).unwrap();
        let deny_idx = p.find(DENY_RULE).expect("deny must cover socket ops");
        let allow_idx = p.find(RW_RULE).expect("allow rule");
        assert!(
            deny_idx > allow_idx,
            "deny must follow allow so last-match-wins re-denies the socket path"
        );
        assert!(p[deny_idx..].contains("(subpath \"/private/tmp/secret\")"));
    }

    #[test]
    fn denied_paths_name_metadata_reads_explicitly() {
        // The baseline emits an unfiltered `(allow file-read-metadata)` for
        // path resolution. A rule naming that operation outranks one that only
        // reaches it through `file-read*`, so the deny has to name it too or a
        // denied path still answers `stat()`.
        let mut r = req();
        r.policy.readwrite_paths = vec!["/private/tmp".into()];
        r.policy.denied_paths = vec!["/private/tmp/secret".into()];
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow file-read-metadata)"));
        let deny_idx = p
            .find(DENY_RULE)
            .expect("deny must name file-read-metadata");
        assert!(p[deny_idx..].contains("(subpath \"/private/tmp/secret\")"));
    }

    #[test]
    fn nested_readonly_keeps_write_away_from_broader_readwrite() {
        // The nested read-only rule must remove the broader write grant.
        let mut r = req();
        r.policy.readwrite_paths = vec!["/private/tmp".into()];
        r.policy.readonly_paths = vec!["/private/tmp/secret".into()];
        let p = build_profile(&r).unwrap();

        let rw_idx = p.find(RW_RULE).expect("readwrite rule");
        let strip_idx = p.find(RO_STRIP).expect("read-only must strip write");
        assert!(
            strip_idx > rw_idx,
            "deepest intent must be emitted last, profile:\n{p}"
        );
        assert!(p[strip_idx..].contains("(subpath \"/private/tmp/secret\")"));
    }

    #[test]
    fn nested_readwrite_still_wins_inside_broader_readonly() {
        // The mirror case: the deeper read-write entry must survive, otherwise
        // depth ordering would have simply inverted the bug.
        let mut r = req();
        r.policy.readonly_paths = vec!["/private/tmp".into()];
        r.policy.readwrite_paths = vec!["/private/tmp/build".into()];
        let p = build_profile(&r).unwrap();

        let strip_idx = p.find(RO_STRIP).expect("read-only strip");
        let rw_idx = p.find(RW_RULE).expect("readwrite rule");
        assert!(
            rw_idx > strip_idx,
            "deeper readwrite must win, profile:\n{p}"
        );
        assert!(p[rw_idx..].contains("(subpath \"/private/tmp/build\")"));
    }

    #[test]
    fn readonly_socket_strip_survives_a_default_allow_outbound() {
        // `egress.default: "allow"` emits an unfiltered `(allow
        // network-outbound)`. The read-only strip still governs AF_UNIX
        // `connect()` under that subtree, because an unfiltered rule does not
        // override a path-filtered one. Verified end-to-end against
        // `mxc-exec-mac` with a listener created outside the sandbox: this
        // policy denies `connect()` with EPERM, while the same policy with the
        // path moved to `readwrite_paths` connects.
        //
        // Emission order relative to the unfiltered allow is deliberately not
        // asserted — it has no bearing on the outcome.
        let mut r = req();
        r.policy.network_egress = Some(egress(NetworkAction::Allow));
        r.policy.readonly_paths = vec!["/private/tmp/ro".into()];
        let p = build_profile(&r).unwrap();

        let strip_idx = p.find(RO_STRIP).expect("read-only strip");
        assert!(p[strip_idx..].contains("(subpath \"/private/tmp/ro\")"));
    }

    #[test]
    fn readonly_wins_over_readwrite_for_the_same_prepared_path() {
        let mut r = req();
        r.policy.readonly_paths = vec!["/private/tmp/x".into()];
        r.policy.readwrite_paths = vec!["/private/tmp/x".into()];
        let p = build_profile(&r).unwrap();

        assert!(fs_section(&p).contains("(subpath \"/private/tmp/x\")"));
        assert!(
            !p.contains(RW_RULE),
            "aliased readwrite entry must be dropped, profile was:\n{p}"
        );
    }

    #[test]
    fn denied_wins_over_the_same_prepared_readonly_and_readwrite() {
        let mut r = req();
        r.policy.denied_paths = vec!["/private/tmp/x".into()];
        r.policy.readonly_paths = vec!["/private/tmp/x".into()];
        r.policy.readwrite_paths = vec!["/private/tmp/x".into()];
        let p = build_profile(&r).unwrap();

        assert!(!p.contains(FS_SECTION), "profile:\n{p}");
        assert!(!p.contains(RW_RULE), "profile:\n{p}");
        let deny_idx = p.find(DENY_RULE).expect("deny rule");
        assert!(p[deny_idx..].contains("(subpath \"/private/tmp/x\")"));
    }

    #[test]
    fn distinct_paths_survive_resolved_precedence() {
        let mut r = req();
        r.policy.readonly_paths = vec!["/private/tmp/ro".into()];
        r.policy.readwrite_paths = vec!["/private/tmp/rw".into()];
        let p = build_profile(&r).unwrap();

        assert!(fs_section(&p).contains("(subpath \"/private/tmp/ro\")"));
        let rw_idx = p.find(RW_RULE).expect("readwrite rule");
        assert!(p[rw_idx..].contains("(subpath \"/private/tmp/rw\")"));
    }

    #[test]
    fn empty_policy_still_compiles_to_valid_profile() {
        let r = req();
        let p = build_profile(&r).unwrap();
        // Profile must always start with `(version 1)` and contain `(deny default)`.
        assert!(p.starts_with("(version 1)"));
        assert!(p.contains("(deny default)"));
        // No empty `(allow file-read*\n)` block — that would be invalid Scheme.
        assert!(!p.contains("(allow file-read*\n)\n"));
    }

    #[test]
    fn gui_access_adds_mach_services_for_gui_apps() {
        let mut r = req();
        r.policy.ui = UiPolicy {
            disable: false,
            clipboard: ClipboardPolicy::None,
            injection: true,
        };
        r.seatbelt = Some(SeatbeltConfig {
            profile_override: None,
            gui_access: true,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        // Wildcard mach-lookup and mach-register for GUI apps
        assert!(
            p.contains("(allow mach-lookup)"),
            "missing wildcard mach-lookup"
        );
        assert!(p.contains("(allow mach-register)"), "missing mach-register");
        // IOKit for GPU
        assert!(p.contains("(allow iokit-open)"), "missing iokit-open");
        // Temp/cache write access
        assert!(p.contains("/private/tmp"), "missing /private/tmp");
        assert!(
            p.contains("/private/var/folders"),
            "missing /private/var/folders"
        );
    }

    #[test]
    fn gui_access_false_omits_gui_services() {
        let mut r = req();
        r.policy.ui = UiPolicy {
            disable: false,
            clipboard: ClipboardPolicy::None,
            injection: true,
        };
        r.seatbelt = Some(SeatbeltConfig {
            profile_override: None,
            gui_access: false,
            // Pin nested_pty off so this test stays focused on
            // gui_access semantics (otherwise it emits iokit-open).
            nested_pty: false,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        // Basic UI services should be present
        assert!(p.contains("com.apple.windowserver.active"));
        // GUI-specific wildcard should NOT be present
        assert!(!p.contains("(allow mach-lookup)\n"));
        assert!(!p.contains("(allow iokit-open)"));
    }

    #[test]
    fn gui_access_requires_ui_enabled() {
        let mut r = req();
        // ui.disable = true (default) but gui_access = true
        r.seatbelt = Some(SeatbeltConfig {
            profile_override: None,
            gui_access: true,
            // Pin nested_pty off so this test isolates the
            // gui_access + ui.disable interaction.
            nested_pty: false,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        // Should NOT emit GUI services when UI is disabled
        assert!(!p.contains("com.apple.CARenderServer"));
        assert!(!p.contains("(allow iokit-open)"));
        // Should have the deny block instead
        assert!(p.contains("ui.disable: deny WindowServer"));
    }

    #[test]
    fn nested_pty_default_on_emits_pty_rules() {
        // When seatbelt is absent the builder should still
        // emit nested_pty rules — that's the documented default behavior.
        let r = req();
        assert!(r.seatbelt.is_none());
        let p = build_profile(&r).unwrap();
        assert!(p.contains("nestedPty"), "nestedPty comment missing");
        assert!(p.contains("(allow pseudo-tty)"));
        assert!(p.contains("(literal \"/dev/ptmx\")"));
    }

    #[test]
    fn nested_pty_explicit_true_emits_pty_rules() {
        let mut r = req();
        r.seatbelt = Some(SeatbeltConfig {
            nested_pty: true,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow pseudo-tty)"));
        assert!(p.contains("(literal \"/dev/ptmx\")"));
    }

    #[test]
    fn nested_pty_false_denies_pty_allocation_in_every_mode() {
        let mut r = req();
        r.seatbelt = Some(SeatbeltConfig {
            nested_pty: false,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        assert!(!p.contains("(allow pseudo-tty)"), "{p}");
        assert!(p.contains("(deny pseudo-tty)"), "{p}");

        // Allow mode's (allow default) must not reopen a written nestedPty=false.
        let mut r = capture_request(CaptureDenialsMode::Allow, false);
        r.seatbelt.as_mut().unwrap().nested_pty = false;
        let p = capture_profile(&r);
        assert!(!p.contains("(allow pseudo-tty)"), "{p}");
        assert!(
            p.contains("(deny pseudo-tty (with message \"mxc-capture-test\"))\n"),
            "{p}"
        );
        assert!(
            p.contains(
                "(deny file-read* file-write* file-ioctl (with message \"mxc-capture-test\") \
                 (literal \"/dev/ptmx\"))\n"
            ),
            "{p}"
        );
    }

    #[test]
    fn gui_access_does_not_grant_pty_allocation() {
        let mut r = req();
        r.policy.ui = UiPolicy {
            disable: false,
            clipboard: ClipboardPolicy::None,
            injection: true,
        };
        for nested_pty in [true, false] {
            r.seatbelt = Some(SeatbeltConfig {
                gui_access: true,
                nested_pty,
                ..Default::default()
            });
            let p = build_profile(&r).unwrap();
            assert!(p.contains("(allow iokit-open)"));
            assert_eq!(p.contains("(allow pseudo-tty)"), nested_pty, "{p}");
            assert_eq!(p.contains("(deny pseudo-tty)"), !nested_pty, "{p}");
        }
    }

    #[test]
    fn nested_pty_emits_when_gui_access_set_but_ui_disabled() {
        // gui_access=true with ui.disable=true means write_ui_rules
        // suppresses the GUI block — so nested_pty must NOT skip itself.
        let mut r = req();
        assert!(
            r.policy.ui.disable,
            "default ui.disable expected to be true"
        );
        r.seatbelt = Some(SeatbeltConfig {
            gui_access: true,
            nested_pty: true,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        assert!(p.contains("nestedPty"));
        assert!(p.contains("(allow pseudo-tty)"));
        assert!(p.contains("/dev/ptmx"));
    }

    #[test]
    fn keychain_access_default_off_denies_keychain_servers() {
        let r = req();
        let p = build_profile(&r).unwrap();
        assert!(!p.contains(";; --- keychainAccess: "));
        assert!(p.contains(
            "(deny mach-lookup\n    (global-name \"com.apple.SecurityServer\")\n    \
             (global-name-prefix \"com.apple.securityd\")\n)"
        ));
        assert!(!p.contains("com.apple.cfprefsd.daemon"));
        assert!(!p.contains("com.apple.lsd"));
        assert!(!p.contains("/Library/Keychains"));
        assert!(!p.contains("/private/var/db/mds"));
    }

    /// guiAccess cannot reach the Keychain servers, but an extraMachLookups
    /// entry still can, as in V1.
    #[test]
    fn keychain_denies_follow_gui_access_but_not_extra_lookups() {
        let mut r = req();
        r.policy.ui.disable = false;
        r.seatbelt = Some(SeatbeltConfig {
            gui_access: true,
            extra_mach_lookups: vec!["com.apple.SecurityServer".into()],
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        let deny = p.find("keychainAccess=false: deny").expect("keychain deny");
        assert!(p.find("(allow mach-lookup)").unwrap() < deny);
        let extra = p.find(";; --- extraMachLookups").unwrap();
        assert!(deny < extra);
        assert!(extra < p.find("ui.clipboard=none: deny").unwrap());

        r.seatbelt.as_mut().unwrap().keychain_access = true;
        let p = build_profile(&r).unwrap();
        assert!(!p.contains("keychainAccess=false"));
    }

    /// Setting folder grants follow the filesystem policy, so a read-only
    /// parent doesn't block them. Policy entries at or inside a granted
    /// folder are repeated after the grants, and deniedPaths stays last.
    #[test]
    fn filesystem_policy_at_or_inside_setting_grants_still_applies() {
        let mut r = req();
        r.policy.ui.disable = false;
        r.policy.readonly_paths = vec![
            "/private".into(),
            "/Users/profile-test".into(),
            "/Users/profile-test/Library/Keychains".into(),
            "/private/tmp/ro".into(),
        ];
        r.policy.readwrite_paths = vec!["/private/tmp/ro/rw".into()];
        r.policy.denied_paths = vec!["/private/var/folders/xy".into()];
        r.seatbelt = Some(SeatbeltConfig {
            gui_access: true,
            keychain_access: true,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        let gui = p.find("guiAccess: allow writing").unwrap();
        let keychain = p.find("keychainAccess: user keychain").unwrap();
        let fs = p.find(FS_SECTION).unwrap();
        let within = p.find(FS_WITHIN_GRANTS_SECTION).unwrap();
        let denied = p.find("policy.deniedPaths").unwrap();
        assert!(fs < keychain && keychain < gui && gui < within && within < denied);

        let repeated = &p[within..denied];
        let strip = |path: &str| format!("{RO_STRIP}    (subpath \"{path}\")");
        assert!(!repeated.contains(&strip("/private")), "{repeated}");
        assert!(
            !repeated.contains(&strip("/Users/profile-test")),
            "{repeated}"
        );
        assert!(repeated.contains(&strip("/Users/profile-test/Library/Keychains")));
        let tmp_ro = repeated.find(&strip("/private/tmp/ro")).unwrap();
        let tmp_rw = repeated
            .find(&format!("{RW_RULE}    (subpath \"/private/tmp/ro/rw\")"))
            .unwrap();
        assert!(tmp_ro < tmp_rw, "{repeated}");
    }

    #[test]
    fn keychain_access_true_allows_securityd_mach_services() {
        let mut r = req();
        r.seatbelt = Some(SeatbeltConfig {
            keychain_access: true,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        assert!(p.contains("keychainAccess"));
        // Mach surface
        assert!(p.contains("com.apple.SecurityServer"));
        assert!(p.contains("com.apple.securityd"));
        assert!(p.contains("com.apple.cfprefsd.daemon"));
        assert!(p.contains("com.apple.xpcd"));
        assert!(p.contains("(global-name-regex #\"^com\\.apple\\.lsd\\.\")"));
    }

    #[test]
    fn keychain_access_true_allows_filesystem_paths() {
        let mut r = req();
        r.seatbelt = Some(SeatbeltConfig {
            keychain_access: true,
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        // /Library/Keychains and /System/Library/Keychains are read via
        // the baseline /Library and /System read-only allows; we don't
        // re-emit them here.
        assert!(p.contains("(subpath \"/private/var/db/mds\")"));
        // Read+write surfaces
        assert!(
            p.contains("(subpath \"/Users/profile-test/Library/Keychains\")"),
            "missing user keychain subpath"
        );
        assert!(p.contains("(subpath \"/private/var/folders\")"));
    }

    #[test]
    fn extra_mach_lookups_emits_grouped_allow_form() {
        let mut r = req();
        r.seatbelt = Some(SeatbeltConfig {
            extra_mach_lookups: vec![
                "com.apple.example.one".to_string(),
                "com.apple.example.two".to_string(),
            ],
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        assert!(p.contains(";; --- extraMachLookups"));
        assert!(p.contains("(allow mach-lookup\n    (global-name \"com.apple.example.one\")\n    (global-name \"com.apple.example.two\")\n)"));
    }

    #[test]
    fn extra_mach_lookups_omitted_when_empty() {
        let mut r = req();
        r.seatbelt = Some(SeatbeltConfig::default());
        let p = build_profile(&r).unwrap();
        assert!(!p.contains("extraMachLookups"));
    }

    #[test]
    fn extra_mach_lookups_escape_embedded_quotes() {
        let mut r = req();
        r.seatbelt = Some(SeatbeltConfig {
            extra_mach_lookups: vec!["weird\"name".to_string()],
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(global-name \"weird\\\"name\")"));
    }

    #[test]
    fn developer_dir_rule_grants_read_only_subpath() {
        let mut out = String::new();
        write_developer_dir_rule(&mut out, Some("/Applications/Xcode.app"));
        assert!(out.contains("(allow file-read* (subpath \"/Applications/Xcode.app\"))"));
        // The xcrun shims only need to read it; a write grant would widen the
        // sandbox for no benefit.
        assert!(!out.contains("file-write"));
    }

    #[test]
    fn developer_dir_rule_escapes_embedded_quotes() {
        let mut out = String::new();
        write_developer_dir_rule(&mut out, Some("/tmp/we\"ird/Developer"));
        assert!(out.contains("(subpath \"/tmp/we\\\"ird/Developer\")"));
    }

    #[test]
    fn developer_dir_absent_emits_nothing() {
        let mut out = String::new();
        write_developer_dir_rule(&mut out, None);
        assert!(out.is_empty());
    }

    #[test]
    fn profile_uses_prepared_paths_instead_of_host_discovery() {
        let mut request = req();
        request.policy.readonly_paths = vec!["/unprepared/path".into()];
        request.seatbelt = Some(SeatbeltConfig {
            keychain_access: true,
            ..Default::default()
        });
        let inputs = ProfileInputs {
            readonly_paths: vec!["/prepared/readonly".into()],
            readwrite_paths: vec!["/prepared/readwrite".into()],
            denied_paths: vec!["/prepared/denied".into()],
            developer_dir: Some("/Applications/ProfileTest.app".into()),
            user_keychains: Some("/Users/prepared/Library/Keychains".into()),
            capture_tag: None,
        };
        let profile = super::build_profile_with_proxy(&request, None, &inputs).unwrap();
        for path in [
            "/prepared/readonly",
            "/prepared/readwrite",
            "/prepared/denied",
            "/Applications/ProfileTest.app",
            "/Users/prepared/Library/Keychains",
        ] {
            assert!(
                profile.contains(&format!("(subpath \"{path}\")")),
                "{profile}"
            );
        }
        assert!(!profile.contains("/unprepared/path"), "{profile}");
    }

    #[test]
    fn keychain_access_requires_a_prepared_user_directory() {
        let mut request = req();
        request.seatbelt = Some(SeatbeltConfig {
            keychain_access: true,
            ..Default::default()
        });
        let error =
            super::build_profile_with_proxy(&request, None, &ProfileInputs::default()).unwrap_err();
        assert!(
            error
                .to_string()
                .contains("not prepared for keychainAccess"),
            "{error}"
        );
    }

    fn capture_request(mode: CaptureDenialsMode, gui_access: bool) -> ExecutionRequest {
        let mut r = req();
        r.policy.ui = UiPolicy {
            disable: !gui_access,
            clipboard: ClipboardPolicy::None,
            injection: false,
        };
        r.policy.network_egress = Some(egress(NetworkAction::Allow));
        r.seatbelt = Some(SeatbeltConfig {
            gui_access,
            capture_denials: Some(crate::mxc_common::models::CaptureDenialsConfig {
                mode,
                ..Default::default()
            }),
            ..Default::default()
        });
        r
    }

    fn capture_profile(request: &ExecutionRequest) -> String {
        let inputs = ProfileInputs {
            denied_paths: vec!["/prepared/denied".into()],
            capture_tag: Some("mxc-capture-test".into()),
            ..Default::default()
        };
        super::build_profile_with_proxy(request, None, &inputs).unwrap()
    }

    fn deny_lines(profile: &str) -> Vec<&str> {
        profile
            .lines()
            .filter(|line| line.starts_with("(deny "))
            .collect()
    }

    #[test]
    fn capture_block_mode_tags_every_deny_rule() {
        let p = capture_profile(&capture_request(CaptureDenialsMode::Block, false));
        assert!(
            p.contains("(deny default (with message \"mxc-capture-test\"))"),
            "{p}"
        );
        // ui.disable, clipboard, injection, hostLoopback, and deniedPaths denies.
        let denies = deny_lines(&p);
        assert!(denies.len() >= 6, "{p}");
        for line in denies {
            assert!(
                line.contains(" (with message \"mxc-capture-test\")"),
                "{line}"
            );
        }
        assert!(p.contains(
            "(deny network-outbound (with message \"mxc-capture-test\") (remote ip \"localhost:*\"))"
        ));
    }

    #[test]
    fn capture_allow_mode_reports_instead_of_denying_by_default() {
        let r = capture_request(CaptureDenialsMode::Allow, false);
        let p = capture_profile(&r);
        assert!(p.starts_with(
            "(version 1)\n(allow default (with report) (with message \"mxc-capture-test\"))\n"
        ));
        assert!(!p.contains("(deny default"), "{p}");
        // Explicit denies stay enforced.
        assert!(p.contains(
            "(deny file-read* file-read-metadata file-write* network-bind network-outbound (with message \"mxc-capture-test\")\n"
        ));
        // Omitted settings allow and report; only written ones are enforced.
        let settings = [
            ("ui.disable", "ui.disable: deny"),
            ("ui.clipboard", "ui.clipboard=none: deny"),
            ("ui.injection", "ui.injection=false: deny"),
            ("keychainAccess", "keychainAccess=false: deny"),
        ];
        let mut written = capture_request(CaptureDenialsMode::Allow, false);
        written.policy.ui_fields_specified.disable = true;
        written.seatbelt.as_mut().unwrap().keychain_access_specified = true;
        for (request, enforced) in [(&r, [false; 4]), (&written, [true, false, false, true])] {
            let p = capture_profile(request);
            for ((field, deny), enforced) in settings.into_iter().zip(enforced) {
                assert_eq!(p.contains(deny), enforced, "{deny}\n{p}");
                let report = format!(";; --- {field} omitted: allow and report ---\n");
                assert_eq!(p.contains(&report), !enforced, "{field}\n{p}");
            }
        }
        assert!(capture_profile(&written).contains(
            ";; --- ui.clipboard omitted: allow and report ---\n\
             (allow mach-lookup (with report) (with message \"mxc-capture-test\") \
             (global-name-prefix \"com.apple.pasteboard.\"))\n"
        ));
    }

    #[test]
    fn capture_allow_mode_preserves_loopback_policy_and_proxy_exception() {
        let inputs = ProfileInputs {
            capture_tag: Some("mxc-capture-test".into()),
            ..Default::default()
        };
        let proxy = ProxyAddress::new("127.0.0.1".into(), 44444);
        for loopback in [NetworkAction::Deny, NetworkAction::Allow] {
            let mut request = capture_request(CaptureDenialsMode::Allow, false);
            request.policy.network_egress = Some(egress(NetworkAction::Deny));
            request.policy.network_ingress =
                Some(crate::mxc_common::models::NetworkIngressPolicy {
                    default: NetworkAction::Allow,
                    host_loopback: loopback,
                });
            let loopback_rule = match loopback {
                NetworkAction::Deny =>
                    "(deny network-outbound (with message \"mxc-capture-test\") (remote ip \"localhost:*\"))",
                NetworkAction::Allow =>
                    "(allow network-outbound (remote ip \"localhost:*\"))",
            };
            let profile = super::build_profile_with_proxy(&request, None, &inputs).unwrap();
            assert!(profile.contains(loopback_rule), "{profile}");

            let profile = super::build_profile_with_proxy(&request, Some(&proxy), &inputs).unwrap();
            let loopback_position = profile.find(loopback_rule).expect("loopback rule");
            let proxy_position = profile
                .find("(allow network-outbound (remote ip \"localhost:44444\"))")
                .expect("proxy-port exception");
            assert!(proxy_position > loopback_position, "{profile}");
        }
    }

    #[test]
    fn capture_reports_broad_gui_grants_under_the_grant_tag() {
        let p = capture_profile(&capture_request(CaptureDenialsMode::Block, true));
        let report = " (with report) (with message \"mxc-capture-test:grant\")";
        for op in [
            "mach-lookup",
            "mach-register",
            "iokit-open",
            GUI_POSIX_SHM_OPERATIONS,
        ] {
            assert!(p.contains(&format!("(allow {op}{report})")), "{op}: {p}");
        }
    }

    #[test]
    fn capture_without_a_prepared_tag_fails_closed() {
        let request = capture_request(CaptureDenialsMode::Block, false);
        let error =
            super::build_profile_with_proxy(&request, None, &ProfileInputs::default()).unwrap_err();
        assert!(
            matches!(&error, ProfileError::Host(m) if m.contains("log tag was not prepared")),
            "{error}"
        );

        let mut request = request;
        request.seatbelt.as_mut().unwrap().profile_override = Some("(version 1)".into());
        let error =
            super::build_profile_with_proxy(&request, None, &ProfileInputs::default()).unwrap_err();
        assert!(
            matches!(&error, ProfileError::Policy(m) if m.contains("profileOverride")),
            "{error}"
        );
    }

    fn custom_rules(
        default: SeatbeltCustomDefault,
        allow: &[&str],
        deny: &[&str],
    ) -> SeatbeltCustomRules {
        SeatbeltCustomRules {
            default: Some(default),
            allow: allow.iter().map(|s| s.to_string()).collect(),
            deny: deny.iter().map(|s| s.to_string()).collect(),
        }
    }

    /// guiAccess with every custom block set to `default: deny` and one
    /// exact and one prefix entry in each list.
    fn custom_request() -> ExecutionRequest {
        let mut r = req();
        r.policy.ui.disable = false;
        let rules = |a: &str, d: &str| {
            custom_rules(SeatbeltCustomDefault::Deny, &[a, &format!("{a}.*")], &[d])
        };
        r.seatbelt = Some(SeatbeltConfig {
            gui_access: true,
            custom_io_kits: Some(custom_rules(
                SeatbeltCustomDefault::Deny,
                &["AGXDeviceUserClient", "IOSurface*"],
                &["AppleUSB*"],
            )),
            custom_mach_lookups: Some(rules("com.example.lookup", "com.example.blocked")),
            custom_mach_registers: Some(SeatbeltCustomMachRegisters {
                global: Some(rules("com.example.global", "com.example.global.no")),
                local: Some(rules("com.example.local", "com.example.local.no")),
            }),
            custom_posix_shm: Some(SeatbeltCustomPosixShm {
                read: vec!["apple.shm.notification_center".into()],
                read_write: vec!["/example.rw".into()],
                own: vec!["/example.app.*".into()],
                deny: vec!["/example.app.secret".into()],
                ..Default::default()
            }),
            ..Default::default()
        });
        r
    }

    #[test]
    fn custom_rules_replace_gui_access_grants() {
        let p = build_profile(&custom_request()).unwrap();
        for broad in [
            "(allow mach-lookup)",
            "(allow mach-register)",
            "(allow mach-register (",
            "(allow iokit-open)",
        ] {
            assert!(!p.contains(broad), "{broad}: {p}");
        }
        assert!(!grants_all_shm(&p), "{p}");
        for rule in [
            "(allow iokit-open\n    (iokit-user-client-class \"AGXDeviceUserClient\")\n    \
             (iokit-user-client-class-regex #\"^IOSurface\")\n)",
            "(allow mach-lookup\n    (global-name \"com.example.lookup\")\n    \
             (global-name-prefix \"com.example.lookup.\")\n)",
            "(allow mach-register\n    (global-name \"com.example.global\")\n    \
             (global-name-prefix \"com.example.global.\")\n)",
            "(allow mach-register\n    (local-name \"com.example.local\")\n    \
             (local-name-prefix \"com.example.local.\")\n)",
            "(deny iokit-open\n    (iokit-user-client-class-regex #\"^AppleUSB\")\n)",
            "(deny mach-lookup\n    (global-name \"com.example.blocked\")\n)",
            "(deny mach-register\n    (local-name \"com.example.local.no\")\n)",
            "(allow ipc-posix-shm-read-data ipc-posix-shm-read-metadata\n    \
             (ipc-posix-name \"apple.shm.notification_center\")\n)\n\
             (deny ipc-posix-shm-write-data ipc-posix-shm-write-create ipc-posix-shm-write-unlink\n    \
             (ipc-posix-name \"apple.shm.notification_center\")\n)",
            "(allow ipc-posix-shm-read-data ipc-posix-shm-read-metadata ipc-posix-shm-write-data\n    \
             (ipc-posix-name \"/example.rw\")\n)\n\
             (deny ipc-posix-shm-write-create ipc-posix-shm-write-unlink\n    \
             (ipc-posix-name \"/example.rw\")\n)",
            "(allow ipc-posix-shm-read-data ipc-posix-shm-read-metadata ipc-posix-shm-write-data \
             ipc-posix-shm-write-create ipc-posix-shm-write-unlink\n    \
             (ipc-posix-name-prefix \"/example.app.\")\n)\n;; ---",
            "(deny ipc-posix-shm* ipc-posix-shm-read-data ipc-posix-shm-read-metadata \
             ipc-posix-shm-write-data ipc-posix-shm-write-create ipc-posix-shm-write-unlink\n    \
             (ipc-posix-name \"/example.app.secret\")\n)",
        ] {
            assert!(p.contains(rule), "{rule}: {p}");
        }
        // guiAccess's filesystem grant remains.
        assert!(p.contains("(subpath \"/private/tmp\")"));
    }

    /// Each block replaces only its own grant; register scopes are separate.
    #[test]
    fn omitted_custom_blocks_keep_gui_access_grants() {
        let mut r = custom_request();
        let config = r.seatbelt.as_mut().unwrap();
        config.custom_io_kits = None;
        config.custom_mach_lookups = None;
        config.custom_posix_shm = None;
        config.custom_mach_registers.as_mut().unwrap().global = None;
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow iokit-open)"), "{p}");
        assert!(
            p.contains(&format!("(allow {GUI_POSIX_SHM_OPERATIONS})")),
            "{p}"
        );
        assert!(p.contains("(allow mach-lookup)"), "{p}");
        assert!(
            p.contains("(allow mach-register (global-name-prefix \"\"))"),
            "{p}"
        );

        let config = r.seatbelt.as_mut().unwrap();
        config.custom_mach_registers = Some(SeatbeltCustomMachRegisters {
            global: Some(custom_rules(SeatbeltCustomDefault::Deny, &[], &[])),
            local: None,
        });
        let p = build_profile(&r).unwrap();
        assert!(
            p.contains("(allow mach-register (local-name-prefix \"\"))"),
            "{p}"
        );
    }

    /// Custom lists apply without guiAccess too, and `default` grants the
    /// whole operation in that scope.
    #[test]
    fn custom_default_allow_grants_the_scope() {
        let mut r = req();
        r.seatbelt = Some(SeatbeltConfig {
            custom_io_kits: Some(custom_rules(SeatbeltCustomDefault::Allow, &[], &[])),
            custom_mach_registers: Some(SeatbeltCustomMachRegisters {
                global: None,
                local: Some(custom_rules(SeatbeltCustomDefault::Allow, &[], &[])),
            }),
            custom_posix_shm: Some(SeatbeltCustomPosixShm {
                default: Some(SeatbeltPosixShmAccess::Create),
                ..Default::default()
            }),
            ..Default::default()
        });
        let p = build_profile(&r).unwrap();
        assert!(p.contains("(allow iokit-open)\n"), "{p}");
        assert!(
            p.contains(
                "(allow ipc-posix-shm-read-data ipc-posix-shm-read-metadata \
                 ipc-posix-shm-write-data ipc-posix-shm-write-create)\n"
            ),
            "{p}"
        );
        assert!(
            p.contains("(allow mach-register (local-name-prefix \"\"))"),
            "{p}"
        );
        assert!(!p.contains("(allow mach-lookup)"), "{p}");
    }

    /// Each shared memory entry gets exactly its list's access, and longer
    /// names come later so they override shorter prefixes.
    #[test]
    fn posix_shm_entries_set_exact_levels_broadest_first() {
        let mut r = req();
        r.seatbelt = Some(SeatbeltConfig {
            custom_posix_shm: Some(SeatbeltCustomPosixShm {
                default: Some(SeatbeltPosixShmAccess::Own),
                read: strings(&["/app.*"]),
                read_write: strings(&["/app.cache"]),
                create: strings(&["/app.c*"]),
                own: strings(&["/a*"]),
                ..Default::default()
            }),
            ..Default::default()
        });
        crate::seatbelt_common::seatbelt_policy::validate_seatbelt_custom_rules(&r).unwrap();
        let p = build_profile(&r).unwrap();
        let all = "ipc-posix-shm-read-data ipc-posix-shm-read-metadata ipc-posix-shm-write-data \
                   ipc-posix-shm-write-create ipc-posix-shm-write-unlink";
        let rules = [
            format!("(allow {all})\n"),
            format!("(allow {all}\n    (ipc-posix-name-prefix \"/a\")\n)\n;; ---"),
            "(allow ipc-posix-shm-read-data ipc-posix-shm-read-metadata\n    \
             (ipc-posix-name-prefix \"/app.\")\n)\n\
             (deny ipc-posix-shm-write-data ipc-posix-shm-write-create ipc-posix-shm-write-unlink\n    \
             (ipc-posix-name-prefix \"/app.\")\n)\n"
                .to_string(),
            "(deny ipc-posix-shm-write-unlink\n    (ipc-posix-name-prefix \"/app.c\")\n)\n".to_string(),
            "(deny ipc-posix-shm-write-create ipc-posix-shm-write-unlink\n    \
             (ipc-posix-name \"/app.cache\")\n)\n"
                .to_string(),
        ];
        let mut last = 0;
        for rule in &rules {
            let at = p
                .find(rule.as_str())
                .unwrap_or_else(|| panic!("{rule}\n{p}"));
            assert!(at > last, "{rule}\n{p}");
            last = at;
        }

        #[cfg(target_os = "macos")]
        {
            let output = sandbox_exec(&p, &["/usr/bin/true"]);
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }

    /// customIoKits replaces guiAccess's IOKit grant, but `ui.injection`
    /// still grants HID input.
    #[test]
    fn custom_io_kits_keep_the_injection_hid_grant() {
        let mut r = custom_request();
        let hid = "(allow iokit-open (iokit-user-client-class \"IOHIDLibUserClient\"))";
        r.policy.ui.injection = true;
        assert!(build_profile(&r).unwrap().contains(hid));
        r.policy.ui.injection = false;
        assert!(!build_profile(&r).unwrap().contains(hid));
    }

    /// Custom denies follow the allows from explicit settings, and those
    /// settings' denies follow the custom allows.
    #[test]
    fn custom_rules_order_around_setting_rules() {
        let mut r = custom_request();
        r.policy.ui.injection = false;
        r.policy.denied_paths = vec!["/private/tmp/denied".into()];
        let p = build_profile(&r).unwrap();
        let custom_allow = p.find(";; --- customMachLookups.allow").unwrap();
        let keychain_deny = p.find("keychainAccess=false: deny").unwrap();
        let injection_deny = p.find("ui.injection=false").unwrap();
        let custom_deny = p.find(";; --- customMachLookups.deny").unwrap();
        let fs_deny = p.find(";; --- policy.deniedPaths").unwrap();
        assert!(custom_allow < injection_deny && custom_allow < keychain_deny);
        assert!(keychain_deny < custom_deny && custom_deny < fs_deny);
        assert!(p.find("ui enabled: allow WindowServer").unwrap() < custom_deny);
        let shm_own = p.find(";; --- customPosixShm.own").unwrap();
        let shm_deny = p.find(";; --- customPosixShm.deny").unwrap();
        assert!(custom_allow < shm_own && shm_own < custom_deny);
        assert!(custom_deny < shm_deny && shm_deny < fs_deny);
    }

    #[test]
    fn capture_reports_custom_default_allow_grants() {
        let mut r = capture_request(CaptureDenialsMode::Block, true);
        r.seatbelt.as_mut().unwrap().custom_mach_lookups =
            Some(custom_rules(SeatbeltCustomDefault::Allow, &[], &[]));
        let p = capture_profile(&r);
        assert!(
            p.contains(
                ";; --- customMachLookups: default allow ---\n\
             (allow mach-lookup (with report) (with message \"mxc-capture-test:grant\"))\n"
            ),
            "{p}"
        );
    }

    #[test]
    fn capture_tagging_leaves_multiline_names_and_paths_unchanged() {
        let names = [
            "com.example\n(deny embedded)",
            "com.example.blocked\n(deny \"quoted\") ; end",
        ];
        let path = "/tmp/mxc\n(deny file-read-data";
        let mut r = capture_request(CaptureDenialsMode::Block, false);
        r.seatbelt.as_mut().unwrap().custom_mach_lookups = Some(custom_rules(
            SeatbeltCustomDefault::Allow,
            &names[..1],
            &names[1..],
        ));
        let inputs = ProfileInputs {
            readonly_paths: vec![path.into()],
            capture_tag: Some("mxc-capture-test".into()),
            ..Default::default()
        };
        let p = super::build_profile_with_proxy(&r, None, &inputs).unwrap();
        for text in names.into_iter().chain([path]) {
            assert!(p.contains(&quote_scheme(text)), "{text:?}\n{p}");
        }
        assert!(
            p.contains("(deny default (with message \"mxc-capture-test\"))"),
            "{p}"
        );

        #[cfg(target_os = "macos")]
        {
            let output = std::process::Command::new("/usr/bin/sandbox-exec")
                .args(["-p", &p, "/usr/bin/true"])
                .output()
                .expect("sandbox-exec runs");
            assert!(
                output.status.success(),
                "{}\n{p}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn custom_rule_profiles_compile_in_the_macos_sandbox() {
        let mut allow_all = custom_request();
        let config = allow_all.seatbelt.as_mut().unwrap();
        config.gui_access = false;
        let allow = Some(SeatbeltCustomDefault::Allow);
        config.custom_io_kits.as_mut().unwrap().default = allow;
        let registers = config.custom_mach_registers.as_mut().unwrap();
        registers.global.as_mut().unwrap().default = allow;
        registers.local.as_mut().unwrap().default = allow;
        config.custom_posix_shm.as_mut().unwrap().default = Some(SeatbeltPosixShmAccess::Own);
        for request in [custom_request(), allow_all] {
            let profile = build_profile(&request).unwrap();
            let output = std::process::Command::new("/usr/bin/sandbox-exec")
                .args(["-p", &profile, "/usr/bin/true"])
                .output()
                .expect("sandbox-exec runs");
            assert!(
                output.status.success(),
                "{}\n{profile}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn capture_profiles_compile_in_the_macos_sandbox() {
        for (mode, gui_access) in [
            (CaptureDenialsMode::Block, false),
            (CaptureDenialsMode::Allow, false),
            (CaptureDenialsMode::Block, true),
            (CaptureDenialsMode::Allow, true),
        ] {
            let profile = capture_profile(&capture_request(mode, gui_access));
            let output = std::process::Command::new("/usr/bin/sandbox-exec")
                .args(["-p", &profile, "/usr/bin/true"])
                .output()
                .expect("sandbox-exec runs");
            assert!(
                output.status.success(),
                "{mode:?}/{gui_access}: {}\n{profile}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }

    #[cfg(target_os = "macos")]
    fn sandbox_exec(profile: &str, program: &[&str]) -> std::process::Output {
        std::process::Command::new("/usr/bin/sandbox-exec")
            .args(["-p", profile])
            .args(program)
            .output()
            .expect("sandbox-exec runs")
    }

    /// Every custom block, with each default, mixed with every setting
    /// (written or omitted) and capture mode: the profile compiles, guiAccess
    /// never adds back a grant a block replaced, settings' denies and custom
    /// denies follow all custom allows, and allow mode reports rather than
    /// enforces the denies of omitted settings.
    #[cfg(target_os = "macos")]
    #[test]
    fn custom_rules_hold_across_setting_combinations() {
        let custom_lines = |p: &str, deny: bool| -> Vec<usize> {
            p.match_indices(";; --- custom")
                .filter(|(at, _)| p[*at..].lines().next().unwrap().contains(".deny ") == deny)
                .map(|(at, _)| at)
                .collect()
        };
        let captures = [
            None,
            Some(CaptureDenialsMode::Block),
            Some(CaptureDenialsMode::Allow),
        ];
        let mut combinations = 0;
        for written in [false, true] {
            for gui_access in [false, true] {
                for keychain_access in [false, true] {
                    for clipboard in [ClipboardPolicy::None, ClipboardPolicy::All] {
                        for injection in [false, true] {
                            for capture in captures {
                                for default in [None, Some(SeatbeltCustomDefault::Allow)] {
                                    let mut r = custom_request();
                                    r.policy.ui.clipboard = clipboard.clone();
                                    r.policy.ui.injection = injection;
                                    r.policy.ui_fields_specified =
                                        crate::mxc_common::models::UiFieldsSpecified {
                                            disable: written,
                                            clipboard: written,
                                            injection: written,
                                        };
                                    let config = r.seatbelt.as_mut().unwrap();
                                    config.gui_access = gui_access;
                                    config.keychain_access = keychain_access;
                                    config.keychain_access_specified = written;
                                    config.capture_denials = capture.map(|mode| {
                                        crate::mxc_common::models::CaptureDenialsConfig {
                                            mode,
                                            ..Default::default()
                                        }
                                    });
                                    config.custom_io_kits.as_mut().unwrap().default = default;
                                    config.custom_mach_lookups.as_mut().unwrap().default = default;
                                    let registers = config.custom_mach_registers.as_mut().unwrap();
                                    registers.global.as_mut().unwrap().default = default;
                                    registers.local.as_mut().unwrap().default = default;
                                    config.custom_posix_shm.as_mut().unwrap().default =
                                        default.map(|_| SeatbeltPosixShmAccess::Own);
                                    let label = format!(
                                    "written={written} gui={gui_access} keychain={keychain_access} \
                                     clipboard={clipboard:?} injection={injection} \
                                     capture={capture:?} default={default:?}"
                                );
                                    crate::seatbelt_common::seatbelt_policy::validate_seatbelt_custom_rules(&r)
                                    .unwrap_or_else(|e| panic!("{label}: {e}"));
                                    let inputs = ProfileInputs {
                                        capture_tag: Some("mxc-capture-test".into()),
                                        user_keychains: keychain_access.then(|| {
                                            "/Users/profile-test/Library/Keychains".into()
                                        }),
                                        ..Default::default()
                                    };
                                    let p = super::build_profile_with_proxy(&r, None, &inputs)
                                        .unwrap_or_else(|e| panic!("{label}: {e}"));

                                    if default.is_none() {
                                        for op in ["mach-lookup", "iokit-open"] {
                                            for broad in [
                                                format!("(allow {op})"),
                                                format!(
                                                    "(allow {op} (with report) (with message \
                                                     \"mxc-capture-test{GRANT_TAG_SUFFIX}\"))\n"
                                                ),
                                            ] {
                                                assert!(
                                                    !p.contains(&broad),
                                                    "{label}: {broad}\n{p}"
                                                );
                                            }
                                        }
                                        assert!(
                                            !p.contains("(allow mach-register ("),
                                            "{label}\n{p}"
                                        );
                                        assert!(!grants_all_shm(&p), "{label}\n{p}");
                                    }
                                    let last_allow = *custom_lines(&p, false).last().unwrap();
                                    let denies = custom_lines(&p, true);
                                    assert_eq!(denies.len(), 5, "{label}\n{p}");
                                    assert!(denies[0] > last_allow, "{label}\n{p}");
                                    let enforced =
                                        written || capture != Some(CaptureDenialsMode::Allow);
                                    for (on, deny, field) in [
                                        (
                                            !keychain_access,
                                            "keychainAccess=false: deny",
                                            "keychainAccess",
                                        ),
                                        (
                                            clipboard == ClipboardPolicy::None,
                                            "ui.clipboard=none",
                                            "ui.clipboard",
                                        ),
                                        (!injection, "ui.injection=false", "ui.injection"),
                                    ] {
                                        let report = format!("{field} omitted: allow and report");
                                        for (marker, expected) in [
                                            (deny, on && enforced),
                                            (report.as_str(), on && !enforced),
                                        ] {
                                            let at = p.find(marker);
                                            assert_eq!(
                                                at.is_some(),
                                                expected,
                                                "{label}: {marker}\n{p}"
                                            );
                                            if let Some(at) = at {
                                                assert!(
                                                    last_allow < at && at < denies[0],
                                                    "{label}: {marker}\n{p}"
                                                );
                                            }
                                        }
                                    }

                                    let output = sandbox_exec(&p, &["/usr/bin/true"]);
                                    assert!(
                                        output.status.success(),
                                        "{label}: {}\n{p}",
                                        String::from_utf8_lossy(&output.stderr)
                                    );
                                    combinations += 1;
                                }
                            }
                        }
                    }
                }
            }
        }
        assert_eq!(combinations, 192);
    }

    /// Quotes, backslashes, parentheses, and newlines in names stay inside
    /// their string literal instead of adding rules to the profile.
    #[cfg(target_os = "macos")]
    #[test]
    fn custom_entries_cannot_add_profile_rules() {
        let hostile = [
            "x\") (allow default) (\"",
            "x\\\") (allow default) ;",
            "x)\n(allow default)\n(",
        ];
        let names: Vec<String> = hostile.iter().map(|s| s.to_string()).collect();
        let rules = || custom_rules(SeatbeltCustomDefault::Deny, &hostile, &hostile);
        let mut r = req();
        r.seatbelt = Some(SeatbeltConfig {
            custom_mach_lookups: Some(rules()),
            custom_mach_registers: Some(SeatbeltCustomMachRegisters {
                global: Some(rules()),
                local: Some(rules()),
            }),
            custom_posix_shm: Some(SeatbeltCustomPosixShm {
                read: names.clone(),
                deny: names,
                ..Default::default()
            }),
            ..Default::default()
        });
        crate::seatbelt_common::seatbelt_policy::validate_seatbelt_custom_rules(&r).unwrap();
        let hostile_profile = build_profile(&r).unwrap();
        let control = build_profile(&req()).unwrap();

        // `id -un` needs a Mach lookup the baseline denies, so it prints the
        // numeric uid unless something allowed every operation.
        let uid = String::from_utf8(
            std::process::Command::new("/usr/bin/id")
                .arg("-u")
                .output()
                .unwrap()
                .stdout,
        )
        .unwrap();
        for profile in [&control, &hostile_profile] {
            let output = sandbox_exec(profile, &["/usr/bin/id", "-un"]);
            assert!(
                output.status.success(),
                "{}\n{profile}",
                String::from_utf8_lossy(&output.stderr)
            );
            assert_eq!(String::from_utf8_lossy(&output.stdout), uid, "{profile}");
        }
    }

    fn strings(entries: &[&str]) -> Vec<String> {
        entries.iter().map(|s| s.to_string()).collect()
    }

    /// Every list of every custom block holds several exact and prefix
    /// entries; each one lands, in order, in its own list's rule.
    #[test]
    fn every_list_emits_each_of_several_entries() {
        let mut r = req();
        r.policy.ui.disable = false;
        let mach = |scope: &str| {
            custom_rules(
                SeatbeltCustomDefault::Deny,
                &[
                    &format!("com.example.{scope}.one"),
                    &format!("com.example.{scope}.two"),
                    &format!("com.example.{scope}.app.*"),
                    &format!("org.other.{scope}.*"),
                ],
                &[
                    &format!("com.example.{scope}.app.no"),
                    &format!("com.example.{scope}.app.secret.*"),
                    &format!("org.other.{scope}.no"),
                ],
            )
        };
        r.seatbelt = Some(SeatbeltConfig {
            gui_access: true,
            custom_io_kits: Some(custom_rules(
                SeatbeltCustomDefault::Deny,
                &[
                    "AGXDeviceUserClient",
                    "IOSurfaceRootUserClient",
                    "IOAccel*",
                    "AppleM2*",
                ],
                &["IOAccelBad", "AppleM2Scaler*", "AppleUSB*"],
            )),
            custom_mach_lookups: Some(mach("lookup")),
            custom_mach_registers: Some(SeatbeltCustomMachRegisters {
                global: Some(mach("global")),
                local: Some(mach("local")),
            }),
            custom_posix_shm: Some(SeatbeltCustomPosixShm {
                deny: strings(&["/o.pre.no", "/w.pre.no", "/d.pre.*"]),
                ..Default::default()
            }),
            ..Default::default()
        });
        crate::seatbelt_common::seatbelt_policy::validate_seatbelt_custom_rules(&r).unwrap();
        let p = build_profile(&r).unwrap();

        let mut expected = vec![
            "(allow iokit-open\n    (iokit-user-client-class \"AGXDeviceUserClient\")\n    \
             (iokit-user-client-class \"IOSurfaceRootUserClient\")\n    \
             (iokit-user-client-class-regex #\"^IOAccel\")\n    \
             (iokit-user-client-class-regex #\"^AppleM2\")\n)\n"
                .to_string(),
            "(deny iokit-open\n    (iokit-user-client-class \"IOAccelBad\")\n    \
             (iokit-user-client-class-regex #\"^AppleM2Scaler\")\n    \
             (iokit-user-client-class-regex #\"^AppleUSB\")\n)\n"
                .to_string(),
        ];
        for (scope, op, exact, prefix) in [
            ("lookup", "mach-lookup", "global-name", "global-name-prefix"),
            (
                "global",
                "mach-register",
                "global-name",
                "global-name-prefix",
            ),
            ("local", "mach-register", "local-name", "local-name-prefix"),
        ] {
            expected.push(format!(
                "(allow {op}\n    ({exact} \"com.example.{scope}.one\")\n    \
                 ({exact} \"com.example.{scope}.two\")\n    \
                 ({prefix} \"com.example.{scope}.app.\")\n    \
                 ({prefix} \"org.other.{scope}.\")\n)\n"
            ));
            expected.push(format!(
                "(deny {op}\n    ({exact} \"com.example.{scope}.app.no\")\n    \
                 ({prefix} \"com.example.{scope}.app.secret.\")\n    \
                 ({exact} \"org.other.{scope}.no\")\n)\n"
            ));
        }
        expected.push(format!(
            "(deny {}\n    (ipc-posix-name \"/o.pre.no\")\n    (ipc-posix-name \"/w.pre.no\")\n    \
             (ipc-posix-name-prefix \"/d.pre.\")\n)\n",
            SHM_DENY_TARGET.operation
        ));
        let mut last_allow = 0;
        let mut first_deny = usize::MAX;
        for rule in &expected {
            assert_eq!(p.matches(rule.as_str()).count(), 1, "{rule}\n{p}");
            let at = p.find(rule.as_str()).unwrap();
            if rule.starts_with("(allow") {
                last_allow = last_allow.max(at);
            } else {
                first_deny = first_deny.min(at);
            }
        }
        assert!(last_allow < first_deny, "{p}");

        #[cfg(target_os = "macos")]
        {
            let output = sandbox_exec(&p, &["/usr/bin/true"]);
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }

    /// Duplicates, nested prefixes, and a name in both allow and deny are
    /// accepted as written. Allows add up, and each deny rule follows every
    /// allow so it wins.
    #[test]
    fn overlapping_and_duplicate_entries_are_kept_and_deny_comes_last() {
        let overlap = || {
            custom_rules(
                SeatbeltCustomDefault::Deny,
                &[
                    "com.example.a",
                    "com.example.a",
                    "com.example.*",
                    "com.example.a.*",
                ],
                &["com.example.a", "com.example.a", "com.example.a.b.*"],
            )
        };
        let mut r = req();
        r.policy.ui.disable = false;
        r.seatbelt = Some(SeatbeltConfig {
            gui_access: true,
            custom_io_kits: Some(custom_rules(
                SeatbeltCustomDefault::Allow,
                &[
                    "IOSurface*",
                    "IOSurfaceRootUserClient",
                    "IOSurfaceRootUserClient",
                ],
                &["IOSurfaceRootUserClient", "IOSurface*"],
            )),
            custom_mach_lookups: Some(overlap()),
            custom_mach_registers: Some(SeatbeltCustomMachRegisters {
                global: Some(overlap()),
                local: Some(overlap()),
            }),
            custom_posix_shm: Some(SeatbeltCustomPosixShm {
                default: Some(SeatbeltPosixShmAccess::Create),
                read: strings(&["/x.a", "/x.a"]),
                own: strings(&["/x.*"]),
                deny: strings(&["/x.a", "/x.a"]),
                ..Default::default()
            }),
            ..Default::default()
        });
        crate::seatbelt_common::seatbelt_policy::validate_seatbelt_custom_rules(&r).unwrap();
        let p = build_profile(&r).unwrap();

        let allows: Vec<usize> = p.match_indices("\n(allow ").map(|(at, _)| at).collect();
        let denies: Vec<usize> = p
            .match_indices(";; --- custom")
            .filter(|(at, _)| p[*at..].lines().next().unwrap().contains(".deny "))
            .map(|(at, _)| at)
            .collect();
        assert_eq!(denies.len(), 5, "{p}");
        assert!(allows.last().unwrap() < &denies[0], "{p}");
        // Duplicates are emitted as written; Seatbelt treats them as one.
        assert_eq!(
            p.matches("(global-name \"com.example.a\")").count(),
            2 * 2 * 2,
            "{p}"
        );
        assert_eq!(
            p.matches("(local-name \"com.example.a\")").count(),
            2 * 2,
            "{p}"
        );
        // Each read entry gets an allow and a deny rule.
        assert_eq!(
            p.matches("(ipc-posix-name \"/x.a\")").count(),
            2 * 2 + 2,
            "{p}"
        );
        assert!(p.contains(
            "(deny iokit-open\n    (iokit-user-client-class \"IOSurfaceRootUserClient\")\n    \
             (iokit-user-client-class-regex #\"^IOSurface\")\n)\n"
        ));

        #[cfg(target_os = "macos")]
        {
            let output = sandbox_exec(&p, &["/usr/bin/true"]);
            assert!(
                output.status.success(),
                "{}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }
}