ostrya 0.19.0

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
//! Commit signatures, the signing engines, and the key store.
//!
//! The engines, the [`Signer`] and [`Verifier`] traits, and [`SignKeys`] come
//! from the `ostrya-sign` crate. A [`Signer`] signs a byte payload. A
//! [`Verifier`] verifies signature blobs against a byte payload. The same
//! engines sign commits and the summary ([`Repo::sign_summary`]).
//!
//! The entry points are:
//!
//! - the signatures of a commit: [`Repo::sign_commit`],
//!   [`Repo::verify_commit`], and [`Repo::delete_signatures`]
//! - the signature blobs of a signature dict and their verification:
//!   [`signatures_for`] and [`verify_all`], which read at most
//!   [`MAX_SIGNATURES_PER_ENGINE`] blobs under the key of one engine
//! - the key store of the ed25519 and spki engines: [`load_sign_keys`] and
//!   [`load_sign_keys_from`]
//! - a verifier that trusts the system key store: [`FromSystemKeys`]
//! - the signing keys of a key group of the repository config, and the
//!   search for their signatures: [`SigningKey`] and
//!   [`Repo::has_signed_commit`]
//!
//! The engines are:
//!
//! - ed25519: [`Ed25519Signer`] and [`Ed25519Verifier`]
//! - the dummy engine for tests: [`DummySigner`] and [`DummyVerifier`]
//! - spki: feature `sign-spki`
//! - GPG: features `verify-gpg` and `sign-gpg`
//!
//! With the feature `sign-x509`, the trait `X509Signer` gives the X.509
//! certificate chain of a signer for a CMS signature.
//!
//! # X.509 chains in the detached metadata
//!
//! A signature of the spki engine can carry X.509 certificate chains and
//! CRLs. A writer of this crate appends the signature, and then the chains
//! and the CRLs that [`Signer::x509_attachments`] gives, with
//! [`append_x509`], under [`X509_CHAINS_KEY`] and [`X509_CRLS_KEY`]. With the
//! features `sign-spki` and `sign-x509`, `spki::X509ChainSigner` is such a
//! signer, and [`SigningKey::from_key_group`] makes one from the keys
//! `certificate-chain-file` and `crl-file` of a key group. The writers are
//! [`Repo::sign_commit`], [`Transaction::sign_commit`](crate::Transaction::sign_commit),
//! [`Repo::sign_summary_all`], [`Repo::regenerate_summaries`], and
//! [`Repo::generate_static_delta`]. The receive endpoint is a writer too: a
//! commit signature that it makes with a server key, for a pushed commit or
//! a server commit, carries the chains and the CRLs of that key.
//!
//! With the features `sign-spki` and `sign-x509`, `spki::X509Trust` holds
//! X.509 trust anchors, and `spki::SpkiVerifier::with_x509` gives them to a
//! verifier with an [`X509Check`]. The verifier then trusts the key of a
//! chain that passes the path check. `load_x509_anchors` reads the anchors
//! of the system key store, and `load_x509_crls` adds its CRLs to a trust.
//! `Repo::x509_crl_context` reads the X.509 CRL cache of a repository, and
//! `Repo::cache_x509_crls` writes it.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use ostrya_core::{Checksum, ObjectType, Value, base64};

use crate::config::repo;
use crate::repo::Repo;

#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
pub(crate) mod crl_cache;
pub(crate) mod key_group;
mod signing_key;

/// [`signatures_for`] applies the limit too. The limit applies to each
/// verification of this crate: a commit, the summary, a static delta, a
/// pull, and the receive endpoint. It also applies to the search of
/// [`SigningKey::has_signed`].
pub use ostrya_sign::MAX_SIGNATURES_PER_ENGINE;
#[cfg(feature = "sign-x509")]
pub use ostrya_sign::X509Signer;
pub use ostrya_sign::{
    DummySigner, DummyVerifier, Ed25519Signer, Ed25519Verifier, MAX_KEY_FILE, MAX_X509_CERTIFICATE,
    MAX_X509_CHAIN_CERTIFICATES, MAX_X509_CHAINS, MAX_X509_CRL, MAX_X509_CRL_FILE, MAX_X509_CRLS,
    SignFuture, SignKeys, SignatureInfo, Signer, Verifier, VerifyOutcome, X509_CHAINS_KEY,
    X509_CRLS_KEY, X509Attachments, X509Check, X509KeptCrl, X509Revocation, append_signature,
    append_x509, key_text, read_key_file, read_key_source,
};
#[doc(hidden)]
pub use ostrya_sign::{Error, Result};
pub use signing_key::SigningKey;

/// A signing key moves freely across tasks and threads.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<SigningKey>();
};

/// Methods that sign and verify commits.
impl Repo {
    /// Signs the commit `checksum` with `signer` and stores the signature.
    ///
    /// The signed payload is the serialized commit object. These bytes are the
    /// normal-form GVariant bytes that give the commit checksum.
    ///
    /// # Storage
    ///
    /// The signature goes into the detached metadata of the commit, the
    /// `.commitmeta` file. The file holds an `a{sv}` dict. Each engine owns one
    /// key of the dict, the [`metadata_key`](Signer::metadata_key) of the
    /// signer. The value of the key is an `aay`, with one `ay` element for each
    /// signature blob.
    ///
    /// The call appends the signature as one `ay` element. If the dict has no
    /// key for the engine, the call adds the key. If the file is absent, the
    /// call creates the file. The arrays of the other engines stay unchanged.
    /// The new file replaces the old file atomically.
    ///
    /// If [`Signer::x509_attachments`] of `signer` gives chains or CRLs, the
    /// call appends them after the signature, with [`append_x509`]: each chain
    /// to `ostrya.x509.chains` and each CRL to `ostrya.x509.crls`, if the
    /// array does not hold it.
    ///
    /// # Locks
    ///
    /// The call makes the signature first, with no lock held. Then it takes
    /// the repository lock as [`Shared`](crate::LockKind::Shared) and the
    /// update lock, as [`begin_update`](Repo::begin_update) does. Under both
    /// locks, it reads the dict, adds the signature, and writes the file.
    ///
    /// Concurrent signers of one commit keep every signature, because each
    /// signer reads and writes the file under both locks. This applies to
    /// tasks of this process, to other processes, and to
    /// [`Transaction::sign_commit`](crate::Transaction::sign_commit). The
    /// `ostree` command can lose a signature in this case.
    ///
    /// If the caller holds an [`UpdateGuard`](crate::UpdateGuard) of this
    /// repository, the call waits for that guard.
    ///
    /// # Errors
    ///
    /// - [`Error::ObjectNotFound`] if the commit object is not in the object
    ///   store.
    /// - [`Error::Signature`] if `signer` cannot make a signature.
    /// - [`Error::LockTimeout`] if the wait for a lock passes `[core]
    ///   lock-timeout-secs`. Each of the two waits gets the full timeout. The
    ///   call then stores no signature.
    /// - [`Error::Core`] if `[core] fsync` or `[core] locking` is not a
    ///   boolean, or if `[core] lock-timeout-secs` is not an integer.
    /// - [`Error::Core`] if the `.commitmeta` file does not parse as an
    ///   `a{sv}` dict.
    /// - [`Error::InvalidFormat`] if `[core] lock-timeout-secs` is less than
    ///   `-1`.
    /// - [`Error::InvalidFormat`] if the value of the key of the engine is not
    ///   an array.
    /// - [`Error::InvalidFormat`] if [`append_x509`] refuses the dict: a value
    ///   of `ostrya.x509.chains` or `ostrya.x509.crls` of another type, or an
    ///   array over its limit after the append.
    /// - [`Error::InvalidFormat`] if the commit object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::InvalidFormat`] if the `.commitmeta` file is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE), is not a regular
    ///   file, or is a symlink.
    /// - [`Error::InvalidFormat`] if `tmp` or `objects/<xx>` of the
    ///   `.commitmeta` file is a symlink or is not a directory.
    /// - [`Error::Io`] with `EXDEV` if `tmp/` and `objects/` are on different
    ///   file systems.
    /// - [`Error::Io`] if another file system operation fails.
    ///
    /// [`Error::ObjectNotFound`]: crate::Error::ObjectNotFound
    /// [`Error::Signature`]: crate::Error::Signature
    /// [`Error::LockTimeout`]: crate::Error::LockTimeout
    /// [`Error::Core`]: crate::Error::Core
    /// [`Error::InvalidFormat`]: crate::Error::InvalidFormat
    /// [`Error::Io`]: crate::Error::Io
    pub async fn sign_commit(&self, checksum: &Checksum, signer: &dyn Signer) -> crate::Result<()> {
        let data = self.load_object_bytes(ObjectType::Commit, checksum).await?;
        let signature = signer.sign(&data).await?;
        let fsync = self.config().get::<repo::Fsync>()?;
        let repo_mode = self.mode();
        let checksum = *checksum;
        let appends = vec![crate::commit::SignatureAppend::of(signer, signature)];
        self.write_locked(move |repo| {
            crate::commit::merge_detached_blocking(
                None,
                repo.objects(),
                &checksum,
                None,
                None,
                Vec::new(),
                appends,
                fsync,
                repo_mode,
            )
        })
        .await
    }

