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
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
// generated by hxc 1.0.0-acgt-compiler from tests/check_observation.hlx -- do not edit by hand
#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
if !ok {
eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
}
ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
std::process::exit(13);
}
c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
use std::os::windows::process::CommandExt;
c.creation_flags(0x08000000);
c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
std::process::exit(13);
}
c
}
// hlx:3
#[cfg(unix)]
// hlx:4
mod obs {
// hlx:5
use std::io::Write;
// hlx:6
use std::path::{Path, PathBuf};
// hlx:7
use std::process::{Command, Stdio};
// hlx:8
use std::sync::atomic::{AtomicUsize, Ordering};
// hlx:9
use std::time::Duration;
// hlx:10
fn bin() -> &'static str {
// hlx:11
env!("CARGO_BIN_EXE_instinct")
// hlx:12
}
// hlx:13
// ---------------------------------------------------------------- minimal JSON reader for the outputs
// hlx:14
#[derive(Debug, Clone, PartialEq)]
// hlx:15
enum J {
// hlx:16
Null,
// hlx:17
Bool(bool),
// hlx:18
Num(String),
// hlx:19
Str(String),
// hlx:20
Arr(Vec<J>),
// hlx:21
Obj(Vec<(String, J)>),
// hlx:22
}
// hlx:23
impl J {
// hlx:24
fn get(&self, k: &str) -> Option<&J> {
// hlx:25
match self {
// hlx:26
J::Obj(v) => v.iter().find(|(a, _)| a == k).map(|(_, b)| b),
// hlx:27
_ => None,
// hlx:28
}
// hlx:29
}
// hlx:30
fn as_str(&self) -> Option<&str> {
// hlx:31
match self {
// hlx:32
J::Str(s) => Some(s),
// hlx:33
_ => None,
// hlx:34
}
// hlx:35
}
// hlx:36
}
// hlx:37
struct P<'a> {
// hlx:38
b: &'a [u8],
// hlx:39
i: usize,
// hlx:40
}
// hlx:41
impl<'a> P<'a> {
// hlx:42
fn ws(&mut self) {
// hlx:43
while self.i < self.b.len() && matches!(self.b[self.i], b' ' | b'\n' | b'\t' | b'\r') {
// hlx:44
self.i += 1;
// hlx:45
}
// hlx:46
}
// hlx:47
fn lit(&mut self, w: &str, v: J) -> Result<J, String> {
// hlx:48
if self.b[self.i..].starts_with(w.as_bytes()) {
// hlx:49
self.i += w.len();
// hlx:50
Ok(v)
// hlx:51
} else {
// hlx:52
Err(format!("bad literal at {}", self.i))
// hlx:53
}
// hlx:54
}
// hlx:55
fn hex4(&mut self) -> Result<u32, String> {
// hlx:56
let h = self.b.get(self.i..self.i + 4).ok_or("short \\u")?;
// hlx:57
let h = std::str::from_utf8(h).map_err(|e| e.to_string())?;
// hlx:58
self.i += 4;
// hlx:59
u32::from_str_radix(h, 16).map_err(|e| e.to_string())
// hlx:60
}
// hlx:61
fn string(&mut self) -> Result<String, String> {
// hlx:62
if self.b.get(self.i) != Some(&b'"') {
// hlx:63
return Err(format!("expected string at {}", self.i));
// hlx:64
}
// hlx:65
self.i += 1;
// hlx:66
let mut out: Vec<u8> = Vec::new();
// hlx:67
loop {
// hlx:68
let c = *self.b.get(self.i).ok_or("unterminated string")?;
// hlx:69
self.i += 1;
// hlx:70
match c {
// hlx:71
b'"' => return String::from_utf8(out).map_err(|e| e.to_string()),
// hlx:72
b'\\' => {
// hlx:73
let e = *self.b.get(self.i).ok_or("bad escape")?;
// hlx:74
self.i += 1;
// hlx:75
let ch = match e {
// hlx:76
b'"' => '"',
// hlx:77
b'\\' => '\\',
// hlx:78
b'/' => '/',
// hlx:79
b'b' => '\u{8}',
// hlx:80
b'f' => '\u{c}',
// hlx:81
b'n' => '\n',
// hlx:82
b'r' => '\r',
// hlx:83
b't' => '\t',
// hlx:84
b'u' => {
// hlx:85
let hi = self.hex4()?;
// hlx:86
if (0xD800..0xDC00).contains(&hi) {
// hlx:87
if self.b.get(self.i) != Some(&b'\\')
|| self.b.get(self.i + 1) != Some(&b'u')
{
// hlx:88
return Err("lone surrogate".into());
// hlx:89
}
// hlx:90
self.i += 2;
// hlx:91
let lo = self.hex4()?;
// hlx:92
char::from_u32(
0x10000 + ((hi - 0xD800) << 10) + (lo.wrapping_sub(0xDC00)),
)
// hlx:93
.ok_or("bad pair")?
// hlx:94
} else {
// hlx:95
char::from_u32(hi).ok_or("lone surrogate")?
// hlx:96
}
// hlx:97
}
// hlx:98
_ => return Err("bad escape".into()),
// hlx:99
};
// hlx:100
let mut buf = [0u8; 4];
// hlx:101
out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
// hlx:102
}
// hlx:103
_ => out.push(c),
// hlx:104
}
// hlx:105
}
// hlx:106
}
// hlx:107
fn val(&mut self) -> Result<J, String> {
// hlx:108
self.ws();
// hlx:109
match self.b.get(self.i).copied() {
// hlx:110
None => Err("eof".into()),
// hlx:111
Some(b'{') => {
// hlx:112
self.i += 1;
// hlx:113
let mut v = Vec::new();
// hlx:114
self.ws();
// hlx:115
if self.b.get(self.i) == Some(&b'}') {
// hlx:116
self.i += 1;
// hlx:117
return Ok(J::Obj(v));
// hlx:118
}
// hlx:119
loop {
// hlx:120
self.ws();
// hlx:121
let k = self.string()?;
// hlx:122
self.ws();
// hlx:123
if self.b.get(self.i) != Some(&b':') {
// hlx:124
return Err("expected colon".into());
// hlx:125
}
// hlx:126
self.i += 1;
// hlx:127
let x = self.val()?;
// hlx:128
v.push((k, x));
// hlx:129
self.ws();
// hlx:130
match self.b.get(self.i) {
// hlx:131
Some(b',') => self.i += 1,
// hlx:132
Some(b'}') => {
// hlx:133
self.i += 1;
// hlx:134
return Ok(J::Obj(v));
// hlx:135
}
// hlx:136
_ => return Err("bad object".into()),
// hlx:137
}
// hlx:138
}
// hlx:139
}
// hlx:140
Some(b'[') => {
// hlx:141
self.i += 1;
// hlx:142
let mut v = Vec::new();
// hlx:143
self.ws();
// hlx:144
if self.b.get(self.i) == Some(&b']') {
// hlx:145
self.i += 1;
// hlx:146
return Ok(J::Arr(v));
// hlx:147
}
// hlx:148
loop {
// hlx:149
v.push(self.val()?);
// hlx:150
self.ws();
// hlx:151
match self.b.get(self.i) {
// hlx:152
Some(b',') => self.i += 1,
// hlx:153
Some(b']') => {
// hlx:154
self.i += 1;
// hlx:155
return Ok(J::Arr(v));
// hlx:156
}
// hlx:157
_ => return Err("bad array".into()),
// hlx:158
}
// hlx:159
}
// hlx:160
}
// hlx:161
Some(b'"') => Ok(J::Str(self.string()?)),
// hlx:162
Some(b't') => self.lit("true", J::Bool(true)),
// hlx:163
Some(b'f') => self.lit("false", J::Bool(false)),
// hlx:164
Some(b'n') => self.lit("null", J::Null),
// hlx:165
Some(_) => {
// hlx:166
let st = self.i;
// hlx:167
while self.i < self.b.len()
&& matches!(
self.b[self.i],
b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9'
)
{
// hlx:168
self.i += 1;
// hlx:169
}
// hlx:170
if st == self.i {
// hlx:171
return Err(format!("unexpected byte at {st}"));
// hlx:172
}
// hlx:173
Ok(J::Num(
String::from_utf8_lossy(&self.b[st..self.i]).into_owned(),
))
// hlx:174
} // hlx:175
}
// hlx:176
}
// hlx:177
}
// hlx:178
fn parse_json(s: &str) -> Result<J, String> {
// hlx:179
let mut p = P {
b: s.as_bytes(),
i: 0,
};
// hlx:180
let v = p.val()?;
// hlx:181
p.ws();
// hlx:182
if p.i != p.b.len() {
// hlx:183
return Err("trailing data".into());
// hlx:184
}
// hlx:185
Ok(v)
// hlx:186
}
// hlx:187
fn to_s(j: &J) -> String {
// hlx:188
match j {
// hlx:189
J::Null => "null".into(),
// hlx:190
J::Bool(b) => b.to_string(),
// hlx:191
J::Num(n) => n.clone(),
// hlx:192
J::Str(s) => format!("{s:?}"),
// hlx:193
J::Arr(v) => format!("[{}]", v.iter().map(to_s).collect::<Vec<_>>().join(",")),
// hlx:194
J::Obj(v) => format!(
"{{{}}}",
v.iter()
.map(|(k, x)| format!("{k:?}:{}", to_s(x)))
.collect::<Vec<_>>()
.join(",")
),
// hlx:195
}
// hlx:196
}
// hlx:197
use std::ffi::OsStr;
// hlx:198
use std::os::unix::ffi::OsStrExt;
// hlx:199
use std::os::unix::fs::PermissionsExt;
// hlx:200
// ---------------------------------------------------------------- isolated environment with a staging area
// hlx:201
struct Out {
// hlx:202
code: Option<i32>,
// hlx:203
out: Vec<u8>,
// hlx:204
err: Vec<u8>,
// hlx:205
}
// hlx:206
impl Out {
// hlx:207
fn text(&self) -> String {
// hlx:208
String::from_utf8_lossy(&self.out).into_owned()
// hlx:209
}
// hlx:210
}
// hlx:211
fn fnv(b: &[u8]) -> u64 {
// hlx:212
let mut h = 0xcbf29ce484222325u64;
// hlx:213
for x in b {
// hlx:214
h ^= *x as u64;
// hlx:215
h = h.wrapping_mul(0x100000001b3);
// hlx:216
}
// hlx:217
h
// hlx:218
}
// hlx:219
// never follows a symlink: links are recorded by their own target text, directories and files with their mode bits
// hlx:220
fn walk(base: &Path, dir: &Path, acc: &mut Vec<String>) {
// hlx:221
let mut ents: Vec<_> = match std::fs::read_dir(dir) {
// hlx:222
Ok(r) => r.filter_map(|e| e.ok()).collect(),
// hlx:223
Err(_) => return,
// hlx:224
};
// hlx:225
ents.sort_by_key(|e| e.file_name());
// hlx:226
for e in ents {
// hlx:227
let p = e.path();
// hlx:228
let rel = p.strip_prefix(base).unwrap().to_string_lossy().into_owned();
// hlx:229
let md = match std::fs::symlink_metadata(&p) {
// hlx:230
Ok(m) => m,
// hlx:231
Err(_) => continue,
// hlx:232
};
// hlx:233
let mode = md.permissions().mode();
// hlx:234
let ft = md.file_type();
// hlx:235
if ft.is_symlink() {
// hlx:236
acc.push(format!("l {rel} {:?}", std::fs::read_link(&p).ok()));
// hlx:237
} else if ft.is_dir() {
// hlx:238
acc.push(format!("d {rel} {mode:o}"));
// hlx:239
walk(base, &p, acc);
// hlx:240
} else if ft.is_file() {
// hlx:241
let b = std::fs::read(&p).unwrap_or_default();
// hlx:242
acc.push(format!("f {rel} {mode:o} {} {:x}", b.len(), fnv(&b)));
// hlx:243
} else {
// hlx:244
acc.push(format!("o {rel} {mode:o}"));
// hlx:245
}
// hlx:246
}
// hlx:247
}
// hlx:248
fn unlock(dir: &Path) {
// hlx:249
if let Ok(md) = std::fs::symlink_metadata(dir) {
// hlx:250
if md.file_type().is_dir() {
// hlx:251
let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755));
// hlx:252
if let Ok(r) = std::fs::read_dir(dir) {
// hlx:253
for e in r.filter_map(|e| e.ok()) {
// hlx:254
unlock(&e.path());
// hlx:255
}
// hlx:256
}
// hlx:257
}
// hlx:258
}
// hlx:259
}
// hlx:260
struct Env {
// hlx:261
root: PathBuf,
// hlx:262
}
// hlx:263
impl Env {
// hlx:264
fn new(name: &str) -> Env {
// hlx:265
static N: AtomicUsize = AtomicUsize::new(0);
// hlx:266
#[cfg(target_os = "macos")]
// hlx:267
let base = PathBuf::from("/tmp"); // short Unix socket path; also exercises the system alias
// hlx:268
#[cfg(not(target_os = "macos"))]
// hlx:269
let base = std::env::temp_dir();
// hlx:270
let root = base.join(format!(
// hlx:271
"icobs-{}-{}-{name}",
// hlx:272
std::process::id(),
// hlx:273
N.fetch_add(1, Ordering::Relaxed) // hlx:274
));
// hlx:275
let _ = std::fs::remove_dir_all(&root);
// hlx:276
for d in [
"home", "data", "local", "cfg", "state", "cache", "cwd", "in", "stage", "outside",
] {
// hlx:277
std::fs::create_dir_all(root.join(d)).unwrap();
// hlx:278
}
// hlx:279
std::fs::write(
root.join("outside").join("OUTSIDE_TARGET_SECRET_731"),
b"top secret",
)
.unwrap();
// hlx:280
std::fs::create_dir_all(root.join("outside").join("OUTSIDE_DIR_SECRET_731")).unwrap();
// hlx:281
std::fs::write(
root.join("outside")
.join("OUTSIDE_DIR_SECRET_731")
.join("inner_731"),
b"x",
)
.unwrap();
// hlx:282
std::fs::write(root.join("home").join("sentinel"), b"home sentinel").unwrap();
// hlx:283
Env { root }
// hlx:284
}
// hlx:285
// an empty observation root inside the staging area
// hlx:286
fn dir(&self, name: &str) -> PathBuf {
// hlx:287
let p = self.root.join("stage").join(name);
// hlx:288
std::fs::create_dir_all(&p).unwrap();
// hlx:289
p
// hlx:290
}
// hlx:291
fn outside(&self) -> PathBuf {
// hlx:292
self.root.join("outside")
// hlx:293
}
// hlx:294
fn put(&self, name: &str, bytes: &[u8]) -> PathBuf {
// hlx:295
let p = self.root.join("in").join(name);
// hlx:296
std::fs::write(&p, bytes).unwrap();
// hlx:297
p
// hlx:298
}
// hlx:299
fn snapshot(&self) -> Vec<String> {
// hlx:300
let mut acc = Vec::new();
// hlx:301
walk(&self.root, &self.root, &mut acc);
// hlx:302
acc
// hlx:303
}
// hlx:304
fn exec_raw(&self, args: &[&str], stdin: &[u8], envs: &[(&str, &str)], snap: bool) -> Out {
// hlx:305
let before = if snap { self.snapshot() } else { Vec::new() };
// hlx:306
let mut c = Command::new(bin());
// hlx:307
c.args(args)
// hlx:308
.current_dir(self.root.join("cwd"))
// hlx:309
.env("HOME", self.root.join("home"))
// hlx:310
.env("XDG_DATA_HOME", self.root.join("data"))
// hlx:311
.env("XDG_CONFIG_HOME", self.root.join("cfg"))
// hlx:312
.env("XDG_STATE_HOME", self.root.join("state"))
// hlx:313
.env("XDG_CACHE_HOME", self.root.join("cache"))
// hlx:314
.env("LOCALAPPDATA", self.root.join("local"))
// hlx:315
.env("APPDATA", self.root.join("local"));
// hlx:316
for (k, _) in std::env::vars() {
// hlx:317
if k.starts_with("INSTINCT_") {
// hlx:318
c.env_remove(k);
// hlx:319
}
// hlx:320
}
// hlx:321
for (k, v) in envs {
// hlx:322
c.env(k, v);
// hlx:323
}
// hlx:324
c.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// hlx:325
let mut child = c.spawn().unwrap();
// hlx:326
let mut si = child.stdin.take().unwrap();
// hlx:327
let data = stdin.to_vec();
// hlx:328
let w = std::thread::spawn(move || {
// hlx:329
let _ = si.write_all(&data);
// hlx:330
});
// hlx:331
let (tx, rx) = std::sync::mpsc::channel();
// hlx:332
std::thread::spawn(move || {
// hlx:333
let _ = tx.send(child.wait_with_output());
// hlx:334
});
// hlx:335
let o = rx
.recv_timeout(Duration::from_secs(180))
.expect("instinct check observe hung")
.unwrap();
// hlx:336
let _ = w.join();
// hlx:337
if snap {
// hlx:338
let after = self.snapshot();
// hlx:339
assert_eq!(
before, after,
"observation changed the filesystem: {args:?}"
);
// hlx:340
}
// hlx:341
Out {
code: o.status.code(),
out: o.stdout,
err: o.stderr,
}
// hlx:342
}
// hlx:343
fn exec(&self, args: &[&str], stdin: &[u8]) -> Out {
// hlx:344
self.exec_raw(args, stdin, &[], true)
// hlx:345
}
// hlx:346
fn observe(&self, root: &Path, policy: &str) -> Out {
// hlx:347
self.exec(
&[
"check",
"observe",
"--root",
root.to_str().unwrap(),
"--input",
"-",
],
policy.as_bytes(),
)
// hlx:348
}
// hlx:349
}
// hlx:350
impl Drop for Env {
// hlx:351
fn drop(&mut self) {
// hlx:352
unlock(&self.root);
// hlx:353
let _ = std::fs::remove_dir_all(&self.root);
// hlx:354
}
// hlx:355
}
// hlx:356
// ---------------------------------------------------------------- fixtures built with std only
// hlx:357
fn put_file(root: &Path, rel: &str) {
// hlx:358
let p = root.join(rel);
// hlx:359
if let Some(parent) = p.parent() {
// hlx:360
std::fs::create_dir_all(parent).unwrap();
// hlx:361
}
// hlx:362
std::fs::write(p, b"contents").unwrap();
// hlx:363
}
// hlx:364
fn put_dir(root: &Path, rel: &str) {
// hlx:365
std::fs::create_dir_all(root.join(rel)).unwrap();
// hlx:366
}
// hlx:367
fn raw_fixture_created(result: std::io::Result<()>) -> bool {
// hlx:368
match result {
// hlx:369
Ok(()) => true,
// hlx:370
Err(e) if cfg!(target_os = "macos") && e.raw_os_error() == Some(92) => {
// hlx:371
eprintln!("SKIP non-UTF-8 fixture: this macOS filesystem rejects the name (EILSEQ); observation not exercised for this case");
// hlx:372
false
// hlx:373
}
// hlx:374
Err(e) => panic!("cannot create raw-name fixture: {e}"),
// hlx:375
}
// hlx:376
}
// hlx:377
fn put_raw_file(root: &Path, name: &[u8]) -> bool {
// hlx:378
raw_fixture_created(std::fs::write(root.join(OsStr::from_bytes(name)), b"raw"))
// hlx:379
}
// hlx:380
// ---------------------------------------------------------------- policy builder
// hlx:381
#[derive(Clone)]
// hlx:382
struct Pol {
// hlx:383
schema: String,
// hlx:384
assum: Option<String>,
// hlx:385
allowed: String,
// hlx:386
required: Option<String>,
// hlx:387
scope: Option<String>,
// hlx:388
limits: Option<String>,
// hlx:389
extra: String,
// hlx:390
}
// hlx:391
fn pol(allowed: &[&str]) -> Pol {
// hlx:392
Pol {
// hlx:393
schema: "\"instinct.artifact-policy/v1\"".into(),
// hlx:394
assum: Some("{\"trusted_quiescent_staging\":true}".into()),
// hlx:395
allowed: jl(allowed),
// hlx:396
required: None,
// hlx:397
scope: None,
// hlx:398
limits: None,
// hlx:399
extra: String::new(),
// hlx:400
}
// hlx:401
}
// hlx:402
// a JSON array of strings; items are already JSON-escaped text
// hlx:403
fn jl(items: &[&str]) -> String {
// hlx:404
format!(
"[{}]",
items
.iter()
.map(|s| format!("\"{s}\""))
.collect::<Vec<_>>()
.join(",")
)
// hlx:405
}
// hlx:406
impl Pol {
// hlx:407
fn raw_allowed(mut self, s: &str) -> Pol {
// hlx:408
self.allowed = s.into();
// hlx:409
self
// hlx:410
}
// hlx:411
fn required(mut self, items: &[&str]) -> Pol {
// hlx:412
self.required = Some(jl(items));
// hlx:413
self
// hlx:414
}
// hlx:415
fn raw_required(mut self, s: &str) -> Pol {
// hlx:416
self.required = Some(s.into());
// hlx:417
self
// hlx:418
}
// hlx:419
fn scope(mut self, s: &str) -> Pol {
// hlx:420
self.scope = Some(s.into());
// hlx:421
self
// hlx:422
}
// hlx:423
fn limits(mut self, s: &str) -> Pol {
// hlx:424
self.limits = Some(s.into());
// hlx:425
self
// hlx:426
}
// hlx:427
fn assum(mut self, s: Option<&str>) -> Pol {
// hlx:428
self.assum = s.map(|x| x.to_string());
// hlx:429
self
// hlx:430
}
// hlx:431
fn schema(mut self, s: &str) -> Pol {
// hlx:432
self.schema = s.into();
// hlx:433
self
// hlx:434
}
// hlx:435
fn extra(mut self, s: &str) -> Pol {
// hlx:436
self.extra.push_str(s);
// hlx:437
self
// hlx:438
}
// hlx:439
fn json(&self) -> String {
// hlx:440
let mut t = format!("{{\"schema\":{}", self.schema);
// hlx:441
if let Some(a) = &self.assum {
// hlx:442
t.push_str(&format!(",\"assumptions\":{a}"));
// hlx:443
}
// hlx:444
t.push_str(&format!(",\"allowed\":{}", self.allowed));
// hlx:445
if let Some(r) = &self.required {
// hlx:446
t.push_str(&format!(",\"required\":{r}"));
// hlx:447
}
// hlx:448
if let Some(s) = &self.scope {
// hlx:449
t.push_str(&format!(",\"scope\":{s}"));
// hlx:450
}
// hlx:451
if let Some(l) = &self.limits {
// hlx:452
t.push_str(&format!(",\"limits\":{l}"));
// hlx:453
}
// hlx:454
t.push_str(&self.extra);
// hlx:455
t.push('}');
// hlx:456
t
// hlx:457
}
// hlx:458
}
// hlx:459
// ---------------------------------------------------------------- output assertions
// hlx:460
fn trunc(s: &str) -> String {
// hlx:461
s.chars().take(500).collect()
// hlx:462
}
// hlx:463
fn obj(o: &Out) -> J {
// hlx:464
let t = o.text();
// hlx:465
let j = parse_json(t.trim())
.unwrap_or_else(|e| panic!("stdout is not one JSON value ({e}): {}", trunc(&t)));
// hlx:466
assert!(
matches!(j, J::Obj(_)),
"stdout must be one JSON object: {}",
trunc(&t)
);
// hlx:467
j
// hlx:468
}
// hlx:469
fn sf<'a>(j: &'a J, k: &str) -> &'a str {
// hlx:470
j.get(k)
.and_then(J::as_str)
.unwrap_or_else(|| panic!("missing string field {k} in {}", trunc(&to_s(j))))
// hlx:471
}
// hlx:472
fn err(o: &Out, ctx: &str) {
// hlx:473
assert_eq!(
o.code,
Some(2),
"{ctx}: expected exit 2, stdout={}",
trunc(&o.text())
);
// hlx:474
let j = obj(o);
// hlx:475
assert_eq!(
sf(&j, "schema"),
"instinct.check-error/v1",
"{ctx}: {}",
trunc(&o.text())
);
// hlx:476
assert_eq!(sf(&j, "verdict"), "error", "{ctx}");
// hlx:477
assert!(!sf(&j, "reason").is_empty(), "{ctx}");
// hlx:478
assert_eq!(sf(&j, "authorization"), "not_evaluated", "{ctx}");
// hlx:479
assert!(
o.out.len() <= 65_537,
"{ctx}: error output must be bounded, got {} bytes",
o.out.len()
);
// hlx:480
}
// hlx:481
// an observation result of either validity
// hlx:482
fn observed(o: &Out) -> J {
// hlx:483
assert_eq!(
o.code,
Some(0),
"expected exit 0: {} {}",
trunc(&o.text()),
trunc(&String::from_utf8_lossy(&o.err))
);
// hlx:484
assert!(
o.out.len() <= 65_537 && o.text().trim_end().len() <= 65_536,
"output is {} bytes",
o.out.len()
);
// hlx:485
let j = obj(o);
// hlx:486
assert_eq!(
sf(&j, "schema"),
"instinct.artifact-observation/v1",
"{}",
trunc(&o.text())
);
// hlx:487
assert_eq!(sf(&j, "adapter"), "artifact-inventory/v1");
// hlx:488
assert!(
["observed_snapshot", "incomplete"].contains(&sf(&j, "validity")),
"{}",
trunc(&o.text())
);
// hlx:489
assert_eq!(sf(&j, "evidence_origin"), "adapter_observed");
// hlx:490
assert_eq!(sf(&j, "authorization"), "not_evaluated");
// hlx:491
assert!(!sf(&j, "reason").is_empty());
// hlx:492
assert!(
matches!(j.get("inventory"), Some(J::Arr(_))),
"inventory must be an array"
);
// hlx:493
assert!(
matches!(j.get("checks"), Some(J::Arr(_))),
"checks must be an array"
);
// hlx:494
assert!(
matches!(j.get("limits"), Some(J::Obj(_))),
"limits must be an object"
);
// hlx:495
assert!(
matches!(j.get("assumptions"), Some(J::Obj(_))),
"assumptions must be echoed: {}",
trunc(&o.text())
);
// hlx:496
match j.get("visited_entries") {
// hlx:497
Some(J::Num(n)) => assert!(n.parse::<u64>().is_ok(), "visited_entries: {n}"),
// hlx:498
other => panic!("visited_entries must be a number: {other:?}"),
// hlx:499
}
// hlx:500
let t = o.text();
// hlx:501
assert!(
!t.contains("safe_to_release"),
"a check result is never labeled safe_to_release"
);
// hlx:502
j
// hlx:503
}
// hlx:504
fn snapshot_ok(o: &Out) -> J {
// hlx:505
let j = observed(o);
// hlx:506
assert_eq!(
sf(&j, "validity"),
"observed_snapshot",
"{}",
trunc(&o.text())
);
// hlx:507
assert_eq!(
j.get("assumptions")
.unwrap()
.get("trusted_quiescent_staging"),
Some(&J::Bool(true)),
"the premise must be echoed"
);
// hlx:508
j
// hlx:509
}
// hlx:510
// incomplete: no inventory, no checks, no completeness claim
// hlx:511
fn incomplete(o: &Out) -> J {
// hlx:512
let j = observed(o);
// hlx:513
assert_eq!(
sf(&j, "validity"),
"incomplete",
"expected incomplete: {}",
trunc(&o.text())
);
// hlx:514
assert_eq!(
j.get("inventory"),
Some(&J::Arr(vec![])),
"incomplete must have an empty inventory: {}",
trunc(&o.text())
);
// hlx:515
assert_eq!(
j.get("checks"),
Some(&J::Arr(vec![])),
"incomplete must have no check results: {}",
trunc(&o.text())
);
// hlx:516
j
// hlx:517
}
// hlx:518
// never a snapshot: either a structured root/argument error or an incomplete observation
// hlx:519
fn not_snapshot(o: &Out, ctx: &str) {
// hlx:520
match o.code {
// hlx:521
Some(2) => err(o, ctx),
// hlx:522
Some(0) => {
// hlx:523
let j = obj(o);
// hlx:524
assert_eq!(
j.get("validity"),
Some(&J::Str("incomplete".into())),
"{ctx}: expected an error or an incomplete observation, got: {}",
trunc(&o.text())
);
// hlx:525
incomplete(o);
// hlx:526
}
// hlx:527
other => panic!("{ctx}: unexpected exit {other:?}: {}", trunc(&o.text())),
// hlx:528
}
// hlx:529
}
// hlx:530
fn inv(j: &J) -> Vec<(String, String)> {
// hlx:531
match j.get("inventory") {
// hlx:532
Some(J::Arr(v)) => v
// hlx:533
.iter()
// hlx:534
.map(|e| {
// hlx:535
match e {
// hlx:536
J::Obj(kv) => assert_eq!(
kv.len(),
2,
"inventory entries carry exactly path and kind: {}",
to_s(e)
),
// hlx:537
_ => panic!("inventory entry must be an object"),
// hlx:538
}
// hlx:539
(sf(e, "path").to_string(), sf(e, "kind").to_string())
// hlx:540
})
// hlx:541
.collect(),
// hlx:542
other => panic!("{other:?}"),
// hlx:543
}
// hlx:544
}
// hlx:545
fn paths(j: &J) -> Vec<String> {
// hlx:546
inv(j).into_iter().map(|(p, _)| p).collect()
// hlx:547
}
// hlx:548
fn is_file(k: &str) -> bool {
// hlx:549
k.to_lowercase().contains("file")
// hlx:550
}
// hlx:551
fn is_dir(k: &str) -> bool {
// hlx:552
k.to_lowercase().contains("dir")
// hlx:553
}
// hlx:554
fn checks(j: &J) -> Vec<J> {
// hlx:555
match j.get("checks") {
// hlx:556
Some(J::Arr(items)) => {
// hlx:557
// docs/check-observation-wire.md says `checks` are M1 results and also speaks of wrapper provenance:
// hlx:558
// accept a bare M1 result or a wrapper {name, provenance, result}. Provenance may attribute only the
// hlx:559
// observed inventory to the adapter, never the caller's allowed/required policy.
// hlx:560
let mut v: Vec<J> = Vec::new();
// hlx:561
for it in items {
// hlx:562
if let Some(inner) = it.get("result") {
// hlx:563
if let Some(J::Obj(prov)) = it.get("provenance") {
// hlx:564
for (k, val) in prov {
// hlx:565
let origin = val.as_str().unwrap_or("");
// hlx:566
if k == "actual" {
// hlx:567
assert_eq!(
origin,
"adapter_observed",
"actual comes from the adapter: {}",
to_s(it)
);
// hlx:568
} else {
// hlx:569
assert_ne!(
origin,
"adapter_observed",
"policy ({k}) must not be relabeled as observed: {}",
to_s(it)
);
// hlx:570
assert!(!origin.is_empty());
// hlx:571
}
// hlx:572
}
// hlx:573
}
// hlx:574
v.push(inner.clone());
// hlx:575
} else {
// hlx:576
v.push(it.clone());
// hlx:577
}
// hlx:578
}
// hlx:579
for c in &v {
// hlx:580
assert_eq!(
sf(c, "schema"),
"instinct.check-result/v1",
"{}",
trunc(&to_s(c))
);
// hlx:581
assert!(["pass", "fail", "abstain"].contains(&sf(c, "verdict")));
// hlx:582
assert_eq!(sf(c, "authorization"), "not_evaluated");
// hlx:583
assert!(!sf(c, "reason").is_empty());
// hlx:584
assert_eq!(
c.get("missing"),
Some(&J::Arr(vec![])),
"observed facts are all supplied: {}",
trunc(&to_s(c))
);
// hlx:585
assert!(matches!(c.get("steps"), Some(J::Num(_))));
// hlx:586
}
// hlx:587
v.clone()
// hlx:588
}
// hlx:589
other => panic!("{other:?}"),
// hlx:590
}
// hlx:591
}
// hlx:592
fn verdicts(j: &J) -> Vec<String> {
// hlx:593
checks(j)
.iter()
.map(|c| sf(c, "verdict").to_string())
.collect()
// hlx:594
}
// hlx:595
fn fails(j: &J) -> Vec<String> {
// hlx:596
let mut w: Vec<String> = checks(j)
// hlx:597
.iter()
// hlx:598
.filter(|c| sf(c, "verdict") == "fail")
// hlx:599
.map(|c| match c.get("witness") {
// hlx:600
Some(J::Str(s)) => s.clone(),
// hlx:601
other => panic!("a failed membership check needs a witness: {other:?}"),
// hlx:602
})
// hlx:603
.collect();
// hlx:604
w.sort();
// hlx:605
w
// hlx:606
}
// hlx:607
fn all_pass(j: &J) {
// hlx:608
let v = verdicts(j);
// hlx:609
assert!(!v.is_empty() && v.iter().all(|x| x == "pass"), "{v:?}");
// hlx:610
}
// hlx:611
fn no_leak(o: &Out, env: &Env) {
// hlx:612
let t = o.text();
// hlx:613
for marker in [
"OUTSIDE_TARGET_SECRET_731",
"OUTSIDE_DIR_SECRET_731",
"inner_731",
"TARGET_INSIDE_731",
] {
// hlx:614
assert!(
!t.contains(marker),
"output disclosed {marker}: {}",
trunc(&t)
);
// hlx:615
}
// hlx:616
assert!(
!t.contains(env.outside().to_str().unwrap()),
"output disclosed a path outside the root"
);
// hlx:617
if let Ok(j) = parse_json(t.trim()) {
// hlx:618
if let Some(J::Str(w)) = j.get("witness") {
// hlx:619
assert!(
!w.starts_with('/') && !w.contains(env.root.to_str().unwrap()),
"witness must be a sanitized relative path: {w}"
);
// hlx:620
}
// hlx:621
}
// hlx:622
}
// hlx:623
fn is_root() -> bool {
// hlx:624
// permission-based fixtures do not block the superuser
// hlx:625
let probe = std::env::temp_dir().join(format!("instinct-obs-probe-{}", std::process::id()));
// hlx:626
let _ = std::fs::remove_dir_all(&probe);
// hlx:627
std::fs::create_dir_all(&probe).unwrap();
// hlx:628
std::fs::set_permissions(&probe, std::fs::Permissions::from_mode(0o000)).unwrap();
// hlx:629
let readable = std::fs::read_dir(&probe).is_ok();
// hlx:630
let _ = std::fs::set_permissions(&probe, std::fs::Permissions::from_mode(0o755));
// hlx:631
let _ = std::fs::remove_dir_all(&probe);
// hlx:632
readable
// hlx:633
}
// hlx:634
// ---------------------------------------------------------------- the clean tree and the delegated checks
// hlx:635
#[test]
// hlx:636
fn clean_tree_is_observed_exactly_and_passes_membership() {
// hlx:637
let env = Env::new("clean");
// hlx:638
let r = env.dir("release");
// hlx:639
put_file(&r, "release.bin");
// hlx:640
put_file(&r, "docs/README");
// hlx:641
let o = env.observe(&r, &pol(&["docs", "docs/README", "release.bin"]).json());
// hlx:642
let j = snapshot_ok(&o);
// hlx:643
assert_eq!(
// hlx:644
inv(&j).iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>(),
// hlx:645
vec!["docs", "docs/README", "release.bin"] // hlx:646
);
// hlx:647
let kinds = inv(&j);
// hlx:648
assert!(
is_dir(&kinds[0].1)
&& is_file(&kinds[1].1)
&& is_file(&kinds[2].1)
&& kinds[0].1 != kinds[1].1,
"{kinds:?}"
);
// hlx:649
assert_eq!(j.get("visited_entries"), Some(&J::Num("3".into())));
// hlx:650
assert_eq!(
verdicts(&j),
vec!["pass"],
"no required list means one membership check"
);
// hlx:651
all_pass(&j);
// hlx:652
let limits = j.get("limits").unwrap();
// hlx:653
assert_eq!(limits.get("max_entries"), Some(&J::Num("10000".into())));
// hlx:654
assert_eq!(limits.get("max_depth"), Some(&J::Num("64".into())));
// hlx:655
assert_eq!(
limits.get("max_inventory_bytes"),
Some(&J::Num("1048576".into()))
);
// hlx:656
// the delegated check result carries the explicit (empty) policy scope
// hlx:657
for c in checks(&j) {
// hlx:658
assert_eq!(c.get("scope"), Some(&J::Obj(vec![])));
// hlx:659
assert_eq!(c.get("witness"), Some(&J::Null));
// hlx:660
}
// hlx:661
}
// hlx:662
#[test]
// hlx:663
fn delegated_results_carry_the_policy_scope_and_the_required_check_when_nonempty() {
// hlx:664
let env = Env::new("scope");
// hlx:665
let r = env.dir("release");
// hlx:666
put_file(&r, "release.bin");
// hlx:667
let p = pol(&["release.bin"])
.required(&["release.bin"])
.scope("{\"project\":\"release-lab\",\"machine\":\"m1\"}");
// hlx:668
let j = snapshot_ok(&env.observe(&r, &p.json()));
// hlx:669
let cs = checks(&j);
// hlx:670
assert_eq!(cs.len(), 2, "membership plus required-membership");
// hlx:671
all_pass(&j);
// hlx:672
for c in cs {
// hlx:673
let mut s: Vec<(String, String)> = match c.get("scope") {
// hlx:674
Some(J::Obj(kv)) => kv
.iter()
.map(|(k, v)| (k.clone(), v.as_str().unwrap().to_string()))
.collect(),
// hlx:675
other => panic!("{other:?}"),
// hlx:676
};
// hlx:677
s.sort();
// hlx:678
assert_eq!(
s,
vec![
("machine".to_string(), "m1".to_string()),
("project".to_string(), "release-lab".to_string())
]
);
// hlx:679
}
// hlx:680
}
// hlx:681
#[test]
// hlx:682
fn an_empty_root_is_a_complete_empty_inventory() {
// hlx:683
let env = Env::new("empty");
// hlx:684
let r = env.dir("release");
// hlx:685
let j = snapshot_ok(&env.observe(&r, &pol(&[]).json()));
// hlx:686
assert!(inv(&j).is_empty());
// hlx:687
assert_eq!(j.get("visited_entries"), Some(&J::Num("0".into())));
// hlx:688
all_pass(&j);
// hlx:689
let j = snapshot_ok(&env.observe(&r, &pol(&["x"]).json()));
// hlx:690
all_pass(&j);
// hlx:691
// required but absent: the separate required check fails with the missing name
// hlx:692
let j = snapshot_ok(&env.observe(&r, &pol(&["x"]).required(&["x"]).json()));
// hlx:693
assert_eq!(verdicts(&j).len(), 2);
// hlx:694
assert_eq!(fails(&j), vec!["x"]);
// hlx:695
}
// hlx:696
// ---------------------------------------------------------------- membership: hidden extras, dirs and exact names
// hlx:697
#[test]
// hlx:698
fn extra_entries_fail_membership_with_the_first_relative_witness() {
// hlx:699
let env = Env::new("extras");
// hlx:700
// (files, dirs, allowed, expected failing witness or None for pass)
// hlx:701
let rows: Vec<(Vec<&str>, Vec<&str>, Vec<&str>, Option<&str>)> = vec![
// hlx:702
(
vec!["release.bin", ".hidden", "docs/.env", "docs/README"],
vec!["scratch"],
vec!["docs", "docs/README", "release.bin"],
Some(".hidden"),
),
// hlx:703
(
vec!["release.bin", "docs/README", "docs/.secret"],
vec![],
vec!["docs", "docs/README", "release.bin"],
Some("docs/.secret"),
),
// hlx:704
(
vec!["release.bin", "docs/README"],
vec!["scratch"],
vec!["docs", "docs/README", "release.bin"],
Some("scratch"),
),
// hlx:705
(
vec!["release.bin", "docs/README"],
vec![],
vec!["docs", "release.bin"],
Some("docs/README"),
),
// hlx:706
(
vec!["release.bin", "docs/README"],
vec![],
vec!["docs/README", "release.bin"],
Some("docs"),
),
// hlx:707
(
vec!["release.bin", ".git/config"],
vec![],
vec!["release.bin"],
Some(".git"),
),
// hlx:708
(
vec!["release.bin", ".git/config"],
vec![],
vec!["release.bin", ".git/config"],
Some(".git"),
),
// hlx:709
(vec!["Readme"], vec![], vec!["README"], Some("Readme")),
// hlx:710
(vec!["README"], vec![], vec!["readme"], Some("README")),
// hlx:711
(
vec!["release.bin"],
vec![],
vec!["release.bin", "ghost", "docs/ghost"],
None,
),
// hlx:712
(vec!["a", "b", "c"], vec![], vec!["c", "b", "a"], None),
// hlx:713
(vec!["a", "b", "c"], vec![], vec!["a", "c"], Some("b")),
// hlx:714
(
vec!["x/y/z/deep.txt"],
vec![],
vec!["x", "x/y", "x/y/z"],
Some("x/y/z/deep.txt"),
),
// hlx:715
(
vec!["x/y/z/deep.txt"],
vec![],
vec!["x", "x/y", "x/y/z", "x/y/z/deep.txt"],
None,
),
// hlx:716
(vec![".a", ".b"], vec![".c"], vec![".a", ".b", ".c"], None),
// hlx:717
(vec!["zz", "aa", "Mm"], vec![], vec![], Some("Mm")),
// hlx:718
];
// hlx:719
for (i, (files, dirs, allowed, want)) in rows.iter().enumerate() {
// hlx:720
let r = env.dir(&format!("t{i}"));
// hlx:721
for f in files {
// hlx:722
put_file(&r, f);
// hlx:723
}
// hlx:724
for d in dirs {
// hlx:725
put_dir(&r, d);
// hlx:726
}
// hlx:727
let j = snapshot_ok(&env.observe(&r, &pol(allowed).json()));
// hlx:728
match want {
// hlx:729
Some(w) => {
// hlx:730
assert_eq!(verdicts(&j), vec!["fail"], "row {i}");
// hlx:731
assert_eq!(fails(&j), vec![w.to_string()], "row {i}");
// hlx:732
}
// hlx:733
None => {
// hlx:734
assert_eq!(verdicts(&j), vec!["pass"], "row {i}");
// hlx:735
} // hlx:736
}
// hlx:737
}
// hlx:738
}
// hlx:739
#[test]
// hlx:740
fn required_membership_is_a_separate_check_from_allowed_membership() {
// hlx:741
let env = Env::new("required");
// hlx:742
let r = env.dir("release");
// hlx:743
put_file(&r, "present");
// hlx:744
put_file(&r, "extra");
// hlx:745
// nothing extra, one required file missing: membership passes, required fails
// hlx:746
let j = snapshot_ok(
&env.observe(
&r,
&pol(&["present", "extra", "need"])
.required(&["need"])
.json(),
),
);
// hlx:747
let v = verdicts(&j);
// hlx:748
assert_eq!(v.len(), 2);
// hlx:749
assert_eq!(v.iter().filter(|x| *x == "pass").count(), 1, "{v:?}");
// hlx:750
assert_eq!(fails(&j), vec!["need"]);
// hlx:751
// extra file and missing required: both fail with their own witnesses
// hlx:752
let j =
snapshot_ok(&env.observe(&r, &pol(&["present", "need"]).required(&["need"]).json()));
// hlx:753
assert_eq!(
verdicts(&j),
vec!["fail", "fail"]
.iter()
.map(|s| s.to_string())
.collect::<Vec<_>>()
.as_slice()
.to_vec()
);
// hlx:754
assert_eq!(fails(&j), vec!["extra", "need"]);
// hlx:755
// required present and nothing extra
// hlx:756
let j = snapshot_ok(&env.observe(
&r,
&pol(&["present", "extra"]).required(&["present"]).json(),
));
// hlx:757
assert_eq!(verdicts(&j).len(), 2);
// hlx:758
all_pass(&j);
// hlx:759
// the first (code-point order) missing required name is the witness
// hlx:760
let j = snapshot_ok(
&env.observe(
&r,
&pol(&["b", "a", "present", "extra", "z"])
.required(&["z", "b", "a", "present"])
.json(),
),
);
// hlx:761
assert_eq!(fails(&j), vec!["a"]);
// hlx:762
// a required directory name
// hlx:763
put_dir(&r, "docs");
// hlx:764
let j = snapshot_ok(
&env.observe(
&r,
&pol(&["present", "extra", "docs"])
.required(&["docs"])
.json(),
),
);
// hlx:765
all_pass(&j);
// hlx:766
// an empty required list is the same as no required list: one check
// hlx:767
let j =
snapshot_ok(&env.observe(&r, &pol(&["present", "extra", "docs"]).required(&[]).json()));
// hlx:768
assert_eq!(verdicts(&j).len(), 1);
// hlx:769
}
// hlx:770
#[test]
// hlx:771
#[cfg_attr(
target_os = "macos",
ignore = "Requires case-sensitive, normalization-distinct filesystem; stock APFS may collapse fixture names. Pure string tests cover Unicode semantics."
)]
// hlx:772
fn names_are_exact_unicode_and_never_normalized_or_case_folded() {
// hlx:773
let env = Env::new("unicode");
// hlx:774
let r = env.dir("release");
// hlx:775
let names = [
// hlx:776
"r\u{e9}sum\u{e9}.txt",
// hlx:777
"e\u{301}.txt",
// hlx:778
"\u{e9}.txt",
// hlx:779
"with space",
// hlx:780
" leading",
// hlx:781
"trailing ",
// hlx:782
"emoji-\u{1F600}",
// hlx:783
"tab\tname",
// hlx:784
"new\nline",
// hlx:785
"back\\slash",
// hlx:786
"quote\"name",
// hlx:787
"star*?[x]",
// hlx:788
"-dash",
// hlx:789
"\u{4e2d}\u{6587}/\u{6587}\u{4ef6}",
// hlx:790
"a\u{200b}b",
// hlx:791
"UPPER",
// hlx:792
"upper",
// hlx:793
];
// hlx:794
for n in names {
// hlx:795
put_file(&r, n);
// hlx:796
}
// hlx:797
let esc = |s: &str| {
// hlx:798
s.chars()
// hlx:799
.map(|c| match c {
// hlx:800
'"' => "\\\"".to_string(),
// hlx:801
'\\' => "\\\\".to_string(),
// hlx:802
'\n' => "\\n".to_string(),
// hlx:803
'\t' => "\\t".to_string(),
// hlx:804
c if (c as u32) < 0x20 => format!("\\u{:04x}", c as u32),
// hlx:805
c => c.to_string(),
// hlx:806
})
// hlx:807
.collect::<String>()
// hlx:808
};
// hlx:809
let mut allowed: Vec<String> = names.iter().map(|n| esc(n)).collect();
// hlx:810
allowed.push("\u{4e2d}\u{6587}".into());
// hlx:811
let refs: Vec<&str> = allowed.iter().map(|s| s.as_str()).collect();
// hlx:812
let j = snapshot_ok(&env.observe(&r, &pol(&refs).json()));
// hlx:813
all_pass(&j);
// hlx:814
let mut got = paths(&j);
// hlx:815
got.sort();
// hlx:816
let mut want: Vec<String> = names.iter().map(|s| s.to_string()).collect();
// hlx:817
want.push("\u{4e2d}\u{6587}".into());
// hlx:818
want.sort();
// hlx:819
assert_eq!(got, want, "exact names retained");
// hlx:820
// dropping one name from the policy names exactly that one
// hlx:821
for (i, n) in names.iter().enumerate() {
// hlx:822
if n.contains('/') {
// hlx:823
continue;
// hlx:824
}
// hlx:825
let rest: Vec<&str> = allowed
.iter()
.enumerate()
.filter(|(k, _)| *k != i)
.map(|(_, s)| s.as_str())
.collect();
// hlx:826
let j = snapshot_ok(&env.observe(&r, &pol(&rest).json()));
// hlx:827
assert_eq!(fails(&j), vec![n.to_string()], "dropping {n:?}");
// hlx:828
}
// hlx:829
// composed vs decomposed are different names
// hlx:830
let j = snapshot_ok(
&env.observe(
&r,
&pol(&refs
.iter()
.copied()
.filter(|s| *s != "\u{e9}.txt")
.collect::<Vec<_>>())
.json(),
),
);
// hlx:831
assert_eq!(fails(&j), vec!["\u{e9}.txt".to_string()]);
// hlx:832
}
// hlx:833
#[test]
// hlx:834
fn inventory_is_sorted_by_code_point_order_of_the_full_relative_path() {
// hlx:835
// docs/checks.md: set ordering is Unicode code-point (UTF-8 byte) lexicographic order. '-' (0x2d) sorts before '/' (0x2f).
// hlx:836
let env = Env::new("sorted");
// hlx:837
let r = env.dir("release");
// hlx:838
for f in [
"docs/README",
"docs-x",
"docs.y",
"Zed",
"alpha",
"\u{e9}",
"\u{1F600}",
"b/c/d",
"b0",
] {
// hlx:839
put_file(&r, f);
// hlx:840
}
// hlx:841
let j = snapshot_ok(&env.observe(&r, &pol(&[]).json()));
// hlx:842
let got = paths(&j);
// hlx:843
let mut want = got.clone();
// hlx:844
want.sort();
// hlx:845
assert_eq!(got, want, "inventory must be sorted by path: {got:?}");
// hlx:846
assert!(got.contains(&"docs".to_string()) && got.contains(&"b/c".to_string()));
// hlx:847
let ix = |p: &str| got.iter().position(|x| x == p).unwrap();
// hlx:848
assert!(
ix("docs") < ix("docs-x")
&& ix("docs-x") < ix("docs.y")
&& ix("docs.y") < ix("docs/README"),
"{got:?}"
);
// hlx:849
}
// hlx:850
// ---------------------------------------------------------------- policy validation happens before any traversal
// hlx:851
fn hostile_tree(env: &Env, name: &str) -> PathBuf {
// hlx:852
// a tree that would make a real traversal incomplete: reaching exit 0 means the policy was not rejected first
// hlx:853
let r = env.dir(name);
// hlx:854
put_file(&r, "ok.txt");
// hlx:855
std::os::unix::fs::symlink(
env.outside().join("OUTSIDE_TARGET_SECRET_731"),
r.join("link"),
)
.unwrap();
// hlx:856
// If APFS cannot create the raw name, the symlink above still makes this tree hostile.
// hlx:857
let _ = put_raw_file(&r, b"bad\xff");
// hlx:858
r
// hlx:859
}
// hlx:860
#[test]
// hlx:861
fn invalid_policy_paths_are_rejected_before_the_tree_is_touched() {
// hlx:862
let env = Env::new("badpaths");
// hlx:863
let r = hostile_tree(&env, "hostile");
// hlx:864
let bad = [
// hlx:865
"",
".",
"..",
"a/..",
"../a",
"a/../b",
"/abs",
"/a",
"a/",
"a//b",
"//a",
"a/./b",
"./a",
"a/.",
"a/b/",
"..//a",
// hlx:866
"a\\u0000b",
"\\u0000",
"C:\\\\Windows",
"C:/Windows",
"c:\\\\x",
"Z:\\\\",
"\\\\\\\\server\\\\share\\\\x",
"\\\\\\\\?\\\\C:\\\\x",
// hlx:867
"//server/share/x",
"/etc/passwd",
"/tmp",
// hlx:868
];
// hlx:869
for b in bad {
// hlx:870
for (field, doc) in [
// hlx:871
("allowed", pol(&[b]).json()),
// hlx:872
("allowed second", pol(&["fine", b]).json()),
// hlx:873
("required", pol(&["fine"]).required(&[b]).json()),
// hlx:874
("both", pol(&[b]).required(&[b]).json()),
// hlx:875
] {
// hlx:876
let o = env.observe(&r, &doc);
// hlx:877
err(&o, &format!("{field} {b:?}"));
// hlx:878
}
// hlx:879
}
// hlx:880
// an absolute policy string naming the root itself is still not a relative path
// hlx:881
let abs = format!("{}/ok.txt", r.display());
// hlx:882
err(
&env.observe(&r, &pol(&[&abs]).json()),
"absolute policy path",
);
// hlx:883
}
// hlx:884
#[test]
// hlx:885
fn ordinary_policy_names_are_accepted_and_backslash_is_a_plain_filename_character() {
// hlx:886
let env = Env::new("goodpaths");
// hlx:887
let r = env.dir("release");
// hlx:888
put_file(&r, "a\\b");
// hlx:889
put_file(&r, "..a");
// hlx:890
put_file(&r, "a..");
// hlx:891
put_file(&r, "...");
// hlx:892
put_file(&r, "ab:c");
// hlx:893
put_file(&r, "x/\u{e9}");
// hlx:894
let j = snapshot_ok(
&env.observe(
&r,
&pol(&[
"a\\\\b", "..a", "a..", "...", "ab:c", "x", "x/\u{e9}", "extra/ok", ".a", "a b",
])
.json(),
),
);
// hlx:895
all_pass(&j);
// hlx:896
assert!(
paths(&j).contains(&"a\\b".to_string()),
"a backslash is part of the name: {:?}",
paths(&j)
);
// hlx:897
// a backslash policy entry matches only the file named with a backslash, not a nested path
// hlx:898
let j = snapshot_ok(&env.observe(
&r,
&pol(&["a/b", "..a", "a..", "...", "ab:c", "x", "x/\u{e9}"]).json(),
));
// hlx:899
assert_eq!(fails(&j), vec!["a\\b".to_string()]);
// hlx:900
}
// hlx:901
#[test]
// hlx:902
fn policy_shape_errors_are_rejected_before_the_tree_is_touched() {
// hlx:903
let env = Env::new("policyshape");
// hlx:904
let r = hostile_tree(&env, "hostile");
// hlx:905
let ok = "\"schema\":\"instinct.artifact-policy/v1\",\"assumptions\":{\"trusted_quiescent_staging\":true},\"allowed\":[]";
// hlx:906
let docs: Vec<String> = vec![
// hlx:907
"".into(),
// hlx:908
"{".into(),
// hlx:909
"[]".into(),
// hlx:910
"null".into(),
// hlx:911
"{}".into(),
// hlx:912
"\"policy\"".into(),
// hlx:913
"{\"allowed\":[]}".into(),
// hlx:914
"{\"schema\":\"instinct.artifact-policy/v1\"}".into(),
// hlx:915
"{\"schema\":\"instinct.artifact-policy/v1\",\"assumptions\":{\"trusted_quiescent_staging\":true}}".into(),
// hlx:916
pol(&[]).schema("\"instinct.artifact-policy/v2\"").json(),
// hlx:917
pol(&[]).schema("\"instinct.check/v1\"").json(),
// hlx:918
pol(&[]).schema("\"Instinct.artifact-policy/v1\"").json(),
// hlx:919
pol(&[]).schema("\"\"").json(),
// hlx:920
pol(&[]).schema("1").json(),
// hlx:921
pol(&[]).schema("null").json(),
// hlx:922
pol(&[]).extra(",\"extra\":1").json(),
// hlx:923
pol(&[]).extra(",\"root\":\"/tmp\"").json(),
// hlx:924
pol(&[]).extra(",\"Allowed\":[]").json(),
// hlx:925
pol(&[]).extra(",\"facts\":{}").json(),
// hlx:926
pol(&[]).extra(",\"check\":{}").json(),
// hlx:927
pol(&[]).raw_allowed("null").json(),
// hlx:928
pol(&[]).raw_allowed("\"docs\"").json(),
// hlx:929
pol(&[]).raw_allowed("{}").json(),
// hlx:930
pol(&[]).raw_allowed("[1]").json(),
// hlx:931
pol(&[]).raw_allowed("[null]").json(),
// hlx:932
pol(&[]).raw_allowed("[[\"a\"]]").json(),
// hlx:933
pol(&[]).raw_allowed("[\"a\",\"a\"]").json(),
// hlx:934
pol(&[]).raw_allowed("[\"a\",\"b\",\"a\"]").json(),
// hlx:935
pol(&[]).raw_allowed("[\"\\u0061\",\"a\"]").json(),
// hlx:936
pol(&["a"]).raw_required("null").json(),
// hlx:937
pol(&["a"]).raw_required("\"a\"").json(),
// hlx:938
pol(&["a"]).raw_required("[1]").json(),
// hlx:939
pol(&["a"]).raw_required("[\"a\",\"a\"]").json(),
// hlx:940
// contradictory policy: required is not a subset of allowed
// hlx:941
pol(&["a"]).required(&["b"]).json(),
// hlx:942
pol(&[]).required(&["a"]).json(),
// hlx:943
pol(&["a", "b"]).required(&["a", "b", "c"]).json(),
// hlx:944
pol(&["a/b"]).required(&["a"]).json(),
// hlx:945
pol(&[]).scope("{\"env\":\"x\"}").json(),
// hlx:946
pol(&[]).scope("{\"project\":\"\"}").json(),
// hlx:947
pol(&[]).scope("{\"project\":\"*\"}").json(),
// hlx:948
pol(&[]).scope("{\"project\":null}").json(),
// hlx:949
pol(&[]).scope("{\"project\":1}").json(),
// hlx:950
pol(&[]).scope("null").json(),
// hlx:951
pol(&[]).scope("[]").json(),
// hlx:952
pol(&[]).scope("\"project\"").json(),
// hlx:953
pol(&[]).assum(Some("null")).json(),
// hlx:954
pol(&[]).assum(Some("[]")).json(),
// hlx:955
pol(&[]).assum(Some("true")).json(),
// hlx:956
pol(&[]).assum(Some("{\"trusted_quiescent_staging\":\"true\"}")).json(),
// hlx:957
pol(&[]).assum(Some("{\"trusted_quiescent_staging\":1}")).json(),
// hlx:958
pol(&[]).assum(Some("{\"trusted_quiescent_staging\":null}")).json(),
// hlx:959
pol(&[]).assum(Some("{\"trusted_quiescent_staging\":\"false\"}")).json(),
// hlx:960
pol(&[]).assum(Some("{\"trusted_quiescent_staging\":[true]}")).json(),
// hlx:961
pol(&[]).assum(Some("{\"trusted_quiescent_staging\":true,\"other\":true}")).json(),
// hlx:962
pol(&[]).assum(Some("{\"trusted\":true}")).json(),
// hlx:963
pol(&[]).assum(Some("{\"Trusted_Quiescent_Staging\":true}")).json(),
// hlx:964
pol(&[]).limits("null").json(),
// hlx:965
pol(&[]).limits("[]").json(),
// hlx:966
pol(&[]).limits("{\"max_files\":5}").json(),
// hlx:967
pol(&[]).limits("{\"max_entries\":10001}").json(),
// hlx:968
pol(&[]).limits("{\"max_entries\":-1}").json(),
// hlx:969
pol(&[]).limits("{\"max_entries\":1.5}").json(),
// hlx:970
pol(&[]).limits("{\"max_entries\":1.0}").json(),
// hlx:971
pol(&[]).limits("{\"max_entries\":1e2}").json(),
// hlx:972
pol(&[]).limits("{\"max_entries\":\"5\"}").json(),
// hlx:973
pol(&[]).limits("{\"max_entries\":null}").json(),
// hlx:974
pol(&[]).limits("{\"max_entries\":true}").json(),
// hlx:975
pol(&[]).limits("{\"max_entries\":01}").json(),
// hlx:976
pol(&[]).limits("{\"max_entries\":+1}").json(),
// hlx:977
pol(&[]).limits("{\"max_entries\":-0}").json(),
// hlx:978
pol(&[]).limits("{\"max_entries\":99999999999999999999}").json(),
// hlx:979
pol(&[]).limits("{\"max_depth\":65}").json(),
// hlx:980
pol(&[]).limits("{\"max_depth\":-1}").json(),
// hlx:981
pol(&[]).limits("{\"max_depth\":2.5}").json(),
// hlx:982
pol(&[]).limits("{\"max_inventory_bytes\":1048577}").json(),
// hlx:983
pol(&[]).limits("{\"max_inventory_bytes\":-1}").json(),
// hlx:984
pol(&[]).limits("{\"max_inventory_bytes\":1e6}").json(),
// hlx:985
pol(&[]).limits("{\"max_inventory_bytes\":\"1000\"}").json(),
// hlx:986
// duplicate keys, including escaped spellings
// hlx:987
pol(&[]).extra(",\"allowed\":[]").json(),
// hlx:988
pol(&[]).extra(",\"all\\u006fwed\":[]").json(),
// hlx:989
pol(&[]).extra(",\"\\u0073chema\":\"instinct.artifact-policy/v1\"").json(),
// hlx:990
pol(&[]).scope("{\"project\":\"p\",\"project\":\"p\"}").json(),
// hlx:991
pol(&[]).scope("{\"project\":\"p\",\"pro\\u006aect\":\"p\"}").json(),
// hlx:992
pol(&[]).limits("{\"max_depth\":1,\"max_depth\":1}").json(),
// hlx:993
pol(&[]).limits("{\"max_depth\":1,\"max_d\\u0065pth\":2}").json(),
// hlx:994
pol(&[]).assum(Some("{\"trusted_quiescent_staging\":true,\"trusted_quiescent_staging\":true}")).json(),
// hlx:995
pol(&[]).assum(Some("{\"trusted_quiescent_staging\":true,\"trusted_quiescent_st\\u0061ging\":false}")).json(),
// hlx:996
pol(&[]).extra(",\"assumptions\":{\"trusted_quiescent_staging\":true}").json(),
// hlx:997
format!("{{{ok}}} x"),
// hlx:998
format!("{{{ok},}}"),
// hlx:999
format!("{{{ok}}}{{{ok}}}"),
// hlx:1000
format!("\u{feff}{{{ok}}}"),
// hlx:1001
format!("{{{ok}}}\u{0}"),
// hlx:1002
format!("{{{}\"allowed\":[\"a\nb\"]}}", "\"schema\":\"instinct.artifact-policy/v1\","),
// hlx:1003
];
// hlx:1004
for doc in &docs {
// hlx:1005
let o = env.observe(&r, doc);
// hlx:1006
err(&o, &trunc(doc));
// hlx:1007
}
// hlx:1008
let mut bytes = pol(&[]).json().into_bytes();
// hlx:1009
bytes.truncate(bytes.len() - 1);
// hlx:1010
bytes.extend_from_slice(b",\"scope\":{\"project\":\"\xff\"}}");
// hlx:1011
err(
&env.exec(
&[
"check",
"observe",
"--root",
r.to_str().unwrap(),
"--input",
"-",
],
&bytes,
),
"invalid UTF-8",
);
// hlx:1012
// input over 1 MiB
// hlx:1013
let mut big = pol(&[]).json().into_bytes();
// hlx:1014
big.resize(1_048_577, b' ');
// hlx:1015
err(
&env.exec(
&[
"check",
"observe",
"--root",
r.to_str().unwrap(),
"--input",
"-",
],
&big,
),
"policy over 1 MiB",
);
// hlx:1016
}
// hlx:1017
#[test]
// hlx:1018
fn limits_inside_the_ceilings_and_their_zero_values_are_valid() {
// hlx:1019
let env = Env::new("limitsok");
// hlx:1020
let r = env.dir("release");
// hlx:1021
for l in [
// hlx:1022
"{}",
// hlx:1023
"{\"max_entries\":0}",
// hlx:1024
"{\"max_entries\":10000}",
// hlx:1025
"{\"max_depth\":0}",
// hlx:1026
"{\"max_depth\":64}",
// hlx:1027
"{\"max_inventory_bytes\":0}",
// hlx:1028
"{\"max_inventory_bytes\":1048576}",
// hlx:1029
"{\"max_entries\":10,\"max_depth\":3,\"max_inventory_bytes\":4096}",
// hlx:1030
] {
// hlx:1031
let o = env.observe(&r, &pol(&[]).limits(l).json());
// hlx:1032
let j = snapshot_ok(&o);
// hlx:1033
// limits may only narrow: the echoed values are the effective ones
// hlx:1034
let eff = j.get("limits").unwrap();
// hlx:1035
let parsed = parse_json(l).unwrap();
// hlx:1036
for (k, def) in [
("max_entries", "10000"),
("max_depth", "64"),
("max_inventory_bytes", "1048576"),
] {
// hlx:1037
let want = parsed.get(k).cloned().unwrap_or(J::Num(def.into()));
// hlx:1038
assert_eq!(eff.get(k), Some(&want), "{l} {k}");
// hlx:1039
}
// hlx:1040
}
// hlx:1041
}
// hlx:1042
// ---------------------------------------------------------------- the quiescence assumption
// hlx:1043
#[test]
// hlx:1044
fn a_missing_or_false_quiescence_assumption_abstains_before_the_filesystem_is_read() {
// hlx:1045
let env = Env::new("assumption");
// hlx:1046
let r = hostile_tree(&env, "hostile");
// hlx:1047
// and a nested unreadable directory, which a traversal would report differently
// hlx:1048
put_file(&r, "locked/inner");
// hlx:1049
let locked = r.join("locked");
// hlx:1050
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
// hlx:1051
let variants: Vec<(&str, Option<&str>)> = vec![
// hlx:1052
("omitted", None),
// hlx:1053
("empty object", Some("{}")),
// hlx:1054
("false", Some("{\"trusted_quiescent_staging\":false}")),
// hlx:1055
];
// hlx:1056
for (name, a) in variants {
// hlx:1057
let o = env.observe(&r, &pol(&["ok.txt"]).assum(a).json());
// hlx:1058
let j = incomplete(&o);
// hlx:1059
assert_eq!(
j.get("visited_entries"),
Some(&J::Num("0".into())),
"{name}: nothing may be visited"
);
// hlx:1060
let reason = sf(&j, "reason").to_lowercase();
// hlx:1061
assert!(
// hlx:1062
reason.contains("assum") || reason.contains("quiescen") || reason.contains("trusted"),
// hlx:1063
"{name}: the reason must name the missing assumption, not a symlink/permission finding: {reason}"
// hlx:1064
);
// hlx:1065
assert!(
!reason.contains("symlink")
&& !reason.contains("permission")
&& !reason.contains("utf"),
"{name}: {reason}"
);
// hlx:1066
assert_ne!(
j.get("assumptions")
.unwrap()
.get("trusted_quiescent_staging"),
Some(&J::Bool(true))
);
// hlx:1067
no_leak(&o, &env);
// hlx:1068
}
// hlx:1069
// a root that does not exist cannot be told apart from an unread one: error or incomplete, never a snapshot
// hlx:1070
let gone = env.root.join("stage").join("does-not-exist");
// hlx:1071
for a in [None, Some("{\"trusted_quiescent_staging\":false}")] {
// hlx:1072
not_snapshot(
&env.observe(&gone, &pol(&[]).assum(a).json()),
"nonexistent root without the assumption",
);
// hlx:1073
}
// hlx:1074
// with the assumption the same hostile root is read, and the findings appear
// hlx:1075
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
// hlx:1076
let o = env.observe(&r, &pol(&["ok.txt"]).json());
// hlx:1077
let j = incomplete(&o);
// hlx:1078
assert!(sf(&j, "reason").len() > 0);
// hlx:1079
// true is the caller's assumption, echoed, never presented as observed proof
// hlx:1080
let clean = env.dir("clean");
// hlx:1081
put_file(&clean, "a");
// hlx:1082
let j = snapshot_ok(&env.observe(&clean, &pol(&["a"]).json()));
// hlx:1083
assert_eq!(
j.get("assumptions"),
Some(&J::Obj(vec![(
"trusted_quiescent_staging".to_string(),
J::Bool(true)
)]))
);
// hlx:1084
assert_eq!(sf(&j, "evidence_origin"), "adapter_observed");
// hlx:1085
}
// hlx:1086
// ---------------------------------------------------------------- root and argument validation
// hlx:1087
#[test]
// hlx:1088
fn root_must_be_explicit_absolute_and_an_actual_directory() {
// hlx:1089
let env = Env::new("roots");
// hlx:1090
let r = env.dir("release");
// hlx:1091
put_file(&r, "a");
// hlx:1092
let doc = pol(&["a"]).json();
// hlx:1093
let ro = r.to_str().unwrap();
// hlx:1094
let run = |args: &[&str]| env.exec(args, doc.as_bytes());
// hlx:1095
// not explicit / not absolute: argument errors
// hlx:1096
err(
&run(&["check", "observe", "--input", "-"]),
"missing --root",
);
// hlx:1097
err(
&run(&["check", "observe", "--root", "--input", "-"]),
"root without value",
);
// hlx:1098
err(
&run(&["check", "observe", "--root", "", "--input", "-"]),
"empty root",
);
// hlx:1099
err(
&run(&["check", "observe", "--root", "release", "--input", "-"]),
"relative root",
);
// hlx:1100
err(
&run(&["check", "observe", "--root", "./release", "--input", "-"]),
"dot-relative root",
);
// hlx:1101
err(
&run(&[
"check",
"observe",
"--root",
"stage/release",
"--input",
"-",
]),
"relative root with slash",
);
// hlx:1102
err(
&run(&["check", "observe", "--root", "~/release", "--input", "-"]),
"tilde root",
);
// hlx:1103
err(
&run(&["check", "observe", "--root", "$HOME", "--input", "-"]),
"variable root",
);
// hlx:1104
// missing input
// hlx:1105
err(&run(&["check", "observe", "--root", ro]), "missing --input");
// hlx:1106
err(
&run(&["check", "observe", "--root", ro, "--input"]),
"input without value",
);
// hlx:1107
// duplicates, unknowns, extra positionals
// hlx:1108
err(
&run(&[
"check", "observe", "--root", ro, "--root", ro, "--input", "-",
]),
"duplicate root",
);
// hlx:1109
err(
&run(&[
"check", "observe", "--root", ro, "--input", "-", "--input", "-",
]),
"duplicate input",
);
// hlx:1110
err(
&run(&["check", "observe", "--root", ro, "--input", "-", "extra"]),
"extra positional",
);
// hlx:1111
err(
&run(&["check", "observe", ro, "--input", "-"]),
"positional root",
);
// hlx:1112
err(
&run(&["check", "observe", "--root", ro, "--input", "-", "--bogus"]),
"unknown option",
);
// hlx:1113
err(
&run(&[
"check",
"observe",
"--root",
ro,
"--input",
"-",
"--follow-symlinks",
]),
"unknown option",
);
// hlx:1114
err(
&run(&["check", "observe", "--root", ro, "--input", "-", "--write"]),
"unknown option",
);
// hlx:1115
err(
&run(&["check", "observe", "--Root", ro, "--input", "-"]),
"case-sensitive option",
);
// hlx:1116
err(
&run(&["check", "observe", "-r", ro, "--input", "-"]),
"short option",
);
// hlx:1117
// the root is never read from the document, the environment or the working directory
// hlx:1118
let in_json = format!("{{\"schema\":\"instinct.artifact-policy/v1\",\"assumptions\":{{\"trusted_quiescent_staging\":true}},\"allowed\":[\"a\"],\"root\":\"{ro}\"}}");
// hlx:1119
err(&run(&["check", "observe", "--input", "-"]), "no root");
// hlx:1120
err(
&env.exec(&["check", "observe", "--input", "-"], in_json.as_bytes()),
"root in JSON",
);
// hlx:1121
let o = env.exec_raw(
&["check", "observe", "--input", "-"],
doc.as_bytes(),
&[("INSTINCT_ROOT", ro), ("INSTINCT_PROJECT", ro), ("PWD", ro)],
true,
);
// hlx:1122
err(&o, "root from the environment");
// hlx:1123
// not a usable root: never a snapshot
// hlx:1124
let file = env.put("a_file", b"x");
// hlx:1125
not_snapshot(
&run(&[
"check",
"observe",
"--root",
file.to_str().unwrap(),
"--input",
"-",
]),
"root is a file",
);
// hlx:1126
not_snapshot(
&run(&[
"check",
"observe",
"--root",
env.root.join("stage/none").to_str().unwrap(),
"--input",
"-",
]),
"root missing",
);
// hlx:1127
let link = env.root.join("stage").join("rootlink");
// hlx:1128
std::os::unix::fs::symlink(&r, &link).unwrap();
// hlx:1129
not_snapshot(
&run(&[
"check",
"observe",
"--root",
link.to_str().unwrap(),
"--input",
"-",
]),
"root is a symlink to a directory",
);
// hlx:1130
let dangling = env.root.join("stage").join("dangling");
// hlx:1131
std::os::unix::fs::symlink(env.root.join("stage/nothing"), &dangling).unwrap();
// hlx:1132
not_snapshot(
&run(&[
"check",
"observe",
"--root",
dangling.to_str().unwrap(),
"--input",
"-",
]),
"root is a dangling symlink",
);
// hlx:1133
// a symlinked component above the root: the root path itself is reached through a link
// hlx:1134
let via = format!("{}/rootlink", env.root.join("stage").display());
// hlx:1135
not_snapshot(
&run(&["check", "observe", "--root", &via, "--input", "-"]),
"root path through a link",
);
// hlx:1136
// the plain root still works
// hlx:1137
snapshot_ok(&run(&["check", "observe", "--root", ro, "--input", "-"]));
// hlx:1138
}
// hlx:1139
#[test]
// hlx:1140
fn input_file_and_stdin_give_identical_observations_and_errors() {
// hlx:1141
let env = Env::new("parity");
// hlx:1142
let r = env.dir("release");
// hlx:1143
put_file(&r, "a");
// hlx:1144
put_file(&r, "b/c");
// hlx:1145
let docs = [
// hlx:1146
pol(&["a", "b", "b/c"]).json(),
// hlx:1147
pol(&["a"]).required(&["a"]).json(),
// hlx:1148
pol(&["a"]).assum(None).json(),
// hlx:1149
"{".to_string(),
// hlx:1150
pol(&["../x"]).json(),
// hlx:1151
];
// hlx:1152
for (i, doc) in docs.iter().enumerate() {
// hlx:1153
let f = env.put(&format!("policy{i}.json"), doc.as_bytes());
// hlx:1154
let a = env.exec(
&[
"check",
"observe",
"--root",
r.to_str().unwrap(),
"--input",
f.to_str().unwrap(),
],
b"",
);
// hlx:1155
let b = env.observe(&r, doc);
// hlx:1156
assert_eq!(a.code, b.code, "doc {i}");
// hlx:1157
assert_eq!(a.out, b.out, "doc {i}");
// hlx:1158
let again = env.observe(&r, doc);
// hlx:1159
assert_eq!(b.out, again.out, "doc {i}: deterministic");
// hlx:1160
}
// hlx:1161
err(
&env.exec(
&[
"check",
"observe",
"--root",
r.to_str().unwrap(),
"--input",
env.root.join("in/none.json").to_str().unwrap(),
],
b"",
),
"missing input file",
);
// hlx:1162
err(
&env.exec(
&[
"check",
"observe",
"--root",
r.to_str().unwrap(),
"--input",
env.root.join("in").to_str().unwrap(),
],
b"",
),
"input is a directory",
);
// hlx:1163
err(
&env.exec(
&[
"check",
"observe",
"--root",
r.to_str().unwrap(),
"--input",
"-",
],
b"",
),
"empty stdin",
);
// hlx:1164
}
// hlx:1165
#[test]
// hlx:1166
fn creation_order_and_repeats_do_not_change_the_observation() {
// hlx:1167
let env = Env::new("determinism");
// hlx:1168
let names = ["m", "a", "z/y", "z/a", "Q", ".h", "b/c/d"];
// hlx:1169
let mut outs = Vec::new();
// hlx:1170
for order in [
[0usize, 1, 2, 3, 4, 5, 6],
[6, 5, 4, 3, 2, 1, 0],
[3, 0, 6, 1, 5, 2, 4],
] {
// hlx:1171
let r = env.dir(&format!(
"o{}",
order.iter().map(|i| i.to_string()).collect::<String>()
));
// hlx:1172
for i in order {
// hlx:1173
put_file(&r, names[i]);
// hlx:1174
}
// hlx:1175
let o = env.observe(&r, &pol(&["a", "m"]).json());
// hlx:1176
let j = snapshot_ok(&o);
// hlx:1177
outs.push((paths(&j), fails(&j)));
// hlx:1178
}
// hlx:1179
assert!(outs.windows(2).all(|w| w[0] == w[1]), "{outs:?}");
// hlx:1180
}
// hlx:1181
// ---------------------------------------------------------------- symlinks and unsupported entries
// hlx:1182
#[test]
// hlx:1183
fn symlinks_make_the_observation_incomplete_without_reading_or_disclosing_targets() {
// hlx:1184
let env = Env::new("symlinks");
// hlx:1185
let outside_file = env.outside().join("OUTSIDE_TARGET_SECRET_731");
// hlx:1186
let outside_dir = env.outside().join("OUTSIDE_DIR_SECRET_731");
// hlx:1187
// (link name, how to create it)
// hlx:1188
type Mk = Box<dyn Fn(&Path, &Path)>;
// hlx:1189
let cases: Vec<(&str, &str, Mk)> = vec![
// hlx:1190
(
"file outside",
"link",
Box::new({
let t = outside_file.clone();
move |r, _| std::os::unix::fs::symlink(&t, r.join("link")).unwrap()
}),
),
// hlx:1191
(
"dir outside",
"link",
Box::new({
let t = outside_dir.clone();
move |r, _| std::os::unix::fs::symlink(&t, r.join("link")).unwrap()
}),
),
// hlx:1192
(
"file inside",
"link",
Box::new(|r, _| {
std::os::unix::fs::symlink(r.join("TARGET_INSIDE_731"), r.join("link")).unwrap()
}),
),
// hlx:1193
(
"relative inside",
"link",
Box::new(|r, _| {
std::os::unix::fs::symlink("TARGET_INSIDE_731", r.join("link")).unwrap()
}),
),
// hlx:1194
(
"dir inside",
"link",
Box::new(|r, _| std::os::unix::fs::symlink(r.join("sub"), r.join("link")).unwrap()),
),
// hlx:1195
(
"dangling",
"link",
Box::new(|r, _| {
std::os::unix::fs::symlink("TARGET_INSIDE_731_missing", r.join("link")).unwrap()
}),
),
// hlx:1196
(
"self loop",
"link",
Box::new(|r, _| std::os::unix::fs::symlink("link", r.join("link")).unwrap()),
),
// hlx:1197
(
"parent loop",
"sub/up",
Box::new(|r, _| std::os::unix::fs::symlink("..", r.join("sub/up")).unwrap()),
),
// hlx:1198
(
"to the root",
"sub/home",
Box::new(|r, _| std::os::unix::fs::symlink(r, r.join("sub/home")).unwrap()),
),
// hlx:1199
(
"to the filesystem root",
"link",
Box::new(|_, r| std::os::unix::fs::symlink("/", r.join("link")).unwrap()),
),
// hlx:1200
(
"nested deep",
"sub/deeper/link",
Box::new({
let t = outside_file.clone();
move |r, _| {
std::fs::create_dir_all(r.join("sub/deeper")).unwrap();
std::os::unix::fs::symlink(&t, r.join("sub/deeper/link")).unwrap()
}
}),
),
// hlx:1201
(
"hidden name",
".hidden-link",
Box::new({
let t = outside_dir.clone();
move |r, _| std::os::unix::fs::symlink(&t, r.join(".hidden-link")).unwrap()
}),
),
// hlx:1202
];
// hlx:1203
for (i, (name, link, mk)) in cases.iter().enumerate() {
// hlx:1204
let r = env.dir(&format!("s{i}"));
// hlx:1205
put_file(&r, "TARGET_INSIDE_731");
// hlx:1206
put_dir(&r, "sub");
// hlx:1207
put_file(&r, "ok.txt");
// hlx:1208
mk(&r, &r);
// hlx:1209
let allowed_all = ["TARGET_INSIDE_731", "sub", "ok.txt", link];
// hlx:1210
for p in [
pol(&allowed_all).json(),
pol(&allowed_all).required(&["ok.txt"]).json(),
pol(&["ok.txt"]).json(),
] {
// hlx:1211
let o = env.observe(&r, &p);
// hlx:1212
let j = incomplete(&o);
// hlx:1213
assert_ne!(sf(&j, "reason"), "", "{name}");
// hlx:1214
no_leak(&o, &env);
// hlx:1215
// an offending-entry witness, when given, is the sanitized relative path of the link itself
// hlx:1216
if let Some(J::Str(w)) = j.get("witness") {
// hlx:1217
assert_eq!(w, link, "{name}: witness");
// hlx:1218
}
// hlx:1219
}
// hlx:1220
}
// hlx:1221
}
// hlx:1222
#[test]
// hlx:1223
fn unsupported_entry_kinds_make_the_observation_incomplete() {
// hlx:1224
let env = Env::new("sockets");
// hlx:1225
let r = env.dir("release");
// hlx:1226
put_file(&r, "ok.txt");
// hlx:1227
let sock = r.join("sock");
// hlx:1228
#[cfg(target_os = "linux")]
// hlx:1229
let socket_dir = std::fs::File::open(&r).unwrap();
// hlx:1230
#[cfg(target_os = "linux")]
// hlx:1231
let bind_path = {
use std::os::fd::AsRawFd;
PathBuf::from(format!("/proc/self/fd/{}/sock", socket_dir.as_raw_fd()))
};
// hlx:1232
#[cfg(not(target_os = "linux"))]
// hlx:1233
let bind_path = sock.clone();
// hlx:1234
let _l = std::os::unix::net::UnixListener::bind(&bind_path).unwrap();
// hlx:1235
let o = env.observe(&r, &pol(&["ok.txt", "sock"]).json());
// hlx:1236
let j = incomplete(&o);
// hlx:1237
if let Some(J::Str(w)) = j.get("witness") {
// hlx:1238
assert_eq!(w, "sock");
// hlx:1239
}
// hlx:1240
no_leak(&o, &env);
// hlx:1241
drop(_l);
// hlx:1242
std::fs::remove_file(&sock).unwrap();
// hlx:1243
snapshot_ok(&env.observe(&r, &pol(&["ok.txt"]).json()));
// hlx:1244
}
// hlx:1245
// ---------------------------------------------------------------- permissions and non-UTF-8 names
// hlx:1246
#[test]
// hlx:1247
fn unreadable_directories_abstain_and_unreadable_file_contents_are_never_opened() {
// hlx:1248
if is_root() {
// hlx:1249
eprintln!("NOT EXERCISED: running as a superuser, permission bits do not block reads");
// hlx:1250
return;
// hlx:1251
}
// hlx:1252
let env = Env::new("perms");
// hlx:1253
let r = env.dir("release");
// hlx:1254
put_file(&r, "ok.txt");
// hlx:1255
put_file(&r, "docs/README");
// hlx:1256
put_file(&r, "docs/locked/secret");
// hlx:1257
let locked = r.join("docs/locked");
// hlx:1258
let allowed = [
"ok.txt",
"docs",
"docs/README",
"docs/locked",
"docs/locked/secret",
];
// hlx:1259
// a file whose contents cannot be read is still just a name: no content is opened in inventory mode
// hlx:1260
let f = r.join("docs/README");
// hlx:1261
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o000)).unwrap();
// hlx:1262
let j = snapshot_ok(&env.observe(&r, &pol(&allowed).json()));
// hlx:1263
all_pass(&j);
// hlx:1264
assert!(paths(&j).contains(&"docs/locked/secret".to_string()));
// hlx:1265
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o644)).unwrap();
// hlx:1266
// an unreadable nested directory can never become an empty-directory success
// hlx:1267
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
// hlx:1268
for p in [
pol(&allowed).json(),
pol(&["ok.txt", "docs", "docs/README", "docs/locked"]).json(),
pol(&[]).json(),
pol(&allowed).required(&["ok.txt"]).json(),
] {
// hlx:1269
let o = env.observe(&r, &p);
// hlx:1270
let j = incomplete(&o);
// hlx:1271
assert!(!sf(&j, "reason").is_empty());
// hlx:1272
no_leak(&o, &env);
// hlx:1273
if let Some(J::Str(w)) = j.get("witness") {
// hlx:1274
assert!(
w == "docs/locked" || w == "docs/locked/secret",
"witness {w}"
);
// hlx:1275
}
// hlx:1276
}
// hlx:1277
// an unreadable root
// hlx:1278
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
// hlx:1279
std::fs::set_permissions(&r, std::fs::Permissions::from_mode(0o000)).unwrap();
// hlx:1280
not_snapshot(&env.observe(&r, &pol(&[]).json()), "unreadable root");
// hlx:1281
std::fs::set_permissions(&r, std::fs::Permissions::from_mode(0o755)).unwrap();
// hlx:1282
// restored: complete again
// hlx:1283
snapshot_ok(&env.observe(&r, &pol(&allowed).json()));
// hlx:1284
}
// hlx:1285
#[test]
// hlx:1286
fn non_utf8_names_abstain_or_use_an_explicit_lossless_encoding() {
// hlx:1287
let env = Env::new("nonutf8");
// hlx:1288
let r = env.dir("release");
// hlx:1289
put_file(&r, "ok.txt");
// hlx:1290
if !put_raw_file(&r, b"bad\xff.txt") {
return;
}
// hlx:1291
for p in [
// hlx:1292
pol(&["ok.txt"]).json(),
// hlx:1293
pol(&["ok.txt", "bad\u{fffd}.txt"]).json(),
// hlx:1294
pol(&["ok.txt", "bad\\ufffd.txt"]).json(),
// hlx:1295
pol(&["ok.txt", "bad\\u00ff.txt"]).json(),
// hlx:1296
pol(&["ok.txt", "bad%ff.txt", "bad\\\\xff.txt"]).json(),
// hlx:1297
] {
// hlx:1298
let o = env.observe(&r, &p);
// hlx:1299
assert_eq!(o.code, Some(0), "{}", trunc(&o.text()));
// hlx:1300
let t = o.text();
// hlx:1301
assert!(
!t.contains('\u{fffd}'),
"a replacement character must never stand in for raw bytes: {}",
trunc(&t)
);
// hlx:1302
let j = observed(&o);
// hlx:1303
if sf(&j, "validity") == "observed_snapshot" {
// hlx:1304
// an explicit encoding: the raw name must not be satisfiable by any lossy spelling of it
// hlx:1305
let v = verdicts(&j);
// hlx:1306
assert!(
v.contains(&"fail".to_string())
|| paths(&j)
.iter()
.any(|x| x.contains("ff") || x.contains("FF") || x.contains("xff")),
"{}",
trunc(&t)
);
// hlx:1307
assert_eq!(inv(&j).len(), 2, "{}", trunc(&t));
// hlx:1308
} else {
// hlx:1309
incomplete(&o);
// hlx:1310
}
// hlx:1311
}
// hlx:1312
// two different raw names must never collapse into one lossy name
// hlx:1313
if !put_raw_file(&r, b"bad\xfe.txt") {
return;
}
// hlx:1314
let o = env.observe(&r, &pol(&["ok.txt", "bad\\ufffd.txt"]).json());
// hlx:1315
let j = observed(&o);
// hlx:1316
if sf(&j, "validity") == "observed_snapshot" {
// hlx:1317
assert_eq!(
inv(&j).len(),
3,
"distinct raw names stay distinct: {}",
trunc(&o.text())
);
// hlx:1318
let mut ps = paths(&j);
// hlx:1319
ps.sort();
// hlx:1320
ps.dedup();
// hlx:1321
assert_eq!(ps.len(), 3);
// hlx:1322
}
// hlx:1323
// a directory with a raw-byte name hides nothing beneath it
// hlx:1324
let r2 = env.dir("release2");
// hlx:1325
if !raw_fixture_created(std::fs::create_dir_all(
r2.join(OsStr::from_bytes(b"d\xff")),
)) {
return;
}
// hlx:1326
std::fs::write(r2.join(OsStr::from_bytes(b"d\xff")).join("inside"), b"x").unwrap();
// hlx:1327
let o = env.observe(&r2, &pol(&[]).json());
// hlx:1328
let j = observed(&o);
// hlx:1329
if sf(&j, "validity") == "observed_snapshot" {
// hlx:1330
assert!(
fails(&j).len() == 1 && inv(&j).len() == 2,
"{}",
trunc(&o.text())
);
// hlx:1331
}
// hlx:1332
}
// hlx:1333
// ---------------------------------------------------------------- budgets
// hlx:1334
#[test]
// hlx:1335
fn depth_budget_is_relative_entry_depth_with_the_root_at_zero() {
// hlx:1336
let env = Env::new("depth");
// hlx:1337
let r = env.dir("release");
// hlx:1338
put_file(&r, "top");
// hlx:1339
put_file(&r, "a/b/c.txt");
// hlx:1340
let allowed = ["top", "a", "a/b", "a/b/c.txt"];
// hlx:1341
// entries: top and a are depth 1, a/b is 2, a/b/c.txt is 3
// hlx:1342
for (d, ok) in [
(64, true),
(4, true),
(3, true),
(2, false),
(1, false),
(0, false),
] {
// hlx:1343
let o = env.observe(
&r,
&pol(&allowed)
.limits(&format!("{{\"max_depth\":{d}}}"))
.json(),
);
// hlx:1344
let j = observed(&o);
// hlx:1345
if ok {
// hlx:1346
assert_eq!(
sf(&j, "validity"),
"observed_snapshot",
"max_depth {d}: {}",
trunc(&o.text())
);
// hlx:1347
assert_eq!(inv(&j).len(), 4);
// hlx:1348
all_pass(&j);
// hlx:1349
} else {
// hlx:1350
incomplete(&o);
// hlx:1351
}
// hlx:1352
}
// hlx:1353
let flat = env.dir("flat");
// hlx:1354
put_file(&flat, "x");
// hlx:1355
snapshot_ok(&env.observe(&flat, &pol(&["x"]).limits("{\"max_depth\":1}").json()));
// hlx:1356
incomplete(&env.observe(&flat, &pol(&["x"]).limits("{\"max_depth\":0}").json()));
// hlx:1357
// an empty root has no entries at all, so even depth 0 is complete
// hlx:1358
let empty = env.dir("none");
// hlx:1359
snapshot_ok(
&env.observe(
&empty,
&pol(&[])
.limits("{\"max_depth\":0,\"max_entries\":0,\"max_inventory_bytes\":0}")
.json(),
),
);
// hlx:1360
// a tree deeper than the 64 ceiling never completes under the default
// hlx:1361
let deep = env.dir("deep");
// hlx:1362
let rel = (0..70)
.map(|i| format!("d{i}"))
.collect::<Vec<_>>()
.join("/");
// hlx:1363
put_dir(&deep, &rel);
// hlx:1364
incomplete(&env.observe(&deep, &pol(&[]).json()));
// hlx:1365
}
// hlx:1366
#[test]
// hlx:1367
fn entry_budget_counts_files_and_directories_but_not_the_root() {
// hlx:1368
let env = Env::new("entries");
// hlx:1369
let r = env.dir("release");
// hlx:1370
put_file(&r, "a");
// hlx:1371
put_file(&r, "d/b");
// hlx:1372
put_dir(&r, "e");
// hlx:1373
// a, d, d/b, e = 4 entries
// hlx:1374
let allowed = ["a", "d", "d/b", "e"];
// hlx:1375
for (n, ok) in [
(10000, true),
(5, true),
(4, true),
(3, false),
(2, false),
(1, false),
(0, false),
] {
// hlx:1376
let o = env.observe(
&r,
&pol(&allowed)
.limits(&format!("{{\"max_entries\":{n}}}"))
.json(),
);
// hlx:1377
let j = observed(&o);
// hlx:1378
if ok {
// hlx:1379
assert_eq!(
sf(&j, "validity"),
"observed_snapshot",
"max_entries {n}: {}",
trunc(&o.text())
);
// hlx:1380
assert_eq!(j.get("visited_entries"), Some(&J::Num("4".into())));
// hlx:1381
} else {
// hlx:1382
incomplete(&o);
// hlx:1383
// visited entries are bounded by the budget, never the whole tree
// hlx:1384
match j.get("visited_entries") {
// hlx:1385
Some(J::Num(v)) => assert!(
v.parse::<u64>().unwrap() <= n as u64,
"max_entries {n} visited {v}"
),
// hlx:1386
other => panic!("{other:?}"),
// hlx:1387
}
// hlx:1388
}
// hlx:1389
}
// hlx:1390
}
// hlx:1391
#[test]
// hlx:1392
fn inventory_byte_budget_is_monotonic_and_covers_at_least_the_path_bytes() {
// hlx:1393
let env = Env::new("bytes");
// hlx:1394
let r = env.dir("release");
// hlx:1395
for f in ["a", "bb", "docs/ccc"] {
// hlx:1396
put_file(&r, f);
// hlx:1397
}
// hlx:1398
let allowed = ["a", "bb", "docs", "docs/ccc"];
// hlx:1399
let path_bytes: u64 = ["a", "bb", "docs", "docs/ccc"]
.iter()
.map(|s| s.len() as u64)
.sum();
// hlx:1400
let exact = path_bytes + 4 * 64;
// hlx:1401
let mut budgets: Vec<u64> = (0..=path_bytes + 2)
.chain([
32,
64,
128,
256,
exact - 1,
exact,
exact + 1,
512,
1024,
4096,
65536,
1_048_576,
])
.collect();
// hlx:1402
budgets.sort();
// hlx:1403
budgets.dedup();
// hlx:1404
let mut seen_complete = false;
// hlx:1405
let mut first_complete = None;
// hlx:1406
for b in budgets {
// hlx:1407
let o = env.observe(
&r,
&pol(&allowed)
.limits(&format!("{{\"max_inventory_bytes\":{b}}}"))
.json(),
);
// hlx:1408
let j = observed(&o);
// hlx:1409
let complete = sf(&j, "validity") == "observed_snapshot";
// hlx:1410
if b < path_bytes {
// hlx:1411
assert!(
!complete,
"a budget of {b} cannot hold {path_bytes} path bytes"
);
// hlx:1412
}
// hlx:1413
if seen_complete {
// hlx:1414
assert!(
complete,
"budget {b} is larger than an earlier sufficient budget but is incomplete"
);
// hlx:1415
}
// hlx:1416
if complete {
// hlx:1417
first_complete.get_or_insert(b);
// hlx:1418
assert_eq!(inv(&j).len(), 4);
// hlx:1419
all_pass(&j);
// hlx:1420
} else {
// hlx:1421
incomplete(&o);
// hlx:1422
}
// hlx:1423
seen_complete |= complete;
// hlx:1424
}
// hlx:1425
assert!(
seen_complete,
"the maximum budget must be enough for four short names"
);
// hlx:1426
let f = first_complete.unwrap();
// hlx:1427
// docs/check-observation-wire.md: path bytes plus 64 bytes per entry, charged per pass
// hlx:1428
assert_eq!(
f,
path_bytes + 4 * 64,
"documented accounting: UTF-8 path bytes plus 64 per entry"
);
// hlx:1429
// a zero budget is fine only when nothing needs charging
// hlx:1430
incomplete(&env.observe(
&r,
&pol(&allowed).limits("{\"max_inventory_bytes\":0}").json(),
));
// hlx:1431
}
// hlx:1432
#[test]
// hlx:1433
fn exceeding_the_default_entry_ceiling_is_incomplete_and_never_a_partial_pass() {
// hlx:1434
let env = Env::new("many");
// hlx:1435
let r = env.dir("release");
// hlx:1436
for i in 0..10_050 {
// hlx:1437
std::fs::write(r.join(format!("f{i:05}")), b"").unwrap();
// hlx:1438
}
// hlx:1439
for p in [
pol(&[]).json(),
pol(&[]).limits("{\"max_entries\":10000}").json(),
pol(&[]).required(&[]).json(),
] {
// hlx:1440
let o = env.observe(&r, &p);
// hlx:1441
let j = incomplete(&o);
// hlx:1442
assert!(!sf(&j, "reason").is_empty());
// hlx:1443
match j.get("visited_entries") {
// hlx:1444
Some(J::Num(v)) => {
assert!(v.parse::<u64>().unwrap() <= 10_000, "visited {v} entries")
}
// hlx:1445
other => panic!("{other:?}"),
// hlx:1446
}
// hlx:1447
}
// hlx:1448
}
// hlx:1449
#[test]
// hlx:1450
fn an_inventory_that_fits_the_output_is_exact_and_one_that_does_not_is_a_bounded_error() {
// hlx:1451
let env = Env::new("outsize");
// hlx:1452
// 800 short names fit comfortably
// hlx:1453
let r = env.dir("fits");
// hlx:1454
let names: Vec<String> = (0..800).map(|i| format!("f{i:04}")).collect();
// hlx:1455
for n in &names {
// hlx:1456
std::fs::write(r.join(n), b"").unwrap();
// hlx:1457
}
// hlx:1458
let refs: Vec<&str> = names.iter().map(|s| s.as_str()).collect();
// hlx:1459
let o = env.observe(&r, &pol(&refs).json());
// hlx:1460
let j = snapshot_ok(&o);
// hlx:1461
assert_eq!(paths(&j), names);
// hlx:1462
all_pass(&j);
// hlx:1463
// 400 maximum-length names cannot fit 64 KiB: explicit output-limit error, not a truncated inventory or a pass
// hlx:1464
let big = env.dir("toobig");
// hlx:1465
for i in 0..400 {
// hlx:1466
let n = format!("{i:03}{}", "n".repeat(252));
// hlx:1467
std::fs::write(big.join(n), b"").unwrap();
// hlx:1468
}
// hlx:1469
let o = env.observe(&big, &pol(&[]).json());
// hlx:1470
err(&o, "inventory larger than the output budget");
// hlx:1471
assert!(
o.text().to_lowercase().contains("limit"),
"the error should be an output-limit error: {}",
trunc(&o.text())
);
// hlx:1472
// the same names under a tight entry budget are an incomplete observation instead
// hlx:1473
let o = env.observe(&big, &pol(&[]).limits("{\"max_entries\":10}").json());
// hlx:1474
incomplete(&o);
// hlx:1475
}
// hlx:1476
// ---------------------------------------------------------------- containment and isolation
// hlx:1477
#[test]
// hlx:1478
fn a_sibling_directory_sharing_the_root_prefix_is_not_part_of_the_observation() {
// hlx:1479
let env = Env::new("prefix");
// hlx:1480
let r = env.dir("rel");
// hlx:1481
put_file(&r, "own.txt");
// hlx:1482
let sibling = env.dir("rel-evil");
// hlx:1483
put_file(&sibling, "SIBLING_ONLY_731");
// hlx:1484
let sibling2 = env.dir("rel2");
// hlx:1485
put_file(&sibling2, "SIBLING2_ONLY_731");
// hlx:1486
let o = env.observe(&r, &pol(&["own.txt"]).json());
// hlx:1487
let j = snapshot_ok(&o);
// hlx:1488
assert_eq!(paths(&j), vec!["own.txt"]);
// hlx:1489
all_pass(&j);
// hlx:1490
assert!(!o.text().contains("SIBLING"), "{}", trunc(&o.text()));
// hlx:1491
// policy names that look like the sibling are only names
// hlx:1492
let j = snapshot_ok(
&env.observe(
&r,
&pol(&[
"own.txt",
"../rel-evil/SIBLING_ONLY_731".replace("../", "").as_str(),
])
.json(),
),
);
// hlx:1493
all_pass(&j);
// hlx:1494
err(
&env.observe(
&r,
&pol(&["own.txt", "../rel-evil/SIBLING_ONLY_731"]).json(),
),
"traversal into a sibling",
);
// hlx:1495
// a trailing slash on the root names the same directory
// hlx:1496
let slashed = format!("{}/", r.display());
// hlx:1497
let o = env.exec(
&["check", "observe", "--root", &slashed, "--input", "-"],
pol(&["own.txt"]).json().as_bytes(),
);
// hlx:1498
if o.code == Some(0) {
// hlx:1499
let j = observed(&o);
// hlx:1500
assert!(!o.text().contains("SIBLING"));
// hlx:1501
if sf(&j, "validity") == "observed_snapshot" {
// hlx:1502
assert_eq!(paths(&j), vec!["own.txt"]);
// hlx:1503
}
// hlx:1504
} else {
// hlx:1505
err(&o, "trailing slash root");
// hlx:1506
}
// hlx:1507
}
// hlx:1508
#[test]
// hlx:1509
fn observation_writes_nothing_and_never_touches_home_or_the_bank() {
// hlx:1510
let env = Env::new("nowrites");
// hlx:1511
let r = env.dir("release");
// hlx:1512
put_file(&r, "a");
// hlx:1513
put_file(&r, "d/b");
// hlx:1514
for p in [
pol(&["a", "d", "d/b"]).json(),
pol(&[]).json(),
pol(&["a"]).assum(None).json(),
"{".to_string(),
pol(&["../x"]).json(),
] {
// hlx:1515
let _ = env.observe(&r, &p);
// hlx:1516
}
// hlx:1517
// every call above was wrapped by a before/after snapshot of the whole environment including the tree
// hlx:1518
assert!(
!env.root.join("data").join("instinct").exists(),
"no bank folder"
);
// hlx:1519
assert!(!env.root.join("local").join("instinct").exists());
// hlx:1520
assert_eq!(
std::fs::read(env.root.join("home").join("sentinel")).unwrap(),
b"home sentinel"
);
// hlx:1521
let leftovers: Vec<_> = std::fs::read_dir(&r)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.file_name())
.collect();
// hlx:1522
assert_eq!(leftovers.len(), 2, "{leftovers:?}");
// hlx:1523
// the home directory is not enumerated into results
// hlx:1524
let o = env.observe(&r, &pol(&["a", "d", "d/b"]).json());
// hlx:1525
assert!(!o.text().contains("sentinel"));
// hlx:1526
// an existing, corrupt bank is not opened or changed
// hlx:1527
std::fs::create_dir_all(env.root.join("data").join("instinct")).unwrap();
// hlx:1528
std::fs::write(
env.root.join("data").join("instinct").join("bank.hxdb"),
b"\xff\xfenot a bank",
)
.unwrap();
// hlx:1529
snapshot_ok(&env.observe(&r, &pol(&["a", "d", "d/b"]).json()));
// hlx:1530
}
// hlx:1531
#[test]
// hlx:1532
fn pure_check_commands_keep_their_syntax_and_gain_no_filesystem_access() {
// hlx:1533
let env = Env::new("pure");
// hlx:1534
let r = env.dir("release");
// hlx:1535
put_file(&r, "present");
// hlx:1536
// `check run` has no --root and no observation side channel
// hlx:1537
let doc = "{\"check\":{\"schema\":\"instinct.check/v1\",\"id\":\"t1\",\"revision\":1,\"inputs\":{\"actual\":\"set<string>\",\"allowed\":\"set<string>\"},\"claim\":{\"op\":\"subset\",\"left\":{\"fact\":\"actual\"},\"right\":{\"fact\":\"allowed\"}}},\"facts\":{\"actual\":[\"x\"],\"allowed\":[]}}";
// hlx:1538
for sub in ["run", "validate", "explain"] {
// hlx:1539
let o = env.exec(
&["check", sub, "--root", r.to_str().unwrap(), "--input", "-"],
doc.as_bytes(),
);
// hlx:1540
err(&o, &format!("{sub} must reject --root"));
// hlx:1541
let o = env.exec(&["check", sub, "--input", "-"], doc.as_bytes());
// hlx:1542
assert_eq!(o.code, Some(0));
// hlx:1543
assert!(!o.text().contains("artifact-observation"));
// hlx:1544
}
// hlx:1545
// the observe command does not accept a pure check document
// hlx:1546
err(&env.observe(&r, doc), "a check document is not a policy");
// hlx:1547
}
// hlx:1548
// ---------------------------------------------------------------- a mutator running during observation (stress, not proof)
// hlx:1549
#[test]
// hlx:1550
fn a_flickering_file_during_observation_never_yields_an_inconsistent_snapshot() {
// hlx:1551
use std::sync::atomic::AtomicBool;
// hlx:1552
use std::sync::Arc;
// hlx:1553
let env = Env::new("stress");
// hlx:1554
let r = env.dir("release");
// hlx:1555
put_file(&r, "base-a");
// hlx:1556
put_file(&r, "sub/base-b");
// hlx:1557
let stop = Arc::new(AtomicBool::new(false));
// hlx:1558
let (s2, r2) = (stop.clone(), r.clone());
// hlx:1559
let t = std::thread::spawn(move || {
// hlx:1560
while !s2.load(Ordering::Relaxed) {
// hlx:1561
let _ = std::fs::write(r2.join("flicker"), b"x");
// hlx:1562
let _ = std::fs::remove_file(r2.join("flicker"));
// hlx:1563
let _ = std::fs::write(r2.join("sub").join("flicker2"), b"x");
// hlx:1564
let _ = std::fs::remove_file(r2.join("sub").join("flicker2"));
// hlx:1565
}
// hlx:1566
});
// hlx:1567
let policy = pol(&["base-a", "sub", "sub/base-b"]).json();
// hlx:1568
let mut snapshots = 0;
// hlx:1569
for _ in 0..40 {
// hlx:1570
let o = env.exec_raw(
&[
"check",
"observe",
"--root",
r.to_str().unwrap(),
"--input",
"-",
],
policy.as_bytes(),
&[],
false,
);
// hlx:1571
let j = observed(&o);
// hlx:1572
if sf(&j, "validity") == "observed_snapshot" {
// hlx:1573
snapshots += 1;
// hlx:1574
let ps = paths(&j);
// hlx:1575
for must in ["base-a", "sub", "sub/base-b"] {
// hlx:1576
assert!(ps.contains(&must.to_string()), "{ps:?}");
// hlx:1577
}
// hlx:1578
assert!(
ps.iter().all(
|p| ["base-a", "sub", "sub/base-b", "flicker", "sub/flicker2"]
.contains(&p.as_str())
),
"{ps:?}"
);
// hlx:1579
let extras: Vec<&String> = ps.iter().filter(|p| p.contains("flicker")).collect();
// hlx:1580
if extras.is_empty() {
// hlx:1581
all_pass(&j);
// hlx:1582
} else {
// hlx:1583
assert_eq!(
verdicts(&j),
vec!["fail"],
"an observed extra must fail membership: {ps:?}"
);
// hlx:1584
assert_eq!(
fails(&j),
vec![extras.iter().map(|s| s.to_string()).min().unwrap()]
);
// hlx:1585
}
// hlx:1586
} else {
// hlx:1587
incomplete(&o);
// hlx:1588
}
// hlx:1589
}
// hlx:1590
stop.store(true, Ordering::Relaxed);
// hlx:1591
t.join().unwrap();
// hlx:1592
eprintln!("stress: {snapshots} of 40 observations completed as snapshots; this establishes nothing about race freedom");
// hlx:1593
}
// hlx:1594
// ---------------------------------------------------------------- explicitly not exercised through the CLI
// hlx:1595
#[test]
// hlx:1596
#[ignore = "NOT EXERCISED: mutation between the two traversal passes needs the internal test seam; the CLI cannot inject it"]
// hlx:1597
fn mutation_between_the_two_passes_abstains() {
// hlx:1598
panic!("NOT EXERCISED: needs an internal seam between passes (docs/check-observation-wire.md, Race and root policy)");
// hlx:1599
}
// hlx:1600
#[test]
// hlx:1601
#[ignore = "NOT IMPLEMENTED in this seam: metadata/content fingerprints, grant/root fingerprints and receipts are later M2 substeps"]
// hlx:1602
fn fingerprints_and_receipts_are_recorded() {
// hlx:1603
panic!("NOT IMPLEMENTED: fingerprints and receipt persistence are explicitly absent from the first seam");
// hlx:1604
}
// hlx:1605
#[test]
// hlx:1606
#[ignore = "NOT EXERCISED: an untrusted or racing context cannot be created through the CLI; only the trusted_quiescent_staging abstention is exercised"]
// hlx:1607
fn hostile_replacement_cannot_escape_the_root() {
// hlx:1608
panic!("NOT EXERCISED: needs descriptor-relative enumeration evidence or the internal race seam");
// hlx:1609
}
// hlx:1610
// docs/check-observation-wire.md: reject symlink components from the root through descendants. A link in an
// hlx:1611
// ANCESTOR of the root (not only the root itself) must not yield a snapshot, and must not disclose its target.
// hlx:1612
#[test]
// hlx:1613
fn a_symlink_in_an_ancestor_of_the_root_is_rejected_without_disclosing_the_target() {
// hlx:1614
let env = Env::new("ancestor");
// hlx:1615
let stage = env.root.join("stage");
// hlx:1616
let real = stage.join("REAL_TARGET_731");
// hlx:1617
std::fs::create_dir_all(real.join("release").join("sub")).unwrap();
// hlx:1618
std::fs::write(real.join("release").join("ok.txt"), b"x").unwrap();
// hlx:1619
std::fs::write(real.join("release").join("sub").join("deep.txt"), b"x").unwrap();
// hlx:1620
let alias = stage.join("alias");
// hlx:1621
std::os::unix::fs::symlink(&real, &alias).unwrap();
// hlx:1622
// one more level: alias2 -> stage/hop, hop/inner -> real
// hlx:1623
let hop = stage.join("hop");
// hlx:1624
std::fs::create_dir_all(&hop).unwrap();
// hlx:1625
std::os::unix::fs::symlink(&real, hop.join("inner")).unwrap();
// hlx:1626
let alias2 = stage.join("alias2");
// hlx:1627
std::os::unix::fs::symlink(&hop, &alias2).unwrap();
// hlx:1628
// a relative link in the middle of the path
// hlx:1629
let rel = stage.join("rel_alias");
// hlx:1630
std::os::unix::fs::symlink("REAL_TARGET_731", &rel).unwrap();
// hlx:1631
let policy = pol(&["ok.txt", "sub", "sub/deep.txt"]).json();
// hlx:1632
// control: the real path works
// hlx:1633
snapshot_ok(&env.observe(&real.join("release"), &policy));
// hlx:1634
for (name, root) in [
// hlx:1635
("ancestor link", alias.join("release")),
// hlx:1636
(
"two-level ancestor link",
alias2.join("inner").join("release"),
),
// hlx:1637
("relative ancestor link", rel.join("release")),
// hlx:1638
(
"link then subdirectory root",
alias.join("release").join("sub"),
),
// hlx:1639
] {
// hlx:1640
let o = env.observe(&root, &policy);
// hlx:1641
not_snapshot(&o, name);
// hlx:1642
let t = o.text();
// hlx:1643
assert!(
!t.contains("REAL_TARGET_731"),
"{name}: the link target must not be disclosed: {}",
trunc(&t)
);
// hlx:1644
assert!(
!t.contains("deep.txt") && !t.contains("ok.txt"),
"{name}: nothing beneath the link may be read: {}",
trunc(&t)
);
// hlx:1645
// the same holds with the quiescence assumption absent
// hlx:1646
let o = env.observe(&root, &pol(&["ok.txt"]).assum(None).json());
// hlx:1647
not_snapshot(&o, name);
// hlx:1648
assert!(!o.text().contains("REAL_TARGET_731"), "{name}");
// hlx:1649
}
// hlx:1650
}
// hlx:1651
// The 64 KiB output bound holds on every branch, not only complete observations: a huge policy scope may be
// hlx:1652
// rejected with a structured limit error, but never produces an oversized result and never a silently altered scope.
// hlx:1653
#[test]
// hlx:1654
fn the_output_bound_holds_on_every_branch_including_incomplete_and_error_paths() {
// hlx:1655
let env = Env::new("outbound");
// hlx:1656
let good = env.dir("good");
// hlx:1657
put_file(&good, "a");
// hlx:1658
let hostile = hostile_tree(&env, "hostile");
// hlx:1659
let many = env.dir("many");
// hlx:1660
for i in 0..20 {
// hlx:1661
put_file(&many, &format!("f{i}"));
// hlx:1662
}
// hlx:1663
let file_root = env.put("not_a_dir", b"x");
// hlx:1664
let gone = env.root.join("stage").join("missing");
// hlx:1665
let link_root = env.root.join("stage").join("rootlink");
// hlx:1666
std::os::unix::fs::symlink(&good, &link_root).unwrap();
// hlx:1667
let on = "{\"trusted_quiescent_staging\":true}";
// hlx:1668
// (branch, root, assumptions, limits, allowed)
// hlx:1669
let branches: Vec<(&str, PathBuf, Option<&str>, Option<&str>, Vec<&str>)> = vec![
// hlx:1670
("observed", good.clone(), Some(on), None, vec!["a"]),
// hlx:1671
("observed with extra", good.clone(), Some(on), None, vec![]),
// hlx:1672
("assumption omitted", good.clone(), None, None, vec!["a"]),
// hlx:1673
(
"assumption false",
good.clone(),
Some("{\"trusted_quiescent_staging\":false}"),
None,
vec![],
),
// hlx:1674
(
"assumption omitted, root missing",
gone.clone(),
None,
None,
vec![],
),
// hlx:1675
("root missing", gone.clone(), Some(on), None, vec![]),
// hlx:1676
("root is a file", file_root.clone(), Some(on), None, vec![]),
// hlx:1677
(
"root is a symlink",
link_root.clone(),
Some(on),
None,
vec![],
),
// hlx:1678
(
"symlink inside",
hostile.clone(),
Some(on),
None,
vec!["ok.txt"],
),
// hlx:1679
(
"assumption omitted, hostile",
hostile.clone(),
None,
None,
vec![],
),
// hlx:1680
(
"entry budget",
many.clone(),
Some(on),
Some("{\"max_entries\":3}"),
vec![],
),
// hlx:1681
(
"depth budget",
many.clone(),
Some(on),
Some("{\"max_depth\":0}"),
vec![],
),
// hlx:1682
(
"byte budget",
many.clone(),
Some(on),
Some("{\"max_inventory_bytes\":10}"),
vec![],
),
// hlx:1683
];
// hlx:1684
for n in [
1_000usize, 20_000, 60_000, 64_000, 65_000, 65_400, 66_000, 90_000, 300_000,
] {
// hlx:1685
let v = "p".repeat(n);
// hlx:1686
let scope = format!("{{\"project\":\"{v}\"}}");
// hlx:1687
for (name, root, assum, limits, allowed) in &branches {
// hlx:1688
let mut p = pol(allowed).scope(&scope).assum(*assum);
// hlx:1689
if let Some(l) = limits {
// hlx:1690
p = p.limits(l);
// hlx:1691
}
// hlx:1692
let o = env.observe(root, &p.json());
// hlx:1693
assert!(
o.out.len() <= 65_537,
"{name} with a {n}-char scope produced {} bytes",
o.out.len()
);
// hlx:1694
match o.code {
// hlx:1695
Some(2) => err(&o, &format!("{name} scope {n}")),
// hlx:1696
Some(0) => {
// hlx:1697
let j = observed(&o);
// hlx:1698
// anything that reports a scope must report it exactly
// hlx:1699
for holder in std::iter::once(&j).chain(checks(&j).iter().map(|_| &j)) {
// hlx:1700
if let Some(s) = holder.get("scope") {
// hlx:1701
let got = pairs_of(s);
// hlx:1702
assert!(
got.is_empty()
|| got == vec![("project".to_string(), v.clone())],
"{name}: scope {n} altered"
);
// hlx:1703
}
// hlx:1704
}
// hlx:1705
for c in checks(&j) {
// hlx:1706
assert_eq!(
pairs_of(c.get("scope").unwrap()),
vec![("project".to_string(), v.clone())],
"{name}: check scope {n} altered"
);
// hlx:1707
}
// hlx:1708
}
// hlx:1709
other => panic!("{name} scope {n}: unexpected exit {other:?}"),
// hlx:1710
}
// hlx:1711
}
// hlx:1712
}
// hlx:1713
// ordinary scope sizes must still be accepted where the branch itself is valid
// hlx:1714
for n in [1_000usize, 20_000] {
// hlx:1715
let v = "p".repeat(n);
// hlx:1716
let o = env.observe(
&good,
&pol(&["a"])
.scope(&format!("{{\"project\":\"{v}\"}}"))
.json(),
);
// hlx:1717
let j = snapshot_ok(&o);
// hlx:1718
for c in checks(&j) {
// hlx:1719
assert_eq!(
pairs_of(c.get("scope").unwrap()),
vec![("project".to_string(), v.clone())]
);
// hlx:1720
}
// hlx:1721
}
// hlx:1722
}
// hlx:1723
fn pairs_of(j: &J) -> Vec<(String, String)> {
// hlx:1724
match j {
// hlx:1725
J::Obj(v) => {
// hlx:1726
let mut r: Vec<(String, String)> = v
.iter()
.map(|(k, x)| (k.clone(), x.as_str().expect("string").to_string()))
.collect();
// hlx:1727
r.sort();
// hlx:1728
r
// hlx:1729
}
// hlx:1730
other => panic!("expected an object, got {}", to_s(other)),
// hlx:1731
}
// hlx:1732
}
// hlx:1733
// Spelling a symlink root with trailing slashes or dot components must not turn it into a traversal, and a root path
// hlx:1734
// carrying `.` or `..` components is not a plain absolute root: reject or abstain, never observe through it.
// hlx:1735
#[test]
// hlx:1736
fn root_spellings_cannot_launder_a_symlink_or_a_noncanonical_path_into_a_snapshot() {
// hlx:1737
let env = Env::new("rootspell");
// hlx:1738
let stage = env.root.join("stage");
// hlx:1739
let real = stage.join("REAL_TARGET_731");
// hlx:1740
std::fs::create_dir_all(real.join("sub")).unwrap();
// hlx:1741
std::fs::write(real.join("ok.txt"), b"x").unwrap();
// hlx:1742
std::fs::write(real.join("sub").join("deep.txt"), b"x").unwrap();
// hlx:1743
let link = stage.join("link");
// hlx:1744
std::os::unix::fs::symlink(&real, &link).unwrap();
// hlx:1745
let alias = stage.join("alias");
// hlx:1746
std::os::unix::fs::symlink(&stage, &alias).unwrap();
// hlx:1747
let clean = env.dir("clean");
// hlx:1748
put_file(&clean, "ok.txt");
// hlx:1749
put_file(&clean, "sub/deep.txt");
// hlx:1750
let policy = pol(&["ok.txt", "sub", "sub/deep.txt"]).json();
// hlx:1751
let run = |root: &str| {
env.exec(
&["check", "observe", "--root", root, "--input", "-"],
policy.as_bytes(),
)
};
// hlx:1752
let s = stage.to_str().unwrap();
// hlx:1753
// direct positive control: the plain clean root observes exactly
// hlx:1754
let j = snapshot_ok(&run(&format!("{s}/clean")));
// hlx:1755
assert_eq!(paths(&j), vec!["ok.txt", "sub", "sub/deep.txt"]);
// hlx:1756
all_pass(&j);
// hlx:1757
// a symlink root in every spelling: never a traversal, never a target disclosure
// hlx:1758
for spelling in [
// hlx:1759
format!("{s}/link"),
// hlx:1760
format!("{s}/link/"),
// hlx:1761
format!("{s}/link//"),
// hlx:1762
format!("{s}/link///"),
// hlx:1763
format!("{s}/link/."),
// hlx:1764
format!("{s}/link/./"),
// hlx:1765
format!("{s}/link/./."),
// hlx:1766
format!("{s}/link//."),
// hlx:1767
format!("{s}/alias/REAL_TARGET_731"),
// hlx:1768
format!("{s}/alias/clean"),
// hlx:1769
format!("{s}/alias/./clean"),
// hlx:1770
format!("{s}/alias//clean"),
// hlx:1771
format!("{s}/alias/clean/"),
// hlx:1772
format!("{s}/alias/clean/."),
// hlx:1773
] {
// hlx:1774
let o = run(&spelling);
// hlx:1775
not_snapshot(&o, &spelling);
// hlx:1776
let t = o.text();
// hlx:1777
assert!(
!t.contains("deep.txt") && !t.contains("ok.txt"),
"{spelling}: nothing beneath a link may be read: {}",
trunc(&t)
);
// hlx:1778
assert!(
!t.contains("REAL_TARGET_731") || spelling.contains("REAL_TARGET_731"),
"{spelling}: the link target must not be disclosed: {}",
trunc(&t)
);
// hlx:1779
}
// hlx:1780
// `.` and `..` components make the root path non-canonical: never a snapshot
// hlx:1781
for spelling in [
// hlx:1782
format!("{s}/./clean"),
// hlx:1783
format!("{s}/clean/./"),
// hlx:1784
format!("{s}/clean/."),
// hlx:1785
format!("{s}/./clean/./"),
// hlx:1786
format!("{s}/clean/../clean"),
// hlx:1787
format!("{s}/clean/sub/.."),
// hlx:1788
format!("{s}/../stage/clean"),
// hlx:1789
format!("{s}/clean/.."),
// hlx:1790
format!("{}/./stage/clean", env.root.display()),
// hlx:1791
format!("{}/stage/../stage/clean", env.root.display()),
// hlx:1792
] {
// hlx:1793
not_snapshot(&run(&spelling), &spelling);
// hlx:1794
}
// hlx:1795
// repeated and trailing separators on a real directory: either rejected, or the exact same observation
// hlx:1796
for spelling in [
format!("{s}//clean"),
format!("{s}/clean/"),
format!("{s}/clean//"),
format!("{}//stage/clean", env.root.display()),
] {
// hlx:1797
let o = run(&spelling);
// hlx:1798
match o.code {
// hlx:1799
Some(2) => err(&o, &spelling),
// hlx:1800
Some(0) => {
// hlx:1801
let j = observed(&o);
// hlx:1802
if sf(&j, "validity") == "observed_snapshot" {
// hlx:1803
assert_eq!(
paths(&j),
vec!["ok.txt", "sub", "sub/deep.txt"],
"{spelling}"
);
// hlx:1804
}
// hlx:1805
}
// hlx:1806
other => panic!("{spelling}: unexpected exit {other:?}"),
// hlx:1807
}
// hlx:1808
}
// hlx:1809
// and the same spellings without the quiescence assumption read nothing
// hlx:1810
for spelling in [
format!("{s}/link/"),
format!("{s}/./clean"),
format!("{s}/clean"),
] {
// hlx:1811
let o = env.exec(
&["check", "observe", "--root", &spelling, "--input", "-"],
pol(&["ok.txt"]).assum(None).json().as_bytes(),
);
// hlx:1812
if o.code == Some(0) {
// hlx:1813
assert_eq!(sf(&observed(&o), "validity"), "incomplete", "{spelling}");
// hlx:1814
} else {
// hlx:1815
err(&o, &spelling);
// hlx:1816
}
// hlx:1817
}
// hlx:1818
}
// hlx:1819
}