ostrya 0.19.1

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

mod common;

use std::path::Path;
use std::process::Command;
use std::sync::Arc;

use common::modes::{WRITABLE, build_tree, repo_of};
use common::{
    ThreadRecorder, TmpDir, anyone, fixture_root, ostree_available, ostree_supports_ed25519,
    read_access,
};
use ostrya::base64;
use ostrya::{
    AdvertisedDelta, Checksum, DeltaOptions, Ed25519Signer, Ed25519Verifier, Ref, RefSelector,
    Repo, RepoMode, Summary, SummaryOptions, Value,
};
use ostrya_rt::block_on;

/// The fixed epoch in the `last-modified` value of both golden summaries.
///
/// `generate.sh` patches this epoch into the golden summaries. It is also the
/// timestamp of the collection anchor commit.
const FIXED_EPOCH: u64 = 1_700_000_000;
/// The collection id of the `summary-collection` fixture.
const COLLECTION_ID: &str = "org.ostrya.Test";
/// The `ostree-metadata` anchor commit of the collection fixture.
///
/// The `ostree` command wrote this commit in the first generation, with no
/// parent and with the timestamp `FIXED_EPOCH`.
const ANCHOR_COMMIT: &str = "04fd8792152380dd12ef240cda008ef098407791011c01b3dd4f75f9964d6068";

/// A fixed ed25519 keypair for sign and verify round trips.
///
/// The keypair comes from `sign_ed25519.rs`.
const SECRET_B64: &str =
    "o74ME/dmhvDeYf64dDJQY8kX2piK0M/nyIRWVi30i6DCOzRsHVcvgYToz6zOb5OvK/v8nH6KfLR3dfdsn6ZSyQ==";
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";

/// Copies a directory tree with its attributes (`cp -a`).
fn copy_tree(from: &Path, to: &Path) {
    let status = Command::new("cp")
        .args(["-a"])
        .arg(from)
        .arg(to)
        .status()
        .expect("run cp");
    assert!(status.success(), "cp -a {from:?} {to:?} failed");
}

/// Copies the `repo/` of a fixture into a new writable temp directory.
///
/// Returns the temp directory and the path of the copy.
fn writable_fixture(fixture: &str, tag: &str) -> (TmpDir, std::path::PathBuf) {
    let tmp = TmpDir::new(tag);
    let repo = tmp.path().join("repo");
    copy_tree(&fixture_root().join(fixture).join("repo"), &repo);
    (tmp, repo)
}

#[test]
fn plain_summary_is_byte_identical_to_the_tool() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-plain");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH),
            metadata_commit_timestamp: None,
            additional_metadata: Vec::new(),
            auth_items_only: false,
            root_summary_only: false,
        })
        .await
        .unwrap();

        let got = repo.read_summary().await.unwrap().expect("summary written");
        let want = std::fs::read(fixture_root().join("summary").join("summary")).unwrap();
        assert_eq!(
            got, want,
            "the port's summary must be byte-identical to the tool's"
        );
    });
}

#[test]
fn regenerate_removes_a_stale_signature() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-stale-sig");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH),
            metadata_commit_timestamp: None,
            additional_metadata: Vec::new(),
            auth_items_only: false,
            root_summary_only: false,
        })
        .await
        .unwrap();
        repo.sign_summary(&Ed25519Signer::from_base64(SECRET_B64).unwrap())
            .await
            .unwrap();
        assert!(repo.read_summary_signature().await.unwrap().is_some());

        // A new summary makes the old signature invalid, so regeneration
        // removes it.
        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH),
            metadata_commit_timestamp: None,
            additional_metadata: Vec::new(),
            auth_items_only: false,
            root_summary_only: false,
        })
        .await
        .unwrap();
        assert!(
            repo.read_summary_signature().await.unwrap().is_none(),
            "regeneration must drop a stale summary.sig"
        );
    });
}

#[test]
fn collection_summary_and_anchor_match_the_tool() {
    let (_tmp, repo_dir) = writable_fixture("summary-collection", "summary-collection");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        assert_eq!(repo.config().collection_id(), Some(COLLECTION_ID));

        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH),
            metadata_commit_timestamp: Some(FIXED_EPOCH),
            additional_metadata: Vec::new(),
            auth_items_only: false,
            root_summary_only: false,
        })
        .await
        .unwrap();

        // ostrya generated the anchor commit. Its checksum matches the commit
        // that the `ostree` command wrote.
        let anchor = repo
            .resolve_rev("ostree-metadata", false)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(
            anchor.to_hex(),
            ANCHOR_COMMIT,
            "the ostree-metadata anchor commit must match the tool's"
        );

        let got = repo.read_summary().await.unwrap().expect("summary written");
        let want =
            std::fs::read(fixture_root().join("summary-collection").join("summary")).unwrap();
        assert_eq!(
            got, want,
            "the port's collection summary must be byte-identical to the tool's"
        );
    });
}

#[test]
fn sign_and_verify_round_trip() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-sign");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH),
            metadata_commit_timestamp: None,
            additional_metadata: Vec::new(),
            auth_items_only: false,
            root_summary_only: false,
        })
        .await
        .unwrap();

        repo.sign_summary(&Ed25519Signer::from_base64(SECRET_B64).unwrap())
            .await
            .unwrap();

        let public = base64::decode(PUBLIC_B64).unwrap();
        let trusted = Ed25519Verifier::new([public], Vec::<Vec<u8>>::new()).unwrap();
        let outcome = repo.verify_summary(&[Arc::new(trusted)]).await.unwrap();
        assert!(outcome.valid, "a signed summary must verify with the key");

        let wrong = Ed25519Verifier::new([vec![0u8; 32]], Vec::<Vec<u8>>::new()).unwrap();
        let outcome = repo.verify_summary(&[Arc::new(wrong)]).await.unwrap();
        assert!(!outcome.valid, "a foreign key must not verify the summary");
    });
}

/// The verification of the summary reads at most 64 signatures under the key
/// of one engine. A summary with 64 signatures of the trusted key verifies. A
/// 65th signature fails the verification.
#[test]
fn a_summary_with_more_than_64_signatures_of_one_engine_is_refused() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-sign-limit");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH),
            metadata_commit_timestamp: None,
            additional_metadata: Vec::new(),
            auth_items_only: false,
            root_summary_only: false,
        })
        .await
        .unwrap();
        let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
        let public = base64::decode(PUBLIC_B64).unwrap();
        let trusted: Arc<dyn ostrya::Verifier> =
            Arc::new(Ed25519Verifier::new([public], Vec::<Vec<u8>>::new()).unwrap());
        repo.sign_summary_all(&[&signer as &dyn ostrya::Signer; 64])
            .await
            .unwrap();
        let outcome = repo
            .verify_summary(std::slice::from_ref(&trusted))
            .await
            .unwrap();
        assert!(outcome.valid);
        assert_eq!(outcome.signatures.len(), 64);

        repo.sign_summary(&signer).await.unwrap();
        let err = repo
            .verify_summary(std::slice::from_ref(&trusted))
            .await
            .unwrap_err();
        assert!(
            matches!(&err, ostrya::Error::Signature(m)
                if m == "the signature dict holds more than 64 signatures under \
                         'ostree.sign.ed25519'"),
            "{err}"
        );
    });
}

/// `Repo::verify_summary` runs the verifiers on the blocking pool, so a
/// verifier that works in the call does not hold the async executor.
#[test]
fn verify_summary_runs_the_verifiers_on_the_blocking_pool() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-pool");
    let recorder = ThreadRecorder::new("ostree.sign.ed25519");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH),
            metadata_commit_timestamp: None,
            additional_metadata: Vec::new(),
            auth_items_only: false,
            root_summary_only: false,
        })
        .await
        .unwrap();
        repo.sign_summary(&Ed25519Signer::from_base64(SECRET_B64).unwrap())
            .await
            .unwrap();
        let outcome = repo
            .verify_summary(&[Arc::new(recorder.clone())])
            .await
            .unwrap();
        assert!(outcome.valid);
    });
    recorder.assert_one_foreign_call();
}

/// The gate in the reverse direction: the `ostree` command verifies a summary
/// that ostrya generated and signed.
///
/// `sign_and_verify_round_trip` tests the refusal of a wrong key with the
/// `verify_summary` of ostrya. The `ostree` command keeps a summary cache. A
/// second verification under a different key in the same test is then not
/// reliable, so this test does not assert it.
#[test]
fn tool_verifies_a_port_signed_summary() {
    if !ostree_supports_ed25519() {
        eprintln!("skipping: ostree tool has no ed25519 engine");
        return;
    }
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-tool-verify");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH),
            metadata_commit_timestamp: None,
            additional_metadata: Vec::new(),
            auth_items_only: false,
            root_summary_only: false,
        })
        .await
        .unwrap();
        repo.sign_summary(&Ed25519Signer::from_base64(SECRET_B64).unwrap())
            .await
            .unwrap();
    });

    let url = format!("file://{}", repo_dir.display());
    let add = |name: &str, key: &str| {
        let status = Command::new("ostree")
            .arg(format!("--repo={}", repo_dir.display()))
            .args(["remote", "add", name, &url, "--no-gpg-verify"])
            .arg(format!("--sign-verify=ed25519=inline:{key}"))
            .status()
            .expect("run ostree remote add");
        assert!(status.success(), "ostree remote add {name} failed");
    };
    let remote_summary = |name: &str| {
        Command::new("ostree")
            .arg(format!("--repo={}", repo_dir.display()))
            .args(["remote", "summary", name])
            .output()
            .expect("run ostree remote summary")
            .status
            .success()
    };

    add("good", PUBLIC_B64);
    assert!(
        remote_summary("good"),
        "the tool must verify a summary the port signed"
    );
}

/// A repository that holds static deltas advertises them in its summary.
///
/// `ostree.static-deltas` maps the name of each delta to the SHA-256 of its
/// superblock. The key is between `tombstone-commits` and `indexed-deltas`.
/// The `ostree` command was observed to write the key at this position.
#[test]
fn the_summary_advertises_the_deltas_the_repository_holds() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-deltas");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();

        // Without a delta the key is absent.
        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH),
            metadata_commit_timestamp: None,
            additional_metadata: Vec::new(),
            auth_items_only: false,
            root_summary_only: false,
        })
        .await
        .unwrap();
        let bytes = repo.read_summary().await.unwrap().unwrap();
        let summary = Summary::parse(&bytes).unwrap();
        assert!(summary.metadata_value("ostree.static-deltas").is_none());
        assert_eq!(summary.static_deltas().unwrap(), []);

        // One delta of each shape: from scratch, and from a source commit.
        let refs = repo.list_refs(None).await.unwrap();
        let (_, to) = refs.first().expect("the fixture holds a ref");
        let (_, from) = refs.get(1).expect("the fixture holds a second ref");
        let opts = DeltaOptions {
            timestamp: Some(FIXED_EPOCH),
            ..DeltaOptions::default()
        };
        let scratch_dir = repo.generate_static_delta(None, to, &opts).await.unwrap();
        let from_to_dir = repo
            .generate_static_delta(Some(from), to, &opts)
            .await
            .unwrap();
        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH),
            metadata_commit_timestamp: None,
            additional_metadata: Vec::new(),
            auth_items_only: false,
            root_summary_only: false,
        })
        .await
        .unwrap();

        let bytes = repo.read_summary().await.unwrap().unwrap();
        let summary = Summary::parse(&bytes).unwrap();
        let map = summary
            .metadata_value("ostree.static-deltas")
            .expect("the summary advertises the deltas");
        // The map names each delta of the repository under the digest of its
        // own superblock.
        let advertised = |name: &str| {
            map.dict_get(name)
                .and_then(Value::as_variant)
                .and_then(|(_, value)| value.as_bytes())
                .unwrap_or_else(|| panic!("the map must name delta {name}"))
        };
        let digest_of = |dir: &Path| {
            let superblock = std::fs::read(repo_dir.join(dir).join("superblock")).unwrap();
            Checksum::sha256(&superblock)
        };
        assert_eq!(
            advertised(&to.to_hex()),
            digest_of(&scratch_dir).as_bytes(),
            "the map must carry the from-scratch delta's superblock digest"
        );
        assert_eq!(
            advertised(&format!("{}-{}", from.to_hex(), to.to_hex())),
            digest_of(&from_to_dir).as_bytes(),
            "the map must carry the from-to delta's superblock digest"
        );

        // The parsed map gives the same two deltas, in delta-name order.
        let mut expected = vec![
            AdvertisedDelta {
                from: None,
                to: *to,
                superblock: digest_of(&scratch_dir),
            },
            AdvertisedDelta {
                from: Some(*from),
                to: *to,
                superblock: digest_of(&from_to_dir),
            },
        ];
        expected.sort_by_key(|delta| match delta.from {
            Some(from) => format!("{}-{}", from.to_hex(), delta.to.to_hex()),
            None => delta.to.to_hex(),
        });
        assert_eq!(summary.static_deltas().unwrap(), expected);

        // The neighbors of the key: the entries appear in the order that byte
        // identity needs.
        let keys: Vec<String> = match &summary.metadata {
            Value::Array(entries) => entries
                .iter()
                .filter_map(|entry| match entry {
                    Value::Tuple(fields) => fields.first()?.as_str().map(str::to_owned),
                    _ => None,
                })
                .collect(),
            other => panic!("the summary metadata is not a dict: {other:?}"),
        };
        let position = |key: &str| keys.iter().position(|k| k == key).expect(key);
        assert!(
            position("ostree.summary.tombstone-commits") < position("ostree.static-deltas")
                && position("ostree.static-deltas") < position("ostree.summary.indexed-deltas"),
            "{keys:?}"
        );
    });
}

/// The `ostree` command reads the delta map that ostrya wrote.
///
/// This interoperability is the purpose of the advertisement: a fetcher finds
/// the deltas through the map.
#[test]
fn the_tool_reads_the_port_written_delta_map() {
    if !ostree_available() {
        eprintln!("skipping: ostree tool not available");
        return;
    }
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-deltas-tool");
    let to = block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let refs = repo.list_refs(None).await.unwrap();
        let (_, to) = *refs.first().expect("the fixture holds a ref");
        repo.generate_static_delta(
            None,
            &to,
            &DeltaOptions {
                timestamp: Some(FIXED_EPOCH),
                ..DeltaOptions::default()
            },
        )
        .await
        .unwrap();
        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH),
            metadata_commit_timestamp: None,
            additional_metadata: Vec::new(),
            auth_items_only: false,
            root_summary_only: false,
        })
        .await
        .unwrap();
        to
    });

    let printed = Command::new("ostree")
        .arg(format!("--repo={}", repo_dir.display()))
        .args(["summary", "--print-metadata-key=ostree.static-deltas"])
        .output()
        .expect("run ostree summary");
    assert!(
        printed.status.success(),
        "the tool must read the port's summary: {}",
        String::from_utf8_lossy(&printed.stderr)
    );
    let text = String::from_utf8_lossy(&printed.stdout);
    assert!(
        text.contains(&to.to_hex()),
        "the tool must list the delta the port advertised: {text}"
    );
}

/// Returns a caller key paired with a string variant.
fn string_entry(key: &str, value: &str) -> (String, Value) {
    (
        key.to_owned(),
        Value::variant(ostrya::Type::Str, Value::Str(value.to_owned())),
    )
}

/// Returns the keys of the global metadata dict of a summary, in stored order.
fn metadata_keys(summary: &Summary) -> Vec<String> {
    summary
        .metadata
        .as_array()
        .expect("the summary metadata is a dict")
        .iter()
        .filter_map(|entry| entry.as_tuple()?.first()?.as_str().map(str::to_owned))
        .collect()
}

/// Regenerates the summary of `repo` at the fixed epoch and parses it.
///
/// `added` gives the caller keys.
async fn regenerate_with(repo: &Repo, added: Vec<(String, Value)>) -> Summary {
    repo.regenerate_summary(&SummaryOptions {
        last_modified: Some(FIXED_EPOCH),
        metadata_commit_timestamp: Some(FIXED_EPOCH),
        additional_metadata: added,
        auth_items_only: false,
        root_summary_only: false,
    })
    .await
    .unwrap();
    Summary::parse(&repo.read_summary().await.unwrap().unwrap()).unwrap()
}

/// The caller keys come after the standard entries, in first-occurrence order.
///
/// - A repeated key keeps its first position and its last value.
/// - The summary keeps the empty key.
/// - If the writer writes a key in the same run, the key keeps the value of
///   the writer.
#[test]
fn caller_metadata_follows_the_standard_entries() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-added");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let summary = regenerate_with(
            &repo,
            vec![
                string_entry("b", "first"),
                string_entry("ostree.summary.mode", "x"),
                string_entry("", "empty"),
                string_entry("a", "only"),
                string_entry("b", "last"),
                string_entry("ostree.summary.last-modified", "y"),
            ],
        )
        .await;
        assert_eq!(
            metadata_keys(&summary),
            [
                "ostree.summary.mode",
                "ostree.summary.last-modified",
                "ostree.summary.tombstone-commits",
                "ostree.summary.indexed-deltas",
                "b",
                "",
                "a",
            ]
        );
        let text = |key: &str| {
            summary
                .metadata_value(key)
                .and_then(Value::as_str)
                .map(str::to_owned)
        };
        assert_eq!(text("b").as_deref(), Some("last"));
        assert_eq!(text("").as_deref(), Some("empty"));
        assert_eq!(text("ostree.summary.mode").as_deref(), Some("archive-z2"));
        assert_eq!(
            summary
                .metadata_value("ostree.summary.last-modified")
                .and_then(Value::as_u64)
                .map(u64::swap_bytes),
            Some(FIXED_EPOCH)
        );
    });
}

/// The summary keeps a caller key that the writer does not write in this run.
///
/// This is true for each key name. The test uses `ostree.summary.expires`, and
/// `ostree.static-deltas` in a repository that holds no delta.
#[test]
fn caller_metadata_keeps_keys_the_writer_does_not_write() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-added-kept");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let expires = (
            "ostree.summary.expires".to_owned(),
            Value::variant(ostrya::Type::U64, Value::U64(9)),
        );
        let summary = regenerate_with(
            &repo,
            vec![expires, string_entry("ostree.static-deltas", "none")],
        )
        .await;
        assert_eq!(
            summary
                .metadata_value("ostree.summary.expires")
                .and_then(Value::as_u64),
            Some(9)
        );
        assert_eq!(
            summary
                .metadata_value("ostree.static-deltas")
                .and_then(Value::as_str),
            Some("none")
        );
    });
}

