sett 0.4.0

Rust port of sett (data compression, encryption and transfer tool).
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
//! OpenPGP certificate store

use super::error;
use std::{
    borrow::Cow,
    path::{Path, PathBuf},
};

use sequoia_cert_store::{Store as _, StoreUpdate as _};

use super::cert::{Cert, Fingerprint};

const LOCAL_TRUST_ROOT_USER_ID: &[u8] = b"Local Trust Root";

#[derive(Clone, Debug, Default)]
/// Options required to instantiate a new certificate store.
pub struct CertStoreOpts<'a> {
    /// Path of the store on disk.
    ///
    /// If `None`, the default, platform-specific, location is used.
    pub location: Option<&'a Path>,
    /// Open the store in read-only mode.
    pub read_only: bool,
}

/// Store for OpenPGP certificates with public material only, i.e. public keys
/// and user IDs.
pub struct CertStore<'store> {
    /// Sequoia store for OpenPGP certificates with public material only.
    inner: sequoia_cert_store::CertStore<'store>,
    // TODO: this field can be replaced by a method that return the path
    // of the CertD certificate store after the next release of pgp-cert-d.
    path: PathBuf,
}

impl<'store> CertStore<'store> {
    /// Environment variable to override the default cert store location.
    const ENV: &'static str = "PGP_CERT_D";

    /// Default directory for the public certificate store.
    ///
    /// <https://www.ietf.org/archive/id/draft-nwjw-openpgp-cert-d-00.html>
    const DEFAULT_DIR: &'static str = "pgp.cert.d";

