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
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
//! OpenPGP certificates

use super::{
    certstore::TrustAmount,
    error::{Error, PgpError, VerificationError},
};
use sequoia_openpgp::{
    parse::Parse as _,
    policy::StandardPolicy,
    serialize::{Serialize as _, SerializeInto as _},
};
use tracing::warn;

pub mod error;

/// Internal representation of the supported cipher suites.
#[derive(Default, Copy, Clone)]
pub enum CipherSuite {
    #[default]
    /// Elliptic-curve cryptography with 256-bit keys.
    Cv25519,
    /// RSA cryptography with 4096-bit keys.
    RSA4k,
}

/// A unique identifier for OpenPGP certificates and keys.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Fingerprint(pub(crate) sequoia_openpgp::Fingerprint);

impl Fingerprint {
    /// Returns the fingerprint as a hexadecimal string.
    ///
    /// This representation uses only uppercase characters without spaces.
    pub fn to_hex(&self) -> String {
        self.0.to_hex()
    }
}

impl std::fmt::Display for Fingerprint {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::str::FromStr for Fingerprint {
    type Err = PgpError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match sequoia_openpgp::Fingerprint::from_str(s) {
            Ok(
                fp @ sequoia_openpgp::Fingerprint::V4(_) | fp @ sequoia_openpgp::Fingerprint::V6(_),
            ) => Ok(Self(fp)),
            Ok(_) => Err(Self::Err::Error(
                "Incompatible fingerprint version".to_string(),
            )),
            Err(e) => Err(Self::Err::from(e)),
        }
    }
}

impl std::fmt::Debug for Fingerprint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.0)
    }
}

/// OpenPGP certificate.
#[derive(Clone, Debug, PartialEq)]
pub struct Cert(pub(crate) sequoia_openpgp::cert::Cert);

/// Valid OpenPGP certificate.
///
/// A certificate is considered valid if it has a valid and live binding
/// signature at the given time.
#[derive(Clone, Debug)]
pub struct ValidCert<'a>(pub(crate) sequoia_openpgp::cert::ValidCert<'a>);

/// Policy for validating OpenPGP certificates.
#[derive(Debug, Default, Clone)]
pub struct ValidCertPolicy<'a>(StandardPolicy<'a>);

impl<'a> ValidCert<'a> {
    /// Returns the fingerprint of the certificate.
    ///
    /// The fingerprint is a unique identifier for the certificate.
    /// It equal to the fingerprint of the primary key.
    pub fn fingerprint(&self) -> Fingerprint {
        Fingerprint(self.0.fingerprint())
    }

    /// Returns the valid keys of the certificate.
    pub fn keys(&self) -> Vec<Key> {
        self.0
            .keys()
            .map(|ka| Key {
                fingerprint: Fingerprint(ka.key().fingerprint()),
            })
            .collect()
    }

    /// Returns the valid user IDs of the certificate.
    pub fn userids(&self) -> Vec<String> {
        self.0
            .userids()
            .map(|uid| uid.userid().to_string())
            .collect()
    }

    /// Returns the certificate type.
    pub fn cert_type(&self) -> CertType {
        if self.0.cert().is_tsk() {
            CertType::Secret
        } else {
            CertType::Public
        }
    }

    /// Returns certificate's expiration time.
    ///
    /// Returns `None` if the certificate does not have an expiration.
    pub fn expiration_time(&self) -> Option<std::time::SystemTime> {
        self.0.primary_key().key_expiration_time()
    }

    /// Returns trust amount in the user id binding provided by the certifier.
    pub fn trust_amount(&self, certifier: &Cert, userid: &str) -> TrustAmount {
        let certifications = super::certstore::active_certification(
            &self.0,
            std::iter::once(sequoia_openpgp::packet::UserID::from(userid)),
            certifier.0.primary_key().key().role_as_unspecified(),
        );
        if certifications.iter().any(|(_, certification)| {
            certification
                .as_ref()
                .is_some_and(|c| c.trust_signature().unwrap_or((0, 120)).1 == 120)
        }) {
            TrustAmount::Full
        } else {
            TrustAmount::None
        }
    }

    /// Returns the revocation status of the certificate.
    pub fn revocation_status(&self) -> RevocationStatus {
        RevocationStatus::from_sequoia(self.0.revocation_status())
    }

    /// Retrieves the email of the certificate's primary user ID.
    pub fn get_primary_email(&self) -> Result<Option<String>, PgpError> {
        self.0
            .primary_userid()
            .map_err(PgpError::from)?
            .userid()
            .email()
            .map_err(PgpError::from)
            .map(|s| s.map(String::from))
    }
}

impl std::fmt::Display for ValidCert<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        // `Name <email> [fingerprint]`
        if let Ok(user_id) = self.0.primary_userid() {
            write!(f, "{}", user_id.userid())?;
        } else {
            write!(f, "Missing or invalid user ID")?;
        }
        write!(f, " [{}]", self.fingerprint().to_hex())
    }
}

impl Cert {
    /// Returns the fingerprint of the certificate.
    ///
    /// The fingerprint is a unique identifier for the certificate.
    /// It equal to the fingerprint of the primary key.
    pub fn fingerprint(&self) -> Fingerprint {
        Fingerprint(self.0.fingerprint())
    }

