sequoia-net 0.32.0

Network services for OpenPGP
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
//! Discovering and publishing OpenPGP certificates over the network.
//!
//! This crate provides access to keyservers using the [HKP] protocol,
//! and searching and publishing [Web Key Directories].
//!
//! Additionally the `pks` module exposes private key operations using
//! the [PKS][PKS] protocol.
//!
//! [HKP]: https://tools.ietf.org/html/draft-shaw-openpgp-hkp-00
//! [Web Key Directories]: https://datatracker.ietf.org/doc/html/draft-koch-openpgp-webkey-service
//! [PKS]: https://gitlab.com/wiktor/pks
//!
//! # HTTP Client
//!
//! To use this create, you need to select an HTTP client.  Currently,
//! this library supports [`rewqest`] and [`isahc`], which you can
//! enable select using the `reqwest` and `isahc` features,
//! respectively.  Alternatively, you can bring your own HTTP client
//! by implementing the [`HttpClient`] trait and passing that to the
//! various functions.
//!
//! [`rewqest`]: https://crates.io/crates/reqwest
//! [`isahc`]: https://crates.io/crates/isahc
//!
//! # Examples
//!
//! This example demonstrates how to fetch a certificate from the
//! default key server:
//!
//! ```no_run
//! # use sequoia_openpgp::KeyID;
//! # use sequoia_net::{KeyServer, Result};
//! # #[cfg(any(feature = "reqwest", feature = "isahc"))]
//! # async fn f() -> Result<()> {
//! let mut ks = KeyServer::default();
//! let keyid: KeyID = "31855247603831FD".parse()?;
//! println!("{:?}", ks.get(keyid).await?);
//! # Ok(())
//! # }
//! ```
//!
//! This example demonstrates how to fetch a certificate using WKD:
//!
//! ```no_run
//! # #[cfg(any(feature = "reqwest", feature = "isahc"))]
//! # async fn f() -> sequoia_net::Result<()> {
//! let certs = sequoia_net::wkd::get("juliett@example.org").await?;
//! # Ok(()) }
//! ```

#![doc(html_favicon_url = "https://docs.sequoia-pgp.org/favicon.png")]
#![doc(html_logo_url = "https://docs.sequoia-pgp.org/logo.svg")]
#![warn(missing_docs)]

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

use async_trait::async_trait;

// Re-exports of crates that we use in our API.

#[cfg(feature = "isahc")]
pub use isahc;
#[cfg(feature = "reqwest")]
pub use reqwest;

use percent_encoding::{percent_encode, AsciiSet, CONTROLS};

use url::Url;

use sequoia_openpgp::{
    self as openpgp,
    cert::{Cert, CertParser},
    KeyHandle,
    packet::UserID,
    parse::Parse,
    serialize::Serialize,
};

#[macro_use] mod macros;
pub mod dane;
mod email;
pub mod updates;
pub mod wkd;

/// <https://url.spec.whatwg.org/#fragment-percent-encode-set>
const KEYSERVER_ENCODE_SET: &AsciiSet =
    // Formerly DEFAULT_ENCODE_SET
    &CONTROLS.add(b' ').add(b'"').add(b'#').add(b'<').add(b'>').add(b'`')
    .add(b'?').add(b'{').add(b'}')
    // The SKS keyserver as of version 1.1.6 is a bit picky with
    // respect to the encoding.
    .add(b'-').add(b'+').add(b'/');
/// Encoding set for HTTP/GET requests
///
/// This expands KEYSERVER_ENCODE_SET by '&', '=' and '%'.
const KEYSERVER_GET_ENCODE_SET: &AsciiSet = &KEYSERVER_ENCODE_SET
    // add chars to protect the key/value structure in a HTTP/GET.
    .add(b'&').add(b'=')
    // as '%' has a special meaning, it needs to also be encoded.
    .add(b'%');

/// For accessing keyservers using HKP.
#[derive(Clone)]
pub struct KeyServer {
    client: Arc<dyn HttpClient>,
    /// The original URL given to the constructor.
    url: Url,
    /// The URL we use for the requests.
    request_url: Url,
    /// The HttpClientOptions to use.
    options: HttpClientOptions,
}

assert_send_and_sync!(KeyServer);