    /// Verifies the signatures of the commit `checksum` with `verifiers`.
    ///
    /// Each verifier gets the serialized commit object and the signature
    /// blobs under its key in the detached metadata of the commit. If the key
    /// or the detached metadata is absent, the verifier gets no blob. If the
    /// value of the key is not an array, the verifier gets no blob. The
    /// verifier does not get an element of the array that is not a byte
    /// string.
    ///
    /// The call reads the blobs of all verifiers before the first verifier
    /// runs. If the detached metadata holds more than
    /// [`MAX_SIGNATURES_PER_ENGINE`] blobs under the key of a verifier, the
    /// call fails and no verifier runs.
    ///
    /// If at least one verifier reports a valid signature, the outcome is
    /// valid. The outcome holds the [`SignatureInfo`] records of all
    /// verifiers, in the order of `verifiers`.
    ///
    /// The read of the commit object, the read of the `.commitmeta` file, and
    /// the parse of the file run in one call on the blocking pool. The read of
    /// the commit object comes first. After the read, the verifiers run in one
    /// more call on the blocking pool, because a verifier does its work in the
    /// call.
    ///
    /// # X.509 chains
    ///
    /// An spki verifier with X.509 trust anchors, from
    /// `SpkiVerifier::with_x509` with the features `sign-spki` and
    /// `sign-x509`, also reads the chains of the `.commitmeta`. The
    /// [`SignatureInfo`] of a blob gives the warnings and the detail of the
    /// check. A library user holds the rule of its boot and deploy paths, and
    /// verifies with [`X509Check::Existing`]:
    ///
    /// - At the boot of an installed deployment, it logs a failed verdict and
    ///   boots.
    /// - At a deploy or an upgrade, it refuses a failed verdict.
    ///
    /// The existing check gives a warning for an expired certificate and
    /// passes, so a host keeps the commits that it has. Its verdict does not
    /// depend on the clock.
    ///
    /// If the `.commitmeta` holds an X.509 chain, the call also reads the
    /// X.509 CRL cache of this repository, as
    /// `Repo::x509_crl_context` reads it, and gives its
    /// CRLs to each verifier as context dicts. A pull or another admission
    /// that learns a CRL writes it to the cache, so a deploy after that
    /// admission refuses a commit whose certificate the CRL revokes. The
    /// CRL warnings of the check are in [`VerifyOutcome::warnings`].
    ///
    /// # Errors
    ///
    /// - [`Error::ObjectNotFound`] if the commit object is not in the object
    ///   store.
    /// - [`Error::Core`] if the `.commitmeta` file does not parse as an
    ///   `a{sv}` dict.
    /// - [`Error::Signature`] with the message of [`signatures_for`] if the
    ///   detached metadata holds more than [`MAX_SIGNATURES_PER_ENGINE`]
    ///   blobs under the key of a verifier.
    /// - [`Error::Signature`] if a verifier fails with the `Signature` variant
    ///   of [`ostrya_sign::Error`], or with a variant that the conversion to
    ///   [`Error`](crate::Error) does not name. Of the verifiers that this
    ///   crate exports, only `GpgVerifier` fails: if a blob is larger than
    ///   1 MiB, holds more than 64 signature packets, or makes the OpenPGP
    ///   parser panic.
    /// - [`Error::InvalidFormat`] or [`Error::Core`] if a verifier of another
    ///   crate fails with the variant of the same name of
    ///   [`ostrya_sign::Error`].
    /// - [`Error::InvalidFormat`] if the commit object or the `.commitmeta`
    ///   file is larger than [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE)
    ///   or is not a regular file, or if a symlink is on its path.
    /// - The errors of `Repo::x509_crl_context` for the
    ///   read of the CRL cache.
    /// - [`Error::Io`] if a file system operation fails.
    ///
    /// [`Error::ObjectNotFound`]: crate::Error::ObjectNotFound
    /// [`Error::Core`]: crate::Error::Core
    /// [`Error::Signature`]: crate::Error::Signature
    /// [`Error::InvalidFormat`]: crate::Error::InvalidFormat
    /// [`Error::Io`]: crate::Error::Io
    pub async fn verify_commit(
        &self,
        checksum: &Checksum,
        verifiers: &[Arc<dyn Verifier>],
    ) -> crate::Result<VerifyOutcome> {
        let (data, dict) = self.load_commit_and_detached(checksum).await?;
        let verifiers = verifiers.to_vec();
        let repo = self.clone();
        ostrya_rt::unblock(move || {
            let verifiers: Vec<&dyn Verifier> = verifiers.iter().map(|v| v.as_ref()).collect();
            let context = cached_crls_for(&repo, &verifiers, dict.as_ref())?;
            let context: Vec<&Value> = context.iter().collect();
            verify_all(&verifiers, &data, dict.as_ref(), &context)
        })
        .await
    }

    /// Returns `true` if the detached metadata of the commit `checksum` holds
    /// a signature of `key`.
    ///
    /// The payload is the serialized commit object, the payload that
    /// [`sign_commit`](Self::sign_commit) signs. The call makes the search of
    /// [`SigningKey::has_signed`], whose rules
    /// [`SigningKey`](SigningKey#existing-signatures) states. A caller that
    /// signs the commit with `key` only when the call gives `false` adds no
    /// second signature of one key, if no other writer signs the commit
    /// between the two calls. The call and the sign are two separate steps,
    /// and no lock holds the detached metadata between them.
    ///
    /// The call sees the stored detached metadata alone. It does not see a
    /// signature that [`Transaction::sign_commit`](crate::Transaction::sign_commit)
    /// queued and did not write.
    ///
    /// The read of the commit object, the read of the `.commitmeta` file, and
    /// the parse of the file run in one call on the blocking pool. If the
    /// detached metadata holds a signature under the metadata key of the
    /// engine of `key`, the search runs in one more call on the blocking
    /// pool, with no copy of the payload.
    ///
    /// # Errors
    ///
    /// The errors of [`load_object_bytes`](Self::load_object_bytes) and
    /// [`read_commit_detached_metadata`](Self::read_commit_detached_metadata):
    ///
    /// - [`Error::ObjectNotFound`] if the commit object is not in the object
    ///   store.
    /// - [`Error::Core`] if the `.commitmeta` file does not parse as an
    ///   `a{sv}` dict.
    /// - [`Error::InvalidFormat`] if the commit object or the `.commitmeta`
    ///   file is larger than [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE)
    ///   or is not a regular file, or if a symlink is on its path.
    /// - [`Error::InvalidFormat`] with the message `<path> is not a directory`
    ///   if `objects/<xx>` of the commit object is not a directory.
    /// - [`Error::Io`] if a file system operation fails.
    ///
    /// The error of the search:
    ///
    /// - [`Error::Signature`] with the message of [`signatures_for`] if the
    ///   detached metadata holds more than [`MAX_SIGNATURES_PER_ENGINE`]
    ///   blobs under the metadata key of the engine of `key`.
    ///
    /// [`Error::ObjectNotFound`]: crate::Error::ObjectNotFound
    /// [`Error::Core`]: crate::Error::Core
    /// [`Error::Signature`]: crate::Error::Signature
    /// [`Error::InvalidFormat`]: crate::Error::InvalidFormat
    /// [`Error::Io`]: crate::Error::Io
    pub async fn has_signed_commit(
        &self,
        checksum: &Checksum,
        key: &SigningKey,
    ) -> crate::Result<bool> {
        let (data, dict) = self.load_commit_and_detached(checksum).await?;
        key.has_signed_payload(&Arc::new(data), dict.as_ref()).await
    }

