ostrya 0.19.0

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

use crate::config::{
    RepoConfig, SPKI_X509_KEYS, Section, SectionExt as _, SignVerify, TRUST_ENGINES,
    refuse_foreign_keys, remote, trust, verification_engine,
};
use crate::error::{Error, Result};
use crate::pull::PullVerify;
use crate::repo::Repo;
use crate::sign::{SYSTEM_KEY_ROOTS, X509Check};

use super::{
    KeySource, Policy, PullTrust, TrustedKeys, Verifiers, build_policy, no_remote, summary_switches,
};

/// Builds the policy of the trust group `name` from its section `section`.
///
/// The policy holds the GPG axis of the group if `gpg_on` is `true`, and the
/// sign-api axis of the group if `sign_on` is `true`. The build reads no key
/// source of an axis that is off. Each call makes its own verifiers, so a
/// policy of a group shares no verifier with a policy of a remote.
///
/// If `best_effort` is `true`, the X.509 trust of the group reads its CRLs as
/// [`X509Revocation::BestEffort`](crate::sign::X509Revocation::BestEffort)
/// whatever `verification-spki-revocation` says, as a media import does.
///
/// The caller checks the group with [`check_trust`] first. As a result, the
/// group turns on at least one axis, and an axis reads each key that the group
/// holds.
pub(crate) async fn trust_group_policy(
    repo: &Repo,
    name: &str,
    section: &Section<'_, trust::Group>,
    gpg_on: bool,
    sign_on: bool,
    best_effort: bool,
) -> Result<Policy> {
    let gpg = gpg_on && section.get::<trust::GpgVerify>()?;
    let sign = if sign_on {
        section.get::<trust::SignVerify>()?
    } else {
        SignVerify::Off
    };
    trust_group_build(
        repo,
        name,
        section,
        gpg,
        &sign,
        X509Check::Admission,
        best_effort,
    )
    .await
}

/// Returns the GPG switch and the sign-api switch of the trust group
/// `section`. The call reads no key source.
pub(crate) fn trust_group_switches(
    section: &Section<'_, trust::Group>,
) -> Result<(bool, SignVerify)> {
    let gpg = section.get::<trust::GpgVerify>()?;
    let sign = section.get::<trust::SignVerify>()?;
    Ok((gpg, sign))
}

/// Builds the policy of the trust group `name` from its section `section`,
/// with the axes that `gpg` and `sign` turn on, and the X.509 check `check`.
/// `best_effort` is the switch of [`trust_group_policy`].
pub(crate) async fn trust_group_build(
    repo: &Repo,
    name: &str,
    section: &Section<'_, trust::Group>,
    gpg: bool,
    sign: &SignVerify,
    check: X509Check,
    best_effort: bool,
) -> Result<Policy> {
    let source = KeySource::Trust {
        name,
        section,
        check,
        best_effort,
    };
    build_policy(repo, &source, &mut Verifiers::default(), gpg, sign).await
}

impl TrustedKeys {
    /// Reads the trusted keys of the trust group `[ex-ostrya trust "NAME"]`
    /// whose name is `name`.
    ///
    /// The group uses the key names of a remote section, and the call reads
    /// them through the key types of [`config::trust`](crate::config::trust):
    ///
    /// - `gpg-verify` turns on the GPG axis. In a trust group, its default is
    ///   `false`.
    /// - `gpgkeypath` names the keyrings of the GPG axis.
    /// - `sign-verify` turns on the sign-api axis and selects its engines.
    /// - `verification-ENGINE-key` and `verification-ENGINE-file` hold the
    ///   keys of the sign-api axis.
    /// - `verification-spki-ca-file`, `verification-spki-intermediates-file`,
    ///   `verification-spki-eku`, `verification-spki-identity`,
    ///   `verification-spki-crl-file`, and `verification-spki-revocation` set
    ///   the X.509 trust of the spki engine, with the rules of a remote.
    ///
    /// The keys are the keys that the group names, and no other key. The call
    /// reads no system key store, no revoked set, no per-remote keyring, and
    /// no global GPG trusted directory. So the call reads no anchor and no
    /// CRL of the system key store, and the X.509 trust of the group needs
    /// `verification-spki-ca-file`. The axes are ANDed: a commit needs a
    /// valid signature on each axis that the group turns on.
    ///
    /// The keys check the X.509 certificate chains of the spki engine with
    /// [`X509Check::Admission`], as a receive admits a commit, and read the
    /// CRLs as `verification-spki-revocation` sets. The check reports no
    /// warning. A push to the receive endpoint and a one-way receive write
    /// the CRLs that the check keeps to the X.509 CRL cache of the
    /// repository, also for a commit that they refuse.
    ///
    /// The call reads the group from [`Repo::config`], the config that the
    /// open of `repo` read. Each [`Error::InvalidInput`],
    /// [`Error::InvalidFormat`], and [`Error::Unsupported`] refusal comes
    /// before the call reads a key source. An [`Error::Core`] refusal of a
    /// value that does not parse, and an [`Error::Signature`] refusal, can
    /// come after the call reads a key source. The call reads each key source
    /// before it returns, and the keys that it gives read no key source
    /// again.
    ///
    /// With the `receive` feature, `ReceiveVerify::Keys` takes the keys, in
    /// the policy of a client group or in a `StreamRule` of a one-way stream.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if `name` is empty or holds a `"` or a
    ///   control character, or if the config has no group
    ///   `[ex-ostrya trust "NAME"]`.
    /// - [`Error::InvalidFormat`] if the group holds a key that it does not
    ///   take, holds a key that no check reads, turns on no signature check,
    ///   names an engine other than `ed25519` or `spki`, sets
    ///   `gpg-verify=true` and its `gpgkeypath` names no keyring or holds an
    ///   empty entry, or breaks a rule of the X.509 keys of a remote. The
    ///   group also refuses `verification-spki-identity` with no
    ///   `verification-spki-ca-file`, with the text `[ex-ostrya trust "NAME"]
    ///   holds 'verification-spki-identity', and no
    ///   verification-spki-ca-file: a trust group reads no system anchor`.
    /// - [`Error::Unsupported`] if the group sets `gpg-verify=true` in a
    ///   build with no `verify-gpg` feature, names the spki engine in a
    ///   build with no `sign-spki` feature, or sets an X.509 key in a build
    ///   with no `sign-x509` feature.
    /// - [`Error::Core`] if `gpg-verify` is not a boolean, if a value holds a
    ///   malformed escape sequence, or if a key is not valid base64.
    /// - [`Error::Signature`] if:
    ///   - a key source cannot be read
    ///   - an engine refuses a key
    ///   - the path check refuses a certificate file or a CRL file of the
    ///     X.509 keys
    ///   - an engine that `sign-verify` names has no trusted key, or no
    ///     engine has a trusted key
    ///   - the keyrings that `gpgkeypath` names hold no certificate.
    ///
    /// # Examples
    ///
    /// A rule of a one-way stream that verifies each new commit against the
    /// keys of the trust group `release`:
    ///
    /// ```no_run
    /// # #[cfg(feature = "receive")]
    /// use std::sync::Arc;
    ///
    /// use ostrya::Repo;
    /// # #[cfg(feature = "receive")]
    /// use ostrya::receive::{ReceiveVerify, StreamPolicy, StreamRule};
    /// use ostrya::verify::TrustedKeys;
    ///
    /// # async fn run() -> ostrya::Result<()> {
    /// let repo = Repo::open("/srv/repo".as_ref()).await?;
    /// let keys = TrustedKeys::from_trust_group(&repo, "release").await?;
    /// # #[cfg(feature = "receive")]
    /// # {
    /// let policy = StreamPolicy {
    ///     default_rule: StreamRule {
    ///         verify: ReceiveVerify::Keys(Arc::new(keys)),
    ///         ..StreamRule::default()
    ///     },
    ///     ..StreamPolicy::default()
    /// };
    /// # let _ = policy;
    /// # }
    /// # #[cfg(not(feature = "receive"))]
    /// # let _ = keys;
    /// # Ok(()) }
    /// ```
    pub async fn from_trust_group(repo: &Repo, name: &str) -> Result<TrustedKeys> {
        let section = named_group(repo.config(), GroupName::Group(name))?;
        let policy = trust_group_policy(repo, name, &section, true, true, false).await?;
        Ok(TrustedKeys::from_policy(policy))
    }
}

/// The source of the name of a trust group: a pull, or a caller of
/// [`TrustedKeys::from_trust_group`].
#[derive(Debug, Clone, Copy)]
pub(crate) enum GroupName<'a> {
    /// The value of the key `trust` of the section of `remote`.
    Key {
        /// The name of the remote.
        remote: &'a str,
        /// The value of the key.
        value: &'a str,
    },
    /// The value of [`PullOptions::trust_group`](crate::PullOptions::trust_group).
    Field(&'a str),
    /// The argument of [`TrustedKeys::from_trust_group`].
    Group(&'a str),
}

impl GroupName<'_> {
    /// Returns the name of the trust group.
    fn value(&self) -> &str {
        match self {
            GroupName::Key { value, .. } | GroupName::Field(value) | GroupName::Group(value) => {
                value
            }
        }
    }
}

/// The trust group that [`PullOptions::trust_group`](crate::PullOptions::trust_group)
/// names, with the commit policy of the group after a call of [`pull_trust`] built it.
///
/// The commit policy of a group depends on the group and on the commit fields of
/// `PullVerify` alone. A pull gives one value to the trust of each of its remotes, so
/// it reads the key sources of the group one time.
pub(crate) struct FieldGroup<'a> {
    /// The name of the trust group.
    pub(super) name: &'a str,
    /// The commit policy of the group, or `None` before a call built it.
    pub(super) commit: Option<Policy>,
}