    /// Returns the default path for the certificate store.
    pub fn default_location() -> Result<std::path::PathBuf, error::Error> {
        Ok(dirs::data_dir()
            .ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::Unsupported,
                    "Unsupported platform: 'data dir' is not defined.",
                )
            })?
            .join(Self::DEFAULT_DIR))
    }

    /// Open a certificate store from disk.
    ///
    /// If no path is provided, the certificate store will be created at the
    /// default, platform-specific, location.
    pub fn open(opts: &CertStoreOpts<'_>) -> Result<CertStore<'store>, error::Error> {
        let store_path = if let Some(p) = opts.location {
            p.into()
        } else if let Some(p) = std::env::var_os(Self::ENV) {
            p.into()
        } else {
            Self::default_location()?
        };
        if !store_path.is_dir() {
            std::fs::create_dir_all(&store_path)?;
        }
        let store = if opts.read_only {
            sequoia_cert_store::CertStore::open_readonly(&store_path)
                .map_err(error::PgpError::from)?
        } else {
            sequoia_cert_store::CertStore::open(&store_path).map_err(error::PgpError::from)?
        };
        Ok(Self {
            inner: store,
            path: store_path,
        })
    }

    /// Opens an in-memory certificate store.
    pub fn open_ephemeral() -> CertStore<'store> {
        Self {
            inner: sequoia_cert_store::CertStore::empty(),
            path: PathBuf::new(),
        }
    }

    /// Returns OpenPGP certificate file location on disk.
    ///
    /// * The certificate is specified via the fingerprint of the primary key.
    /// * If the certificate is not present in the store, an error is returned.
    ///
    /// Certificates are stored as files under the path:
    ///  * `/path/of/store/<first 2 chars of fingerprint>/<remainder of fingerprint>`.
    ///  * Example: `~/.local/share/pgp.cert.d/1e/a0292ecbf2457cadae20e2b94fa6a56d9fa1fb`.
    pub fn get_cert_path(&self, fingerprint: &Fingerprint) -> Result<PathBuf, error::PgpError> {
        // Make sure the certificate is present in the store.
        if let Err(err_msg) = self.get_cert_by_fingerprint(fingerprint) {
            return Err(error::PgpError::Error(format!(
                "Cannot get key path: {err_msg}"
            )));
        }

        // Return path of certificate.
        let fingerprint_as_string = fingerprint.0.to_hex().to_ascii_lowercase();
        Ok(self
            .path
            .join(&fingerprint_as_string[..2])
            .join(&fingerprint_as_string[2..]))
    }

    /// Add a public certificate (i.e. with no secret material) to the public
    /// store. If a certificate with secret material is passed, the secret
    /// material is stripped away and only the public part of the certificate
    /// is stored.
    /// If a certificate with the same fingerprint is already present, it gets
    /// updated with the new info (if any) present in the certificate being
    /// added.
    fn add_pub_cert(&mut self, cert: &Cert) -> Result<Cert, error::PgpError> {
        let imported_cert = self
            .inner
            .update_by(
                std::sync::Arc::new(sequoia_cert_store::LazyCert::from_cert(
                    cert.0.clone().strip_secret_key_material(),
                )),
                &(),
            )
            .map_err(error::PgpError::from)?
            .to_cert()
            .map_err(error::PgpError::from)?
            .clone();

        // Make sure any secret material has been stripped from the certificate.
        assert!(!imported_cert.is_tsk());
        Ok(Cert(imported_cert))
    }

    /// Add an OpenPGP certificate to a local store.
    ///
    /// Only the public part of the certificate is stored in the store.
    /// If a certificate with the same fingerprint is already present, it
    ///   gets updated with the new material (if any) present in the
    ///   certificate being added.
    pub fn import(&mut self, cert: &Cert) -> Result<Cert, error::PgpError> {
        cert.validate(&Default::default())?;
        self.add_pub_cert(cert)
    }

    /// Retrieves an OpenPGP certificate by its fingerprint.
    ///
    /// If no certificates matching the specified `fingerprint` is found,
    /// an error is returned.
    ///
    /// # Arguments
    ///
    /// * `fingerprint`: `Fingerprint` of the certificate (or any of its
    ///   subkeys) to retrieve.
    pub(crate) fn get_cert_by_fingerprint(
        &self,
        fingerprint: &Fingerprint,
    ) -> Result<Cert, error::PgpError> {
        let key_handle = sequoia_openpgp::KeyHandle::Fingerprint(fingerprint.0.clone());
        if let Ok(certs) = self.inner.lookup_by_cert_or_subkey(&key_handle) {
            if certs.len() == 1 {
                return Ok(Cert(
                    certs[0].to_cert().map_err(error::PgpError::from)?.clone(),
                ));
            }
            if certs.len() > 1 {
                return Err(error::PgpError::Error(format!(
                    "Multiple keys with the same fingerprint \
                    '{fingerprint}' were found."
                )));
            }
        }
        Err(error::PgpError::Error(format!(
            "No key matching the specified fingerprint \
                '{fingerprint}' was found."
        )))
    }

    /// Retrieve an OpenPGP certificate from the store by email.
    ///
    /// Search is case-insensitive.
    ///
    /// Returns an error if no certificate matching the specified email is
    /// found.
    fn get_cert_by_email(&self, email: &str) -> Result<Vec<Cert>, error::PgpError> {
        // This implementation is the same as
        // sequoia_cert_store::Store::lookup_by_email, but case-insensitive.
        let email = sequoia_cert_store::email_to_userid(email)
            .map_err(error::PgpError::from)?
            .email_normalized()
            .map_err(error::PgpError::from)?
            .expect("have one");
        self.inner
            .select_userid(
                sequoia_cert_store::store::UserIDQueryParams::new()
                    .set_email(true)
                    .set_anchor_start(true)
                    .set_anchor_end(true)
                    .set_ignore_case(true),
                &email,
            )
            .map_err(|_| {
                error::PgpError::Error(format!(
                    "No public key matching the email '{email}' was found"
                ))
            })?
            .iter()
            .map(|lazy_cert| {
                Ok(Cert(
                    lazy_cert.to_cert().map_err(error::PgpError::from)?.clone(),
                ))
            })
            .collect()
    }

    /// Retrieve OpenPGP certificates from the `CertStore` by searching for a
    /// `query_term` that can be either a fingerprint or an email address.
    /// * The function returns a `Vec` of certificates, because there can be
    ///   multiple certificates with the same email in the store.
    /// * If no certificates matching the specified `query_term` is found,
    ///   an error is returned.
    ///
    /// # Arguments
    ///
    /// * `query_term`: fingerprint or an email address of the certificate to
    ///   retrieve. Must be passed as a `QueryTerm` variant.
    pub fn get_cert(&self, query_term: &QueryTerm) -> Result<Vec<Cert>, error::PgpError> {
        match query_term {
            QueryTerm::Fingerprint(f) => Ok(vec![self.get_cert_by_fingerprint(f)?]),
            QueryTerm::Email(email) => self.get_cert_by_email(email),
        }
    }

    /// Retrieves all certificates from the store.
    ///
    /// Excludes special certificates as described in
    /// <https://www.ietf.org/archive/id/draft-nwjw-openpgp-cert-d-00.html#name-special-names>
    /// (currently only `trust-root`).
    pub fn certs<'a>(&'a self) -> Box<dyn Iterator<Item = Result<Cert, error::PgpError>> + 'a> {
        // In the read-only mode, certstore doesn't provide access to `CertD`,
        // (`CertStore::certd`, returns `None`), a type with methods for
        // handling special certificates. As a workaround, this implementation
        // searches for the trust root by its `UserID`.
        let trust_root_userid =
            sequoia_openpgp::packet::UserID::from_static_bytes(LOCAL_TRUST_ROOT_USER_ID);
        let trust_root = self
            .inner
            .lookup_by_userid(&trust_root_userid)
            .ok()
            .and_then(|certs| certs.first().map(|cert| cert.fingerprint()));
        if let Some(local_trust_root) = trust_root {
            Box::new(self.inner.certs().filter_map(move |lazy_cert| {
                (lazy_cert.fingerprint() != local_trust_root).then(|| {
                    lazy_cert
                        .to_cert()
                        .map(|cert| Cert(cert.clone()))
                        .map_err(error::PgpError::from)
                })
            }))
        } else {
            Box::new(self.inner.certs().map(|lazy_cert| {
                Ok(Cert(
                    lazy_cert.to_cert().map_err(error::PgpError::from)?.clone(),
                ))
            }))
        }
    }

    pub(crate) fn get_certs_by_key_handle(
        &self,
        key_handle: &sequoia_openpgp::KeyHandle,
    ) -> Result<Vec<sequoia_openpgp::Cert>, error::PgpError> {
        self.inner
            .lookup_by_cert_or_subkey(key_handle)
            .map_err(error::PgpError::from)?
            .into_iter()
            .map(|lazy_cert| Ok(lazy_cert.to_cert().map_err(error::PgpError::from)?.clone()))
            .collect()
    }

    /// Returns store's local trust root certificate
    pub fn trust_root(&self) -> Result<Cert, error::PgpError> {
        let (trust_root, _) = self
            .inner
            .certd()
            .ok_or_else(|| error::PgpError::from("No certificate directory found"))?
            .trust_root()
            .map_err(error::PgpError::from)?;
        Ok(Cert(
            trust_root.to_cert().map_err(error::PgpError::from)?.clone(),
        ))
    }

    /// Manage user ID certifications
    ///
    /// This function adds or removes certifications for all valid self-signed
    /// UserID packets. It uses the Trust Root certificate from the user's
    /// certificate store to perform these actions.
    ///
    /// On successful execution, it returns a certificate that includes the
    /// updated certifications along with a status indicator. This status
    /// indicates whether the certificate has been modified, specifically if
    /// new certifications have been added or existing ones removed.
    pub fn certify(
        &self,
        cert: &Cert,
        trust_amount: TrustAmount,
    ) -> Result<(Cert, bool), error::PgpError> {
        let policy = sequoia_openpgp::policy::StandardPolicy::new();
        let now = std::time::SystemTime::now();
        let trust_root = self.trust_root()?.0;
        let cert = cert
            .0
            .with_policy(&policy, now)
            .map_err(error::PgpError::from)?;
        if trust_root.fingerprint() == cert.fingerprint() {
            return Err(error::PgpError::from(
                "Certificate to certify must be different from the certificate used for certification",
            ));
        }
        let userids = cert.userids().collect::<Vec<_>>();
        let trust_root_certifications = active_certification(
            &cert,
            userids.iter().map(|ua| ua.userid().clone()),
            trust_root.primary_key().key().role_as_unspecified(),
        );
        if trust_root_certifications.is_empty() {
            match trust_amount {
                TrustAmount::None => {
                    return Err(error::PgpError::Error(format!(
                        "Failed to retract signatures for certificate: {} (no active signatures found)",
                        cert.fingerprint()
                    )));
                }
                TrustAmount::Full => {
                    return Err(error::PgpError::Error(format!(
                        "Failed to sign the certificate: {} (no self-signed signatures found)",
                        cert.fingerprint()
                    )));
                }
            }
        }
        let mut signer = trust_root
            .keys()
            .with_policy(&policy, None)
            .supported()
            .alive()
            .revoked(false)
            .for_certification()
            .next()
            .ok_or_else(|| error::PgpError::from("certification-incapable certificate"))?
            .key()
            .parts_as_secret()
            .map_err(error::PgpError::from)?
            .clone()
            .into_keypair()
            .map_err(error::PgpError::from)?;

        let certification_needed = |certification: Option<&sequoia_openpgp::packet::Signature>| {
            if let Some(c) = certification {
                let trust_signature = c.trust_signature().unwrap_or((0, 120));
                match (trust_amount, trust_signature) {
                    (TrustAmount::None, (0, 0)) => false,
                    (TrustAmount::None, _) => true,
                    (TrustAmount::Full, (0, 120)) => false,
                    (TrustAmount::Full, _) => true,
                }
            } else {
                match trust_amount {
                    TrustAmount::None => false,
                    TrustAmount::Full => true,
                }
            }
        };

        let new_certifications = trust_root_certifications
            .iter()
            .filter(|(_, certification)| certification_needed(certification.as_ref()))
            .map(|(userid, _)| create_certification(userid, &cert, trust_amount, &mut signer, now))
            .collect::<Result<Vec<_>, _>>()?;
        if new_certifications.is_empty() {
            tracing::debug!("No new certifications to add");
            return Ok((Cert(cert.cert().clone()), false));
        }
        cert.cert()
            .clone()
            .insert_packets(new_certifications)
            .map_err(error::PgpError::from)
            .map(|(cert, changed)| (Cert(cert), changed))
    }
}