    /// Removes the signatures of a commit that `remove` selects.
    ///
    /// The call removes each blob under `metadata_key` in the detached
    /// metadata for which `remove(payload, blob)` returns `true`. `payload` is
    /// the serialized commit object, the payload that
    /// [`sign_commit`](Self::sign_commit) signs. `blob` is one stored
    /// signature. With the predicate, a caller can match a signature to a key.
    /// For example, the predicate can verify the blob again (ed25519 and
    /// spki), or read the issuer fingerprint (GPG). The call returns the
    /// number of signatures that it removed.
    ///
    /// # Rewrite rules
    ///
    /// - The new `.commitmeta` file replaces the old file atomically.
    /// - If the array of the engine becomes empty, the call removes the key
    ///   from the dict.
    /// - If the dict becomes empty, the call writes the zero-length file that
    ///   marks no metadata.
    /// - The arrays of the other engines stay unchanged. An element that is
    ///   not a byte string stays in the array.
    /// - If the commit has no detached metadata, or no blob matches, the call
    ///   removes nothing and does not write the file.
    ///
    /// # X.509 chains
    ///
    /// If `metadata_key` is `ostree.sign.spki` and the call removes at least
    /// one blob, it also removes the chain of each removed signature from
    /// `ostrya.x509.chains`. A chain belongs to a signature through the key
    /// of its first certificate, the leaf. The call removes each chain whose
    /// leaf key verifies no blob left under `ostree.sign.spki`, and keeps
    /// each chain whose leaf key verifies a blob left:
    ///
    /// - A chain stays if it holds no certificate, if its first certificate
    ///   is not one strict DER certificate, or if the spki engine refuses the
    ///   key of that certificate. Such an element is an element of another
    ///   writer.
    /// - If the value of `ostrya.x509.chains` is not a variant that holds an
    ///   `aaay`, the call does not change it.
    /// - If the array of the chains becomes empty, the call removes the key.
    /// - The call never changes `ostrya.x509.crls`.
    /// - The work has no limit: the call verifies each blob left with the key
    ///   of each chain, up to the first blob that verifies. The size cap of
    ///   the `.commitmeta` file bounds it.
    ///
    /// A build without the feature `sign-spki` or `sign-x509` keeps each
    /// chain.
    ///
    /// # Locks
    ///
    /// The call loads the payload first. Then it takes the locks that
    /// [`sign_commit`](Self::sign_commit) takes, and reads, edits, and writes
    /// the dict under them. `remove` runs on the dict that the file holds at
    /// that time. A signer of the same commit, in this process or in
    /// another process, writes the file before or after the removal.
    ///
    /// `remove` runs on the blocking pool. For this reason it must be `Send`
    /// and own the data that it matches against.
    ///
    /// # Errors
    ///
    /// - [`Error::ObjectNotFound`] if the commit object is not in the object
    ///   store.
    /// - [`Error::LockTimeout`] if the wait for a lock passes `[core]
    ///   lock-timeout-secs`. Each of the two waits gets the full timeout.
    /// - [`Error::Core`] if `[core] fsync` or `[core] locking` is not a
    ///   boolean, or if `[core] lock-timeout-secs` is not an integer.
    /// - [`Error::Core`] if the `.commitmeta` file does not parse as an
    ///   `a{sv}` dict.
    /// - [`Error::InvalidFormat`] if `[core] lock-timeout-secs` is less than
    ///   `-1`.
    /// - [`Error::InvalidFormat`] if the value of `metadata_key` is not an
    ///   array.
    /// - [`Error::InvalidFormat`] if the commit object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::InvalidFormat`] if the `.commitmeta` file is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE), is not a regular
    ///   file, or is a symlink.
    /// - [`Error::InvalidFormat`] if `tmp` or `objects/<xx>` of the
    ///   `.commitmeta` file is a symlink or is not a directory.
    /// - [`Error::Io`] with `EXDEV` if `tmp/` and `objects/` are on different
    ///   file systems.
    /// - [`Error::Io`] if another file system operation fails.
    ///
    /// [`Error::ObjectNotFound`]: crate::Error::ObjectNotFound
    /// [`Error::LockTimeout`]: crate::Error::LockTimeout
    /// [`Error::Core`]: crate::Error::Core
    /// [`Error::InvalidFormat`]: crate::Error::InvalidFormat
    /// [`Error::Io`]: crate::Error::Io
    pub async fn delete_signatures(
        &self,
        checksum: &Checksum,
        metadata_key: &str,
        mut remove: impl FnMut(&[u8], &[u8]) -> bool + Send + 'static,
    ) -> crate::Result<usize> {
        let payload = self.load_object_bytes(ObjectType::Commit, checksum).await?;
        let fsync = self.config().get::<repo::Fsync>()?;
        let repo_mode = self.mode();
        let checksum = *checksum;
        let metadata_key = metadata_key.to_owned();
        self.write_locked(move |repo| {
            crate::commit::prune_detached_signatures_blocking(
                repo.objects(),
                &checksum,
                &metadata_key,
                &payload,
                &mut remove,
                fsync,
                repo_mode,
            )
        })
        .await
    }
}

/// Returns the signature blobs under `metadata_key` in the `a{sv}` dict `dict`.
///
/// `dict` is a signature dict: the detached metadata of a commit, the
/// `summary.sig` file, or the signatures of a signed static delta. Each engine
/// owns one key of the dict, the [`metadata_key`](Verifier::metadata_key) of
/// its verifier. The value of the key is an `aay`, with one `ay` element for
/// each signature blob. If a variant holds the value, the call reads the value
/// in the variant. The result holds the blobs in stored order.
///
/// If the key is absent or its value is not an array, the result is empty.
/// If `dict` is not an array, the result is also empty. The result skips each
/// element that is not a byte string. A malformed entry of another writer does
/// not cause an error, so it cannot fail a verification.
///
/// The call reads at most [`MAX_SIGNATURES_PER_ENGINE`] blobs. Only the byte
/// strings count. The call stops the scan at the first byte string over the
/// limit, and it then copies no blob.
///
/// # Errors
///
/// - [`Error::Signature`] with the message
///   `the signature dict holds more than 64 signatures under '<metadata_key>'`
///   if the value of the key holds more than [`MAX_SIGNATURES_PER_ENGINE`]
///   byte strings.
///
/// [`Error::Signature`]: crate::Error::Signature
///
/// # Examples
///
/// ```
/// use ostrya::Value;
/// use ostrya::sign::{append_signature, signatures_for};
///
/// let mut dict = Value::Array(Vec::new());
/// append_signature(&mut dict, "ostree.sign.dummy", b"one".to_vec())?;
/// append_signature(&mut dict, "ostree.sign.dummy", b"two".to_vec())?;
///
/// let blobs = signatures_for(&dict, "ostree.sign.dummy")?;
/// assert_eq!(blobs, [b"one".to_vec(), b"two".to_vec()]);
/// assert!(signatures_for(&dict, "ostree.sign.ed25519")?.is_empty());
/// # Ok::<(), ostrya::Error>(())
/// ```
pub fn signatures_for(dict: &Value, metadata_key: &str) -> crate::Result<Vec<Vec<u8>>> {
    Ok(capped_signatures(dict, metadata_key)?
        .into_iter()
        .map(<[u8]>::to_vec)
        .collect())
}

