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
//! # PGP native module
//!
//! This module contains the native PGP backend.

use log::debug;
pub use pgp::native::{SignedPublicKey, SignedSecretKey};
use secret::{keyring::KeyringEntry, Secret};
use shellexpand_utils::shellexpand_path;
use std::{collections::HashSet, path::PathBuf};

use crate::{Error, Result};

/// The native PGP secret key source.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[cfg_attr(
    feature = "derive",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "kebab-case")
)]
pub enum NativePgpSecretKey {
    #[default]
    None,

    /// The native PGP secret key is given as it is (raw).
    #[cfg_attr(feature = "derive", serde(skip))]
    Raw(SignedSecretKey),

    /// The native PGP secret key is located at the given path.
    Path(PathBuf),

    /// The native PGP secret key is located in the user's global
    /// keyring at the given entry.
    Keyring(KeyringEntry),
}

impl NativePgpSecretKey {
    // FIXME: use the recipient from the template instead of the PGP
    // config. This can be done once the `pgp` module can manage both
    // secret and public keys.
    pub async fn get(&self, recipient: impl ToString) -> Result<SignedSecretKey> {
        let recipient = recipient.to_string();
        match self {
            Self::None => Ok(Err(Error::GetNativePgpSecretKeyNoneError(
                recipient.clone(),
            ))?),
            Self::Raw(skey) => Ok(skey.clone()),
            Self::Path(path) => {
                let path = shellexpand_path(path);
                let skey = pgp::read_skey_from_file(path)
                    .await
                    .map_err(Error::ReadNativePgpSecretKeyError)?;
                Ok(skey)
            }
            Self::Keyring(entry) => {
                let data = entry
                    .get_secret()
                    .await
                    .map_err(Error::GetPgpSecretKeyFromKeyringError)?;
                let skey = pgp::read_skey_from_string(data)
                    .await
                    .map_err(Error::ReadNativePgpSecretKeyError)?;
                Ok(skey)
            }
        }
    }
}

/// The native PGP public key resolver.
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(
    feature = "derive",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "kebab-case")
)]
pub enum NativePgpPublicKeysResolver {
    /// The given email string is associated with the given raw public
    /// key.
    #[cfg_attr(feature = "derive", serde(skip))]
    Raw(String, SignedPublicKey),

    /// The public key is resolved using the Web Key Directory
    /// protocol.
    Wkd,

    /// The public key is resolved using the given key servers.
    ///
    /// Supported protocols: `http(s)://`, `hkp(s)://`.
    KeyServers(Vec<String>),
}

/// The native PGP backend.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[cfg_attr(
    feature = "derive",
    derive(serde::Serialize, serde::Deserialize),
    serde(rename_all = "kebab-case")
)]
pub struct NativePgp {
    /// The secret key of the sender.
    pub secret_key: NativePgpSecretKey,

    /// The passphrase associated to the secret key.
    pub secret_key_passphrase: Secret,

    /// The list of public key resolvers.
    pub public_keys_resolvers: Vec<NativePgpPublicKeysResolver>,
}

impl NativePgp {
    /// Encrypts the given plain bytes using the given recipients.
    pub async fn encrypt(
        &self,
        emails: impl IntoIterator<Item = String>,
        data: Vec<u8>,
    ) -> Result<Vec<u8>> {
        let mut pkeys = Vec::new();
        let mut recipients: HashSet<String> = HashSet::from_iter(emails.into_iter());

        for resolver in &self.public_keys_resolvers {
            match resolver {
                NativePgpPublicKeysResolver::Raw(recipient, pkey) => {
                    if recipients.remove(recipient) {
                        debug!("found pgp public key for {recipient} using raw pair");
                        pkeys.push(pkey.clone())
                    }
                }
                NativePgpPublicKeysResolver::Wkd => {
                    let recipients_clone = recipients.clone().into_iter().collect();
                    let wkd_pkeys = pgp::wkd::get_all(recipients_clone).await;

                    pkeys.extend(wkd_pkeys.into_iter().fold(
                        Vec::new(),
                        |mut pkeys, (ref recipient, res)| {
                            match res {
                                Ok(pkey) => {
                                    if recipients.remove(recipient) {
                                        debug!("found pgp public key for {recipient} using wkd");
                                        pkeys.push(pkey);
                                    }
                                }
                                Err(err) => {
                                    let msg = format!("cannot find pgp public key for {recipient}");
                                    debug!("{msg} using wkd: {err}");
                                    debug!("{err:?}");
                                }
                            }
                            pkeys
                        },
                    ));
                }
                NativePgpPublicKeysResolver::KeyServers(key_servers) => {
                    let recipients_clone = recipients.clone().into_iter().collect();
                    let http_pkeys =
                        pgp::http::get_all(recipients_clone, key_servers.to_owned()).await;

                    pkeys.extend(http_pkeys.into_iter().fold(
                        Vec::default(),
                        |mut pkeys, (ref recipient, res)| {
                            match res {
                                Ok(pkey) => {
                                    if recipients.remove(recipient) {
                                        let msg = format!("found pgp public key for {recipient}");
                                        debug!("{msg} using key servers");
                                        pkeys.push(pkey);
                                    }
                                }
                                Err(err) => {
                                    let msg = format!("cannot find pgp public key for {recipient}");
                                    debug!("{msg} using key servers: {err}");
                                    debug!("{err:?}");
                                }
                            }
                            pkeys
                        },
                    ));
                }
            }

            if recipients.is_empty() {
                break;
            }
        }

        let data = pgp::encrypt(pkeys, data)
            .await
            .map_err(Error::EncryptNativePgpError)?;

        Ok(data)
    }