impl<'a> FieldGroup<'a> {
    /// Creates the trust group `name`, with no commit policy built.
    pub(crate) fn new(name: &'a str) -> FieldGroup<'a> {
        FieldGroup { name, commit: None }
    }
}

/// Resolves the trust of a pull whose trust group `name` names.
///
/// `remote` is the remote of the pull, if the pull names one, and `section`
/// is its section, if the config has one. The trust group sets the commit
/// policy, and the summary keys of the section set the summary policy. A
/// field `Some(false)` of `verify` turns off its commit axis of the group.
/// The summary fields of `verify` override the summary keys of the section.
/// A pull that names no remote checks no summary.
///
/// The checks come in this order, and each one comes before the call reads a
/// key source:
///
/// 1. the name is a valid group name, and the group exists;
/// 2. [`check_trust`] accepts the group;
/// 3. `verify` does not turn on a commit check;
/// 4. a pull that names no remote does not turn on a summary check;
/// 5. the section turns on no commit check, and holds no key source that no
///    summary check reads;
/// 6. the summary keys of the section that `verify` does not override
///    parse.
///
/// The first check refuses a name of the key `trust` with
/// [`Error::InvalidFormat`], and a name of
/// [`PullOptions::trust_group`](crate::PullOptions::trust_group) with
/// [`Error::InvalidInput`]. The words of each refusal name the source of the
/// name.
///
/// `commit` holds the commit policy of the group if an earlier call with the
/// same group and the same `verify` built it. In that case the call reads no
/// key source of the group. Otherwise the call builds the policy after the
/// checks and keeps it in `commit`.
///
/// `best_effort` is the switch of
/// [`PullTrust::resolve`](super::PullTrust::resolve): with it, the X.509
/// trust of the group and of the summary keys of the section read their CRLs
/// as best-effort.
pub(crate) async fn pull_trust(
    repo: &Repo,
    remote: Option<&str>,
    section: Option<&Section<'_, remote::Group>>,
    name: GroupName<'_>,
    verify: &PullVerify,
    commit: &mut Option<Policy>,
    best_effort: bool,
) -> Result<PullTrust> {
    let value = name.value();
    let trust = named_group(repo.config(), name)?;
    let group = trust.header();
    for (field, check) in [
        (verify.gpg, "the GPG check"),
        (verify.sign, "the sign-api check"),
    ] {
        if field == Some(true) {
            return Err(Error::InvalidInput(match name {
                GroupName::Key { remote, .. } => format!(
                    "remote '{remote}' takes its commit keys from [{group}], so a pull \
                     cannot turn on {check} of the commits"
                ),
                GroupName::Field(_) | GroupName::Group(_) => format!(
                    "the pull takes its commit keys from [{group}], so it cannot turn on \
                     {check} of the commits"
                ),
            }));
        }
    }
    // With no remote, no section supplies the keys of a summary check.
    if remote.is_none() && (verify.gpg_summary == Some(true) || verify.sign_summary == Some(true)) {
        return Err(no_remote());
    }
    if let (Some(remote), Some(section)) = (remote, section) {
        refuse_void_key(remote, section, name, group)?;
    }
    let (gpg_summary, sign_summary) = summary_switches(section, verify)?;

    let commit = match commit.as_ref() {
        Some(policy) => policy.clone(),
        None => commit
            .insert(
                trust_group_policy(
                    repo,
                    value,
                    &trust,
                    verify.gpg != Some(false),
                    verify.sign != Some(false),
                    best_effort,
                )
                .await?,
            )
            .clone(),
    };
    let summary = match remote {
        Some(remote) => {
            let source = KeySource::Remote {
                name: remote,
                section,
                repo_keyring: true,
                system_keys: true,
                roots: &SYSTEM_KEY_ROOTS,
                check: X509Check::Admission,
                best_effort,
            };
            build_policy(
                repo,
                &source,
                &mut Verifiers::default(),
                gpg_summary,
                &sign_summary,
            )
            .await?
        }
        None => Policy::default(),
    };
    Ok(PullTrust {
        commit: commit.applies().then(|| TrustedKeys::from_policy(commit)),
        summary: summary.applies().then(|| TrustedKeys::from_policy(summary)),
    })
}

/// Checks the trust group that `name` names in `config`, and returns its
/// section.
///
/// The checks are the first two checks of [`pull_trust`], and the checks of
/// [`TrustedKeys::from_trust_group`] before it reads a key source: the name
/// is a valid group name, the group exists, and [`check_trust`] accepts the
/// group.
fn named_group<'a>(
    config: &'a RepoConfig,
    name: GroupName<'_>,
) -> Result<Section<'a, trust::Group>> {
    let value = name.value();
    let group = || format!("ex-ostrya trust \"{value}\"");
    // The value type of the key `trust` refuses a malformed name of the key.
    if !matches!(name, GroupName::Key { .. }) && !valid_group_name(value) {
        return Err(Error::InvalidInput(format!(
            "malformed trust group name '{value}': the name is not empty, and holds no '\"' \
             and no control character"
        )));
    }
    let Some(section) = config.section::<trust::Group>(value) else {
        return Err(match name {
            GroupName::Key { remote, .. } => Error::InvalidFormat(format!(
                "[remote \"{remote}\"] trust={value} names no [{}] group",
                group()
            )),
            GroupName::Field(_) => Error::InvalidInput(format!(
                "the pull names the trust group '{value}', and the config has no [{}] group",
                group()
            )),
            GroupName::Group(_) => {
                Error::InvalidInput(format!("the config has no [{}] group", group()))
            }
        });
    };
    check_trust(&section)?;
    Ok(section)
}

/// Refuses the section `section` of `remote` if it holds a key that the trust
/// group `group`, which `name` names, makes void.
fn refuse_void_key(
    remote: &str,
    section: &Section<'_, remote::Group>,
    name: GroupName<'_>,
    group: &str,
) -> Result<()> {
    let Some(VoidKey { holds, key, reason }) = void_commit_key(section)? else {
        return Ok(());
    };
    let value = name.value();
    Err(Error::InvalidFormat(match name {
        GroupName::Key { .. } => {
            let verb = if holds { "holds " } else { "" };
            format!("[remote \"{remote}\"] sets trust={value} and {verb}{key}{reason}")
        }
        GroupName::Field(_) | GroupName::Group(_) => {
            let verb = if holds { "holds" } else { "sets" };
            format!(
                "the pull takes its commit keys from [{group}], and [remote \"{remote}\"] \
                 {verb} {key}{reason}"
            )
        }
    }))
}

/// Checks the trust group that the key `trust` of the section `section` of
/// `remote` names, as a pull of `remote` checks it, and returns the section
/// of the group.
///
/// `value` is the value of the key. The call refuses the section if it holds
/// a key that the group makes void. It reads no key source.
pub(crate) fn check_remote_group<'a>(
    repo: &'a Repo,
    remote: &str,
    section: &Section<'_, remote::Group>,
    value: &str,
) -> Result<Section<'a, trust::Group>> {
    let name = GroupName::Key { remote, value };
    let trust = named_group(repo.config(), name)?;
    refuse_void_key(remote, section, name, trust.header())?;
    Ok(trust)
}

/// Returns `true` if `name` is a valid name of a trust group or of a key
/// group: it is not empty, and holds no `"` and no control character.
pub(crate) fn valid_group_name(name: &str) -> bool {
    !name.is_empty() && !name.contains('"') && !name.contains(char::is_control)
}

/// A key of a remote section that a trust group makes void.
struct VoidKey {
    /// `true` if the section holds the key, and `false` if the section
    /// sets the key to the value that `key` names.
    holds: bool,
    /// The key, as the refusal names it.
    key: String,
    /// The reason of the refusal, with its leading punctuation.
    reason: String,
}

/// Returns the first key of the remote section `section` that a trust group
/// makes void: a key that turns on a commit check, or a key source that no
/// summary check reads. `None` if the section holds no such key.
///
/// The rule reads the summary keys of the section, and no override of a pull.
fn void_commit_key(section: &Section<'_, remote::Group>) -> Result<Option<VoidKey>> {
    let sets = |key: String, reason: &str| {
        Some(VoidKey {
            holds: false,
            key,
            reason: reason.to_owned(),
        })
    };
    if section.file_value::<remote::GpgVerify>()? == Some(true) {
        return Ok(sets(
            "gpg-verify=true".to_owned(),
            ": the trust group sets the commit checks, so set gpg-verify=false or \
             remove the key",
        ));
    }
    if section.get::<remote::SignVerify>()? != SignVerify::Off {
        let raw = section
            .raw_value::<remote::SignVerify>()
            .unwrap_or_default();
        return Ok(sets(
            format!("sign-verify={raw}"),
            ": the trust group sets the commit checks, so remove sign-verify",
        ));
    }
    if section.contains::<remote::GpgKeyPath>() && !section.get::<remote::GpgVerifySummary>()? {
        return Ok(sets(
            "gpgkeypath".to_owned(),
            ", and gpg-verify-summary is not true, so no check reads it",
        ));
    }
    let summary = section.get::<remote::SignVerifySummary>()?;
    let engines: Vec<&str> = match &summary {
        SignVerify::Off => Vec::new(),
        SignVerify::All => TRUST_ENGINES.to_vec(),
        SignVerify::Engines(names) => names.iter().map(String::as_str).collect(),
    };
    for key in section.key_names() {
        if let Some(engine) = verification_engine(key)
            && !engines.contains(&engine)
        {
            return Ok(Some(VoidKey {
                holds: true,
                key: format!("'{key}'"),
                reason: format!(
                    ", and sign-verify-summary does not select {engine}, so no check \
                     reads it"
                ),
            }));
        }
    }
    Ok(None)
}