/// Appends `signature` under `metadata_key` to the `a{sv}` dict `dict`, and
/// then the chains and the CRLs of `x509`.
///
/// The writers that the docs of this module list call this function, the
/// receive endpoint too, so the keys `ostrya.x509.chains` and
/// `ostrya.x509.crls` come after the signature that carries them.
/// [`append_signature`] and [`append_x509`] state the rules and the errors.
pub(crate) fn append_signed(
    dict: &mut Value,
    metadata_key: &str,
    signature: Vec<u8>,
    x509: Option<&X509Attachments>,
) -> Result<()> {
    append_signature(dict, metadata_key, signature)?;
    match x509 {
        Some(attachments) => append_x509(dict, attachments),
        None => Ok(()),
    }
}

/// Returns the signature blobs under `metadata_key` in `dict` as slices of
/// `dict`, with the rules and the error of [`signatures_for`]. The call copies
/// no blob.
pub(crate) fn capped_signatures<'a>(
    dict: &'a Value,
    metadata_key: &str,
) -> crate::Result<Vec<&'a [u8]>> {
    Ok(ostrya_sign::signatures_in(dict, metadata_key)?)
}

/// Verifies `data` with each verifier of `verifiers` against the signature
/// dict `dict`, with the context dicts `context`.
///
/// Each verifier gets `data`, `dict`, and `context` in a call to
/// [`Verifier::verify_metadata`]. A verifier reads its blobs under its
/// [`metadata_key`](Verifier::metadata_key) in `dict`, as [`signatures_for`]
/// reads them. If `dict` is `None`, each verifier gets no blob. The call also
/// calls a verifier that gets no blob. An spki verifier with X.509 trust
/// anchors also reads the X.509 certificate chains and the CRLs of `dict`,
/// and the CRLs of each dict of `context`, for example the dicts of
/// `Repo::x509_crl_context`. It gives the warnings and the details of its
/// check in each [`SignatureInfo`].
///
/// The outcome holds the CRLs of [`VerifyOutcome::crls`] and the warnings of
/// [`VerifyOutcome::warnings`] of each verifier, each one time, in the order
/// of `verifiers`.
///
/// The call counts the blobs of all verifiers before the first verifier
/// runs. If the dict holds more than [`MAX_SIGNATURES_PER_ENGINE`] blobs
/// under the key of a verifier, the call fails and no verifier runs.
///
/// If at least one verifier reports a valid signature, the outcome is valid.
/// The outcome holds the [`SignatureInfo`] records of all verifiers, in the
/// order of `verifiers`.
///
/// The verifiers run in the calling thread, one after the other. The call
/// holds the thread for the time of the verification, as
/// [`Verifier::verify`] states. A caller on an async executor that verifies
/// untrusted input runs the call on the blocking pool.
///
/// # Errors
///
/// - [`Error::Signature`] with the message of [`signatures_for`] if `dict`
///   holds more than [`MAX_SIGNATURES_PER_ENGINE`] blobs under the key of a
///   verifier. No verifier runs.
///
/// The first verifier that fails stops the call. The verifiers after it do not
/// run. The call returns the error of that verifier, converted to
/// [`Error`](crate::Error):
///
/// - [`Error::Signature`] if the verifier fails with the `Signature` variant
///   of [`ostrya_sign::Error`], or with a variant that the conversion does
///   not name. Of the verifiers that this crate exports, only `GpgVerifier`
///   fails: if a blob is larger than 1 MiB, holds more than 64 signature
///   packets, or makes the OpenPGP parser panic.
/// - [`Error::InvalidFormat`] or [`Error::Core`] if a verifier of another
///   crate fails with the variant of the same name of
///   [`ostrya_sign::Error`].
///
/// [`Error::Signature`]: crate::Error::Signature
/// [`Error::InvalidFormat`]: crate::Error::InvalidFormat
/// [`Error::Core`]: crate::Error::Core
///
/// # Examples
///
/// ```
/// use ostrya::Value;
/// use ostrya::sign::{DummyVerifier, append_signature, verify_all};
///
/// let mut dict = Value::Array(Vec::new());
/// append_signature(&mut dict, "ostree.sign.dummy", b"trusted".to_vec())?;
///
/// let verifier = DummyVerifier::new([b"trusted".to_vec()]);
/// let outcome = verify_all(&[&verifier], b"payload", Some(&dict), &[])?;
/// assert!(outcome.valid);
/// assert_eq!(outcome.signatures.len(), 1);
///
/// let outcome = verify_all(&[&verifier], b"payload", None, &[])?;
/// assert!(!outcome.valid);
/// assert!(outcome.signatures.is_empty());
/// # Ok::<(), ostrya::Error>(())
/// ```
pub fn verify_all(
    verifiers: &[&dyn Verifier],
    data: &[u8],
    dict: Option<&Value>,
    context: &[&Value],
) -> crate::Result<VerifyOutcome> {
    if let Some(dict) = dict {
        for verifier in verifiers {
            capped_signatures(dict, verifier.metadata_key())?;
        }
    }
    let mut outcome = VerifyOutcome::default();
    for verifier in verifiers {
        let result = verifier.verify_metadata(data, dict, context)?;
        outcome.valid |= result.valid;
        if outcome.signatures.is_empty() {
            outcome.signatures = result.signatures;
        } else {
            outcome.signatures.extend(result.signatures);
        }
        for crl in result.crls {
            if !outcome.crls.contains(&crl) {
                outcome.crls.push(crl);
            }
        }
        for warning in result.warnings {
            if !outcome.warnings.contains(&warning) {
                outcome.warnings.push(warning);
            }
        }
    }
    Ok(outcome)
}

/// Returns the CRLs of the X.509 CRL cache of `repo` for a verify of the
/// signature dict `dict` with `verifiers` as context dicts, if `dict` holds
/// an X.509 chain. The call reads the issuer directories of the candidate
/// CRL signers of `verifiers` alone. Otherwise, or in a build with no X.509
/// path check, the call reads nothing and gives no dict.
///
/// The read blocks: the caller runs it on the blocking pool.
pub(crate) fn cached_crls_for(
    repo: &Repo,
    verifiers: &[&dyn Verifier],
    dict: Option<&Value>,
) -> crate::Result<Vec<Value>> {
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    if dict.is_some_and(|dict| !ostrya_sign::x509_chains_in(dict).is_empty()) {
        let dirs = crl_cache::cache_dirs(verifiers.iter().copied(), dict);
        return crl_cache::read(repo.root_dir(), &dirs).map(crl_cache::dicts);
    }
    #[cfg(not(all(feature = "sign-spki", feature = "sign-x509")))]
    let _ = (repo, verifiers, dict);
    Ok(Vec::new())
}

/// Removes each blob under `metadata_key` in the `a{sv}` dict `dict` for which
/// `remove(payload, blob)` returns `true`.
///
/// If the array of the engine becomes empty, the call removes the entry of the
/// engine. An element that is not a byte string stays. The entries of the
/// other engines stay unchanged. Returns the number of removed blobs.
pub(crate) fn remove_signatures(
    dict: &mut Value,
    metadata_key: &str,
    payload: &[u8],
    remove: &mut dyn FnMut(&[u8], &[u8]) -> bool,
) -> crate::Result<usize> {
    let entries = match dict {
        Value::Array(entries) => entries,
        _ => {
            return Err(crate::Error::InvalidFormat(
                "detached metadata must be an a{sv} dict".into(),
            ));
        }
    };
    let mut removed = 0usize;
    let mut emptied = false;
    for entry in entries.iter_mut() {
        if let Value::Tuple(fields) = entry
            && let [key, value] = fields.as_mut_slice()
            && key.as_str() == Some(metadata_key)
        {
            let array = match value {
                Value::Variant(inner) => &mut inner.1,
                other => other,
            };
            let Value::Array(blobs) = array else {
                return Err(crate::Error::InvalidFormat(
                    "detached-metadata signature value is not an array".into(),
                ));
            };
            let before = blobs.len();
            blobs.retain(|blob| match blob.as_bytes() {
                Some(bytes) => !remove(payload, bytes),
                None => true,
            });
            removed = before - blobs.len();
            emptied = blobs.is_empty();
            break;
        }
    }
    if emptied {
        entries.retain(|entry| {
            entry
                .as_tuple()
                .and_then(<[Value]>::first)
                .and_then(Value::as_str)
                != Some(metadata_key)
        });
    }
    Ok(removed)
}

