yacme 5.0.1

Yet another ACME client.
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
//! Client for sending HTTP requests to an ACME server

use reqwest::header::HeaderMap;
use reqwest::Certificate;
use serde::{Deserialize, Serialize};

use crate::protocol::errors::AcmeHTTPError;

use super::errors::{AcmeError, AcmeErrorCode, AcmeErrorDocument};
use super::jose::Nonce;
use super::request::Key;
use super::response::{Decode, Response};
use super::Request;
use super::Url;

pub use AcmeClient as Client;

#[cfg(feature = "trace-requests")]
use jaws::fmt::JWTFormat;

#[cfg(feature = "trace-requests")]
use super::request::Encode;

const NONCE_HEADER: &str = "Replay-Nonce";

/// Builder struct for an ACME HTTP client.
#[derive(Debug)]
pub struct ClientBuilder {
    inner: reqwest::ClientBuilder,
    new_nonce: Option<Url>,
    configuration: AcmeClientConfiguration,
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl ClientBuilder {
    pub(crate) fn new() -> Self {
        let builder =
            reqwest::Client::builder().user_agent(concat!("YACME / ", env!("CARGO_PKG_VERSION")));

        ClientBuilder {
            inner: builder,
            new_nonce: None,
            configuration: Default::default(),
        }
    }

    /// Set the URL to use to fetch a new nonce.
    ///
    /// This is used to bootstrap the nonce at the start of an interaction
    /// with an ACME provider, and to acquire a new nonce if an old one
    /// ends up invalidated. Both of these actions happen transparently
    /// when using the [`Client::execute`] method, to ensure that the JWT always
    /// contains a valid nonce.
    pub fn with_nonce_url(mut self, url: Url) -> Self {
        self.new_nonce = Some(url);
        self
    }

    /// Add a custom root certificate to the underlying [`reqwest::Client`].
    ///
    /// This is useful if you are using a self-signed certificate from your ACME
    /// provider for testing, e.g. when using [Pebble](https://github.com/letsencrypt/pebble).
    pub fn add_root_certificate(mut self, cert: Certificate) -> Self {
        self.inner = self.inner.add_root_certificate(cert);
        self
    }

    /// Set a timeout on the underlying [`reqwest::Client`].
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.inner = self.inner.timeout(timeout);
        self
    }

    /// Set a connect timeout on the underlying [`reqwest::Client`].
    pub fn connect_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.inner = self.inner.connect_timeout(timeout);
        self
    }

    /// Set the number of retries to use when a bad nonce is encountered.
    pub fn bad_nonce_retries(mut self, retries: usize) -> Self {
        self.configuration.nonce_retries = retries;
        self
    }

    /// Finalize this and build this client. See [`reqwest::ClientBuilder::build`].
    pub fn build(self) -> Result<AcmeClient, reqwest::Error> {
        Ok(AcmeClient {
            inner: self.inner.build()?,
            nonce: None,
            new_nonce: self.new_nonce,
            configuration: self.configuration,
        })
    }
}

/// Client configuration specific to ACME
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AcmeClientConfiguration {
    /// How many times to retry when a bad nonce is encountered.
    pub nonce_retries: usize,
}

impl Default for AcmeClientConfiguration {
    fn default() -> Self {
        Self { nonce_retries: 3 }
    }
}

/// ACME HTTP Client
///
/// The client handles sending ACME HTTP requests, and providing ACME HTTP
/// responses using the [`super::Request`] and [`super::Response`] objects
/// respectively.
///
/// # Example
///
/// You can use a Client to send HTTP requests to an ACME provider, using either
/// [`Client::get`] to send a plain HTTP GET request, or [`Client::execute`] to
/// send a signed ACME HTTP request.
///
/// See [`super::Request`] for more information on how to create a request.
///
/// ```no_run
/// # use std::sync::Arc;
/// # use yacme::protocol::AcmeClient;
/// # use yacme::protocol::Request;
/// # use yacme::protocol::Response;
/// # use signature::rand_core::OsRng;
/// #
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
///
/// let key: Arc<::ecdsa::SigningKey<p256::NistP256>> = Arc::new(::ecdsa::SigningKey::random(&mut OsRng));
///
/// let mut client = AcmeClient::default();
/// client.set_new_nonce_url("https://acme.example.com/new-nonce".parse().unwrap());
///
/// let request = Request::get("https://acme.example.com/account/1".parse().unwrap(), key);
/// // This would normally be an actual response payload type, and not serde_json::Value.
/// let response: Response<serde_json::Value> = client.execute(request).await?;
///
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Default)]
pub struct AcmeClient {
    pub(super) inner: reqwest::Client,
    nonce: Option<Nonce>,
    new_nonce: Option<Url>,
    configuration: AcmeClientConfiguration,
}

