ostrya 0.19.1

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
//! The client groups and the server settings of a repository config.
//!
//! A client group, `[ex-ostrya client "NAME"]`, states how a client
//! authenticates, which refs it can read and change in each namespace, how
//! its commits are verified, and which keys sign them. `[ex-ostrya server]`
//! holds the settings of a server. [`ClientAccess::from_config`] reads both
//! kinds of group.
//!
//! - [`ClientAccess`] holds the groups and the server settings, and selects
//!   the group of an auth item.
//! - [`ClientGroup`] is one client group.
//! - [`AuthItem`] is one item of the `auth` list, and [`IpNet`] is the
//!   network of a `net:` item or of a `trusted-proxy` entry.
//! - [`AccessRules`] holds the allow items and the deny items of a group in
//!   one namespace, and gives the effective rights of a ref as
//!   [`AccessModes`]. [`NamespaceRules`] holds the rules of each namespace.
//! - [`ServerSettings`] holds the keys of `[ex-ostrya server]`.
//!   [`ServerFile`] is the path of a PEM file of a server, and
//!   [`ServerSettings::read_tls_files`] reads these files as
//!   [`ServerTlsFiles`].
//! - [`Claims`] holds the claims of a client certificate, and
//!   [`Claims::rules`] gives their rules for one namespace.
//! - [`ForwardedHeader`] is a value of `trusted-proxy-header`, and
//!   [`is_header_name`] checks a value of `trusted-proxy-client-cert`.
//! - [`ReadAccess`] holds the read rights of one identified client, which
//!   the archive view, the ref listing, and a pull session take.
//!
//! # Client group keys
//!
//! - `auth` (list, necessary) -- the [`AuthItem`]s of the group. An item
//!   that occurs two times in one group counts one time.
//! - `allow` (list) -- the [`AllowItem`]s, each `[MODES:]PATTERN` for the
//!   local refs or `[MODES:]@ID:PATTERN` for the collection `ID`. Without the
//!   key, the group has no right on a ref.
//! - `deny` (list) -- the deny items, each `PATTERN` for the local refs or
//!   `@ID:PATTERN` for the collection `ID`. `PATTERN` is a
//!   [`RefPattern`](crate::RefPattern).
//! - `tls-accept-claim` (boolean, default false) -- read the claims of the
//!   client certificate (see [Claims](#claims)). A group with no `tls:*`,
//!   `tls:NAME`, or `tls-sha256:HEX` item cannot hold this key, with any
//!   value.
//! - `verify` (`trust:NAME`) -- the trust group that verifies each
//!   client-built commit of the group.
//! - `allow-unsigned` (boolean) -- accept a client-built commit with no
//!   signature. The default is true without `verify`, and false with
//!   `verify`. `allow-unsigned=false` needs `verify`.
//! - `sign` (list) -- the key groups that sign each new commit of a ref
//!   update of the group. A name that occurs two times counts one time. An
//!   empty value is refused.
//! - `allow-privileged` (boolean, default false) -- accept the privileged
//!   file modes and extended attributes in a `bare` repository.
//! - `disable-verify-bindings` (boolean, default false) -- skip the check of
//!   `ostree.ref-binding` of each ref update and each tag of a push of the
//!   group. The check of `ostree.collection-binding` stays on. A pull without
//!   `--disable-verify-bindings` refuses a ref that a push writes with it,
//!   and `fsck --verify-bindings` reports the ref.
//! - `summary` (boolean, default false) -- give each auth item of the group a
//!   summary (see [Summaries](#summaries)). A group with
//!   `tls-accept-claim=true` cannot set `summary=true`.
//!
//! `ID` is a collection id. It passes
//! [`is_collection_id`](crate::is_collection_id) and is at most
//! [`MAX_COLLECTION_ID_LEN`](ostrya_core::MAX_COLLECTION_ID_LEN) bytes. The
//! text splits at the first `:` after the `@`. An item with `@ID:` of
//! `[core] collection-id` is an item of the local refs, so `@OWN:PATTERN` is
//! the same as `PATTERN`. [`NamespaceRules`] holds the items of each
//! namespace.
//!
//! [`config::client`](crate::config::client) holds the key types of a client
//! group. [`ServerSettings`] lists the keys of `[ex-ostrya server]`, and
//! [`config::server`](crate::config::server) holds their key types.
//!
//! # Checks
//!
//! [`ClientAccess::from_config`] refuses a group name that starts with
//! `ex-ostrya ` and has no shape of a known group, and a key that a client
//! group or the server group does not take. It reads each key of the server
//! group through its key type of [`config::server`](crate::config::server),
//! and each key of a client group through its key type of
//! [`config::client`](crate::config::client), with the errors of the key
//! type. It refuses `[ex-ostrya receive]`
//! and `[ex-ostrya receive "PATTERN"]` with a message that names
//! `[ex-ostrya client "NAME"]`. It refuses the key `collection` of a client
//! group with a message that names `@ID:PATTERN`. It also refuses the config
//! in these cases:
//!
//! - Two groups carry the same item.
//! - A value of `tls-cert`, `tls-key`, or `tls-client-ca` is a relative path
//!   with a `..` component.
//! - The collection id of an item fails the collection-id rule.
//! - A network has host bits set.
//! - A group sets `tls-accept-claim=true` and `summary=true`.
//! - `verify`, `sign`, or `sign-summary` names a trust group or a key group
//!   that does not exist.
//!
//! [`ServerSettings::overridden_by`] puts the values of the command line in
//! place of the keys that they replace, and [`ClientAccess::check_server`]
//! checks the result.
//!
//! # Claims
//!
//! A claim is a URI SAN of a client certificate that states an allow item or
//! a deny item. [`Claim`] lists the forms. With `tls-accept-claim=true`, a
//! server reads the claims of the certificate that gives the auth item of a
//! request:
//!
//! - A claim with no `@ID:` and a claim with `@ID:` of `[core] collection-id`
//!   name the local refs. A claim with another `@ID:` names the collection
//!   `ID`.
//! - When the certificate holds one or more claims for a namespace, they
//!   replace the allow items and the deny items of the group for that
//!   namespace.
//! - In a namespace for which the certificate holds no claim, the items of
//!   the group apply.
//!
//! The claims can give more rights than the group, so the client CA grants
//! the rights of each certificate that it signs. The other keys of the group
//! apply as they are.
//!
//! # Read access
//!
//! A client reads `refs/heads/NAME` and `refs/mirrors/ID/NAME` when the
//! group of its item has `r` on `NAME` in the namespace of the path. No
//! client reads a path under `refs/mirrors/` of the own collection id. An
//! alias needs `r` on its name and on its target. No client reads another
//! path under `refs/`. `summary` and `summary.sig` give the summary of the
//! item of the client (see [Summaries](#summaries)). [`ReadAccess`] states
//! the rules.
//!
//! # Summaries
//!
//! An auth item has a summary when its group has `summary=true`. Each other
//! item has no summary. The summary of an item holds the refs that the item
//! reads in each namespace.
//!
//! [`ClientAccess::summary_digest`] gives the access digest of an item: the
//! SHA-256 digest of a text that holds `[core] collection-id`, and the
//! allow items, the deny items, and the value of `summary` of the group of
//! the item in each namespace:
//!
//! ```text
//! collection-id=ID
//! namespace=NS
//! allow=ITEMS
//! deny=PATTERNS
//! summary=BOOL
//! ```
//!
//! - `ID` is `[core] collection-id`, or empty with no collection id.
//! - Each namespace adds the four lines `namespace=`, `allow=`, `deny=`, and
//!   `summary=`: the local refs, each collection with one or more items, and
//!   each other collection in the implicit group. The namespaces come in the
//!   byte-wise order of their `namespace=` lines.
//! - `NS` is empty for the local refs, the collection id for a collection,
//!   and `*` for each other collection of the implicit group.
//! - `ITEMS` is the allow items of the namespace in the form
//!   `MODES:PATTERN`, with no `@ID:`, and with the modes in the order
//!   `rwctd`. Each distinct item occurs one time. The items are sorted
//!   byte-wise and joined by `;`.
//! - `PATTERNS` is the deny patterns, in the same way.
//! - `BOOL` is `true` or `false`, the value of `summary`.
//! - Each line ends with a newline.
//!
//! The digest changes when a change to the config can change the refs of
//! the summary. The group name is not in the text, so a new group name keeps
//! the digest.
//!
//! # Implicit group
//!
//! A config with no client group has one implicit group, `anonymous`. It
//! carries the item `anonymous`, has `summary=true`, and gives `r` on each
//! local ref and on each ref of each collection. No `allow` value names each
//! collection, so a client group cannot state the rights of the implicit
//! group.
//!
//! # Examples
//!
//! ```
//! use ostrya::config::RepoConfig;
//! use ostrya::access::{AccessModes, AuthItem, ClientAccess, Namespace};
//!
//! let config = RepoConfig::parse(
//!     "[core]\nrepo_version=1\nmode=archive-z2\n\
//!      [ex-ostrya client \"developer\"]\nauth=ssh:user\nallow=cd:devel/user/**\n",
//! )?;
//! let access = ClientAccess::from_config(&config)?;
//! let item = AuthItem::parse("ssh:user")?;
//! let group = access.select(&item).unwrap();
//! assert_eq!(group.name(), "developer");
//! let rights = group.rules().rights(&Namespace::Local, "devel/user/main");
//! assert!(rights.contains(AccessModes::COMMIT));
//! assert!(rights.contains(AccessModes::READ));
//! # Ok::<(), ostrya::Error>(())
//! ```

mod claim;
mod item;
mod read;
mod reader;
mod rights;

use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::net::SocketAddr;
use std::path::PathBuf;

pub use claim::{Claim, ClaimError, ClaimRule, Claims, MAX_CLAIMS};
pub use item::{AuthItem, IpNet};
pub(crate) use item::{parse_item, parse_net};
pub use read::ReadAccess;
pub(crate) use read::reads;
#[cfg(feature = "receive")]
pub(crate) use reader::{Group, classify};
pub use rights::{AccessModes, AccessRules, AllowItem, NamespaceRules};
pub(crate) use rights::{parse_allow_item, parse_deny_item};

use ostrya_core::Checksum;
use ostrya_core::config::relative_with_parent;

use crate::config::{KeyOrigin, KeyPath, RepoConfig};
use crate::endpoint::{caller_path, read_pem_file};
use crate::error::{Error, Result};
use crate::repo::Repo;

/// The namespace of a request: the local refs or the refs of one
/// collection.
///
/// [`Namespace::of`] and [`ClientAccess::namespace`] map a collection id to
/// a namespace.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Namespace {
    /// The local refs, under `refs/heads/`.
    Local,
    /// The refs of one collection, under `refs/mirrors/ID/`.
    Collection(String),
}

