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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@ specification.
* Support for external account binding
* Support for certificate revocation
* Support for the [ACME renewal information (ARI)] extension
* Support for the [profiles] extension
* Uses hyper with rustls and Tokio for HTTP requests
* Uses *ring* or aws-lc-rs for ECDSA signing
* Minimum supported Rust version (MSRV): 1.70

[ACME renewal information (ARI)]: https://www.ietf.org/archive/id/draft-ietf-acme-ari-08.html
[profiles]: https://datatracker.ietf.org/doc/draft-aaron-acme-profiles/

## Cargo features

Expand Down
39 changes: 25 additions & 14 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ pub use types::RenewalInfo;
pub use types::{
AccountCredentials, Authorization, AuthorizationState, AuthorizationStatus,
AuthorizedIdentifier, CertificateIdentifier, Challenge, ChallengeType, Error, Identifier,
LetsEncrypt, NewAccount, NewOrder, OrderState, OrderStatus, Problem, RevocationReason,
RevocationRequest, ZeroSsl,
LetsEncrypt, NewAccount, NewOrder, OrderState, OrderStatus, Problem, ProfileMeta,
RevocationReason, RevocationRequest, ZeroSsl,
};
use types::{
DirectoryUrls, Empty, FinalizeRequest, Header, JoseJson, Jwk, KeyOrKeyId, NewAccountPayload,
Directory, Empty, FinalizeRequest, Header, JoseJson, Jwk, KeyOrKeyId, NewAccountPayload,
Signer, SigningAlgorithm,
};

Expand Down Expand Up @@ -582,15 +582,15 @@ impl Account {
.map(|eak| {
JoseJson::new(
Some(&Jwk::new(&key.inner)),
eak.header(None, &client.urls.new_account),
eak.header(None, &client.directory.new_account),
eak,
)
})
.transpose()?,
};

let rsp = client
.post(Some(&payload), None, &key, &client.urls.new_account)
.post(Some(&payload), None, &key, &client.directory.new_account)
.await?;