    /// Validates the certificate using the given policy.
    pub fn validate<'a>(&'a self, policy: &'a ValidCertPolicy) -> Result<ValidCert<'a>, PgpError> {
        self.0
            .with_policy(&policy.0, None)
            .map(ValidCert)
            .map_err(|e| {
                PgpError::Error(format!(
                    "Invalid key: no valid self-signature was found. {e}"
                ))
            })
    }

    /// Sets the certificate's expiration time.
    ///
    /// The expiration time is set for the primary key, all subkeys, and all user IDs.
    pub async fn set_expiration_time(
        mut self,
        signer: crate::openpgp::keystore::Key,
        expiration_time: Option<std::time::SystemTime>,
    ) -> Result<Self, Error> {
        use sequoia_openpgp::packet::signature::SignatureBuilder;
        let mut signer = signer.inner;
        tokio::task::spawn_blocking(move || -> Result<_, Error> {
            let now = std::time::SystemTime::now();
            let policy = StandardPolicy::new();
            let mut signatures = Vec::new();
            // Subkeys
            for ka in self.0.keys().subkeys() {
                signatures.push(
                    ka.key()
                        .bind(
                            &mut signer,
                            &self.0,
                            SignatureBuilder::from(
                                ka.binding_signature(&policy, now)
                                    .or_else(|_| {
                                        ka.self_signatures()
                                            .next()
                                            .ok_or(PgpError::from("no subkey binding signature"))
                                    })?
                                    .clone(),
                            )
                            .set_signature_creation_time(now)
                            .map_err(PgpError::from)?
                            .set_key_expiration_time(ka.key(), expiration_time)
                            .map_err(PgpError::from)?,
                        )
                        .map_err(PgpError::from)?,
                );
            }
            // Primary key
            signatures.push(
                SignatureBuilder::from(
                    self.0
                        .primary_key()
                        .binding_signature(&policy, now)
                        .or_else(|_| {
                            self.0
                                .primary_key()
                                .self_signatures()
                                .next()
                                .ok_or(PgpError::from("no primary key signature"))
                        })?
                        .clone(),
                )
                .set_type(sequoia_openpgp::types::SignatureType::DirectKey)
                .set_signature_creation_time(now)
                .map_err(PgpError::from)?
                .set_key_expiration_time(self.0.primary_key().key(), expiration_time)
                .map_err(PgpError::from)?
                .sign_direct_key(&mut signer, None)
                .map_err(PgpError::from)?,
            );
            // User IDs
            for ua in self.0.userids() {
                signatures.push(
                    ua.userid()
                        .bind(
                            &mut signer,
                            &self.0,
                            SignatureBuilder::from(
                                ua.binding_signature(&policy, now)
                                    .or_else(|_| {
                                        ua.self_signatures()
                                            .next()
                                            .ok_or(PgpError::from("no user ID binding signature"))
                                    })?
                                    .clone(),
                            )
                            .set_signature_creation_time(now)
                            .map_err(PgpError::from)?
                            .set_key_expiration_time(self.0.primary_key().key(), expiration_time)
                            .map_err(PgpError::from)?,
                        )
                        .map_err(PgpError::from)?,
                );
            }
            self.0 = self.0.insert_packets(signatures).map_err(PgpError::from)?.0;
            Ok(self)
        })
        .await?
    }

    /// Return the first certificate found in the input bytes.
    pub fn from_bytes(data: impl AsRef<[u8]>) -> Result<Self, PgpError> {
        Ok(Self(
            sequoia_openpgp::cert::Cert::from_bytes(data.as_ref()).map_err(PgpError::from)?,
        ))
    }

    /// Return the certificate type.
    pub fn cert_type(&self) -> CertType {
        if self.0.is_tsk() {
            CertType::Secret
        } else {
            CertType::Public
        }
    }

    /// Check if the certificate's primary key is encrypted.
    pub fn is_encrypted(&self) -> Result<bool, PgpError> {
        Ok(self
            .0
            .primary_key()
            .key()
            .clone()
            .parts_into_secret()
            .map_err(PgpError::from)?
            .secret()
            .is_encrypted())
    }

    /// Return the revocation status of the certificate.
    pub fn revocation_status(&self) -> RevocationStatus {
        RevocationStatus::from_sequoia(self.0.revocation_status(&StandardPolicy::new(), None))
    }

    /// Generate revocation signature.
    pub async fn generate_rev_sig(
        &self,
        signer: crate::openpgp::keystore::Key,
        code: ReasonForRevocation,
        reason: String,
    ) -> Result<Vec<u8>, Error> {
        let mut signer = signer.inner;
        let cert = self.0.clone();
        let signature = tokio::task::spawn_blocking(move || -> Result<_, PgpError> {
            cert.revoke(&mut signer, code.into_sequoia(), reason.as_bytes())
                .map_err(PgpError::from)
        })
        .await??;
        Ok(serialize_revocation_signature(&self.0, signature)?)
    }

