capsule-runtime 0.7.0

The runtime that executes Murmur capsules. Runs packaged AI agents in isolation, enforcing WASI capability grants on a Wasmtime component sandbox.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
//! The `sealed` containment mechanism: a private mount namespace pivoted onto a composed root.
//!
//! `scoped` (Landlock + seccomp, see [`crate::sandbox`]) can deliver "nothing outside the workdir
//! is readable or writable". It can never deliver "nothing outside the workdir *exists*", because
//! Landlock is an access filter — it does not change what a process can see, name or traverse. A
//! mount namespace can, and that is the whole of what this module adds.
//!
//! ## What the mechanism is
//!
//! Inside the forked child's `pre_exec` window — before fd hygiene, before the capability drop,
//! before the seccomp filter, and before the Landlock ruleset — the child:
//!
//!   1. `unshare(CLONE_NEWUSER | CLONE_NEWNS)`, then maps its own uid/gid one-to-one into the new
//!      user namespace (`/proc/self/uid_map`), which is what gives it `CAP_SYS_ADMIN` *inside that
//!      namespace* and nowhere else. Nothing here needs the host's root.
//!
//!      On every kernel tier this now runs *after* [`crate::network_namespace`] has already
//!      created a user+network namespace, so the one built here is **nested** inside it. That is
//!      load-bearing rather than incidental: a task in a descendant user namespace holds no
//!      capability in the ancestor, so a `sealed` capsule cannot reconfigure the network namespace
//!      it is confined to.
//!   2. Makes mount propagation private (`MS_REC | MS_PRIVATE` on `/`), so nothing it does leaks
//!      back into the host's mount table.
//!   3. Mounts a fresh `tmpfs` over a base directory ([`choose_root_base`]) and composes the new
//!      root inside it: the host runtime directories ([`SEALED_RUNTIME_PATHS`]) and a fixed,
//!      narrow `/etc` set ([`SEALED_ETC_PATHS`]) bind-mounted **read-only**, the session workdir
//!      bind-mounted **read-write at its own absolute path**, a private `/dev` tmpfs carrying the
//!      OCI default device set ([`SEALED_DEVICE_NODES`]), and a `/proc` — masked with `hidepid`
//!      where the kernel permits it, bound from the host where it does not
//!      ([`PROC_HIDEPID_OPTIONS`] documents which is which, and why).
//!   4. `pivot_root`s onto it, detaches the old root, remounts the new root read-only, and
//!      `chdir`s back into the workdir.
//!
//! Everything outside that root is then not merely access-denied — it is *absent*. There is no
//! pathname for `/etc/shadow`, for a Docker socket, or for `/dev/sda`, so the escape classes that
//! `scoped` has to enumerate and refuse (pathname unix sockets, device nodes, metadata visibility,
//! stdlib directory enumeration) stop being reachable rather than being individually denied.
//!
//! `/proc` is the one exception to that sentence: mounting a private `procfs` unprivileged needs a
//! PID namespace this module deliberately does not create, so on a bare host the composed root
//! carries a bind of the host's `/proc` and
//! host process metadata stays *visible* there (opens through it are still Landlock's to refuse).
//! See [`PROC_HIDEPID_OPTIONS`].
//!
//! ## What it does *not* replace
//!
//! Landlock and seccomp still install afterwards, now scoped to the private root. `sealed` is
//! defence in depth over `scoped`'s mechanism, not a substitute for it: the syscall allowlist is
//! still the only thing standing between a capsule and `io_uring`, `bpf` or `ptrace`, none of
//! which a mount namespace has an opinion about.
//!
//! ## Why the plan is precomputed
//!
//! Everything the child does is driven by [`SealedRootSpec`], a fully-resolved list of
//! NUL-terminated paths built in the **parent**, before `fork()`. The `pre_exec` window permits
//! only async-signal-safe work: allocating there (a `format!`, a `PathBuf::join`) can deadlock on
//! the allocator lock a *different* thread of the parent held at fork time. Splitting the decision
//! ([`plan_composed_root`], pure and unit-testable against a fake host layout) from the execution
//! ([`construct_composed_root`], raw syscalls over already-built `CString`s) is what keeps the
//! child side allocation-free on its success path — and it is what makes the composed-root layout
//! testable at all on a host that cannot create a namespace.

// The composed-root planner and the synthetic `/etc` content are pure so they stay unit-tested on
// every OS, but outside tests only the Linux `linux` submodule and `sandbox`'s Linux enforcement
// call them, so off Linux they are dead by construction.
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]

use std::path::{Path, PathBuf};

// ---------------------------------------------------------------- AppArmor

/// Name of the AppArmor profile this runtime ships, as it appears in
/// `/sys/kernel/security/apparmor/profiles` and in `/proc/self/attr/current`.
///
/// On a host where AppArmor's `restrict_unprivileged_userns` knob is on (Ubuntu 23.10+ and
/// derivatives), an unconfined process's `unshare(CLONE_NEWUSER)` is transitioned into the
/// restricted `unprivileged_userns` profile, which denies `CAP_SYS_ADMIN` and therefore every
/// `mount(2)` that follows. Loading this profile — which attaches to the `mur` binary and carries
/// `userns,` — is what lifts that, exactly as Ubuntu's own shipped profiles do for Chrome and
/// Firefox.
pub const SEALED_APPARMOR_PROFILE_NAME: &str = "mur-sealed";

/// Where [`scripts/install.sh`](../../../scripts/install.sh) installs the shipped profile, and the
/// path the refusal message tells an operator to load.
pub const SEALED_APPARMOR_PROFILE_PATH: &str = "/etc/apparmor.d/mur-sealed";

/// SHA-256 (lowercase hex) of `packaging/apparmor/mur-sealed` as this build ships it.
///
/// A literal rather than an `include_str!` digest: `capsule-runtime` is published to crates.io,
/// `cargo package` copies only files under the crate's own directory, and a path escaping the
/// crate root compiles in the workspace and then fails the packaging verification build. The unit
/// test `shipped_profile_digest_constant_matches_the_file` reads the real file through
/// `CARGO_MANIFEST_DIR` and fails with the digest to paste in here — that test does not run during
/// `cargo package`, so publishing stays green while a profile edit that forgot this constant is
/// caught by `cargo test`.
///
/// Compares *file bytes*. It says nothing about what `apparmor_parser` has actually loaded — see
/// [`classify_installed_profile`].
pub const SEALED_APPARMOR_PROFILE_SHA256: &str =
    "1669f6c0038dddea393cfacd95b078ac99ec718a538c8ebb52701f6ba686a892";

/// Where this host's permission to create an unprivileged user namespace comes from.
///
/// Three of the four variants permit the namespace, and they are not interchangeable: AppArmor
/// being absent is a distribution fact nobody chose, the shipped profile confining `mur` is the
/// configuration murmur ships, and the restriction being switched off host-wide removes the
/// hardening for *every* binary on the machine. The three reach the same achieved class, so
/// `mur doctor`, `--explain-scope` and the session trace each report the variant: without it a
/// `sealed` result obtained on a weakened host cannot be told apart from one obtained through the
/// profile.
///
/// The grant never decides whether a run is refused — only [`Self::permits_userns`] does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UsernsGrant {
    /// AppArmor is not enabled on this host (Fedora, Arch, a kernel built without it, …). There is
    /// no restriction to lift and no profile to install.
    ApparmorAbsent,
    /// AppArmor is enabled but `kernel.apparmor_restrict_unprivileged_userns` is `0`, so no binary
    /// on this host is transitioned into the restricted `unprivileged_userns` profile. Legitimate,
    /// and on some hosts the only option — but it is not the configuration murmur ships, and it is
    /// what `W-SEC-013` reports.
    RestrictionDisabledHostWide,
    /// The restriction is on and this process is confined by a profile whose name begins with
    /// [`SEALED_APPARMOR_PROFILE_NAME`] — the shipped profile, or the checkout profile
    /// `scripts/install-dev-apparmor.sh` generates. The grant is narrow: it applies to this binary
    /// and nothing else.
    ProfileConfining,
    /// The restriction is on and nothing grants this binary anything. The only variant that keeps
    /// a host below `sealed`, and the default so an unprobed host claims nothing.
    #[default]
    Withheld,
}

impl UsernsGrant {
    /// Every variant, so a caller reasoning about "which grant did this host give" cannot silently
    /// miss one. Same convention as [`SealedBlocker::ALL`].
    pub const ALL: &'static [UsernsGrant] = &[
        UsernsGrant::ApparmorAbsent,
        UsernsGrant::RestrictionDisabledHostWide,
        UsernsGrant::ProfileConfining,
        UsernsGrant::Withheld,
    ];

    /// Whether an unprivileged `unshare(CLONE_NEWUSER)` gets through on this host.
    ///
    /// The whole of what the runtime decisions read: [`sealed_blocker`],
    /// [`crate::network_namespace::egress_namespace_blocker`] and `sandbox::tier_from_probe`
    /// consult this and nothing else about the grant, so provenance is reported without ever
    /// changing an outcome.
    #[must_use]
    pub fn permits_userns(self) -> bool {
        !matches!(self, UsernsGrant::Withheld)
    }

    /// Stable wire name, as it appears in `--explain-scope --json`, in `session_start` and in
    /// `mur doctor`. Distinct per variant, and not a `Debug` rendering, which is free to change.
    #[must_use]
    pub fn wire_name(self) -> &'static str {
        match self {
            UsernsGrant::ApparmorAbsent => "apparmor_absent",
            UsernsGrant::RestrictionDisabledHostWide => "restriction_disabled_host_wide",
            UsernsGrant::ProfileConfining => "profile_confining",
            UsernsGrant::Withheld => "withheld",
        }
    }

    /// One line naming the mechanism in words, for the `mur doctor` block. States what the grant
    /// covers — one binary or the whole host — because that is the difference the wire name alone
    /// does not spell out.
    #[must_use]
    pub fn summary(self) -> &'static str {
        match self {
            UsernsGrant::ApparmorAbsent => {
                "AppArmor is not enabled on this host, so nothing restricts unprivileged user \
                 namespaces and no profile is needed"
            }
            UsernsGrant::RestrictionDisabledHostWide => {
                "kernel.apparmor_restrict_unprivileged_userns is off, so unprivileged user \
                 namespaces are unrestricted for every binary on this host, not just for mur"
            }
            UsernsGrant::ProfileConfining => {
                "the restriction is on and the mur-sealed AppArmor profile is confining this \
                 binary, so the grant covers mur alone — the configuration murmur ships"
            }
            UsernsGrant::Withheld => {
                "the restriction is on and no mur-sealed AppArmor profile is confining this \
                 binary, so unprivileged user namespaces are withheld from mur"
            }
        }
    }

    /// The whole decision, over the three host readings that produce it: whether AppArmor is
    /// enabled, whether its `restrict_unprivileged_userns` knob is on, and what profile confines
    /// this process. Each argument is the file's trimmed contents, or `None` when it is missing or
    /// empty.
    ///
    /// Pure, and separate from the reading for the same reason [`classify_installed_profile`] is:
    /// every combination is then testable on any OS, with no `/sys` and no `/proc`.
    /// `linux::userns_grant` is the reader and holds no logic of its own.
    ///
    /// A missing or unreadable restriction knob counts as *not restricted*, not as withheld — a
    /// kernel that does not implement the knob does not restrict anything.
    #[must_use]
    pub fn from_readings(
        enabled: Option<&str>,
        restricted: Option<&str>,
        current_profile: Option<&str>,
    ) -> UsernsGrant {
        if !matches!(enabled, Some("Y") | Some("1")) {
            return UsernsGrant::ApparmorAbsent;
        }
        if !matches!(restricted, Some("Y") | Some("1")) {
            return UsernsGrant::RestrictionDisabledHostWide;
        }
        match current_profile {
            Some(profile) if profile.starts_with(SEALED_APPARMOR_PROFILE_NAME) => {
                UsernsGrant::ProfileConfining
            }
            _ => UsernsGrant::Withheld,
        }
    }
}

/// How `/etc/apparmor.d/mur-sealed` on this host compares to the profile this build ships.
///
/// A *file-level* finding and deliberately nothing more. AppArmor loads profiles from the kernel's
/// own policy cache, not from this path at call time, so a file can be edited without
/// `apparmor_parser -r` ever running and a profile can be loaded from a file that has since been
/// deleted. [`UsernsGrant`] is the behavioural answer and stays the source of truth; this only
/// tells an operator whether the bytes on disk are the bytes murmur ships.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InstalledProfileState {
    /// The installed file hashes to [`SEALED_APPARMOR_PROFILE_SHA256`].
    Matches,
    /// The file is present and hashes to something else — an older revision, or an edited copy.
    /// Operator customisation belongs in `/etc/apparmor.d/local/mur-sealed`, which both shipped
    /// profiles `include if exists` and which is not hashed here.
    Drifted {
        /// Lowercase hex SHA-256 of the bytes actually on disk.
        installed_sha256: String,
    },
    /// No file at [`SEALED_APPARMOR_PROFILE_PATH`]. Expected on a host without AppArmor, and on a
    /// checkout build using `scripts/install-dev-apparmor.sh`, which writes its own separate file.
    Absent,
    /// The path exists and could not be read — a permission or I/O error, kept apart from
    /// [`Self::Absent`] so "I could not look" never reads as "it is not there".
    Unreadable {
        /// The `std::io::Error`, rendered.
        error: String,
    },
}

/// Classifies a read of [`SEALED_APPARMOR_PROFILE_PATH`] against the shipped digest.
///
/// Takes the already-performed read rather than the path, so all four outcomes are unit-testable
/// with no filesystem mutation and no privilege.
#[must_use]
pub fn classify_installed_profile(read: Result<Vec<u8>, std::io::Error>) -> InstalledProfileState {
    match read {
        Ok(bytes) => {
            let installed_sha256 = murmur_artifact::sha256_hex(&bytes);
            if installed_sha256 == SEALED_APPARMOR_PROFILE_SHA256 {
                InstalledProfileState::Matches
            } else {
                InstalledProfileState::Drifted { installed_sha256 }
            }
        }
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => InstalledProfileState::Absent,
        Err(error) => InstalledProfileState::Unreadable {
            error: error.to_string(),
        },
    }
}

/// [`classify_installed_profile`] over the real [`SEALED_APPARMOR_PROFILE_PATH`]. Reads one file
/// and needs no privilege.
#[must_use]
pub fn inspect_installed_profile() -> InstalledProfileState {
    classify_installed_profile(std::fs::read(SEALED_APPARMOR_PROFILE_PATH))
}

/// The paths the two shipped profiles in `packaging/apparmor/mur-sealed` attach to, as their
/// AppArmor path globs.
///
/// **Remediation text only.** Nothing decides anything by matching the running binary's path
/// against this list: matching a path is inference, while reading `/proc/self/attr/current` is
/// what the kernel actually did, and [`classify_profile_attachment`] uses only the latter. This
/// exists so `mur doctor` can tell an operator running a binary from an unusual location where the
/// shipped profile *does* attach, without pretending to have measured anything.
pub const SEALED_APPARMOR_ATTACHMENT_PATHS: &[&str] = &[
    "/{usr/local/,usr/,opt/mur/}bin/mur",
    "@{HOME}/{.local,.cargo}/bin/mur",
];

/// Which AppArmor profile, if any, the kernel reports as confining *this* process.
///
/// AppArmor attaches profiles by executable path, so a `mur` at a bind mount, a build output or a
/// test fixture gets no profile however correctly the shipped one is installed. That is invisible
/// in [`UsernsGrant`] alone — it reports [`UsernsGrant::Withheld`] identically for "the profile is
/// not installed" and "the profile is installed and does not attach here" — which is why this is
/// reported beside it rather than folded into it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProfileAttachment {
    /// A profile whose name begins with [`SEALED_APPARMOR_PROFILE_NAME`] confines this process —
    /// the shipped profile, or the checkout profile `scripts/install-dev-apparmor.sh` generates.
    /// The same condition [`UsernsGrant::ProfileConfining`] is decided on.
    Sealed {
        /// The profile name as the kernel reports it, without the trailing enforcement mode.
        profile: String,
    },
    /// Some other profile confines this process. It grants nothing murmur asked for, and it may
    /// be *narrower* than unconfined — a snap or a container runtime profile, for instance.
    Other {
        /// The profile name as the kernel reports it, without the trailing enforcement mode.
        profile: String,
    },
    /// The kernel reports `unconfined`: AppArmor is present and no profile attaches to this
    /// binary's path.
    Unconfined,
    /// `/proc/self/attr/current` is absent or unreadable — no AppArmor on this host, or not
    /// Linux. Never collapsed into [`Self::Unconfined`], on the same terms
    /// [`InstalledProfileState::Unreadable`] is kept apart from
    /// [`InstalledProfileState::Absent`]: "nothing attaches" and "I could not look" are different
    /// findings.
    NotReported,
}

/// Classifies the contents of `/proc/self/attr/current` into a [`ProfileAttachment`].
///
/// Takes the already-performed read rather than the path, so all four outcomes are unit-testable
/// on any OS — the same split [`classify_installed_profile`] uses.
///
/// The kernel writes the profile name followed by its enforcement mode in parentheses
/// (`mur-sealed (unconfined)`, `unconfined`), so the mode is stripped before the name is compared.
#[must_use]
pub fn classify_profile_attachment(current_profile: Option<&str>) -> ProfileAttachment {
    let Some(raw) = current_profile
        .map(str::trim)
        .filter(|value| !value.is_empty())
    else {
        return ProfileAttachment::NotReported;
    };
    let name = raw
        .split_once(" (")
        .map_or(raw, |(name, _mode)| name)
        .trim();
    if name.is_empty() || name == "unconfined" {
        return ProfileAttachment::Unconfined;
    }
    if name.starts_with(SEALED_APPARMOR_PROFILE_NAME) {
        return ProfileAttachment::Sealed {
            profile: name.to_string(),
        };
    }
    ProfileAttachment::Other {
        profile: name.to_string(),
    }
}

/// [`classify_profile_attachment`] over the real `/proc/self/attr/current`. Holds no logic: the
/// file is missing on every non-Linux host and on a Linux host without AppArmor, and both read as
/// [`ProfileAttachment::NotReported`].
#[must_use]
pub fn inspect_profile_attachment() -> ProfileAttachment {
    classify_profile_attachment(
        std::fs::read_to_string("/proc/self/attr/current")
            .ok()
            .as_deref(),
    )
}

// ---------------------------------------------------------------- blockers

/// The one mechanism that stands between this host and `sealed`, named specifically enough that
/// the refusal carries a command the operator can run.
///
/// Deliberately a small closed enum rather than a free-form string: `containment.rs` renders it,
/// `sandbox.rs` derives it from the probe, and the manual-verification document asserts the exact
/// text of each rendering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SealedBlocker {
    /// Not Linux. Mount namespaces do not exist here and never will — the same permanence
    /// `EnforcementTier::EnvironmentOnly` carries.
    NotLinux,
    /// AppArmor's unprivileged-user-namespace restriction is active and this binary is not
    /// confined by the shipped [`SEALED_APPARMOR_PROFILE_NAME`] profile.
    AppArmorProfileMissing,
    /// `unshare(CLONE_NEWUSER | CLONE_NEWNS)` was refused outright — the container case: no
    /// `CAP_SYS_ADMIN`, or the container's own seccomp filter blocking the syscall.
    NamespaceCreationDenied,
    /// The namespace was created, but writing the identity `uid_map`/`gid_map` was refused, so the
    /// process cannot own it. Nothing to do with `CAP_SYS_ADMIN` or containers.
    IdMapDenied,
    /// The namespace was created, but `mount(2)` inside it was refused. The signature of a
    /// confinement that permits `userns_create` and then denies `CAP_SYS_ADMIN`.
    MountDenied,
    /// The namespace was created and `mount(2)` inside it worked, but the `pivot_root(2)`
    /// sequence the composed root's step 6 performs did not. A separate finding from
    /// [`Self::MountDenied`] because the two have separate remediations: `mount` is what an
    /// AppArmor profile grants, while `pivot_root` is a distinct rule in that profile and a
    /// distinct entry in a container runtime's seccomp allowlist, so a host can grant one and
    /// refuse the other.
    PivotRootDenied,
    /// The kernel has no unprivileged user namespace support at all (`CONFIG_USER_NS=n`, or
    /// `user.max_user_namespaces=0`).
    KernelUnsupported,
    /// Namespaces are available but Landlock is not, so the defence-in-depth layer `sealed`
    /// is required to keep would be missing. `sealed` is strictly stronger than `scoped`; a host
    /// that cannot back `scoped` cannot back `sealed` either.
    LandlockUnavailable,
}

