1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
use std::borrow::Cow;
use std::fmt;
use base64::URL_SAFE_NO_PAD;
use hyper::{Body, Response};
use ring::digest::{digest, Digest, SHA256};
use ring::signature::{EcdsaKeyPair, KeyPair};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("API error: {0}")]
Api(#[from] Problem),
#[error("base64 decoding failed: {0}")]
Base64(#[from] base64::DecodeError),
#[error("cryptographic operation failed: {0}")]
Crypto(#[from] ring::error::Unspecified),
#[error("invalid key bytes: {0}")]
CryptoKey(#[from] ring::error::KeyRejected),
#[error("HTTP request failure: {0}")]
Http(#[from] hyper::Error),
#[error("invalid URI: {0}")]
InvalidUri(#[from] hyper::http::uri::InvalidUri),
#[error("failed to (de)serialize JSON: {0}")]
Json(#[from] serde_json::Error),
#[error("missing data: {0}")]
Str(&'static str),
}
impl From<&'static str> for Error {
fn from(s: &'static str) -> Self {
Error::Str(s)
}
}
#[derive(Deserialize, Serialize)]
pub struct AccountCredentials<'a> {
pub(crate) id: Cow<'a, str>,
pub(crate) key_pkcs8: String,
pub(crate) urls: Cow<'a, DirectoryUrls>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Problem {
pub r#type: String,
pub detail: String,
pub status: u16,
}
impl Problem {
pub(crate) async fn check<T: DeserializeOwned>(rsp: Response<Body>) -> Result<T, Error> {
Ok(serde_json::from_slice(
&hyper::body::to_bytes(Self::from_response(rsp).await?).await?,
)?)
}
pub(crate) async fn from_response(rsp: Response<Body>) -> Result<Body, Error> {
let status = rsp.status();
let body = rsp.into_body();
if status.is_informational() || status.is_success() || status.is_redirection() {
return Ok(body);
}
let body = hyper::body::to_bytes(body).await?;
Err(serde_json::from_slice::<Problem>(&body)?.into())
}
}
impl fmt::Display for Problem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "API error: {} ({})", self.detail, self.r#type)
}
}
impl std::error::Error for Problem {}
pub struct KeyAuthorization(pub(crate) String);
impl KeyAuthorization {
pub fn as_str(&self) -> &str {
&self.0
}
pub fn dns_value(&self) -> String {
base64::encode_config(digest(&SHA256, self.0.as_bytes()), URL_SAFE_NO_PAD)
}
}
impl fmt::Debug for KeyAuthorization {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("KeyAuthorization").finish()
}
}
#[derive(Debug, Serialize)]
pub(crate) struct FinalizeRequest {
csr: String,
}
impl FinalizeRequest {
pub(crate) fn new(csr_der: &[u8]) -> Self {
Self {
csr: base64::encode_config(csr_der, URL_SAFE_NO_PAD),
}
}
}
#[derive(Debug, Serialize)]
pub(crate) struct Header<'a> {
pub(crate) alg: SigningAlgorithm,
#[serde(flatten)]
pub(crate) key: KeyOrKeyId<'a>,
pub(crate) nonce: &'a str,
pub(crate) url: &'a str,
}
#[derive(Debug, Serialize)]
pub(crate) enum KeyOrKeyId<'a> {
#[serde(rename = "jwk")]
Key(Jwk),
#[serde(rename = "kid")]
KeyId(&'a str),
}
impl<'a> KeyOrKeyId<'a> {
pub(crate) fn from_key(key: &EcdsaKeyPair) -> KeyOrKeyId<'static> {
KeyOrKeyId::Key(Jwk::new(key))
}
}
#[derive(Debug, Serialize)]
pub(crate) struct Jwk {
alg: SigningAlgorithm,
crv: &'static str,
kty: &'static str,
r#use: &'static str,
x: String,
y: String,
}
impl Jwk {
pub(crate) fn new(key: &EcdsaKeyPair) -> Self {
let (x, y) = key.public_key().as_ref()[1..].split_at(32);
Self {
alg: SigningAlgorithm::Es256,
crv: "P-256",
kty: "EC",
r#use: "sig",
x: base64::encode_config(x, URL_SAFE_NO_PAD),
y: base64::encode_config(y, URL_SAFE_NO_PAD),
}
}
pub(crate) fn thumb_sha256(key: &EcdsaKeyPair) -> Result<Digest, serde_json::Error> {
let jwk = Self::new(key);
Ok(digest(
&SHA256,
&serde_json::to_vec(&JwkThumb {
crv: jwk.crv,
kty: jwk.kty,
x: &jwk.x,
y: &jwk.y,
})?,
))
}
}
#[derive(Debug, Serialize)]
struct JwkThumb<'a> {
crv: &'a str,
kty: &'a str,
x: &'a str,
y: &'a str,
}
#[derive(Debug, Deserialize)]
pub struct Challenge {
pub r#type: ChallengeType,
pub url: String,
pub token: String,
pub status: ChallengeStatus,
pub error: Option<Problem>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderState {
pub status: OrderStatus,
pub authorizations: Vec<String>,
pub error: Option<Problem>,
pub finalize: String,
pub certificate: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NewOrder<'a> {
pub identifiers: &'a [Identifier],
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NewAccount<'a> {
pub contact: &'a [&'a str],
pub terms_of_service_agreed: bool,
pub only_return_existing: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct DirectoryUrls {
pub(crate) new_nonce: String,
pub(crate) new_account: String,
pub(crate) new_order: String,
}
#[derive(Serialize)]
pub(crate) struct JoseJson {
pub(crate) protected: String,
pub(crate) payload: String,
pub(crate) signature: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Authorization {
pub identifier: Identifier,
pub status: AuthorizationStatus,
pub challenges: Vec<Challenge>,
}
#[allow(missing_docs)]
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AuthorizationStatus {
Pending,
Valid,
Invalid,
Revoked,
Expired,
}
#[allow(missing_docs)]
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "camelCase")]
pub enum Identifier {
Dns(String),
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
#[allow(missing_docs)]
pub enum ChallengeType {
#[serde(rename = "http-01")]
Http01,
#[serde(rename = "dns-01")]
Dns01,
#[serde(rename = "tls-alpn-01")]
TlsAlpn01,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ChallengeStatus {
Pending,
Processing,
Valid,
Invalid,
}
#[allow(missing_docs)]
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum OrderStatus {
Pending,
Ready,
Processing,
Valid,
Invalid,
}
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug)]
pub enum LetsEncrypt {
Production,
Staging,
}
impl LetsEncrypt {
pub const fn url(&self) -> &'static str {
match self {
LetsEncrypt::Production => "https://acme-v02.api.letsencrypt.org/directory",
LetsEncrypt::Staging => "https://acme-staging-v02.api.letsencrypt.org/directory",
}
}
}
#[derive(Clone, Copy, Debug, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub(crate) enum SigningAlgorithm {
Es256,
}
#[derive(Debug, Serialize)]
pub(crate) struct Empty {}