    /// Revoke the certificate with the provided revocation `signature`.
    ///
    /// Appends the revocation signature(s) found in `signature` to the
    /// certificate.
    /// Note that if `signature` contains multiple OpenPGP blocks, only the
    /// first of these blocks will be used (others are ignored).
    pub fn revoke<R: std::io::Read + Send + Sync>(&self, signature: R) -> Result<Self, PgpError> {
        // Parse input for revocation signature(s).
        let mut ppr = sequoia_openpgp::parse::PacketParserBuilder::from_reader(signature)
            .and_then(|ppb| ppb.buffer_unread_content().build())
            .map_err(|_| error::RevocationError::NoSignature)?;
        let mut revocations = Vec::new();
        while let sequoia_openpgp::parse::PacketParserResult::Some(pp) = ppr {
            let (packet, next_ppr) = pp
                .recurse()
                .map_err(|e| error::RevocationError::ParsingError(e.to_string()))?;
            ppr = next_ppr;

            if let sequoia_openpgp::Packet::Signature(sig) = packet
                && matches!(
                    sig.typ(),
                    sequoia_openpgp::types::SignatureType::CertificationRevocation
                        | sequoia_openpgp::types::SignatureType::KeyRevocation
                        | sequoia_openpgp::types::SignatureType::SubkeyRevocation
                )
            {
                revocations.push(sig);
            }
        }
        if revocations.is_empty() {
            return Err(error::RevocationError::NoSignature.into());
        }

        // Generate a revoked copy of the certificate.
        let revoked_cert = Self(
            self.0
                .clone()
                .insert_packets(revocations)
                .map_err(PgpError::from)?
                .0,
        );

        // Make sure the provided signature was able to revoke the certificate.
        // This is checked because it's technically possible to add any
        // signature block to a certificate.
        if let RevocationStatus::Revoked(_) = revoked_cert.revocation_status() {
            Ok(revoked_cert)
        } else {
            Err(error::RevocationError::WrongSignature.into())
        }
    }

    /// Updates the certificate with the secret material from the specified key
    /// store.
    ///
    /// Returns the certificate enriched with the secret material, or an error
    /// if the secret material for the primary key or any subkey cannot be
    /// found in the specified keystore.
    pub async fn update_secret_material(
        self,
        key_store: &mut crate::openpgp::keystore::KeyStore,
    ) -> Result<Cert, PgpError> {
        let mut packets: Vec<sequoia_openpgp::Packet> = Vec::new();
        let primary_fingerprint = self.0.primary_key().key().fingerprint();

        let primary_or_subkey_text = |fingerprint: &sequoia_openpgp::Fingerprint| {
            if fingerprint == &primary_fingerprint {
                "".to_string()
            } else {
                format!(" the subkey '{fingerprint}' of")
            }
        };

        // For each key (primary and all subkeys) of the certificate, retrieve
        // the secret material associated with it from the specified keystore
        // (keystores contain the key's secret material).
        for fingerprint in self.0.keys().map(|ka| ka.key().fingerprint()) {
            // Verify that secret material for the key exists in the keystore.
            if key_store
                .inner
                .find_key_async(fingerprint.clone().into())
                .await
                .map_err(PgpError::from)?
                .is_empty()
            {
                return Err(PgpError::Error(format!(
                    "No secret material was found in the keystore for{primary_fingerprint} \
                the certificate '{}'",
                    primary_or_subkey_text(&fingerprint)
                )));
            }

            // Get the key's secret material.
            let secret_key = key_store.export(&fingerprint).await.map_err(|_| {
                PgpError::Error(format!(
                    "Secret material for{} the certificate '{primary_fingerprint}' \
                cannot be exported from the keystore",
                    primary_or_subkey_text(&fingerprint)
                ))
            })?;
            if fingerprint == primary_fingerprint {
                packets.push(secret_key.role_into_primary().into())
            } else {
                packets.push(secret_key.role_into_subordinate().into())
            }
        }

        // Return a certificate based on the original certificate, enriched
        // with the secret material retrieved for all primary/sub-keys.
        let (cert, _modified) = self.0.insert_packets(packets).map_err(PgpError::from)?;
        Ok(Cert(cert))
    }

    /// Return a view to the public part of the key for export
    pub fn public(&self) -> CertDataView<&sequoia_openpgp::cert::Cert> {
        CertDataView(&self.0)
    }

    /// Return a view to the secret part of the key for export
    pub fn secret(&self) -> Result<CertDataView<SecretCertDataView<'_>>, PgpError> {
        if !self.0.is_tsk() {
            return Err(PgpError::from(
                "Secret material is missing, cannot generate a revocation signature for a public key.",
            ));
        }
        Ok(CertDataView(SecretCertDataView(&self.0)))
    }
}

impl std::fmt::Display for Cert {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let user_id = self
            .0
            .with_policy(&StandardPolicy::new(), None)
            .map_or_else(
                |_| String::from("Invalid key: no valid self-signature was found"),
                |valid_cert| {
                    valid_cert.primary_userid().map_or_else(
                        |_| String::from("Missing or no valid user ID"),
                        |user_id| user_id.userid().to_string(),
                    )
                },
            );
        // `Name <email> [fingerprint]`
        write!(f, "{} [{}]", user_id, self.fingerprint().to_hex())
    }
}

