aws-manager 0.30.4

AWS SDK manager
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
use std::collections::HashMap;

use crate::errors::{self, Error, Result};
use aws_sdk_acmpca::{
    operation::delete_certificate_authority::DeleteCertificateAuthorityError,
    types::{
        Asn1Subject, CertificateAuthority, CertificateAuthorityConfiguration,
        CertificateAuthorityStatus, CertificateAuthorityType, CertificateAuthorityUsageMode,
        KeyAlgorithm, RevocationReason, SigningAlgorithm, Tag, Validity, ValidityPeriodType,
    },
    Client,
};
use aws_smithy_client::SdkError;
use aws_types::SdkConfig as AwsSdkConfig;
use tokio::fs;

/// Implements AWS Private CA manager.
#[derive(Debug, Clone)]
pub struct Manager {
    pub region: String,
    pub cli: Client,
}

impl Manager {
    pub fn new(shared_config: &AwsSdkConfig) -> Self {
        Self {
            region: shared_config.region().unwrap().to_string(),
            cli: Client::new(shared_config),
        }
    }

    /// Creates a new private root CA with RSA2048 key algorithm and SHA256 RSA signing algorithm.
    /// ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_CreateCertificateAuthority.html>
    /// ref. <https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-acmpca-certificateauthority.html>
    /// ref. <https://docs.aws.amazon.com/privateca/latest/userguide/Create-CA-CLI.html>
    pub async fn create_root_ca(
        &self,
        org: &str,
        common_name: &str,
        tags: Option<HashMap<String, String>>,
    ) -> Result<String> {
        log::info!("creating a new private CA with org '{org}' and common name '{common_name}'");

        let mut req = self
            .cli
            .create_certificate_authority()
            .certificate_authority_type(CertificateAuthorityType::Root)
            .usage_mode(CertificateAuthorityUsageMode::GeneralPurpose)
            .certificate_authority_configuration(
                CertificateAuthorityConfiguration::builder()
                    .key_algorithm(KeyAlgorithm::Rsa2048)
                    .signing_algorithm(SigningAlgorithm::Sha256Withrsa)
                    .subject(
                        Asn1Subject::builder()
                            .country("US")
                            .organization(org)
                            .common_name(common_name)
                            .build(),
                    )
                    .build(),
            );
        if let Some(tags) = &tags {
            for (k, v) in tags.iter() {
                req = req.tags(Tag::builder().key(k).value(v).build());
            }
        }

        let resp = match req.send().await {
            Ok(v) => v,
            Err(e) => {
                return Err(Error::API {
                    message: format!("failed create_certificate_authority {:?}", e),
                    retryable: errors::is_sdk_err_retryable(&e),
                });
            }
        };

        let ca_arn = resp.certificate_authority_arn().unwrap().to_owned();
        log::info!("successfully created a private CA '{ca_arn}'");

        Ok(ca_arn)
    }

    /// Disables the private CA.
    /// Note that self-signed cert cannot be revoked.
    /// ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_UpdateCertificateAuthority.html>
    pub async fn disable_ca(&self, ca_arn: &str) -> Result<()> {
        log::info!("disabling private CA '{ca_arn}'");
        match self
            .cli
            .update_certificate_authority()
            .certificate_authority_arn(ca_arn)
            .status(CertificateAuthorityStatus::Disabled)
            .send()
            .await
        {
            Ok(_) => log::info!("successfully disabled the private CA"),
            Err(e) => {
                return Err(Error::API {
                    message: format!("failed update_certificate_authority {:?}", e),
                    retryable: errors::is_sdk_err_retryable(&e),
                });
            }
        };

        Ok(())
    }