impl Namespace {
    /// Returns the namespace of the collection id `collection` in a
    /// repository whose own collection id is `own`.
    ///
    /// `None` and `own` give [`Local`](Namespace::Local). Each other id gives
    /// [`Collection`](Namespace::Collection).
    pub fn of(collection: Option<&str>, own: Option<&str>) -> Namespace {
        match collection {
            Some(id) if Some(id) != own => Namespace::Collection(id.to_owned()),
            _ => Namespace::Local,
        }
    }
}

/// One client group, `[ex-ostrya client "NAME"]`.
///
/// [`ClientAccess::from_config`] builds each group. The module doc lists the
/// keys of a group.
#[derive(Debug, Clone)]
pub struct ClientGroup {
    name: String,
    auth: Vec<AuthItem>,
    rules: NamespaceRules,
    tls_accept_claim: bool,
    verify_trust: Option<String>,
    allow_unsigned: bool,
    sign: Vec<String>,
    allow_privileged: bool,
    disable_verify_bindings: bool,
    summary: bool,
    implicit: bool,
}

impl ClientGroup {
    /// Returns the name of the group, the quoted part of its group name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the auth items of the group, in the order of the config, each
    /// one time.
    pub fn auth(&self) -> &[AuthItem] {
        &self.auth
    }

    /// Returns the allow items and the deny items of the group, for each
    /// namespace.
    pub fn rules(&self) -> &NamespaceRules {
        &self.rules
    }

    /// Returns the value of `tls-accept-claim`: `true` if the claims of a
    /// client certificate replace the rules of the group.
    ///
    /// The [module doc](crate::access#claims) states the rule.
    pub fn tls_accept_claim(&self) -> bool {
        self.tls_accept_claim
    }

    /// Returns the name of the trust group of `verify`, or `None` with no
    /// `verify` key.
    pub fn verify_trust(&self) -> Option<&str> {
        self.verify_trust.as_deref()
    }

    /// Returns the value of `allow-unsigned`, or its default.
    ///
    /// The default is `true` without `verify`, and `false` with `verify`.
    pub fn allow_unsigned(&self) -> bool {
        self.allow_unsigned
    }

    /// Returns the names of the key groups of `sign`, each one time.
    pub fn sign(&self) -> &[String] {
        &self.sign
    }

    /// Returns the value of `allow-privileged`.
    pub fn allow_privileged(&self) -> bool {
        self.allow_privileged
    }

    /// Returns the value of `disable-verify-bindings`: `true` if a push of
    /// the group skips the check of `ostree.ref-binding`.
    pub fn disable_verify_bindings(&self) -> bool {
        self.disable_verify_bindings
    }

    /// Returns the value of `summary`: `true` if the namespace of the group
    /// is in the summary of each auth item of the group.
    ///
    /// The [module doc](crate::access#summaries) states the rule.
    pub fn summary(&self) -> bool {
        self.summary
    }

    /// Returns `true` for the group that a config with no client group has.
    pub fn is_implicit(&self) -> bool {
        self.implicit
    }

    /// Returns the group name of the group, for the error messages.
    fn header(&self) -> String {
        format!("[ex-ostrya client \"{}\"]", self.name)
    }
}

/// The request header from which a server reads the client address of a
/// request from a trusted proxy: a value of `trusted-proxy-header`.
///
/// The text form is the lowercase name of the header. [`parse`](Self::parse)
/// takes that form alone.
///
/// # Examples
///
/// ```
/// use ostrya::access::ForwardedHeader;
///
/// let header = ForwardedHeader::parse("x-forwarded-for")?;
/// assert_eq!(header, ForwardedHeader::XForwardedFor);
/// assert_eq!(header.to_string(), "x-forwarded-for");
/// assert!(ForwardedHeader::parse("X-Forwarded-For").is_err());
/// # Ok::<(), ostrya::Error>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ForwardedHeader {
    /// `forwarded`: the `Forwarded` header of RFC 7239.
    Forwarded,
    /// `x-forwarded-for`: the `X-Forwarded-For` header.
    XForwardedFor,
    /// `x-real-ip`: the `X-Real-IP` header.
    XRealIp,
}

impl ForwardedHeader {
    /// Parses a value of `trusted-proxy-header`: `forwarded`,
    /// `x-forwarded-for`, or `x-real-ip`.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] for each other text, also for a name in
    /// another case.
    pub fn parse(text: &str) -> Result<ForwardedHeader> {
        match text {
            "forwarded" => Ok(ForwardedHeader::Forwarded),
            "x-forwarded-for" => Ok(ForwardedHeader::XForwardedFor),
            "x-real-ip" => Ok(ForwardedHeader::XRealIp),
            _ => Err(Error::InvalidFormat(format!(
                "malformed trusted-proxy-header value '{text}': the value is forwarded, \
                 x-forwarded-for, or x-real-ip"
            ))),
        }
    }

    /// Returns the text form: the lowercase name of the header.
    pub fn as_str(self) -> &'static str {
        match self {
            ForwardedHeader::Forwarded => "forwarded",
            ForwardedHeader::XForwardedFor => "x-forwarded-for",
            ForwardedHeader::XRealIp => "x-real-ip",
        }
    }
}

impl fmt::Display for ForwardedHeader {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Returns `true` if `name` is a name of an HTTP header: a token of HTTP, one
/// or more of the ASCII letters, the digits, and the characters
/// ``!#$%&'*+-.^_`|~``.
///
/// A value of `trusted-proxy-client-cert` must pass this check.
///
/// # Examples
///
/// ```
/// use ostrya::access::is_header_name;
///
/// assert!(is_header_name("X-SSL-Client-Cert"));
/// assert!(!is_header_name("X Client"));
/// assert!(!is_header_name(""));
/// ```
pub fn is_header_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b))
}

/// The path of a PEM file of a server: a value of `tls-cert`, `tls-key`, or
/// `tls-client-ca`, or the path of a caller for one of these keys.
///
/// The source of the path sets the base of a relative path.
/// [`ServerSettings::read_tls_files`] reads the file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ServerFile {
    /// A value of `[ex-ostrya server]` in the repository config. The path is
    /// absolute, or relative to the repository root.
    /// [`ClientAccess::from_config`] gives each value of a key in this form,
    /// and refuses a relative value with a `..` component.
    Config(PathBuf),
    /// A path of the caller, for example the value of a command-line option.
    /// The path is absolute, or relative to the working directory.
    /// [`ServerSettings::read_tls_files`] refuses a relative path with a `..`
    /// component.
    Caller(PathBuf),
}

/// The content of the PEM files of [`ServerSettings`], as
/// [`ServerSettings::read_tls_files`] gives it.
///
/// Each field is `None` when its field of [`ServerSettings`] is `None`. The
/// `Debug` output gives the size of the key and no byte of it.
#[derive(Clone, Default)]
pub struct ServerTlsFiles {
    /// The bytes of the file of `tls-cert`: the PEM certificate chain.
    pub cert: Option<Vec<u8>>,
    /// The bytes of the file of `tls-key`: the PEM private key.
    pub key: Option<Vec<u8>>,
    /// The bytes of the file of `tls-client-ca`: the PEM CA certificates.
    pub client_ca: Option<Vec<u8>>,
}

impl fmt::Debug for ServerTlsFiles {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ServerTlsFiles")
            .field("cert", &self.cert)
            .field(
                "key",
                &self
                    .key
                    .as_ref()
                    .map(|key| format!("<{} bytes redacted>", key.len())),
            )
            .field("client_ca", &self.client_ca)
            .finish()
    }
}

/// The keys of `[ex-ostrya server]`.
///
/// [`config::server`](crate::config::server) holds the key type of each
/// field, which states the parse of the value. Each field is `None` when the
/// key is absent. The server takes its default for an absent key. A caller
/// can build the struct with `..Default::default()`.
///
/// `tls_cert`, `tls_key`, and `tls_client_ca` name PEM files as
/// [`ServerFile`] values. [`ClientAccess::from_config`] reads no file, and
/// [`read_tls_files`](ServerSettings::read_tls_files) reads the files.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ServerSettings {
    /// `listen`: the addresses to listen on, each `ADDR:PORT`. A host name is
    /// refused, and so is an empty value.
    pub listen: Option<Vec<SocketAddr>>,
    /// `tls-cert`: the PEM certificate chain.
    pub tls_cert: Option<ServerFile>,
    /// `tls-key`: the PEM private key of `tls-cert`.
    pub tls_key: Option<ServerFile>,
    /// `tls-client-ca`: the PEM CA certificates that verify a client
    /// certificate. A server with no `tls-cert` and no
    /// `trusted-proxy-client-cert` ignores the key (see
    /// [`overridden_by`](ServerSettings::overridden_by)).
    pub tls_client_ca: Option<ServerFile>,
    /// `trusted-proxy`: the networks of the peers whose forwarding data the
    /// server reads. An empty value is refused.
    pub trusted_proxy: Option<Vec<IpNet>>,
    /// `trusted-proxy-header`: the request header from which the server reads
    /// the client address of a request from a trusted proxy.
    pub trusted_proxy_header: Option<ForwardedHeader>,
    /// `trusted-proxy-client-cert`: the name of the request header that
    /// carries the client certificate from a trusted proxy. The name passes
    /// [`is_header_name`].
    pub trusted_proxy_client_cert: Option<String>,
    /// `proxy-protocol`: each connection starts with a PROXY protocol header.
    pub proxy_protocol: Option<bool>,
    /// `allow-cleartext-credentials`: take a credential on a connection with
    /// no TLS.
    pub allow_cleartext_credentials: Option<bool>,
    /// `session-timeout`: the idle time of a push session, in seconds, 1 or
    /// more.
    pub session_timeout: Option<u64>,
    /// `max-sessions`: the number of push sessions at the same time, 1 or
    /// more.
    pub max_sessions: Option<u64>,
    /// `parallel-uploads`: the number of object streams of a push session,
    /// 1 to 31.
    pub parallel_uploads: Option<u32>,
    /// `body-timeout`: the time that a response waits for the client, in
    /// seconds, 1 or more.
    pub body_timeout: Option<u64>,
    /// `sign-summary`: the key groups that sign a summary that a push writes
    /// again, or that a command writes again under
    /// `[core] auto-update-summary` through
    /// [`Repo::regenerate_summaries_if_configured`](crate::Repo::regenerate_summaries_if_configured),
    /// each one time. An empty value is refused.
    pub sign_summary: Option<Vec<String>>,
}

