ostrya 0.16.0

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
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
//! The resolution of a remote to an [`Endpoint`].
//!
//! [`resolve_pull`] and `resolve_push` read the keys of a remote section of
//! the repository config, read the files that the keys name, and give an
//! [`Endpoint`] that holds all values in memory. The `push` feature gates
//! `resolve_push`. [`EndpointOverrides`] holds the values of the caller. A
//! value of the caller wins over its remote key.
//!
//! With the `s3` feature, [`resolve_pull`] also gives the endpoint of a pull
//! from an `s3://` address, and `resolve_push` the endpoint of a push to an
//! `s3://` address. `resolve_bucket` gives the endpoint of each other writer
//! of a bucket repository, for example the init. They read the AWS
//! credentials and settings from the environment of the process and from the
//! shared AWS files. A build without the feature refuses an `s3://` address.
//! [`pull_address_is_s3`] tells if the address of a pull is an `s3://`
//! address, with no file and no environment. `check_push` makes each refusal
//! of `resolve_push` that needs no file, the refusals of
//! `PushSession::prepare` that need no file, and the parse of an `s3://`
//! address. It gives the kind of the
//! push.
//!
//! [`Repo::pull`](crate::Repo::pull) calls [`resolve_pull`] with
//! [`PullOptions::overrides`](crate::PullOptions::overrides).
//! [`Repo::remote_fetch_summary_with`](crate::Repo::remote_fetch_summary_with)
//! calls it with the overrides of the caller, and
//! [`Repo::remote_fetch_summary`](crate::Repo::remote_fetch_summary) with
//! the default overrides. A caller that selects its own server opens a
//! [`PullSession`](crate::remote::PullSession) and calls
//! [`Repo::pull_with_session`](crate::Repo::pull_with_session).
//!
//! A resolver reads the token file and the PEM files of one endpoint in one
//! job on the blocking pool. A path of a key in `config` is absolute, or
//! relative to the repository root. A path of a key in a `.conf` file of the
//! remotes directory is absolute, or relative to that directory. A path of
//! the caller is absolute, or relative to the working directory. A relative
//! path with a `..` component is refused. The read follows a symlink at each
//! component, opens the file with `O_NONBLOCK`, and refuses each file that is
//! not a regular file, so a FIFO does not block the read.
//! [`Remote`](crate::config::Remote#paths) states the rules of a key. The read
//! of a PEM file takes at most 1 MiB and one byte. The read of a token file
//! stops at the first LF, and takes at most 1 MiB and one byte. Each error
//! names the key and the path.
//!
//! The trust policy of the remote keys is in the resolvers. [`resolve_pull`]
//! maps `tls-permissive=true` to [`TrustRoots::DangerousAcceptAnyChain`], for
//! an HTTP address and for an `s3://` address. `resolve_push` refuses
//! `tls-permissive=true` for an `https://` address and for an `s3://`
//! address, and `resolve_bucket` refuses it.
//! A caller that builds an [`Endpoint`] itself sets the trust policy of its
//! own.

use std::fmt;
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::config::{KeyPath, Remote, RepoConfig, io_of, relative_with_parent};
use crate::error::{Error, Result};
#[cfg(feature = "push")]
use crate::fetch::{BasicAuth, BearerToken};
use crate::fetch::{ClientIdentity, FetcherOptions, LowSpeed, Proxy, TrustRoots};
use crate::remote::{self, Endpoint, SshAddress, SshOptions};
use crate::repo::Repo;
use crate::repo_fs::{FsError, Named, Reason, open_named};

/// The largest first line of a token file, and the largest PEM file: 1 MiB.
const FILE_CAP: u64 = 1 << 20;

/// The retry count of a pull if the caller names no count.
const PULL_RETRIES: u32 = 5;
/// The number of requests of a pull in flight.
const PULL_OUTSTANDING: usize = 8;
/// The rate in bytes per second at or below which the fetcher stops a
/// transfer, if the caller names no rate.
const DEFAULT_LOW_SPEED_LIMIT: u32 = 1000;
/// The time that the rate can stay at or below the limit, if the caller names
/// no time.
const DEFAULT_LOW_SPEED_TIME: Duration = Duration::from_secs(30);

/// The values of the caller for [`resolve_pull`] and `resolve_push`.
///
/// A field that is `None`, `false`, or empty sets nothing. A field that a
/// remote key backs wins over that key. Each field resolves on its own.
///
/// A resolver refuses a field that applies to the other direction or to the
/// other transport. The refusal names the field by its remote key, or by the
/// option of the `ostrya` command that sets it.
///
/// A path field is a path of the caller. A relative path is relative to the
/// working directory of the process, and a resolver refuses a relative path
/// with a `..` component. The paths of the remote keys have other bases, as
/// [`Remote`](crate::config::Remote#paths) states.
///
/// The [`Debug`] output shows `url` and `s3_endpoint` without their
/// userinfo, and shows `<redacted>` in place of each header value.
///
/// The struct carries no `#[non_exhaustive]`. A caller builds it with
/// `..Default::default()`.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct EndpointOverrides {
    /// The address of a pull. It wins over the keys `pull-url` and `url`.
    ///
    /// `resolve_push` refuses it.
    pub url: Option<String>,
    /// The token file of a push. It wins over the key `push-token-file`.
    ///
    /// [`resolve_pull`] refuses it. `resolve_push` refuses it for an
    /// `s3://` address.
    pub push_token_file: Option<PathBuf>,
    /// The user name of a Basic credential of a push. It wins over the key
    /// `push-user`. The token is the password.
    ///
    /// [`resolve_pull`] refuses it. `resolve_push` refuses it for an
    /// `s3://` address.
    pub push_user: Option<String>,
    /// The PEM file of the trust anchors. It wins over the key `tls-ca-path`.
    pub tls_ca_path: Option<PathBuf>,
    /// The PEM file of the client certificate chain. It wins over the key
    /// `tls-client-cert-path`.
    pub tls_client_cert_path: Option<PathBuf>,
    /// The PEM file of the client key. It wins over the key
    /// `tls-client-key-path`. The key must need no passphrase.
    pub tls_client_key_path: Option<PathBuf>,
    /// The ssh program and its arguments. It goes to
    /// [`SshOptions::command`].
    pub ssh_command: Option<Vec<String>>,
    /// The command that the remote side runs over ssh. For a push, it wins
    /// over the key `receive-command`. For a pull, it wins over the key
    /// `send-command`. It goes to [`SshOptions::remote_command`].
    pub remote_command: Option<String>,
    /// The permission for a credential to go to an `http://` address. No
    /// remote key sets it.
    pub allow_cleartext_credentials: bool,
    /// The extra headers of each HTTP request, as name and value pairs.
    pub http_headers: Vec<(String, String)>,
    /// The number of times that the HTTP client repeats a round after a
    /// retryable failure. A value of 0 turns the retries off.
    pub max_retries: Option<u32>,
    /// The lowest transfer rate in bytes per second. A value of 0 turns the
    /// low-speed check off.
    pub low_speed_limit_bytes: Option<u32>,
    /// The longest time that the rate can stay at the limit or less. A value
    /// of zero turns the low-speed check off.
    pub low_speed_time: Option<Duration>,
    /// The region of the signature of each request to an `s3://` address. It
    /// wins over the key `s3-region`.
    ///
    /// [`resolve_pull`] and `resolve_push` refuse it for another address.
    pub s3_region: Option<String>,
    /// The `http://` or `https://` URL of the S3 server of an `s3://` address.
    /// It wins over the key `s3-endpoint`.
    ///
    /// [`resolve_pull`] and `resolve_push` refuse it for another address.
    pub s3_endpoint: Option<String>,
    /// The addressing style of the bucket of an `s3://` address: `path` or
    /// `virtual`. It wins over the key `s3-addressing`.
    ///
    /// [`resolve_pull`] and `resolve_push` refuse it for another address.
    pub s3_addressing: Option<String>,
    /// The profile of the shared AWS files for an `s3://` address. It wins
    /// over the key `s3-profile`.
    ///
    /// [`resolve_pull`] and `resolve_push` refuse it for another address.
    pub s3_profile: Option<String>,
}

impl fmt::Debug for EndpointOverrides {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let EndpointOverrides {
            url,
            push_token_file,
            push_user,
            tls_ca_path,
            tls_client_cert_path,
            tls_client_key_path,
            ssh_command,
            remote_command,
            allow_cleartext_credentials,
            http_headers,
            max_retries,
            low_speed_limit_bytes,
            low_speed_time,
            s3_region,
            s3_endpoint,
            s3_addressing,
            s3_profile,
        } = self;
        // A url can hold a password, and a header value can be a credential.
        let headers: Vec<(&str, &str)> = http_headers
            .iter()
            .map(|(name, _)| (name.as_str(), "<redacted>"))
            .collect();
        f.debug_struct("EndpointOverrides")
            .field("url", &url.as_deref().map(remote::without_userinfo))
            .field("push_token_file", push_token_file)
            .field("push_user", push_user)
            .field("tls_ca_path", tls_ca_path)
            .field("tls_client_cert_path", tls_client_cert_path)
            .field("tls_client_key_path", tls_client_key_path)
            .field("ssh_command", ssh_command)
            .field("remote_command", remote_command)
            .field("allow_cleartext_credentials", allow_cleartext_credentials)
            .field("http_headers", &headers)
            .field("max_retries", max_retries)
            .field("low_speed_limit_bytes", low_speed_limit_bytes)
            .field("low_speed_time", low_speed_time)
            .field("s3_region", s3_region)
            .field(
                "s3_endpoint",
                &s3_endpoint.as_deref().map(remote::without_userinfo),
            )
            .field("s3_addressing", s3_addressing)
            .field("s3_profile", s3_profile)
            .finish()
    }
}

/// Returns the refusal of an endpoint that is neither ssh nor HTTP, for
/// example an S3 endpoint, by `operation`.
pub(crate) fn neither_ssh_nor_http(operation: &str) -> Error {
    Error::Unsupported(format!(
        "{operation} takes an ssh or an HTTP endpoint, and this endpoint is neither"
    ))
}

/// The environment that the resolution of an `s3://` address reads.
///
/// With the `s3` feature, it is the environment of
/// `ostrya_remote::s3::resolve`. A build without the feature reads no
/// environment for an `s3://` address, because it refuses the address.
#[cfg(feature = "s3")]
pub(crate) type S3Environment = remote::s3::Environment;
/// The environment that the resolution of an `s3://` address reads.
///
/// A build without the `s3` feature refuses an `s3://` address, so it reads
/// no environment for it.
#[cfg(not(feature = "s3"))]
pub(crate) type S3Environment = ();

/// Resolves the remote `remote` of the config of `repo` to the endpoint of a
/// pull.
///
/// With no `repo`, no remote has a section, and the values of the caller
/// apply alone.
///
/// # Address
///
/// The address is the first of these that is set: [`EndpointOverrides::url`],
/// the key `pull-url`, and the key `url`. An address that starts with
/// `s3://` is the address of a bucket repository. An address that starts with
/// `ssh://`, or that holds no `://`, is an ssh address, and
/// [`SshAddress::parse`] reads it. Each other address is an HTTP address, and
/// goes to the fetcher as written. The key `url` cannot hold an ssh address
/// or an `s3://` address, because the `ostree` command also reads it. The
/// function ignores the keys `contenturl` and `metalink`.
///
/// The fetcher refuses a `file://` address.
/// [`Repo::pull_collection`](crate::Repo::pull_collection) reads a remote at
/// a `file://` address as a local repository, and does not call this
/// function for it.
///
/// A `url` of the caller replaces the address alone. The TLS keys, the key
/// `proxy`, the ssh keys, and the S3 keys of the section still apply.
///
/// The S3 keys are `s3-region`, `s3-endpoint`, `s3-addressing`, and
/// `s3-profile`. The function refuses a section that sets one of them if
/// neither `pull-url` nor `push-url` of the section holds an `s3://` address.
/// It makes this check for each address.
///
/// # HTTP address
///
/// The function gives [`Endpoint::Http`] with these values:
///
/// - The trust anchors are the PEM file of `tls_ca_path` or of the key
///   `tls-ca-path`. If the caller gives no `tls_ca_path` and the section sets
///   `tls-permissive=true`, the trust setting is
///   [`TrustRoots::DangerousAcceptAnyChain`], and the function does not read
///   the key `tls-ca-path`. With neither, the trust setting is
///   [`TrustRoots::System`].
/// - The client certificate and its key come from `tls_client_cert_path` and
///   `tls_client_key_path`, or from their keys. The key must need no
///   passphrase.
/// - The proxy is the key `proxy`. An empty or absent key, or no section,
///   gives [`Proxy::Environment`].
/// - The headers and the cleartext permission are the values of the caller.
/// - The retry count is `max_retries`, or 5. A value of 0 turns the retries
///   off.
/// - The number of requests in flight is 8.
/// - The low-speed rule takes 1000 bytes per second for 30 seconds in place
///   of a field left `None`. A zero in either field turns the rule off.
///
/// No field of [`EndpointOverrides`] sets the other fields of
/// [`FetcherOptions`], for example the timeouts or the number of requests in
/// flight. A caller changes them in the returned endpoint.
///
/// # ssh address
///
/// The function gives [`Endpoint::Ssh`]. `ssh_command` gives
/// [`SshOptions::command`], and the key `ssh-command` gives
/// [`SshOptions::config_command`]. `remote_command`, or else the key
/// `send-command`, gives [`SshOptions::remote_command`].
///
/// # S3 address
///
/// The address `s3://BUCKET[/PREFIX]` names a bucket repository. A build
/// with the `s3` feature gives `Endpoint::S3` with these values:
///
/// - The region, the endpoint, the addressing style, and the profile are the
///   fields `s3_region`, `s3_endpoint`, `s3_addressing`, and `s3_profile` of
///   the caller, else the keys of the same names. `S3Endpoint::resolve` of
///   `ostrya_remote::s3` gives each setting that neither one sets, and the
///   key pair, from the environment of the process, from the shared AWS
///   files, and from the defaults. `ostrya_remote::s3::resolve` states the
///   order of these sources.
/// - The HTTP options are the options of an HTTP address in the list
///   above. `S3Endpoint::pull_options` adds the mirror of the bucket
///   repository, the signer, and no redirect when the pull opens its
///   session.
///
/// The function ignores the keys `ssh-command` and `send-command` for an
/// `s3://` address.
///
/// # Errors
///
/// The function makes each refusal that needs no file before it reads a file.
///
/// - [`Error::InvalidInput`] if the caller sets `push_token_file` or
///   `push_user`.
/// - [`Error::Pull`] if `config` holds no section for `remote` and the caller
///   gives no `url`, or if the section has neither `pull-url` nor `url`.
/// - [`Error::Pull`] if the key `url` holds an ssh address or an `s3://`
///   address. The message shows the value without the text up to its last
///   `@`.
/// - [`Error::Pull`] if the section sets an S3 key, and neither `pull-url`
///   nor `push-url` holds an `s3://` address. The message names the key.
/// - [`Error::InvalidInput`] with the text of the parser if an ssh address is
///   malformed.
/// - [`Error::InvalidInput`] for an HTTP address or an ssh address if the
///   caller sets `s3_region`, `s3_endpoint`, `s3_addressing`, or
///   `s3_profile`. The message names the first such field by its key.
/// - [`Error::InvalidInput`] for an HTTP address or an `s3://` address if the
///   caller sets `ssh_command` or `remote_command`.
/// - [`Error::Pull`] for an HTTP address or an `s3://` address if a client
///   certificate has no key, or a key has no certificate.
/// - [`Error::Unsupported`] if the key `proxy` has white space at its start
///   or its end.
/// - [`Error::InvalidInput`] for an ssh address if the caller sets a field of
///   an HTTP address: a TLS path, `allow_cleartext_credentials`,
///   `http_headers`, a `max_retries` above 0, or a low-speed field. The
///   message names the first such field and shows the address without its
///   user.
/// - [`Error::Unsupported`] for an `s3://` address in a build without the
///   `s3` feature. The message names the feature.
/// - [`Error::InvalidInput`] for an `s3://` address if the addressing style
///   is neither `path` nor `virtual`.
/// - For an `s3://` address, the errors of `S3Endpoint::resolve`. A refused
///   address, a refused setting, and no key pair are
///   [`Error::InvalidInput`]. A shared AWS file that exists and cannot be
///   read is [`Error::Io`].
/// - [`Error::InvalidInput`] for an `s3://` address if the endpoint is
///   `http://`, and the caller does not set `allow_cleartext_credentials`.
///   The signature of each request would go to the server in cleartext. The
///   check comes after the read of the shared AWS files, because the
///   endpoint can come from them.
/// - [`Error::InvalidInput`] if a TLS path of the caller is a relative path
///   with a `..` component.
/// - [`Error::InvalidFormat`] if a TLS key is a relative path with a `..`
///   component.
/// - The errors of the read of a PEM file: [`Error::Io`] if the file cannot
///   be opened or read, and [`Error::InvalidInput`] if it is not a regular
///   file or is larger than 1 MiB. The message names the key and the path,
///   and holds no byte of the file.
/// - [`Error::Core`] if a key that the function reads holds a malformed
///   escape sequence, or if `tls-permissive` is not a boolean.
pub async fn resolve_pull(
    repo: Option<&Repo>,
    remote: &str,
    overrides: EndpointOverrides,
) -> Result<Endpoint> {
    resolve_pull_in(repo, remote, overrides, &S3Environment::default()).await
}

/// Resolves the remote `remote` to the endpoint of a pull, as
/// [`resolve_pull`] does, with `env` as the environment of an `s3://`
/// address.
#[cfg_attr(not(feature = "s3"), allow(unused_variables))]
pub(crate) async fn resolve_pull_in(
    repo: Option<&Repo>,
    remote: &str,
    overrides: EndpointOverrides,
    env: &S3Environment,
) -> Result<Endpoint> {
    let mut o = overrides;
    let section = repo.and_then(|repo| repo.config().remote(remote));
    if let Some(name) = push_field(&o) {
        return Err(Error::InvalidInput(format!(
            "{name} applies to a push, and this is a pull"
        )));
    }
    let address = pull_address(section.as_ref(), remote, o.url.take())?;
    check_s3_keys(remote, section.as_ref())?;
    let endpoint = match address {
        PullAddress::Endpoint(endpoint) => endpoint,
        PullAddress::S3(address) => {
            #[cfg(feature = "s3")]
            return Box::pin(pull_s3(remote, section.as_ref(), &address, o, env, repo)).await;
            #[cfg(not(feature = "s3"))]
            return Err(Error::Unsupported(format!(
                "the pull address '{}' is an s3:// address, and this build of ostrya has no S3 \
                 support: turn on the feature s3 of ostrya",
                remote::without_userinfo(&address)
            )));
        }
    };
    match endpoint {
        Endpoint::Http(http) => pull_http(remote, section.as_ref(), http, o, repo).await,
        Endpoint::Ssh { address, .. } => {
            if let Some(name) = s3_field(&o) {
                return Err(Error::InvalidInput(format!(
                    "{name} applies to a pull from an s3:// address, and '{}' is an ssh address",
                    address.without_user()
                )));
            }
            if let Some(name) = http_field(&o) {
                return Err(Error::InvalidInput(format!(
                    "{name} applies to a pull over HTTP, and '{}' is an ssh address",
                    address.without_user()
                )));
            }
            let (config_command, remote_command) = match &section {
                Some(section) => (
                    section.ssh_command()?,
                    match o.remote_command {
                        Some(command) => Some(command),
                        None => section.send_command()?,
                    },
                ),
                None => (None, o.remote_command),
            };
            Ok(Endpoint::Ssh {
                address,
                options: SshOptions {
                    command: o.ssh_command,
                    config_command,
                    remote_command,
                },
            })
        }
        _ => Err(neither_ssh_nor_http("a pull")),
    }
}

/// The address of a pull.
// The endpoint variant is much larger than the S3 variant. A pull resolves
// one address, so a box saves no work, and the variant stays inline.
#[allow(clippy::large_enum_variant)]
enum PullAddress {
    /// An ssh or an HTTP address, as an endpoint with default options.
    Endpoint(Endpoint),
    /// An `s3://` address, as written.
    S3(String),
}

/// Returns the address of a pull of `remote`, from `url` of the caller, or
/// else from `section`.
fn pull_address(
    section: Option<&Remote<'_>>,
    remote: &str,
    url: Option<String>,
) -> Result<PullAddress> {
    if let Some(url) = url {
        return parse_pull_address(&url);
    }
    let section =
        section.ok_or_else(|| Error::Pull(format!("no remote '{remote}' is configured")))?;
    if let Some(pull_url) = section.pull_url()? {
        return parse_pull_address(&pull_url);
    }
    match section.url()? {
        Some(url) if is_s3(&url) => Err(Error::Pull(format!(
            "remote '{remote}': url '{}' is an s3:// address; the port reads an s3:// \
             address from pull-url alone",
            remote::without_userinfo(&url)
        ))),
        Some(url) if is_ssh(&url) && is_ssh_address(&url) => Err(Error::Pull(format!(
            "remote '{remote}': url '{}' is an ssh address; the port reads an ssh \
             address from pull-url alone",
            remote::without_userinfo(&url)
        ))),
        Some(url) => Ok(PullAddress::Endpoint(Endpoint::Http(FetcherOptions::new(
            url,
        )))),
        None => Err(Error::Pull(format!(
            "remote '{remote}' has no pull-url and no url"
        ))),
    }
}

/// Returns `Some(true)` if the address of a pull of `remote` is an `s3://`
/// address, `Some(false)` if it is an HTTP or an ssh address, and `None` if
/// [`resolve_pull`] refuses the address.
///
/// The address is the one that [`resolve_pull`] reads: `url`, else the key
/// `pull-url` of the section of `remote` in `config`, else the key `url` of
/// the section. A caller gives the value of [`EndpointOverrides::url`] in
/// `url`. A caller can so refuse an option that applies to an `s3://`
/// address alone before it resolves the endpoint. With `None`, the caller
/// lets [`resolve_pull`] report the refusal.
///
/// The function reads `config` alone, and it reads no file and no
/// environment. [`resolve_pull`] refuses no section and no `url`, a section
/// with neither `pull-url` nor `url`, an `s3://` address in the key `url`, an
/// address that does not parse, and a key that holds a malformed escape
/// sequence. The result does not depend on the `s3` feature.
pub fn pull_address_is_s3(
    config: Option<&RepoConfig>,
    remote: &str,
    url: Option<&str>,
) -> Option<bool> {
    let section = config.and_then(|config| config.remote(remote));
    match pull_address(section.as_ref(), remote, url.map(str::to_owned)) {
        Ok(PullAddress::S3(_)) => Some(true),
        Ok(PullAddress::Endpoint(_)) => Some(false),
        Err(_) => None,
    }
}

/// Returns `true` if `value` is an `s3://` address.
fn is_s3(value: &str) -> bool {
    value.starts_with("s3://")
}

/// Returns `true` if a pull reads `value` as an ssh address: it starts with
/// `ssh://`, or it holds no `://`.
fn is_ssh(value: &str) -> bool {
    value.starts_with("ssh://") || !value.contains("://")
}

/// Returns `true` if `value` in the key `url` is an ssh address.
///
/// The caller gives a `value` for which [`is_ssh`] returns `true`. The value is
/// an ssh address if it starts with `ssh://` or if the parser accepts it.
fn is_ssh_address(value: &str) -> bool {
    value.starts_with("ssh://") || SshAddress::parse(value).is_ok()
}

/// Parses the address `value` of the caller or of `pull-url`.
///
/// # Errors
///
/// - [`Error::InvalidInput`] with the text of the parser if `value` is a
///   malformed ssh address.
fn parse_pull_address(value: &str) -> Result<PullAddress> {
    if is_s3(value) {
        return Ok(PullAddress::S3(value.to_owned()));
    }
    if !is_ssh(value) {
        return Ok(PullAddress::Endpoint(Endpoint::Http(FetcherOptions::new(
            value,
        ))));
    }
    let address = SshAddress::parse(value).map_err(|e| match e {
        remote::Error::InvalidInput(msg) => Error::InvalidInput(msg),
        other => Error::Remote(other),
    })?;
    Ok(PullAddress::Endpoint(Endpoint::Ssh {
        address,
        options: SshOptions::default(),
    }))
}