impl AcmeClient {
    /// Create a new client builder to configure a client.
    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    /// Set the URL used for fetching a new Nonce from the ACME provider.
    pub fn set_new_nonce_url(&mut self, url: Url) {
        self.new_nonce = Some(url);
    }
}

impl AcmeClient {
    /// Run a plain HTTP `GET` request without using the ACME HTTP JWS
    /// protocol.
    pub async fn get<R>(&mut self, url: Url) -> Result<Response<R>, AcmeError>
    where
        R: Decode,
    {
        let response = self.inner.get(url.as_str()).send().await?;
        Response::from_decoded_response(response).await
    }

    /// Submit a post request to the ACME provider, using the ACME HTTP JWS
    #[cfg(all(feature = "trace-requests", not(doc)))]
    pub async fn post<P, K, L, R>(
        &mut self,
        url: Url,
        payload: P,
        key: K,
    ) -> Result<Response<R>, AcmeError>
    where
        P: Serialize,
        R: Decode + Encode,
        K: Into<Key<L>>,
        L: jaws::algorithms::TokenSigner<jaws::SignatureBytes>,
    {
        let request = Request::post(payload, url, key);
        self.execute(request).await
    }

    /// Submit a post-as-get request to the ACME provider, using the ACME HTTP JWS
    #[cfg(all(feature = "trace-requests", not(doc)))]
    pub async fn get_as_post<K, L, R>(&mut self, url: Url, key: K) -> Result<Response<R>, AcmeError>
    where
        R: Decode + Encode,
        K: Into<Key<L>>,
        L: jaws::algorithms::TokenSigner<jaws::SignatureBytes>,
    {
        let request = Request::get(url, key);
        self.execute(request).await
    }

    /// Submit a post request to the ACME provider, using the ACME HTTP JWS
    #[cfg(any(not(feature = "trace-requests"), doc))]
    pub async fn post<P, K, L, R>(
        &mut self,
        url: Url,
        payload: P,
        key: K,
    ) -> Result<Response<R>, AcmeError>
    where
        P: Serialize,
        R: Decode,
        K: Into<Key<L>>,
        L: jaws::algorithms::TokenSigner<jaws::SignatureBytes>,
    {
        let request = Request::post(payload, url, key);
        self.execute(request).await
    }

    /// Submit a post-as-get request to the ACME provider, using the ACME HTTP JWS
    #[cfg(any(not(feature = "trace-requests"), doc))]
    pub async fn get_as_post<K, L, R>(&mut self, url: Url, key: K) -> Result<Response<R>, AcmeError>
    where
        R: Decode,
        K: Into<Key<L>>,
        L: jaws::algorithms::TokenSigner<jaws::SignatureBytes>,
    {
        let request = Request::get(url, key);
        self.execute(request).await
    }

    /// Execute an HTTP request using the ACME protocol.
    ///
    /// See [`super::Request`] for more information on how to create a request.
    ///
    /// Request payloads must be serializable, and request responses must implement [`Decode`].
    /// `Decode` is implemented for all types that implement [`serde::Deserialize`].
    #[cfg(any(not(feature = "trace-requests"), doc))]
    pub async fn execute<P, K, R>(
        &mut self,
        request: Request<P, K>,
    ) -> Result<Response<R>, AcmeError>
    where
        P: Serialize,
        R: Decode,
        K: jaws::algorithms::TokenSigner<jaws::SignatureBytes>,
    {
        Response::from_decoded_response(self.execute_internal(request).await?).await
    }

