sequoia-cert-store 0.4.2

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

use anyhow::Context;

use sequoia_openpgp as openpgp;
use openpgp::Fingerprint;
use openpgp::KeyHandle;
use openpgp::Result;
use openpgp::cert::prelude::*;
use openpgp::cert::raw::RawCertParser;
use openpgp::packet::Packet;
use openpgp::packet::UserID;
use openpgp::packet::signature::SignatureBuilder;
use openpgp::parse::Parse;
use openpgp::serialize::SerializeInto;
use openpgp::types::KeyFlags;
use openpgp::types::SignatureType;

use openpgp_cert_d as cert_d;

use crate::LazyCert;
use crate::store::Certs;
use crate::store::MergeCerts;
use crate::store::Store;
use crate::store::StoreUpdate;
use crate::store::UserIDQueryParams;

use crate::TRACE;

/// The creation time for the trust root and intermediate CAs.
///
/// We use a creation time in the past (Feb 2002) so that it is still
/// possible to use the CA when the reference time is in the past.
fn ca_creation_time() -> SystemTime {
    SystemTime::UNIX_EPOCH + Duration::new(1014235320, 0)
}

struct CA<'a> {
    cert: Arc<LazyCert<'a>>,
    // The tag of the file stored under the special name.
    special_tag: cert_d::Tag,
    // The tag of the file stored under the fingerprint.
    public_tag: cert_d::Tag,
}

pub struct CertD<'a> {
    certd: cert_d::CertD,

    certs: Certs<'a>,

    /// A cache of the trust root, and shadow CAs keyed by the cert-d
    /// special name.
    cas: Mutex<BTreeMap<String, CA<'a>>>,
}

impl<'a> CertD<'a> {
    /// Returns the canonicalized path.
    ///
    /// If path is `None`, then returns the default location.
    fn path(path: Option<&Path>) -> Result<PathBuf>
    {
        if let Some(path) = path {
            Ok(path.to_owned())
        } else {
            Ok(cert_d::CertD::user_configured_store_path()?)
        }
    }

    /// Opens the default cert-d for reading and writing.
    pub fn open_default() -> Result<Self>
    {
        let path = Self::path(None)?;
        Self::open(path)
    }

    /// Opens a cert-d for reading and writing.
    pub fn open<P>(path: P) -> Result<Self>
        where P: AsRef<Path>,
    {
        tracer!(TRACE, "CertD::open");

        let path = path.as_ref();
        t!("loading cert-d {:?}", path);

        let certd = cert_d::CertD::with_base_dir(&path)
            .map_err(|err| {
                t!("While opening the certd {:?}: {}", path, err);
                let err = anyhow::Error::from(err)
                    .context(format!("While opening the certd {:?}", path));
                err
            })?;

        let mut certd = Self {
            certd,
            certs: Certs::empty(),
            cas: Default::default(),
        };

        certd.initialize(true)?;
        Ok(certd)
    }

    /// Returns a reference to the low-level `CertD`.
    pub fn certd(&self) -> &cert_d::CertD {
        &self.certd
    }

    /// Returns a mutable reference to the low-level `CertD`.
    pub fn certd_mut(&mut self) -> &mut cert_d::CertD {
        &mut self.certd
    }

    // Initialize a certd by reading the entries and populating the
    // index.
    fn initialize(&mut self, lazy: bool) -> Result<()>
    {
        use rayon::prelude::*;

        tracer!(TRACE, "CertD::initialize");

        let open = |fpr: &str| -> Option<( _, _)> {
            match self.certd.get_file(&fpr) {
                Ok(Some(file)) => {
                    match cert_d::Tag::try_from(&file) {
                        Ok(tag) => Some((tag, file)),
                        Err(err) => {
                            t!("Reading tag for {}: {}", fpr, err);
                            None
                        }
                    }
                }
                Ok(None) => {
                    t!("{} disappeared", fpr);
                    None
                }
                Err(err) => {
                    t!("Failed to read {}: {}", fpr, err);
                    None
                }
            }
        };

        let items = self.certd.fingerprints()
            .filter_map(|fpr| fpr.ok());

        let result: Vec<(String, cert_d::Tag, LazyCert)> = if lazy {
            items.collect::<Vec<_>>().into_par_iter()
                .filter_map(|fp| {
                    // XXX: Once we have a cached tag, avoid the
                    // work if tags match.
                    t!("loading {} from overlay", fp);

                    let (tag, file) = open(&fp)?;

                    let mut parser = match RawCertParser::from_reader(file) {
                        Ok(parser) => parser,
                        Err(err) => {
                            t!("While reading {:?} from the certd {:?}: {}",
                               fp, self.certd.base_dir(), err);
                            return None;
                        }
                    };

                    match parser.next() {
                        Some(Ok(cert)) => Some((fp, tag, LazyCert::from(cert))),
                        Some(Err(err)) => {
                            t!("While parsing {:?} from the certd {:?}: {}",
                                fp, self.certd.base_dir(), err);
                            None
                        }
                        None => {
                            t!("While parsing {:?} from the certd {:?}: empty file",
                                fp, self.certd.base_dir());
                            None
                        }
                    }
                })
                .collect()
        } else {
            // For performance reasons, we read, parse, and
            // canonicalize certs in parallel.
            items.collect::<Vec<_>>().into_par_iter()
                .filter_map(|fp| {
                    let (tag, file) = open(&fp)?;

                    // XXX: Once we have a cached tag and
                    // presumably a Sync index, avoid the work if
                    // tags match.
                    t!("loading {} from overlay", fp);
                    match Cert::from_reader(file) {
                        Ok(cert) => Some((fp, tag, LazyCert::from(cert))),
                        Err(err) => {
                            t!("While parsing {:?} from the certd {:?}: {}",
                               fp, self.certd.base_dir(), err);
                            None
                        }
                    }
                })
                .collect()
        };

        for (fp, _tag, cert) in result {
            if let Err(err) = self.certs.update(Arc::new(cert)) {
                // This is an in-memory index and updates doesn't
                // fail.  Nevertheless, we don't panic.
                t!("Error inserting {} into the in-memory index: {}",
                   fp, err);
            }
        }

        Ok(())
    }

    /// Returns the certificate directory's local trust root, and
    /// whether it was just created.
    ///
    /// If the local trust root does not yet exist, it is created.
    pub fn trust_root(&self) -> Result<(Arc<LazyCert<'a>>, bool)> {
        self.get_ca(cert_d::TRUST_ROOT,
                    true,
                    &UserID::from_static_bytes(b"Local Trust Root"),
                    None)
    }

    /// Converts a shadow CA's name to a certificate directory's
    /// special name.
    ///
    /// For instance, this converts "keys.openpgp.org" to its special
    /// name.
    fn shadow_ca_special(name: &str) -> Cow<str> {
        if name == cert_d::TRUST_ROOT {
            Cow::Borrowed(name)
        } else {
            Cow::Owned(format!("_sequoia_ca_{}.pgp", name))
        }
    }

    // '/', '\\', ':', and whitespace are invalid.
    fn valid_name(name: &str) -> bool {
        name.chars().all(Self::valid_char)
    }

    /// Returns whether `c` may be used in names.
    fn valid_char(c: char) -> bool {
        ! (c.is_whitespace()
           || c == '/'
           || c == '\\'
           || c == ':')
    }