/// Checks the trust group `section`.
///
/// Each key must be one that an axis reads. The group must turn on at least
/// one axis. The X.509 keys of the spki engine follow the rules of a remote,
/// and `verification-spki-identity` needs `verification-spki-ca-file`,
/// because a trust group reads no anchor of the system key store.
pub(crate) fn check_trust(section: &Section<'_, trust::Group>) -> Result<()> {
    refuse_foreign_keys(section)?;
    let group = section.header();
    // After the check of the key names, each verification key names an
    // engine of a trust group.
    let engine_keys: Vec<(&str, &str)> = section
        .key_names()
        .filter_map(|key| verification_engine(key).map(|engine| (key, engine)))
        .collect();

    let gpg = section.get::<trust::GpgVerify>()?;
    let sign = section.get::<trust::SignVerify>()?;
    let engines: Vec<&str> = match &sign {
        SignVerify::Off => Vec::new(),
        SignVerify::All => TRUST_ENGINES.to_vec(),
        SignVerify::Engines(names) => names.iter().map(String::as_str).collect(),
    };
    for engine in &engines {
        if !TRUST_ENGINES.contains(engine) {
            return Err(Error::InvalidFormat(format!(
                "[{group}] sign-verify names '{engine}', which is not ed25519 or spki"
            )));
        }
    }
    if !gpg && engines.is_empty() {
        return Err(Error::InvalidFormat(format!(
            "[{group}] turns on no signature check: set gpg-verify=true or sign-verify"
        )));
    }

    let keypath = section.contains::<trust::GpgKeyPath>();
    if keypath && !gpg {
        return Err(Error::InvalidFormat(format!(
            "[{group}] sets gpgkeypath, and gpg-verify is not true, so no check reads it"
        )));
    }
    // `sign-verify=true` names every engine of the build, so it names spki
    // only in a build that has it.
    let names_spki = matches!(&sign, SignVerify::Engines(names) if names.iter().any(|n| n == "spki"))
        || engine_keys.iter().any(|(_, engine)| *engine == "spki");
    if cfg!(not(feature = "sign-spki")) && names_spki {
        return Err(Error::Unsupported(format!(
            "[{group}] names the spki engine, which this build has no engine for; \
             build with the sign-spki feature"
        )));
    }
    section.check_x509()?;
    let x509 = engine_keys
        .iter()
        .any(|(key, _)| SPKI_X509_KEYS.contains(key));
    if cfg!(not(feature = "sign-x509")) && x509 {
        return Err(Error::Unsupported(format!(
            "[{group}] sets an X.509 trust of the spki engine, which this build has no path \
             check for; build with the sign-x509 feature"
        )));
    }
    if section.contains::<trust::VerificationSpkiIdentity>()
        && !section.contains::<trust::VerificationSpkiCaFile>()
    {
        return Err(Error::InvalidFormat(format!(
            "[{group}] holds 'verification-spki-identity', and no verification-spki-ca-file: \
             a trust group reads no system anchor"
        )));
    }
    for (key, engine) in engine_keys {
        if !engines.contains(&engine) {
            return Err(Error::InvalidFormat(format!(
                "[{group}] holds '{key}', and sign-verify does not select {engine}, so \
                 no check reads it"
            )));
        }
        if key.ends_with("-file") {
            section.verification_file(engine)?;
        }
    }
    if gpg {
        if cfg!(not(feature = "verify-gpg")) {
            return Err(Error::Unsupported(format!(
                "[{group}] asks for GPG verification, which this build has no engine \
                 for; build with the verify-gpg feature"
            )));
        }
        let keypath = section.get::<trust::GpgKeyPath>()?.into_entries();
        if keypath.is_empty() {
            return Err(Error::InvalidFormat(format!(
                "[{group}] sets gpg-verify=true, and gpgkeypath names no keyring"
            )));
        }
        if keypath.iter().any(String::is_empty) {
            return Err(Error::InvalidFormat(format!(
                "[{group}] gpgkeypath holds an empty entry"
            )));
        }
    }
    Ok(())
}

#[cfg(test)]
pub(crate) mod tests {
    use std::sync::{Arc, Mutex};
    use std::thread::ThreadId;

    use ostrya_core::{KeyFile, Value};

    use super::*;
    use crate::sign::{Ed25519Signer, Signer, append_signature};
    use crate::verify::CrlScope;
    use crate::{CreateOptions, RepoMode};

    /// The base64 of a 64-byte ed25519 secret key (seed, then public key).
    const SECRET_B64: &str =
        "o74ME/dmhvDeYf64dDJQY8kX2piK0M/nyIRWVi30i6DCOzRsHVcvgYToz6zOb5OvK/v8nH6KfLR3dfdsn6ZSyQ==";
    /// The matching 32-byte ed25519 public key.
    const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
    /// Another ed25519 secret key.
    const OTHER_SECRET_B64: &str =
        "5ILWxT+l9G/u3h0BptRpmSi35C9uog7YDdD+Fp1Xk+Hz52p0NlYh6xBA73kJEJKhKbbnjcE0rsWA5XA/K5Sq5Q==";

    pub(crate) const PAYLOAD: &[u8] = b"the commit bytes";

    /// A scratch directory with an archive repository at `repo`. The guard
    /// removes the directory when it drops.
    struct Scratch {
        dir: std::path::PathBuf,
    }

    impl Scratch {
        fn new(label: &str) -> Scratch {
            let dir = std::env::temp_dir().join(format!(
                "ostrya-trust-{label}-{}-{}",
                std::process::id(),
                crate::write::unique()
            ));
            std::fs::create_dir_all(&dir).unwrap();
            Scratch { dir }
        }

        fn repo(&self) -> Repo {
            ostrya_rt::block_on(Repo::create(
                &self.dir.join("repo"),
                CreateOptions::new(RepoMode::Archive),
            ))
            .unwrap()
        }
    }

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

    /// A detached-metadata dict that holds `blob` under `key`.
    pub(crate) fn dict_with(key: &str, blob: Vec<u8>) -> Value {
        let mut dict = Value::Array(Vec::new());
        append_signature(&mut dict, key, blob).unwrap();
        dict
    }

    /// The address of the data and a copy of the data of one call to
    /// `verify`.
    pub(crate) type SeenPayload = (usize, Vec<u8>);

    /// A verifier that accepts or rejects each blob and records the thread and
    /// the data of each call.
    ///
    /// A clone shares the record, so a test keeps a handle on the record after
    /// it gives the verifier away.
    #[derive(Clone)]
    pub(crate) struct ThreadRecorder {
        /// The detached-metadata key that the verifier reads.
        key: &'static str,
        /// If `true`, the verifier accepts a blob. If `false`, it rejects each
        /// blob.
        valid: bool,
        /// The thread of each call to `verify`, in order.
        threads: Arc<Mutex<Vec<ThreadId>>>,
        /// The address of the data and a copy of the data of each call to
        /// `verify`, in order.
        payloads: Arc<Mutex<Vec<SeenPayload>>>,
    }

    impl ThreadRecorder {
        /// Creates a recorder that reads the blobs under `key` and accepts
        /// them.
        pub(crate) fn new(key: &'static str) -> ThreadRecorder {
            ThreadRecorder {
                key,
                valid: true,
                threads: Arc::default(),
                payloads: Arc::default(),
            }
        }

        /// Creates a recorder that reads the blobs under `key` and rejects
        /// them.
        pub(crate) fn rejecting(key: &'static str) -> ThreadRecorder {
            ThreadRecorder {
                valid: false,
                ..ThreadRecorder::new(key)
            }
        }

        /// Returns the thread of each call to `verify`, in order.
        pub(crate) fn threads(&self) -> Vec<ThreadId> {
            self.threads.lock().unwrap().clone()
        }

        /// Returns the address of the data and a copy of the data of each
        /// call to `verify`, in order.
        pub(crate) fn payloads(&self) -> Vec<SeenPayload> {
            self.payloads.lock().unwrap().clone()
        }

        /// Asserts that one call to `verify` ran, on a thread other than the
        /// thread of the test.
        pub(crate) fn assert_one_foreign_call(&self) {
            let threads = self.threads();
            assert_eq!(threads.len(), 1, "{threads:?}");
            assert_ne!(threads[0], std::thread::current().id());
        }

        /// Asserts that each call to `verify` got `data` at its address, with
        /// no copy.
        pub(crate) fn assert_no_copy_of(&self, data: &[u8]) {
            let payloads = self.payloads();
            assert!(!payloads.is_empty());
            for (address, bytes) in payloads {
                assert_eq!(address, data.as_ptr() as usize);
                assert_eq!(bytes, data);
            }
        }
    }

    impl crate::sign::Verifier for ThreadRecorder {
        fn metadata_key(&self) -> &str {
            self.key
        }

        fn verify(
            &self,
            data: &[u8],
            signatures: &[Vec<u8>],
        ) -> ostrya_sign::Result<crate::sign::VerifyOutcome> {
            self.threads
                .lock()
                .unwrap()
                .push(std::thread::current().id());
            self.payloads
                .lock()
                .unwrap()
                .push((data.as_ptr() as usize, data.to_vec()));
            let mut outcome = crate::sign::VerifyOutcome::default();
            outcome.valid = self.valid && !signatures.is_empty();
            Ok(outcome)
        }
    }

    /// The ed25519 signature of `secret` over [`PAYLOAD`], in its dict.
    fn ed25519_signed(secret: &str) -> Value {
        let signer = Ed25519Signer::from_base64(secret).unwrap();
        let blob = ostrya_rt::block_on(signer.sign(PAYLOAD)).unwrap();
        dict_with(signer.metadata_key(), blob)
    }