/// View to either the public or the secret part of a certificate.
///
/// The view can be converted to [`Vec<u8>`] or [AsciiArmored] via [TryFrom] and
/// serde serialized in ascii armored format.
#[derive(Debug, Clone, Copy)]
pub struct CertDataView<T>(T);

/// Ascii armored export format for a [CertDataView] via [TryFrom].
#[derive(Debug)]
pub struct AsciiArmored(pub(crate) Vec<u8>);

impl AsRef<[u8]> for AsciiArmored {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl std::ops::Deref for AsciiArmored {
    type Target = [u8];
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<AsciiArmored> for Vec<u8> {
    fn from(value: AsciiArmored) -> Self {
        value.0
    }
}

/// Helper type to work around the lack of Copy of [sequoia_openpgp::serialize::TSK].
#[derive(Debug, Copy, Clone)]
pub struct SecretCertDataView<'a>(&'a sequoia_openpgp::cert::Cert);

impl TryFrom<CertDataView<&sequoia_openpgp::cert::Cert>> for Vec<u8> {
    type Error = PgpError;
    fn try_from(value: CertDataView<&sequoia_openpgp::cert::Cert>) -> Result<Self, Self::Error> {
        value.0.to_vec().map_err(Self::Error::from)
    }
}
impl TryFrom<CertDataView<SecretCertDataView<'_>>> for Vec<u8> {
    type Error = PgpError;
    fn try_from(value: CertDataView<SecretCertDataView<'_>>) -> Result<Self, Self::Error> {
        value.0.0.as_tsk().to_vec().map_err(Self::Error::from)
    }
}

impl TryFrom<CertDataView<&sequoia_openpgp::cert::Cert>> for AsciiArmored {
    type Error = PgpError;
    fn try_from(value: CertDataView<&sequoia_openpgp::cert::Cert>) -> Result<Self, Self::Error> {
        Ok(Self(value.0.armored().to_vec().map_err(Self::Error::from)?))
    }
}

impl TryFrom<CertDataView<SecretCertDataView<'_>>> for AsciiArmored {
    type Error = PgpError;
    fn try_from(value: CertDataView<SecretCertDataView<'_>>) -> Result<Self, Self::Error> {
        Ok(Self(
            value
                .0
                .0
                .as_tsk()
                .armored()
                .to_vec()
                .map_err(Self::Error::from)?,
        ))
    }
}

impl<T> serde::Serialize for CertDataView<T>
where
    AsciiArmored: TryFrom<CertDataView<T>>,
    <AsciiArmored as TryFrom<CertDataView<T>>>::Error: std::fmt::Display,
    CertDataView<T>: Copy,
{
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::Error;
        let bytes = AsciiArmored::try_from(*self).map_err(Error::custom)?;
        let decoded = std::str::from_utf8(&bytes).map_err(Error::custom)?;
        serializer.collect_str(decoded)
    }
}

/// Builder for creating OpenPGP certificates.
pub struct CertBuilder<'a> {
    builder: sequoia_openpgp::cert::CertBuilder<'a>,
}

impl Default for CertBuilder<'_> {
    fn default() -> Self {
        Self {
            builder: sequoia_openpgp::cert::CertBuilder::new()
                .set_cipher_suite(sequoia_openpgp::cert::CipherSuite::Cv25519),
        }
    }
}

impl CertBuilder<'_> {
    /// Creates a new `CertBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a user ID to the certificate.
    pub fn add_userid(mut self, uid: &str) -> Self {
        self.builder = self.builder.add_userid(uid);
        self
    }

    /// Sets the certificate's validity period.
    pub fn set_validity_period(
        mut self,
        validity_period: impl Into<Option<std::time::Duration>>,
    ) -> Self {
        self.builder = self.builder.set_validity_period(validity_period);
        self
    }

    /// Sets the certificate's cipher suite.
    pub fn set_cipher_suite(mut self, cipher: CipherSuite) -> Self {
        self.builder = self.builder.set_cipher_suite(match cipher {
            CipherSuite::Cv25519 => sequoia_openpgp::cert::CipherSuite::Cv25519,
            CipherSuite::RSA4k => sequoia_openpgp::cert::CipherSuite::RSA4k,
        });
        self
    }

    /// Sets the password for encrypting the secret key material.
    pub fn set_password(mut self, password: Option<crate::secret::Secret>) -> Self {
        self.builder = self
            .builder
            .set_password(password.map(|p| p.as_inner().to_owned()));
        self
    }

    /// Generates an OpenPGP certificate and a revocation signature.
    pub fn generate(self) -> Result<(Cert, Vec<u8>), PgpError> {
        let (cert, rev) = self
            .builder
            .add_authentication_subkey()
            .add_signing_subkey()
            .add_subkey(
                sequoia_openpgp::types::KeyFlags::empty()
                    .set_transport_encryption()
                    .set_storage_encryption(),
                None,
                None,
            )
            .generate()
            .map_err(PgpError::from)?;
        let rev_sig = serialize_revocation_signature(&cert, rev)?;
        Ok((Cert(cert), rev_sig))
    }
}

