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

* feat(acm): provision AWS::CertificateManager::Certificate

Adds AcmCfnProvisioner over the existing AcmService. Ref and
Fn::GetAtt CertificateArn both resolve to the certificate ARN instead
of the stub's literal "LogicalId.CertificateArn". Maps DomainName,
SubjectAlternativeNames, ValidationMethod (default DNS), KeyAlgorithm
and Tags; DomainValidationOptions is accepted and ignored because the
certificate is ISSUED at once, there is nothing to validate locally.

UpdateStack: a change to a createOnly property (DomainName,
SubjectAlternativeNames, KeyAlgorithm) requests a new certificate and
deletes the previous one; otherwise tags are reconciled in place.
Delete tolerates an already removed certificate and lets
ResourceInUseException propagate.

Tests: AcmCfnProvisionerTest (attribute keys, update paths, delete),
AcmCfnIntegrationTest (stack output is an ARN DescribeCertificate
finds, gone after DeleteStack). Inventory TSV, fixture wiring and the
generated resource-type table updated.

* fix(acm): remove the replacement certificate when the prior one cannot be deleted

On a replacing update, a failure deleting the previous certificate
(ResourceInUseException, for one) made the update fail after the new
certificate existed. CloudFormationService restores the previous
StackResource on a failed update and never learns the new ARN, which
orphaned that certificate. Delete it and mark the resource restored
for the rollback walker, as Route53CfnProvisioner does for zones.

Also pins that a ValidationMethod-only update keeps the certificate:
the property is writeOnly in the registry schema and "No interruption"
in the AWS docs, and ACM has no call to change it on an issued
certificate.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-03 23:46:03 -04:00
1 parent de92212b1b
commit 38176b9e05
7 files changed
+496

No files matched your search

@@ -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);
}
}
@@ -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;
@@ -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));
}
}