impl SealedBlocker {
    /// Every variant, so a caller that has to reason about "which refusal did this host give"
    /// cannot silently miss one. Added because a hand-maintained list of the expected refusal
    /// texts in `murmur-cli`'s CLI test drifted the moment a variant was added, and the drift
    /// showed up as a failing assertion about the *host* rather than about the list.
    pub const ALL: &'static [SealedBlocker] = &[
        SealedBlocker::NotLinux,
        SealedBlocker::AppArmorProfileMissing,
        SealedBlocker::NamespaceCreationDenied,
        SealedBlocker::IdMapDenied,
        SealedBlocker::MountDenied,
        SealedBlocker::PivotRootDenied,
        SealedBlocker::KernelUnsupported,
        SealedBlocker::LandlockUnavailable,
    ];

    /// One sentence naming the missing mechanism, plus the exact remediation. Rendered into
    /// `RuntimeError::ContainmentFloorUnmet`'s `reason`, so this is the text an operator sees
    /// under `E-CAP-003`.
    #[must_use]
    pub fn reason(self) -> String {
        match self {
            SealedBlocker::NotLinux => {
                "sealed requires a Linux mount namespace + pivot_root; this \
                 platform has no such primitive and never will (macOS and every non-Linux target \
                 stay at advisory permanently)"
                    .to_string()
            }
            SealedBlocker::AppArmorProfileMissing => format!(
                "sealed requires an unprivileged user+mount namespace, and AppArmor's \
                 unprivileged-userns restriction is active on this host while the '{name}' profile \
                 is not confining this binary. Install and load the profile shipped with mur: \
                 `sudo install -m 644 packaging/apparmor/{name} {path} && sudo apparmor_parser -r \
                 {path}` (or re-run the mur installer as root), then re-run. Building out of a \
                 checkout, where the binary sits at ./target/{{debug,release}}/mur and no shipped \
                 profile attaches to it: run `scripts/install-dev-apparmor.sh`, which generates \
                 and loads the same grant for those two paths. LAST RESORT, only where a profile \
                 genuinely cannot be loaded: `sudo sysctl -w \
                 kernel.apparmor_restrict_unprivileged_userns=0` — this removes \
                 unprivileged-userns hardening from every program on the machine, not just from \
                 mur, and is not the configuration murmur ships.",
                name = SEALED_APPARMOR_PROFILE_NAME,
                path = SEALED_APPARMOR_PROFILE_PATH,
            ),
            SealedBlocker::NamespaceCreationDenied => {
                "sealed requires unshare(CLONE_NEWUSER | CLONE_NEWNS), which this host refused. \
                 This is the usual answer inside a container: CAP_SYS_ADMIN is absent, or the \
                 container's own seccomp filter blocks unshare(2). Either add `--cap-add \
                 SYS_ADMIN` to the container invocation, or establish the mount namespace outside \
                 the container and run mur inside it. The runtime will not fall back to a weaker \
                 class."
                    .to_string()
            }
            SealedBlocker::IdMapDenied => {
                "sealed created a user+mount namespace, but writing the identity uid_map/gid_map \
                 into it was refused, so the process cannot own the namespace it just made. This \
                 is an id-mapping problem, not a missing capability: check that \
                 /proc/sys/user/max_user_namespaces is non-zero, that no LSM policy blocks \
                 uid_map writes for this binary, and that mur is not already running inside an \
                 unmapped user namespace. The runtime will not fall back to a weaker class."
                    .to_string()
            }
            SealedBlocker::MountDenied => format!(
                "sealed created a user+mount namespace but mount(2) inside it was refused, which \
                 is what a confinement that permits userns_create and then denies CAP_SYS_ADMIN \
                 looks like. On an AppArmor host, load the shipped profile: `sudo apparmor_parser \
                 -r {path}`. Inside a container, add `--cap-add SYS_ADMIN` to the container \
                 invocation, or establish the mount namespace outside the container.",
                path = SEALED_APPARMOR_PROFILE_PATH,
            ),
            SealedBlocker::PivotRootDenied => format!(
                "sealed created a user+mount namespace and mounted inside it, but pivot_root(2) \
                 was refused, so the composed root cannot become this capsule's root. mount(2) \
                 working while pivot_root(2) does not is what a policy that grants one and not \
                 the other looks like: on an AppArmor host, check that the loaded profile carries \
                 a `pivot_root,` rule and reload it with `sudo apparmor_parser -r {path}`; inside \
                 a container, pivot_root(2) is commonly absent from the runtime's seccomp \
                 allowlist even where CAP_SYS_ADMIN is granted, so establish the mount namespace \
                 outside the container instead. The runtime will not fall back to a weaker class.",
                path = SEALED_APPARMOR_PROFILE_PATH,
            ),
            SealedBlocker::KernelUnsupported => {
                "sealed requires unprivileged user namespaces, which this kernel does not provide \
                 (CONFIG_USER_NS=n, or user.max_user_namespaces=0). Raise \
                 `sudo sysctl -w user.max_user_namespaces=10000` if the sysctl is merely zeroed, \
                 otherwise run on a kernel built with CONFIG_USER_NS=y."
                    .to_string()
            }
            SealedBlocker::LandlockUnavailable => {
                "sealed keeps Landlock and seccomp inside the composed root as defence in depth, \
                 and this host provides no usable Landlock ABI (Linux 5.13+ required). A host that \
                 cannot back scoped cannot back sealed either."
                    .to_string()
            }
        }
    }
}

// ---------------------------------------------------------------- host probe result

/// Outcome of really rehearsing the composed root's construction in a forked child.
///
/// The states are not interchangeable: `Denied`, `MountDenied` and `PivotRootDenied` all mean "no
/// sealed here" but point at completely different remediations (container capability, AppArmor
/// profile, seccomp allowlist), which is the entire reason this is not a `bool`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum NamespaceProbe {
    /// The child completed the whole composed-root shape in its own throwaway namespace:
    /// `unshare`, the identity maps, private propagation, a `tmpfs` over a root base candidate,
    /// the parking directory, `pivot_root(2)` and `umount2(MNT_DETACH)`.
    Ok,
    /// `unshare` itself was refused (`EPERM`).
    Denied,
    /// `unshare` succeeded, but writing the identity `uid_map`/`gid_map` did not — the namespace
    /// exists and cannot be owned. Distinct from [`Denied`](Self::Denied) because the remediation
    /// is completely different: `Denied` points at `CAP_SYS_ADMIN` and container flags, while this
    /// points at id-mapping policy. Collapsing the two sent an operator hunting a container
    /// problem on a host that had created the namespace perfectly well.
    MapDenied,
    /// `unshare` succeeded, `mount(2)` inside the namespace did not — either the
    /// `MS_REC | MS_PRIVATE` propagation change or the new root's `tmpfs`. The two fold together
    /// because they are the same mechanism with the same remediation.
    MountDenied,
    /// Every mount succeeded and the `pivot_root(2)` sequence did not. Kept apart from
    /// [`MountDenied`](Self::MountDenied) because a host can permit `mount(2)` and refuse
    /// `pivot_root(2)`. Folding the two together lets such a host clear the launch probe and
    /// fail at the first subprocess with `E-RUN-014`.
    PivotRootDenied,
    /// The kernel does not implement it (`ENOSYS`/`EINVAL`), or the probe could not run at all.
    #[default]
    Unsupported,
}

/// Everything the host probe learned about `sealed`, kept separate from the decision that uses it
/// so `sandbox::tier_from_probe` stays pure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct SealedProbe {
    /// Where this host's permission to create an unprivileged user namespace comes from, or
    /// [`UsernsGrant::Withheld`] when it gives none.
    ///
    /// Named for the question that actually matters rather than for "is the profile loaded",
    /// because a Fedora or Arch host with no AppArmor at all needs no profile and must not be
    /// refused for lacking one. Every decision below reads only
    /// [`UsernsGrant::permits_userns`]; the rest of the value is provenance, reported and never
    /// acted on.
    pub(crate) userns_grant: UsernsGrant,
    /// What a real rehearsal of the composed root's construction — through `pivot_root(2)` and
    /// `umount2(MNT_DETACH)` — did in a forked child.
    pub(crate) namespace: NamespaceProbe,
}

/// Which single mechanism to blame, given the probe. Pure; the ordering is the order an operator
/// has to fix things in.
///
/// `None` means every precondition holds and this host can back `sealed`.
pub(crate) fn sealed_blocker(
    is_linux: bool,
    landlock_fully_enforced: bool,
    probe: SealedProbe,
) -> Option<SealedBlocker> {
    if !is_linux {
        return Some(SealedBlocker::NotLinux);
    }
    // Attribute to AppArmor before the namespace outcome: when the restriction is on and the
    // shipped profile is not loaded, the namespace failure is a *consequence*, and naming
    // `--cap-add SYS_ADMIN` on a bare host sends the operator somewhere useless.
    if !probe.userns_grant.permits_userns() {
        return Some(SealedBlocker::AppArmorProfileMissing);
    }
    match probe.namespace {
        NamespaceProbe::Ok => {
            if landlock_fully_enforced {
                None
            } else {
                Some(SealedBlocker::LandlockUnavailable)
            }
        }
        NamespaceProbe::Denied => Some(SealedBlocker::NamespaceCreationDenied),
        NamespaceProbe::MapDenied => Some(SealedBlocker::IdMapDenied),
        NamespaceProbe::MountDenied => Some(SealedBlocker::MountDenied),
        NamespaceProbe::PivotRootDenied => Some(SealedBlocker::PivotRootDenied),
        NamespaceProbe::Unsupported => Some(SealedBlocker::KernelUnsupported),
    }
}

// ---------------------------------------------------------------- the composed root, declared

/// Host directories bind-mounted read-only into every composed root, in order.
///
/// Fixed, not derived: a whole-tree bind of `/usr` plus the non-usrmerge spellings of the same
/// tree. On a usrmerge distro `/bin`, `/sbin`, `/lib`,
/// `/lib64`… are *symlinks* into `/usr`; [`plan_composed_root`] recreates them as symlinks rather
/// than bind-mounting through them, so the composed root has the same shape as the host and a
/// hashbang like `#!/bin/sh` resolves.
///
/// Deliberately a whole-directory bind rather than a curated per-file set: the point of `sealed`
/// is that it *deletes* the ELF-closure derivation `scoped` needs, along with its lock-time
/// pinning problem. `capabilities.shell.staged_runtime` is **additive** to this list, not a
/// replacement for it: a declared runtime tree arrives through
/// [`plan_composed_root`]'s own `staged_runtime_read_only` parameter, as a *required* bind, while
/// this fixed list stays exactly as it is. Anything a `shell.allow` binary needs at runtime must
/// therefore be under one of these, under a staged runtime tree, or under a directory derived
/// from the manifest — see `extra_read_only` in [`plan_composed_root`].
pub const SEALED_RUNTIME_PATHS: &[&str] = &[
    "/usr", "/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32",
];

/// One entry of the fixed `/etc` allowlist: the host path to bind, plus whether it is a directory.
///
/// The `directory` bit exists because the same list drives two mechanisms with different needs.
/// [`plan_composed_root`] does not need it — it asks the host what each path is via
/// [`HostLayout::kind`] and mirrors accordingly. `sandbox::resolve_sealed_etc_landlock_grants` does:
/// it must decide `ReadDir` per entry, and it is required to be pure and syscall-free (it runs on
/// any platform, for paths that need not exist). Carrying the classification *in the list* rather
/// than in a second parallel constant is what makes the bound set and the granted set structurally
/// incapable of drifting apart — the same reason [`SealedDevice`] carries its own `writable` bit
/// rather than deriving it from a separate table.
///
/// It is a static claim about mainstream Linux, not a fact read off this host: `/etc/ssl` and
/// friends are directories on Debian, Ubuntu, Fedora, RHEL, Arch and Alpine alike. A host that
/// disagrees costs the entry its enumerability and nothing else — `open_landlock_fds` narrows
/// `list_dir` back to `false` for anything that does not `fstat` as a directory, because the kernel
/// rejects (`EINVAL`) a `ReadDir` rule on a non-directory and that would otherwise refuse the whole
/// launch.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SealedEtcPath {
    /// Absolute path inside the composed root. Also the host path bind-mounted there, except for
    /// an entry carrying [`Self::synthetic`], whose content the parent writes itself.
    pub path: &'static str,
    /// Whether this path is a directory on a mainstream Linux host, and therefore whether its
    /// Landlock rule carries `ReadDir`. `false` for regular files and for symlinks (the symlink is
    /// followed when the rule's fd is opened, so `/etc/localtime`'s rule lands on the zoneinfo file
    /// it points at).
    pub directory: bool,
    /// `Some` when [`Self::path`] is backed by a file the *parent* synthesises rather than by the
    /// host's own file at that path — the account databases, and nothing else.
    ///
    /// Carried on the entry for the same reason as `directory`: the alternative is a second
    /// parallel list of "the ones we do not mirror", which is free to drift out of step with this
    /// one. Typed rather than a `bool` so the content each synthetic entry gets is decided by an
    /// exhaustive `match` — adding a third one is then a compile error until it is given content,
    /// instead of a launch-time failure to bind a file nobody wrote.
    pub synthetic: Option<SyntheticEtcFile>,
}

/// An `/etc` file a composed root gets in synthesised form instead of the host's.
///
/// Both are account databases, and both are world-readable on every distribution — so binding the
/// host's copy hands the capsule the machine's full account list for no benefit. What a capsule
/// actually needs from them is that `getpwuid(3)`/`getgrgid(3)` resolve *its own* id: a shell's `~`
/// expansion, `os.path.expanduser`, `whoami`, and anything reading `$HOME` through the password
/// database. Two entries — `root` and the id the capsule runs as — satisfy all of that.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyntheticEtcFile {
    /// `/etc/passwd`, in the seven colon-separated fields of `passwd(5)`.
    Passwd,
    /// `/etc/group`, in the four colon-separated fields of `group(5)`.
    Group,
}

/// The uid/gid a capsule's subprocesses run as, and the `HOME` they are given.
///
/// Read off the session workdir the parent created rather than from `getuid(2)`: this crate is
/// `#![deny(unsafe_code)]` and the workdir's owner *is* the spawning process's identity, so
/// `std::fs::metadata(workdir).uid()` answers the question in safe std — the same pattern
/// `crate::resources` already uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SealedAccountIdentity<'a> {
    pub(crate) uid: u32,
    pub(crate) gid: u32,
    /// The synthetic `HOME`, exactly as `crate::shell::build_shell_env` sets it in the subprocess
    /// environment. Byte-identical or the whole exercise is pointless: a `pw_dir` that disagrees
    /// with `$HOME` is worse than no entry at all, because tools silently pick one of the two.
    pub(crate) home: &'a str,
}

/// Login shell recorded for both synthetic accounts. Present in the composed root
/// (`/bin` is on [`SEALED_RUNTIME_PATHS`]) and *not* thereby made runnable — the exec allowlist is
/// Landlock's, and a shell field is a string in a database, not a grant.
const SYNTHETIC_LOGIN_SHELL: &str = "/bin/sh";

/// Account and group name for the capsule's own entry. Deliberately not the host's login name:
/// that name is itself part of the account list this file exists to stop leaking.
const SYNTHETIC_ACCOUNT_NAME: &str = "capsule";

impl SyntheticEtcFile {
    /// File name under the session's `sealed-etc/`. The basename of the target path, so that
    /// directory reads like the `/etc` it stands in for.
    pub(crate) fn file_name(self) -> &'static str {
        match self {
            Self::Passwd => "passwd",
            Self::Group => "group",
        }
    }

    /// The exact bytes written to the staging file, for one capsule identity.
    ///
    /// At most two lines: `root`, plus the capsule's own id when that is not already 0. A capsule
    /// running as root gets **one** line — the `root` line, with `$HOME` as its home directory —
    /// rather than a duplicate entry for uid 0, which `getpwuid(3)` would resolve to whichever came
    /// first.
    ///
    /// Fails rather than emits a corrupt database when the home path contains a field separator or
    /// a newline: `passwd(5)` has no escaping, so a workdir named with a `:` would silently shift
    /// every field after it. Parent-side and synchronous, so it surfaces as a named launch failure.
    pub(crate) fn render(self, identity: &SealedAccountIdentity) -> Result<String, String> {
        let SealedAccountIdentity { uid, gid, home } = *identity;
        match self {
            Self::Passwd => {
                if home.contains(':') || home.contains('\n') {
                    return Err(format!(
                        "sealed: the synthetic HOME {home} contains a character /etc/passwd cannot \
                         quote (':' or a newline), so no valid passwd entry can name it"
                    ));
                }
                // name:password:uid:gid:gecos:home:shell — `x` in the password field is the
                // universal "look in shadow", and there is no shadow file in a composed root.
                if uid == 0 {
                    return Ok(format!(
                        "root:x:0:{gid}:root:{home}:{SYNTHETIC_LOGIN_SHELL}\n"
                    ));
                }
                Ok(format!(
                    "root:x:0:0:root:/root:{SYNTHETIC_LOGIN_SHELL}\n\
                     {SYNTHETIC_ACCOUNT_NAME}:x:{uid}:{gid}:Murmur capsule:{home}:\
                     {SYNTHETIC_LOGIN_SHELL}\n"
                ))
            }
            // name:password:gid:members — the member list is empty because membership of the
            // capsule's own group comes from its passwd entry's gid field.
            Self::Group => {
                if gid == 0 {
                    return Ok("root:x:0:\n".to_string());
                }
                Ok(format!("root:x:0:\n{SYNTHETIC_ACCOUNT_NAME}:x:{gid}:\n"))
            }
        }
    }
}