/// Removes each chain of `ostrya.x509.chains` in the `a{sv}` dict `dict`
/// whose leaf key verifies no blob under `ostree.sign.spki` over `payload`.
///
/// The call reads the first entry of `ostrya.x509.chains`. If its value is
/// not a variant that holds an `aaay` with at least one chain, the call
/// changes nothing and reads no blob. A chain stays if it holds no
/// certificate, if its first certificate is not one strict DER certificate,
/// or if the spki engine refuses the key of that certificate. Each other
/// chain stays if a verifier that trusts its leaf key alone verifies one blob
/// of `ostree.sign.spki`. For each chain, the call verifies the blobs in
/// order, up to the first blob that verifies, with no limit. If the call
/// removes the last chain, it removes the entry. The call never changes
/// `ostrya.x509.crls`. Returns the number of removed chains.
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
pub(crate) fn remove_orphan_chains(dict: &mut Value, payload: &[u8]) -> usize {
    use crate::spki::SpkiVerifier;

    let Value::Array(entries) = dict else {
        return 0;
    };
    // The first entry of the chains, if it holds a variant of a non-empty
    // `aaay`. Else the call changes nothing, and reads no blob.
    let Some(index) = entries.iter().position(
        |entry| matches!(entry.as_tuple(), Some([key, _]) if key.as_str() == Some(X509_CHAINS_KEY)),
    ) else {
        return 0;
    };
    let holds_chains = entries[index].as_tuple().is_some_and(|fields| {
        matches!(fields[1].as_variant(), Some((ty, inner))
            if ty.signature() == "aaay" && inner.as_array().is_some_and(|c| !c.is_empty()))
    });
    if !holds_chains {
        return 0;
    }
    let blobs: Vec<Vec<u8>> = entries
        .iter()
        .find_map(|entry| match entry.as_tuple() {
            Some([key, value]) if key.as_str() == Some(SPKI_METADATA_KEY) => Some(value),
            _ => None,
        })
        .map(|value| match value.as_variant() {
            Some((_, inner)) => inner,
            None => value,
        })
        .and_then(Value::as_array)
        .map(|elements| {
            elements
                .iter()
                .filter_map(Value::as_bytes)
                .map(<[u8]>::to_vec)
                .collect()
        })
        .unwrap_or_default();
    // `true` if a verifier of the leaf key of `chain` verifies a blob left,
    // or if the chain does not give a key. The search stops at the first blob
    // that verifies.
    let keep = |chain: &Value| -> bool {
        let Some(leaf) = chain
            .as_array()
            .and_then(<[Value]>::first)
            .and_then(Value::as_bytes)
        else {
            return true;
        };
        // `from_certificates` reads an item that does not start with the
        // tag of a `SEQUENCE` as PEM text.
        if leaf.first() != Some(&0x30) {
            return true;
        }
        let Ok(verifier) = SpkiVerifier::from_certificates([leaf]) else {
            return true;
        };
        blobs.iter().any(|blob| {
            verifier
                .verify(payload, std::slice::from_ref(blob))
                .map_or(true, |outcome| outcome.valid)
        })
    };
    let mut removed = 0;
    if let Value::Tuple(fields) = &mut entries[index]
        && let Value::Variant(inner) = &mut fields[1]
        && let Value::Array(chains) = &mut inner.1
    {
        let before = chains.len();
        chains.retain(|chain| keep(chain));
        removed = before - chains.len();
        if chains.is_empty() {
            entries.remove(index);
        }
    }
    removed
}

/// The detached-metadata key of the spki engine.
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
const SPKI_METADATA_KEY: &str = "ostree.sign.spki";

/// The system directories of the key store, in search order.
///
/// The second directory is `<datadir>/ostree`.
pub(crate) const SYSTEM_KEY_ROOTS: [&str; 2] = ["/etc/ostree", "/usr/share/ostree"];

/// Loads the trusted and revoked keys of `sign_type` from the system key store.
///
/// The call gives the directories `/etc/ostree` and `/usr/share/ostree`, in
/// this order, to [`load_sign_keys_from`]. That function states the files that
/// the call reads. `sign_type` is the sign-type name of the engine: `ed25519`
/// or `spki`.
///
/// # Errors
///
/// The errors of [`load_sign_keys_from`]:
///
/// - [`Error::Signature`] if a key file cannot be opened or read, is not a
///   regular file, or is larger than [`MAX_KEY_FILE`].
/// - [`Error::Signature`] if an ed25519 key file is not valid UTF-8, or if
///   the reader of PEM `PUBLIC KEY` blocks refuses an spki key file.
/// - [`Error::Core`] if a line of an ed25519 key file is not valid base64.
/// - [`Error::Io`] if a `.d` directory cannot be read.
/// - [`Error::Unsupported`] if `sign_type` is `spki` and the build has no
///   `sign-spki` feature.
///
/// [`Error::Signature`]: crate::Error::Signature
/// [`Error::Core`]: crate::Error::Core
/// [`Error::Io`]: crate::Error::Io
/// [`Error::Unsupported`]: crate::Error::Unsupported
pub fn load_sign_keys(sign_type: &str) -> crate::Result<SignKeys> {
    let roots: Vec<PathBuf> = SYSTEM_KEY_ROOTS.iter().map(PathBuf::from).collect();
    let refs: Vec<&Path> = roots.iter().map(PathBuf::as_path).collect();
    load_sign_keys_from(&refs, sign_type)
}

/// A verifier that loads its keys from the system key store.
///
/// The `ostrya-sign` crate has no system search path, so this crate adds the
/// constructor as a trait. A caller brings the trait into scope to call it.
pub trait FromSystemKeys: Sized {
    /// Creates a verifier from the keys of its engine in the system key store.
    ///
    /// The call reads `trusted.<type>`, `revoked.<type>`, and their `.d`
    /// directories with [`load_sign_keys`]. `<type>` is the sign-type name of
    /// the engine.
    ///
    /// # Errors
    ///
    /// - The errors of [`load_sign_keys`].
    /// - [`Error::Signature`] if the engine refuses a key.
    ///
    /// [`Error::Signature`]: crate::Error::Signature
    fn from_system_keys() -> crate::Result<Self>;
}

impl FromSystemKeys for Ed25519Verifier {
    /// Creates an ed25519 verifier from the system key store.
    ///
    /// The call reads `trusted.ed25519`, `revoked.ed25519`, and their `.d`
    /// directories with [`load_sign_keys`].
    ///
    /// # Errors
    ///
    /// - The errors of [`load_sign_keys`].
    /// - [`Error::Signature`] if a key is not 32 bytes long, or if a trusted key
    ///   that is not revoked is not a valid curve point. The rules are on
    ///   [`Ed25519Verifier::new`].
    ///
    /// [`Error::Signature`]: crate::Error::Signature
    fn from_system_keys() -> crate::Result<Ed25519Verifier> {
        Ok(Ed25519Verifier::from_sign_keys(load_sign_keys("ed25519")?)?)
    }
}

#[cfg(feature = "sign-spki")]
impl FromSystemKeys for crate::spki::SpkiVerifier {
    /// Creates an spki verifier from the system key store.
    ///
    /// The call reads `trusted.spki`, `revoked.spki`, and their `.d`
    /// directories with [`load_sign_keys`].
    ///
    /// # Errors
    ///
    /// - The errors of [`load_sign_keys`].
    /// - [`Error::Signature`] if a key does not parse. The rules are on
    ///   [`SpkiVerifier::new`](crate::spki::SpkiVerifier::new).
    ///
    /// [`Error::Signature`]: crate::Error::Signature
    fn from_system_keys() -> crate::Result<crate::spki::SpkiVerifier> {
        Ok(crate::spki::SpkiVerifier::from_sign_keys(load_sign_keys(
            "spki",
        )?)?)
    }
}