let account_url = rsp
Expand Down Expand Up @@ -630,13 +630,13 @@ impl Account {
///
/// Returns an [`Order`] instance. Use the [`Order::state()`] method to inspect its state.
pub async fn new_order(&self, order: &NewOrder<'_>) -> Result<Order, Error> {
if order.replaces.is_some() && self.inner.client.urls.renewal_info.is_none() {
if order.replaces.is_some() && self.inner.client.directory.renewal_info.is_none() {
return Err(Error::Unsupported("ACME renewal information (ARI)"));
}

let rsp = self
.inner
.post(Some(order), None, &self.inner.client.urls.new_order)
.post(Some(order), None, &self.inner.client.directory.new_order)
.await?;

let nonce = nonce_from_response(&rsp);
Expand Down Expand Up @@ -694,7 +694,7 @@ impl Account {

/// Revokes a previously issued certificate
pub async fn revoke<'a>(&'a self, payload: &RevocationRequest<'a>) -> Result<(), Error> {
let revoke_url = match self.inner.client.urls.revoke_cert.as_deref() {
let revoke_url = match self.inner.client.directory.revoke_cert.as_deref() {
Some(url) => url,
// This happens because the current account credentials were deserialized from an
// older version which only serialized a subset of the directory URLs. You should
Expand Down Expand Up @@ -726,7 +726,7 @@ impl Account {
&self,
certificate_id: &CertificateIdentifier<'_>,
) -> Result<RenewalInfo, Error> {
let renewal_info_url = match self.inner.client.urls.renewal_info.as_deref() {
let renewal_info_url = match self.inner.client.directory.renewal_info.as_deref() {
Some(url) => url,
None => return Err(Error::Unsupported("ACME renewal information (ARI)")),
};
Expand Down Expand Up @@ -771,6 +771,17 @@ impl Account {
Ok(())
}

/// Yield the profiles supported according to the account's server directory
pub fn profiles(&self) -> impl Iterator<Item = ProfileMeta<'_>> {
self.inner
.client
.directory
.meta
.profiles
.iter()
.map(|(name, description)| ProfileMeta { name, description })
}

/// Get the account ID
pub fn id(&self) -> &str {
&self.inner.id
Expand All @@ -793,7 +804,7 @@ impl AccountInner {
key: Key::from_pkcs8_der(credentials.key_pkcs8.as_ref())?,
client: match (credentials.directory, credentials.urls) {
(Some(server_url), _) => Client::new(&server_url, http).await?,
(None, Some(urls)) => Client { http, urls },
(None, Some(directory)) => Client { http, directory },
(None, None) => return Err("no server URLs found".into()),
},
})
Expand Down Expand Up @@ -839,7 +850,7 @@ impl Signer for AccountInner {

struct Client {
http: Box<dyn HttpClient>,
urls: DirectoryUrls,
directory: Directory,
}

impl Client {
Expand All @@ -852,7 +863,7 @@ impl Client {
let body = rsp.body().await.map_err(Error::Other)?;
Ok(Client {
http,
urls: serde_json::from_slice(&body)?,
directory: serde_json::from_slice(&body)?,
})
}

Expand Down Expand Up @@ -918,7 +929,7 @@ impl Client {

let request = Request::builder()
.method(Method::HEAD)
.uri(&self.urls.new_nonce)
.uri(&self.directory.new_nonce)
.body(Full::default())
.expect("infallible error should not occur");

Expand All @@ -941,7 +952,7 @@ impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Client")
.field("client", &"..")
.field("urls", &self.urls)
.field("directory", &self.directory)
.finish()
}
}
Expand Down
42 changes: 36 additions & 6 deletions src/types.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::borrow::Cow;
use std::fmt;
use std::fmt::Write;
use std::collections::HashMap;
use std::fmt::{self, Write};
use std::net::IpAddr;

use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine};
Expand Down Expand Up @@ -98,7 +98,7 @@ pub struct AccountCredentials {
/// We never serialize `urls` by default, but we support deserializing them
/// in order to support serialized data from older versions of the library.
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) urls: Option<DirectoryUrls>,
pub(crate) urls: Option<Directory>,
}

mod pkcs8_serde {
Expand Down Expand Up @@ -366,6 +366,9 @@ pub struct OrderState {
#[serde(deserialize_with = "deserialize_static_certificate_identifier")]
#[serde(default)]
pub replaces: Option<CertificateIdentifier<'static>>,
/// The profile to be used for the order
#[serde(default)]
pub profile: Option<String>,
}

/// A wrapper for [`AuthorizationState`] as held in the [`OrderState`]
Expand Down Expand Up @@ -408,6 +411,7 @@ pub struct NewOrder<'a> {
pub(crate) replaces: Option<CertificateIdentifier<'a>>,
/// Identifiers to be included in the order
identifiers: &'a [Identifier],
profile: Option<&'a str>,
}

impl<'a> NewOrder<'a> {
Expand All @@ -418,6 +422,7 @@ impl<'a> NewOrder<'a> {
Self {
identifiers,
replaces: None,
profile: None,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think similar to ARI we should also gain a profile: Option<String> field on the OrderState.

That would let NewOrder's that don't specify a profile learn what "default" profile the server assigned their order:

If the server is advertizing profiles and receives a newOrder request which does not identify a specific profile, it is RECOMMENDED that the server select a profile and associate it with the new Order object.

Relatedly, the profiles spec doesn't say the server MUST reflect the matching profile for new order requests that do specify a profile. That's probably good feedback to give to the author. I think ideally we would enforce it matches like for ARI.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The spec isn't specific at all about whether the order state will actually reflect back the selected profile, I think?

Copy link
Collaborator

@cpu cpu Mar 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I think there's language missing to make that crystal clear. I'm partly inferring it based on the registry update ("ACME Order Object Fields") and the accompanying Pebble logic:

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's also similar in the Boulder order JSON

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I couldn't think of a great way to test this.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I think the Pebble test code makes it annoying to get at the order state while also using all the shared logic for completing the order. Seems fine to not test it explicitly for now. I think the spec should be updated to be clearer and then we can check it in the lib.rs code.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The spec isn't specific at all about whether the order state will actually reflect back the selected profile, I think?

@djc It looks like this got addressed in -01 🎉

diff

}
}

Expand All @@ -433,11 +438,20 @@ impl<'a> NewOrder<'a> {
/// present in the certificate being replaced. If the ACME CA does not support the
/// ACME renewal information (ARI) extension, the [crate::Account::new_order()] method will
/// return an error.
pub fn replaces(&mut self, replaces: CertificateIdentifier<'a>) -> &mut Self {
pub fn replaces(mut self, replaces: CertificateIdentifier<'a>) -> Self {
self.replaces = Some(replaces);
self
}

/// Set the profile to be used for the order
///
/// [`Account::new_order()`] will yield an error if the ACME server does not support
/// the profiles extension or if the specified profile is not supported.
pub fn profile(mut self, profile: &'a str) -> Self {
self.profile = Some(profile);
self
}

/// Identifiers to be included in the order
pub fn identifiers(&self) -> &[Identifier] {
self.identifiers
Expand Down Expand Up @@ -517,12 +531,12 @@ pub struct NewAccount<'a> {

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct DirectoryUrls {
pub(crate) struct Directory {
pub(crate) new_nonce: String,
pub(crate) new_account: String,
pub(crate) new_order: String,
// The fields below were added later and old `AccountCredentials` may not have it.
// Newer deserialized account credentials grab a fresh set of `DirectoryUrls` on
// Newer deserialized account credentials grab a fresh set of `Directory` on
// deserialization, so they should be fine. Newer fields should be optional, too.
pub(crate) new_authz: Option<String>,
pub(crate) revoke_cert: Option<String>,
Expand All @@ -531,6 +545,22 @@ pub(crate) struct DirectoryUrls {
//
// <https://www.ietf.org/archive/id/draft-ietf-acme-ari-07.html>
pub(crate) renewal_info: Option<String>,
#[serde(default)]
pub(crate) meta: Meta,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub(crate) struct Meta {
#[serde(default)]
pub(crate) profiles: HashMap<String, String>,
}

/// Profile meta information from the server directory
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug)]
pub struct ProfileMeta<'a> {
pub name: &'a str,
pub description: &'a str,
}

#[derive(Serialize)]
Expand Down
24 changes: 23 additions & 1 deletion tests/pebble.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,12 +232,34 @@ async fn replacement_order() -> Result<(), Box<dyn StdError>> {
assert!(renewal_info.suggested_window.start < OffsetDateTime::now_utc());

// So, let's go ahead and issue a replacement certificate.
env.test::<Http01>(NewOrder::new(&dns_identifiers(names)).replaces(initial_cert_id))
env.test::<Http01>(&NewOrder::new(&dns_identifiers(names)).replaces(initial_cert_id))
.await?;

Ok(())
}

/// Test order profiles
#[cfg(feature = "x509-parser")]
#[tokio::test]
#[ignore]
async fn profiles() -> Result<(), Box<dyn StdError>> {
try_tracing_init();

// Creat an env/initial account
let mut env = Environment::new(EnvironmentConfig::default()).await?;
let identifiers = dns_identifiers(["example.com"]);
let cert = env
.test::<Http01>(&NewOrder::new(&identifiers).profile("shortlived"))
.await?;

let (_, cert) = x509_parser::parse_x509_certificate(cert.as_ref())?;
let validity = cert.validity.time_to_expiration().unwrap();
let default_profile = env.config.pebble.profiles.get("default").unwrap();
assert!(validity < default_profile.validity_period);

Ok(())
}

/// Test that it is possible to deactivate an order's authorizations
#[tokio::test]
#[ignore]
Expand Down
Loading