/// A regeneration refuses a caller value that is not a variant before it
/// writes.
///
/// The summary does not change, and the collection anchor commit does not
/// advance.
#[test]
fn caller_metadata_that_is_no_variant_is_refused_first() {
    let (_tmp, repo_dir) = writable_fixture("summary-collection", "summary-added-bad");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        regenerate_with(&repo, Vec::new()).await;
        let before = repo.read_summary().await.unwrap();
        let anchor = repo.resolve_rev("ostree-metadata", false).await.unwrap();

        let err = repo
            .regenerate_summary(&SummaryOptions {
                last_modified: Some(FIXED_EPOCH + 1),
                metadata_commit_timestamp: Some(FIXED_EPOCH + 1),
                additional_metadata: vec![("bare".to_owned(), Value::U32(1))],
                auth_items_only: false,
                root_summary_only: false,
            })
            .await
            .unwrap_err();
        assert!(matches!(err, ostrya::Error::InvalidFormat(_)), "{err}");
        assert!(err.to_string().contains("'bare'"), "{err}");
        assert_eq!(repo.read_summary().await.unwrap(), before);
        assert_eq!(
            repo.resolve_rev("ostree-metadata", false).await.unwrap(),
            anchor
        );
    });
}

/// With no caller keys, the summary is byte-identical to the golden summary.
///
/// This is true for the plain fixture and for the collection fixture. The
/// `ostree` command wrote both golden summaries.
#[test]
fn no_caller_metadata_keeps_the_golden_bytes() {
    for fixture in ["summary", "summary-collection"] {
        let (_tmp, repo_dir) = writable_fixture(fixture, "summary-added-none");
        block_on(async {
            let repo = Repo::open(&repo_dir).await.unwrap();
            regenerate_with(&repo, Vec::new()).await;
            let got = repo.read_summary().await.unwrap().unwrap();
            let want = std::fs::read(fixture_root().join(fixture).join("summary")).unwrap();
            assert_eq!(got, want, "{fixture}");
        });
    }
}

/// In a collection repository, a regeneration refuses a caller key before it
/// writes.
///
/// The `ostree` command copies the caller keys into the `ostree-metadata`
/// anchor commit. ostrya does not reproduce this copy, so it refuses the key
/// and writes no anchor that differs from the anchor of the `ostree` command.
/// The summary, its signature, and the anchor ref do not change.
#[test]
fn caller_metadata_in_a_collection_repository_is_refused() {
    let (_tmp, repo_dir) = writable_fixture("summary-collection", "summary-added-collection");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        regenerate_with(&repo, Vec::new()).await;
        repo.sign_summary(&Ed25519Signer::from_base64(SECRET_B64).unwrap())
            .await
            .unwrap();
        let summary = repo.read_summary().await.unwrap();
        let signature = std::fs::read(repo_dir.join("summary.sig")).unwrap();
        let anchor = repo.resolve_rev("ostree-metadata", false).await.unwrap();

        let err = repo
            .regenerate_summary(&SummaryOptions {
                last_modified: Some(FIXED_EPOCH + 1),
                metadata_commit_timestamp: Some(FIXED_EPOCH + 1),
                additional_metadata: vec![string_entry("k", "v")],
                auth_items_only: false,
                root_summary_only: false,
            })
            .await
            .unwrap_err();
        assert!(matches!(err, ostrya::Error::Unsupported(_)), "{err}");
        assert_eq!(repo.read_summary().await.unwrap(), summary);
        assert_eq!(
            std::fs::read(repo_dir.join("summary.sig")).unwrap(),
            signature
        );
        assert_eq!(
            repo.resolve_rev("ostree-metadata", false).await.unwrap(),
            anchor
        );
    });
}

/// A signer that refuses to sign, for the test of a failed batch.
struct RefusingSigner;

impl ostrya::Signer for RefusingSigner {
    fn name(&self) -> &str {
        "ed25519"
    }

    fn metadata_key(&self) -> &str {
        "ostree.sign.ed25519"
    }

    fn sign<'a>(&'a self, _: &'a [u8]) -> ostrya::SignFuture<'a> {
        Box::pin(async { Err(ostrya::sign::Error::Signature("refused".into())) })
    }
}

/// One batch of signers writes the same `summary.sig` as one call for each
/// signer.
///
/// The batch signs in slice order. The entry of the dummy engine keeps the
/// position of its first signature.
#[test]
fn sign_summary_all_writes_what_one_call_per_signer_writes() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-sign-all");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        regenerate_with(&repo, Vec::new()).await;
        let ed25519 = Ed25519Signer::from_base64(SECRET_B64).unwrap();
        let dummy = ostrya::DummySigner::new("dummy-key");
        let signers: [&dyn ostrya::Signer; 3] = [&dummy, &ed25519, &ed25519];
        for signer in signers {
            repo.sign_summary(signer).await.unwrap();
        }
        let one_by_one = std::fs::read(repo_dir.join("summary.sig")).unwrap();

        regenerate_with(&repo, Vec::new()).await;
        repo.sign_summary_all(&signers).await.unwrap();
        let batch = std::fs::read(repo_dir.join("summary.sig")).unwrap();
        assert_eq!(batch, one_by_one);

        // An empty batch writes nothing.
        repo.sign_summary_all(&[]).await.unwrap();
        assert_eq!(std::fs::read(repo_dir.join("summary.sig")).unwrap(), batch);
    });
}

/// If a signer fails in the middle of a batch, `summary.sig` does not change.
///
/// The batch writes the file one time, after it makes all signatures.
#[test]
fn sign_summary_all_writes_nothing_when_a_signer_fails() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-sign-all-fail");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        regenerate_with(&repo, Vec::new()).await;
        let ed25519 = Ed25519Signer::from_base64(SECRET_B64).unwrap();
        repo.sign_summary(&ed25519).await.unwrap();
        let before = std::fs::read(repo_dir.join("summary.sig")).unwrap();

        let err = repo
            .sign_summary_all(&[&ed25519, &RefusingSigner, &ed25519])
            .await
            .unwrap_err();
        assert!(matches!(err, ostrya::Error::Signature(_)), "{err}");
        assert_eq!(std::fs::read(repo_dir.join("summary.sig")).unwrap(), before);
    });
}

/// Copies the collection fixture and sets `lock-timeout-secs=0` in its config.
fn collection_fixture_with_no_wait(tag: &str) -> (TmpDir, std::path::PathBuf) {
    let (tmp, repo_dir) = writable_fixture("summary-collection", tag);
    let config = repo_dir.join("config");
    let mut text = std::fs::read_to_string(&config).unwrap();
    text.push_str("lock-timeout-secs=0\n");
    std::fs::write(&config, text).unwrap();
    (tmp, repo_dir)
}

/// If no guard is held, a regeneration at `lock-timeout-secs=0` takes both
/// locks at the first attempt and refreshes the anchor.
#[test]
fn a_regeneration_with_no_guard_takes_its_locks_at_once() {
    let (_tmp, repo_dir) = collection_fixture_with_no_wait("summary-no-wait");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&SummaryOptions::default())
            .await
            .unwrap();
        let anchor = repo
            .resolve_ref_tip(&Ref::local("ostree-metadata"))
            .await
            .unwrap();
        assert!(anchor.is_some(), "the anchor was written");
        assert!(repo_dir.join("summary").exists());
    });
}

/// A regeneration waits for a held `UpdateGuard`.
///
/// At `lock-timeout-secs=0`, it fails with `LockTimeout` and writes no
/// summary, no anchor, and no ref.
#[test]
fn a_regeneration_waits_for_a_held_guard() {
    let (_tmp, repo_dir) = collection_fixture_with_no_wait("summary-guard");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let refs = common::file_inventory(&repo_dir, "refs");
        let objects = common::file_inventory(&repo_dir, "objects");
        let guard = repo.begin_update().await.unwrap();

        let err = repo
            .regenerate_summary(&SummaryOptions::default())
            .await
            .unwrap_err();
        assert!(
            matches!(err, ostrya::Error::LockTimeout { secs: 0 }),
            "{err}"
        );
        assert!(!repo_dir.join("summary").exists(), "no summary written");
        assert_eq!(common::file_inventory(&repo_dir, "refs"), refs);
        assert_eq!(common::file_inventory(&repo_dir, "objects"), objects);

        guard.finish().await.unwrap();
        repo.regenerate_summary(&SummaryOptions::default())
            .await
            .unwrap();
        assert!(repo_dir.join("summary").exists());
    });
}

/// A regeneration refuses a caller value that the dict cannot hold before it
/// takes a lock, so a held guard does not delay the refusal.
#[test]
fn a_refusal_comes_before_the_locks() {
    let (_tmp, repo_dir) = collection_fixture_with_no_wait("summary-guard-refusal");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let guard = repo.begin_update().await.unwrap();
        let err = repo
            .regenerate_summary(&SummaryOptions {
                additional_metadata: vec![("bare".to_owned(), Value::U32(1))],
                ..SummaryOptions::default()
            })
            .await
            .unwrap_err();
        assert!(matches!(err, ostrya::Error::InvalidFormat(_)), "{err}");
        guard.finish().await.unwrap();
    });
}

/// Returns the names of the refs that a ref listing holds, in stored order.
fn listed_names(listing: &[u8]) -> Vec<String> {
    Summary::parse(listing)
        .unwrap()
        .refs
        .into_iter()
        .map(|entry| entry.name)
        .collect()
}

/// Asserts that `bytes` are in normal form, so two equal values in such
/// bytes have equal bytes.
fn assert_normal_form(bytes: &[u8]) {
    let ty = ostrya::Type::parse("(a(s(taya{sv}))a{sv})").unwrap();
    let value = ostrya::from_bytes(&ty, bytes).unwrap();
    assert_eq!(ostrya_core::to_bytes(&ty, &value).unwrap(), bytes);
}

/// Adds the refs `a/b`, `a/bc`, `a/c/d`, `ab`, `x/y`, and the alias `x/al` of
/// `a/b` to the `summary` fixture. Returns the commits of `main` and `other`.
async fn add_prefix_refs(repo: &Repo) -> (Checksum, Checksum) {
    let refs = repo.list_refs(None).await.unwrap();
    let (main, other) = (refs[0].1, refs[1].1);
    assert_eq!((refs[0].0.as_str(), refs[1].0.as_str()), ("main", "other"));
    for (name, commit) in [
        ("a/b", main),
        ("a/bc", main),
        ("a/c/d", other),
        ("ab", other),
        ("x/y", other),
    ] {
        repo.set_ref_immediate(&Ref::local(name), Some(&commit))
            .await
            .unwrap();
    }
    repo.set_ref_alias_immediate(&Ref::local("x/al"), &Ref::local("a/b"))
        .await
        .unwrap();
    (main, other)
}

/// Parses `entries` as a selector.
fn selector(entries: &[&str]) -> RefSelector {
    RefSelector::parse(entries.iter().copied()).unwrap()
}

/// Builds the ref listing of the selector that `entries` give, with the
/// rights of an anonymous client under the implicit group.
async fn list(repo: &Repo, entries: &[&str]) -> Result<Vec<u8>, ostrya::Error> {
    repo.build_ref_listing(&selector(entries), None, &anyone())
        .await
        .map(|listing| listing.bytes)
}

/// Returns the names of `list_refs(None)` that the selector of `entries`
/// selects, sorted. This is the oracle of a listing. It holds in a
/// repository where each ref reads.
async fn oracle(repo: &Repo, entries: &[&str]) -> Vec<String> {
    let selector = selector(entries);
    let refs = repo.list_refs(None).await.unwrap();
    refs.into_iter()
        .map(|(name, _)| name)
        .filter(|name| selector.matches(name))
        .collect()
}

/// Copies the ref file `from` to `to`, below `refs/heads`, so the new ref
/// names the same commit. The call can create a name that no ref write
/// accepts.
fn copy_ref_file(repo_dir: &Path, from: &str, to: &str) {
    let heads = repo_dir.join("refs/heads");
    let target = heads.join(to);
    std::fs::create_dir_all(target.parent().unwrap()).unwrap();
    std::fs::copy(heads.join(from), target).unwrap();
}

/// A selector selects the refs that its patterns match. `a/*` takes one name
/// part and `a/**` takes one or more. A negative entry removes refs, and a
/// selector with no positive entry starts from each ref. The order of the
/// entries has no effect, so a positive `a/b` does not bring back a ref that
/// `!a/**` removes. Each set of entries lists the same names as the
/// matcher gives over `list_refs`, each ref one time.
///
/// The cases cover a pattern that is a ref file, a directory, an alias, a
/// dangling alias, or missing, and a pattern below a ref file, below an
/// alias, and below a missing directory. A pattern below a symlink to a
/// directory selects nothing, because a walk of the refs does not descend
/// into a symlink.
#[test]
fn a_ref_listing_selects_refs_by_pattern() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-patterns");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (main, _) = add_prefix_refs(&repo).await;
        let heads = repo_dir.join("refs/heads");
        std::os::unix::fs::symlink("absent", heads.join("x/dangling")).unwrap();
        let all = ["a/b", "a/bc", "a/c/d", "ab", "main", "other", "x/al", "x/y"];
        let cases: [(&[&str], Vec<&str>); 31] = [
            (&["a/b"], vec!["a/b"]),
            (&["main"], vec!["main"]),
            (&["a"], vec![]),
            (&["a/*"], vec!["a/b", "a/bc"]),
            (&["a/**"], vec!["a/b", "a/bc", "a/c/d"]),
            (&["ab"], vec!["ab"]),
            (&["a/**", "ab"], vec!["a/b", "a/bc", "a/c/d", "ab"]),
            (&["a/c/*"], vec!["a/c/d"]),
            (&["a/c"], vec![]),
            (&["a/*/d"], vec!["a/c/d"]),
            (&["a/**/d"], vec!["a/c/d"]),
            (&["a/*/c"], vec![]),
            (&["**/d"], vec!["a/c/d"]),
            (&["*/*"], vec!["a/b", "a/bc", "x/al", "x/y"]),
            (&["*"], vec!["ab", "main", "other"]),
            (&["**"], all.to_vec()),
            (&["*/y"], vec!["x/y"]),
            (&["x/**", "main"], vec!["main", "x/al", "x/y"]),
            (&["x/al"], vec!["x/al"]),
            (&["x/*"], vec!["x/al", "x/y"]),
            (&["x/dangling"], vec![]),
            (&[], all.to_vec()),
            (&["!a/**"], vec!["ab", "main", "other", "x/al", "x/y"]),
            (&["!a/**", "a/b"], vec![]),
            (&["a/b", "!a/**"], vec![]),
            (&["a/**", "!a/c/**"], vec!["a/b", "a/bc"]),
            (&["!*"], vec!["a/b", "a/bc", "a/c/d", "x/al", "x/y"]),
            (&["!**"], vec![]),
            (
                &["**", "!a/*", "!x/y"],
                vec!["a/c/d", "ab", "main", "other", "x/al"],
            ),
            (
                &["a/b", "a/b", "a/*", "a/**", "a/b"],
                vec!["a/b", "a/bc", "a/c/d"],
            ),
            (
                &[
                    "absent", "a/b/c", "main/x", "x/al/q", "absent/q", "*/*/*/*", "absent/*",
                ],
                vec![],
            ),
        ];
        for (entries, want) in cases {
            let listing = list(&repo, entries).await.unwrap();
            let names = listed_names(&listing);
            assert_eq!(names, want, "{entries:?}");
            assert_eq!(names, oracle(&repo, entries).await, "{entries:?}");
        }

        // The alias is listed under its own name, with the commit of its
        // target.
        let listing = list(&repo, &["x/al"]).await.unwrap();
        assert_eq!(Summary::parse(&listing).unwrap().lookup("x/al"), Some(main));

        // A walk reports a symlink to a directory as one entry. The alias
        // names no regular file, so the listing leaves it out, as the archive
        // view does not serve it, and `list_refs` leaves it out too. A
        // pattern below it selects nothing.
        std::os::unix::fs::symlink("a", heads.join("ln")).unwrap();
        assert!(repo.list_refs(Some("ln")).await.unwrap().is_empty());
        for (entries, want) in [
            (&["ln"][..], vec![]),
            (&["a/**", "ln"][..], vec!["a/b", "a/bc", "a/c/d"]),
            (&["*"][..], vec!["ab", "main", "other"]),
            (&["**"][..], all.to_vec()),
            (&[][..], all.to_vec()),
            (&["!a/**"][..], vec!["ab", "main", "other", "x/al", "x/y"]),
        ] {
            let listing = list(&repo, entries).await.unwrap();
            assert_eq!(listed_names(&listing), want, "{entries:?}");
        }
        for entries in [
            &["ln/*"][..],
            &["ln/**"][..],
            &["ln/b"][..],
            &["ln/*/d"][..],
        ] {
            let listing = list(&repo, entries).await.unwrap();
            assert_eq!(listed_names(&listing), Vec::<String>::new(), "{entries:?}");
        }
        let listing = list(&repo, &["ln/b", "ln/c", "a/c/**"]).await.unwrap();
        assert_eq!(listed_names(&listing), ["a/c/d"]);
        let listing = list(&repo, &["!ln"]).await.unwrap();
        assert_eq!(listed_names(&listing), all);
    });
}

/// A pattern with a part longer than 255 bytes, which no file name can have,
/// selects no ref, as an absent name does. This holds for a long first part,
/// a long last part, and a long part under a ref directory, with a literal
/// or with a wildcard before and after it.
#[test]
fn a_ref_listing_of_a_too_long_part_selects_nothing() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-long-part");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        add_prefix_refs(&repo).await;
        let long = "l".repeat(256);
        let absent = list(&repo, &["absent"]).await.unwrap();
        let only_a = list(&repo, &["a/**"]).await.unwrap();
        for pattern in [
            long.clone(),
            format!("a/{long}"),
            format!("{long}/b"),
            format!("*/{long}"),
            format!("{long}/*"),
            format!("a/*/{long}"),
        ] {
            let listing = list(&repo, &[pattern.as_str()]).await;
            assert_eq!(listing.unwrap(), absent, "{pattern}");
            let listing = list(&repo, &["a/**", pattern.as_str()]).await;
            assert_eq!(listing.unwrap(), only_a, "{pattern}");
        }
    });
}