    /// Execute an HTTP request using the ACME protocol, and trace the request.
    ///
    /// Tracing is done using the [RFC 8885](https://tools.ietf.org/html/rfc8885) format,
    /// via the `tracing` crate, at the `trace` level.
    #[cfg(all(feature = "trace-requests", not(doc)))]
    pub async fn execute<P, K, R>(
        &mut self,
        request: Request<P, K>,
    ) -> Result<Response<R>, AcmeError>
    where
        P: Serialize,
        R: Decode + Encode,
        K: jaws::algorithms::TokenSigner<jaws::SignatureBytes>,
    {
        tracing::trace!("REQ: \n{}", request.as_signed().formatted());
        Response::from_decoded_response(self.execute_internal(request).await?)
            .await
            .inspect(|r| {
                tracing::trace!("RES: \n{}", r.formatted());
            })
    }

    #[inline]
    async fn execute_internal<P, K>(
        &mut self,
        request: Request<P, K>,
    ) -> Result<reqwest::Response, AcmeError>
    where
        P: Serialize,
        K: jaws::algorithms::TokenSigner<jaws::SignatureBytes>,
    {
        let mut nonce = self.get_nonce().await?;
        for retry in 0..self.configuration.nonce_retries {
            let signed = request.sign(nonce)?;
            let response = self.inner.execute(signed.into_inner()).await?;
            self.record_nonce(response.headers())?;
            if response.status().is_success() {
                return Ok(response);
            }

            match process_error_response(response).await {
                AcmeError::Acme(document) if matches!(document.kind(), AcmeErrorCode::BadNonce) => {
                    tracing::trace!(%retry, "Retrying request with next nonce");
                    nonce = self.get_nonce().await?;
                }
                error => {
                    return Err(error);
                }
            }
        }

        tracing::trace!("Nonce retries exhausted");
        Err(AcmeError::NonceRetriesExhausted(
            self.configuration.nonce_retries,
        ))
    }
}

async fn process_error_response(response: reqwest::Response) -> AcmeError {
    debug_assert!(
        !response.status().is_success(),
        "expected to process an error result"
    );
    let status = response.status();
    let body = match response.bytes().await {
        Ok(body) => body,
        Err(error) => {
            return AcmeError::HttpRequest(error);
        }
    };

    if body.is_empty() {
        return AcmeHTTPError::new(status, None).into();
    }

    let document: AcmeErrorDocument = match serde_json::from_slice(&body) {
        Ok(error) => error,
        Err(error) if status.is_client_error() => {
            tracing::error!(%status, "Failed to parse error document {}: {}", error, String::from_utf8_lossy(&body));
            return AcmeHTTPError::new(status, Some(body)).into();
        }
        Err(_) => {
            let text = String::from_utf8_lossy(&body);
            tracing::trace!(%status, "RES: \n{}", text);
            return AcmeHTTPError::new(status, Some(body)).into();
        }
    };

    let text = String::from_utf8_lossy(&body);
    tracing::trace!(%document, "RES: \n{}", text);

    AcmeError::Acme(document)
}

pub(crate) fn extract_nonce(headers: &HeaderMap) -> Result<Nonce, AcmeError> {
    let value = headers.get(NONCE_HEADER).ok_or(AcmeError::MissingNonce)?;
    Ok(Nonce::from(
        value
            .to_str()
            .map_err(|_| AcmeError::InvalidNonce(Some(value.clone())))?
            .to_owned(),
    ))
}

impl AcmeClient {
    fn record_nonce(&mut self, headers: &HeaderMap) -> Result<(), AcmeError> {
        self.nonce = Some(extract_nonce(headers)?);
        Ok(())
    }

    async fn get_nonce(&mut self) -> Result<Nonce, AcmeError> {
        if let Some(value) = self.nonce.take() {
            return Ok(value);
        }

        if let Some(url) = &self.new_nonce {
            tracing::debug!("Requesting a new nonce");
            let response = self
                .inner
                .head(url.as_str())
                .send()
                .await
                .map_err(AcmeError::nonce)?;

            response.error_for_status_ref().map_err(AcmeError::nonce)?;

            let value = extract_nonce(response.headers())?;
            Ok(value)
        } else {
            tracing::warn!("No nonce URL provided, unable to fetch new nonce");
            Err(AcmeError::MissingNonce)
        }
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn extract_nonce_from_header() {
        let response = crate::response!("new-nonce.http");
        let nonce = extract_nonce(response.headers()).unwrap();
        assert_eq!(nonce.as_ref(), "oFvnlFP1wIhRlYS2jTaXbA");
    }
}