    /// A trust group verifies a commit against the key that it names. A
    /// signature from this key passes. A commit with no signature fails, and a
    /// signature from another key fails.
    #[test]
    fn a_trust_group_checks_a_commit() {
        let scratch = Scratch::new("group");
        let repo = scratch.repo();
        let group = "ex-ostrya trust \"t\"";
        let keyfile = KeyFile::parse(&format!(
            "[{group}]\nsign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n"
        ))
        .unwrap();
        let policy = ostrya_rt::block_on(trust_group_policy(
            &repo,
            "t",
            &Section::from_parts(&keyfile, group, None),
            true,
            true,
            false,
        ))
        .unwrap();
        let own = ed25519_signed(SECRET_B64);
        let other = ed25519_signed(OTHER_SECRET_B64);
        let (valid, unsigned, untrusted) = ostrya_rt::block_on(async {
            (
                policy
                    .check("commit", PAYLOAD, Some(&own), &CrlScope::default())
                    .await,
                policy
                    .check("commit", PAYLOAD, None, &CrlScope::default())
                    .await,
                policy
                    .check("commit", PAYLOAD, Some(&other), &CrlScope::default())
                    .await,
            )
        });
        valid.expect("a signature from the named key passes");
        let err = unsigned.unwrap_err();
        assert!(err.to_string().contains("carries no signature"), "{err}");
        let err = untrusted.unwrap_err();
        assert!(
            err.to_string()
                .contains("no sign-api signature is from a trusted key"),
            "{err}"
        );
    }