/// A name that the ref-name rule refuses is still on disk. A wildcard
/// selects it, as `list_refs` lists it. No literal pattern can name it.
#[test]
fn a_ref_listing_enumerates_names_that_the_name_rule_refuses() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-refused-names");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        for odd in ["odd~1", "q/a b", "q/main^", ".hidden", "q/-dash"] {
            copy_ref_file(&repo_dir, "main", odd);
        }
        let odd = [".hidden", "odd~1", "q/-dash", "q/a b", "q/main^"];
        let listing = list(&repo, &["**", "!main", "!other"]).await.unwrap();
        assert_eq!(listed_names(&listing), odd);
        let listing = list(&repo, &["*", "!main", "!other"]).await.unwrap();
        assert_eq!(listed_names(&listing), [".hidden", "odd~1"]);
        let listing = list(&repo, &["q/*"]).await.unwrap();
        assert_eq!(listed_names(&listing), ["q/-dash", "q/a b", "q/main^"]);
        let listing = list(&repo, &["q/**", "!q/*"]).await.unwrap();
        assert_eq!(listed_names(&listing), Vec::<String>::new());
        assert_eq!(
            listed_names(&list(&repo, &[]).await.unwrap()),
            oracle(&repo, &[]).await
        );
        assert!(RefSelector::parse(["odd~1"]).is_err());
    });
}

/// Entries that overlap, repeat, or come in another order give one entry for
/// each ref and the same bytes. Two builds of one state give the same bytes.
#[test]
fn a_ref_listing_of_overlapping_patterns_is_deterministic() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-overlap");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        add_prefix_refs(&repo).await;
        let one = list(&repo, &["a/**"]).await.unwrap();
        for entries in [
            &["a/**", "a/*", "a/b", "a/c/d", "a/**"][..],
            &["a/c/d", "a/b", "a/bc", "a/**", "a/*/d"][..],
            &["**", "!ab", "!main", "!other", "!x/**"][..],
            &["!ab", "!x/**", "!main", "!other"][..],
        ] {
            let listing = list(&repo, entries).await.unwrap();
            assert_eq!(listing, one, "{entries:?}");
            assert_eq!(list(&repo, entries).await.unwrap(), listing);
        }
        let parsed = Summary::parse(&one).unwrap();
        let names: Vec<&str> = parsed.refs.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(names, ["a/b", "a/bc", "a/c/d"]);
    });
}

/// Each entry of a listing has the bytes of the entry of the same ref in the
/// summary. The listing is in normal form, so equal values are equal bytes.
#[test]
fn a_ref_listing_entry_has_the_bytes_of_the_summary_entry() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-entries");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        add_prefix_refs(&repo).await;
        let summary = regenerate_with(&repo, Vec::new()).await;
        for prefixes in [&[][..], &["a/**"][..], &["x/**", "other"][..]] {
            let listing = list(&repo, prefixes).await.unwrap();
            assert_normal_form(&listing);
            let parsed = Summary::parse(&listing).unwrap();
            assert!(!parsed.refs.is_empty(), "{prefixes:?}");
            for entry in &parsed.refs {
                let stored = summary
                    .refs
                    .iter()
                    .find(|stored| stored.name == entry.name)
                    .expect("the summary lists each listed ref");
                assert_eq!(entry, stored);
            }
        }
    });
}

/// The metadata of a listing holds the mode and, after an index pass, the
/// deltas that the index files advertise on the paths back from the listed
/// commits. A prefix that leaves a ref out leaves its deltas out. Two builds
/// of one state give the same bytes.
#[test]
fn a_ref_listing_advertises_the_indexed_deltas_of_its_commits() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-deltas");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let listing = list(&repo, &[]).await.unwrap();
        let parsed = Summary::parse(&listing).unwrap();
        assert_eq!(metadata_keys(&parsed), ["ostree.summary.mode"]);
        assert_eq!(
            parsed.metadata_value("ostree.summary.mode"),
            Some(&Value::Str("archive-z2".into()))
        );

        let refs = repo.list_refs(None).await.unwrap();
        let (main, other) = (refs[0].1, refs[1].1);
        let opts = DeltaOptions {
            timestamp: Some(FIXED_EPOCH),
            ..DeltaOptions::default()
        };
        for (from, to) in [(None, &main), (Some(&other), &main), (None, &other)] {
            repo.generate_static_delta(from, to, &opts).await.unwrap();
        }
        // The deltas have no index file yet, so the listing names none.
        let listing = list(&repo, &[]).await.unwrap();
        assert_eq!(
            metadata_keys(&Summary::parse(&listing).unwrap()),
            ["ostree.summary.mode"]
        );

        repo.reindex_static_deltas().await.unwrap();
        let summary = regenerate_with(&repo, Vec::new()).await;
        let listing = list(&repo, &[]).await.unwrap();
        assert_eq!(listing, list(&repo, &[]).await.unwrap());
        assert_normal_form(&listing);
        let parsed = Summary::parse(&listing).unwrap();
        assert_eq!(
            metadata_keys(&parsed),
            ["ostree.summary.mode", "ostree.static-deltas"]
        );
        // The map has the value of the summary map, so the same bytes.
        assert_eq!(
            parsed.metadata_value("ostree.static-deltas"),
            summary.metadata_value("ostree.static-deltas")
        );
        assert_eq!(parsed.static_deltas().unwrap().len(), 3);

        // `main` reaches the delta to `other` through its delta from `other`.
        let listing = list(&repo, &["main"]).await.unwrap();
        assert_eq!(
            Summary::parse(&listing).unwrap().static_deltas().unwrap(),
            summary.static_deltas().unwrap()
        );

        // `other` reaches its own delta alone.
        let listing = list(&repo, &["other"]).await.unwrap();
        let deltas = Summary::parse(&listing).unwrap().static_deltas().unwrap();
        assert_eq!(deltas.len(), 1);
        assert_eq!((deltas[0].from, deltas[0].to), (None, other));

        // No listed commit gives no delta map.
        let listing = list(&repo, &["absent"]).await.unwrap();
        assert_eq!(
            metadata_keys(&Summary::parse(&listing).unwrap()),
            ["ostree.summary.mode"]
        );
    });
}

/// The ref listing states `archive-z2` in each mode. In `archive` mode it
/// names the indexed delta, and a `delta-indexes` that is a regular file
/// fails it. In `bare-user` mode it names no delta and reads nothing under
/// `delta-indexes/`, so the same file does not fail it.
#[test]
fn a_ref_listing_names_deltas_in_archive_mode_alone() {
    let tmp = TmpDir::new("listing-modes");
    let src = build_tree(tmp.path());
    block_on(async {
        for mode in [RepoMode::Archive, RepoMode::BareUser] {
            let (path, repo, commit) = repo_of(tmp.path(), mode, &src).await;
            let opts = DeltaOptions {
                timestamp: Some(FIXED_EPOCH),
                ..DeltaOptions::default()
            };
            repo.generate_static_delta(None, &commit, &opts)
                .await
                .unwrap();
            repo.reindex_static_deltas().await.unwrap();
            let listing = Summary::parse(&list(&repo, &[]).await.unwrap()).unwrap();
            assert_eq!(
                listing.metadata_value("ostree.summary.mode"),
                Some(&Value::Str("archive-z2".into())),
                "{mode:?}"
            );
            if mode == RepoMode::Archive {
                assert_eq!(delta_names(&listing), [commit.to_hex()]);
            } else {
                assert_eq!(metadata_keys(&listing), ["ostree.summary.mode"]);
            }

            std::fs::remove_dir_all(path.join("delta-indexes")).unwrap();
            std::fs::write(path.join("delta-indexes"), b"").unwrap();
            let listing = list(&repo, &[]).await;
            if mode == RepoMode::Archive {
                assert!(
                    matches!(&listing, Err(ostrya::Error::InvalidFormat(m))
                        if m == "delta-indexes is not a directory"),
                    "{listing:?}"
                );
            } else {
                let listing = Summary::parse(&listing.unwrap()).unwrap();
                assert_eq!(metadata_keys(&listing), ["ostree.summary.mode"]);
            }
        }
    });
}

/// A repository with a collection id names it in the listing metadata after
/// the mode. The listing holds no mirror ref and no collection map. The build
/// takes no lock, so a held guard does not delay it.
#[test]
fn a_ref_listing_names_the_collection_and_no_mirror_ref() {
    let (_tmp, repo_dir) = collection_fixture_with_no_wait("listing-collection");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (_, commit) = repo.list_refs(None).await.unwrap()[0].clone();
        repo.set_ref_immediate(
            &ostrya::Ref::collection("org.ostrya.Other", "mirrored"),
            Some(&commit),
        )
        .await
        .unwrap();
        let summary = regenerate_with(&repo, Vec::new()).await;
        assert_eq!(summary.collection_map().unwrap().len(), 1);

        let guard = repo.begin_update().await.unwrap();
        let listing = list(&repo, &[]).await.unwrap();
        guard.finish().await.unwrap();
        let parsed = Summary::parse(&listing).unwrap();
        assert_eq!(
            metadata_keys(&parsed),
            ["ostree.summary.mode", "ostree.summary.collection-id"]
        );
        assert_eq!(
            parsed.metadata_value("ostree.summary.collection-id"),
            Some(&Value::Str(COLLECTION_ID.into()))
        );
        assert_eq!(listed_names(&listing), ["main", "ostree-metadata"]);
    });
}

/// The walk reads no ref outside the subtrees that the patterns can match,
/// and no ref that a negative entry removes. A ref file with no checksum, and
/// a ref that names a missing commit, fail only a listing that selects them.
#[test]
fn a_ref_listing_reads_only_the_refs_that_it_selects() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-bad-refs");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        add_prefix_refs(&repo).await;
        let missing = Checksum::from_bytes([7; 32]);
        repo.set_ref_immediate(&Ref::local("broken"), Some(&missing))
            .await
            .unwrap();
        let heads = repo_dir.join("refs/heads");
        std::fs::write(heads.join("garbage"), "no checksum\n").unwrap();
        std::fs::write(heads.join("a/c/bad"), "no checksum\n").unwrap();

        // A listing that selects a bad ref fails. A ref file with no
        // checksum is `Core`, and a ref with a missing commit fails later.
        for entries in [
            &[][..],
            &["*"][..],
            &["**"][..],
            &["garbage"][..],
            &["garbage", "main"][..],
            &["a/**"][..],
            &["a/c/*"][..],
            &["a/c/bad"][..],
            &["a/**/bad"][..],
            &["!main"][..],
            &["**", "!a/b"][..],
        ] {
            let outcome = list(&repo, entries).await;
            assert!(
                matches!(outcome, Err(ostrya::Error::Core(_))),
                "{entries:?}: {outcome:?}"
            );
        }
        let outcome = list(&repo, &["broken"]).await;
        assert!(
            matches!(outcome, Err(ostrya::Error::ObjectNotFound { .. })),
            "{outcome:?}"
        );

        // A listing that selects no bad ref succeeds. The bad file at the
        // top is not read by a pattern with a literal or wildcard first
        // part and more parts after it, and the bad file below `a/c` is not
        // read by a pattern that stops above it or names another ref.
        for (entries, want) in [
            (&["*/y"][..], vec!["x/y"]),
            (&["*/*"][..], vec!["a/b", "a/bc", "x/al", "x/y"]),
            (&["a/*"][..], vec!["a/b", "a/bc"]),
            (&["a/b", "a/c/d"][..], vec!["a/b", "a/c/d"]),
            (&["a/*/d"][..], vec!["a/c/d"]),
            (&["x/**", "main"][..], vec!["main", "x/al", "x/y"]),
            (&["main"][..], vec!["main"]),
            (
                &["!garbage", "!broken", "!a/c/bad"][..],
                vec!["a/b", "a/bc", "a/c/d", "ab", "main", "other", "x/al", "x/y"],
            ),
            (
                &["**", "!garbage", "!broken", "!a/c/bad"][..],
                vec!["a/b", "a/bc", "a/c/d", "ab", "main", "other", "x/al", "x/y"],
            ),
            (&["a/**", "!a/c/*"][..], vec!["a/b", "a/bc"]),
            (&["a/**", "!a/**/bad"][..], vec!["a/b", "a/bc", "a/c/d"]),
        ] {
            let listing = list(&repo, entries).await.unwrap();
            assert_eq!(listed_names(&listing), want, "{entries:?}");
        }
    });
}

/// The listing holds the selected refs that the group of the item can
/// read. A ref that the client cannot read is not read, so a broken ref of
/// that kind fails no listing of this client. The same ref fails the
/// listing of a client that reads it.
#[test]
fn a_ref_listing_holds_the_readable_refs_alone() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-rights");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        add_prefix_refs(&repo).await;
        let heads = repo_dir.join("refs/heads");
        std::fs::write(heads.join("garbage"), "no checksum\n").unwrap();
        let missing = Checksum::from_bytes([7; 32]);
        repo.set_ref_immediate(&Ref::local("broken"), Some(&missing))
            .await
            .unwrap();
        let reader = read_access(
            "[ex-ostrya client \"c\"]\nauth=ssh:u\nallow=r:a/**;w:main;d:ab\ndeny=a/c/**\n",
            "ssh:u",
        );
        for (entries, want) in [
            (&[][..], vec!["a/b", "a/bc", "main"]),
            (&["*"][..], vec!["main"]),
            (&["a/**", "ab", "garbage"][..], vec!["a/b", "a/bc"]),
            (&["!a/bc"][..], vec!["a/b", "main"]),
        ] {
            let listing = repo
                .build_ref_listing(&selector(entries), None, &reader)
                .await
                .unwrap()
                .bytes;
            assert_eq!(listed_names(&listing), want, "{entries:?}");
        }
        let stranger = read_access(
            "[ex-ostrya client \"c\"]\nauth=ssh:u\nallow=r:**\n",
            "ssh:v",
        );
        let listing = repo
            .build_ref_listing(&selector(&[]), None, &stranger)
            .await
            .unwrap()
            .bytes;
        assert!(listed_names(&listing).is_empty());
        let outcome = list(&repo, &["garbage"]).await;
        assert!(
            matches!(outcome, Err(ostrya::Error::Core(_))),
            "{outcome:?}"
        );
        let all = read_access(
            "[ex-ostrya client \"c\"]\nauth=ssh:u\nallow=r:**\n",
            "ssh:u",
        );
        let outcome = repo
            .build_ref_listing(&selector(&["broken"]), None, &all)
            .await;
        assert!(
            matches!(outcome, Err(ostrya::Error::ObjectNotFound { .. })),
            "{outcome:?}"
        );
    });
}

/// A client with no group, a client whose group has items of a collection
/// alone, and a client whose group gives no `r` on a local ref, read no
/// entry of `refs/heads`. The listing
/// of each one is empty also when `refs/heads` is a regular file, which
/// fails the listing of a client that reads local refs.
#[test]
fn a_client_that_reads_no_local_ref_reads_no_entry_of_refs_heads() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-no-local");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let heads = repo_dir.join("refs/heads");
        std::fs::remove_dir_all(&heads).unwrap();
        std::fs::write(&heads, "").unwrap();
        let groups = "[ex-ostrya client \"mirrors\"]\nauth=ssh:m\nallow=r:@org.example.M:**\n\
                      [ex-ostrya client \"delete\"]\nauth=ssh:d\nallow=d:**\n\
                      [ex-ostrya client \"all\"]\nauth=ssh:a\nallow=r:**\n";
        for item in ["ssh:m", "ssh:d", "ssh:other"] {
            let listing = repo
                .build_ref_listing(&selector(&[]), None, &read_access(groups, item))
                .await
                .unwrap()
                .bytes;
            assert!(listed_names(&listing).is_empty(), "{item}");
        }
        let outcome = repo
            .build_ref_listing(&selector(&[]), None, &read_access(groups, "ssh:a"))
            .await;
        assert!(
            matches!(&outcome, Err(ostrya::Error::InvalidFormat(m)) if m == "refs/heads is not a directory"),
            "{outcome:?}"
        );
    });
}

/// An alias is in the listing when the client reads its name and its
/// target, and the alias resolves by the rule of the archive view: a
/// relative body inside `refs/`, one link, and a regular file at the
/// target. An absolute body, an alias of an alias, and an alias to a ref
/// under `refs/remotes/` are left out, also under the implicit group.
#[test]
fn the_listing_applies_the_alias_rule() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-alias-rule");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (main, _) = add_prefix_refs(&repo).await;
        let heads = repo_dir.join("refs/heads");
        let remotes = repo_dir.join("refs/remotes/o");
        std::fs::create_dir_all(&remotes).unwrap();
        std::fs::copy(heads.join("main"), remotes.join("x")).unwrap();
        let absolute = heads.join("a/b").canonicalize().unwrap();
        for (alias, body) in [
            ("x/hidden", "../ab"),
            ("x/abs", absolute.to_str().unwrap()),
            ("x/chain", "al"),
            ("x/remote", "../../remotes/o/x"),
            ("x/out", "../../../config"),
            ("zz", "a/b"),
        ] {
            std::os::unix::fs::symlink(body, heads.join(alias)).unwrap();
        }
        let reader = read_access(
            "[ex-ostrya client \"c\"]\nauth=anonymous\nallow=r:x/**;r:a/b\n",
            "anonymous",
        );
        let listing = repo
            .build_ref_listing(&selector(&["x/**", "zz"]), None, &reader)
            .await
            .unwrap()
            .bytes;
        assert_eq!(listed_names(&listing), ["x/al", "x/y"]);
        assert_eq!(Summary::parse(&listing).unwrap().lookup("x/al"), Some(main));
        let listing = list(&repo, &["x/**", "zz"]).await.unwrap();
        assert_eq!(listed_names(&listing), ["x/al", "x/hidden", "x/y", "zz"]);
    });
}

/// The walk does not read a directory that a negative entry covers. A
/// directory with mode 0 fails a listing that reads it and not a listing
/// that skips it. The test returns at once for a user that ignores the mode.
#[test]
fn a_ref_listing_skips_a_directory_that_a_negative_entry_covers() {
    use std::os::unix::fs::PermissionsExt;
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-skip-dir");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        add_prefix_refs(&repo).await;
        let locked = repo_dir.join("refs/heads/a/c");
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        let restore = || {
            std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
        };
        if std::fs::read_dir(&locked).is_ok() {
            restore();
            return;
        }
        for entries in [&["a/**"][..], &["**"][..], &["a/*/d"][..], &[][..]] {
            assert!(list(&repo, entries).await.is_err(), "{entries:?}");
        }
        for (entries, want) in [
            (&["a/**", "!a/c/**"][..], vec!["a/b", "a/bc"]),
            (&["a/**", "!a/*/**"][..], vec!["a/b", "a/bc"]),
            (&["a/**", "!**"][..], vec![]),
            (
                &["**", "!a/c/**"][..],
                vec!["a/b", "a/bc", "ab", "main", "other", "x/al", "x/y"],
            ),
            (
                &["!a/c/**"][..],
                vec!["a/b", "a/bc", "ab", "main", "other", "x/al", "x/y"],
            ),
        ] {
            let listing = list(&repo, entries).await.unwrap();
            assert_eq!(listed_names(&listing), want, "{entries:?}");
        }
        restore();
    });
}

