ostrya 0.8.0

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

// The module also builds the policy of a target from a key source: the
// configuration section of a remote, or a trust group.
// The pull and the receive path share this build.

#[cfg(feature = "verify-gpg")]
use std::os::fd::{AsFd, BorrowedFd};
use std::sync::Arc;

use ostrya_core::{Value, base64};
use rustix::fs::{Mode, OFlags};
#[cfg(feature = "verify-gpg")]
use rustix::io::Errno;

use crate::config::{Remote, SignVerify, valid_remote_name};
use crate::error::{Error, Result};
#[cfg(feature = "verify-gpg")]
use crate::gpg::read_keyring_fd;
use crate::pull::PullVerify;
use crate::repo::Repo;
use crate::sign::{
    Ed25519Verifier, MAX_KEY_FILE, SignKeys, Verifier, key_text, load_sign_keys, read_key_source,
    signatures_for,
};

pub(crate) mod trust;

/// The detached-metadata key of the dummy engine.
const DUMMY_METADATA_KEY: &str = "ostree.sign.dummy";

/// A set of trusted keys and the signature axes that it requires.
///
/// A set with a GPG axis and a sign-api axis needs a valid signature on each
/// axis. On the sign-api axis, one valid signature from one engine is enough.
/// The set holds its verifiers, so the verification of a commit reads no key
/// source.
///
/// [`TrustedKeys::new`] takes verifiers that the caller holds, and so does
/// `TrustedKeys::with_gpg` with the `verify-gpg` feature.
/// [`TrustedKeys::from_trust_group`] reads the keys of a trust group of the
/// repository config.
///
/// [`PullTrust`] holds a set for the commits and a set for the summary of one
/// pull. With the `receive` feature, the policy of a client group and a rule
/// of a one-way stream can each hold a set, in `ReceiveVerify::Keys`, for the
/// commits that they accept.
#[derive(Clone)]
pub struct TrustedKeys {
    /// The built axes. At least one axis applies.
    policy: Policy,
}

impl TrustedKeys {
    /// Creates trusted keys with a sign-api axis over `sign`.
    ///
    /// `sign` holds one verifier for each engine. The call refuses a verifier
    /// of the dummy engine, because its signature is its key and proves
    /// nothing about the signer.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if `sign` is empty, because an empty set
    ///   trusts no key.
    /// - [`Error::InvalidFormat`] if `sign` holds a verifier of the dummy
    ///   engine.
    pub fn new(sign: Vec<Arc<dyn Verifier>>) -> Result<TrustedKeys> {
        if sign.is_empty() {
            return Err(Error::InvalidFormat(
                "the trusted keys name no verifier".into(),
            ));
        }
        refuse_dummy(&sign)?;
        Ok(TrustedKeys {
            policy: Policy::from_axes(None, Some(sign)),
        })
    }

    /// Creates trusted keys with a GPG axis over `gpg`.
    ///
    /// If `sign` is not empty, the set also gets a sign-api axis over `sign`.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] if `sign` holds a verifier of the dummy engine,
    /// as [`new`](TrustedKeys::new) refuses it.
    #[cfg(feature = "verify-gpg")]
    pub fn with_gpg(
        gpg: crate::gpg::GpgVerifier,
        sign: Vec<Arc<dyn Verifier>>,
    ) -> Result<TrustedKeys> {
        refuse_dummy(&sign)?;
        let sign = (!sign.is_empty()).then_some(sign);
        Ok(TrustedKeys {
            policy: Policy::from_axes(Some(Arc::new(gpg)), sign),
        })
    }

    /// Creates trusted keys over a built policy.
    ///
    /// The policy must apply: it holds at least one axis.
    pub(crate) fn from_policy(policy: Policy) -> TrustedKeys {
        debug_assert!(policy.applies(), "trusted keys need at least one axis");
        TrustedKeys { policy }
    }

    /// Returns the policy of this set.
    #[cfg(any(feature = "receive", feature = "s3"))]
    pub(crate) fn policy(&self) -> &Policy {
        &self.policy
    }

    /// Returns the policy of this set, and drops the set.
    pub(crate) fn into_policy(self) -> Policy {
        self.policy
    }
}

/// Refuses a verifier of the dummy engine in `sign`.
fn refuse_dummy(sign: &[Arc<dyn Verifier>]) -> Result<()> {
    if sign.iter().any(|v| v.metadata_key() == DUMMY_METADATA_KEY) {
        return Err(Error::InvalidFormat(
            "the trusted keys name a dummy verifier, whose signature is its key".into(),
        ));
    }
    Ok(())
}

impl std::fmt::Debug for TrustedKeys {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let sign: Option<Vec<&str>> = self
            .policy
            .sign_axis()
            .map(|engines| engines.iter().map(|v| v.metadata_key()).collect());
        f.debug_struct("TrustedKeys")
            .field("gpg", &self.policy.gpg_axis())
            .field("sign", &sign)
            .finish()
    }
}

/// The trusted keys of one pull: a set for the commits, and a set for the
/// summary of the remote.
///
/// A pull checks each target, each parent that its depth takes, and each
/// commit of a chain of static deltas against the commit set, and the summary
/// against the summary set. A dependency in no other role gets no check. The
/// pull does not check a target that has no set. If the commit set has a
/// sign-api axis and the static delta of a target or of a step of a chain
/// carries signatures that this axis reads, one of them must be valid. The
/// pull checks no other signature of a static delta, and no signature of the
/// static delta of a dependency.
///
/// [`PullTrust::from_remote`] reads the trust that [`Repo::pull`] uses.
/// [`PullTrust::commits`] and [`PullTrust::with_summary`] take keys that the
/// caller holds. [`PullTrust::unverified`] checks nothing.
///
/// # Examples
///
/// The trust of a pull that checks its commits against one ed25519 key:
///
/// ```
/// use std::sync::Arc;
///
/// use ostrya::base64;
/// use ostrya::sign::Ed25519Verifier;
/// use ostrya::verify::{PullTrust, TrustedKeys};
///
/// # fn main() -> ostrya::Result<()> {
/// let public = base64::decode("wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=")?;
/// let verifier = Ed25519Verifier::new([public], Vec::<Vec<u8>>::new())?;
/// let trust = PullTrust::commits(TrustedKeys::new(vec![Arc::new(verifier)])?);
/// # let _ = trust;
/// # Ok(()) }
/// ```
#[derive(Clone, Debug)]
pub struct PullTrust {
    /// The keys of the commits, or `None` if the pull does not check them.
    commit: Option<TrustedKeys>,
    /// The keys of the summary, or `None` if the pull does not check it.
    summary: Option<TrustedKeys>,
}

impl PullTrust {
    /// Creates the trust of a pull that checks no signature.
    pub fn unverified() -> PullTrust {
        PullTrust {
            commit: None,
            summary: None,
        }
    }

    /// Creates the trust of a pull that checks its commits against `keys`.
    ///
    /// The pull does not check the summary. `keys` is the whole trusted set of
    /// the commits: the pull reads no system key store and no keyring of the
    /// repository for them.
    pub fn commits(keys: TrustedKeys) -> PullTrust {
        PullTrust {
            commit: Some(keys),
            summary: None,
        }
    }

    /// Sets the keys that the pull checks the summary of the remote against.
    ///
    /// `keys` replaces the summary keys that this trust held before. The
    /// commit keys do not change. `keys` is the whole trusted set of the
    /// summary: the pull reads no system key store and no keyring of the
    /// repository for it.
    pub fn with_summary(self, keys: TrustedKeys) -> PullTrust {
        PullTrust {
            summary: Some(keys),
            ..self
        }
    }

    /// Returns the keys that the pull checks the summary of the remote
    /// against, or `None` if the pull does not check the summary.
    ///
    /// With the `s3` feature, `BucketRepo::fsck` takes these keys in
    /// `BucketFsckOptions::summary_keys`.
    pub fn summary_keys(&self) -> Option<&TrustedKeys> {
        self.summary.as_ref()
    }

    /// Reads the trust that [`Repo::pull`] uses for a pull from `remote`.
    ///
    /// The keys come from the `[remote "NAME"]` section of the repository
    /// config and from these key sources:
    ///
    /// - `gpgkeypath`
    /// - the repository keyring `<repo>/NAME.trustedkeys.gpg`
    /// - the system keyring `/etc/ostree/remotes.d/NAME.trustedkeys.gpg`
    /// - the global GPG trusted directory
    /// - the `verification-*` keys
    /// - the system sign-api key store, minus its revoked set
    ///
    /// Each field of `verify` that is set overrides the config key of the
    /// same name (see [`PullVerify`]). If the config has no section for
    /// `remote`, the trust takes the defaults of a described remote: the GPG
    /// verification of the commits is on, and the other checks are off.
    ///
    /// The call reads each key source before it returns. The trust that it
    /// gives reads no key source again.
    ///
    /// # Trust groups
    ///
    /// If the section holds the key [`trust`](crate::config::Remote::trust),
    /// the trust group `[ex-ostrya trust "NAME"]` that the key names sets the
    /// commit policy. The commit keys come from the group alone: no system
    /// key store, no repository keyring `<repo>/NAME.trustedkeys.gpg`, no
    /// system keyring, and no global GPG trusted directory. The keys
    /// `gpg-verify-summary` and `sign-verify-summary` of the section and the
    /// key sources that they read set the summary policy, as without a trust
    /// group. The two policies share no verifier.
    ///
    /// The call checks the group as the receive side does, and builds only
    /// the axes that stay on. `Some(false)` in `verify.gpg` or `verify.sign`
    /// turns off that commit axis of the group. The summary fields of
    /// `verify` override the summary keys of the section.
    ///
    /// The section must not turn on a commit check: the call refuses
    /// `gpg-verify=true` and a `sign-verify` value other than false. It
    /// accepts `gpg-verify=false` and an absent `gpg-verify`, and both give no
    /// GPG check of the commits. The call also refuses a key source of the
    /// section that no summary check reads: `gpgkeypath` when
    /// `gpg-verify-summary` is not true, and a `verification-ENGINE-key` or a
    /// `verification-ENGINE-file` of an engine that `sign-verify-summary` does
    /// not select. `sign-verify-summary=true` selects `ed25519` and `spki`.
    /// This rule reads the summary keys of the section, and not the fields of
    /// `verify`.
    ///
    /// Each refusal of a trust group comes before the call reads a key
    /// source.
    ///
    /// This call reads the key `trust` alone. [`Repo::pull`] and
    /// [`Repo::pull_collection`] also read
    /// [`PullOptions::trust_group`](crate::PullOptions::trust_group). The field
    /// names a trust group that wins over the key, and the rules of this
    /// section apply to that group.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if [`valid_remote_name`] refuses `remote`.
    ///   The call refuses the name before it reads a key source.
    /// - [`Error::InvalidFormat`] if the `trust` value is empty or holds a `"`
    ///   or a control character, if it names no trust group, if the group
    ///   fails the check of a trust group, or if the section breaks a rule of
    ///   a trust group above.
    /// - [`Error::InvalidInput`] if the section holds `trust`, and
    ///   `verify.gpg` or `verify.sign` is `Some(true)`.
    /// - [`Error::Core`] if `gpg-verify` or `gpg-verify-summary` is not a
    ///   boolean, if a value holds a malformed escape sequence, or if a
    ///   sign-api key is not valid base64.
    /// - [`Error::Signature`] if `sign-verify` or `sign-verify-summary` names
    ///   an engine that has no trusted key, or if a check of every engine finds
    ///   no engine with a trusted key.
    /// - [`Error::Signature`] if a keyring or a key file cannot be read, or if
    ///   its content is not valid for its engine.
    /// - [`Error::Unsupported`] if `sign-verify` or `sign-verify-summary` names
    ///   an engine that this build does not verify with.
    /// - [`Error::Unsupported`] if the trust asks for GPG verification and the
    ///   build has no `verify-gpg` feature. Also if a trust group sets
    ///   `gpg-verify=true` in such a build, or names the spki engine in a
    ///   build with no `sign-spki` feature, whatever the fields of `verify`.
    /// - [`Error::Io`] if a directory of keys cannot be listed.
    pub async fn from_remote(repo: &Repo, remote: &str, verify: &PullVerify) -> Result<PullTrust> {
        PullTrust::for_pull(repo, remote, verify, None).await
    }