/// Returns the path of the local repository that a pull of collection refs
/// reads for `remote`, or `None` if the pull address of `remote` is not a
/// `file:` address.
///
/// The address is the first of these that is set: `url` of `o`, the key
/// `pull-url`, and the key `url`. It is a `file:` address if its scheme is
/// `file`, in ASCII letters of either case. A `file:` address is `file://`
/// followed by an absolute path. The function takes the path as written: it
/// decodes no `%` escape. `None` also comes for a remote with no section or
/// with no address, so that [`resolve_pull`] states the refusal.
///
/// For a `file:` address, the function also refuses the S3 keys of the
/// section as [`resolve_pull`] does, and each field of `o` that applies to
/// another transport. It reads no file, and it ignores the TLS keys, the key
/// `proxy`, and the ssh keys of the section.
///
/// # Errors
///
/// - [`Error::InvalidInput`] if `o` sets `push_token_file` or `push_user`,
///   for each address, before the function reads a key.
/// - [`Error::Pull`] if a `file:` address does not start with `file://`,
///   names a host (`localhost` too), has no path, or holds `%`, `?`, or `#`.
///   The message shows the address without the text up to its last `@`.
/// - [`Error::Pull`] if the section sets an S3 key, as [`resolve_pull`]
///   states.
/// - [`Error::InvalidInput`] if `o` sets a field of an HTTP address, of an
///   `s3://` address, or of an ssh address: a TLS path,
///   `allow_cleartext_credentials`, `http_headers`, a `max_retries` above 0,
///   a low-speed field, an S3 field, `ssh_command`, or `remote_command`. The
///   message names the first such field.
/// - [`Error::Core`] if a key that the function reads holds a malformed
///   escape sequence.
pub(crate) fn local_pull_path(
    config: &RepoConfig,
    remote: &str,
    o: &EndpointOverrides,
) -> Result<Option<PathBuf>> {
    if let Some(name) = push_field(o) {
        return Err(Error::InvalidInput(format!(
            "{name} applies to a push, and this is a pull"
        )));
    }
    let section = config.remote(remote);
    let address = match (&o.url, &section) {
        (Some(url), _) => Some(url.clone()),
        (None, Some(section)) => match section.pull_url()? {
            Some(pull_url) => Some(pull_url),
            None => section.url()?,
        },
        (None, None) => None,
    };
    let Some(address) = address else {
        return Ok(None);
    };
    if !address
        .get(..5)
        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("file:"))
    {
        return Ok(None);
    }
    let refused = |reason: &str| {
        Error::Pull(format!(
            "remote '{remote}': the file address '{}' {reason}; a local repository is file:// \
             followed by an absolute path",
            remote::without_userinfo(&address)
        ))
    };
    let Some(rest) = address[5..].strip_prefix("//") else {
        return Err(refused("does not start with file://"));
    };
    if rest.is_empty() {
        return Err(refused("has no path"));
    }
    if !rest.starts_with('/') {
        return Err(refused("names a host"));
    }
    if rest.contains(['%', '?', '#']) {
        return Err(refused("holds '%', '?', or '#'"));
    }
    check_s3_keys(remote, section.as_ref())?;
    let field = http_field(o)
        .map(|name| (name, "a pull over HTTP"))
        .or_else(|| s3_field(o).map(|name| (name, "a pull from an s3:// address")))
        .or_else(|| ssh_field(o, "send-command").map(|name| (name, "a pull over ssh")));
    if let Some((name, transport)) = field {
        return Err(Error::InvalidInput(format!(
            "{name} applies to {transport}, and the pull address of remote '{remote}' is a \
             local repository"
        )));
    }
    Ok(Some(PathBuf::from(rest)))
}

/// Returns the name of the first field of `o` that applies to a push
/// alone, or `None` if `o` sets no such field. Each name is the remote key
/// of the field.
fn push_field(o: &EndpointOverrides) -> Option<&'static str> {
    let set = [
        ("push-token-file", o.push_token_file.is_some()),
        ("push-user", o.push_user.is_some()),
    ];
    set.iter().find(|(_, set)| *set).map(|(name, _)| *name)
}

/// Returns the name of the first field of `o` that applies to an ssh
/// address alone, or `None` if `o` sets no such field. Each name is the
/// remote key of the field. `command_key` is the remote key of the remote
/// command: `send-command` for a pull, `receive-command` for a push.
fn ssh_field(o: &EndpointOverrides, command_key: &'static str) -> Option<&'static str> {
    let set = [
        ("ssh-command", o.ssh_command.is_some()),
        (command_key, o.remote_command.is_some()),
    ];
    set.iter().find(|(_, set)| *set).map(|(name, _)| *name)
}

/// Refuses an S3 key of `section`, the section of `remote`, if neither
/// `pull-url` nor `push-url` of the section holds an `s3://` address.
fn check_s3_keys(remote: &str, section: Option<&Remote<'_>>) -> Result<()> {
    let Some(section) = section else {
        return Ok(());
    };
    let keys = [
        ("s3-region", section.s3_region()?),
        ("s3-endpoint", section.s3_endpoint()?),
        ("s3-addressing", section.s3_addressing()?),
        ("s3-profile", section.s3_profile()?),
    ];
    let Some((name, _)) = keys.iter().find(|(_, value)| value.is_some()) else {
        return Ok(());
    };
    let s3 = |value: Option<String>| value.is_some_and(|value| is_s3(&value));
    if s3(section.pull_url()?) || s3(section.push_url()?) {
        return Ok(());
    }
    Err(Error::Pull(format!(
        "remote '{remote}': {name} applies to an s3:// address, and neither pull-url nor \
         push-url holds one"
    )))
}

/// Returns the name of the first field of `o` that applies to an `s3://`
/// address alone, or `None` if `o` sets no such field. Each name is the
/// remote key of the field.
fn s3_field(o: &EndpointOverrides) -> Option<&'static str> {
    let set = [
        ("s3-region", o.s3_region.is_some()),
        ("s3-endpoint", o.s3_endpoint.is_some()),
        ("s3-addressing", o.s3_addressing.is_some()),
        ("s3-profile", o.s3_profile.is_some()),
    ];
    set.iter().find(|(_, set)| *set).map(|(name, _)| *name)
}

/// Completes `http`, the options of an HTTP pull of `remote`, from `o` and
/// the keys of `section`, a section of the config of `repo`.
async fn pull_http(
    remote: &str,
    section: Option<&Remote<'_>>,
    mut http: FetcherOptions,
    o: EndpointOverrides,
    repo: Option<&Repo>,
) -> Result<Endpoint> {
    if let Some(name) = ssh_field(&o, "send-command") {
        return Err(Error::InvalidInput(format!(
            "{name} applies to a pull over ssh, and this pull runs over HTTP"
        )));
    }
    if let Some(name) = s3_field(&o) {
        return Err(Error::InvalidInput(format!(
            "{name} applies to a pull from an s3:// address, and this pull runs over HTTP"
        )));
    }
    PullHttp::read(remote, section, o)?
        .apply(&mut http, repo)
        .await?;
    Ok(Endpoint::Http(http))
}

/// Completes the endpoint of a pull of `remote` from the `s3://` address
/// `address`, from `o`, the keys of `section`, a section of the config of
/// `repo`, and `env`.
#[cfg(feature = "s3")]
async fn pull_s3(
    remote: &str,
    section: Option<&Remote<'_>>,
    address: &str,
    o: EndpointOverrides,
    env: &S3Environment,
    repo: Option<&Repo>,
) -> Result<Endpoint> {
    if let Some(name) = ssh_field(&o, "send-command") {
        return Err(Error::InvalidInput(format!(
            "{name} applies to a pull over ssh, and this pull reads an s3:// address"
        )));
    }
    let refusals = S3Refusals {
        invalid: Error::InvalidInput,
        remote: Error::Pull,
    };
    let (settings, http) = s3_settings(remote, section, o, refusals)?;
    s3_resolve(address, &settings, http, env, refusals, repo).await
}

/// The errors of the refusals of [`s3_settings`] and [`s3_resolve`].
#[cfg(feature = "s3")]
#[derive(Clone, Copy)]
struct S3Refusals {
    /// The error of a value that the caller or a key gives.
    invalid: fn(String) -> Error,
    /// The error of a remote whose keys do not go together.
    remote: fn(String) -> Error,
}

#[cfg(feature = "s3")]
impl S3Refusals {
    /// Returns the error of `e`, an error of `S3Endpoint::resolve` of
    /// `ostrya_remote::s3`.
    fn resolve_error(self, e: remote::Error) -> Error {
        match e {
            remote::Error::InvalidInput(msg) => (self.invalid)(msg),
            remote::Error::Io(e) => Error::Io(e),
            other => Error::Remote(other),
        }
    }
}

/// Reads the S3 fields and the HTTP fields of `o` and the keys of `section`,
/// the section of `remote`, for an S3 endpoint.
///
/// The call reads no ssh field of `o`, no file, and no environment. It refuses an addressing style
/// other than `path` and `virtual`, and each value that [`PullHttp::read`]
/// refuses.
#[cfg(feature = "s3")]
fn s3_settings(
    remote: &str,
    section: Option<&Remote<'_>>,
    mut o: EndpointOverrides,
    refusals: S3Refusals,
) -> Result<(remote::s3::Settings, PullHttp)> {
    use remote::s3::{Addressing, Settings};

    let region = or_key(o.s3_region.take(), section, |s| s.s3_region())?;
    let endpoint = or_key(o.s3_endpoint.take(), section, |s| s.s3_endpoint())?;
    let addressing = or_key(o.s3_addressing.take(), section, |s| s.s3_addressing())?;
    let profile = or_key(o.s3_profile.take(), section, |s| s.s3_profile())?;
    let addressing = match addressing {
        Some(name) => Some(Addressing::from_name(&name).ok_or_else(|| {
            (refusals.invalid)(format!(
                "s3-addressing '{name}' is neither path nor virtual"
            ))
        })?),
        None => None,
    };
    let settings = Settings {
        region,
        endpoint,
        addressing,
        profile,
    };
    let http = PullHttp::read(remote, section, o).map_err(|e| match e {
        Error::Pull(msg) => (refusals.remote)(msg),
        Error::InvalidInput(msg) => (refusals.invalid)(msg),
        other => other,
    })?;
    Ok((settings, http))
}

/// Completes the S3 endpoint of the `s3://` address `address` from
/// `settings`, `http`, and `env`.
///
/// The call reads the shared AWS files and the PEM files. A relative path of
/// a PEM file resolves as [`KeyPath::locate`] states with `repo`. It refuses
/// an `http://` endpoint with no `allow_cleartext_credentials`.
#[cfg(feature = "s3")]
async fn s3_resolve(
    address: &str,
    settings: &remote::s3::Settings,
    http: PullHttp,
    env: &S3Environment,
    refusals: S3Refusals,
    repo: Option<&Repo>,
) -> Result<Endpoint> {
    use remote::s3::S3Endpoint;

    let mut endpoint = S3Endpoint::resolve(address, settings, env)
        .await
        .map_err(|e| refusals.resolve_error(e))?;
    let url = endpoint.location.endpoint();
    let cleartext = url
        .get(..7)
        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("http://"));
    if cleartext && !http.allow_cleartext_credentials {
        return Err((refusals.invalid)(format!(
            "the S3 endpoint '{url}' is http://, so the signature of each request would \
             travel in cleartext: use https, or set allow-cleartext-credentials"
        )));
    }
    http.apply(&mut endpoint.http, repo).await?;
    Ok(Endpoint::S3(endpoint))
}

/// Returns `value` of the caller if it is set, else the key that `read`
/// reads from `section`.
#[cfg(feature = "s3")]
fn or_key(
    value: Option<String>,
    section: Option<&Remote<'_>>,
    read: impl FnOnce(&Remote<'_>) -> Result<Option<String>>,
) -> Result<Option<String>> {
    match (value, section) {
        (Some(value), _) => Ok(Some(value)),
        (None, Some(section)) => read(section),
        (None, None) => Ok(None),
    }
}

/// The HTTP options of a pull that the fields of the caller and the keys of
/// a remote give, before the pull reads a PEM file.
///
/// An HTTP address and an `s3://` address take the same options.
struct PullHttp {
    /// `true` if the section sets `tls-permissive=true` and the caller gives
    /// no CA path.
    any_chain: bool,
    /// The PEM file of the trust anchors.
    ca_path: Option<KeyPath>,
    /// The PEM files of the client certificate chain and of its key.
    client_files: Option<(KeyPath, KeyPath)>,
    proxy: Proxy,
    headers: Vec<(String, String)>,
    allow_cleartext_credentials: bool,
    max_retries: Option<u32>,
    low_speed_limit_bytes: Option<u32>,
    low_speed_time: Option<Duration>,
}

impl PullHttp {
    /// Reads the HTTP fields of `o` and the HTTP keys of `section`, the
    /// section of `remote`.
    ///
    /// The call reads no file. It refuses a path of the caller or of a key
    /// that is a relative path with a `..` component, a client certificate
    /// with no key, a key with no certificate, and a key `proxy` with white
    /// space at its start or its end.
    fn read(remote: &str, section: Option<&Remote<'_>>, o: EndpointOverrides) -> Result<PullHttp> {
        // `tls-permissive` keeps the host name check and ignores
        // `tls-ca-path`. Both facts are observed on the `ostree` command: a
        // CA that signed nothing in the chain works, and a path that names an
        // absent file works too. So the function does not read the path, and
        // an absent file is no failure. `DangerousAcceptAnyChain` keeps the
        // name check and takes the chain as presented. A CA path of the
        // caller wins over the key.
        //
        // `DangerousAcceptAnyChain` also drops the expiry check. That part is
        // a reading of ostrya, with no observation behind it. A peer
        // verification that ignores the CA path is libcurl peer verification
        // turned off, and that setting also drops the validity dates.
        let mut any_chain = false;
        let ca_path = match (caller_path("tls-ca-path", o.tls_ca_path)?, section) {
            (Some(path), _) => Some(path),
            (None, Some(section)) if section.tls_permissive()? => {
                any_chain = true;
                None
            }
            (None, Some(section)) => section.key_path("tls-ca-path")?,
            (None, None) => None,
        };
        let cert = path_or_key("tls-client-cert-path", o.tls_client_cert_path, section)?;
        let key = path_or_key("tls-client-key-path", o.tls_client_key_path, section)?;
        let client_files = match (cert, key) {
            (Some(cert), Some(key)) => Some((cert, key)),
            (None, None) => None,
            _ => {
                return Err(Error::Pull(format!(
                    "remote '{remote}': a client certificate needs both \
                     tls-client-cert-path and tls-client-key-path"
                )));
            }
        };
        let proxy = match section {
            Some(section) => remote_proxy(remote, section)?,
            None => Proxy::Environment,
        };
        Ok(PullHttp {
            any_chain,
            ca_path,
            client_files,
            proxy,
            headers: o.http_headers,
            allow_cleartext_credentials: o.allow_cleartext_credentials,
            max_retries: o.max_retries,
            low_speed_limit_bytes: o.low_speed_limit_bytes,
            low_speed_time: o.low_speed_time,
        })
    }

    /// Reads the PEM files, and sets the options in `http`.
    ///
    /// A relative path of a key resolves as [`KeyPath::locate`] states with
    /// `repo`.
    async fn apply(self, http: &mut FetcherOptions, repo: Option<&Repo>) -> Result<()> {
        if self.any_chain {
            http.tls.roots = TrustRoots::DangerousAcceptAnyChain;
        }
        let files = EndpointFiles {
            token: None,
            ca: self.ca_path,
            client: self.client_files,
        }
        .read(repo)
        .await?;
        if let Some(pem) = files.ca {
            http.tls.roots = TrustRoots::Pem(pem);
        }
        http.tls.client_identity = files.client;
        http.headers = self.headers;
        http.allow_cleartext_credentials = self.allow_cleartext_credentials;
        http.proxy = self.proxy;
        http.max_retries = self.max_retries.unwrap_or(PULL_RETRIES);
        http.max_outstanding = PULL_OUTSTANDING;
        http.low_speed = low_speed(self.low_speed_limit_bytes, self.low_speed_time);
        Ok(())
    }
}

/// Resolves `remote_or_address` to the endpoint of a push.
///
/// # Address
///
/// A value with a `:` or a `/` is an address, by the rule of
/// [`is_push_address`](crate::is_push_address). An address that starts with
/// `s3://` is the address of a bucket repository. [`Endpoint::parse`] reads
/// each other address. The function reads no configuration for an address.
/// Each other value is the name of a remote section of the config of `repo`.
/// The address of the section is its key `push-url`. If `push-url` is absent, a key `url`
/// that starts with `http://` or `https://` is the address. The function
/// reads `url` only if `push-url` is absent. The key `url` cannot hold an
/// `s3://` address, because the `ostree` command also reads it.
///
/// The S3 keys are `s3-region`, `s3-endpoint`, `s3-addressing`, and
/// `s3-profile`. For a remote name, the function refuses a section that sets
/// one of them if neither `pull-url` nor `push-url` of the section holds an
/// `s3://` address.
///
/// # HTTP address
///
/// The function gives [`Endpoint::Http`] with these values:
///
/// - The keys `push-token-file`, `push-user`, `tls-ca-path`,
///   `tls-client-cert-path`, and `tls-client-key-path` fill each field of
///   `overrides` that is `None`. A relative path of a key resolves by the
///   rules of [`Remote`](crate::config::Remote#paths), and a relative path of
///   the caller is relative to the working directory.
/// - The token of the token file and a `push_user` give
///   [`basic_auth`](FetcherOptions::basic_auth). The token alone gives
///   [`bearer_token`](FetcherOptions::bearer_token).
/// - The trust anchors and the client identity are the PEM files. The client
///   key must need no passphrase. For an `http://` address, the function
///   reads no PEM file, because the push uses no TLS.
/// - The proxy is the key `proxy`. An empty or absent key, or no section,
///   gives [`Proxy::Environment`].
/// - The headers, the cleartext permission, and the retry count are the
///   values of the caller. A retry count of `None` keeps the default of
///   [`FetcherOptions`]. The function does not refuse an `Authorization`
///   header beside the token.
///   [`PushSession::prepare`](crate::remote::PushSession::prepare) refuses
///   the pair when it builds the HTTP client.
/// - With no low-speed field, the push has no low-speed rule. With one
///   field, the other field takes 1000 bytes per second or 30 seconds. A zero
///   in either field turns the rule off.
///
/// No field of [`EndpointOverrides`] sets the other fields of
/// [`FetcherOptions`], for example the timeouts or the number of requests in
/// flight. A caller changes them in the returned endpoint.
///
/// # ssh address
///
/// The function gives [`Endpoint::Ssh`]. `ssh_command` gives
/// [`SshOptions::command`], and the key `ssh-command` gives
/// [`SshOptions::config_command`]. `remote_command`, or else the key
/// `receive-command`, gives [`SshOptions::remote_command`]. The function does
/// not read the HTTP keys of the section.
///
/// # S3 address
///
/// The address `s3://BUCKET[/PREFIX]` names a bucket repository. A build
/// with the `s3` feature gives `Endpoint::S3` with the values that
/// [`resolve_pull`] gives for the same address: the region, the endpoint,
/// the addressing style, and the profile of the fields and the keys, the
/// settings and the key pair of the environment and of the shared AWS
/// files, and the HTTP options of the TLS keys, the key `proxy`, and the
/// HTTP fields. The push takes the retry count, the number of requests in
/// flight, and the low-speed rule of a pull. [`Repo::push`](crate::Repo::push)
/// writes the bucket repository through the bucket client of the endpoint.
///
/// The signer gives the credential of each request, so the function refuses
/// the fields and the keys `push-token-file` and `push-user`. It ignores the
/// keys `ssh-command`, `send-command`, and `receive-command`.
///
/// # Errors
///
/// The function makes each refusal that needs no file before it reads a file.
/// [`check_push`] makes these refusals alone, with no file read. It also
/// makes the refusals of
/// [`PushSession::prepare`](crate::remote::PushSession::prepare) that need
/// no file, and the refusal of a malformed `s3://` address.
/// Each refusal of the list is [`Error::Remote`] with
/// [`InvalidInput`](crate::remote::Error::InvalidInput):
///
/// - The caller sets `url`.
/// - A path of the caller is a relative path with a `..` component.
/// - The config of `repo` holds no section for the name, or the section has
///   no push address. The message shows a `url` that is no push address without the
///   text up to its last `@`. A `url` that holds an `s3://` address is no
///   push address.
/// - The section sets an S3 key, and neither `pull-url` nor `push-url` holds
///   an `s3://` address. The message names the key.
/// - The address is HTTP or ssh, and the caller sets `s3_region`,
///   `s3_endpoint`, `s3_addressing`, or `s3_profile`. The message names the
///   first such field by its key.
/// - The address is `https://` or `s3://`, and the section sets
///   `tls-permissive=true`, because a push verifies the certificate chain of
///   the server.
/// - The address is HTTP or `s3://`, and the caller sets `ssh_command` or
///   `remote_command`.
/// - The address is `s3://`, and the caller or the section sets
///   `push-token-file` or `push-user`.
/// - A client certificate has no key, or a key has no certificate.
/// - A `push_user` has no token file, or is empty, or holds `:`.
/// - The address is `http://`, the push has a token file, and the caller
///   does not set `allow_cleartext_credentials`. The token would go to the
///   server in cleartext. This refusal comes before the read of the key
///   `proxy`.
/// - The address is ssh, and the caller sets a field of an HTTP address. The
///   message names the first such field and shows the address without its
///   user.
/// - The address is `s3://`, and its addressing style is neither `path` nor
///   `virtual`.
/// - The address is `s3://`, the endpoint is `http://`, and the caller does
///   not set `allow_cleartext_credentials`. The signature of each request
///   would go to the server in cleartext. The check comes after the read of
///   the shared AWS files, because the endpoint can come from them.
/// - For an `s3://` address, a refusal of `S3Endpoint::resolve` of
///   `ostrya_remote::s3`: a refused address, a refused setting, or no key
///   pair.
///
/// These errors are also possible:
///
/// - [`Error::Remote`] with the error of [`Endpoint::parse`] if the address
///   does not parse.
/// - [`Error::Unsupported`] if the key `proxy` has white space at its start
///   or its end.
/// - [`Error::Unsupported`] for an `s3://` address in a build without the
///   `s3` feature. The message names the feature.
/// - [`Error::Io`] for an `s3://` address if a shared AWS file exists and
///   cannot be read.
/// - [`Error::InvalidFormat`] if a key that names a file is a relative path
///   with a `..` component.
/// - The errors of the read of the token file: [`Error::Io`] if the file
///   cannot be opened or read, and [`Error::InvalidInput`] if it is not a
///   regular file, or if its first line is longer than 1 MiB, is empty,
///   holds a CR, is not UTF-8, or is not token68. The token has the token68
///   syntax: one or more ASCII letters, digits, `-`, `.`, `_`, `~`, `+`, or
///   `/`, then zero or more `=`. No error holds a part of the token, and the
///   read checks no permission of the file.
/// - The errors of the read of a PEM file: [`Error::Io`] if the file cannot
///   be opened or read, and [`Error::InvalidInput`] if it is not a regular
///   file or is larger than 1 MiB.
/// - [`Error::Core`] if a key that the function reads holds a malformed
///   escape sequence, or if `tls-permissive` is not a boolean.
///
/// Each error of a read names the key and the path.
#[cfg(feature = "push")]
pub async fn resolve_push(
    repo: Option<&Repo>,
    remote_or_address: &str,
    overrides: EndpointOverrides,
) -> Result<Endpoint> {
    resolve_push_in(
        repo,
        remote_or_address,
        overrides,
        &S3Environment::default(),
    )
    .await
}

/// Resolves `remote_or_address` to the endpoint of a push, as
/// [`resolve_push`] does, with `env` as the environment of an `s3://`
/// address.
#[cfg(feature = "push")]
#[cfg_attr(not(feature = "s3"), allow(unused_variables))]
pub(crate) async fn resolve_push_in(
    repo: Option<&Repo>,
    remote_or_address: &str,
    overrides: EndpointOverrides,
    env: &S3Environment,
) -> Result<Endpoint> {
    match checked_push(repo.map(Repo::config), remote_or_address, overrides)? {
        CheckedPush::Ssh(address, options) => Ok(Endpoint::Ssh { address, options }),
        CheckedPush::Http(push) => push.read_files(repo).await,
        #[cfg(feature = "s3")]
        CheckedPush::S3(push) => {
            Box::pin(s3_resolve(
                &push.address,
                &push.settings,
                push.http,
                env,
                push.refusals,
                repo,
            ))
            .await
        }
    }
}

/// The kind of a push that [`check_push`] gives.
#[cfg(feature = "push")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PushKind {
    /// A push over ssh or HTTP. [`Repo::push`](crate::Repo::push) sends it
    /// through a push session.
    Session,
    /// A push to a bucket repository at an `s3://` address. A build without
    /// the `s3` feature never gives it, because [`check_push`] refuses the
    /// address.
    Bucket,
}