fn serialize_revocation_signature(
    cert: &sequoia_openpgp::Cert,
    rev: sequoia_openpgp::packet::Signature,
) -> Result<Vec<u8>, PgpError> {
    let mut rev_serialized = Vec::new();
    let mut writer = sequoia_openpgp::armor::Writer::with_headers(
        &mut rev_serialized,
        sequoia_openpgp::armor::Kind::Signature,
        std::iter::once(("Comment", "Revocation certificate for")).chain(
            cert.armor_headers()
                .iter()
                .map(|value| ("Comment", value.as_str())),
        ),
    )
    .map_err(PgpError::from)?;
    sequoia_openpgp::packet::Packet::Signature(rev)
        .serialize(&mut writer)
        .map_err(PgpError::from)?;
    writer.finalize().map_err(PgpError::from)?;
    Ok(rev_serialized)
}

/// Reads OpenPGP certificates a reader.
///
/// Input data may contain multiple certificates. The parser will return
/// an error if the data contains invalid certificates.
pub fn parse_certs<R: std::io::Read + Send + Sync>(data: R) -> Result<Vec<Cert>, PgpError> {
    sequoia_openpgp::cert::CertParser::from(
        sequoia_openpgp::parse::PacketParser::from_reader(data).map_err(PgpError::from)?,
    )
    .map(|c| Ok(Cert(c.map_err(PgpError::from)?)))
    .collect()
}

/// Enum indicating whether an OpenPGP certificate stores only public material,
/// or if it also contains secret material.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum CertType {
    /// Certificate contains only public material.
    #[default]
    Public,
    /// Certificate contains both public and secret material.
    Secret,
}

// Allows to print a `CertType` variant as a string.
impl std::fmt::Display for CertType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            CertType::Public => write!(f, "public"),
            CertType::Secret => write!(f, "private"),
        }
    }
}

#[derive(Debug, Clone)]
/// Internal representation of an OpenPGP signature.
pub struct Signature(sequoia_openpgp::packet::Signature);

impl Signature {
    /// Return the reason for the revocation of the signature.
    pub fn reason_for_revocation(&self) -> Option<(ReasonForRevocation, &[u8])> {
        self.0
            .reason_for_revocation()
            .map(|(code, msg)| (ReasonForRevocation::from_sequoia(code), msg))
    }
}

#[derive(Debug, Clone)]
/// Internal representation of an OpenPGP key revocation status.
pub enum RevocationStatus {
    /// Key is revoked.
    Revoked(Vec<Signature>),
    /// There is a revocation certificate from a possible designated
    /// revoker.
    CouldBe(Vec<Signature>),
    /// Key does not appear to be revoked.
    NotAsFarAsWeKnow,
}

impl RevocationStatus {
    fn from_sequoia(value: sequoia_openpgp::types::RevocationStatus) -> Self {
        use sequoia_openpgp::types::RevocationStatus::*;
        match value {
            Revoked(s) => {
                RevocationStatus::Revoked(s.into_iter().map(|s| Signature(s.clone())).collect())
            }
            CouldBe(s) => {
                RevocationStatus::CouldBe(s.into_iter().map(|s| Signature(s.clone())).collect())
            }
            NotAsFarAsWeKnow => RevocationStatus::NotAsFarAsWeKnow,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
/// Describes the reason for a revocation.
/// This enum cannot be exhaustively matched to allow future extensions.
pub enum ReasonForRevocation {
    /// None of the other reasons apply. This can be used can be used when
    /// creating a revocation signature in advance.
    Unspecified,
    /// The private key has been replaced by a new one.
    KeySuperseded,
    /// The private key material (may) have been compromised.
    KeyCompromised,
    /// This public key should not be used anymore and there is no
    /// replacement key.
    KeyRetired,
    /// User ID information is no longer valid (cert revocations).
    UIDRetired,
    /// Private reason identifier.
    Private(u8),
    /// Unknown reason identifier.
    Unknown(u8),
}

impl std::fmt::Display for ReasonForRevocation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.clone().into_sequoia())
    }
}

impl ReasonForRevocation {
    pub(super) fn into_sequoia(self) -> sequoia_openpgp::types::ReasonForRevocation {
        use sequoia_openpgp::types::ReasonForRevocation::*;
        match self {
            ReasonForRevocation::Unspecified => Unspecified,
            ReasonForRevocation::KeySuperseded => KeySuperseded,
            ReasonForRevocation::KeyCompromised => KeyCompromised,
            ReasonForRevocation::KeyRetired => KeyRetired,
            ReasonForRevocation::UIDRetired => UIDRetired,
            ReasonForRevocation::Private(v) => Private(v),
            ReasonForRevocation::Unknown(v) => Unknown(v),
        }
    }

    pub(super) fn from_sequoia(val: sequoia_openpgp::types::ReasonForRevocation) -> Self {
        use sequoia_openpgp::types::ReasonForRevocation::*;
        match val {
            Unspecified => Self::Unspecified,
            KeySuperseded => Self::KeySuperseded,
            KeyCompromised => Self::KeyCompromised,
            KeyRetired => Self::KeyRetired,
            UIDRetired => Self::UIDRetired,
            Private(v) => Self::Private(v),
            Unknown(v) => Self::Unknown(v),
            // TODO: currently it's unreachable, but it might change in the
            // future if Sequoia extends the enum.
            _ => todo!(),
        }
    }
}

