Skip to main content

sequoia_net/
lib.rs

1//! Discovering and publishing OpenPGP certificates over the network.
2//!
3//! This crate provides access to keyservers using the [HKP] protocol,
4//! and searching and publishing [Web Key Directories].
5//!
6//! Additionally the `pks` module exposes private key operations using
7//! the [PKS][PKS] protocol.
8//!
9//! [HKP]: https://tools.ietf.org/html/draft-shaw-openpgp-hkp-00
10//! [Web Key Directories]: https://datatracker.ietf.org/doc/html/draft-koch-openpgp-webkey-service
11//! [PKS]: https://gitlab.com/wiktor/pks
12//!
13//! # HTTP Client
14//!
15//! To use this create, you need to select an HTTP client.  Currently,
16//! this library supports [`rewqest`] and [`isahc`], which you can
17//! enable select using the `reqwest` and `isahc` features,
18//! respectively.  Alternatively, you can bring your own HTTP client
19//! by implementing the [`HttpClient`] trait and passing that to the
20//! various functions.
21//!
22//! [`rewqest`]: https://crates.io/crates/reqwest
23//! [`isahc`]: https://crates.io/crates/isahc
24//!
25//! # Examples
26//!
27//! This example demonstrates how to fetch a certificate from the
28//! default key server:
29//!
30//! ```no_run
31//! # use sequoia_openpgp::KeyID;
32//! # use sequoia_net::{KeyServer, Result};
33//! # #[cfg(any(feature = "reqwest", feature = "isahc"))]
34//! # async fn f() -> Result<()> {
35//! let mut ks = KeyServer::default();
36//! let keyid: KeyID = "31855247603831FD".parse()?;
37//! println!("{:?}", ks.get(keyid).await?);
38//! # Ok(())
39//! # }
40//! ```
41//!
42//! This example demonstrates how to fetch a certificate using WKD:
43//!
44//! ```no_run
45//! # #[cfg(any(feature = "reqwest", feature = "isahc"))]
46//! # async fn f() -> sequoia_net::Result<()> {
47//! let certs = sequoia_net::wkd::get("juliett@example.org").await?;
48//! # Ok(()) }
49//! ```
50
51#![doc(html_favicon_url = "https://docs.sequoia-pgp.org/favicon.png")]
52#![doc(html_logo_url = "https://docs.sequoia-pgp.org/logo.svg")]
53#![warn(missing_docs)]
54
55use std::sync::Arc;
56
57// Re-exports of crates that we use in our API.
58
59#[cfg(feature = "isahc")]
60pub use isahc;
61#[cfg(feature = "reqwest")]
62pub use reqwest;
63
64use percent_encoding::{percent_encode, AsciiSet, CONTROLS};
65
66use url::Url;
67
68use sequoia_openpgp::{
69    self as openpgp,
70    cert::{Cert, CertParser},
71    KeyHandle,
72    packet::UserID,
73    parse::Parse,
74    serialize::Serialize,
75};
76
77#[macro_use] mod macros;
78pub mod dane;
79mod email;
80pub mod updates;
81pub mod wkd;
82
83/// <https://url.spec.whatwg.org/#fragment-percent-encode-set>
84const KEYSERVER_ENCODE_SET: &AsciiSet =
85    // Formerly DEFAULT_ENCODE_SET
86    &CONTROLS.add(b' ').add(b'"').add(b'#').add(b'<').add(b'>').add(b'`')
87    .add(b'?').add(b'{').add(b'}')
88    // The SKS keyserver as of version 1.1.6 is a bit picky with
89    // respect to the encoding.
90    .add(b'-').add(b'+').add(b'/');
91/// Encoding set for HTTP/GET requests
92///
93/// This expands KEYSERVER_ENCODE_SET by '&', '=' and '%'.
94const KEYSERVER_GET_ENCODE_SET: &AsciiSet = &KEYSERVER_ENCODE_SET
95    // add chars to protect the key/value structure in a HTTP/GET.
96    .add(b'&').add(b'=')
97    // as '%' has a special meaning, it needs to also be encoded.
98    .add(b'%');
99
100/// For accessing keyservers using HKP.
101#[derive(Clone)]
102pub struct KeyServer {
103    client: Arc<dyn HttpClient>,
104    /// The original URL given to the constructor.
105    url: Url,
106    /// The URL we use for the requests.
107    request_url: Url,
108}
109
110assert_send_and_sync!(KeyServer);
111
112#[cfg(any(feature = "reqwest", feature = "isahc"))]
113impl Default for KeyServer {
114    fn default() -> Self {
115	Self::new("hkps://keys.openpgp.org/").unwrap()
116    }
117}
118
119impl KeyServer {
120    #[allow(unreachable_code)]
121    #[cfg(any(feature = "reqwest", feature = "isahc"))]
122    /// Returns a handle for the given URL.
123    pub fn new(url: &str) -> Result<Self> {
124        #[cfg(feature = "reqwest")]
125        {
126            return Self::with_client(url, Box::new(reqwest::Client::new()));
127        }
128        #[cfg(feature = "isahc")]
129        {
130            Self::with_client(url, Box::new(isahc::HttpClient::new()?))
131        }
132    }
133
134    /// Returns a handle for the given URL with a custom `Client`.
135    pub fn with_client(url: &str, client: Box<dyn HttpClient>) -> Result<Self> {
136        let client = client.into();
137        let url = Url::parse(url)?;
138
139        let s = url.scheme();
140        match s {
141            "hkp" => (),
142            "hkps" => (),
143            _ => return Err(Error::MalformedUrl.into()),
144        }
145
146        let request_url =
147            format!("{}://{}:{}",
148                    match s {"hkp" => "http", "hkps" => "https",
149                             _ => unreachable!()},
150                    url.host().ok_or(Error::MalformedUrl)?,
151                    match s {
152                        "hkp" => url.port().or(Some(11371)),
153                        "hkps" => url.port().or(Some(443)),
154                        _ => unreachable!(),
155                    }.unwrap()).parse()?;
156
157        Ok(KeyServer { client, url, request_url })
158    }
159
160    /// Returns the keyserver's base URL.
161    pub fn url(&self) -> &Url {
162        &self.url
163    }
164
165    /// Retrieves the certificate with the given handle.
166    ///
167    /// # Warning
168    ///
169    /// Returned certificates must be mistrusted, and be carefully
170    /// interpreted under a policy and trust model.
171    pub async fn get<H: Into<KeyHandle>>(&self, handle: H)
172                                         -> Result<Vec<Result<Cert>>>
173    {
174        let handle = handle.into();
175        let url = self.request_url.join(&format!(
176            "pks/lookup?op=get&options=mr&search=0x{:X}",
177            handle
178        ))?;
179
180        let body = Box::into_pin(self.client.get(url)).await?;
181        let certs = CertParser::from_bytes(&body)?.collect();
182        Ok(certs)
183    }
184
185    /// Retrieves certificates containing the given `UserID`.
186    ///
187    /// If the given [`UserID`] does not follow the de facto
188    /// conventions for userids, or it does not contain a email
189    /// address, an error is returned.
190    ///
191    ///   [`UserID`]: sequoia_openpgp::packet::UserID
192    ///
193    /// # Warning
194    ///
195    /// Returned certificates must be mistrusted, and be carefully
196    /// interpreted under a policy and trust model.
197    pub async fn search<U: Into<UserID>>(&self, userid: U)
198                                         -> Result<Vec<Result<Cert>>>
199    {
200        let userid = userid.into();
201        let email = userid.email().and_then(|addr| addr.ok_or_else(||
202            openpgp::Error::InvalidArgument(
203                "UserID does not contain an email address".into()).into()))?;
204        let url = self.request_url.join(
205            &format!("pks/lookup?op=get&options=mr&search={}",
206                percent_encode(email.as_bytes(), KEYSERVER_GET_ENCODE_SET)
207            ))?;
208
209        let body = Box::into_pin(self.client.get(url)).await?;
210        let certs = CertParser::from_bytes(&body)?.collect();
211        Ok(certs)
212    }
213
214    /// Sends the given key to the server.
215    pub async fn send(&self, key: &Cert) -> Result<()> {
216        use sequoia_openpgp::armor::{Writer, Kind};
217
218        let url = self.request_url.join("pks/add")?;
219        let mut w =  Writer::new(Vec::new(), Kind::PublicKey)?;
220        key.serialize(&mut w)?;
221
222        let armored_blob = w.finalize()?;
223
224        // Prepare to send url-encoded data.
225        let mut post_data = b"keytext=".to_vec();
226        post_data.extend_from_slice(percent_encode(&armored_blob, KEYSERVER_ENCODE_SET)
227                                    .collect::<String>().as_bytes());
228
229        Box::into_pin(self
230            .client
231            .post(url, post_data))
232            .await
233
234    }
235}
236
237/// Results for sequoia-net.
238pub type Result<T> = ::std::result::Result<T, anyhow::Error>;
239
240#[derive(thiserror::Error, Debug)]
241/// Errors returned from the network routines.
242#[non_exhaustive]
243pub enum Error {
244    /// A requested cert was not found.
245    #[error("Cert not found")]
246    NotFound,
247    /// A given keyserver URL was malformed.
248    #[error("Malformed URL; expected hkp: or hkps:")]
249    MalformedUrl,
250    /// The server provided malformed data.
251    #[error("Malformed response from server")]
252    MalformedResponse,
253    /// A communication partner violated the protocol.
254    #[error("Protocol violation")]
255    ProtocolViolation,
256    /// Encountered an unexpected low-level http status.
257    #[error("server returned status {0}")]
258    HttpStatus(http::StatusCode),
259    /// A `url::ParseError` occurred.
260    #[error(transparent)]
261    UrlError(#[from] url::ParseError),
262    /// A `http::Error` occurred.
263    #[error(transparent)]
264    HttpError(#[from] http::Error),
265
266    /// wkd errors:
267    /// An email address is malformed
268    #[error("Malformed email address {0}")]
269    MalformedEmail(String),
270
271    /// An email address was not found in Cert userids.
272    #[error("Email address {0} not found in Cert's userids")]
273    EmailNotInUserids(String),
274}
275
276/// Helper trait to encapsulate different HTTP clients.
277pub trait HttpClient: Send + Sync {
278    /// Submit a standard GET request and return the response.
279    fn get(&'_ self, url: Url) -> Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + '_>;
280    /// Submit a standard POST request of `Content-Type` equal to "application/x-www-form-urlencoded".
281    fn post(&'_ self, url: Url, post_data: Vec<u8>) -> Box<dyn std::future::Future<Output = Result<()>> + Send + '_>;
282}
283
284#[cfg(feature = "reqwest")]
285impl HttpClient for reqwest::Client {
286    fn get(&'_ self, url: Url) -> Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + '_> {
287        Box::new(async {
288            let res = self.get(url).send().await?;
289            match res.status() {
290                http::StatusCode::OK => {
291                    Ok(res.bytes().await?.to_vec())
292                }
293                http::StatusCode::NOT_FOUND => Err(Error::NotFound.into()),
294                n => Err(Error::HttpStatus(n).into()),
295            }
296        })
297    }
298
299    fn post(&'_ self, url: Url, post_data: Vec<u8>) -> Box<dyn std::future::Future<Output = Result<()>> + Send + '_> {
300        Box::new(async {
301            let res = self
302                .post(url)
303                .header("content-type", "application/x-www-form-urlencoded")
304                .header("content-length", post_data.len().to_string())
305                .body(post_data)
306                .send()
307                .await?;
308
309            match res.status() {
310                http::StatusCode::OK => Ok(()),
311                http::StatusCode::NOT_FOUND => Err(Error::ProtocolViolation.into()),
312                n => Err(Error::HttpStatus(n).into()),
313            }
314        })
315    }
316}
317
318#[cfg(feature = "isahc")]
319impl HttpClient for isahc::HttpClient {
320    fn get(
321        &'_ self,
322        url: Url,
323    ) -> Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + '_> {
324        use isahc::AsyncReadResponseExt;
325        Box::new(async move {
326            let mut res = self.get_async(url.as_str()).await?;
327            match res.status() {
328                http::StatusCode::OK => Ok(res.bytes().await?.to_vec()),
329                http::StatusCode::NOT_FOUND => Err(Error::NotFound.into()),
330                n => Err(Error::HttpStatus(n).into()),
331            }
332        })
333    }
334
335    fn post(
336        &'_ self,
337        url: Url,
338        post_data: Vec<u8>,
339    ) -> Box<dyn std::future::Future<Output = Result<()>> + Send + '_> {
340        Box::new(async move {
341            let request = isahc::Request::post(url.as_str())
342                .header("Content-Type", "application/x-www-form-urlencoded")
343                .header("Content-Length", post_data.len().to_string())
344                .body(post_data)?;
345            let res = self.send_async(request).await?;
346
347            match res.status() {
348                http::StatusCode::OK => Ok(()),
349                http::StatusCode::NOT_FOUND => Err(Error::ProtocolViolation.into()),
350                n => Err(Error::HttpStatus(n).into()),
351            }
352        })
353    }
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    #[cfg(any(feature = "reqwest", feature = "isahc"))]
361    #[test]
362    fn urls() {
363        assert!(KeyServer::new("keys.openpgp.org").is_err());
364        assert!(KeyServer::new("hkp://keys.openpgp.org").is_ok());
365        assert!(KeyServer::new("hkps://keys.openpgp.org").is_ok());
366    }
367
368    #[test]
369    fn encoding() {
370        assert_eq!(
371            percent_encode(b"alice@example.com",
372                           KEYSERVER_GET_ENCODE_SET)
373                .collect::<String>(),
374            "alice@example.com"
375        );
376        assert_eq!(
377            percent_encode(b"alice+tag@example.com",
378                           KEYSERVER_GET_ENCODE_SET)
379                .collect::<String>(),
380            "alice%2Btag@example.com"
381        );
382        assert_eq!(
383            percent_encode(b"alice+tag&role=admin%@example.com",
384                           KEYSERVER_GET_ENCODE_SET)
385                .collect::<String>(),
386            "alice%2Btag%26role%3Dadmin%25@example.com"
387        );
388
389    }
390}