/// A selector of the local refs with the negative entry `**` does not read
/// `refs/heads`, and no listing reads the mirror directory of the
/// collection id of the repository. A listing with that selector succeeds
/// with both directories unreadable, with or without collection refs. A
/// listing that reads `refs/heads` fails. The test returns at once for a
/// user that ignores the mode.
#[test]
fn a_listing_with_no_local_ref_reads_no_local_directory() {
    use std::os::unix::fs::PermissionsExt;
    let (_tmp, repo_dir) = writable_fixture("summary-collection", "listing-no-local-dir");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let main = repo.list_refs(None).await.unwrap()[0].1;
        write_mirror_file(
            &repo_dir,
            &format!("{COLLECTION_ID}/own"),
            &format!("{main}\n"),
        );
        set_mirror(&repo, "org.a", "main", &main).await;
        let access = collection_access("", "anonymous");
        let locked = [
            repo_dir.join("refs/heads"),
            repo_dir.join("refs/mirrors").join(COLLECTION_ID),
        ];
        for dir in &locked {
            std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o000)).unwrap();
        }
        let restore = || {
            for dir in &locked {
                std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755)).unwrap();
            }
        };
        if locked.iter().any(|dir| std::fs::read_dir(dir).is_ok()) {
            restore();
            return;
        }
        for collections in [None, Some(selector(&[]))] {
            let all = repo
                .build_ref_listing(&selector(&[]), collections.as_ref(), &access)
                .await;
            assert!(all.is_err(), "{collections:?}");
        }
        let none = list_with(&repo, &["!**"], None, &access).await;
        assert!(listed_names(&none.bytes).is_empty());
        let some = list_with(&repo, &["!**"], Some(&[]), &access).await;
        assert!(listed_names(&some.bytes).is_empty());
        assert_eq!(
            collection_names(&some.bytes),
            names_of(&[("org.a", &["main"])])
        );
        let some = list_with(&repo, &["a/**", "!**"], Some(&["org.a/**"]), &access).await;
        assert!(listed_names(&some.bytes).is_empty());
        assert_eq!(
            collection_names(&some.bytes),
            names_of(&[("org.a", &["main"])])
        );
        restore();
    });
}

/// With no positive entry, the walk of a namespace reads only the
/// directories that an allow item that gives `r` can match, and it skips a
/// directory that a deny item of the group covers. A directory with mode 0
/// outside these directories fails no listing of the client, and the
/// listing holds the refs that the client reads. A positive entry walks by
/// its patterns. The test returns at once for a user that ignores the mode.
#[test]
fn a_ref_listing_walks_the_directories_that_the_client_reads() {
    use std::os::unix::fs::PermissionsExt;
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-readable-dirs");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (main, other) = add_prefix_refs(&repo).await;
        for (name, commit) in [
            ("pub/a", main),
            ("pub/b/c", other),
            ("pub/b/d/e", main),
            ("pub/secret/s", other),
            ("pub/x", main),
            ("priv/p", other),
            ("locked/l", main),
        ] {
            repo.set_ref_immediate(&Ref::local(name), Some(&commit))
                .await
                .unwrap();
        }
        repo.set_ref_alias_immediate(&Ref::local("pub/al"), &Ref::local("main"))
            .await
            .unwrap();
        repo.set_ref_alias_immediate(&Ref::local("pub/hid"), &Ref::local("priv/p"))
            .await
            .unwrap();
        for name in ["c/a", "c/b/c", "c/no/b", "z/x"] {
            set_mirror(&repo, "org.example.M", name, &main).await;
        }
        let groups = "[ex-ostrya client \"pub\"]\nauth=ssh:u\n\
                      allow=r:pub/**;w:main;d:priv/**;r:@org.example.M:c/**\n\
                      deny=pub/secret/**;pub/x;@org.example.M:c/no/**\n";
        let reader = read_access(groups, "ssh:u");
        let check = |listing: ostrya::RefListing, local: Names<'_>, map: Map<'_>| {
            assert_eq!(listed_names(&listing.bytes), local);
            assert_eq!(collection_names(&listing.bytes), names_of(map));
        };
        let readable = ["main", "pub/a", "pub/al", "pub/b/c", "pub/b/d/e"];
        let map: Map<'_> = &[("org.example.M", &["c/a", "c/b/c"])];
        check(
            list_with(&repo, &[], Some(&[]), &reader).await,
            &readable,
            map,
        );

        let locked = [
            repo_dir.join("refs/heads/locked"),
            repo_dir.join("refs/heads/pub/secret"),
            repo_dir.join("refs/mirrors/org.example.M/c/no"),
            repo_dir.join("refs/mirrors/org.example.M/z"),
        ];
        for dir in &locked {
            std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o000)).unwrap();
        }
        let restore = || {
            for dir in &locked {
                std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755)).unwrap();
            }
        };
        if std::fs::read_dir(&locked[0]).is_ok() {
            restore();
            return;
        }
        check(
            list_with(&repo, &[], Some(&[]), &reader).await,
            &readable,
            map,
        );
        check(
            list_with(&repo, &["!pub/b/**"], Some(&["!*/c/b/**"]), &reader).await,
            &["main", "pub/a", "pub/al"],
            &[("org.example.M", &["c/a"])],
        );
        for (refs, collections) in [(&["**"][..], &[][..]), (&[][..], &["*/**"][..])] {
            let outcome = repo
                .build_ref_listing(&selector(refs), Some(&selector(collections)), &reader)
                .await;
            assert!(
                matches!(outcome, Err(ostrya::Error::Io(_))),
                "{refs:?} {collections:?}: {outcome:?}"
            );
        }
        restore();
    });
}

/// An entry that `RefSelector::parse` refuses never reaches a listing. The
/// parse comes before each read, so a repository with a bad ref gives the
/// same refusal.
#[test]
fn a_bad_entry_is_refused_by_the_parser() {
    for bad in [
        "", "/", "/a", "a/", "a//b", ".", "..", "a/./b", "a/../b", "a\0b", "a b", "-a", "a*",
        "a/.b", "a!", "!!a", "!", "!/a", "**x", "x**", "***", "a/b*c", "~a",
    ] {
        for entries in [&[bad][..], &["main", bad][..], &["!main", bad][..]] {
            let outcome = RefSelector::parse(entries.iter().copied());
            assert!(
                matches!(outcome, Err(ostrya_core::Error::InvalidRefPattern(_))),
                "{entries:?}: {outcome:?}"
            );
        }
    }
}

/// Returns the SHA-256 digest of `bytes` in hex.
fn digest(bytes: &[u8]) -> String {
    Checksum::sha256(bytes).to_hex()
}

/// Builds the ref listing of the selectors that `refs` and `collections`
/// give, with the rights `access`.
async fn list_with(
    repo: &Repo,
    refs: &[&str],
    collections: Option<&[&str]>,
    access: &ostrya::access::ReadAccess,
) -> ostrya::RefListing {
    let collections = collections.map(selector);
    repo.build_ref_listing(&selector(refs), collections.as_ref(), access)
        .await
        .unwrap()
}

/// Returns the collections of the collection map of `listing`, each with the
/// names of its refs, in stored order.
fn collection_names(listing: &[u8]) -> Vec<(String, Vec<String>)> {
    Summary::parse(listing)
        .unwrap()
        .collection_map()
        .unwrap()
        .into_iter()
        .map(|(id, refs)| (id, refs.into_iter().map(|entry| entry.name).collect()))
        .collect()
}

/// A list of ref names or of selector entries.
type Names<'a> = &'a [&'a str];

/// The collections of a collection map, each with the names of its refs.
type Map<'a> = &'a [(&'a str, Names<'a>)];

/// Returns the map that `collection_names` gives, from string slices.
fn names_of(map: Map<'_>) -> Vec<(String, Vec<String>)> {
    map.iter()
        .map(|(id, names)| {
            let names = names.iter().map(|name| (*name).to_owned()).collect();
            ((*id).to_owned(), names)
        })
        .collect()
}

/// Sets the mirror ref `id/name` of `repo` to `commit`.
async fn set_mirror(repo: &Repo, id: &str, name: &str, commit: &Checksum) {
    repo.set_ref_immediate(&ostrya::Ref::collection(id, name), Some(commit))
        .await
        .unwrap();
}

/// Writes `body` to the file `refs/mirrors/<path>` of the repository at
/// `repo_dir`, and creates its parents. The path can name a directory that
/// no ref write accepts.
fn write_mirror_file(repo_dir: &Path, path: &str, body: &str) {
    let file = repo_dir.join("refs/mirrors").join(path);
    std::fs::create_dir_all(file.parent().unwrap()).unwrap();
    std::fs::write(file, body).unwrap();
}

/// Returns the read rights of the client with the auth item `item` under
/// the client groups `groups`, in a repository with the collection id of
/// the collection fixture.
fn collection_access(groups: &str, item: &str) -> ostrya::access::ReadAccess {
    let text =
        format!("[core]\nrepo_version=1\nmode=archive-z2\ncollection-id={COLLECTION_ID}\n{groups}");
    let config = ostrya::RepoConfig::parse(&text).unwrap();
    let access = ostrya::access::ClientAccess::from_config(&config).unwrap();
    let item = ostrya::access::AuthItem::parse(item).unwrap();
    ostrya::access::ReadAccess::new(std::sync::Arc::new(access), item, None)
}

/// A request with no selector of the collection refs has the bytes of the
/// listing before collection refs entered the listing. The SHA-256 digests
/// below pin those bytes, for the `summary` fixture with several selectors,
/// with more refs, with rights, with deltas, and for the collection fixture
/// before and after its first summary. Mirror refs of other collections and
/// a directory that is no collection change no byte, and a selector of the
/// collection refs that selects nothing gives the same bytes.
#[test]
fn a_listing_without_collections_keeps_its_bytes() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-pinned-bytes");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (main, other) = {
            let refs = repo.list_refs(None).await.unwrap();
            (refs[0].1, refs[1].1)
        };
        set_mirror(&repo, "org.other", "x", &main).await;
        set_mirror(&repo, "org.other", "y/z", &other).await;
        write_mirror_file(&repo_dir, "bad/x", "no checksum\n");
        write_mirror_file(&repo_dir, "file", "no checksum\n");
        let anyone = anyone();
        let check = |repo: &Repo, refs: &'static [&'static str], want: &'static str| {
            let repo = repo.clone();
            let anyone = anyone.clone();
            async move {
                let plain = list_with(&repo, refs, None, &anyone).await;
                assert_eq!(digest(&plain.bytes), want, "{refs:?}");
                assert!(plain.invalid_collection_dirs.is_empty());
                let none = list_with(&repo, refs, Some(&["!**"]), &anyone).await;
                assert_eq!(none.bytes, plain.bytes, "{refs:?}");
                assert_eq!(none.invalid_collection_dirs, ["bad"]);
            }
        };
        let cases: [(&[&str], &str); 4] = [
            (
                &[],
                "a4d5a9eeb9ef261850b4b7005e7e8e8c50322e3003257ea89e16b2088c12b6f5",
            ),
            (
                &["main"],
                "371e66dc81781e8837b85e89c58098dc764405d98fcaeb3a2a358760ae69285f",
            ),
            (
                &["!main"],
                "fc5552356bdd83513ca1f5d849ad52c88176f1626aa230f3c9b8a90535088659",
            ),
            (
                &["**"],
                "a4d5a9eeb9ef261850b4b7005e7e8e8c50322e3003257ea89e16b2088c12b6f5",
            ),
        ];
        for (refs, want) in cases {
            check(&repo, refs, want).await;
        }

        add_prefix_refs(&repo).await;
        let cases: [(&[&str], &str); 4] = [
            (
                &[],
                "299fe13ac4273c6d4a5372870004bde38e4d284d887106371553f794a2acb7ae",
            ),
            (
                &["a/**"],
                "dfa5a07c6d06da621484232a02ba4a40792f46e2d722f96559aef254bbae4a2d",
            ),
            (
                &["x/**", "main"],
                "f776a1efcc603212dec0855f05e1815b733854bdd32ab7d6b962e540597415c9",
            ),
            (
                &["!a/**"],
                "0ee45df0f1a4baa1f81dafa789d57da2cc9eec94ddc8c8756819914d5cc160ca",
            ),
        ];
        for (refs, want) in cases {
            check(&repo, refs, want).await;
        }
        let reader = read_access(
            "[ex-ostrya client \"c\"]\nauth=ssh:u\nallow=r:a/**;w:main\n",
            "ssh:u",
        );
        let listing = list_with(&repo, &[], None, &reader).await;
        assert_eq!(
            digest(&listing.bytes),
            "0c4bd6287f9d8470eca9aae719423dad3079def94f3915c2953c693865a0c203"
        );

        let opts = DeltaOptions {
            timestamp: Some(FIXED_EPOCH),
            ..DeltaOptions::default()
        };
        for (from, to) in [(None, &main), (Some(&other), &main), (None, &other)] {
            repo.generate_static_delta(from, to, &opts).await.unwrap();
        }
        repo.reindex_static_deltas().await.unwrap();
        let cases: [(&[&str], &str); 2] = [
            (
                &[],
                "56f6755238adb6aba5aedbdfe427d90335ae27938bf34586959ee64bb814a3cf",
            ),
            (
                &["other"],
                "6b1973202aa00771ed99b949b25d82aa941fce0fc98529fe1cb60780c0205a99",
            ),
        ];
        for (refs, want) in cases {
            check(&repo, refs, want).await;
        }
    });

    let (_tmp, repo_dir) = collection_fixture_with_no_wait("listing-pinned-collection");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (_, commit) = repo.list_refs(None).await.unwrap()[0].clone();
        set_mirror(&repo, "org.ostrya.Other", "mirrored", &commit).await;
        write_mirror_file(&repo_dir, "a..b/x", "no checksum\n");
        let listing = list_with(&repo, &[], None, &anyone()).await;
        assert_eq!(
            digest(&listing.bytes),
            "d95d180e87476907feee797a1aa16edc3a340d975e746eb72420cd90450d724b"
        );
        // The summary writer reads each mirror ref, so the bad directory is
        // out of the tree while it runs.
        std::fs::remove_dir_all(repo_dir.join("refs/mirrors/a..b")).unwrap();
        regenerate_with(&repo, Vec::new()).await;
        write_mirror_file(&repo_dir, "a..b/x", "no checksum\n");
        let listing = list_with(&repo, &[], None, &anyone()).await;
        assert_eq!(
            digest(&listing.bytes),
            "db34fc4fc0a5350df8a518828906cf7f775f5fa03306cc760786647ae99f519a"
        );
        let none = list_with(&repo, &[], Some(&["!**"]), &anyone()).await;
        assert_eq!(none.bytes, listing.bytes);
        assert_eq!(none.invalid_collection_dirs, ["a..b"]);
    });
}

/// A selector of the collection refs selects them by `ID/NAME`. Field 0
/// stays the listing of the local refs. The map holds each collection with
/// a selected ref, both levels sorted byte-wise, and a selector that selects
/// no collection ref gives no map. An entry of one part selects nothing.
#[test]
fn a_listing_selects_collection_refs_by_id_and_name() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-collections");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let refs = repo.list_refs(None).await.unwrap();
        let (main, other) = (refs[0].1, refs[1].1);
        for (id, name, commit) in [
            ("org.b", "main", &main),
            ("org.b", "dev", &other),
            ("org.a", "x/y", &other),
            ("org.a", "main", &main),
        ] {
            set_mirror(&repo, id, name, commit).await;
        }
        let local = list_with(&repo, &[], None, &anyone()).await.bytes;
        let both: &[(&str, &[&str])] = &[("org.a", &["main", "x/y"]), ("org.b", &["dev", "main"])];
        let cases: [(Names, Map); 10] = [
            (&[], both),
            (&["**"], both),
            (&["*/main"], &[("org.a", &["main"]), ("org.b", &["main"])]),
            (&["org.a/**"], &[("org.a", &["main", "x/y"])]),
            (&["org.a/*"], &[("org.a", &["main"])]),
            (&["!org.b/**"], &[("org.a", &["main", "x/y"])]),
            (
                &["**", "!*/main"],
                &[("org.a", &["x/y"]), ("org.b", &["dev"])],
            ),
            (
                &["org.a/x/y", "org.b/dev"],
                &[("org.a", &["x/y"]), ("org.b", &["dev"])],
            ),
            (&["org.a"], &[]),
            (&["org.c/**", "main"], &[]),
        ];
        for (collections, want) in cases {
            let listing = list_with(&repo, &[], Some(collections), &anyone()).await;
            assert_normal_form(&listing.bytes);
            assert_eq!(
                collection_names(&listing.bytes),
                names_of(want),
                "{collections:?}"
            );
            let parsed = Summary::parse(&listing.bytes).unwrap();
            assert_eq!(listed_names(&listing.bytes), ["main", "other"]);
            let keys = metadata_keys(&parsed);
            if want.is_empty() {
                assert_eq!(listing.bytes, local, "{collections:?}");
            } else {
                assert_eq!(
                    keys,
                    ["ostree.summary.mode", "ostree.summary.collection-map"],
                    "{collections:?}"
                );
            }
        }
        let listing = list_with(&repo, &["!**"], Some(&[]), &anyone()).await;
        let parsed = Summary::parse(&listing.bytes).unwrap();
        assert!(parsed.refs.is_empty());
        let map = parsed.collection_map().unwrap();
        assert_eq!(map[0].1[1].commit, other);
        assert_eq!(map[1].1[1].commit, main);
    });
}

/// Each collection entry of a listing has the bytes of the entry of the
/// same ref in the collection map of a summary of the same state, and a
/// listing of all collection refs has the map of the summary.
#[test]
fn a_collection_entry_has_the_bytes_of_the_summary_entry() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-collection-entries");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let refs = repo.list_refs(None).await.unwrap();
        let (main, other) = (refs[0].1, refs[1].1);
        for (id, name, commit) in [
            ("org.a", "main", &main),
            ("org.a", "x/y", &other),
            ("org.b", "dev", &other),
        ] {
            set_mirror(&repo, id, name, commit).await;
        }
        let summary = regenerate_with(&repo, Vec::new()).await;
        let stored = summary.collection_map().unwrap();
        let listing = list_with(&repo, &[], Some(&[]), &anyone()).await;
        let parsed = Summary::parse(&listing.bytes).unwrap();
        assert_eq!(parsed.collection_map().unwrap(), stored);
        assert_eq!(
            parsed.metadata_value("ostree.summary.collection-map"),
            summary.metadata_value("ostree.summary.collection-map")
        );
        let listing = list_with(&repo, &[], Some(&["org.a/x/**"]), &anyone()).await;
        let map = Summary::parse(&listing.bytes)
            .unwrap()
            .collection_map()
            .unwrap();
        assert_eq!(map, [(stored[0].0.clone(), vec![stored[0].1[1].clone()])]);
    });
}