/// OpenPGP key.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Key {
    pub(super) fingerprint: Fingerprint,
}

impl Key {
    /// Returns the fingerprint of the key.
    ///
    /// The fingerprint is a unique identifier for the key.
    pub fn fingerprint(&self) -> Fingerprint {
        self.fingerprint.clone()
    }
}

/// Warns if the certificate expires in the next 90 days.
pub(crate) fn warn_if_cert_expires_soon(valid_cert: &sequoia_openpgp::cert::ValidCert) {
    use chrono::{DateTime, Duration, Utc};
    if let Some(expiration_time) = valid_cert.primary_key().key_expiration_time() {
        let expiration_time = DateTime::<Utc>::from(expiration_time);
        if expiration_time < Utc::now() + Duration::days(90) {
            warn!(
                "Certificate {}[{}] expires on {}, consider renewing it",
                valid_cert
                    .userids()
                    .next()
                    .map_or_else(String::new, |uid| format!("{} ", uid.userid())),
                valid_cert.fingerprint(),
                expiration_time
            );
        }
    }
}

/// Verify the signature of a file.
pub(crate) fn verify_file_signature(
    body: &[u8],
    signature: &[u8],
    cert_store: &super::certstore::CertStore<'_>,
) -> Result<(), PgpError> {
    use sequoia_openpgp::parse::{Parse, stream::DetachedVerifierBuilder};
    DetachedVerifierBuilder::from_bytes(signature)
        .map_err(PgpError::from)?
        .with_policy(
            &sequoia_openpgp::policy::StandardPolicy::new(),
            None,
            crate::openpgp::crypto::VerificationHelper { cert_store },
        )
        .map_err(PgpError::from)?
        .verify_bytes(body)
        .map_err(|e| match e.downcast() {
            Ok(VerificationError::MissingKey { fingerprint }) => {
                PgpError::VerificationError(VerificationError::MissingKey { fingerprint })
            }
            Ok(VerificationError::Error(value)) => {
                PgpError::VerificationError(VerificationError::Error(value))
            }
            Err(value) => PgpError::from(value),
        })
}

#[cfg(test)]
mod tests {
    use sequoia_openpgp::{cert::CertBuilder, packet::UserID};

    use super::*;

    const VALID_USER_ID1: &str = "chuck norris <chuck@roundhouse.org>";
    const VALID_USER_ID2: &str = "cn <cn@roundhouse.org>";
    const INVALID_USER_ID: &str = "sgt hartman <invalid@roundhouse.org>";

    #[test]
    fn parse_fingerprint() {
        use std::str::FromStr;
        // Passing a valid fingerprint should work.
        assert_eq!(
            Fingerprint::from_str("B2E961753ECE0B345E718E74BA6F29C998DDD9BF")
                .unwrap()
                .0,
            sequoia_openpgp::Fingerprint::from_bytes(
                4,
                &[
                    0xB2, 0xE9, 0x61, 0x75, 0x3E, 0xCE, 0x0B, 0x34, 0x5E, 0x71, 0x8E, 0x74, 0xBA,
                    0x6F, 0x29, 0xC9, 0x98, 0xDD, 0xD9, 0xBF
                ]
            )
            .unwrap()
        );
        assert_eq!(
            Fingerprint::from_str("B2E9 6175 3ECE 0B34 5E71 8E74 BA6F 29C9 98DD D9BF")
                .unwrap()
                .0,
            sequoia_openpgp::Fingerprint::from_bytes(
                4,
                &[
                    0xB2, 0xE9, 0x61, 0x75, 0x3E, 0xCE, 0x0B, 0x34, 0x5E, 0x71, 0x8E, 0x74, 0xBA,
                    0x6F, 0x29, 0xC9, 0x98, 0xDD, 0xD9, 0xBF
                ]
            )
            .unwrap()
        );
        sequoia_openpgp::Fingerprint::from_bytes(
            6,
            &[
                0xB2, 0xE9, 0x61, 0x75, 0x3E, 0xCE, 0x0B, 0x34, 0x5E, 0x71, 0x8E, 0x74, 0xBA, 0x6F,
                0x29, 0xC9, 0x98, 0xDD, 0xD9, 0xBF, 0xB2, 0xE9, 0x61, 0x75, 0x3E, 0xCE, 0x0B, 0x34,
                0x5E, 0x71, 0x8E, 0x74,
            ],
        )
        .unwrap();
        assert_eq!(
            Fingerprint::from_str(
                "B2E9 6175 3ECE 0B34 5E71 8E74 BA6F 29C9 98DD D9BF B2E9 6175 3ECE 0B34 5E71 8E74"
            )
            .unwrap()
            .0,
            sequoia_openpgp::Fingerprint::from_bytes(
                6,
                &[
                    0xB2, 0xE9, 0x61, 0x75, 0x3E, 0xCE, 0x0B, 0x34, 0x5E, 0x71, 0x8E, 0x74, 0xBA,
                    0x6F, 0x29, 0xC9, 0x98, 0xDD, 0xD9, 0xBF, 0xB2, 0xE9, 0x61, 0x75, 0x3E, 0xCE,
                    0x0B, 0x34, 0x5E, 0x71, 0x8E, 0x74
                ]
            )
            .unwrap()
        );
        // Passing an empty string should fail.
        assert!(Fingerprint::from_str("").is_err());
        // Short, fingerprint-like values should fail.
        assert!(Fingerprint::from_str("aaa").is_err());
        assert!(Fingerprint::from_str("aaaa").is_err());
    }