#[cfg(any(feature = "reqwest", feature = "isahc"))]
impl Default for KeyServer {
    fn default() -> Self {
	Self::new("hkps://keys.openpgp.org/").unwrap()
    }
}

impl KeyServer {
    #[allow(unreachable_code)]
    #[cfg(any(feature = "reqwest", feature = "isahc"))]
    /// Returns a handle for the given URL.
    pub fn new(url: &str) -> Result<Self> {
        #[cfg(feature = "reqwest")]
        {
            return Self::with_client(url, Box::new(reqwest::Client::new()));
        }
        #[cfg(feature = "isahc")]
        {
            Self::with_client(url, Box::new(isahc::HttpClient::new()?))
        }
    }

    /// Returns a handle for the given URL with a custom `Client`.
    pub fn with_client(url: &str, client: Box<dyn HttpClient>) -> Result<Self> {
        let client = client.into();
        let url = Url::parse(url)?;

        let s = url.scheme();
        match s {
            "hkp" => (),
            "hkps" => (),
            _ => return Err(Error::MalformedUrl.into()),
        }

        let request_url =
            format!("{}://{}:{}",
                    match s {"hkp" => "http", "hkps" => "https",
                             _ => unreachable!()},
                    url.host().ok_or(Error::MalformedUrl)?,
                    match s {
                        "hkp" => url.port().or(Some(11371)),
                        "hkps" => url.port().or(Some(443)),
                        _ => unreachable!(),
                    }.unwrap()).parse()?;

        let options = HttpClientOptions::certificate();

        Ok(KeyServer { client, url, request_url, options })
    }

    /// Overrides the HTTP client options.
    ///
    /// By default, `KeyServer` uses an instance of
    /// [`HttpClientOptions::certificate`].
    pub fn options(&mut self, options: HttpClientOptions) {
        self.options = options;
    }

    /// Returns the keyserver's base URL.
    pub fn url(&self) -> &Url {
        &self.url
    }

    /// Retrieves the certificate with the given handle.
    ///
    /// # Warning
    ///
    /// Returned certificates must be mistrusted, and be carefully
    /// interpreted under a policy and trust model.
    pub async fn get<H: Into<KeyHandle>>(&self, handle: H)
                                         -> Result<Vec<Result<Cert>>>
    {
        let handle = handle.into();
        let url = self.request_url.join(&format!(
            "pks/lookup?op=get&options=mr&search=0x{:X}",
            handle
        ))?;

        let body = self.client.get(&self.options, url).await?;
        let certs = CertParser::from_bytes(&body)?.collect();
        Ok(certs)
    }

    /// Retrieves certificates containing the given `UserID`.
    ///
    /// If the given [`UserID`] does not follow the de facto
    /// conventions for userids, or it does not contain a email
    /// address, an error is returned.
    ///
    ///   [`UserID`]: sequoia_openpgp::packet::UserID
    ///
    /// # Warning
    ///
    /// Returned certificates must be mistrusted, and be carefully
    /// interpreted under a policy and trust model.
    pub async fn search<U: Into<UserID>>(&self, userid: U)
                                         -> Result<Vec<Result<Cert>>>
    {
        let userid = userid.into();
        let email = userid.email().and_then(|addr| addr.ok_or_else(||
            openpgp::Error::InvalidArgument(
                "UserID does not contain an email address".into()).into()))?;
        let url = self.request_url.join(
            &format!("pks/lookup?op=get&options=mr&search={}",
                percent_encode(email.as_bytes(), KEYSERVER_GET_ENCODE_SET)
            ))?;

        let body = self.client.get(&self.options, url).await?;
        let certs = CertParser::from_bytes(&body)?.collect();
        Ok(certs)
    }

    /// Sends the given key to the server.
    pub async fn send(&self, key: &Cert) -> Result<()> {
        use sequoia_openpgp::armor::{Writer, Kind};

        let url = self.request_url.join("pks/add")?;
        let mut w =  Writer::new(Vec::new(), Kind::PublicKey)?;
        key.serialize(&mut w)?;

        let armored_blob = w.finalize()?;

        // Prepare to send url-encoded data.
        let mut post_data = b"keytext=".to_vec();
        post_data.extend_from_slice(percent_encode(&armored_blob, KEYSERVER_ENCODE_SET)
                                    .collect::<String>().as_bytes());

        self
            .client
            .post(&self.options, url, post_data)
            .await

    }
}

