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
//! A certificate store abstraction.
//!
//! This crates provides a unified interface for different certificate
//! stores via the [`Store`] and [`StoreUpdate`] traits.  It also
//! provides a number of helper functions and data structures, like
//! [`UserIDIndex`] to help implement this functionality.
//!
//! [`UserIDIndex`]: store::UserIDIndex
//!
//! The [`CertStore`] data structure combines multiple certificate
//! backends in a transparent way to users.
//!
//! # Examples
//!
//! We can store certificates in an in-memory store, and query the store:
//!
//! ```rust
//! use std::sync::Arc;
//! use sequoia_openpgp::cert::{Cert, CertBuilder};
//! use sequoia_cert_store::{CertStore, LazyCert, Store, StoreUpdate};
//!
//! # fn main() -> anyhow::Result<()> {
//! // Create an in-memory certificate store.  To use the default
//! // on-disk certificate store, use `CertStore::new`.
//! let mut certs = CertStore::empty();
//!
//! let (cert, _rev) = CertBuilder::new().generate()?;
//! let fpr = cert.fingerprint();
//!
//! // It's not in the cert store yet:
//! assert!(certs.lookup_by_cert_fpr(&fpr).is_err());
//!
//! // Insert a certificate.  If using a backing store, it would
//! // also be written to disk.
//! certs.update(Arc::new(LazyCert::from(cert)))?;
//!
//! // Make sure it is there.
//! let cert = certs.lookup_by_cert_fpr(&fpr).expect("present");
//! assert_eq!(cert.fingerprint(), fpr);
//!
//! // Resolve the `LazyCert` to a `Cert`.  Certificates are stored
//! // using `LazyCert` so that it is possible to work with `RawCert`s
//! // and `Cert`s.  This allows the implementation to defer fully parsing
//! // and validating the certificate until it is actually needed.
//! let cert: &Cert = cert.to_cert()?;
//! # Ok(()) }
//! ```
//!
//! We can use the same API on a persistent certificate store, kept on the
//! filesystem:
//!
//! ```rust
//! use std::fs;
//! # use tempfile;
//! #
//! # use std::sync::Arc;
//! #
//! # use sequoia_openpgp as openpgp;
//! # use openpgp::Result;
//! # use openpgp::cert::{Cert, CertBuilder};
//! #
//! # use sequoia_cert_store::{CertStore, LazyCert, Store, StoreUpdate};
//!
//! # fn main() -> Result<()> {
//! // Make a certificate store on the file system, in a fresh empty directory.
//! let directory = "/tmp/test-sequoia-certificate-directory";
//! # let directory_object = tempfile::tempdir()?; let directory = directory_object.path();
//! fs::create_dir_all(directory)?;
//! let mut store = CertStore::open(directory)?;
//!
//! // Make a new certificate.
//! let (cert, _rev) = CertBuilder::new().generate()?;
//! let fpr = cert.fingerprint();
//!
//! // The certificate of course will not be in the store yet.
//! assert!(store.lookup_by_cert_fpr(&fpr).is_err());
//!
//! // Add it.
//! store.update(Arc::new(LazyCert::from(cert)))?;
//!
//! // Now the certificate can be found.
//! let found = store.lookup_by_cert_fpr(&fpr).expect("present");
//! assert_eq!(found.fingerprint(), fpr);
//!
//! // Again, we can resolve the `LazyCert` to a `Cert`.
//! let cert: &Cert = found.to_cert()?;
//! # Ok(()) }
//! ```

use std::str;

use sequoia_openpgp as openpgp;
use openpgp::Result;
use openpgp::packet::UserID;

#[macro_use] mod log;
#[macro_use] mod macros;

pub mod store;
pub use store::Store;
pub use store::StoreUpdate;
mod cert_store;
pub use cert_store::CertStore;
pub use cert_store::AccessMode;

mod lazy_cert;
pub use lazy_cert::LazyCert;

const TRACE: bool = false;