    /// Reads the trust of a pull from `remote`, as
    /// [`from_remote`](PullTrust::from_remote) does, with the trust group
    /// `group` of [`PullOptions::trust_group`](crate::PullOptions::trust_group).
    ///
    /// The call refuses a name that [`valid_remote_name`] refuses with
    /// [`Error::InvalidInput`], before it reads a key source.
    pub(crate) async fn for_pull(
        repo: &Repo,
        remote: &str,
        verify: &PullVerify,
        group: Option<&mut trust::FieldGroup<'_>>,
    ) -> Result<PullTrust> {
        if !valid_remote_name(remote) {
            return Err(Error::InvalidInput(format!(
                "invalid remote name: {remote}"
            )));
        }
        PullTrust::resolve(repo, Some(remote), verify, group, Defaults::Config).await
    }

    /// Resolves the trust of a pull of `remote` from its config in `repo` and
    /// the overrides in `verify`.
    ///
    /// The config section of `remote` supplies the policy and the keys.
    /// `defaults` gives the policy of a remote that has no section. If a
    /// local pull names no remote and asks for a verification, this function
    /// fails with [`Error::Pull`]. The failure comes before the pull imports
    /// an object.
    ///
    /// `group` is the trust group that the options of the pull name. It wins
    /// over the key `trust` of the section, and the call then does not read
    /// that key. With a trust group, the group sets the commit policy, and the
    /// call ignores `defaults`. A pull with a trust group that names no remote
    /// checks no summary. The call keeps the commit policy of the group in
    /// `group`, and a later call with the same `group` and the same `verify`
    /// reads no key source of the group again.
    pub(crate) async fn resolve(
        repo: &Repo,
        remote: Option<&str>,
        verify: &PullVerify,
        group: Option<&mut trust::FieldGroup<'_>>,
        defaults: Defaults,
    ) -> Result<PullTrust> {
        let section = remote.and_then(|name| repo.config().remote(name));
        // A trust group that the options of the pull name, or else the trust
        // group that the key `trust` of the remote names, supplies the commit
        // keys.
        if let Some(group) = group {
            let name = trust::GroupName::Field(group.name);
            return trust::pull_trust(
                repo,
                remote,
                section.as_ref(),
                name,
                verify,
                &mut group.commit,
            )
            .await;
        }
        if let (Some(remote), Some(section)) = (remote, &section)
            && let Some(value) = section.trust()?
        {
            let name = trust::GroupName::Key {
                remote,
                value: &value,
            };
            return trust::pull_trust(repo, Some(remote), Some(section), name, verify, &mut None)
                .await;
        }

        let gpg_commit = switch(verify.gpg, || match &section {
            Some(section) => section.gpg_verify(),
            // If an HTTP pull names a remote that the config does not
            // describe, the remote takes the default of a described remote.
            None => Ok(defaults == Defaults::Config),
        })?;
        let sign_commit = engines(verify.sign, || match &section {
            Some(section) => section.sign_verify(),
            None => Ok(SignVerify::Off),
        })?;
        let (gpg_summary, sign_summary) = summary_switches(section.as_ref(), verify)?;

        let asks_for_a_check = gpg_commit
            || gpg_summary
            || sign_commit != SignVerify::Off
            || sign_summary != SignVerify::Off;
        let Some(name) = remote else {
            if asks_for_a_check {
                return Err(no_remote());
            }
            return Ok(PullTrust::unverified());
        };

        let source = KeySource::Remote {
            name,
            section: section.as_ref(),
            repo_keyring: true,
            system_keys: true,
        };
        let mut cache = Verifiers::default();
        let commit = build_policy(repo, &source, &mut cache, gpg_commit, &sign_commit).await?;
        let summary = build_policy(repo, &source, &mut cache, gpg_summary, &sign_summary).await?;
        Ok(PullTrust {
            commit: commit.applies().then(|| TrustedKeys::from_policy(commit)),
            summary: summary.applies().then(|| TrustedKeys::from_policy(summary)),
        })
    }

    /// Returns the commit policy and the summary policy of this trust. A
    /// target with no keys gets a policy that holds no axis.
    pub(crate) fn into_policies(self) -> (Policy, Policy) {
        (
            self.commit
                .map(TrustedKeys::into_policy)
                .unwrap_or_default(),
            self.summary
                .map(TrustedKeys::into_policy)
                .unwrap_or_default(),
        )
    }
}

/// The verifiers of a remote, built from the configuration of the remote and
/// from the keys of the remote alone.
///
/// [`RemoteKeys::commits`] reads the keys that check the commits of a remote.
/// [`RemoteKeys::summary`] reads the keys that check its summary. Each call
/// reads the switches that a pull reads, and builds one verifier for each
/// engine that the switches turn on:
///
/// - For the commits: `gpg-verify` and `sign-verify`, or the trust group that
///   the key [`trust`](crate::config::Remote::trust) names.
/// - For the summary: `gpg-verify-summary` and `sign-verify-summary`.
///
/// The keys are the keys of the remote alone:
///
/// - the repository keyring `<repo>/NAME.trustedkeys.gpg`
/// - the system keyring `/etc/ostree/remotes.d/NAME.trustedkeys.gpg`
/// - each `gpgkeypath` entry
/// - the `verification-ENGINE-key` and `verification-ENGINE-file` keys
///
/// With a trust group, the commit keys come from the group alone, as in a
/// pull. The calls read no global GPG trusted directory and no system sign-api
/// key store. [`PullTrust::from_remote`] also reads these two sources.
///
/// A caller can select engines. The call then builds the selected engines
/// alone, and reads no key source of an engine that it does not select.
///
/// A pull accepts a valid signature of any one sign-api engine. Each verifier
/// of a `RemoteKeys` is available on its own, so a caller can require a valid
/// signature of each engine.
#[derive(Clone)]
pub struct RemoteKeys {
    /// The GPG verifier, if the switches turn on the GPG check.
    gpg: Option<Arc<dyn Verifier>>,
    /// One verifier for each sign-api engine that the switches turn on, in the
    /// order of the switch value or of the selection.
    sign: Vec<Arc<dyn Verifier>>,
}

impl RemoteKeys {
    /// Reads the verifiers that check the commits of `remote`.
    ///
    /// If the section of `remote` holds the key `trust`, the trust group that
    /// the key names gives the commit verifiers. The call checks the group as
    /// [`PullTrust::from_remote`] does.
    ///
    /// `engines` selects the engines to build. With `None`, the call builds
    /// each engine that the switches turn on. With `Some(names)`, it builds
    /// the engines of `names` alone: `gpg` names the GPG engine, and each
    /// other name names a sign-api engine, as in the value of `sign-verify`.
    /// A selected sign-api engine must have a trusted key, also under
    /// `sign-verify=true`.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if [`valid_remote_name`] refuses `remote`.
    /// - [`Error::RemoteNotFound`] if the config has no section for `remote`.
    /// - [`Error::InvalidFormat`] if the trust group fails a check of
    ///   [`PullTrust::from_remote`].
    /// - [`Error::Signature`] if the switches turn on no check, if they do not
    ///   turn on an engine of `engines`, if a GPG check finds no certificate
    ///   in the keyrings of the remote, or if a sign-api check finds no
    ///   trusted key, as [`PullTrust::from_remote`] states.
    /// - The other errors of [`PullTrust::from_remote`], for a value that
    ///   does not parse, a key source that cannot be read, or an engine that
    ///   this build does not have.
    ///
    /// Each refusal of the name, of the section, of the trust group, and of the
    /// switches comes before the call reads a key source.
    pub async fn commits(
        repo: &Repo,
        remote: &str,
        engines: Option<&[&str]>,
    ) -> Result<RemoteKeys> {
        RemoteKeys::read(repo, remote, true, engines).await
    }

    /// Reads the verifiers that check the summary of `remote`.
    ///
    /// If the section of `remote` holds the key `trust`, the call checks the
    /// trust group as [`PullTrust::from_remote`] does, and reads no key of the
    /// group. `engines` selects the engines as in
    /// [`commits`](RemoteKeys::commits).
    ///
    /// # Errors
    ///
    /// The errors of [`commits`](RemoteKeys::commits).
    pub async fn summary(
        repo: &Repo,
        remote: &str,
        engines: Option<&[&str]>,
    ) -> Result<RemoteKeys> {
        RemoteKeys::read(repo, remote, false, engines).await
    }

    /// Returns the GPG verifier, or `None` if the switches do not turn on the
    /// GPG check or the selection does not name it.
    pub fn gpg(&self) -> Option<&Arc<dyn Verifier>> {
        self.gpg.as_ref()
    }

    /// Returns one verifier for each sign-api engine that the call builds.
    /// With a selection, the engines are in the order of the selection. With
    /// no selection, a switch that names engines gives them in the order of
    /// its value, and `true` gives each engine of this build that has a
    /// trusted key.
    pub fn sign(&self) -> &[Arc<dyn Verifier>] {
        &self.sign
    }

