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
429
430
431
432
433
434
435
use crate::{
    api::{Api, ExternalAccountOptions},
    certificate::{Certificate, CertificateBuilder},
    error::Result,
    responses::{self, AccountStatus, RevocationReason},
    Error,
};
use base64::engine::{general_purpose::URL_SAFE_NO_PAD as BASE64, Engine};
use openssl::hash::MessageDigest;
use openssl::{
    ec::{EcGroup, EcKey},
    nid::Nid,
    pkey::{PKey, Private},
    x509::X509,
};
use std::collections::HashSet;
use tracing::{field, instrument, Level, Span};

pub struct NoPrivateKey;
pub struct WithPrivateKey(PKey<Private>);

/// Used to configure a the creation/lookup of an account
pub struct AccountBuilder<'o, T> {
    api: Api,

    contacts: Option<Vec<String>>,
    terms_of_service_agreed: bool,
    private_key: T,
    external_account_options: Option<ExternalAccountOptions<'o>>,
}

impl<'o, T> AccountBuilder<'o, T> {
    pub(crate) fn new(api: Api) -> AccountBuilder<'o, NoPrivateKey> {
        AccountBuilder {
            api,
            contacts: None,
            terms_of_service_agreed: false,
            private_key: NoPrivateKey,
            external_account_options: None,
        }
    }

    /// Specify whether the ToS for the CA are agreed to
    pub fn terms_of_service_agreed(mut self, agreed: bool) -> Self {
        self.terms_of_service_agreed = agreed;
        self
    }

    /// Set the account contacts
    pub fn contacts(mut self, contacts: Vec<String>) -> Self {
        self.contacts = Some(contacts);
        self
    }

    /// Set the external account credentials to bind this account to. The HMAC should be encoded
    /// using Base64 URL-encoding without padding.
    pub fn external_account(mut self, key_id: &'o str, hmac: &'o str) -> Self {
        self.external_account_options = Some(ExternalAccountOptions { kid: key_id, hmac });
        self
    }
}

impl<'o> AccountBuilder<'o, NoPrivateKey> {
    /// Set the account's private key
    pub fn private_key(self, key: PKey<Private>) -> AccountBuilder<'o, WithPrivateKey> {
        AccountBuilder {
            api: self.api,
            contacts: self.contacts,
            terms_of_service_agreed: self.terms_of_service_agreed,
            private_key: WithPrivateKey(key),
            external_account_options: self.external_account_options,
        }
    }

    /// Create the account if it doesn't already exists, returning the existing account if it does.
    /// Will generate a private key for the account.
    #[instrument(
        level = Level::INFO,
        name = "AccountBuilder<NoPrivateKey>::create_if_not_exists",
        err,
        skip_all,
        fields(
            account.id, account.status,
            ?self.contacts,
            ?self.terms_of_service_agreed,
            self.external_account_options.key_id = ?self.external_account_options.as_ref().map(|o| o.kid),
        ),
    )]
    pub async fn create_if_not_exists(self) -> Result<Account> {
        let key = {
            let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1)?;
            let ec = EcKey::generate(&group)?;
            PKey::from_ec_key(ec)?
        };

        let (id, account) = self
            .api
            .new_account(
                self.contacts,
                self.terms_of_service_agreed,
                false,
                self.external_account_options,
                &key,
            )
            .await?;
        Span::current().record("account.id", &id);
        Span::current().record("account.status", field::debug(account.status));

        into_account(self.api, key, id, account)
    }
}