    /// Decrypts the given encrypted bytes using the given recipient.
    pub async fn decrypt(&self, email: impl ToString, data: Vec<u8>) -> Result<Vec<u8>> {
        let skey = self.secret_key.get(email).await?;
        let passphrase = self
            .secret_key_passphrase
            .get()
            .await
            .map_err(Error::GetSecretKeyPassphraseFromKeyringError)?;
        let data = pgp::decrypt(skey, passphrase, data)
            .await
            .map_err(Error::DecryptNativePgpError)?;
        Ok(data)
    }

    /// Signs the given plain bytes using the given recipient.
    pub async fn sign(&self, email: impl ToString, data: Vec<u8>) -> Result<Vec<u8>> {
        let skey = self.secret_key.get(email).await?;
        let passphrase = self
            .secret_key_passphrase
            .get()
            .await
            .map_err(Error::GetSecretKeyPassphraseFromKeyringError)?;
        let data = pgp::sign(skey, passphrase, data)
            .await
            .map_err(Error::SignNativePgpError)?;
        Ok(data)
    }

    /// Verifies the given signed bytes as well as the signature bytes
    /// using the given recipient.
    pub async fn verify(&self, email: impl AsRef<str>, sig: Vec<u8>, data: Vec<u8>) -> Result<()> {
        let email = email.as_ref();
        let mut pkey_found = None;

        for resolver in &self.public_keys_resolvers {
            match resolver {
                NativePgpPublicKeysResolver::Raw(recipient, pkey) => {
                    if recipient == email {
                        debug!("found pgp public key for {recipient} using raw pair");
                        pkey_found = Some(pkey.clone());
                        break;
                    } else {
                        continue;
                    }
                }
                NativePgpPublicKeysResolver::Wkd => {
                    let pkey = pgp::wkd::get_one(email.to_owned()).await;
                    match pkey {
                        Ok(pkey) => {
                            debug!("found pgp public key for {email} using wkd");
                            pkey_found = Some(pkey);
                            break;
                        }
                        Err(err) => {
                            let msg = format!("cannot find pgp public key for {email}");
                            debug!("{msg} using wkd: {err}");
                            debug!("{err:?}");
                            continue;
                        }
                    }
                }
                NativePgpPublicKeysResolver::KeyServers(key_servers) => {
                    let pkey = pgp::http::get_one(email.to_owned(), key_servers.clone()).await;
                    match pkey {
                        Ok(pkey) => {
                            debug!("found pgp public key for {email} using key servers");
                            pkey_found = Some(pkey);
                            break;
                        }
                        Err(err) => {
                            let msg = format!("cannot find pgp public key for {email}");
                            debug!("{msg} using key servers: {err}");
                            debug!("{err:?}");
                            continue;
                        }
                    }
                }
            }
        }

        let pkey = pkey_found.ok_or(Error::FindPgpPublicKeyError(email.to_owned()))?;
        let sig = pgp::read_sig_from_bytes(sig)
            .await
            .map_err(Error::ReadNativePgpSignatureError)?;
        pgp::verify(pkey, sig, data)
            .await
            .map_err(Error::VerifyNativePgpSignatureError)?;

        Ok(())
    }
}