    /// Deletes a private CA.
    pub async fn delete_ca(&self, ca_arn: &str) -> Result<()> {
        log::info!("deleting private CA '{ca_arn}'");
        match self
            .cli
            .delete_certificate_authority()
            .certificate_authority_arn(ca_arn)
            .send()
            .await
        {
            Ok(_) => log::info!("successfully deleted the private CA"),
            Err(e) => {
                if is_err_not_found_delete_certificate_authority(&e) {
                    log::warn!(
                        "private CA '{ca_arn}' not found thus no need to delete ({})",
                        e
                    );
                    return Ok(());
                }
                return Err(Error::API {
                    message: format!("failed delete_certificate_authority {:?}", e),
                    retryable: errors::is_sdk_err_retryable(&e)
                        || is_err_retryable_delete_certificate_authority(&e),
                });
            }
        };

        Ok(())
    }

    /// Describes a private root CA.
    pub async fn describe_ca(&self, ca_arn: &str) -> Result<CertificateAuthority> {
        log::info!("describing private CA '{ca_arn}'");
        let resp = match self
            .cli
            .describe_certificate_authority()
            .certificate_authority_arn(ca_arn)
            .send()
            .await
        {
            Ok(v) => v,
            Err(e) => {
                return Err(Error::API {
                    message: format!("failed describe_certificate_authority {:?}", e),
                    retryable: errors::is_sdk_err_retryable(&e),
                });
            }
        };

        let ca = resp.certificate_authority().unwrap();
        Ok(ca.clone())
    }

    /// Get the certificate, and returns the certificate in the base64-encoded PEM format.
    /// ref. <https://docs.aws.amazon.com/privateca/latest/userguide/PCACertInstall.html#InstallRoot>
    /// ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_GetCertificateAuthorityCsr.html>
    pub async fn get_ca_csr(&self, ca_arn: &str) -> Result<String> {
        log::info!("getting CSR for CA '{ca_arn}'");

        // ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_GetCertificateAuthorityCsr.html>
        let resp = match self
            .cli
            .get_certificate_authority_csr()
            .certificate_authority_arn(ca_arn)
            .send()
            .await
        {
            Ok(v) => v,
            Err(e) => {
                return Err(Error::API {
                    message: format!("failed get_certificate_authority_certificate {:?}", e),
                    retryable: errors::is_sdk_err_retryable(&e),
                });
            }
        };

        let csr_pem = resp.csr().unwrap();
        Ok(csr_pem.to_string())
    }

    /// Issues a new certificate with SHA256 RSA signing algorithm from the root CA.
    /// And returns the created certificate arn.
    /// CSR must be for the root. Otherwise fails with "Root CA CSR is not provided".
    /// ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_IssueCertificate.html>
    /// ref. <https://docs.aws.amazon.com/privateca/latest/userguide/PCACertInstall.html#InstallRoot>
    /// ref. <https://docs.aws.amazon.com/privateca/latest/userguide/UsingTemplates.html>
    pub async fn issue_self_signed_cert_from_root_ca(
        &self,
        root_ca_arn: &str,
        valid_days: i64,
        csr_blob: aws_smithy_types::Blob,
    ) -> Result<String> {
        log::info!(
            "with CSR, issuing self-signed cert from root CA '{root_ca_arn}' with valid days {valid_days}"
        );

        // ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_IssueCertificate.html#API_IssueCertificate_RequestSyntax>
        let resp = match self
            .cli
            .issue_certificate()
            .certificate_authority_arn(root_ca_arn)
            .signing_algorithm(SigningAlgorithm::Sha256Withrsa)
            .validity(
                Validity::builder()
                    .r#type(ValidityPeriodType::Days)
                    .value(valid_days)
                    .build(),
            )
            .csr(csr_blob)
            // ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_IssueCertificate.html#privateca-IssueCertificate-request-TemplateArn>
            // ref. <https://docs.aws.amazon.com/privateca/latest/userguide/PCACertInstall.html#InstallRoot>
            // ref. <https://docs.aws.amazon.com/privateca/latest/userguide/UsingTemplates.html>
            // ref. <https://docs.aws.amazon.com/privateca/latest/userguide/UsingTemplates.html#RootCACertificate-V1>
            .template_arn("arn:aws:acm-pca:::template/RootCACertificate/V1")
            .send()
            .await
        {
            Ok(v) => v,
            Err(e) => {
                return Err(Error::API {
                    message: format!("failed issue_certificate {:?}", e),
                    retryable: errors::is_sdk_err_retryable(&e),
                });
            }
        };

        let issued_cert_arn = resp.certificate_arn().unwrap();
        log::info!("successfully issued cert '{issued_cert_arn}' for root CA '{root_ca_arn}'");

        Ok(issued_cert_arn.to_string())
    }

