#![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::sync::Arc;
#[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;
const KEYSERVER_ENCODE_SET: &AsciiSet =
&CONTROLS.add(b' ').add(b'"').add(b'#').add(b'<').add(b'>').add(b'`')
.add(b'?').add(b'{').add(b'}')
.add(b'-').add(b'+').add(b'/');
const KEYSERVER_GET_ENCODE_SET: &AsciiSet = &KEYSERVER_ENCODE_SET
.add(b'&').add(b'=')
.add(b'%');
#[derive(Clone)]
pub struct KeyServer {
client: Arc<dyn HttpClient>,
url: Url,
request_url: Url,
}
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"))]
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()?))
}
}
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()?;
Ok(KeyServer { client, url, request_url })
}
pub fn url(&self) -> &Url {
&self.url
}
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 = Box::into_pin(self.client.get(url)).await?;
let certs = CertParser::from_bytes(&body)?.collect();
Ok(certs)
}
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 = Box::into_pin(self.client.get(url)).await?;
let certs = CertParser::from_bytes(&body)?.collect();
Ok(certs)
}
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()?;
let mut post_data = b"keytext=".to_vec();
post_data.extend_from_slice(percent_encode(&armored_blob, KEYSERVER_ENCODE_SET)
.collect::<String>().as_bytes());
Box::into_pin(self
.client
.post(url, post_data))
.await
}
}
pub type Result<T> = ::std::result::Result<T, anyhow::Error>;
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error("Cert not found")]
NotFound,
#[error("Malformed URL; expected hkp: or hkps:")]
MalformedUrl,
#[error("Malformed response from server")]
MalformedResponse,
#[error("Protocol violation")]
ProtocolViolation,
#[error("server returned status {0}")]
HttpStatus(http::StatusCode),
#[error(transparent)]
UrlError(#[from] url::ParseError),
#[error(transparent)]
HttpError(#[from] http::Error),
#[error("Malformed email address {0}")]
MalformedEmail(String),
#[error("Email address {0} not found in Cert's userids")]
EmailNotInUserids(String),
}
pub trait HttpClient: Send + Sync {
fn get(&'_ self, url: Url) -> Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + '_>;
fn post(&'_ self, url: Url, post_data: Vec<u8>) -> Box<dyn std::future::Future<Output = Result<()>> + Send + '_>;
}
#[cfg(feature = "reqwest")]
impl HttpClient for reqwest::Client {
fn get(&'_ self, url: Url) -> Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + '_> {
Box::new(async {
let res = self.get(url).send().await?;
match res.status() {
http::StatusCode::OK => {
Ok(res.bytes().await?.to_vec())
}
http::StatusCode::NOT_FOUND => Err(Error::NotFound.into()),
n => Err(Error::HttpStatus(n).into()),
}
})
}
fn post(&'_ self, url: Url, post_data: Vec<u8>) -> Box<dyn std::future::Future<Output = Result<()>> + Send + '_> {
Box::new(async {
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")]
impl HttpClient for isahc::HttpClient {
fn get(
&'_ self,
url: Url,
) -> Box<dyn std::future::Future<Output = Result<Vec<u8>>> + Send + '_> {
use isahc::AsyncReadResponseExt;
Box::new(async move {
let mut res = self.get_async(url.as_str()).await?;
match res.status() {
http::StatusCode::OK => Ok(res.bytes().await?.to_vec()),
http::StatusCode::NOT_FOUND => Err(Error::NotFound.into()),
n => Err(Error::HttpStatus(n).into()),
}
})
}
fn post(
&'_ self,
url: Url,
post_data: Vec<u8>,
) -> Box<dyn std::future::Future<Output = Result<()>> + Send + '_> {
Box::new(async move {
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"
);
}
}