lers 0.4.0

An async, user-friendly Let's Encrypt/ACMEv2 library written in Rust
Documentation
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use crate::{
    error::{Error, Result},
    solver::SolverManager,
    Solver,
};
use chrono::{DateTime, Utc};
use openssl::pkey::{PKey, Private};
use reqwest::{header, Client, Response};
use serde::Serialize;
use std::{future::Future, sync::Arc, time::Duration};
use tokio::time;
use tracing::{instrument, Level, Span};

mod jws;
mod nonce;
pub mod responses;

pub(crate) use jws::key_authorization;
use responses::ErrorType;

#[derive(Debug)]
pub(crate) struct ExternalAccountOptions<'o> {
    pub kid: &'o str,
    pub hmac: &'o str,
}

#[derive(Debug)]
pub(crate) struct Api(Arc<ApiInner>);

#[derive(Debug)]
struct ApiInner {
    client: Client,
    urls: responses::Directory,
    nonces: nonce::Pool,
    solvers: SolverManager,
}

impl Api {
    /// Construct the API for a directory from a URL
    #[instrument(
        level = Level::TRACE,
        name = "Api::from_url",
        err,
        skip(client, solvers),
    )]
    pub(crate) async fn from_url(
        url: String,
        client: Client,
        max_nonces: usize,
        solvers: SolverManager,
    ) -> Result<Api> {
        let urls = client.get(url).send().await?.json().await?;

        let inner = ApiInner {
            client,
            urls,
            nonces: nonce::Pool::new(max_nonces),
            solvers,
        };
        Ok(Api(Arc::new(inner)))
    }

    /// Get optional metadata about the directory
    #[inline(always)]
    pub(crate) fn meta(&self) -> &responses::DirectoryMeta {
        &self.0.urls.meta
    }

    /// Retrieve the next nonce from the pool
    #[inline(always)]
    async fn next_nonce(&self) -> Result<String> {
        self.0
            .nonces
            .get(&self.0.urls.new_nonce, &self.0.client)
            .await
    }

    /// Perform an authenticated request to the API with a JSON body
    async fn request_json<S: Serialize>(
        &self,
        url: &str,
        body: S,
        private_key: &PKey<Private>,
        account_id: Option<&str>,
    ) -> Result<Response> {
        let body = serde_json::to_string(&body)?;
        self.request(url, &body, private_key, account_id).await
    }

    /// Perform an authenticated request to the API
    #[instrument(
        level = Level::TRACE,
        name = "Api::request",
        err,
        skip_all,
        fields(
            ?account_id,
            http.body.len = body.len(),
            http.url = %url,
            http.method = "POST",
            http.status,
        )
    )]
    async fn request(
        &self,
        url: &str,
        body: &str,
        private_key: &PKey<Private>,
        account_id: Option<&str>,
    ) -> Result<Response> {
        let mut attempt = 0;

        loop {
            attempt += 1;

            let nonce = self.next_nonce().await?;
            let body = jws::sign(url, nonce, body, private_key, account_id)?;
            let body = serde_json::to_vec(&body)?;

            let response = self
                .0
                .client
                .post(url)
                .header(header::CONTENT_TYPE, "application/jose+json")
                .body(body)
                .send()
                .await?;

            let status = response.status();
            Span::current().record("http.status", status.as_u16());

            self.0.nonces.extract_from_response(&response)?;

            if status.is_success() {
                return Ok(response);
            }

            let err = response.json::<responses::Error>().await?;
            if err.type_ == ErrorType::BadNonce && attempt <= 3 {
                continue;
            }

            return Err(Error::Server(err));
        }
    }

    /// Perform the [newAccount](https://www.rfc-editor.org/rfc/rfc8555.html#section-7.3) operation.
    /// Returns the account's ID and creation response.
    pub async fn new_account(
        &self,
        contacts: Option<Vec<String>>,
        terms_of_service_agreed: bool,
        only_return_existing: bool,
        external_account_options: Option<ExternalAccountOptions<'_>>,
        private_key: &PKey<Private>,
    ) -> Result<(String, responses::Account)> {
        let external_account_binding = external_account_options
            .map(|opts| {
                jws::sign_with_eab(&self.0.urls.new_account, private_key, opts.kid, opts.hmac)
            })
            .transpose()?;

        let payload = responses::NewAccount {
            contacts,
            terms_of_service_agreed,
            only_return_existing,
            external_account_binding,
        };
        let response = self
            .request_json(&self.0.urls.new_account, &payload, private_key, None)
            .await?;

        let id = location_header(&response)?;
        let account = response.json::<responses::Account>().await?;
        Ok((id, account))
    }

    /// Perform the [newOrder](https://www.rfc-editor.org/rfc/rfc8555.html#section-7.4) operation.
    /// Returns the order's URL and creation response.
    pub async fn new_order(
        &self,
        identifiers: Vec<responses::Identifier>,
        not_before: Option<DateTime<Utc>>,
        not_after: Option<DateTime<Utc>>,
        private_key: &PKey<Private>,
        account_id: &str,
    ) -> Result<(String, responses::Order)> {
        let payload = responses::NewOrder {
            identifiers,
            not_before,
            not_after,
        };
        let response = self
            .request_json(
                &self.0.urls.new_order,
                &payload,
                private_key,
                Some(account_id),
            )
            .await?;

        let url = location_header(&response)?;
        let order = response.json().await?;
        Ok((url, order))
    }

    /// Fetch an order
    pub async fn fetch_order(
        &self,
        url: &str,
        private_key: &PKey<Private>,
        account_id: &str,
    ) -> Result<responses::Order> {
        let response = self.request(url, "", private_key, Some(account_id)).await?;
        let order = response.json().await?;
        Ok(order)
    }

    /// Fetch an authorization
    pub async fn fetch_authorization(
        &self,
        url: &str,
        private_key: &PKey<Private>,
        account_id: &str,
    ) -> Result<responses::Authorization> {
        let response = self.request(url, "", private_key, Some(account_id)).await?;
        let authorization = response.json().await?;
        Ok(authorization)
    }

    /// Fetch a challenge
    pub async fn fetch_challenge(
        &self,
        url: &str,
        private_key: &PKey<Private>,
        account_id: &str,
    ) -> Result<responses::Challenge> {
        let response = self.request(url, "", private_key, Some(account_id)).await?;
        let challenge = response.json().await?;
        Ok(challenge)
    }

    /// Enqueue a challenge for validation
    pub async fn validate_challenge(
        &self,
        url: &str,
        private_key: &PKey<Private>,
        account_id: &str,
    ) -> Result<responses::Challenge> {
        let response = self
            .request(url, "{}", private_key, Some(account_id))
            .await?;
        let challenge = response.json().await?;
        Ok(challenge)
    }

    /// Finalize an order using the provided CSR
    pub async fn finalize_order(
        &self,
        url: &str,
        csr: String,
        private_key: &PKey<Private>,
        account_id: &str,
    ) -> Result<responses::Order> {
        let payload = responses::FinalizeOrder { csr };
        let response = self
            .request_json(url, &payload, private_key, Some(account_id))
            .await?;
        let order = response.json().await?;
        Ok(order)
    }

    /// Download the certificate from the order
    pub async fn download_certificate(
        &self,
        url: &str,
        private_key: &PKey<Private>,
        account_id: &str,
    ) -> Result<String> {
        let response = self.request(url, "", private_key, Some(account_id)).await?;
        let certificate = response.text().await?;
        Ok(certificate)
    }

    /// Revoke a certificate
    ///
    /// If the `account_key` is not `None`, the `private_key` must be that of the account. Otherwise,
    /// it must be the certificate's private key.
    pub async fn revoke_certificate(
        &self,
        certificate: String,
        reason: Option<responses::RevocationReason>,
        private_key: &PKey<Private>,
        account_id: Option<&str>,
    ) -> Result<()> {
        self.request_json(
            &self.0.urls.revoke_cert,
            &responses::RevocationRequest {
                certificate,
                reason,
            },
            private_key,
            account_id,
        )
        .await?;
        Ok(())
    }

    /// Wait until the fetched resource meets a condition or the maximum attempts are exceeded.
    #[allow(clippy::too_many_arguments)]
    pub async fn wait_until<'a, F, P, T, Fut>(
        &self,
        fetcher: F,
        predicate: P,
        url: &'a str,
        private_key: &'a PKey<Private>,
        account_id: &'a str,
        interval: Duration,
        max_attempts: usize,
    ) -> Result<T>
    where
        F: Fn(&'a str, &'a PKey<Private>, &'a str) -> Fut,
        Fut: Future<Output = Result<T>>,
        P: Fn(&T) -> bool,
    {
        let mut resource = fetcher(url, private_key, account_id).await?;
        let mut attempts: usize = 0;

        while !predicate(&resource) {
            if attempts >= max_attempts {
                return Err(Error::MaxAttemptsExceeded);
            }

            time::sleep(interval).await;

            resource = fetcher(url, private_key, account_id).await?;
            attempts += 1;
        }

        Ok(resource)
    }

    /// Get the solver for the challenge, if it exists.
    pub fn solver_for(&self, challenge: &responses::Challenge) -> Option<&dyn Solver> {
        self.0.solvers.get(challenge.type_)
    }
}