    #[test]
    fn test_userids() {
        let policy = ValidCertPolicy::default();
        // Test that a Cert with a single valid UserID returns a single value.
        let (cert, _sig) = CertBuilder::general_purpose(Some(VALID_USER_ID1))
            .generate()
            .unwrap();
        assert_eq!(cert.userids().len(), 1);
        assert_eq!(
            Cert(cert).validate(&policy).unwrap().userids(),
            vec![VALID_USER_ID1]
        );

        // Test that a Cert with 2 valid UserIDs returns a vector of 2 values.
        let (cert, _sig) = CertBuilder::general_purpose(Some(VALID_USER_ID1))
            .add_userid(VALID_USER_ID2)
            .generate()
            .unwrap();
        assert_eq!(cert.userids().len(), 2);
        assert_eq!(
            Cert(cert).validate(&policy).unwrap().userids(),
            vec![VALID_USER_ID1, VALID_USER_ID2]
        );

        // Test that a Cert with no UserID returns an empty vector.
        let (cert, _sig) = CertBuilder::general_purpose(None::<UserID>)
            .generate()
            .unwrap();
        let empty_vec: Vec<String> = Vec::new();
        assert_eq!(cert.userids().len(), 0);
        assert_eq!(Cert(cert).validate(&policy).unwrap().userids(), empty_vec);

        // Test that a Cert with an invalid (non-self-signed) UserID returns
        // an empty vector.
        let (cert, _sig) = CertBuilder::general_purpose(None::<UserID>)
            .generate()
            .unwrap();
        let invalid_user: UserID = INVALID_USER_ID.into();
        let (cert, changed) = cert.insert_packets(invalid_user).unwrap();
        assert!(changed);
        assert_eq!(cert.userids().len(), 1);
        assert_eq!(Cert(cert).validate(&policy).unwrap().userids(), empty_vec);

        // Test that a Cert with one valid and one invalid (non-self-signed)
        // UserID returns only the valid UserID.
        let (cert, _sig) = CertBuilder::general_purpose(Some(VALID_USER_ID1))
            .generate()
            .unwrap();
        let invalid_user: UserID = INVALID_USER_ID.into();
        let (cert, changed) = cert.insert_packets(invalid_user).unwrap();
        assert!(changed);
        assert_eq!(cert.userids().len(), 2);
        assert_eq!(
            Cert(cert).validate(&policy).unwrap().userids(),
            vec![VALID_USER_ID1]
        );

        // Test that a Cert with only an invalid UserID returns an error.
        let future_time = std::time::SystemTime::now() + std::time::Duration::from_secs(60);
        let (cert, _) = CertBuilder::new()
            .set_creation_time(future_time)
            .add_userid(INVALID_USER_ID)
            .generate()
            .unwrap();
        assert_eq!(cert.userids().len(), 1);
        assert!(Cert(cert).validate(&policy).is_err());
    }

    const PUB: &[u8] =
        include_bytes!("../../tests/data/B2E961753ECE0B345E718E74BA6F29C998DDD9BF.pub");
    const SEC: &[u8] =
        include_bytes!("../../tests/data/B2E961753ECE0B345E718E74BA6F29C998DDD9BF.sec");
    #[test]
    fn test_export_public_cert_to_bytes_works() {
        let cert = Cert::from_bytes(PUB).unwrap();
        let exported_cert: Vec<u8> = cert.public().try_into().unwrap();
        let reimported_cert = Cert::from_bytes(&exported_cert).unwrap();
        assert_eq!(reimported_cert, cert);
    }

    #[test]
    fn test_export_public_cert_to_ascii_armored_works() {
        let cert = Cert::from_bytes(PUB).unwrap();
        let exported_cert = serde_json::to_string(&cert.public()).unwrap();
        let reimported_cert =
            Cert::from_bytes(serde_json::from_str::<String>(&exported_cert).unwrap()).unwrap();
        assert_eq!(reimported_cert, cert);
    }

    #[test]
    fn test_export_secret_cert_to_bytes_works() {
        let cert = Cert::from_bytes(SEC).unwrap();
        let exported_cert: Vec<u8> = cert.secret().unwrap().try_into().unwrap();
        let reimported_cert = Cert::from_bytes(&exported_cert).unwrap();
        assert_eq!(reimported_cert, cert);
    }

