Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
228 changes: 186 additions & 42 deletions src/certificates/acme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,135 @@ impl HttpClient {
}
}

async fn connect_stream(
url: &url::Url,
tls: &Arc<rustls::ClientConfig>,
) -> io::Result<Box<dyn crate::async_stream::AsyncStream>> {
let host = url
.host_str()
.ok_or_else(|| invalid("ACME URL has no host"))?
.trim_matches(['[', ']']);
let location = crate::address::NetLocation::new(
crate::address::Address::from(host)?,
url.port_or_known_default().unwrap(),
);
let addresses = crate::resolver::Resolver::resolve_location(
&crate::resolver::NativeResolver::new(),
&location,
)
.await?;
let mut stream = None;
for address in addresses.into_iter().take(8) {
let socket = crate::socket_util::new_tcp_socket(None, address.is_ipv6())?;
if let Ok(Ok(connected)) =
tokio::time::timeout(Duration::from_secs(5), socket.connect(address)).await
{
stream = Some(connected);
break;
}
}
let stream = stream.ok_or_else(|| io::Error::other("ACME connection failed"))?;
if url.scheme() == "https" {
let name = rustls::pki_types::ServerName::try_from(host.to_owned())
.map_err(|_| invalid("invalid ACME TLS hostname"))?;
let connection = rustls::ClientConnection::new(tls.clone(), name)
.map_err(io::Error::other)?;
Ok(Box::new(
crate::crypto::CryptoTlsStream::handshake(
stream,
crate::crypto::TlsConnection::new(connection),
crate::crypto::TlsReadMode::Stream,
&[],
)
.await?,
))
} else {
Ok(Box::new(stream))
}
}

#[derive(Serialize)]
struct AcmeDnsPayload<'a> {
subdomain: &'a str,
txt: &'a str,
}

pub(super) async fn update_acme_dns(
tls: Arc<rustls::ClientConfig>,
server_url: &str,
username: &str,
password: &str,
subdomain: &str,
txt: &str,
) -> io::Result<()> {
let mut url = validate_url(server_url)?;
if url.query().is_some() {
return Err(invalid("ACME-DNS server_url must not contain a query string"));
}
url.path_segments_mut()
.map_err(|()| invalid("invalid ACME-DNS server_url"))?
.pop_if_empty();
if url.path_segments().and_then(|mut s| s.next_back()) != Some("update") {
url.path_segments_mut()
.map_err(|()| invalid("invalid ACME-DNS server_url"))?
.push("update");
}
let authority = url[url::Position::BeforeHost..url::Position::AfterPort].to_owned();
let path_and_query = url.path().to_owned();

let payload = serde_json::to_vec(&AcmeDnsPayload { subdomain, txt })
.map_err(|e| io::Error::other(format!("failed to serialize ACME-DNS payload: {e}")))?;

let request = http::Request::builder()
.method("POST")
.uri(path_and_query)
.header(http::header::HOST, authority)
.header("X-Api-User", username)
.header("X-Api-Key", password)
.header(http::header::CONTENT_TYPE, "application/json")
.header(http::header::CONNECTION, "close")
.body(Full::new(Bytes::from(payload)))
.map_err(|e| io::Error::other(format!("failed to build ACME-DNS request: {e}")))?;

tokio::time::timeout(REQUEST_TIMEOUT, async {
let stream = connect_stream(&url, &tls).await?;
let (mut sender, connection) = hyper::client::conn::http1::Builder::new()
.max_buf_size(32 * 1024)
.handshake(hyper_util::rt::TokioIo::new(stream))
.await
.map_err(io::Error::other)?;
let response = async {
let response = sender
.send_request(request)
.await
.map_err(io::Error::other)?;
let (parts, body) = response.into_parts();
Limited::new(body, MAX_RESPONSE)
.collect()
.await
.map_err(|_| io::Error::other("ACME-DNS response failed or exceeded limit"))?;
// Never log the remote body; the status is enough to diagnose.
if !parts.status.is_success() {
return Err(io::Error::other(format!(
"ACME-DNS update returned HTTP {}",
parts.status
)));
}
Ok::<_, io::Error>(())
};
tokio::pin!(response, connection);
tokio::select! {
result = &mut response => result,
result = &mut connection => {
result.map_err(io::Error::other)?;
response.await
}
}
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "ACME-DNS request timed out"))?
}

