Skip to content

polling for challenge ready and certs with timeout and retry-after #104

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ aws-lc-rs = { version = "1.8.0", optional = true }
base64 = "0.22"
bytes = "1"
http = "1"
httpdate = "1.0"
http-body = "1"
http-body-util = "0.1.2"
hyper = { version = "1.3.1", features = ["client", "http1", "http2"], optional = true }
Expand Down
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,13 @@ fn nonce_from_response(rsp: &BytesResponse) -> Option<String> {
.and_then(|hv| String::from_utf8(hv.as_ref().to_vec()).ok())
}

fn retry_after_from_response(rsp: &BytesResponse) -> Option<String> {
rsp.parts
.headers
.get(RETRY_AFTER)
.and_then(|header_value| String::from_utf8(header_value.as_ref().to_vec()).ok())
}

#[cfg(feature = "hyper-rustls")]
struct DefaultClient(HyperClient<hyper_rustls::HttpsConnector<HttpConnector>, Full<Bytes>>);

Expand Down Expand Up @@ -320,6 +327,7 @@ mod crypto {

const JOSE_JSON: &str = "application/jose+json";
const REPLAY_NONCE: &str = "Replay-Nonce";
const RETRY_AFTER: &str = "Retry-After";

#[cfg(test)]
mod tests {
Expand Down
89 changes: 88 additions & 1 deletion src/order.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::types::{
Authorization, AuthorizationState, AuthorizationStatus, AuthorizedIdentifier, Challenge,
ChallengeType, Empty, FinalizeRequest, OrderState, OrderStatus, Problem,
};
use crate::{Error, Key, crypto, nonce_from_response};
use crate::{Error, Key, crypto, nonce_from_response, retry_after_from_response};

/// An ACME order as described in RFC 8555 (section 7.1.3)
///
Expand Down Expand Up @@ -194,6 +194,93 @@ impl Order {
Ok(&self.state)
}

/// Poll the order with timeout until in a final state
///
/// Refresh the order state from the server with a timeout `timeout`.
/// If a server sets the Retry-After header for rate-limiting access to the CA, the
/// provided value is used for polling as long as it fits into the boxed timeout window.
///
/// Yields the [`OrderStatus`] immediately if `Ready` or `Invalid`.
pub async fn wait_ready(&mut self, timeout: Duration) -> Result<OrderStatus, Error> {
self.wait_status_internal(timeout, &[OrderStatus::Ready, OrderStatus::Invalid])
.await
}

/// Wait for certificate with timeout
///
/// Query the issued certificate from the server with a timeout `timeout`.
/// If a server sets the Retry-After header for rate-limiting access to the CA, the
/// provided value is used for polling as long as it fits into the boxed timeout window.
///
/// Yields the certificate for the order.
pub async fn wait_certificate(&mut self, timeout: Duration) -> Result<Option<String>, Error> {
let _ = self
.wait_status_internal(timeout, &[OrderStatus::Valid, OrderStatus::Invalid])
.await?;
self.certificate().await
}

async fn wait_status_internal(
&mut self,
timeout: Duration,
order_states: &[OrderStatus],
) -> Result<OrderStatus, Error> {
let started = std::time::Instant::now();

// Yields the order status immediately if Ready or Invalid.
let mut next_retry = Duration::from_secs(0);

// This is the same retry fallback as ACME4J
let fallback_retry = Duration::from_secs(3);

let boxed = started + timeout;

loop {
sleep(next_retry).await;

let rsp = self
.account
.post(None::<&Empty>, self.nonce.take(), &self.url)
.await?;

self.nonce = nonce_from_response(&rsp);

next_retry = fallback_retry;

// Should retry_after become a member of Order that is updated in refresh()?

if let Some(retry_after) = retry_after_from_response(&rsp) {
if let Ok(retry_after_datetime) = httpdate::parse_http_date(&retry_after) {
if let Ok(next_duration) =
retry_after_datetime.duration_since(std::time::SystemTime::now())
{
next_retry = next_duration;
}
} else if let Ok(retry_after_seconds) = retry_after.parse::<u64>() {
next_retry = Duration::from_secs(retry_after_seconds);
}
}

self.state = Problem::check::<OrderState>(rsp).await?;

if order_states.contains(&self.state.status) {
return Ok(self.state.status);
};

let now = std::time::Instant::now();

if now > boxed {
break;
}

if now + next_retry > boxed {
next_retry = boxed - now;
}
}

Ok(self.state.status)
}

/// Extract the URL and last known state from the `Order`
pub fn into_parts(self) -> (String, OrderState) {
(self.url, self.state)
Expand Down
Loading