/// Search term to use when retrieving an OpenPGP certificate from a
/// `CertStore` by either email or fingerprint.
#[derive(Debug, Clone, PartialEq)]
pub enum QueryTerm<'a> {
    /// Fingerprint associated with the certificate to retrieve.
    Fingerprint(Cow<'a, Fingerprint>),
    /// Email associated with the user ID of the certificate to retrieve.
    Email(Cow<'a, str>),
}

impl std::fmt::Display for QueryTerm<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Fingerprint(fingerprint) => write!(f, "{fingerprint}"),
            Self::Email(email) => write!(f, "{email}"),
        }
    }
}

impl std::str::FromStr for QueryTerm<'_> {
    type Err = error::PgpError;

    /// Converts the input string `s` to a `QueryTerm` Enum.
    /// * If `s` is a valid OpenPGP Fingerprint, return the `Fingerprint` variant.
    /// * If `s` is a valid email, return the `Email` variant.
    /// * Otherwise return an error.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(fingerprint) = s.parse() {
            Ok(Self::Fingerprint(Cow::Owned(fingerprint)))
        } else if sequoia_cert_store::email_to_userid(s).is_ok() {
            Ok(Self::Email(Cow::Owned(s.into())))
        } else {
            Err(error::PgpError::Error(format!(
                "Invalid query term: '{s}' is not a valid fingerprint or email."
            )))
        }
    }
}