/// Makes each refusal of [`resolve_push`] that needs no file, and gives the
/// kind of the push.
///
/// The function reads the keys of the remote section as [`resolve_push`]
/// reads them, up to the first file. It reads no token file, no PEM file, no
/// shared AWS file, no AWS credential of the environment, and no trust
/// store, and it opens no connection. It also makes these checks, which need
/// no file:
///
/// - For an ssh or an HTTP address, the checks of
///   [`PushSession::check`](crate::remote::PushSession::check), on the
///   endpoint with no file read. These are the refusals of
///   [`PushSession::prepare`](crate::remote::PushSession::prepare) that read
///   no file. For ssh, the function reads the `OSTRYA_SSH_COMMAND`
///   environment variable. For HTTP, it checks the push address, the headers,
///   the low-speed rule, and the proxy, and for [`Proxy::Environment`] it
///   reads the proxy variables of the environment.
/// - For an `s3://` address, the parse of the address, which
///   `S3Endpoint::resolve` of `ostrya_remote::s3` makes before it reads a
///   file.
///
/// A caller can check the options of a push with it when it does not go on
/// to the push, for example when the push selects no ref.
///
/// The function does not make the refusals that come after a file read.
/// These are the errors of the reads of the token file and of the PEM files,
/// and,
/// for an `s3://` address, the other refusals of `S3Endpoint::resolve`, the
/// refusal of an `http://` S3 endpoint with no
/// `allow_cleartext_credentials`, and the refusal of the proxy by the HTTP
/// client of the bucket. For an HTTP address, it does not make the refusals
/// of the TLS setup of the HTTP client, and the refusals of the HTTP client
/// that depend on the token, because it reads no token file. So a success
/// of this function does not show that [`resolve_push`] or the push
/// succeeds.
///
/// # Errors
///
/// - Each error of the list of [`resolve_push`] that comes before a file
///   read, with the same variant and the same message. These include the
///   refusal of an option of the other transport, of a bad `push_user`, of a
///   `push_user` or a token file for an `s3://` address, of a client
///   certificate with no key, of a token to an `http://` address with no
///   `allow_cleartext_credentials`, of the key `proxy`, of an addressing
///   style, and of an `s3://` address in a build without the `s3` feature.
/// - [`Error::Remote`] with
///   [`InvalidInput`](crate::remote::Error::InvalidInput) for an `s3://`
///   address that `Address::parse` of `ostrya_remote::s3` refuses, with the
///   message of [`resolve_push`].
/// - [`Error::Remote`] with the error of
///   [`PushSession::check`](crate::remote::PushSession::check) for an ssh
///   or an HTTP address. For ssh: an empty ssh command or receive command,
///   or an `OSTRYA_SSH_COMMAND` that is empty or not UTF-8. For HTTP: an
///   error of [`check_options`](crate::fetch::check_options), for example a
///   bad header or a proxy URL of the key `proxy` or of the environment that
///   the HTTP client refuses.
#[cfg(feature = "push")]
pub fn check_push(
    config: Option<&RepoConfig>,
    remote_or_address: &str,
    overrides: EndpointOverrides,
) -> Result<PushKind> {
    match checked_push(config, remote_or_address, overrides)? {
        CheckedPush::Ssh(address, options) => {
            remote::PushSession::check(&Endpoint::Ssh { address, options })?;
            Ok(PushKind::Session)
        }
        CheckedPush::Http(push) => {
            remote::PushSession::check(&Endpoint::Http(push.http))?;
            Ok(PushKind::Session)
        }
        #[cfg(feature = "s3")]
        CheckedPush::S3(push) => {
            remote::s3::Address::parse(&push.address)
                .map_err(|e| push.refusals.resolve_error(e))?;
            Ok(PushKind::Bucket)
        }
    }
}

/// A push after the refusals that need no file.
// The HTTP variant is much larger than the ssh variant. A push resolves one
// address, so a box saves no work, and the variant stays inline.
#[cfg(feature = "push")]
#[allow(clippy::large_enum_variant)]
enum CheckedPush {
    /// The address and the options of an ssh push. The push reads no file.
    Ssh(SshAddress, SshOptions),
    /// An HTTP push before the read of its token file and its PEM files.
    Http(HttpPush),
    /// A push to an `s3://` address before the read of the shared AWS files
    /// and of the PEM files.
    #[cfg(feature = "s3")]
    S3(S3Push),
}

/// A push to an `s3://` address after the refusals that need no file.
#[cfg(feature = "s3")]
struct S3Push {
    address: String,
    settings: remote::s3::Settings,
    http: PullHttp,
    refusals: S3Refusals,
}

/// Makes each refusal of [`resolve_push_in`] that needs no file, in the
/// order of [`resolve_push`].
#[cfg(feature = "push")]
fn checked_push(
    config: Option<&RepoConfig>,
    remote_or_address: &str,
    overrides: EndpointOverrides,
) -> Result<CheckedPush> {
    let remote = remote_or_address;
    if overrides.url.is_some() {
        return Err(push_invalid("url applies to a pull, and this is a push"));
    }
    let (section, address) = if crate::is_push_address(remote) {
        (None, remote.to_owned())
    } else {
        let section = config
            .and_then(|config| config.remote(remote))
            .ok_or_else(|| push_invalid(format!("no remote '{remote}' is configured")))?;
        check_s3_keys(remote, Some(&section)).map_err(|e| match e {
            Error::Pull(msg) => push_invalid(msg),
            other => other,
        })?;
        let address = match section.push_url()? {
            Some(push_url) => push_url,
            None => match section.url()? {
                Some(url) if url.starts_with("http://") || url.starts_with("https://") => url,
                Some(url) if is_s3(&url) => {
                    return Err(push_invalid(format!(
                        "remote '{remote}' has no push-url, and its url '{}' is an s3:// \
                         address; the port reads an s3:// address from push-url alone",
                        remote::without_userinfo(&url)
                    )));
                }
                Some(url) => {
                    return Err(push_invalid(format!(
                        "remote '{remote}' has no push-url, and its url '{}' is no push address",
                        remote::without_userinfo(&url)
                    )));
                }
                None => {
                    return Err(push_invalid(format!(
                        "remote '{remote}' has no push-url and no url"
                    )));
                }
            },
        };
        (Some(section), address)
    };
    if is_s3(&address) {
        // The name of an address in a message is the address without its
        // userinfo, which can hold a key pair.
        #[cfg(feature = "s3")]
        let name = match section {
            Some(_) => std::borrow::Cow::Borrowed(remote),
            None => remote::without_userinfo(remote),
        };
        #[cfg(feature = "s3")]
        return check_push_s3(&name, section.as_ref(), address, overrides).map(CheckedPush::S3);
        #[cfg(not(feature = "s3"))]
        return Err(Error::Unsupported(format!(
            "the push address '{}' is an s3:// address, and this build of ostrya has no S3 \
             support: turn on the feature s3 of ostrya",
            remote::without_userinfo(&address)
        )));
    }
    match Endpoint::parse(&address)? {
        Endpoint::Http(http) => {
            if let Some(name) = s3_field(&overrides) {
                return Err(push_invalid(format!(
                    "{name} applies to an s3:// address, and '{}' is an HTTP address",
                    remote::without_userinfo(&address)
                )));
            }
            check_push_http(remote, section.as_ref(), &address, http, overrides)
                .map(CheckedPush::Http)
        }
        Endpoint::Ssh { address, .. } => {
            if let Some(name) = s3_field(&overrides) {
                return Err(push_invalid(format!(
                    "{name} applies to an s3:// address, and '{}' is an ssh address",
                    address.without_user()
                )));
            }
            let options = push_ssh(section.as_ref(), &address, overrides)?;
            Ok(CheckedPush::Ssh(address, options))
        }
        _ => Err(neither_ssh_nor_http("a push")),
    }
}

/// Makes each refusal of a push of `remote` to the `s3://` address `address`
/// that needs no file, from `o` and the keys of `section`.
///
/// [`resolve_bucket`] gives the endpoint of each other writer of a bucket
/// repository through this function, so each writer makes the refusals of a
/// push.
#[cfg(feature = "s3")]
fn check_push_s3(
    remote: &str,
    section: Option<&Remote<'_>>,
    address: String,
    o: EndpointOverrides,
) -> Result<S3Push> {
    let shown = remote::without_userinfo(&address);
    let (token_key, user_key) = match section {
        Some(section) => (
            section.push_token_file()?.is_some(),
            section.push_user()?.is_some(),
        ),
        None => (false, false),
    };
    let http_fields = [
        ("push-token-file", o.push_token_file.is_some() || token_key),
        ("push-user", o.push_user.is_some() || user_key),
    ];
    if let Some((name, _)) = http_fields.iter().find(|(_, set)| *set) {
        return Err(push_invalid(format!(
            "{name} applies to an HTTP address, and '{shown}' is an s3:// address"
        )));
    }
    if let Some(name) = ssh_field(&o, "receive-command") {
        return Err(push_invalid(format!(
            "{name} applies to an ssh address, and '{shown}' is an s3:// address"
        )));
    }
    if let Some(section) = section
        && section.tls_permissive()?
    {
        return Err(push_invalid(format!(
            "remote '{remote}' sets tls-permissive=true, which a writer of a bucket \
             repository refuses: the writer verifies the certificate chain of the server"
        )));
    }
    let refusals = S3Refusals {
        invalid: |msg| push_invalid(msg),
        remote: |msg| push_invalid(msg),
    };
    let (settings, http) = s3_settings(remote, section, o, refusals)?;
    Ok(S3Push {
        address,
        settings,
        http,
        refusals,
    })
}

/// Resolves a remote name or an `s3://` address to the endpoint of a writer
/// of a bucket repository other than a push.
///
/// A remote name is the name of a section of the config of `repo`.
///
/// [`BucketRepo::init`](crate::bucket::BucketRepo::init) is such a writer.
/// `resolve_push` gives the endpoint of a push.
///
/// # Address
///
/// A value that starts with `s3://` is the address, and the function reads
/// no configuration for it. Each other value is the name of a remote section
/// of `config`. The address of the section is its key `push-url` if that key
/// holds an `s3://` address, else its key `pull-url` if that key holds an
/// `s3://` address. The function never reads the key `url`.
///
/// # Endpoint
///
/// The function gives the S3 endpoint that `resolve_push` gives for the
/// same `s3://` address and the same section, and makes the same refusals.
/// The signer gives the credential of each request, so the function refuses
/// the fields and the keys `push-token-file` and `push-user`, and the ssh
/// fields. It refuses `tls-permissive=true`, because a writer verifies the
/// certificate chain of the server. It ignores the keys `ssh-command`,
/// `send-command`, and `receive-command`.
///
/// # Errors
///
/// The function makes each refusal that needs no file before it reads a file.
/// Each refusal of the list is [`Error::Remote`] with
/// [`InvalidInput`](crate::remote::Error::InvalidInput):
///
/// - The caller sets `url`.
/// - A TLS path of the caller is a relative path with a `..` component.
/// - The value holds a `:` or a `/`, and does not start with `s3://`.
/// - `config` holds no section for the name, or neither `push-url` nor
///   `pull-url` of the section holds an `s3://` address.
/// - The caller or the section sets `push-token-file` or `push-user`.
/// - The caller sets `ssh_command` or `remote_command`.
/// - The section sets `tls-permissive=true`.
/// - A client certificate has no key, or a key has no certificate.
/// - The addressing style is neither `path` nor `virtual`.
/// - The endpoint is `http://`, and the caller does not set
///   `allow_cleartext_credentials`. The signature of each request would go
///   to the server in cleartext. The check comes after the read of the
///   shared AWS files, because the endpoint can come from them.
/// - A refusal of `S3Endpoint::resolve` of `ostrya_remote::s3`: a refused
///   address, a refused setting, or no key pair.
///
/// These errors are also possible:
///
/// - [`Error::Unsupported`] if the key `proxy` has white space at its start
///   or its end.
/// - [`Error::Io`] if a shared AWS file exists and cannot be read.
/// - [`Error::InvalidFormat`] if a TLS key is a relative path with a `..`
///   component.
/// - The errors of the read of a PEM file, as [`resolve_pull`] states them.
/// - [`Error::Core`] if a key that the function reads holds a malformed
///   escape sequence, or if `tls-permissive` is not a boolean.
#[cfg(feature = "s3")]
pub async fn resolve_bucket(
    repo: Option<&Repo>,
    name_or_address: &str,
    overrides: EndpointOverrides,
) -> Result<remote::s3::S3Endpoint> {
    resolve_bucket_in(repo, name_or_address, overrides, &S3Environment::default()).await
}

/// Resolves `name_or_address` to the endpoint of a writer of a bucket
/// repository, as [`resolve_bucket`] does, with `env` as the environment of
/// the `s3://` address.
#[cfg(feature = "s3")]
pub(crate) async fn resolve_bucket_in(
    repo: Option<&Repo>,
    name_or_address: &str,
    overrides: EndpointOverrides,
    env: &S3Environment,
) -> Result<remote::s3::S3Endpoint> {
    let value = name_or_address;
    if overrides.url.is_some() {
        return Err(push_invalid(
            "url applies to a pull, and this is a write to a bucket repository",
        ));
    }
    let (section, address) = if is_s3(value) {
        (None, value.to_owned())
    } else if value.contains([':', '/']) {
        return Err(push_invalid(format!(
            "'{}' is no s3:// address",
            remote::without_userinfo(value)
        )));
    } else {
        let section = repo
            .and_then(|repo| repo.config().remote(value))
            .ok_or_else(|| push_invalid(format!("no remote '{value}' is configured")))?;
        let s3 = |address: Option<String>| address.filter(|address| is_s3(address));
        let address = match s3(section.push_url()?) {
            Some(address) => address,
            None => s3(section.pull_url()?).ok_or_else(|| {
                push_invalid(format!(
                    "remote '{value}' holds no s3:// address in push-url or pull-url"
                ))
            })?,
        };
        (Some(section), address)
    };
    // The name of an address in a message is the address without its
    // userinfo, which can hold a key pair.
    let name = match section {
        Some(_) => std::borrow::Cow::Borrowed(value),
        None => remote::without_userinfo(value),
    };
    let push = check_push_s3(&name, section.as_ref(), address, overrides)?;
    let endpoint = Box::pin(s3_resolve(
        &push.address,
        &push.settings,
        push.http,
        env,
        push.refusals,
        repo,
    ))
    .await?;
    let Endpoint::S3(endpoint) = endpoint else {
        unreachable!("the endpoint of an s3:// address is an S3 endpoint");
    };
    Ok(endpoint)
}

/// An HTTP push after the refusals that need no file.
#[cfg(feature = "push")]
struct HttpPush {
    /// The options of the push, with each value that needs no file.
    http: FetcherOptions,
    /// The token file of the push.
    token_file: Option<KeyPath>,
    /// The user of a Basic credential.
    user: Option<String>,
    /// The PEM file of the trust anchors.
    ca_path: Option<KeyPath>,
    /// The PEM files of the client certificate chain and of its key.
    client_files: Option<(KeyPath, KeyPath)>,
    /// `true` for an `http://` address.
    cleartext: bool,
}

/// Makes each refusal of an HTTP push to `address` that needs no file, with
/// `http`, `o`, and the keys of `section`, the section of `remote`.
#[cfg(feature = "push")]
fn check_push_http(
    remote: &str,
    section: Option<&Remote<'_>>,
    address: &str,
    mut http: FetcherOptions,
    o: EndpointOverrides,
) -> Result<HttpPush> {
    if let Some(section) = section
        && address.starts_with("https://")
        && section.tls_permissive()?
    {
        return Err(push_invalid(format!(
            "remote '{remote}' sets tls-permissive=true, which a push refuses: a \
             push verifies the certificate chain of the server"
        )));
    }
    if let Some(name) = ssh_field(&o, "receive-command") {
        return Err(push_invalid(format!(
            "{name} applies to an ssh address, and '{address}' is an HTTP address"
        )));
    }
    let pick = |key: &str, path: Option<PathBuf>| {
        path_or_key(key, path, section).map_err(|e| match e {
            Error::InvalidInput(msg) => push_invalid(msg),
            other => other,
        })
    };
    let token_file = pick("push-token-file", o.push_token_file)?;
    let push_user = match (o.push_user, section) {
        (Some(user), _) => Some(user),
        (None, Some(section)) => section.push_user()?,
        (None, None) => None,
    };
    let ca_path = pick("tls-ca-path", o.tls_ca_path)?;
    let cert = pick("tls-client-cert-path", o.tls_client_cert_path)?;
    let key = pick("tls-client-key-path", o.tls_client_key_path)?;
    let client_files = match (cert, key) {
        (Some(cert), Some(key)) => Some((cert, key)),
        (None, None) => None,
        _ => {
            return Err(push_invalid(
                "a client certificate needs both tls-client-cert-path and tls-client-key-path",
            ));
        }
    };
    match (&push_user, &token_file) {
        (Some(_), None) => {
            return Err(push_invalid("push-user needs push-token-file"));
        }
        (Some(user), Some(_)) if user.is_empty() || user.contains(':') => {
            return Err(push_invalid(
                "push-user is empty or holds ':', which a Basic credential cannot carry",
            ));
        }
        _ => {}
    }
    let cleartext = address
        .get(..7)
        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("http://"));
    if token_file.is_some() && cleartext && !o.allow_cleartext_credentials {
        return Err(push_invalid(format!(
            "the push address '{address}' is http://, so the token would travel in cleartext: \
             use https, or set allow-cleartext-credentials"
        )));
    }
    http.proxy = match section {
        Some(section) => remote_proxy(remote, section)?,
        None => Proxy::Environment,
    };
    http.headers = o.http_headers;
    http.allow_cleartext_credentials = o.allow_cleartext_credentials;
    if let Some(retries) = o.max_retries {
        http.max_retries = retries;
    }
    if o.low_speed_limit_bytes.is_some() || o.low_speed_time.is_some() {
        http.low_speed = low_speed(o.low_speed_limit_bytes, o.low_speed_time);
    }
    Ok(HttpPush {
        http,
        token_file,
        user: push_user,
        ca_path,
        client_files,
        cleartext,
    })
}

#[cfg(feature = "push")]
impl HttpPush {
    /// Reads the token file and the PEM files, and completes the endpoint.
    ///
    /// A relative path of a key resolves as [`KeyPath::locate`] states with
    /// `repo`.
    async fn read_files(self, repo: Option<&Repo>) -> Result<Endpoint> {
        let HttpPush {
            mut http,
            token_file,
            user,
            ca_path,
            client_files,
            cleartext,
        } = self;
        // The HTTP client of a push session follows no redirect, so an
        // `http://` address uses no TLS, and the push reads no TLS file.
        let files = EndpointFiles {
            token: token_file,
            ca: ca_path.filter(|_| !cleartext),
            client: client_files.filter(|_| !cleartext),
        }
        .read(repo)
        .await?;
        if let Some(token) = files.token {
            match user {
                Some(user) => {
                    http.basic_auth = Some(BasicAuth {
                        user,
                        password: token,
                    })
                }
                None => http.bearer_token = Some(BearerToken { token }),
            }
        }
        if let Some(pem) = files.ca {
            http.tls.roots = TrustRoots::Pem(pem);
        }
        if files.client.is_some() {
            http.tls.client_identity = files.client;
        }
        Ok(Endpoint::Http(http))
    }
}

/// Gives the ssh options of a push to the ssh address `address`, with `o`
/// and the ssh keys of `section`.
#[cfg(feature = "push")]
fn push_ssh(
    section: Option<&Remote<'_>>,
    address: &SshAddress,
    o: EndpointOverrides,
) -> Result<SshOptions> {
    let name = push_field(&o).or_else(|| http_field(&o));
    if let Some(name) = name {
        return Err(push_invalid(format!(
            "{name} applies to an HTTP address, and '{}' is an ssh address",
            address.without_user()
        )));
    }
    let (config_command, remote_command) = match section {
        Some(section) => (
            section.ssh_command()?,
            match o.remote_command {
                Some(command) => Some(command),
                None => section.receive_command()?,
            },
        ),
        None => (None, o.remote_command),
    };
    Ok(SshOptions {
        command: o.ssh_command,
        config_command,
        remote_command,
    })
}

/// Returns the error of a push request that the resolver refuses.
#[cfg(any(feature = "push", feature = "s3"))]
fn push_invalid(msg: impl Into<String>) -> Error {
    Error::Remote(remote::Error::InvalidInput(msg.into()))
}

/// Returns the name of the first field of `o` that applies to an HTTP
/// address alone, or `None` if `o` sets no such field.
///
/// A field that a remote key backs gets the name of the key. Each other field
/// gets the name of the option of `ostrya pull` that sets it. A retry count
/// of 0 is no refusal, because a session over ssh never sends a request
/// again.
fn http_field(o: &EndpointOverrides) -> Option<&'static str> {
    let set = [
        ("tls-ca-path", o.tls_ca_path.is_some()),
        ("tls-client-cert-path", o.tls_client_cert_path.is_some()),
        ("tls-client-key-path", o.tls_client_key_path.is_some()),
        ("allow-cleartext-credentials", o.allow_cleartext_credentials),
        ("http-header", !o.http_headers.is_empty()),
        ("network-retries", o.max_retries.is_some_and(|n| n > 0)),
        ("low-speed-limit-bytes", o.low_speed_limit_bytes.is_some()),
        ("low-speed-time-seconds", o.low_speed_time.is_some()),
    ];
    set.iter().find(|(_, set)| *set).map(|(name, _)| *name)
}

/// Returns the low-speed rule of `limit` and `time`. A value left `None`
/// takes its default, and a zero in either value turns the rule off.
fn low_speed(limit: Option<u32>, time: Option<Duration>) -> Option<LowSpeed> {
    let limit = limit.unwrap_or(DEFAULT_LOW_SPEED_LIMIT);
    let time = time.unwrap_or(DEFAULT_LOW_SPEED_TIME);
    (limit != 0 && !time.is_zero()).then_some(LowSpeed { limit, time })
}

/// Reads the proxy that the `proxy` key of a remote names. An empty or absent
/// key leaves the proxy to the environment variables.
///
/// The function refuses a value with white space at its start or end, as the
/// `ostree` command refuses it. The fetcher trims a proxy URL, so without this
/// check it connects through such a value. The message leaves out the value,
/// because the userinfo of the value can hold a password.
fn remote_proxy(remote: &str, section: &Remote<'_>) -> Result<Proxy> {
    Ok(match section.proxy()? {
        Some(url) if url.trim() != url => {
            return Err(Error::Unsupported(format!(
                "remote '{remote}': the proxy key has white space at the start or \
                 the end of its value"
            )));
        }
        Some(url) if !url.is_empty() => Proxy::Url(url),
        _ => Proxy::Environment,
    })
}

/// Returns the path of the caller `path` for the field of the key `key`, or
/// else the path of the key `key` of `section`.
///
/// # Errors
///
/// - [`Error::InvalidInput`] if `path` is a relative path with a `..`
///   component.
/// - The errors of [`Remote::key_path`].
fn path_or_key(
    key: &str,
    path: Option<PathBuf>,
    section: Option<&Remote<'_>>,
) -> Result<Option<KeyPath>> {
    match (caller_path(key, path)?, section) {
        (Some(path), _) => Ok(Some(path)),
        (None, Some(section)) => section.key_path(key),
        (None, None) => Ok(None),
    }
}

/// Returns `path`, the path of the caller for the field of the key `key`, as
/// a [`KeyPath`] of the caller.
///
/// # Errors
///
/// [`Error::InvalidInput`] if `path` is a relative path with a `..`
/// component.
pub(crate) fn caller_path(key: &str, path: Option<PathBuf>) -> Result<Option<KeyPath>> {
    match path {
        Some(path) if relative_with_parent(&path) => Err(Error::InvalidInput(format!(
            "{key} {} is a relative path with a `..` component",
            path.display()
        ))),
        path => Ok(path.map(KeyPath::caller)),
    }
}

/// The files of one endpoint that a resolver reads.
struct EndpointFiles {
    /// The token file of a push.
    token: Option<KeyPath>,
    /// The PEM file of the trust anchors.
    ca: Option<KeyPath>,
    /// The PEM files of the client certificate chain and of its key.
    client: Option<(KeyPath, KeyPath)>,
}

/// The content of the files of [`EndpointFiles`].
struct ReadFiles {
    // A pull reads no token file, so a build without a push reads no token.
    #[cfg_attr(not(feature = "push"), allow(dead_code))]
    token: Option<String>,
    ca: Option<Vec<u8>>,
    client: Option<ClientIdentity>,
}