impl instant_acme::HttpClient for HttpClient {
fn request(
&self,
Expand All @@ -238,47 +367,7 @@ impl instant_acme::HttpClient for HttpClient {
"ACME HTTPS directory cannot downgrade to HTTP endpoints",
));
}
let host = url
.host_str()
.ok_or_else(|| invalid("ACME URL has no host"))?
.trim_matches(['[', ']']);
let location = crate::address::NetLocation::new(
crate::address::Address::from(host)?,
url.port_or_known_default().unwrap(),
);
let addresses = crate::resolver::Resolver::resolve_location(
&crate::resolver::NativeResolver::new(),
&location,
)
.await?;
let mut stream = None;
for address in addresses.into_iter().take(8) {
let socket = crate::socket_util::new_tcp_socket(None, address.is_ipv6())?;
if let Ok(Ok(connected)) =
tokio::time::timeout(Duration::from_secs(5), socket.connect(address)).await
{
stream = Some(connected);
break;
}
}
let stream = stream.ok_or_else(|| io::Error::other("ACME connection failed"))?;
let stream: Box<dyn crate::async_stream::AsyncStream> = if url.scheme() == "https" {
let name = rustls::pki_types::ServerName::try_from(host.to_owned())
.map_err(|_| invalid("invalid ACME TLS hostname"))?;
let connection = rustls::ClientConnection::new(client.tls.clone(), name)
.map_err(io::Error::other)?;
Box::new(
crate::crypto::CryptoTlsStream::handshake(
stream,
crate::crypto::TlsConnection::new(connection),
crate::crypto::TlsReadMode::Stream,
&[],
)
.await?,
)
} else {
Box::new(stream)
};
let stream = connect_stream(&url, &client.tls).await?;
let authority = request
.uri()
.authority()
Expand Down Expand Up @@ -1070,6 +1159,7 @@ impl Scheduler {
deadline: tokio::time::Instant,
) -> Result<(), Failure> {
let client = self.client(config)?;
let mut dns_published = false;
let mut authorizations = order.authorizations();
loop {
let (authorization, response) = client
Expand Down Expand Up @@ -1098,9 +1188,10 @@ impl Scheduler {
});
}
Self::defer_hint(config, state, response)?;
let kind = match config.challenge {
let kind = match &config.challenge {
ChallengeConfig::Http01 { .. } => ChallengeType::Http01,
ChallengeConfig::TlsAlpn01 => ChallengeType::TlsAlpn01,
ChallengeConfig::AcmeDns { .. } => ChallengeType::Dns01,
};
let mut challenge =
authorization
Expand Down Expand Up @@ -1138,6 +1229,30 @@ impl Scheduler {
return Err(instant_acme::Error::Str("CA returned invalid challenge token").into());
}
let authorization = challenge.key_authorization();
if let ChallengeConfig::AcmeDns {
server_url,
username,
password,
subdomain,
..
} = &config.challenge
{
// Publish every TXT value now; challenges are marked ready after one shared wait below.
if challenge.status == ChallengeStatus::Pending {
update_acme_dns(
client_tls(None).map_err(|error| instant_acme::Error::Other(Box::new(error)))?,
server_url,
username,
&password.0,
subdomain,
&authorization.dns_value(),
)
.await
.map_err(|error| instant_acme::Error::Other(Box::new(error)))?;
dns_published = true;
}
continue;
}
let tls = if kind == ChallengeType::TlsAlpn01 {
Some(
challenge::tls_config(&domain, authorization.digest().as_ref())
Expand All @@ -1162,6 +1277,35 @@ impl Scheduler {
Self::defer_hint(config, state, response)?;
}
}
if dns_published {
if let ChallengeConfig::AcmeDns {
propagation_delay: Some(delay),
..
} = &config.challenge
{
let wake = tokio::time::Instant::now() + Duration::from_secs(*delay);
tokio::time::sleep_until(wake.min(deadline)).await;
}
let mut authorizations = order.authorizations();
loop {
let (authorization, response) = client
.perform(deadline, async { authorizations.next().await.transpose() })
.await?;
let Some(mut authorization) = authorization else {
break;
};
if authorization.status != AuthorizationStatus::Pending {
continue;
}
Self::defer_hint(config, state, response)?;
if let Some(mut challenge) = authorization.challenge(ChallengeType::Dns01)
&& challenge.status == ChallengeStatus::Pending
{
let ((), response) = client.perform(deadline, challenge.set_ready()).await?;
Self::defer_hint(config, state, response)?;
}
}
}
Ok(())
}
}
Expand Down
Loading
Loading