/// Loads the trusted and revoked keys of `sign_type` from the directories
/// `roots`.
///
/// # Files
///
/// The call reads each root in order and adds its keys to one [`SignKeys`]
/// set. Under each root, it reads these files, in this order:
///
/// 1. The file `trusted.<type>`, then each regular file in the directory
///    `trusted.<type>.d/`, in sorted name order.
/// 2. The file `revoked.<type>`, then each regular file in the directory
///    `revoked.<type>.d/`, in sorted name order.
///
/// `<type>` is `sign_type`. A missing file or directory is not an error. In a
/// `.d` directory, the call reads only regular files. It skips a symlink, also
/// a symlink to a regular file. The call follows a symlink at `trusted.<type>`
/// or `revoked.<type>`.
///
/// The form of a file depends on `sign_type`:
///
/// - `spki`: the file holds PEM `PUBLIC KEY` blocks. The function
///   `spki_public_keys` of the `spki` module reads the file and states the
///   rules. An empty file, or a file of white space only, adds no keys. Each
///   other file that the reader refuses fails the call, also a file of the
///   revoked set.
/// - Each other type: each line of a file holds one base64 key. The call skips
///   an empty line and a line of white space only. Each other line must
///   decode.
///
/// The call reads each file with [`read_key_source`]: only a regular file, and
/// only up to [`MAX_KEY_FILE`] bytes. The error for a file names that file.
///
/// # Errors
///
/// - [`Error::Signature`] with the message
///   `the key file '<path>' cannot be opened: <e>` if the open of a file fails
///   for a reason other than a missing file.
/// - [`Error::Signature`] if a file cannot be read, is not a regular file, or
///   is larger than [`MAX_KEY_FILE`]. [`read_key_source`] gives the messages.
/// - [`Error::Signature`] if a file of a type other than `spki` is not valid
///   UTF-8. [`key_text`] gives the message.
/// - [`Error::Signature`] if `spki_public_keys` refuses an `spki` file.
/// - [`Error::Core`] if a line of a file of a type other than `spki` is not
///   valid base64.
/// - [`Error::Io`] if a `.d` directory cannot be read, or if it is not a
///   directory.
/// - [`Error::Unsupported`] if `sign_type` is `spki` and the build has no
///   `sign-spki` feature.
///
/// [`Error::Signature`]: crate::Error::Signature
/// [`Error::Core`]: crate::Error::Core
/// [`Error::Io`]: crate::Error::Io
/// [`Error::Unsupported`]: crate::Error::Unsupported
pub fn load_sign_keys_from(roots: &[&Path], sign_type: &str) -> crate::Result<SignKeys> {
    #[cfg(not(feature = "sign-spki"))]
    if sign_type == "spki" {
        return Err(crate::Error::Unsupported(
            "the spki key store needs the feature 'sign-spki'".into(),
        ));
    }
    let mut keys = SignKeys::default();
    for root in roots {
        collect_keys(root, sign_type, "trusted", &mut keys.trusted)?;
        collect_keys(root, sign_type, "revoked", &mut keys.revoked)?;
    }
    Ok(keys)
}

/// Loads the revoked keys of `sign_type` from the directories `roots`: the
/// file `revoked.<type>` and the files of `revoked.<type>.d/` of each root,
/// by the rules of [`load_sign_keys_from`]. The call reads no trusted key.
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
pub(crate) fn load_revoked_keys_from(
    roots: &[&Path],
    sign_type: &str,
) -> crate::Result<Vec<Vec<u8>>> {
    let mut revoked = Vec::new();
    for root in roots {
        collect_keys(root, sign_type, "revoked", &mut revoked)?;
    }
    Ok(revoked)
}

/// Reads the keys of `<root>/<set>.<sign_type>` and of each regular file in
/// `<root>/<set>.<sign_type>.d/` into `out`.
fn collect_keys(
    root: &Path,
    sign_type: &str,
    set: &str,
    out: &mut Vec<Vec<u8>>,
) -> crate::Result<()> {
    for file in store_files(root, &format!("{set}.{sign_type}"))? {
        read_store_file(&file, sign_type, out)?;
    }
    Ok(())
}

/// Returns the path `<root>/<base>`, then the path of each regular file in
/// the directory `<root>/<base>.d/`, in sorted name order. A missing
/// directory adds no path. The call does not check that `<root>/<base>`
/// exists.
fn store_files(root: &Path, base: &str) -> crate::Result<Vec<PathBuf>> {
    let mut files = vec![root.join(base)];
    let dir = root.join(format!("{base}.d"));
    let entries = match std::fs::read_dir(&dir) {
        Ok(entries) => entries,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(files),
        Err(e) => return Err(e.into()),
    };
    let mut found = Vec::new();
    for entry in entries {
        let entry = entry?;
        if entry.file_type()?.is_file() {
            found.push(entry.path());
        }
    }
    found.sort();
    files.extend(found);
    Ok(files)
}

/// Loads the X.509 trust anchors of the system key store.
///
/// The call gives the directories `/etc/ostree` and `/usr/share/ostree`, in
/// this order, to [`load_x509_anchors_from`]. That function states the files
/// that the call reads.
///
/// # Errors
///
/// The errors of [`load_x509_anchors_from`].
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
pub fn load_x509_anchors() -> crate::Result<Vec<Vec<u8>>> {
    let roots: Vec<&Path> = SYSTEM_KEY_ROOTS.iter().map(Path::new).collect();
    load_x509_anchors_from(&roots)
}

/// Loads the X.509 trust anchors of the spki engine from the directories
/// `roots`.
///
/// Under each root, in order, the call reads the file `trusted.x509`, then
/// each regular file in the directory `trusted.x509.d/`, in sorted name
/// order. It returns the DER of each certificate, in the order of the files.
/// A missing file or directory is not an error. In the `.d` directory, the
/// call reads only regular files, and skips a symlink. The call follows a
/// symlink at `trusted.x509`.
///
/// A file holds PEM `CERTIFICATE` blocks, which `spki::x509_certificates`
/// reads. The key of each certificate is of a key type of the spki engine.
/// An empty file, or a file of white space only, adds no anchor. The call
/// reads each file with [`read_key_source`]: only a regular file, and only
/// up to [`MAX_KEY_FILE`] bytes.
///
/// # Errors
///
/// - [`Error::Signature`] with the message
///   `the anchor file '<path>' cannot be opened: <e>` if the open of a file
///   fails for a reason other than a missing file.
/// - [`Error::Signature`] if a file cannot be read, is not a regular file, or
///   is larger than [`MAX_KEY_FILE`].
/// - [`Error::Signature`] if `spki::x509_certificates` refuses a file. The
///   message names the file as `the anchor file '<path>'`.
/// - [`Error::Io`] if a `.d` directory cannot be read, or if it is not a
///   directory.
///
/// [`Error::Signature`]: crate::Error::Signature
/// [`Error::Io`]: crate::Error::Io
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
pub fn load_x509_anchors_from(roots: &[&Path]) -> crate::Result<Vec<Vec<u8>>> {
    let mut anchors = Vec::new();
    for root in roots {
        for file in store_files(root, "trusted.x509")? {
            let subject = format!("the anchor file '{}'", file.display());
            let Some(bytes) = read_key_file(&file, &subject, MAX_KEY_FILE)? else {
                continue;
            };
            if bytes.iter().all(u8::is_ascii_whitespace) {
                continue;
            }
            anchors.extend(ostrya_sign::x509_certificates(&bytes, &subject)?);
        }
    }
    Ok(anchors)
}

