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
use std::{
    convert::TryInto,
    env, fs,
    io::{self, Read, Write},
    path::{Path, PathBuf},
};

use fd_lock::RwLock;
use tempfile::NamedTempFile;

use crate::SPECIAL_NAMES;
use crate::{pgp, InternalError};
use crate::{Data, Error, Result, Tag};

const PATH_PREFIX_LEN: usize = 2;

/// A certificate store.
///
/// This is a handle to an on-disk certificate store that can be used
/// to lookup and insert certificates.
#[derive(Debug)]
pub struct CertD {
    base: PathBuf,
}

impl CertD {
    /// Opens the default certificate store.
    ///
    /// If not explicitly requested otherwise, an application SHOULD
    /// use the [default store].  To use a store with a different
    /// location, use [`CertD::with_base_dir`].
    ///
    /// [default store]: https://www.ietf.org/archive/id/draft-nwjw-openpgp-cert-d-00.html#name-default-stores-location
    pub fn new() -> Result<CertD> {
        CertD::with_base_dir(
            env::var_os("PGP_CERT_D")
                .map(Into::into)
                .unwrap_or_else(CertD::default_location),
        )
    }

    fn default_location() -> PathBuf {
        // XXX: Other platforms?
        dirs::data_dir()
            .expect("Unsupported platform")
            .join("pgp.cert.d")
    }

    /// Opens a store with an explicit location.
    ///
    /// Note: If not explicitly requested otherwise, an application
    /// SHOULD use the [default store] using [`CertD::new`].
    ///
    /// [default store]: https://www.ietf.org/archive/id/draft-nwjw-openpgp-cert-d-00.html#name-default-stores-location
    pub fn with_base_dir<P: AsRef<Path>>(base: P) -> Result<CertD> {
        Ok(CertD {
            base: base.as_ref().into(),
        })
    }

    /// Get the this Certd's base path.
    pub fn get_base_dir(&self) -> &Path {
        &self.base
    }

    /// Turns a fingerprint into a path in the store, according to cert-d
    /// specification.
    fn get_path_by_fp(&self, fingerprint: &str) -> Result<PathBuf> {
        if fingerprint.len() != 40 {
            return Err(Error::BadName);
        }
        if fingerprint.chars().any(|c| !c.is_ascii_hexdigit()) {
            return Err(Error::BadName);
        }
        let fingerprint = fingerprint.to_ascii_lowercase();
        Ok(self.base.join(&fingerprint[..2]).join(&fingerprint[2..]))
    }

    /// Turns a path in the store into a fingerprint, if it conforms to the cert-d
    /// specification.
    fn get_fp_by_path(
        &self,
        path: &Path,
    ) -> std::result::Result<String, InternalError> {
        let path = if path.is_absolute() {
            path.strip_prefix(&self.base)
                .map_err(|_| InternalError::PathNotInStore)?
        } else {
            path
        };
        if !self.base.join(path).is_file() {
            return Err(InternalError::BadFingerprintPath);
        }
        if path.components().count() != 2 {
            return Err(InternalError::BadFingerprintPath);
        }
        let components =
            path.components().map(|c| c.as_os_str()).collect::<Vec<_>>();
        if components.iter().any(|c| !c.is_ascii()) {
            return Err(InternalError::BadFingerprintPath);
        }
        let head = components[0].to_string_lossy();
        if head.len() != PATH_PREFIX_LEN {
            return Err(InternalError::BadFingerprintPath);
        }
        let tail = components[1].to_string_lossy();
        if tail.len() != pgp::FP_LEN_CHARS_V4 - PATH_PREFIX_LEN
            && tail.len() != pgp::FP_LEN_CHARS_V5 - PATH_PREFIX_LEN
        {
            return Err(InternalError::BadFingerprintPath);
        }
        Ok(head.to_string() + &tail)
    }

    /// Turns a special name into a path in the store.
    fn get_path_by_special(&self, special: &str) -> Result<PathBuf> {
        let special = special.to_lowercase();
        if SPECIAL_NAMES.binary_search(&special.as_ref()).is_ok() {
            Ok(self.base.join(special))
        } else {
            Err(Error::BadName)
        }
    }

