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#[derive(Debug, Error)]
26#[non_exhaustive]
27pub enum Error {
28 #[error(transparent)]
32 Api(#[from] Problem),
33 #[error("cryptographic operation failed")]
35 Crypto,
36 #[error("invalid key bytes")]
38 KeyRejected,
39 #[error("HTTP request failure: {0}")]
41 Http(#[from] http::Error),
42 #[cfg(feature = "hyper-rustls")]
44 #[error("HTTP request failure: {0}")]
45 Hyper(#[from] hyper::Error),
46 #[error("invalid URI: {0}")]
48 InvalidUri(#[from] http::uri::InvalidUri),
49 #[error("failed to (de)serialize JSON: {0}")]
51 Json(#[from] serde_json::Error),
52 #[error("timed out waiting for an order update")]
56 Timeout(Option<Instant>),
57 #[error("ACME server does not support: {0}")]
59 Unsupported(&'static str),
60 #[error(transparent)]
62 Other(Box<dyn std::error::Error + Send + Sync + 'static>),
63 #[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#[must_use]
88#[derive(Deserialize, Serialize)]
89pub struct AccountCredentials {
90 pub(crate) id: String,
91 #[serde(with = "pkcs8_serde")]
93 pub(crate) key_pkcs8: PrivatePkcs8KeyDer<'static>,
94 pub(crate) directory: Option<String>,
95 #[serde(skip_serializing_if = "Option::is_none")]
98 pub(crate) urls: Option<Directory>,
99}
100
101impl AccountCredentials {
102 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#[derive(Clone, Debug, Deserialize)]
149#[serde(rename_all = "camelCase")]
150pub struct Problem {
151 pub r#type: Option<String>,
155 pub detail: Option<String>,
157 pub status: Option<u16>,
159 #[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#[derive(Clone, Debug, Deserialize)]
213pub struct Subproblem {
214 pub identifier: Option<Identifier>,
216 pub r#type: Option<String>,
220 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#[derive(Debug, Deserialize)]
330pub struct Challenge {
331 pub r#type: ChallengeType,
333 pub url: String,
335 pub token: String,
337 pub status: ChallengeStatus,
339 pub error: Option<Problem>,
341}
342
343#[derive(Debug, Deserialize)]
349#[non_exhaustive]
350#[serde(rename_all = "camelCase")]
351pub struct OrderState {
352 pub status: OrderStatus,
354 pub authorizations: Vec<Authorization>,
364 pub error: Option<Problem>,
366 pub finalize: String,
368 pub certificate: Option<String>,
370 #[serde(deserialize_with = "deserialize_static_certificate_identifier")]
372 #[serde(default)]
373 pub replaces: Option<CertificateIdentifier<'static>>,
374 #[serde(default)]
376 pub profile: Option<String>,
377}
378
379#[derive(Debug)]
387pub struct Authorization {
388 pub url: String,
390 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#[derive(Debug, Serialize)]
413#[serde(rename_all = "camelCase")]
414pub struct NewOrder<'a> {
415 #[serde(skip_serializing_if = "Option::is_none")]
417 pub(crate) replaces: Option<CertificateIdentifier<'a>>,
418 identifiers: &'a [Identifier],
420 #[serde(skip_serializing_if = "Option::is_none")]
421 profile: Option<&'a str>,
422}
423
424impl<'a> NewOrder<'a> {
425 pub fn new(identifiers: &'a [Identifier]) -> Self {
429 Self {
430 identifiers,
431 replaces: None,
432 profile: None,
433 }
434 }
435
436 pub fn replaces(mut self, replaces: CertificateIdentifier<'a>) -> Self {
449 self.replaces = Some(replaces);
450 self
451 }
452
453 pub fn profile(mut self, profile: &'a str) -> Self {
459 self.profile = Some(profile);
460 self
461 }
462
463 pub fn identifiers(&self) -> &[Identifier] {
465 self.identifiers
466 }
467}
468
469#[derive(Debug)]
472pub struct RevocationRequest<'a> {
473 pub certificate: &'a CertificateDer<'a>,
475 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#[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#[derive(Debug, Serialize)]
528#[serde(rename_all = "camelCase")]
529pub struct NewAccount<'a> {
530 pub contact: &'a [&'a str],
532 pub terms_of_service_agreed: bool,
534 pub only_return_existing: bool,
538}
539
540#[derive(Debug, Clone, Deserialize, Serialize)]
541#[serde(rename_all = "camelCase")]
542pub(crate) struct Directory {
543 pub(crate) new_nonce: String,
544 pub(crate) new_account: String,
545 pub(crate) new_order: String,
546 pub(crate) new_authz: Option<String>,
550 pub(crate) revoke_cert: Option<String>,
551 pub(crate) key_change: Option<String>,
552 pub(crate) renewal_info: Option<String>,
556 #[serde(default)]
557 pub(crate) meta: Meta,
558}
559
560#[derive(Clone, Debug, Default, Deserialize, Serialize)]
561pub(crate) struct Meta {
562 #[serde(default)]
563 pub(crate) profiles: HashMap<String, String>,
564}
565
566#[allow(missing_docs)]
568#[derive(Clone, Copy, Debug)]
569pub struct ProfileMeta<'a> {
570 pub name: &'a str,
571 pub description: &'a str,
572}
573
574#[derive(Serialize)]
575pub(crate) struct JoseJson {
576 pub(crate) protected: String,
577 pub(crate) payload: String,
578 pub(crate) signature: String,
579}
580
581impl JoseJson {
582 pub(crate) fn new(
583 payload: Option<&impl Serialize>,
584 protected: Header<'_>,
585 signer: &impl Signer,
586 ) -> Result<Self, Error> {
587 let protected = base64(&protected)?;
588 let payload = match payload {
589 Some(data) => base64(&data)?,
590 None => String::new(),
591 };
592
593 let combined = format!("{protected}.{payload}");
594 let signature = signer.sign(combined.as_bytes())?;
595 Ok(Self {
596 protected,
597 payload,
598 signature: BASE64_URL_SAFE_NO_PAD.encode(signature.as_ref()),
599 })
600 }
601}
602
603pub(crate) trait Signer {
604 type Signature: AsRef<[u8]>;
605
606 fn header<'n, 'u: 'n, 's: 'u>(&'s self, nonce: Option<&'n str>, url: &'u str) -> Header<'n>;
607
608 fn sign(&self, payload: &[u8]) -> Result<Self::Signature, Error>;
609}
610
611fn base64(data: &impl Serialize) -> Result<String, serde_json::Error> {
612 Ok(BASE64_URL_SAFE_NO_PAD.encode(serde_json::to_vec(data)?))
613}
614
615#[derive(Debug, Deserialize)]
617#[non_exhaustive]
618#[serde(rename_all = "camelCase")]
619pub struct AuthorizationState {
620 identifier: Identifier,
622 pub status: AuthorizationStatus,
624 pub challenges: Vec<Challenge>,
626 #[serde(default)]
628 pub wildcard: bool,
629}
630
631impl AuthorizationState {
632 pub fn identifier(&self) -> AuthorizedIdentifier<'_> {
634 self.identifier.authorized(self.wildcard)
635 }
636}
637
638#[allow(missing_docs)]
640#[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, PartialEq)]
641#[serde(rename_all = "camelCase")]
642pub enum AuthorizationStatus {
643 Pending,
644 Valid,
645 Invalid,
646 Revoked,
647 Expired,
648 Deactivated,
649}
650
651#[allow(missing_docs)]
653#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
654#[non_exhaustive]
655#[serde(tag = "type", content = "value", rename_all = "kebab-case")]
656pub enum Identifier {
657 Dns(String),
658
659 Ip(IpAddr),
663
664 PermanentIdentifier(String),
668
669 HardwareModule(String),
673}
674
675impl Identifier {
676 pub fn authorized(&self, wildcard: bool) -> AuthorizedIdentifier<'_> {
681 AuthorizedIdentifier {
682 identifier: self,
683 wildcard,
684 }
685 }
686}
687
688#[non_exhaustive]
690#[derive(Debug)]
691pub struct AuthorizedIdentifier<'a> {
692 pub identifier: &'a Identifier,
694 pub wildcard: bool,
699}
700
701impl fmt::Display for AuthorizedIdentifier<'_> {
702 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
703 match (self.wildcard, self.identifier) {
704 (true, Identifier::Dns(dns)) => f.write_fmt(format_args!("*.{dns}")),
705 (false, Identifier::Dns(dns)) => f.write_str(dns),
706 (_, Identifier::Ip(addr)) => write!(f, "{addr}"),
707 (_, Identifier::PermanentIdentifier(permanent_identifier)) => {
708 f.write_str(permanent_identifier)
709 }
710 (_, Identifier::HardwareModule(hardware_module)) => f.write_str(hardware_module),
711 }
712 }
713}
714
715#[allow(missing_docs)]
717#[non_exhaustive]
718#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
719pub enum ChallengeType {
720 #[serde(rename = "http-01")]
721 Http01,
722 #[serde(rename = "dns-01")]
723 Dns01,
724 #[serde(rename = "tls-alpn-01")]
725 TlsAlpn01,
726 #[serde(rename = "device-attest-01")]
727 DeviceAttest01,
728 #[serde(untagged)]
729 Unknown(String),
730}
731
732#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
733#[serde(rename_all = "camelCase")]
734pub enum ChallengeStatus {
735 Pending,
736 Processing,
737 Valid,
738 Invalid,
739}
740
741#[allow(missing_docs)]
743#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
744#[serde(rename_all = "camelCase")]
745pub enum OrderStatus {
746 Pending,
747 Ready,
748 Processing,
749 Valid,
750 Invalid,
751}
752
753#[allow(missing_docs)]
755#[derive(Clone, Copy, Debug)]
756pub enum LetsEncrypt {
757 Production,
758 Staging,
759}
760
761impl LetsEncrypt {
762 pub const fn url(&self) -> &'static str {
764 match self {
765 Self::Production => "https://acme-v02.api.letsencrypt.org/directory",
766 Self::Staging => "https://acme-staging-v02.api.letsencrypt.org/directory",
767 }
768 }
769}
770
771#[allow(missing_docs)]
773#[derive(Clone, Copy, Debug)]
774pub enum ZeroSsl {
775 Production,
776}
777
778impl ZeroSsl {
779 pub const fn url(&self) -> &'static str {
781 match self {
782 Self::Production => "https://acme.zerossl.com/v2/DV90",
783 }
784 }
785}
786
787#[derive(Clone, Debug, Eq, PartialEq)]
792pub struct CertificateIdentifier<'a> {
793 pub authority_key_identifier: Cow<'a, str>,
795
796 pub serial: Cow<'a, str>,
798}
799
800impl CertificateIdentifier<'_> {
801 pub fn new(authority_key_identifier: Der<'_>, serial: Der<'_>) -> Self {
819 Self {
820 authority_key_identifier: BASE64_URL_SAFE_NO_PAD
821 .encode(authority_key_identifier)
822 .into(),
823 serial: BASE64_URL_SAFE_NO_PAD.encode(serial).into(),
824 }
825 }
826
827 pub fn into_owned(self) -> CertificateIdentifier<'static> {
829 CertificateIdentifier {
830 authority_key_identifier: Cow::Owned(self.authority_key_identifier.into_owned()),
831 serial: Cow::Owned(self.serial.into_owned()),
832 }
833 }
834}
835
836impl<'de: 'a, 'a> Deserialize<'de> for CertificateIdentifier<'a> {
837 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
838 let s = <&str>::deserialize(deserializer)?;
839
840 let Some((aki, serial)) = s.split_once('.') else {
841 return Err(de::Error::invalid_value(
842 de::Unexpected::Str(s),
843 &"a string containing 2 '.'-delimited parts",
844 ));
845 };
846
847 if serial.contains('.') {
848 return Err(de::Error::invalid_value(
849 de::Unexpected::Str(s),
850 &"only one '.' delimiter should be present",
851 ));
852 }
853
854 Ok(CertificateIdentifier {
855 authority_key_identifier: Cow::Borrowed(aki),
856 serial: Cow::Borrowed(serial),
857 })
858 }
859}
860
861impl Serialize for CertificateIdentifier<'_> {
862 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
863 serializer.collect_str(self)
864 }
865}
866
867#[cfg(feature = "x509-parser")]
868impl<'a> TryFrom<&'a CertificateDer<'_>> for CertificateIdentifier<'_> {
869 type Error = String;
870
871 fn try_from(cert: &'a CertificateDer) -> Result<Self, Self::Error> {
872 let (_, parsed_cert) = parse_x509_certificate(cert.as_ref())
873 .map_err(|e| format!("failed to parse certificate: {e}"))?;
874
875 let Some(authority_key_identifier) =
876 parsed_cert
877 .iter_extensions()
878 .find_map(|ext| match ext.parsed_extension() {
879 ParsedExtension::AuthorityKeyIdentifier(aki_ext) => aki_ext
880 .key_identifier
881 .as_ref()
882 .map(|aki| Der::from_slice(aki.0)),
883 _ => None,
884 })
885 else {
886 return Err(
887 "certificate does not contain an Authority Key Identifier (AKI) extension".into(),
888 );
889 };
890
891 Ok(Self::new(
892 authority_key_identifier,
893 Der::from_slice(parsed_cert.tbs_certificate.raw_serial()),
894 ))
895 }
896}
897
898impl fmt::Display for CertificateIdentifier<'_> {
899 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
900 f.write_str(&self.authority_key_identifier)?;
901 f.write_char('.')?;
902 f.write_str(&self.serial)
903 }
904}
905
906#[derive(Clone, Debug, Deserialize)]
910#[serde(rename_all = "camelCase")]
911#[cfg(feature = "time")]
912pub struct RenewalInfo {
913 pub suggested_window: SuggestedWindow,
915 #[serde(rename = "explanationURL")]
917 pub explanation_url: Option<String>,
918}
919
920#[derive(Clone, Debug, Deserialize)]
924#[serde(rename_all = "camelCase")]
925#[cfg(feature = "time")]
926pub struct SuggestedWindow {
927 #[serde(with = "time::serde::rfc3339")]
929 pub start: OffsetDateTime,
930 #[serde(with = "time::serde::rfc3339")]
932 pub end: OffsetDateTime,
933}
934
935fn deserialize_static_certificate_identifier<'de, D: serde::Deserializer<'de>>(
936 deserializer: D,
937) -> Result<Option<CertificateIdentifier<'static>>, D::Error> {
938 let Some(cert_id) = Option::<CertificateIdentifier<'_>>::deserialize(deserializer)? else {
939 return Ok(None);
940 };
941
942 Ok(Some(cert_id.into_owned()))
943}
944
945#[derive(Clone, Copy, Debug, Serialize)]
946#[serde(rename_all = "UPPERCASE")]
947pub(crate) enum SigningAlgorithm {
948 Es256,
950 Hs256,
952}
953
954#[derive(Serialize)]
958#[serde(rename_all = "camelCase")]
959pub struct DeviceAttestation<'a> {
960 pub att_obj: Cow<'a, [u8]>,
962}
963
964#[derive(Debug, Serialize)]
965pub(crate) struct Empty {}
966
967#[cfg(test)]
968mod tests {
969 #[cfg(feature = "x509-parser")]
970 use rcgen::{
971 BasicConstraints, CertificateParams, DistinguishedName, IsCa, Issuer, KeyIdMethod, KeyPair,
972 SerialNumber,
973 };
974
975 use super::*;
976
977 #[test]
979 fn order() {
980 const ORDER: &str = r#"{
981 "status": "pending",
982 "expires": "2016-01-05T14:09:07.99Z",
983
984 "notBefore": "2016-01-01T00:00:00Z",
985 "notAfter": "2016-01-08T00:00:00Z",
986
987 "identifiers": [
988 { "type": "dns", "value": "www.example.org" },
989 { "type": "dns", "value": "example.org" }
990 ],
991
992 "authorizations": [
993 "https://example.com/acme/authz/PAniVnsZcis",
994 "https://example.com/acme/authz/r4HqLzrSrpI"
995 ],
996
997 "finalize": "https://example.com/acme/order/TOlocE8rfgo/finalize"
998 }"#;
999
1000 let obj = serde_json::from_str::<OrderState>(ORDER).unwrap();
1001 assert_eq!(obj.status, OrderStatus::Pending);
1002 assert_eq!(obj.authorizations.len(), 2);
1003 assert_eq!(
1004 obj.finalize,
1005 "https://example.com/acme/order/TOlocE8rfgo/finalize"
1006 );
1007 }
1008
1009 #[test]
1011 fn authorization() {
1012 const AUTHORIZATION: &str = r#"{
1013 "status": "valid",
1014 "expires": "2018-09-09T14:09:01.13Z",
1015
1016 "identifier": {
1017 "type": "dns",
1018 "value": "www.example.org"
1019 },
1020
1021 "challenges": [
1022 {
1023 "type": "http-01",
1024 "url": "https://example.com/acme/chall/prV_B7yEyA4",
1025 "status": "valid",
1026 "validated": "2014-12-01T12:05:13.72Z",
1027 "token": "IlirfxKKXAsHtmzK29Pj8A"
1028 }
1029 ]
1030 }"#;
1031
1032 let obj = serde_json::from_str::<AuthorizationState>(AUTHORIZATION).unwrap();
1033 assert_eq!(obj.status, AuthorizationStatus::Valid);
1034 assert_eq!(obj.identifier, Identifier::Dns("www.example.org".into()));
1035 assert_eq!(obj.challenges.len(), 1);
1036 }
1037
1038 #[test]
1040 fn challenge() {
1041 const CHALLENGE: &str = r#"{
1042 "type": "dns-01",
1043 "url": "https://example.com/acme/chall/Rg5dV14Gh1Q",
1044 "status": "pending",
1045 "token": "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
1046 }"#;
1047
1048 let obj = serde_json::from_str::<Challenge>(CHALLENGE).unwrap();
1049 assert_eq!(obj.r#type, ChallengeType::Dns01);
1050 assert_eq!(obj.url, "https://example.com/acme/chall/Rg5dV14Gh1Q");
1051 assert_eq!(obj.status, ChallengeStatus::Pending);
1052 assert_eq!(obj.token, "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA");
1053 }
1054
1055 #[test]
1057 fn problem() {
1058 const PROBLEM: &str = r#"{
1059 "type": "urn:ietf:params:acme:error:unauthorized",
1060 "detail": "No authorization provided for name example.org"
1061 }"#;
1062
1063 let obj = serde_json::from_str::<Problem>(PROBLEM).unwrap();
1064 assert_eq!(
1065 obj.r#type,
1066 Some("urn:ietf:params:acme:error:unauthorized".into())
1067 );
1068 assert_eq!(
1069 obj.detail,
1070 Some("No authorization provided for name example.org".into())
1071 );
1072 assert!(obj.subproblems.is_empty());
1073 }
1074
1075 #[test]
1077 fn subproblems() {
1078 const PROBLEM: &str = r#"{
1079 "type": "urn:ietf:params:acme:error:malformed",
1080 "detail": "Some of the identifiers requested were rejected",
1081 "subproblems": [
1082 {
1083 "type": "urn:ietf:params:acme:error:malformed",
1084 "detail": "Invalid underscore in DNS name \"_example.org\"",
1085 "identifier": {
1086 "type": "dns",
1087 "value": "_example.org"
1088 }
1089 },
1090 {
1091 "type": "urn:ietf:params:acme:error:rejectedIdentifier",
1092 "detail": "This CA will not issue for \"example.net\"",
1093 "identifier": {
1094 "type": "dns",
1095 "value": "example.net"
1096 }
1097 }
1098 ]
1099 }"#;
1100
1101 let obj = serde_json::from_str::<Problem>(PROBLEM).unwrap();
1102 assert_eq!(
1103 obj.r#type,
1104 Some("urn:ietf:params:acme:error:malformed".into())
1105 );
1106 assert_eq!(
1107 obj.detail,
1108 Some("Some of the identifiers requested were rejected".into())
1109 );
1110
1111 let subproblems = &obj.subproblems;
1112 assert_eq!(subproblems.len(), 2);
1113
1114 let first_subproblem = subproblems.first().unwrap();
1115 assert_eq!(
1116 first_subproblem.identifier,
1117 Some(Identifier::Dns("_example.org".into()))
1118 );
1119 assert_eq!(
1120 first_subproblem.r#type,
1121 Some("urn:ietf:params:acme:error:malformed".into())
1122 );
1123 assert_eq!(
1124 first_subproblem.detail,
1125 Some(r#"Invalid underscore in DNS name "_example.org""#.into())
1126 );
1127
1128 let second_subproblem = subproblems.get(1).unwrap();
1129 assert_eq!(
1130 second_subproblem.identifier,
1131 Some(Identifier::Dns("example.net".into()))
1132 );
1133 assert_eq!(
1134 second_subproblem.r#type,
1135 Some("urn:ietf:params:acme:error:rejectedIdentifier".into())
1136 );
1137 assert_eq!(
1138 second_subproblem.detail,
1139 Some(r#"This CA will not issue for "example.net""#.into())
1140 );
1141
1142 let expected_display = "\
1143 API error: Some of the identifiers requested were rejected (urn:ietf:params:acme:error:malformed): \
1144 2 subproblems: \
1145 for \"_example.org\": Invalid underscore in DNS name \"_example.org\" (urn:ietf:params:acme:error:malformed), \
1146 for \"example.net\": This CA will not issue for \"example.net\" (urn:ietf:params:acme:error:rejectedIdentifier)";
1147 assert_eq!(format!("{obj}"), expected_display);
1148 }
1149
1150 #[test]
1152 fn certificate_identifier() {
1153 const ORDER: &str = r#"{
1154 "status": "pending",
1155 "expires": "2016-01-05T14:09:07.99Z",
1156
1157 "notBefore": "2016-01-01T00:00:00Z",
1158 "notAfter": "2016-01-08T00:00:00Z",
1159
1160 "identifiers": [
1161 { "type": "dns", "value": "www.example.org" },
1162 { "type": "dns", "value": "example.org" }
1163 ],
1164
1165 "authorizations": [
1166 "https://example.com/acme/authz/PAniVnsZcis",
1167 "https://example.com/acme/authz/r4HqLzrSrpI"
1168 ],
1169
1170 "finalize": "https://example.com/acme/order/TOlocE8rfgo/finalize",
1171
1172 "replaces": "aYhba4dGQEHhs3uEe6CuLN4ByNQ.AIdlQyE"
1173 }"#;
1174
1175 let order = serde_json::from_str::<OrderState>(ORDER).unwrap();
1176 let cert_id = order.replaces.unwrap();
1177 assert_eq!(
1178 cert_id.authority_key_identifier,
1179 "aYhba4dGQEHhs3uEe6CuLN4ByNQ"
1180 );
1181 assert_eq!(cert_id.serial, "AIdlQyE");
1182
1183 let serialized = serde_json::to_string(&cert_id).unwrap();
1184 assert_eq!(serialized, r#""aYhba4dGQEHhs3uEe6CuLN4ByNQ.AIdlQyE""#);
1185 }
1186
1187 #[cfg(feature = "x509-parser")]
1188 #[test]
1189 fn encoded_certificate_identifier_from_cert() {
1190 let ca_key_id = vec![0xC0, 0xFF, 0xEE];
1192 let ca_key = KeyPair::generate().unwrap();
1193 let mut ca_params = CertificateParams::default();
1194 ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
1195 ca_params.key_identifier_method = KeyIdMethod::PreSpecified(ca_key_id);
1196 let ca = Issuer::new(ca_params, ca_key);
1197
1198 let ee_key = KeyPair::generate().unwrap();
1201 let ee_serial = [0xCA, 0xFE];
1202 let mut ee_params = CertificateParams::new(["example.com".to_owned()]).unwrap();
1203 ee_params.distinguished_name = DistinguishedName::new();
1204 ee_params.serial_number = Some(SerialNumber::from_slice(ee_serial.as_slice()));
1205 ee_params.use_authority_key_identifier_extension = true;
1206 let ee_cert = ee_params.signed_by(&ee_key, &ca).unwrap();
1207
1208 let encoded = CertificateIdentifier::try_from(ee_cert.der()).unwrap();
1211
1212 assert_eq!(format!("{encoded}"), "wP_u.AMr-");
1214 }
1215
1216 #[test]
1218 #[cfg(feature = "time")]
1219 fn renewal_info() {
1220 const INFO: &str = r#"{
1221 "suggestedWindow": {
1222 "start": "2025-01-02T04:00:00Z",
1223 "end": "2025-01-03T04:00:00Z"
1224 },
1225 "explanationURL": "https://acme.example.com/docs/ari"
1226 }
1227 "#;
1228
1229 let info = serde_json::from_str::<RenewalInfo>(INFO).unwrap();
1230 assert_eq!(
1231 info.explanation_url.unwrap(),
1232 "https://acme.example.com/docs/ari"
1233 );
1234 let window = info.suggested_window;
1235 assert_eq!(window.start.day(), 2);
1236 assert_eq!(window.end.day(), 3);
1237 }
1238}