/// Adds the X.509 CRLs of the system key store to the X.509 trust `trust`.
///
/// The call gives the directories `/etc/ostree` and `/usr/share/ostree`, in
/// this order, to [`load_x509_crls_from`]. That function states the files
/// that the call reads.
///
/// # Errors
///
/// The errors of [`load_x509_crls_from`].
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
pub fn load_x509_crls(trust: crate::spki::X509Trust) -> crate::Result<crate::spki::X509Trust> {
    let roots: Vec<&Path> = SYSTEM_KEY_ROOTS.iter().map(Path::new).collect();
    load_x509_crls_from(trust, &roots)
}

/// Adds the X.509 CRLs of the spki engine in the directories `roots` to the
/// X.509 trust `trust`.
///
/// Under each root, in order, the call reads the file `crl.x509`, then each
/// regular file in the directory `crl.x509.d/`, in sorted name order. It
/// adds the CRLs to the trust with `spki::X509Trust::with_crls`, in the
/// order of the files, and returns the trust. A missing file or directory is
/// not an error. In the `.d` directory, the call reads only regular files,
/// and skips a symlink. The call follows a symlink at `crl.x509`.
///
/// A file holds PEM `X509 CRL` blocks, which `spki::x509_crls` reads. An
/// empty file, or a file of white space only, adds no CRL. The call reads
/// each file with [`read_key_source`]: only a regular file, and only up to
/// [`MAX_X509_CRL_FILE`] bytes. Each CRL of a file is one that the path
/// check of the spki engine uses, as `spki::X509Trust::with_crls` states,
/// else the call refuses the file. The call checks no signature of a CRL.
///
/// # Errors
///
/// - [`Error::Signature`] with the message
///   `the CRL file '<path>' cannot be opened: <e>` if the open of a file
///   fails for a reason other than a missing file.
/// - [`Error::Signature`] if a file cannot be read, is not a regular file, or
///   is larger than [`MAX_X509_CRL_FILE`].
/// - [`Error::Signature`] if `spki::x509_crls` refuses a file. The message
///   names the file as `the CRL file '<path>'`.
/// - [`Error::Signature`] with the message
///   `the CRL file '<path>': x509 CRL <n>: <reason>` if the path check does
///   not use a CRL of the file, with the reason of
///   `spki::X509Trust::with_crls`.
/// - [`Error::Io`] if a `.d` directory cannot be read, or if it is not a
///   directory.
///
/// [`Error::Signature`]: crate::Error::Signature
/// [`Error::Io`]: crate::Error::Io
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
pub fn load_x509_crls_from(
    mut trust: crate::spki::X509Trust,
    roots: &[&Path],
) -> crate::Result<crate::spki::X509Trust> {
    for root in roots {
        for file in store_files(root, "crl.x509")? {
            let subject = format!("the CRL file '{}'", file.display());
            let Some(bytes) = read_key_file(&file, &subject, MAX_X509_CRL_FILE)? else {
                continue;
            };
            if bytes.iter().all(u8::is_ascii_whitespace) {
                continue;
            }
            trust = with_file_crls(trust, ostrya_sign::x509_crls(&bytes, &subject)?, &subject)?;
        }
    }
    Ok(trust)
}

/// Adds the CRLs `crls` of the file `subject` to the X.509 trust `trust`,
/// if the path check of the spki engine uses each of them. Otherwise
/// refuses the file with the message `<subject>: x509 CRL <n>: <reason>`.
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
pub(crate) fn with_file_crls(
    trust: crate::spki::X509Trust,
    crls: Vec<Vec<u8>>,
    subject: &str,
) -> crate::Result<crate::spki::X509Trust> {
    trust
        .with_crls(&crls)
        .map_err(|e| crate::Error::Signature(format!("{subject}: {}", sign_message(e))))
}

/// Returns the message of the error `e` of the X.509 trust.
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
fn sign_message(e: ostrya_sign::Error) -> String {
    match e {
        ostrya_sign::Error::Signature(message) => message,
        other => other.to_string(),
    }
}