/// Converts an email address to a User ID.
///
/// If the email address is not valid, returns an error.
///
/// The email address must be a bare email address.  That is it must
/// have the form `localpart@example.org`, and not be surrounded by
/// angle brackets like `<localpart@example.org>`.
///
/// The email address is checked for validity.  Specifically, it is
/// checked to conform with [`RFC 2822`]'s [`addr-spec`] grammar.
///
/// Returns a UserID containing the normalized User ID in angle
/// brackets.
///
/// [`RFC 2822`]: https://www.rfc-editor.org/rfc/rfc2822
/// [`addr-spec`]: https://www.rfc-editor.org/rfc/rfc2822#section-3.4.1
pub fn email_to_userid(email: &str) -> Result<UserID> {
    let email_check = UserID::from(format!("<{}>", email));
    match email_check.email2() {
        Ok(Some(email_check)) => {
            if email != email_check {
                return Err(anyhow::anyhow!(
                    "{:?} does not appear to be an email address",
                    email));
            }
        }
        Ok(None) => {
            return Err(anyhow::anyhow!(
                "{:?} does not appear to be an email address",
                email));
        }
        Err(err) => {
            return Err(err.context(format!(
                "{:?} does not appear to be an email address",
                email)));
        }
    }

    let userid = UserID::from(&email[..]);
    match userid.email_normalized() {
        Err(err) => {
            Err(err.context(format!(
                "'{}' is not a valid email address", email)))
        }
        Ok(None) => {
            Err(anyhow::anyhow!("'{}' is not a valid email address", email))
        }
        Ok(Some(_email)) => {
            Ok(userid)
        }
    }
}

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

    use std::path::PathBuf;
    use std::str;
    use std::sync::Arc;

    use anyhow::Context;
    /// Prints the error and causes, if any.
    pub fn print_error_chain(err: &anyhow::Error) {
        let _ = write_error_chain_into(&mut std::io::stderr(), err);
    }

    /// Prints the error and causes, if any.
    fn write_error_chain_into(sink: &mut dyn std::io::Write, err: &anyhow::Error)
                              -> Result<()> {
        writeln!(sink, "           {}", err)?;
        for cause in err.chain().skip(1) {
            writeln!(sink, "  because: {}", cause)?;
        }
        Ok(())
    }

    use openpgp::Fingerprint;
    use openpgp::KeyHandle;
    use openpgp::KeyID;
    use openpgp::Cert;
    use openpgp::parse::Parse;
    use openpgp::policy::StandardPolicy;
    use openpgp::serialize::Serialize;

    use openpgp_cert_d as cert_d;

    use store::Certs;
    use store::Pep;
    use store::StoreError;
    use store::UserIDQueryParams;

    fn certd_merge<'a>(new: &'a [u8], disk: Option<&[u8]>)
        -> cert_d::Result<cert_d::MergeResult<'a>>
    {
        if let Some(disk) = disk {
            let new = Cert::from_bytes(&new).expect("valid");
            let disk = Cert::from_bytes(&disk).expect("valid");
            let merged = new.merge_public(disk).expect("valid");
            let mut bytes = Vec::new();
            merged.serialize(&mut bytes).expect("valid");
            Ok(bytes.into())
        } else {
            Ok(cert_d::MergeResult::DataRef(new))
        }
    }

    include!("../tests/keyring.rs");

    fn test_backend<'a, B>(backend: &B)
        where B: Store<'a>
    {
        // Check Store::list.
        {
            let mut got: Vec<Fingerprint> = backend.fingerprints().collect();
            got.sort();
            let mut expected: Vec<Fingerprint> = keyring::certs.iter()
                .map(|c| c.fingerprint.parse::<Fingerprint>().expect("valid"))
                .collect();
            expected.sort();
            expected.dedup();
            assert_eq!(got.len(), expected.len());
            assert_eq!(got, expected);
        }

        std::thread::yield_now();

        // Check Store::iter.
        {
            let mut got: Vec<Fingerprint>
                = backend.certs().map(|c| c.fingerprint()).collect();
            got.sort();
            let mut expected: Vec<Fingerprint> = keyring::certs.iter()
                .map(|c| c.fingerprint.parse::<Fingerprint>().expect("valid"))
                .collect();
            expected.sort();
            expected.dedup();
            assert_eq!(got.len(), expected.len());
            assert_eq!(got, expected);
        }

        std::thread::yield_now();

        // Iterate over the certificates in the keyring and check that
        // can look up the certificate by fingerprint, by key, by User
        // ID, and by email in various ways.
        for handle in keyring::certs.iter() {
            let fpr: Fingerprint = handle.fingerprint.parse().expect("valid");
            let cert = handle.to_cert().expect("valid");
            assert_eq!(fpr, cert.fingerprint(),
                       "{}", handle.base);
            let keyid = KeyID::from(fpr.clone());

            // Check by_cert_fpr.
            let got = backend.lookup_by_cert_fpr(&fpr).expect("present");
            assert_eq!(got.fingerprint(), fpr,
                       "{}, by_cert_fpr, primary", handle.base);

            // Look up by subkey and make sure we don't get cert.
            // Note: if a subkey is also a primary key (as is the case
            // for the ed certificate), then we'll get a certificate
            // back.
            for sk in cert.keys().subkeys() {
                match backend.lookup_by_cert_fpr(&sk.fingerprint()) {
                    Ok(got) => {
                        // Make sure what we got is what we looked up.
                        assert_eq!(got.fingerprint(), sk.fingerprint());

                        // Make sure subkey is also a primary key.
                        assert!(
                            keyring::certs.iter().any(|c| {
                                c.fingerprint.parse::<Fingerprint>().unwrap()
                                    == got.fingerprint()
                            }),
                            "{}, lookup_by_cert_fpr, subkey, unexpectedly got {}",
                            handle.base, got.fingerprint());
                    }
                    Err(err) => {
                        match err.downcast_ref::<StoreError>() {
                            Some(StoreError::NotFound(_)) => (),
                            _ => panic!("Expected StoreError::NotFound, \
                                         got: {}",
                                        err),
                        }
                    },
                }

                std::thread::yield_now();
            }

            // Check lookup_by_cert using key ids.
            let got = backend.lookup_by_cert(&KeyHandle::from(&keyid))
                .expect("present");
            // Make sure all the returned certificates match.
            assert!(got.iter()
                    .all(|c| {
                        c.keys().any(|k| k.keyid() == keyid)
                    }),
                    "{}, lookup_by_cert, keyid, primary",
                    handle.base);

            // Make sure one of the returned certs is the cert we're
            // looking for.
            assert!(got.into_iter().any(|c| c.fingerprint() == fpr),
                    "{}, lookup_by_cert, keyid, primary", handle.base);

            // Look up by subkey.  This will only return something if
            // the subkey also happens to be a primary key.
            for sk in cert.keys().subkeys() {
                match backend.lookup_by_cert(&KeyHandle::from(sk.keyid())) {
                    Ok(got) => {
                        // We should never see an empty result.
                        // Instead, the backend should return
                        // StoreError::NotFound.
                        assert!(! got.is_empty());

                        // Make sure we got what we looked up.
                        for got in got.iter() {
                            assert_eq!(got.keyid(), sk.keyid());
                        }

                        // Make sure subkey is also a primary key.
                        for got in got.into_iter() {
                            assert!(
                                keyring::certs.iter().any(|c| {
                                    c.fingerprint.parse::<Fingerprint>()
                                        .unwrap()
                                        == got.fingerprint()
                                }),
                                "{}, lookup_by_cert_fpr, subkey, \
                                 unexpectedly got {}",
                                handle.base, got.fingerprint());
                        }
                    }
                    Err(err) => {
                        match err.downcast_ref::<StoreError>() {
                            Some(StoreError::NotFound(_)) => (),
                            _ => panic!("Expected StoreError::NotFound, \
                                         got: {}",
                                        err),
                        }
                    },
                }

                std::thread::yield_now();
            }

            // Check lookup_by_cert_or_subkey using fingerprints.
            let got = backend.lookup_by_cert_or_subkey(&KeyHandle::from(fpr.clone()))
                .expect("present");
            // Make sure all the returned certificates match.
            assert!(got.iter()
                    .all(|c| {
                        c.keys().any(|k| k.fingerprint() == fpr)
                    }),
                    "{}, lookup_by_cert_or_subkey, with fingerprint, primary",
                    handle.base);

            // Make sure one of the returned certs is the cert we're
            // looking for.
            assert!(got.into_iter().any(|c| c.fingerprint() == fpr),
                    "{}, lookup_by_cert_or_subkey, with fingerprint, primary",
                    handle.base);

            // Look up by subkey and make sure we get cert.
            for sk in cert.keys().subkeys() {
                let got = backend.lookup_by_cert_or_subkey(
                    &KeyHandle::from(sk.fingerprint()))
                    .expect("present");
                // Make sure all the returned certificates match.
                for got in got.iter() {
                    assert!(
                        got.keys().any(|k| k.fingerprint() == sk.fingerprint()),
                        "{}, lookup_by_cert_or_subkey({}), with fingerprint, subkey",
                        handle.base, sk.fingerprint());
                }

                // Make sure one of the returned certs is the cert
                // we're looking for.
                assert!(got.into_iter().any(|c| c.fingerprint() == fpr),
                        "{}, lookup_by_cert_or_subkey({}), with fingerprint, subkey",
                        handle.base, sk.fingerprint());

                std::thread::yield_now();
            }


            // Check lookup_by_cert_or_subkey using keyids.
            let got = backend.lookup_by_cert_or_subkey(&KeyHandle::from(keyid.clone()))
                .expect("present");
            // Make sure all the returned certificates match.
            for got in got.iter() {
                assert!(
                    got.keys().any(|k| k.keyid() == keyid),
                    "{}, lookup_by_cert_or_subkey({}), with keyid, primary",
                    handle.base, keyid);
            }

            // Make sure one of the returned certs is the cert
            // we're looking for.
            assert!(got.into_iter().any(|c| c.fingerprint() == fpr),
                    "{}, lookup_by_cert_or_subkey({}), with keyid, primary",
                    handle.base, keyid);

            // Look up by subkey and make sure we get cert.
            for sk in cert.keys().subkeys() {
                let got = backend.lookup_by_cert_or_subkey(&KeyHandle::from(sk.keyid()))
                    .expect("present");
                // Make sure all the returned certificates match.
                for got in got.iter() {
                    assert!(
                        got.keys().any(|k| k.keyid() == sk.keyid()),
                        "{}, lookup_by_cert_or_subkey({}), with keyid, subkey",
                        handle.base, sk.keyid());
                }

                // Make sure one of the returned certs is the cert
                // we're looking for.
                assert!(got.into_iter().any(|c| c.fingerprint() == fpr),
                        "{}, lookup_by_cert_or_subkey({}), with keyid, subkey",
                        handle.base, sk.keyid());

                std::thread::yield_now();
            }


            // Check look up by User ID address by querying for each
            // User ID, email, domain, etc.
            for ua in cert.userids() {
                let userid = ua.userid();

                // Search by exact user id.
                let got = backend.lookup_by_userid(userid)
                    .expect(&format!("{}, lookup_by_userid({:?})",
                                     handle.base, userid));
                // Make sure all the returned certificates match.
                for got in got.iter() {
                    assert!(
                        got.userids().any(|u| &u == userid),
                        "{}, lookup_by_userid({:?})", handle.base, userid);
                }

                // Make sure one of the returned certs is the cert
                // we're looking for.
                assert!(got.into_iter().any(|c| c.fingerprint() == fpr),
                        "{}, lookup_by_userid({:?})",
                        handle.base, userid);

                // Extract an interior substring (nor anchored at the
                // start or the end), and uppercase it.
                let pattern = str::from_utf8(userid.value()).expect("utf-8");
                let pattern = &pattern[1..pattern.len() - 1];
                let pattern = pattern.to_uppercase();

                // grep removes all constraints so we should still
                // find it.
                let got = backend.grep_userid(&pattern)
                    .expect(&format!("{}, grep_userid({:?})",
                                     handle.base, pattern));

                // Make sure all the returned certificates match.
                let mut query = UserIDQueryParams::new();
                query.set_email(false);
                query.set_anchor_start(false);
                query.set_anchor_end(false);
                query.set_ignore_case(true);
                for got in got.iter() {
                    assert!(
                        got.userids().any(|u| query.check(&u, &pattern)),
                        "{}, grep_userid({:?})", handle.base, pattern);
                }

                // Make sure one of the returned certs is the cert
                // we're looking for.
                assert!(got.into_iter().any(|c| c.fingerprint() == fpr),
                        "{}, grep_userid({:?})", handle.base, pattern);

                // Now use an anchor at the start, or the end, ignore
                // case, or not.  The only one combination that should
                // return any results is no constraints, which we
                // tested above.
                for (start, end, ignore_case) in
                    [(false, false, false),
                     //(false, false,  true),
                     (false,  true, false),
                     (false,  true,  true),
                     ( true, false, false),
                     ( true, false,  true),
                     ( true,  true, false),
                     ( true,  true,  true)]
                {
                    let result = backend.select_userid(
                        UserIDQueryParams::new()
                            .set_email(false)
                            .set_anchor_start(start)
                            .set_anchor_end(end)
                            .set_ignore_case(ignore_case),
                        &pattern);
                    match result {
                        Ok(got) => {
                            panic!("{}, select_userid({:?}) -> {}",
                                   handle.base, pattern,
                                   got.into_iter()
                                   .map(|c| c.fingerprint().to_string())
                                   .collect::<Vec<String>>()
                                   .join(", "));
                        }
                        Err(err) => {
                            match err.downcast_ref::<StoreError>() {
                                Some(StoreError::NoMatches(_)) => (),
                                _ => panic!("{}, select_userid({:?}) -> {}",
                                            handle.base, pattern, err),
                            }
                        }
                    }
                }

                // Search by exact email.
                let email = if let Ok(Some(email)) = userid.email2() {
                    email
                } else {
                    // No email address.
                    continue;
                };

                // Search with the User ID using lookup_by_email.  This will
                // fail: a User ID that contains an email address is
                // never a valid email address.
                assert!(
                    backend.lookup_by_email(
                        str::from_utf8(userid.value()).expect("valid utf-8"))
                        .is_err(),
                    "{}, lookup_by_email({:?})", handle.base, userid);

                // Search by email.
                let got = backend.lookup_by_email(&email)
                    .expect(&format!("{}, lookup_by_email({:?})",
                                     handle.base, email));
                // Make sure all the returned certificates match.
                let mut query = UserIDQueryParams::new();
                query.set_email(true);
                query.set_anchor_start(true);
                query.set_anchor_end(true);
                query.set_ignore_case(false);
                for got in got.iter() {
                    assert!(
                        got.userids().any(|u| query.check(&u, &email)),
                        "{}, lookup_by_email({:?})",
                        handle.base, email);
                }

                // Make sure one of the returned certs is the cert
                // we're looking for.
                assert!(got.into_iter().any(|c| c.fingerprint() == fpr),
                        "{}, lookup_by_email({:?})", handle.base, userid);

                // Extract an interior substring (nor anchored at the
                // start or the end), and uppercase it.
                let pattern = &email[1..email.len() - 1];
                let pattern = pattern.to_uppercase();

                // grep removes all constraints so we should still
                // find it.
                let got = backend.grep_email(&pattern)
                    .expect(&format!("{}, grep_email({:?})",
                                     handle.base, pattern));
                // Make sure all the returned certificates match.
                let mut query = UserIDQueryParams::new();
                query.set_email(true);
                query.set_anchor_start(false);
                query.set_anchor_end(false);
                query.set_ignore_case(true);
                for got in got.iter() {
                    assert!(
                        got.userids().any(|u| query.check(&u, &pattern)),
                        "{}, grep_email({:?})", handle.base, pattern);
                }

                // Make sure one of the returned certs is the cert
                // we're looking for.
                assert!(got.into_iter().any(|c| c.fingerprint() == fpr),
                        "{}, grep_email({:?})", handle.base, pattern);

                // Now use an anchor at the start, or the end, ignore
                // case, or not.  This should not return any results;
                // the only one that should return any results is no
                // constraints, which we tested above.
                for (start, end, ignore_case) in
                    [(false, false, false),
                     //(false, false,  true),
                     (false,  true, false),
                     (false,  true,  true),
                     ( true, false, false),
                     ( true, false,  true),
                     ( true,  true, false),
                     ( true,  true,  true)]
                {
                    let result = backend.select_userid(
                        UserIDQueryParams::new()
                            .set_email(true)
                            .set_anchor_start(start)
                            .set_anchor_end(end)
                            .set_ignore_case(ignore_case),
                        &pattern);
                    match result {
                        Ok(got) => {
                            panic!("{}, select_userid({:?}) -> {}",
                                   handle.base, pattern,
                                   got.into_iter()
                                   .map(|c| c.fingerprint().to_string())
                                   .collect::<Vec<String>>()
                                   .join(", "));
                        }
                        Err(err) => {
                            match err.downcast_ref::<StoreError>() {
                                Some(StoreError::NoMatches(_)) => (),
                                _ => panic!("{}, select_userid({:?}) -> {}",
                                            handle.base, pattern, err),
                            }
                        }
                    }
                }



                // Search by domain.
                let domain = email.rsplit('@').next().expect("have an @");

                // Search with the User ID using lookup_by_email_domain.
                // This will fail: a User ID that contains an email
                // address is never a valid email address.
                assert!(
                    backend.lookup_by_email_domain(
                        str::from_utf8(userid.value()).expect("valid utf-8"))
                        .is_err(),
                    "{}, lookup_by_email_domain({:?})", handle.base, userid);
                // Likewise with the email address.
                assert!(
                    backend.lookup_by_email_domain(&email).is_err(),
                    "{}, lookup_by_email_domain({:?})", handle.base, email);

                // Search by domain.  We should find it.
                let got = backend.lookup_by_email_domain(&domain)
                    .expect(&format!("{}, lookup_by_email_domain({:?})",
                                     handle.base, domain));
                // Make sure all the returned certificates match.
                let mut query = UserIDQueryParams::new();
                query.set_email(true);
                query.set_anchor_start(false);
                query.set_anchor_end(true);
                query.set_ignore_case(true);
                let at_domain = format!("@{}", domain);
                for got in got.iter() {
                    assert!(
                        got.userids().any(|u| query.check(&u, &at_domain)),
                        "{}, lookup_by_email_domain({:?})",
                        handle.base, domain);
                }

                // Make sure one of the returned certs is the cert
                // we're looking for.
                assert!(got.into_iter().any(|c| c.fingerprint() == fpr),
                        "{}, lookup_by_email_domain({:?})",
                        handle.base, userid);

                // Uppercase it.  We should still find it.
                let pattern = domain.to_uppercase();
                let got = backend.lookup_by_email_domain(&pattern)
                    .expect(&format!("{}, lookup_by_email_domain({:?})",
                                     handle.base, pattern));
                // Make sure all the returned certificates match.
                let mut query = UserIDQueryParams::new();
                query.set_email(true);
                query.set_anchor_start(false);
                query.set_anchor_end(true);
                query.set_ignore_case(true);
                let at_domain = format!("@{}", pattern);
                for got in got.iter() {
                    assert!(
                        got.userids().any(|u| query.check(&u, &at_domain)),
                        "{}, lookup_by_email_domain({:?})",
                        handle.base, domain);
                }

                // Make sure one of the returned certs is the cert
                // we're looking for.
                assert!(got.into_iter().any(|c| c.fingerprint() == fpr),
                        "{}, lookup_by_email_domain({:?})",
                        handle.base, pattern);

                // Extract a substring that we shouldn't find.
                let pattern = &domain[1..pattern.len() - 1];
                let result = backend.lookup_by_email_domain(pattern);
                match result {
                    Ok(got) => {
                        // We should never see an empty result.
                        // Instead, the backend should return
                        // StoreError::NotFound.
                        assert!(! got.is_empty());

                        assert!(
                            got.into_iter().all(|c| {
                                c.fingerprint() != fpr
                            }),
                            "{}, lookup_by_email_domain({:?}, unexpectedly got {}",
                            handle.base, pattern, fpr);
                    }
                    Err(err) => {
                        match err.downcast_ref::<StoreError>() {
                            Some(StoreError::NoMatches(_)) => (),
                            _ => panic!("{}, lookup_by_email_domain({:?}) -> {}",
                                        handle.base, pattern, err),
                        }
                    }
                }

                std::thread::yield_now();
            }
        }

        // So far, the tests have been generic in the sense that we
        // look up what is there.  We now do some data set-specific
        // tests.

        let sort_vec = |mut v: Vec<_>| -> Vec<_> {
            v.sort();
            v
        };

        // alice and alice2 share a subkey.
        assert_eq!(
            sort_vec(backend.lookup_by_cert_or_subkey(
                &"5989D7BE9908AE24799DF6CFBE678043781349F1"
                    .parse::<KeyHandle>().expect("valid"))
                .expect("present")
                .into_iter()
                .map(|c| c.fingerprint())
                .collect::<Vec<Fingerprint>>()),
            sort_vec(
                vec![
                    keyring::alice.fingerprint
                        .parse::<Fingerprint>().expect("valid"),
                    keyring::alice2_adopted_alice.fingerprint
                        .parse::<Fingerprint>().expect("valid"),
            ]));

        std::thread::yield_now();

        // ed's primary is also a subkey on the same certificate.
        {
            let ed_fpr = "0C346B2B6241263F64E9C7CF1EA300797258A74E"
                .parse::<Fingerprint>().expect("valid");
            let ed_kh = KeyHandle::from(&ed_fpr);

            assert_eq!(
                sort_vec(backend.lookup_by_cert_or_subkey(&ed_kh)
                         .expect("present")
                         .into_iter()
                         .map(|c| c.fingerprint())
                         .collect::<Vec<Fingerprint>>()),
                sort_vec(
                    vec![
                        keyring::ed.fingerprint
                            .parse::<Fingerprint>().expect("valid"),
                    ]));

            // Also test that the CertStore implementation is not
            // impacted.
            let cert = backend.lookup_by_cert_fpr(&ed_fpr)
                .expect("found cert");
            assert_eq!(cert.fingerprint(), ed_fpr);

            // Make sure the implementation doesn't return the certificate
            // twice, once when matching on the primary key, and once when
            // matching on the subkey.
            let certs = backend.lookup_by_cert(&ed_kh)
                .expect("found cert");
            assert_eq!(certs.len(), 1);
            assert_eq!(certs[0].fingerprint(), ed_fpr);

            let certs = backend.lookup_by_cert_or_subkey(&ed_kh)
                .expect("found cert");
            assert_eq!(certs.len(), 1);
            assert_eq!(certs[0].fingerprint(), ed_fpr);

            let certs = backend.certs();
            assert_eq!(certs.filter(|c| c.fingerprint() == ed_fpr).count(),
                       1);

            let fprs = backend.fingerprints();
            assert_eq!(fprs.filter(|fpr| fpr == &ed_fpr).count(),
                       1);
        }

        // david has a subkey that doesn't have a binding signature,
        // but the backend is not supposed to check that.  (That
        // subkey is bound to carol.)
        assert_eq!(
            sort_vec(backend.lookup_by_cert_or_subkey(
                &"CD22D4BD99FF10FDA11A83D4213DCB92C95346CE"
                    .parse::<KeyHandle>().expect("valid"))
                .expect("present")
                .into_iter()
                .map(|c| c.fingerprint())
                .collect::<Vec<Fingerprint>>()),
            sort_vec(
                vec![
                    keyring::carol.fingerprint
                        .parse::<Fingerprint>().expect("valid"),
                    keyring::david.fingerprint
                        .parse::<Fingerprint>().expect("valid"),
            ]));


        // Try a key that is not present.
        match backend.lookup_by_cert_fpr(
            &"0123 4567 89AB CDEF 0123  4567 89AB CDEF 0123 4567"
                .parse::<Fingerprint>().expect("valid"))
        {
            Ok(cert) => panic!("lookup_by_cert_fpr(not present) -> {}",
                               cert.fingerprint()),
            Err(err) => {
                match err.downcast_ref::<StoreError>() {
                    Some(StoreError::NotFound(_)) => (),
                    _ => panic!("lookup_by_cert(not present) -> {}", err),
                }
            }
        }

        match backend.lookup_by_cert_or_subkey(
            &"0123 4567 89AB CDEF 0123  4567 89AB CDEF 0123 4567"
                .parse::<KeyHandle>().expect("valid"))
        {
            Ok(certs) => panic!("lookup_by_cert_or_subkey(not present) -> {}",
                                certs
                                    .into_iter()
                                    .map(|c| c.fingerprint().to_string())
                                    .collect::<Vec<String>>()
                                    .join(", ")),
            Err(err) => {
                match err.downcast_ref::<StoreError>() {
                    Some(StoreError::NotFound(_)) => (),
                    _ => panic!("lookup_by_cert(not present) -> {}", err),
                }
            }
        }

        std::thread::yield_now();

        assert!(
            backend.lookup_by_cert_or_subkey(
                &"0123 4567 89AB CDEF 0123 4567 89AB CDEF"
                    .parse::<KeyHandle>().expect("valid"))
                .is_err());

        // Check puny code handling.

        // Look up the User ID using puny code.
        assert_eq!(
            backend.lookup_by_email("hans@xn--bcher-kva.tld")
                .expect("present")
                .len(),
            1);
        // And without puny code.
        assert_eq!(
            backend.lookup_by_email("hans@bücher.tld")
                .expect("present")
                .into_iter()
                .map(|c| c.fingerprint())
                .collect::<Vec<Fingerprint>>(),
            vec![ keyring::hans_puny_code.fingerprint
                  .parse::<Fingerprint>().expect("valid") ]);
        // A substring shouldn't match.
        assert_eq!(
            backend.lookup_by_email("hans@bücher.tl")
                .unwrap_or(Vec::new())
                .len(),
            0);

        // The same, but just look up by domain.
        assert_eq!(
            backend.lookup_by_email_domain("xn--bcher-kva.tld")
                .expect("present")
                .into_iter()
                .map(|c| c.fingerprint())
                .collect::<Vec<Fingerprint>>(),
            vec![ keyring::hans_puny_code.fingerprint
                  .parse::<Fingerprint>().expect("valid") ]);
        // And without puny code.
        assert_eq!(
            backend.lookup_by_email_domain("bücher.tld")
                .expect("present")
                .into_iter()
                .map(|c| c.fingerprint())
                .collect::<Vec<Fingerprint>>(),
            vec![ keyring::hans_puny_code.fingerprint
                  .parse::<Fingerprint>().expect("valid") ]);


        std::thread::yield_now();

        // Check that when looking up a subdomain, we don't get back
        // User IDs in a subdomain.
        assert_eq!(
            backend.lookup_by_email_domain("company.com")
                .expect("present")
                .into_iter()
                .map(|c| c.fingerprint())
                .collect::<Vec<Fingerprint>>(),
            vec![ keyring::una.fingerprint
                  .parse::<Fingerprint>().expect("valid") ]);
        assert_eq!(
            backend.lookup_by_email_domain("sub.company.com")
                .expect("present")
                .into_iter()
                .map(|c| c.fingerprint())
                .collect::<Vec<Fingerprint>>(),
            vec![ keyring::steve.fingerprint
                  .parse::<Fingerprint>().expect("valid") ]);


        // Check searching by domain.
        assert_eq!(
            sort_vec(backend.lookup_by_email_domain("verein.de")
                .expect("present")
                .into_iter()
                .map(|c| c.fingerprint())
                .collect::<Vec<Fingerprint>>()),
            sort_vec(
                vec![
                    keyring::alice2_adopted_alice.fingerprint
                        .parse::<Fingerprint>().expect("valid"),
                    keyring::carol.fingerprint
                        .parse::<Fingerprint>().expect("valid"),
            ]));

        // It should be case insenitive.
        assert_eq!(
            sort_vec(backend.lookup_by_email_domain("VEREIN.DE")
                .expect("present")
                .into_iter()
                .map(|c| c.fingerprint())
                .collect::<Vec<Fingerprint>>()),
            sort_vec(
                vec![
                    keyring::alice2_adopted_alice.fingerprint
                        .parse::<Fingerprint>().expect("valid"),
                    keyring::carol.fingerprint
                        .parse::<Fingerprint>().expect("valid"),
            ]));
    }

    #[test]
    fn certd() -> Result<()> {
        use std::io::Read;

        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
            })?;

        for cert in keyring::certs.iter() {
            let bytes = cert.bytes();
            let mut reader = openpgp::armor::Reader::from_bytes(
                &bytes,
                openpgp::armor::ReaderMode::VeryTolerant);
            let mut bytes = Vec::new();
            reader.read_to_end(&mut bytes)
                .expect(&format!("{}", cert.base));

            certd
                .insert_data(&bytes, false, certd_merge)
                .with_context(|| {
                    format!("{} ({})", cert.base, cert.fingerprint)
                })
                .expect("can insert");
        }
        drop (certd);

        let certd = store::certd::CertD::open(&path).expect("exists");
        test_backend(&certd);

        Ok(())
    }


    #[test]
    fn cert_store() -> Result<()> {
        use std::io::Read;

        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
            })?;

        for cert in keyring::certs.iter() {
            let bytes = cert.bytes();
            let mut reader = openpgp::armor::Reader::from_bytes(
                &bytes,
                openpgp::armor::ReaderMode::VeryTolerant);
            let mut bytes = Vec::new();
            reader.read_to_end(&mut bytes)
                .expect(&format!("{}", cert.base));

            certd
                .insert_data(&bytes, false, certd_merge)
                .with_context(|| {
                    format!("{} ({})", cert.base, cert.fingerprint)
                })
                .expect("can insert");
        }
        drop(certd);

        let cert_store = CertStore::open(&path).expect("exists");
        test_backend(&cert_store);

        Ok(())
    }

    #[test]
    fn cert_store_layered() -> Result<()> {
        use std::io::Read;

        // A certd for each certificate.
        let mut paths: Vec<tempfile::TempDir> = Vec::new();

        let mut cert_store = CertStore::empty();

        for cert in keyring::certs.iter() {
            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
                })?;

            let bytes = cert.bytes();
            let mut reader = openpgp::armor::Reader::from_bytes(
                &bytes,
                openpgp::armor::ReaderMode::VeryTolerant);
            let mut bytes = Vec::new();
            reader.read_to_end(&mut bytes)
                .expect(&format!("{}", cert.base));

            certd
                .insert_data(&bytes, false, certd_merge)
                .with_context(|| {
                    format!("{} ({})", cert.base, cert.fingerprint)
                })
                .expect("can insert");
            drop(certd);

            let certd = store::CertD::open(&path).expect("valid");
            cert_store.add_backend(Box::new(certd), AccessMode::Always);

            paths.push(path);
        }

        test_backend(&cert_store);

        Ok(())
    }

    #[test]
    fn certs() -> Result<()> {
        use std::io::Read;

        let mut bytes = Vec::new();
        for cert in keyring::certs.iter() {
            let binary = cert.bytes();
            let mut reader = openpgp::armor::Reader::from_bytes(
                &binary,
                openpgp::armor::ReaderMode::VeryTolerant);
            reader.read_to_end(&mut bytes)
                .expect(&format!("{}", cert.base));
        }

        let backend = store::Certs::from_bytes(&bytes)
            .expect("valid");
        test_backend(&backend);

        Ok(())
    }

    #[test]
    fn certd_with_prefetch() -> Result<()> {
        use std::io::Read;

        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
            })?;

        for cert in keyring::certs.iter() {
            let bytes = cert.bytes();
            let mut reader = openpgp::armor::Reader::from_bytes(
                &bytes,
                openpgp::armor::ReaderMode::VeryTolerant);
            let mut bytes = Vec::new();
            reader.read_to_end(&mut bytes)
                .expect(&format!("{}", cert.base));

            certd
                .insert_data(&bytes, false, certd_merge)
                .with_context(|| {
                    format!("{} ({})", cert.base, cert.fingerprint)
                })
                .expect("can insert");
        }
        drop (certd);

        let certd = store::CertD::open(&path).expect("exists");
        certd.prefetch_all();
        test_backend(&certd);

        Ok(())
    }

    #[test]
    fn certs_with_prefetch() -> Result<()> {
        use std::io::Read;

        let mut bytes = Vec::new();
        for cert in keyring::certs.iter() {
            let binary = cert.bytes();
            let mut reader = openpgp::armor::Reader::from_bytes(
                &binary,
                openpgp::armor::ReaderMode::VeryTolerant);
            reader.read_to_end(&mut bytes)
                .expect(&format!("{}", cert.base));
        }

        let backend = store::Certs::from_bytes(&bytes)
            .expect("valid");
        backend.prefetch_all();
        test_backend(&backend);

        Ok(())
    }

    #[test]
    fn keyrings() -> Result<()> {
        let mut cert_store = CertStore::empty();

        let mut base = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        base.push("tests");

        cert_store.add_keyrings(
            keyring::certs.iter().map(|c| {
                PathBuf::from(&base).join(c.filename)
            }))?;

        test_backend(&cert_store);

        Ok(())
    }

    #[test]
    fn certs_multithreaded() -> Result<()> {
        use std::io::Read;

        let mut bytes = Vec::new();
        for cert in keyring::certs.iter() {
            let binary = cert.bytes();
            let mut reader = openpgp::armor::Reader::from_bytes(
                &binary,
                openpgp::armor::ReaderMode::VeryTolerant);
            reader.read_to_end(&mut bytes)
                .expect(&format!("{}", cert.base));
        }

        let backend = store::Certs::from_bytes(&bytes)
            .expect("valid");

        std::thread::scope(|s| {
            let threads = (0..4usize)
                .map(|_| {
                    s.spawn(|| {
                        // Really make sure all threads start by sleeping
                        // for 10ms.
                        std::thread::sleep(std::time::Duration::new(0, 10));

                        test_backend(&backend);
                    })
                })
                .collect::<Vec<_>>();

            threads.into_iter().for_each(|h| {
                h.join().expect("joined");
            });
        });

        Ok(())
    }

    #[test]
    fn pep() -> Result<()> {
        use std::io::Read;

        let mut bytes = Vec::new();
        for cert in keyring::certs.iter() {
            let binary = cert.bytes();
            let mut reader = openpgp::armor::Reader::from_bytes(
                &binary,
                openpgp::armor::ReaderMode::VeryTolerant);
            reader.read_to_end(&mut bytes)
                .expect(&format!("{}", cert.base));
        }

        let backend = Pep::from_bytes(&bytes).expect("valid");
        backend.prefetch_all();
        test_backend(&backend);

        Ok(())
    }

    // Make sure that when we update a certificate, we are able to
    // find any new components and we are still able to find the old
    // components.
    fn test_store_update<'a, B>(backend: B) -> Result<()>
        where B: store::StoreUpdate<'a>
    {
        let p = &StandardPolicy::new();

        let signing_cert =
            Cert::from_bytes(&keyring::halfling_signing.bytes())
                .expect("valid");
        let fpr = signing_cert.fingerprint();

        // We expect a primary and two subkeys.
        assert_eq!(signing_cert.keys().count(), 3);
        let signing_vc = signing_cert.with_policy(p, None).expect("ok");
        let signing_fpr = signing_vc.keys().subkeys()
            .for_signing()
            .map(|ka| ka.fingerprint())
            .collect::<Vec<Fingerprint>>();
        assert_eq!(signing_fpr.len(), 1);
        let signing_fpr = KeyHandle::from(
            signing_fpr.into_iter().next().expect("have one"));

        let auth_fpr = signing_vc.keys().subkeys()
            .for_authentication()
            .map(|ka| ka.fingerprint())
            .collect::<Vec<Fingerprint>>();
        assert_eq!(auth_fpr.len(), 1);
        let auth_fpr = KeyHandle::from(
            auth_fpr.into_iter().next().expect("have one"));

        let encryption_cert =
            Cert::from_bytes(&keyring::halfling_encryption.bytes())
                .expect("valid");
        assert_eq!(fpr, encryption_cert.fingerprint());

        // We expect a primary and two subkeys.
        assert_eq!(encryption_cert.keys().count(), 3);
        let encryption_vc = encryption_cert.with_policy(p, None).expect("ok");
        let encryption_fpr = encryption_vc.keys().subkeys()
            .for_transport_encryption()
            .map(|ka| ka.fingerprint())
            .collect::<Vec<Fingerprint>>();
        assert_eq!(encryption_fpr.len(), 1);
        let encryption_fpr = KeyHandle::from(
            encryption_fpr.into_iter().next().expect("have one"));

        assert_ne!(signing_fpr, encryption_fpr);

        let auth2_fpr = encryption_vc.keys().subkeys()
            .for_authentication()
            .map(|ka| ka.fingerprint())
            .collect::<Vec<Fingerprint>>();
        assert_eq!(auth2_fpr.len(), 1);
        let auth2_fpr = KeyHandle::from(
            auth2_fpr.into_iter().next().expect("have one"));

        assert_eq!(auth_fpr, auth2_fpr);

        let merged_cert = signing_cert.clone()
            .merge_public(encryption_cert.clone()).expect("ok");

        let check = |backend: &B, have_enc: bool, cert: &Cert| {
            let r = backend.lookup_by_cert(&KeyHandle::from(fpr.clone())).unwrap();
            assert_eq!(r.len(), 1);
            assert_eq!(r[0].to_cert().expect("ok"), cert);

            let r = backend.lookup_by_cert_or_subkey(&signing_fpr).unwrap();
            assert_eq!(r.len(), 1);
            assert_eq!(r[0].to_cert().expect("ok"), cert);

            let r = backend.lookup_by_cert_or_subkey(&auth_fpr).unwrap();
            assert_eq!(r.len(), 1);
            assert_eq!(r[0].to_cert().expect("ok"), cert);

            if have_enc {
                let r = backend.lookup_by_cert_or_subkey(&encryption_fpr).unwrap();
                assert_eq!(r.len(), 1);
                assert_eq!(r[0].to_cert().expect("ok"), cert);
            } else {
                assert!(backend.lookup_by_cert_or_subkey(&encryption_fpr).is_err());
            }

            let r = backend.lookup_by_userid(
                &UserID::from("<regis@pup.com>")).unwrap();
            assert_eq!(r.len(), 1);
            assert_eq!(r[0].to_cert().expect("ok"), cert);

            let r = backend.lookup_by_userid(
                &UserID::from("Halfling <signing@halfling.org>")).unwrap();
            assert_eq!(r.len(), 1);
            assert_eq!(r[0].to_cert().expect("ok"), cert);

            if have_enc {
                let r = backend.lookup_by_userid(
                    &UserID::from("Halfling <encryption@halfling.org>"))
                    .unwrap();
                assert_eq!(r.len(), 1);
                assert_eq!(r[0].to_cert().expect("ok"), cert);
            } else {
                assert!(backend.lookup_by_cert_or_subkey(&encryption_fpr).is_err());
            }
        };

        // Insert the signing certificate.
        backend.update(Arc::new(LazyCert::from(signing_cert.clone())))
            .expect("ok");
        check(&backend, false, &signing_cert);

        backend.update(Arc::new(LazyCert::from(encryption_cert.clone())))
            .expect("ok");
        check(&backend, true, &merged_cert);

        backend.update(Arc::new(LazyCert::from(signing_cert.clone())))
            .expect("ok");
        check(&backend, true, &merged_cert);

        Ok(())
    }

    // Test StoreUpdate::update for CertStore.
    #[test]
    fn test_store_update_cert_store() -> Result<()> {
        let path = tempfile::tempdir()?;
        let cert_store = CertStore::open(&path).expect("exists");
        test_store_update(cert_store)
    }

    /// Test StoreUpdate::update for CertD.
    #[test]
    fn test_store_update_certd() -> Result<()> {
        let path = tempfile::tempdir()?;
        let certs = store::CertD::open(&path)?;
        test_store_update(&certs)?;

        // We're the only user of the cert-d.  Therefore, we should be
        // able to keep the persistent index and the in-memory index
        // in sync with the cert-d without having to do any hard
        // reloads.
        assert_eq!(
            certs.load_stats.in_memory_loads(), 0);
        assert_eq!(
            certs.load_stats.persistent_index_scans(), 1);
        Ok(())
    }

    // Test StoreUpdate::update for Certs.
    #[test]
    fn test_store_update_certs() -> Result<()> {
        let certs = Certs::empty();
        test_store_update(certs)
    }

    // Test StoreUpdate::update for Pep.
    #[test]
    fn test_store_update_pep() -> Result<()> {
        let certs = Pep::empty()?;
        test_store_update(certs)
    }

    #[test]
    fn test_store_multithreaded_update_cert_store() -> Result<()> {
        let path = tempfile::tempdir()?;
        let backend = CertStore::open(&path)?;
        test_store_multithreaded_update(backend)
    }

    #[test]
    fn test_store_multithreaded_update_certd() -> Result<()> {
        let path = tempfile::tempdir()?;
        let backend = store::CertD::open(&path)?;
        test_store_multithreaded_update(backend)
    }

    #[test]
    fn test_store_multithreaded_update_certs() -> Result<()> {
        let backend = store::Certs::empty();
        test_store_multithreaded_update(backend)
    }

    #[test]
    fn test_store_multithreaded_update_pep() -> Result<()> {
        let backend = Pep::empty()?;
        test_store_multithreaded_update(backend)
    }

    fn test_store_multithreaded_update<'a, B>(backend: B) -> Result<()>
        where B: store::StoreUpdate<'a> + Sync
    {
        let mut certs = Vec::new();
        for cert in keyring::certs.iter() {
            let cert = Cert::from_bytes(&cert.bytes()).expect("valid");
            certs.push(cert);
        }

        let mut fprs: Vec<Fingerprint>
            = certs.iter().map(|cert| cert.fingerprint()).collect();
        fprs.sort();
        fprs.dedup();

        std::thread::scope(|s| {
            let backend = &backend;
            let threads = certs.into_iter()
                .map(|cert| {
                    s.spawn(move || {
                        // Really make sure all threads start by sleeping
                        // for 10ms.
                        std::thread::sleep(std::time::Duration::new(0, 10));

                        let kh = cert.key_handle();
                        backend.update(Arc::new(LazyCert::from(cert)))
                            .expect("ok");
                        assert!(backend.lookup_by_cert(&kh).is_ok());
                        assert!(backend.lookup_by_cert_or_subkey(&kh).is_ok());
                    })
                })
                .collect::<Vec<_>>();

            threads.into_iter().for_each(|h| {
                h.join().expect("joined");
            });
        });

        assert_eq!(backend.certs().count(), fprs.len());

        Ok(())
    }

}