/// Each collection takes the items of the group of the item for that
/// collection. A deny item wins, `d` alone gives no read, a collection with
/// no item is left out, and an item whose group has no collection item gets
/// no map. In a group with `tls-accept-claim=true`, the claims of a
/// namespace replace the rules of the group for that namespace alone. Field
/// 0 keeps the rights of the local refs.
#[test]
fn the_collection_map_follows_the_items_of_each_namespace() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-collection-rights");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (_, main) = repo.list_refs(None).await.unwrap()[0].clone();
        for (id, name) in [
            ("org.a", "main"),
            ("org.a", "x/y"),
            ("org.b", "main"),
            ("org.b", "dev"),
            ("org.c", "main"),
        ] {
            set_mirror(&repo, id, name, &main).await;
        }
        let groups = "[ex-ostrya client \"u\"]\nauth=ssh:u\n\
                      allow=r:main;r:@org.a:x/**;r:@org.b:main;d:@org.b:dev;r:@org.c:main\n\
                      [ex-ostrya client \"deny\"]\nauth=ssh:v\n\
                      allow=r:@org.a:**;r:@org.b:**;r:@org.c:**\ndeny=@org.b:dev\n\
                      [ex-ostrya client \"only-local\"]\nauth=ssh:w\nallow=r:**\n\
                      [ex-ostrya client \"one\"]\nauth=ssh:x\nallow=w:@org.b:**\n";
        let cases: [(&str, Names, Map); 4] = [
            (
                "ssh:u",
                &["main"],
                &[
                    ("org.a", &["x/y"]),
                    ("org.b", &["main"]),
                    ("org.c", &["main"]),
                ],
            ),
            (
                "ssh:v",
                &[],
                &[
                    ("org.a", &["main", "x/y"]),
                    ("org.b", &["main"]),
                    ("org.c", &["main"]),
                ],
            ),
            ("ssh:w", &["main", "other"], &[]),
            ("ssh:x", &[], &[("org.b", &["dev", "main"])]),
        ];
        for (item, local, map) in cases {
            let access = read_access(groups, item);
            let listing = list_with(&repo, &[], Some(&[]), &access).await;
            assert_eq!(listed_names(&listing.bytes), local, "{item}");
            assert_eq!(collection_names(&listing.bytes), names_of(map), "{item}");
        }

        let config = ostrya::RepoConfig::parse(
            "[core]\nrepo_version=1\nmode=archive-z2\n\
             [ex-ostrya client \"certs\"]\nauth=tls:*\ntls-accept-claim=true\n\
             allow=r:main;r:@org.a:main;r:@org.b:main;r:@org.c:main\n",
        )
        .unwrap();
        let access = ostrya::access::ClientAccess::from_config(&config).unwrap();
        let claims = ostrya::access::Claims::parse(["ostrya:ref:r:@org.a:x/**"]).unwrap();
        let access = ostrya::access::ReadAccess::new(
            std::sync::Arc::new(access),
            ostrya::access::AuthItem::TlsAny,
            Some(std::sync::Arc::new(claims)),
        );
        let listing = list_with(&repo, &[], Some(&[]), &access).await;
        assert_eq!(listed_names(&listing.bytes), ["main"]);
        assert_eq!(
            collection_names(&listing.bytes),
            names_of(&[
                ("org.a", &["x/y"]),
                ("org.b", &["main"]),
                ("org.c", &["main"]),
            ])
        );
    });
}

/// A directory under `refs/mirrors/` whose name fails the collection-id rule
/// is left out of the listing, and its ref files are not read, so their
/// content fails no listing. The listing names each such directory one time,
/// sorted byte-wise, whatever its selector selects. A file at the top level,
/// and a name that is not UTF-8, are left out with no report, also when the
/// name passes the collection-id rule. A symlink at the top level fails each
/// listing with a selector of the collection refs, whatever its selector
/// selects and whatever the link names. A listing with no selector of the
/// collection refs reads none of them.
/// The archive view does not serve a ref of such a directory.
#[test]
fn a_listing_leaves_out_an_invalid_collection_directory() {
    use std::os::unix::ffi::OsStrExt;
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-invalid-dirs");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (_, main) = repo.list_refs(None).await.unwrap()[0].clone();
        set_mirror(&repo, "org.a", "main", &main).await;
        for path in [
            "bad/x",
            "bad/y/z",
            "a..b/x",
            "1a.b/main",
            "file",
            "org.file",
        ] {
            write_mirror_file(&repo_dir, path, "no checksum\n");
        }
        let mirrors = repo_dir.join("refs/mirrors");
        let raw = mirrors.join(std::ffi::OsStr::from_bytes(b"\xff.b"));
        std::fs::create_dir(&raw).unwrap();
        std::fs::write(raw.join("main"), "no checksum\n").unwrap();

        let selectors = [&[][..], &["**"], &["org.a/**"], &["*/main"], &["!**"]];
        for collections in selectors {
            let listing = list_with(&repo, &[], Some(collections), &anyone()).await;
            assert_eq!(
                listing.invalid_collection_dirs,
                ["1a.b", "a..b", "bad"],
                "{collections:?}"
            );
            let want: &[(&str, &[&str])] = if collections == ["!**"] {
                &[]
            } else {
                &[("org.a", &["main"])]
            };
            assert_eq!(
                collection_names(&listing.bytes),
                names_of(want),
                "{collections:?}"
            );
        }
        let listing = list_with(&repo, &[], None, &anyone()).await;
        assert!(listing.invalid_collection_dirs.is_empty());
        assert!(collection_names(&listing.bytes).is_empty());

        let view = ostrya::ArchiveView::new(repo.clone());
        for path in ["refs/mirrors/bad/x", "refs/mirrors/1a.b/main"] {
            let answer = view.get(path, &anyone()).await.unwrap();
            assert!(
                matches!(
                    answer,
                    ostrya::ArchiveAnswer::NotFound | ostrya::ArchiveAnswer::Refused
                ),
                "{path}"
            );
        }

        for (name, target) in [
            ("link", "bad"),
            ("org.link", "org.a"),
            ("org.gone", "org.absent"),
        ] {
            let link = mirrors.join(name);
            std::os::unix::fs::symlink(target, &link).unwrap();
            let refused = format!("refs/mirrors/{name} passes through a symlink");
            for collections in selectors {
                let outcome = repo
                    .build_ref_listing(&selector(&[]), Some(&selector(collections)), &anyone())
                    .await;
                assert!(
                    matches!(&outcome, Err(ostrya::Error::InvalidFormat(m)) if m.starts_with(&refused)),
                    "{name} {collections:?}: {outcome:?}"
                );
            }
            let listing = list_with(&repo, &[], None, &anyone()).await;
            assert!(collection_names(&listing.bytes).is_empty(), "{name}");
            std::fs::remove_file(&link).unwrap();
        }
    });
}

/// A collection ref that the client cannot read is not read: a ref file with
/// no checksum in a collection with no item of the group, or under a name
/// that the group denies, fails no listing of that client, and fails the
/// listing of a client that reads it. The directory of a collection whose
/// items give no `r` is not opened: a directory with mode 0 fails only the
/// listing of a client that reads it. The second part returns at once for a
/// user that ignores the mode.
#[test]
fn a_collection_ref_that_the_client_cannot_read_is_not_read() {
    use std::os::unix::fs::PermissionsExt;
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-collection-unread");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (_, main) = repo.list_refs(None).await.unwrap()[0].clone();
        set_mirror(&repo, "org.a", "main", &main).await;
        write_mirror_file(&repo_dir, "org.a/secret", "no checksum\n");
        write_mirror_file(&repo_dir, "org.b/x", "no checksum\n");
        let groups = "[ex-ostrya client \"a\"]\nauth=ssh:u\nallow=r:@org.a:**;d:@org.b:**\n\
                      deny=@org.a:secret\n\
                      [ex-ostrya client \"all\"]\nauth=ssh:all\nallow=r:@org.a:**;r:@org.b:**\n";
        let reader = read_access(groups, "ssh:u");
        let listing = list_with(&repo, &[], Some(&[]), &reader).await;
        assert_eq!(
            collection_names(&listing.bytes),
            names_of(&[("org.a", &["main"])])
        );
        let all = read_access(groups, "ssh:all");
        for collections in [&["org.a/secret"][..], &["org.b/**"]] {
            let outcome = repo
                .build_ref_listing(&selector(&[]), Some(&selector(collections)), &all)
                .await;
            assert!(
                matches!(outcome, Err(ostrya::Error::Core(_))),
                "{collections:?}: {outcome:?}"
            );
        }

        std::fs::remove_file(repo_dir.join("refs/mirrors/org.b/x")).unwrap();
        let locked = repo_dir.join("refs/mirrors/org.b");
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        let restore = || {
            std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
        };
        if std::fs::read_dir(&locked).is_ok() {
            restore();
            return;
        }
        let listing = list_with(&repo, &[], Some(&[]), &reader).await;
        assert_eq!(
            collection_names(&listing.bytes),
            names_of(&[("org.a", &["main"])])
        );
        let outcome = repo
            .build_ref_listing(&selector(&[]), Some(&selector(&["org.b/**"])), &all)
            .await;
        assert!(matches!(outcome, Err(ostrya::Error::Io(_))), "{outcome:?}");
        restore();
    });
}

/// The delta map of a listing holds the deltas that the index files
/// advertise from the commits of field 0 and of the collection map. A
/// selector of the collection refs that selects nothing adds no delta.
#[test]
fn a_listing_with_collections_advertises_the_deltas_of_collection_commits() {
    let (_tmp, repo_dir) = writable_fixture("summary", "listing-collection-deltas");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let refs = repo.list_refs(None).await.unwrap();
        let (main, other) = (refs[0].1, refs[1].1);
        set_mirror(&repo, "org.a", "x", &other).await;
        let opts = DeltaOptions {
            timestamp: Some(FIXED_EPOCH),
            ..DeltaOptions::default()
        };
        for to in [&main, &other] {
            repo.generate_static_delta(None, to, &opts).await.unwrap();
        }
        repo.reindex_static_deltas().await.unwrap();
        let targets = |listing: &[u8]| -> Vec<Checksum> {
            let parsed = Summary::parse(listing).unwrap();
            let mut to: Vec<Checksum> = parsed
                .static_deltas()
                .unwrap()
                .into_iter()
                .map(|delta| delta.to)
                .collect();
            to.sort_by_key(Checksum::to_hex);
            to
        };
        let mut both = vec![main, other];
        both.sort_by_key(Checksum::to_hex);
        let cases: [(Names, Option<Names>, Vec<Checksum>); 5] = [
            (&["main"], None, vec![main]),
            (&["main"], Some(&["org.b/**"]), vec![main]),
            (&["main"], Some(&["org.a/**"]), both.clone()),
            (&["!**"], Some(&[]), vec![other]),
            (&["!**"], None, Vec::new()),
        ];
        for (refs, collections, want) in cases {
            let listing = list_with(&repo, refs, collections, &anyone()).await;
            assert_eq!(targets(&listing.bytes), want, "{refs:?} {collections:?}");
        }
        let listing = list_with(&repo, &["main"], Some(&[]), &anyone()).await;
        let summary = regenerate_with(&repo, Vec::new()).await;
        let parsed = Summary::parse(&listing.bytes).unwrap();
        assert_eq!(
            metadata_keys(&parsed),
            [
                "ostree.summary.mode",
                "ostree.static-deltas",
                "ostree.summary.collection-map"
            ]
        );
        assert_eq!(
            parsed.metadata_value("ostree.static-deltas"),
            summary.metadata_value("ostree.static-deltas")
        );
    });
}

/// In a repository with a collection id, field 0 holds the refs of
/// `refs/heads` alone. The refs under `refs/mirrors/ID/` of that id are in
/// no listing, and such a ref does not hide the ref of `refs/heads` of the
/// same name. The `ostree` command puts these refs into field 0 of a
/// summary, so this is a divergence. The id is no key of the collection
/// map.
#[test]
fn own_id_mirror_refs_are_in_no_listing() {
    let (_tmp, repo_dir) = collection_fixture_with_no_wait("listing-own-mirrors");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (_, main) = repo.list_refs(None).await.unwrap()[0].clone();
        regenerate_with(&repo, Vec::new()).await;
        let anchor = repo
            .resolve_rev("ostree-metadata", false)
            .await
            .unwrap()
            .unwrap();
        assert_ne!(anchor, main);
        write_mirror_file(
            &repo_dir,
            &format!("{COLLECTION_ID}/main"),
            &format!("{anchor}\n"),
        );
        write_mirror_file(
            &repo_dir,
            &format!("{COLLECTION_ID}/extra/x"),
            &format!("{main}\n"),
        );
        set_mirror(&repo, "org.ostrya.Other", "m", &main).await;

        let all = collection_access("", "anonymous");
        for collections in [None, Some(&[][..])] {
            let listing = list_with(&repo, &[], collections, &all).await;
            let parsed = Summary::parse(&listing.bytes).unwrap();
            assert_eq!(listed_names(&listing.bytes), ["main", "ostree-metadata"]);
            assert_eq!(parsed.lookup("main"), Some(main));
            let want: &[(&str, &[&str])] = match collections {
                Some(_) => &[("org.ostrya.Other", &["m"])],
                None => &[],
            };
            assert_eq!(collection_names(&listing.bytes), names_of(want));
        }
        let listing = list_with(&repo, &[], Some(&["org.ostrya.Test/**"]), &all).await;
        assert!(collection_names(&listing.bytes).is_empty());

        let groups = "[ex-ostrya client \"local\"]\nauth=ssh:u\n\
                      allow=r:main;r:@org.ostrya.Other:**\n\
                      [ex-ostrya client \"mirrors\"]\nauth=ssh:m\nallow=r:@org.ostrya.Other:**\n";
        let listing = list_with(&repo, &[], Some(&[]), &collection_access(groups, "ssh:u")).await;
        assert_eq!(listed_names(&listing.bytes), ["main"]);
        let parsed = Summary::parse(&listing.bytes).unwrap();
        assert_eq!(parsed.lookup("main"), Some(main));
        let listing = list_with(&repo, &[], Some(&[]), &collection_access(groups, "ssh:m")).await;
        assert!(listed_names(&listing.bytes).is_empty());
        assert_eq!(
            collection_names(&listing.bytes),
            names_of(&[("org.ostrya.Other", &["m"])])
        );
    });
}

// ---------------------------------------------------------------------------
// The summaries of the auth items.
// ---------------------------------------------------------------------------

/// Appends `groups` to the config of the repository at `repo_dir`, and
/// opens the repository again so its config holds the groups.
async fn with_groups(repo_dir: &Path, groups: &str) -> Repo {
    let config = repo_dir.join("config");
    let mut text = std::fs::read_to_string(&config).unwrap();
    text.push_str(groups);
    std::fs::write(&config, text).unwrap();
    Repo::open(repo_dir).await.unwrap()
}

/// Returns the auth item of `text`.
fn item(text: &str) -> ostrya::access::AuthItem {
    ostrya::access::AuthItem::parse(text).unwrap()
}

/// Returns the path of a file of the summary of the item `text` under
/// `extensions/ostrya/summary/`, with `suffix`.
fn item_file(repo_dir: &Path, text: &str, suffix: &str) -> std::path::PathBuf {
    let stem = Checksum::sha256(text.as_bytes());
    repo_dir.join(format!("extensions/ostrya/summary/{stem}{suffix}"))
}

/// Returns the parsed summary of the item `text`.
async fn summary_of(repo: &Repo, text: &str) -> Summary {
    let bytes = repo.read_summary_of(&item(text)).await.unwrap().unwrap();
    Summary::parse(&bytes).unwrap()
}

/// Returns the names of the refs in field 0 of `summary`.
fn ref_names(summary: &Summary) -> Vec<String> {
    summary
        .refs
        .iter()
        .map(|entry| entry.name.clone())
        .collect()
}

/// Returns the names of the deltas that `summary` lists.
fn delta_names(summary: &Summary) -> Vec<String> {
    summary
        .static_deltas()
        .unwrap()
        .into_iter()
        .map(|delta| match delta.from {
            Some(from) => format!("{from}-{}", delta.to),
            None => delta.to.to_hex(),
        })
        .collect()
}

/// The options of each regeneration of the item tests.
fn fixed() -> SummaryOptions {
    SummaryOptions {
        last_modified: Some(FIXED_EPOCH),
        ..SummaryOptions::default()
    }
}

/// Each item whose group has `summary=true` gets the refs that the group
/// reads: the local refs in field 0, and the collection refs
/// in the collection map. The root summary holds each ref, and each summary
/// has the same `ostree.summary.last-modified`. An item with no summary gets
/// no file, and each `.access` file holds the digest of its item.
#[test]
fn each_item_gets_the_summary_of_its_groups() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-groups");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (_, main) = repo.list_refs(None).await.unwrap()[0].clone();
        set_mirror(&repo, "org.example.M", "m", &main).await;
        let repo = with_groups(
            &repo_dir,
            "[ex-ostrya client \"public\"]\nauth=anonymous\n\
             allow=r:main;r:@org.example.M:**\nsummary=true\n\
             [ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:**\nsummary=true\n\
             [ex-ostrya client \"ops\"]\nauth=ssh:ops\nallow=r:**\n",
        )
        .await;
        let report = repo.regenerate_summaries(&fixed(), &[]).await.unwrap();
        assert!(report.invalid_collection_dirs.is_empty());

        let root = Summary::parse(&repo.read_summary().await.unwrap().unwrap()).unwrap();
        assert_eq!(ref_names(&root), ["main", "other"]);
        let map = root.collection_map().unwrap();
        assert_eq!(map.len(), 1);
        assert_eq!(map[0].0, "org.example.M");

        let anonymous = summary_of(&repo, "anonymous").await;
        assert_eq!(ref_names(&anonymous), ["main"]);
        let map = anonymous.collection_map().unwrap();
        assert_eq!(map.len(), 1);
        assert_eq!(map[0].0, "org.example.M");
        assert_eq!(map[0].1[0].name, "m");

        let ci = summary_of(&repo, "ssh:ci").await;
        assert_eq!(ref_names(&ci), ["main", "other"]);
        assert!(ci.metadata_value("ostree.summary.collection-map").is_none());
        for summary in [&root, &anonymous, &ci] {
            assert_eq!(
                summary.metadata_value("ostree.summary.last-modified"),
                anonymous.metadata_value("ostree.summary.last-modified")
            );
        }
        assert!(
            repo.read_summary_of(&item("ssh:ops"))
                .await
                .unwrap()
                .is_none()
        );
        assert!(!item_file(&repo_dir, "ssh:ops", ".access").exists());

        let access = ostrya::access::ClientAccess::from_config(repo.config()).unwrap();
        for text in ["anonymous", "ssh:ci"] {
            let digest = access.summary_digest(&item(text)).unwrap();
            assert_eq!(
                std::fs::read(item_file(&repo_dir, text, ".access")).unwrap(),
                format!("{digest}\n").into_bytes(),
                "{text}"
            );
        }
    });
}

