use openssl::sha::sha256;
use std::sync::Arc;
use std::thread;
use std::{convert::TryInto, time::Duration};
use crate::acc::AccountInner;
use crate::acc::AcmeKey;
use crate::api::{ApiAuth, ApiChallenge, ApiEmptyObject, ApiEmptyString};
use crate::error;
use crate::jwt::*;
use crate::util::{base64url, read_json};
#[derive(Debug)]
pub struct Auth {
inner: Arc<AccountInner>,
api_auth: ApiAuth,
auth_url: String,
}
impl Auth {
pub(crate) async fn new(inner: &Arc<AccountInner>, api_auth: ApiAuth, auth_url: &str) -> Self {
Auth {
inner: inner.clone(),
api_auth,
auth_url: auth_url.into(),
}
}
pub async fn domain_name(&self) -> &str {
&self.api_auth.identifier.value
}
pub async fn need_challenge(&self) -> bool {
!self.api_auth.is_status_valid()
}
pub async fn http_challenge(&self) -> Option<Challenge<Http>> {
let chall = self.api_auth.http_challenge()?;
Some(Challenge::new(&self.inner, chall.clone(), &self.auth_url).await)
}
pub async fn dns_challenge(&self) -> Option<Challenge<Dns>> {
let chall = self.api_auth.dns_challenge()?;
Some(Challenge::new(&self.inner, chall.clone(), &self.auth_url).await)
}
pub async fn tls_alpn_challenge(&self) -> Option<Challenge<TlsAlpn>> {
let chall = self.api_auth.tls_alpn_challenge()?;
Some(Challenge::new(&self.inner, chall.clone(), &self.auth_url).await)
}
pub async fn api_auth(&self) -> &ApiAuth {
&self.api_auth
}
}
#[doc(hidden)]
pub struct Http;
#[doc(hidden)]
pub struct Dns;
#[doc(hidden)]
pub struct TlsAlpn;
pub struct Challenge<A> {
inner: Arc<AccountInner>,
api_challenge: ApiChallenge,
auth_url: String,
_ph: std::marker::PhantomData<A>,
}
impl Challenge<Http> {
pub async fn http_token(&self) -> &str {
&self.api_challenge.token
}
pub async fn http_proof(&self) -> Result<String, error::Error> {
let acme_key = self.inner.transport.acme_key().await;
let proof = key_authorization(&self.api_challenge.token, acme_key, false).await?;
Ok(proof)
}
}
impl Challenge<Dns> {
pub async fn dns_proof(&self) -> Result<String, error::Error> {
let acme_key = self.inner.transport.acme_key().await;
let proof = key_authorization(&self.api_challenge.token, acme_key, true).await?;
Ok(proof)
}
}
impl Challenge<TlsAlpn> {
pub async fn tls_alpn_proof(&self) -> Result<[u8; 32], error::Error> {
let acme_key = self.inner.transport.acme_key().await;
let proof = key_authorization(&self.api_challenge.token, acme_key, false).await?;
Ok(sha256(proof.as_bytes()))
}
}
impl<A> Challenge<A> {
async fn new(inner: &Arc<AccountInner>, api_challenge: ApiChallenge, auth_url: &str) -> Self {
Challenge {
inner: inner.clone(),
api_challenge,
auth_url: auth_url.into(),
_ph: std::marker::PhantomData,
}
}
pub async fn need_validate(&self) -> bool {
self.api_challenge.is_status_pending()
}
pub async fn validate(&self, delay: Duration) -> Result<(), error::Error> {
let url_chall = &self.api_challenge.url;
let res = self
.inner
.transport
.call(url_chall, &ApiEmptyObject)
.await?;
let _: ApiChallenge = read_json(res).await?;
let auth = wait_for_auth_status(&self.inner, &self.auth_url, delay).await?;
if !auth.is_status_valid() {
let error = auth
.challenges
.iter()
.filter_map(|c| c.error.as_ref())
.next();
let reason = if let Some(error) = error {
format!(
"Failed: {}",
error.detail.clone().unwrap_or_else(|| error._type.clone())
)
} else {
"Validation failed and no error found".into()
};
return Err(error::Error::LetsEncryptError(format!(
"Validation failed: {:?}",
reason
)));
}
Ok(())
}
pub async fn api_challenge(&self) -> &ApiChallenge {
&self.api_challenge
}
}
async fn key_authorization(
token: &str,
key: &AcmeKey,
extra_sha256: bool,
) -> Result<String, error::Error> {
let jwk: Jwk = key.try_into()?;
let jwk_thumb: JwkThumb = (&jwk).into();
let jwk_json = serde_json::to_string(&jwk_thumb)?;
let digest = base64url(&sha256(jwk_json.as_bytes()));
let key_auth = format!("{}.{}", token, digest);
let res = if extra_sha256 {
base64url(&sha256(key_auth.as_bytes()))
} else {
key_auth
};
Ok(res)
}
async fn wait_for_auth_status(
inner: &Arc<AccountInner>,
auth_url: &str,
delay: Duration,
) -> Result<ApiAuth, error::Error> {
let auth = loop {
let res = inner.transport.call(auth_url, &ApiEmptyString).await?;
let auth: ApiAuth = read_json(res).await?;
if !auth.is_status_pending() {
break auth;
}
thread::sleep(delay);
};
Ok(auth)
}
#[cfg(test)]
mod test {
use crate::*;
#[tokio::test]
async fn test_get_challenges() -> Result<(), error::Error> {
let server = crate::test::with_directory_server();
let url = DirectoryUrl::Other(&server.dir_url);
let dir = Directory::from_url(url).await?;
let acc = dir
.register_account(vec!["mailto:foo@bar.com".to_string()])
.await?;
let ord = acc.new_order("acmetest.example.com", &[]).await?;
let authz = ord.authorizations().await?;
assert!(authz.len() == 1);
let auth = &authz[0];
{
let http = auth.http_challenge().await.unwrap();
assert!(http.need_validate().await);
}
{
let dns = auth.dns_challenge().await.unwrap();
assert!(dns.need_validate().await);
}
Ok(())
}
}