    /// Looks up a certificate in the store by an name, i.e. a fingerprint
    /// or a special name.
    ///
    /// If the certificate exists, this function returns `Ok(Some((tag,
    /// cert)))`.  See [`Tag`] for how this can be used to cache lookups.
    ///
    /// If the certificate does not exist, this function returns `Ok(None)`.
    ///
    /// If an I/O error occurs, or the name was invalid, this function returns
    /// an [`Error`].
    pub fn get(&self, name: &str) -> Result<Option<(Tag, Data)>> {
        let path = self.get_path(name)?;
        match fs::File::open(path) {
            Ok(mut f) => {
                let tag = f.metadata()?.try_into()?;
                let mut buf = Vec::new();
                f.read_to_end(&mut buf)?;
                Ok(Some((tag, buf.into())))
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(e.into()),
        }
    }

    /// Looks up a certificate in the store by an name, i.e. a fingerprint
    /// or a special name, with the [`Tag`] from the previous lookup.
    ///
    /// If the certificate has changed, this function returns `Ok(Some((cert,
    /// tag)))`.  The tag can be used in subsequent calls to this function.
    ///
    /// If the certificate has not changed or does not exist, this function
    /// returns `Ok(None)`.
    ///
    /// If an I/O error occurs, or the name was invalid, this function returns
    /// an [`Error`].
    pub fn get_if_changed(
        &self,
        since: Tag,
        name: &str,
    ) -> Result<Option<(Tag, Data)>> {
        let path = self.get_path(name)?;
        match fs::File::open(path) {
            Ok(mut f) => {
                let tag = f.metadata()?.try_into()?;
                if since == tag {
                    Ok(None) // Not modified.
                } else {
                    let mut buf = Vec::new();
                    f.read_to_end(&mut buf)?;
                    Ok(Some((tag, buf.into())))
                }
            }
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(e.into()),
        }
    }

    /// Get the path to a certificate.
    pub fn get_path(&self, name: &str) -> Result<PathBuf> {
        // Try to convert the name to a path, first as a fingerprint and
        // if that fails as a special name.
        // If the errors get more insightful than just Error::BadName, prefer
        // returning the one from fp_to_path.
        self.get_path_by_fp(name)
            .or_else(|_| self.get_path_by_special(name))
    }

    /// Inserts or updates a cert.
    ///
    /// Requires the fingerprint and a callback function.  The callback is
    /// invoked with an `Option<Data>` of the existing cert data (if any),
    /// and is expected to merge the two copies of the certificate together.
    /// The returned `Data` is written to the store.
    /// (Note: The function may decide to omit (parts of) the existing data,
    /// but this should be done with great care as not to lose any vital
    /// information.)
    ///
    /// Acquires lock to the store, blocking the current thread until it's able
    /// to do so.
    ///
    /// The insertion method returns the merged certificate data and the tag.
    /// See [`Tag`] for how this can be used to cache lookups.
    pub fn insert<M>(&self, data: Data, merge: M) -> Result<(Tag, Data)>
    where
        M: FnOnce(Data, Option<Data>) -> Result<Data>,
    {
        let blocking = true;
        let name = pgp::fingerprint(data.as_ref())?;
        self.insert_impl(&name, data, merge, blocking)
    }

    /// Inserts or updates a cert, non-blocking variant.
    ///
    /// Requires the fingerprint and a callback function.  The callback is
    /// invoked with an `Option<Data>` of the existing cert data (if any),
    /// and is expected to merge the two copies of the certificate together.
    /// The returned `Data` is written to the store.
    /// (Note: The function may decide to omit (parts of) the existing data,
    /// but this should be done with great care as not to lose any vital
    /// information.)
    ///
    /// Attempts to lock the store. Does not block, instead returns an
    /// [`Error::IoError`] with an [`std::io::ErrorKind::WouldBlock`]
    /// if the lock cannot be acquired.
    ///
    /// The insertion method returns the merged certificate data and the tag.
    /// See [`Tag`] for how this can be used to cache lookups.
    pub fn try_insert<M>(&self, data: Data, merge: M) -> Result<(Tag, Data)>
    where
        M: FnOnce(Data, Option<Data>) -> Result<Data>,
    {
        let blocking = false;
        let name = pgp::fingerprint(data.as_ref())?;
        self.insert_impl(&name, data, merge, blocking)
    }

    /// Inserts or updates the cert or key stored under a special name.
    ///
    /// Requires the special name, the cert or key in binary format and a
    /// callback function.  The callback is invoked with an `Option<Data>` of
    /// the existing data (if any), and is expected to merge the two copies
    /// together.  The returned `Data` is written to the
    /// store under the special name.  (Note: The function may decide to omit
    /// (parts of) the existing data, but this should be done with great care as
    /// not to lose any vital information.)
    ///
    /// Acquires lock to the store, blocking the current thread until it's able
    /// to do so.
    ///
    /// The insertion method returns the merged data and the tag.
    /// See [`Tag`] for how this can be used to cache lookups.
    pub fn insert_special<M>(
        &self,
        special_name: &str,
        data: Data,
        merge: M,
    ) -> Result<(Tag, Data)>
    where
        M: FnOnce(Data, Option<Data>) -> Result<Data>,
    {
        let blocking = true;
        pgp::plausible_tsk_or_tpk(&data)?;
        self.insert_impl(special_name, data, merge, blocking)
    }

    /// Inserts or updates the cert or key stored under a special
    /// name, non-blocking variant.
    ///
    /// Requires the special name, the cert or key in binary format and a
    /// callback function.  The callback is invoked with an `Option<Data>` of
    /// the existing data (if any), and is expected to merge the two copies
    /// together.  The returned `Data` is written to the
    /// store under the special name.  (Note: The function may decide to omit
    /// (parts of) the existing data, but this should be done with great care as
    /// not to lose any vital information.)
    ///
    /// Attempts to lock the store. Does not block, instead returns an
    /// [`Error::IoError`] with an [`std::io::ErrorKind::WouldBlock`]
    /// if the lock cannot be acquired.
    ///
    /// The insertion method returns the merged data and the tag.
    /// See [`Tag`] for how this can be used to cache lookups.
    pub fn try_insert_special<M>(
        &self,
        special_name: &str,
        data: Data,
        merge: M,
    ) -> Result<(Tag, Data)>
    where
        M: FnOnce(Data, Option<Data>) -> Result<Data>,
    {
        let blocking = false;
        pgp::plausible_tsk_or_tpk(&data)?;
        self.insert_impl(special_name, data, merge, blocking)
    }

    fn insert_impl<M>(
        &self,
        name: &str,
        data: Data,
        merge: M,
        blocking: bool,
    ) -> Result<(Tag, Data)>
    where
        M: FnOnce(Data, Option<Data>) -> Result<Data>,
    {
        let target_path = self.get_path(name)?;
        // Make sure the directory exists.
        fs::create_dir_all(target_path.parent().expect("at least one leg"))?;

        let mut lf = RwLock::new(self.idempotent_create_lockfile()?);
        // Lock exclusively
        let lock = if blocking {
            lf.write()?
        } else {
            lf.try_write()?
        };

        let old_cert = self.get(name)?.map(|(_, cert)| cert);
        let new_cert = merge(data, old_cert)?;

        {
            let mut tmp = NamedTempFile::new_in(&self.base)?;
            tmp.write_all(new_cert.as_ref())?;
            tmp.persist(&target_path).map_err(|e| e.error)?;
        }

        let tag = fs::File::open(&target_path)?.metadata()?.try_into()?;

        drop(lock);

        Ok((tag, new_cert))
    }

    /// Iterates over the certs in the store returning their fingerprints.
    pub fn iter_fingerprints(&self) -> Result<impl Iterator<Item = String> + '_> {
        Ok(fs::read_dir(&self.base)?
            .filter_map(|toplevel| toplevel.ok())
            .filter(|toplevel| {
                toplevel.file_type().map(|t| t.is_dir()).unwrap_or(false)
                    && toplevel.file_name().len() == 2
            })
            .flat_map(|toplevel| fs::read_dir(toplevel.path()))
            .flatten()
            .filter_map(|entry| entry.ok())
            .map(move |entry| self.get_fp_by_path(&entry.path()).unwrap()))
    }