impl EndpointFiles {
    /// Reads the files in one job on the blocking pool: the token file, the
    /// PEM file of the trust anchors, the client certificate chain, and the
    /// client key, in this order. The first error stops the read.
    ///
    /// A relative path resolves as [`KeyPath::locate`] states with `repo`.
    /// The call reads one file at a time, and starts no job if no file is
    /// set.
    async fn read(self, repo: Option<&Repo>) -> Result<ReadFiles> {
        if self.token.is_none() && self.ca.is_none() && self.client.is_none() {
            return Ok(ReadFiles {
                token: None,
                ca: None,
                client: None,
            });
        }
        let repo = repo.cloned();
        ostrya_rt::unblock(move || {
            let repo = repo.as_ref();
            let token = match &self.token {
                Some(path) => Some(read_token_file(path, repo)?),
                None => None,
            };
            let ca = match &self.ca {
                Some(path) => Some(read_pem_file("tls-ca-path", path, repo)?),
                None => None,
            };
            let client = match &self.client {
                Some((cert, key)) => Some(ClientIdentity {
                    cert_chain_pem: read_pem_file("tls-client-cert-path", cert, repo)?,
                    key_pem: read_pem_file("tls-client-key-path", key, repo)?,
                    // A remote has no config key for a passphrase, so the key
                    // must need no passphrase.
                    key_passphrase: None,
                }),
                None => None,
            };
            Ok(ReadFiles { token, ca, client })
        })
        .await
    }
}

/// Returns the token of the token file at `path`, which resolves as
/// [`KeyPath::locate`] states with `repo`.
///
/// The token is the first line of the file: the bytes up to the first LF, or
/// the whole file if it holds no LF. The function stops at the first LF, and
/// reads at most 1 MiB and one byte of the file. The token
/// must have the token68 syntax: one or more ASCII letters, digits, `-`,
/// `.`, `_`, `~`, `+`, or `/`, then zero or more `=`.
///
/// No error holds a part of the token. The function checks no permission of
/// the file. The call blocks the calling thread.
///
/// # Errors
///
/// - The errors of [`open_key_file`] for the key `push-token-file`.
/// - [`Error::Io`] if the file cannot be read. The message names the key
///   `push-token-file` and the path.
/// - [`Error::InvalidInput`] if the first line is longer than 1 MiB, or if it
///   is empty, holds a CR, is not UTF-8, or is not token68. The message names
///   the key `push-token-file` and the path.
fn read_token_file(path: &KeyPath, repo: Option<&Repo>) -> Result<String> {
    const KEY: &str = "push-token-file";
    let (file, shown) = open_key_file(KEY, path, repo)?;
    let mut bytes = Vec::new();
    BufReader::new(file.take(FILE_CAP + 1))
        .read_until(b'\n', &mut bytes)
        .map_err(|e| io_error(KEY, &shown, e))?;
    let line = match bytes.split_last() {
        Some((b'\n', line)) => line,
        _ if bytes.len() as u64 > FILE_CAP => {
            return Err(Error::InvalidInput(format!(
                "the first line of {KEY} '{}' is over 1 MiB",
                shown.display()
            )));
        }
        _ => &bytes[..],
    };
    token_of(line).map_err(|why| Error::InvalidInput(format!("{KEY} '{}': {why}", shown.display())))
}

/// Returns the bytes of the PEM file at `path`, which the key `key` of a
/// remote or of the server names. The path resolves as [`KeyPath::locate`]
/// states with `repo`.
///
/// The function reads at most 1 MiB and one byte of the file. It does not
/// check the PEM syntax. The fetcher or the server reads the bytes. The call
/// blocks the calling thread.
///
/// # Errors
///
/// - The errors of [`open_key_file`].
/// - [`Error::Io`] if the file cannot be read. The message names `key` and
///   the path, and holds no byte of the file.
/// - [`Error::InvalidInput`] if the file is larger than 1 MiB. The message
///   names `key` and the path.
pub(crate) fn read_pem_file(key: &str, path: &KeyPath, repo: Option<&Repo>) -> Result<Vec<u8>> {
    let (file, shown) = open_key_file(key, path, repo)?;
    // The read stops one byte over the cap, so a file over the cap is
    // refused with no read of the rest.
    let mut bytes = Vec::with_capacity(8 * 1024);
    file.take(FILE_CAP + 1)
        .read_to_end(&mut bytes)
        .map_err(|e| io_error(key, &shown, e))?;
    if bytes.len() as u64 > FILE_CAP {
        return Err(Error::InvalidInput(format!(
            "{key} '{}' is over 1 MiB",
            shown.display()
        )));
    }
    Ok(bytes)
}

/// Opens the file at `path`, which the key `key` names, and returns it with
/// the path that names it in a message.
///
/// The path resolves as [`KeyPath::locate`] states with `repo`. The open
/// follows a symlink at each component, and uses `O_NONBLOCK`, so the open of
/// a FIFO does not wait for a writer. The type check after the open refuses
/// each file that is not a regular file.
///
/// # Errors
///
/// - [`Error::Io`] if the file cannot be opened. The message names `key` and
///   the path. An absent file gives the kind
///   [`NotFound`](std::io::ErrorKind::NotFound).
/// - [`Error::InvalidInput`] if the file is not a regular file. The message
///   names `key` and the path.
fn open_key_file(
    key: &str,
    path: &KeyPath,
    repo: Option<&Repo>,
) -> Result<(std::fs::File, PathBuf)> {
    let (base, at, shown) = path.locate(repo);
    match open_named(base, &at, Named::File) {
        Ok(fd) => Ok((std::fs::File::from(fd), shown)),
        Err(FsError::Invalid {
            reason: Reason::NotRegular(_),
            ..
        }) => Err(Error::InvalidInput(format!(
            "{key} '{}' is not a regular file",
            shown.display()
        ))),
        Err(err) => Err(io_error(key, &shown, io_of(err))),
    }
}

/// Returns the [`Error::Io`] of the failure `e` to read the file at `path`,
/// which the key `key` names. The message names the key and the path.
fn io_error(key: &str, path: &Path, e: std::io::Error) -> Error {
    Error::Io(std::io::Error::new(
        e.kind(),
        format!("{key} '{}': {e}", path.display()),
    ))
}

/// Returns the token of `line`, the first line of a token file, or the
/// reason of its refusal.
fn token_of(line: &[u8]) -> std::result::Result<String, &'static str> {
    if line.contains(&b'\r') {
        return Err("the first line holds a carriage return");
    }
    if line.is_empty() {
        return Err("the first line is empty");
    }
    let token = std::str::from_utf8(line).map_err(|_| "the first line is not UTF-8")?;
    if !is_token68(token) {
        return Err(
            "the token is not token68: it holds letters, digits, -, ., _, ~, +, or /, \
                    then any number of =",
        );
    }
    Ok(token.to_owned())
}

/// Returns `true` if `token` has the token68 syntax of HTTP authentication.
/// The syntax is one or more ASCII letters, digits, `-`, `.`, `_`, `~`, `+`,
/// or `/`, then any number of `=`.
fn is_token68(token: &str) -> bool {
    let body = token.trim_end_matches('=');
    !body.is_empty()
        && body
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"-._~+/".contains(&b))
}