/// Results for sequoia-net.
pub type Result<T> = ::std::result::Result<T, anyhow::Error>;

#[derive(thiserror::Error, Debug)]
/// Errors returned from the network routines.
#[non_exhaustive]
pub enum Error {
    /// A requested cert was not found.
    #[error("Cert not found")]
    NotFound,
    /// A given keyserver URL was malformed.
    #[error("Malformed URL; expected hkp: or hkps:")]
    MalformedUrl,
    /// The server provided malformed data.
    #[error("Malformed response from server")]
    MalformedResponse,
    /// A communication partner violated the protocol.
    #[error("Protocol violation")]
    ProtocolViolation,
    /// Encountered an unexpected low-level http status.
    #[error("server returned status {0}")]
    HttpStatus(http::StatusCode),
    /// A `url::ParseError` occurred.
    #[error(transparent)]
    UrlError(#[from] url::ParseError),
    /// A `http::Error` occurred.
    #[error(transparent)]
    HttpError(#[from] http::Error),

    /// wkd errors:
    /// An email address is malformed
    #[error("Malformed email address {0}")]
    MalformedEmail(String),

    /// An email address was not found in Cert userids.
    #[error("Email address {0} not found in Cert's userids")]
    EmailNotInUserids(String),

    /// The server's response exceeded the threshold.
    #[error("Server's response exceeded threshold ({} bytes)", .0)]
    ResponseTooLarge(u64),

    /// The file or the directory containing it is a symbolic link.
    ///
    /// Note: on Unix we enforce this on the file using `O_NOFOLLOW`,
    /// which means that the error will be
    /// `IoError(std::io::ErrorKind::FilesystemLoop)`.
    #[error("Files and directories in the certificate directory must not \
             be symbolic links ({})",
            .0.display())]
    SymbolicLink(PathBuf),
}

/// Helper trait to encapsulate different HTTP clients.
///
/// An implementation must respect the options in `HttpClientOptions`.
#[async_trait]
pub trait HttpClient: Send + Sync {
    /// Submit a standard GET request and return the response.
    async fn get(&'_ self, options: &HttpClientOptions, url: Url)
        -> Result<Vec<u8>>;
    /// Submit a standard POST request of `Content-Type` equal to "application/x-www-form-urlencoded".
    async fn post(&'_ self, options: &HttpClientOptions,
                  url: Url, post_data: Vec<u8>)
        -> Result<()>;
}

/// A generous size limit to use fetching a certificate from a key
/// server or a WKD.
///
/// Note: a WKD may have a couple of certificates, e.g., a v4 and a v6
/// certificate as well as some revocation certificates.  This limit
/// takes that into consideration.
///
/// As a reference, the [debian keyring] as shipped with Debian Trixie
/// (released 2025) is 30 MB and contains 936 certificates.
///
/// [debian keyring]: https://packages.debian.org/trixie/debian-keyring
pub const CERTIFICATE_LIMIT: u64 = 8 * 1024 * 1024;

/// Options for the `HttpClient`.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct HttpClientOptions {
    /// The download limit.
    pub limit: Option<u64>,
}

impl HttpClientOptions {
    /// Returns a set of relaxed options.
    ///
    /// The options do not impose a download limit.
    pub fn unconstrained() -> Self {
        HttpClientOptions {
            limit: None,
        }
    }

    /// Returns options that are appropriate for downloading a few
    /// certificates.
    ///
    /// The download limit is set to [`CERTIFICATE_LIMIT`], which is a
    /// generous size limit for fetching a certificate from a key
    /// server or a WKD.
    pub fn certificate() -> Self {
        Self::unconstrained().limit(CERTIFICATE_LIMIT)
    }

    /// Sets the download limit.
    ///
    /// If a download exceeds the specified number of bytes, the
    /// download is aborted.
    ///
    /// If `limit` is `None`, then no limit is enforced.
    pub fn limit<L>(self, limit: L) -> Self
    where
        L: Into<Option<u64>>
    {
        HttpClientOptions {
            limit: limit.into(),
        }
    }
}