    /// Reads the verifiers of the commits of `remote` if `commits` is `true`,
    /// or of its summary, for the engines of `engines`.
    async fn read(
        repo: &Repo,
        remote: &str,
        commits: bool,
        engines: Option<&[&str]>,
    ) -> Result<RemoteKeys> {
        if !valid_remote_name(remote) {
            return Err(Error::InvalidInput(format!(
                "invalid remote name: {remote}"
            )));
        }
        let Some(section) = repo.config().remote(remote) else {
            return Err(Error::RemoteNotFound(remote.to_owned()));
        };
        let group = match section.trust()? {
            Some(value) => {
                let group = trust::check_remote_group(repo, remote, &section, &value)?;
                Some((value, group))
            }
            None => None,
        };
        let target = if commits { "commits" } else { "summary" };
        let keyfile = repo.config().keyfile();
        let (gpg, sign) = match &group {
            Some((_, group)) if commits => trust::trust_group_switches(keyfile, group)?,
            _ if commits => (section.gpg_verify()?, section.sign_verify()?),
            _ => (
                section.gpg_verify_summary()?,
                section.sign_verify_summary()?,
            ),
        };
        let (gpg, sign) = match engines {
            Some(names) => select_engines(remote, target, gpg, &sign, names)?,
            None => (gpg, sign),
        };
        if !gpg && sign == SignVerify::Off {
            return Err(no_check(remote, target));
        }
        let policy = match &group {
            Some((value, group)) if commits => {
                trust::trust_group_build(repo, keyfile, value, group, gpg, &sign).await?
            }
            _ => {
                let source = KeySource::Remote {
                    name: remote,
                    section: Some(&section),
                    repo_keyring: true,
                    system_keys: false,
                };
                build_policy(repo, &source, &mut Verifiers::default(), gpg, &sign).await?
            }
        };
        if !policy.applies() {
            return Err(no_check(remote, target));
        }
        Ok(RemoteKeys {
            gpg: policy.gpg,
            sign: policy.sign.unwrap_or_default(),
        })
    }
}

/// Returns the switches of the engines `names` of a remote whose switches are
/// `gpg` and `sign`. `gpg` names the GPG engine, and each other name names a
/// sign-api engine. A name that the switches do not turn on is refused. The
/// sign-api engines are in the order of `names`, each one once, and each one
/// must have a trusted key.
fn select_engines(
    remote: &str,
    target: &str,
    gpg: bool,
    sign: &SignVerify,
    names: &[&str],
) -> Result<(bool, SignVerify)> {
    let mut gpg_selected = false;
    let mut selected: Vec<String> = Vec::with_capacity(names.len());
    for name in names {
        let on = match (*name, sign) {
            ("gpg", _) => gpg,
            (_, SignVerify::Off) => false,
            (_, SignVerify::All) => ALL_ENGINES.contains(name),
            (_, SignVerify::Engines(held)) => held.iter().any(|held| held == name),
        };
        if !on {
            return Err(Error::Signature(format!(
                "remote '{remote}' turns on no {name} check of its {target}"
            )));
        }
        if *name == "gpg" {
            gpg_selected = true;
        } else if !selected.iter().any(|held| held == name) {
            selected.push((*name).to_owned());
        }
    }
    let sign = if selected.is_empty() {
        SignVerify::Off
    } else {
        SignVerify::Engines(selected)
    };
    Ok((gpg_selected, sign))
}

/// Returns the refusal of a remote whose switches turn on no check of
/// `target`.
fn no_check(remote: &str, target: &str) -> Error {
    Error::Signature(format!(
        "remote '{remote}' turns on no signature check of its {target}"
    ))
}

impl std::fmt::Debug for RemoteKeys {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let sign: Vec<&str> = self.sign.iter().map(|v| v.metadata_key()).collect();
        f.debug_struct("RemoteKeys")
            .field("gpg", &self.gpg.is_some())
            .field("sign", &sign)
            .finish()
    }
}

/// The trust types move freely across tasks and threads, so one trust can
/// serve pulls on many tasks.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<TrustedKeys>();
    assert_send_sync::<PullTrust>();
    assert_send_sync::<RemoteKeys>();
};

/// Returns the refusal of a check that takes its keys from the section of a
/// remote, in a pull that names no remote.
fn no_remote() -> Error {
    Error::Pull(
        "a signature check takes its keys from a remote's configuration, so the pull \
         has to name a remote"
            .into(),
    )
}

/// The source of the policy when the options of a pull state no policy.
///
/// A trust group of the pull sets the commit policy whatever the source.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Defaults {
    /// Read the config of the remote. A remote with no section takes the
    /// defaults of a described remote, so the GPG check of the commits is on.
    /// [`Repo::pull`] uses this source.
    Config,
    /// Read the config of the remote if the config has a section for it. A
    /// remote with no section, or no remote, gives no check.
    /// [`Repo::pull_local`] uses this source.
    Section,
}

/// Resolves the summary switches of a pull: the overrides in `verify`, or else
/// the summary keys of `section`. A remote with no section checks no summary.
fn summary_switches(
    section: Option<&Remote<'_>>,
    verify: &PullVerify,
) -> Result<(bool, SignVerify)> {
    let gpg = switch(verify.gpg_summary, || match section {
        Some(section) => section.gpg_verify_summary(),
        None => Ok(false),
    })?;
    let sign = engines(verify.sign_summary, || match section {
        Some(section) => section.sign_verify_summary(),
        None => Ok(SignVerify::Off),
    })?;
    Ok((gpg, sign))
}

/// Resolves one boolean switch: the override of the pull, or else the config.
fn switch(override_: Option<bool>, configured: impl FnOnce() -> Result<bool>) -> Result<bool> {
    match override_ {
        Some(value) => Ok(value),
        None => configured(),
    }
}

/// Resolves one sign-api switch: the override of the pull, or else the config.
///
/// An override of `true` selects each engine of this build.
fn engines(
    override_: Option<bool>,
    configured: impl FnOnce() -> Result<SignVerify>,
) -> Result<SignVerify> {
    match override_ {
        Some(true) => Ok(SignVerify::All),
        Some(false) => Ok(SignVerify::Off),
        None => configured(),
    }
}

/// The sign-api engines that `sign-verify=true` selects: every engine of this
/// build.
///
/// The list does not hold the dummy engine, because its signature is its key.
/// Any writer can make a dummy signature, so a dummy verification proves
/// nothing. If a configuration names `dummy` by hand, `dummy` resolves to no
/// verifier here. The pull then fails as for any other unknown name.
///
/// The `ostree` command has the dummy engine and accepts
/// `sign-verify=ed25519;dummy`.
pub(crate) const ALL_ENGINES: &[&str] = &[
    "ed25519",
    #[cfg(feature = "sign-spki")]
    "spki",
];

/// The signature policy of one target. Each axis of the policy must find a
/// valid signature.
///
/// The policy holds each verifier in an [`Arc`], so the two targets of one pull
/// share the verifiers that both ask for, and a check can run each verifier on
/// the blocking pool. The default policy holds no axis.
#[derive(Clone, Default)]
pub(crate) struct Policy {
    /// The GPG axis, if it applies.
    gpg: Option<Arc<dyn Verifier>>,
    /// The sign-api axis, if it applies, with one verifier for each engine that
    /// the policy names. A valid signature from any one verifier satisfies it.
    sign: Option<Vec<Arc<dyn Verifier>>>,
}

impl Policy {
    /// Returns `true` if this policy holds at least one axis.
    pub(crate) fn applies(&self) -> bool {
        self.gpg.is_some() || self.sign.is_some()
    }

    /// Returns the verifiers of the sign-api axis, or `None` if the axis does
    /// not apply.
    pub(crate) fn sign_axis(&self) -> Option<&[Arc<dyn Verifier>]> {
        self.sign.as_deref()
    }

    /// Creates a policy from the given axes, each present if it applies.
    pub(crate) fn from_axes(
        gpg: Option<Arc<dyn Verifier>>,
        sign: Option<Vec<Arc<dyn Verifier>>>,
    ) -> Policy {
        Policy { gpg, sign }
    }

    /// Returns `true` if the GPG axis applies.
    pub(crate) fn gpg_axis(&self) -> bool {
        self.gpg.is_some()
    }

    /// Verifies the signatures over `payload` on every axis of this policy.
    ///
    /// `signatures` is the detached-metadata dict that holds the signatures. It
    /// is `None` if the payload carries no signatures. `subject` names the
    /// payload in an error message.
    ///
    /// The verifiers run on the blocking pool, because a verifier does its
    /// work in the call. The verifiers of one axis run in one call. The axes
    /// share one copy of `payload` on the pool. [`Payload`] states when the
    /// check makes this copy.
    pub(crate) async fn check<'p>(
        &self,
        subject: &str,
        payload: impl Into<Payload<'p>>,
        signatures: Option<&Value>,
    ) -> Result<()> {
        let mut payload = PoolCopy::new(payload.into());
        if let Some(gpg) = &self.gpg {
            check_axis(
                subject,
                "GPG",
                std::slice::from_ref(gpg),
                &mut payload,
                signatures,
            )
            .await?;
        }
        if let Some(engines) = &self.sign {
            check_axis(subject, "sign-api", engines, &mut payload, signatures).await?;
        }
        Ok(())
    }
}

/// The payload of a signature check, as the caller holds it.
///
/// The verifiers of a check run on the blocking pool, and the pool gets the
/// payload in an [`Arc`]. If the caller holds the payload in an `Arc`, it
/// gives [`Payload::Shared`], and the pool gets no copy. The check copies a
/// [`Payload::Borrowed`] payload one time, when the first axis with a
/// signature goes to the pool.
#[derive(Clone, Copy)]
pub(crate) enum Payload<'a> {
    /// A payload that the caller borrows.
    Borrowed(&'a [u8]),
    /// A payload that the caller holds in an [`Arc`].
    Shared(&'a Arc<Vec<u8>>),
}

impl<'a> Payload<'a> {
    /// Returns the bytes of the payload.
    #[cfg_attr(not(feature = "receive"), allow(dead_code))]
    pub(crate) fn bytes(self) -> &'a [u8] {
        match self {
            Payload::Borrowed(bytes) => bytes,
            Payload::Shared(bytes) => bytes,
        }
    }

    /// Returns the payload in an [`Arc`] for the blocking pool. A shared
    /// payload gives a clone of its `Arc`, and a borrowed payload gives a
    /// copy.
    pub(crate) fn to_shared(self) -> Arc<Vec<u8>> {
        match self {
            Payload::Borrowed(bytes) => Arc::new(bytes.to_vec()),
            Payload::Shared(bytes) => Arc::clone(bytes),
        }
    }
}