impl ServerSettings {
    /// Returns the settings with each field of `flags` that is set in place
    /// of the field of `self`.
    ///
    /// A server takes the keys of `[ex-ostrya server]` as `self` and the
    /// values of its command line as `flags`. A field that is `None` in
    /// `flags` keeps the value of `self`. A list in `flags` replaces the
    /// whole list of `self`.
    ///
    /// When the result has no `tls_cert` and no `trusted_proxy_client_cert`,
    /// it has no `tls_client_ca` from `self`. Thus a plain HTTP server ignores
    /// the `tls-client-ca` key, and can share the config of an HTTPS server.
    /// A `tls_client_ca` in `flags` stays.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::access::ServerSettings;
    ///
    /// let keys = ServerSettings {
    ///     listen: Some(vec!["0.0.0.0:80".parse()?, "[::]:80".parse()?]),
    ///     max_sessions: Some(8),
    ///     ..ServerSettings::default()
    /// };
    /// let flags = ServerSettings {
    ///     listen: Some(vec!["127.0.0.1:8080".parse()?]),
    ///     ..ServerSettings::default()
    /// };
    /// let merged = keys.overridden_by(&flags);
    /// assert_eq!(merged.listen, flags.listen);
    /// assert_eq!(merged.max_sessions, Some(8));
    /// # Ok::<(), std::net::AddrParseError>(())
    /// ```
    pub fn overridden_by(&self, flags: &ServerSettings) -> ServerSettings {
        fn pick<T: Clone>(flag: &Option<T>, key: &Option<T>) -> Option<T> {
            flag.as_ref().or(key.as_ref()).cloned()
        }
        // The pattern names each field, so a new field does not compile
        // until it is merged here.
        let ServerSettings {
            listen,
            tls_cert,
            tls_key,
            tls_client_ca,
            trusted_proxy,
            trusted_proxy_header,
            trusted_proxy_client_cert,
            proxy_protocol,
            allow_cleartext_credentials,
            session_timeout,
            max_sessions,
            parallel_uploads,
            body_timeout,
            sign_summary,
        } = flags;
        let mut merged = ServerSettings {
            listen: pick(listen, &self.listen),
            tls_cert: pick(tls_cert, &self.tls_cert),
            tls_key: pick(tls_key, &self.tls_key),
            tls_client_ca: pick(tls_client_ca, &self.tls_client_ca),
            trusted_proxy: pick(trusted_proxy, &self.trusted_proxy),
            trusted_proxy_header: pick(trusted_proxy_header, &self.trusted_proxy_header),
            trusted_proxy_client_cert: pick(
                trusted_proxy_client_cert,
                &self.trusted_proxy_client_cert,
            ),
            proxy_protocol: pick(proxy_protocol, &self.proxy_protocol),
            allow_cleartext_credentials: pick(
                allow_cleartext_credentials,
                &self.allow_cleartext_credentials,
            ),
            session_timeout: pick(session_timeout, &self.session_timeout),
            max_sessions: pick(max_sessions, &self.max_sessions),
            parallel_uploads: pick(parallel_uploads, &self.parallel_uploads),
            body_timeout: pick(body_timeout, &self.body_timeout),
            sign_summary: pick(sign_summary, &self.sign_summary),
        };
        if tls_client_ca.is_none()
            && merged.tls_cert.is_none()
            && merged.trusted_proxy_client_cert.is_none()
        {
            merged.tls_client_ca = None;
        }
        merged
    }

    /// Reads the PEM files of `tls_cert`, `tls_key`, and `tls_client_ca`.
    ///
    /// The call first checks the path of each field that is set. If a check
    /// fails, the call opens no file and starts no job. It then reads each
    /// field that is set, in the order `tls_cert`, `tls_key`, and
    /// `tls_client_ca`, in one job on the blocking pool. It reads one file at
    /// a time, and the first error stops the read. It opens no file for a
    /// field that is `None`, and starts no job if no field is set.
    ///
    /// A [`ServerFile::Config`] path resolves against the root of `repo`, and
    /// a [`ServerFile::Caller`] path against the working directory. The read
    /// follows a symlink at each component of the path, also to a path
    /// outside the repository. It opens the file with `O_NONBLOCK`, and then
    /// refuses each file that is not a regular file, so a FIFO, a device, a
    /// socket, or a directory at the path fails the read. It reads at most
    /// 1 MiB and one byte of a file, and does not check the PEM syntax.
    ///
    /// # Errors
    ///
    /// No message holds a byte of a file.
    ///
    /// - [`Error::InvalidInput`] if a [`ServerFile::Caller`] path is relative
    ///   and has a `..` component. The message names the key, `tls-cert`,
    ///   `tls-key`, or `tls-client-ca`, and the path.
    /// - [`Error::InvalidFormat`] if a [`ServerFile::Config`] path is
    ///   relative and has a `..` component. The message names the group
    ///   `[ex-ostrya server]`, the key, and the path, as
    ///   [`ClientAccess::from_config`] does.
    /// - [`Error::Io`] if a file cannot be opened or read. The message names
    ///   the key and the path. An absent file gives the kind
    ///   [`NotFound`](std::io::ErrorKind::NotFound).
    /// - [`Error::InvalidInput`] if a file is not a regular file, or is
    ///   larger than 1 MiB. The message names the key and the path.
    pub async fn read_tls_files(&self, repo: &Repo) -> Result<ServerTlsFiles> {
        let [cert, key, client_ca] = [
            tls_path("tls-cert", &self.tls_cert)?,
            tls_path("tls-key", &self.tls_key)?,
            tls_path("tls-client-ca", &self.tls_client_ca)?,
        ];
        if cert.is_none() && key.is_none() && client_ca.is_none() {
            return Ok(ServerTlsFiles::default());
        }
        let repo = repo.clone();
        ostrya_rt::unblock(move || {
            let read = |key: &str, path: Option<KeyPath>| -> Result<Option<Vec<u8>>> {
                path.map(|path| read_pem_file(key, &path, Some(&repo)))
                    .transpose()
            };
            Ok(ServerTlsFiles {
                cert: read("tls-cert", cert)?,
                key: read("tls-key", key)?,
                client_ca: read("tls-client-ca", client_ca)?,
            })
        })
        .await
    }
}

/// Returns `file`, the path of the key `key`, as a [`KeyPath`]. The call
/// opens no file.
///
/// # Errors
///
/// - [`Error::InvalidInput`] if a [`ServerFile::Caller`] path is relative
///   and has a `..` component.
/// - [`Error::InvalidFormat`] if a [`ServerFile::Config`] path is relative
///   and has a `..` component.
fn tls_path(key: &str, file: &Option<ServerFile>) -> Result<Option<KeyPath>> {
    match file {
        None => Ok(None),
        Some(ServerFile::Config(value)) if relative_with_parent(value) => {
            Err(reader::parent_component(reader::SERVER_GROUP, key, value))
        }
        Some(ServerFile::Config(value)) => Ok(Some(KeyPath {
            value: value.clone(),
            origin: KeyOrigin::Config,
        })),
        Some(ServerFile::Caller(value)) => caller_path(key, Some(value.clone())),
    }
}

/// The client groups and the server settings of a repository config.
///
/// [`from_config`](ClientAccess::from_config) builds the value. The module
/// doc lists the keys and the checks.
#[derive(Debug, Clone)]
pub struct ClientAccess {
    collection_id: Option<String>,
    server: ServerSettings,
    groups: Vec<ClientGroup>,
    /// The indexes in `groups` of the groups that carry each item, in the
    /// order of the config.
    by_item: HashMap<AuthItem, Vec<usize>>,
    /// The summary files of each item that has a summary.
    summaries: HashMap<AuthItem, SummaryFiles>,
}

/// The access digest of one auth item with a summary, and the stem of the
/// names of its files under `extensions/ostrya/summary/`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SummaryFiles {
    /// The access digest of the item.
    pub(crate) digest: Checksum,
    /// `HEX`: the SHA-256 digest of the text of the item, in 64 lowercase
    /// hex digits.
    pub(crate) stem: String,
}

impl ClientAccess {
    /// Reads `[ex-ostrya server]` and each `[ex-ostrya client "NAME"]` of
    /// `config`.
    ///
    /// The call reads each key of `[ex-ostrya server]` through its key type
    /// of [`config::server`](crate::config::server), after the check that
    /// the group holds no other key. It reads each key of a client group
    /// through its key type of [`config::client`](crate::config::client),
    /// after the checks that the group holds no key `collection` and no
    /// other key that the group does not take. It gives a value of `tls-cert`,
    /// `tls-key`, or `tls-client-ca` as a [`ServerFile::Config`] path, and
    /// reads no file. It records the names of the `[ex-ostrya trust "NAME"]`
    /// and `[ex-ostrya key "NAME"]` groups, for the checks of `verify`,
    /// `sign`, and `sign-summary`, and reads no key of these groups.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if a group, a key, or a value is malformed,
    ///   or if a check of the module doc fails. The message names the group
    ///   and the key.
    /// - [`Error::Core`] if a boolean or an integer value does not parse, or
    ///   if a value holds a malformed escape sequence.
    pub fn from_config(config: &RepoConfig) -> Result<ClientAccess> {
        reader::read(config)
    }

    /// Returns the implicit group of a config with no client group, with the
    /// own collection id `collection_id` and the default server settings.
    ///
    /// The value is the value that
    /// [`from_config`](ClientAccess::from_config) gives for a config with no
    /// client group, no `[ex-ostrya server]`, and `[core] collection-id` set
    /// to `collection_id`. The call checks no value.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::access::{AuthItem, ClientAccess, Namespace};
    ///
    /// let access = ClientAccess::implicit(Some("com.example.own"));
    /// assert!(!access.has_client_groups());
    /// let own = access.namespace(Some("com.example.own"));
    /// assert_eq!(own, Namespace::Local);
    /// let group = access.select(&AuthItem::Anonymous).unwrap();
    /// assert_eq!(group.name(), "anonymous");
    /// ```
    pub fn implicit(collection_id: Option<&str>) -> ClientAccess {
        let groups = reader::implicit_groups();
        let by_item = reader::index(&groups);
        let summaries = reader::summary_digests(&groups, &by_item, collection_id);
        ClientAccess {
            collection_id: collection_id.map(str::to_owned),
            server: ServerSettings::default(),
            groups,
            by_item,
            summaries,
        }
    }

    /// Returns the keys of `[ex-ostrya server]`.
    pub fn server(&self) -> &ServerSettings {
        &self.server
    }

    /// Returns the client groups, in the order of the config, or the implicit
    /// group.
    pub fn groups(&self) -> &[ClientGroup] {
        &self.groups
    }

    /// Returns each group that carries `item`, in the order of the config.
    pub fn groups_of<'a>(&'a self, item: &'a AuthItem) -> impl Iterator<Item = &'a ClientGroup> {
        self.carriers(item).iter().map(|&i| &self.groups[i])
    }