impl<'o> AccountBuilder<'o, WithPrivateKey> {
    /// Lookup the account by private key, fails if it doesn't exist or a private key was
    /// not specified.
    #[instrument(
        level = Level::INFO,
        name = "AccountBuilder<WithPrivateKey>::lookup",
        err,
        skip_all,
        fields(
            account.id, account.status,
            ?self.contacts,
            ?self.terms_of_service_agreed,
            self.external_account_options.key_id = ?self.external_account_options.as_ref().map(|o| o.kid),
        ),
    )]
    pub async fn lookup(self) -> Result<Account> {
        let (id, account) = self
            .api
            .new_account(
                self.contacts,
                self.terms_of_service_agreed,
                true,
                self.external_account_options,
                &self.private_key.0,
            )
            .await?;
        Span::current().record("account.id", &id);
        Span::current().record("account.status", field::debug(&account.status));

        into_account(self.api, self.private_key.0, id, account)
    }

    /// Create the account if it doesn't already exists, returning the existing account if it does.
    #[instrument(
        level = Level::INFO,
        name = "AccountBuilder<WithPrivateKey>::create_if_not_exists",
        err,
        skip_all,
        fields(
            account.id, account.status,
            ?self.contacts,
            ?self.terms_of_service_agreed,
            self.external_account_options.key_id = ?self.external_account_options.as_ref().map(|o| o.kid),
        ),
    )]
    pub async fn create_if_not_exists(self) -> Result<Account> {
        let (id, account) = self
            .api
            .new_account(
                self.contacts,
                self.terms_of_service_agreed,
                false,
                self.external_account_options,
                &self.private_key.0,
            )
            .await?;
        Span::current().record("account.id", &id);
        Span::current().record("account.status", field::debug(&account.status));

        into_account(self.api, self.private_key.0, id, account)
    }
}

/// Finalize the creation of the account
fn into_account(
    api: Api,
    private_key: PKey<Private>,
    id: String,
    account: responses::Account,
) -> Result<Account> {
    if account.status != AccountStatus::Valid {
        return Err(Error::InvalidAccount(account.status));
    }

    Ok(Account {
        api,
        private_key,
        id,
    })
}

/// An ACME account. This is used to identify a subscriber to an ACME server.
#[derive(Debug)]
pub struct Account {
    pub(crate) api: Api,
    pub(crate) private_key: PKey<Private>,
    pub(crate) id: String,
}

impl Account {
    /// Get the private key for the account
    pub fn private_key(&self) -> &PKey<Private> {
        &self.private_key
    }

    /// Access the builder to issue a new certificate.
    pub fn certificate(&self) -> CertificateBuilder {
        CertificateBuilder::new(self)
    }

    /// Renew a certificate
    #[instrument(
        level = Level::INFO,
        name = "Account::renew_certificate",
        err,
        skip_all,
        fields(self.id, certificate = %certificate.digest()),
    )]
    pub async fn renew_certificate(&self, certificate: Certificate) -> Result<Certificate> {
        let inner = certificate.x509();
        let mut domains = HashSet::new();

        // Extract the common name
        if let Some(name) = inner
            .subject_name()
            .entries()
            .find(|e| e.object().nid() == Nid::COMMONNAME)
        {
            let domain = name.data().as_utf8()?.to_string();
            domains.insert(domain);
        }

        // Extract any SANs
        if let Some(alt_names) = inner.subject_alt_names() {
            for name in alt_names {
                if let Some(domain) = name.dnsname() {
                    domains.insert(domain.to_owned());
                }
            }
        }

        // Build the request
        let mut builder = self.certificate().private_key(certificate.private_key);
        for domain in domains.into_iter() {
            builder = builder.add_domain(domain);
        }

        builder.obtain().await
    }

    /// Revoke a certificate
    #[instrument(
        level = Level::INFO,
        name = "Account::revoke_certificate",
        err,
        skip_all,
        fields(self.id, certificate = %x509_digest(certificate)),
    )]
    pub async fn revoke_certificate(&self, certificate: &X509) -> Result<()> {
        let der = BASE64.encode(certificate.to_der()?);
        self.api
            .revoke_certificate(der, None, &self.private_key, Some(&self.id))
            .await
    }

    /// Revoke a certificate with a reason.
    #[instrument(
        level = Level::INFO,
        name = "Account::revoke_certificate_with_reason",
        err,
        skip(self, certificate),
        fields(self.id, certificate = %x509_digest(certificate)),
    )]
    pub async fn revoke_certificate_with_reason(
        &self,
        certificate: &X509,
        reason: RevocationReason,
    ) -> Result<()> {
        let der = BASE64.encode(certificate.to_der()?);
        self.api
            .revoke_certificate(der, Some(reason), &self.private_key, Some(&self.id))
            .await
    }
}

fn x509_digest(certificate: &X509) -> String {
    let digest = certificate
        .digest(MessageDigest::sha256())
        .expect("digest should always succeed");
    hex::encode(digest)
}