/// The only `/etc` entries that exist inside a composed root, each bind-mounted read-only and each
/// silently skipped when the host does not have it.
///
/// An allowlist, never `/etc` wholesale, and never a denylist of sensitive names: `/etc/shadow`,
/// `/etc/sudoers`, `/etc/ssh`, cloud-init credentials and every future addition to `/etc` are
/// absent by construction rather than by enumeration. The entries here are the ones without which
/// ordinary tooling misreports rather than fails cleanly — the dynamic loader's cache, the TLS
/// trust store, DNS configuration, the timezone, and the passwd/group databases `getpwuid(3)`
/// needs.
///
/// `/etc/passwd` and `/etc/group` are the two entries the host does *not* supply. They are
/// world-readable on every distribution, so binding the host's copies would hand the capsule the
/// machine's full account list; instead the parent writes a two-line database naming only `root`
/// and the capsule's own id, and the composed root binds *that* at the same path, read-only. See
/// [`SyntheticEtcFile`]. It stays on this list because the list is also the grant list — an entry
/// removed from here loses its Landlock rule and becomes unreadable, which is the opposite of what
/// this narrowing is for.
///
/// Binding these is only half the job: Landlock still mediates *inside* the composed root, so an
/// entry bound here but absent from the ruleset exists and is unopenable — a trust store present
/// at `/etc/ssl/certs/ca-certificates.crt` but `EACCES` on open fails TLS verification.
/// `sandbox::resolve_sealed_etc_landlock_grants` turns this list into the matching read grants.
/// Keep the two sets aligned. A Landlock rule names the *inode* an fd resolved to, not the path
/// string it was opened by, so an entry whose bind source is not the host path of the same name
/// needs its rule taken on the file actually bound — see `sandbox::LandlockChildFds`'s
/// `sealed_identity_fds`, which does that for the two synthetic entries.
pub const SEALED_ETC_PATHS: &[SealedEtcPath] = &[
    SealedEtcPath {
        path: "/etc/ld.so.cache",
        directory: false,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/ld.so.conf",
        directory: false,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/ld.so.conf.d",
        directory: true,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/alternatives",
        directory: true,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/ssl",
        directory: true,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/pki",
        directory: true,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/ca-certificates",
        directory: true,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/ca-certificates.conf",
        directory: false,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/resolv.conf",
        directory: false,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/hosts",
        directory: false,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/nsswitch.conf",
        directory: false,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/localtime",
        directory: false,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/timezone",
        directory: false,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/terminfo",
        directory: true,
        synthetic: None,
    },
    SealedEtcPath {
        path: "/etc/passwd",
        directory: false,
        synthetic: Some(SyntheticEtcFile::Passwd),
    },
    SealedEtcPath {
        path: "/etc/group",
        directory: false,
        synthetic: Some(SyntheticEtcFile::Group),
    },
];

/// One entry of the private `/dev` tmpfs.
///
/// `major`/`minor`/`mode` are recorded for the record and for the manual-verification document to
/// assert against — they are **not** used to create the node. Device nodes cannot be `mknod`ed
/// from inside a non-initial user namespace at all (the kernel refuses regardless of
/// `CAP_MKNOD`), so each entry is created as an empty file in the tmpfs and the host's node is
/// bind-mounted over it. This is what bubblewrap and rootless podman do, and it means the numbers
/// a capsule actually sees are the host's — which on every mainstream distribution are exactly the
/// ones below.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SealedDevice {
    /// Name under `/dev`, without the directory.
    pub name: &'static str,
    /// The host path bind-mounted over the tmpfs entry — `/dev/` + [`Self::name`], spelled out
    /// because it is also what the composed root's Landlock rule set is built from.
    pub path: &'static str,
    pub major: u32,
    pub minor: u32,
    pub mode: u32,
    /// Whether the composed root's Landlock rule for this device carries `WriteFile` on top of
    /// `ReadFile`.
    ///
    /// Landlock still mediates inside a composed root — that is the whole point of keeping it as
    /// defence in depth — so a device present in `/dev` but absent from the rule set would exist
    /// and be unopenable, which is worse than not being there. The read-only pair is the two
    /// entropy sources, where nothing legitimate writes; the rest carry write because their write
    /// side is defined to discard (`null`, `zero`), to report `ENOSPC` (`full`), or to be a
    /// terminal (`tty`).
    pub writable: bool,
}

/// The OCI runtime-spec default device set, which is what a `sealed` capsule's `/dev` contains and
/// all it contains.
///
/// This is deliberately *independent* of `sandbox::CAPSULE_DEVICE_GRANTS`, the three-device
/// Landlock grant set that services `scoped`. That set is a rule list layered over the host's real
/// `/dev`; this one is the entire contents of a private tmpfs. They answer different questions and
/// neither should be derived from the other.
///
/// `/dev/console` is omitted (the OCI spec creates it only for a terminal-attached container, and
/// a capsule subprocess has pipes, not a controlling terminal). `/dev/ptmx` and `/dev/pts` come
/// from a `devpts` mount rather than from this list, and `/dev/shm` is omitted deliberately: it is
/// writable, and the session workdir is the only writable path in a composed root.
pub const SEALED_DEVICE_NODES: &[SealedDevice] = &[
    SealedDevice {
        name: "null",
        path: "/dev/null",
        major: 1,
        minor: 3,
        mode: 0o666,
        writable: true,
    },
    SealedDevice {
        name: "zero",
        path: "/dev/zero",
        major: 1,
        minor: 5,
        mode: 0o666,
        writable: true,
    },
    SealedDevice {
        name: "full",
        path: "/dev/full",
        major: 1,
        minor: 7,
        mode: 0o666,
        writable: true,
    },
    SealedDevice {
        name: "random",
        path: "/dev/random",
        major: 1,
        minor: 8,
        mode: 0o666,
        writable: false,
    },
    SealedDevice {
        name: "urandom",
        path: "/dev/urandom",
        major: 1,
        minor: 9,
        mode: 0o666,
        writable: false,
    },
    SealedDevice {
        name: "tty",
        path: "/dev/tty",
        major: 5,
        minor: 0,
        mode: 0o666,
        writable: true,
    },
];

/// The OCI default `/dev` symlinks, `(link name under /dev, target)`.
pub const SEALED_DEVICE_SYMLINKS: &[(&str, &str)] = &[
    ("fd", "/proc/self/fd"),
    ("stdin", "/proc/self/fd/0"),
    ("stdout", "/proc/self/fd/1"),
    ("stderr", "/proc/self/fd/2"),
    ("ptmx", "pts/ptmx"),
];

/// Directory created inside the session workdir and bind-mounted at `/tmp` in the composed root.
///
/// `/tmp` has to exist — bash heredocs, `mktemp`, compilers and package managers all fail without
/// it in ways that read as runtime bugs rather than as policy. Backing it with a directory *inside
/// the workdir* is what keeps "the capsule's workdir is the only writable path" literally true:
/// the bytes written to `/tmp` land in the workdir, are counted by the existing workdir-size guard
/// (`capabilities.resources.workdir_max_bytes`), and are discarded with the session.
///
/// Under `--workdir` the session workdir is `<accessible workdir>/.murmur/<session id>/`, so this
/// directory sits under the one prefix a consumer diffing the accessible workdir excludes, and
/// inside the subtree `WorkdirGuard` measures. Declared as a runtime write by
/// [`crate::workdir_writes`]. The capsule never names this path: it sees `/tmp`.
pub const SEALED_TMP_DIR_NAME: &str = ".mur-tmp";

/// Host path of the file backing one synthetic `/etc` entry, in the session's `sealed-etc/`
/// directory beside its runtime directory, which no capsule command can write.
///
/// The single place this path is composed. Three callers need to agree on it byte for byte — the
/// planner that binds it, the parent that writes it, and the Landlock fd that grants it — and two
/// of them run in different phases of the launch.
pub(crate) fn synthetic_etc_source(sealed_etc_dir: &Path, file: SyntheticEtcFile) -> PathBuf {
    sealed_etc_dir.join(file.file_name())
}

/// The host-side sources a composed root binds that the runtime itself provides, each resolved
/// by the parent before the fork.
#[derive(Debug, Clone, Copy)]
pub(crate) struct SealedBindSources<'a> {
    /// The session workdir's [`SEALED_TMP_DIR_NAME`], bound at `/tmp`, with the `(st_dev,
    /// st_ino)` of the descriptor the parent took on it with no link followed — the identity the
    /// bind verifies, so a link swapped in after that moves nothing ([`RootOp::BindVerified`]).
    pub(crate) tmp_store: (&'a Path, (u64, u64)),
    /// The session's `sealed-etc/` directory, holding the synthetic `/etc/passwd` and
    /// `/etc/group`.
    pub(crate) etc_dir: &'a Path,
    /// The session's runtime directory and the identity of the runtime root's own descriptor,
    /// bound read-only and required at its own absolute path.
    pub(crate) runtime_dir: Option<(&'a Path, (u64, u64))>,
    /// The session's records directory and the identity of the records root's own descriptor,
    /// bound read-only and required at its own absolute path, on [`Self::runtime_dir`]'s terms.
    pub(crate) records_dir: Option<(&'a Path, (u64, u64))>,
}

/// Directory the old root is parked in between `pivot_root(2)` and `umount2(MNT_DETACH)`.
/// Removed immediately afterwards, so it does not exist for any process the capsule can run.
const OLD_ROOT_NAME: &str = ".mur-oldroot";

/// [`OLD_ROOT_NAME`] relative, and rooted at `/` after the pivot, as NUL-terminated literals.
///
/// Same reason [`SEALED_ROOT_BASE_CANDIDATES_C`] exists: the probe child rehearses the pivot after
/// `fork()`, where composing a `CString` is not allowed. `old_root_names_agree` keeps the three
/// spellings in step.
pub(crate) const OLD_ROOT_NAME_C: &std::ffi::CStr = c".mur-oldroot";

/// [`OLD_ROOT_NAME`] as it is named from inside the new root, once `pivot_root(2)` has parked the
/// old one there.
pub(crate) const OLD_ROOT_PIVOTED_C: &std::ffi::CStr = c"/.mur-oldroot";

/// Base directories the new-root `tmpfs` may be mounted over, most preferred first.
///
/// The base is overmounted inside the private namespace, so whatever the host has there becomes
/// unreachable for the rest of the setup — which is why the chosen base must not be an ancestor of
/// the session workdir (a workdir under `/tmp` is entirely normal) and must not be one of the
/// directories the composed root goes on to bind-mount from.
pub const SEALED_ROOT_BASE_CANDIDATES: &[&str] = &["/tmp", "/run", "/var/tmp", "/mnt", "/media"];

/// [`SEALED_ROOT_BASE_CANDIDATES`] as NUL-terminated literals, in the same order.
///
/// The host probe's child rehearses the composed root inside a `fork()`, where composing a
/// `CString` would touch the allocator a sibling thread of the parent may have held frozen at fork
/// time. Static literals are the only form usable there. `probe_root_base_candidates_match_the_str_list`
/// keeps the two lists identical, so the probe can never rehearse a base the real construction
/// would not choose.
pub(crate) const SEALED_ROOT_BASE_CANDIDATES_C: &[&std::ffi::CStr] =
    &[c"/tmp", c"/run", c"/var/tmp", c"/mnt", c"/media"];

/// `hidepid` spellings tried, in order, when mounting the composed root's `/proc` with
/// `mount -t proc`. The numeric form is the legacy parser's; `invisible` is the Linux 5.8+
/// spelling; the empty string is a plain private `procfs` with no masking.
///
/// **On a bare host none of the three succeeds, and that is a kernel rule.**
/// `proc_fill_super` requires `CAP_SYS_ADMIN` over the user namespace *owning the PID namespace*.
/// `unshare(CLONE_NEWUSER | CLONE_NEWNS)` leaves the process in the host's initial PID namespace,
/// whose owner is the initial user namespace — where an unprivileged process has no capabilities
/// at all — so every `mount -t proc` returns `EPERM`. Adding `CLONE_NEWPID` does not help either:
/// `unshare` moves only *future children* into the new PID namespace, so the mounting process is
/// still judged against the old one. Mounting a private `procfs` unprivileged genuinely requires
/// forking so the child becomes PID 1, which changes reaping and signal semantics for the whole
/// capsule subprocess tree and is out of scope here (see the PID-namespace note in
/// `docs/content/reference/sealed-containment-manual-verification.md`).
///
/// They are still tried first, and in this order, because they *do* succeed where the process has
/// that privilege — as root, and inside a container run with `--cap-add SYS_ADMIN` — and because
/// a later PID-namespace slice makes them succeed everywhere without touching this list.
///
/// When they all fail the executor binds the host's `/proc` instead. The capsule can then
/// enumerate host PIDs and read the `/proc/<pid>/root` and `/proc/<pid>/cwd` symlinks, so `/proc`
/// is the one part of the composed root where "outside does not exist" degrades to `scoped`'s
/// "outside is denied" — Landlock's ruleset covers no path under `/proc`, so opens through it are
/// refused, and `ptrace_may_access` gates the rest. Every other axis of the root stays absolute. The alternative is a capsule with no `/proc` at all, which
/// breaks `/dev/fd`, process substitution and every runtime that reads `/proc/self/*`.
const PROC_HIDEPID_OPTIONS: &[&str] = &["hidepid=2", "hidepid=invisible", ""];

// ---------------------------------------------------------------- host layout (test seam)

/// What a path is on the host, as far as composing a root cares.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PathKind {
    Dir,
    /// Any non-directory: a regular file, a device node, a socket. All are bind-mount targets that
    /// need an empty *file* created for them rather than a directory.
    File,
    /// A symlink, with its literal (un-resolved) target.
    Symlink(PathBuf),
}

/// The host filesystem facts [`plan_composed_root`] reads. A trait purely so the planner can be
/// unit-tested against a synthetic usrmerge / non-usrmerge layout on any machine — production has
/// exactly one implementation, [`RealHostLayout`].
pub(crate) trait HostLayout {
    fn kind(&self, path: &Path) -> Option<PathKind>;
}

/// The real filesystem, read with `symlink_metadata` so a usrmerge `/bin -> usr/bin` reports as a
/// symlink rather than as the directory it points at.
pub(crate) struct RealHostLayout;

impl HostLayout for RealHostLayout {
    fn kind(&self, path: &Path) -> Option<PathKind> {
        let meta = std::fs::symlink_metadata(path).ok()?;
        if meta.file_type().is_symlink() {
            return Some(PathKind::Symlink(std::fs::read_link(path).ok()?));
        }
        if meta.is_dir() {
            return Some(PathKind::Dir);
        }
        Some(PathKind::File)
    }
}

// ---------------------------------------------------------------- the plan

/// One filesystem operation in the composed-root plan.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RootOp {
    /// `mkdir(path, 0755)`. `EEXIST` is success.
    MkDir(PathBuf),
    /// Create an empty regular file, to be bind-mounted over.
    MkFile(PathBuf),
    /// `symlink(target, link)` — used to reproduce the host's usrmerge shape and the OCI `/dev`
    /// symlinks.
    Symlink { target: PathBuf, link: PathBuf },
    /// `mount(source, target, MS_BIND | MS_REC)`, followed by a second
    /// `MS_REMOUNT | MS_BIND | MS_RDONLY` call when `read_only`. The second call is required: a
    /// single `MS_BIND | MS_RDONLY` mount does *not* produce a read-only bind.
    Bind {
        source: PathBuf,
        target: PathBuf,
        read_only: bool,
    },
    /// [`Self::Bind`] of a directory the parent holds a descriptor on: the child opens `source`
    /// after it has entered its own mount namespace, refuses unless the directory it reached has
    /// `identity` — the `(st_dev, st_ino)` of the parent's descriptor — and binds through the
    /// descriptor it opened. A link swapped onto `source` after the parent took its descriptor
    /// fails the step rather than redirecting the bind.
    ///
    /// The parent's descriptor itself cannot be the source: a bind's source must be a mount in
    /// the caller's own namespace, and one opened before `unshare(CLONE_NEWNS)` is not (`EINVAL`).
    BindVerified {
        source: PathBuf,
        target: PathBuf,
        read_only: bool,
        identity: (u64, u64),
    },
    /// A fresh `tmpfs`.
    Tmpfs {
        target: PathBuf,
        options: &'static str,
    },
    /// A `/proc`: a fresh `procfs` masked with `hidepid` where the kernel permits one, a bind of
    /// the host's where it does not. Which of the two a host gets is decided at execution time, not
    /// here — see [`PROC_HIDEPID_OPTIONS`].
    Proc { target: PathBuf },
    /// A fresh `devpts` instance, so the capsule can allocate its own ptys without seeing the
    /// host's.
    DevPts { target: PathBuf },
    /// `mount(NULL, target, NULL, MS_REMOUNT | MS_BIND | MS_RDONLY)` — used to seal `/dev` after
    /// its device nodes have been bound into it.
    RemountReadOnly(PathBuf),
}

/// One planned operation plus whether failing it aborts the launch.
///
/// `required: false` is the "shrink, do not fail" convention this crate already uses for optional
/// device grants in `sandbox::open_landlock_fds`: losing an optional bind makes the composed root
/// *narrower*, never wider, so refusing the launch over it would trade a working capsule for no
/// security gain.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RootStep {
    pub(crate) op: RootOp,
    pub(crate) required: bool,
}

/// The full, host-resolved recipe for one composed root.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ComposedRootPlan {
    /// Directory the new-root `tmpfs` is mounted over, and the directory `pivot_root` is handed.
    pub(crate) base: PathBuf,
    pub(crate) steps: Vec<RootStep>,
    /// The workdir's path *inside* the composed root. Identical to its host path by design: env
    /// vars, `PWD`, log paths and anything a previous turn recorded keep working, and the capsule
    /// never has to be told it moved.
    pub(crate) workdir_in_root: PathBuf,
}

/// Picks the directory the new-root `tmpfs` is mounted over.
///
/// Rejects any candidate that is the workdir or an ancestor of it — overmounting an ancestor of
/// the workdir would hide the very directory the plan then has to bind-mount — and any candidate
/// the host does not have. Pure apart from the injected `exists` predicate.
pub(crate) fn choose_root_base(
    workdir: &Path,
    candidates: &[&str],
    exists: impl Fn(&Path) -> bool,
) -> Option<PathBuf> {
    candidates
        .iter()
        .map(Path::new)
        .find(|candidate| !workdir.starts_with(candidate) && exists(candidate))
        .map(Path::to_path_buf)
}