impl Clone for Api {
    fn clone(&self) -> Self {
        Api(Arc::clone(&self.0))
    }
}

fn location_header(response: &Response) -> Result<String> {
    Ok(response
        .headers()
        .get(header::LOCATION)
        .ok_or(Error::MissingHeader("location"))?
        .to_str()
        .map_err(|e| Error::InvalidHeader("location", e))?
        .to_owned())
}

#[cfg(test)]
mod tests {
    use super::Api;
    use crate::{
        solver::SolverManager,
        test::{client, TEST_URL},
        LETS_ENCRYPT_STAGING_URL,
    };
    use test_log::test;

    async fn create_api(url: String) -> Api {
        Api::from_url(url, client(), 10, SolverManager::default())
            .await
            .unwrap()
    }

    #[test(tokio::test)]
    async fn new_api_lets_encrypt() {
        let api = create_api(LETS_ENCRYPT_STAGING_URL.to_string()).await;

        assert_eq!(
            api.0.urls.new_nonce,
            "https://acme-staging-v02.api.letsencrypt.org/acme/new-nonce"
        );
        assert_eq!(
            api.0.urls.new_account,
            "https://acme-staging-v02.api.letsencrypt.org/acme/new-acct"
        );
        assert_eq!(
            api.0.urls.new_order,
            "https://acme-staging-v02.api.letsencrypt.org/acme/new-order"
        );
        assert_eq!(
            api.0.urls.revoke_cert,
            "https://acme-staging-v02.api.letsencrypt.org/acme/revoke-cert"
        );
        assert_eq!(
            api.0.urls.key_change,
            "https://acme-staging-v02.api.letsencrypt.org/acme/key-change"
        );
        assert_eq!(api.0.urls.new_authz, None);
    }

    #[test(tokio::test)]
    async fn new_api_pebble() {
        let api = create_api(TEST_URL.to_string()).await;

        assert_eq!(api.0.urls.new_nonce, "https://10.30.50.2:14000/nonce-plz");
        assert_eq!(
            api.0.urls.new_account,
            "https://10.30.50.2:14000/sign-me-up"
        );
        assert_eq!(api.0.urls.new_order, "https://10.30.50.2:14000/order-plz");
        assert_eq!(
            api.0.urls.revoke_cert,
            "https://10.30.50.2:14000/revoke-cert"
        );
        assert_eq!(
            api.0.urls.key_change,
            "https://10.30.50.2:14000/rollover-account-key"
        );
        assert_eq!(api.0.urls.new_authz, None);
    }
}