    /// Iterates over the certs in the store.
    ///
    /// Iterates over the certs in the store returning fingerprints,
    /// tags, and the data for each cert.
    pub fn iter(
        &self,
    ) -> Result<impl Iterator<Item = (String, Tag, Data)> + '_> {
        Ok(self.iter_fingerprints()?.filter_map(move |fp| {
            self.get(&fp)
                .ok()
                .flatten()
                .map(|(tag, data)| (fp, tag, data))
        }))
    }

    fn idempotent_create_lockfile(&self) -> Result<std::fs::File> {
        let lock_path = self.base.join("writelock");
        // Open the lockfile for writing, and create it if it does not exist yet.
        std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .open(lock_path)
            .map_err(Into::into)
    }
}

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

    use crate::TRUST_ROOT;

    fn test_base() -> assert_fs::TempDir {
        let base = assert_fs::TempDir::new().unwrap();
        match std::env::var_os("CERTD_TEST_PERSIST") {
            Some(_) => {
                eprintln!("Test base dir: {}", &base.path().to_string_lossy());
                base.into_persistent()
            }
            None => base,
        }
    }

    struct Testdata<'a> {
        data: &'a [u8],
        fingerprint: &'a str,
    }

    impl Testdata<'_> {
        fn path(&self) -> String {
            [&self.fingerprint[..2], &self.fingerprint[2..]].join("/")
        }

        fn add_to_certd(&self, base: &assert_fs::TempDir) {
            base.child(self.path()).write_binary(self.data).unwrap();
        }
    }

    static ALICE: Testdata = Testdata {
        fingerprint: "eb85bb5fa33a75e15e944e63f231550c4f47e38e",
        data: include_bytes!("../../testdata/alice.asc"),
    };

    static BOB: Testdata = Testdata {
        fingerprint: "d1a66e1a23b182c9980f788cfbfcc82a015e7330",
        data: include_bytes!("../../testdata/bob.asc"),
    };

    static TESTY: Testdata = Testdata {
        fingerprint: "39d100ab67d5bd8c04010205fb3751f1587daef1",
        data: include_bytes!("../../testdata/testy-new.pgp"),
    };

    fn setup_testdir(
        testdata: &[&Testdata],
    ) -> Result<(assert_fs::TempDir, CertD)> {
        let base = test_base();
        for t in testdata.iter() {
            t.add_to_certd(&base);
        }

        let trust_root_data = include_bytes!("../../testdata/sender.pgp");
        base.child("trust-root")
            .write_binary(trust_root_data)
            .unwrap();

        let certd = CertD::with_base_dir(&base)?;
        Ok((base, certd))
    }

    #[test]
    fn get_fp() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let data = include_bytes!("../../testdata/testy-new.pgp");

        let base = test_base();
        base.child("39/d100ab67d5bd8c04010205fb3751f1587daef1")
            .write_binary(data)
            .unwrap();

        let certd = CertD::with_base_dir(&base)?;

        let (tag, cert) = certd
            .get("39d100ab67d5bd8c04010205fb3751f1587daef1")?
            .unwrap();
        assert_eq!(cert.as_ref(), data);

        assert!(certd
            .get_if_changed(tag, "39d100ab67d5bd8c04010205fb3751f1587daef1")?
            .is_none());

        base.close().unwrap();
        Ok(())
    }

    #[test]
    fn get_special() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let data = include_bytes!("../../testdata/sender.pgp");

        let base = test_base();
        base.child("trust-root").write_binary(data).unwrap();

        let certd = CertD::with_base_dir(&base)?;

        let (tag, cert) = certd.get(TRUST_ROOT)?.unwrap();
        assert_eq!(cert.as_ref(), data);

        assert!(certd.get_if_changed(tag, TRUST_ROOT)?.is_none());

        base.close().unwrap();
        Ok(())
    }

    #[test]
    fn get_not_found() -> Result<()> {
        let base = test_base();
        let certd = CertD::with_base_dir(&base)?;
        let result = certd.get("39d100ab67d5bd8c04010205fb3751f1587daef1");
        assert!(matches!(result, Ok(None)));
        Ok(())
    }

    #[test]
    fn insert_locked() -> Result<()> {
        let data = include_bytes!("../../testdata/testy-new.pgp");
        let base = test_base();

        let file = base.child("39/d100ab67d5bd8c04010205fb3751f1587daef1");
        file.assert(predicate::path::missing());

        let certd = CertD::with_base_dir(&base)?;
        let f = |new: Data, old: Option<Data>| {
            assert!(old.is_none());
            Ok(new)
        };

        // Lock the lockfile before we try to insert
        let mut lf = RwLock::new(certd.idempotent_create_lockfile()?);
        // Lock exclusively
        let _lock = lf.write()?;

        let result = certd.try_insert(data.to_vec().into_boxed_slice(), &f);

        match result.unwrap_err() {
            Error::IoError(e) if e.kind() == io::ErrorKind::WouldBlock => {
                Ok(())
            }
            e => Err(e),
        }
    }

    #[test]
    fn insert_special_locked() -> Result<()> {
        let data = include_bytes!("../../testdata/sender.pgp");
        let base = test_base();

        let file = base.child("trust-root");
        file.assert(predicate::path::missing());

        let certd = CertD::with_base_dir(&base)?;
        let f = |new: Data, old: Option<Data>| {
            assert!(old.is_none());
            Ok(new)
        };

        // Lock the lockfile before we try to insert
        let mut lock = RwLock::new(certd.idempotent_create_lockfile()?);
        // Lock exclusively
        let _lock = lock.write()?;

        let result = certd.try_insert_special(
            TRUST_ROOT,
            data.to_vec().into_boxed_slice(),
            &f,
        );

        match result.unwrap_err() {
            Error::IoError(e) if e.kind() == io::ErrorKind::WouldBlock => {
                Ok(())
            }
            e => Err(e),
        }
    }

    #[test]
    fn insert_new() -> Result<()> {
        let data = include_bytes!("../../testdata/testy-new.pgp");
        let base = test_base();

        let file = base.child("39/d100ab67d5bd8c04010205fb3751f1587daef1");
        file.assert(predicate::path::missing());

        let certd = CertD::with_base_dir(&base)?;

        let f = |new: Data, old: Option<Data>| {
            assert!(old.is_none());
            Ok(new)
        };

        let (_, inserted) =
            certd.insert(data.to_vec().into_boxed_slice(), &f)?;
        file.assert(data.as_ref());
        assert_eq!(inserted, data.to_vec().into_boxed_slice());

        Ok(())
    }

    #[test]
    fn insert_special_new() -> Result<()> {
        let data = include_bytes!("../../testdata/sender.pgp");
        let base = test_base();

        let file = base.child("trust-root");
        file.assert(predicate::path::missing());

        let certd = CertD::with_base_dir(&base)?;

        let f = |new: Data, old: Option<Data>| {
            assert!(old.is_none());
            Ok(new)
        };

        let (_, inserted) = certd.insert_special(
            "trust-root",
            data.to_vec().into_boxed_slice(),
            &f,
        )?;
        file.assert(data.as_ref());
        assert_eq!(inserted, data.to_vec().into_boxed_slice());

        Ok(())
    }

    #[test]
    fn insert_update() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let data = include_bytes!("../../testdata/testy-new.pgp");
        let base = test_base();

        let file = base.child("39/d100ab67d5bd8c04010205fb3751f1587daef1");
        file.touch().unwrap();
        file.assert(predicate::str::is_empty());

        let certd = CertD::with_base_dir(&base)?;

        let f = |new: Data, old: Option<Data>| {
            assert!(old.is_some());
            Ok(new)
        };

        let (_, inserted) =
            certd.insert(data.to_vec().into_boxed_slice(), &f)?;
        file.assert(data.as_ref());
        assert_eq!(inserted, data.to_vec().into_boxed_slice());

        Ok(())
    }

    #[test]
    fn insert_special_update(
    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
        let data = include_bytes!("../../testdata/sender.pgp");
        let base = test_base();

        let file = base.child("trust-root");
        file.touch().unwrap();
        file.assert(predicate::str::is_empty());

        let certd = CertD::with_base_dir(&base)?;

        let f = |new: Data, old: Option<Data>| {
            assert!(old.is_some());
            Ok(new)
        };

        let (_, inserted) = certd.insert_special(
            TRUST_ROOT,
            data.to_vec().into_boxed_slice(),
            &f,
        )?;
        file.assert(data.as_ref());
        assert_eq!(inserted, data.to_vec().into_boxed_slice());

        Ok(())
    }

    #[test]
    fn insert_get() -> std::result::Result<(), Box<dyn std::error::Error>> {
        let data = include_bytes!("../../testdata/testy-new.pgp");
        let base = test_base();

        let certd = CertD::with_base_dir(&base)?;

        let f = |new: Data, old: Option<Data>| {
            assert!(old.is_none());
            Ok(new)
        };

        certd.insert(data.to_vec().into_boxed_slice(), &f)?;
        let (_, cert) = certd
            .get("39d100ab67d5bd8c04010205fb3751f1587daef1")?
            .unwrap();
        assert_eq!(cert.as_ref(), data);

        Ok(())
    }

    #[test]
    fn get_path_by_fp() -> Result<()> {
        let base = test_base();
        let certd = CertD::with_base_dir(&base)?;

        let expected = base
            .path()
            .join("39")
            .join("d100ab67d5bd8c04010205fb3751f1587daef1");

        let fingerprint = "39d100ab67d5bd8c04010205fb3751f1587daef1";
        assert_eq!(certd.get_path_by_fp(fingerprint)?, expected);

        let fingerprint = "39D100AB67D5BD8C04010205FB3751F1587DAEF1";
        assert_eq!(certd.get_path_by_fp(fingerprint)?, expected);

        let fingerprint = "39D100ab67D5bD8C04010205FB3751f1587DAeF1";
        assert_eq!(certd.get_path_by_fp(fingerprint)?, expected);

        Ok(())
    }

    #[test]
    fn get_path_by_fp_negative() -> Result<()> {
        let base = test_base();
        let certd = CertD::with_base_dir(&base)?;

        // empty
        let fingerprint = "";
        let result = certd.get_path_by_fp(fingerprint);
        assert!(matches!(result.unwrap_err(), Error::BadName));

        // too short
        let fingerprint = "39d100ab67d5bd8c04010205fb3751f1587daef";
        let result = certd.get_path_by_fp(fingerprint);
        assert!(matches!(result.unwrap_err(), Error::BadName));

        // not ascii hex
        let fingerprint = "peter";
        let result = certd.get_path_by_fp(fingerprint);
        assert!(matches!(result.unwrap_err(), Error::BadName));
        Ok(())
    }

    #[test]
    fn get_path_by_special() -> Result<()> {
        let base = test_base();
        let certd = CertD::with_base_dir(&base)?;

        let expected = base.path().join(TRUST_ROOT);

        let name = "trust-root";
        assert_eq!(certd.get_path_by_special(name)?, expected);

        let name = "TRUST-ROOT";
        assert_eq!(certd.get_path_by_special(name)?, expected);

        let name = "TrUsT-RooT";
        assert_eq!(certd.get_path_by_special(name)?, expected);

        Ok(())
    }

    #[test]
    fn get_path_by_special_negative() -> Result<()> {
        let base = test_base();
        let certd = CertD::with_base_dir(&base)?;

        // empty
        let name = "";
        let result = certd.get_path_by_special(name);
        assert!(matches!(result.unwrap_err(), Error::BadName));

        // unknown
        let name = "mySpecialName";
        let result = certd.get_path_by_special(name);
        assert!(matches!(result.unwrap_err(), Error::BadName));
        Ok(())
    }

    #[test]
    fn iter_fingerprints() -> Result<()> {
        use std::collections::HashSet;

        let (_base, certd) = setup_testdir(&[&ALICE, &BOB, &TESTY])?;

        let iter_fp = certd.iter_fingerprints()?;
        let fps = iter_fp.collect::<HashSet<_>>();
        let expected: HashSet<_> =
            [ALICE.fingerprint, BOB.fingerprint, TESTY.fingerprint]
                .iter()
                .map(|&s| s.to_owned())
                .collect();
        assert_eq!(expected, fps);

        Ok(())
    }

    #[test]
    fn iter() -> Result<()> {
        use std::collections::HashSet;

        let (_base, certd) = setup_testdir(&[&ALICE, &BOB, &TESTY])?;

        let mut expected: HashSet<_> = [&ALICE, &BOB, &TESTY]
            .iter()
            .map(|&s| {
                (
                    s.fingerprint.to_owned(),
                    certd.get(s.fingerprint).unwrap().unwrap().0,
                    s.data.to_vec().into_boxed_slice(),
                )
            })
            .collect();

        for item in certd.iter()? {
            assert!(expected.contains(&item));
            expected.remove(&item);
        }
        assert!(expected.is_empty());

        Ok(())
    }

    #[test]
    fn base_path() -> Result<()> {
        let base = assert_fs::TempDir::new().unwrap();
        let certd = CertD::with_base_dir(&base)?;

        assert_eq!(certd.get_base_dir(), base.path());
        Ok(())
    }
}