/// The client groups do not change the root summary: with groups that hide
/// refs from each item, the root summary has the bytes of the root summary
/// with no client group, and its signature file.
#[test]
fn the_root_summary_does_not_follow_the_client_groups() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-root");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (_, main) = repo.list_refs(None).await.unwrap()[0].clone();
        set_mirror(&repo, "org.example.M", "m", &main).await;
        let signer = ostrya::DummySigner::new(b"sig".to_vec());
        repo.regenerate_summaries(&fixed(), &[&signer])
            .await
            .unwrap();
        let summary = std::fs::read(repo_dir.join("summary")).unwrap();
        let sig = std::fs::read(repo_dir.join("summary.sig")).unwrap();

        let repo = with_groups(
            &repo_dir,
            "[ex-ostrya client \"public\"]\nauth=anonymous\nallow=r:main\nsummary=true\n\
             [ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:other\nsummary=true\n",
        )
        .await;
        repo.regenerate_summaries(&fixed(), &[&signer])
            .await
            .unwrap();
        assert_eq!(std::fs::read(repo_dir.join("summary")).unwrap(), summary);
        assert_eq!(std::fs::read(repo_dir.join("summary.sig")).unwrap(), sig);
        assert_eq!(ref_names(&summary_of(&repo, "anonymous").await), ["main"]);
        assert_eq!(ref_names(&summary_of(&repo, "ssh:ci").await), ["other"]);
    });
}

/// A summary of each local ref and each collection ref lists each delta.
/// Each other summary lists the deltas to the commits of its refs, also
/// when it holds each local ref and the repository holds a collection ref.
#[test]
fn the_delta_map_follows_the_refs_of_the_summary() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-deltas");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let refs = repo.list_refs(None).await.unwrap();
        let (main, other) = (refs[0].1, refs[1].1);
        let opts = DeltaOptions {
            timestamp: Some(FIXED_EPOCH),
            ..DeltaOptions::default()
        };
        repo.generate_static_delta(None, &main, &opts)
            .await
            .unwrap();
        repo.generate_static_delta(Some(&other), &main, &opts)
            .await
            .unwrap();
        repo.generate_static_delta(None, &other, &opts)
            .await
            .unwrap();
        // No ref names `other` now, so only a summary of each ref lists the
        // delta to it.
        repo.set_ref_immediate(&Ref::local("other"), Some(&main))
            .await
            .unwrap();
        set_mirror(&repo, "org.example.M", "m", &main).await;
        let repo = with_groups(
            &repo_dir,
            "[ex-ostrya client \"all\"]\nauth=anonymous\n\
             allow=r:**;r:@org.example.M:**\nsummary=true\n\
             [ex-ostrya client \"local\"]\nauth=ssh:local\nallow=r:**\nsummary=true\n\
             [ex-ostrya client \"none\"]\nauth=ssh:none\nallow=r:nothing\nsummary=true\n",
        )
        .await;
        repo.regenerate_summary(&fixed()).await.unwrap();

        let every = [main.to_hex(), other.to_hex(), format!("{other}-{main}")];
        let mut sorted = every.to_vec();
        sorted.sort();
        assert_eq!(delta_names(&summary_of(&repo, "anonymous").await), sorted);
        let mut to_main = vec![main.to_hex(), format!("{other}-{main}")];
        to_main.sort();
        assert_eq!(delta_names(&summary_of(&repo, "ssh:local").await), to_main);
        let none = summary_of(&repo, "ssh:none").await;
        assert!(none.refs.is_empty());
        assert!(none.metadata_value("ostree.static-deltas").is_none());
    });
}

/// In each mode, the root summary states the mode of the repository, and the
/// summary of `anonymous` states `archive-z2`, the mode of the archive view
/// that serves it.
#[test]
fn the_summary_of_an_item_states_archive_z2_in_each_mode() {
    let tmp = TmpDir::new("items-modes");
    let src = build_tree(tmp.path());
    block_on(async {
        for mode in WRITABLE {
            let (_, repo, _) = repo_of(tmp.path(), mode, &src).await;
            repo.regenerate_summary(&fixed()).await.unwrap();
            let root = Summary::parse(&repo.read_summary().await.unwrap().unwrap()).unwrap();
            assert_eq!(
                root.metadata_value("ostree.summary.mode"),
                Some(&Value::Str(mode.as_mode_str().into())),
                "{mode:?}"
            );
            let served = summary_of(&repo, "anonymous").await;
            assert_eq!(
                served.metadata_value("ostree.summary.mode"),
                Some(&Value::Str("archive-z2".into())),
                "{mode:?}"
            );
        }
    });
}

/// In a `bare-user` repository with an indexed delta, the root summary names
/// the delta and holds `ostree.summary.indexed-deltas`. The summary of
/// `anonymous` holds neither key, and it drops the caller keys of the two
/// names. Both summaries keep each other caller key.
#[test]
fn the_summary_of_an_item_outside_archive_mode_names_no_delta() {
    let tmp = TmpDir::new("items-bare-deltas");
    let src = build_tree(tmp.path());
    block_on(async {
        let (_, repo, commit) = repo_of(tmp.path(), RepoMode::BareUser, &src).await;
        let opts = DeltaOptions {
            timestamp: Some(FIXED_EPOCH),
            ..DeltaOptions::default()
        };
        repo.generate_static_delta(None, &commit, &opts)
            .await
            .unwrap();
        repo.reindex_static_deltas().await.unwrap();
        repo.regenerate_summary(&SummaryOptions {
            additional_metadata: vec![
                string_entry("ostree.static-deltas", "x"),
                string_entry("ostree.summary.indexed-deltas", "x"),
                string_entry("k", "v"),
            ],
            ..fixed()
        })
        .await
        .unwrap();

        let root = Summary::parse(&repo.read_summary().await.unwrap().unwrap()).unwrap();
        assert_eq!(delta_names(&root), [commit.to_hex()]);
        assert_eq!(
            metadata_keys(&root),
            [
                "ostree.summary.mode",
                "ostree.summary.last-modified",
                "ostree.summary.tombstone-commits",
                "ostree.static-deltas",
                "ostree.summary.indexed-deltas",
                "k",
            ]
        );
        let served = summary_of(&repo, "anonymous").await;
        assert!(delta_names(&served).is_empty());
        assert_eq!(
            metadata_keys(&served),
            [
                "ostree.summary.mode",
                "ostree.summary.last-modified",
                "ostree.summary.tombstone-commits",
                "k",
            ]
        );
    });
}

/// With no client group, the root summary holds each local ref and each
/// collection ref. The summary directory holds the summary of `anonymous`,
/// with the bytes of the root summary, and its `.access` file. A directory
/// under `refs/mirrors/` whose name is not a collection id is in the report
/// and in no summary.
#[test]
fn with_no_client_group_the_root_summary_holds_each_ref() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-implicit");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (_, main) = repo.list_refs(None).await.unwrap()[0].clone();
        set_mirror(&repo, "org.example.M", "m", &main).await;
        write_mirror_file(&repo_dir, "bad/x", &format!("{main}\n"));
        let report = repo.regenerate_summaries(&fixed(), &[]).await.unwrap();
        assert_eq!(report.invalid_collection_dirs, ["bad"]);
        let summary = Summary::parse(&repo.read_summary().await.unwrap().unwrap()).unwrap();
        assert_eq!(ref_names(&summary), ["main", "other"]);
        let map = summary.collection_map().unwrap();
        assert_eq!(map.len(), 1);
        assert_eq!(map[0].0, "org.example.M");
        let mut dir: Vec<String> = std::fs::read_dir(repo_dir.join("extensions/ostrya/summary"))
            .unwrap()
            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
            .collect();
        dir.sort();
        let stem = Checksum::sha256(b"anonymous");
        assert_eq!(dir, [stem.to_hex(), format!("{stem}.access")]);
        assert_eq!(
            repo.read_summary_of(&item("anonymous")).await.unwrap(),
            repo.read_summary().await.unwrap()
        );
    });
}

/// A write removes the files of each item that has no summary: the
/// `.access` file, the summary, and its signature file. With no summary of
/// `anonymous`, it still writes the root summary. It removes a temp file of
/// a summary file, and leaves each other entry.
#[test]
fn the_files_of_an_item_with_no_summary_are_removed() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-removed");
    block_on(async {
        let groups = "[ex-ostrya client \"public\"]\nauth=anonymous\nallow=r:**\nsummary=true\n\
                      [ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:**\nsummary=true\n";
        let repo = with_groups(&repo_dir, groups).await;
        let signer = ostrya::DummySigner::new(b"sig".to_vec());
        repo.regenerate_summaries(&fixed(), &[&signer])
            .await
            .unwrap();
        let item_files: Vec<_> = ["ssh:ci", "anonymous"]
            .into_iter()
            .flat_map(|text| {
                ["", ".sig", ".access"].map(|suffix| item_file(&repo_dir, text, suffix))
            })
            .collect();
        for file in &item_files {
            assert!(file.exists(), "{file:?}");
        }
        assert!(repo_dir.join("summary.sig").exists());
        let dir = repo_dir.join("extensions/ostrya/summary");
        std::fs::write(dir.join("notes"), b"keep").unwrap();
        let temp = format!("{}.sig.tmp-1-2", Checksum::sha256(b"ssh:ci"));
        std::fs::write(dir.join(&temp), b"temp").unwrap();
        let other = format!("{}.access", Checksum::sha256(b"ssh:other"));
        std::fs::write(dir.join(&other), b"x\n").unwrap();

        let text = std::fs::read_to_string(repo_dir.join("config")).unwrap();
        let text = text
            .replace(
                "[ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:**\nsummary=true\n",
                "",
            )
            .replace("allow=r:**\nsummary=true\n", "allow=r:**\nsummary=false\n");
        std::fs::write(repo_dir.join("config"), text).unwrap();
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&fixed()).await.unwrap();
        for file in &item_files {
            assert!(!file.exists(), "{file:?}");
        }
        let root = Summary::parse(&repo.read_summary().await.unwrap().unwrap()).unwrap();
        assert_eq!(ref_names(&root), ["main", "other"]);
        // An unsigned write removes the old signatures.
        assert!(!repo_dir.join("summary.sig").exists());
        assert!(!dir.join(&temp).exists());
        assert!(!dir.join(&other).exists());
        assert_eq!(std::fs::read(dir.join("notes")).unwrap(), b"keep");
    });
}

/// A new group name keeps the `.access` file, and a change to `deny` changes
/// it.
#[test]
fn a_new_group_name_keeps_the_access_file() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-rename");
    block_on(async {
        let groups = "[ex-ostrya client \"public\"]\nauth=anonymous\nallow=r:**\nsummary=true\n";
        let repo = with_groups(&repo_dir, groups).await;
        repo.regenerate_summary(&fixed()).await.unwrap();
        let access = item_file(&repo_dir, "anonymous", ".access");
        let before = std::fs::read(&access).unwrap();
        let config = repo_dir.join("config");
        let text = std::fs::read_to_string(&config).unwrap();
        std::fs::write(&config, text.replace("\"public\"", "\"renamed\"")).unwrap();
        Repo::open(&repo_dir)
            .await
            .unwrap()
            .regenerate_summary(&fixed())
            .await
            .unwrap();
        assert_eq!(std::fs::read(&access).unwrap(), before);
        let text = std::fs::read_to_string(&config).unwrap();
        std::fs::write(
            &config,
            text.replace("summary=true\n", "deny=other\nsummary=true\n"),
        )
        .unwrap();
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&fixed()).await.unwrap();
        assert_ne!(std::fs::read(&access).unwrap(), before);
        assert_eq!(ref_names(&summary_of(&repo, "anonymous").await), ["main"]);
    });
}

/// A write with signers signs the root summary and each summary of an item,
/// `anonymous` included. A signing with no write adds a signature to each
/// existing summary.
#[test]
fn each_summary_is_signed() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-signed");
    block_on(async {
        let groups = "[ex-ostrya client \"public\"]\nauth=anonymous\nallow=r:**\nsummary=true\n\
                      [ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:main\nsummary=true\n";
        let repo = with_groups(&repo_dir, groups).await;
        let first = ostrya::DummySigner::new(b"first-signature".to_vec());
        repo.regenerate_summaries(&fixed(), &[&first])
            .await
            .unwrap();
        let holds = |path: &Path, needle: &[u8]| {
            let bytes = std::fs::read(path).unwrap();
            bytes.windows(needle.len()).any(|w| w == needle)
        };
        let sigs = [
            repo_dir.join("summary.sig"),
            item_file(&repo_dir, "anonymous", ".sig"),
            item_file(&repo_dir, "ssh:ci", ".sig"),
        ];
        for sig in &sigs {
            assert!(holds(sig, b"first-signature"), "{sig:?}");
        }
        let second = ostrya::DummySigner::new(b"second-signature".to_vec());
        repo.sign_summary_all(&[&second]).await.unwrap();
        for sig in &sigs {
            assert!(holds(sig, b"first-signature"), "{sig:?}");
            assert!(holds(sig, b"second-signature"), "{sig:?}");
        }
        repo.regenerate_summary(&fixed()).await.unwrap();
        for sig in &sigs {
            assert!(!sig.exists(), "{sig:?}");
        }
    });
}

/// A write of the summaries of the auth items alone writes and signs the
/// summary of each item, and removes the files of each item with no
/// summary. It leaves `summary` and `summary.sig` at the root as they are.
#[test]
fn the_summaries_of_the_auth_items_alone_leave_the_root_summary() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-alone");
    block_on(async {
        let groups = "[ex-ostrya client \"public\"]\nauth=anonymous\nallow=r:main\nsummary=true\n\
                      [ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:**\nsummary=true\n\
                      [ex-ostrya client \"ops\"]\nauth=ssh:ops\nallow=r:**\nsummary=true\n";
        let repo = with_groups(&repo_dir, groups).await;
        let first = ostrya::DummySigner::new(b"first-signature".to_vec());
        repo.regenerate_summaries(&fixed(), &[&first])
            .await
            .unwrap();
        let summary = std::fs::read(repo_dir.join("summary")).unwrap();
        let sig = std::fs::read(repo_dir.join("summary.sig")).unwrap();
        let ops: Vec<_> = ["", ".sig", ".access"]
            .map(|suffix| item_file(&repo_dir, "ssh:ops", suffix))
            .into();
        for file in &ops {
            assert!(file.exists(), "{file:?}");
        }

        let (_, main) = repo.list_refs(None).await.unwrap()[0].clone();
        repo.set_ref_immediate(&Ref::local("added"), Some(&main))
            .await
            .unwrap();
        let config = repo_dir.join("config");
        let text = std::fs::read_to_string(&config).unwrap();
        let text = text.replace(
            "[ex-ostrya client \"ops\"]\nauth=ssh:ops\nallow=r:**\nsummary=true\n",
            "",
        );
        std::fs::write(&config, text).unwrap();
        let repo = Repo::open(&repo_dir).await.unwrap();
        let second = ostrya::DummySigner::new(b"second-signature".to_vec());
        let opts = SummaryOptions {
            last_modified: Some(FIXED_EPOCH + 1),
            auth_items_only: true,
            ..SummaryOptions::default()
        };
        repo.regenerate_summaries(&opts, &[&second]).await.unwrap();

        assert_eq!(std::fs::read(repo_dir.join("summary")).unwrap(), summary);
        assert_eq!(std::fs::read(repo_dir.join("summary.sig")).unwrap(), sig);
        let root = Summary::parse(&summary).unwrap();
        assert_eq!(ref_names(&root), ["main", "other"]);
        let ci = summary_of(&repo, "ssh:ci").await;
        assert_eq!(ref_names(&ci), ["added", "main", "other"]);
        let anonymous = summary_of(&repo, "anonymous").await;
        assert_eq!(ref_names(&anonymous), ["main"]);
        let last_modified = |summary: &Summary| {
            summary
                .metadata_value("ostree.summary.last-modified")
                .and_then(Value::as_u64)
                .map(u64::swap_bytes)
        };
        assert_eq!(last_modified(&ci), Some(FIXED_EPOCH + 1));
        assert_eq!(last_modified(&anonymous), Some(FIXED_EPOCH + 1));
        assert_eq!(last_modified(&root), Some(FIXED_EPOCH));
        let holds = |path: &Path, needle: &[u8]| {
            let bytes = std::fs::read(path).unwrap();
            bytes.windows(needle.len()).any(|w| w == needle)
        };
        for text in ["anonymous", "ssh:ci"] {
            let sig = item_file(&repo_dir, text, ".sig");
            assert!(holds(&sig, b"second-signature"), "{sig:?}");
            assert!(!holds(&sig, b"first-signature"), "{sig:?}");
        }
        for file in &ops {
            assert!(!file.exists(), "{file:?}");
        }
        let access = ostrya::access::ClientAccess::from_config(repo.config()).unwrap();
        for text in ["anonymous", "ssh:ci"] {
            let digest = access.summary_digest(&item(text)).unwrap();
            assert_eq!(
                std::fs::read(item_file(&repo_dir, text, ".access")).unwrap(),
                format!("{digest}\n").into_bytes(),
                "{text}"
            );
        }
    });
}

/// A write of the summaries of the auth items alone in a repository with no
/// root summary writes the summary of each item, and no `summary` and no
/// `summary.sig`.
#[test]
fn the_summaries_of_the_auth_items_alone_write_no_root_summary() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-alone-no-root");
    block_on(async {
        assert!(!repo_dir.join("summary").exists());
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&SummaryOptions {
            auth_items_only: true,
            ..fixed()
        })
        .await
        .unwrap();
        assert_eq!(
            ref_names(&summary_of(&repo, "anonymous").await),
            ["main", "other"]
        );
        assert!(item_file(&repo_dir, "anonymous", ".access").exists());
        assert!(!repo_dir.join("summary").exists());
        assert!(!repo_dir.join("summary.sig").exists());
    });
}