    /// Returns the indexes in `groups` of the groups that carry `item`, in
    /// the order of the config.
    fn carriers(&self, item: &AuthItem) -> &[usize] {
        self.by_item.get(item).map_or(&[], Vec::as_slice)
    }

    /// Returns the access digest of `item`, or `None` if `item` has no
    /// summary.
    ///
    /// An item has a summary when its group has `summary=true`. The digest
    /// covers `[core] collection-id`, and the allow items, the deny items,
    /// and the value of `summary` of the group of the item in each
    /// namespace. The
    /// [module doc](crate::access#summaries) states the text.
    /// The value computes the digests one time, when it reads the config.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::RepoConfig;
    /// use ostrya::access::{AuthItem, ClientAccess};
    ///
    /// let config = RepoConfig::parse(
    ///     "[core]\nrepo_version=1\nmode=archive-z2\n\
    ///      [ex-ostrya client \"public\"]\nauth=anonymous\nallow=r:pub/**\nsummary=true\n\
    ///      [ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=r:**\n",
    /// )?;
    /// let access = ClientAccess::from_config(&config)?;
    /// assert!(access.summary_digest(&AuthItem::Anonymous).is_some());
    /// assert!(access.summary_digest(&AuthItem::parse("ssh:ci")?).is_none());
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub fn summary_digest(&self, item: &AuthItem) -> Option<Checksum> {
        self.summaries.get(item).map(|files| files.digest)
    }

    /// Returns the access digest of `item` and the stem of the names of its
    /// files, or `None` if `item` has no summary.
    pub(crate) fn summary_files(&self, item: &AuthItem) -> Option<&SummaryFiles> {
        self.summaries.get(item)
    }

    /// Returns the namespace of the collection id `collection`.
    ///
    /// `None` and the own collection id of the repository give
    /// [`Local`](Namespace::Local). Each other id gives
    /// [`Collection`](Namespace::Collection), also an id that fails the
    /// collection-id rule.
    pub fn namespace(&self, collection: Option<&str>) -> Namespace {
        Namespace::of(collection, self.collection_id.as_deref())
    }

    /// Returns the group that carries `item`, or `None`.
    ///
    /// The config has at most one group for each item. The selection
    /// compares `item` alone, so a `tls:NAME` item never selects a group of
    /// `tls:*`.
    pub fn select(&self, item: &AuthItem) -> Option<&ClientGroup> {
        self.select_index(item).map(|i| &self.groups[i])
    }

    /// Returns the index in `groups` of the group that
    /// [`select`](ClientAccess::select) returns.
    pub(crate) fn select_index(&self, item: &AuthItem) -> Option<usize> {
        self.carriers(item).first().copied()
    }

    /// Returns the rules of the claims of `claims` for `namespace`, or `None`
    /// if no claim names `namespace`.
    ///
    /// A claim of the collection `[core] collection-id` names the
    /// [`Local`](Namespace::Local) namespace. A
    /// [`Collection`](Namespace::Collection) of that id is the
    /// [`Local`](Namespace::Local) namespace too, as in
    /// [`namespace`](ClientAccess::namespace). The allow items and the deny
    /// items keep the order of `claims`. With `Some`, the rules replace the
    /// rules of a group with `tls-accept-claim=true`. The [module
    /// doc](crate::access#claims) states the rule.
    ///
    /// The call gives the rules of [`Claims::rules`], with
    /// `[core] collection-id` as the own collection id.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::RepoConfig;
    /// use ostrya::access::{AccessModes, Claims, ClientAccess, Namespace};
    ///
    /// let config = RepoConfig::parse(
    ///     "[core]\nrepo_version=1\nmode=archive-z2\ncollection-id=com.example.own\n",
    /// )?;
    /// let access = ClientAccess::from_config(&config)?;
    /// let claims = Claims::parse([
    ///     "ostrya:ref:w:main",
    ///     "ostrya:ref:!@com.example.own:secret",
    ///     "ostrya:ref:r:@com.example.os:os/**",
    /// ])
    /// .unwrap();
    /// let local = access.claim_rules(&claims, &Namespace::Local).unwrap();
    /// assert!(local.rights("main").contains(AccessModes::WRITE));
    /// assert_eq!(local.deny.len(), 1);
    /// let own = Namespace::Collection("com.example.own".into());
    /// assert_eq!(access.claim_rules(&claims, &own), Some(local));
    /// let other = Namespace::Collection("org.example.other".into());
    /// assert!(access.claim_rules(&claims, &other).is_none());
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub fn claim_rules(&self, claims: &Claims, namespace: &Namespace) -> Option<AccessRules> {
        claims.rules(namespace, self.collection_id.as_deref())
    }

    /// Returns the rules of `group`, with the claims of `claims`.
    ///
    /// When the group has `tls-accept-claim=true` and `claims` holds one or
    /// more claims, the result is owned. It holds the rules of the group, and
    /// the rules of the claims of each namespace for which `claims` holds a
    /// claim, as [`claim_rules`](ClientAccess::claim_rules) gives them, in
    /// place of the rules of the group for that namespace. Else the result is
    /// the rules of the group, borrowed. The [module
    /// doc](crate::access#claims) states the rule.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::borrow::Cow;
    ///
    /// use ostrya::config::RepoConfig;
    /// use ostrya::access::{AccessModes, AuthItem, Claims, ClientAccess, Namespace};
    ///
    /// let config = RepoConfig::parse(
    ///     "[core]\nrepo_version=1\nmode=archive-z2\n\
    ///      [ex-ostrya client \"certs\"]\nauth=tls:*\ntls-accept-claim=true\n\
    ///      allow=r:**;r:@com.example.os:**\n",
    /// )?;
    /// let access = ClientAccess::from_config(&config)?;
    /// let group = access.select(&AuthItem::TlsAny).unwrap();
    /// let claims = Claims::parse(["ostrya:ref:w:main"]).unwrap();
    /// let rules = access.effective_rules(group, Some(&claims));
    /// assert!(matches!(rules, Cow::Owned(_)));
    /// assert!(rules.rights(&Namespace::Local, "main").contains(AccessModes::WRITE));
    /// assert!(rules.rights(&Namespace::Local, "other").is_empty());
    /// let os = Namespace::Collection("com.example.os".into());
    /// assert_eq!(rules.rights(&os, "os/stable"), AccessModes::READ);
    /// let rules = access.effective_rules(group, None);
    /// assert!(matches!(rules, Cow::Borrowed(_)));
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub fn effective_rules<'g>(
        &self,
        group: &'g ClientGroup,
        claims: Option<&Claims>,
    ) -> Cow<'g, NamespaceRules> {
        let claims = match claims {
            Some(claims) if group.tls_accept_claim && !claims.is_empty() => claims,
            _ => return Cow::Borrowed(&group.rules),
        };
        let mut local: Option<AccessRules> = None;
        let mut collections: BTreeMap<String, AccessRules> = BTreeMap::new();
        for claim in claims.as_slice() {
            let claimed = match &claim.namespace {
                Namespace::Collection(id) if !self.is_own_collection(id) => {
                    collections.entry(id.clone()).or_default()
                }
                _ => local.get_or_insert_default(),
            };
            match &claim.rule {
                ClaimRule::Allow(item) => claimed.allow.push(item.clone()),
                ClaimRule::Deny(pattern) => claimed.deny.push(pattern.clone()),
            }
        }
        for (id, rules) in &group.rules.collections {
            if !collections.contains_key(id) {
                collections.insert(id.clone(), rules.clone());
            }
        }
        Cow::Owned(NamespaceRules {
            local: local.unwrap_or_else(|| group.rules.local.clone()),
            collections,
            other: group.rules.other.clone(),
        })
    }

    /// Returns `true` if the config has one or more client groups, and
    /// `false` if it has the implicit group.
    pub fn has_client_groups(&self) -> bool {
        !self.groups.iter().all(ClientGroup::is_implicit)
    }

    /// Returns `true` if `id` is `[core] collection-id`.
    fn is_own_collection(&self, id: &str) -> bool {
        Some(id) == self.collection_id.as_deref()
    }

    /// Returns each auth item of the groups one time, in the order of its
    /// first group in the config.
    pub fn items(&self) -> impl Iterator<Item = &AuthItem> {
        self.groups.iter().enumerate().flat_map(move |(i, group)| {
            group
                .auth
                .iter()
                .filter(move |item| self.carriers(item).first() == Some(&i))
        })
    }

    /// Checks the server settings that a server runs with.
    ///
    /// `merged` holds the keys of `[ex-ostrya server]`, with the values of
    /// the command line in place of the keys that they replace. The call
    /// refuses these cases:
    ///
    /// - `trusted_proxy_client_cert` is set, and `tls_client_ca` is `None`.
    /// - `trusted_proxy_client_cert` is set, and `trusted_proxy` is `None`.
    /// - `trusted_proxy` is set, and `trusted_proxy_header` is `None`.
    /// - `trusted_proxy_header` is set, and `trusted_proxy` is `None`.
    /// - `tls_cert` is set and `tls_key` is `None`, or the reverse.
    /// - `tls_client_ca` is set, and `tls_cert` and
    ///   `trusted_proxy_client_cert` are `None`.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] for each case above.
    pub fn check_server(&self, merged: &ServerSettings) -> Result<()> {
        if merged.tls_client_ca.is_none() && merged.trusted_proxy_client_cert.is_some() {
            return Err(Error::InvalidFormat(
                "trusted-proxy-client-cert is set, and the server has no tls-client-ca".to_owned(),
            ));
        }
        if merged.trusted_proxy_client_cert.is_some() && merged.trusted_proxy.is_none() {
            return Err(Error::InvalidFormat(
                "trusted-proxy-client-cert is set, and the server has no trusted-proxy".to_owned(),
            ));
        }
        match (&merged.trusted_proxy, &merged.trusted_proxy_header) {
            (Some(_), None) => {
                return Err(Error::InvalidFormat(
                    "trusted-proxy is set, and the server has no trusted-proxy-header".to_owned(),
                ));
            }
            (None, Some(_)) => {
                return Err(Error::InvalidFormat(
                    "trusted-proxy-header is set, and the server has no trusted-proxy".to_owned(),
                ));
            }
            _ => {}
        }
        match (&merged.tls_cert, &merged.tls_key) {
            (Some(_), None) => {
                return Err(Error::InvalidFormat(
                    "tls-cert is set, and tls-key is not".to_owned(),
                ));
            }
            (None, Some(_)) => {
                return Err(Error::InvalidFormat(
                    "tls-key is set, and tls-cert is not".to_owned(),
                ));
            }
            _ => {}
        }
        if merged.tls_client_ca.is_some()
            && merged.tls_cert.is_none()
            && merged.trusted_proxy_client_cert.is_none()
        {
            return Err(Error::InvalidFormat(
                "tls-client-ca is set, and tls-cert and trusted-proxy-client-cert are not"
                    .to_owned(),
            ));
        }
        Ok(())
    }
}