    /// A trust group refuses an engine with no key. The system key store does
    /// not supply a key for the engine.
    #[test]
    fn a_trust_group_engine_needs_a_key() {
        let scratch = Scratch::new("nokey");
        let repo = scratch.repo();
        let group = "ex-ostrya trust \"t\"";
        let keyfile = KeyFile::parse(&format!("[{group}]\nsign-verify=ed25519\n")).unwrap();
        let Err(err) = ostrya_rt::block_on(trust_group_policy(
            &repo,
            "t",
            &Section::from_parts(&keyfile, group, None),
            true,
            true,
            false,
        )) else {
            panic!("an engine with no key is refused");
        };
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("no trusted key for signature engine 'ed25519'")),
            "{err}"
        );
    }

    /// The build of a trust group builds only the axes that stay on, and
    /// reads no key source of an axis that is off. With both axes off, the
    /// policy holds no axis.
    #[test]
    fn a_trust_group_builds_the_axes_that_stay_on() {
        let scratch = Scratch::new("axes");
        let repo = scratch.repo();
        let group = "ex-ostrya trust \"t\"";
        // The keyring path does not exist, so a build of the GPG axis fails.
        let keyfile = KeyFile::parse(&format!(
            "[{group}]\ngpg-verify=true\ngpgkeypath={}\n\
             sign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n",
            scratch.dir.join("absent.gpg").display()
        ))
        .unwrap();
        let build = |gpg_on: bool, sign_on: bool| {
            ostrya_rt::block_on(trust_group_policy(
                &repo,
                "t",
                &Section::from_parts(&keyfile, group, None),
                gpg_on,
                sign_on,
                false,
            ))
        };

        let sign = build(false, true).expect("the GPG axis is off, so no keyring is read");
        assert!(!sign.gpg_axis());
        assert_eq!(sign.sign_axis().map(<[_]>::len), Some(1));
        let own = ed25519_signed(SECRET_B64);
        ostrya_rt::block_on(sign.check("commit", PAYLOAD, Some(&own), &CrlScope::default()))
            .expect("the sign-api axis reads the key of the group");

        let none = build(false, false).unwrap();
        assert!(!none.applies());

        let Err(err) = build(true, false) else {
            panic!("the GPG axis reads the keyring that the group names");
        };
        #[cfg(feature = "verify-gpg")]
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("absent.gpg")),
            "{err}"
        );
        #[cfg(not(feature = "verify-gpg"))]
        assert!(matches!(&err, Error::Unsupported(_)), "{err}");
    }

    /// Returns `true` if `gpg` answers.
    ///
    /// If `gpg` does not answer, a test that needs it skips. If
    /// `OSTRYA_REQUIRE_GNUPG` is set, the absence of `gpg` fails the test.
    #[cfg(feature = "verify-gpg")]
    fn gpg_or_skip() -> bool {
        if crate::gpg::tests::gpg_available() {
            return true;
        }
        assert!(
            std::env::var_os("OSTRYA_REQUIRE_GNUPG").is_none(),
            "OSTRYA_REQUIRE_GNUPG is set and `gpg` is not available"
        );
        eprintln!("skipping: gpg not available");
        false
    }

    /// The environment variable that tells the child process of
    /// [`the_global_gpg_directory_is_not_part_of_a_trust_group`] where its
    /// fixtures are.
    #[cfg(feature = "verify-gpg")]
    const FIXTURE_ENV: &str = "OSTRYA_TRUST_TEST_FIXTURES";

    /// The global GPG trusted directory, which `OSTREE_GPG_HOME` names, is not
    /// part of a trust group. The test sets the environment for a child
    /// process, so no test of this process reads the directory.
    #[cfg(feature = "verify-gpg")]
    #[test]
    fn the_global_gpg_directory_is_not_part_of_a_trust_group() {
        use crate::gpg::tests::KeyFixture;

        if !gpg_or_skip() {
            return;
        }
        let key = KeyFixture::new("Global <global@example.org>");
        let stranger = KeyFixture::new("Stranger <stranger@example.org>");
        let scratch = Scratch::new("global");
        let global = scratch.dir.join("global");
        std::fs::create_dir(&global).unwrap();
        std::fs::write(global.join("global.gpg"), key.export(false)).unwrap();
        std::fs::write(scratch.dir.join("own.gpg"), key.export(false)).unwrap();
        std::fs::write(scratch.dir.join("stranger.gpg"), stranger.export(false)).unwrap();
        std::fs::write(scratch.dir.join("signature"), key.sign(PAYLOAD)).unwrap();

        let child = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "verify::trust::tests::global_gpg_directory_subprocess",
                "--exact",
                "--ignored",
                "--nocapture",
            ])
            .env("OSTREE_GPG_HOME", &global)
            .env(FIXTURE_ENV, &scratch.dir)
            .output()
            .expect("re-execute this test binary");
        let stdout = String::from_utf8_lossy(&child.stdout);
        assert!(
            child.status.success() && stdout.contains("1 passed"),
            "the child reported {}:\n{stdout}{}",
            child.status,
            String::from_utf8_lossy(&child.stderr),
        );
    }

    /// The half of [`the_global_gpg_directory_is_not_part_of_a_trust_group`]
    /// that builds the trusted keys. It runs only if this test binary runs
    /// again with the environment set.
    ///
    /// A trust group whose keyring holds the key of the signature passes, so
    /// the signature is valid. A trust group whose keyring holds another key
    /// fails, and the global directory does not supply the key.
    #[cfg(feature = "verify-gpg")]
    #[test]
    #[ignore = "helper process for the_global_gpg_directory_is_not_part_of_a_trust_group"]
    fn global_gpg_directory_subprocess() {
        let Some(fixtures) = std::env::var_os(FIXTURE_ENV).map(std::path::PathBuf::from) else {
            return;
        };
        let signed = dict_with(
            "ostree.gpgsigs",
            std::fs::read(fixtures.join("signature")).unwrap(),
        );
        let scratch = Scratch::new("global-child");
        let repo = scratch.repo();
        let check = |keyring: &str| {
            let group = "ex-ostrya trust \"t\"";
            let keyfile = KeyFile::parse(&format!(
                "[{group}]\ngpg-verify=true\ngpgkeypath={}\n",
                fixtures.join(keyring).display()
            ))
            .unwrap();
            ostrya_rt::block_on(async {
                trust_group_policy(
                    &repo,
                    "t",
                    &Section::from_parts(&keyfile, group, None),
                    true,
                    true,
                    false,
                )
                .await
                .unwrap()
                .check("commit", PAYLOAD, Some(&signed), &CrlScope::default())
                .await
            })
        };
        check("own.gpg").expect("the keyring of the group holds the key");
        let err = check("stranger.gpg").expect_err("a trust group reads no global directory");
        assert!(matches!(err, Error::Signature(_)), "{err}");
    }

    /// Opens the repository of `scratch` with `remotes` added to its config.
    fn repo_with_remotes(scratch: &Scratch, remotes: &str) -> Repo {
        drop(scratch.repo());
        let config = scratch.dir.join("repo/config");
        let mut text = std::fs::read_to_string(&config).unwrap();
        text.push_str(remotes);
        std::fs::write(&config, text).unwrap();
        ostrya_rt::block_on(Repo::open(&scratch.dir.join("repo"))).unwrap()
    }

    /// `RemoteKeys` reads the commit switches for the commits and the summary
    /// switches for the summary. It refuses a target that the switches do not
    /// check, a remote with no section, and a name that is not valid.
    #[test]
    fn remote_keys_follow_the_switches_of_each_target() {
        use crate::verify::RemoteKeys;

        let scratch = Scratch::new("remote-keys");
        let repo = repo_with_remotes(
            &scratch,
            &format!(
                "[remote \"origin\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n\
                 [remote \"plain\"]\nurl=http://localhost/\ngpg-verify=false\n"
            ),
        );
        let keys = ostrya_rt::block_on(RemoteKeys::commits(&repo, "origin", None)).unwrap();
        assert!(
            keys.gpg().is_none(),
            "gpg-verify=false gives no GPG verifier"
        );
        let engines: Vec<&str> = keys.sign().iter().map(|v| v.metadata_key()).collect();
        assert_eq!(engines, ["ostree.sign.ed25519"]);

        let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
        let blob = ostrya_rt::block_on(signer.sign(PAYLOAD)).unwrap();
        assert!(keys.sign()[0].verify(PAYLOAD, &[blob]).unwrap().valid);

        for err in [
            ostrya_rt::block_on(RemoteKeys::summary(&repo, "origin", None)).unwrap_err(),
            ostrya_rt::block_on(RemoteKeys::commits(&repo, "plain", None)).unwrap_err(),
        ] {
            assert!(
                matches!(&err, Error::Signature(m) if m.contains("turns on no signature check")),
                "{err}"
            );
        }
        let err = ostrya_rt::block_on(RemoteKeys::commits(&repo, "nosuch", None)).unwrap_err();
        assert!(matches!(err, Error::RemoteNotFound(_)), "{err}");
        let err = ostrya_rt::block_on(RemoteKeys::commits(&repo, "a/b", None)).unwrap_err();
        assert!(matches!(err, Error::InvalidInput(_)), "{err}");
    }

    /// A selection of engines builds the selected engines alone. The call
    /// reads no key source of an engine that it does not select, and refuses
    /// an engine that the switches do not turn on before it reads a key.
    #[cfg(feature = "verify-gpg")]
    #[test]
    fn remote_keys_build_the_selected_engines_alone() {
        use crate::verify::RemoteKeys;

        let scratch = Scratch::new("remote-keys-select");
        let missing = scratch.dir.join("missing");
        let repo = repo_with_remotes(
            &scratch,
            &format!(
                "[remote \"both\"]\nurl=http://localhost/\ngpgkeypath={}\n\
                 sign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n\
                 [remote \"all\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=true\nverification-ed25519-file={}\n",
                missing.join("keyring.gpg").display(),
                missing.join("ed25519.keys").display(),
            ),
        );
        let keys =
            ostrya_rt::block_on(RemoteKeys::commits(&repo, "both", Some(&["ed25519"]))).unwrap();
        assert!(keys.gpg().is_none(), "gpg is not selected");
        let engines: Vec<&str> = keys.sign().iter().map(|v| v.metadata_key()).collect();
        assert_eq!(engines, ["ostree.sign.ed25519"]);

        for (remote, names, text) in [
            (
                "both",
                &["spki"][..],
                "turns on no spki check of its commits",
            ),
            ("all", &["gpg"][..], "turns on no gpg check of its commits"),
            (
                "both",
                &["ed25519"][..],
                "turns on no ed25519 check of its summary",
            ),
        ] {
            let summary = text.ends_with("summary");
            let err = ostrya_rt::block_on(async {
                if summary {
                    RemoteKeys::summary(&repo, remote, Some(names)).await
                } else {
                    RemoteKeys::commits(&repo, remote, Some(names)).await
                }
            })
            .unwrap_err();
            assert!(
                matches!(&err, Error::Signature(m) if m.contains(text)),
                "{remote} {names:?}: {err}"
            );
        }
        let err =
            ostrya_rt::block_on(RemoteKeys::commits(&repo, "both", Some(&["gpg"]))).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("gpgkeypath")),
            "the selected GPG engine reads gpgkeypath: {err}"
        );
        let err =
            ostrya_rt::block_on(RemoteKeys::commits(&repo, "all", Some(&["ed25519"]))).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("ed25519.keys")),
            "the selected engine reads its key file: {err}"
        );
    }

    /// With the key `trust`, the commit keys of `RemoteKeys` come from the
    /// trust group. The summary keys come from the section, and a section
    /// that a trust group makes void is refused for both targets.
    #[test]
    fn remote_keys_read_the_trust_group_for_the_commits() {
        use crate::verify::RemoteKeys;

        let scratch = Scratch::new("remote-keys-trust");
        let repo = repo_with_remotes(
            &scratch,
            &format!(
                "[remote \"t\"]\nurl=http://localhost/\ntrust=g\ngpg-verify=false\n\
                 [remote \"void\"]\nurl=http://localhost/\ntrust=g\ngpg-verify=true\n\
                 [ex-ostrya trust \"g\"]\nsign-verify=ed25519\n\
                 verification-ed25519-key={PUBLIC_B64}\n"
            ),
        );
        let keys = ostrya_rt::block_on(RemoteKeys::commits(&repo, "t", None)).unwrap();
        assert!(keys.gpg().is_none());
        assert_eq!(keys.sign().len(), 1);
        let err = ostrya_rt::block_on(RemoteKeys::summary(&repo, "t", None)).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("of its summary")),
            "{err}"
        );
        for err in [
            ostrya_rt::block_on(RemoteKeys::commits(&repo, "void", None)).unwrap_err(),
            ostrya_rt::block_on(RemoteKeys::summary(&repo, "void", None)).unwrap_err(),
        ] {
            assert!(
                matches!(&err, Error::InvalidFormat(m) if m.contains("gpg-verify=true")),
                "{err}"
            );
        }
    }

    /// `RemoteKeys` reads no global GPG trusted directory. A remote with the
    /// GPG check on and no keyring of its own is refused, where the trust of
    /// a pull reads the key from the global directory. The test sets the
    /// environment for a child process, so no test of this process reads the
    /// directory.
    #[cfg(feature = "verify-gpg")]
    #[test]
    fn remote_keys_read_no_global_gpg_directory() {
        use crate::gpg::tests::KeyFixture;

        if !gpg_or_skip() {
            return;
        }
        let key = KeyFixture::new("Global <global@example.org>");
        let scratch = Scratch::new("remote-keys-global");
        let global = scratch.dir.join("global");
        std::fs::create_dir(&global).unwrap();
        std::fs::write(global.join("global.gpg"), key.export(false)).unwrap();
        std::fs::write(scratch.dir.join("own.gpg"), key.export(false)).unwrap();
        std::fs::write(scratch.dir.join("signature"), key.sign(PAYLOAD)).unwrap();

        let child = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "verify::trust::tests::remote_keys_global_gpg_subprocess",
                "--exact",
                "--ignored",
                "--nocapture",
            ])
            .env("OSTREE_GPG_HOME", &global)
            .env(FIXTURE_ENV, &scratch.dir)
            .output()
            .expect("re-execute this test binary");
        let stdout = String::from_utf8_lossy(&child.stdout);
        assert!(
            child.status.success() && stdout.contains("1 passed"),
            "the child reported {}:\n{stdout}{}",
            child.status,
            String::from_utf8_lossy(&child.stderr),
        );
    }

    /// The half of [`remote_keys_read_no_global_gpg_directory`] that reads
    /// the keys. It runs only if this test binary runs again with the
    /// environment set.
    #[cfg(feature = "verify-gpg")]
    #[test]
    #[ignore = "helper process for remote_keys_read_no_global_gpg_directory"]
    fn remote_keys_global_gpg_subprocess() {
        use crate::pull::PullVerify;
        use crate::verify::RemoteKeys;

        let Some(fixtures) = std::env::var_os(FIXTURE_ENV).map(std::path::PathBuf::from) else {
            return;
        };
        let signature = std::fs::read(fixtures.join("signature")).unwrap();
        let scratch = Scratch::new("remote-keys-global-child");
        let repo = repo_with_remotes(
            &scratch,
            &format!(
                "[remote \"bare\"]\nurl=http://localhost/\n\
                 [remote \"own\"]\nurl=http://localhost/\ngpgkeypath={}\n",
                fixtures.join("own.gpg").display()
            ),
        );
        let err = ostrya_rt::block_on(RemoteKeys::commits(&repo, "bare", None)).unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("hold no certificate")),
            "{err}"
        );
        let signed = dict_with("ostree.gpgsigs", signature.clone());
        let pull = ostrya_rt::block_on(PullTrust::from_remote(
            &repo,
            "bare",
            &PullVerify::default(),
        ))
        .unwrap();
        ostrya_rt::block_on(pull.into_policies().0.check(
            "commit",
            PAYLOAD,
            Some(&signed),
            &CrlScope::default(),
        ))
        .expect("the trust of a pull reads the global directory");

        let keys = ostrya_rt::block_on(RemoteKeys::commits(&repo, "own", None)).unwrap();
        let gpg = keys.gpg().expect("gpg-verify defaults to true");
        assert!(gpg.verify(PAYLOAD, &[signature]).unwrap().valid);
        assert!(keys.sign().is_empty());
    }

    /// `TrustedKeys::from_trust_group` reads the keys of the group that it
    /// names. A signature from the key of the group passes. A commit with no
    /// signature fails, and a signature from another key fails.
    #[test]
    fn from_trust_group_verifies_a_commit() {
        let scratch = Scratch::new("from-group");
        let repo = repo_with_remotes(
            &scratch,
            &format!(
                "[ex-ostrya trust \"t\"]\nsign-verify=ed25519\n\
                 verification-ed25519-key={PUBLIC_B64}\n"
            ),
        );
        let policy = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, "t"))
            .unwrap()
            .into_policy();
        let own = ed25519_signed(SECRET_B64);
        let other = ed25519_signed(OTHER_SECRET_B64);
        let (valid, unsigned, untrusted) = ostrya_rt::block_on(async {
            (
                policy
                    .check("commit", PAYLOAD, Some(&own), &CrlScope::default())
                    .await,
                policy
                    .check("commit", PAYLOAD, None, &CrlScope::default())
                    .await,
                policy
                    .check("commit", PAYLOAD, Some(&other), &CrlScope::default())
                    .await,
            )
        });
        valid.expect("a signature from the key of the group passes");
        let err = unsigned.unwrap_err();
        assert!(err.to_string().contains("carries no signature"), "{err}");
        let err = untrusted.unwrap_err();
        assert!(
            err.to_string()
                .contains("no sign-api signature is from a trusted key"),
            "{err}"
        );
    }

    /// `TrustedKeys::from_trust_group` refuses a name that is empty or holds
    /// a `"` or a control character with `Error::InvalidInput`.
    #[test]
    fn from_trust_group_refuses_a_malformed_name() {
        let scratch = Scratch::new("from-group-name");
        let repo = scratch.repo();
        for name in ["", "a\"b", "a\nb"] {
            let err = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, name)).unwrap_err();
            let Error::InvalidInput(m) = &err else {
                panic!("{name:?}: {err}");
            };
            assert_eq!(
                m,
                &format!(
                    "malformed trust group name '{name}': the name is not empty, and holds \
                     no '\"' and no control character"
                )
            );
        }
    }

    /// `TrustedKeys::from_trust_group` refuses a name of a group that the
    /// config does not hold with `Error::InvalidInput`. The words name the
    /// group and do not name a pull.
    #[test]
    fn from_trust_group_refuses_an_absent_group() {
        let scratch = Scratch::new("from-group-absent");
        let repo = repo_with_remotes(
            &scratch,
            &format!(
                "[ex-ostrya trust \"t\"]\nsign-verify=ed25519\n\
                 verification-ed25519-key={PUBLIC_B64}\n"
            ),
        );
        let err = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, "u")).unwrap_err();
        let Error::InvalidInput(m) = &err else {
            panic!("{err}");
        };
        assert_eq!(m, "the config has no [ex-ostrya trust \"u\"] group");
        assert!(!m.contains("pull"), "{m}");
    }

    /// `TrustedKeys::from_trust_group` refuses a group that fails the check
    /// of a trust group. The refusal comes before the call reads a key
    /// source: the group names a keyring and a key file that do not exist,
    /// and the error is the error of the check.
    #[test]
    fn from_trust_group_refuses_a_malformed_group() {
        let scratch = Scratch::new("from-group-malformed");
        let repo = repo_with_remotes(
            &scratch,
            &format!(
                "[ex-ostrya trust \"empty\"]\n\
                 [ex-ostrya trust \"summary\"]\ngpg-verify=true\ngpgkeypath={}\n\
                 sign-verify=ed25519\nverification-ed25519-file={}\n\
                 gpg-verify-summary=true\n",
                scratch.dir.join("absent.gpg").display(),
                scratch.dir.join("absent.keys").display(),
            ),
        );
        for (name, text) in [
            (
                "empty",
                "[ex-ostrya trust \"empty\"] turns on no signature check: set \
                 gpg-verify=true or sign-verify",
            ),
            (
                "summary",
                "[ex-ostrya trust \"summary\"] holds 'gpg-verify-summary', and a trust \
                 group sets a commit policy alone",
            ),
        ] {
            let err = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, name)).unwrap_err();
            assert!(
                matches!(&err, Error::InvalidFormat(m) if m == text),
                "{name}: {err}"
            );
        }
    }

    /// `verification_engine` returns the engine that a verification key
    /// names.
    #[test]
    fn verification_keys_name_their_engine() {
        assert_eq!(
            verification_engine("verification-ed25519-key"),
            Some("ed25519")
        );
        assert_eq!(verification_engine("verification-spki-file"), Some("spki"));
        assert_eq!(verification_engine("verification-x-y"), None);
        assert_eq!(verification_engine("gpgkeypath"), None);
    }

    /// The header of the trust group of the check tests.
    const GROUP_T: &str = "ex-ostrya trust \"t\"";

    /// Returns the result of the check of the trust group `t` whose keys are
    /// `keys`.
    fn check_group(keys: &str) -> Result<()> {
        let keyfile = KeyFile::parse(&format!("[{GROUP_T}]\n{keys}")).unwrap();
        check_trust(&Section::from_parts(&keyfile, GROUP_T, None))
    }

    /// Returns the switches of the trust group `t` whose keys are `keys`.
    fn switches_of(keys: &str) -> (bool, SignVerify) {
        let keyfile = KeyFile::parse(&format!("[{GROUP_T}]\n{keys}")).unwrap();
        trust_group_switches(&Section::from_parts(&keyfile, GROUP_T, None)).unwrap()
    }

    /// The check of a trust group gives each refusal with its text and its
    /// error variant, and finds the refusals in a fixed order.
    #[test]
    fn the_check_keeps_its_texts_and_its_order() {
        let key = format!("verification-ed25519-key={PUBLIC_B64}\n");
        let invalid = |keys: &str, text: &str| {
            let err = check_group(keys).unwrap_err();
            assert!(
                matches!(&err, Error::InvalidFormat(m) if m == text),
                "{keys:?}: {err:?}"
            );
        };
        let core = |keys: &str, text: &str| {
            let err = check_group(keys).unwrap_err();
            assert!(
                matches!(&err, Error::Core(_)) && err.to_string() == text,
                "{keys:?}: {err:?}"
            );
        };
        invalid(
            &format!("sign-verify=ed25519\n{key}zzz=1\n"),
            "[ex-ostrya trust \"t\"] holds the unknown key 'zzz'",
        );
        invalid(
            &format!("sign-verify=ed25519\n{key}verification-foo-key=AAAA\n"),
            "[ex-ostrya trust \"t\"] holds 'verification-foo-key', and 'foo' is not ed25519 \
             or spki",
        );
        invalid(
            &format!("sign-verify=ed25519\n{key}sign-verify-summary=ed25519\n"),
            "[ex-ostrya trust \"t\"] holds 'sign-verify-summary', and a trust group sets a \
             commit policy alone",
        );
        // The keys are read in the order of the file.
        invalid(
            "zzz=1\ngpg-verify-summary=true\n",
            "[ex-ostrya trust \"t\"] holds the unknown key 'zzz'",
        );
        invalid(
            "gpg-verify-summary=true\nzzz=1\n",
            "[ex-ostrya trust \"t\"] holds 'gpg-verify-summary', and a trust group sets a \
             commit policy alone",
        );
        core(
            "gpg-verify=maybe\n",
            "keyfile: value 'maybe' for ex-ostrya trust \"t\".gpg-verify is not a boolean",
        );
        core(
            &format!("sign-verify=ed\\q\n{key}"),
            "keyfile: invalid escape '\\q'",
        );
        invalid(
            &format!("sign-verify=dummy\n{key}"),
            "[ex-ostrya trust \"t\"] sign-verify names 'dummy', which is not ed25519 or spki",
        );
        // A `,` stays in a name, and a `;` alone is one empty name.
        invalid(
            &format!("sign-verify=ed25519,spki\n{key}"),
            "[ex-ostrya trust \"t\"] sign-verify names 'ed25519,spki', which is not ed25519 \
             or spki",
        );
        invalid(
            &format!("sign-verify=;\n{key}"),
            "[ex-ostrya trust \"t\"] sign-verify names '', which is not ed25519 or spki",
        );
        // The check does not read the value of an inline key.
        check_group("sign-verify=ed25519\nverification-ed25519-key=\\q\n").unwrap();
        // A key of an engine that the group does not select comes before the
        // `..` component of its path.
        invalid(
            "gpg-verify=true\ngpgkeypath=/k.gpg\nverification-ed25519-file=../k\n",
            "[ex-ostrya trust \"t\"] holds 'verification-ed25519-file', and sign-verify does \
             not select ed25519, so no check reads it",
        );
        let err = check_group("gpg-verify=true\ngpgkeypath=../k.gpg\n").unwrap_err();
        #[cfg(feature = "verify-gpg")]
        assert!(
            matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] gpgkeypath \
                ../k.gpg has a `..` component, which a relative path in a config cannot have"),
            "{err:?}"
        );
        #[cfg(not(feature = "verify-gpg"))]
        assert!(
            matches!(&err, Error::Unsupported(m) if m == "[ex-ostrya trust \"t\"] asks for GPG \
                verification, which this build has no engine for; build with the verify-gpg \
                feature"),
            "{err:?}"
        );
    }

    /// The switches of a trust group: an absent `gpg-verify` turns the GPG
    /// check off, a leading space of a value is not part of the value, and
    /// the last of two lines of one key wins.
    #[test]
    fn the_switches_read_the_values_of_the_file() {
        let engines = SignVerify::Engines(vec!["ed25519".to_owned()]);
        assert_eq!(switches_of("sign-verify=ed25519\n"), (false, engines));
        assert_eq!(switches_of("gpg-verify= true\n"), (true, SignVerify::Off));
        assert_eq!(
            switches_of("gpg-verify=true\ngpg-verify=false\n"),
            (false, SignVerify::Off)
        );
    }

    /// The check of a trust group refuses a relative key file with a `..`
    /// component before the build reads a key source.
    #[test]
    fn the_check_refuses_a_key_file_with_a_parent_component() {
        let group = "ex-ostrya trust \"t\"";
        let keyfile = KeyFile::parse(&format!(
            "[{group}]\nsign-verify=ed25519\nverification-ed25519-file=../k.ed25519\n"
        ))
        .unwrap();
        let err = check_trust(&Section::from_parts(&keyfile, group, None)).unwrap_err();
        assert!(
            matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] \
                verification-ed25519-file ../k.ed25519 has a `..` component, which a relative \
                path in a config cannot have"),
            "{err:?}"
        );
    }

    /// Returns the bytes of the X.509 fixture file `name`.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    fn x509_fixture(name: &str) -> Vec<u8> {
        let root =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/x509");
        std::fs::read(root.join(name)).unwrap()
    }

    /// Returns a dict with the signature of the leaf `leaf` over `PAYLOAD`
    /// and the chain of the leaf.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    fn chain_signed(leaf: &str) -> Value {
        file_chain_signed(leaf, &format!("chain-{leaf}.pem"))
    }

    /// Returns a dict with the signature of the leaf `leaf` over `PAYLOAD`
    /// and the chain of the fixture file `chain`.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    fn file_chain_signed(leaf: &str, chain: &str) -> Value {
        use crate::spki::{X509Chain, spki_secret_keys};
        let signer = spki_secret_keys(x509_fixture(&format!("leaf-{leaf}.key.pem")), "k")
            .unwrap()
            .remove(0);
        let chain = X509Chain::from_pem(&x509_fixture(chain), "c").unwrap();
        let signer = signer.with_x509(vec![chain], Vec::new()).unwrap();
        let mut dict = Value::Array(Vec::new());
        let blob = ostrya_rt::block_on(signer.sign(PAYLOAD)).unwrap();
        crate::sign::append_signed(
            &mut dict,
            "ostree.sign.spki",
            blob,
            signer.x509_attachments(),
        )
        .unwrap();
        dict
    }

    /// Returns the base64 body of the PEM file `name`.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    fn pem_body(name: &str) -> String {
        String::from_utf8(x509_fixture(name))
            .unwrap()
            .lines()
            .filter(|line| !line.starts_with("-----"))
            .collect()
    }

    /// Returns the PEM `PUBLIC KEY` block of the key of the secret key
    /// fixture `name`.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    fn public_pem(name: &str) -> Vec<u8> {
        let der = crate::spki::spki_secret_keys(x509_fixture(name), "k")
            .unwrap()
            .remove(0)
            .public_key_der();
        let body = ostrya_core::base64::encode(&der);
        let lines: Vec<&str> = body
            .as_bytes()
            .chunks(64)
            .map(|line| std::str::from_utf8(line).unwrap())
            .collect();
        format!(
            "-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----\n",
            lines.join("\n")
        )
        .into_bytes()
    }

    /// `RemoteKeys` trusts the anchors of the system key store for a remote
    /// that sets `verification-spki-identity`, and reads none for a remote
    /// without it. The system revoked set applies to the X.509 trust alone,
    /// and not to the raw keys of the remote. A remote with an identity and
    /// no anchor in any source is refused.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    #[test]
    fn remote_keys_read_the_system_anchors_with_an_identity() {
        use crate::verify::RemoteKeys;

        let scratch = Scratch::new("remote-keys-x509");
        let roots = scratch.dir.join("etc-ostree");
        std::fs::create_dir_all(roots.join("trusted.x509.d")).unwrap();
        std::fs::write(
            roots.join("trusted.x509.d/root.pem"),
            x509_fixture("root.pem"),
        )
        .unwrap();
        let p384 = pem_body("leaf-p384.pub.pem");
        let repo = repo_with_remotes(
            &scratch,
            &format!(
                "[remote \"named\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=spki\nverification-spki-identity=uri:https://example.org/leaf-p256\n\
                 verification-spki-key={p384}\n\
                 [remote \"raw\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=spki\nverification-spki-key={p384}\n"
            ),
        );
        let roots_text = roots.to_str().unwrap();
        let read = |remote: &str| {
            ostrya_rt::block_on(RemoteKeys::read_at(
                &repo,
                remote,
                true,
                None,
                &[roots_text],
            ))
        };
        let p256 = chain_signed("p256");
        let valid = |keys: &RemoteKeys, dict: &Value| {
            keys.sign()[0]
                .verify_metadata(PAYLOAD, Some(dict), &[])
                .unwrap()
                .valid
        };
        let named = read("named").unwrap();
        assert!(valid(&named, &p256), "the system anchor admits the chain");
        let raw = read("raw").unwrap();
        assert!(
            !valid(&raw, &p256),
            "a remote with no identity reads no anchor"
        );

        // The system revoked set removes the leaf of the chain, and keeps the
        // raw key of the remote.
        std::fs::write(
            roots.join("revoked.spki"),
            [
                x509_fixture("leaf-p256.pub.pem"),
                x509_fixture("leaf-p384.pub.pem"),
            ]
            .concat(),
        )
        .unwrap();
        let named = read("named").unwrap();
        let outcome = named.sign()[0]
            .verify_metadata(PAYLOAD, Some(&p256), &[])
            .unwrap();
        assert!(!outcome.valid);
        assert_eq!(
            outcome.signatures[0].detail.as_deref(),
            Some("certificate \"CN=ostrya test leaf p256\" holds a revoked key")
        );
        assert!(
            valid(&named, &chain_signed("p384")),
            "the raw key stays trusted"
        );

        // With no anchor in any source, the identity is refused.
        std::fs::remove_file(roots.join("trusted.x509.d/root.pem")).unwrap();
        let err = read("named").unwrap_err();
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("no anchor source holds an anchor")),
            "{err}"
        );
    }

    /// The X.509 trust of a remote reads the CRLs of
    /// `verification-spki-crl-file` and of the system key store, `crl.x509`
    /// and `crl.x509.d/`. A CRL that the path check does not use refuses its
    /// file, and the refusal names the file.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    #[test]
    fn remote_keys_read_the_crls_of_the_config_and_of_the_system_store() {
        use crate::verify::RemoteKeys;

        let scratch = Scratch::new("remote-keys-crl");
        let fixtures =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/x509");
        let roots = scratch.dir.join("etc-ostree");
        std::fs::create_dir_all(roots.join("crl.x509.d")).unwrap();
        let fixture_path = |name: &str| fixtures.join(name).display().to_string();
        let repo = repo_with_remotes(
            &scratch,
            &format!(
                "[remote \"plain\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=spki\nverification-spki-identity=*\n\
                 verification-spki-ca-file={}\n\
                 [remote \"crl\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=spki\nverification-spki-identity=*\n\
                 verification-spki-ca-file={}\nverification-spki-crl-file={}\n\
                 [remote \"bad\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=spki\nverification-spki-identity=*\n\
                 verification-spki-ca-file={}\nverification-spki-crl-file={}\n",
                fixture_path("root.pem"),
                fixture_path("root.pem"),
                fixture_path("intermediate-2.crl.pem"),
                fixture_path("root.pem"),
                fixture_path("crl-no-number.pem"),
            ),
        );
        let roots_text = roots.to_str().unwrap();
        let read = |remote: &str| {
            ostrya_rt::block_on(RemoteKeys::read_at(
                &repo,
                remote,
                true,
                None,
                &[roots_text],
            ))
        };
        let revoked = chain_signed("revoked");
        let detail = |keys: &RemoteKeys| {
            let outcome = keys.sign()[0]
                .verify_metadata(PAYLOAD, Some(&revoked), &[])
                .unwrap();
            assert!(!outcome.valid);
            assert!(outcome.signatures[0].revoked);
            outcome.signatures[0].detail.clone().unwrap()
        };
        let text = "certificate \"CN=ostrya test leaf revoked\" is revoked by the CRL of \
                    \"CN=ostrya test intermediate\"";
        // With no CRL, the leaf passes.
        let plain = read("plain").unwrap();
        assert!(
            plain.sign()[0]
                .verify_metadata(PAYLOAD, Some(&revoked), &[])
                .unwrap()
                .valid
        );
        // The CRL file of the config revokes the leaf.
        assert_eq!(detail(&read("crl").unwrap()), text);
        // A CRL of the system store revokes the leaf of a remote with no CRL
        // file.
        std::fs::copy(
            fixtures.join("intermediate-2.crl.pem"),
            roots.join("crl.x509.d/intermediate.pem"),
        )
        .unwrap();
        assert_eq!(detail(&read("plain").unwrap()), text);
        // A CRL with no cRLNumber refuses its file.
        let err = read("bad").unwrap_err();
        assert_eq!(
            err.to_string(),
            format!(
                "signature: the 'spki' CRL file '{}': x509 CRL 1: it has no \
                 cRLNumber",
                fixture_path("crl-no-number.pem")
            )
        );
        std::fs::copy(fixtures.join("crl-no-number.pem"), roots.join("crl.x509")).unwrap();
        let err = read("plain").unwrap_err();
        assert_eq!(
            err.to_string(),
            format!(
                "signature: the CRL file '{}': x509 CRL 1: it has no \
                 cRLNumber",
                roots.join("crl.x509").display()
            )
        );
    }

    /// The trust of a pull trusts the anchors of the system key store for a
    /// remote that sets `verification-spki-identity`, and reads none for a
    /// remote without it. An intermediate certificate of
    /// `verification-spki-intermediates-file` completes a chain that holds
    /// the leaf alone. The system revoked set removes an intermediate
    /// certificate and an anchor that hold a revoked key, and keeps the raw
    /// key of the remote.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    #[test]
    fn a_pull_reads_the_system_anchors_with_an_identity() {
        let scratch = Scratch::new("pull-x509");
        let roots = scratch.dir.join("etc-ostree");
        std::fs::create_dir_all(roots.join("trusted.x509.d")).unwrap();
        std::fs::write(
            roots.join("trusted.x509.d/root.pem"),
            x509_fixture("root.pem"),
        )
        .unwrap();
        let intermediates =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/x509");
        let p384 = pem_body("leaf-p384.pub.pem");
        let repo = repo_with_remotes(
            &scratch,
            &format!(
                "[remote \"named\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=spki\nverification-spki-identity=uri:https://example.org/leaf-p256\n\
                 verification-spki-key={p384}\n\
                 [remote \"raw\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=spki\nverification-spki-key={p384}\n\
                 [remote \"via-int\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=spki\nverification-spki-identity=uri:https://example.org/leaf-p256\n\
                 verification-spki-intermediates-file={}\n",
                intermediates.join("intermediate.pem").display()
            ),
        );
        let roots_text = roots.to_str().unwrap();
        let outcome = |remote: &str, dict: &Value| {
            let section = repo.config().section::<remote::Group>(remote);
            let source = KeySource::Remote {
                name: remote,
                section: section.as_ref(),
                repo_keyring: true,
                system_keys: true,
                roots: &[roots_text],
                check: X509Check::Admission,
                best_effort: false,
            };
            let sign = SignVerify::Engines(vec!["spki".to_owned()]);
            let policy = ostrya_rt::block_on(build_policy(
                &repo,
                &source,
                &mut Verifiers::default(),
                false,
                &sign,
            ))
            .unwrap();
            policy.sign_axis().unwrap()[0]
                .verify_metadata(PAYLOAD, Some(dict), &[])
                .unwrap()
        };
        let p256 = chain_signed("p256");
        let leaf_alone = file_chain_signed("p256", "leaf-p256.pem");
        assert!(
            outcome("named", &p256).valid,
            "the system anchor admits the chain"
        );
        assert!(
            !outcome("raw", &p256).valid,
            "a remote with no identity reads no anchor"
        );
        assert!(
            outcome("via-int", &leaf_alone).valid,
            "the intermediate of the config completes the chain"
        );

        // A revoked intermediate key removes the intermediate of the config.
        std::fs::write(
            roots.join("revoked.spki"),
            public_pem("intermediate.key.pem"),
        )
        .unwrap();
        let via_int = outcome("via-int", &leaf_alone);
        assert!(!via_int.valid && via_int.signatures[0].key_missing);
        assert!(
            via_int.signatures[0]
                .detail
                .as_deref()
                .unwrap()
                .starts_with(
                    "certificate \"CN=ostrya test leaf p256\" has no valid path to a trusted \
                     anchor: "
                ),
            "{via_int:?}"
        );

        // A revoked root key removes the system anchor, and keeps the raw key
        // of the remote.
        std::fs::write(roots.join("revoked.spki"), public_pem("root.key.pem")).unwrap();
        let named = outcome("named", &p256);
        assert!(!named.valid && named.signatures[0].key_missing, "{named:?}");
        assert!(
            outcome("named", &chain_signed("p384")).valid,
            "the raw key stays trusted"
        );
    }

    /// `RemoteKeys` reads no raw key of the system key store, and the system
    /// revoked set removes a system anchor.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    #[test]
    fn remote_keys_read_no_system_raw_key() {
        use crate::verify::RemoteKeys;

        let scratch = Scratch::new("remote-keys-system");
        let roots = scratch.dir.join("etc-ostree");
        std::fs::create_dir_all(&roots).unwrap();
        std::fs::write(roots.join("trusted.x509"), x509_fixture("root.pem")).unwrap();
        std::fs::write(
            roots.join("trusted.spki"),
            x509_fixture("leaf-p256.pub.pem"),
        )
        .unwrap();
        let p384 = pem_body("leaf-p384.pub.pem");
        let repo = repo_with_remotes(
            &scratch,
            &format!(
                "[remote \"named\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=spki\nverification-spki-identity=uri:https://example.org/leaf-p256\n\
                 verification-spki-key={p384}\n\
                 [remote \"raw\"]\nurl=http://localhost/\ngpg-verify=false\n\
                 sign-verify=spki\nverification-spki-key={p384}\n"
            ),
        );
        let roots_text = roots.to_str().unwrap();
        let valid = |remote: &str, dict: &Value| {
            let keys = ostrya_rt::block_on(RemoteKeys::read_at(
                &repo,
                remote,
                true,
                None,
                &[roots_text],
            ))
            .unwrap();
            keys.sign()[0]
                .verify_metadata(PAYLOAD, Some(dict), &[])
                .unwrap()
                .valid
        };
        let p256 = chain_signed("p256");
        let p384_signed = chain_signed("p384");
        assert!(valid("named", &p256), "the system anchor admits the chain");
        assert!(
            !valid("raw", &p256),
            "the raw keys of the system store do not reach the remote"
        );

        // A revoked root key removes the system anchor.
        std::fs::write(roots.join("revoked.spki"), public_pem("root.key.pem")).unwrap();
        assert!(!valid("named", &p256), "the revoked anchor admits no chain");
        assert!(valid("named", &p384_signed), "the raw key stays trusted");
    }

    /// The check of a trust group takes the X.509 keys of the spki engine
    /// with the rules of a remote, and the texts of a remote with the header
    /// of the group. A trust group reads no system anchor, so it refuses an
    /// identity with no CA file. An X.509 key needs a `sign-verify` that
    /// selects spki.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    #[test]
    fn a_trust_group_takes_the_x509_keys() {
        let anchor = "verification-spki-ca-file=ca.pem\n\
                      verification-spki-identity=dns:a.example.org\n";
        check_group(&format!("sign-verify=spki\n{anchor}")).unwrap();
        for key in [
            "verification-spki-intermediates-file=i.pem",
            "verification-spki-eku=1.3.6.1.5.5.7.3.3",
            "verification-spki-crl-file=crl.pem",
            "verification-spki-revocation=required",
        ] {
            check_group(&format!("sign-verify=spki\n{anchor}{key}\n")).unwrap();
            let name = key.split('=').next().unwrap();
            let err = check_group(&format!("sign-verify=spki\n{key}\n")).unwrap_err();
            assert!(
                matches!(&err, Error::InvalidFormat(m) if *m == format!(
                    "[ex-ostrya trust \"t\"] holds '{name}', and no anchor source: set \
                     verification-spki-ca-file or verification-spki-identity"
                )),
                "{key}: {err:?}"
            );
        }
        let err = check_group("sign-verify=spki\nverification-spki-ca-file=ca.pem\n").unwrap_err();
        assert!(
            matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] holds \
                'verification-spki-ca-file', and no verification-spki-identity: an anchor \
                needs an identity"),
            "{err:?}"
        );
        let err = check_group("sign-verify=spki\nverification-spki-identity=dns:a.example.org\n")
            .unwrap_err();
        assert!(
            matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] holds \
                'verification-spki-identity', and no verification-spki-ca-file: a trust group \
                reads no system anchor"),
            "{err:?}"
        );
        let err = check_group(&format!(
            "sign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n{anchor}"
        ))
        .unwrap_err();
        assert!(
            matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] holds \
                'verification-spki-ca-file', and sign-verify does not select spki, so no check \
                reads it"),
            "{err:?}"
        );
    }

    /// Returns the key file of the trust group `t` that trusts the fixture
    /// root for the leaves `p256` and `expired`.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    fn x509_group() -> KeyFile {
        let root =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/x509");
        KeyFile::parse(&format!(
            "[{GROUP_T}]\nsign-verify=spki\nverification-spki-ca-file={}\n\
             verification-spki-identity=uri:https://example.org/leaf-p256;\
             uri:https://example.org/leaf-expired\n",
            root.join("root.pem").display()
        ))
        .unwrap()
    }

    /// The X.509 trust of a trust group checks a chain at admission: a valid
    /// chain to the anchor of the group passes, and an expired leaf fails.
    /// The refusal names the certificate and the system time.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    #[test]
    fn a_trust_group_x509_trust_checks_a_chain_at_admission() {
        let scratch = Scratch::new("group-x509-admission");
        let repo = scratch.repo();
        let keyfile = x509_group();
        let section = Section::from_parts(&keyfile, GROUP_T, None);
        check_trust(&section).unwrap();
        let policy =
            ostrya_rt::block_on(trust_group_policy(&repo, "t", &section, true, true, false))
                .unwrap();
        let (p256, expired) = (chain_signed("p256"), chain_signed("expired"));
        let (valid, expired) = ostrya_rt::block_on(async {
            (
                policy
                    .check("commit", PAYLOAD, Some(&p256), &CrlScope::default())
                    .await,
                policy
                    .check("commit", PAYLOAD, Some(&expired), &CrlScope::default())
                    .await,
            )
        });
        valid.expect("a chain to the anchor of the group passes");
        let err = expired.unwrap_err();
        assert!(
            err.to_string().contains(
                "no sign-api signature is from a trusted key: certificate \
                 \"CN=ostrya test leaf expired\" expired at 2001-01-01T00:00:00Z; system time "
            ),
            "{err}"
        );
    }

    /// The builder of a trust group takes the X.509 check from its caller.
    /// With the existing check, an expired leaf passes with a warning.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    #[test]
    fn a_trust_group_x509_trust_follows_the_check_of_its_caller() {
        let scratch = Scratch::new("group-x509-existing");
        let repo = scratch.repo();
        let keyfile = x509_group();
        let section = Section::from_parts(&keyfile, GROUP_T, None);
        let sign = SignVerify::Engines(vec!["spki".to_owned()]);
        let policy = ostrya_rt::block_on(trust_group_build(
            &repo,
            "t",
            &section,
            false,
            &sign,
            X509Check::Existing,
            false,
        ))
        .unwrap();
        let outcome = policy.sign_axis().unwrap()[0]
            .verify_metadata(PAYLOAD, Some(&chain_signed("expired")), &[])
            .unwrap();
        assert!(outcome.valid);
        let info = &outcome.signatures[0];
        assert!(info.expired);
        assert_eq!(info.warnings.len(), 1, "{:?}", info.warnings);
        assert!(
            info.warnings[0].starts_with("certificate \"CN=ostrya test leaf expired\" expired at"),
            "{:?}",
            info.warnings
        );
    }

    /// A build with the spki engine and no path check refuses the X.509 keys
    /// of a trust group with `Error::Unsupported`, before it reads a key
    /// source, so a CA file that does not exist gives the same refusal.
    #[cfg(all(feature = "sign-spki", not(feature = "sign-x509")))]
    #[test]
    fn a_trust_group_needs_the_path_check() {
        let scratch = Scratch::new("group-x509-unsupported");
        let repo = repo_with_remotes(
            &scratch,
            "[ex-ostrya trust \"t\"]\nsign-verify=spki\n\
             verification-spki-ca-file=/nonexistent/ca.pem\nverification-spki-identity=*\n",
        );
        let err = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, "t")).unwrap_err();
        assert!(
            matches!(&err, Error::Unsupported(m) if m == "[ex-ostrya trust \"t\"] sets an X.509 \
                trust of the spki engine, which this build has no path check for; build with \
                the sign-x509 feature"),
            "{err:?}"
        );
    }

    /// A build with the spki engine and no path check refuses a break of
    /// the rules of the X.509 keys of a remote before it refuses the X.509
    /// keys with `Error::Unsupported`, as the build refuses the keys of a
    /// remote: a CA file with no identity is `Error::InvalidFormat`.
    #[cfg(all(feature = "sign-spki", not(feature = "sign-x509")))]
    #[test]
    fn a_trust_group_checks_the_x509_rules_before_the_path_check() {
        let scratch = Scratch::new("group-x509-rules-first");
        let repo = repo_with_remotes(
            &scratch,
            "[ex-ostrya trust \"t\"]\nsign-verify=spki\n\
             verification-spki-ca-file=/nonexistent/ca.pem\n",
        );
        let err = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, "t")).unwrap_err();
        assert!(
            matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] holds \
                'verification-spki-ca-file', and no verification-spki-identity: an anchor needs \
                an identity"),
            "{err:?}"
        );
    }
}