ostrya 0.13.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
//! The trust groups, `[ex-ostrya trust "NAME"]`: the check of a group, the
//! build of its policy, the trust of a pull that names a group, and the
//! trusted keys of a group.
//!
//! `check_trust` checks the keys and the values of a group. It reads no file
//! and runs no program. `trust_group_policy` builds the policy of a group that
//! passed the check. `pull_trust` resolves the trust of a pull that names a
//! group: in the key `trust` of the section of its remote, or in
//! `PullOptions::trust_group`. `TrustedKeys::from_trust_group` resolves the
//! name of a group that its caller gives, and builds the keys of the group.

use ostrya_core::KeyFile;

use crate::config::{Remote, SignVerify};
use crate::error::{Error, Result};
use crate::pull::PullVerify;
use crate::repo::Repo;

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

/// The sign-api engines that a trust group can name.
const TRUST_ENGINES: &[&str] = &["ed25519", "spki"];

/// Builds the policy of the trust group `name` from the key-file group
/// `group`.
///
/// The policy holds the GPG axis of the group if `gpg_on` is `true`, and the
/// sign-api axis of the group if `sign_on` is `true`. The build reads no key
/// source of an axis that is off. Each call makes its own verifiers, so a
/// policy of a group shares no verifier with a policy of a remote.
///
/// The caller checks the group with [`check_trust`] first. As a result, the
/// group turns on at least one axis, and an axis reads each key that the group
/// holds.
pub(crate) async fn trust_group_policy(
    repo: &Repo,
    keyfile: &KeyFile,
    name: &str,
    group: &str,
    gpg_on: bool,
    sign_on: bool,
) -> Result<Policy> {
    let gpg = gpg_on && keyfile.get_bool(group, "gpg-verify")?.unwrap_or(false);
    let sign = if sign_on {
        Remote::view(keyfile, group.to_owned()).sign_verify()?
    } else {
        SignVerify::Off
    };
    trust_group_build(repo, keyfile, name, group, gpg, &sign).await
}

/// Returns the GPG switch and the sign-api switch of the key-file group
/// `group`. The call reads no key source.
pub(crate) fn trust_group_switches(keyfile: &KeyFile, group: &str) -> Result<(bool, SignVerify)> {
    let gpg = keyfile.get_bool(group, "gpg-verify")?.unwrap_or(false);
    let sign = Remote::view(keyfile, group.to_owned()).sign_verify()?;
    Ok((gpg, sign))
}

/// Builds the policy of the trust group `name` from the key-file group
/// `group`, with the axes that `gpg` and `sign` turn on.
pub(crate) async fn trust_group_build(
    repo: &Repo,
    keyfile: &KeyFile,
    name: &str,
    group: &str,
    gpg: bool,
    sign: &SignVerify,
) -> Result<Policy> {
    let section = Remote::view(keyfile, group.to_owned());
    let source = KeySource::Trust {
        name,
        section: &section,
    };
    build_policy(repo, &source, &mut Verifiers::default(), gpg, sign).await
}

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

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

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

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

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

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

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

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

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

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

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

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

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

/// Checks the trust group `group`.
///
/// Each key must be one that an axis reads. The group must turn on at least
/// one axis.
pub(crate) fn check_trust(keyfile: &KeyFile, group: &str) -> Result<()> {
    let mut engine_keys: Vec<(&str, &str)> = Vec::new();
    for key in keyfile.keys(group) {
        match key {
            "gpg-verify" | "gpgkeypath" | "sign-verify" => {}
            "gpg-verify-summary" | "sign-verify-summary" => {
                return Err(Error::InvalidFormat(format!(
                    "[{group}] holds '{key}', and a trust group sets a commit policy alone"
                )));
            }
            _ => match verification_engine(key) {
                Some(engine) if TRUST_ENGINES.contains(&engine) => {
                    engine_keys.push((key, engine));
                }
                Some(engine) => {
                    return Err(Error::InvalidFormat(format!(
                        "[{group}] holds '{key}', and '{engine}' is not ed25519 or spki"
                    )));
                }
                None => return Err(unknown_key(group, key)),
            },
        }
    }

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

    let keypath = keyfile.get_value(group, "gpgkeypath").is_some();
    if keypath && !gpg {
        return Err(Error::InvalidFormat(format!(
            "[{group}] sets gpgkeypath, and gpg-verify is not true, so no check reads it"
        )));
    }
    // `sign-verify=true` names every engine of the build, so it names spki
    // only in a build that has it.
    let names_spki = matches!(&sign, SignVerify::Engines(names) if names.iter().any(|n| n == "spki"))
        || engine_keys.iter().any(|(_, engine)| *engine == "spki");
    if cfg!(not(feature = "sign-spki")) && names_spki {
        return Err(Error::Unsupported(format!(
            "[{group}] names the spki engine, which this build has no engine for; \
             build with the sign-spki feature"
        )));
    }
    for (key, engine) in engine_keys {
        if !engines.contains(&engine) {
            return Err(Error::InvalidFormat(format!(
                "[{group}] holds '{key}', and sign-verify does not select {engine}, so \
                 no check reads it"
            )));
        }
        if key.ends_with("-file") {
            Remote::view(keyfile, group.to_owned()).verification_file(engine)?;
        }
    }
    if gpg {
        if cfg!(not(feature = "verify-gpg")) {
            return Err(Error::Unsupported(format!(
                "[{group}] asks for GPG verification, which this build has no engine \
                 for; build with the verify-gpg feature"
            )));
        }
        let keypath = Remote::view(keyfile, group.to_owned()).gpgkeypath()?;
        if keypath.is_empty() {
            return Err(Error::InvalidFormat(format!(
                "[{group}] sets gpg-verify=true, and gpgkeypath names no keyring"
            )));
        }
        if keypath.iter().any(String::is_empty) {
            return Err(Error::InvalidFormat(format!(
                "[{group}] gpgkeypath holds an empty entry"
            )));
        }
    }
    Ok(())
}

/// Returns the engine that a `verification-ENGINE-key` or
/// `verification-ENGINE-file` key names, or `None` for another key.
fn verification_engine(key: &str) -> Option<&str> {
    let rest = key.strip_prefix("verification-")?;
    rest.strip_suffix("-key")
        .or_else(|| rest.strip_suffix("-file"))
}

/// Returns the error for a key that `group` does not take.
pub(crate) fn unknown_key(group: &str, key: &str) -> Error {
    Error::InvalidFormat(format!("[{group}] holds the unknown key '{key}'"))
}

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

    use ostrya_core::Value;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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