/// The access types move freely across tasks and threads, so one value can
/// serve each connection of a server.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<ClientAccess>();
    assert_send_sync::<ClientGroup>();
    assert_send_sync::<ServerSettings>();
    assert_send_sync::<ServerFile>();
    assert_send_sync::<ServerTlsFiles>();
    assert_send_sync::<Namespace>();
    assert_send_sync::<NamespaceRules>();
    assert_send_sync::<AuthItem>();
    assert_send_sync::<IpNet>();
    assert_send_sync::<ForwardedHeader>();
    assert_send_sync::<AccessModes>();
    assert_send_sync::<AllowItem>();
    assert_send_sync::<AccessRules>();
    assert_send_sync::<Claims>();
    assert_send_sync::<Claim>();
    assert_send_sync::<ClaimRule>();
    assert_send_sync::<ClaimError>();
    assert_send_sync::<ReadAccess>();
};

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

    /// The `[core]` group of each test config.
    const CORE: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";

    fn access(text: &str) -> ClientAccess {
        try_access(text).unwrap()
    }

    fn try_access(text: &str) -> Result<ClientAccess> {
        let config = RepoConfig::parse(&format!("{CORE}{text}"))?;
        ClientAccess::from_config(&config)
    }

    fn item(text: &str) -> AuthItem {
        AuthItem::parse(text).unwrap()
    }

    fn collection(id: &str) -> Namespace {
        Namespace::Collection(id.to_owned())
    }

    fn selected<'a>(access: &'a ClientAccess, item_text: &str) -> Option<&'a str> {
        access.select(&item(item_text)).map(ClientGroup::name)
    }

    /// Returns the allow items of `rules` as text, in order.
    fn allow_texts(rules: &AccessRules) -> Vec<String> {
        rules.allow.iter().map(AllowItem::to_string).collect()
    }

    /// The example config of the client groups parses, and each request
    /// selects the group that the example states.
    #[test]
    fn the_example_config_selects_its_groups() {
        let access = access(
            r#"
[ex-ostrya server]
listen=0.0.0.0:8443
tls-cert=/etc/ostrya/server.pem
tls-key=/etc/ostrya/server.key
tls-client-ca=/etc/ostrya/clients-ca.pem
trusted-proxy=10.0.0.0/24
trusted-proxy-header=x-forwarded-for

[ex-ostrya client "public"]
auth=anonymous
allow=r:**;r:@com.company.os:**

[ex-ostrya client "developer"]
auth=ssh:user
allow=cd:devel/user/**;c:@com.company.client:role/client/main/head;t:@com.company.client:role/client/release/**
sign=release-key

[ex-ostrya client "mirror"]
auth=tls:mirror.example.com
allow=w:@com.company.os:os/stable;w:@com.company.os:os/beta;t:@com.company.os:os/release/**
verify=trust:release

[ex-ostrya client "farm"]
auth=net:10.0.1.0/24;net:2001:db8::/56
allow=r:devel/**

[ex-ostrya client "ci-cert"]
auth=tls:*
tls-accept-claim=true
allow=r:release/**

[ex-ostrya trust "release"]
sign-verify=ed25519
verification-ed25519-file=/etc/ostrya/release.ed25519

[ex-ostrya key "release-key"]
type=ed25519
secret-key-file=/etc/ostrya/release.secret
"#,
        );
        access.check_server(access.server()).unwrap();
        assert_eq!(access.groups().len(), 5);
        assert!(access.groups().iter().all(|g| !g.is_implicit()));

        let os = collection("com.company.os");
        let client = collection("com.company.client");
        let other = collection("org.example.other");
        let local = Namespace::Local;
        assert_eq!(selected(&access, "anonymous"), Some("public"));
        assert_eq!(selected(&access, "ssh:user"), Some("developer"));
        assert_eq!(selected(&access, "tls:mirror.example.com"), Some("mirror"));
        assert_eq!(selected(&access, "tls:*"), Some("ci-cert"));
        assert_eq!(selected(&access, "net:10.0.1.0/24"), Some("farm"));
        assert_eq!(selected(&access, "net:2001:0db8::/56"), Some("farm"));
        assert_eq!(selected(&access, "ssh:other"), None);

        let public = access.select(&item("anonymous")).unwrap();
        assert_eq!(public.rules().rights(&local, "main"), AccessModes::READ);
        assert_eq!(public.rules().rights(&os, "os/stable"), AccessModes::READ);
        assert!(public.rules().get(&other).is_none());
        let mirror = access.select(&item("tls:mirror.example.com")).unwrap();
        assert_eq!(mirror.verify_trust(), Some("release"));
        assert!(!mirror.allow_unsigned());
        assert!(mirror.rules().opens_push_session());
        assert_eq!(
            mirror.rules().rights(&os, "os/stable"),
            AccessModes::parse("rw").unwrap()
        );
        assert_eq!(
            mirror.rules().rights(&local, "os/stable"),
            AccessModes::NONE
        );
        let developer = access.select(&item("ssh:user")).unwrap();
        assert_eq!(developer.sign(), ["release-key"]);
        assert!(developer.allow_unsigned());
        assert_eq!(
            developer.rules().rights(&client, "role/client/release/1"),
            AccessModes::parse("rt").unwrap()
        );
        assert_eq!(
            developer.rules().rights(&local, "devel/user/a"),
            AccessModes::parse("rcd").unwrap()
        );
        let ci = access.select(&item("tls:*")).unwrap();
        assert!(ci.tls_accept_claim());
        assert!(!ci.rules().opens_push_session());
        assert_eq!(
            access.server().trusted_proxy,
            Some(vec![IpNet::parse("10.0.0.0/24").unwrap()])
        );
        assert_eq!(
            access.server().trusted_proxy_header,
            Some(ForwardedHeader::XForwardedFor)
        );
    }

    /// A config with no client group has the implicit group, also when it
    /// has a server group. The group reads each local ref and each ref of
    /// each collection.
    #[test]
    fn a_config_with_no_client_group_has_the_implicit_group() {
        for text in [
            "",
            "[ex-ostrya server]\nlisten=127.0.0.1:0\n",
            "[ex-ostrya key \"k\"]\ntype=ed25519\n",
        ] {
            let access = access(text);
            let groups = access.groups();
            assert_eq!(groups.len(), 1, "{text:?}");
            let group = &groups[0];
            assert_eq!(group.name(), "anonymous");
            assert!(group.is_implicit());
            assert_eq!(group.auth(), [AuthItem::Anonymous]);
            assert_eq!(allow_texts(&group.rules().local), ["r:**"]);
            assert!(group.rules().local.deny.is_empty());
            assert!(group.rules().collections.is_empty());
            for ns in [Namespace::Local, collection("a.b")] {
                assert_eq!(group.rules().rights(&ns, "x/y"), AccessModes::READ);
            }
            assert!(group.rules().get(&collection("bad")).is_none());
            assert!(group.allow_unsigned());
            assert!(!group.rules().opens_push_session());
            assert_eq!(selected(&access, "anonymous"), Some("anonymous"));
        }
    }

    /// [`ClientAccess::implicit`] gives the groups and the server settings
    /// of a config with no client group. It keeps the own collection id as
    /// given, also an id that a config text holds only with an escape.
    #[test]
    fn the_implicit_access_has_the_groups_of_a_config_with_no_client_group() {
        let from_config = access("");
        for id in [None, Some("a.b"), Some("a\\b"), Some(" a.b")] {
            let implicit = ClientAccess::implicit(id);
            assert_eq!(
                format!("{:?}", implicit.groups()),
                format!("{:?}", from_config.groups()),
                "{id:?}"
            );
            assert_eq!(implicit.server(), from_config.server(), "{id:?}");
            assert!(!implicit.has_client_groups(), "{id:?}");
            if let Some(id) = id {
                assert_eq!(implicit.namespace(Some(id)), Namespace::Local, "{id:?}");
            }
        }
        assert_eq!(
            ClientAccess::implicit(None).namespace(Some("a.b")),
            collection("a.b")
        );
    }

    /// One client group of any kind removes the implicit group.
    #[test]
    fn one_client_group_removes_the_implicit_group() {
        let access = access("[ex-ostrya client \"c\"]\nauth=ssh:c\n");
        assert_eq!(access.groups().len(), 1);
        assert!(!access.groups()[0].is_implicit());
        assert_eq!(selected(&access, "anonymous"), None);
    }

    /// One group holds the items of each namespace. The items of one
    /// collection never apply to another collection or to the local refs.
    #[test]
    fn one_group_holds_the_items_of_each_namespace() {
        let access = access(
            "[ex-ostrya client \"c\"]\nauth=ssh:u\n\
             allow=r:main;w:@a.b:os/**;@c.d:x;d:@a.b:os/old\ndeny=secret;@a.b:os/secret\n",
        );
        let rules = access.select(&item("ssh:u")).unwrap().rules();
        assert_eq!(allow_texts(&rules.local), ["r:main"]);
        let ab = rules.get(&collection("a.b")).unwrap();
        assert_eq!(allow_texts(ab), ["w:os/**", "d:os/old"]);
        assert_eq!(ab.deny.len(), 1);
        assert_eq!(allow_texts(rules.get(&collection("c.d")).unwrap()), ["r:x"]);
        assert!(rules.get(&collection("e.f")).is_none());
        let local = Namespace::Local;
        assert_eq!(rules.rights(&local, "main"), AccessModes::READ);
        assert_eq!(rules.rights(&local, "os/a"), AccessModes::NONE);
        assert_eq!(rules.rights(&local, "secret"), AccessModes::NONE);
        assert_eq!(
            rules.rights(&collection("a.b"), "os/old"),
            AccessModes::parse("rwd").unwrap()
        );
        assert_eq!(
            rules.rights(&collection("a.b"), "os/secret"),
            AccessModes::NONE
        );
        assert_eq!(rules.rights(&collection("a.b"), "main"), AccessModes::NONE);
        assert_eq!(rules.rights(&collection("c.d"), "os/a"), AccessModes::NONE);
        assert_eq!(rules.rights(&collection("e.f"), "x"), AccessModes::NONE);
        assert!(rules.opens_push_session());
    }

    /// An item with `@ID:` of the own collection id is an item of the local
    /// refs. With no own collection id, the item names the collection.
    #[test]
    fn an_item_of_the_own_collection_id_is_a_local_item() {
        let groups = "[ex-ostrya client \"c\"]\nauth=ssh:u\n\
                      allow=r:a;w:@own.id:b\ndeny=@own.id:a/secret\n";
        let config = RepoConfig::parse(&format!("{CORE}collection-id=own.id\n{groups}")).unwrap();
        let access = ClientAccess::from_config(&config).unwrap();
        let rules = access.select(&item("ssh:u")).unwrap().rules();
        assert_eq!(allow_texts(&rules.local), ["r:a", "w:b"]);
        assert_eq!(rules.local.deny.len(), 1);
        assert!(rules.collections.is_empty());
        let own = access.namespace(Some("own.id"));
        assert_eq!(rules.rights(&own, "b"), AccessModes::parse("rw").unwrap());

        let no_own_id = self::access(groups);
        let rules = no_own_id.select(&item("ssh:u")).unwrap().rules();
        assert_eq!(allow_texts(&rules.local), ["r:a"]);
        assert_eq!(
            allow_texts(rules.get(&collection("own.id")).unwrap()),
            ["w:b"]
        );
    }

    /// The selection never moves to another item.
    #[test]
    fn the_selection_never_falls_back_to_another_item() {
        let access = access(
            "[ex-ostrya client \"name\"]\nauth=tls:n\n\
             [ex-ostrya client \"any\"]\nauth=tls:*\n",
        );
        assert_eq!(selected(&access, "tls:n"), Some("name"));
        assert_eq!(selected(&access, "tls:*"), Some("any"));
        assert_eq!(selected(&access, "anonymous"), None);
    }

    /// The own collection id maps to the local namespace, and an id that
    /// fails the collection-id rule gives no rules.
    #[test]
    fn the_own_id_maps_to_the_local_namespace() {
        let config = RepoConfig::parse(&format!(
            "{CORE}collection-id=own.id\n\
             [ex-ostrya client \"c\"]\nauth=anonymous\nallow=r:**\n"
        ))
        .unwrap();
        let access = ClientAccess::from_config(&config).unwrap();
        assert_eq!(access.namespace(Some("own.id")), Namespace::Local);
        assert_eq!(access.namespace(None), Namespace::Local);
        assert_eq!(access.namespace(Some("a.b")), collection("a.b"));
        assert_eq!(access.namespace(Some("bad")), collection("bad"));
        let implicit = ClientAccess::implicit(Some("own.id"));
        let rules = implicit.select(&AuthItem::Anonymous).unwrap().rules();
        for id in ["bad", "a..b", "1a.b"] {
            assert!(rules.get(&collection(id)).is_none(), "{id}");
        }
    }

    /// With no own collection id, each id maps to its collection, and no id
    /// maps to the local namespace.
    #[test]
    fn with_no_own_id_each_id_maps_to_its_collection() {
        let access = access("");
        assert_eq!(access.namespace(Some("a.b")), collection("a.b"));
        assert_eq!(access.namespace(None), Namespace::Local);
    }

    /// The rules of the claims for a namespace hold the claims of that
    /// namespace alone, in order. A claim of the own collection id counts
    /// for the local refs. No claim for a namespace gives `None`, also with
    /// claims of other namespaces.
    #[test]
    fn the_claim_rules_hold_the_claims_of_one_namespace() {
        let config = RepoConfig::parse(&format!("{CORE}collection-id=own.id\n")).unwrap();
        let access = ClientAccess::from_config(&config).unwrap();
        let claims = Claims::parse([
            "ostrya:ref:w:main",
            "ostrya:ref:t:@a.b:os/**",
            "ostrya:ref:!secret/**",
            "ostrya:ref:d:@own.id:devel/**",
            "ostrya:ref:!@a.b:os/secret",
        ])
        .unwrap();
        let local = access.claim_rules(&claims, &Namespace::Local).unwrap();
        assert_eq!(allow_texts(&local), ["w:main", "d:devel/**"]);
        assert_eq!(local.deny.len(), 1);
        assert_eq!(local.deny[0].as_str(), "secret/**");
        assert_eq!(local.rights("main"), AccessModes::parse("rw").unwrap());
        assert_eq!(local.rights("secret/a"), AccessModes::NONE);

        let ab = access.claim_rules(&claims, &collection("a.b")).unwrap();
        assert_eq!(allow_texts(&ab), ["t:os/**"]);
        assert_eq!(ab.rights("os/secret"), AccessModes::NONE);
        assert!(access.claim_rules(&claims, &collection("c.d")).is_none());
        assert!(
            access
                .claim_rules(&Claims::default(), &Namespace::Local)
                .is_none()
        );

        let collections_only = Claims::parse(["ostrya:ref:w:@a.b:main"]).unwrap();
        assert!(
            access
                .claim_rules(&collections_only, &Namespace::Local)
                .is_none()
        );
        let deny_only = Claims::parse(["ostrya:ref:!secret/**"]).unwrap();
        let rules = access.claim_rules(&deny_only, &Namespace::Local).unwrap();
        assert!(rules.allow.is_empty());
        assert_eq!(rules.rights("main"), AccessModes::NONE);

        let no_own_id = self::access("");
        let own = Claims::parse(["ostrya:ref:w:@own.id:main"]).unwrap();
        assert!(no_own_id.claim_rules(&own, &Namespace::Local).is_none());
        assert!(no_own_id.claim_rules(&own, &collection("own.id")).is_some());
    }

    /// `Claims::rules` gives the rules of `claim_rules` for each namespace,
    /// with and without an own collection id.
    #[test]
    fn the_rules_of_the_claims_are_the_claim_rules() {
        let config = RepoConfig::parse(&format!("{CORE}collection-id=own.id\n")).unwrap();
        let with_own = ClientAccess::from_config(&config).unwrap();
        let claims = Claims::parse([
            "ostrya:ref:w:main",
            "ostrya:ref:t:@a.b:os/**",
            "ostrya:ref:!secret/**",
            "ostrya:ref:d:@own.id:devel/**",
            "ostrya:ref:!@a.b:os/secret",
        ])
        .unwrap();
        for (access, own) in [(&with_own, Some("own.id")), (&self::access(""), None)] {
            for namespace in [
                Namespace::Local,
                collection("a.b"),
                collection("own.id"),
                collection("c.d"),
            ] {
                assert_eq!(
                    claims.rules(&namespace, own),
                    access.claim_rules(&claims, &namespace),
                    "{own:?} {namespace:?}"
                );
            }
        }
    }

    /// The namespace of the own collection id gives the rules of the local
    /// refs: the claims with no `@ID:` and the claims of the own id.
    #[test]
    fn the_own_collection_id_gives_the_claim_rules_of_the_local_refs() {
        let config = RepoConfig::parse(&format!("{CORE}collection-id=own.id\n")).unwrap();
        let access = ClientAccess::from_config(&config).unwrap();
        let claims = Claims::parse([
            "ostrya:ref:w:main",
            "ostrya:ref:d:@own.id:devel/**",
            "ostrya:ref:t:@a.b:os/**",
            "ostrya:ref:!secret/**",
        ])
        .unwrap();
        let own = access.claim_rules(&claims, &collection("own.id")).unwrap();
        assert_eq!(allow_texts(&own), ["w:main", "d:devel/**"]);
        assert_eq!(own.deny.len(), 1);
        assert_eq!(Some(own), access.claim_rules(&claims, &Namespace::Local));
        let refs_only = Claims::parse(["ostrya:ref:w:main"]).unwrap();
        assert!(
            access
                .claim_rules(&refs_only, &collection("own.id"))
                .is_some()
        );
    }

    /// The claims of one namespace replace the rules of the group in that
    /// namespace alone. The other namespaces keep the rules of the group. A
    /// claim of a collection with no item in the group gives rules there.
    /// A group with `tls-accept-claim=false` ignores the claims.
    #[test]
    fn the_claims_of_one_namespace_keep_the_rules_of_the_others() {
        let groups = "[ex-ostrya client \"certs\"]\nauth=tls:*\ntls-accept-claim=true\n\
                      allow=r:group/**;r:@a.b:group/**;r:@c.d:group/**\n\
                      [ex-ostrya client \"names\"]\nauth=tls:n\nallow=r:group/**\n";
        let config = RepoConfig::parse(&format!("{CORE}collection-id=own.id\n{groups}")).unwrap();
        let access = ClientAccess::from_config(&config).unwrap();
        let certs = access.select(&AuthItem::TlsAny).unwrap();
        let claims = Claims::parse([
            "ostrya:ref:w:@a.b:claim/**",
            "ostrya:ref:@e.f:claim/**",
            "ostrya:ref:!@own.id:group/secret",
        ])
        .unwrap();
        let rules = access.effective_rules(certs, Some(&claims));
        assert!(matches!(rules, Cow::Owned(_)));
        let (ab, cd, ef) = (collection("a.b"), collection("c.d"), collection("e.f"));
        let local = Namespace::Local;
        assert_eq!(
            rules.rights(&ab, "claim/x"),
            AccessModes::parse("rw").unwrap()
        );
        assert_eq!(rules.rights(&ab, "group/x"), AccessModes::NONE);
        assert_eq!(rules.rights(&cd, "group/x"), AccessModes::READ);
        assert_eq!(rules.rights(&ef, "claim/x"), AccessModes::READ);
        assert_eq!(rules.rights(&local, "group/x"), AccessModes::NONE);
        assert_eq!(rules.rights(&local, "group/secret"), AccessModes::NONE);
        assert!(rules.local.allow.is_empty());

        let only_ab = Claims::parse(["ostrya:ref:@a.b:claim/**"]).unwrap();
        let rules = access.effective_rules(certs, Some(&only_ab));
        assert_eq!(rules.rights(&local, "group/x"), AccessModes::READ);
        assert_eq!(rules.rights(&cd, "group/x"), AccessModes::READ);
        assert_eq!(rules.rights(&ab, "group/x"), AccessModes::NONE);

        let none = access.effective_rules(certs, Some(&Claims::default()));
        assert!(matches!(none, Cow::Borrowed(_)));
        let names = access.select(&item("tls:n")).unwrap();
        assert!(matches!(
            access.effective_rules(names, Some(&claims)),
            Cow::Borrowed(_)
        ));
    }

    /// `groups_of` gives the group of an item.
    #[test]
    fn groups_of_gives_the_group_of_an_item() {
        let access = access(
            "[ex-ostrya client \"a\"]\nauth=ssh:u;anonymous\n\
             [ex-ostrya client \"b\"]\nauth=ssh:v\n",
        );
        let ssh = item("ssh:u");
        let names: Vec<&str> = access.groups_of(&ssh).map(ClientGroup::name).collect();
        assert_eq!(names, ["a"]);
        assert_eq!(access.groups_of(&item("ssh:w")).count(), 0);
    }

    /// `items` gives each item one time, in the order of its group. Two
    /// texts of one network are one item.
    #[test]
    fn items_gives_each_item_one_time() {
        let access = access(
            "[ex-ostrya client \"a\"]\nauth=ssh:u;anonymous\n\
             [ex-ostrya client \"b\"]\nauth=net:2001:0db8::/56;ssh:v;net:2001:db8::/56\n\
             [ex-ostrya client \"c\"]\nauth=tls:*\n",
        );
        let items: Vec<String> = access.items().map(AuthItem::to_string).collect();
        assert_eq!(
            items,
            ["ssh:u", "anonymous", "net:2001:db8::/56", "ssh:v", "tls:*"]
        );
        let implicit = self::access("");
        let items: Vec<&AuthItem> = implicit.items().collect();
        assert_eq!(items, [&AuthItem::Anonymous]);
    }

    /// Two groups with one item are refused, whatever their items name.
    #[test]
    fn an_item_in_two_groups_is_refused() {
        for (a, b) in [
            ("", ""),
            ("allow=r:@a.b:x\n", "allow=r:@c.d:x\n"),
            ("allow=r:x\n", "allow=r:@c.d:x\n"),
        ] {
            let text = format!(
                "[ex-ostrya client \"one\"]\nauth=ssh:u\n{a}\
                 [ex-ostrya client \"two\"]\nauth=anonymous;ssh:u\n{b}"
            );
            let Err(Error::InvalidFormat(message)) = try_access(&text) else {
                panic!("{a:?} {b:?} was accepted");
            };
            assert!(message.contains("ssh:u"), "{message}");
            assert!(message.contains("\"one\""), "{message}");
            assert!(message.contains("\"two\""), "{message}");
        }
        let text = "[ex-ostrya client \"one\"]\nauth=net:2001:db8::/56\n\
                    [ex-ostrya client \"two\"]\nauth=net:2001:0db8::/56\n";
        assert!(try_access(text).is_err());
    }

    /// Returns the config path `path` of a server file.
    fn config(path: &str) -> Option<ServerFile> {
        Some(ServerFile::Config(path.into()))
    }

    /// Returns the caller path `path` of a server file.
    fn caller(path: &str) -> Option<ServerFile> {
        Some(ServerFile::Caller(path.into()))
    }

    fn settings() -> ServerSettings {
        ServerSettings {
            tls_cert: config("/c.pem"),
            tls_key: config("/k.pem"),
            tls_client_ca: config("/ca.pem"),
            ..ServerSettings::default()
        }
    }

    fn check(access: &ClientAccess, merged: &ServerSettings) -> String {
        match access.check_server(merged) {
            Err(Error::InvalidFormat(message)) => message,
            other => panic!("{merged:?}: {other:?}"),
        }
    }

    /// A TLS item needs no `tls-client-ca`, and a proxy certificate header
    /// needs it.
    #[test]
    fn a_proxy_certificate_header_needs_the_client_ca() {
        for item_text in [
            "tls:*",
            "tls:n",
            "tls-sha256:0000000000000000000000000000000000000000000000000000000000000000",
        ] {
            let access = access(&format!("[ex-ostrya client \"c\"]\nauth={item_text}\n"));
            access.check_server(&settings()).unwrap();
            access.check_server(&ServerSettings::default()).unwrap();
            let merged = ServerSettings {
                tls_client_ca: None,
                ..settings()
            };
            access.check_server(&merged).unwrap();
        }
        let access = access("[ex-ostrya client \"c\"]\nauth=anonymous\n");
        access.check_server(&ServerSettings::default()).unwrap();
        let proxy = Some(vec![IpNet::parse("10.0.0.0/24").unwrap()]);
        let merged = ServerSettings {
            trusted_proxy_client_cert: Some("X-Client-Cert".into()),
            trusted_proxy: proxy.clone(),
            ..ServerSettings::default()
        };
        let message = check(&access, &merged);
        assert!(message.contains("trusted-proxy-client-cert"), "{message}");
        assert!(message.contains("tls-client-ca"), "{message}");
        let merged = ServerSettings {
            trusted_proxy_client_cert: Some("X-Client-Cert".into()),
            trusted_proxy: proxy,
            trusted_proxy_header: Some(ForwardedHeader::XForwardedFor),
            tls_client_ca: config("/ca.pem"),
            ..ServerSettings::default()
        };
        access.check_server(&merged).unwrap();
    }

    /// A proxy certificate header needs `trusted-proxy`.
    #[test]
    fn a_proxy_certificate_header_needs_a_trusted_proxy() {
        let anonymous = access("[ex-ostrya client \"c\"]\nauth=anonymous\n");
        let merged = ServerSettings {
            trusted_proxy_client_cert: Some("X-Client-Cert".into()),
            tls_client_ca: config("/ca.pem"),
            ..ServerSettings::default()
        };
        let message = check(&anonymous, &merged);
        assert_eq!(
            message,
            "trusted-proxy-client-cert is set, and the server has no trusted-proxy"
        );
        let configured = access(
            "[ex-ostrya server]\ntls-client-ca=/ca.pem\n\
             trusted-proxy-client-cert=X-Client-Cert\n",
        );
        let message = check(&configured, configured.server());
        assert!(message.contains("no trusted-proxy"), "{message}");
    }

    /// `trusted-proxy` and `trusted-proxy-header` go together, from a key or
    /// from a flag.
    #[test]
    fn a_trusted_proxy_and_its_header_go_together() {
        let anonymous = access("[ex-ostrya client \"c\"]\nauth=anonymous\n");
        let proxy = Some(vec![IpNet::parse("10.0.0.0/24").unwrap()]);
        let merged = ServerSettings {
            trusted_proxy: proxy.clone(),
            ..ServerSettings::default()
        };
        assert_eq!(
            check(&anonymous, &merged),
            "trusted-proxy is set, and the server has no trusted-proxy-header"
        );
        let merged = ServerSettings {
            trusted_proxy_header: Some(ForwardedHeader::Forwarded),
            ..ServerSettings::default()
        };
        assert_eq!(
            check(&anonymous, &merged),
            "trusted-proxy-header is set, and the server has no trusted-proxy"
        );
        let merged = ServerSettings {
            trusted_proxy: proxy,
            trusted_proxy_header: Some(ForwardedHeader::XRealIp),
            ..ServerSettings::default()
        };
        anonymous.check_server(&merged).unwrap();
        let configured = access("[ex-ostrya server]\ntrusted-proxy-header=x-real-ip\n");
        let message = check(&configured, configured.server());
        assert!(message.contains("no trusted-proxy"), "{message}");
        let configured = access("[ex-ostrya server]\ntrusted-proxy=10.0.0.0/8\n");
        let flags = ServerSettings {
            trusted_proxy_header: Some(ForwardedHeader::Forwarded),
            ..ServerSettings::default()
        };
        let merged = configured.server().overridden_by(&flags);
        configured.check_server(&merged).unwrap();
    }

    /// A value of `trusted-proxy-header` is one of three lowercase names.
    #[test]
    fn a_forwarded_header_has_three_names() {
        for (text, header) in [
            ("forwarded", ForwardedHeader::Forwarded),
            ("x-forwarded-for", ForwardedHeader::XForwardedFor),
            ("x-real-ip", ForwardedHeader::XRealIp),
        ] {
            assert_eq!(ForwardedHeader::parse(text).unwrap(), header);
            assert_eq!(header.to_string(), text);
        }
        for text in [
            "",
            "Forwarded",
            "X-Real-IP",
            "x-forwarded-proto",
            " forwarded",
        ] {
            let err = ForwardedHeader::parse(text).unwrap_err();
            assert!(matches!(err, Error::InvalidFormat(_)), "{text:?}: {err}");
        }
    }

    /// `is_header_name` takes the characters of an HTTP token.
    #[test]
    fn a_header_name_is_an_http_token() {
        for name in ["X-Client-Cert", "ssl_client_cert", "a!#$%&'*+-.^_`|~9"] {
            assert!(is_header_name(name), "{name}");
        }
        for name in ["", "a b", "a:b", "a\"b", "a(b", "a/b", "\u{e9}", "a\tb"] {
            assert!(!is_header_name(name), "{name:?}");
        }
    }

    /// A field of the flags that is set replaces the key, a list in whole,
    /// and a field that is `None` keeps the key.
    #[test]
    fn a_flag_overrides_its_key() {
        let net = |text: &str| IpNet::parse(text).unwrap();
        let keys = ServerSettings {
            listen: Some(vec![
                "127.0.0.1:1".parse().unwrap(),
                "127.0.0.1:2".parse().unwrap(),
            ]),
            tls_cert: config("/key/c.pem"),
            tls_key: config("/key/k.pem"),
            tls_client_ca: config("/key/ca.pem"),
            trusted_proxy: Some(vec![net("10.0.0.0/8"), net("10.1.0.0/16")]),
            trusted_proxy_header: Some(ForwardedHeader::Forwarded),
            trusted_proxy_client_cert: Some("X-Key".into()),
            proxy_protocol: Some(false),
            allow_cleartext_credentials: Some(true),
            session_timeout: Some(1),
            max_sessions: Some(2),
            parallel_uploads: Some(3),
            body_timeout: Some(4),
            sign_summary: Some(vec!["a".into(), "b".into()]),
        };
        let flags = ServerSettings {
            listen: Some(vec!["127.0.0.1:3".parse().unwrap()]),
            tls_cert: caller("flag/c.pem"),
            tls_key: caller("flag/k.pem"),
            tls_client_ca: caller("flag/ca.pem"),
            trusted_proxy: Some(vec![net("192.0.2.0/24")]),
            trusted_proxy_header: Some(ForwardedHeader::XRealIp),
            trusted_proxy_client_cert: Some("X-Flag".into()),
            proxy_protocol: Some(true),
            allow_cleartext_credentials: Some(false),
            session_timeout: Some(10),
            max_sessions: Some(20),
            parallel_uploads: Some(30),
            body_timeout: Some(40),
            sign_summary: Some(vec!["c".into()]),
        };
        assert_eq!(keys.overridden_by(&flags), flags);
        assert_eq!(keys.overridden_by(&ServerSettings::default()), keys);
        assert_eq!(ServerSettings::default().overridden_by(&flags), flags);
        let one = ServerSettings {
            max_sessions: Some(20),
            ..ServerSettings::default()
        };
        let merged = keys.overridden_by(&one);
        assert_eq!(merged.max_sessions, Some(20));
        assert_eq!(
            merged,
            ServerSettings {
                max_sessions: Some(20),
                ..keys.clone()
            }
        );
    }

    /// The `tls-client-ca` key stays with `tls-cert` or
    /// `trusted-proxy-client-cert`, from a key or from a flag. With neither,
    /// the key goes, and the flag stays, so that `check_server` refuses it.
    #[test]
    fn a_plain_server_ignores_the_client_ca_key() {
        let ca = |file: Option<ServerFile>| ServerSettings {
            tls_client_ca: file,
            ..ServerSettings::default()
        };
        let merged = ca(config("/key/ca.pem")).overridden_by(&ServerSettings::default());
        assert_eq!(merged, ServerSettings::default());
        access("").check_server(&merged).unwrap();
        let merged = ca(config("/key/ca.pem")).overridden_by(&ca(caller("flag/ca.pem")));
        assert_eq!(merged, ca(caller("flag/ca.pem")));
        assert!(check(&access(""), &merged).contains("tls-client-ca"));
        let flags = ServerSettings {
            tls_cert: caller("flag/c.pem"),
            tls_key: caller("flag/k.pem"),
            ..ServerSettings::default()
        };
        let merged = ca(config("/key/ca.pem")).overridden_by(&flags);
        assert_eq!(merged.tls_client_ca, config("/key/ca.pem"));
        let keys = ServerSettings {
            trusted_proxy_client_cert: Some("X-Key".into()),
            ..ca(config("/key/ca.pem"))
        };
        let merged = keys.overridden_by(&ServerSettings::default());
        assert_eq!(merged.tls_client_ca, config("/key/ca.pem"));
    }

    /// `tls-cert` and `tls-key` go together, and `tls-client-ca` needs
    /// `tls-cert` or a proxy certificate header.
    #[test]
    fn the_tls_files_go_together() {
        let access = access("");
        let merged = ServerSettings {
            tls_key: None,
            ..settings()
        };
        assert!(check(&access, &merged).contains("tls-key"));
        let merged = ServerSettings {
            tls_cert: None,
            ..settings()
        };
        assert!(check(&access, &merged).contains("tls-cert"));
        let merged = ServerSettings {
            tls_client_ca: config("/ca.pem"),
            ..ServerSettings::default()
        };
        assert!(check(&access, &merged).contains("tls-client-ca"));
        let merged = ServerSettings {
            tls_client_ca: None,
            ..settings()
        };
        access.check_server(&merged).unwrap();
    }

    /// A temp directory with a repository at `repo`, which the drop removes.
    struct TlsDir {
        dir: crate::repo_fs::TestDir,
        repo: Repo,
    }

    impl TlsDir {
        fn new() -> TlsDir {
            let dir = crate::repo_fs::TestDir::new("tls-files");
            let root = dir.path().join("repo");
            let repo = ostrya_rt::block_on(async {
                Repo::create(
                    &root,
                    crate::CreateOptions::new(ostrya_core::RepoMode::Archive),
                )
                .await
                .unwrap()
            });
            TlsDir { dir, repo }
        }

        /// Returns the path of the directory joined with `name`.
        fn path(&self, name: &str) -> PathBuf {
            self.dir.path().join(name)
        }

        /// Reads the files of `settings` against the repository.
        fn read(&self, settings: &ServerSettings) -> Result<ServerTlsFiles> {
            ostrya_rt::block_on(settings.read_tls_files(&self.repo))
        }
    }

    /// Returns the message of an [`Error::InvalidInput`].
    fn invalid_input(result: Result<ServerTlsFiles>) -> String {
        match result {
            Err(Error::InvalidInput(message)) => message,
            other => panic!("{other:?}"),
        }
    }

    /// A relative config path resolves against the repository root, and not
    /// against the working directory. An absolute caller path opens, and so
    /// does an absolute config path with a `..` component. The read follows
    /// a symlink to a file outside the repository.
    #[test]
    fn the_tls_files_resolve_against_the_base_of_their_source() {
        let dir = TlsDir::new();
        let root = dir.repo.path().to_owned();
        std::fs::create_dir(root.join("certs")).unwrap();
        std::fs::write(root.join("certs/c.pem"), b"CERT").unwrap();
        std::fs::write(dir.path("k.pem"), b"KEY").unwrap();
        std::fs::write(dir.path("ca.pem"), b"CA").unwrap();
        std::os::unix::fs::symlink(dir.path("ca.pem"), root.join("ca-link.pem")).unwrap();
        assert!(!std::path::Path::new("certs/c.pem").exists());
        let settings = ServerSettings {
            tls_cert: config("certs/c.pem"),
            tls_key: Some(ServerFile::Caller(dir.path("k.pem"))),
            tls_client_ca: config("ca-link.pem"),
            ..ServerSettings::default()
        };
        let files = dir.read(&settings).unwrap();
        assert_eq!(files.cert.as_deref(), Some(&b"CERT"[..]));
        assert_eq!(files.key.as_deref(), Some(&b"KEY"[..]));
        assert_eq!(files.client_ca.as_deref(), Some(&b"CA"[..]));

        let parent = root.join("certs/../certs/c.pem");
        let settings = ServerSettings {
            tls_cert: Some(ServerFile::Config(parent.clone())),
            tls_key: Some(ServerFile::Caller(parent)),
            ..ServerSettings::default()
        };
        let files = dir.read(&settings).unwrap();
        assert_eq!(files.cert.as_deref(), Some(&b"CERT"[..]));
        assert_eq!(files.key.as_deref(), Some(&b"CERT"[..]));
        assert_eq!(files.client_ca, None);
    }

    /// A relative path with a `..` component is refused: a caller path with
    /// [`Error::InvalidInput`], and a config path with
    /// [`Error::InvalidFormat`] that names the key. A refused path of a later
    /// field stops the read before the call opens the file of an earlier
    /// field.
    #[test]
    fn a_relative_tls_path_with_a_parent_component_is_refused() {
        let dir = TlsDir::new();
        let settings = ServerSettings {
            tls_key: caller("../k.pem"),
            ..ServerSettings::default()
        };
        assert_eq!(
            invalid_input(dir.read(&settings)),
            "tls-key ../k.pem is a relative path with a `..` component"
        );
        let settings = ServerSettings {
            tls_cert: config("absent.pem"),
            tls_client_ca: config("certs/../../ca.pem"),
            ..ServerSettings::default()
        };
        match dir.read(&settings) {
            Err(Error::InvalidFormat(message)) => assert_eq!(
                message,
                "[ex-ostrya server] tls-client-ca certs/../../ca.pem has a `..` component, \
                 which a relative path in a config cannot have"
            ),
            other => panic!("{other:?}"),
        }
    }

    /// A FIFO, a directory, and a device at a TLS path fail the read 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_is_refused() {
        let dir = TlsDir::new();
        let fifo = dir.path("fifo.pem");
        rustix::fs::mknodat(
            rustix::fs::CWD,
            &fifo,
            rustix::fs::FileType::Fifo,
            rustix::fs::Mode::from_raw_mode(0o600),
            0,
        )
        .unwrap();
        let dir = std::sync::Arc::new(dir);
        for path in [fifo, dir.path(""), PathBuf::from("/dev/null")] {
            let settings = ServerSettings {
                tls_cert: Some(ServerFile::Caller(path.clone())),
                ..ServerSettings::default()
            };
            let worker = {
                let dir = dir.clone();
                std::thread::spawn(move || dir.read(&settings))
            };
            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
            while !worker.is_finished() && std::time::Instant::now() < deadline {
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
            assert!(worker.is_finished(), "the read does not end in 10 seconds");
            assert_eq!(
                invalid_input(worker.join().unwrap()),
                format!("tls-cert '{}' is not a regular file", path.display())
            );
        }
    }

    /// A file of 1 MiB is read, and a file of 1 MiB and one byte is refused.
    #[test]
    fn a_tls_file_over_1_mib_is_refused() {
        let dir = TlsDir::new();
        let root = dir.repo.path().to_owned();
        std::fs::write(root.join("cap.pem"), vec![b'a'; 1 << 20]).unwrap();
        std::fs::write(root.join("over.pem"), vec![b'a'; (1 << 20) + 1]).unwrap();
        let settings = ServerSettings {
            tls_client_ca: config("cap.pem"),
            ..ServerSettings::default()
        };
        let files = dir.read(&settings).unwrap();
        assert_eq!(files.client_ca.map(|ca| ca.len()), Some(1 << 20));
        let settings = ServerSettings {
            tls_client_ca: config("over.pem"),
            ..ServerSettings::default()
        };
        assert_eq!(
            invalid_input(dir.read(&settings)),
            "tls-client-ca 'over.pem' is over 1 MiB"
        );
    }

    /// The read stops at the first error, in the order cert, key, and client
    /// CA, and a field that is `None` gives `None`.
    #[test]
    fn the_tls_read_stops_at_the_first_error() {
        let dir = TlsDir::new();
        let root = dir.repo.path().to_owned();
        std::fs::write(root.join("k.pem"), b"KEY").unwrap();
        assert_eq!(
            format!("{:?}", dir.read(&ServerSettings::default()).unwrap()),
            "ServerTlsFiles { cert: None, key: None, client_ca: None }"
        );
        let settings = ServerSettings {
            tls_cert: config("absent.pem"),
            tls_key: config("k.pem"),
            tls_client_ca: config("/"),
            ..ServerSettings::default()
        };
        let err = dir.read(&settings).unwrap_err();
        assert!(
            matches!(&err, Error::Io(e) if e.kind() == std::io::ErrorKind::NotFound
                && e.to_string().starts_with("tls-cert 'absent.pem': ")),
            "{err:?}"
        );
        let settings = ServerSettings {
            tls_cert: None,
            ..settings
        };
        assert_eq!(
            invalid_input(dir.read(&settings)),
            "tls-client-ca '/' is not a regular file"
        );
        let settings = ServerSettings {
            tls_client_ca: None,
            ..settings
        };
        let files = dir.read(&settings).unwrap();
        assert_eq!(files.cert, None);
        assert_eq!(files.key.as_deref(), Some(&b"KEY"[..]));
        assert_eq!(files.client_ca, None);
    }

    /// The `Debug` output of the files gives the size of the key and no byte
    /// of it.
    #[test]
    fn the_debug_output_hides_the_key() {
        let files = ServerTlsFiles {
            cert: Some(b"C".to_vec()),
            key: Some(b"SECRET".to_vec()),
            client_ca: None,
        };
        let text = format!("{files:?}");
        assert!(!text.contains("83, 69, 67"), "{text}");
        assert!(!text.contains("SECRET"), "{text}");
        assert_eq!(
            text,
            "ServerTlsFiles { cert: Some([67]), key: Some(\"<6 bytes redacted>\"), \
             client_ca: None }"
        );
    }
}