impl<'a> From<&'a [u8]> for Payload<'a> {
    fn from(bytes: &'a [u8]) -> Payload<'a> {
        Payload::Borrowed(bytes)
    }
}

impl<'a> From<&'a Arc<Vec<u8>>> for Payload<'a> {
    fn from(bytes: &'a Arc<Vec<u8>>) -> Payload<'a> {
        Payload::Shared(bytes)
    }
}

/// The payload of one check, with the copy that its verifiers share on the
/// blocking pool.
struct PoolCopy<'a> {
    payload: Payload<'a>,
    /// The copy of a borrowed payload, made when the first axis goes to the
    /// pool.
    copy: Option<Arc<Vec<u8>>>,
}

impl<'a> PoolCopy<'a> {
    fn new(payload: Payload<'a>) -> PoolCopy<'a> {
        PoolCopy {
            payload,
            copy: None,
        }
    }

    /// Returns the payload for the verifiers of one axis on the pool. The first
    /// call for a borrowed payload copies it.
    fn shared(&mut self) -> Arc<Vec<u8>> {
        match self.payload {
            Payload::Shared(bytes) => Arc::clone(bytes),
            Payload::Borrowed(_) => {
                Arc::clone(self.copy.get_or_insert_with(|| self.payload.to_shared()))
            }
        }
    }
}

/// The result of the verification of a payload on one axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Found {
    /// One of the verifiers accepted a signature.
    Valid,
    /// The payload carries signatures that the axis reads, and no verifier
    /// accepted one.
    Untrusted,
    /// The payload carries no signature that a verifier of the axis reads.
    Nothing,
}

/// Verifies `payload` on one axis and reports what it found.
///
/// The result tells if any of `verifiers` reports a valid signature over the
/// payload, and if a signature was there to verify. The callers keep the last
/// two cases apart, as the `ostree` command does. For a commit or a summary,
/// [`Found::Nothing`] is a refusal. An unsigned static delta gives
/// [`Found::Nothing`], and the delta check accepts it.
///
/// The search reads the blobs of each verifier before the verifiers run. The
/// verifiers that have a blob then run in one call on the blocking pool, in
/// order, with the payload that they share. The call stops at the first valid
/// signature. [`Payload`] states when the check copies the payload.
pub(crate) async fn examine<'p>(
    verifiers: &[Arc<dyn Verifier>],
    payload: impl Into<Payload<'p>>,
    signatures: Option<&Value>,
) -> Result<Found> {
    examine_pooled(verifiers, &mut PoolCopy::new(payload.into()), signatures).await
}

/// Verifies `payload` on one axis as [`examine`] does. The verifiers get the
/// shared copy of `payload` in one call on the blocking pool. An axis with no
/// blob gets no copy.
async fn examine_pooled(
    verifiers: &[Arc<dyn Verifier>],
    payload: &mut PoolCopy<'_>,
    signatures: Option<&Value>,
) -> Result<Found> {
    let Some(dict) = signatures else {
        return Ok(Found::Nothing);
    };
    let jobs: Vec<Job> = verifiers
        .iter()
        .filter_map(|verifier| {
            let blobs = signatures_for(dict, verifier.metadata_key());
            (!blobs.is_empty()).then(|| (Arc::clone(verifier), blobs))
        })
        .collect();
    if jobs.is_empty() {
        return Ok(Found::Nothing);
    }
    let payload = payload.shared();
    if ostrya_rt::unblock(move || first_valid(&jobs, &payload)).await? {
        Ok(Found::Valid)
    } else {
        Ok(Found::Untrusted)
    }
}

/// A verifier of an axis and the blobs that the search reads for it.
type Job = (Arc<dyn Verifier>, Vec<Vec<u8>>);