/// Builds the ordered operation list for one composed root. Pure with respect to `host`.
///
/// `extra_read_only` carries the host directories this *particular* capsule needs beyond
/// [`SEALED_RUNTIME_PATHS`] — the containing directory of each resolved `shell.allow` binary and
/// each `capabilities.shell.interpreter_runtime` directory. They are whole-directory binds, not a
/// per-file grant set: a bind carries a directory's whole contents, so this must not grow into a
/// second ELF-closure derivation. Entries already covered by a fixed path are dropped.
///
/// `staged_runtime_read_only` carries the `source_path` of each declared
/// `capabilities.shell.staged_runtime` grant. It is a *separate* parameter from `extra_read_only`
/// rather than more entries in it, because the two have opposite failure semantics and the
/// difference is the whole point of the capability. See [`PlanBuilder::require_bind`].
pub(crate) fn plan_composed_root(
    accessible_workdir: &Path,
    sources: &SealedBindSources<'_>,
    base: &Path,
    extra_read_only: &[PathBuf],
    staged_runtime_read_only: &[PathBuf],
    host: &dyn HostLayout,
) -> ComposedRootPlan {
    let mut builder = PlanBuilder::new(base);

    // 0. Declared `staged_runtime` trees, read-only and REQUIRED — before everything else.
    //
    //    Ordering is load-bearing, not tidiness. `mirror` below deduplicates by target path via
    //    the `made` set, so whichever loop registers a target first wins it and any later loop
    //    silently no-ops on the same target. Running the required binds first means a staged path
    //    that happens to collide with an optional one can only ever be *upgraded* to required,
    //    never silently downgraded to optional.
    //
    //    These are also planned ahead of /dev, /proc, /tmp and the workdir bind — and therefore
    //    ahead of `pivot_root`, which `construct_composed_root` performs only after every planned
    //    step has run. A capsule never reaches a shell tool call inside a root that is missing a
    //    runtime tree it declared.
    for path in staged_runtime_read_only {
        builder.require_bind(path);
    }

    // 1. The host runtime tree, read-only. A usrmerge symlink is reproduced as a symlink so the
    //    composed root has the host's shape; a real directory is bind-mounted.
    for path in SEALED_RUNTIME_PATHS
        .iter()
        .map(Path::new)
        .chain(extra_read_only.iter().map(PathBuf::as_path))
    {
        builder.mirror(path, host, /* required */ false);
    }

    // 2. The narrow /etc allowlist, read-only. Everything else under /etc simply does not exist.
    //
    //    An entry marked synthetic is not mirrored from the host at all: its target is bound from
    //    the file the parent wrote in the session's `sealed-etc/` directory.
    //    `required: true` there, unlike the host-mirrored entries' `required: false` — those are
    //    optional because a distribution may genuinely not have them, whereas the parent wrote
    //    these two itself, so a bind that fails is a broken runtime rather than a narrower one, and
    //    the empty `MkFile` left in its place would be a passwd database with no accounts in it.
    for entry in SEALED_ETC_PATHS {
        let path = Path::new(entry.path);
        match entry.synthetic {
            None => builder.mirror(path, host, /* required */ false),
            Some(file) => builder.bind_file(
                synthetic_etc_source(sources.etc_dir, file),
                rebase(base, path),
                /* required */ true,
            ),
        }
    }

    // 3. A private /dev tmpfs carrying the OCI default device set, sealed read-only once it is
    //    populated. Device nodes are bind-mounted from the host because `mknod` of a device is
    //    refused inside a user namespace — see `SealedDevice`.
    let dev = base.join("dev");
    builder.mkdir_p(&dev);
    builder.push(
        RootOp::Tmpfs {
            target: dev.clone(),
            options: "mode=0755,size=1m",
        },
        true,
    );
    for device in SEALED_DEVICE_NODES {
        let source = PathBuf::from(device.path);
        if host.kind(&source).is_none() {
            continue;
        }
        let target = dev.join(device.name);
        builder.push(RootOp::MkFile(target.clone()), false);
        builder.push(
            RootOp::Bind {
                source,
                target,
                read_only: false,
            },
            false,
        );
    }
    let pts = dev.join("pts");
    builder.push(RootOp::MkDir(pts.clone()), false);
    builder.push(RootOp::DevPts { target: pts }, false);
    for (link, target) in SEALED_DEVICE_SYMLINKS {
        builder.push(
            RootOp::Symlink {
                target: PathBuf::from(*target),
                link: dev.join(link),
            },
            false,
        );
    }
    builder.push(RootOp::RemountReadOnly(dev), false);

    // 4. /proc — masked with hidepid where the kernel allows it, bound from the host where it does
    //    not. See `PROC_HIDEPID_OPTIONS`.
    let proc = base.join("proc");
    builder.push(RootOp::MkDir(proc.clone()), true);
    builder.push(RootOp::Proc { target: proc }, true);

    // 5. /tmp, backed by a directory inside the session workdir so it stays inside the one
    //    writable path and inside the workdir size budget.
    //
    //    Before the workdir, not after, and the ordering is load-bearing rather than tidy. A
    //    session workdir under `/tmp` is not an edge case — it is `mur run`'s default, since
    //    `--workdir` falls back to a temporary directory. With the workdir reproduced first, this
    //    mount landed *on top of* the path leading to it, the workdir bind vanished under it, and
    //    the construction died at `chdir into the workdir inside the root: ENOENT` — after the
    //    pivot, with the host root already detached. Mounting `/tmp` first means the workdir's path
    //    components are created inside it, so the deeper mount is the one that survives.
    let tmp = base.join("tmp");
    builder.push(RootOp::MkDir(tmp.clone()), true);
    builder.push(
        RootOp::BindVerified {
            source: sources.tmp_store.0.to_path_buf(),
            target: tmp,
            read_only: false,
            identity: sources.tmp_store.1,
        },
        true,
    );

    // 6. The capsule's workdir — the accessible one, which is also the subprocess cwd — at its
    //    own absolute path, read-write. The only writable path in the composed root, and the
    //    subtree holding the session directory that backs /tmp above.
    let workdir_target = rebase(base, accessible_workdir);
    builder.mkdir_p(&workdir_target);
    builder.push(
        RootOp::Bind {
            source: accessible_workdir.to_path_buf(),
            target: workdir_target,
            read_only: false,
        },
        true,
    );

    // 7. The session's runtime directory, read-only and REQUIRED, at its own absolute path, so
    //    `$MURMUR_RUNTIME_DIR` names the same directory inside the root as on the host. After the
    //    workdir for the reason /tmp precedes it: a runtime directory under either is created
    //    inside it, and the deeper mount is the one that survives. A runtime directory that
    //    cannot be bound ends the session rather than leaving its commands without their task
    //    and tools.
    if let Some((path, identity)) = sources.runtime_dir {
        let target = rebase(base, path);
        builder.mkdir_p(&target);
        builder.push(
            RootOp::BindVerified {
                source: path.to_path_buf(),
                target,
                read_only: true,
                identity,
            },
            true,
        );
    }

    // 8. The session's records directory, read-only and REQUIRED, at its own absolute path, so
    //    `$MURMUR_RECORDS_DIR` names it inside the root: a command reads the trace and logs and
    //    changes none of them. Bound after the runtime directory, so the deeper bind wins when one
    //    lies beneath the other. A records directory that cannot be bound ends the session rather than leaving
    //    it writable, or absent from a root whose commands are told where it is.
    if let Some((path, identity)) = sources.records_dir {
        let target = rebase(base, path);
        builder.mkdir_p(&target);
        builder.push(
            RootOp::BindVerified {
                source: path.to_path_buf(),
                target,
                read_only: true,
                identity,
            },
            true,
        );
    }

    ComposedRootPlan {
        base: base.to_path_buf(),
        steps: builder.steps,
        workdir_in_root: accessible_workdir.to_path_buf(),
    }
}

/// `base` + `path`, where `path` is absolute: `/tmp` + `/usr/lib` → `/tmp/usr/lib`.
///
/// `pub(crate)` so [`crate::staged_runtime::target_under_root`] can reuse this instead of
/// reimplementing the same re-basing rule.
pub(crate) fn rebase(base: &Path, path: &Path) -> PathBuf {
    let relative = path.strip_prefix("/").unwrap_or(path);
    base.join(relative)
}

struct PlanBuilder {
    base: PathBuf,
    steps: Vec<RootStep>,
    /// Directories already scheduled for creation, so a shared prefix (`/usr`, `/etc`) is not
    /// `mkdir`ed once per entry under it.
    made: std::collections::HashSet<PathBuf>,
}

impl PlanBuilder {
    fn new(base: &Path) -> Self {
        let mut made = std::collections::HashSet::new();
        made.insert(base.to_path_buf());
        Self {
            base: base.to_path_buf(),
            steps: Vec::new(),
            made,
        }
    }

    fn push(&mut self, op: RootOp, required: bool) {
        self.steps.push(RootStep { op, required });
    }

    /// Schedules `mkdir` for every not-yet-scheduled component of `target` under the base.
    fn mkdir_p(&mut self, target: &Path) {
        let mut current = self.base.clone();
        let Ok(relative) = target.strip_prefix(&self.base) else {
            return;
        };
        for component in relative.components() {
            current = current.join(component);
            if self.made.insert(current.clone()) {
                self.steps.push(RootStep {
                    op: RootOp::MkDir(current.clone()),
                    required: true,
                });
            }
        }
    }

    /// Schedules an unconditional, **required** read-only directory bind of `source`.
    ///
    /// The deliberate difference from [`Self::mirror`] is that this never consults [`HostLayout`].
    /// `mirror` asks the host whether a path exists and, when it does not, returns having
    /// scheduled *nothing at all* — not even a step that would fail. That is right for
    /// `extra_read_only`, where a missing path should make the composed root narrower rather than
    /// refuse the launch. It is exactly wrong for `staged_runtime`, where a missing source must
    /// fail the launch: routed through `mirror`, a capsule declaring a runtime tree the host does
    /// not have would launch successfully into a root silently lacking it.
    ///
    /// So no existence pre-check happens here, or anywhere else in this module. The plan always
    /// carries the step, `required: true`, and the real `mount(2)` in `execute_step`'s
    /// [`CStepKind::Bind`] arm is the single source of truth for "does this exist" — a missing
    /// source fails with `ENOENT` at construction time, in the child, which
    /// `construct_composed_root`'s `step.required` check turns into a `SealedRootFailure`. That
    /// path already reaches the operator as `RuntimeError::SealedRootConstructionFailed`
    /// (`E-RUN-014`), already names the offending path via [`SealedRootSpec::describe`], and is
    /// already session-fatal, so no error variant of its own is needed.
    ///
    /// Always a directory bind: a staged runtime tree is a tree. `mkdir_p` registers the target in
    /// `made`, so a later `mirror` of the same path is the one that no-ops, never this.
    fn require_bind(&mut self, source: &Path) {
        let target = rebase(&self.base, source);
        if self.made.contains(&target) {
            return;
        }
        self.mkdir_p(&target);
        self.push(
            RootOp::Bind {
                source: source.to_path_buf(),
                target,
                read_only: true,
            },
            /* required */ true,
        );
    }

    /// Reproduces one host path inside the composed root: a symlink as a symlink, a directory or
    /// file as a read-only bind mount. A path the host does not have contributes nothing.
    fn mirror(&mut self, source: &Path, host: &dyn HostLayout, required: bool) {
        let Some(kind) = host.kind(source) else {
            return;
        };
        let target = rebase(&self.base, source);
        if self.made.contains(&target) {
            return;
        }
        match kind {
            PathKind::Symlink(link_target) => {
                if let Some(parent) = target.parent() {
                    self.mkdir_p(parent);
                }
                self.made.insert(target.clone());
                self.push(
                    RootOp::Symlink {
                        target: link_target,
                        link: target,
                    },
                    required,
                );
            }
            PathKind::Dir => {
                self.mkdir_p(&target);
                self.push(
                    RootOp::Bind {
                        source: source.to_path_buf(),
                        target,
                        read_only: true,
                    },
                    required,
                );
            }
            PathKind::File => self.bind_file(source.to_path_buf(), target, required),
        }
    }

    /// Schedules the mountpoint-then-bind pair one file bind needs: `mkdir -p` of its parent, an
    /// empty file to mount over (a bind needs an existing target of the right kind), then the
    /// read-only bind itself.
    ///
    /// Takes `source` and `target` separately rather than deriving one from the other, which is the
    /// whole reason it is a method: [`Self::mirror`] binds a host path at its own path, while a
    /// synthetic `/etc` entry binds a file from inside the workdir at a path that names something
    /// else entirely.
    fn bind_file(&mut self, source: PathBuf, target: PathBuf, required: bool) {
        if self.made.contains(&target) {
            return;
        }
        if let Some(parent) = target.parent() {
            self.mkdir_p(parent);
        }
        self.made.insert(target.clone());
        self.push(RootOp::MkFile(target.clone()), required);
        self.push(
            RootOp::Bind {
                source,
                target,
                read_only: true,
            },
            required,
        );
    }
}

// ---------------------------------------------------------------- Linux: probe + execution

/// Marker every composed-root failure message carries, so `shell.rs` can tell a `pre_exec`
/// sealed-root failure apart from a Landlock or seccomp one after reading it back off the
/// diagnostic pipe — the pipe carries one flat string, so the classification has to live in the
/// text. Declared here rather than inside the Linux submodule because the reader is
/// cross-platform code.
pub(crate) const SEALED_ROOT_FAILURE_PREFIX: &str = "sealed-root:";

#[cfg(target_os = "linux")]
pub(crate) use linux::{
    build_sealed_root_spec, construct_composed_root, probe_sealed_support, SealedRootSpec,
};

/// The post-`fork()` namespace primitives [`crate::network_namespace`] reuses rather than
/// reimplementing.
///
/// The `dumpable` pair is shared because a non-dumpable task's `/proc/self/uid_map` is root-owned
/// and therefore unopenable by the task itself, and every namespace `mur` creates hits that trap
/// identically — see [`linux::make_dumpable_for_map_writes`].
///
/// `userns_grant` is shared because it answers where the permission for `unshare(CLONE_NEWUSER)`
/// comes from, which `sealed` and the capsule network namespace both need. Two implementations of
/// one host question could return two answers, and the operator would be told to fix two different
/// things.
#[cfg(target_os = "linux")]
pub(crate) use linux::{
    make_dumpable_for_map_writes, restore_dumpable, userns_grant, write_decimal_map,
};

#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
mod linux {
    use std::ffi::CString;
    use std::os::unix::ffi::OsStrExt;
    use std::path::Path;

    use super::{
        ComposedRootPlan, NamespaceProbe, RootOp, RootStep, SealedProbe, UsernsGrant,
        OLD_ROOT_NAME, OLD_ROOT_NAME_C, OLD_ROOT_PIVOTED_C, PROC_HIDEPID_OPTIONS,
        SEALED_ROOT_BASE_CANDIDATES_C, SEALED_ROOT_FAILURE_PREFIX,
    };

    // ------------------------------------------------------------ probe

    /// Reads AppArmor's unprivileged-userns restriction and, if it is not in the way, really
    /// creates a user+mount namespace in a forked child.
    ///
    /// Forking rather than testing in-process is required, not defensive: `unshare(CLONE_NEWUSER)`
    /// is irreversible for the calling process, and putting the whole runtime into a user
    /// namespace as a side effect of a capability check would be exactly the "probe that changes
    /// the thing it measures" mistake `probe_landlock_full_access` documents avoiding.
    pub(crate) fn probe_sealed_support() -> SealedProbe {
        SealedProbe {
            userns_grant: userns_grant(),
            namespace: probe_namespace(),
        }
    }

    /// Reads the three host files [`UsernsGrant::from_readings`] decides on, which holds the
    /// whole decision.
    ///
    /// The knob is read from `/sys/module/apparmor/parameters` first and from `/proc/sys/kernel`
    /// only if that is missing: the two are the same value, and the `/sys` path is the one that
    /// exists on kernels where the `/proc` alias does not. Reading `/proc/self/attr/current`
    /// rather than the loaded-profile list is deliberate: a profile that is loaded but does not
    /// *attach* to the path `mur` was installed at helps nobody, and this asks the question that
    /// decides the outcome.
    pub(crate) fn userns_grant() -> UsernsGrant {
        let enabled = read_trimmed("/sys/module/apparmor/parameters/enabled");
        let restricted =
            read_trimmed("/sys/module/apparmor/parameters/restrict_unprivileged_userns")
                .or_else(|| read_trimmed("/proc/sys/kernel/apparmor_restrict_unprivileged_userns"));
        let current = read_trimmed("/proc/self/attr/current");
        UsernsGrant::from_readings(
            enabled.as_deref(),
            restricted.as_deref(),
            current.as_deref(),
        )
    }

    fn read_trimmed(path: &str) -> Option<String> {
        std::fs::read_to_string(path)
            .ok()
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
    }