    #[test]
    fn test_export_secret_cert_to_ascii_armored_works() {
        let cert = Cert::from_bytes(SEC).unwrap();
        let exported_cert = serde_json::to_string(&cert.secret().unwrap()).unwrap();
        let reimported_cert =
            Cert::from_bytes(serde_json::from_str::<String>(&exported_cert).unwrap()).unwrap();
        assert_eq!(reimported_cert, cert);
    }

    #[test]
    fn test_export_public_part_of_cert_to_bytes_strips_secret_part() {
        let public = Cert::from_bytes(PUB).unwrap();
        let cert = Cert::from_bytes(SEC).unwrap();
        let exported_cert: Vec<u8> = cert.public().try_into().unwrap();
        let reimported_cert = Cert::from_bytes(&exported_cert).unwrap();
        assert_eq!(reimported_cert, public);
    }

    #[test]
    fn test_export_public_part_of_cert_to_ascii_armored_strips_secret_part() {
        let public = Cert::from_bytes(PUB).unwrap();
        let cert = Cert::from_bytes(SEC).unwrap();
        let exported_cert = serde_json::to_string(&cert.public()).unwrap();
        let reimported_cert =
            Cert::from_bytes(serde_json::from_str::<String>(&exported_cert).unwrap()).unwrap();
        assert_eq!(reimported_cert, public);
    }

    #[test]
    fn test_export_secret_part_of_public_cert_fails() {
        let public = Cert::from_bytes(PUB).unwrap();
        assert!(public.secret().is_err());
    }

    const MATCHING_REV_SIG: &[u8] =
        include_bytes!("../../tests/data/B2E961753ECE0B345E718E74BA6F29C998DDD9BF.rev");
    const NON_MATCHING_REV_SIG: &[u8] =
        include_bytes!("../../tests/data/1EA0292ECBF2457CADAE20E2B94FA6A56D9FA1FB.rev");

    fn assert_cert_gets_revoked(revocation_certificate: &str) {
        let public = Cert::from_bytes(PUB).unwrap();
        let revoked_cert = public.revoke(std::io::Cursor::new(revocation_certificate));
        assert!(
            matches!(
                revoked_cert.map(|cert| cert.revocation_status()),
                Ok(RevocationStatus::Revoked(_))
            ),
            "The certificate RevocationStatus should now be revoked"
        );
    }

    #[test]
    fn test_revoke_cert_with_matching_signature_succeeds() {
        let revocation_certificate = std::str::from_utf8(MATCHING_REV_SIG).unwrap();
        assert_cert_gets_revoked(revocation_certificate);
    }

    /// Same test as above, but adding some non-relevant text into the
    /// revocation certificate.
    #[test]
    fn test_revoke_cert_with_correct_signature_and_junk_succeeds() {
        let revocation_certificate = format!(
            "# Some comments\n{}\n\nA suffix.\n-----BEGIN PGP SIGNATURE-----",
            std::str::from_utf8(MATCHING_REV_SIG).unwrap()
        );
        assert_cert_gets_revoked(&revocation_certificate);
    }

    /// Same test as above, but with multiple signatures in the revocation
    /// certificate.
    #[test]
    fn test_revoke_cert_with_matching_and_non_matching_signatures_succeeds() {
        let revocation_certificate = format!(
            "# Matching:\n{}\n\n# Non-matching\n{}",
            std::str::from_utf8(MATCHING_REV_SIG).unwrap(),
            std::str::from_utf8(NON_MATCHING_REV_SIG).unwrap(),
        );
        assert_cert_gets_revoked(&revocation_certificate);
    }

    fn assert_cert_revocation_fails(
        revocation_certificate: &str,
        expected_err: error::RevocationError,
    ) {
        let public = Cert::from_bytes(PUB).unwrap();
        let revoked_cert = public.revoke(std::io::Cursor::new(revocation_certificate));
        match revoked_cert.unwrap_err() {
            PgpError::CertError(error::CertError::RevocationError(error)) => {
                assert_eq!(error, expected_err)
            }
            other => panic!("Expected {expected_err}, got: {other:?}"),
        }
    }

    #[test]
    fn test_revoke_cert_with_a_wrong_signature_fails() {
        let revocation_certificate = std::str::from_utf8(NON_MATCHING_REV_SIG).unwrap();
        assert_cert_revocation_fails(
            revocation_certificate,
            error::RevocationError::WrongSignature,
        );
    }

    #[test]
    fn test_revoke_cert_with_empty_signature_fails() {
        let revocation_certificate = "";
        assert_cert_revocation_fails(revocation_certificate, error::RevocationError::NoSignature);
    }

    #[test]
    fn test_revoke_cert_with_not_a_signature_fails() {
        let revocation_certificate = "not a valid signature";
        assert_cert_revocation_fails(revocation_certificate, error::RevocationError::NoSignature);
    }

    #[test]
    fn test_revoke_cert_with_not_a_signature_fails_2() {
        let revocation_certificate = "-----BEGIN PGP SIGNATURE-----\n
            not a valid signature\n
            -----END PGP SIGNATURE-----";
        assert_cert_revocation_fails(
            revocation_certificate,
            error::RevocationError::ParsingError("Malformed packet: Truncated packet".to_string()),
        );
    }
}