#[cfg(feature = "reqwest")]
#[async_trait]
impl HttpClient for reqwest::Client {
    async fn get(&'_ self, options: &HttpClientOptions, url: Url)
        -> Result<Vec<u8>>
    {
        use futures_util::StreamExt;

        let res = self.get(url).send().await?;
        match res.status() {
            http::StatusCode::OK => {
                let mut stream = res.bytes_stream();
                let mut buffer = Vec::new();
                while let Some(bytes) = stream.next().await {
                    buffer.extend_from_slice(&bytes?);
                    if let Some(&limit) = options.limit.as_ref() {
                        if buffer.len() as u64 > limit {
                            return Err(Error::ResponseTooLarge(limit).into());
                        }
                    }
                }

                Ok(buffer)
            }
            http::StatusCode::NOT_FOUND => Err(Error::NotFound.into()),
            n => Err(Error::HttpStatus(n).into()),
        }
    }

    async fn post(&'_ self, _options: &HttpClientOptions,
                  url: Url, post_data: Vec<u8>)
        -> Result<()>
    {
        let res = self
            .post(url)
            .header("content-type", "application/x-www-form-urlencoded")
            .header("content-length", post_data.len().to_string())
            .body(post_data)
            .send()
            .await?;

        match res.status() {
            http::StatusCode::OK => Ok(()),
            http::StatusCode::NOT_FOUND => Err(Error::ProtocolViolation.into()),
            n => Err(Error::HttpStatus(n).into()),
        }
    }
}

#[cfg(feature = "isahc")]
#[async_trait]
impl HttpClient for isahc::HttpClient {
    async fn get(&'_ self, options: &HttpClientOptions, url: Url)
        -> Result<Vec<u8>>
    {
        use futures::io::AsyncReadExt;

        use isahc::AsyncBody;

        let res = self.get_async(url.as_str()).await?;
        match res.status() {
            http::StatusCode::OK => {
                let mut output = Vec::new();
                let mut body: AsyncBody = res.into_body();
                if let Some(&limit) = options.limit.as_ref() {
                    body.take(limit.saturating_add(1))
                        .read_to_end(&mut output).await?;
                    if output.len() as u64 > limit {
                        return Err(Error::ResponseTooLarge(limit).into());
                    }
                } else {
                    body.read_to_end(&mut output).await?;
                }
                Ok(output)
            },
            http::StatusCode::NOT_FOUND => Err(Error::NotFound.into()),
            n => Err(Error::HttpStatus(n).into()),
        }
    }

    async fn post(&'_ self, _options: &HttpClientOptions,
                  url: Url, post_data: Vec<u8>)
        -> Result<()>
    {
        let request = isahc::Request::post(url.as_str())
            .header("Content-Type", "application/x-www-form-urlencoded")
            .header("Content-Length", post_data.len().to_string())
            .body(post_data)?;
        let res = self.send_async(request).await?;

        match res.status() {
            http::StatusCode::OK => Ok(()),
            http::StatusCode::NOT_FOUND => Err(Error::ProtocolViolation.into()),
            n => Err(Error::HttpStatus(n).into()),
        }
    }
}

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

    #[cfg(any(feature = "reqwest", feature = "isahc"))]
    #[test]
    fn urls() {
        assert!(KeyServer::new("keys.openpgp.org").is_err());
        assert!(KeyServer::new("hkp://keys.openpgp.org").is_ok());
        assert!(KeyServer::new("hkps://keys.openpgp.org").is_ok());
    }

    #[test]
    fn encoding() {
        assert_eq!(
            percent_encode(b"alice@example.com",
                           KEYSERVER_GET_ENCODE_SET)
                .collect::<String>(),
            "alice@example.com"
        );
        assert_eq!(
            percent_encode(b"alice+tag@example.com",
                           KEYSERVER_GET_ENCODE_SET)
                .collect::<String>(),
            "alice%2Btag@example.com"
        );
        assert_eq!(
            percent_encode(b"alice+tag&role=admin%@example.com",
                           KEYSERVER_GET_ENCODE_SET)
                .collect::<String>(),
            "alice%2Btag%26role%3Dadmin%25@example.com"
        );

    }
}