/// Runs each verifier of `jobs` over `payload` with its blobs, in order.
/// Returns `true` at the first valid signature, and the verifiers after it do
/// not run. Returns the first error of a verifier.
fn first_valid(jobs: &[Job], payload: &[u8]) -> ostrya_sign::Result<bool> {
    for (verifier, blobs) in jobs {
        if verifier.verify(payload, blobs)?.valid {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Verifies `payload` on one axis, and refuses it if no key of the axis signed
/// it or if it carries no signature. The verifiers run on the blocking pool.
async fn check_axis(
    subject: &str,
    axis: &str,
    verifiers: &[Arc<dyn Verifier>],
    payload: &mut PoolCopy<'_>,
    signatures: Option<&Value>,
) -> Result<()> {
    match examine_pooled(verifiers, payload, signatures).await? {
        Found::Valid => Ok(()),
        Found::Untrusted => Err(Error::Signature(format!(
            "{subject}: no {axis} signature is from a trusted key"
        ))),
        Found::Nothing => Err(Error::Signature(format!(
            "{subject}: {axis} verification is enabled, but it carries no signature"
        ))),
    }
}

/// The origin of the trusted keys of a policy.
pub(crate) enum KeySource<'a> {
    /// The configuration section of a remote, as a pull reads it. `section` is
    /// `None` for a remote that the configuration does not describe.
    Remote {
        /// The name of the remote, which names its keyrings.
        name: &'a str,
        /// The configuration section of the remote.
        section: Option<&'a Remote<'a>>,
        /// If `true`, the `<remote>.trustedkeys.gpg` file of the repository
        /// adds to the GPG trusted set.
        #[cfg_attr(not(feature = "verify-gpg"), allow(dead_code))]
        repo_keyring: bool,
        /// If `true`, the system sign-api key store adds to the keys of the
        /// remote, as in a pull. The global GPG trusted directory also adds
        /// its keys, but only when no keyring of the remote exists in the
        /// repository or in `/etc/ostree/remotes.d`. If `false`, the keys are
        /// the keys of the remote alone, and a GPG axis whose keyrings hold no
        /// certificate is refused.
        system_keys: bool,
    },
    /// A trust group, `[ex-ostrya trust "NAME"]`. The accessors of a remote
    /// section read it.
    Trust {
        /// The name of the group, which a refusal names.
        name: &'a str,
        /// The group, read as a remote section.
        section: &'a Remote<'a>,
    },
}

impl KeySource<'_> {
    /// Returns the inline trusted key for one sign-api engine.
    fn verification_key(&self, engine: &str) -> Result<Option<String>> {
        match self {
            KeySource::Remote { section, .. } => match section {
                Some(section) => section.verification_key(engine),
                None => Ok(None),
            },
            KeySource::Trust { section, .. } => section.verification_key(engine),
        }
    }

    /// Returns the path of a file of trusted keys for one sign-api engine.
    fn verification_file(&self, engine: &str) -> Result<Option<String>> {
        match self {
            KeySource::Remote { section, .. } => match section {
                Some(section) => section.verification_file(engine),
                None => Ok(None),
            },
            KeySource::Trust { section, .. } => section.verification_file(engine),
        }
    }

    /// Returns `true` if the system key store and its revoked set add to the
    /// keys that this source names.
    fn system_store(&self) -> bool {
        match self {
            KeySource::Remote { system_keys, .. } => *system_keys,
            KeySource::Trust { .. } => false,
        }
    }
}

/// The verifiers that one policy build makes, each from one read of its key
/// sources.
///
/// Both targets of a pull take their keys from the same remote. If the commit
/// policy and the summary policy ask for the same verifier, the build makes it
/// once and both policies hold it. A pull from a remote with a trust group
/// takes its commit keys from the group, so each target gets its own set.
#[derive(Default)]
pub(crate) struct Verifiers {
    /// The GPG verifier, built for the first target that asks for it.
    gpg: Option<Arc<dyn Verifier>>,
    /// One entry for each sign-api engine that a target asks for. An entry is
    /// `None` if no source holds a key for that engine.
    sign: Vec<(String, Option<Arc<dyn Verifier>>)>,
}

impl Verifiers {
    /// Returns the GPG verifier for `source`, from one read of its keyrings.
    async fn gpg(&mut self, repo: &Repo, source: &KeySource<'_>) -> Result<Arc<dyn Verifier>> {
        match &self.gpg {
            Some(verifier) => Ok(Arc::clone(verifier)),
            None => {
                let verifier = gpg_verifier(repo, source).await?;
                self.gpg = Some(Arc::clone(&verifier));
                Ok(verifier)
            }
        }
    }

    /// Returns the verifier for one sign-api engine, from one read of its key
    /// sources.
    ///
    /// `None` means that the engine has no key to verify with.
    async fn sign(
        &mut self,
        engine: &str,
        source: &KeySource<'_>,
    ) -> Result<Option<Arc<dyn Verifier>>> {
        if let Some((_, verifier)) = self.sign.iter().find(|(name, _)| name == engine) {
            return Ok(verifier.clone());
        }
        let verifier = sign_verifier(engine, source).await?;
        self.sign.push((engine.to_owned(), verifier.clone()));
        Ok(verifier)
    }
}

/// Builds the policy of one target from the two resolved switches.
///
/// Each verifier comes from `cache`, so the policy of the other target shares
/// it.
pub(crate) async fn build_policy(
    repo: &Repo,
    source: &KeySource<'_>,
    cache: &mut Verifiers,
    gpg: bool,
    sign: &SignVerify,
) -> Result<Policy> {
    let mut policy = Policy::default();
    if gpg {
        policy.gpg = Some(cache.gpg(repo, source).await?);
    }
    // If the configuration names an engine by hand, the engine must have a key.
    // The configuration asks for it, and an engine with no key refuses every
    // signature. `sign-verify=true` names every engine of this build. Under it,
    // the build skips an engine with no key, and refuses only a policy that
    // ends with no engine. The `ostree` command reports the two cases
    // separately too.
    let (names, required): (Vec<String>, bool) = match sign {
        SignVerify::Off => (Vec::new(), false),
        SignVerify::All => (
            ALL_ENGINES.iter().map(|name| (*name).to_owned()).collect(),
            false,
        ),
        SignVerify::Engines(names) => (each_engine_once(names), true),
    };
    if !names.is_empty() {
        let mut verifiers: Vec<Arc<dyn Verifier>> = Vec::with_capacity(names.len());
        for name in &names {
            match cache.sign(name, source).await? {
                Some(verifier) => verifiers.push(verifier),
                None if required => {
                    return Err(Error::Signature(format!(
                        "no trusted key for signature engine '{name}'"
                    )));
                }
                None => {}
            }
        }
        if verifiers.is_empty() {
            return Err(Error::Signature(
                "signature verification is enabled, but no engine of this build \
                 has a trusted key"
                    .into(),
            ));
        }
        policy.sign = Some(verifiers);
    }
    Ok(policy)
}

/// Returns the engine names of a `sign-verify` value, each name once, at the
/// place where the value first names it.
///
/// `ostrya remote add` writes `sign-verify=ed25519,ed25519` for an engine
/// given twice.
/// With one verifier for each name, the build verifies each signature against
/// the keys of that engine as many times as the value names it.
fn each_engine_once(names: &[String]) -> Vec<String> {
    let mut kept: Vec<String> = Vec::with_capacity(names.len());
    for name in names {
        if !kept.iter().any(|held| held == name) {
            kept.push(name.clone());
        }
    }
    kept
}

/// Builds the GPG verifier for a key source.
///
/// For a remote, the trusted set has these parts:
///
/// - the keyring of the repository for the remote, read through the repository
///   descriptor, if the source asks for it
/// - the system keyring of the remote
/// - the global trusted set, if the source asks for the system keys and
///   neither keyring of the remote exists
/// - the keyrings that `gpgkeypath` names
///
/// The keyrings of the remote and the global keyring files must be binary
/// OpenPGP packet streams. The rules are those of
/// [`for_remote_keyrings`](crate::gpg::FromOstreeKeyrings::for_remote_keyrings).
///
/// A remote source without the system keys refuses a trusted set that holds
/// no certificate.
///
/// For a trust group, the trusted set is the keyrings that its `gpgkeypath`
/// names, and nothing else.
#[cfg(feature = "verify-gpg")]
async fn gpg_verifier(repo: &Repo, source: &KeySource<'_>) -> Result<Arc<dyn Verifier>> {
    let verifier = match source {
        KeySource::Remote {
            name,
            section,
            repo_keyring,
            system_keys,
        } => {
            let keyring = if *repo_keyring {
                read_repo_keyring(repo, name).await?
            } else {
                None
            };
            let keypath = match section {
                Some(section) => section.gpgkeypath()?,
                None => Vec::new(),
            };
            let remote = (*name).to_owned();
            let global = *system_keys;
            let verifier = ostrya_rt::unblock(move || {
                crate::gpg::remote_keyrings(keyring, &remote, &keypath, global)
            })
            .await?;
            if !global && verifier.is_empty() {
                return Err(Error::Signature(format!(
                    "remote '{name}' asks for GPG verification, and its keyrings hold no \
                     certificate"
                )));
            }
            verifier
        }
        KeySource::Trust { name, section } => {
            let keypath = section.gpgkeypath()?;
            let key = format!("[ex-ostrya trust \"{name}\"] gpgkeypath");
            ostrya_rt::unblock(move || crate::gpg::from_keypath(&key, &keypath)).await?
        }
    };
    Ok(Arc::new(verifier))
}

/// Returns [`Error::Unsupported`], because a build without the GPG engine
/// cannot verify a GPG axis.
///
/// The build refuses, so it never passes a commit that it did not verify.
#[cfg(not(feature = "verify-gpg"))]
async fn gpg_verifier(_repo: &Repo, source: &KeySource<'_>) -> Result<Arc<dyn Verifier>> {
    match source {
        KeySource::Remote { name, .. } => Err(Error::Unsupported(format!(
            "remote '{name}' asks for GPG verification, which this build has no \
             engine for; build with the verify-gpg feature or set gpg-verify=false"
        ))),
        KeySource::Trust { name, .. } => Err(Error::Unsupported(format!(
            "[ex-ostrya trust \"{name}\"] asks for GPG verification, which this \
             build has no engine for; build with the verify-gpg feature"
        ))),
    }
}

/// The engines that this build verifies with.
///
/// The build resolves a name to one of these engines before it reads a key
/// source.
enum Engine {
    Ed25519,
    #[cfg(feature = "sign-spki")]
    Spki,
}

/// Builds the verifier for one sign-api engine from the keys that `source`
/// names.
///
/// For a remote, the keys of the system key store add to these keys.
///
/// `None` means that the engine has no key to verify with. The policy decides
/// the result. It refuses an engine that it names by hand. It skips an engine
/// that it reached through a value that names every engine.
async fn sign_verifier(engine: &str, source: &KeySource<'_>) -> Result<Option<Arc<dyn Verifier>>> {
    let kind = match engine {
        "ed25519" => Engine::Ed25519,
        #[cfg(feature = "sign-spki")]
        "spki" => Engine::Spki,
        _ => {
            return Err(Error::Unsupported(format!(
                "signature engine '{engine}' is not one this build verifies with"
            )));
        }
    };
    let Some(keys) = sign_keys(engine, source).await? else {
        return Ok(None);
    };
    build_verifier(kind, keys)
}

/// Builds the verifier of one engine over the keys of its sources, or returns
/// `None` if the engine has no key left.
///
/// The engine applies the revoked set when it matches keys. Each engine uses
/// its own key equality. The set of keys that is left after this step decides.
///
/// If the store revokes the only key that the sources hold, the engine has no
/// key, and the function returns `None`. A verifier with no key refuses every
/// commit with an error about the signature of the commit. That error does not
/// name the cause, the revocation.
fn build_verifier(kind: Engine, keys: SignKeys) -> Result<Option<Arc<dyn Verifier>>> {
    Ok(match kind {
        Engine::Ed25519 => {
            let verifier = Ed25519Verifier::from_sign_keys(keys)?;
            (!verifier.is_empty()).then(|| Arc::new(verifier) as Arc<dyn Verifier>)
        }
        #[cfg(feature = "sign-spki")]
        Engine::Spki => {
            let verifier = crate::spki::SpkiVerifier::from_sign_keys(keys)?;
            (!verifier.is_empty()).then(|| Arc::new(verifier) as Arc<dyn Verifier>)
        }
    })
}

/// Returns the trusted and revoked keys for one engine.
///
/// The keys come from the inline key and the key file of the source. For a
/// remote, the system key store adds its keys, and its revoked set applies to
/// all of them.
///
/// This function reads the configuration. The blocking pool reads the paths
/// that the configuration names, so a slow path holds a pool thread and cannot
/// hold an executor thread.
///
/// `None` means that no source holds a key for the engine.
async fn sign_keys(engine: &str, source: &KeySource<'_>) -> Result<Option<SignKeys>> {
    let inline = source.verification_key(engine)?;
    let path = source.verification_file(engine)?;
    let system = source.system_store();
    let engine = engine.to_owned();
    ostrya_rt::unblock(move || read_sign_keys(&engine, inline, path, system)).await
}

/// Runs the blocking half of [`sign_keys`].
///
/// The function decodes the inline key and reads the key file. If `system` is
/// `true`, it adds the keys of the system key store.
///
/// The inline key is base64. For the spki engine, the function removes each
/// white space character of the key before the decode, so the key can hold
/// the line breaks of a PEM body. White space is space, horizontal tab, LF,
/// form feed, and CR. For the other engines, the function removes the leading
/// and trailing white space alone. Then it decodes the key with
/// `base64::decode`.
fn read_sign_keys(
    engine: &str,
    inline: Option<String>,
    path: Option<String>,
    system: bool,
) -> Result<Option<SignKeys>> {
    let mut keys = SignKeys::default();
    if let Some(mut inline) = inline {
        if engine == "spki" {
            inline.retain(|c| !c.is_ascii_whitespace());
        }
        keys.trusted.push(base64::decode(inline.trim())?);
    }
    if let Some(path) = path {
        keys.trusted.extend(read_verification_file(engine, &path)?);
    }
    if system {
        let store = load_sign_keys(engine)?;
        keys.trusted.extend(store.trusted);
        keys.revoked.extend(store.revoked);
    }
    if keys.trusted.is_empty() {
        return Ok(None);
    }
    Ok(Some(keys))
}

/// Reads the `<remote>.trustedkeys.gpg` file of the repository, up to
/// [`MAX_KEYRING`](ostrya_sign::MAX_KEYRING) bytes.
///
/// Returns `None` if the repository holds no such file. The name resolves
/// through the repository descriptor on the blocking pool. A keyring on a slow
/// file system holds a pool thread and cannot hold an executor thread.
#[cfg(feature = "verify-gpg")]
async fn read_repo_keyring(repo: &Repo, remote: &str) -> Result<Option<Vec<u8>>> {
    let repo_fd = repo.repo_fd().try_clone_to_owned()?;
    let name = format!("{remote}.trustedkeys.gpg");
    ostrya_rt::unblock(move || read_keyring_blocking(repo_fd.as_fd(), &name)).await
}

/// Runs the blocking half of [`read_repo_keyring`].
///
/// The name resolves against the repository descriptor. The bytes come through
/// [`read_keyring_fd`], which applies the same rule to every other keyring
/// source. If a symlink is at the name, the read follows it. The `ostree`
/// command was observed to follow it too.
#[cfg(feature = "verify-gpg")]
fn read_keyring_blocking(repo_fd: BorrowedFd<'_>, name: &str) -> Result<Option<Vec<u8>>> {
    // `NONBLOCK` makes a fifo answer the open at once. Without it, the open
    // waits for a writer. On a regular file, the flag has no effect on the
    // read that the reader makes.
    let fd = match rustix::fs::openat(
        repo_fd,
        name,
        OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
        Mode::empty(),
    ) {
        Ok(fd) => fd,
        Err(Errno::NOENT) => return Ok(None),
        Err(e) => {
            return Err(Error::Signature(format!(
                "the keyring '{name}' cannot be opened: {e}"
            )));
        }
    };
    read_keyring_fd(fd, name).map(Some)
}

/// Reads the keys of one `verification-<engine>-file`, up to [`MAX_KEY_FILE`]
/// bytes, under the rule that [`read_key_source`] states.
///
/// The function opens the path once and reads it through the ceiling, so the
/// keys come from the bytes that the ceiling admits. It refuses a file of
/// another kind, a file over the ceiling, and a file that it cannot read. Each
/// error names the file, so an operator can find the entry that names it.
///
/// A file of the spki engine holds PEM `PUBLIC KEY` blocks, which
/// `spki_public_keys` reads. An empty file adds no keys. A file of another
/// engine holds one base64 key on each line, and the function skips a line of
/// white space only.
fn read_verification_file(engine: &str, path: &str) -> Result<Vec<Vec<u8>>> {
    let subject = format!("the '{engine}' key file '{path}'");
    // `NONBLOCK` makes a fifo answer the open at once. Without it, the open
    // waits for a writer. On a regular file, the flag has no effect on the
    // later read.
    let fd = rustix::fs::open(
        path,
        OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
        Mode::empty(),
    )
    .map_err(|e| Error::Signature(format!("{subject} cannot be read: {e}")))?;
    let bytes = read_key_source(std::fs::File::from(fd), &subject, MAX_KEY_FILE)?;
    #[cfg(feature = "sign-spki")]
    if engine == "spki" {
        return Ok(crate::spki::spki_public_keys(&bytes, &subject)?);
    }
    let mut keys = Vec::new();
    for line in key_text(bytes, &subject)?.lines() {
        let line = line.trim();
        if !line.is_empty() {
            keys.push(base64::decode(line)?);
        }
    }
    Ok(keys)
}

#[cfg(test)]
mod tests {
    use rustix::fs::FileType;

    use super::*;

    /// A remote that the configuration does not describe.
    const NO_SECTION: KeySource<'static> = KeySource::Remote {
        name: "origin",
        section: None,
        repo_keyring: true,
        system_keys: true,
    };

    /// 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=";

    const PAYLOAD: &[u8] = b"the commit bytes";

    /// A P-256 secret key, base64 of the PKCS#8 DER.
    #[cfg(feature = "sign-spki")]
    const SPKI_SECRET_A: &str = concat!(
        "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg2L708EsnnzHER0SYasMNIUcG",
        "v63QapC/3kVsoPerzKGhRANCAATxfzfHKUPeJtyLTGMUoxHhvBS1NT9guWhUQPGiZRLZIcB8Wc3",
        "csdVU1iOiTRmbZGKJTtekOdEAbVRrx5HxIpst",
    );
    /// A second P-256 secret key, base64 of the PKCS#8 DER.
    #[cfg(feature = "sign-spki")]
    const SPKI_SECRET_B: &str = concat!(
        "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgU5tYPz/hTTxfsSTPOxD/H9U+",
        "IkBj5qWV4/H3D1NBfRChRANCAAQPyTr9rh2d6WiYOi3oxNiE3ppTP2g5JP2xX9D7rEKnzixp",
        "MqVuqA9XnzQr5GlCYd71m/D7BnYIqS4MytNawYrR",
    );

    /// The ed25519 signature of `secret` over [`PAYLOAD`], in its dict.
    fn ed25519_signed(secret: &str) -> Value {
        use crate::sign::{Ed25519Signer, Signer, append_signature};

        let signer = Ed25519Signer::from_base64(secret).unwrap();
        let blob = ostrya_rt::block_on(signer.sign(PAYLOAD)).unwrap();
        let mut dict = Value::Array(Vec::new());
        append_signature(&mut dict, signer.metadata_key(), blob).unwrap();
        dict
    }

    /// An override takes precedence over the config. With no override, the
    /// config applies.
    #[test]
    fn switches_resolve_the_override_first() {
        assert!(switch(Some(true), || Ok(false)).unwrap());
        assert!(!switch(Some(false), || Ok(true)).unwrap());
        assert!(switch(None, || Ok(true)).unwrap());

        assert_eq!(
            engines(Some(true), || Ok(SignVerify::Off)).unwrap(),
            SignVerify::All
        );
        assert_eq!(
            engines(Some(false), || Ok(SignVerify::All)).unwrap(),
            SignVerify::Off
        );
        assert_eq!(
            engines(None, || Ok(SignVerify::Engines(vec!["ed25519".to_owned()]))).unwrap(),
            SignVerify::Engines(vec!["ed25519".to_owned()])
        );
    }

    /// `TrustedKeys::new` refuses an empty set, and a set with one verifier
    /// verifies a signature from its key.
    #[test]
    fn explicit_keys_need_a_verifier() {
        let err = TrustedKeys::new(Vec::new()).unwrap_err();
        assert!(matches!(err, Error::InvalidFormat(_)), "{err}");
        let verifier =
            Ed25519Verifier::new([base64::decode(PUBLIC_B64).unwrap()], Vec::<Vec<u8>>::new())
                .unwrap();
        let keys = TrustedKeys::new(vec![Arc::new(verifier)]).unwrap();
        ostrya_rt::block_on(keys.policy.check(
            "commit",
            PAYLOAD,
            Some(&ed25519_signed(SECRET_B64)),
        ))
        .unwrap();
    }

    /// A policy check runs the verifier of each axis on the blocking pool, so
    /// a verifier that works in the call does not hold the async executor.
    #[test]
    fn each_axis_verifies_on_the_blocking_pool() {
        use crate::sign::append_signature;
        use crate::verify::trust::tests::ThreadRecorder;

        let gpg = ThreadRecorder::new("ostree.gpgsigs");
        let sign = ThreadRecorder::new("ostree.sign.ed25519");
        let policy = Policy::from_axes(
            Some(Arc::new(gpg.clone())),
            Some(vec![Arc::new(sign.clone())]),
        );
        let mut dict = Value::Array(Vec::new());
        append_signature(&mut dict, "ostree.gpgsigs", vec![1; 8]).unwrap();
        append_signature(&mut dict, "ostree.sign.ed25519", vec![7; 64]).unwrap();
        ostrya_rt::block_on(policy.check("commit", PAYLOAD, Some(&dict))).unwrap();
        gpg.assert_one_foreign_call();
        sign.assert_one_foreign_call();
        // The two axes share one copy of a borrowed payload.
        let (gpg, sign) = (gpg.payloads(), sign.payloads());
        assert_eq!(gpg, sign);
        assert_eq!(gpg[0].1, PAYLOAD);
        assert_ne!(gpg[0].0, PAYLOAD.as_ptr() as usize);
    }

    /// A policy check gives a payload in an [`Arc`] to the verifier of each
    /// axis with no copy.
    #[test]
    fn a_shared_payload_reaches_each_axis_with_no_copy() {
        use crate::sign::append_signature;
        use crate::verify::trust::tests::ThreadRecorder;

        let gpg = ThreadRecorder::new("ostree.gpgsigs");
        let sign = ThreadRecorder::new("ostree.sign.ed25519");
        let policy = Policy::from_axes(
            Some(Arc::new(gpg.clone())),
            Some(vec![Arc::new(sign.clone())]),
        );
        let mut dict = Value::Array(Vec::new());
        append_signature(&mut dict, "ostree.gpgsigs", vec![1; 8]).unwrap();
        append_signature(&mut dict, "ostree.sign.ed25519", vec![7; 64]).unwrap();
        let payload = Arc::new(PAYLOAD.to_vec());
        ostrya_rt::block_on(policy.check("commit", &payload, Some(&dict))).unwrap();
        gpg.assert_no_copy_of(&payload);
        sign.assert_no_copy_of(&payload);
    }

    /// The verifiers of an axis stop at the first valid signature. A verifier
    /// after it does not run, though the payload carries its blobs.
    #[test]
    fn an_axis_stops_at_the_first_valid_signature() {
        use crate::sign::append_signature;
        use crate::verify::trust::tests::ThreadRecorder;

        let first = ThreadRecorder::new("ostree.sign.ed25519");
        let second = ThreadRecorder::new("ostree.sign.spki");
        let policy = Policy::from_axes(
            None,
            Some(vec![Arc::new(first.clone()), Arc::new(second.clone())]),
        );
        let mut dict = Value::Array(Vec::new());
        append_signature(&mut dict, "ostree.sign.ed25519", vec![7; 64]).unwrap();
        append_signature(&mut dict, "ostree.sign.spki", vec![9; 64]).unwrap();
        ostrya_rt::block_on(policy.check("commit", PAYLOAD, Some(&dict))).unwrap();
        first.assert_one_foreign_call();
        assert!(second.threads().is_empty());
    }

    /// An axis whose verifiers find no blob calls no verifier, and the check
    /// refuses the payload as unsigned.
    #[test]
    fn an_axis_with_no_blob_calls_no_verifier() {
        use crate::verify::trust::tests::{ThreadRecorder, dict_with};

        let first = ThreadRecorder::new("ostree.sign.ed25519");
        let second = ThreadRecorder::new("ostree.sign.spki");
        let policy = Policy::from_axes(
            None,
            Some(vec![Arc::new(first.clone()), Arc::new(second.clone())]),
        );
        let dict = dict_with("ostree.sign.other", vec![7; 64]);
        let err = ostrya_rt::block_on(policy.check("commit", PAYLOAD, Some(&dict))).unwrap_err();
        assert!(
            err.to_string()
                .contains("sign-api verification is enabled, but it carries no signature"),
            "{err}"
        );
        assert!(first.threads().is_empty());
        assert!(second.threads().is_empty());
    }

    /// The verifiers of an axis run in one call on the blocking pool. One poll
    /// of the check gives a verifier that rejects its blobs and the verifier
    /// after it to the pool.
    #[test]
    fn the_verifiers_of_an_axis_run_in_one_call() {
        use std::task::Poll;
        use std::time::{Duration, Instant};

        use crate::sign::append_signature;
        use crate::verify::trust::tests::ThreadRecorder;

        let rejecting = ThreadRecorder::rejecting("ostree.sign.ed25519");
        let accepting = ThreadRecorder::new("ostree.sign.spki");
        let policy = Policy::from_axes(
            None,
            Some(vec![
                Arc::new(rejecting.clone()),
                Arc::new(accepting.clone()),
            ]),
        );
        let mut dict = Value::Array(Vec::new());
        append_signature(&mut dict, "ostree.sign.ed25519", vec![7; 64]).unwrap();
        append_signature(&mut dict, "ostree.sign.spki", vec![9; 64]).unwrap();
        ostrya_rt::block_on(async {
            let mut check = std::pin::pin!(policy.check("commit", PAYLOAD, Some(&dict)));
            // The test does not poll the check again before the accepting
            // verifier runs. Thus the one poll gives each verifier of the
            // axis to the pool.
            let first = std::future::poll_fn(|cx| Poll::Ready(check.as_mut().poll(cx))).await;
            match first {
                Poll::Ready(result) => {
                    result.unwrap();
                    assert_eq!(accepting.threads().len(), 1);
                }
                Poll::Pending => {
                    let deadline = Instant::now() + Duration::from_secs(5);
                    while accepting.threads().is_empty() && Instant::now() < deadline {
                        std::thread::sleep(Duration::from_millis(1));
                    }
                    assert_eq!(accepting.threads().len(), 1);
                    check.await.unwrap();
                }
            }
        });
        rejecting.assert_one_foreign_call();
        accepting.assert_one_foreign_call();
    }

    /// `TrustedKeys::new` refuses a dummy verifier, alone and next to a real
    /// engine.
    #[test]
    fn explicit_keys_refuse_the_dummy_engine() {
        let dummy = || -> Arc<dyn Verifier> { Arc::new(crate::sign::DummyVerifier::new([b"k"])) };
        let ed25519: Arc<dyn Verifier> = Arc::new(
            Ed25519Verifier::new([base64::decode(PUBLIC_B64).unwrap()], Vec::<Vec<u8>>::new())
                .unwrap(),
        );
        for sign in [vec![dummy()], vec![ed25519, dummy()]] {
            let err = TrustedKeys::new(sign).unwrap_err();
            assert!(
                matches!(&err, Error::InvalidFormat(m) if m.contains("dummy verifier")),
                "{err}"
            );
        }
    }

    /// `sign-verify=true` names the engines of this build. It never names the
    /// dummy engine, because the dummy signature is its key.
    #[test]
    fn all_engines_excludes_the_dummy_engine() {
        assert!(ALL_ENGINES.contains(&"ed25519"));
        assert!(!ALL_ENGINES.contains(&"dummy"));
    }

    /// `sign_verifier` refuses by name an engine that no build verifies with.
    /// For an engine that no source holds a key for, it reports no key. The
    /// policy reads that report to refuse an engine that it names by hand.
    #[test]
    fn unknown_engines_and_empty_key_sets_are_told_apart() {
        ostrya_rt::block_on(async {
            let Err(err) = sign_verifier("nosuchengine", &NO_SECTION).await else {
                panic!("an engine this build has no verifier for is refused");
            };
            assert!(
                err.to_string().contains("not one this build verifies with"),
                "{err}"
            );
            // There is no remote section. On a host with no key store of its
            // own, the engine has no key at all.
            if load_sign_keys("ed25519").unwrap().trusted.is_empty() {
                assert!(
                    sign_verifier("ed25519", &NO_SECTION)
                        .await
                        .unwrap()
                        .is_none()
                );
            }
        });
    }

    /// `sign_verifier` refuses a configuration that names the dummy engine, by
    /// that name. The dummy signature is the bytes of the dummy key. A commit
    /// verified against it passes a verification that reads no key.
    #[test]
    fn the_dummy_engine_is_refused_by_name() {
        ostrya_rt::block_on(async {
            let Err(err) = sign_verifier("dummy", &NO_SECTION).await else {
                panic!("a configuration naming the dummy engine is refused");
            };
            assert!(
                err.to_string().contains("not one this build verifies with"),
                "{err}"
            );
        });
    }

    /// If the store revokes the only key of an engine, the engine has no key at
    /// all. The set of keys that is left after the revoked set applies decides.
    ///
    /// The policy then reports the engine. It refuses an engine that the
    /// configuration names by hand. It skips an engine that it reached through
    /// a value that names every engine. No commit goes to a verifier that
    /// trusts nothing.
    ///
    /// The test makes the decision at this level because the revoked set comes
    /// from the system key store. The store is under `/etc/ostree` and
    /// `/usr/share/ostree`, and a test cannot write there.
    #[test]
    fn a_revoked_key_leaves_the_engine_without_a_key() {
        const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
        let key = base64::decode(PUBLIC_B64).unwrap();

        let held = SignKeys {
            trusted: vec![key.clone()],
            revoked: Vec::new(),
        };
        assert!(
            build_verifier(Engine::Ed25519, held).unwrap().is_some(),
            "a key no source revokes builds a verifier"
        );

        let revoked = SignKeys {
            trusted: vec![key.clone()],
            revoked: vec![key],
        };
        assert!(
            build_verifier(Engine::Ed25519, revoked).unwrap().is_none(),
            "the engine's only key is revoked, so the engine has no key"
        );
    }

    /// An engine that the value names twice builds one verifier, so each
    /// signature gets one verification against the keys of that engine.
    /// `ostrya remote add` writes such a value for an engine given twice.
    #[test]
    fn a_repeated_engine_name_builds_one_verifier() {
        use crate::{CreateOptions, RepoMode};

        const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
        let config = crate::config::RepoConfig::parse(&format!(
            "[core]\nrepo_version=1\nmode=archive\n\
             [remote \"origin\"]\nurl=http://localhost/\n\
             sign-verify=ed25519,ed25519\nverification-ed25519-key={PUBLIC_B64}\n"
        ))
        .unwrap();
        let section = config.remote("origin");
        let sign = section.as_ref().unwrap().sign_verify().unwrap();
        assert_eq!(
            sign,
            SignVerify::Engines(vec!["ed25519".to_owned(), "ed25519".to_owned()]),
            "the configured value names the engine twice"
        );

        let dir = std::env::temp_dir().join(format!(
            "ostrya-verify-repeat-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        let root = dir.join("repo");
        std::fs::create_dir_all(&dir).unwrap();
        let outcome = ostrya_rt::block_on(async {
            let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
                .await
                .unwrap();
            let mut cache = Verifiers::default();
            let source = KeySource::Remote {
                name: "origin",
                section: section.as_ref(),
                repo_keyring: true,
                system_keys: true,
            };
            build_policy(&repo, &source, &mut cache, false, &sign).await
        });
        std::fs::remove_dir_all(&dir).unwrap();
        let policy = outcome.expect("the configured key builds a policy");
        let verifiers = policy.sign.expect("the sign-api axis applies");
        assert_eq!(verifiers.len(), 1, "the repeated name holds one verifier");
    }

    /// The two targets of one pull share the verifier that both ask for. The
    /// cache reads the key sources of an engine once and hands out the same
    /// verifier again.
    #[test]
    fn an_engine_is_read_once_for_both_targets() {
        const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
        let config = crate::config::RepoConfig::parse(&format!(
            "[core]\nrepo_version=1\nmode=archive\n\
             [remote \"origin\"]\nurl=http://localhost/\n\
             verification-ed25519-key={PUBLIC_B64}\n"
        ))
        .unwrap();
        let section = config.remote("origin");
        ostrya_rt::block_on(async {
            let source = KeySource::Remote {
                name: "origin",
                section: section.as_ref(),
                repo_keyring: true,
                system_keys: true,
            };
            let mut cache = Verifiers::default();
            let first = cache.sign("ed25519", &source).await.unwrap();
            let second = cache.sign("ed25519", &source).await.unwrap();
            let (Some(first), Some(second)) = (first, second) else {
                panic!("the configured key builds a verifier");
            };
            assert!(Arc::ptr_eq(&first, &second));
            assert_eq!(cache.sign.len(), 1);
        });
    }

    /// A pull from a remote with a trust group builds the commit policy from
    /// the group and the summary policy from the remote, and the two share no
    /// verifier. The group trusts key A, and the remote trusts key B for the
    /// summary: the commit policy refuses B, and the summary policy refuses A.
    #[test]
    fn a_trust_group_and_the_remote_share_no_verifier() {
        use crate::{CreateOptions, RepoMode};

        const OTHER_SECRET_B64: &str = "5ILWxT+l9G/u3h0BptRpmSi35C9uog7YDdD+Fp1Xk+Hz52p0NlYh6xBA73kJEJKhKbbnjcE0rsWA5XA/K5Sq5Q==";
        const OTHER_PUBLIC_B64: &str = "8+dqdDZWIesQQO95CRCSoSm2543BNK7FgOVwPyuUquU=";
        let dir = std::env::temp_dir().join(format!(
            "ostrya-verify-trust-split-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        let root = dir.join("repo");
        std::fs::create_dir_all(&dir).unwrap();
        let group_key = ed25519_signed(SECRET_B64);
        let remote_key = ed25519_signed(OTHER_SECRET_B64);
        let outcome = ostrya_rt::block_on(async {
            drop(
                Repo::create(&root, CreateOptions::new(RepoMode::Archive))
                    .await
                    .unwrap(),
            );
            let config = root.join("config");
            let mut text = std::fs::read_to_string(&config).unwrap();
            text.push_str(&format!(
                "\n[remote \"origin\"]\nurl=http://localhost/\ngpg-verify=false\ntrust=t\n\
                 sign-verify-summary=ed25519\nverification-ed25519-key={OTHER_PUBLIC_B64}\n\
                 [ex-ostrya trust \"t\"]\nsign-verify=ed25519\n\
                 verification-ed25519-key={PUBLIC_B64}\n"
            ));
            std::fs::write(&config, text).unwrap();
            let repo = Repo::open(&root).await.unwrap();
            let trust = PullTrust::from_remote(&repo, "origin", &PullVerify::default())
                .await
                .unwrap();
            let (commit, summary) = trust.into_policies();
            (
                commit.check("commit", PAYLOAD, Some(&group_key)).await,
                commit.check("commit", PAYLOAD, Some(&remote_key)).await,
                summary.check("summary", PAYLOAD, Some(&remote_key)).await,
                summary.check("summary", PAYLOAD, Some(&group_key)).await,
            )
        });
        std::fs::remove_dir_all(&dir).unwrap();
        let (commit_a, commit_b, summary_b, summary_a) = outcome;
        commit_a.expect("the commit policy trusts the key of the group");
        let err = commit_b.expect_err("the commit policy does not trust the remote key");
        assert!(err.to_string().contains("is from a trusted key"), "{err}");
        summary_b.expect("the summary policy trusts the key of the remote");
        let err = summary_a.expect_err("the summary policy does not trust the group key");
        assert!(err.to_string().contains("is from a trusted key"), "{err}");
    }

    /// `read_verification_file` refuses a key file over the ceiling by its own
    /// name, so the size of the file cannot decide an allocation.
    #[test]
    fn an_oversized_key_file_is_refused_by_name() {
        let dir = std::env::temp_dir().join(format!(
            "ostrya-verify-keyfile-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("keys.ed25519");
        std::fs::File::create(&path)
            .unwrap()
            .set_len(MAX_KEY_FILE + 1)
            .unwrap();
        let outcome = read_verification_file("ed25519", &path.display().to_string());
        std::fs::remove_dir_all(&dir).unwrap();
        let err = outcome.expect_err("a key file over the ceiling has to be refused");
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("keys.ed25519") && m.contains("ceiling")),
            "{err}"
        );
    }

    /// `gpg_verifier` refuses a repository keyring over the ceiling by its own
    /// name. A read of the part that the ceiling admits gives the pull a
    /// trusted set that the operator never put there. No message reports it.
    #[cfg(feature = "verify-gpg")]
    #[test]
    fn an_oversized_repository_keyring_is_refused_by_name() {
        use crate::{CreateOptions, RepoMode};
        use ostrya_sign::MAX_KEYRING;

        let dir = std::env::temp_dir().join(format!(
            "ostrya-verify-keyring-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        let root = dir.join("repo");
        std::fs::create_dir_all(&dir).unwrap();
        let outcome = ostrya_rt::block_on(async {
            let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
                .await
                .unwrap();
            std::fs::File::create(root.join("origin.trustedkeys.gpg"))
                .unwrap()
                .set_len(MAX_KEYRING + 1)
                .unwrap();
            gpg_verifier(&repo, &NO_SECTION).await.map(|_| ())
        });
        std::fs::remove_dir_all(&dir).unwrap();
        let err = outcome.expect_err("a keyring over the ceiling has to be refused");
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("origin.trustedkeys.gpg")
                && m.contains("ceiling")),
            "{err}"
        );
    }

    /// `gpg_verifier` refuses a fifo at the name of a repository keyring, by
    /// that name. A read of a fifo returns what its writers sent, so a pull
    /// that reads one takes its trusted set from them. The open uses
    /// `NONBLOCK`, so it does not wait for a writer. The read refuses the file
    /// kind before it reads a byte.
    #[cfg(feature = "verify-gpg")]
    #[test]
    fn a_fifo_repository_keyring_is_refused_by_name() {
        use crate::{CreateOptions, RepoMode};

        let dir = std::env::temp_dir().join(format!(
            "ostrya-verify-keyfifo-repo-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        let root = dir.join("repo");
        std::fs::create_dir_all(&dir).unwrap();
        let outcome = ostrya_rt::block_on(async {
            let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
                .await
                .unwrap();
            rustix::fs::mknodat(
                rustix::fs::CWD,
                root.join("origin.trustedkeys.gpg"),
                FileType::Fifo,
                Mode::from_raw_mode(0o600),
                0,
            )
            .unwrap();
            gpg_verifier(&repo, &NO_SECTION).await.map(|_| ())
        });
        std::fs::remove_dir_all(&dir).unwrap();
        let err = outcome.expect_err("a fifo at a keyring's name has to be refused");
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("origin.trustedkeys.gpg")
                && m.contains("regular file")),
            "{err}"
        );
    }

    /// `read_verification_file` refuses a fifo at the name of a key file, by
    /// that name. A blocking read of a fifo holds the thread until a writer
    /// opens it. The length that a fifo reports is not the length of its
    /// content. The open uses `NONBLOCK`, so it does not wait for a writer. The
    /// read refuses the file kind before it reads a byte.
    #[test]
    fn a_fifo_key_file_is_refused_by_name() {
        let dir = std::env::temp_dir().join(format!(
            "ostrya-verify-keyfifo-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("keys.ed25519");
        rustix::fs::mknodat(
            rustix::fs::CWD,
            &path,
            FileType::Fifo,
            Mode::from_raw_mode(0o600),
            0,
        )
        .unwrap();
        let outcome = read_verification_file("ed25519", &path.display().to_string());
        std::fs::remove_dir_all(&dir).unwrap();
        let err = outcome.expect_err("a fifo at a key file's name has to be refused");
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("keys.ed25519")
                && m.contains("regular file")),
            "{err}"
        );
    }

    /// A `verification-spki-file` holds PEM `PUBLIC KEY` blocks. A file of
    /// base64 lines is refused by its name. An empty file adds no keys, so the
    /// engine has no key.
    #[cfg(feature = "sign-spki")]
    #[test]
    fn an_spki_key_file_holds_pem_blocks() {
        const SPKI_B64: &str = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8X83xylD3ibci0xjFKMR4bwUtTU/\
                                YLloVEDxomUS2SHAfFnN3LHVVNYjok0Zm2RiiU7XpDnRAG1Ua8eR8SKbLQ==";
        let dir = std::env::temp_dir().join(format!(
            "ostrya-verify-spkifile-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let write = |name: &str, text: &str| {
            let path = dir.join(name);
            std::fs::write(&path, text).unwrap();
            path.display().to_string()
        };
        let pem = write(
            "pem",
            &format!(
                "-----BEGIN PUBLIC KEY-----\n{}\n{}\n-----END PUBLIC KEY-----\n",
                &SPKI_B64[..64],
                &SPKI_B64[64..]
            ),
        );
        let lines = write("lines", &format!("{SPKI_B64}\n"));
        let empty = write("empty", "");
        let read = |path: &str| read_sign_keys("spki", None, Some(path.to_owned()), false);
        let by_pem = read(&pem);
        let by_lines = read(&lines);
        let by_empty = read(&empty);
        std::fs::remove_dir_all(&dir).unwrap();

        let keys = by_pem.unwrap().expect("the PEM file holds a key");
        assert_eq!(keys.trusted, [base64::decode(SPKI_B64).unwrap()]);
        let err = by_lines.expect_err("a file of base64 lines has to be refused");
        assert!(
            matches!(&err, Error::Signature(m) if m.ends_with(&format!(
                "the 'spki' key file '{lines}' holds no PEM PUBLIC KEY block"
            ))),
            "{err}"
        );
        assert!(by_empty.unwrap().is_none());
    }

    /// An inline `verification-spki-key` and a PEM `verification-spki-file`
    /// add their keys together. A signature of each key verifies.
    #[cfg(feature = "sign-spki")]
    #[test]
    fn an_spki_inline_key_and_key_file_are_both_trusted() {
        use crate::sign::Signer;
        use crate::spki::SpkiSigner;

        let inline = SpkiSigner::from_base64(SPKI_SECRET_A).unwrap();
        let in_file = SpkiSigner::from_base64(SPKI_SECRET_B).unwrap();
        let b64 = base64::encode(&in_file.public_key_der());
        let lines: Vec<&str> = b64
            .as_bytes()
            .chunks(64)
            .map(|c| std::str::from_utf8(c).unwrap())
            .collect();
        let dir = std::env::temp_dir().join(format!(
            "ostrya-verify-spkiboth-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("pem");
        std::fs::write(
            &path,
            format!(
                "-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----\n",
                lines.join("\n")
            ),
        )
        .unwrap();
        let read = read_sign_keys(
            "spki",
            Some(base64::encode(&inline.public_key_der())),
            Some(path.display().to_string()),
            false,
        );
        std::fs::remove_dir_all(&dir).unwrap();

        let keys = read.unwrap().expect("both sources hold a key");
        assert_eq!(
            keys.trusted,
            [inline.public_key_der(), in_file.public_key_der()]
        );
        let verifier = build_verifier(Engine::Spki, keys).unwrap().unwrap();
        for signer in [&inline, &in_file] {
            let signature = ostrya_rt::block_on(signer.sign(PAYLOAD)).unwrap();
            let outcome = verifier.verify(PAYLOAD, &[signature]).unwrap();
            assert!(outcome.valid);
        }
    }

    /// An inline `verification-spki-key` is the base64 of a
    /// SubjectPublicKeyInfo DER, and it can hold line breaks. A SEC1 point,
    /// the base64 of the PEM text, and a PKCS#8 secret key are refused when
    /// the verifier is built.
    #[cfg(feature = "sign-spki")]
    #[test]
    fn an_spki_inline_key_is_a_subject_public_key_info() {
        use crate::spki::SpkiSigner;

        let der = SpkiSigner::from_base64(SPKI_SECRET_A)
            .unwrap()
            .public_key_der();
        let b64 = base64::encode(&der);
        let (head, tail) = b64.split_at(64);
        for inline in [
            b64.clone(),
            format!("{head}\n{tail}\n"),
            format!("{head}\r\n{tail}\r\n"),
            format!(" {head}\t{tail} "),
        ] {
            let keys = read_sign_keys("spki", Some(inline), None, false)
                .unwrap()
                .expect("the inline key is a key");
            assert_eq!(keys.trusted, std::slice::from_ref(&der));
            assert!(build_verifier(Engine::Spki, keys).unwrap().is_some());
        }

        let pem = format!("-----BEGIN PUBLIC KEY-----\n{head}\n{tail}\n-----END PUBLIC KEY-----\n");
        let point = der[der.len() - 65..].to_vec();
        let secret = base64::decode(SPKI_SECRET_A).unwrap();
        for bytes in [point, pem.into_bytes(), secret] {
            let keys = read_sign_keys("spki", Some(base64::encode(&bytes)), None, false)
                .unwrap()
                .expect("the inline key decodes");
            match build_verifier(Engine::Spki, keys) {
                Err(Error::Signature(m)) => {
                    assert_eq!(m, "spki public key: expected SubjectPublicKeyInfo DER");
                }
                Err(other) => panic!("not a signature error: {other}"),
                Ok(_) => panic!("the key has to be refused"),
            }
        }

        // An ed25519 inline key keeps its strict decode, with no white space
        // inside the key.
        let (a, b) = PUBLIC_B64.split_at(20);
        assert!(read_sign_keys("ed25519", Some(format!("{a}\n{b}")), None, false).is_err());
    }

    /// The trust source reads the `verification-*` keys of its group. The
    /// remote keys of the same name do not reach it. The trust source reads no
    /// system key store, and a remote source reads one.
    #[test]
    fn trust_source_reads_its_own_group() {
        let keyfile = ostrya_core::KeyFile::parse(
            "[remote \"t\"]\nverification-ed25519-key=REMOTE\n\
             [ex-ostrya trust \"t\"]\nverification-ed25519-key=INLINE\n\
             verification-ed25519-file=/keys.ed25519\n",
        )
        .unwrap();
        let section = Remote::view(&keyfile, "ex-ostrya trust \"t\"".to_owned());
        let source = KeySource::Trust {
            name: "t",
            section: &section,
        };
        assert_eq!(
            source.verification_key("ed25519").unwrap().as_deref(),
            Some("INLINE")
        );
        assert_eq!(
            source.verification_file("ed25519").unwrap().as_deref(),
            Some("/keys.ed25519")
        );
        assert_eq!(source.verification_key("spki").unwrap(), None);
        assert!(!source.system_store());
        assert!(NO_SECTION.system_store());
    }

    /// A remote source without the repository keyring does not open
    /// `<repo>/<remote>.trustedkeys.gpg`. A keyring there over the ceiling,
    /// which the pull refuses, does not reach the build.
    #[cfg(feature = "verify-gpg")]
    #[test]
    fn a_source_without_the_repository_keyring_does_not_read_it() {
        use crate::{CreateOptions, RepoMode};
        use ostrya_sign::MAX_KEYRING;

        let dir = std::env::temp_dir().join(format!(
            "ostrya-verify-nokeyring-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        let root = dir.join("repo");
        std::fs::create_dir_all(&dir).unwrap();
        let outcome = ostrya_rt::block_on(async {
            let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
                .await
                .unwrap();
            std::fs::File::create(root.join("origin.trustedkeys.gpg"))
                .unwrap()
                .set_len(MAX_KEYRING + 1)
                .unwrap();
            let without = KeySource::Remote {
                name: "origin",
                section: None,
                repo_keyring: false,
                system_keys: true,
            };
            (
                gpg_verifier(&repo, &without).await.map(|_| ()),
                gpg_verifier(&repo, &NO_SECTION).await.map(|_| ()),
            )
        });
        std::fs::remove_dir_all(&dir).unwrap();
        let (without, with) = outcome;
        without.expect("the repository keyring is not read");
        let err = with.expect_err("the repository keyring is read, and refused");
        assert!(
            matches!(&err, Error::Signature(m) if m.contains("origin.trustedkeys.gpg")),
            "{err}"
        );
    }
}