instant_acme/
types.rs

1use std::borrow::Cow;
2use std::collections::HashMap;
3use std::fmt::{self, Write};
4use std::net::IpAddr;
5use std::time::Instant;
6
7use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine};
8use bytes::Bytes;
9use rustls_pki_types::{CertificateDer, Der, PrivatePkcs8KeyDer};
10use serde::de::{self, DeserializeOwned};
11use serde::ser::SerializeMap;
12use serde::{Deserialize, Serialize};
13use thiserror::Error;
14#[cfg(feature = "time")]
15use time::OffsetDateTime;
16#[cfg(feature = "x509-parser")]
17use x509_parser::extensions::ParsedExtension;
18#[cfg(feature = "x509-parser")]
19use x509_parser::parse_x509_certificate;
20
21use crate::BytesResponse;
22use crate::crypto::{self, KeyPair};
23
24/// Error type for instant-acme
25#[derive(Debug, Error)]
26#[non_exhaustive]
27pub enum Error {
28    /// An JSON problem as returned by the ACME server
29    ///
30    /// RFC 8555 uses problem documents as described in RFC 7807.
31    #[error(transparent)]
32    Api(#[from] Problem),
33    /// Failed from cryptographic operations
34    #[error("cryptographic operation failed")]
35    Crypto,
36    /// Failed to instantiate a private key
37    #[error("invalid key bytes")]
38    KeyRejected,
39    /// HTTP failure
40    #[error("HTTP request failure: {0}")]
41    Http(#[from] http::Error),
42    /// Hyper request failure
43    #[cfg(feature = "hyper-rustls")]
44    #[error("HTTP request failure: {0}")]
45    Hyper(#[from] hyper::Error),
46    /// Invalid ACME server URL
47    #[error("invalid URI: {0}")]
48    InvalidUri(#[from] http::uri::InvalidUri),
49    /// Failed to (de)serialize a JSON object
50    #[error("failed to (de)serialize JSON: {0}")]
51    Json(#[from] serde_json::Error),
52    /// Timed out while waiting for the server to update [`OrderStatus`]
53    ///
54    /// If `Some`, the nested `Instant` indicates when the server suggests to poll next.
55    #[error("timed out waiting for an order update")]
56    Timeout(Option<Instant>),
57    /// ACME server does not support a requested feature
58    #[error("ACME server does not support: {0}")]
59    Unsupported(&'static str),
60    /// Other kind of error
61    #[error(transparent)]
62    Other(Box<dyn std::error::Error + Send + Sync + 'static>),
63    /// Miscellaneous errors
64    #[error("missing data: {0}")]
65    Str(&'static str),
66}
67
68impl Error {
69    #[cfg(feature = "rcgen")]
70    pub(crate) fn from_rcgen(err: rcgen::Error) -> Self {
71        Self::Other(Box::new(err))
72    }
73}
74
75impl From<&'static str> for Error {
76    fn from(s: &'static str) -> Self {
77        Error::Str(s)
78    }
79}
80
81/// ACME account credentials
82///
83/// This opaque type contains the account ID, the private key data and the
84/// server URLs from the relevant ACME server. This can be used to serialize
85/// the account credentials to a file or secret manager and restore the
86/// account from persistent storage.
87#[must_use]
88#[derive(Deserialize, Serialize)]
89pub struct AccountCredentials {
90    pub(crate) id: String,
91    /// Stored in DER, serialized as base64
92    #[serde(with = "pkcs8_serde")]
93    pub(crate) key_pkcs8: PrivatePkcs8KeyDer<'static>,
94    pub(crate) directory: Option<String>,
95    /// We never serialize `urls` by default, but we support deserializing them
96    /// in order to support serialized data from older versions of the library.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub(crate) urls: Option<Directory>,
99}
100
101impl AccountCredentials {
102    /// The account's private key
103    pub fn private_key(&self) -> &PrivatePkcs8KeyDer<'_> {
104        &self.key_pkcs8
105    }
106}
107
108mod pkcs8_serde {
109    use std::fmt;
110
111    use base64::prelude::{BASE64_URL_SAFE_NO_PAD, Engine};
112    use rustls_pki_types::PrivatePkcs8KeyDer;
113    use serde::{Deserializer, Serializer, de};
114
115    pub(crate) fn serialize<S: Serializer>(
116        key_pkcs8: &PrivatePkcs8KeyDer<'_>,
117        serializer: S,
118    ) -> Result<S::Ok, S::Error> {
119        let encoded = BASE64_URL_SAFE_NO_PAD.encode(key_pkcs8.secret_pkcs8_der());
120        serializer.serialize_str(&encoded)
121    }
122
123    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
124        deserializer: D,
125    ) -> Result<PrivatePkcs8KeyDer<'static>, D::Error> {
126        struct Visitor;
127
128        impl de::Visitor<'_> for Visitor {
129            type Value = PrivatePkcs8KeyDer<'static>;
130
131            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
132                formatter.write_str("a base64-encoded PKCS#8 private key")
133            }
134
135            fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
136                match BASE64_URL_SAFE_NO_PAD.decode(v) {
137                    Ok(bytes) => Ok(PrivatePkcs8KeyDer::from(bytes)),
138                    Err(err) => Err(de::Error::custom(err)),
139                }
140            }
141        }
142
143        deserializer.deserialize_str(Visitor)
144    }
145}
146
147/// An RFC 7807 problem document as returned by the ACME server
148#[derive(Clone, Debug, Deserialize)]
149#[serde(rename_all = "camelCase")]
150pub struct Problem {
151    /// One of an enumerated list of problem types
152    ///
153    /// See <https://datatracker.ietf.org/doc/html/rfc8555#section-6.7>
154    pub r#type: Option<String>,
155    /// A human-readable explanation of the problem
156    pub detail: Option<String>,
157    /// The HTTP status code returned for this response
158    pub status: Option<u16>,
159    /// One or more subproblems associated with specific identifiers
160    ///
161    /// See <https://www.rfc-editor.org/rfc/rfc8555#section-6.7.1>
162    #[serde(default)]
163    pub subproblems: Vec<Subproblem>,
164}
165
166impl Problem {
167    pub(crate) async fn check<T: DeserializeOwned>(rsp: BytesResponse) -> Result<T, Error> {
168        Ok(serde_json::from_slice(&Self::from_response(rsp).await?)?)
169    }
170
171    pub(crate) async fn from_response(rsp: BytesResponse) -> Result<Bytes, Error> {
172        let status = rsp.parts.status;
173        let body = rsp.body().await.map_err(Error::Other)?;
174        match status.is_informational() || status.is_success() || status.is_redirection() {
175            true => Ok(body),
176            false => Err(serde_json::from_slice::<Problem>(&body)?.into()),
177        }
178    }
179}
180
181impl fmt::Display for Problem {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        f.write_str("API error")?;
184        if let Some(detail) = &self.detail {
185            write!(f, ": {detail}")?;
186        }
187
188        if let Some(r#type) = &self.r#type {
189            write!(f, " ({type})")?;
190        }
191
192        if !self.subproblems.is_empty() {
193            let count = self.subproblems.len();
194            write!(f, ": {count} subproblems: ")?;
195            for (i, subproblem) in self.subproblems.iter().enumerate() {
196                write!(f, "{subproblem}")?;
197                if i != count - 1 {
198                    f.write_str(", ")?;
199                }
200            }
201        }
202
203        Ok(())
204    }
205}
206
207impl std::error::Error for Problem {}
208
209/// An RFC 8555 subproblem document contained within a problem returned by the ACME server
210///
211/// See <https://www.rfc-editor.org/rfc/rfc8555#section-6.7.1>
212#[derive(Clone, Debug, Deserialize)]
213pub struct Subproblem {
214    /// The identifier associated with this problem
215    pub identifier: Option<Identifier>,
216    /// One of an enumerated list of problem types
217    ///
218    /// See <https://datatracker.ietf.org/doc/html/rfc8555#section-6.7>
219    pub r#type: Option<String>,
220    /// A human-readable explanation of the problem
221    pub detail: Option<String>,
222}
223
224impl fmt::Display for Subproblem {
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        if let Some(identifier) = &self.identifier {
227            write!(f, r#"for "{}""#, identifier.authorized(false))?;
228        }
229
230        if let Some(detail) = &self.detail {
231            write!(f, ": {detail}")?;
232        }
233
234        if let Some(r#type) = &self.r#type {
235            write!(f, " ({type})")?;
236        }
237
238        Ok(())
239    }
240}
241
242#[derive(Debug, Serialize)]
243pub(crate) struct FinalizeRequest {
244    csr: String,
245}
246
247impl FinalizeRequest {
248    pub(crate) fn new(csr_der: &[u8]) -> Self {
249        Self {
250            csr: BASE64_URL_SAFE_NO_PAD.encode(csr_der),
251        }
252    }
253}
254
255#[derive(Debug, Serialize)]
256pub(crate) struct Header<'a> {
257    pub(crate) alg: SigningAlgorithm,
258    #[serde(flatten)]
259    pub(crate) key: KeyOrKeyId<'a>,
260    #[serde(skip_serializing_if = "Option::is_none")]
261    pub(crate) nonce: Option<&'a str>,
262    pub(crate) url: &'a str,
263}
264
265#[derive(Debug, Serialize)]
266pub(crate) enum KeyOrKeyId<'a> {
267    #[serde(rename = "jwk")]
268    Key(Jwk),
269    #[serde(rename = "kid")]
270    KeyId(&'a str),
271}
272
273impl KeyOrKeyId<'_> {
274    pub(crate) fn from_key(key: &crypto::EcdsaKeyPair) -> KeyOrKeyId<'static> {
275        KeyOrKeyId::Key(Jwk::new(key))
276    }
277}
278
279#[derive(Debug, Serialize)]
280pub(crate) struct Jwk {
281    alg: SigningAlgorithm,
282    crv: &'static str,
283    kty: &'static str,
284    r#use: &'static str,
285    x: String,
286    y: String,
287}
288
289impl Jwk {
290    pub(crate) fn new(key: &crypto::EcdsaKeyPair) -> Self {
291        let (x, y) = key.public_key().as_ref()[1..].split_at(32);
292        Self {
293            alg: SigningAlgorithm::Es256,
294            crv: "P-256",
295            kty: "EC",
296            r#use: "sig",
297            x: BASE64_URL_SAFE_NO_PAD.encode(x),
298            y: BASE64_URL_SAFE_NO_PAD.encode(y),
299        }
300    }
301
302    pub(crate) fn thumb_sha256(
303        key: &crypto::EcdsaKeyPair,
304    ) -> Result<crypto::Digest, serde_json::Error> {
305        let jwk = Self::new(key);
306        Ok(crypto::digest(
307            &crypto::SHA256,
308            &serde_json::to_vec(&JwkThumb {
309                crv: jwk.crv,
310                kty: jwk.kty,
311                x: &jwk.x,
312                y: &jwk.y,
313            })?,
314        ))
315    }
316}
317
318#[derive(Debug, Serialize)]
319struct JwkThumb<'a> {
320    crv: &'a str,
321    kty: &'a str,
322    x: &'a str,
323    y: &'a str,
324}
325
326/// An ACME challenge as described in RFC 8555 (section 7.1.5)
327///
328/// <https://datatracker.ietf.org/doc/html/rfc8555#section-7.1.5>
329#[derive(Debug, Deserialize)]
330pub struct Challenge {
331    /// Type of challenge
332    pub r#type: ChallengeType,
333    /// Challenge identifier
334    pub url: String,
335    /// Token for this challenge
336    pub token: String,
337    /// Current status
338    pub status: ChallengeStatus,
339    /// Potential error state
340    pub error: Option<Problem>,
341}
342
343/// Contents of an ACME order as described in RFC 8555 (section 7.1.3)
344///
345/// The order identity will usually be represented by an [Order](crate::Order).
346///
347/// <https://datatracker.ietf.org/doc/html/rfc8555#section-7.1.3>
348#[derive(Debug, Deserialize)]
349#[non_exhaustive]
350#[serde(rename_all = "camelCase")]
351pub struct OrderState {
352    /// Current status
353    pub status: OrderStatus,
354    /// Authorizations for this order.
355    ///
356    /// There should be one authorization per identifier in the order.
357    ///
358    /// Callers will usually interact with an [`AuthorizationHandle`] obtained
359    /// via [`Order::authorizations()`] instead of using this directly.
360    ///
361    /// [`AuthorizationHandle`]: crate::AuthorizationHandle
362    /// [`Order::authorizations()`]: crate::Order::authorizations()
363    pub authorizations: Vec<Authorization>,
364    /// Potential error state
365    pub error: Option<Problem>,
366    /// A finalization URL, to be used once status becomes `Ready`
367    pub finalize: String,
368    /// The certificate URL, which becomes available after finalization
369    pub certificate: Option<String>,
370    /// The certificate that this order is replacing, if any
371    #[serde(deserialize_with = "deserialize_static_certificate_identifier")]
372    #[serde(default)]
373    pub replaces: Option<CertificateIdentifier<'static>>,
374    /// The profile to be used for the order
375    #[serde(default)]
376    pub profile: Option<String>,
377}
378
379/// A wrapper for [`AuthorizationState`] as held in the [`OrderState`]
380///
381/// Callers will usually interact with an [`AuthorizationHandle`] obtained
382/// via [`Order::authorizations()`] instead of using this directly.
383///
384/// [`AuthorizationHandle`]: crate::AuthorizationHandle
385/// [`Order::authorizations()`]: crate::Order::authorizations()
386#[derive(Debug)]
387pub struct Authorization {
388    /// URL for this authorization
389    pub url: String,
390    /// Current state of the authorization
391    ///
392    /// This starts out as `None` when the [`OrderState`] is first deserialized.
393    /// It is populated when the authorization is first fetched from the server,
394    /// typically via [`Order::authorizations()`].
395    ///
396    /// [`Order::authorizations()`]: crate::Order::authorizations()
397    pub state: Option<AuthorizationState>,
398}
399
400impl<'de> Deserialize<'de> for Authorization {
401    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
402        Ok(Self {
403            url: String::deserialize(deserializer)?,
404            state: None,
405        })
406    }
407}
408
409/// Input data for [Order](crate::Order) creation
410///
411/// To be passed into [Account::new_order()](crate::Account::new_order()).
412#[derive(Debug, Serialize)]
413#[serde(rename_all = "camelCase")]
414pub struct NewOrder<'a> {
415    /// The [`CertificateIdentifier`] of a previously issued certificate being replaced by the order
416    #[serde(skip_serializing_if = "Option::is_none")]
417    pub(crate) replaces: Option<CertificateIdentifier<'a>>,
418    /// Identifiers to be included in the order
419    identifiers: &'a [Identifier],
420    #[serde(skip_serializing_if = "Option::is_none")]
421    profile: Option<&'a str>,
422}
423
424impl<'a> NewOrder<'a> {
425    /// Prepare to create a new order for the given identifiers
426    ///
427    /// To be passed into [Account::new_order()](crate::Account::new_order()).
428    pub fn new(identifiers: &'a [Identifier]) -> Self {
429        Self {
430            identifiers,
431            replaces: None,
432            profile: None,
433        }
434    }
435
436    /// Indicate to the ACME server that the `NewOrder` is replacing a previously issued certificate
437    ///
438    /// The previously issued certificate must be identified by a `EncodedCertificateIdentifier`.
439    ///
440    /// Some ACME servers may give preferential rate limits to orders that replace
441    /// existing certificates, or use this information to determine when it is safe
442    /// to revoke a certificate affected by a compliance incident.
443    ///
444    /// When provided, at least one of the `identifiers` for the new order must have been
445    /// present in the certificate being replaced. If the ACME CA does not support the
446    /// ACME renewal information (ARI) extension, the [crate::Account::new_order()] method will
447    /// return an error.
448    pub fn replaces(mut self, replaces: CertificateIdentifier<'a>) -> Self {
449        self.replaces = Some(replaces);
450        self
451    }
452
453    /// Set the profile to be used for the order
454    ///
455    /// [`Account::new_order()`][crate::Account::new_order()] will yield an error if the ACME
456    /// server does not support the profiles extension or if the specified profile is not
457    /// supported.
458    pub fn profile(mut self, profile: &'a str) -> Self {
459        self.profile = Some(profile);
460        self
461    }
462
463    /// Identifiers to be included in the order
464    pub fn identifiers(&self) -> &[Identifier] {
465        self.identifiers
466    }
467}
468
469/// Payload for a certificate revocation request
470/// Defined in <https://datatracker.ietf.org/doc/html/rfc8555#section-7.6>
471#[derive(Debug)]
472pub struct RevocationRequest<'a> {
473    /// The certificate to revoke
474    pub certificate: &'a CertificateDer<'a>,
475    /// Reason for revocation
476    pub reason: Option<RevocationReason>,
477}
478
479impl Serialize for RevocationRequest<'_> {
480    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
481        let base64 = BASE64_URL_SAFE_NO_PAD.encode(self.certificate);
482        let mut map = serializer.serialize_map(Some(2))?;
483        map.serialize_entry("certificate", &base64)?;
484        if let Some(reason) = &self.reason {
485            map.serialize_entry("reason", reason)?;
486        }
487        map.end()
488    }
489}
490
491/// The reason for a certificate revocation
492/// Defined in <https://datatracker.ietf.org/doc/html/rfc5280#section-5.3.1>
493#[allow(missing_docs)]
494#[derive(Debug, Clone)]
495#[repr(u8)]
496pub enum RevocationReason {
497    Unspecified = 0,
498    KeyCompromise = 1,
499    CaCompromise = 2,
500    AffiliationChanged = 3,
501    Superseded = 4,
502    CessationOfOperation = 5,
503    CertificateHold = 6,
504    RemoveFromCrl = 8,
505    PrivilegeWithdrawn = 9,
506    AaCompromise = 10,
507}
508
509impl Serialize for RevocationReason {
510    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
511        serializer.serialize_u8(self.clone() as u8)
512    }
513}
514
515#[derive(Serialize)]
516#[serde(rename_all = "camelCase")]
517pub(crate) struct NewAccountPayload<'a> {
518    #[serde(flatten)]
519    pub(crate) new_account: &'a NewAccount<'a>,
520    #[serde(skip_serializing_if = "Option::is_none")]
521    pub(crate) external_account_binding: Option<JoseJson>,
522}
523
524/// Input data for [Account](crate::Account) creation
525///
526/// To be passed into [AccountBuilder::create()](crate::AccountBuilder::create()).
527#[derive(Debug, Serialize)]
528#[serde(rename_all = "camelCase")]
529pub struct NewAccount<'a> {
530    /// A list of contact URIs (like `mailto:info@example.com`)
531    pub contact: &'a [&'a str],
532    /// Whether you agree to the terms of service
533    pub terms_of_service_agreed: bool,
534    /// Set to `true` in order to retrieve an existing account
535    ///
536    /// Setting this to `false` has not been tested.
537    #[serde(skip_serializing_if = "std::ops::Not::not")]
538    pub only_return_existing: bool,
539}
540
541#[derive(Debug, Clone, Deserialize, Serialize)]
542#[serde(rename_all = "camelCase")]
543pub(crate) struct Directory {
544    pub(crate) new_nonce: String,
545    pub(crate) new_account: String,
546    pub(crate) new_order: String,
547    // The fields below were added later and old `AccountCredentials` may not have it.
548    // Newer deserialized account credentials grab a fresh set of `Directory` on
549    // deserialization, so they should be fine. Newer fields should be optional, too.
550    pub(crate) new_authz: Option<String>,
551    pub(crate) revoke_cert: Option<String>,
552    pub(crate) key_change: Option<String>,
553    // Endpoint for the ACME renewal information (ARI) extension
554    //
555    // <https://www.rfc-editor.org/rfc/rfc9773.html>
556    pub(crate) renewal_info: Option<String>,
557    #[serde(default)]
558    pub(crate) meta: Meta,
559}
560
561#[derive(Clone, Debug, Default, Deserialize, Serialize)]
562pub(crate) struct Meta {
563    #[serde(default)]
564    pub(crate) profiles: HashMap<String, String>,
565}
566
567/// Profile meta information from the server directory
568#[allow(missing_docs)]
569#[derive(Clone, Copy, Debug)]
570pub struct ProfileMeta<'a> {
571    pub name: &'a str,
572    pub description: &'a str,
573}
574
575#[derive(Serialize)]
576pub(crate) struct JoseJson {
577    pub(crate) protected: String,
578    pub(crate) payload: String,
579    pub(crate) signature: String,
580}
581
582impl JoseJson {
583    pub(crate) fn new(
584        payload: Option<&impl Serialize>,
585        protected: Header<'_>,
586        signer: &impl Signer,
587    ) -> Result<Self, Error> {
588        let protected = base64(&protected)?;
589        let payload = match payload {
590            Some(data) => base64(&data)?,
591            None => String::new(),
592        };
593
594        let combined = format!("{protected}.{payload}");
595        let signature = signer.sign(combined.as_bytes())?;
596        Ok(Self {
597            protected,
598            payload,
599            signature: BASE64_URL_SAFE_NO_PAD.encode(signature.as_ref()),
600        })
601    }
602}
603
604pub(crate) trait Signer {
605    type Signature: AsRef<[u8]>;
606
607    fn header<'n, 'u: 'n, 's: 'u>(&'s self, nonce: Option<&'n str>, url: &'u str) -> Header<'n>;
608
609    fn sign(&self, payload: &[u8]) -> Result<Self::Signature, Error>;
610}
611
612fn base64(data: &impl Serialize) -> Result<String, serde_json::Error> {
613    Ok(BASE64_URL_SAFE_NO_PAD.encode(serde_json::to_vec(data)?))
614}
615
616/// An ACME authorization's state as described in RFC 8555 (section 7.1.4)
617#[derive(Debug, Deserialize)]
618#[non_exhaustive]
619#[serde(rename_all = "camelCase")]
620pub struct AuthorizationState {
621    /// The identifier that the account is authorized to represent
622    identifier: Identifier,
623    /// Current state of the authorization
624    pub status: AuthorizationStatus,
625    /// Possible challenges for the authorization
626    pub challenges: Vec<Challenge>,
627    /// Whether the identifier represents a wildcard domain name
628    #[serde(default)]
629    pub wildcard: bool,
630}
631
632impl AuthorizationState {
633    /// Creates an [`AuthorizedIdentifier`] for the identifier in this authorization
634    pub fn identifier(&self) -> AuthorizedIdentifier<'_> {
635        self.identifier.authorized(self.wildcard)
636    }
637}
638
639/// Status for an [`AuthorizationState`]
640#[allow(missing_docs)]
641#[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq)]
642#[serde(rename_all = "camelCase")]
643pub enum AuthorizationStatus {
644    Pending,
645    Valid,
646    Invalid,
647    Revoked,
648    Expired,
649    Deactivated,
650}
651
652/// Represent an identifier in an ACME [Order](crate::Order)
653#[allow(missing_docs)]
654#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
655#[non_exhaustive]
656#[serde(tag = "type", content = "value", rename_all = "kebab-case")]
657pub enum Identifier {
658    Dns(String),
659
660    /// An IP address (IPv4 or IPv6) identifier
661    ///
662    /// Note that not all ACME servers will accept an order with an IP address identifier.
663    Ip(IpAddr),
664
665    /// Permanent Identifier
666    ///
667    /// Note that this identifier is only used for attestation.
668    PermanentIdentifier(String),
669
670    /// Hardware Module identifier
671    ///
672    /// Note that this identifier is only used for attestation.
673    HardwareModule(String),
674}
675
676impl Identifier {
677    /// Create an [`AuthorizedIdentifier`], which implements `Display`
678    ///
679    /// Needs the `wildcard` context bit to determine whether the identifier represents a
680    /// wildcard domain.
681    pub fn authorized(&self, wildcard: bool) -> AuthorizedIdentifier<'_> {
682        AuthorizedIdentifier {
683            identifier: self,
684            wildcard,
685        }
686    }
687}
688
689/// An [`Identifier`] which knows its `wildcard` context
690#[non_exhaustive]
691#[derive(Debug)]
692pub struct AuthorizedIdentifier<'a> {
693    /// The source identifier, missing any wildcard context
694    pub identifier: &'a Identifier,
695    /// Whether the identifier should be interpreted as a wildcard
696    ///
697    /// This is only relevant for DNS identifiers and must be false for other
698    /// types of identifiers (e.g. IP addresses).
699    pub wildcard: bool,
700}
701
702impl fmt::Display for AuthorizedIdentifier<'_> {
703    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
704        match (self.wildcard, self.identifier) {
705            (true, Identifier::Dns(dns)) => f.write_fmt(format_args!("*.{dns}")),
706            (false, Identifier::Dns(dns)) => f.write_str(dns),
707            (_, Identifier::Ip(addr)) => write!(f, "{addr}"),
708            (_, Identifier::PermanentIdentifier(permanent_identifier)) => {
709                f.write_str(permanent_identifier)
710            }
711            (_, Identifier::HardwareModule(hardware_module)) => f.write_str(hardware_module),
712        }
713    }
714}
715
716/// The challenge type
717#[allow(missing_docs)]
718#[non_exhaustive]
719#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
720pub enum ChallengeType {
721    #[serde(rename = "http-01")]
722    Http01,
723    #[serde(rename = "dns-01")]
724    Dns01,
725    #[serde(rename = "tls-alpn-01")]
726    TlsAlpn01,
727    #[serde(rename = "device-attest-01")]
728    DeviceAttest01,
729    #[serde(untagged)]
730    Unknown(String),
731}
732
733#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
734#[serde(rename_all = "camelCase")]
735pub enum ChallengeStatus {
736    Pending,
737    Processing,
738    Valid,
739    Invalid,
740}
741
742/// Status of an [Order](crate::Order)
743#[allow(missing_docs)]
744#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
745#[serde(rename_all = "camelCase")]
746pub enum OrderStatus {
747    Pending,
748    Ready,
749    Processing,
750    Valid,
751    Invalid,
752}
753
754/// Helper type to reference Let's Encrypt server URLs
755#[allow(missing_docs)]
756#[derive(Clone, Copy, Debug)]
757pub enum LetsEncrypt {
758    Production,
759    Staging,
760}
761
762impl LetsEncrypt {
763    /// Get the directory URL for the given Let's Encrypt server
764    pub const fn url(&self) -> &'static str {
765        match self {
766            Self::Production => "https://acme-v02.api.letsencrypt.org/directory",
767            Self::Staging => "https://acme-staging-v02.api.letsencrypt.org/directory",
768        }
769    }
770}
771
772/// ZeroSSL ACME only supports production at the moment
773#[allow(missing_docs)]
774#[derive(Clone, Copy, Debug)]
775pub enum ZeroSsl {
776    Production,
777}
778
779impl ZeroSsl {
780    /// Get the directory URL for the given ZeroSSL server
781    pub const fn url(&self) -> &'static str {
782        match self {
783            Self::Production => "https://acme.zerossl.com/v2/DV90",
784        }
785    }
786}
787
788/// A unique certificate identifier for the ACME renewal information (ARI) extension
789///
790/// See <https://www.rfc-editor.org/rfc/rfc9773.html#section-4.1> for
791/// more information.
792#[derive(Clone, Debug, Eq, PartialEq)]
793pub struct CertificateIdentifier<'a> {
794    /// The BASE64URL-encoded authority key identifier (AKI) extension `keyIdentifier` of the certificate
795    pub authority_key_identifier: Cow<'a, str>,
796
797    /// The BASE64URL-encoded serial number of the certificate
798    pub serial: Cow<'a, str>,
799}
800
801impl CertificateIdentifier<'_> {
802    /// Encode a unique certificate identifier using the provided authority key ID and serial
803    ///
804    /// `authority_key_identifier` must be the DER-encoded ASN.1 octet string from the
805    /// `keyIdentifier` field of the `AuthorityKeyIdentifier` extension found in the certificate
806    /// to be identified.
807    ///
808    /// `serial` must be the DER-encoded ASN.1 serial number from the certificate to be identified.
809    /// Care must be taken to use the **encoded** serial number, not a big integer representation.
810    ///
811    /// The combination uniquely identifies a certificate within all certificates issued by the
812    /// same CA.
813    ///
814    /// See [RFC 5280 §4.1.2.2], [RFC 5280 §4.2.1.1], and [RFC 9773 §4.1]
815    ///
816    /// [RFC 5280 §4.1.2.2]: https://www.rfc-editor.org/rfc/rfc5280#section-4.1.2.2
817    /// [RFC 5280 §4.2.1.1]: https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.1
818    /// [RFC 9773 §4.1]: https://www.rfc-editor.org/rfc/rfc9773.html#section-4.1
819    pub fn new(authority_key_identifier: Der<'_>, serial: Der<'_>) -> Self {
820        Self {
821            authority_key_identifier: BASE64_URL_SAFE_NO_PAD
822                .encode(authority_key_identifier)
823                .into(),
824            serial: BASE64_URL_SAFE_NO_PAD.encode(serial).into(),
825        }
826    }
827
828    /// Convert the `CertificateIdentifier` into an owned version with a static lifetime
829    pub fn into_owned(self) -> CertificateIdentifier<'static> {
830        CertificateIdentifier {
831            authority_key_identifier: Cow::Owned(self.authority_key_identifier.into_owned()),
832            serial: Cow::Owned(self.serial.into_owned()),
833        }
834    }
835}
836
837impl<'de: 'a, 'a> Deserialize<'de> for CertificateIdentifier<'a> {
838    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
839        let s = <&str>::deserialize(deserializer)?;
840
841        let Some((aki, serial)) = s.split_once('.') else {
842            return Err(de::Error::invalid_value(
843                de::Unexpected::Str(s),
844                &"a string containing 2 '.'-delimited parts",
845            ));
846        };
847
848        if serial.contains('.') {
849            return Err(de::Error::invalid_value(
850                de::Unexpected::Str(s),
851                &"only one '.' delimiter should be present",
852            ));
853        }
854
855        Ok(CertificateIdentifier {
856            authority_key_identifier: Cow::Borrowed(aki),
857            serial: Cow::Borrowed(serial),
858        })
859    }
860}
861
862impl Serialize for CertificateIdentifier<'_> {
863    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
864        serializer.collect_str(self)
865    }
866}
867
868#[cfg(feature = "x509-parser")]
869impl<'a> TryFrom<&'a CertificateDer<'_>> for CertificateIdentifier<'_> {
870    type Error = String;
871
872    fn try_from(cert: &'a CertificateDer) -> Result<Self, Self::Error> {
873        let (_, parsed_cert) = parse_x509_certificate(cert.as_ref())
874            .map_err(|e| format!("failed to parse certificate: {e}"))?;
875
876        let Some(authority_key_identifier) =
877            parsed_cert
878                .iter_extensions()
879                .find_map(|ext| match ext.parsed_extension() {
880                    ParsedExtension::AuthorityKeyIdentifier(aki_ext) => aki_ext
881                        .key_identifier
882                        .as_ref()
883                        .map(|aki| Der::from_slice(aki.0)),
884                    _ => None,
885                })
886        else {
887            return Err(
888                "certificate does not contain an Authority Key Identifier (AKI) extension".into(),
889            );
890        };
891
892        Ok(Self::new(
893            authority_key_identifier,
894            Der::from_slice(parsed_cert.tbs_certificate.raw_serial()),
895        ))
896    }
897}
898
899impl fmt::Display for CertificateIdentifier<'_> {
900    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
901        f.write_str(&self.authority_key_identifier)?;
902        f.write_char('.')?;
903        f.write_str(&self.serial)
904    }
905}
906
907/// Information about a suggested renewal window for a certificate
908///
909/// See <https://www.rfc-editor.org/rfc/rfc9773.html#section-4.2>
910#[derive(Clone, Debug, Deserialize)]
911#[serde(rename_all = "camelCase")]
912#[cfg(feature = "time")]
913pub struct RenewalInfo {
914    /// The suggested renewal window for a certificate
915    pub suggested_window: SuggestedWindow,
916    /// A URL to a page explaining why the suggested renewal window has its current value
917    #[serde(rename = "explanationURL")]
918    pub explanation_url: Option<String>,
919}
920
921/// A suggested renewal window for a certificate
922///
923/// See <https://www.rfc-editor.org/rfc/rfc9773.html#section-4.2>
924#[derive(Clone, Debug, Deserialize)]
925#[serde(rename_all = "camelCase")]
926#[cfg(feature = "time")]
927pub struct SuggestedWindow {
928    /// The start [`OffsetDateTime`] of the suggested renewal window
929    #[serde(with = "time::serde::rfc3339")]
930    pub start: OffsetDateTime,
931    /// The end [`OffsetDateTime`] of the suggested renewal window
932    #[serde(with = "time::serde::rfc3339")]
933    pub end: OffsetDateTime,
934}
935
936fn deserialize_static_certificate_identifier<'de, D: serde::Deserializer<'de>>(
937    deserializer: D,
938) -> Result<Option<CertificateIdentifier<'static>>, D::Error> {
939    let Some(cert_id) = Option::<CertificateIdentifier<'_>>::deserialize(deserializer)? else {
940        return Ok(None);
941    };
942
943    Ok(Some(cert_id.into_owned()))
944}
945
946#[derive(Clone, Copy, Debug, Serialize)]
947#[serde(rename_all = "UPPERCASE")]
948pub(crate) enum SigningAlgorithm {
949    /// ECDSA using P-256 and SHA-256
950    Es256,
951    /// HMAC with SHA-256,
952    Hs256,
953}
954
955/// Attestation payload used for device-attest-01
956///
957/// See <https://datatracker.ietf.org/doc/draft-acme-device-attest/> for details.
958#[derive(Serialize)]
959#[serde(rename_all = "camelCase")]
960pub struct DeviceAttestation<'a> {
961    /// attestation payload
962    pub att_obj: Cow<'a, [u8]>,
963}
964
965#[derive(Debug, Serialize)]
966pub(crate) struct Empty {}
967
968#[cfg(test)]
969mod tests {
970    #[cfg(feature = "x509-parser")]
971    use rcgen::{
972        BasicConstraints, CertificateParams, DistinguishedName, IsCa, Issuer, KeyIdMethod, KeyPair,
973        SerialNumber,
974    };
975
976    use super::*;
977
978    // https://datatracker.ietf.org/doc/html/rfc8555#section-7.4
979    #[test]
980    fn order() {
981        const ORDER: &str = r#"{
982          "status": "pending",
983          "expires": "2016-01-05T14:09:07.99Z",
984
985          "notBefore": "2016-01-01T00:00:00Z",
986          "notAfter": "2016-01-08T00:00:00Z",
987
988          "identifiers": [
989            { "type": "dns", "value": "www.example.org" },
990            { "type": "dns", "value": "example.org" }
991          ],
992
993          "authorizations": [
994            "https://example.com/acme/authz/PAniVnsZcis",
995            "https://example.com/acme/authz/r4HqLzrSrpI"
996          ],
997
998          "finalize": "https://example.com/acme/order/TOlocE8rfgo/finalize"
999        }"#;
1000
1001        let obj = serde_json::from_str::<OrderState>(ORDER).unwrap();
1002        assert_eq!(obj.status, OrderStatus::Pending);
1003        assert_eq!(obj.authorizations.len(), 2);
1004        assert_eq!(
1005            obj.finalize,
1006            "https://example.com/acme/order/TOlocE8rfgo/finalize"
1007        );
1008    }
1009
1010    // https://datatracker.ietf.org/doc/html/rfc8555#section-7.5.1
1011    #[test]
1012    fn authorization() {
1013        const AUTHORIZATION: &str = r#"{
1014          "status": "valid",
1015          "expires": "2018-09-09T14:09:01.13Z",
1016
1017          "identifier": {
1018            "type": "dns",
1019            "value": "www.example.org"
1020          },
1021
1022          "challenges": [
1023            {
1024              "type": "http-01",
1025              "url": "https://example.com/acme/chall/prV_B7yEyA4",
1026              "status": "valid",
1027              "validated": "2014-12-01T12:05:13.72Z",
1028              "token": "IlirfxKKXAsHtmzK29Pj8A"
1029            }
1030          ]
1031        }"#;
1032
1033        let obj = serde_json::from_str::<AuthorizationState>(AUTHORIZATION).unwrap();
1034        assert_eq!(obj.status, AuthorizationStatus::Valid);
1035        assert_eq!(obj.identifier, Identifier::Dns("www.example.org".into()));
1036        assert_eq!(obj.challenges.len(), 1);
1037    }
1038
1039    // https://datatracker.ietf.org/doc/html/rfc8555#section-8.4
1040    #[test]
1041    fn challenge() {
1042        const CHALLENGE: &str = r#"{
1043          "type": "dns-01",
1044          "url": "https://example.com/acme/chall/Rg5dV14Gh1Q",
1045          "status": "pending",
1046          "token": "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
1047        }"#;
1048
1049        let obj = serde_json::from_str::<Challenge>(CHALLENGE).unwrap();
1050        assert_eq!(obj.r#type, ChallengeType::Dns01);
1051        assert_eq!(obj.url, "https://example.com/acme/chall/Rg5dV14Gh1Q");
1052        assert_eq!(obj.status, ChallengeStatus::Pending);
1053        assert_eq!(obj.token, "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA");
1054    }
1055
1056    // https://datatracker.ietf.org/doc/html/rfc8555#section-7.6
1057    #[test]
1058    fn problem() {
1059        const PROBLEM: &str = r#"{
1060          "type": "urn:ietf:params:acme:error:unauthorized",
1061          "detail": "No authorization provided for name example.org"
1062        }"#;
1063
1064        let obj = serde_json::from_str::<Problem>(PROBLEM).unwrap();
1065        assert_eq!(
1066            obj.r#type,
1067            Some("urn:ietf:params:acme:error:unauthorized".into())
1068        );
1069        assert_eq!(
1070            obj.detail,
1071            Some("No authorization provided for name example.org".into())
1072        );
1073        assert!(obj.subproblems.is_empty());
1074    }
1075
1076    // https://www.rfc-editor.org/rfc/rfc8555#section-6.7.1
1077    #[test]
1078    fn subproblems() {
1079        const PROBLEM: &str = r#"{
1080            "type": "urn:ietf:params:acme:error:malformed",
1081            "detail": "Some of the identifiers requested were rejected",
1082            "subproblems": [
1083                {
1084                    "type": "urn:ietf:params:acme:error:malformed",
1085                    "detail": "Invalid underscore in DNS name \"_example.org\"",
1086                    "identifier": {
1087                        "type": "dns",
1088                        "value": "_example.org"
1089                    }
1090                },
1091                {
1092                    "type": "urn:ietf:params:acme:error:rejectedIdentifier",
1093                    "detail": "This CA will not issue for \"example.net\"",
1094                    "identifier": {
1095                        "type": "dns",
1096                        "value": "example.net"
1097                    }
1098                }
1099            ]
1100        }"#;
1101
1102        let obj = serde_json::from_str::<Problem>(PROBLEM).unwrap();
1103        assert_eq!(
1104            obj.r#type,
1105            Some("urn:ietf:params:acme:error:malformed".into())
1106        );
1107        assert_eq!(
1108            obj.detail,
1109            Some("Some of the identifiers requested were rejected".into())
1110        );
1111
1112        let subproblems = &obj.subproblems;
1113        assert_eq!(subproblems.len(), 2);
1114
1115        let first_subproblem = subproblems.first().unwrap();
1116        assert_eq!(
1117            first_subproblem.identifier,
1118            Some(Identifier::Dns("_example.org".into()))
1119        );
1120        assert_eq!(
1121            first_subproblem.r#type,
1122            Some("urn:ietf:params:acme:error:malformed".into())
1123        );
1124        assert_eq!(
1125            first_subproblem.detail,
1126            Some(r#"Invalid underscore in DNS name "_example.org""#.into())
1127        );
1128
1129        let second_subproblem = subproblems.get(1).unwrap();
1130        assert_eq!(
1131            second_subproblem.identifier,
1132            Some(Identifier::Dns("example.net".into()))
1133        );
1134        assert_eq!(
1135            second_subproblem.r#type,
1136            Some("urn:ietf:params:acme:error:rejectedIdentifier".into())
1137        );
1138        assert_eq!(
1139            second_subproblem.detail,
1140            Some(r#"This CA will not issue for "example.net""#.into())
1141        );
1142
1143        let expected_display = "\
1144    API error: Some of the identifiers requested were rejected (urn:ietf:params:acme:error:malformed): \
1145    2 subproblems: \
1146    for \"_example.org\": Invalid underscore in DNS name \"_example.org\" (urn:ietf:params:acme:error:malformed), \
1147    for \"example.net\": This CA will not issue for \"example.net\" (urn:ietf:params:acme:error:rejectedIdentifier)";
1148        assert_eq!(format!("{obj}"), expected_display);
1149    }
1150
1151    // https://www.rfc-editor.org/rfc/rfc9773.html#section-4.1
1152    #[test]
1153    fn certificate_identifier() {
1154        const ORDER: &str = r#"{
1155          "status": "pending",
1156          "expires": "2016-01-05T14:09:07.99Z",
1157
1158          "notBefore": "2016-01-01T00:00:00Z",
1159          "notAfter": "2016-01-08T00:00:00Z",
1160
1161          "identifiers": [
1162            { "type": "dns", "value": "www.example.org" },
1163            { "type": "dns", "value": "example.org" }
1164          ],
1165
1166          "authorizations": [
1167            "https://example.com/acme/authz/PAniVnsZcis",
1168            "https://example.com/acme/authz/r4HqLzrSrpI"
1169          ],
1170
1171          "finalize": "https://example.com/acme/order/TOlocE8rfgo/finalize",
1172
1173          "replaces": "aYhba4dGQEHhs3uEe6CuLN4ByNQ.AIdlQyE"
1174        }"#;
1175
1176        let order = serde_json::from_str::<OrderState>(ORDER).unwrap();
1177        let cert_id = order.replaces.unwrap();
1178        assert_eq!(
1179            cert_id.authority_key_identifier,
1180            "aYhba4dGQEHhs3uEe6CuLN4ByNQ"
1181        );
1182        assert_eq!(cert_id.serial, "AIdlQyE");
1183
1184        let serialized = serde_json::to_string(&cert_id).unwrap();
1185        assert_eq!(serialized, r#""aYhba4dGQEHhs3uEe6CuLN4ByNQ.AIdlQyE""#);
1186    }
1187
1188    #[cfg(feature = "x509-parser")]
1189    #[test]
1190    fn encoded_certificate_identifier_from_cert() {
1191        // Generate a CA key_pair and self-signed cert with a specific subject key identifier.
1192        let ca_key_id = vec![0xC0, 0xFF, 0xEE];
1193        let ca_key = KeyPair::generate().unwrap();
1194        let mut ca_params = CertificateParams::default();
1195        ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
1196        ca_params.key_identifier_method = KeyIdMethod::PreSpecified(ca_key_id);
1197        let ca = Issuer::new(ca_params, ca_key);
1198
1199        // Generate an end entity certificate issued by the CA, with a specific serial number
1200        // and an AKI extension.
1201        let ee_key = KeyPair::generate().unwrap();
1202        let ee_serial = [0xCA, 0xFE];
1203        let mut ee_params = CertificateParams::new(["example.com".to_owned()]).unwrap();
1204        ee_params.distinguished_name = DistinguishedName::new();
1205        ee_params.serial_number = Some(SerialNumber::from_slice(ee_serial.as_slice()));
1206        ee_params.use_authority_key_identifier_extension = true;
1207        let ee_cert = ee_params.signed_by(&ee_key, &ca).unwrap();
1208
1209        // Extract the AKI and serial number from the EE certificate and create an encoded
1210        // certificate identifier.
1211        let encoded = CertificateIdentifier::try_from(ee_cert.der()).unwrap();
1212
1213        // We should arrive at the expected encoded certificate identifier.
1214        assert_eq!(format!("{encoded}"), "wP_u.AMr-");
1215    }
1216
1217    // https://www.rfc-editor.org/rfc/rfc9773.html#section-4.2
1218    #[test]
1219    #[cfg(feature = "time")]
1220    fn renewal_info() {
1221        const INFO: &str = r#"{
1222          "suggestedWindow": {
1223            "start": "2025-01-02T04:00:00Z",
1224            "end": "2025-01-03T04:00:00Z"
1225          },
1226          "explanationURL": "https://acme.example.com/docs/ari"
1227        }
1228        "#;
1229
1230        let info = serde_json::from_str::<RenewalInfo>(INFO).unwrap();
1231        assert_eq!(
1232            info.explanation_url.unwrap(),
1233            "https://acme.example.com/docs/ari"
1234        );
1235        let window = info.suggested_window;
1236        assert_eq!(window.start.day(), 2);
1237        assert_eq!(window.end.day(), 3);
1238    }
1239}