    /// The root CA must be "ACTIVE" in order to issue this cert.
    /// Make sure the valid days is within the root CA validation period.
    /// Otherwise, "The certificate validity specified exceeds the certificate authority validity".
    /// ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_IssueCertificate.html>
    /// ref. <https://docs.aws.amazon.com/privateca/latest/userguide/PCACertInstall.html#InstallRoot>
    /// ref. <https://docs.aws.amazon.com/privateca/latest/userguide/UsingTemplates.html>
    pub async fn issue_end_cert_from_root_ca(
        &self,
        root_ca_arn: &str,
        valid_days: i64,
        csr_blob: aws_smithy_types::Blob,
    ) -> Result<String> {
        log::info!(
            "with CSR, issuing end cert from root CA '{root_ca_arn}' with valid days {valid_days}"
        );

        // ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_IssueCertificate.html#API_IssueCertificate_RequestSyntax>
        let resp = match self
            .cli
            .issue_certificate()
            .certificate_authority_arn(root_ca_arn)
            .signing_algorithm(SigningAlgorithm::Sha256Withrsa)
            .validity(
                Validity::builder()
                    .r#type(ValidityPeriodType::Days)
                    .value(valid_days)
                    .build(),
            )
            .csr(csr_blob)
            // ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_IssueCertificate.html#privateca-IssueCertificate-request-TemplateArn>
            // ref. <https://docs.aws.amazon.com/privateca/latest/userguide/PCACertInstall.html#InstallRoot>
            // ref. <https://docs.aws.amazon.com/privateca/latest/userguide/UsingTemplates.html>
            // ref. <https://docs.aws.amazon.com/privateca/latest/userguide/UsingTemplates.html#EndEntityCertificate-V1>
            .template_arn("arn:aws:acm-pca:::template/EndEntityCertificate/V1")
            .send()
            .await
        {
            Ok(v) => v,
            Err(e) => {
                return Err(Error::API {
                    message: format!("failed issue_certificate {:?}", e),
                    retryable: errors::is_sdk_err_retryable(&e),
                });
            }
        };

        let issued_cert_arn = resp.certificate_arn().unwrap();
        log::info!("successfully issued cert '{issued_cert_arn}' for root CA '{root_ca_arn}'");

        Ok(issued_cert_arn.to_string())
    }

    /// Get the certificate, and returns the certificate in the base64-encoded PEM format.
    /// ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_GetCertificate.html>
    /// ref. <https://docs.aws.amazon.com/privateca/latest/userguide/PCACertInstall.html#InstallRoot>
    pub async fn get_cert_pem(&self, ca_arn: &str, cert_arn: &str) -> Result<String> {
        log::info!("getting cert PEM '{cert_arn}' for CA '{ca_arn}'");

        // ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_GetCertificate.html>
        // ref. <https://docs.aws.amazon.com/privateca/latest/userguide/PCACertInstall.html#InstallRoot>
        let resp = match self
            .cli
            .get_certificate()
            .certificate_authority_arn(ca_arn)
            .certificate_arn(cert_arn)
            .send()
            .await
        {
            Ok(v) => v,
            Err(e) => {
                return Err(Error::API {
                    message: format!("failed get_certificate {:?}", e),
                    retryable: errors::is_sdk_err_retryable(&e),
                });
            }
        };

        let cert_pem = resp.certificate().unwrap();
        Ok(cert_pem.to_string())
    }