#[cfg(test)]
mod tests {
    use crate::{responses::ErrorType, test::directory, Error};
    use once_cell::sync::Lazy;
    use openssl::{
        ec::{EcGroup, EcKey},
        nid::Nid,
        pkey::{PKey, Private},
    };
    use parking_lot::Mutex;
    use std::{collections::HashSet, fs};
    use test_log::test;

    static ACCOUNT_IDS: Lazy<Mutex<HashSet<String>>> = Lazy::new(|| {
        let raw = fs::read("testdata/account-ids.json").unwrap();
        let ids = serde_json::from_slice(&raw).unwrap();
        Mutex::new(ids)
    });

    fn private_key(account: u8) -> PKey<Private> {
        let pem = fs::read(format!("testdata/accounts/{account}.pem")).unwrap();
        PKey::private_key_from_pem(&pem).unwrap()
    }

    #[test(tokio::test)]
    async fn lookup_when_exists() {
        let directory = directory().await;
        let account = directory
            .account()
            .contacts(vec!["mailto:exists@lookup.test".into()])
            .private_key(private_key(1))
            .lookup()
            .await
            .unwrap();

        let mut ids = ACCOUNT_IDS.lock();
        assert!(!ids.insert(account.id));
    }

    #[test(tokio::test)]
    async fn lookup_when_does_not_exists() {
        let directory = directory().await;

        let key = {
            let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
            let ec = EcKey::generate(&group).unwrap();
            PKey::from_ec_key(ec).unwrap()
        };
        let result = directory
            .account()
            .contacts(vec!["mailto:does-not-exist@lookup.test".into()])
            .private_key(key)
            .lookup()
            .await;

        let Error::Server(error) = result.unwrap_err() else { panic!("must be server error") };
        assert_eq!(error.type_, ErrorType::AccountDoesNotExist);
        assert_eq!(error.title, None);
        assert_eq!(
            error.detail,
            Some("unable to find existing account for only-return-existing request".into())
        );
        assert_eq!(error.status, Some(400));
        assert!(error.subproblems.is_none());
    }

    #[test(tokio::test)]
    async fn create_if_not_exists_when_does_not_exist() {
        let directory = directory().await;
        let account = directory
            .account()
            .terms_of_service_agreed(true)
            .contacts(vec!["mailto:does-not-exist@create.test".into()])
            .create_if_not_exists()
            .await
            .unwrap();

        let mut ids = ACCOUNT_IDS.lock();
        assert!(ids.insert(account.id));
    }

    #[test(tokio::test)]
    async fn create_if_not_exists_when_exists() {
        let directory = directory().await;
        let account = directory
            .account()
            .terms_of_service_agreed(true)
            .contacts(vec!["mailto:exists@create.test".into()])
            .private_key(private_key(2))
            .create_if_not_exists()
            .await
            .unwrap();

        let mut ids = ACCOUNT_IDS.lock();
        assert!(!ids.insert(account.id));
    }

    #[test(tokio::test)]
    async fn create_if_not_exists_with_external_account() {
        let directory = directory().await;
        let account = directory
            .account()
            .terms_of_service_agreed(true)
            .contacts(vec!["mailto:external-account@create.test".into()])
            .external_account(
                "V6iRR0p3",
                "zWNDZM6eQGHWpSRTPal5eIUYFTu7EajVIoguysqZ9wG44nMEtx3MUAsUDkMTQ12W",
            )
            .create_if_not_exists()
            .await
            .unwrap();

        let mut ids = ACCOUNT_IDS.lock();
        assert!(ids.insert(account.id));
    }

    #[test(tokio::test)]
    async fn create_if_not_exists_with_non_existent_external_account() {
        let directory = directory().await;
        let result = directory
            .account()
            .terms_of_service_agreed(true)
            .contacts(vec!["mailto:external-account@create.test".into()])
            .external_account(
                "this-does-not-exist",
                "zWNDZM6eQGHWpSRTPal5eIUYFTu7EajVIoguysqZ9wG44nMEtx3MUAsUDkMTQ12W",
            )
            .create_if_not_exists()
            .await;

        let Error::Server(error) = result.unwrap_err() else { panic!("must be server error") };
        assert_eq!(error.type_, ErrorType::Unauthorized);
        assert_eq!(error.title, None);
        assert_eq!(
            error.detail,
            Some("the field 'kid' references a key that is not known to the ACME server".into())
        );
        assert_eq!(error.status, Some(403));
        assert!(error.subproblems.is_none());
    }
}