    /// Flips `PR_SET_DUMPABLE` for the duration of the identity-map writes, and back again.
    ///
    /// Not optional. `mur` marks itself
    /// non-dumpable at startup (`security::harden_process_dumpable`, `prctl(PR_SET_DUMPABLE, 0)`)
    /// so that no same-uid process can read its `/proc/<pid>/environ`. That flag is inherited
    /// across `fork()`, and the kernel's `task_dump_owner()` reassigns *every* `/proc/<pid>/*`
    /// entry of a non-dumpable task to root — including `setgroups`, `uid_map` and `gid_map`. An
    /// unprivileged process therefore cannot open its own `uid_map` for writing, and the namespace
    /// it just created is one it can never own.
    ///
    /// The symptom is misleading: `unshare` succeeds, the map write fails with `EACCES`, and the
    /// refusal blames the host's id-mapping policy — on a host whose id-mapping policy is fine,
    /// and where the identical syscall sequence run from any other program succeeds. Without this
    /// flip, `sealed` is unreachable on every host for that reason alone.
    ///
    /// The window is reopened for exactly the three `open`/`write`/`close` pairs that need it and
    /// closed again before the first mount, so the child spends no longer readable than the map
    /// writes take.
    ///
    /// [`restore_dumpable`] puts back whatever the flag *was*, read here and returned, rather than
    /// assuming `0`. Hardcoding `0` looked equivalent — `mur` always runs non-dumpable — and was
    /// not: it also cleared the flag for every process that had *not* hardened itself, which
    /// includes this crate's own integration tests, and a non-dumpable child is one whose
    /// `/proc/<pid>/mem` the seccomp-notify supervisor could not read — every allowlisted `execve`
    /// then failed closed to `EACCES`.
    ///
    /// # Safety
    /// Post-`fork()`, pre-exec child context only — `prctl(2)` is async-signal-safe, but the
    /// dumpable window this reopens is only sound while this process is the single-threaded child
    /// that is about to `execve` a sandboxed binary.
    pub(crate) unsafe fn make_dumpable_for_map_writes() -> libc::c_int {
        // SAFETY: both `prctl` calls take four integer arguments; no pointers cross the boundary.
        // `PR_GET_DUMPABLE` returning `-1` means the query failed, in which case the restore below
        // is skipped rather than guessing.
        unsafe {
            let previous = libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0);
            libc::prctl(libc::PR_SET_DUMPABLE, 1 as libc::c_int, 0, 0, 0);
            previous
        }
    }

    /// Undoes [`make_dumpable_for_map_writes`], restoring the exact value it found.
    ///
    /// # Safety
    /// Same window and same constraints as [`make_dumpable_for_map_writes`]; `previous` must be
    /// the value that call returned.
    pub(crate) unsafe fn restore_dumpable(previous: libc::c_int) {
        if previous < 0 {
            return;
        }
        // SAFETY: integer-only `prctl`, in the post-fork child.
        unsafe {
            libc::prctl(libc::PR_SET_DUMPABLE, previous, 0, 0, 0);
        }
    }

    // Exit codes the probe child reports. Kept as small distinct integers so the parent learns the
    // *step* that failed without any IPC beyond `waitpid`.
    const PROBE_OK: i32 = 0;
    const PROBE_UNSHARE_DENIED: i32 = 1;
    const PROBE_UNSHARE_UNSUPPORTED: i32 = 2;
    const PROBE_MOUNT_DENIED: i32 = 3;
    const PROBE_MAP_DENIED: i32 = 4;
    /// No candidate in [`SEALED_ROOT_BASE_CANDIDATES_C`] accepted a `tmpfs` mount. Same mechanism
    /// and same remediation as [`PROBE_MOUNT_DENIED`], so it folds into `MountDenied`.
    const PROBE_TMPFS_DENIED: i32 = 5;
    /// The parking directory could not be made, or the child could not `chdir` into the new root —
    /// composed-root step 6 before the syscall itself.
    const PROBE_PIVOT_PREPARE_DENIED: i32 = 6;
    /// `syscall(SYS_pivot_root, ".", ".mur-oldroot")` was refused.
    const PROBE_PIVOT_ROOT_DENIED: i32 = 7;
    /// `pivot_root` succeeded and detaching the parked old root did not — composed-root step 7.
    const PROBE_OLD_ROOT_DETACH_DENIED: i32 = 8;

    fn probe_namespace() -> NamespaceProbe {
        // Read before the fork, and therefore before `unshare`: inside a fresh user namespace
        // with no mapping written yet, `getuid()`/`getgid()` report the *overflow* ids (65534),
        // not the real ones. Writing `65534 65534 1` into `uid_map` is refused with `EPERM` on
        // every host, so reading them after the unshare made the probe fail everywhere and
        // report the host as the culprit. This is the one ordering in this function that is
        // load-bearing.
        // SAFETY: getuid/getgid take no arguments, dereference nothing and cannot fail.
        let uid = unsafe { libc::getuid() };
        let gid = unsafe { libc::getgid() };

        // SAFETY: `fork()` from a possibly-multithreaded process is sound as long as the child
        // touches nothing but async-signal-safe primitives. The child below calls `unshare`,
        // `prctl`, `mount`, the `open`/`write`/`close` triples that write the identity maps,
        // `chdir`, `mkdir`, `pivot_root` via `syscall`, `umount2`, and `_exit` — every one of them
        // async-signal-safe, and no allocation, no locks, no stdio. Anything added to the child
        // must hold to the same list.
        let pid = unsafe { libc::fork() };
        if pid < 0 {
            return NamespaceProbe::Unsupported;
        }
        if pid == 0 {
            // SAFETY: forked-child context, syscalls only; every branch ends in `_exit`.
            unsafe {
                if libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS) != 0 {
                    let errno = *libc::__errno_location();
                    libc::_exit(match errno {
                        libc::EPERM => PROBE_UNSHARE_DENIED,
                        _ => PROBE_UNSHARE_UNSUPPORTED,
                    });
                }
                // Rehearse the identity uid/gid mapping too, rather than stopping at
                // `unshare`. A probe that skips it is not measuring what the real construction
                // does: a host can allow the namespace and still refuse to let the process own
                // it, and finding that out at spawn time instead of at launch time is exactly
                // the surprise this probe exists to prevent.
                //
                // `uid`/`gid` come from before the fork — see `probe_namespace`.
                //
                // Dumpable for the map writes only, and restored immediately: see
                // `make_dumpable_for_map_writes` for why an inherited non-dumpable flag makes
                // these three files root-owned.
                let previous_dumpable = make_dumpable_for_map_writes();
                let _ = write_decimal_map(c"/proc/self/setgroups", None, 0);
                let mapped = write_decimal_map(c"/proc/self/uid_map", Some(uid), uid).is_ok()
                    && write_decimal_map(c"/proc/self/gid_map", Some(gid), gid).is_ok();
                restore_dumpable(previous_dumpable);
                if !mapped {
                    libc::_exit(PROBE_MAP_DENIED);
                }

                // The first mount any composed root performs, and the one AppArmor's
                // `unprivileged_userns` profile denies: if this works, `CAP_SYS_ADMIN` is real
                // inside the new namespace.
                if libc::mount(
                    std::ptr::null(),
                    c"/".as_ptr(),
                    std::ptr::null(),
                    libc::MS_REC | libc::MS_PRIVATE,
                    std::ptr::null(),
                ) != 0
                {
                    libc::_exit(PROBE_MOUNT_DENIED);
                }

                // Steps 4, 6 and 7 of `construct_composed_root`, in the same order and with the
                // same syscalls. A probe that stops at the mount above clears a host that refuses
                // `pivot_root(2)`, which then fails at the first subprocess after an inference
                // call has already been paid for.
                //
                // Everything below happens inside this child's own mount namespace, whose
                // propagation the mount above just made private, so the host's mount table is
                // unchanged whatever the outcome — and the child `_exit`s a few syscalls later
                // without ever unwinding any of it.
                let mut based = false;
                for base in SEALED_ROOT_BASE_CANDIDATES_C {
                    if libc::mount(
                        c"tmpfs".as_ptr(),
                        base.as_ptr(),
                        c"tmpfs".as_ptr(),
                        libc::MS_NOSUID | libc::MS_NODEV,
                        c"mode=0755".as_ptr() as *const libc::c_void,
                    ) == 0
                    {
                        // `chdir` first, so the parking directory and `pivot_root`'s two
                        // arguments are all relative and no path has to be composed here.
                        if libc::chdir(base.as_ptr()) != 0 {
                            libc::_exit(PROBE_PIVOT_PREPARE_DENIED);
                        }
                        based = true;
                        break;
                    }
                }
                if !based {
                    libc::_exit(PROBE_TMPFS_DENIED);
                }

                if libc::mkdir(OLD_ROOT_NAME_C.as_ptr(), 0o700) != 0 {
                    libc::_exit(PROBE_PIVOT_PREPARE_DENIED);
                }
                if libc::syscall(
                    libc::SYS_pivot_root,
                    c".".as_ptr(),
                    OLD_ROOT_NAME_C.as_ptr(),
                ) != 0
                {
                    libc::_exit(PROBE_PIVOT_ROOT_DENIED);
                }
                if libc::chdir(c"/".as_ptr()) != 0 {
                    libc::_exit(PROBE_PIVOT_PREPARE_DENIED);
                }
                if libc::umount2(OLD_ROOT_PIVOTED_C.as_ptr(), libc::MNT_DETACH) != 0 {
                    libc::_exit(PROBE_OLD_ROOT_DETACH_DENIED);
                }
                libc::_exit(PROBE_OK);
            }
        }

        let mut status: libc::c_int = 0;
        // SAFETY: `pid` is the child just forked; `status` is a live local.
        let waited = unsafe { libc::waitpid(pid, &mut status, 0) };
        if waited != pid {
            return NamespaceProbe::Unsupported;
        }
        if !libc::WIFEXITED(status) {
            return NamespaceProbe::Unsupported;
        }
        match libc::WEXITSTATUS(status) {
            PROBE_OK => NamespaceProbe::Ok,
            PROBE_UNSHARE_DENIED => NamespaceProbe::Denied,
            // Kept apart from `Denied`: the child already told us which step failed, and
            // throwing that away made a map failure indistinguishable from the kernel refusing
            // the namespace outright — so the reported cause, and the remediation offered with
            // it, named the wrong thing entirely.
            PROBE_MAP_DENIED => NamespaceProbe::MapDenied,
            // A tmpfs the kernel would not accept over any candidate base is the same mechanism
            // and the same remediation as the propagation mount above, so the two report as one.
            PROBE_MOUNT_DENIED | PROBE_TMPFS_DENIED => NamespaceProbe::MountDenied,
            // The whole of composed-root steps 6 and 7. The parking `mkdir`, the two `chdir`s and
            // the `umount2` are the sequence `pivot_root(2)` is performed with, and a host that
            // refuses any of them refuses the pivot; the exit codes stay distinct so the *stage*
            // is still recoverable from a core-less child, while the blocker names the mechanism
            // an operator has to grant.
            PROBE_PIVOT_PREPARE_DENIED | PROBE_PIVOT_ROOT_DENIED | PROBE_OLD_ROOT_DETACH_DENIED => {
                NamespaceProbe::PivotRootDenied
            }
            _ => NamespaceProbe::Unsupported,
        }
    }

    /// Writes either the literal `deny` (when `id` is `None`) or an identity map line
    /// `"<id> <id> 1\n"`, formatting the number into a stack buffer.
    ///
    /// Hand-rolled rather than `format!` because this runs in a forked child: the parent may have
    /// been mid-allocation on another thread when `fork()` returned, so touching the allocator
    /// here can deadlock. `id` never exceeds `u32::MAX`, so ten digits is the whole range.
    ///
    /// # Safety
    /// Must only be called from the post-`fork()`, pre-exec window in the child, before any other
    /// thread could exist in this process — the same async-signal-safety constraint documented on
    /// [`construct_composed_root`]'s `unsafe` block, which this function's callers all sit inside.
    pub(crate) unsafe fn write_decimal_map(
        path: &std::ffi::CStr,
        id: Option<libc::uid_t>,
        value: libc::uid_t,
    ) -> Result<(), ()> {
        let Some(_) = id else {
            return write_file(path, b"deny");
        };

        let mut buf = [0u8; 32];
        let mut len = 0usize;
        push_decimal(&mut buf, &mut len, value);
        buf[len] = b' ';
        len += 1;
        push_decimal(&mut buf, &mut len, value);
        buf[len] = b' ';
        len += 1;
        buf[len] = b'1';
        len += 1;
        buf[len] = b'\n';
        len += 1;

        write_file(path, &buf[..len])
    }

    // ------------------------------------------------------------ spec (parent side)

    /// One planned operation, lowered to NUL-terminated C strings plus a pre-rendered label.
    ///
    /// The label is built here, in the parent, precisely so the child never has to: a failure
    /// message that names its step costs one `String` per step at spawn time and zero allocation
    /// inside `pre_exec`.
    struct CStep {
        kind: CStepKind,
        required: bool,
        label: String,
    }

    enum CStepKind {
        MkDir(CString),
        MkFile(CString),
        Symlink {
            target: CString,
            link: CString,
        },
        Bind {
            source: CString,
            target: CString,
            read_only: bool,
        },
        BindVerified {
            source: CString,
            target: CString,
            read_only: bool,
            identity: (u64, u64),
        },
        Tmpfs {
            target: CString,
            options: CString,
        },
        Proc {
            target: CString,
        },
        DevPts {
            target: CString,
        },
        RemountReadOnly(CString),
    }

    /// Everything the child needs to build a composed root, fully resolved before `fork()`.
    pub(crate) struct SealedRootSpec {
        uid_map: Vec<u8>,
        gid_map: Vec<u8>,
        base: CString,
        /// `<base>/.mur-oldroot` — created before the pivot.
        old_root_full: CString,
        /// `.mur-oldroot`, relative, as `pivot_root(2)` wants it with `cwd == base`.
        old_root_relative: CString,
        /// `/.mur-oldroot`, as it is named after the pivot, for the detach and the rmdir.
        old_root_pivoted: CString,
        steps: Vec<CStep>,
        workdir_in_root: CString,
    }

    /// Where a composed root's construction failed. `Copy` and allocation-free by construction —
    /// it is produced inside `pre_exec`; the message is rendered by the caller, afterwards.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) struct SealedRootFailure {
        /// Index into the spec's step list, or `usize::MAX` for one of the fixed
        /// unshare/pivot/chdir stages.
        pub(crate) step: usize,
        /// A fixed stage name when `step` is `usize::MAX`; otherwise unused.
        pub(crate) stage: &'static str,
        pub(crate) errno: i32,
    }

    impl SealedRootFailure {
        fn stage(stage: &'static str) -> Self {
            Self {
                step: usize::MAX,
                stage,
                errno: std::io::Error::last_os_error().raw_os_error().unwrap_or(0),
            }
        }

        fn step(index: usize) -> Self {
            Self {
                step: index,
                stage: "",
                errno: std::io::Error::last_os_error().raw_os_error().unwrap_or(0),
            }
        }
    }

    impl SealedRootSpec {
        /// Renders a failure into the message that reaches the operator, naming both the step and
        /// the errno. Runs in the *parent's* error path (via the diagnostic pipe) or in the
        /// child's, where an allocation is already unavoidable because the launch is over.
        pub(crate) fn describe(&self, failure: SealedRootFailure) -> String {
            let what = if failure.step == usize::MAX {
                failure.stage.to_string()
            } else {
                self.steps
                    .get(failure.step)
                    .map(|step| step.label.clone())
                    .unwrap_or_else(|| format!("step {}", failure.step))
            };
            format!(
                "{SEALED_ROOT_FAILURE_PREFIX} {what} failed: {}",
                std::io::Error::from_raw_os_error(failure.errno)
            )
        }
    }

    /// Remounts the bind at `target` read-only and `nosuid`, keeping the flags its source mount
    /// locks.
    ///
    /// # Safety
    /// Post-`fork()`, pre-exec only, on [`execute_step`]'s terms.
    unsafe fn remount_read_only(target: &CString) -> Result<(), ()> {
        // Inside a user namespace the bind inherits the source mount's flags locked: a remount
        // that does not repeat them is refused with `EPERM`. `statvfs` on the new bind reports
        // them from the kernel's `statfs` `f_flags`, with no allocation.
        let mut stat: libc::statvfs = std::mem::zeroed();
        let kept = if libc::statvfs(target.as_ptr(), &mut stat) == 0 {
            remount_flags_kept(stat.f_flag)
        } else {
            0
        };
        if libc::mount(
            std::ptr::null(),
            target.as_ptr(),
            std::ptr::null(),
            libc::MS_REMOUNT | libc::MS_BIND | libc::MS_RDONLY | libc::MS_NOSUID | kept,
            std::ptr::null(),
        ) != 0
        {
            return Err(());
        }
        Ok(())
    }

    /// `"/proc/self/fd/"` and the longest decimal `c_int` and a NUL.
    const PROC_FD_PATH_LEN: usize = 32;

    /// Writes `/proc/self/fd/<fd>` and a NUL into `out`, with no allocation.
    pub(crate) fn proc_fd_path(
        fd: libc::c_int,
        out: &mut [u8; PROC_FD_PATH_LEN],
    ) -> Result<(), ()> {
        const PREFIX: &[u8] = b"/proc/self/fd/";
        if fd < 0 {
            return Err(());
        }
        out[..PREFIX.len()].copy_from_slice(PREFIX);
        let mut len = PREFIX.len();
        push_decimal(out, &mut len, fd as u32);
        out[len] = 0;
        Ok(())
    }

    /// Appends `n` in decimal to `buf` at `*len`, advancing `*len`. Allocation-free, for the
    /// post-`fork()` window; `buf` must have room for ten more bytes.
    fn push_decimal(buf: &mut [u8], len: &mut usize, mut n: u32) {
        let mut digits = [0u8; 10];
        let mut count = 0;
        loop {
            digits[count] = b'0' + (n % 10) as u8;
            count += 1;
            n /= 10;
            if n == 0 {
                break;
            }
        }
        while count > 0 {
            count -= 1;
            buf[*len] = digits[count];
            *len += 1;
        }
    }

    /// Opens the directory at `source` with `O_PATH`, and returns its descriptor only when its
    /// `(st_dev, st_ino)` is `identity`. A mismatch closes it and fails with `ESTALE`.
    ///
    /// # Safety
    /// Allocation-free; callable post-`fork()`, pre-exec.
    pub(crate) unsafe fn open_verified_dir(
        source: &CString,
        identity: (u64, u64),
    ) -> Result<libc::c_int, ()> {
        let fd = libc::open(
            source.as_ptr(),
            libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC,
        );
        if fd < 0 {
            return Err(());
        }
        let mut stat: libc::stat = std::mem::zeroed();
        if libc::fstat(fd, &mut stat) != 0 {
            let errno = *libc::__errno_location();
            libc::close(fd);
            *libc::__errno_location() = errno;
            return Err(());
        }
        if (stat.st_dev as u64, stat.st_ino as u64) != identity {
            libc::close(fd);
            *libc::__errno_location() = libc::ESTALE;
            return Err(());
        }
        Ok(fd)
    }

    /// The mount flags a read-only remount of a bind has to repeat from the mount it was bound
    /// from, given that mount's `statvfs` `f_flag`: `nodev`, `noexec`, `nosuid` and the atime
    /// mode. A user namespace locks each of them on a mount it did not create, and a remount that
    /// drops one is refused with `EPERM`. No atime flag at all is `strictatime`, which is stated
    /// explicitly because a remount naming none defaults to `relatime`.
    pub(crate) fn remount_flags_kept(f_flags: libc::c_ulong) -> libc::c_ulong {
        let has = |flag: libc::c_ulong| f_flags & flag != 0;
        let mut kept: libc::c_ulong = 0;
        for (st, ms) in [
            (libc::ST_NODEV, libc::MS_NODEV),
            (libc::ST_NOEXEC, libc::MS_NOEXEC),
            (libc::ST_NOSUID, libc::MS_NOSUID),
            (libc::ST_NOATIME, libc::MS_NOATIME),
            (libc::ST_NODIRATIME, libc::MS_NODIRATIME),
            (libc::ST_RELATIME, libc::MS_RELATIME),
        ] {
            if has(st) {
                kept |= ms;
            }
        }
        if !has(libc::ST_NOATIME) && !has(libc::ST_RELATIME) {
            kept |= libc::MS_STRICTATIME;
        }
        kept
    }

    /// Lowers a [`ComposedRootPlan`] into the C-string form the child executes. Fails only on a
    /// path containing an interior NUL, which no real path does.
    pub(crate) fn build_sealed_root_spec(
        plan: &ComposedRootPlan,
    ) -> Result<SealedRootSpec, String> {
        // SAFETY: `getuid`/`getgid` take no arguments, dereference nothing and cannot fail.
        let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };

        let mut steps = Vec::with_capacity(plan.steps.len());
        for RootStep { op, required } in &plan.steps {
            let (kind, label) = match op {
                RootOp::MkDir(path) => (
                    CStepKind::MkDir(cstr(path)?),
                    format!("mkdir {}", path.display()),
                ),
                RootOp::MkFile(path) => (
                    CStepKind::MkFile(cstr(path)?),
                    format!("create {}", path.display()),
                ),
                RootOp::Symlink { target, link } => (
                    CStepKind::Symlink {
                        target: cstr(target)?,
                        link: cstr(link)?,
                    },
                    format!("symlink {} -> {}", link.display(), target.display()),
                ),
                RootOp::Bind {
                    source,
                    target,
                    read_only,
                } => (
                    CStepKind::Bind {
                        source: cstr(source)?,
                        target: cstr(target)?,
                        read_only: *read_only,
                    },
                    format!(
                        "bind{} {} -> {}",
                        if *read_only { " (ro)" } else { "" },
                        source.display(),
                        target.display()
                    ),
                ),
                RootOp::BindVerified {
                    source,
                    target,
                    read_only,
                    identity,
                } => (
                    CStepKind::BindVerified {
                        source: cstr(source)?,
                        target: cstr(target)?,
                        read_only: *read_only,
                        identity: *identity,
                    },
                    format!(
                        "bind{} {} (dev:ino {}:{}) -> {}",
                        if *read_only { " (ro)" } else { "" },
                        source.display(),
                        identity.0,
                        identity.1,
                        target.display()
                    ),
                ),
                RootOp::Tmpfs { target, options } => (
                    CStepKind::Tmpfs {
                        target: cstr(target)?,
                        options: CString::new(*options).map_err(|error| error.to_string())?,
                    },
                    format!("tmpfs on {}", target.display()),
                ),
                RootOp::Proc { target } => (
                    CStepKind::Proc {
                        target: cstr(target)?,
                    },
                    format!("proc on {}", target.display()),
                ),
                RootOp::DevPts { target } => (
                    CStepKind::DevPts {
                        target: cstr(target)?,
                    },
                    format!("devpts on {}", target.display()),
                ),
                RootOp::RemountReadOnly(path) => (
                    CStepKind::RemountReadOnly(cstr(path)?),
                    format!("remount read-only {}", path.display()),
                ),
            };
            steps.push(CStep {
                kind,
                required: *required,
                label,
            });
        }

        Ok(SealedRootSpec {
            // Identity maps: the capsule keeps the uid it already had, so files it writes into the
            // bind-mounted workdir are owned by the real user rather than by `nobody`.
            uid_map: format!("{uid} {uid} 1\n").into_bytes(),
            gid_map: format!("{gid} {gid} 1\n").into_bytes(),
            base: cstr(&plan.base)?,
            old_root_full: cstr(&plan.base.join(OLD_ROOT_NAME))?,
            old_root_relative: CString::new(OLD_ROOT_NAME).map_err(|e| e.to_string())?,
            old_root_pivoted: CString::new(format!("/{OLD_ROOT_NAME}"))
                .map_err(|e| e.to_string())?,
            steps,
            workdir_in_root: cstr(&plan.workdir_in_root)?,
        })
    }

    fn cstr(path: &Path) -> Result<CString, String> {
        CString::new(path.as_os_str().as_bytes())
            .map_err(|_| format!("path contains an interior NUL: {}", path.display()))
    }

    // ------------------------------------------------------------ execution (child side)

    /// Builds the composed root and pivots onto it. Runs inside the forked child's `pre_exec`
    /// window, before fd hygiene, the capability drop, seccomp and Landlock — which is the only
    /// window in which `unshare`/`mount`/`pivot_root` are available at all, since
    /// `sandbox::SECCOMP_MUST_STAY_DENIED` denies all three to every process the filter covers.
    ///
    /// Allocation-free on the success path: every path was turned into a `CString` by
    /// [`build_sealed_root_spec`] before `fork()`.
    pub(crate) fn construct_composed_root(spec: &SealedRootSpec) -> Result<(), SealedRootFailure> {
        // SAFETY: every call below is a bare syscall over pointers into `spec`, which outlives
        // this function. No allocation, no locks, no reentrancy — the constraints of the
        // post-fork/pre-exec window.
        unsafe {
            // 1. The namespaces. `CLONE_NEWUSER` is what makes `CLONE_NEWNS` available without
            //    host root; asking for both in one call means the mount namespace is created with
            //    the new user namespace's credentials already in force.
            if libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS) != 0 {
                return Err(SealedRootFailure::stage(
                    "unshare(CLONE_NEWUSER|CLONE_NEWNS)",
                ));
            }

            // 2. Identity uid/gid maps. `setgroups=deny` first, which the kernel requires before
            //    an unprivileged process may write `gid_map`. A host without `setgroups` (pre-3.19)
            //    is tolerated; a failing `uid_map` is not, because running as the overflow uid
            //    would leave the capsule unable to write its own workdir.
            //
            //    Dumpable is flipped on for exactly these three writes and put back before the
            //    first mount: `mur` runs non-dumpable, and a non-dumpable task's `/proc/self/*`
            //    entries are owned by root, which makes its own `uid_map` unopenable. See
            //    [`make_dumpable_for_map_writes`].
            let previous_dumpable = make_dumpable_for_map_writes();
            let _ = write_file(c"/proc/self/setgroups", b"deny");
            let uid_mapped = write_file(c"/proc/self/uid_map", &spec.uid_map).is_ok();
            let gid_mapped = uid_mapped && write_file(c"/proc/self/gid_map", &spec.gid_map).is_ok();
            restore_dumpable(previous_dumpable);
            if !uid_mapped {
                return Err(SealedRootFailure::stage("write /proc/self/uid_map"));
            }
            if !gid_mapped {
                return Err(SealedRootFailure::stage("write /proc/self/gid_map"));
            }

            // 3. Private propagation, so none of what follows escapes back to the host's mounts.
            if libc::mount(
                std::ptr::null(),
                c"/".as_ptr(),
                std::ptr::null(),
                libc::MS_REC | libc::MS_PRIVATE,
                std::ptr::null(),
            ) != 0
            {
                return Err(SealedRootFailure::stage("mount --make-rprivate /"));
            }

            // 4. The new root: an empty tmpfs over the chosen base. It is a mount point, which is
            //    what `pivot_root(2)` requires of its new root.
            if libc::mount(
                c"tmpfs".as_ptr(),
                spec.base.as_ptr(),
                c"tmpfs".as_ptr(),
                libc::MS_NOSUID | libc::MS_NODEV,
                c"mode=0755".as_ptr() as *const libc::c_void,
            ) != 0
            {
                return Err(SealedRootFailure::stage(
                    "mount tmpfs for the composed root",
                ));
            }

            // 5. The plan.
            for (index, step) in spec.steps.iter().enumerate() {
                if execute_step(step).is_err() && step.required {
                    return Err(SealedRootFailure::step(index));
                }
            }

            // 6. Pivot. `chdir` into the new root first so `pivot_root` can be handed the pair of
            //    relative paths the syscall is happiest with.
            if libc::mkdir(spec.old_root_full.as_ptr(), 0o700) != 0 {
                return Err(SealedRootFailure::stage(
                    "mkdir the old-root parking directory",
                ));
            }
            if libc::chdir(spec.base.as_ptr()) != 0 {
                return Err(SealedRootFailure::stage("chdir into the composed root"));
            }
            if libc::syscall(
                libc::SYS_pivot_root,
                c".".as_ptr(),
                spec.old_root_relative.as_ptr(),
            ) != 0
            {
                return Err(SealedRootFailure::stage("pivot_root"));
            }
            if libc::chdir(c"/".as_ptr()) != 0 {
                return Err(SealedRootFailure::stage("chdir / after pivot_root"));
            }

            // 7. Detach and remove the old root. After this there is no pathname anywhere in this
            //    namespace that reaches the host filesystem.
            if libc::umount2(spec.old_root_pivoted.as_ptr(), libc::MNT_DETACH) != 0 {
                return Err(SealedRootFailure::stage("umount2 the old root"));
            }
            // Best-effort, deliberately: `MNT_DETACH` already removed the old root from this
            // namespace's tree, so a leftover empty directory here is cosmetic. Failing a launch
            // over it would trade a working capsule for nothing.
            libc::rmdir(spec.old_root_pivoted.as_ptr());

            // 8. Seal the root tmpfs itself. `MS_REMOUNT | MS_BIND` changes per-mount flags only,
            //    which is the well-defined way to make an existing mount read-only; the workdir
            //    bind underneath it keeps its own (writable) flags.
            if libc::mount(
                std::ptr::null(),
                c"/".as_ptr(),
                std::ptr::null(),
                libc::MS_REMOUNT
                    | libc::MS_BIND
                    | libc::MS_RDONLY
                    | libc::MS_NOSUID
                    | libc::MS_NODEV,
                std::ptr::null(),
            ) != 0
            {
                return Err(SealedRootFailure::stage(
                    "remount the composed root read-only",
                ));
            }

            // 9. Back into the workdir, at the same absolute path it had on the host. `Command`
            //    already `chdir`ed here before this closure ran, but that was in the old root.
            if libc::chdir(spec.workdir_in_root.as_ptr()) != 0 {
                return Err(SealedRootFailure::stage(
                    "chdir into the workdir inside the root",
                ));
            }
        }

        Ok(())
    }

    /// Executes one planned step. `Err(())` carries no detail — the caller pairs the index with
    /// the spec's pre-rendered label and the live errno.
    ///
    /// # Safety
    /// Must only be called from the post-`fork()`, pre-exec window: every branch is a bare
    /// syscall over `CStr` pointers borrowed from `step`, which the caller guarantees outlives
    /// the call, and none may allocate or take a lock that a sibling thread could hold frozen at
    /// `fork()` time.
    unsafe fn execute_step(step: &CStep) -> Result<(), ()> {
        match &step.kind {
            CStepKind::MkDir(path) => {
                if libc::mkdir(path.as_ptr(), 0o755) != 0
                    && *libc::__errno_location() != libc::EEXIST
                {
                    return Err(());
                }
            }
            CStepKind::MkFile(path) => {
                let fd = libc::open(
                    path.as_ptr(),
                    libc::O_CREAT | libc::O_WRONLY | libc::O_CLOEXEC,
                    libc::mode_t::from(0o644u16),
                );
                if fd < 0 {
                    return Err(());
                }
                libc::close(fd);
            }
            CStepKind::Symlink { target, link } => {
                if libc::symlink(target.as_ptr(), link.as_ptr()) != 0 {
                    return Err(());
                }
            }
            CStepKind::Bind {
                source,
                target,
                read_only,
            } => {
                if libc::mount(
                    source.as_ptr(),
                    target.as_ptr(),
                    std::ptr::null(),
                    libc::MS_BIND | libc::MS_REC,
                    std::ptr::null(),
                ) != 0
                {
                    return Err(());
                }
                if *read_only {
                    remount_read_only(target)?;
                }
            }
            CStepKind::BindVerified {
                source,
                target,
                read_only,
                identity,
            } => {
                let fd = open_verified_dir(source, *identity)?;
                let mut path = [0u8; PROC_FD_PATH_LEN];
                let bound = proc_fd_path(fd, &mut path).is_ok()
                    && libc::mount(
                        path.as_ptr() as *const libc::c_char,
                        target.as_ptr(),
                        std::ptr::null(),
                        libc::MS_BIND | libc::MS_REC,
                        std::ptr::null(),
                    ) == 0;
                // `close` may overwrite `errno`; the mount's is the one the failure reports.
                let errno = *libc::__errno_location();
                libc::close(fd);
                if !bound {
                    *libc::__errno_location() = errno;
                    return Err(());
                }
                if *read_only {
                    remount_read_only(target)?;
                }
            }
            CStepKind::Tmpfs { target, options } => {
                if libc::mount(
                    c"tmpfs".as_ptr(),
                    target.as_ptr(),
                    c"tmpfs".as_ptr(),
                    libc::MS_NOSUID,
                    options.as_ptr() as *const libc::c_void,
                ) != 0
                {
                    return Err(());
                }
            }
            CStepKind::Proc { target } => {
                // Try each `hidepid` spelling in turn, then a recursive bind of the host's
                // `/proc` — see `PROC_HIDEPID_OPTIONS` for the bind's rationale and exposure.
                for option in PROC_HIDEPID_OPTIONS {
                    let mut buffer = [0u8; 32];
                    let bytes = option.as_bytes();
                    if bytes.len() >= buffer.len() {
                        continue;
                    }
                    buffer[..bytes.len()].copy_from_slice(bytes);
                    let data = if bytes.is_empty() {
                        std::ptr::null()
                    } else {
                        buffer.as_ptr() as *const libc::c_void
                    };
                    if libc::mount(
                        c"proc".as_ptr(),
                        target.as_ptr(),
                        c"proc".as_ptr(),
                        libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC,
                        data,
                    ) == 0
                    {
                        return Ok(());
                    }
                }

                // Last resort: bind the host's `/proc` in. `mount -t proc` needs `CAP_SYS_ADMIN`
                // over the *PID* namespace's user namespace, which an unprivileged user namespace
                // never has, so on a bare host every spelling above fails with `EPERM` and this is
                // the branch that actually runs. A bind of an existing mount needs no such
                // privilege. Recursive so the `/proc` submounts a modern host carries come with it
                // rather than leaving empty stubs.
                if libc::mount(
                    c"/proc".as_ptr(),
                    target.as_ptr(),
                    std::ptr::null(),
                    libc::MS_BIND | libc::MS_REC,
                    std::ptr::null(),
                ) != 0
                {
                    return Err(());
                }
                // Best-effort hardening of the bind. `MS_REMOUNT | MS_BIND` changes per-mount
                // flags only — unlike `hidepid`, which is a superblock option and stays refused —
                // so this narrows what the bind can do without touching the host's own `/proc`.
                // Not fatal: a `/proc` that is present and merely unhardened beats no `/proc`.
                libc::mount(
                    std::ptr::null(),
                    target.as_ptr(),
                    std::ptr::null(),
                    libc::MS_REMOUNT
                        | libc::MS_BIND
                        | libc::MS_NOSUID
                        | libc::MS_NODEV
                        | libc::MS_NOEXEC,
                    std::ptr::null(),
                );
                return Ok(());
            }
            CStepKind::DevPts { target } => {
                if libc::mount(
                    c"devpts".as_ptr(),
                    target.as_ptr(),
                    c"devpts".as_ptr(),
                    libc::MS_NOSUID | libc::MS_NOEXEC,
                    c"newinstance,ptmxmode=0666,mode=0620".as_ptr() as *const libc::c_void,
                ) != 0
                {
                    return Err(());
                }
            }
            CStepKind::RemountReadOnly(target) => {
                if libc::mount(
                    std::ptr::null(),
                    target.as_ptr(),
                    std::ptr::null(),
                    libc::MS_REMOUNT | libc::MS_BIND | libc::MS_RDONLY | libc::MS_NOSUID,
                    std::ptr::null(),
                ) != 0
                {
                    return Err(());
                }
            }
        }
        Ok(())
    }

    /// `open`/`write`/`close` over a static path, with no allocation — the `/proc/self/*_map`
    /// writes are the only file I/O the composed-root construction performs.
    ///
    /// # Safety
    /// Must only be called from the post-`fork()`, pre-exec window, for the same reason as
    /// [`execute_step`]: `path` and `data` are borrowed for the duration of the call only, and the
    /// raw `open`/`write`/`close` sequence must stay allocation- and lock-free in that window.
    unsafe fn write_file(path: &std::ffi::CStr, data: &[u8]) -> Result<(), ()> {
        let fd = libc::open(path.as_ptr(), libc::O_WRONLY | libc::O_CLOEXEC);
        if fd < 0 {
            return Err(());
        }
        let mut written = 0usize;
        while written < data.len() {
            let n = libc::write(
                fd,
                data[written..].as_ptr() as *const libc::c_void,
                data.len() - written,
            );
            if n < 0 {
                if *libc::__errno_location() == libc::EINTR {
                    continue;
                }
                libc::close(fd);
                return Err(());
            }
            if n == 0 {
                break;
            }
            written += n as usize;
        }
        libc::close(fd);
        if written == data.len() {
            Ok(())
        } else {
            Err(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    struct FakeHost(HashMap<PathBuf, PathKind>);

    impl FakeHost {
        fn usrmerge() -> Self {
            let mut map = HashMap::new();
            map.insert(PathBuf::from("/usr"), PathKind::Dir);
            map.insert(
                PathBuf::from("/bin"),
                PathKind::Symlink(PathBuf::from("usr/bin")),
            );
            map.insert(
                PathBuf::from("/sbin"),
                PathKind::Symlink(PathBuf::from("usr/sbin")),
            );
            map.insert(
                PathBuf::from("/lib"),
                PathKind::Symlink(PathBuf::from("usr/lib")),
            );
            map.insert(
                PathBuf::from("/lib64"),
                PathKind::Symlink(PathBuf::from("usr/lib64")),
            );
            map.insert(PathBuf::from("/etc/ld.so.cache"), PathKind::File);
            map.insert(PathBuf::from("/etc/ssl"), PathKind::Dir);
            // Present on the fake host precisely so the synthesis tests below can show that having
            // them is not what decides whether they are mirrored.
            map.insert(PathBuf::from("/etc/passwd"), PathKind::File);
            map.insert(PathBuf::from("/etc/group"), PathKind::File);
            for device in SEALED_DEVICE_NODES {
                map.insert(PathBuf::from(device.path), PathKind::File);
            }
            Self(map)
        }
    }

    impl HostLayout for FakeHost {
        fn kind(&self, path: &Path) -> Option<PathKind> {
            self.0.get(path).cloned()
        }
    }

    /// The session workdir's `.mur-tmp` under a `--workdir` of `/home/u/w`, and the identity of
    /// the descriptor `prepare_enforcement` took on it.
    const TEST_TMP_SOURCE: &str = "/home/u/w/.murmur/ses_plan_tests/.mur-tmp";
    const TEST_TMP_IDENTITY: (u64, u64) = (64, 7);

    /// The session's `sealed-etc/`, beside its runtime directory.
    const TEST_ETC_DIR: &str = "/home/u/.murmur/sessions/ses_plan_tests/sealed-etc";

    /// The runtime directory and the identity of its root's descriptor.
    const TEST_RUNTIME_DIR: &str = "/home/u/.murmur/sessions/ses_plan_tests/runtime";
    const TEST_RUNTIME_IDENTITY: (u64, u64) = (64, 8);

    /// The runtime-provided bind sources, with no runtime directory: the planner's steps 1–6.
    fn test_sources() -> SealedBindSources<'static> {
        SealedBindSources {
            tmp_store: (Path::new(TEST_TMP_SOURCE), TEST_TMP_IDENTITY),
            etc_dir: Path::new(TEST_ETC_DIR),
            runtime_dir: None,
            records_dir: None,
        }
    }

    fn plan_for(workdir: &str) -> ComposedRootPlan {
        plan_composed_root(
            Path::new(workdir),
            &test_sources(),
            Path::new("/tmp"),
            &[],
            &[],
            &FakeHost::usrmerge(),
        )
    }

    fn ops(plan: &ComposedRootPlan) -> Vec<RootOp> {
        plan.steps.iter().map(|step| step.op.clone()).collect()
    }

    #[test]
    fn base_selection_skips_any_ancestor_of_the_workdir() {
        // The default case: a workdir under the user's home, so `/tmp` is free.
        assert_eq!(
            choose_root_base(Path::new("/home/u/w"), SEALED_ROOT_BASE_CANDIDATES, |_| {
                true
            }),
            Some(PathBuf::from("/tmp"))
        );
        // A workdir under /tmp — overmounting /tmp would hide the workdir before it can be bound.
        assert_eq!(
            choose_root_base(
                Path::new("/tmp/session/w"),
                SEALED_ROOT_BASE_CANDIDATES,
                |_| true
            ),
            Some(PathBuf::from("/run"))
        );
        // A host missing the first two candidates falls through to the third.
        assert_eq!(
            choose_root_base(
                Path::new("/home/u/w"),
                SEALED_ROOT_BASE_CANDIDATES,
                |path| { path != Path::new("/tmp") && path != Path::new("/run") }
            ),
            Some(PathBuf::from("/var/tmp"))
        );
        assert_eq!(
            choose_root_base(Path::new("/home/u/w"), SEALED_ROOT_BASE_CANDIDATES, |_| {
                false
            }),
            None
        );
    }

    #[test]
    fn usrmerge_symlinks_are_reproduced_rather_than_bound_through() {
        let plan = plan_for("/home/u/w");
        assert!(ops(&plan).contains(&RootOp::Symlink {
            target: PathBuf::from("usr/bin"),
            link: PathBuf::from("/tmp/bin"),
        }));
        assert!(ops(&plan).contains(&RootOp::Bind {
            source: PathBuf::from("/usr"),
            target: PathBuf::from("/tmp/usr"),
            read_only: true,
        }));
        // `/lib32` and `/libx32` are absent from this fake host, so they contribute nothing.
        assert!(!ops(&plan)
            .iter()
            .any(|op| matches!(op, RootOp::Bind { source, .. } if source == Path::new("/lib32"))));
    }

    #[test]
    fn every_runtime_and_etc_bind_is_read_only_and_only_the_workdir_is_not() {
        let plan = plan_for("/home/u/w");
        let writable: Vec<&PathBuf> = plan
            .steps
            .iter()
            .filter_map(|step| match &step.op {
                RootOp::Bind {
                    source,
                    read_only: false,
                    ..
                } => Some(source),
                _ => None,
            })
            .collect();

        // The workdir, /tmp's workdir-backed store, and the /dev nodes (whose write side is the
        // device driver's, not the filesystem's) — and nothing else.
        for source in &writable {
            assert!(
                source.starts_with("/home/u/w") || source.starts_with("/dev/"),
                "unexpected writable bind of {}",
                source.display()
            );
        }
        assert!(writable.contains(&&PathBuf::from("/home/u/w")));
    }

    #[test]
    fn etc_is_an_allowlist_so_shadow_is_absent_by_construction() {
        let plan = plan_for("/home/u/w");
        let bound: Vec<String> = plan
            .steps
            .iter()
            .filter_map(|step| match &step.op {
                RootOp::Bind { source, .. } => Some(source.display().to_string()),
                _ => None,
            })
            .collect();

        assert!(bound.iter().any(|path| path == "/etc/ld.so.cache"));
        assert!(!bound.iter().any(|path| path == "/etc"));
        assert!(!bound.iter().any(|path| path.starts_with("/etc/shadow")));
        assert!(!bound.iter().any(|path| path.starts_with("/root")));
        assert!(!bound.iter().any(|path| path.starts_with("/home/u/.ssh")));
    }

    /// The host has both files (see `FakeHost::usrmerge`) and the plan mirrors neither: their
    /// targets are bound from the files the parent writes into `sealed-etc/` instead.
    #[test]
    fn passwd_and_group_are_bound_from_the_staging_files_never_from_the_host() {
        let plan = plan_for("/home/u/w");

        for host_path in ["/etc/passwd", "/etc/group"] {
            assert!(
                !plan.steps.iter().any(|step| matches!(
                    &step.op,
                    RootOp::Bind { source, .. } if source == Path::new(host_path)
                )),
                "the host's {host_path} carries every account on the machine and must not be \
                 bound into a capsule",
            );
        }

        for (file, target) in [
            (SyntheticEtcFile::Passwd, "/tmp/etc/passwd"),
            (SyntheticEtcFile::Group, "/tmp/etc/group"),
        ] {
            let expected = RootStep {
                op: RootOp::Bind {
                    source: synthetic_etc_source(Path::new(TEST_ETC_DIR), file),
                    target: PathBuf::from(target),
                    read_only: true,
                },
                // Not the host-mirrored entries' `required: false`: the parent wrote this file, so
                // a failed bind is a broken runtime, not a distribution that lacks the path.
                required: true,
            };
            assert!(
                plan.steps.contains(&expected),
                "expected {expected:?} in {:?}",
                plan.steps,
            );
            // And the mountpoint the bind lands on, since a bind needs an existing target.
            assert!(ops(&plan).contains(&RootOp::MkFile(PathBuf::from(target))));
        }

        // Every other /etc entry is still the host's own file, untouched by this.
        assert!(ops(&plan).contains(&RootOp::Bind {
            source: PathBuf::from("/etc/ld.so.cache"),
            target: PathBuf::from("/tmp/etc/ld.so.cache"),
            read_only: true,
        }));
    }

    /// Two lines, and the `pw_dir` field is the synthetic `HOME` verbatim — the property a capsule
    /// observes as `pwd.getpwuid(os.getuid()).pw_dir == os.environ["HOME"]`.
    #[test]
    fn the_synthetic_databases_name_root_and_the_capsules_own_id_and_nothing_else() {
        let identity = SealedAccountIdentity {
            uid: 1000,
            gid: 1000,
            home: "/w/.capsule-home",
        };

        let passwd = SyntheticEtcFile::Passwd.render(&identity).unwrap();
        assert_eq!(
            passwd,
            "root:x:0:0:root:/root:/bin/sh\n\
             capsule:x:1000:1000:Murmur capsule:/w/.capsule-home:/bin/sh\n"
        );
        let group = SyntheticEtcFile::Group.render(&identity).unwrap();
        assert_eq!(group, "root:x:0:\ncapsule:x:1000:\n");

        for (file, contents) in [
            (SyntheticEtcFile::Passwd, &passwd),
            (SyntheticEtcFile::Group, &group),
        ] {
            assert_eq!(
                contents.lines().count(),
                2,
                "{file:?} must stay a two-line database"
            );
            assert!(
                contents.ends_with('\n'),
                "{file:?} must end its last record with a newline"
            );
        }
    }

    /// A capsule already running as uid 0 gets *one* passwd line, not a second `root` — two entries
    /// for uid 0 would leave `getpwuid(0)` resolving to whichever the parser saw first.
    #[test]
    fn a_root_capsule_gets_a_single_passwd_line_carrying_its_own_home() {
        let identity = SealedAccountIdentity {
            uid: 0,
            gid: 0,
            home: "/w/.capsule-home",
        };

        assert_eq!(
            SyntheticEtcFile::Passwd.render(&identity).unwrap(),
            "root:x:0:0:root:/w/.capsule-home:/bin/sh\n"
        );
        assert_eq!(
            SyntheticEtcFile::Group.render(&identity).unwrap(),
            "root:x:0:\n"
        );
    }

    /// `passwd(5)` has no escaping, so a home path containing the field separator would silently
    /// shift every field after it — a `pw_shell` of half a path, or worse.
    #[test]
    fn a_home_path_that_cannot_be_spelled_in_a_passwd_field_is_refused() {
        for home in ["/w/od:d", "/w/two\nlines"] {
            let identity = SealedAccountIdentity {
                uid: 1000,
                gid: 1000,
                home,
            };
            let error = SyntheticEtcFile::Passwd.render(&identity).unwrap_err();
            assert!(
                error.contains(home),
                "the message must name the offending path: {error}"
            );
        }
    }

    /// Step 7: the runtime directory, read-only and required, at its own absolute path, from the
    /// descriptor the parent took, after the workdir's own bind.
    #[test]
    fn the_runtime_directory_is_bound_read_only_and_required_after_the_workdir() {
        let plan = plan_composed_root(
            Path::new("/home/u/w"),
            &SealedBindSources {
                runtime_dir: Some((Path::new(TEST_RUNTIME_DIR), TEST_RUNTIME_IDENTITY)),
                ..test_sources()
            },
            Path::new("/tmp"),
            &[],
            &[],
            &FakeHost::usrmerge(),
        );
        let bind = RootOp::BindVerified {
            source: PathBuf::from(TEST_RUNTIME_DIR),
            target: PathBuf::from("/tmp").join(TEST_RUNTIME_DIR.trim_start_matches('/')),
            read_only: true,
            identity: TEST_RUNTIME_IDENTITY,
        };
        let at = plan
            .steps
            .iter()
            .position(|step| step.op == bind)
            .expect("the runtime directory is bound");
        assert!(
            plan.steps[at].required,
            "a missing runtime directory ends the session"
        );
        let workdir = plan
            .steps
            .iter()
            .position(|step| {
                matches!(&step.op, RootOp::Bind { source, .. } if source == Path::new("/home/u/w"))
            })
            .unwrap();
        assert!(
            workdir < at,
            "the runtime directory is planned after the workdir"
        );
        assert_eq!(at, plan.steps.len() - 1);
        assert!(plan_for("/home/u/w").steps.iter().all(|step| !matches!(
            &step.op,
            RootOp::BindVerified { source, .. } if source == Path::new(TEST_RUNTIME_DIR)
        )));
    }

    /// The records directory is bound read-only and required at its own path, after the runtime
    /// directory, so the deeper bind survives a records directory beneath either.
    #[test]
    fn the_records_directory_is_bound_read_only_and_required_after_the_runtime_directory() {
        const TEST_RECORDS_DIR: &str = "/home/u/.murmur/records/home/u/w/ses_x";
        const TEST_RECORDS_IDENTITY: (u64, u64) = (7, 77);
        let plan = plan_composed_root(
            Path::new("/home/u/w"),
            &SealedBindSources {
                runtime_dir: Some((Path::new(TEST_RUNTIME_DIR), TEST_RUNTIME_IDENTITY)),
                records_dir: Some((Path::new(TEST_RECORDS_DIR), TEST_RECORDS_IDENTITY)),
                ..test_sources()
            },
            Path::new("/tmp"),
            &[],
            &[],
            &FakeHost::usrmerge(),
        );
        let position = |source: &str| {
            plan.steps
                .iter()
                .position(|step| {
                    matches!(&step.op, RootOp::BindVerified { source: s, read_only: true, .. } if s == Path::new(source))
                })
                .unwrap_or_else(|| panic!("{source} is bound read-only"))
        };
        let records = position(TEST_RECORDS_DIR);
        assert!(
            plan.steps[records].required,
            "a missing records directory ends the session"
        );
        assert!(position(TEST_RUNTIME_DIR) < records);
        assert_eq!(
            plan.steps[records].op,
            RootOp::BindVerified {
                source: PathBuf::from(TEST_RECORDS_DIR),
                target: PathBuf::from("/tmp").join(TEST_RECORDS_DIR.trim_start_matches('/')),
                read_only: true,
                identity: TEST_RECORDS_IDENTITY,
            }
        );
    }

    /// The remount keeps every flag a user namespace locks on the source mount.
    #[test]
    #[cfg(target_os = "linux")]
    fn a_read_only_remount_keeps_the_source_mounts_locked_flags() {
        let kept = linux::remount_flags_kept(
            libc::ST_NODEV | libc::ST_NOEXEC | libc::ST_NOSUID | libc::ST_RELATIME,
        );
        for flag in [
            libc::MS_NODEV,
            libc::MS_NOEXEC,
            libc::MS_NOSUID,
            libc::MS_RELATIME,
        ] {
            assert_ne!(kept & flag, 0, "{flag:#x}");
        }
        assert_eq!(kept & libc::MS_STRICTATIME, 0);
        let strict = linux::remount_flags_kept(0);
        assert_ne!(strict & libc::MS_STRICTATIME, 0);
        assert_eq!(strict & (libc::MS_NODEV | libc::MS_NOEXEC), 0);
    }

    #[test]
    fn the_workdir_keeps_its_absolute_path_inside_the_root() {
        let plan = plan_for("/home/u/.murmur/sessions/abc");
        assert_eq!(
            plan.workdir_in_root,
            PathBuf::from("/home/u/.murmur/sessions/abc")
        );
        assert!(ops(&plan).contains(&RootOp::Bind {
            source: PathBuf::from("/home/u/.murmur/sessions/abc"),
            target: PathBuf::from("/tmp/home/u/.murmur/sessions/abc"),
            read_only: false,
        }));
        // Every parent component is created before the bind, exactly once.
        let mkdirs: Vec<&RootOp> = plan
            .steps
            .iter()
            .map(|step| &step.op)
            .filter(|op| matches!(op, RootOp::MkDir(path) if path.starts_with("/tmp/home")))
            .collect();
        assert_eq!(mkdirs.len(), 5, "got {mkdirs:?}");
    }

    #[test]
    fn tmp_is_bound_only_when_it_is_the_directory_the_parent_holds() {
        let plan = plan_for("/home/u/w");
        assert!(ops(&plan).contains(&RootOp::BindVerified {
            source: PathBuf::from(TEST_TMP_SOURCE),
            target: PathBuf::from("/tmp/tmp"),
            read_only: false,
            identity: TEST_TMP_IDENTITY,
        }));
        // Never an unverified bind of a path a capsule's command could have replaced with a link.
        assert!(!ops(&plan).iter().any(|op| matches!(
            op,
            RootOp::Bind { source, .. } if source.ends_with(SEALED_TMP_DIR_NAME)
        )));
    }

    /// The child's check: the directory reached is the one whose identity the parent recorded,
    /// or nothing is bound. A link swapped in after the parent's descriptor was taken reaches
    /// another directory, and is refused with `ESTALE`.
    #[test]
    #[cfg(target_os = "linux")]
    #[allow(unsafe_code)]
    fn a_verified_bind_source_refuses_a_directory_swapped_in_after_the_descriptor() {
        use std::os::unix::fs::MetadataExt;

        let dir = tempfile::tempdir().unwrap();
        let store = dir.path().join(".mur-tmp");
        let outside = dir.path().join("outside");
        std::fs::create_dir_all(&store).unwrap();
        std::fs::create_dir_all(&outside).unwrap();
        let meta = std::fs::metadata(&store).unwrap();
        let identity = (meta.dev(), meta.ino());
        let source = std::ffi::CString::new(store.to_str().unwrap()).unwrap();

        // SAFETY: open, fstat and close on a path this test owns; nothing else holds the fd.
        let fd = unsafe { linux::open_verified_dir(&source, identity) }.expect("same directory");
        let mut path = [0u8; 32];
        linux::proc_fd_path(fd, &mut path).unwrap();
        let resolved = std::fs::canonicalize(
            std::ffi::CStr::from_bytes_until_nul(&path)
                .unwrap()
                .to_str()
                .unwrap(),
        )
        .unwrap();
        assert_eq!(resolved, store.canonicalize().unwrap());
        // SAFETY: `fd` was returned open by `open_verified_dir` and is closed once.
        unsafe { libc::close(fd) };

        std::fs::rename(&store, dir.path().join("moved")).unwrap();
        std::os::unix::fs::symlink(&outside, &store).unwrap();
        // SAFETY: `source` is a NUL-terminated path this test owns; on the identity mismatch it
        // reports, `open_verified_dir` has already closed the descriptor it opened.
        assert!(unsafe { linux::open_verified_dir(&source, identity) }.is_err());
        assert_eq!(
            std::io::Error::last_os_error().raw_os_error(),
            Some(libc::ESTALE)
        );
    }

    /// The composed root's own `/tmp` must not land on top of the path leading to the workdir.
    ///
    /// This is `mur run`'s default layout, not a curiosity: with no `--workdir`, the session
    /// workdir is a temporary directory, which is under `/tmp`. Planned in the other order, the
    /// `/tmp` bind hid the workdir bind underneath it and the construction died at `chdir` —
    /// *after* `pivot_root`, with the host root already detached, so the failure arrived as a bare
    /// `ENOENT` from inside a root that no longer had a way back.
    #[test]
    fn a_workdir_under_tmp_survives_the_composed_tmp_mounted_over_its_path() {
        let workdir = "/tmp/session-1234/w";
        let plan = plan_for(workdir);
        let operations = ops(&plan);

        // A workdir under /tmp forces a base other than /tmp, so both mounts are still expressible.
        assert_eq!(
            choose_root_base(Path::new(workdir), SEALED_ROOT_BASE_CANDIDATES, |_| true),
            Some(PathBuf::from("/run")),
        );

        let tmp_index = operations
            .iter()
            .position(
                |op| matches!(op, RootOp::BindVerified { target, .. } if target == Path::new("/tmp/tmp")),
            )
            .expect("the composed /tmp is bound");
        let workdir_index = operations
            .iter()
            .position(
                |op| matches!(op, RootOp::Bind { source, .. } if source == Path::new(workdir)),
            )
            .expect("the workdir is bound");
        assert!(
            tmp_index < workdir_index,
            "/tmp must be mounted before the workdir path is built inside it, or the workdir bind \
             is hidden by it",
        );
    }

    #[test]
    fn dev_carries_the_oci_default_set_and_is_sealed_afterwards() {
        let plan = plan_for("/home/u/w");
        let operations = ops(&plan);

        for device in SEALED_DEVICE_NODES {
            assert!(
                operations.contains(&RootOp::Bind {
                    source: PathBuf::from("/dev").join(device.name),
                    target: PathBuf::from("/tmp/dev").join(device.name),
                    read_only: false,
                }),
                "missing /dev/{}",
                device.name
            );
        }
        // No block device, and nothing outside the OCI default set.
        assert!(!operations.iter().any(
            |op| matches!(op, RootOp::Bind { source, .. } if source == Path::new("/dev/sda"))
        ));

        let tmpfs_index = operations
            .iter()
            .position(
                |op| matches!(op, RootOp::Tmpfs { target, .. } if target == Path::new("/tmp/dev")),
            )
            .expect("/dev tmpfs");
        let sealed_index = operations
            .iter()
            .position(
                |op| matches!(op, RootOp::RemountReadOnly(path) if path == Path::new("/tmp/dev")),
            )
            .expect("/dev sealed read-only");
        assert!(
            tmpfs_index < sealed_index,
            "the device nodes must be bound before /dev is sealed"
        );
    }

    /// The plan always asks for a masked `/proc`; whether the kernel grants one is a runtime
    /// question the executor answers, and on a bare host the answer is no — see
    /// [`PROC_HIDEPID_OPTIONS`] for the `CAP_SYS_ADMIN`-over-the-PID-namespace rule that forces
    /// the bind fallback. What this pins is the *preference order*: masking is tried first, and
    /// the unmasked private `procfs` is the last of the three before the fallback, never the
    /// first.
    #[test]
    fn proc_is_planned_and_masking_is_preferred_over_an_unmasked_mount() {
        let plan = plan_for("/home/u/w");
        assert!(ops(&plan).contains(&RootOp::Proc {
            target: PathBuf::from("/tmp/proc")
        }));
        assert_eq!(PROC_HIDEPID_OPTIONS[0], "hidepid=2");
        assert_eq!(
            PROC_HIDEPID_OPTIONS.last(),
            Some(&""),
            "the unmasked spelling must be tried last, after every masked one",
        );
    }

    #[test]
    fn manifest_derived_directories_are_whole_directory_binds_and_deduped() {
        let mut host = FakeHost::usrmerge();
        host.0
            .insert(PathBuf::from("/opt/python3.12"), PathKind::Dir);
        let plan = plan_composed_root(
            Path::new("/home/u/w"),
            &test_sources(),
            Path::new("/tmp"),
            &[PathBuf::from("/opt/python3.12"), PathBuf::from("/usr")],
            &[],
            &host,
        );
        let operations = ops(&plan);

        assert!(operations.contains(&RootOp::Bind {
            source: PathBuf::from("/opt/python3.12"),
            target: PathBuf::from("/tmp/opt/python3.12"),
            read_only: true,
        }));
        // `/usr` was already bound by the fixed list; naming it again adds nothing.
        assert_eq!(
            operations
                .iter()
                .filter(
                    |op| matches!(op, RootOp::Bind { source, .. } if source == Path::new("/usr"))
                )
                .count(),
            1
        );
    }

    /// The property the whole capability rests on: `extra_read_only` shrinks when the host is
    /// missing a path, `staged_runtime_read_only` fails. Both directions are asserted from the
    /// same plan so the contrast cannot drift apart.
    #[test]
    fn a_staged_runtime_path_absent_from_the_host_still_plans_a_required_bind() {
        // Neither path is in `FakeHost::usrmerge()` — the host has neither.
        let plan = plan_composed_root(
            Path::new("/home/u/w"),
            &test_sources(),
            Path::new("/tmp"),
            &[PathBuf::from("/opt/optional-tree")],
            &[PathBuf::from("/opt/staged-tree")],
            &FakeHost::usrmerge(),
        );

        // The optional entry contributes nothing at all — not even a step that would fail. This
        // is `mirror`'s silent-skip-on-absence, and it is why `extra_read_only` could not be the
        // destination for a staged grant.
        assert!(
            !plan.steps.iter().any(|step| matches!(
                &step.op,
                RootOp::Bind { source, .. } if source == Path::new("/opt/optional-tree")
            )),
            "an absent extra_read_only path must plan no step",
        );

        // The staged entry is planned regardless, and is required — so the real `mount(2)`
        // returning ENOENT aborts the construction before `pivot_root`.
        let staged = plan
            .steps
            .iter()
            .find(|step| {
                matches!(
                    &step.op,
                    RootOp::Bind { source, .. } if source == Path::new("/opt/staged-tree")
                )
            })
            .expect("an absent staged_runtime path must still plan a bind");
        assert_eq!(
            staged.op,
            RootOp::Bind {
                source: PathBuf::from("/opt/staged-tree"),
                target: PathBuf::from("/tmp/opt/staged-tree"),
                read_only: true,
            },
            "staged trees are re-based read-only binds at their own absolute path",
        );
        assert!(
            staged.required,
            "a staged_runtime bind must be required, so a missing source is session-fatal \
             rather than a silently narrower root",
        );
    }

    /// Staged binds land before `/etc`, `/dev`, `/proc`, `/tmp` and the workdir — and therefore
    /// before the `pivot_root` that `construct_composed_root` performs after every planned step.
    #[test]
    fn staged_runtime_binds_are_planned_before_every_other_step() {
        let mut host = FakeHost::usrmerge();
        host.0
            .insert(PathBuf::from("/opt/staged-tree"), PathKind::Dir);
        let plan = plan_composed_root(
            Path::new("/home/u/w"),
            &test_sources(),
            Path::new("/tmp"),
            &[],
            &[PathBuf::from("/opt/staged-tree")],
            &host,
        );

        let position = |predicate: &dyn Fn(&RootOp) -> bool| {
            plan.steps
                .iter()
                .position(|step| predicate(&step.op))
                .expect("step must be planned")
        };

        let staged = position(
            &|op| matches!(op, RootOp::Bind { source, .. } if source == Path::new("/opt/staged-tree")),
        );
        let fixed_runtime_tree = position(
            &|op| matches!(op, RootOp::Bind { source, .. } if source == Path::new("/usr")),
        );
        let etc = position(
            &|op| matches!(op, RootOp::Bind { source, .. } if source == Path::new("/etc/ssl")),
        );
        let dev = position(
            &|op| matches!(op, RootOp::Tmpfs { target, .. } if target == Path::new("/tmp/dev")),
        );
        let proc = position(&|op| matches!(op, RootOp::Proc { .. }));
        let tmp = position(
            &|op| matches!(op, RootOp::BindVerified { target, .. } if target == Path::new("/tmp/tmp")),
        );
        let workdir = position(
            &|op| matches!(op, RootOp::Bind { source, .. } if source == Path::new("/home/u/w")),
        );

        // Ahead of the fixed runtime tree / `extra_read_only` loop, so a coincidental target
        // collision is won by the required registration rather than the optional one.
        assert!(
            staged < fixed_runtime_tree,
            "staged binds precede the fixed runtime tree"
        );
        assert!(staged < etc, "staged binds precede /etc");
        assert!(staged < dev, "staged binds precede /dev");
        assert!(staged < proc, "staged binds precede /proc");
        assert!(staged < tmp, "staged binds precede /tmp");
        assert!(staged < workdir, "staged binds precede the workdir bind");
    }

    /// The collision case the ordering above exists to protect: a path named by *both* parameters
    /// is registered once, by the required loop.
    #[test]
    fn a_path_named_both_staged_and_optional_stays_required() {
        let mut host = FakeHost::usrmerge();
        host.0.insert(PathBuf::from("/opt/shared"), PathKind::Dir);
        let plan = plan_composed_root(
            Path::new("/home/u/w"),
            &test_sources(),
            Path::new("/tmp"),
            &[PathBuf::from("/opt/shared")],
            &[PathBuf::from("/opt/shared")],
            &host,
        );

        let binds: Vec<&RootStep> = plan
            .steps
            .iter()
            .filter(|step| {
                matches!(
                    &step.op,
                    RootOp::Bind { source, .. } if source == Path::new("/opt/shared")
                )
            })
            .collect();
        assert_eq!(
            binds.len(),
            1,
            "the shared target is registered exactly once"
        );
        assert!(
            binds[0].required,
            "and the required registration is the one that won"
        );
    }

    // ---- `UsernsGrant` ---------------------------------------------------------------------

    /// Every variant, produced from the combination of readings that must produce it. The three
    /// permitting cases are the point: they reach the same achieved class, so only the variant
    /// separates a `sealed` result on a host whose hardening is switched off from one obtained
    /// through the shipped profile.
    #[test]
    fn every_userns_grant_comes_from_its_own_combination_of_readings() {
        let cases = [
            // AppArmor off, or the knob file missing entirely: nothing restricts anything.
            ((None, None, None), UsernsGrant::ApparmorAbsent),
            (
                (Some("N"), Some("1"), Some("unconfined")),
                UsernsGrant::ApparmorAbsent,
            ),
            // Enabled, restriction explicitly off host-wide — the `/etc/sysctl.d` drop-in case.
            (
                (Some("Y"), Some("0"), Some("unconfined")),
                UsernsGrant::RestrictionDisabledHostWide,
            ),
            // Enabled and the knob unreadable: not restricted, so not withheld.
            (
                (Some("1"), None, Some("unconfined")),
                UsernsGrant::RestrictionDisabledHostWide,
            ),
            // Restriction on, and a profile whose name begins with `mur-sealed` is attached —
            // both the shipped profile and the checkout profile the dev script generates.
            (
                (Some("Y"), Some("Y"), Some("mur-sealed (unconfined)")),
                UsernsGrant::ProfileConfining,
            ),
            (
                (Some("Y"), Some("1"), Some("mur-sealed-home (unconfined)")),
                UsernsGrant::ProfileConfining,
            ),
            (
                (Some("Y"), Some("1"), Some("mur-sealed-dev (unconfined)")),
                UsernsGrant::ProfileConfining,
            ),
            // Restriction on and nothing attached, or something else attached.
            (
                (Some("Y"), Some("Y"), Some("unconfined")),
                UsernsGrant::Withheld,
            ),
            (
                (Some("Y"), Some("1"), Some("firefox (enforce)")),
                UsernsGrant::Withheld,
            ),
            ((Some("Y"), Some("1"), None), UsernsGrant::Withheld),
        ];

        for ((enabled, restricted, current), expected) in cases {
            assert_eq!(
                UsernsGrant::from_readings(enabled, restricted, current),
                expected,
                "enabled={enabled:?} restricted={restricted:?} current={current:?}"
            );
        }
    }

    /// The wire names are what `--explain-scope --json`, `session_start` and `mur doctor` all
    /// print, so two variants sharing one would re-collapse exactly the distinction this enum
    /// exists to make. `permits_userns` is the whole of what the runtime decisions read, and it
    /// must be false for `Withheld` alone — any other variant denying would refuse a host the
    /// runtime is required to keep serving.
    #[test]
    fn every_grant_has_a_distinct_wire_name_and_only_withheld_denies() {
        let names: Vec<&str> = UsernsGrant::ALL
            .iter()
            .map(|grant| grant.wire_name())
            .collect();
        let mut unique = names.clone();
        unique.sort_unstable();
        unique.dedup();
        assert_eq!(unique.len(), names.len(), "two grants share a wire name");
        assert_eq!(
            names,
            [
                "apparmor_absent",
                "restriction_disabled_host_wide",
                "profile_confining",
                "withheld",
            ]
        );

        for grant in UsernsGrant::ALL {
            assert_eq!(
                grant.permits_userns(),
                *grant != UsernsGrant::Withheld,
                "{grant:?} must permit the namespace unless it is Withheld"
            );
            assert_eq!(
                serde_json::to_value(grant).unwrap(),
                serde_json::Value::String(grant.wire_name().to_string()),
                "the serialized form and the wire name must be one string"
            );
        }

        // The `mur doctor` line under each wire name has to say something different for each, or
        // the block repeats the wire name in longer words and tells an operator nothing.
        let mut summaries: Vec<&str> = UsernsGrant::ALL.iter().map(|g| g.summary()).collect();
        summaries.sort_unstable();
        summaries.dedup();
        assert_eq!(
            summaries.len(),
            UsernsGrant::ALL.len(),
            "two grants share a summary"
        );

        // An unprobed host claims nothing, exactly as the `bool` field's `false` default did.
        assert_eq!(UsernsGrant::default(), UsernsGrant::Withheld);
    }

    // ---- the installed profile ------------------------------------------------------------

    /// All four outcomes, driven by a `Result` rather than by the filesystem, so a host with no
    /// AppArmor and a host with an unreadable `/etc/apparmor.d` are both covered without root and
    /// without touching a byte of `/etc`.
    #[test]
    fn the_installed_profile_classifier_separates_all_four_outcomes() {
        let shipped = std::fs::read(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../packaging/apparmor/mur-sealed"
        ))
        .expect("the shipped profile is in the workspace");
        assert_eq!(
            classify_installed_profile(Ok(shipped)),
            InstalledProfileState::Matches
        );

        let drifted = classify_installed_profile(Ok(b"# an older revision\n".to_vec()));
        match drifted {
            InstalledProfileState::Drifted { installed_sha256 } => {
                assert_ne!(installed_sha256, SEALED_APPARMOR_PROFILE_SHA256);
                assert_eq!(installed_sha256.len(), 64);
            }
            other => panic!("edited bytes must read as drift, got {other:?}"),
        }

        assert_eq!(
            classify_installed_profile(Err(std::io::Error::from(std::io::ErrorKind::NotFound))),
            InstalledProfileState::Absent
        );

        // "I could not look" must never read as "it is not there".
        match classify_installed_profile(Err(std::io::Error::from(
            std::io::ErrorKind::PermissionDenied,
        ))) {
            InstalledProfileState::Unreadable { error } => assert!(!error.is_empty()),
            other => panic!("a read error must stay distinct from absence, got {other:?}"),
        }
    }

    /// A refused `pivot_root(2)` is its own finding, with its own remediation. Without this
    /// variant a host that permits `mount(2)` and refuses the pivot probes as `Ok` and fails at
    /// the first subprocess with `E-RUN-014`, after an inference call has already been paid for.
    #[test]
    fn a_refused_pivot_root_is_its_own_blocker() {
        let probe = SealedProbe {
            userns_grant: UsernsGrant::ProfileConfining,
            namespace: NamespaceProbe::PivotRootDenied,
        };
        assert_eq!(
            sealed_blocker(true, true, probe),
            Some(SealedBlocker::PivotRootDenied)
        );

        let reason = SealedBlocker::PivotRootDenied.reason();
        assert!(reason.contains("pivot_root(2)"), "reason was: {reason}");
        // Distinguishable from `MountDenied`'s: an operator handed the mount remediation on a
        // host whose mounts already work has been sent somewhere useless.
        assert_ne!(reason, SealedBlocker::MountDenied.reason());
        assert!(reason.contains("seccomp"), "reason was: {reason}");
    }

    /// Every [`NamespaceProbe`] variant reaches a blocker decision, so a variant added later
    /// cannot fall through to "this host can back sealed".
    #[test]
    fn every_namespace_probe_outcome_is_attributed() {
        const ALL: &[NamespaceProbe] = &[
            NamespaceProbe::Ok,
            NamespaceProbe::Denied,
            NamespaceProbe::MapDenied,
            NamespaceProbe::MountDenied,
            NamespaceProbe::PivotRootDenied,
            NamespaceProbe::Unsupported,
        ];
        for namespace in ALL {
            let probe = SealedProbe {
                userns_grant: UsernsGrant::ProfileConfining,
                namespace: *namespace,
            };
            let blocker = sealed_blocker(true, true, probe);
            if *namespace == NamespaceProbe::Ok {
                assert_eq!(blocker, None, "a complete rehearsal must back sealed");
            } else {
                let blocker = blocker.unwrap_or_else(|| panic!("{namespace:?} named no blocker"));
                assert!(
                    SealedBlocker::ALL.contains(&blocker),
                    "{blocker:?} is missing from SealedBlocker::ALL"
                );
            }
        }
    }

    /// The probe child cannot compose a `CString`, so it carries its own NUL-terminated copies of
    /// the base candidates. A copy that drifted would have the probe rehearse a base the real
    /// construction would never choose.
    #[test]
    fn probe_root_base_candidates_match_the_str_list() {
        let literals: Vec<&str> = SEALED_ROOT_BASE_CANDIDATES_C
            .iter()
            .map(|value| value.to_str().expect("ASCII path literal"))
            .collect();
        assert_eq!(literals, SEALED_ROOT_BASE_CANDIDATES);
    }

    /// Same reason, for the old-root parking directory: three spellings of one name.
    #[test]
    fn old_root_names_agree() {
        assert_eq!(OLD_ROOT_NAME_C.to_str().unwrap(), OLD_ROOT_NAME);
        assert_eq!(
            OLD_ROOT_PIVOTED_C.to_str().unwrap(),
            format!("/{OLD_ROOT_NAME}")
        );
    }

    /// Four outcomes, none of them inferred from a path. `unconfined` and "I could not look" stay
    /// apart for the same reason [`InstalledProfileState`]'s two absences do.
    #[test]
    fn profile_attachment_reports_only_what_the_kernel_said() {
        assert_eq!(
            classify_profile_attachment(Some("mur-sealed (unconfined)")),
            ProfileAttachment::Sealed {
                profile: "mur-sealed".to_string()
            }
        );
        assert_eq!(
            classify_profile_attachment(Some("mur-sealed-home")),
            ProfileAttachment::Sealed {
                profile: "mur-sealed-home".to_string()
            }
        );
        assert_eq!(
            classify_profile_attachment(Some("snap.chromium.chromium (enforce)")),
            ProfileAttachment::Other {
                profile: "snap.chromium.chromium".to_string()
            }
        );
        assert_eq!(
            classify_profile_attachment(Some("unconfined")),
            ProfileAttachment::Unconfined
        );
        assert_eq!(
            classify_profile_attachment(Some("unconfined\n")),
            ProfileAttachment::Unconfined
        );
        assert_eq!(
            classify_profile_attachment(None),
            ProfileAttachment::NotReported
        );
        assert_eq!(
            classify_profile_attachment(Some("   ")),
            ProfileAttachment::NotReported
        );
    }

    /// The attachment list is documentation of the shipped profile, never a verdict — nothing
    /// decides anything by matching a path against it. This keeps it honest about what the file
    /// actually declares.
    #[test]
    fn attachment_paths_are_the_ones_the_shipped_profile_declares() {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../packaging/apparmor/mur-sealed"
        );
        let profile =
            std::fs::read_to_string(path).expect("the shipped profile is in the workspace");
        for attachment in SEALED_APPARMOR_ATTACHMENT_PATHS {
            assert!(
                profile.contains(attachment),
                "{attachment} is not an attachment in packaging/apparmor/mur-sealed"
            );
        }
    }

    /// The digest constant is a literal because `capsule-runtime` is published to crates.io and
    /// `cargo package` would not carry a file from outside the crate directory. This test is what
    /// keeps the literal honest, and it does not run during `cargo package`.
    #[test]
    fn shipped_profile_digest_constant_matches_the_file() {
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../packaging/apparmor/mur-sealed"
        );
        let bytes = std::fs::read(path).expect("the shipped profile is in the workspace");
        let actual = murmur_artifact::sha256_hex(&bytes);
        assert_eq!(
            actual, SEALED_APPARMOR_PROFILE_SHA256,
            "packaging/apparmor/mur-sealed changed. Update SEALED_APPARMOR_PROFILE_SHA256 in \
             crates/capsule-runtime/src/sealed.rs to:\n    {actual}"
        );
    }

    /// The profile is the fix and the sysctl is a fallback that costs the whole host its
    /// unprivileged-userns hardening. Both must be in the text — on a host where no profile can be
    /// loaded the sysctl is the right answer — but their order and the stated cost are what stop a
    /// reader taking them for peers.
    #[test]
    fn the_apparmor_reason_offers_the_profile_before_the_sysctl() {
        let reason = SealedBlocker::AppArmorProfileMissing.reason();
        let profile = reason
            .find("apparmor_parser -r")
            .expect("the profile install command must be named");
        let sysctl = reason
            .find("kernel.apparmor_restrict_unprivileged_userns=0")
            .expect("the fallback must still be named for hosts that cannot load a profile");
        assert!(
            profile < sysctl,
            "the profile install must come first: {reason}"
        );
        assert!(
            reason.contains("LAST RESORT"),
            "the sysctl must be labelled a fallback, not offered as a peer: {reason}"
        );
        assert!(
            reason.contains("every program on the machine"),
            "the sysctl's host-wide cost must be stated: {reason}"
        );
        assert!(
            reason.contains("scripts/install-dev-apparmor.sh"),
            "a checkout build must be told how to get the narrow grant: {reason}"
        );
    }

    #[test]
    fn blocker_blames_apparmor_before_the_namespace_outcome_it_causes() {
        let probe = SealedProbe {
            userns_grant: UsernsGrant::Withheld,
            namespace: NamespaceProbe::Denied,
        };
        assert_eq!(
            sealed_blocker(true, true, probe),
            Some(SealedBlocker::AppArmorProfileMissing)
        );
        let reason = SealedBlocker::AppArmorProfileMissing.reason();
        assert!(reason.contains("mur-sealed"));
        assert!(reason.contains("apparmor_parser -r"));
    }

    #[test]
    fn blocker_names_the_container_remediation_verbatim() {
        let probe = SealedProbe {
            userns_grant: UsernsGrant::ProfileConfining,
            namespace: NamespaceProbe::Denied,
        };
        assert_eq!(
            sealed_blocker(true, true, probe),
            Some(SealedBlocker::NamespaceCreationDenied)
        );
        let reason = SealedBlocker::NamespaceCreationDenied.reason();
        assert!(reason.contains("--cap-add SYS_ADMIN"));
        assert!(reason.contains("outside the container"));
    }

    #[test]
    fn a_map_failure_is_not_reported_as_the_container_case() {
        // `MapDenied` must stay distinct from `Denied`: a host that creates the namespace and
        // then refuses the id mapping is not the container case, and must not be told to add
        // `--cap-add SYS_ADMIN` to a container it is not running in.
        let probe = SealedProbe {
            userns_grant: UsernsGrant::ProfileConfining,
            namespace: NamespaceProbe::MapDenied,
        };
        assert_eq!(
            sealed_blocker(true, true, probe),
            Some(SealedBlocker::IdMapDenied)
        );

        let reason = SealedBlocker::IdMapDenied.reason();
        assert!(
            reason.contains("uid_map"),
            "must name the step that failed: {reason}"
        );
        assert!(
            !reason.contains("CAP_SYS_ADMIN") && !reason.contains("--cap-add"),
            "must not send the operator after a capability that isn't the problem: {reason}",
        );

        // And the container case must keep its own, different advice.
        let denied = SealedProbe {
            userns_grant: UsernsGrant::ProfileConfining,
            namespace: NamespaceProbe::Denied,
        };
        assert_eq!(
            sealed_blocker(true, true, denied),
            Some(SealedBlocker::NamespaceCreationDenied)
        );
        assert_ne!(
            SealedBlocker::IdMapDenied.reason(),
            SealedBlocker::NamespaceCreationDenied.reason(),
        );
    }

    /// `SealedBlocker::ALL` is what `murmur-cli`'s containment test matches a refusal against, so a
    /// variant missing from it makes that test assert something false about the *host*. Adding a
    /// variant must break this test — loudly, here — rather than surface three crates away.
    #[test]
    fn every_blocker_is_listed_in_all_with_its_own_actionable_reason() {
        // The exhaustive match is the mechanism: a new variant fails to compile until it is added
        // here, and the `contains` below then forces it into `ALL` too.
        for blocker in SealedBlocker::ALL {
            let named = match blocker {
                SealedBlocker::NotLinux
                | SealedBlocker::AppArmorProfileMissing
                | SealedBlocker::NamespaceCreationDenied
                | SealedBlocker::IdMapDenied
                | SealedBlocker::MountDenied
                | SealedBlocker::PivotRootDenied
                | SealedBlocker::KernelUnsupported
                | SealedBlocker::LandlockUnavailable => *blocker,
            };
            assert!(
                SealedBlocker::ALL.contains(&named),
                "{named:?} is missing from SealedBlocker::ALL",
            );
        }

        let reasons: Vec<String> = SealedBlocker::ALL
            .iter()
            .map(|blocker| blocker.reason())
            .collect();
        for reason in &reasons {
            assert!(reason.starts_with("sealed "), "got: {reason}");
            assert!(!reason.contains('\n'), "got: {reason}");
            assert!(
                reason.len() > 80,
                "a blocker reason must name the mechanism and its remediation, not just fail: \
                 {reason}",
            );
        }
        let mut unique = reasons.clone();
        unique.sort();
        unique.dedup();
        assert_eq!(
            unique.len(),
            reasons.len(),
            "two blockers share a reason, so the refusal cannot say which one applies",
        );
    }

    #[test]
    fn blocker_is_none_only_when_every_precondition_holds() {
        let ok = SealedProbe {
            userns_grant: UsernsGrant::ProfileConfining,
            namespace: NamespaceProbe::Ok,
        };
        assert_eq!(sealed_blocker(true, true, ok), None);
        assert_eq!(
            sealed_blocker(false, true, ok),
            Some(SealedBlocker::NotLinux)
        );
        assert_eq!(
            sealed_blocker(true, false, ok),
            Some(SealedBlocker::LandlockUnavailable)
        );
        assert_eq!(
            sealed_blocker(
                true,
                true,
                SealedProbe {
                    userns_grant: UsernsGrant::ProfileConfining,
                    namespace: NamespaceProbe::MountDenied
                }
            ),
            Some(SealedBlocker::MountDenied)
        );
        assert_eq!(
            sealed_blocker(
                true,
                true,
                SealedProbe {
                    userns_grant: UsernsGrant::ProfileConfining,
                    namespace: NamespaceProbe::Unsupported
                }
            ),
            Some(SealedBlocker::KernelUnsupported)
        );
    }

    #[test]
    fn the_device_set_is_exactly_the_oci_default_and_excludes_shm() {
        let names: Vec<&str> = SEALED_DEVICE_NODES.iter().map(|d| d.name).collect();
        assert_eq!(names, ["null", "zero", "full", "random", "urandom", "tty"]);
        assert!(!names.contains(&"shm"));
        assert!(!names.contains(&"console"));
        // Every entry records the canonical major/minor the OCI spec names.
        assert_eq!(
            SEALED_DEVICE_NODES
                .iter()
                .map(|d| (d.path, d.major, d.minor, d.mode, d.writable))
                .collect::<Vec<_>>(),
            [
                ("/dev/null", 1, 3, 0o666, true),
                ("/dev/zero", 1, 5, 0o666, true),
                ("/dev/full", 1, 7, 0o666, true),
                ("/dev/random", 1, 8, 0o666, false),
                ("/dev/urandom", 1, 9, 0o666, false),
                ("/dev/tty", 5, 0, 0o666, true),
            ]
        );
    }
}