/// Represents the level of trust associated with a certificate binding.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrustAmount {
    /// No trust.
    None,
    /// Full trust.
    Full,
}

/// Creates a new certification between User ID and primary key
fn create_certification(
    userid: &sequoia_openpgp::packet::UserID,
    cert: &sequoia_openpgp::cert::ValidCert,
    trust_amount: TrustAmount,
    signer: &mut dyn sequoia_openpgp::crypto::Signer,
    creation_time: std::time::SystemTime,
) -> Result<sequoia_openpgp::packet::Packet, error::PgpError> {
    use sequoia_openpgp::packet::signature::SignatureBuilder;
    use sequoia_openpgp::types::SignatureType;

    let builder = SignatureBuilder::new(SignatureType::GenericCertification)
        .set_signature_creation_time(creation_time)
        .map_err(error::PgpError::from)?
        .set_exportable_certification(false)
        .map_err(error::PgpError::from)?;
    let builder = match trust_amount {
        TrustAmount::None => builder
            .set_trust_signature(0, 0)
            .map_err(error::PgpError::from)?,
        // Use default trust signature, i.e., level=0, trust=120
        TrustAmount::Full => builder,
    };
    builder
        .sign_userid_binding(signer, cert.primary_key().key(), userid)
        .map_err(error::PgpError::from)
        .map(Into::into)
}