// The overrides move freely across tasks and threads.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<EndpointOverrides>();
};

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicU32, Ordering};

    use super::*;
    use crate::fetch::TlsOptions;

    struct Dir(PathBuf);

    impl Dir {
        fn new() -> Dir {
            static N: AtomicU32 = AtomicU32::new(0);
            let path = std::env::temp_dir().join(format!(
                "ostrya-endpoint-{}-{}",
                std::process::id(),
                N.fetch_add(1, Ordering::Relaxed)
            ));
            let _ = std::fs::remove_dir_all(&path);
            std::fs::create_dir_all(&path).unwrap();
            Dir(path)
        }

        fn file(&self, name: &str, bytes: &[u8]) -> PathBuf {
            let path = self.0.join(name);
            std::fs::write(&path, bytes).unwrap();
            path
        }

        /// Returns the path of `name` in the directory, with no file at it.
        fn absent(&self, name: &str) -> PathBuf {
            self.0.join(name)
        }
    }

    impl Drop for Dir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    /// A repository in a temp directory, which the drop removes.
    struct TestRepo {
        repo: Repo,
        _dir: Dir,
    }

    impl std::ops::Deref for TestRepo {
        type Target = Repo;

        fn deref(&self) -> &Repo {
            &self.repo
        }
    }

    /// Returns the handle of a new repository whose config holds the remote
    /// sections `sections`.
    fn config(sections: &str) -> TestRepo {
        let dir = Dir::new();
        let root = dir.0.join("repo");
        let repo = ostrya_rt::block_on(async {
            Repo::create(
                &root,
                crate::CreateOptions::new(ostrya_core::RepoMode::Archive),
            )
            .await
            .unwrap();
            std::fs::write(
                root.join("config"),
                format!("[core]\nrepo_version=1\nmode=archive-z2\n\n{sections}"),
            )
            .unwrap();
            Repo::open(&root).await.unwrap()
        });
        TestRepo { repo, _dir: dir }
    }

    /// Returns the handle of `repo`.
    fn handle(repo: Option<&TestRepo>) -> Option<&Repo> {
        repo.map(|repo| &repo.repo)
    }

    fn pull(repo: Option<&TestRepo>, remote: &str, o: EndpointOverrides) -> Result<Endpoint> {
        ostrya_rt::block_on(resolve_pull(handle(repo), remote, o))
    }

    fn http_of(endpoint: Result<Endpoint>) -> FetcherOptions {
        match endpoint {
            Ok(Endpoint::Http(http)) => http,
            other => panic!("{other:?}"),
        }
    }

    fn ssh(endpoint: Result<Endpoint>) -> (SshAddress, SshOptions) {
        match endpoint {
            Ok(Endpoint::Ssh { address, options }) => (address, options),
            other => panic!("{other:?}"),
        }
    }

    fn invalid_input<T: fmt::Debug>(result: Result<T>) -> String {
        match result {
            Err(Error::InvalidInput(msg)) => msg,
            other => panic!("expected InvalidInput, got {other:?}"),
        }
    }

    fn pull_error<T: fmt::Debug>(result: Result<T>) -> String {
        match result {
            Err(Error::Pull(msg)) => msg,
            other => panic!("expected Pull, got {other:?}"),
        }
    }

    /// Returns the message of an [`Error::Io`], and checks its kind.
    fn not_found<T: fmt::Debug>(result: Result<T>) -> String {
        match result {
            Err(Error::Io(e)) => {
                assert_eq!(e.kind(), std::io::ErrorKind::NotFound);
                e.to_string()
            }
            other => panic!("expected Io, got {other:?}"),
        }
    }

    fn token(path: &Path) -> Result<String> {
        read_token_file(&KeyPath::caller(path), None)
    }

    fn pem(key: &str, path: &Path) -> Result<Vec<u8>> {
        read_pem_file(key, &KeyPath::caller(path), None)
    }

    /// The token is the first line of the file. A file with no line end holds
    /// the token alone.
    #[test]
    fn the_token_is_the_first_line_of_the_file() {
        let dir = Dir::new();
        let file = dir.file("token", b"s3cr3t-T0ken==\nsecond line\n");
        assert_eq!(token(&file).unwrap(), "s3cr3t-T0ken==");
        assert_eq!(token(&dir.file("bare", b"abc")).unwrap(), "abc");
        assert_eq!(
            token(&dir.file("all", b"aZ0-._~+/==")).unwrap(),
            "aZ0-._~+/=="
        );
    }

    /// A token that is empty, holds a carriage return, is not UTF-8, or is
    /// not token68 is refused, and the refusal holds no part of it.
    #[test]
    fn a_bad_token_is_refused_without_the_token() {
        let dir = Dir::new();
        for (bytes, part) in [
            (&b"\nQXZ"[..], "is empty"),
            (b"", "is empty"),
            (b"QXZ\r\n", "carriage return"),
            (b"QX\rZ", "carriage return"),
            (b"QXZ\xff\n", "not UTF-8"),
            (b"QX Z\n", "not token68"),
            (b"QXZ:x\n", "not token68"),
            (b"==\n", "not token68"),
            (b"QX=Z\n", "not token68"),
        ] {
            let path = dir.file("t", bytes);
            let m = invalid_input(token(&path));
            assert!(m.contains(part), "{bytes:?}: {m}");
            assert!(!m.contains("QX"), "{m}");
            assert!(
                m.starts_with(&format!("push-token-file '{}': ", path.display())),
                "{m}"
            );
        }
    }

    /// A first line over 1 MiB and a PEM file over 1 MiB are refused, and the
    /// message names the key and the path. A token file whose first line is
    /// short can be longer.
    #[test]
    fn a_file_over_the_cap_is_refused() {
        let dir = Dir::new();
        let long = vec![b'a'; FILE_CAP as usize + 1];
        let path = dir.file("long", &long);
        let m = invalid_input(token(&path));
        assert_eq!(
            m,
            format!(
                "the first line of push-token-file '{}' is over 1 MiB",
                path.display()
            )
        );
        let mut short = b"abc\n".to_vec();
        short.extend_from_slice(&long);
        assert_eq!(token(&dir.file("short", &short)).unwrap(), "abc");
        let mut at_cap = vec![b'a'; FILE_CAP as usize];
        at_cap.push(b'\n');
        assert_eq!(token(&dir.file("at-cap", &at_cap)).unwrap().len(), 1 << 20);

        let m = invalid_input(pem("tls-ca-path", &path));
        assert_eq!(m, format!("tls-ca-path '{}' is over 1 MiB", path.display()));
        let at_cap = dir.file("pem-at-cap", &vec![b'a'; FILE_CAP as usize]);
        assert_eq!(pem("tls-ca-path", &at_cap).unwrap().len(), 1 << 20);
    }

    /// A file that cannot be read is an I/O error that names the key and the
    /// path.
    #[test]
    fn an_absent_file_is_an_io_error_that_names_the_key_and_the_path() {
        let dir = Dir::new();
        let absent = dir.absent("absent");
        let m = not_found(token(&absent));
        assert!(
            m.starts_with(&format!("push-token-file '{}': ", absent.display())),
            "{m}"
        );
        for key in ["tls-ca-path", "tls-client-cert-path", "tls-client-key-path"] {
            let m = not_found(pem(key, &absent));
            assert!(
                m.starts_with(&format!("{key} '{}': ", absent.display())),
                "{m}"
            );
        }
    }

    /// An empty path of a key in a `.conf` file names no file, as the same
    /// value in `config` does, so the read gives the same refusal of an
    /// absent file. The case runs for each form of the remotes directory.
    #[test]
    fn an_empty_key_path_of_a_remotes_file_is_absent_as_in_config() {
        use crate::config::tests::repos_with_remotes_file;

        const KEYS: [&str; 4] = [
            "push-token-file",
            "tls-ca-path",
            "tls-client-cert-path",
            "tls-client-key-path",
        ];
        let dir = Dir::new();
        let section = |name: &str| {
            let mut text = format!("[remote \"{name}\"]\nurl=https://h/\n");
            for key in KEYS {
                text.push_str(&format!("{key}=\n"));
            }
            text
        };
        let root = dir.0.join("repo");
        for repo in repos_with_remotes_file(&root, &section("c"), &section("o")) {
            for key in KEYS {
                let messages: Vec<String> = ["c", "o"]
                    .into_iter()
                    .map(|name| {
                        let remote = repo.config().remote(name).unwrap();
                        let path = remote.key_path(key).unwrap().unwrap();
                        let result = match key {
                            "push-token-file" => read_token_file(&path, Some(&repo)).map(|_| ()),
                            _ => read_pem_file(key, &path, Some(&repo)).map(|_| ()),
                        };
                        not_found(result)
                    })
                    .collect();
                assert!(
                    messages[0].starts_with(&format!("{key} '': No such file or directory")),
                    "{messages:?}"
                );
                assert_eq!(messages[0], messages[1], "{:?}", repo.remotes_dir());
            }
        }
    }

    /// The `Debug` output shows no password of the url and no header value.
    /// It shows the header names and the paths.
    #[test]
    fn the_debug_output_shows_no_secret() {
        let o = EndpointOverrides {
            url: Some("https://user-QXZ:pw-QXZ@ex.com/repo".into()),
            push_token_file: Some("/etc/ostrya/token".into()),
            tls_ca_path: Some("/etc/ostrya/ca.pem".into()),
            http_headers: vec![
                ("Authorization".into(), "Bearer QXZ".into()),
                ("Cookie".into(), "id=QXZ".into()),
            ],
            ..EndpointOverrides::default()
        };
        let text = format!("{o:?}");
        assert!(!text.contains("QXZ"), "{text}");
        for part in [
            "https://ex.com/repo",
            "/etc/ostrya/token",
            "/etc/ostrya/ca.pem",
            "Authorization",
            "Cookie",
            "<redacted>",
        ] {
            assert!(text.contains(part), "{part}: {text}");
        }
    }

    const PULL_SECTIONS: &str = "[remote \"both\"]\nurl=https://ex.com/pull\n\
                                 pull-url=ssh://puller@ex.com/srv/repo\n\
                                 ssh-command=ssh -o BatchMode=yes\n\
                                 send-command=/opt/bin/ostrya send\n\
                                 tls-ca-path=/nonexistent/ca.pem\n\
                                 tls-permissive=maybe\n\n\
                                 [remote \"http-pull-url\"]\nurl=ssh://h/dead\n\
                                 pull-url=http://pull.ex.com/repo\n\
                                 ssh-command=ssh -q\n\
                                 send-command=ostrya send\n\n\
                                 [remote \"upper\"]\npull-url=HTTP://ex.com/repo\n\n\
                                 [remote \"file\"]\npull-url=file:///srv/repo\n\n\
                                 [remote \"scp\"]\npull-url=h:srv/repo\n\n\
                                 [remote \"bad-pull-url\"]\npull-url=ssh://h\n\n\
                                 [remote \"local-path\"]\npull-url=/srv/repo\n\n\
                                 [remote \"url\"]\nurl=https://ex.com/repo\n\
                                 contenturl=https://content.ex.com/repo\n\
                                 metalink=https://ex.com/metalink.xml\n\
                                 ssh-command=ssh -q\n\n\
                                 [remote \"ssh-url\"]\nurl=ssh://h/srv/repo\n\n\
                                 [remote \"scp-url\"]\nurl=u@h:/srv/repo\n\n\
                                 [remote \"file-url\"]\nurl=file:///srv/repo\n\n\
                                 [remote \"path-url\"]\nurl=/srv/repo\n\n\
                                 [remote \"none\"]\ngpg-verify=false\n";

    fn pull_url(name: &str, url: Option<&str>) -> Result<Endpoint> {
        let o = EndpointOverrides {
            url: url.map(str::to_owned),
            ..EndpointOverrides::default()
        };
        pull(Some(&config(PULL_SECTIONS)), name, o)
    }

    fn mirror(endpoint: Result<Endpoint>) -> String {
        let http = http_of(endpoint);
        assert_eq!(http.mirrors.len(), 1);
        http.mirrors[0].clone()
    }

    /// The url of the caller has precedence over `pull-url`, and `pull-url`
    /// has precedence over `url`.
    #[test]
    fn the_pull_takes_the_url_override_then_pull_url_then_url() {
        assert_eq!(
            mirror(pull_url("http-pull-url", Some("https://other.ex.com/"))),
            "https://other.ex.com/"
        );
        assert_eq!(
            ssh(pull_url("both", None)).0,
            SshAddress::parse("ssh://puller@ex.com/srv/repo").unwrap()
        );
        assert_eq!(
            ssh(pull_url("http-pull-url", Some("u@h:x"))).0,
            SshAddress::parse("u@h:x").unwrap()
        );
        // If `pull-url` is set, the pull does not read a dead ssh `url`.
        assert_eq!(
            mirror(pull_url("http-pull-url", None)),
            "http://pull.ex.com/repo"
        );
        assert_eq!(mirror(pull_url("url", None)), "https://ex.com/repo");
        assert_eq!(
            ssh(pull_url("scp", None)).0,
            SshAddress::parse("h:srv/repo").unwrap()
        );
    }

    /// A value with `://` and a scheme other than `ssh` goes to the fetcher
    /// as written.
    #[test]
    fn another_scheme_goes_to_the_fetcher() {
        assert_eq!(mirror(pull_url("upper", None)), "HTTP://ex.com/repo");
        assert_eq!(mirror(pull_url("file", None)), "file:///srv/repo");
        assert_eq!(mirror(pull_url("file-url", None)), "file:///srv/repo");
        assert_eq!(
            mirror(pull_url("none", Some("file:///srv/repo"))),
            "file:///srv/repo"
        );
    }

    /// A malformed ssh address of the caller or in `pull-url` gives
    /// `InvalidInput` with the text of the parser.
    #[test]
    fn a_malformed_ssh_address_is_invalid_input() {
        for (name, url, value) in [
            ("bad-pull-url", None, "ssh://h"),
            ("local-path", None, "/srv/repo"),
            ("none", Some("ssh://h"), "ssh://h"),
            ("none", Some("/srv/repo"), "/srv/repo"),
        ] {
            let msg = invalid_input(pull_url(name, url));
            assert!(msg.starts_with(&format!("address '{value}': ")), "{msg}");
        }
    }

    /// The pull refuses an ssh address in `url`, in the `ssh://` form and in
    /// the scp form. A `url` that is not an ssh address goes to the fetcher.
    #[test]
    fn an_ssh_address_in_url_is_refused() {
        for (name, value) in [("ssh-url", "ssh://h/srv/repo"), ("scp-url", "h:/srv/repo")] {
            assert_eq!(
                pull_error(pull_url(name, None)),
                format!(
                    "remote '{name}': url '{value}' is an ssh address; the port reads an ssh \
                     address from pull-url alone"
                )
            );
        }
        assert_eq!(mirror(pull_url("path-url", None)), "/srv/repo");
    }

    /// The refusal of an ssh address in `url` shows no user name and no
    /// password.
    #[test]
    fn the_refusal_of_an_ssh_url_shows_no_userinfo() {
        let config = config(
            "[remote \"ssh-userinfo\"]\nurl=ssh://user-QXZ:pw-QXZ@ex.com/srv/repo\n\n\
             [remote \"scp-user\"]\nurl=user-QXZ@ex.com:/srv/repo\n",
        );
        for (name, shown) in [
            ("ssh-userinfo", "ssh://ex.com/srv/repo"),
            ("scp-user", "ex.com:/srv/repo"),
        ] {
            let msg = pull_error(pull(Some(&config), name, EndpointOverrides::default()));
            assert!(!msg.contains("QXZ"), "{name}: {msg}");
            assert_eq!(
                msg,
                format!(
                    "remote '{name}': url '{shown}' is an ssh address; the port reads an ssh \
                     address from pull-url alone"
                )
            );
        }
    }

    /// The pull refuses a remote with no section and no url of the caller.
    /// It also refuses a section with neither key.
    #[test]
    fn a_pull_remote_with_no_address_is_refused() {
        assert_eq!(
            pull_error(pull_url("absent", None)),
            "no remote 'absent' is configured"
        );
        assert_eq!(
            pull_error(pull(None, "absent", EndpointOverrides::default())),
            "no remote 'absent' is configured"
        );
        assert_eq!(
            pull_error(pull_url("none", None)),
            "remote 'none' has no pull-url and no url"
        );
        assert_eq!(
            ssh(pull_url("absent", Some("ssh://h/x"))).0,
            SshAddress::parse("ssh://h/x").unwrap()
        );
    }

    /// An HTTP pull with no override gets the defaults of a pull, and the
    /// keys `contenturl` and `metalink` change nothing.
    #[test]
    fn an_http_pull_gets_the_defaults_of_a_pull() {
        for http in [
            http_of(pull_url("url", None)),
            http_of(pull(
                None,
                "absent",
                EndpointOverrides {
                    url: Some("https://ex.com/repo".into()),
                    ..EndpointOverrides::default()
                },
            )),
        ] {
            assert_eq!(http.mirrors, ["https://ex.com/repo"]);
            assert_eq!(http.max_retries, 5);
            assert_eq!(http.max_outstanding, 8);
            assert_eq!(
                http.low_speed,
                Some(LowSpeed {
                    limit: 1000,
                    time: Duration::from_secs(30)
                })
            );
            assert_eq!(http.tls, TlsOptions::default());
            assert!(matches!(http.proxy, Proxy::Environment));
            assert!(http.headers.is_empty());
            assert!(http.basic_auth.is_none());
            assert!(http.bearer_token.is_none());
            assert!(!http.allow_cleartext_credentials);
            let d = FetcherOptions::default();
            assert_eq!(http.max_redirects, d.max_redirects);
            assert_eq!(http.fetch_timeout, d.fetch_timeout);
        }
    }

    /// A low-speed value left `None` takes its default, and a zero in either
    /// value turns the rule off. A retry count of 0 turns the retries off.
    #[test]
    fn the_pull_applies_the_http_overrides() {
        let secs = Duration::from_secs;
        for (limit, time, expected) in [
            (None, None, Some((1000, secs(30)))),
            (Some(5), None, Some((5, secs(30)))),
            (None, Some(secs(10)), Some((1000, secs(10)))),
            (Some(5), Some(secs(10)), Some((5, secs(10)))),
            (Some(0), None, None),
            (None, Some(Duration::ZERO), None),
            (Some(0), Some(secs(10)), None),
        ] {
            let o = EndpointOverrides {
                low_speed_limit_bytes: limit,
                low_speed_time: time,
                ..EndpointOverrides::default()
            };
            let http = http_of(pull(Some(&config(PULL_SECTIONS)), "url", o));
            let expected = expected.map(|(limit, time)| LowSpeed { limit, time });
            assert_eq!(http.low_speed, expected, "{limit:?} {time:?}");
        }
        let o = EndpointOverrides {
            http_headers: vec![("X-A".into(), "b".into())],
            allow_cleartext_credentials: true,
            max_retries: Some(0),
            ..EndpointOverrides::default()
        };
        let http = http_of(pull(Some(&config(PULL_SECTIONS)), "url", o));
        assert_eq!(http.headers, [("X-A".to_owned(), "b".to_owned())]);
        assert!(http.allow_cleartext_credentials);
        assert_eq!(http.max_retries, 0);
    }

    /// `tls-permissive=true` gives `DangerousAcceptAnyChain`, and the pull
    /// does not read `tls-ca-path`. A CA path of the caller wins over the key.
    #[test]
    fn the_pull_maps_tls_permissive_to_any_chain() {
        let dir = Dir::new();
        let ca = dir.file("ca.pem", b"CA");
        let config = config(&format!(
            "[remote \"permissive\"]\nurl=https://ex.com/repo\n\
             tls-ca-path={}\ntls-permissive=true\n\n\
             [remote \"bad\"]\nurl=http://ex.com/repo\ntls-permissive=maybe\n",
            dir.absent("absent.pem").display()
        ));
        let http = http_of(pull(
            Some(&config),
            "permissive",
            EndpointOverrides::default(),
        ));
        assert_eq!(http.tls.roots, TrustRoots::DangerousAcceptAnyChain);
        let o = EndpointOverrides {
            tls_ca_path: Some(ca),
            ..EndpointOverrides::default()
        };
        let http = http_of(pull(Some(&config), "permissive", o));
        assert_eq!(http.tls.roots, TrustRoots::Pem(b"CA".to_vec()));
        // The pull reads the key for an `http://` address too.
        assert!(matches!(
            pull(Some(&config), "bad", EndpointOverrides::default()),
            Err(Error::Core(_))
        ));
    }

    /// Returns the PEM files of a CA and of a client, and a config whose
    /// remote `keys` names them.
    fn tls_keys(dir: &Dir, url: &str) -> TestRepo {
        let ca = dir.file("key-ca.pem", b"KEY-CA");
        let cert = dir.file("key-cert.pem", b"KEY-CERT");
        let key = dir.file("key-key.pem", b"KEY-KEY");
        let token = dir.file("key-token", b"KEY-TOKEN\n");
        config(&format!(
            "[remote \"keys\"]\nurl={url}\n\
             push-token-file={}\npush-user=alice\n\
             tls-ca-path={}\ntls-client-cert-path={}\ntls-client-key-path={}\n\
             proxy=http://proxy.ex.com:3128\n\
             ssh-command=ssh -o BatchMode=yes\n\
             receive-command=/opt/bin/ostrya receive\n\
             send-command=/opt/bin/ostrya send\n",
            token.display(),
            ca.display(),
            cert.display(),
            key.display()
        ))
    }

    /// The paths that a caller gives in place of the keys.
    fn given(dir: &Dir) -> [PathBuf; 4] {
        [
            dir.file("given-ca.pem", b"GIVEN-CA"),
            dir.file("given-cert.pem", b"GIVEN-CERT"),
            dir.file("given-key.pem", b"GIVEN-KEY"),
            dir.file("given-token", b"GIVEN-TOKEN\n"),
        ]
    }

    fn identity(http: &FetcherOptions) -> (Vec<u8>, Vec<u8>) {
        let identity = http.tls.client_identity.as_ref().unwrap();
        assert_eq!(identity.key_passphrase, None);
        (identity.cert_chain_pem.clone(), identity.key_pem.clone())
    }

    /// The pull reads the TLS keys and the `proxy` key, and an override wins
    /// over each TLS key on its own.
    #[test]
    fn an_override_wins_over_each_tls_key_of_the_pull() {
        let dir = Dir::new();
        let config = tls_keys(&dir, "https://ex.com/repo");
        let http = http_of(pull(Some(&config), "keys", EndpointOverrides::default()));
        assert_eq!(http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
        assert_eq!(identity(&http), (b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec()));
        assert!(matches!(&http.proxy, Proxy::Url(url) if url == "http://proxy.ex.com:3128"));

        let [ca, cert, key, _] = given(&dir);
        let o = EndpointOverrides {
            tls_ca_path: Some(ca.clone()),
            ..EndpointOverrides::default()
        };
        let http = http_of(pull(Some(&config), "keys", o));
        assert_eq!(http.tls.roots, TrustRoots::Pem(b"GIVEN-CA".to_vec()));
        assert_eq!(identity(&http), (b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec()));
        let o = EndpointOverrides {
            tls_client_cert_path: Some(cert.clone()),
            ..EndpointOverrides::default()
        };
        let http = http_of(pull(Some(&config), "keys", o));
        assert_eq!(http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
        assert_eq!(
            identity(&http),
            (b"GIVEN-CERT".to_vec(), b"KEY-KEY".to_vec())
        );
        let o = EndpointOverrides {
            tls_client_key_path: Some(key.clone()),
            ..EndpointOverrides::default()
        };
        let http = http_of(pull(Some(&config), "keys", o));
        assert_eq!(
            identity(&http),
            (b"KEY-CERT".to_vec(), b"GIVEN-KEY".to_vec())
        );
        // With no section, the paths of the caller apply alone.
        let o = EndpointOverrides {
            url: Some("https://ex.com/repo".into()),
            tls_ca_path: Some(ca),
            tls_client_cert_path: Some(cert),
            tls_client_key_path: Some(key),
            ..EndpointOverrides::default()
        };
        let http = http_of(pull(None, "absent", o));
        assert_eq!(http.tls.roots, TrustRoots::Pem(b"GIVEN-CA".to_vec()));
        assert_eq!(
            identity(&http),
            (b"GIVEN-CERT".to_vec(), b"GIVEN-KEY".to_vec())
        );
        assert!(matches!(http.proxy, Proxy::Environment));
    }

    /// A lone certificate or a lone key is refused before the pull reads a
    /// file.
    #[test]
    fn a_lone_certificate_or_key_is_refused_by_the_pull() {
        let dir = Dir::new();
        let pem = dir.file("pem", b"");
        let config = config(&format!(
            "[remote \"cert\"]\nurl=https://ex.com/repo\ntls-ca-path={}\n\
             tls-client-cert-path={}\n",
            dir.absent("absent.pem").display(),
            pem.display()
        ));
        let expected = "remote 'cert': a client certificate needs both tls-client-cert-path \
                        and tls-client-key-path";
        assert_eq!(
            pull_error(pull(Some(&config), "cert", EndpointOverrides::default())),
            expected
        );
        let o = EndpointOverrides {
            url: Some("https://ex.com/repo".into()),
            tls_client_key_path: Some(pem),
            ..EndpointOverrides::default()
        };
        assert_eq!(pull_error(pull(None, "cert", o)), expected);
    }

    /// A proxy value with white space at its start or end is refused before
    /// the pull reads a file.
    #[test]
    fn the_pull_refuses_a_proxy_with_white_space() {
        let dir = Dir::new();
        let config = config(&format!(
            "[remote \"proxy\"]\nurl=https://ex.com/repo\nproxy=http://user-QXZ:pw@p:1   \n\
             tls-ca-path={}\n",
            dir.absent("absent.pem").display()
        ));
        match pull(Some(&config), "proxy", EndpointOverrides::default()) {
            Err(Error::Unsupported(msg)) => {
                assert!(msg.contains("white space") && !msg.contains("QXZ"), "{msg}")
            }
            other => panic!("{other:?}"),
        }
    }

    /// The pull passes a `socks5h://` proxy value with its userinfo to the
    /// fetcher unchanged.
    #[test]
    fn the_pull_passes_a_socks5h_proxy_unchanged() {
        let config = config(
            "[remote \"socks\"]\nurl=https://ex.com/repo\n\
             proxy=socks5h://u:p@proxy.ex.com:1080\n",
        );
        let http = http_of(pull(Some(&config), "socks", EndpointOverrides::default()));
        assert!(matches!(&http.proxy, Proxy::Url(url) if url == "socks5h://u:p@proxy.ex.com:1080"));
    }

    /// A TLS file over 1 MiB and an absent TLS file fail the pull, and the
    /// error names the key and the path.
    #[test]
    fn a_tls_file_over_the_cap_fails_the_pull() {
        let dir = Dir::new();
        let long = dir.file("long", &vec![b'a'; FILE_CAP as usize + 1]);
        let absent = dir.absent("absent");
        let pem = dir.file("pem", b"");
        for (key, path) in [
            ("tls-ca-path", &long),
            ("tls-client-cert-path", &long),
            ("tls-client-key-path", &long),
        ] {
            let mut o = EndpointOverrides {
                url: Some("https://ex.com/repo".into()),
                tls_client_cert_path: Some(pem.clone()),
                tls_client_key_path: Some(pem.clone()),
                ..EndpointOverrides::default()
            };
            match key {
                "tls-ca-path" => o.tls_ca_path = Some(path.clone()),
                "tls-client-cert-path" => o.tls_client_cert_path = Some(path.clone()),
                _ => o.tls_client_key_path = Some(path.clone()),
            }
            assert_eq!(
                invalid_input(pull(None, "r", o.clone())),
                format!("{key} '{}' is over 1 MiB", path.display())
            );
            match key {
                "tls-ca-path" => o.tls_ca_path = Some(absent.clone()),
                "tls-client-cert-path" => o.tls_client_cert_path = Some(absent.clone()),
                _ => o.tls_client_key_path = Some(absent.clone()),
            }
            let m = not_found(pull(None, "r", o));
            assert!(
                m.starts_with(&format!("{key} '{}': ", absent.display())),
                "{m}"
            );
        }
    }

    /// The pull refuses the fields of a push for each transport, before it
    /// resolves the address.
    #[test]
    fn the_pull_refuses_the_fields_of_a_push() {
        for (name, o) in [
            (
                "push-token-file",
                EndpointOverrides {
                    push_token_file: Some("/t".into()),
                    push_user: Some("alice".into()),
                    ..EndpointOverrides::default()
                },
            ),
            (
                "push-user",
                EndpointOverrides {
                    push_user: Some("alice".into()),
                    ..EndpointOverrides::default()
                },
            ),
        ] {
            for url in ["https://ex.com/repo", "ssh://h/r"] {
                let o = EndpointOverrides {
                    url: Some(url.into()),
                    ..o.clone()
                };
                assert_eq!(
                    invalid_input(pull(None, "r", o)),
                    format!("{name} applies to a push, and this is a pull")
                );
            }
            assert_eq!(
                invalid_input(pull(None, "absent", o)),
                format!("{name} applies to a push, and this is a pull")
            );
        }
    }

    /// An HTTP pull refuses the ssh fields, and names them by their keys.
    #[test]
    fn the_pull_refuses_the_ssh_fields_for_an_http_address() {
        for (name, o) in [
            (
                "ssh-command",
                EndpointOverrides {
                    ssh_command: Some(vec!["ssh".into()]),
                    remote_command: Some("ostrya send".into()),
                    ..EndpointOverrides::default()
                },
            ),
            (
                "send-command",
                EndpointOverrides {
                    remote_command: Some("ostrya send".into()),
                    ..EndpointOverrides::default()
                },
            ),
        ] {
            assert_eq!(
                invalid_input(pull(Some(&config(PULL_SECTIONS)), "url", o)),
                format!("{name} applies to a pull over ssh, and this pull runs over HTTP")
            );
        }
    }

    /// The keys fill the ssh options that the caller leaves `None`. A field
    /// that the caller sets has precedence over its key.
    #[test]
    fn the_pull_fills_the_ssh_options_from_the_keys() {
        let config = config(PULL_SECTIONS);
        let (_, options) = ssh(pull(Some(&config), "both", EndpointOverrides::default()));
        assert_eq!(
            options,
            SshOptions {
                command: None,
                config_command: Some("ssh -o BatchMode=yes".into()),
                remote_command: Some("/opt/bin/ostrya send".into()),
            }
        );
        let o = EndpointOverrides {
            ssh_command: Some(vec!["my-ssh".into()]),
            remote_command: Some("my send".into()),
            ..EndpointOverrides::default()
        };
        let (_, options) = ssh(pull(Some(&config), "both", o.clone()));
        assert_eq!(
            options,
            SshOptions {
                command: Some(vec!["my-ssh".into()]),
                config_command: Some("ssh -o BatchMode=yes".into()),
                remote_command: Some("my send".into()),
            }
        );
        let o = EndpointOverrides {
            url: Some("ssh://h/r".into()),
            ..o
        };
        let (_, options) = ssh(pull(None, "absent", o));
        assert_eq!(options.config_command, None);
        assert_eq!(options.remote_command.as_deref(), Some("my send"));
        let (_, options) = ssh(pull_url("none", Some("ssh://h/r")));
        assert_eq!(options, SshOptions::default());
    }

    /// Returns each field of an HTTP address alone, in the order of the
    /// check, with its name.
    fn http_fields() -> Vec<(&'static str, EndpointOverrides)> {
        let d = EndpointOverrides::default;
        vec![
            (
                "tls-ca-path",
                EndpointOverrides {
                    tls_ca_path: Some("/c".into()),
                    ..d()
                },
            ),
            (
                "tls-client-cert-path",
                EndpointOverrides {
                    tls_client_cert_path: Some("/c".into()),
                    ..d()
                },
            ),
            (
                "tls-client-key-path",
                EndpointOverrides {
                    tls_client_key_path: Some("/k".into()),
                    ..d()
                },
            ),
            (
                "allow-cleartext-credentials",
                EndpointOverrides {
                    allow_cleartext_credentials: true,
                    ..d()
                },
            ),
            (
                "http-header",
                EndpointOverrides {
                    http_headers: vec![("A".into(), "B".into())],
                    ..d()
                },
            ),
            (
                "network-retries",
                EndpointOverrides {
                    max_retries: Some(1),
                    ..d()
                },
            ),
            (
                "low-speed-limit-bytes",
                EndpointOverrides {
                    low_speed_limit_bytes: Some(0),
                    ..d()
                },
            ),
            (
                "low-speed-time-seconds",
                EndpointOverrides {
                    low_speed_time: Some(Duration::ZERO),
                    ..d()
                },
            ),
        ]
    }

    /// Returns the overrides that set each field of `fields` from `first` on.
    fn from_field(fields: &[(&str, EndpointOverrides)], first: usize) -> EndpointOverrides {
        let mut o = EndpointOverrides::default();
        for (_, f) in &fields[first..] {
            o.tls_ca_path = o.tls_ca_path.or(f.tls_ca_path.clone());
            o.tls_client_cert_path = o.tls_client_cert_path.or(f.tls_client_cert_path.clone());
            o.tls_client_key_path = o.tls_client_key_path.or(f.tls_client_key_path.clone());
            o.allow_cleartext_credentials |= f.allow_cleartext_credentials;
            o.http_headers.extend(f.http_headers.iter().cloned());
            o.max_retries = o.max_retries.or(f.max_retries);
            o.low_speed_limit_bytes = o.low_speed_limit_bytes.or(f.low_speed_limit_bytes);
            o.low_speed_time = o.low_speed_time.or(f.low_speed_time);
            o.push_token_file = o.push_token_file.or(f.push_token_file.clone());
            o.push_user = o.push_user.or(f.push_user.clone());
        }
        o
    }

    /// For an ssh address, the pull refuses each field of an HTTP address
    /// alone, and names the first one that is set. The message shows the
    /// address with no user. A retry count of 0 is accepted.
    #[test]
    fn the_pull_refuses_each_http_field_for_an_ssh_address() {
        let fields = http_fields();
        for (first, (name, _)) in fields.iter().enumerate() {
            let o = EndpointOverrides {
                url: Some("user-QXZ@h:x".into()),
                ..from_field(&fields, first)
            };
            assert_eq!(
                invalid_input(pull(None, "r", o)),
                format!("{name} applies to a pull over HTTP, and 'ssh://h/~/x' is an ssh address")
            );
        }
        let o = EndpointOverrides {
            url: Some("ssh://h/x".into()),
            max_retries: Some(0),
            ..EndpointOverrides::default()
        };
        ssh(pull(None, "r", o));
    }

    /// The refusal of a field of an HTTP address shows no user name of the
    /// ssh address. It shows the address in the `ssh://` form with no user, so
    /// an `@` in the path stays.
    #[test]
    fn the_refusal_of_an_http_field_shows_no_user_name() {
        for (written, shown) in [
            ("ssh://user-QXZ@ex.com/srv/repo", "ssh://ex.com/srv/repo"),
            ("user-QXZ@ex.com:srv/repo", "ssh://ex.com/~/srv/repo"),
            ("ssh://user-QXZ@ex.com/srv/a@b", "ssh://ex.com/srv/a@b"),
        ] {
            let o = EndpointOverrides {
                url: Some(written.into()),
                http_headers: vec![("A".into(), "B".into())],
                ..EndpointOverrides::default()
            };
            let msg = invalid_input(pull(None, "r", o));
            assert!(!msg.contains("QXZ"), "{written}: {msg}");
            assert_eq!(
                msg,
                format!("http-header applies to a pull over HTTP, and '{shown}' is an ssh address")
            );
        }
    }

    /// A url of the caller replaces the address alone. The pull still reads
    /// the TLS keys and the `proxy` key of the named section.
    #[test]
    fn a_url_override_keeps_the_tls_and_proxy_keys_of_the_section() {
        let dir = Dir::new();
        let config = tls_keys(&dir, "https://ex.com/repo");
        let o = EndpointOverrides {
            url: Some("https://other.ex.com/".into()),
            ..EndpointOverrides::default()
        };
        let http = http_of(pull(Some(&config), "keys", o));
        assert_eq!(http.mirrors, ["https://other.ex.com/"]);
        assert_eq!(http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
        assert_eq!(identity(&http), (b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec()));
        assert!(matches!(&http.proxy, Proxy::Url(url) if url == "http://proxy.ex.com:3128"));
    }

    const LOCAL_SECTIONS: &str = "[remote \"url\"]\nurl=file:///srv/repo\n\n\
                                  [remote \"upper\"]\npull-url=FILE:///srv/a@b c\n\
                                  url=https://ex.com/repo\n\n\
                                  [remote \"http-pull-url\"]\npull-url=https://ex.com/repo\n\
                                  url=file:///srv/repo\n\n\
                                  [remote \"http\"]\nurl=https://ex.com/repo\n\n\
                                  [remote \"ssh\"]\npull-url=ssh://h/srv/repo\n\n\
                                  [remote \"keys\"]\nurl=file:///srv/repo\n\
                                  tls-ca-path=/nowhere/ca.pem\nproxy=http://proxy.ex.com\n\
                                  ssh-command=ssh -q\nsend-command=ostrya send\n\n\
                                  [remote \"s3-key\"]\nurl=file:///srv/repo\n\
                                  s3-region=eu-west-1\n\n\
                                  [remote \"none\"]\ngpg-verify=false\n";

    fn local(remote: &str, o: &EndpointOverrides) -> Result<Option<PathBuf>> {
        local_pull_path(config(LOCAL_SECTIONS).config(), remote, o)
    }

    /// A `file:` address of a pull, in either case of the scheme, gives the
    /// path as written. The TLS, proxy, and ssh keys of the section do not
    /// apply. Each other address, an absent section, and a section with no
    /// address give `None`. `pull-url` wins over `url`, and the url of the
    /// caller wins over both.
    #[test]
    fn a_file_address_gives_the_path_of_a_local_repository() {
        let d = EndpointOverrides::default();
        assert_eq!(local("url", &d).unwrap(), Some("/srv/repo".into()));
        assert_eq!(local("upper", &d).unwrap(), Some("/srv/a@b c".into()));
        assert_eq!(local("keys", &d).unwrap(), Some("/srv/repo".into()));
        for name in ["http-pull-url", "http", "ssh", "absent", "none"] {
            assert_eq!(local(name, &d).unwrap(), None, "{name}");
        }
        let o = EndpointOverrides {
            url: Some("file:////srv//x".into()),
            ..EndpointOverrides::default()
        };
        assert_eq!(local("http", &o).unwrap(), Some("//srv//x".into()));
        let o = EndpointOverrides {
            url: Some("https://ex.com/".into()),
            ..EndpointOverrides::default()
        };
        assert_eq!(local("url", &o).unwrap(), None);
    }

    /// A `file:` address with a host part, with no path, with no `//`, or
    /// with `%`, `?`, or `#` is refused with the name of the remote.
    #[test]
    fn a_malformed_file_address_is_refused() {
        for (address, reason) in [
            ("file://localhost/srv/repo", "names a host"),
            ("file://h/srv/repo", "names a host"),
            ("file://u-QXZ@h/srv/repo", "names a host"),
            ("file://", "has no path"),
            ("file:/srv/repo", "does not start with file://"),
            ("file:///srv/a%20b", "holds '%', '?', or '#'"),
            ("file:///srv/a?b", "holds '%', '?', or '#'"),
            ("file:///srv/a#b", "holds '%', '?', or '#'"),
        ] {
            let config = config(&format!("[remote \"r\"]\nurl={address}\n"));
            let msg = pull_error(local_pull_path(
                config.config(),
                "r",
                &EndpointOverrides::default(),
            ));
            assert!(!msg.contains("QXZ"), "{msg}");
            assert!(
                msg.starts_with("remote 'r': the file address '")
                    && msg.contains(&format!("' {reason}; ")),
                "{address}: {msg}"
            );
        }
    }

    /// For a `file:` address, a field of the caller that applies to another
    /// transport is refused with its name, and so is a field of a push. An
    /// S3 key of the section is refused. A retry count of 0 is accepted.
    #[test]
    fn a_local_repository_refuses_the_fields_of_another_transport() {
        let ssh = [
            (
                "ssh-command",
                EndpointOverrides {
                    ssh_command: Some(vec!["ssh".into()]),
                    ..EndpointOverrides::default()
                },
            ),
            (
                "send-command",
                EndpointOverrides {
                    remote_command: Some("ostrya send".into()),
                    ..EndpointOverrides::default()
                },
            ),
        ];
        let fields = http_fields().into_iter().chain(s3_fields()).chain(ssh);
        for (name, o) in fields {
            let msg = invalid_input(local("url", &o));
            assert!(
                msg.starts_with(&format!("{name} applies to "))
                    && msg.ends_with("the pull address of remote 'url' is a local repository"),
                "{msg}"
            );
        }
        let o = EndpointOverrides {
            push_user: Some("u".into()),
            ..EndpointOverrides::default()
        };
        assert_eq!(
            invalid_input(local("url", &o)),
            "push-user applies to a push, and this is a pull"
        );
        let o = EndpointOverrides {
            max_retries: Some(0),
            ..EndpointOverrides::default()
        };
        assert_eq!(local("url", &o).unwrap(), Some("/srv/repo".into()));
        let msg = pull_error(local("s3-key", &EndpointOverrides::default()));
        assert!(
            msg.contains("s3-region applies to an s3:// address"),
            "{msg}"
        );
    }

    /// Runs `f` on a thread, and fails the test if it does not end in 10
    /// seconds. A read that blocks on a FIFO so fails the test with no hang.
    fn in_time<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
        let worker = std::thread::spawn(f);
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        while !worker.is_finished() && std::time::Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(10));
        }
        assert!(worker.is_finished(), "the read does not end in 10 seconds");
        worker.join().unwrap()
    }

    /// Makes a FIFO at `path`. Returns `false` if the file system refuses it.
    fn make_fifo(path: &Path) -> bool {
        rustix::fs::mknodat(
            rustix::fs::CWD,
            path,
            rustix::fs::FileType::Fifo,
            rustix::fs::Mode::from_raw_mode(0o600),
            0,
        )
        .is_ok()
    }

    /// A relative TLS key in `config` is relative to the repository root,
    /// and not to the working directory. The read follows a symlink, and an
    /// absolute path with a `..` component opens. A relative key with a `..`
    /// component is refused at the read of the key, and a relative path of
    /// the caller with a `..` component is refused before a file is read.
    #[test]
    fn a_relative_tls_key_is_relative_to_the_repository_root() {
        let repo = config(
            "[remote \"rel\"]\nurl=https://ex.com/repo\ntls-ca-path=certs/ca.pem\n\
             tls-client-cert-path=certs/link.pem\ntls-client-key-path=certs/key.pem\n\
             [remote \"up\"]\nurl=https://ex.com/repo\ntls-ca-path=../ca.pem\n",
        );
        let certs = repo.path().join("certs");
        std::fs::create_dir(&certs).unwrap();
        // Before the files exist at the root, the pull fails, so no file of
        // the working directory serves it.
        let m = not_found(pull(Some(&repo), "rel", EndpointOverrides::default()));
        assert!(m.starts_with("tls-ca-path 'certs/ca.pem': "), "{m}");
        std::fs::write(certs.join("ca.pem"), b"ROOT-CA").unwrap();
        std::fs::write(certs.join("cert.pem"), b"ROOT-CERT").unwrap();
        std::fs::write(certs.join("key.pem"), b"ROOT-KEY").unwrap();
        std::os::unix::fs::symlink(certs.join("cert.pem"), certs.join("link.pem")).unwrap();
        let http = http_of(pull(Some(&repo), "rel", EndpointOverrides::default()));
        assert_eq!(http.tls.roots, TrustRoots::Pem(b"ROOT-CA".to_vec()));
        assert_eq!(
            identity(&http),
            (b"ROOT-CERT".to_vec(), b"ROOT-KEY".to_vec())
        );

        let err = pull(Some(&repo), "up", EndpointOverrides::default()).unwrap_err();
        assert!(
            matches!(&err, Error::InvalidFormat(m) if m == "[remote \"up\"] tls-ca-path \
                ../ca.pem has a `..` component, which a relative path in a config cannot have"),
            "{err:?}"
        );
        let o = EndpointOverrides {
            tls_ca_path: Some("../ca.pem".into()),
            ..EndpointOverrides::default()
        };
        assert_eq!(
            invalid_input(pull(Some(&repo), "rel", o)),
            "tls-ca-path ../ca.pem is a relative path with a `..` component"
        );
        let o = EndpointOverrides {
            tls_ca_path: Some(certs.join("../certs/ca.pem")),
            ..EndpointOverrides::default()
        };
        let http = http_of(pull(Some(&repo), "rel", o));
        assert_eq!(http.tls.roots, TrustRoots::Pem(b"ROOT-CA".to_vec()));
    }

    /// A FIFO, a directory, and a device at a TLS path fail the pull as a
    /// file that is not a regular file, and the FIFO does not block it.
    #[test]
    fn a_tls_path_that_is_not_a_regular_file_fails_the_pull() {
        let dir = Dir::new();
        let fifo = dir.absent("fifo.pem");
        let mut paths = vec![dir.0.clone(), PathBuf::from("/dev/null")];
        if make_fifo(&fifo) {
            paths.push(fifo);
        }
        for path in paths {
            let o = EndpointOverrides {
                url: Some("https://ex.com/repo".into()),
                tls_ca_path: Some(path.clone()),
                ..EndpointOverrides::default()
            };
            let result = in_time(move || pull(None, "r", o));
            assert_eq!(
                invalid_input(result),
                format!("tls-ca-path '{}' is not a regular file", path.display())
            );
        }
    }

    #[cfg(feature = "push")]
    mod push {
        use super::*;

        const CONFIG: &str = "[remote \"both\"]\nurl=https://ex.com/pull\n\
                              push-url=ssh://pusher@ex.com/srv/repo\n\
                              ssh-command=ssh -o BatchMode=yes\n\
                              receive-command=/opt/bin/ostrya receive\n\
                              push-token-file=/etc/ostrya/ssh-token\n\
                              push-user=ssh-user\n\
                              tls-ca-path=/etc/ostrya/ssh-ca.pem\n\
                              tls-client-cert-path=/etc/ostrya/ssh-client.pem\n\
                              tls-client-key-path=/etc/ostrya/ssh-client.key\n\
                              tls-permissive=true\n\n\
                              [remote \"https\"]\nurl=https://ex.com/repo\n\n\
                              [remote \"http-push-url\"]\nurl=https://pull.ex.com/repo\n\
                              push-url=http://push.ex.com/\n\n\
                              [remote \"permissive\"]\nurl=https://ex.com/repo\n\
                              tls-permissive=true\n\n\
                              [remote \"permissive-push-url\"]\nurl=https://ex.com/repo\n\
                              push-url=https://push.ex.com/\n\
                              tls-permissive=true\n\n\
                              [remote \"permissive-http\"]\nurl=https://ex.com/repo\n\
                              push-url=http://push.ex.com/\n\
                              tls-permissive=true\n\n\
                              [remote \"permissive-bad\"]\nurl=http://ex.com/repo\n\
                              tls-permissive=maybe\n\n\
                              [remote \"http\"]\nurl=http://ex.com/repo\n\n\
                              [remote \"file\"]\nurl=file:///srv/repo\n\n\
                              [remote \"metalink\"]\nurl=metalink=https://ex.com/metalink.xml\n\n\
                              [remote \"mirrorlist\"]\nurl=mirrorlist=https://ex.com/mirrors\n\n\
                              [remote \"none\"]\ngpg-verify=false\n\n\
                              [remote \"file-push\"]\nurl=file:///srv/repo\n\
                              push-url=host:srv/repo\n\n\
                              [remote \"bad-url\"]\nurl=a\\zb\n\
                              push-url=ssh://h/p\n";

        fn push(repo: Option<&TestRepo>, remote: &str, o: EndpointOverrides) -> Result<Endpoint> {
            ostrya_rt::block_on(resolve_push(handle(repo), remote, o))
        }

        fn push_named(name: &str) -> Result<Endpoint> {
            push(Some(&config(CONFIG)), name, EndpointOverrides::default())
        }

        fn refused<T: fmt::Debug>(result: Result<T>) -> String {
            match result {
                Err(Error::Remote(remote::Error::InvalidInput(msg))) => msg,
                other => panic!("expected InvalidInput, got {other:?}"),
            }
        }

        /// Returns the address of an endpoint as a string.
        fn address(endpoint: Result<Endpoint>) -> String {
            match endpoint {
                Ok(Endpoint::Http(http)) => {
                    assert_eq!(http.mirrors.len(), 1);
                    http.mirrors[0].clone()
                }
                Ok(Endpoint::Ssh { address, .. }) => address.to_string(),
                other => panic!("{other:?}"),
            }
        }

        fn parsed(value: &str) -> String {
            address(Endpoint::parse(value).map_err(Error::Remote))
        }

        #[test]
        fn a_value_with_a_colon_or_a_slash_is_an_address() {
            let cfg = config(CONFIG);
            for value in [
                "host:srv/repo",
                "host:repo",
                "ssh://host/srv/repo",
                "https://ex.com/r",
            ] {
                let endpoint = push(Some(&cfg), value, EndpointOverrides::default());
                assert_eq!(address(endpoint), parsed(value));
            }
            // No configuration is read for an address.
            let (address, options) = ssh(push(None, "host:srv/repo", EndpointOverrides::default()));
            assert_eq!(address, SshAddress::parse("host:srv/repo").unwrap());
            assert_eq!(options, SshOptions::default());
            let http = http_of(push(None, "https://ex.com/r", EndpointOverrides::default()));
            assert!(matches!(http.proxy, Proxy::Environment));
            assert_eq!(http.tls, TlsOptions::default());
            // An address that does not parse keeps the error of the parser,
            // also when it holds a `/` alone.
            for value in ["ftp://host/r", "srv/repo"] {
                let expected = match Endpoint::parse(value) {
                    Err(remote::Error::InvalidInput(msg)) => msg,
                    other => panic!("{value}: {other:?}"),
                };
                assert_eq!(
                    refused(push(Some(&cfg), value, EndpointOverrides::default())),
                    expected
                );
            }
        }

        #[test]
        fn push_url_wins_over_url() {
            assert_eq!(
                address(push_named("both")),
                parsed("ssh://pusher@ex.com/srv/repo")
            );
            // The push-url is the address also when the url is not a push
            // address.
            assert_eq!(address(push_named("file-push")), parsed("host:srv/repo"));
            // The keyfile cannot read the escape `\z` of this url, and the
            // push does not read it.
            assert!(
                config(CONFIG)
                    .config()
                    .remote("bad-url")
                    .unwrap()
                    .url()
                    .is_err()
            );
            assert_eq!(address(push_named("bad-url")), parsed("ssh://h/p"));
        }

        #[test]
        fn an_http_url_is_the_address_when_push_url_is_absent() {
            assert_eq!(address(push_named("https")), "https://ex.com/repo");
            assert_eq!(address(push_named("http")), "http://ex.com/repo");
            assert_eq!(address(push_named("http-push-url")), "http://push.ex.com/");
        }

        #[test]
        fn a_url_of_another_form_is_no_push_address() {
            for name in ["file", "metalink", "mirrorlist"] {
                let msg = refused(push_named(name));
                assert!(msg.contains("is no push address"), "{msg}");
            }
            assert_eq!(
                refused(push_named("none")),
                "remote 'none' has no push-url and no url"
            );
            let cfg = config(
                "[remote \"upper\"]\nurl=HTTPS://user-QXZ:pw-QXZ@ex.com/repo\n\n\
                 [remote \"ftp\"]\nurl=ftp://user-QXZ:pw-QXZ@ex.com/repo\n",
            );
            for (name, shown) in [
                ("upper", "HTTPS://ex.com/repo"),
                ("ftp", "ftp://ex.com/repo"),
            ] {
                let msg = refused(push(Some(&cfg), name, EndpointOverrides::default()));
                assert!(!msg.contains("QXZ"), "{name}: {msg}");
                assert_eq!(
                    msg,
                    format!(
                        "remote '{name}' has no push-url, and its url '{shown}' is no push \
                         address"
                    )
                );
            }
        }

        #[test]
        fn an_unknown_remote_is_refused_by_the_push() {
            assert_eq!(
                refused(push_named("absent")),
                "no remote 'absent' is configured"
            );
            assert_eq!(
                refused(push(None, "both", EndpointOverrides::default())),
                "no remote 'both' is configured"
            );
        }

        #[test]
        fn the_push_refuses_a_url_override() {
            for remote in ["https", "host:srv/repo", "absent"] {
                let o = EndpointOverrides {
                    url: Some("https://ex.com/repo".into()),
                    ..EndpointOverrides::default()
                };
                assert_eq!(
                    refused(push(Some(&config(CONFIG)), remote, o)),
                    "url applies to a pull, and this is a push"
                );
            }
        }

        #[test]
        fn the_push_refuses_tls_permissive_for_https() {
            for name in ["permissive", "permissive-push-url"] {
                assert_eq!(
                    refused(push_named(name)),
                    format!(
                        "remote '{name}' sets tls-permissive=true, which a push refuses: a \
                         push verifies the certificate chain of the server"
                    )
                );
            }
            // An `http://` push address uses no TLS, so the push does not read
            // the key. A value that is not a boolean causes no error.
            assert_eq!(
                address(push_named("permissive-http")),
                "http://push.ex.com/"
            );
            assert_eq!(address(push_named("permissive-bad")), "http://ex.com/repo");
            // An address reads no section, so no key refuses it.
            push(
                Some(&config(CONFIG)),
                "https://ex.com/repo",
                EndpointOverrides::default(),
            )
            .unwrap();
        }

        /// The push reads the `proxy` key of the section. It refuses a value
        /// with white space before it reads a file.
        #[test]
        fn the_push_reads_the_proxy_key() {
            let dir = Dir::new();
            let cfg = tls_keys(&dir, "https://ex.com/repo");
            let http = http_of(push(Some(&cfg), "keys", EndpointOverrides::default()));
            assert!(matches!(&http.proxy, Proxy::Url(url) if url == "http://proxy.ex.com:3128"));
            let http = http_of(push_named("https"));
            assert!(matches!(http.proxy, Proxy::Environment));
            let cfg = config(&format!(
                "[remote \"p\"]\nurl=https://ex.com/repo\nproxy=\\s\npush-token-file={}\n",
                dir.absent("absent").display()
            ));
            match push(Some(&cfg), "p", EndpointOverrides::default()) {
                Err(Error::Unsupported(msg)) => assert!(msg.contains("white space"), "{msg}"),
                other => panic!("{other:?}"),
            }
        }

        /// The push passes a `socks5h://` proxy value with its userinfo to the
        /// fetcher unchanged.
        #[test]
        fn the_push_passes_a_socks5h_proxy_unchanged() {
            let cfg = config(
                "[remote \"socks\"]\nurl=https://ex.com/repo\n\
                 proxy=socks5h://u:p@proxy.ex.com:1080\n",
            );
            let http = http_of(push(Some(&cfg), "socks", EndpointOverrides::default()));
            assert!(
                matches!(&http.proxy, Proxy::Url(url) if url == "socks5h://u:p@proxy.ex.com:1080")
            );
        }

        /// A token with `push-user` gives `basic_auth`. A token alone gives
        /// `bearer_token`.
        #[test]
        fn a_push_token_gives_a_bearer_token_or_a_basic_credential() {
            let dir = Dir::new();
            let cfg = tls_keys(&dir, "https://ex.com/repo");
            let http = http_of(push(Some(&cfg), "keys", EndpointOverrides::default()));
            assert_eq!(
                http.basic_auth,
                Some(BasicAuth {
                    user: "alice".into(),
                    password: "KEY-TOKEN".into()
                })
            );
            assert_eq!(http.bearer_token, None);
            assert_eq!(http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
            assert_eq!(identity(&http), (b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec()));

            let token = dir.file("t", b"s3cr3t==\n");
            let o = EndpointOverrides {
                push_token_file: Some(token),
                ..EndpointOverrides::default()
            };
            let http = http_of(push(None, "https://ex.com/r", o));
            assert_eq!(
                http.bearer_token,
                Some(BearerToken {
                    token: "s3cr3t==".into()
                })
            );
            assert_eq!(http.basic_auth, None);
            // With no token, the push has no credential.
            let http = http_of(push_named("https"));
            assert_eq!(http.bearer_token, None);
            assert_eq!(http.basic_auth, None);
        }

        /// A relative `push-token-file` in `config` is relative to the
        /// repository root. A relative key with a `..` component and a
        /// relative path of the caller with a `..` component are refused. A
        /// FIFO at the path fails the push with no hang.
        #[test]
        fn a_relative_push_token_file_is_relative_to_the_repository_root() {
            let cfg = config(
                "[remote \"rel\"]\npush-url=https://ex.com/r\npush-token-file=t/token\n\
                 [remote \"up\"]\npush-url=https://ex.com/r\npush-token-file=../token\n\
                 [remote \"fifo\"]\npush-url=https://ex.com/r\npush-token-file=t/fifo\n",
            );
            std::fs::create_dir(cfg.path().join("t")).unwrap();
            let m = not_found(push(Some(&cfg), "rel", EndpointOverrides::default()));
            assert!(m.starts_with("push-token-file 't/token': "), "{m}");
            std::fs::write(cfg.path().join("t/token"), b"r00t==\n").unwrap();
            let http = http_of(push(Some(&cfg), "rel", EndpointOverrides::default()));
            assert_eq!(
                http.bearer_token,
                Some(BearerToken {
                    token: "r00t==".into()
                })
            );
            let err = push(Some(&cfg), "up", EndpointOverrides::default()).unwrap_err();
            assert!(
                matches!(&err, Error::InvalidFormat(m)
                    if m.starts_with("[remote \"up\"] push-token-file ../token has a `..`")),
                "{err:?}"
            );
            let o = EndpointOverrides {
                push_token_file: Some("../token".into()),
                ..EndpointOverrides::default()
            };
            assert_eq!(
                refused(push(Some(&cfg), "rel", o)),
                "push-token-file ../token is a relative path with a `..` component"
            );
            if make_fifo(&cfg.path().join("t/fifo")) {
                let root = cfg.path().to_owned();
                let result = in_time(move || {
                    let repo = ostrya_rt::block_on(Repo::open(&root)).unwrap();
                    ostrya_rt::block_on(resolve_push(
                        Some(&repo),
                        "fifo",
                        EndpointOverrides::default(),
                    ))
                });
                assert_eq!(
                    invalid_input(result),
                    "push-token-file 't/fifo' is not a regular file"
                );
            }
        }

        /// An override wins over each key of the push on its own.
        #[test]
        fn an_override_wins_over_each_key_of_the_push() {
            let dir = Dir::new();
            let cfg = tls_keys(&dir, "https://ex.com/repo");
            let [ca, cert, key, token] = given(&dir);
            let resolve = |o: EndpointOverrides| http_of(push(Some(&cfg), "keys", o));
            let d = EndpointOverrides::default;

            let http = resolve(EndpointOverrides {
                push_token_file: Some(token),
                ..d()
            });
            assert_eq!(http.basic_auth.unwrap().password, "GIVEN-TOKEN");
            let http = resolve(EndpointOverrides {
                push_user: Some("bob".into()),
                ..d()
            });
            let auth = http.basic_auth.unwrap();
            assert_eq!(
                (auth.user.as_str(), auth.password.as_str()),
                ("bob", "KEY-TOKEN")
            );
            let http = resolve(EndpointOverrides {
                tls_ca_path: Some(ca),
                ..d()
            });
            assert_eq!(http.tls.roots, TrustRoots::Pem(b"GIVEN-CA".to_vec()));
            assert_eq!(identity(&http), (b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec()));
            let http = resolve(EndpointOverrides {
                tls_client_cert_path: Some(cert),
                ..d()
            });
            assert_eq!(http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
            assert_eq!(
                identity(&http),
                (b"GIVEN-CERT".to_vec(), b"KEY-KEY".to_vec())
            );
            let http = resolve(EndpointOverrides {
                tls_client_key_path: Some(key),
                ..d()
            });
            assert_eq!(
                identity(&http),
                (b"KEY-CERT".to_vec(), b"GIVEN-KEY".to_vec())
            );
        }

        /// The push applies the headers, the cleartext permission, the retry
        /// count, and the low-speed rule of the caller.
        #[test]
        fn the_push_applies_the_http_overrides() {
            let defaults = FetcherOptions::default();
            let http = http_of(push_named("https"));
            assert_eq!(http.max_retries, defaults.max_retries);
            assert_eq!(http.max_outstanding, defaults.max_outstanding);
            assert_eq!(http.low_speed, None);
            assert!(http.headers.is_empty());
            assert!(!http.allow_cleartext_credentials);

            let o = EndpointOverrides {
                http_headers: vec![("X-A".into(), "b".into())],
                allow_cleartext_credentials: true,
                max_retries: Some(0),
                ..EndpointOverrides::default()
            };
            let http = http_of(push(Some(&config(CONFIG)), "https", o));
            assert_eq!(http.headers, [("X-A".to_owned(), "b".to_owned())]);
            assert!(http.allow_cleartext_credentials);
            assert_eq!(http.max_retries, 0);

            let secs = Duration::from_secs;
            for (limit, time, expected) in [
                (Some(5), None, Some((5, secs(30)))),
                (None, Some(secs(10)), Some((1000, secs(10)))),
                (Some(5), Some(secs(10)), Some((5, secs(10)))),
                (Some(0), None, None),
                (None, Some(Duration::ZERO), None),
            ] {
                let o = EndpointOverrides {
                    low_speed_limit_bytes: limit,
                    low_speed_time: time,
                    ..EndpointOverrides::default()
                };
                let http = http_of(push(Some(&config(CONFIG)), "https", o));
                let expected = expected.map(|(limit, time)| LowSpeed { limit, time });
                assert_eq!(http.low_speed, expected, "{limit:?} {time:?}");
            }
        }

        /// `push_user` needs a token file. It cannot be empty or hold `:`.
        /// The refusals come before the push reads a file.
        #[test]
        fn push_user_needs_a_token_file() {
            let dir = Dir::new();
            let o = EndpointOverrides {
                push_user: Some("alice".into()),
                ..EndpointOverrides::default()
            };
            assert_eq!(
                refused(push(None, "https://h/", o)),
                "push-user needs push-token-file"
            );
            for user in ["", "a:b"] {
                let o = EndpointOverrides {
                    push_user: Some(user.into()),
                    push_token_file: Some(dir.absent("absent")),
                    ..EndpointOverrides::default()
                };
                assert_eq!(
                    refused(push(None, "https://h/", o)),
                    "push-user is empty or holds ':', which a Basic credential cannot carry"
                );
            }
        }

        /// A token to an `http://` address without the cleartext permission
        /// is refused before the push reads a file. The token file and the
        /// CA file are absent, so a read gives an I/O error in place of the
        /// refusal.
        #[test]
        fn the_push_refuses_a_cleartext_token_before_it_reads_a_file() {
            let dir = Dir::new();
            let absent = dir.absent("absent");
            let expected = |address: &str| {
                format!(
                    "the push address '{address}' is http://, so the token would travel in \
                     cleartext: use https, or set allow-cleartext-credentials"
                )
            };
            let o = EndpointOverrides {
                push_token_file: Some(absent.clone()),
                tls_ca_path: Some(absent.clone()),
                ..EndpointOverrides::default()
            };
            assert_eq!(refused(push(None, "http://h/", o)), expected("http://h/"));
            let cfg = config(&format!(
                "[remote \"keys\"]\nurl=http://ex.com/repo\n\
                 push-token-file={0}\ntls-ca-path={0}\n",
                absent.display()
            ));
            assert_eq!(
                refused(push(Some(&cfg), "keys", EndpointOverrides::default())),
                expected("http://ex.com/repo")
            );
        }

        /// With `allow_cleartext_credentials`, a token goes to an `http://`
        /// address.
        #[test]
        fn the_cleartext_permission_lets_a_token_go_to_an_http_address() {
            let dir = Dir::new();
            let cfg = tls_keys(&dir, "http://ex.com/repo");
            let o = EndpointOverrides {
                allow_cleartext_credentials: true,
                ..EndpointOverrides::default()
            };
            let http = http_of(push(Some(&cfg), "keys", o));
            assert!(http.allow_cleartext_credentials);
            assert_eq!(
                http.basic_auth,
                Some(BasicAuth {
                    user: "alice".into(),
                    password: "KEY-TOKEN".into()
                })
            );
            assert_eq!(http.tls, TlsOptions::default());

            let o = EndpointOverrides {
                push_token_file: Some(dir.file("t", b"s3cr3t==\n")),
                allow_cleartext_credentials: true,
                ..EndpointOverrides::default()
            };
            let http = http_of(push(None, "http://h/", o));
            assert_eq!(
                http.bearer_token,
                Some(BearerToken {
                    token: "s3cr3t==".into()
                })
            );
        }

        /// An `http://` push address uses no TLS, so the push reads no TLS
        /// file of the caller or of the keys. The files are absent, so a read
        /// gives an I/O error.
        #[test]
        fn a_cleartext_push_reads_no_tls_file() {
            let dir = Dir::new();
            let absent = dir.absent("absent");
            let o = EndpointOverrides {
                tls_ca_path: Some(absent.clone()),
                tls_client_cert_path: Some(absent.clone()),
                tls_client_key_path: Some(absent.clone()),
                ..EndpointOverrides::default()
            };
            let http = http_of(push(None, "http://h/", o));
            assert_eq!(http.tls, TlsOptions::default());
            let cfg = config(&format!(
                "[remote \"keys\"]\nurl=http://ex.com/repo\n\
                 tls-ca-path={0}\ntls-client-cert-path={0}\ntls-client-key-path={0}\n",
                absent.display()
            ));
            let http = http_of(push(Some(&cfg), "keys", EndpointOverrides::default()));
            assert_eq!(http.tls, TlsOptions::default());
        }

        /// The push gives an `Authorization` header of the caller beside the
        /// token. The HTTP client of the push session refuses the pair, so
        /// the session does not send one of the two in place of the other.
        #[test]
        fn the_push_session_refuses_an_authorization_header_beside_a_token() {
            let dir = Dir::new();
            let token = dir.file("t", b"s3cr3t==\n");
            for (user, part) in [
                (None, "a bearer token and an authorization header"),
                (
                    Some("alice"),
                    "basic-auth credentials and an authorization header",
                ),
            ] {
                let o = EndpointOverrides {
                    push_token_file: Some(token.clone()),
                    push_user: user.map(str::to_owned),
                    http_headers: vec![("Authorization".into(), "Bearer other".into())],
                    ..EndpointOverrides::default()
                };
                let endpoint = push(None, "https://h/", o).unwrap();
                match ostrya_rt::block_on(remote::PushSession::prepare(endpoint)) {
                    Err(remote::Error::Fetch(e)) => {
                        let msg = e.to_string();
                        assert!(msg.contains(part), "{msg}");
                        assert!(!msg.contains("s3cr3t"), "{msg}");
                    }
                    other => panic!("{user:?}: {other:?}"),
                }
            }
        }

        /// A lone certificate or a lone key is refused before the push reads
        /// a file.
        #[test]
        fn a_lone_certificate_or_key_is_refused_by_the_push() {
            let dir = Dir::new();
            let absent = dir.absent("absent");
            for (cert, key) in [(Some(absent.clone()), None), (None, Some(absent.clone()))] {
                // An `http://` address reads no TLS file, and the refusal
                // stays.
                for address in ["https://h/", "http://h/"] {
                    let o = EndpointOverrides {
                        push_token_file: Some(absent.clone()),
                        tls_ca_path: Some(absent.clone()),
                        tls_client_cert_path: cert.clone(),
                        tls_client_key_path: key.clone(),
                        ..EndpointOverrides::default()
                    };
                    assert_eq!(
                        refused(push(None, address, o)),
                        "a client certificate needs both tls-client-cert-path and \
                         tls-client-key-path"
                    );
                }
            }
        }

        /// A file over 1 MiB and an absent file fail the push, and the error
        /// names the key and the path.
        #[test]
        fn a_file_over_the_cap_fails_the_push() {
            let dir = Dir::new();
            let long = dir.file("long", &vec![b'a'; FILE_CAP as usize + 1]);
            let absent = dir.absent("absent");
            let pem = dir.file("pem", b"");
            type Field = fn(&mut EndpointOverrides) -> &mut Option<PathBuf>;
            let cases: [(&str, Field); 4] = [
                ("push-token-file", |o| &mut o.push_token_file),
                ("tls-ca-path", |o| &mut o.tls_ca_path),
                ("tls-client-cert-path", |o| &mut o.tls_client_cert_path),
                ("tls-client-key-path", |o| &mut o.tls_client_key_path),
            ];
            for (key, field) in cases {
                let mut o = EndpointOverrides {
                    tls_client_cert_path: Some(pem.clone()),
                    tls_client_key_path: Some(pem.clone()),
                    ..EndpointOverrides::default()
                };
                *field(&mut o) = Some(long.clone());
                let msg = invalid_input(push(None, "https://h/", o.clone()));
                assert!(
                    msg.contains(&format!("{key} '{}'", long.display())),
                    "{msg}"
                );
                assert!(msg.ends_with("over 1 MiB"), "{msg}");
                *field(&mut o) = Some(absent.clone());
                let m = not_found(push(None, "https://h/", o));
                assert!(
                    m.starts_with(&format!("{key} '{}': ", absent.display())),
                    "{m}"
                );
            }
        }

        /// An HTTP push refuses the ssh fields of the caller, and it does not
        /// read the ssh keys of the section.
        #[test]
        fn the_push_refuses_the_ssh_fields_for_an_http_address() {
            for (name, o) in [
                (
                    "ssh-command",
                    EndpointOverrides {
                        ssh_command: Some(vec!["ssh".into()]),
                        remote_command: Some("ostrya receive".into()),
                        ..EndpointOverrides::default()
                    },
                ),
                (
                    "receive-command",
                    EndpointOverrides {
                        remote_command: Some("ostrya receive".into()),
                        ..EndpointOverrides::default()
                    },
                ),
            ] {
                assert_eq!(
                    refused(push(None, "https://h/", o)),
                    format!(
                        "{name} applies to an ssh address, and 'https://h/' is an HTTP address"
                    )
                );
            }
            // The keyfile cannot read the escape `\z` of these keys, and the
            // push does not read them.
            let cfg = config(
                "[remote \"bad-ssh\"]\nurl=https://ex.com/repo\n\
                 ssh-command=a\\zb\nreceive-command=a\\zb\n",
            );
            let section = cfg.config().remote("bad-ssh").unwrap();
            assert!(section.ssh_command().is_err());
            assert!(section.receive_command().is_err());
            assert_eq!(
                address(push(Some(&cfg), "bad-ssh", EndpointOverrides::default())),
                "https://ex.com/repo"
            );
        }

        /// The keys fill the ssh options that the caller leaves `None`. The
        /// push does not read the HTTP keys of the section.
        #[test]
        fn the_push_fills_the_ssh_options_from_the_keys() {
            let (_, options) = ssh(push_named("both"));
            assert_eq!(
                options,
                SshOptions {
                    command: None,
                    config_command: Some("ssh -o BatchMode=yes".into()),
                    remote_command: Some("/opt/bin/ostrya receive".into()),
                }
            );
            let o = EndpointOverrides {
                ssh_command: Some(vec!["my-ssh".into()]),
                remote_command: Some("receiver".into()),
                ..EndpointOverrides::default()
            };
            let (_, options) = ssh(push(Some(&config(CONFIG)), "both", o.clone()));
            assert_eq!(
                options,
                SshOptions {
                    command: Some(vec!["my-ssh".into()]),
                    config_command: Some("ssh -o BatchMode=yes".into()),
                    remote_command: Some("receiver".into()),
                }
            );
            let (_, options) = ssh(push(None, "h:r", o));
            assert_eq!(options.config_command, None);
            assert_eq!(options.remote_command.as_deref(), Some("receiver"));
        }

        /// For an ssh address, the push refuses each field of an HTTP address
        /// alone, and names the first one that is set. The message shows the
        /// address with no user. A retry count of 0 is accepted.
        #[test]
        fn the_push_refuses_each_http_field_for_an_ssh_address() {
            let d = EndpointOverrides::default;
            let mut fields = vec![
                (
                    "push-token-file",
                    EndpointOverrides {
                        push_token_file: Some("/t".into()),
                        ..d()
                    },
                ),
                (
                    "push-user",
                    EndpointOverrides {
                        push_user: Some("u".into()),
                        ..d()
                    },
                ),
            ];
            fields.extend(http_fields());
            for (first, (name, _)) in fields.iter().enumerate() {
                let o = from_field(&fields, first);
                assert_eq!(
                    refused(push(None, "user-QXZ@h:x", o)),
                    format!(
                        "{name} applies to an HTTP address, and 'ssh://h/~/x' is an ssh address"
                    )
                );
            }
            // The message shows the `ssh://` form with no user. An `@` in the
            // path stays.
            for (value, shown) in [
                ("ssh://user-QXZ@ex.com/srv/repo", "ssh://ex.com/srv/repo"),
                ("user-QXZ@ex.com:srv/a@b", "ssh://ex.com/~/srv/a@b"),
            ] {
                let o = EndpointOverrides {
                    push_user: Some("u".into()),
                    ..d()
                };
                assert_eq!(
                    refused(push(None, value, o)),
                    format!(
                        "push-user applies to an HTTP address, and '{shown}' is an ssh address"
                    )
                );
            }
            let o = EndpointOverrides {
                max_retries: Some(0),
                ..d()
            };
            ssh(push(None, "h:x", o));
        }

        /// The push refuses each S3 field for an HTTP address and for an
        /// ssh address, for a remote name and for an address.
        #[test]
        fn the_push_refuses_the_s3_fields_for_another_address() {
            for (name, o) in s3_fields() {
                for (remote, shown) in [
                    ("https", "'https://ex.com/repo' is an HTTP address"),
                    ("https://ex.com/r", "'https://ex.com/r' is an HTTP address"),
                    ("ssh://u-QXZ@h/r", "'ssh://h/r' is an ssh address"),
                ] {
                    assert_eq!(
                        refused(push(Some(&config(CONFIG)), remote, o.clone())),
                        format!("{name} applies to an s3:// address, and {shown}")
                    );
                }
            }
        }

        /// A `url` with an `s3://` address is no push address, and the
        /// message names the `s3://` form with no userinfo.
        #[test]
        fn an_s3_address_in_url_is_no_push_address() {
            let config = config(S3_SECTIONS);
            for name in ["s3-url", "s3-url-user"] {
                assert_eq!(
                    refused(push(Some(&config), name, EndpointOverrides::default())),
                    format!(
                        "remote '{name}' has no push-url, and its url 's3://bkt/repo' is an \
                         s3:// address; the port reads an s3:// address from push-url alone"
                    )
                );
            }
        }

        /// An S3 key in a remote with no `s3://` address is refused for a
        /// push too.
        #[test]
        fn an_s3_key_with_no_s3_address_is_refused_by_the_push() {
            let config = config(S3_SECTIONS);
            assert_eq!(
                refused(push(
                    Some(&config),
                    "stray-key",
                    EndpointOverrides::default()
                )),
                "remote 'stray-key': s3-profile applies to an s3:// address, and neither \
                 pull-url nor push-url holds one"
            );
        }

        /// A build without the `s3` feature refuses an `s3://` push address,
        /// and the message names the feature and shows no userinfo.
        #[cfg(not(feature = "s3"))]
        #[test]
        fn a_build_without_s3_refuses_an_s3_push_address() {
            let config = config(S3_SECTIONS);
            for result in [
                push(Some(&config), "push", EndpointOverrides::default()),
                push(
                    None,
                    "s3://AKID-QXZ:s@bkt/repo",
                    EndpointOverrides::default(),
                ),
            ] {
                match result {
                    Err(Error::Unsupported(msg)) => {
                        assert!(msg.contains("the feature s3 of ostrya"), "{msg}");
                        assert!(msg.contains("'s3://bkt/repo'"), "{msg}");
                        assert!(!msg.contains("QXZ"), "{msg}");
                    }
                    other => panic!("{other:?}"),
                }
            }
        }

        /// `check_push` gives the error of `resolve_push` for each refusal
        /// that needs no file.
        #[test]
        fn check_push_gives_the_refusals_of_resolve_push_that_need_no_file() {
            let dir = Dir::new();
            let config = config(CONFIG);
            let d = EndpointOverrides::default;
            let cases = [
                (
                    "https",
                    EndpointOverrides {
                        url: Some("https://ex.com/".into()),
                        ..d()
                    },
                ),
                ("absent", d()),
                ("none", d()),
                ("permissive", d()),
                ("file", d()),
                (
                    "https",
                    EndpointOverrides {
                        s3_region: Some("eu-west-1".into()),
                        ..d()
                    },
                ),
                (
                    "https",
                    EndpointOverrides {
                        remote_command: Some("receive".into()),
                        ..d()
                    },
                ),
                (
                    "https",
                    EndpointOverrides {
                        push_user: Some(String::new()),
                        push_token_file: Some(dir.absent("token")),
                        ..d()
                    },
                ),
                (
                    "http",
                    EndpointOverrides {
                        push_token_file: Some(dir.absent("token")),
                        ..d()
                    },
                ),
                (
                    "both",
                    EndpointOverrides {
                        push_user: Some("u".into()),
                        ..d()
                    },
                ),
            ];
            for (name, o) in cases {
                let checked = check_push(Some(config.config()), name, o.clone());
                let resolved = push(Some(&config), name, o);
                assert!(checked.is_err(), "{name}: {checked:?}");
                assert_eq!(
                    format!("{checked:?}"),
                    format!("{:?}", resolved.map(drop)),
                    "{name}"
                );
            }
        }

        /// `check_push` reads no token file and no PEM file, and makes the
        /// ssh checks of the push session.
        #[test]
        fn check_push_reads_no_file_and_checks_the_ssh_command() {
            let dir = Dir::new();
            let o = EndpointOverrides {
                push_token_file: Some(dir.absent("token")),
                push_user: Some("alice".into()),
                tls_ca_path: Some(dir.absent("ca.pem")),
                ..EndpointOverrides::default()
            };
            assert_eq!(
                check_push(None, "https://h/", o.clone()).unwrap(),
                PushKind::Session
            );
            assert!(matches!(push(None, "https://h/", o), Err(Error::Io(_))));
            let ssh = |command: Vec<String>| EndpointOverrides {
                ssh_command: Some(command),
                ..EndpointOverrides::default()
            };
            assert_eq!(
                check_push(None, "ssh://h/srv/repo", ssh(vec!["ssh".into()])).unwrap(),
                PushKind::Session
            );
            // The resolver takes an empty ssh command, and the push session
            // refuses it.
            push(None, "ssh://h/srv/repo", ssh(Vec::new())).unwrap();
            match check_push(None, "ssh://h/srv/repo", ssh(Vec::new())) {
                Err(Error::Remote(remote::Error::InvalidInput(msg))) => {
                    assert_eq!(msg, "the ssh command of the options is empty")
                }
                other => panic!("{other:?}"),
            }
            let o = EndpointOverrides {
                ssh_command: Some(vec!["ssh".into()]),
                remote_command: Some(" ".into()),
                ..EndpointOverrides::default()
            };
            assert!(matches!(
                check_push(None, "ssh://h/srv/repo", o),
                Err(Error::Remote(remote::Error::InvalidInput(_)))
            ));
        }

        /// `check_push` refuses the options of an HTTP push that the HTTP
        /// client of the push session refuses before its TLS setup, with the
        /// error of the push session, and reads no token file.
        #[test]
        fn check_push_makes_the_refusals_of_the_push_session_that_need_no_file() {
            let dir = Dir::new();
            let config = config(
                "[remote \"proxied\"]\nurl=https://h/repo\nproxy=ftp://proxy:3128\n\n\
                 [remote \"plain\"]\nurl=https://h/repo\nproxy=http://proxy:3128\n\n\
                 [remote \"cleartext\"]\nurl=http://h/repo\nproxy=http://proxy:3128\n",
            );
            let d = EndpointOverrides::default;
            let headers = |pairs: &[(&str, &str)]| EndpointOverrides {
                http_headers: pairs
                    .iter()
                    .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
                    .collect(),
                ..d()
            };
            // The last case has a bad header and a bad proxy. The header
            // comes first in both calls.
            for (name, o) in [
                ("proxied", d()),
                ("plain", headers(&[("Host", "other")])),
                ("plain", headers(&[("Connection", "close")])),
                ("cleartext", headers(&[("Cookie", "id=1")])),
                ("proxied", headers(&[("Host", "other")])),
            ] {
                let endpoint = push(Some(&config), name, o.clone()).unwrap();
                let prepared = ostrya_rt::block_on(remote::PushSession::prepare(endpoint))
                    .map(drop)
                    .map_err(Error::Remote);
                let checked = check_push(Some(config.config()), name, o);
                assert!(
                    matches!(checked, Err(Error::Remote(remote::Error::Fetch(_)))),
                    "{checked:?}"
                );
                assert_eq!(format!("{checked:?}"), format!("{prepared:?}"), "{name}");
            }
            assert_eq!(
                check_push(Some(config.config()), "plain", d()).unwrap(),
                PushKind::Session
            );
            // The token file is absent, so a read of it would fail the check.
            let o = EndpointOverrides {
                push_token_file: Some(dir.absent("token")),
                ..d()
            };
            assert!(matches!(
                check_push(Some(config.config()), "proxied", o),
                Err(Error::Remote(remote::Error::Fetch(_)))
            ));
        }
    }

    /// Returns each S3 field alone, with the name of its key.
    fn s3_fields() -> Vec<(&'static str, EndpointOverrides)> {
        let d = EndpointOverrides::default;
        vec![
            (
                "s3-region",
                EndpointOverrides {
                    s3_region: Some("eu-west-1".into()),
                    ..d()
                },
            ),
            (
                "s3-endpoint",
                EndpointOverrides {
                    s3_endpoint: Some("https://s3.ex.com".into()),
                    ..d()
                },
            ),
            (
                "s3-addressing",
                EndpointOverrides {
                    s3_addressing: Some("path".into()),
                    ..d()
                },
            ),
            (
                "s3-profile",
                EndpointOverrides {
                    s3_profile: Some("p".into()),
                    ..d()
                },
            ),
        ]
    }

    const S3_SECTIONS: &str = "[remote \"s3-url\"]\nurl=s3://bkt/repo\n\n\
                               [remote \"s3-url-user\"]\nurl=s3://u-QXZ:p-QXZ@bkt/repo\n\n\
                               [remote \"pull\"]\npull-url=s3://bkt/repo\n\n\
                               [remote \"push\"]\nurl=https://ex.com/repo\n\
                               push-url=s3://bkt/repo\ns3-region=eu-west-1\n\n\
                               [remote \"stray-key\"]\nurl=https://ex.com/repo\n\
                               push-url=ssh://h/srv/repo\ns3-profile=p\n\n\
                               [remote \"stray-region\"]\npull-url=https://ex.com/repo\n\
                               s3-region=eu-west-1\ns3-endpoint=https://s3.ex.com\n";

    /// The pull refuses an `s3://` address in `url`, in each build, and
    /// shows no userinfo.
    #[test]
    fn an_s3_address_in_url_is_refused() {
        let config = config(S3_SECTIONS);
        for name in ["s3-url", "s3-url-user"] {
            let msg = pull_error(pull(Some(&config), name, EndpointOverrides::default()));
            assert_eq!(
                msg,
                format!(
                    "remote '{name}': url 's3://bkt/repo' is an s3:// address; the port reads \
                     an s3:// address from pull-url alone"
                )
            );
        }
    }

    /// The address of a pull is `s3://` by the order of the pull: the url of
    /// the caller, then `pull-url`, then `url`. An `s3://` address in `url`
    /// and an absent remote give `None`, the refusal of the resolver.
    #[test]
    fn the_s3_test_of_a_pull_address_follows_the_order_of_the_pull() {
        let config = config(S3_SECTIONS);
        let is_s3 = |remote, url| pull_address_is_s3(Some(config.config()), remote, url);
        assert_eq!(is_s3("pull", None), Some(true));
        assert_eq!(is_s3("push", None), Some(false));
        assert_eq!(is_s3("s3-url", None), None);
        assert_eq!(is_s3("absent", None), None);
        assert_eq!(is_s3("push", Some("s3://b/x")), Some(true));
        assert_eq!(is_s3("pull", Some("https://ex.com/r")), Some(false));
        assert_eq!(is_s3("pull", Some("h:/srv/r")), Some(false));
        assert_eq!(pull_address_is_s3(None, "r", Some("s3://b/x")), Some(true));
        assert_eq!(pull_address_is_s3(None, "r", None), None);
    }

    /// An S3 key in a remote whose `pull-url` and `push-url` hold no `s3://`
    /// address is refused, also with an `s3://` url of the caller. A remote
    /// with an `s3://` `push-url` keeps its HTTP pull with the S3 keys.
    #[test]
    fn an_s3_key_with_no_s3_address_is_refused() {
        let config = config(S3_SECTIONS);
        for (name, key, url) in [
            ("stray-key", "s3-profile", None),
            ("stray-region", "s3-region", None),
            ("stray-region", "s3-region", Some("s3://bkt/repo")),
        ] {
            let o = EndpointOverrides {
                url: url.map(str::to_owned),
                ..EndpointOverrides::default()
            };
            assert_eq!(
                pull_error(pull(Some(&config), name, o)),
                format!(
                    "remote '{name}': {key} applies to an s3:// address, and neither \
                     pull-url nor push-url holds one"
                )
            );
        }
        assert_eq!(
            mirror(pull(Some(&config), "push", EndpointOverrides::default())),
            "https://ex.com/repo"
        );
    }

    /// The pull refuses each S3 field for an HTTP address and for an ssh
    /// address, and names it by its key.
    #[test]
    fn the_pull_refuses_the_s3_fields_for_another_address() {
        for (name, o) in s3_fields() {
            let http = EndpointOverrides {
                url: Some("https://ex.com/repo".into()),
                ..o.clone()
            };
            assert_eq!(
                invalid_input(pull(None, "r", http)),
                format!(
                    "{name} applies to a pull from an s3:// address, and this pull runs over \
                     HTTP"
                )
            );
            let ssh = EndpointOverrides {
                url: Some("user-QXZ@h:x".into()),
                ..o
            };
            assert_eq!(
                invalid_input(pull(None, "r", ssh)),
                format!(
                    "{name} applies to a pull from an s3:// address, and 'ssh://h/~/x' is an \
                     ssh address"
                )
            );
        }
    }

    /// The pull refuses the fields of a push for an `s3://` address, in each
    /// build.
    #[test]
    fn the_pull_refuses_the_fields_of_a_push_for_an_s3_address() {
        for (name, o) in [
            (
                "push-token-file",
                EndpointOverrides {
                    push_token_file: Some("/t".into()),
                    ..EndpointOverrides::default()
                },
            ),
            (
                "push-user",
                EndpointOverrides {
                    push_user: Some("alice".into()),
                    ..EndpointOverrides::default()
                },
            ),
        ] {
            let o = EndpointOverrides {
                url: Some("s3://bkt/repo".into()),
                ..o
            };
            assert_eq!(
                invalid_input(pull(None, "r", o)),
                format!("{name} applies to a push, and this is a pull")
            );
        }
    }

    /// The `Debug` output shows the S3 endpoint with no userinfo.
    #[test]
    fn the_debug_output_shows_no_userinfo_of_the_s3_endpoint() {
        let o = EndpointOverrides {
            s3_endpoint: Some("https://user-QXZ:pw-QXZ@s3.ex.com".into()),
            s3_profile: Some("prod".into()),
            ..EndpointOverrides::default()
        };
        let text = format!("{o:?}");
        assert!(!text.contains("QXZ"), "{text}");
        assert!(text.contains("https://s3.ex.com"), "{text}");
        assert!(text.contains("prod"), "{text}");
    }

    /// A build without the `s3` feature refuses an `s3://` address, and the
    /// message names the feature.
    #[cfg(not(feature = "s3"))]
    #[test]
    fn a_build_without_s3_refuses_an_s3_address() {
        let config = config(S3_SECTIONS);
        let o = EndpointOverrides {
            url: Some("s3://bkt/repo".into()),
            ..EndpointOverrides::default()
        };
        for result in [
            pull(Some(&config), "pull", EndpointOverrides::default()),
            pull(None, "r", o),
        ] {
            match result {
                Err(Error::Unsupported(msg)) => {
                    assert!(msg.contains("the feature s3 of ostrya"), "{msg}")
                }
                other => panic!("{other:?}"),
            }
        }
    }

    /// The refusal of an `s3://` address by a build without the `s3`
    /// feature shows no userinfo of the address.
    #[cfg(not(feature = "s3"))]
    #[test]
    fn the_refusal_of_an_s3_address_shows_no_userinfo() {
        let config = config("[remote \"keyed\"]\npull-url=s3://AKID-QXZ:secret-QXZ@bkt/repo\n");
        let o = EndpointOverrides {
            url: Some("s3://AKID-QXZ:secret-QXZ@bkt/repo".into()),
            ..EndpointOverrides::default()
        };
        for result in [
            pull(Some(&config), "keyed", EndpointOverrides::default()),
            pull(None, "r", o),
        ] {
            match result {
                Err(Error::Unsupported(msg)) => {
                    assert!(!msg.contains("QXZ"), "{msg}");
                    assert!(msg.contains("'s3://bkt/repo'"), "{msg}");
                }
                other => panic!("{other:?}"),
            }
        }
    }

    #[cfg(feature = "s3")]
    mod s3 {
        use super::*;
        use crate::remote::s3::{Addressing, Environment, S3Endpoint};

        /// Returns the environment of a test: a key pair, the two shared
        /// files at absent paths under `dir`, and then `extra`.
        fn env(dir: &Dir, extra: &[(&str, &str)]) -> Environment {
            let mut variables = vec![
                ("AWS_ACCESS_KEY_ID".to_owned(), "AKIDEXAMPLE".to_owned()),
                ("AWS_SECRET_ACCESS_KEY".to_owned(), "SECRET-QXZ".to_owned()),
                (
                    "AWS_CONFIG_FILE".to_owned(),
                    dir.absent("aws-config").display().to_string(),
                ),
                (
                    "AWS_SHARED_CREDENTIALS_FILE".to_owned(),
                    dir.absent("aws-credentials").display().to_string(),
                ),
            ];
            variables.extend(
                extra
                    .iter()
                    .map(|(name, value)| ((*name).to_owned(), (*value).to_owned())),
            );
            Environment::Variables(variables)
        }

        fn pull_in(
            repo: Option<&TestRepo>,
            remote: &str,
            o: EndpointOverrides,
            env: &Environment,
        ) -> Result<Endpoint> {
            ostrya_rt::block_on(resolve_pull_in(handle(repo), remote, o, env))
        }

        fn s3_of(endpoint: Result<Endpoint>) -> S3Endpoint {
            match endpoint {
                Ok(Endpoint::S3(s3)) => s3,
                other => panic!("{other:?}"),
            }
        }

        /// An `s3://` address of `pull-url` or of the caller gives an S3
        /// endpoint with the defaults of a pull.
        #[test]
        fn an_s3_address_gives_an_s3_endpoint() {
            let dir = Dir::new();
            let config = config(S3_SECTIONS);
            let other = EndpointOverrides {
                url: Some("s3://other/x".into()),
                ..EndpointOverrides::default()
            };
            for (name, o, repository) in [
                (
                    "pull",
                    EndpointOverrides::default(),
                    "https://bkt.s3.us-east-1.amazonaws.com/repo",
                ),
                (
                    "absent",
                    other,
                    "https://other.s3.us-east-1.amazonaws.com/x",
                ),
            ] {
                let s3 = s3_of(pull_in(Some(&config), name, o, &env(&dir, &[])));
                assert_eq!(s3.location.repository_url(), repository);
                assert_eq!(s3.location.region(), "us-east-1");
                assert_eq!(s3.credentials.access_key_id(), "AKIDEXAMPLE");
                assert_eq!(s3.http.max_retries, 5);
                assert_eq!(s3.http.max_outstanding, 8);
                assert_eq!(
                    s3.http.low_speed,
                    Some(LowSpeed {
                        limit: 1000,
                        time: Duration::from_secs(30)
                    })
                );
                assert_eq!(s3.http.tls, TlsOptions::default());
                assert!(matches!(s3.http.proxy, Proxy::Environment));
                assert!(!s3.http.allow_cleartext_credentials);
                assert!(s3.http.mirrors.is_empty());
                assert!(s3.http.signer.is_none());
            }
        }

        /// A field of the caller wins over its key, and a key wins over the
        /// environment.
        #[test]
        fn an_override_wins_over_the_key_and_the_key_over_the_environment() {
            let dir = Dir::new();
            let config = config(
                "[remote \"keys\"]\npull-url=s3://bkt/repo\ns3-region=eu-west-1\n\
                 s3-endpoint=https://keys.ex.com\ns3-addressing=virtual\n\n\
                 [remote \"bare\"]\npull-url=s3://bkt/repo\n",
            );
            let env = env(
                &dir,
                &[
                    ("AWS_REGION", "us-west-2"),
                    ("AWS_ENDPOINT_URL_S3", "https://env.ex.com"),
                ],
            );
            let s3 = s3_of(pull_in(
                Some(&config),
                "keys",
                EndpointOverrides::default(),
                &env,
            ));
            assert_eq!(s3.location.region(), "eu-west-1");
            assert_eq!(s3.location.endpoint(), "https://keys.ex.com");
            assert_eq!(s3.location.addressing(), Addressing::Virtual);
            assert_eq!(s3.location.repository_url(), "https://bkt.keys.ex.com/repo");
            let o = EndpointOverrides {
                s3_region: Some("ap-south-1".into()),
                s3_endpoint: Some("https://given.ex.com".into()),
                s3_addressing: Some("path".into()),
                ..EndpointOverrides::default()
            };
            let s3 = s3_of(pull_in(Some(&config), "keys", o, &env));
            assert_eq!(s3.location.region(), "ap-south-1");
            assert_eq!(s3.location.endpoint(), "https://given.ex.com");
            assert_eq!(
                s3.location.repository_url(),
                "https://given.ex.com/bkt/repo"
            );
            // With no key and no field, the environment gives the values.
            let s3 = s3_of(pull_in(
                Some(&config),
                "bare",
                EndpointOverrides::default(),
                &env,
            ));
            assert_eq!(s3.location.region(), "us-west-2");
            assert_eq!(s3.location.endpoint(), "https://env.ex.com");
        }

        /// A profile that the key `s3-profile` names turns off the key pair
        /// of the environment.
        #[test]
        fn a_profile_of_the_key_turns_off_the_keys_of_the_environment() {
            let dir = Dir::new();
            let credentials = dir.file(
                "credentials",
                b"[keyed]\naws_access_key_id = AKIDPROFILE\naws_secret_access_key = S\n",
            );
            let config = config("[remote \"p\"]\npull-url=s3://bkt/repo\ns3-profile=keyed\n");
            let env = Environment::Variables(vec![
                ("AWS_ACCESS_KEY_ID".into(), "AKIDEXAMPLE".into()),
                ("AWS_SECRET_ACCESS_KEY".into(), "SECRET-QXZ".into()),
                (
                    "AWS_CONFIG_FILE".into(),
                    dir.absent("config").display().to_string(),
                ),
                (
                    "AWS_SHARED_CREDENTIALS_FILE".into(),
                    credentials.display().to_string(),
                ),
            ]);
            let s3 = s3_of(pull_in(
                Some(&config),
                "p",
                EndpointOverrides::default(),
                &env,
            ));
            assert_eq!(s3.credentials.access_key_id(), "AKIDPROFILE");
        }

        /// A style other than `path` and `virtual` is refused, from the key
        /// and from a field.
        #[test]
        fn a_bad_addressing_style_is_refused() {
            let dir = Dir::new();
            let config = config("[remote \"auto\"]\npull-url=s3://bkt/repo\ns3-addressing=auto\n");
            assert_eq!(
                invalid_input(pull_in(
                    Some(&config),
                    "auto",
                    EndpointOverrides::default(),
                    &env(&dir, &[])
                )),
                "s3-addressing 'auto' is neither path nor virtual"
            );
            let o = EndpointOverrides {
                url: Some("s3://bkt/repo".into()),
                s3_addressing: Some("Path".into()),
                ..EndpointOverrides::default()
            };
            assert_eq!(
                invalid_input(pull_in(None, "r", o, &env(&dir, &[]))),
                "s3-addressing 'Path' is neither path nor virtual"
            );
        }

        /// The pull refuses the ssh fields for an `s3://` address.
        #[test]
        fn the_pull_refuses_the_ssh_fields_for_an_s3_address() {
            let dir = Dir::new();
            for (name, o) in [
                (
                    "ssh-command",
                    EndpointOverrides {
                        ssh_command: Some(vec!["ssh".into()]),
                        ..EndpointOverrides::default()
                    },
                ),
                (
                    "send-command",
                    EndpointOverrides {
                        remote_command: Some("ostrya send".into()),
                        ..EndpointOverrides::default()
                    },
                ),
            ] {
                let o = EndpointOverrides {
                    url: Some("s3://bkt/repo".into()),
                    ..o
                };
                assert_eq!(
                    invalid_input(pull_in(None, "r", o, &env(&dir, &[]))),
                    format!(
                        "{name} applies to a pull over ssh, and this pull reads an s3:// \
                         address"
                    )
                );
            }
        }

        /// An `http://` endpoint needs the cleartext permission. The endpoint
        /// can come from the environment, so the check comes after the
        /// resolution.
        #[test]
        fn an_http_endpoint_needs_the_cleartext_permission() {
            let dir = Dir::new();
            let config = config(S3_SECTIONS);
            let env = env(&dir, &[("AWS_ENDPOINT_URL", "http://127.0.0.1:9000")]);
            assert_eq!(
                invalid_input(pull_in(
                    Some(&config),
                    "pull",
                    EndpointOverrides::default(),
                    &env,
                )),
                "the S3 endpoint 'http://127.0.0.1:9000' is http://, so the signature of each \
                 request would travel in cleartext: use https, or set \
                 allow-cleartext-credentials"
            );
            let o = EndpointOverrides {
                allow_cleartext_credentials: true,
                ..EndpointOverrides::default()
            };
            let s3 = s3_of(pull_in(Some(&config), "pull", o, &env));
            assert!(s3.http.allow_cleartext_credentials);
            assert_eq!(
                s3.location.repository_url(),
                "http://127.0.0.1:9000/bkt/repo"
            );
        }

        /// The TLS keys, the proxy key, and the HTTP fields of the caller go
        /// into the HTTP options of the S3 endpoint. The pull ignores the ssh
        /// keys and `push-token-file` of the section.
        #[test]
        fn the_http_options_go_into_the_s3_endpoint() {
            let dir = Dir::new();
            let config = tls_keys(&dir, "https://ex.com/repo");
            let o = EndpointOverrides {
                url: Some("s3://bkt/repo".into()),
                http_headers: vec![("X-A".into(), "b".into())],
                max_retries: Some(2),
                low_speed_limit_bytes: Some(0),
                ..EndpointOverrides::default()
            };
            let s3 = s3_of(pull_in(Some(&config), "keys", o, &env(&dir, &[])));
            assert_eq!(s3.http.tls.roots, TrustRoots::Pem(b"KEY-CA".to_vec()));
            assert_eq!(
                identity(&s3.http),
                (b"KEY-CERT".to_vec(), b"KEY-KEY".to_vec())
            );
            assert!(matches!(&s3.http.proxy, Proxy::Url(url) if url == "http://proxy.ex.com:3128"));
            assert_eq!(s3.http.headers, [("X-A".to_owned(), "b".to_owned())]);
            assert_eq!(s3.http.max_retries, 2);
            assert_eq!(s3.http.low_speed, None);
            let config = super::config(
                "[remote \"permissive\"]\npull-url=s3://bkt/repo\ntls-permissive=true\n\
                 tls-ca-path=/nonexistent/ca.pem\n",
            );
            let s3 = s3_of(pull_in(
                Some(&config),
                "permissive",
                EndpointOverrides::default(),
                &env(&dir, &[]),
            ));
            assert_eq!(s3.http.tls.roots, TrustRoots::DangerousAcceptAnyChain);
        }

        /// A refusal that needs no file comes before the read of the shared
        /// files: a credentials file that cannot be read gives no error.
        #[test]
        fn a_refusal_comes_before_the_read_of_the_shared_files() {
            let dir = Dir::new();
            // A directory at the path of the credentials file cannot be read
            // as a file.
            let credentials = dir.absent("aws-credentials");
            std::fs::create_dir(&credentials).unwrap();
            let env = Environment::Variables(vec![(
                "AWS_SHARED_CREDENTIALS_FILE".into(),
                credentials.display().to_string(),
            )]);
            let o = EndpointOverrides {
                url: Some("s3://bkt/repo".into()),
                tls_client_cert_path: Some("/c".into()),
                ..EndpointOverrides::default()
            };
            assert_eq!(
                pull_error(pull_in(None, "r", o, &env)),
                "remote 'r': a client certificate needs both tls-client-cert-path and \
                 tls-client-key-path"
            );
            let o = EndpointOverrides {
                url: Some("s3://bkt/repo".into()),
                ..EndpointOverrides::default()
            };
            assert!(matches!(pull_in(None, "r", o, &env), Err(Error::Io(_))));
        }

        #[cfg(feature = "push")]
        fn push_in(
            repo: Option<&TestRepo>,
            remote: &str,
            o: EndpointOverrides,
            env: &Environment,
        ) -> Result<Endpoint> {
            ostrya_rt::block_on(resolve_push_in(handle(repo), remote, o, env))
        }

        #[cfg(feature = "push")]
        fn push_refused<T: fmt::Debug>(result: Result<T>) -> String {
            match result {
                Err(Error::Remote(remote::Error::InvalidInput(msg))) => msg,
                other => panic!("expected InvalidInput, got {other:?}"),
            }
        }

        /// `check_push` gives the kind of a push to an `s3://` address with
        /// no key pair and with the shared AWS files at absent paths. It
        /// gives the refusals of `resolve_push` that need no file.
        #[cfg(feature = "push")]
        #[test]
        fn check_push_reads_no_aws_file() {
            let dir = Dir::new();
            let no_keys = Environment::Variables(vec![
                (
                    "AWS_CONFIG_FILE".to_owned(),
                    dir.absent("aws-config").display().to_string(),
                ),
                (
                    "AWS_SHARED_CREDENTIALS_FILE".to_owned(),
                    dir.absent("aws-credentials").display().to_string(),
                ),
            ]);
            let config = config(S3_SECTIONS);
            let d = EndpointOverrides::default;
            assert!(push_in(Some(&config), "push", d(), &no_keys).is_err());
            assert_eq!(
                check_push(Some(config.config()), "push", d()).unwrap(),
                PushKind::Bucket
            );
            assert_eq!(
                check_push(None, "s3://bkt/x", d()).unwrap(),
                PushKind::Bucket
            );
            for o in [
                EndpointOverrides {
                    push_user: Some("u".into()),
                    ..d()
                },
                EndpointOverrides {
                    remote_command: Some("x".into()),
                    ..d()
                },
                EndpointOverrides {
                    s3_addressing: Some("other".into()),
                    ..d()
                },
                EndpointOverrides {
                    tls_client_cert_path: Some(dir.absent("cert.pem")),
                    ..d()
                },
            ] {
                let checked = check_push(Some(config.config()), "push", o.clone());
                let resolved = push_in(Some(&config), "push", o, &env(&dir, &[]));
                assert_eq!(push_refused(checked), push_refused(resolved));
            }
            // The resolution parses the address before it reads a file.
            for address in ["s3://Bad_Bucket/x", "s3://bkt/a//b"] {
                let checked = push_refused(check_push(None, address, d()));
                let resolved = push_refused(push_in(None, address, d(), &no_keys));
                assert!(checked.starts_with("S3 address: "), "{checked}");
                assert_eq!(checked, resolved);
            }
        }

        /// An `s3://` address and an `s3://` `push-url` give an S3 endpoint
        /// with the keys of the remote.
        #[cfg(feature = "push")]
        #[test]
        fn an_s3_push_address_gives_an_s3_endpoint() {
            let dir = Dir::new();
            let config = config(S3_SECTIONS);
            let s3 = s3_of(push_in(
                Some(&config),
                "push",
                EndpointOverrides::default(),
                &env(&dir, &[]),
            ));
            assert_eq!(
                s3.location.repository_url(),
                "https://bkt.s3.eu-west-1.amazonaws.com/repo"
            );
            assert_eq!(s3.credentials.access_key_id(), "AKIDEXAMPLE");
            assert_eq!(s3.http.max_retries, 5);
            assert_eq!(s3.http.max_outstanding, 8);
            let o = EndpointOverrides {
                s3_endpoint: Some("http://127.0.0.1:9000".into()),
                allow_cleartext_credentials: true,
                ..EndpointOverrides::default()
            };
            let s3 = s3_of(push_in(None, "s3://bkt/x", o, &env(&dir, &[])));
            assert_eq!(s3.location.repository_url(), "http://127.0.0.1:9000/bkt/x");
            assert!(s3.http.allow_cleartext_credentials);
        }

        /// A push to an `s3://` address refuses the token file and the user
        /// of an HTTP push, as fields and as keys, and the ssh fields.
        #[cfg(feature = "push")]
        #[test]
        fn an_s3_push_refuses_the_fields_of_another_transport() {
            let dir = Dir::new();
            let d = EndpointOverrides::default;
            for (name, o) in [
                (
                    "push-token-file",
                    EndpointOverrides {
                        push_token_file: Some("/t".into()),
                        ..d()
                    },
                ),
                (
                    "push-user",
                    EndpointOverrides {
                        push_user: Some("u".into()),
                        ..d()
                    },
                ),
            ] {
                assert_eq!(
                    push_refused(push_in(None, "s3://u-QXZ@bkt/r", o, &env(&dir, &[]))),
                    format!(
                        "{name} applies to an HTTP address, and 's3://bkt/r' is an s3:// \
                         address"
                    )
                );
            }
            for (key, name) in [
                ("push-token-file=/t", "push-token-file"),
                ("push-user=u", "push-user"),
            ] {
                let config = config(&format!("[remote \"r\"]\npush-url=s3://bkt/r\n{key}\n"));
                assert_eq!(
                    push_refused(push_in(Some(&config), "r", d(), &env(&dir, &[]))),
                    format!(
                        "{name} applies to an HTTP address, and 's3://bkt/r' is an s3:// \
                         address"
                    )
                );
            }
            for (name, o) in [
                (
                    "ssh-command",
                    EndpointOverrides {
                        ssh_command: Some(vec!["ssh".into()]),
                        ..d()
                    },
                ),
                (
                    "receive-command",
                    EndpointOverrides {
                        remote_command: Some("ostrya receive".into()),
                        ..d()
                    },
                ),
            ] {
                assert_eq!(
                    push_refused(push_in(None, "s3://bkt/r", o, &env(&dir, &[]))),
                    format!(
                        "{name} applies to an ssh address, and 's3://bkt/r' is an s3:// address"
                    )
                );
            }
            // The ssh keys of the section do not apply, and pass.
            let config = config(
                "[remote \"r\"]\npush-url=s3://bkt/r\nssh-command=ssh\n\
                 receive-command=x\nsend-command=y\n",
            );
            s3_of(push_in(Some(&config), "r", d(), &env(&dir, &[])));
        }

        /// A push refuses `tls-permissive=true` for an `s3://` address, and
        /// an `http://` endpoint with no cleartext permission.
        #[cfg(feature = "push")]
        #[test]
        fn an_s3_push_verifies_the_chain_and_refuses_cleartext() {
            let dir = Dir::new();
            let config =
                config("[remote \"permissive\"]\npush-url=s3://bkt/repo\ntls-permissive=true\n");
            assert_eq!(
                push_refused(push_in(
                    Some(&config),
                    "permissive",
                    EndpointOverrides::default(),
                    &env(&dir, &[])
                )),
                "remote 'permissive' sets tls-permissive=true, which a writer of a bucket \
                 repository refuses: the writer verifies the certificate chain of the server"
            );
            let env = env(&dir, &[("AWS_ENDPOINT_URL", "http://127.0.0.1:9000")]);
            assert!(
                push_refused(push_in(
                    None,
                    "s3://bkt/r",
                    EndpointOverrides::default(),
                    &env
                ))
                .contains("is http://, so the signature of each request would travel")
            );
            let o = EndpointOverrides {
                url: None,
                tls_client_cert_path: Some("/c".into()),
                ..EndpointOverrides::default()
            };
            assert_eq!(
                push_refused(push_in(None, "s3://bkt/r", o, &env)),
                "remote 's3://bkt/r': a client certificate needs both tls-client-cert-path \
                 and tls-client-key-path"
            );
        }

        /// A refusal of an `s3://` push address names the address without
        /// its userinfo.
        #[cfg(feature = "push")]
        #[test]
        fn a_refusal_of_an_s3_push_address_shows_no_userinfo() {
            let dir = Dir::new();
            let env = env(&dir, &[("AWS_ENDPOINT_URL", "http://127.0.0.1:9000")]);
            let o = EndpointOverrides {
                url: None,
                tls_client_cert_path: Some("/c".into()),
                ..EndpointOverrides::default()
            };
            let message = push_refused(push_in(None, "s3://AKID:SECRET@bkt/r", o, &env));
            assert!(!message.contains("AKID"), "{message}");
            assert!(!message.contains("SECRET"), "{message}");
            assert_eq!(
                message,
                "remote 's3://bkt/r': a client certificate needs both tls-client-cert-path \
                 and tls-client-key-path"
            );
        }

        fn bucket_in(
            repo: Option<&TestRepo>,
            value: &str,
            o: EndpointOverrides,
            env: &Environment,
        ) -> Result<S3Endpoint> {
            ostrya_rt::block_on(resolve_bucket_in(handle(repo), value, o, env))
        }

        fn bucket_refused(result: Result<S3Endpoint>) -> String {
            match result {
                Err(Error::Remote(remote::Error::InvalidInput(msg))) => msg,
                other => panic!("expected InvalidInput, got {other:?}"),
            }
        }

        /// A writer of a bucket repository takes an `s3://` address, else the
        /// `s3://` address of `push-url`, else that of `pull-url`, and never
        /// `url`.
        #[test]
        fn a_bucket_writer_takes_push_url_then_pull_url() {
            let dir = Dir::new();
            let config = config(
                "[remote \"both\"]\npull-url=s3://pull/a\npush-url=s3://push/b\n\n\
                 [remote \"pull\"]\nurl=https://ex.com/r\npull-url=s3://pull/a\n\
                 push-url=https://ex.com/p\ns3-region=eu-west-1\n\n\
                 [remote \"url\"]\nurl=s3://bkt/repo\n\n\
                 [remote \"http\"]\npull-url=https://ex.com/r\npush-url=ssh://h/r\n",
            );
            let d = EndpointOverrides::default;
            let url_of = |value: &str| {
                bucket_in(Some(&config), value, d(), &env(&dir, &[]))
                    .unwrap()
                    .location
                    .repository_url()
                    .to_owned()
            };
            assert_eq!(url_of("both"), "https://push.s3.us-east-1.amazonaws.com/b");
            assert_eq!(url_of("pull"), "https://pull.s3.eu-west-1.amazonaws.com/a");
            assert_eq!(
                url_of("s3://bkt/x"),
                "https://bkt.s3.us-east-1.amazonaws.com/x"
            );
            for (value, message) in [
                (
                    "url",
                    "remote 'url' holds no s3:// address in push-url or pull-url",
                ),
                (
                    "http",
                    "remote 'http' holds no s3:// address in push-url or pull-url",
                ),
                ("absent", "no remote 'absent' is configured"),
                (
                    "https://u:p@ex.com/r",
                    "'https://ex.com/r' is no s3:// address",
                ),
                ("h:/srv/r", "'h:/srv/r' is no s3:// address"),
            ] {
                assert_eq!(
                    bucket_refused(bucket_in(Some(&config), value, d(), &env(&dir, &[]))),
                    message
                );
            }
            let o = EndpointOverrides {
                url: Some("s3://bkt/x".into()),
                ..d()
            };
            assert_eq!(
                bucket_refused(bucket_in(None, "s3://bkt/x", o, &env(&dir, &[]))),
                "url applies to a pull, and this is a write to a bucket repository"
            );
        }

        /// A writer of a bucket repository makes the refusals of a push to an
        /// `s3://` address, and takes the S3 fields and the cleartext
        /// permission of the caller.
        #[test]
        fn a_bucket_writer_makes_the_refusals_of_a_push() {
            let dir = Dir::new();
            let d = EndpointOverrides::default;
            let config = config(
                "[remote \"token\"]\npush-url=s3://bkt/r\npush-token-file=/t\n\n\
                 [remote \"permissive\"]\npull-url=s3://bkt/r\ntls-permissive=true\n",
            );
            assert_eq!(
                bucket_refused(bucket_in(Some(&config), "token", d(), &env(&dir, &[]))),
                "push-token-file applies to an HTTP address, and 's3://bkt/r' is an s3:// \
                 address"
            );
            assert_eq!(
                bucket_refused(bucket_in(Some(&config), "permissive", d(), &env(&dir, &[]))),
                "remote 'permissive' sets tls-permissive=true, which a writer of a bucket \
                 repository refuses: the writer verifies the certificate chain of the server"
            );
            let o = EndpointOverrides {
                push_user: Some("u".into()),
                ..d()
            };
            assert_eq!(
                bucket_refused(bucket_in(None, "s3://bkt/r", o, &env(&dir, &[]))),
                "push-user applies to an HTTP address, and 's3://bkt/r' is an s3:// address"
            );
            let o = EndpointOverrides {
                ssh_command: Some(vec!["ssh".into()]),
                ..d()
            };
            assert_eq!(
                bucket_refused(bucket_in(None, "s3://bkt/r", o, &env(&dir, &[]))),
                "ssh-command applies to an ssh address, and 's3://bkt/r' is an s3:// address"
            );
            let o = EndpointOverrides {
                s3_endpoint: Some("http://127.0.0.1:9000".into()),
                ..d()
            };
            assert!(
                bucket_refused(bucket_in(None, "s3://bkt/r", o.clone(), &env(&dir, &[])))
                    .contains("is http://, so the signature of each request would travel")
            );
            let o = EndpointOverrides {
                allow_cleartext_credentials: true,
                s3_region: Some("eu-north-1".into()),
                ..o
            };
            let s3 = bucket_in(None, "s3://bkt/r", o, &env(&dir, &[])).unwrap();
            assert_eq!(s3.location.repository_url(), "http://127.0.0.1:9000/bkt/r");
            assert_eq!(s3.location.region(), "eu-north-1");
            assert!(s3.http.allow_cleartext_credentials);
        }

        /// The `Debug` output of the S3 endpoint shows no secret.
        #[test]
        fn the_s3_endpoint_shows_no_secret() {
            let dir = Dir::new();
            let o = EndpointOverrides {
                url: Some("s3://bkt/repo".into()),
                ..EndpointOverrides::default()
            };
            let endpoint = pull_in(None, "r", o, &env(&dir, &[])).unwrap();
            let text = format!("{endpoint:?}");
            assert!(!text.contains("QXZ"), "{text}");
            assert!(text.contains("AKIDEXAMPLE"), "{text}");
        }
    }
}