    /// Returns a shadow CA's key, and whether it was just created.
    ///
    /// # Introduction
    ///
    /// Shadow CAs are used to encode evidence of a binding's veracity
    /// in standard web of trust data structures so that the
    /// information can be automatically incorportated into web of
    /// trust calculations.
    ///
    /// Consider [`keys.openpgp.org`], which is a verifying keyserver.
    /// `keys.openpgp.org` checks whether a user ID should be
    /// associated with a certificate using a challenge-response
    /// authentication scheme.  When someone uploads a certificate,
    /// `keys.openpgp.org` iterates over the user IDs, and if a user
    /// ID contains an email address, sends an email to it containing
    /// a secret link.  The owner of the email address can visit the
    /// link to confirm to `keys.openpgp.org` that the email address
    /// should be associated with the certificate.
    ///
    /// Although `keys.openpgp.org` verifies User IDs, it does not
    /// issue third-party certifications attesting to that fact.  But,
    /// clients can infer this from `keys.openpgp.org` behavior: when
    /// `keys.openpgp.org` returns a certificate, it only returns user
    /// IDs that it has verified as belonging to the certificate.
    ///
    /// An OpenPGP client could record the fact that
    /// `keys.openpgp.org` returned a user ID in a database.  The main
    /// question is then how to combine that information with other
    /// information in a coherent manner.  Alternatively, we can
    /// encode the assertion as a certification using a so-called
    /// shadow CA.  By encoding this information as a normal OpenPGP
    /// artifact, it can be directly integrated into web of trust
    /// calculations; another, parallel system to combine evidence is
    /// not needed.
    ///
    ///   [keys.openpgp.org]: https://keys.openpgp.org
    ///
    /// # Usage
    ///
    /// `name` is the shadow CA's name.  This is converted to the
    /// special name `_sequoia_ca_ + name + .pgp`.  Names must not
    /// contain white space (` ` or `\n`), path separators (`\` or
    /// `/`), or colons (`:`).
    ///
    /// If the shadow CA doesn't exist and `create` is true, it is
    /// created.  In this case, the user ID is set to `userid`, and if
    /// `trust_amount` is greater than 0, it is designed a trusted
    /// introducer by the last `CA` listed in `intermediaries`, or the
    /// local trust root, if the list is empty.  The certification's
    /// trust amount is set to `trust_amount`.
    ///
    /// `intermediaries` is a list of tuples consisting of a name, a
    /// user ID, and a trust amount.  Each tuple corresponds to an
    /// intermediary shadow CA.  It may be empty; the local trust root
    /// is always the trust anchor and shouldn't be listed explicitly.
    ///
    /// This function works from the trust root towards the shadow CA.
    /// If an intermediate shadow CA does not exist and `create` is
    /// true, it is created, and certified by its parent CA.
    ///
    /// On success, the shadow CA is returned, and whether the shadow
    /// CA was just created.
    ///
    /// # Examples
    ///
    /// The following code looks up the shadow CA for
    /// `keys.openpgp.org`.  It is not directly certified by the trust
    /// root, but by a partially trusted intermediary named
    /// `public_directories`, which acts as a type of resistor for all
    /// public directories.  Note: if you are actually looking up the
    /// shadow CA for `keys.openpgp.org`, you should use
    /// [`CertD::shadow_ca_keys_openpgp_org`] instead.
    ///
    /// The local key for `keys.openpgp.org` is then used to certify
    /// the user IDs on a certificate, which was presumably returned
    /// by `keys.openpgp.org`.
    ///
    /// ```rust
    /// use std::sync::Arc;
    ///
    /// use anyhow::Context;
    ///
    /// use sequoia_openpgp as openpgp;
    /// use openpgp::cert::CertBuilder;
    /// use openpgp::Cert;
    /// use openpgp::packet::Packet;
    /// use openpgp::packet::UserID;
    /// use openpgp::packet::signature::SignatureBuilder;
    /// use openpgp::types::SignatureType;
    ///
    /// use sequoia_cert_store as cert_store;
    /// use cert_store::LazyCert;
    /// use cert_store::store::certd::CertD;
    /// use cert_store::store::StoreUpdate;
    ///
    /// # fn main() -> openpgp::Result<()> {
    /// # let certd_path = tempfile::tempdir()?;
    /// let mut certd = CertD::open(&certd_path)?;
    ///
    /// let (koo, _created) = certd.shadow_ca(
    ///     "keys.openpgp.org",
    ///     true,
    ///     "Downloaded from keys.openpgp.org",
    ///     1,
    ///     &[
    ///         ( "public_directories", UserID::from("Public Directories"), 40),
    ///     ])?;
    ///
    /// // Pretend the following certificate was fetched from keys.openpgp.org.
    /// let alice_userid = "<alice@example.org>";
    /// let (alice, _rev) = CertBuilder::general_purpose(None, Some(alice_userid))
    ///     .generate()?;
    ///
    /// // Certify the binding using the shadow CA.
    /// let mut koo_signer = koo.to_cert()?.primary_key().key().parts_as_secret()
    ///     .context("CA is not certification capable.")?
    ///     .clone().into_keypair()
    ///     .context("CA is not certification capable.")?;
    ///
    /// let sig = SignatureBuilder::new(SignatureType::GenericCertification)
    ///     .set_exportable_certification(false)?
    ///     .sign_userid_binding(
    ///         &mut koo_signer,
    ///         alice.primary_key().key(),
    ///         &UserID::from(alice_userid))
    ///     .context("Signing binding")?;
    ///
    /// let alice = alice.insert_packets([
    ///     Packet::from(UserID::from(alice_userid)),
    ///     Packet::from(sig),
    /// ])?;
    ///
    /// certd.update(Arc::new(LazyCert::from(alice)));
    /// # Ok(()) }
    /// ```
    pub fn shadow_ca<U>(&self, name: &str,
                        create: bool, userid: U, trust_amount: u8,
                        intermediaries: &[(&str, UserID, u8)], )
        -> Result<(Arc<LazyCert<'a>>, bool)>
        where U: Into<UserID>,
    {
        let userid = userid.into();

        tracer!(TRACE, "CertD::shadow_ca");
        t!("{}, create: {}, userid: {:?}, {}, {} intermediaries",
           name, create, String::from_utf8_lossy(userid.value()), trust_amount,
           intermediaries.len());

        let name = CertD::shadow_ca_special(name);

        // If the CA is cached in memory, short-circuit everything.
        if let Ok(result) = self.get_ca(&name, false, &userid, None) {
            t!("Returning cached certificate {} for {}",
               result.0.fingerprint(), name);
            return Ok(result);
        }

        // Iterate from the trust root towards the shadow CA.
        let mut ca: (Arc<LazyCert>, bool) = self.get_ca(
            cert_d::TRUST_ROOT,
            create,
            &UserID::from_static_bytes(b"Local Trust Root"),
            None)?;

        for (name, userid, trust_amount) in
            intermediaries
                .into_iter()
                .map(|(name, userid, amount)| {
                    (CertD::shadow_ca_special(name), userid, *amount)
                })
                .chain(iter::once((name, &userid, trust_amount)))
        {
            if ! Self::valid_name(&name) {
                return Err(cert_d::Error::BadName.into());
            }

            t!("Getting {} (create: {}, userid: {:?}, {})",
               name, create, String::from_utf8_lossy(userid.value()),
               trust_amount);

            ca = self.get_ca(&name, create, &userid,
                             Some((ca.0, trust_amount)))?;

            t!("{} -> {}", name, ca.0.fingerprint());
        }

        Ok(ca)
    }

    /// Returns the specified CA, optionally creating and certifying
    /// it if it doesn't exist.
    ///
    /// See [`CertD::shadow_ca`] for details about shadow CAs.
    ///
    /// This function first checks if the specified CA is in the
    /// in-memory cache.  If so, it checks that the cached version is
    /// up to date, and then returns the result.
    ///
    /// If the CA is not in the in-memory cache, it is loaded from
    /// disk.  If it doesn't exist on disk an `create` is `true`, it
    /// the shadow CA is created.  See [`CertD::load_ca`] for details
    /// of what is exactly done.
    fn get_ca(&self, special_name: &str,
              create: bool, userid: &UserID,
              parent: Option<(Arc<LazyCert<'_>>, u8)>)
        -> Result<(Arc<LazyCert<'a>>, bool)>
    {
        tracer!(TRACE, "CertD::get_ca");

        let mut cas = self.cas.lock().unwrap();

        let get_if_changed = |tag, name| -> Result<Option<_>> {
            match self.certd.get_if_changed(tag, name) {
                Ok(None) => {
                    // The certificate on disk did not change.
                    return Ok(None);
                },
                Ok(Some((new_tag, bytes))) => {
                    // The certificate on disk changed.  Reparse it.
                    t!("{} changed on disk, reloading.", name);
                    match Cert::from_bytes(&bytes) {
                        Ok(cert) => {
                            return Ok(Some((cert, new_tag)));
                        }
                        Err(err) => {
                            // An error occurred while parsing the
                            // data.  That's not great.  We just keep
                            // using what we have.
                            t!("While reparsing {}: {}", name, err);
                            return Ok(None);
                        }
                    }
                }
                // An error occurred while reading the file.  That's
                // not great.  We just keep using what we have.
                Err(err) => {
                    t!("While rereading {}: {}", name, err);
                    return Ok(None);
                }
            }
        };

        if let Some(CA { cert: ca, special_tag, public_tag })
            = cas.get_mut(special_name)
        {
            // The certificate is cached it memory.  Make sure the
            // in-memory version is up to date.
            t!("{} -> {} is cached in memory",
               special_name, ca.fingerprint());

            if let Some((cert, tag))
                = get_if_changed(*special_tag, special_name)?
            {
                *ca = Arc::new(LazyCert::from(
                    ca.to_cert()?
                        .clone()
                        .merge_public_and_secret(cert)?));
                *special_tag = tag;
            }

            if let Some((cert, tag))
                = get_if_changed(*public_tag, &ca.fingerprint().to_string())?
            {
                *ca = Arc::new(LazyCert::from(
                    ca.to_cert()?
                        .clone()
                        .merge_public_and_secret(cert)?));
                *public_tag = tag;
            }

            Ok((Arc::clone(ca), false))
        } else {
            // The certificate is not cached in memory; we need to
            // read it from disk, or generate it.

            let (ca, created)
                = self.load_ca(special_name, create, userid, parent)?;

            let cert = Arc::clone(&ca.cert);

            t!("Loaded {} ({}) from disk, caching in memory",
               special_name, cert.fingerprint());

            match cas.entry(special_name.to_string()) {
                btree_map::Entry::Occupied(mut oe) => {
                    oe.insert(ca);
                }
                btree_map::Entry::Vacant(ve) => {
                    ve.insert(ca);
                }
            }

            Ok((cert, created))
        }
    }

    /// Loads a CA's certificate from the certificate directory, or
    /// optionally generates one if it does not exist.
    ///
    /// Loads the certificate stored under the specified special name
    /// from the certificate directory.  If the special name exists,
    /// this also reads and merges in the certificate data stored
    /// under the fingerprint.
    ///
    /// If `create` is `false` and the certificate does not exist,
    /// returns `std::io::ErrorKind::NotFound`.
    ///
    /// If `create` is `true`, and we need to generate a certificate,
    /// we are careful to so while we hold the certificate directory's
    /// lock to avoid races.
    ///
    /// If we create a certificate, and `parent` is not `None`, then
    /// we certify the certificate using `parent` as a trusted
    /// introducer for the specified trust amount.  Note: if the CA is
    /// not created, this function does **not** check that the parent
    /// has certified the CA.
    ///
    /// If we create a certificate, we write it to disk under both its
    /// special name, and its fingerprint.
    fn load_ca(&self, name: &str, create: bool, userid: &UserID,
               parent: Option<(Arc<LazyCert<'_>>, u8)>)
        -> Result<(CA<'a>, bool)>
    {
        tracer!(TRACE, "CertD::load_ca");

        let certd = self.certd();

        // Exclusively lock the certificate directory by inserting the
        // trust root.  We may discover that the trust already exists.
        // In that case, we won't generate a new one, but just load
        // the existing one.
        let mut ca = Err(anyhow::anyhow!("merge callback not invoked"));
        let mut created = false;
        let (special_tag, _) = certd.insert_special(
            name,
            (), false,
            |(), disk| {
                if let Some(disk) = disk {
                    // We have one.
                    ca = Cert::from_bytes(&disk);
                    Ok(cert_d::MergeResult::Keep)
                } else if create {
                    // We don't have one, and we should create one.
                    let key = Self::generate_ca_key(userid)?;
                    t!("Created {} for {}", key.fingerprint(), name);
                    let bytes = key.as_tsk().to_vec()?;
                    ca = Ok(key);
                    created = true;
                    Ok(cert_d::MergeResult::Data(bytes))
                } else {
                    // We don't have one, and we shouldn't create one.
                    Err(cert_d::Error::Other(
                        std::io::Error::new(
                            std::io::ErrorKind::NotFound,
                            format!("{} not found", name)).into()))
                }
            })?;
        let mut ca = ca?;
        let ca_fpr = format!("{:x}", ca.fingerprint());

        let mut certify = |parent_cert: Arc<LazyCert>, trust_amount|
                              -> Result<()>
        {
            t!("Using {} to make {} a trusted introducer",
               parent_cert.fingerprint(), ca.fingerprint());

            let mut signer = parent_cert
                .to_cert()?
                .primary_key()
                .key()
                .parts_as_secret()
                .context("Trust root can't be used for signing.")?
                .clone()
                .into_keypair()
                .context("Trust root can't be used for signing.")?;

            let sig = SignatureBuilder::new(SignatureType::GenericCertification)
                .set_exportable_certification(false)?
                .set_trust_signature(255, trust_amount)?
                .set_signature_creation_time(ca_creation_time())?
                .sign_userid_binding(
                    &mut signer,
                    ca.primary_key().key(),
                    &userid)
                .with_context(|| {
                    format!("Creating certification for {} {:?}",
                            ca.fingerprint(),
                            String::from_utf8_lossy(userid.value()))
                })?;

            ca = ca.clone().insert_packets([
                Packet::from(userid.clone()),
                Packet::from(sig),
            ])?;

            Ok(())
        };

        let public_tag = if created {
            // Make the CA a trusted introducer.
            if let Some((parent_cert, trust_amount)) = parent {
                if let Err(err) = certify(parent_cert, trust_amount) {
                    // XXX: What should we do with the error?
                    t!("Failed to authorize CA, {:?}: {}",
                       userid, err);
                }
            }

            // Insert the public bits under the fingerprint.
            let (public_tag, _) = certd.insert(
                &ca_fpr, &ca, false,
                |new, _old| {
                    Ok(cert_d::MergeResult::Data(new.to_vec()?))
                })?;

            public_tag
        } else {
            // We didn't create it.  Read in the public version and
            // merge it.
            match certd.get(&ca_fpr) {
                Ok(Some((public_tag, bytes))) => {
                    let cert = Cert::from_bytes(&bytes)
                        .with_context(|| {
                            format!("Parsing {}'s public certificate ({})",
                                    name, ca.fingerprint())
                        })?;
                    ca = ca.clone().merge_public(cert)
                        .with_context(|| {
                            format!("Merging {}'s public certificate ({})",
                                    name, ca.fingerprint())
                        })?;

                    public_tag
                }
                Ok(None) => {
                    // The certificate is saved under the special
                    // name, but not its fingerprint.  Something went
                    // wrong in the past, but we can fix it.
                    let (public_tag, _) = certd.insert(
                        &ca_fpr, &ca, false,
                        |new, _old| {
                            Ok(cert_d::MergeResult::Data(new.to_vec()?))
                        })?;

                    public_tag
                }
                Err(err) => {
                    t!("Reading {}'s public certificate: {}", name, err);
                    return Err(err.into());
                }
            }
        };

        let ca = CA {
            cert: Arc::new(LazyCert::from(ca)),
            special_tag,
            public_tag,
        };

        Ok((ca, created))
    }

    /// Returns a new key, which is appropriate for a CA.
    ///
    /// That is, it has just a certification capable primary and no
    /// subkeys.
    fn generate_ca_key(userid: &UserID) -> Result<Cert> {
        // XXX: The self signatures and direct key signature should be
        // non-exportable, but Sequoia doesn't have an easy way to do
        // that yet.
        let (root, _) = CertBuilder::new()
            .set_primary_key_flags(KeyFlags::empty().set_certification())
            .set_creation_time(ca_creation_time())
            // CAs should *not* expire.
            .set_validity_period(None)
            .add_userid_with(
                userid.clone(),
                SignatureBuilder::new(SignatureType::PositiveCertification)
                    .set_exportable_certification(false)?)?
            .generate()?;

        Ok(root)
    }

    const PUBLIC_DIRECTORY_NAME: &'static str = "public_directories";
    const PUBLIC_DIRECTORY_USERID: UserID
        = UserID::from_static_bytes(b"Public Directories");
    const PUBLIC_DIRECTORY_TRUST_AMOUNT: u8 = 40;

    /// A local, intermediate CA used to authorize the shadow CAs for
    /// public directories.
    ///
    /// Shadow CAs for public directories like
    /// `hkps://keys.openpgp.org` and WKD are not directly certified
    /// by the local trust root, but by a local, intermediate CA.
    /// This CA acts as a resistor, which limits the combined trust
    /// amount of public directories.
    pub fn public_directory_ca(&self)
        -> Result<(Arc<LazyCert<'a>>, bool)>
    {
        self.shadow_ca(
            Self::PUBLIC_DIRECTORY_NAME,
            true,
            Self::PUBLIC_DIRECTORY_USERID,
            Self::PUBLIC_DIRECTORY_TRUST_AMOUNT,
            &[])
    }

    fn via_public_directory_ca(&self, name: &str, userid: &str)
        -> Result<(Arc<LazyCert<'a>>, bool)>
    {
        self.shadow_ca(
            name,
            true,
            userid,
            // A public directory has the smallest, positive trust
            // amount: 1 out of 120.
            1,
            &[
                // The public directory CA acts as a resistor and
                // limits the combined trust amount of public
                // directories.
                (Self::PUBLIC_DIRECTORY_NAME,
                 Self::PUBLIC_DIRECTORY_USERID,
                 Self::PUBLIC_DIRECTORY_TRUST_AMOUNT),
            ])
    }

    /// Returns the shadow CA for keys.openpgp.org.
    ///
    /// See [`CertD::shadow_ca`] for more information about shadow
    /// CAs.
    pub fn shadow_ca_keys_openpgp_org(&self)
        -> Result<(Arc<LazyCert<'a>>, bool)>
    {
        self.via_public_directory_ca(
            "keys.openpgp.org",
            "Downloaded from keys.openpgp.org")
    }

    /// Returns the shadow CA for Proton.
    ///
    /// See [`CertD::shadow_ca`] for more information about shadow
    /// CAs.
    pub fn shadow_ca_proton_me(&self)
        -> Result<(Arc<LazyCert<'a>>, bool)>
    {
        self.via_public_directory_ca(
            "proton.me",
            "Downloaded from Proton Mail")
    }

    /// Returns the shadow CA for keys.mailvelope.com.
    ///
    /// See [`CertD::shadow_ca`] for more information about shadow
    /// CAs.
    pub fn shadow_ca_keys_mailvelope_com(&self)
        -> Result<(Arc<LazyCert<'a>>, bool)>
    {
        self.via_public_directory_ca(
            "keys.mailvelope.com",
            "Downloaded from keys.mailvelope.com")
    }

    /// Returns the shadow CA for WKDs.
    ///
    /// See [`CertD::shadow_ca`] for more information about shadow
    /// CAs.
    pub fn shadow_ca_wkd(&self) -> Result<(Arc<LazyCert<'a>>, bool)> {
        self.via_public_directory_ca(
            "wkd",
            "Downloaded from a Web Key Directory (WKD)")
    }

    /// Returns the shadow CA for DANE.
    ///
    /// See [`CertD::shadow_ca`] for more information about shadow
    /// CAs.
    pub fn shadow_ca_dane(&self) -> Result<(Arc<LazyCert<'a>>, bool)> {
        self.via_public_directory_ca(
            "dane",
            "Downloaded from DANE")
    }

    const WEB_NAME: &'static str = "web";
    const WEB_USERID_STR: &'static str = "Downloaded from the Web";
    const WEB_USERID: UserID
        = UserID::from_static_bytes(b"Downloaded from the Web");
    const WEB_TRUST_AMOUNT: u8 = 1;

    /// Returns the shadow CA for the Web.
    ///
    /// See [`CertD::shadow_ca`] for more information about shadow
    /// CAs.
    pub fn shadow_ca_web(&self) -> Result<(Arc<LazyCert<'a>>, bool)> {
        debug_assert_eq!(Self::WEB_USERID_STR.as_bytes(),
                         Self::WEB_USERID.value());

        self.via_public_directory_ca(
            Self::WEB_NAME,
            Self::WEB_USERID_STR)
    }

    /// Returns the shadow CA for the give URL.
    ///
    /// See [`CertD::shadow_ca`] for more information about shadow
    /// CAs.
    pub fn shadow_ca_for_url(&self, url: &str)
                             -> Result<Option<(Arc<LazyCert<'a>>, bool)>>
    {
        debug_assert_eq!(Self::WEB_USERID_STR.as_bytes(),
                         Self::WEB_USERID.value());

        // First, parse and sanitize the URL.
        let mut url = sequoia_net::reqwest::Url::parse(url)?;
        // We only certify the certificate if the transport was
        // encrypted and authenticated.
        if url.scheme() != "https" {
            return Ok(None);
        }
        // Drop sensitive and irrelevant information.
        url.set_username("").expect("https? supports authentication");
        url.set_password(None).expect("https? supports authentication");
        url.set_fragment(None);

        // Percent-encode characters not valid in names.
        let mut name = String::from("shadow_of_url_");
        for c in url.as_str().chars() {
            if Self::valid_char(c) && c != '%' {
                name.push(c);
            } else {
                // Note: all invalid chars are ASCII characters, so
                // u8::try_from will succeed.
                debug_assert_eq!(c.len_utf8(), 1);
                name.push_str(
                    &format!("%{:02X}", u8::try_from(c).unwrap_or(0)));
            }
        }

        self.shadow_ca(
            &name,
            true,
            format!("Downloaded from {}", url.as_str()),
            1,
            &[
                (Self::PUBLIC_DIRECTORY_NAME,
                 Self::PUBLIC_DIRECTORY_USERID,
                 Self::PUBLIC_DIRECTORY_TRUST_AMOUNT),
                (Self::WEB_NAME,
                 Self::WEB_USERID,
                 Self::WEB_TRUST_AMOUNT),
            ])
            .map(Some)
    }

    /// Returns a shadow CA for the specified keyserver.
    ///
    /// If a keyserver is not known to be a verifying keyserver, then
    /// this returns `Ok(None)`.
    ///
    /// The URI should be of the form `hkps://server.example.com`.
    /// Other protocols are not supported.  The server name is matched
    /// case insensitively.
    ///
    /// See [`CertD::shadow_ca`] for more information about shadow
    /// CAs.
    pub fn shadow_ca_keyserver(&self, uri: &str)
        -> Result<Option<(Arc<LazyCert<'a>>, bool)>>
    {
        let uri = uri.to_ascii_lowercase();

        // We only certify the certificate if the transport was
        // encrypted and authenticated.
        let server = if let Some(server) = uri.strip_prefix("hkps://") {
            server
        } else {
            return Ok(None);
        };

        let server = server.strip_suffix("/").unwrap_or(server);

        // A basic sanity check on the name, which we are about to use
        // as a filename: it can't start with a dot, and no
        // whitespace, no slashes, and no colons are allowed.
        if server.chars().next() == Some('.') || ! Self::valid_name(server) {
            return Ok(None);
        }

        // The known verifying key servers.
        match &server[..] {
            "keys.openpgp.org" | "keys.openpgp.io" =>
                self.shadow_ca_keys_openpgp_org().map(Some),
            "keys.mailvelope.com" =>
                self.shadow_ca_keys_mailvelope_com().map(Some),
            "mail-api.proton.me" | "api.protonmail.ch" =>
                self.shadow_ca_proton_me().map(Some),
            _ => Ok(None),
        }
    }

    const AUTOCRYPT_NAME: &'static str = "autocrypt";
    const AUTOCRYPT_USERID: UserID
        = UserID::from_static_bytes(b"Imported from Autocrypt");
    const AUTOCRYPT_TRUST_AMOUNT: u8 = 40;

    /// Returns the shadow CA for Autocrypt.
    ///
    /// See [`CertD::shadow_ca`] for more information about shadow
    /// CAs.
    pub fn shadow_ca_autocrypt(&self) -> Result<(Arc<LazyCert<'a>>, bool)> {
        self.shadow_ca(
            Self::AUTOCRYPT_NAME,
            true,
            Self::AUTOCRYPT_USERID,
            Self::AUTOCRYPT_TRUST_AMOUNT,
            &[])
    }

    const AUTOCRYPT_GOSSIP_NAME: &'static str = "autocrypt-gossip";
    const AUTOCRYPT_GOSSIP_USERID: UserID
        = UserID::from_static_bytes(b"Imported from Autocrypt Gossip");
    const AUTOCRYPT_GOSSIP_TRUST_AMOUNT: u8 = 40;

    /// Returns the shadow CA for Autocrypt Gossip.
    ///
    /// See [`CertD::shadow_ca`] for more information about shadow
    /// CAs.
    pub fn shadow_ca_autocrypt_gossip(&self)
                                      -> Result<(Arc<LazyCert<'a>>, bool)>
    {
        self.shadow_ca(
            Self::AUTOCRYPT_GOSSIP_NAME,
            true,
            Self::AUTOCRYPT_GOSSIP_USERID,
            Self::AUTOCRYPT_GOSSIP_TRUST_AMOUNT,
            &[
                (Self::AUTOCRYPT_NAME,
                 Self::AUTOCRYPT_USERID,
                 Self::AUTOCRYPT_TRUST_AMOUNT),
            ])
    }

    /// Returns the shadow CA for recording Autocrypt Gossip in the
    /// name of the given cert and sender address.
    ///
    /// If you observe an Autocrypt mail from `addr` signed by `cert`,
    /// and the message contains Autocrypt Gossip headers in the
    /// encrypted payload, use this function to get a shadow CA to
    /// turn the Autocrypt Gossip into OpenPGP certifications.
    ///
    /// See [`CertD::shadow_ca`] for more information about shadow
    /// CAs.
    pub fn shadow_ca_autocrypt_gossip_for(&self, cert: &Cert, addr: &str)
                                          -> Result<(Arc<LazyCert<'a>>, bool)>
    {
        // Sanity-check the address.
        let u = UserID::from_address(
            "Autocrypt Gossip from".into(), None, addr)?;

        self.shadow_ca(
            &format!("shadow_of_{:x}", cert.fingerprint()),
            true,
            u,
            1,
            &[
                (Self::AUTOCRYPT_NAME,
                 Self::AUTOCRYPT_USERID,
                 Self::AUTOCRYPT_TRUST_AMOUNT),
                (Self::AUTOCRYPT_GOSSIP_NAME,
                 Self::AUTOCRYPT_GOSSIP_USERID,
                 Self::AUTOCRYPT_GOSSIP_TRUST_AMOUNT),
            ])
    }
}

impl<'a> Store<'a> for CertD<'a> {
    fn lookup_by_cert(&self, kh: &KeyHandle) -> Result<Vec<Arc<LazyCert<'a>>>> {
        self.certs.lookup_by_cert(kh)
    }

    fn lookup_by_cert_fpr(&self, fingerprint: &Fingerprint)
        -> Result<Arc<LazyCert<'a>>>
    {
        self.certs.lookup_by_cert_fpr(fingerprint)
    }

    fn lookup_by_cert_or_subkey(&self, kh: &KeyHandle) -> Result<Vec<Arc<LazyCert<'a>>>> {
        self.certs.lookup_by_cert_or_subkey(kh)
    }

    fn select_userid(&self, query: &UserIDQueryParams, pattern: &str)
        -> Result<Vec<Arc<LazyCert<'a>>>>
    {
        self.certs.select_userid(query, pattern)
    }

    fn lookup_by_userid(&self, userid: &UserID) -> Result<Vec<Arc<LazyCert<'a>>>> {
        self.certs.lookup_by_userid(userid)
    }

    fn grep_userid(&self, pattern: &str) -> Result<Vec<Arc<LazyCert<'a>>>> {
        self.certs.grep_userid(pattern)
    }

    fn lookup_by_email(&self, email: &str) -> Result<Vec<Arc<LazyCert<'a>>>> {
        self.certs.lookup_by_email(email)
    }

    fn grep_email(&self, pattern: &str) -> Result<Vec<Arc<LazyCert<'a>>>> {
        self.certs.grep_email(pattern)
    }

    fn lookup_by_email_domain(&self, domain: &str) -> Result<Vec<Arc<LazyCert<'a>>>> {
        self.certs.lookup_by_email_domain(domain)
    }

    fn fingerprints<'b>(&'b self) -> Box<dyn Iterator<Item=Fingerprint> + 'b> {
        self.certs.fingerprints()
    }

    fn certs<'b>(&'b self)
        -> Box<dyn Iterator<Item=Arc<LazyCert<'a>>> + 'b>
        where 'a: 'b
    {
        self.certs.certs()
    }

    fn prefetch_all(&mut self) {
        self.certs.prefetch_all()
    }

    fn prefetch_some(&mut self, certs: &[KeyHandle]) {
        self.certs.prefetch_some(certs)
    }
}

impl<'a> StoreUpdate<'a> for CertD<'a> {
    fn update_by(&mut self, cert: Arc<LazyCert<'a>>,
                 merge_strategy: &mut dyn MergeCerts<'a>)
        -> Result<Arc<LazyCert<'a>>>
    {
        tracer!(TRACE, "CertD::update_by");
        t!("Inserting {}", cert.fingerprint());

        // This is slightly annoying: cert-d expects bytes.  But
        // serializing cert is a complete waste if we have to merge
        // the certificate with another one.  cert-d actually only
        // needs the primary key, which it uses to derive the
        // fingerprint, so, we only serialize that.
        let fpr = cert.fingerprint();
        let fpr_str = format!("{:x}", fpr);

        let mut merged = None;
        self.certd.insert(&fpr_str, (), false, |(), disk_bytes| {
            let disk: Option<Arc<LazyCert>>
                = if let Some(disk_bytes) = disk_bytes
            {
                let mut parser = RawCertParser::from_bytes(disk_bytes)
                    .with_context(|| {
                        format!("Parsing {} as returned from the cert directory",
                                fpr)
                    })
                    .map_err(|err| {
                        t!("Reading disk version: {}", err);
                        err
                    })?;
                let disk = parser.next().transpose()
                    .with_context(|| {
                        format!("Parsing {} as returned from the cert directory",
                                fpr)
                    })
                    .map_err(|err| {
                        t!("Parsing disk version: {}", err);
                        err
                    })?;
                disk.map(|disk| Arc::new(LazyCert::from(disk)))
            } else {
                t!("No disk version");
                None
            };

            let merged_ = merge_strategy.merge_public(cert, disk)
                .with_context(|| {
                    format!("Merging versions of {}", fpr)
                })
                .map_err(|err| {
                    t!("Merging: {}", err);
                    err
                })?;
            let bytes = merged_.to_vec()?;
            merged = Some(merged_);
            Ok(cert_d::MergeResult::Data(bytes))
        })?;

        let merged = merged.expect("set");
        // Inserting into the in-memory index is infallible.
        if let Err(err) = self.certs.update(merged) {
            t!("Inserting {} into in-memory index: {}", fpr, err);
        }
        // Annoyingly, there is no easy way to get index to return a
        // reference to what it just inserted.
        Ok(self.certs.lookup_by_cert_fpr(&fpr).expect("just set"))
    }
}

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

    use anyhow::Context;

    use openpgp::packet::UserID;
    use openpgp::policy::StandardPolicy;
    use openpgp::serialize::Serialize;

    use crate::store::StoreError;
    use crate::tests::print_error_chain;

    // Make sure that we can read a huge cert-d.  Specifically, the
    // typical file descriptor limit is 1024.  Make sure we can
    // initialize and iterate over a cert-d with a few more entries
    // than that.
    #[test]
    fn huge_cert_d() -> Result<()> {
        let path = tempfile::tempdir()?;
        let certd = cert_d::CertD::with_base_dir(&path)
            .map_err(|err| {
                let err = anyhow::Error::from(err)
                    .context(format!("While opening the certd {:?}", path));
                print_error_chain(&err);
                err
            })?;

        // Generate some certificates and write them to a cert-d using
        // the low-level interface.
        const N: usize = 1050;

        let mut certs = Vec::new();
        let mut certs_fpr = Vec::new();
        let mut subkeys_fpr = Vec::new();
        let mut userids = Vec::new();

        for i in 0..N {
            let userid = format!("<{}@example.org>", i);

            let (cert, _rev) = CertBuilder::new()
                .set_cipher_suite(CipherSuite::Cv25519)
                .add_userid(UserID::from(&userid[..]))
                .add_storage_encryption_subkey()
                .generate()
                .expect("ok");

            certs_fpr.push(cert.fingerprint());
            subkeys_fpr.extend(cert.keys().subkeys().map(|ka| ka.fingerprint()));
            userids.push(userid);

            let mut bytes = Vec::new();
            cert.serialize(&mut bytes).expect("can serialize to a vec");
            certd
                .insert_data(&bytes, false, |new, disk| {
                    assert!(disk.is_none());

                    Ok(cert_d::MergeResult::DataRef(new))
                })
                .with_context(|| {
                    format!("{:?} ({})", path, cert.fingerprint())
                })
                .expect("can insert");

            certs.push(cert);
        }

        // One subkey per certificate.
        assert_eq!(certs_fpr.len(), subkeys_fpr.len());

        certs_fpr.sort();

        // Open the cert-d and make sure we can read what we wrote via
        // the low-level interface.
        let certd = CertD::open(&path).expect("exists");

        // Test Store::iter.  In particular, make sure we get
        // everything back.
        let mut certs_read = certd.certs().collect::<Vec<_>>();
        assert_eq!(
            certs_read.len(), certs.len(),
            "Looks like you're exhausting the available file descriptors");

        certs_read.sort_by_key(|c| c.fingerprint());
        let certs_read_fpr
            = certs_read.iter().map(|c| c.fingerprint()).collect::<Vec<_>>();
        assert_eq!(certs_fpr, certs_read_fpr);

        // Test Store::by_cert.
        for cert in certs.iter() {
            let certs_read = certd.lookup_by_cert(&cert.key_handle()).expect("present");
            // We expect exactly one cert.
            assert_eq!(certs_read.len(), 1);
            let cert_read = certs_read.iter().next().expect("have one")
                .to_cert().expect("valid");
            assert_eq!(cert_read, cert);
        }

        for subkey in subkeys_fpr.iter() {
            let kh = KeyHandle::from(subkey.clone());
            match certd.lookup_by_cert(&kh) {
                Ok(certs) => panic!("Expected nothing, got {} certs", certs.len()),
                Err(err) => {
                    if let Some(&StoreError::NotFound(ref got))
                        = err.downcast_ref::<StoreError>()
                    {
                        assert_eq!(&kh, got);
                    } else {
                        panic!("Expected NotFound, got: {}", err);
                    }
                }
            }
        }

        // Test Store::lookup_by_cert_or_subkey.
        for fpr in certs.iter().map(|cert| cert.fingerprint())
            .chain(subkeys_fpr.iter().cloned())
        {
            let certs_read
                = certd.lookup_by_cert_or_subkey(&KeyHandle::from(fpr.clone())).expect("present");
            // We expect exactly one cert.
            assert_eq!(certs_read.len(), 1);
            let cert_read = certs_read.iter().next().expect("have one")
                .to_cert().expect("valid");

            assert!(cert_read.keys().any(|k| k.fingerprint() == fpr));
        }

        // Test Store::lookup_by_userid.
        for userid in userids.iter() {
            let userid = UserID::from(&userid[..]);

            let certs_read
                = certd.lookup_by_userid(&userid).expect("present");
            // We expect exactly one cert.
            assert_eq!(certs_read.len(), 1);
            let cert_read = certs_read.iter().next().expect("have one")
                .to_cert().expect("valid");

            assert!(cert_read.userids().any(|u| u.userid() == &userid));
        }

        Ok(())
    }

    #[test]
    fn shadow_ca() -> Result<()> {
        tracer!(true, "shadow_ca");

        let path = tempfile::tempdir()?;
        let certd = CertD::open(&path)?;

        // Check that the special exists, and includes secret key
        // material, and that there is a corresponding entry under its
        // fingerprint, which doesn't include any secret key material.
        let check = |name: &str| {
            t!("check({})", name);
            assert!(cert_d::CertD::is_special(name).is_ok());
            let (_tag, ca) = certd.certd()
                .get(name)
                .unwrap()
                .expect("exists");
            let ca = Cert::from_bytes(&ca).expect("valid");
            assert!(ca.is_tsk());

            let (_tag, cert) = certd.certd()
                .get(&ca.fingerprint().to_string())
                .unwrap()
                .expect("exists");
            let cert = Cert::from_bytes(&cert).expect("valid");
            assert!(! cert.is_tsk());

            assert_eq!(ca.fingerprint(), cert.fingerprint());

            ca
        };

        let (koo, _tag) = certd.shadow_ca(
            "keys.openpgp.org",
            true,
            UserID::from_static_bytes(b"Downloaded from keys.openpgp.org"),
            1,
            &[
                ( "public_directories",
                   UserID::from_static_bytes(b"Public Directories"),
                   10,
                ),
            ])?;

        let cert = check(&CertD::shadow_ca_special("keys.openpgp.org"));
        assert_eq!(cert.fingerprint(), koo.fingerprint());
        let public_directories
            = check(&CertD::shadow_ca_special("public_directories"));
        let trust_root
            = check(&CertD::shadow_ca_special(cert_d::TRUST_ROOT));

        let (dane, _tag) = certd.shadow_ca(
            "dane",
            true,
            UserID::from_static_bytes(b"Downloaded from DANE"),
            1,
            &[
                ( "public_directories",
                   UserID::from_static_bytes(b"Public Directories"),
                   10),
            ])?;

        let cert = check(&CertD::shadow_ca_special("dane"));
        assert_eq!(cert.fingerprint(), dane.fingerprint());
        let cert = check(&CertD::shadow_ca_special("keys.openpgp.org"));
        assert_eq!(cert.fingerprint(), koo.fingerprint());
        let cert = check(&CertD::shadow_ca_special("public_directories"));
        assert_eq!(cert, public_directories);
        let cert = check(&CertD::shadow_ca_special(cert_d::TRUST_ROOT));
        assert_eq!(cert, trust_root);

        let (tofu, _tag) = certd.shadow_ca(
            "tofu",
            true,
            UserID::from_static_bytes(b"Trust on First Use (TOFU)"),
            120,
            &[])?;

        let cert = check(&CertD::shadow_ca_special("tofu"));
        assert_eq!(cert.fingerprint(), tofu.fingerprint());
        let cert = check(&CertD::shadow_ca_special("dane"));
        assert_eq!(cert.fingerprint(), dane.fingerprint());
        let cert = check(&CertD::shadow_ca_special("keys.openpgp.org"));
        assert_eq!(cert.fingerprint(), koo.fingerprint());
        let cert = check(&CertD::shadow_ca_special("public_directories"));
        assert_eq!(cert, public_directories);
        let cert = check(&CertD::shadow_ca_special(cert_d::TRUST_ROOT));
        assert_eq!(cert, trust_root);

        Ok(())
    }

    #[test]
    fn shadow_ca_keyserver() -> Result<()> {
        tracer!(true, "keyserver_shadow_ca");

        let path = tempfile::tempdir()?;

        let test = |certd: &CertD, may_create: bool| {
            let (koo, created) = certd.shadow_ca_keys_openpgp_org().unwrap();
            if ! may_create {
                assert!(! created);
            }
            let koo = koo.fingerprint();

            let (mailvelope, created)
                = certd.shadow_ca_keys_mailvelope_com().unwrap();
            if ! may_create {
                assert!(! created);
            }
            let mailvelope = mailvelope.fingerprint();

            let lookup = |uri, expected: Option<&Fingerprint>| {
                let result = certd.shadow_ca_keyserver(uri).unwrap();
                if let Some(fingerprint) = expected {
                    let (ca, created) = result.expect("valid URI");
                    if ! may_create {
                        assert!(! created);
                    }
                    assert_eq!(fingerprint, &ca.fingerprint());
                } else {
                    assert!(result.is_none());
                }
            };

            lookup("hkps://keys.openpgp.org", Some(&koo));
            lookup("HKPS://KEYS.OPENPGP.ORG", Some(&koo));
            lookup("HKPS://KEYS.OPENPGP.io", Some(&koo));
            // hkp is not considered secure.
            lookup("hkp://keys.openpgp.org", None);
            // https is not the right protocol.
            lookup("https://keys.openpgp.org", None);
            // Not a verifying keyserver.
            lookup("hkps://keyserver.ubuntu.com", None);

            lookup("hkps://keys.mailvelope.com", Some(&mailvelope));
        };

        // The first time through we create the trust root and CAs.
        t!("Creating CAs");
        let certd = CertD::open(&path)?;
        test(&certd, true);

        // The second time through we load them from disk.
        t!("Loading CAs");
        let certd2 = CertD::open(&path)?;
        test(&certd2, false);

        Ok(())
    }

    fn check_certifiation(certd: &CertD, certifier: &Cert, cert: Fingerprint,
                          count: usize)
    {
        const P: &StandardPolicy = &StandardPolicy::new();
        let cert: Arc<LazyCert>
            = certd.lookup_by_cert_fpr(&cert).expect("exists");
        let cert: &Cert = cert.to_cert().expect("valid cert");

        let userids: Vec<UserIDAmalgamation> = cert.userids().collect();
        assert_eq!(userids.len(), 1);

        let certifications = userids[0].valid_certifications_by_key(
            P, None, certifier.primary_key().key());
        assert_eq!(certifications.count(), count);
    }

    #[test]
    fn shadow_ca_cerified() -> Result<()> {

        // Check that the shadow CA and intermediate CA are actually
        // certified.
        tracer!(true, "keyserver_shadow_certified");

        let path = tempfile::tempdir()?;

        // The first time through we create the trust root and CAs.
        t!("Creating CAs");
        let certd = CertD::open(&path)?;

        let (koo, created) = certd.shadow_ca_keys_openpgp_org().unwrap();
        assert!(created);
        let koo = koo.to_cert().expect("valid cert");

        let (pd, created) = certd.public_directory_ca().unwrap();
        // This should have been created in the last step.
        assert!(! created);
        let pd = pd.to_cert().expect("valid cert");

        let (tr, created) = certd.trust_root().unwrap();
        // This should have been created in the last step.
        assert!(! created);
        let tr = tr.to_cert().expect("valid cert");

        let (kmc, created) = certd.shadow_ca_keys_mailvelope_com().unwrap();
        assert!(created);
        let kmc = kmc.to_cert().expect("valid cert");

        // Avoid the in-memory cache.
        let certd = CertD::open(&path)?;

        t!("Checking that the PD CA certified the KOO shadow CA.");
        check_certifiation(&certd, &pd, koo.fingerprint(), 1);
        t!("Checking that the PD CA certified the KMC shadow CA.");
        check_certifiation(&certd, &pd, kmc.fingerprint(), 1);
        t!("Checking that the trust root certified the PD CA.");
        check_certifiation(&certd, &tr, pd.fingerprint(), 1);
        t!("Checking that the trust root didn't the KOO shadow CA.");
        check_certifiation(&certd, &tr, koo.fingerprint(), 0);
        t!("Checking that the trust root didn't the KMC shadow CA.");
        check_certifiation(&certd, &tr, kmc.fingerprint(), 0);

        Ok(())
    }

    #[test]
    fn shadow_ca_for_url() -> Result<()> {
        tracer!(true, "shadow_ca_for_url");

        let path = tempfile::tempdir()?;

        let test = |certd: &CertD, may_create: bool| {
            let (alice, created) = certd
                .shadow_ca_for_url("https://example.org/alice.pgp")
                .unwrap().unwrap();
            if ! may_create {
                assert!(! created);
            }
            let alice = alice.fingerprint();

            #[derive(Debug)]
            enum Expectation { Alice, Other, NoCA }
            use Expectation::*;
            let lookup = |uri, expectation| {
                t!("looking up {} expecting {:?}", uri, expectation);
                let result = certd.shadow_ca_for_url(uri).unwrap();
                match expectation {
                    Alice => {
                        let (ca, created) = result.expect("valid URI");
                        if ! may_create {
                            assert!(! created);
                        }
                        assert_eq!(alice, ca.fingerprint());
                    },
                    Other => {
                        let (_ca, created) = result.expect("valid URI");
                        if ! may_create {
                            assert!(! created);
                        }
                    },
                    NoCA => {
                        assert!(result.is_none());
                    },
                }
            };

            lookup("https://example.org/alice.pgp", Alice);
            lookup("HTTPS://EXAMPLE.ORG/alice.pgp", Alice);
            lookup("https://foo@example.org/alice.pgp", Alice);
            lookup("https://foo:bar@example.org/alice.pgp", Alice);
            lookup("https://foo:bar@example.org/alice.pgp#fragment", Alice);
            // http is not considered secure.
            lookup("http://example.org/alice.pgp", NoCA);
            // hkps is not the right protocol.
            lookup("hkps://example.org/alice.pgp", NoCA);
            // Different URLs.
            lookup("https://example.org/bob.pgp", Other);
            lookup("https://example.net/alice.pgp", Other);
            lookup("https://example.org/alice.pgp?some=query", Other);
            lookup("https://example.org/alice.pgp/other/path", Other);
        };

        // The first time through we create the trust root and CAs.
        t!("Creating CAs");
        let certd = CertD::open(&path)?;
        test(&certd, true);

        // The second time through we load them from disk.
        t!("Loading CAs");
        let certd2 = CertD::open(&path)?;
        test(&certd2, false);

        Ok(())
    }

    #[test]
    fn shadow_ca_for_web_cerified() -> Result<()> {
        // Check that the shadow CA and intermediate CA are actually
        // certified.
        tracer!(true, "shadow_ca_for_web_cerified");

        let path = tempfile::tempdir()?;

        // The first time through we create the trust root and CAs.
        t!("Creating CAs");
        let certd = CertD::open(&path)?;

        let (alice, created) = certd
            .shadow_ca_for_url("https://example.org/alice.pgp")
            .unwrap().unwrap();
        assert!(created);
        let alice = alice.to_cert().expect("valid cert");

        let (tr, created) = certd.trust_root().unwrap();
        // This should have been created in the first step.
        assert!(! created);
        let tr = tr.to_cert().expect("valid cert");

        let (pd, created) = certd.public_directory_ca().unwrap();
        // This should have been created in the first step.
        assert!(! created);
        let pd = pd.to_cert().expect("valid cert");

        let (web, created) = certd.shadow_ca_web().unwrap();
        // This should have been created in the first step.
        assert!(! created);
        let web = web.to_cert().expect("valid cert");

        // Avoid the in-memory cache.
        let certd = CertD::open(&path)?;

        t!("Checking that the trust root certified the PD CA.");
        check_certifiation(&certd, &tr, pd.fingerprint(), 1);
        t!("Checking that the PD CA certified the web CA.");
        check_certifiation(&certd, &pd, web.fingerprint(), 1);
        t!("Checking that the web CA certified the ALICE shadow CA.");
        check_certifiation(&certd, &web, alice.fingerprint(), 1);
        t!("Checking that the trust root didn't the web CA.");
        check_certifiation(&certd, &tr, web.fingerprint(), 0);
        t!("Checking that the trust root didn't the ALICE shadow CA.");
        check_certifiation(&certd, &tr, alice.fingerprint(), 0);
        t!("Checking that the PD CA didn't the ALICE shadow CA.");
        check_certifiation(&certd, &pd, alice.fingerprint(), 0);

        Ok(())
    }

    /// Test that we can create and sanitize, or reject CAs for funny
    /// URLs.
    #[test]
    fn shadow_ca_for_url_escapes() -> Result<()> {
        tracer!(true, "shadow_ca_for_url_escapes");

        let path = tempfile::tempdir()?;
        let test = |certd: &CertD, url, stripped| {
            t!("trying {:?}", url);
            let (alice, _created) =
                certd.shadow_ca_for_url(url).unwrap().unwrap();
            if let Some(c) = stripped {
                // Make sure the character is stripped.
                assert!(alice.userids().all(
                    |uid| ! str::from_utf8(uid.value()).unwrap().contains(c)));
            } else {
                // Make sure the odd character is percent-encoded.
                assert!(alice.userids().all(
                    |uid| str::from_utf8(uid.value()).unwrap().contains("%")));
            }
        };

        let test_fail = |certd: &CertD, url| {
            t!("trying {:?}", url);
            certd.shadow_ca_for_url(url).unwrap_err();
        };

        let certd = CertD::open(&path)?;

        // In the path:
        test(&certd, "https://example.org/alice\u{0a}bob.pgp", Some("\u{0a}"));
        test(&certd, "https://example.org/alice\u{0d}bob.pgp", Some("\u{0d}"));
        test(&certd, "https://example.org/alice\u{09}bob.pgp", Some("\u{09}"));
        test(&certd, "https://example.org/alice\u{0c}bob.pgp", Some("\u{0c}"));
        test(&certd, "https://example.org/alice\u{08}\u{08}\u{08}\u{08}\u{08}bob.pgp", None);
        test(&certd, "https://example.org/alice\u{200f}bob.pgp", None); // RTL mark

        // In the query:
        test(&certd, "https://example.org/alice.pgp?q=\u{0a}bob.pgp", Some("\u{0a}"));
        test(&certd, "https://example.org/alice.pgp?q=\u{0d}bob.pgp", Some("\u{0d}"));
        test(&certd, "https://example.org/alice.pgp?q=\u{09}bob.pgp", Some("\u{09}"));
        test(&certd, "https://example.org/alice.pgp?q=\u{0c}bob.pgp", Some("\u{0c}"));
        test(&certd, "https://example.org/alice.pgp?q=\u{08}\u{08}\u{08}\u{08}\u{08}bob.pgp", None);
        test(&certd, "https://example.org/alice.pgp?q=\u{200f}bob.pgp", None); // RTL mark

        // In the host:
        test(&certd, "https://example.\u{0a}bob.pgp.org/alice.pgp", Some("\u{0a}"));
        test(&certd, "https://example.\u{0d}bob.pgp.org/alice.pgp", Some("\u{0d}"));
        test(&certd, "https://example.\u{09}bob.pgp.org/alice.pgp", Some("\u{09}"));
        test_fail(&certd, "https://example.\u{0c}bob.pgp.org/alice.pgp");
        test_fail(&certd, "https://example.\u{08}\u{08}\u{08}\u{08}\u{08}bob.pgp.org/alice.pgp");
        test_fail(&certd, "https://example.\u{200f}bob.pgp.org/alice.pgp"); // RTL mark

        Ok(())
    }
}