Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(acm): provision AWS::CertificateManager::Certificate (#3003)

Mario Toffia38176b9e054b
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 9295005c99..1962ac6a8d 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -80,6 +80,7 @@ cross-resource references.
| CodeBuild | `Project` |
| Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` |
| Cognito | `UserPool`, `UserPoolClient` |
+| ACM | `Certificate` |
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy` |
| EventBridge Scheduler | `ScheduleGroup` |
| Pipes | `Pipe` |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AcmCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AcmCfnProvisioner.java
new file mode 100644
index 0000000000..33ebf1e5fb
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AcmCfnProvisioner.java
@@ -0,0 +1,133 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.acm.AcmService;
+import io.github.hectorvent.floci.services.acm.model.Certificate;
+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
+import io.github.hectorvent.floci.services.acm.model.ValidationMethod;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import jakarta.enterprise.context.ApplicationScoped;
+import org.jboss.logging.Logger;
+
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Provisions {@code AWS::CertificateManager::Certificate}.
+ *
+ * <p>The certificate is ISSUED as soon as it is requested. Real ACM waits for DNS or email
+ * validation and CloudFormation waits with it; the emulator has nothing to validate, so
+ * {@code DomainValidationOptions} is accepted and ignored.
+ */
+@ApplicationScoped
+public class AcmCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final Logger LOG = Logger.getLogger(AcmCfnProvisioner.class);
+
+ private final AcmService acmService;
+
+ public AcmCfnProvisioner(AcmService acmService) {
+ this.acmService = acmService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of("AWS::CertificateManager::Certificate");
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String domainName = ctx.resolveOptional(props, "DomainName");
+ if (domainName == null || domainName.isBlank()) {
+ throw new IllegalArgumentException("AWS::CertificateManager::Certificate requires DomainName");
+ }
+ List<String> sans = ctx.resolveStringList(props, "SubjectAlternativeNames");
+ String method = ctx.resolveOptional(props, "ValidationMethod");
+ ValidationMethod validationMethod = method == null ? ValidationMethod.DNS : ValidationMethod.valueOf(method);
+ KeyAlgorithm keyAlgorithm = KeyAlgorithm.fromAwsName(ctx.resolveOptional(props, "KeyAlgorithm"));
+ Map<String, String> tags = ctx.resolveTags(props, "Tags");
+
+ // DomainName, SubjectAlternativeNames and KeyAlgorithm are createOnly in the schema: a change
+ // to any of them replaces the certificate, and there is no generic replacement flow, so the
+ // previous one is deleted here once the new one exists. Anything else updates in place.
+ Certificate existing = ctx.isUpdate() ? findExisting(ctx.priorPhysicalId(), ctx.region()) : null;
+ String arn;
+ if (existing != null && sameCreateOnlyProperties(existing, domainName, sans, keyAlgorithm)) {
+ arn = existing.getArn();
+ reconcileTags(arn, tags, ctx.region());
+ } else {
+ arn = acmService.requestCertificate(domainName, sans, validationMethod, null,
+ keyAlgorithm, null, null, tags, ctx.region()).getArn();
+ if (existing != null) {
+ deletePriorOrUnwind(r, existing.getArn(), arn, ctx.region());
+ }
+ }
+ r.setPhysicalId(arn);
+ r.getAttributes().put("CertificateArn", arn);
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ CfnDeletes.safeDelete("certificate", physicalId,
+ () -> acmService.deleteCertificate(physicalId, region), "ResourceNotFoundException");
+ }
+
+ /**
+ * Removes the certificate a replacement supersedes. If that fails (ResourceInUseException, for
+ * one), the update fails and CloudFormationService restores the previous StackResource without
+ * ever learning the new ARN, so the certificate this attempt created is removed here and the
+ * rollback walker is told the prior one is intact.
+ */
+ private void deletePriorOrUnwind(StackResource r, String priorArn, String newArn, String region) {
+ try {
+ delete(r.getResourceType(), priorArn, region);
+ } catch (AwsException failure) {
+ LOG.warnv("Could not delete certificate {0} replaced by {1}, removing the replacement: {2}",
+ priorArn, newArn, failure.getMessage());
+ acmService.deleteCertificate(newArn, region);
+ r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
+ throw failure;
+ }
+ }
+
+ private Certificate findExisting(String arn, String region) {
+ try {
+ return acmService.describeCertificate(arn, region);
+ } catch (AwsException e) {
+ if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
+ throw e;
+ }
+ LOG.debugv("Certificate {0} from the previous execution is gone, requesting a new one", arn);
+ return null;
+ }
+ }
+
+ private static boolean sameCreateOnlyProperties(Certificate existing, String domainName,
+ List<String> sans, KeyAlgorithm keyAlgorithm) {
+ Set<String> desiredNames = new LinkedHashSet<>();
+ desiredNames.add(domainName);
+ desiredNames.addAll(sans);
+ Set<String> storedNames = existing.getSubjectAlternativeNames() == null
+ ? Set.of(existing.getDomainName())
+ : new LinkedHashSet<>(existing.getSubjectAlternativeNames());
+ return domainName.equals(existing.getDomainName())
+ && desiredNames.equals(storedNames)
+ && keyAlgorithm == existing.getKeyAlgorithm();
+ }
+
+ private void reconcileTags(String arn, Map<String, String> desired, String region) {
+ List<Map<String, String>> stale = ProvisionContext
+ .staleTagKeys(acmService.listTagsForCertificate(arn, region), desired).stream()
+ .map(key -> Map.of("Key", key))
+ .toList();
+ if (!stale.isEmpty()) {
+ acmService.removeTagsFromCertificate(arn, stale, region);
+ }
+ if (!desired.isEmpty()) {
+ acmService.addTagsToCertificate(arn, desired, region);
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/AcmCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AcmCfnIntegrationTest.java
new file mode 100644
index 0000000000..c717c6e17e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AcmCfnIntegrationTest.java
@@ -0,0 +1,109 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Provisions an {@code AWS::CertificateManager::Certificate} through a CloudFormation stack and
+ * asserts that {@code Ref} and {@code Fn::GetAtt CertificateArn} are a real ARN that ACM's
+ * {@code DescribeCertificate} finds. A status-only assertion would pass for the stub arm too,
+ * where the attribute resolves to the literal {@code Cert.CertificateArn}.
+ */
+@QuarkusTest
+class AcmCfnIntegrationTest {
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260903/us-east-1/cloudformation/aws4_request";
+ private static final String ACM_CONTENT_TYPE = "application/x-amz-json-1.1";
+ private static final String STACK = "acm-cfn-it";
+
+ private static final String TEMPLATE = """
+ {
+ "Resources": {
+ "Cert": {
+ "Type": "AWS::CertificateManager::Certificate",
+ "Properties": {
+ "DomainName": "api.cfn-it.example.com",
+ "SubjectAlternativeNames": ["www.cfn-it.example.com"],
+ "ValidationMethod": "DNS",
+ "DomainValidationOptions": [
+ {"DomainName": "api.cfn-it.example.com", "HostedZoneId": "Z0000000000000000000A"}
+ ],
+ "Tags": [{"Key": "stack", "Value": "acm-cfn-it"}]
+ }
+ }
+ },
+ "Outputs": {
+ "CertRef": {"Value": {"Ref": "Cert"}},
+ "CertArn": {"Value": {"Fn::GetAtt": ["Cert", "CertificateArn"]}}
+ }
+ }
+ """;
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void certificateStackExposesAnArnThatDescribeCertificateFinds() {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", STACK)
+ .formParam("TemplateBody", TEMPLATE)
+ .when().post("/").then().statusCode(200);
+
+ String stacks = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", STACK)
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
+ .extract().asString();
+
+ String arn = outputValue(stacks, "CertArn");
+ assertTrue(arn.startsWith("arn:aws:acm:us-east-1:"), "Fn::GetAtt CertificateArn must be an ARN: " + arn);
+ assertEquals(arn, outputValue(stacks, "CertRef"));
+
+ describeCertificate(arn).then()
+ .statusCode(200)
+ .body("Certificate.CertificateArn", equalTo(arn))
+ .body("Certificate.DomainName", equalTo("api.cfn-it.example.com"))
+ .body("Certificate.Status", equalTo("ISSUED"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", STACK)
+ .when().post("/").then().statusCode(200);
+
+ describeCertificate(arn).then()
+ .statusCode(404)
+ .body("__type", equalTo("ResourceNotFoundException"));
+ }
+
+ private static io.restassured.response.Response describeCertificate(String arn) {
+ return given()
+ .header("X-Amz-Target", "CertificateManager.DescribeCertificate")
+ .contentType(ACM_CONTENT_TYPE)
+ .body("{\"CertificateArn\": \"" + arn + "\"}")
+ .when().post("/");
+ }
+
+ private static String outputValue(String xml, String key) {
+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index 8dac67a320..06de9a0f64 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
+import io.github.hectorvent.floci.services.acm.AcmService;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
@@ -20,6 +21,7 @@ import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.wafv2.WafV2Service;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.AcmCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayAccountCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
@@ -133,6 +135,7 @@ final class CfnProvisionerFixture {
private KinesisService kinesisService;
private CloudWatchMetricsService cloudWatchMetricsService;
private AutoScalingService autoScalingService;
+ private AcmService acmService;
private FirehoseService firehoseService;
private DocDbService docDbService;
private CloudFrontService cloudFrontService;
@@ -227,6 +230,9 @@ final class CfnProvisionerFixture {
if (autoScalingService != null) {
discovered.add(new AutoScalingLifecycleHookCfnProvisioner(autoScalingService));
}
+ if (acmService != null) {
+ discovered.add(new AcmCfnProvisioner(acmService));
+ }
if (lambdaService != null) {
discovered.add(new LambdaAddressingCfnProvisioner(lambdaService));
discovered.add(new LambdaVersionAliasCfnProvisioner(lambdaService));
@@ -421,6 +427,11 @@ final class CfnProvisionerFixture {
return this;
}
+ public Builder acm(AcmService v) {
+ this.acmService = v;
+ return this;
+ }
+
public Builder firehose(FirehoseService v) {
this.firehoseService = v;
return this;
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AcmCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AcmCfnProvisionerTest.java
new file mode 100644
index 0000000000..e1c92dbac9
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AcmCfnProvisionerTest.java
@@ -0,0 +1,239 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.acm.AcmService;
+import io.github.hectorvent.floci.services.acm.model.Certificate;
+import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
+import io.github.hectorvent.floci.services.acm.model.ValidationMethod;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * The ACM CFN provisioner in isolation: one mocked service. Every case asserts the exact physical
+ * id and the exact {@code Fn::GetAtt} attribute keys, since an unmapped type still reports
+ * CREATE_COMPLETE through the dispatcher's stub arm.
+ */
+class AcmCfnProvisionerTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String ARN = "arn:aws:acm:us-east-1:000000000000:certificate/11111111-2222-3333-4444-555555555555";
+
+ private final AcmService acm = mock(AcmService.class);
+ private final AcmCfnProvisioner provisioner = new AcmCfnProvisioner(acm);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ return ctx(null);
+ }
+
+ private ProvisionContext ctx(String priorPhysicalId) {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
+ }
+
+ private StackResource resource() {
+ StackResource r = new StackResource();
+ r.setLogicalId("Cert");
+ r.setResourceType("AWS::CertificateManager::Certificate");
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private static Certificate certificate(String arn, String domainName) {
+ Certificate cert = new Certificate();
+ cert.setArn(arn);
+ cert.setDomainName(domainName);
+ return cert;
+ }
+
+ @Test
+ void certificateSetsArnAsPhysicalIdAndCertificateArnAttribute() {
+ when(acm.requestCertificate(eq("api.example.com"), any(), any(), isNull(), any(), isNull(), any(), any(), eq(REGION)))
+ .thenReturn(certificate(ARN, "api.example.com"));
+ StackResource r = resource();
+ ObjectNode props = mapper.createObjectNode().put("DomainName", "api.example.com");
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals(ARN, r.getPhysicalId());
+ assertEquals(Map.of("CertificateArn", ARN), r.getAttributes());
+ }
+
+ @Test
+ void certificatePassesTemplatePropertiesToRequestCertificate() {
+ when(acm.requestCertificate(any(), any(), any(), isNull(), any(), isNull(), any(), any(), eq(REGION)))
+ .thenReturn(certificate(ARN, "api.example.com"));
+ StackResource r = resource();
+ ObjectNode props = mapper.createObjectNode()
+ .put("DomainName", "api.example.com")
+ .put("ValidationMethod", "EMAIL")
+ .put("KeyAlgorithm", "EC_prime256v1");
+ props.putArray("SubjectAlternativeNames").add("www.example.com");
+ props.putArray("Tags").addObject().put("Key", "env").put("Value", "test");
+
+ provisioner.provision(r, props, ctx());
+
+ verify(acm).requestCertificate("api.example.com", List.of("www.example.com"), ValidationMethod.EMAIL,
+ null, KeyAlgorithm.EC_prime256v1, null, null, Map.of("env", "test"), REGION);
+ }
+
+ @Test
+ void validationMethodDefaultsToDns() {
+ when(acm.requestCertificate(any(), any(), any(), isNull(), any(), isNull(), any(), any(), eq(REGION)))
+ .thenReturn(certificate(ARN, "api.example.com"));
+
+ provisioner.provision(resource(), mapper.createObjectNode().put("DomainName", "api.example.com"), ctx());
+
+ verify(acm).requestCertificate(eq("api.example.com"), eq(List.of()), eq(ValidationMethod.DNS), isNull(),
+ eq(KeyAlgorithm.RSA_2048), isNull(), isNull(), eq(Map.of()), eq(REGION));
+ }
+
+ @Test
+ void updateWithUnchangedCreateOnlyPropertiesKeepsTheCertificateAndReconcilesTags() {
+ Certificate stored = certificate(ARN, "api.example.com");
+ stored.setSubjectAlternativeNames(List.of("api.example.com", "www.example.com"));
+ stored.setKeyAlgorithm(KeyAlgorithm.RSA_2048);
+ when(acm.describeCertificate(ARN, REGION)).thenReturn(stored);
+ when(acm.listTagsForCertificate(ARN, REGION)).thenReturn(Map.of("stale", "x", "env", "old"));
+ StackResource r = resource();
+ ObjectNode props = mapper.createObjectNode().put("DomainName", "api.example.com");
+ props.putArray("SubjectAlternativeNames").add("www.example.com");
+ props.putArray("Tags").addObject().put("Key", "env").put("Value", "test");
+
+ provisioner.provision(r, props, ctx(ARN));
+
+ verify(acm, never()).requestCertificate(any(), any(), any(), any(), any(), any(), any(), any(), any());
+ verify(acm, never()).deleteCertificate(any(), any());
+ verify(acm).removeTagsFromCertificate(ARN, List.of(Map.of("Key", "stale")), REGION);
+ verify(acm).addTagsToCertificate(ARN, Map.of("env", "test"), REGION);
+ assertEquals(ARN, r.getPhysicalId());
+ assertEquals(Map.of("CertificateArn", ARN), r.getAttributes());
+ }
+
+ @Test
+ void updateWithChangedDomainNameReplacesTheCertificate() {
+ String newArn = "arn:aws:acm:us-east-1:000000000000:certificate/99999999-2222-3333-4444-555555555555";
+ Certificate stored = certificate(ARN, "old.example.com");
+ stored.setSubjectAlternativeNames(List.of("old.example.com"));
+ stored.setKeyAlgorithm(KeyAlgorithm.RSA_2048);
+ when(acm.describeCertificate(ARN, REGION)).thenReturn(stored);
+ when(acm.requestCertificate(eq("new.example.com"), any(), any(), isNull(), any(), isNull(), any(), any(), eq(REGION)))
+ .thenReturn(certificate(newArn, "new.example.com"));
+ StackResource r = resource();
+
+ provisioner.provision(r, mapper.createObjectNode().put("DomainName", "new.example.com"), ctx(ARN));
+
+ verify(acm).deleteCertificate(ARN, REGION);
+ assertEquals(newArn, r.getPhysicalId());
+ assertEquals(Map.of("CertificateArn", newArn), r.getAttributes());
+ }
+
+ @Test
+ void replacementThatCannotDeleteThePriorCertificateRemovesTheNewOneAndFails() {
+ // CloudFormationService restores the previous StackResource when an update fails and never
+ // learns the new ARN, so the certificate this attempt created must not be left behind.
+ String newArn = "arn:aws:acm:us-east-1:000000000000:certificate/99999999-2222-3333-4444-555555555555";
+ Certificate stored = certificate(ARN, "old.example.com");
+ stored.setSubjectAlternativeNames(List.of("old.example.com"));
+ stored.setKeyAlgorithm(KeyAlgorithm.RSA_2048);
+ when(acm.describeCertificate(ARN, REGION)).thenReturn(stored);
+ when(acm.requestCertificate(eq("new.example.com"), any(), any(), isNull(), any(), isNull(), any(), any(), eq(REGION)))
+ .thenReturn(certificate(newArn, "new.example.com"));
+ doThrow(new AwsException("ResourceInUseException", "in use", 409))
+ .when(acm).deleteCertificate(ARN, REGION);
+ StackResource r = resource();
+
+ AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(
+ r, mapper.createObjectNode().put("DomainName", "new.example.com"), ctx(ARN)));
+
+ assertEquals("ResourceInUseException", failure.getErrorCode());
+ verify(acm).deleteCertificate(newArn, REGION);
+ assertEquals("true", r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
+ assertNull(r.getPhysicalId());
+ }
+
+ @Test
+ void updateChangingOnlyValidationMethodKeepsTheCertificate() {
+ // ValidationMethod is writeOnly in the registry schema and "No interruption" in the AWS
+ // docs: it matters only while a certificate is being issued, and ACM has no call to change
+ // it afterwards. So, as on AWS, an issued certificate is neither replaced nor touched.
+ Certificate stored = certificate(ARN, "api.example.com");
+ stored.setSubjectAlternativeNames(List.of("api.example.com"));
+ stored.setKeyAlgorithm(KeyAlgorithm.RSA_2048);
+ stored.setValidationMethod(ValidationMethod.DNS);
+ when(acm.describeCertificate(ARN, REGION)).thenReturn(stored);
+ StackResource r = resource();
+ ObjectNode props = mapper.createObjectNode()
+ .put("DomainName", "api.example.com")
+ .put("ValidationMethod", "EMAIL");
+
+ provisioner.provision(r, props, ctx(ARN));
+
+ verify(acm, never()).requestCertificate(any(), any(), any(), any(), any(), any(), any(), any(), any());
+ verify(acm, never()).deleteCertificate(any(), any());
+ assertEquals(ARN, r.getPhysicalId());
+ }
+
+ @Test
+ void updateWhosePriorCertificateIsGoneRequestsANewOne() {
+ when(acm.describeCertificate(ARN, REGION))
+ .thenThrow(new AwsException("ResourceNotFoundException", "gone", 404));
+ when(acm.requestCertificate(any(), any(), any(), isNull(), any(), isNull(), any(), any(), eq(REGION)))
+ .thenReturn(certificate(ARN, "api.example.com"));
+ StackResource r = resource();
+
+ provisioner.provision(r, mapper.createObjectNode().put("DomainName", "api.example.com"), ctx(ARN));
+
+ verify(acm, never()).deleteCertificate(any(), any());
+ assertEquals(ARN, r.getPhysicalId());
+ }
+
+ @Test
+ void deleteDelegatesToService() {
+ provisioner.delete("AWS::CertificateManager::Certificate", ARN, REGION);
+ verify(acm).deleteCertificate(ARN, REGION);
+ }
+
+ @Test
+ void deleteToleratesAnAlreadyDeletedCertificate() {
+ doThrow(new AwsException("ResourceNotFoundException", "gone", 404))
+ .when(acm).deleteCertificate(ARN, REGION);
+
+ assertDoesNotThrow(() -> provisioner.delete("AWS::CertificateManager::Certificate", ARN, REGION));
+ }
+
+ @Test
+ void deletePropagatesACertificateStillInUse() {
+ doThrow(new AwsException("ResourceInUseException", "in use", 409))
+ .when(acm).deleteCertificate(ARN, REGION);
+
+ assertThrows(AwsException.class,
+ () -> provisioner.delete("AWS::CertificateManager::Certificate", ARN, REGION));
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index f5baace543..33d43c1f35 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -18,6 +18,7 @@ AWS::Batch::ComputeEnvironment LEGACY_SWITCH
AWS::Batch::JobDefinition LEGACY_SWITCH
AWS::Batch::JobQueue LEGACY_SWITCH
AWS::CDK::Metadata CdkMetadataCfnProvisioner
+AWS::CertificateManager::Certificate AcmCfnProvisioner
AWS::CloudFormation::CustomResource LEGACY_SWITCH
AWS::CloudFront::Distribution LEGACY_SWITCH
AWS::CloudWatch::Alarm CloudWatchCfnProvisioner
diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml
index 01b4a96a6f..3ec07a6ab7 100644
--- a/tools/docs/cfn_resource_types.yaml
+++ b/tools/docs/cfn_resource_types.yaml
@@ -35,6 +35,7 @@ order:
- AWS::CodeBuild
- AWS::Batch
- AWS::Cognito
+ - AWS::CertificateManager
- AWS::Events
- AWS::Scheduler
- AWS::Pipes
@@ -98,6 +99,7 @@ service_labels:
AWS::AutoScaling: Auto Scaling
AWS::Batch: Batch
AWS::CDK: CDK
+ AWS::CertificateManager: ACM
AWS::CloudFormation: CloudFormation
AWS::CloudFront: CloudFront
AWS::CloudWatch: CloudWatch