/// A write of the summaries of the auth items alone with no item that has a
/// summary removes the files of each item. It leaves `summary` and
/// `summary.sig` at the root as they are.
#[test]
fn the_summaries_of_the_auth_items_alone_with_no_summary_remove_the_item_files() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-alone-none");
    block_on(async {
        let groups = "[ex-ostrya client \"public\"]\nauth=anonymous\nallow=r:**\nsummary=true\n\
                      [ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:**\nsummary=true\n";
        let repo = with_groups(&repo_dir, groups).await;
        let signer = ostrya::DummySigner::new(b"sig".to_vec());
        repo.regenerate_summaries(&fixed(), &[&signer])
            .await
            .unwrap();
        let summary = std::fs::read(repo_dir.join("summary")).unwrap();
        let sig = std::fs::read(repo_dir.join("summary.sig")).unwrap();
        let item_files: Vec<_> = ["ssh:ci", "anonymous"]
            .into_iter()
            .flat_map(|text| {
                ["", ".sig", ".access"].map(|suffix| item_file(&repo_dir, text, suffix))
            })
            .collect();
        for file in &item_files {
            assert!(file.exists(), "{file:?}");
        }

        let config = repo_dir.join("config");
        let text = std::fs::read_to_string(&config).unwrap();
        std::fs::write(&config, text.replace("summary=true\n", "summary=false\n")).unwrap();
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summaries(
            &SummaryOptions {
                auth_items_only: true,
                ..fixed()
            },
            &[&signer],
        )
        .await
        .unwrap();
        for file in &item_files {
            assert!(!file.exists(), "{file:?}");
        }
        assert_eq!(std::fs::read(repo_dir.join("summary")).unwrap(), summary);
        assert_eq!(std::fs::read(repo_dir.join("summary.sig")).unwrap(), sig);
    });
}

/// In a repository with a collection id, a write of the summaries of the
/// auth items alone writes no anchor commit, and ignores the timestamp of
/// the anchor commit. The summary of `anonymous` lists the anchor commit
/// that is in place.
#[test]
fn the_summaries_of_the_auth_items_alone_write_no_anchor_commit() {
    let (_tmp, repo_dir) = collection_fixture_with_no_wait("items-alone-anchor");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&fixed()).await.unwrap();
        let tip = repo
            .resolve_ref_tip(&Ref::local("ostree-metadata"))
            .await
            .unwrap();
        let tip = tip.expect("the anchor was written");
        let summary = std::fs::read(repo_dir.join("summary")).unwrap();
        let refs = common::file_inventory(&repo_dir, "refs");

        repo.regenerate_summary(&SummaryOptions {
            metadata_commit_timestamp: Some(FIXED_EPOCH + 1),
            auth_items_only: true,
            ..fixed()
        })
        .await
        .unwrap();
        assert_eq!(
            repo.resolve_ref_tip(&Ref::local("ostree-metadata"))
                .await
                .unwrap(),
            Some(tip)
        );
        assert_eq!(common::file_inventory(&repo_dir, "refs"), refs);
        assert_eq!(std::fs::read(repo_dir.join("summary")).unwrap(), summary);
        let anonymous = summary_of(&repo, "anonymous").await;
        let entry = anonymous
            .refs
            .iter()
            .find(|entry| entry.name == "ostree-metadata")
            .expect("the summary lists the anchor");
        assert_eq!(entry.commit, tip);
    });
}

/// In a repository with a collection id, a write of the root summary alone
/// writes `summary`, removes `summary.sig`, writes no anchor commit, and
/// writes no file of an auth item. The summary lists no anchor ref.
#[test]
fn the_root_summary_alone_writes_no_anchor_commit_and_no_item_summary() {
    let (_tmp, repo_dir) = collection_fixture_with_no_wait("root-alone");
    block_on(async {
        std::fs::write(repo_dir.join("summary.sig"), b"stale").unwrap();
        let refs = common::file_inventory(&repo_dir, "refs");
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&SummaryOptions {
            root_summary_only: true,
            ..fixed()
        })
        .await
        .unwrap();
        assert_eq!(common::file_inventory(&repo_dir, "refs"), refs);
        assert_eq!(
            repo.resolve_ref_tip(&Ref::local("ostree-metadata"))
                .await
                .unwrap(),
            None
        );
        let summary = Summary::parse(&std::fs::read(repo_dir.join("summary")).unwrap()).unwrap();
        assert!(!ref_names(&summary).is_empty());
        assert!(
            !ref_names(&summary)
                .iter()
                .any(|name| name == "ostree-metadata")
        );
        assert!(!repo_dir.join("summary.sig").exists());
        assert!(!item_file(&repo_dir, "anonymous", "").exists());
        assert!(!item_file(&repo_dir, "anonymous", ".access").exists());
    });
}

/// A write of the root summary alone leaves the files of each auth item as
/// they are.
#[test]
fn the_root_summary_alone_keeps_the_item_files() {
    let (_tmp, repo_dir) = writable_fixture("summary", "root-alone-items");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&fixed()).await.unwrap();
        let files = common::file_inventory(&repo_dir, "extensions");
        assert!(!files.is_empty());
        let summary = std::fs::read(repo_dir.join("summary")).unwrap();
        let config = repo_dir.join("config");
        let text = std::fs::read_to_string(&config).unwrap();
        std::fs::write(
            &config,
            format!("{text}[ex-ostrya client \"none\"]\nauth=anonymous\nsummary=false\n"),
        )
        .unwrap();
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&SummaryOptions {
            last_modified: Some(FIXED_EPOCH + 1),
            root_summary_only: true,
            ..SummaryOptions::default()
        })
        .await
        .unwrap();
        assert_eq!(common::file_inventory(&repo_dir, "extensions"), files);
        assert_ne!(std::fs::read(repo_dir.join("summary")).unwrap(), summary);
    });
}

/// A write that asks for the auth items alone and for the root summary alone
/// is refused, and writes nothing.
#[test]
fn the_root_summary_alone_with_the_auth_items_alone_is_refused() {
    let (_tmp, repo_dir) = collection_fixture_with_no_wait("root-alone-refused");
    block_on(async {
        let before = common::file_inventory(&repo_dir, "");
        let repo = Repo::open(&repo_dir).await.unwrap();
        let err = repo
            .regenerate_summary(&SummaryOptions {
                auth_items_only: true,
                root_summary_only: true,
                ..fixed()
            })
            .await
            .unwrap_err();
        assert!(matches!(err, ostrya::Error::InvalidInput(_)), "{err:?}");
        assert_eq!(common::file_inventory(&repo_dir, ""), before);
    });
}

/// The mirror refs of the own collection id are in no summary, and such a
/// ref does not hide the ref of `refs/heads` of the same name. The own id is
/// no key of the map.
#[test]
fn a_summary_leaves_out_the_mirror_refs_of_the_own_id() {
    let (_tmp, repo_dir) = collection_fixture_with_no_wait("items-own-mirrors");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let (_, main) = repo.list_refs(None).await.unwrap()[0].clone();
        regenerate_with(&repo, Vec::new()).await;
        let anchor = repo
            .resolve_rev("ostree-metadata", false)
            .await
            .unwrap()
            .unwrap();
        write_mirror_file(
            &repo_dir,
            &format!("{COLLECTION_ID}/main"),
            &format!("{anchor}\n"),
        );
        write_mirror_file(
            &repo_dir,
            &format!("{COLLECTION_ID}/extra/x"),
            &format!("{main}\n"),
        );
        set_mirror(&repo, "org.ostrya.Other", "m", &main).await;
        let summary = regenerate_with(&repo, Vec::new()).await;
        assert_eq!(ref_names(&summary), ["main", "ostree-metadata"]);
        assert_eq!(summary.lookup("main"), Some(main));
        let map = summary.collection_map().unwrap();
        assert_eq!(map.len(), 1);
        assert_eq!(map[0].0, "org.ostrya.Other");
    });
}

/// A signer that counts its signatures, for the tests of the summaries with
/// the same bytes.
struct CountingSigner {
    count: std::sync::atomic::AtomicUsize,
}

impl ostrya::Signer for CountingSigner {
    fn name(&self) -> &str {
        "dummy"
    }

    fn metadata_key(&self) -> &str {
        "ostree.sign.dummy"
    }

    fn sign<'a>(&'a self, _: &'a [u8]) -> ostrya::SignFuture<'a> {
        self.count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        Box::pin(async { Ok(b"counted-signature".to_vec()) })
    }
}

/// Two summaries with the same bytes get one signature of each signer, in
/// a write and in a signing with no write. Each signature file holds it.
#[test]
fn summaries_with_the_same_bytes_are_signed_one_time() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-same-bytes");
    block_on(async {
        let groups = "[ex-ostrya client \"public\"]\nauth=anonymous\nallow=r:**\nsummary=true\n\
                      [ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:**\nsummary=true\n\
                      [ex-ostrya client \"main\"]\nauth=ssh:main\nallow=r:main\nsummary=true\n";
        let repo = with_groups(&repo_dir, groups).await;
        let counting = || CountingSigner {
            count: std::sync::atomic::AtomicUsize::new(0),
        };
        let signer = counting();
        repo.regenerate_summaries(&fixed(), &[&signer])
            .await
            .unwrap();
        assert_eq!(signer.count.into_inner(), 2);
        assert_eq!(
            repo.read_summary().await.unwrap(),
            repo.read_summary_of(&item("ssh:ci")).await.unwrap()
        );
        let sigs = [
            repo_dir.join("summary.sig"),
            item_file(&repo_dir, "ssh:ci", ".sig"),
            item_file(&repo_dir, "ssh:main", ".sig"),
        ];
        let signer = counting();
        repo.sign_summary_all(&[&signer]).await.unwrap();
        assert_eq!(signer.count.into_inner(), 2);
        for sig in &sigs {
            let bytes = std::fs::read(sig).unwrap();
            let needle = b"counted-signature";
            let found = bytes.windows(needle.len()).filter(|w| w == needle).count();
            assert_eq!(found, 2, "{sig:?}");
        }
    });
}

/// When the access digest of an item changes, the write removes the old
/// `.access` file before it writes the summary. So a write that fails at the
/// summary leaves no `.access` file of the old digest.
#[test]
fn a_changed_access_file_goes_before_the_summary() {
    let (_tmp, repo_dir) = writable_fixture("summary", "items-access-first");
    block_on(async {
        let groups = "[ex-ostrya client \"public\"]\nauth=anonymous\nallow=r:**\nsummary=true\n";
        let repo = with_groups(&repo_dir, groups).await;
        repo.regenerate_summary(&fixed()).await.unwrap();
        let access = item_file(&repo_dir, "anonymous", ".access");
        let before = std::fs::read(&access).unwrap();

        // The same digest keeps the file through a failed write.
        let file = item_file(&repo_dir, "anonymous", "");
        std::fs::remove_file(&file).unwrap();
        std::fs::create_dir_all(file.join("block")).unwrap();
        repo.regenerate_summary(&fixed()).await.unwrap_err();
        assert_eq!(std::fs::read(&access).unwrap(), before);

        let config = repo_dir.join("config");
        let text = std::fs::read_to_string(&config).unwrap();
        std::fs::write(
            &config,
            text.replace("summary=true\n", "deny=other\nsummary=true\n"),
        )
        .unwrap();
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&fixed()).await.unwrap_err();
        assert!(!access.exists());

        std::fs::remove_dir_all(&file).unwrap();
        repo.regenerate_summary(&fixed()).await.unwrap();
        let after = std::fs::read(&access).unwrap();
        assert_ne!(after, before);
        assert_eq!(ref_names(&summary_of(&repo, "anonymous").await), ["main"]);
    });
}

/// A write keeps the `.access` file of an item that holds the access digest
/// of the item: the file is not written again.
#[test]
fn an_access_file_that_holds_the_digest_is_not_written_again() {
    use std::os::unix::fs::MetadataExt;

    let (_tmp, repo_dir) = writable_fixture("summary", "items-access-kept");
    block_on(async {
        let groups = "[ex-ostrya client \"public\"]\nauth=anonymous\nallow=r:**\nsummary=true\n\
                      [ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:main\nsummary=true\n";
        let repo = with_groups(&repo_dir, groups).await;
        repo.regenerate_summary(&fixed()).await.unwrap();
        let files = [
            item_file(&repo_dir, "anonymous", ".access"),
            item_file(&repo_dir, "ssh:ci", ".access"),
        ];
        let before: Vec<(u64, Vec<u8>)> = files
            .iter()
            .map(|file| {
                (
                    std::fs::metadata(file).unwrap().ino(),
                    std::fs::read(file).unwrap(),
                )
            })
            .collect();
        repo.set_ref_immediate(&Ref::local("main"), None)
            .await
            .unwrap();
        repo.regenerate_summary(&fixed()).await.unwrap();
        for (file, (ino, bytes)) in files.iter().zip(&before) {
            assert_eq!(std::fs::metadata(file).unwrap().ino(), *ino, "{file:?}");
            assert_eq!(&std::fs::read(file).unwrap(), bytes, "{file:?}");
        }
        assert!(ref_names(&summary_of(&repo, "ssh:ci").await).is_empty());
    });
}

/// Returns the names of the entries of the directory `dir`.
fn entry_names(dir: &Path) -> Vec<String> {
    std::fs::read_dir(dir)
        .unwrap()
        .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
        .collect()
}

/// Makes a FIFO at `path`.
fn make_fifo(path: &Path) {
    rustix::fs::mknodat(
        rustix::fs::CWD,
        path,
        rustix::fs::FileType::Fifo,
        rustix::fs::Mode::from_raw_mode(0o644),
        0,
    )
    .unwrap();
}

/// Each write of a summary makes its temp file in `tmp/`, and the open of
/// `tmp/` follows no symlink. A symlink at `tmp` fails the write of the
/// summaries, the write of the summaries of the items alone, and the signing
/// of the summaries with `tmp passes through a symlink`. The failure comes
/// before each change: each summary, each signature file, and each `.access`
/// file keeps its bytes, also an `.access` file that holds another digest.
/// The target of the symlink gets no entry.
#[test]
fn a_symlink_at_tmp_fails_each_summary_write() {
    let (tmp, repo_dir) = writable_fixture("summary", "summary-tmp-link");
    let other = tmp.path().join("other");
    std::fs::create_dir(&other).unwrap();
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        let signer = ostrya::DummySigner::new(b"sig".to_vec());
        repo.regenerate_summaries(&fixed(), &[&signer])
            .await
            .unwrap();
        let access = item_file(&repo_dir, "anonymous", ".access");
        std::fs::write(&access, b"another digest\n").unwrap();
        let files = [
            repo_dir.join("summary"),
            repo_dir.join("summary.sig"),
            item_file(&repo_dir, "anonymous", ""),
            item_file(&repo_dir, "anonymous", ".sig"),
            access,
        ];
        let before: Vec<Vec<u8>> = files.iter().map(|f| std::fs::read(f).unwrap()).collect();
        std::fs::remove_dir_all(repo_dir.join("tmp")).unwrap();
        std::os::unix::fs::symlink(&other, repo_dir.join("tmp")).unwrap();
        let repo = Repo::open(&repo_dir).await.unwrap();

        let symlinked = |result: ostrya::Result<()>, what: &str| match result {
            Err(ostrya::Error::InvalidFormat(m)) => {
                assert!(m.starts_with("tmp passes through a symlink"), "{what}: {m}");
            }
            other => panic!("{what}: {other:?}"),
        };
        let later = SummaryOptions {
            last_modified: Some(FIXED_EPOCH + 1),
            ..SummaryOptions::default()
        };
        symlinked(
            repo.regenerate_summaries(&later, &[&signer])
                .await
                .map(|_| ()),
            "regenerate",
        );
        symlinked(
            repo.regenerate_summaries(
                &SummaryOptions {
                    auth_items_only: true,
                    ..later.clone()
                },
                &[&signer],
            )
            .await
            .map(|_| ()),
            "regenerate the items",
        );
        symlinked(repo.sign_summary_all(&[&signer]).await, "sign");
        for (file, before) in files.iter().zip(&before) {
            assert_eq!(&std::fs::read(file).unwrap(), before, "{file:?}");
        }
        assert!(entry_names(&other).is_empty(), "{:?}", entry_names(&other));
    });
}

/// A write of the summaries and a signing leave no temp file: not at the
/// repository root, not in `extensions/ostrya/summary`, and not in `tmp/`.
#[test]
fn a_summary_write_leaves_no_temp_file() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-no-temp");
    block_on(async {
        let groups = "[ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:main\nsummary=true\n";
        let repo = with_groups(&repo_dir, groups).await;
        let signer = ostrya::DummySigner::new(b"sig".to_vec());
        repo.regenerate_summaries(&fixed(), &[&signer])
            .await
            .unwrap();
        repo.sign_summary_all(&[&signer]).await.unwrap();
        assert!(item_file(&repo_dir, "ssh:ci", ".sig").exists());
        for dir in [
            repo_dir.clone(),
            repo_dir.join("extensions/ostrya/summary"),
            repo_dir.join("tmp"),
        ] {
            let names = entry_names(&dir);
            assert!(
                !names.iter().any(|name| name.contains(".tmp-")),
                "{dir:?}: {names:?}"
            );
        }
    });
}

/// A read of a summary or of a signature file refuses a FIFO at once and a
/// symlink, with `InvalidFormat` and the path of the file, on the handle of a
/// plain open.
#[test]
fn a_summary_read_refuses_a_fifo_and_a_symlink() {
    let (_tmp, repo_dir) = writable_fixture("summary", "summary-read-fifo");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&fixed()).await.unwrap();
        let file = item_file(&repo_dir, "anonymous", "");
        let rel = file.strip_prefix(&repo_dir).unwrap().display().to_string();

        std::fs::remove_file(&file).unwrap();
        make_fifo(&file);
        let err = repo.read_summary_of(&item("anonymous")).await;
        assert!(
            matches!(&err, Err(ostrya::Error::InvalidFormat(m))
                if *m == format!("{rel} is not a regular file")),
            "{err:?}"
        );
        std::fs::remove_file(&file).unwrap();
        std::os::unix::fs::symlink("summary", &file).unwrap();
        let err = repo.read_summary_of(&item("anonymous")).await;
        assert!(
            matches!(&err, Err(ostrya::Error::InvalidFormat(m))
            if *m == format!(
                "{rel} passes through a symlink; ostrya refuses a symlink in the repository"
            )),
            "{err:?}"
        );

        make_fifo(&repo_dir.join("summary.sig"));
        let err = repo.read_summary_signature().await;
        assert!(
            matches!(&err, Err(ostrya::Error::InvalidFormat(m))
                if m == "summary.sig is not a regular file"),
            "{err:?}"
        );
        std::fs::remove_file(repo_dir.join("summary.sig")).unwrap();
        std::fs::rename(repo_dir.join("summary"), repo_dir.join("moved")).unwrap();
        std::os::unix::fs::symlink("moved", repo_dir.join("summary")).unwrap();
        let err = repo.read_summary().await;
        assert!(
            matches!(&err, Err(ostrya::Error::InvalidFormat(m))
                if m.starts_with("summary passes through a symlink")),
            "{err:?}"
        );
    });
}