/// Reads the keys of one key file of the store into `out`.
///
/// A file of the spki engine holds PEM `PUBLIC KEY` blocks, which
/// `spki_public_keys` reads. A file of
/// another engine holds one base64 key on each line. The read obeys the rules
/// of [`read_key_source`]. A missing file is not an error.
fn read_store_file(path: &Path, sign_type: &str, out: &mut Vec<Vec<u8>>) -> crate::Result<()> {
    let subject = format!("the key file '{}'", path.display());
    let Some(bytes) = read_key_file(path, &subject, MAX_KEY_FILE)? else {
        return Ok(());
    };
    #[cfg(feature = "sign-spki")]
    if sign_type == "spki" {
        out.extend(crate::spki::spki_public_keys(&bytes, &subject)?);
        return Ok(());
    }
    #[cfg(not(feature = "sign-spki"))]
    let _ = sign_type;
    for line in key_text(bytes, &subject)?.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        out.push(base64::decode(line)?);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use super::*;

    /// A verifier that records the payload and the number of blobs of each
    /// call.
    ///
    /// Each blob gives one [`SignatureInfo`] whose fingerprint is
    /// `<metadata key>:<blob>`. The outcome is `valid`, or the error
    /// `refused` if `fails` is set.
    struct Recorder {
        key: &'static str,
        valid: bool,
        fails: bool,
        calls: Mutex<Vec<(Vec<u8>, usize)>>,
    }

    impl Recorder {
        fn new(key: &'static str, valid: bool) -> Recorder {
            Recorder {
                key,
                valid,
                fails: false,
                calls: Mutex::new(Vec::new()),
            }
        }

        fn failing(key: &'static str) -> Recorder {
            Recorder {
                fails: true,
                ..Recorder::new(key, false)
            }
        }

        fn calls(&self) -> Vec<usize> {
            self.calls.lock().unwrap().iter().map(|(_, n)| *n).collect()
        }

        fn payloads(&self) -> Vec<Vec<u8>> {
            self.calls
                .lock()
                .unwrap()
                .iter()
                .map(|(d, _)| d.clone())
                .collect()
        }
    }

    impl Verifier for Recorder {
        fn metadata_key(&self) -> &str {
            self.key
        }

        fn verify(&self, data: &[u8], signatures: &[Vec<u8>]) -> Result<VerifyOutcome> {
            self.calls
                .lock()
                .unwrap()
                .push((data.to_vec(), signatures.len()));
            if self.fails {
                return Err(Error::Signature("refused".into()));
            }
            let signatures = signatures
                .iter()
                .map(|blob| {
                    let mut info = SignatureInfo::default();
                    info.valid = self.valid;
                    info.fingerprint =
                        Some(format!("{}:{}", self.key, String::from_utf8_lossy(blob)));
                    info
                })
                .collect();
            let mut outcome = VerifyOutcome::default();
            outcome.valid = self.valid;
            outcome.signatures = signatures;
            Ok(outcome)
        }
    }

    fn fingerprints(outcome: &VerifyOutcome) -> Vec<&str> {
        outcome
            .signatures
            .iter()
            .map(|info| info.fingerprint.as_deref().unwrap())
            .collect()
    }

    /// The outcome is valid if one verifier is valid, in each order. The
    /// signatures of the first verifier come before the signatures of the
    /// second. Each verifier gets the payload of the call.
    #[test]
    fn the_outcome_joins_the_verifiers_in_order() {
        let mut dict = Value::Array(Vec::new());
        append_signature(&mut dict, "test.b", b"b1".to_vec()).unwrap();
        append_signature(&mut dict, "test.a", b"a1".to_vec()).unwrap();
        append_signature(&mut dict, "test.a", b"a2".to_vec()).unwrap();
        let first = Recorder::new("test.a", false);
        let second = Recorder::new("test.b", true);

        let outcome = verify_all(&[&first, &second], b"data", Some(&dict), &[]).unwrap();

        assert!(outcome.valid);
        assert_eq!(
            fingerprints(&outcome),
            ["test.a:a1", "test.a:a2", "test.b:b1"]
        );
        assert_eq!(first.calls(), [2]);
        assert_eq!(second.calls(), [1]);
        assert_eq!(first.payloads(), [b"data"]);
        assert_eq!(second.payloads(), [b"data"]);

        let outcome = verify_all(&[&second, &first], b"data", Some(&dict), &[]).unwrap();

        assert!(outcome.valid);
        assert_eq!(
            fingerprints(&outcome),
            ["test.b:b1", "test.a:a1", "test.a:a2"]
        );

        let outcome = verify_all(&[&first], b"data", Some(&dict), &[]).unwrap();
        assert!(!outcome.valid);
    }

    /// A verifier whose key has no entry in the dict is called with no blob.
    /// With no dict, each verifier is called with no blob.
    #[test]
    fn a_verifier_with_no_blob_is_called() {
        let mut dict = Value::Array(Vec::new());
        append_signature(&mut dict, "test.a", b"a1".to_vec()).unwrap();
        let signed = Recorder::new("test.a", true);
        let unsigned = Recorder::new("test.b", true);

        let outcome = verify_all(&[&signed, &unsigned], b"data", Some(&dict), &[]).unwrap();
        assert_eq!(fingerprints(&outcome), ["test.a:a1"]);
        assert_eq!(signed.calls(), [1]);
        assert_eq!(unsigned.calls(), [0]);

        let outcome = verify_all(&[&signed, &unsigned], b"data", None, &[]).unwrap();
        assert!(outcome.signatures.is_empty());
        assert_eq!(signed.calls(), [1, 0]);
        assert_eq!(unsigned.calls(), [0, 0]);
    }

    /// The error of the first verifier that fails is the result, and the
    /// verifiers after it do not run.
    #[test]
    fn the_first_error_stops_the_call() {
        let mut dict = Value::Array(Vec::new());
        append_signature(&mut dict, "test.a", b"a1".to_vec()).unwrap();
        let failing = Recorder::failing("test.a");
        let second = Recorder::new("test.b", true);

        let err = verify_all(&[&failing, &second], b"data", Some(&dict), &[]).unwrap_err();

        assert!(
            matches!(&err, crate::Error::Signature(m) if m == "refused"),
            "{err}"
        );
        assert_eq!(failing.calls(), [1]);
        assert!(second.calls().is_empty());
    }

    /// Returns a dict that holds `count` different blobs under `key`.
    fn dict_of(key: &str, count: usize) -> Value {
        let mut dict = Value::Array(Vec::new());
        for i in 0..count {
            append_signature(&mut dict, key, i.to_be_bytes().to_vec()).unwrap();
        }
        dict
    }

    /// The refusal of a dict with more than 64 blobs under `key`.
    fn limit_error(key: &str) -> String {
        format!("the signature dict holds more than 64 signatures under '{key}'")
    }

    /// `signatures_for` reads 64 blobs under one key, in stored order, and
    /// refuses 65.
    #[test]
    fn signatures_for_reads_at_most_64_blobs() {
        assert_eq!(MAX_SIGNATURES_PER_ENGINE, 64);
        let blobs = signatures_for(&dict_of("test.a", 64), "test.a").unwrap();
        assert_eq!(blobs.len(), 64);
        assert_eq!(blobs[0], 0usize.to_be_bytes());
        assert_eq!(blobs[63], 63usize.to_be_bytes());

        let err = signatures_for(&dict_of("test.a", 65), "test.a").unwrap_err();
        assert!(
            matches!(&err, crate::Error::Signature(m) if *m == limit_error("test.a")),
            "{err}"
        );
    }

    /// The blobs under the key of another engine do not count.
    #[test]
    fn the_blobs_of_another_key_do_not_count() {
        let mut dict = dict_of("test.b", 65);
        append_signature(&mut dict, "test.a", b"a1".to_vec()).unwrap();
        assert_eq!(signatures_for(&dict, "test.a").unwrap(), [b"a1".to_vec()]);
        let verifier = Recorder::new("test.a", true);
        let outcome = verify_all(&[&verifier], b"data", Some(&dict), &[]).unwrap();
        assert!(outcome.valid);
        assert_eq!(verifier.calls(), [1]);
    }

    /// An element that is not a byte string does not count to the limit.
    #[test]
    fn an_element_that_is_not_a_byte_string_does_not_count() {
        let mut elements: Vec<Value> = (0..64u8).map(|i| Value::Bytes(vec![i])).collect();
        elements.extend((0..10).map(|i| Value::Str(format!("not a blob {i}"))));
        let dict = Value::Array(vec![Value::Tuple(vec![
            Value::Str("test.a".into()),
            Value::variant(
                ostrya_core::Type::parse("av").unwrap(),
                Value::Array(elements),
            ),
        ])]);
        assert_eq!(signatures_for(&dict, "test.a").unwrap().len(), 64);
    }

    /// `verify_all` reads the blobs of each verifier first. A key over the
    /// limit refuses the call before any verifier runs, also a verifier that
    /// comes before that key and holds a valid blob.
    #[test]
    fn verify_all_refuses_before_a_verifier_runs() {
        let mut dict = dict_of("test.b", 65);
        append_signature(&mut dict, "test.a", b"a1".to_vec()).unwrap();
        let first = Recorder::new("test.a", true);
        let second = Recorder::new("test.b", true);

        let err = verify_all(&[&first, &second], b"data", Some(&dict), &[]).unwrap_err();

        assert!(
            matches!(&err, crate::Error::Signature(m) if *m == limit_error("test.b")),
            "{err}"
        );
        assert!(first.calls().is_empty());
        assert!(second.calls().is_empty());
    }

    /// `remove_orphan_chains` keeps a dict with no chain as it is, also with
    /// an empty array of chains or a value of another type. A chain stays
    /// when its leaf key verifies one blob among blobs that do not verify,
    /// and a chain whose leaf key verifies no blob goes.
    #[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
    #[test]
    fn orphan_chains_go_and_a_dict_with_no_chain_stays() {
        use crate::spki::X509Chain;

        let fixture = |name: &str| {
            std::fs::read(
                Path::new(env!("CARGO_MANIFEST_DIR"))
                    .join("../../tests/fixtures/x509")
                    .join(name),
            )
            .unwrap()
        };
        let chain = |ty: &str| {
            X509Chain::from_pem(&fixture(&format!("chain-{ty}.pem")), "chain")
                .unwrap()
                .certificates()
                .to_vec()
        };
        let signer = crate::spki::spki_secret_keys(fixture("leaf-p256.key.pem"), "leaf")
            .unwrap()
            .remove(0);
        let payload = b"payload";
        let signature = ostrya_rt::block_on(signer.sign(payload)).unwrap();
        let mut dict = Value::Array(Vec::new());
        for blob in [b"not a signature".to_vec(), signature, b"x".to_vec()] {
            append_signature(&mut dict, SPKI_METADATA_KEY, blob).unwrap();
        }

        let before = dict.clone();
        assert_eq!(remove_orphan_chains(&mut dict, payload), 0);
        assert_eq!(dict, before);
        for (ty, value) in [
            ("aaay", Value::Array(Vec::new())),
            ("aay", Value::Array(vec![Value::Bytes(b"a".to_vec())])),
        ] {
            let mut odd = before.clone();
            let Value::Array(entries) = &mut odd else {
                unreachable!()
            };
            entries.push(Value::Tuple(vec![
                Value::Str(X509_CHAINS_KEY.into()),
                Value::variant(ostrya_core::Type::parse(ty).unwrap(), value),
            ]));
            let kept = odd.clone();
            assert_eq!(remove_orphan_chains(&mut odd, payload), 0);
            assert_eq!(odd, kept);
        }

        let attachments =
            X509Attachments::new(vec![chain("p256"), chain("p384")], Vec::new()).unwrap();
        append_x509(&mut dict, &attachments).unwrap();
        assert_eq!(remove_orphan_chains(&mut dict, payload), 1);
        let (_, chains) = dict
            .dict_get(X509_CHAINS_KEY)
            .unwrap()
            .as_variant()
            .unwrap();
        let first = chains.as_array().unwrap()[0].as_array().unwrap();
        assert_eq!(first[0].as_bytes(), Some(chain("p256")[0].as_slice()));
        assert_eq!(chains.as_array().unwrap().len(), 1);
    }
}