    /// Imports the base64-encoded PEM formatted certificate into the CA.
    /// Can only import a self-signed cert if the CA is a type root.
    /// ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_ImportCertificateAuthorityCertificate.html>
    /// ref. <https://docs.aws.amazon.com/privateca/latest/userguide/PCACertInstall.html#InstallRoot>
    pub async fn import_cert(&self, cert_file_path: &str, ca_arn: &str) -> Result<()> {
        log::info!("importing cert PEM '{cert_file_path}' to CA '{ca_arn}'");
        let cert_raw = fs::read(cert_file_path).await.map_err(|e| Error::Other {
            message: format!("failed File::open {:?}", e),
            retryable: false,
        })?;

        // ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_ImportCertificateAuthorityCertificate.html>
        // ref. <https://docs.aws.amazon.com/privateca/latest/userguide/PCACertInstall.html#InstallRoot>
        let _ = match self
            .cli
            .import_certificate_authority_certificate()
            .certificate(aws_smithy_types::Blob::new(cert_raw))
            .certificate_authority_arn(ca_arn)
            .send()
            .await
        {
            Ok(_) => {
                log::info!("successfully imported cert PEM '{cert_file_path}' to CA '{ca_arn}'");
            }
            Err(e) => {
                return Err(Error::API {
                    message: format!("failed import_certificate_authority_certificate {:?}", e),
                    retryable: errors::is_sdk_err_retryable(&e),
                });
            }
        };

        Ok(())
    }

    /// Get the imported CA certificate, and returns the certificate in the base64-encoded PEM format.
    /// Fails if the CA is still pending certificate.
    /// ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_GetCertificateAuthorityCertificate.html>
    pub async fn get_ca_cert_pem(&self, ca_arn: &str) -> Result<String> {
        log::info!("getting cert PEM for CA '{ca_arn}'");

        // ref. <https://docs.aws.amazon.com/privateca/latest/APIReference/API_GetCertificateAuthorityCertificate.html>
        let resp = match self
            .cli
            .get_certificate_authority_certificate()
            .certificate_authority_arn(ca_arn)
            .send()
            .await
        {
            Ok(v) => v,
            Err(e) => {
                return Err(Error::API {
                    message: format!("failed get_certificate_authority_certificate {:?}", e),
                    retryable: errors::is_sdk_err_retryable(&e),
                });
            }
        };

        let cert_pem = resp.certificate().unwrap();
        Ok(cert_pem.to_string())
    }

    /// Revokes the private CA.
    /// Note that self-signed cert cannot be revoked.
    pub async fn revoke_ca(&self, ca_arn: &str, cert_serial: &str) -> Result<()> {
        log::info!("revoking a private CA '{ca_arn}'");
        match self
            .cli
            .revoke_certificate()
            .certificate_authority_arn(ca_arn)
            .certificate_serial(cert_serial)
            .revocation_reason(RevocationReason::CessationOfOperation)
            .send()
            .await
        {
            Ok(_) => log::info!("successfully disabled the private CA"),
            Err(e) => {
                return Err(Error::API {
                    message: format!("failed revoke_certificate {:?}", e),
                    retryable: errors::is_sdk_err_retryable(&e),
                });
            }
        };

        Ok(())
    }
}

#[inline]
pub fn is_err_retryable_delete_certificate_authority(
    e: &SdkError<
        DeleteCertificateAuthorityError,
        aws_smithy_runtime_api::client::orchestrator::HttpResponse,
    >,
) -> bool {
    match e {
        SdkError::ServiceError(err) => err.err().is_concurrent_modification_exception(),
        _ => false,
    }
}

#[inline]
pub fn is_err_not_found_delete_certificate_authority(
    e: &SdkError<
        DeleteCertificateAuthorityError,
        aws_smithy_runtime_api::client::orchestrator::HttpResponse,
    >,
) -> bool {
    match e {
        SdkError::ServiceError(err) => err.err().is_resource_not_found_exception(),
        _ => false,
    }
}