/// An `.access` file that is a symlink or a FIFO holds no digest: the write
/// removes it and writes a regular file with the digest. The target of the
/// symlink does not change.
#[test]
fn an_access_entry_that_is_no_regular_file_is_written_again() {
    let (tmp, repo_dir) = writable_fixture("summary", "summary-access-entry");
    block_on(async {
        let repo = Repo::open(&repo_dir).await.unwrap();
        repo.regenerate_summary(&fixed()).await.unwrap();
        let access = item_file(&repo_dir, "anonymous", ".access");
        let want = std::fs::read(&access).unwrap();
        let target = tmp.path().join("target");
        std::fs::write(&target, &want).unwrap();

        std::fs::remove_file(&access).unwrap();
        std::os::unix::fs::symlink(&target, &access).unwrap();
        repo.regenerate_summary(&fixed()).await.unwrap();
        assert!(std::fs::symlink_metadata(&access).unwrap().is_file());
        assert_eq!(std::fs::read(&access).unwrap(), want);
        assert_eq!(std::fs::read(&target).unwrap(), want);

        std::fs::remove_file(&access).unwrap();
        make_fifo(&access);
        repo.regenerate_summary(&fixed()).await.unwrap();
        assert!(std::fs::symlink_metadata(&access).unwrap().is_file());
        assert_eq!(std::fs::read(&access).unwrap(), want);
    });
}

/// In a `bare-user-shared` repository, the directories that the write of the
/// summaries makes get the mode `02770`, and each summary file gets the mode
/// `0644`.
#[test]
fn the_summary_files_take_the_shared_modes() {
    use std::os::unix::fs::PermissionsExt;

    let tmp = TmpDir::new("summary-shared");
    let repo_dir = tmp.path().join("repo");
    block_on(async {
        let repo = Repo::create(
            &repo_dir,
            ostrya::CreateOptions::new(RepoMode::BareUserShared),
        )
        .await
        .unwrap();
        let signer = ostrya::DummySigner::new(b"sig".to_vec());
        repo.regenerate_summaries(&fixed(), &[&signer])
            .await
            .unwrap();
        let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o7777;
        for dir in ["extensions/ostrya", "extensions/ostrya/summary"] {
            assert_eq!(mode(&repo_dir.join(dir)), 0o2770, "{dir}");
        }
        let files = [
            repo_dir.join("summary"),
            repo_dir.join("summary.sig"),
            item_file(&repo_dir, "anonymous", ""),
            item_file(&repo_dir, "anonymous", ".sig"),
            item_file(&repo_dir, "anonymous", ".access"),
        ];
        for file in &files {
            assert_eq!(mode(file), 0o644, "{file:?}");
        }
    });
}

/// In a `bare-user-private` repository, the directories and the files that the
/// write of the summaries makes get the same modes as in a `bare-user`
/// repository in the same process. No directory gets the set-group-ID bit or
/// the shared mode `02770`. The root summary states the mode
/// `bare-user-private`.
#[test]
fn the_summary_files_take_the_default_modes_in_a_private_repository() {
    use std::os::unix::fs::PermissionsExt;

    let tmp = TmpDir::new("summary-private");
    let plain = tmp.path().join("bare-user");
    let private = tmp.path().join("bare-user-private");
    block_on(async {
        for (repo_dir, mode) in [
            (&plain, RepoMode::BareUser),
            (&private, RepoMode::BareUserPrivate),
        ] {
            let repo = Repo::create(repo_dir, ostrya::CreateOptions::new(mode))
                .await
                .unwrap();
            let signer = ostrya::DummySigner::new(b"sig".to_vec());
            repo.regenerate_summaries(&fixed(), &[&signer])
                .await
                .unwrap();
        }
    });
    let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o7777;
    for dir in ["extensions/ostrya", "extensions/ostrya/summary"] {
        let got = mode(&private.join(dir));
        assert_eq!(got, mode(&plain.join(dir)), "{dir}");
        assert_eq!(got & 0o2000, 0, "set-group-ID bit on {dir}");
        assert_ne!(got, 0o2770, "shared mode on {dir}");
    }
    let files = |repo_dir: &Path| {
        [
            repo_dir.join("summary"),
            repo_dir.join("summary.sig"),
            item_file(repo_dir, "anonymous", ""),
            item_file(repo_dir, "anonymous", ".sig"),
            item_file(repo_dir, "anonymous", ".access"),
        ]
    };
    for (file, reference) in files(&private).iter().zip(files(&plain)) {
        assert_eq!(mode(file), mode(&reference), "{file:?}");
    }

    let bytes = std::fs::read(private.join("summary")).unwrap();
    let summary = Summary::parse(&bytes).unwrap();
    assert_eq!(
        summary.metadata_value("ostree.summary.mode"),
        Some(&Value::Str("bare-user-private".into()))
    );
}

// ---------------------------------------------------------------------------
// The summary write under `[core] auto-update-summary`.
// ---------------------------------------------------------------------------

/// The bytes that a test writes into `summary.sig` before a call, so that a
/// removal and a keep of the file are visible.
const MARKER: &[u8] = b"marker signature";

/// Copies the fixture `fixture`, appends `config` to its config, writes
/// [`MARKER`] into `summary.sig`, and opens the copy.
///
/// The config of each summary fixture ends in `[core]`, so a key at the start
/// of `config` goes into `[core]`.
async fn auto_fixture(
    fixture: &str,
    tag: &str,
    config: &str,
) -> (TmpDir, std::path::PathBuf, Repo) {
    let (tmp, repo_dir) = writable_fixture(fixture, tag);
    std::fs::write(repo_dir.join("summary.sig"), MARKER).unwrap();
    let repo = with_groups(&repo_dir, config).await;
    (tmp, repo_dir, repo)
}

/// Writes the ed25519 secret key `secret_b64` to `path` as one line.
fn write_secret(path: &Path, secret_b64: &str) {
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, format!("\n{secret_b64}\n")).unwrap();
}

/// An ed25519 key group `name` whose key is `file`.
fn ed25519_group(name: &str, file: &Path) -> String {
    format!(
        "[ex-ostrya key \"{name}\"]\ntype=ed25519\nsecret-key-file={}\n",
        file.display()
    )
}

/// Returns the keys of the dict in `summary.sig` of `repo_dir`, in stored
/// order.
fn signature_keys(repo_dir: &Path) -> Vec<String> {
    let bytes = std::fs::read(repo_dir.join("summary.sig")).unwrap();
    let dict = ostrya::from_bytes(&ostrya::Type::parse("a{sv}").unwrap(), &bytes).unwrap();
    dict.as_array()
        .unwrap()
        .iter()
        .map(|entry| entry.as_tuple().unwrap()[0].as_str().unwrap().to_owned())
        .collect()
}

/// With the key absent or false, the call returns `None` and writes nothing.
/// It reads no other group, so a `sign-summary` value that names no key
/// group does not stop it.
#[test]
fn an_auto_update_with_the_key_off_writes_nothing() {
    for (case, config) in [
        ("absent", ""),
        ("false", "auto-update-summary=false\n"),
        ("alias-false", "commit-update-summary=false\n"),
        (
            "both-false",
            "auto-update-summary=false\ncommit-update-summary=false\n",
        ),
    ] {
        let config = format!("{config}[ex-ostrya server]\nsign-summary=nosuch\n");
        block_on(async {
            let (_tmp, repo_dir, repo) =
                auto_fixture("summary", &format!("auto-off-{case}"), &config).await;
            let report = repo.regenerate_summaries_if_configured().await.unwrap();
            assert!(report.is_none(), "{case}");
            assert!(!repo_dir.join("summary").exists(), "{case}");
            assert_eq!(
                std::fs::read(repo_dir.join("summary.sig")).unwrap(),
                MARKER,
                "{case}"
            );
        });
    }
}

/// With the key true, the call writes the summary of each ref and removes
/// the old `summary.sig`. A value of `commit-update-summary` does not change
/// the result.
#[test]
fn an_auto_update_with_the_key_on_writes_the_summary() {
    for (case, config) in [
        ("key", "auto-update-summary=true\n"),
        (
            "key-and-alias-false",
            "auto-update-summary=true\ncommit-update-summary=false\n",
        ),
        (
            "key-and-alias-yes",
            "auto-update-summary=true\ncommit-update-summary=yes\n",
        ),
    ] {
        block_on(async {
            let (_tmp, repo_dir, repo) =
                auto_fixture("summary", &format!("auto-on-{case}"), config).await;
            let report = repo.regenerate_summaries_if_configured().await.unwrap();
            let report = report.expect("the key is on");
            assert!(report.invalid_collection_dirs.is_empty(), "{case}");
            let summary =
                Summary::parse(&std::fs::read(repo_dir.join("summary")).unwrap()).unwrap();
            assert_eq!(ref_names(&summary), ["main", "other"], "{case}");
            assert!(!repo_dir.join("summary.sig").exists(), "{case}");
        });
    }
}

/// The call does not read `commit-update-summary`. With that key alone, true
/// or not a boolean, the call returns `None` and writes nothing.
#[test]
fn an_auto_update_ignores_commit_update_summary() {
    for (case, config) in [
        ("true", "commit-update-summary=true\n"),
        ("yes", "commit-update-summary=yes\n"),
    ] {
        block_on(async {
            let (_tmp, repo_dir, repo) =
                auto_fixture("summary", &format!("auto-alias-{case}"), config).await;
            let report = repo.regenerate_summaries_if_configured().await.unwrap();
            assert!(report.is_none(), "{case}");
            assert!(!repo_dir.join("summary").exists(), "{case}");
            assert_eq!(
                std::fs::read(repo_dir.join("summary.sig")).unwrap(),
                MARKER,
                "{case}"
            );
        });
    }
}

/// A value of the key that is not a boolean is an `Error::Core`, also when
/// `commit-update-summary` is true. The call writes nothing.
#[test]
fn an_auto_update_refuses_a_value_that_is_not_a_boolean() {
    for (case, config) in [
        ("key", "auto-update-summary=yes\n"),
        (
            "key-alias-true",
            "auto-update-summary=yes\ncommit-update-summary=true\n",
        ),
    ] {
        block_on(async {
            let (_tmp, repo_dir, repo) =
                auto_fixture("summary", &format!("auto-bad-{case}"), config).await;
            let err = repo.regenerate_summaries_if_configured().await.unwrap_err();
            assert!(matches!(err, ostrya::Error::Core(_)), "{case}: {err}");
            assert!(!repo_dir.join("summary").exists(), "{case}");
            assert_eq!(
                std::fs::read(repo_dir.join("summary.sig")).unwrap(),
                MARKER,
                "{case}"
            );
        });
    }
}

/// The key group that `sign-summary` names signs the summary. The new
/// `summary.sig` holds its signature alone, and the signature verifies.
#[test]
fn an_auto_update_signs_with_the_sign_summary_groups() {
    let tmp = TmpDir::new("auto-sign-key");
    let key = tmp.path().join("secret.ed25519");
    write_secret(&key, SECRET_B64);
    let config = format!(
        "auto-update-summary=true\n[ex-ostrya server]\nsign-summary=e\n{}",
        ed25519_group("e", &key)
    );
    block_on(async {
        let (_fixture, repo_dir, repo) = auto_fixture("summary", "auto-sign", &config).await;
        repo.regenerate_summaries_if_configured()
            .await
            .unwrap()
            .expect("the key is on");
        assert_eq!(signature_keys(&repo_dir), ["ostree.sign.ed25519"]);
        let public = base64::decode(PUBLIC_B64).unwrap();
        let trusted = Ed25519Verifier::new([public], Vec::<Vec<u8>>::new()).unwrap();
        let outcome = repo.verify_summary(&[Arc::new(trusted)]).await.unwrap();
        assert!(outcome.valid);
    });
}

/// A GPG key group signs before an ed25519 key group, also when
/// `sign-summary` names the ed25519 group first.
#[cfg(feature = "sign-gpg")]
#[test]
fn an_auto_update_signs_with_the_gpg_keys_first() {
    if !common::gnupg_available(&["gpg", "gpgconf"]) {
        return;
    }
    let tmp = TmpDir::new("auto-sign-gpg");
    let home = common::GnupgHome::new(&tmp.path().join("gnupg"), "Signer <signer@example.org>");
    let key = tmp.path().join("secret.ed25519");
    write_secret(&key, SECRET_B64);
    let config = format!(
        "auto-update-summary=true\n[ex-ostrya server]\nsign-summary=e;g\n{}\
         [ex-ostrya key \"g\"]\ntype=gpg\ngpg-key=signer@example.org\ngpg-homedir={}\n",
        ed25519_group("e", &key),
        home.dir.display()
    );
    block_on(async {
        let (_fixture, repo_dir, repo) = auto_fixture("summary", "auto-gpg", &config).await;
        repo.regenerate_summaries_if_configured()
            .await
            .unwrap()
            .expect("the key is on");
        assert_eq!(
            signature_keys(&repo_dir),
            ["ostree.gpgsigs", "ostree.sign.ed25519"]
        );
    });
}

/// A key group that `sign-summary` does not name is not built, so a broken
/// definition of such a group does not stop the call.
#[test]
fn an_auto_update_builds_no_key_group_that_sign_summary_does_not_name() {
    let tmp = TmpDir::new("auto-sign-other");
    let key = tmp.path().join("secret.ed25519");
    write_secret(&key, SECRET_B64);
    let config = format!(
        "auto-update-summary=true\n[ex-ostrya server]\nsign-summary=e\n{}\
         [ex-ostrya key \"broken\"]\ntype=dummy\nsecret-key-file=/nonexistent\n\
         [ex-ostrya key \"absent\"]\ntype=ed25519\nsecret-key-file=/nonexistent\n",
        ed25519_group("e", &key)
    );
    block_on(async {
        let (_fixture, repo_dir, repo) = auto_fixture("summary", "auto-other", &config).await;
        repo.regenerate_summaries_if_configured()
            .await
            .unwrap()
            .expect("the key is on");
        assert_eq!(signature_keys(&repo_dir), ["ostree.sign.ed25519"]);
    });
}

/// A `sign-summary` value that names no key group, and a named key group
/// that cannot be built, are errors. The call writes nothing.
#[test]
fn an_auto_update_with_a_bad_sign_summary_group_writes_nothing() {
    let tmp = TmpDir::new("auto-sign-bad");
    let key = tmp.path().join("secret.ed25519");
    write_secret(&key, SECRET_B64);
    let absent = tmp.path().join("absent.ed25519");
    let cases = [
        (
            "unknown",
            "auto-update-summary=true\n[ex-ostrya server]\nsign-summary=nosuch\n".to_owned(),
        ),
        (
            "no-key-file",
            format!(
                "auto-update-summary=true\n[ex-ostrya server]\nsign-summary=e;a\n{}{}",
                ed25519_group("e", &key),
                ed25519_group("a", &absent)
            ),
        ),
    ];
    for (case, config) in &cases {
        block_on(async {
            let (_fixture, repo_dir, repo) =
                auto_fixture("summary", &format!("auto-bad-group-{case}"), config).await;
            let err = repo.regenerate_summaries_if_configured().await.unwrap_err();
            match *case {
                "unknown" => assert!(
                    matches!(&err, ostrya::Error::InvalidFormat(m) if m.contains("nosuch")),
                    "{err}"
                ),
                _ => assert!(
                    matches!(&err, ostrya::Error::Signature(m)
                        if m.starts_with("[ex-ostrya key \"a\"]: ")),
                    "{err}"
                ),
            }
            assert!(!repo_dir.join("summary").exists(), "{case}");
            assert_eq!(
                std::fs::read(repo_dir.join("summary.sig")).unwrap(),
                MARKER,
                "{case}"
            );
        });
    }
}

/// With a collection id, the call writes no new anchor commit. The
/// `ostree-metadata` ref stays, no commit object is added, and the summary
/// lists `ostree-metadata` at its current commit. A summary update with
/// `regenerate_summaries` still writes a new anchor commit.
#[test]
fn an_auto_update_with_a_collection_id_writes_no_anchor_commit() {
    block_on(async {
        let (_tmp, repo_dir, repo) = auto_fixture(
            "summary-collection",
            "auto-collection",
            "auto-update-summary=true\n",
        )
        .await;
        repo.regenerate_summary(&fixed()).await.unwrap();
        let anchor = Ref::local("ostree-metadata");
        let tip = repo.resolve_ref_tip(&anchor).await.unwrap();
        let tip = tip.expect("the anchor was written");
        let objects = common::file_inventory(&repo_dir, "objects");
        let refs = common::file_inventory(&repo_dir, "refs");
        std::fs::write(repo_dir.join("summary.sig"), MARKER).unwrap();

        repo.regenerate_summaries_if_configured()
            .await
            .unwrap()
            .expect("the key is on");
        assert_eq!(repo.resolve_ref_tip(&anchor).await.unwrap(), Some(tip));
        assert_eq!(common::file_inventory(&repo_dir, "objects"), objects);
        assert_eq!(common::file_inventory(&repo_dir, "refs"), refs);
        assert!(!repo_dir.join("summary.sig").exists());
        let summary = Summary::parse(&std::fs::read(repo_dir.join("summary")).unwrap()).unwrap();
        let entry = summary
            .refs
            .iter()
            .find(|entry| entry.name == "ostree-metadata")
            .expect("the summary lists the anchor");
        assert_eq!(entry.commit, tip);
        assert!(ref_names(&summary).iter().any(|name| name == "main"));

        repo.regenerate_summary(&fixed()).await.unwrap();
        let next = repo.resolve_ref_tip(&anchor).await.unwrap();
        assert!(next.is_some_and(|next| next != tip));
    });
}