/// Returns active certifications for user IDs of a certificate.
///
/// Returns `None` if no certification is found for a user ID by a given issuer.
pub(super) fn active_certification(
    cert: &sequoia_openpgp::cert::ValidCert,
    userids: impl Iterator<Item = sequoia_openpgp::packet::UserID>,
    issuer: &sequoia_openpgp::packet::Key<
        sequoia_openpgp::packet::key::PublicParts,
        sequoia_openpgp::packet::key::UnspecifiedRole,
    >,
) -> Vec<(
    sequoia_openpgp::packet::UserID,
    Option<sequoia_openpgp::packet::Signature>,
)> {
    use sequoia_openpgp::policy::{Policy as _, StandardPolicy};

    let now = std::time::SystemTime::now();
    let policy = StandardPolicy::new();
    let issuer_key_handle = issuer.key_handle();
    userids
        .map(|userid| {
            let Some(ua) = cert.userids().find(|ua| ua.userid() == &userid) else {
                return (userid, None);
            };
            // Return the most recent signature matching these conditions:
            //  - certificate contains a userid
            //  - signature has a creation time
            //  - creation time is in the past
            //  - signature is not expired
            //  - signature aliases the provided issuer
            //  - signature is valid for the given policy
            let mut certifications: Vec<_> = ua
                .bundle()
                .certifications()
                .filter(|signature| {
                    signature
                        .signature_creation_time()
                        .is_some_and(|creation_time| {
                            creation_time < now
                                && signature
                                    .signature_validity_period()
                                    .map(|validity_period| now < creation_time + validity_period)
                                    .unwrap_or(true)
                        })
                        && signature
                            .get_issuers()
                            .iter()
                            .any(|i| i.aliases(&issuer_key_handle))
                        && policy
                            .signature(
                                signature,
                                sequoia_openpgp::policy::HashAlgoSecurity::CollisionResistance,
                            )
                            .is_ok()
                })
                .collect();
            certifications.sort_unstable_by(|a, b| {
                a.signature_creation_time()
                    .expect("has creation time")
                    .cmp(&b.signature_creation_time().expect("has creation time"))
                    .reverse()
                    .then(a.mpis().cmp(b.mpis()))
            });
            let primary_key = ua.cert().primary_key().key();
            let valid_certification = certifications
                .into_iter()
                .find(|signature| {
                    signature
                        .verify_userid_binding(issuer, primary_key, &userid)
                        .is_ok()
                })
                .cloned();
            (userid, valid_certification)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use crate::openpgp::cert::{CertType, ReasonForRevocation, RevocationStatus};

    use super::*;

    fn generate_tmp_certstore<'a>() -> Result<CertStore<'a>, error::Error> {
        let tmp_dir = tempfile::tempdir()?.keep();
        CertStore::open(&CertStoreOpts {
            location: Some(&tmp_dir.join(CertStore::DEFAULT_DIR)),
            ..Default::default()
        })
    }

    #[test]
    fn default_certstore_location() {
        let default_dir = "pgp.cert.d";
        let default_location = dirs::data_dir().unwrap().join(default_dir);
        assert_eq!(CertStore::default_location().unwrap(), default_location);
    }

    #[test]
    fn custom_certstore_location() {
        let tmp_dir = tempfile::tempdir().unwrap().keep();
        let store = CertStore::open(&CertStoreOpts {
            location: Some(&tmp_dir),
            ..Default::default()
        })
        .unwrap();
        assert_eq!(store.path, tmp_dir);
    }

    #[test]
    fn open_certstore() {
        // Creating a new certstore should work.
        let store = generate_tmp_certstore().unwrap();
        assert!(store.path.is_dir());
    }

    // Test adding certificates to the store.
    #[test]
    fn import_cert() -> Result<(), error::Error> {
        let mut store = generate_tmp_certstore()?;

        macro_rules! assert_import {
            ($file_name:expr) => {
                // Add cert to store.
                let cert = store.import(&Cert::from_bytes(include_bytes!(concat!(
                    "../../tests/data/",
                    $file_name
                )))?)?;
                // Make sure secret certificates are stripped from their secret
                // material.
                assert_eq!(cert.0.is_tsk(), false);
                // Make sure the certificate file is stored at the expected
                // place.
                assert!(store.get_cert_path(&cert.fingerprint())?.is_file());
                // Make sure cert can be retrieved from the store.
                let fingerprint = &$file_name[..40];
                assert_eq!(
                    store
                        .get_cert_by_fingerprint(&fingerprint.parse()?,)?
                        .fingerprint()
                        .to_string(),
                    fingerprint,
                );
            };
        }

        // Adding a certificate with only public material should pass.
        assert_import!("1EA0292ECBF2457CADAE20E2B94FA6A56D9FA1FB.pub");
        assert_eq!(store.certs().count(), 1);

        // Adding a certificate with secret material should pass.
        assert_import!("B2E961753ECE0B345E718E74BA6F29C998DDD9BF.sec");
        assert_eq!(store.certs().count(), 2);

        // Adding the same certificate again should update the existing one,
        // i.e. the number of certificates should not increase.
        assert_import!("B2E961753ECE0B345E718E74BA6F29C998DDD9BF.sec");
        assert_eq!(store.certs().count(), 2);
        // Adding a different certificate should increase the number of certs.
        assert_import!("C0621CB3669020CC31050A361956EC38A96CA852.sec");
        assert_eq!(store.certs().count(), 3);
        Ok(())
    }

    // Test that a certificate can be revoked. This also tests that adding
    // content to a (in this case the revocation signature) is done properly.
    #[test]
    fn revoke_cert() -> Result<(), error::Error> {
        let mut store = generate_tmp_certstore()?;
        macro_rules! assert_revoke {
            ($fingerprint:expr, $revocation_message:expr) => {
                let fingerprint = $fingerprint.parse().unwrap();
                // Add the certificate to the store.
                store.import(&Cert::from_bytes(include_bytes!(concat!(
                    "../../tests/data/",
                    $fingerprint,
                    ".pub"
                )))?)?;
                // Make sure the certificate is originally not revoked.
                let cert = store.get_cert_by_fingerprint(&fingerprint)?;
                assert!(matches!(
                    cert.revocation_status(),
                    RevocationStatus::NotAsFarAsWeKnow
                ));
                // Revoke the certificate and add the revoked version of the
                // certificate to the store.
                store.import(&cert.revoke(std::io::Cursor::new(&include_bytes!(concat!(
                    "../../tests/data/",
                    $fingerprint,
                    ".rev"
                ))))?)?;
                // Make sure the certificate in the store is now revoked.
                let revoked_cert = store.get_cert_by_fingerprint(&fingerprint)?;
                assert!(matches!(
                    revoked_cert.revocation_status(),
                    RevocationStatus::Revoked(_)
                ));
                if let RevocationStatus::Revoked(sig) = revoked_cert.revocation_status() {
                    assert_eq!(sig.len(), 1);
                    let (reason, message) = sig[0]
                        .reason_for_revocation()
                        .expect("This signature has a revocation reason.");
                    assert_eq!(reason, ReasonForRevocation::KeyCompromised);
                    assert_eq!(message, $revocation_message.as_bytes())
                }
            };
        }
        assert_revoke!(
            "1EA0292ECBF2457CADAE20E2B94FA6A56D9FA1FB",
            "CN does not compromise"
        );
        assert_revoke!(
            "B2E961753ECE0B345E718E74BA6F29C998DDD9BF",
            "CN does not remember passwords, passwords remember him!"
        );
        Ok(())
    }

    // Test that certificates can be retrieved from the CertStore.
    #[test]
    fn get_cert() -> Result<(), error::Error> {
        let mut store = generate_tmp_certstore()?;

        // Contains only public material
        let cert_1 = store.import(&Cert::from_bytes(include_bytes!(
            "../../tests/data/1EA0292ECBF2457CADAE20E2B94FA6A56D9FA1FB.pub"
        ))?)?;
        // Contains both public and secret material.
        let cert_2 = store.import(&Cert::from_bytes(include_bytes!(
            "../../tests/data/B2E961753ECE0B345E718E74BA6F29C998DDD9BF.sec"
        ))?)?;

        // Retrieving all certificates should yield the correct number of certs.
        assert_eq!(store.certs().count(), 2);

        // Retrieving certificates by their fingerprint should work.
        assert_eq!(
            store.get_cert_by_fingerprint(&cert_1.fingerprint())?,
            cert_1
        );
        assert_eq!(
            store.get_cert_by_fingerprint(&cert_2.fingerprint())?,
            cert_2
        );
        let cert1_vec = vec![cert_1];
        let cert2_vec = vec![cert_2];

        // Retrieving certificates by their email should work.
        assert_eq!(
            &store.get_cert_by_email("chuck.norris@roundhouse.org")?,
            &cert1_vec
        );
        assert_eq!(
            &store.get_cert_by_email("chuck.norris@roundhouse.swiss")?,
            &cert2_vec
        );
        assert_eq!(
            &store.get_cert_by_email("Chuck.Norris@roundhouse.org")?,
            &cert1_vec
        );

        // Retrieving certificates by QueryTerm (fingerprint or email) should
        // work.
        assert_eq!(
            &store.get_cert(&QueryTerm::Email("chuck.norris@roundhouse.org".into()),)?,
            &cert1_vec
        );
        assert_eq!(
            &store.get_cert(&QueryTerm::Fingerprint(Cow::Owned(
                "B2E961753ECE0B345E718E74BA6F29C998DDD9BF".parse().unwrap()
            )),)?,
            &cert2_vec
        );

        // Trying to retrieve a non-existing certificate by its fingerprint or
        // email should fail.
        assert!(store.get_cert_by_email("chuck.norris@missing.com").is_err());
        Ok(())
    }

    #[test]
    fn queryterm_from_str() {
        use std::str::FromStr;
        // Passing a valid fingerprint should work.
        assert_eq!(
            QueryTerm::from_str("B2E961753ECE0B345E718E74BA6F29C998DDD9BF").unwrap(),
            QueryTerm::Fingerprint(Cow::Owned(
                "B2E961753ECE0B345E718E74BA6F29C998DDD9BF".parse().unwrap()
            ))
        );
        assert_eq!(
            QueryTerm::from_str("B2E9 6175 3ECE 0B34 5E71 8E74 BA6F 29C9 98DD D9BF").unwrap(),
            QueryTerm::Fingerprint(Cow::Owned(
                "B2E961753ECE0B345E718E74BA6F29C998DDD9BF".parse().unwrap()
            ))
        );
        // Passing a valid email should work.
        assert_eq!(
            QueryTerm::from_str("chuck.norris@roundhouse.gov").unwrap(),
            QueryTerm::Email(Cow::Owned("chuck.norris@roundhouse.gov".into()))
        );
        // Passing an empty string should fail.
        assert!(QueryTerm::from_str("").is_err());
        // Short, fingerprint-like values should fail.
        assert!(QueryTerm::from_str("aaa").is_err());
        assert!(QueryTerm::from_str("aaaa").is_err());
        // Passing non-valid fingerprints or emails should fail.
        assert!(QueryTerm::from_str("not_a_fingerprint_nor_an_email").is_err());
    }

    #[test]
    fn cert_type_to_string() -> Result<(), error::PgpError> {
        // Verify that variants of CertType are correctly converted to
        // string.
        assert_eq!(format!("{}", CertType::Public), "public");
        assert_eq!(format!("{}", CertType::Secret), "private");
        Ok(())
    }
}