diff --git a/docs/services/cloudfront.md b/docs/services/cloudfront.md
index f4ef3d5754..93ca144782 100644
--- a/docs/services/cloudfront.md
+++ b/docs/services/cloudfront.md
@@ -457,6 +457,8 @@ These operations store what they are given and return it, so code that manages t
created with no `ViewerCertificate` at all reads the same way, the default certificate on `TLSv1`.
The `us-east-1` restriction AWS states for ACM certificates is not enforced: a certificate is
resolved from whatever region its ARN names, as long as it exists.
+- `AWS::CloudFront::Distribution` passes `ViewerCertificate` through, on create and on update, so the
+ certificate and protocol rules above apply to a stack the same way they do to the API.
- `ConnectionMode` is stored and returned by `GetDistribution`, `GetDistributionConfig`,
`ListDistributions` and the create and update responses, and `AWS::CloudFront::Distribution`
passes it through. It is held to `direct` and `tenant-only`; anything else is `InvalidArgument`
diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/AcmCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/AcmCfnProvisioner.java
index 119f17a1ff..7ed6e4476e 100644
--- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/AcmCfnProvisioner.java
+++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/AcmCfnProvisioner.java
@@ -11,6 +11,7 @@ import io.floci.aws.services.cloudformation.model.StackResource;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
+import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -27,6 +28,12 @@ import java.util.Set;
* certificate's options. The first is createOnly in the registry schema, so a change replaces the
* certificate; the second updates in place through {@code UpdateCertificateOptions}, as
* CloudFormation does.
+ *
+ *
A replacement creates the new certificate and leaves the displaced one to
+ * {@link ReplacementCleanup}: it is deleted once the stack update commits, after the resources that
+ * referenced it (a CloudFront distribution, an API Gateway domain) moved to the new one, because ACM
+ * refuses to delete a certificate that is still in use. A failed update deletes the new certificate
+ * and points the resource back at the old one.
*/
@ApplicationScoped
public class AcmCfnProvisioner implements CfnResourceProvisioner {
@@ -47,6 +54,12 @@ public class AcmCfnProvisioner implements CfnResourceProvisioner {
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ if (ctx.isUpdate()) {
+ // The rollback undoes this update; only ContinueUpdateRollback retries the delete the
+ // last rollback could not make.
+ ReplacementCleanup.endRollbackRetry(r);
+ }
+ Map attributesBefore = new HashMap<>(r.getAttributes());
String domainName = ctx.resolveOptional(props, "DomainName");
if (domainName == null || domainName.isBlank()) {
throw new AwsException("ValidationError", "AWS::CertificateManager::Certificate requires DomainName", 400);
@@ -61,9 +74,8 @@ public class AcmCfnProvisioner implements CfnResourceProvisioner {
CertificateOptions options = new CertificateOptions(transparencyLogging, export);
// DomainName, SubjectAlternativeNames, KeyAlgorithm and CertificateExport 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.
+ // the schema: a change to any of them replaces the certificate, and the previous one is left
+ // to ReplacementCleanup. 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, export)) {
@@ -73,12 +85,10 @@ public class AcmCfnProvisioner implements CfnResourceProvisioner {
} else {
arn = acmService.requestCertificate(domainName, sans, validationMethod, null,
keyAlgorithm, null, options, tags, ctx.region()).getArn();
- if (existing != null) {
- deletePriorOrUnwind(r, existing.getArn(), arn, ctx.region());
- }
}
r.setPhysicalId(arn);
r.getAttributes().put("CertificateArn", arn);
+ ReplacementCleanup.record(r, ctx, attributesBefore);
}
@Override
@@ -87,22 +97,29 @@ public class AcmCfnProvisioner implements CfnResourceProvisioner {
() -> 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;
- }
+ @Override
+ public boolean hasReplacementUpdate(StackResource resource) {
+ return ReplacementCleanup.hasReplacement(resource);
+ }
+
+ @Override
+ public String updateCleanupPhysicalId(StackResource resource) {
+ return ReplacementCleanup.cleanupPhysicalId(resource);
+ }
+
+ @Override
+ public UpdateCleanupResult completeUpdate(StackResource resource) {
+ return ReplacementCleanup.complete(resource, this::delete);
+ }
+
+ @Override
+ public void clearUpdate(StackResource resource) {
+ ReplacementCleanup.clear(resource);
+ }
+
+ @Override
+ public boolean rollbackUpdate(StackResource resource) {
+ return ReplacementCleanup.rollback(resource, this::delete);
}
private Certificate findExisting(String arn, String region) {
diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java
index 2abf09c2d1..69212da0f7 100644
--- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java
+++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisioner.java
@@ -28,6 +28,7 @@ import java.util.Base64;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
@@ -532,6 +533,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
config.setDefaultCacheBehavior(cfnDefaultCacheBehavior(dc.path("DefaultCacheBehavior"), engine));
config.setCacheBehaviors(cfnCacheBehaviors(dc, engine));
config.setCustomErrorResponses(cfnCustomErrorResponses(dc, engine));
+ config.setViewerCertificate(cfnViewerCertificate(dc.path("ViewerCertificate"), engine));
}
Distribution dist = new Distribution();
@@ -549,6 +551,27 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("DomainName", dist.getDomainName());
r.getAttributes().put("Arn", dist.getArn());
}
+
+ /**
+ * The template's {@code ViewerCertificate} under the API member names the REST controller stores,
+ * so the service's certificate rules read it the same way. Only members the template sets are
+ * carried; a template with none leaves the config unset, which the service reads as the default
+ * certificate.
+ */
+ private Map cfnViewerCertificate(JsonNode node, CloudFormationTemplateEngine engine) {
+ if (node == null || !node.isObject()) {
+ return null;
+ }
+ Map certificate = new LinkedHashMap<>();
+ putIfPresent(certificate, "ACMCertificateArn", cfnText(node, "AcmCertificateArn", engine));
+ putIfPresent(certificate, "IAMCertificateId", cfnText(node, "IamCertificateId", engine));
+ putIfPresent(certificate, "CloudFrontDefaultCertificate",
+ cfnText(node, "CloudFrontDefaultCertificate", engine).toLowerCase(Locale.ROOT));
+ putIfPresent(certificate, "MinimumProtocolVersion", cfnText(node, "MinimumProtocolVersion", engine));
+ putIfPresent(certificate, "SSLSupportMethod", cfnText(node, "SslSupportMethod", engine));
+ return certificate.isEmpty() ? null : certificate;
+ }
+
private List cfnOrigins(JsonNode dc, CloudFormationTemplateEngine engine) {
List origins = new ArrayList<>();
JsonNode items = dc.path("Origins");
@@ -665,7 +688,7 @@ public class CloudFrontCfnProvisioner implements CfnResourceProvisioner {
}
return result;
}
- private static void putIfPresent(Map map, String key, String value) {
+ private static void putIfPresent(Map map, String key, String value) {
if (value != null && !value.isEmpty()) {
map.put(key, value);
}
diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java
index 12a181b7c3..b675ed5050 100644
--- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationCloudFrontDistributionIntegrationTest.java
@@ -1,5 +1,9 @@
package io.floci.aws.services.cloudformation;
+import io.floci.aws.core.common.AwsException;
+import io.floci.aws.services.acm.AcmService;
+import io.floci.aws.services.acm.CertificateGenerator;
+import io.floci.aws.services.acm.model.KeyAlgorithm;
import io.floci.aws.services.cloudfront.CloudFrontService;
import io.floci.aws.services.cloudfront.model.Distribution;
import io.floci.aws.services.cloudfront.model.KeyGroup;
@@ -17,13 +21,16 @@ import java.security.KeyPairGenerator;
import java.util.Base64;
import java.util.List;
import java.util.Map;
+import java.util.UUID;
import static io.restassured.RestAssured.given;
+import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.xml.HasXPath.hasXPath;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* End-to-end check that CloudFormation provisions an {@code AWS::CloudFront::Distribution} for real
@@ -44,6 +51,9 @@ class CloudFormationCloudFrontDistributionIntegrationTest {
@Inject
CloudFrontService cloudFrontService;
+ @Inject
+ AcmService acmService;
+
@Test
void createStackProvisionsBrowsableDistributionWithResolvedDomainName() {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -422,4 +432,162 @@ class CloudFormationCloudFrontDistributionIntegrationTest {
.body(hasXPath("//*[local-name()='DistributionConfig']/*[local-name()='ConnectionMode']",
equalTo("tenant-only")));
}
+
+ @Test
+ void createStackRefusesSslv3WithSniOnlyOnTheViewerCertificate() {
+ String stackName = "cfn-cloudfront-sslv3-" + Long.toString(System.nanoTime(), 36);
+ String template = """
+ {
+ "Resources": {
+ "Dist": {
+ "Type": "AWS::CloudFront::Distribution",
+ "Properties": {
+ "DistributionConfig": {
+ "Enabled": true,
+ "Origins": [{
+ "Id": "origin",
+ "DomainName": "origin.example.com",
+ "CustomOriginConfig": {"OriginProtocolPolicy": "https-only"}
+ }],
+ "DefaultCacheBehavior": {
+ "TargetOriginId": "origin",
+ "ViewerProtocolPolicy": "redirect-to-https"
+ },
+ "ViewerCertificate": {
+ "AcmCertificateArn": "%s",
+ "SslSupportMethod": "sni-only",
+ "MinimumProtocolVersion": "SSLv3"
+ }
+ }
+ }
+ }
+ }
+ }
+ """.formatted("arn:aws:acm:us-east-1:000000000000:certificate/" + UUID.randomUUID());
+
+ CfnRequests.deploy("CreateStack", stackName, template, CFN_AUTH, "ROLLBACK_COMPLETE");
+
+ assertThat(CfnStackWaits.failedResourceReason(stackName, CFN_AUTH), containsString(
+ "You cannot specify SSLv3 as the minimum protocol version if you only want to "
+ + "support only clients that support Server Name Indication (SNI)."));
+ }
+
+ @Test
+ void createStackCarriesTheViewerCertificateOntoTheDistribution() {
+ String stackName = "cfn-cloudfront-viewer-cert-" + Long.toString(System.nanoTime(), 36);
+ CertificateGenerator.GeneratedCertificate pair = new CertificateGenerator()
+ .generateSelfSignedCertificate("cfn.certs.test.local", List.of(), KeyAlgorithm.EC_prime256v1);
+ String certificateArn = acmService.importCertificate(
+ pair.certificatePem(), pair.privateKeyPem(), null, null, Map.of(), "us-east-1").getArn();
+ String template = """
+ {
+ "Resources": {
+ "Dist": {
+ "Type": "AWS::CloudFront::Distribution",
+ "Properties": {
+ "DistributionConfig": {
+ "Enabled": true,
+ "Origins": [{
+ "Id": "origin",
+ "DomainName": "origin.example.com",
+ "CustomOriginConfig": {"OriginProtocolPolicy": "https-only"}
+ }],
+ "DefaultCacheBehavior": {
+ "TargetOriginId": "origin",
+ "ViewerProtocolPolicy": "redirect-to-https"
+ },
+ "ViewerCertificate": {
+ "AcmCertificateArn": "%s",
+ "SslSupportMethod": "sni-only",
+ "MinimumProtocolVersion": "TLSv1.2_2021"
+ }
+ }
+ }
+ }
+ }
+ }
+ """.formatted(certificateArn);
+
+ CfnRequests.deploy("CreateStack", stackName, template, CFN_AUTH, "CREATE_COMPLETE");
+ String distributionId = CfnRequests.physicalId(stackName, "Dist", CFN_AUTH);
+
+ given()
+ .when()
+ .get("/2020-05-31/distribution/" + distributionId)
+ .then()
+ .statusCode(200)
+ .body(hasXPath("//*[local-name()='ViewerCertificate']/*[local-name()='ACMCertificateArn']",
+ equalTo(certificateArn)))
+ .body(hasXPath("//*[local-name()='ViewerCertificate']/*[local-name()='SSLSupportMethod']",
+ equalTo("sni-only")))
+ .body(hasXPath("//*[local-name()='ViewerCertificate']/*[local-name()='MinimumProtocolVersion']",
+ equalTo("TLSv1.2_2021")));
+ }
+
+ @Test
+ void replacingTheViewerCertificateMovesTheDistributionOverBeforeTheOldOneIsDeleted() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = "cfn-cloudfront-cert-swap-" + suffix;
+ CfnRequests.deploy("CreateStack", stackName, certificateAndDistributionTemplate("old-" + suffix),
+ CFN_AUTH, "CREATE_COMPLETE");
+ String oldCertificateArn = CfnRequests.physicalId(stackName, "Cert", CFN_AUTH);
+ String distributionId = CfnRequests.physicalId(stackName, "Dist", CFN_AUTH);
+ assertThat(viewerCertificateArn(distributionId), equalTo(oldCertificateArn));
+
+ CfnRequests.deploy("UpdateStack", stackName, certificateAndDistributionTemplate("new-" + suffix),
+ CFN_AUTH, "UPDATE_COMPLETE");
+
+ String newCertificateArn = CfnRequests.physicalId(stackName, "Cert", CFN_AUTH);
+ assertThat(newCertificateArn, not(equalTo(oldCertificateArn)));
+ assertThat(viewerCertificateArn(distributionId), equalTo(newCertificateArn));
+ AwsException gone = assertThrows(AwsException.class,
+ () -> acmService.describeCertificate(oldCertificateArn, "us-east-1"));
+ assertEquals("ResourceNotFoundException", gone.getErrorCode());
+ assertEquals(newCertificateArn, acmService.describeCertificate(newCertificateArn, "us-east-1").getArn());
+ }
+
+ private static String certificateAndDistributionTemplate(String certificateDomainLabel) {
+ return """
+ {
+ "Resources": {
+ "Cert": {
+ "Type": "AWS::CertificateManager::Certificate",
+ "Properties": {"DomainName": "%s.cfn-cloudfront.example.test"}
+ },
+ "Dist": {
+ "Type": "AWS::CloudFront::Distribution",
+ "Properties": {
+ "DistributionConfig": {
+ "Enabled": true,
+ "Origins": [{
+ "Id": "origin",
+ "DomainName": "origin.example.com",
+ "CustomOriginConfig": {"OriginProtocolPolicy": "https-only"}
+ }],
+ "DefaultCacheBehavior": {
+ "TargetOriginId": "origin",
+ "ViewerProtocolPolicy": "redirect-to-https"
+ },
+ "ViewerCertificate": {
+ "AcmCertificateArn": {"Ref": "Cert"},
+ "SslSupportMethod": "sni-only",
+ "MinimumProtocolVersion": "TLSv1.2_2021"
+ }
+ }
+ }
+ }
+ }
+ }
+ """.formatted(certificateDomainLabel);
+ }
+
+ private static String viewerCertificateArn(String distributionId) {
+ return given()
+ .when()
+ .get("/2020-05-31/distribution/" + distributionId)
+ .then()
+ .statusCode(200)
+ .extract().xmlPath()
+ .getString("**.find { it.name() == 'ACMCertificateArn' }");
+ }
}
diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/AcmCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/AcmCfnProvisionerTest.java
index d6815f784b..89bc97e801 100644
--- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/AcmCfnProvisionerTest.java
+++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/AcmCfnProvisionerTest.java
@@ -19,6 +19,7 @@ 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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -325,10 +326,10 @@ class AcmCfnProvisionerTest {
verify(acm).requestCertificate(eq("api.example.com"), any(), any(), isNull(), any(), isNull(),
eq(new CertificateOptions("ENABLED", "ENABLED")), any(), eq(REGION));
- verify(acm).deleteCertificate(ARN, REGION);
+ verify(acm, never()).deleteCertificate(any(), any());
verify(acm, never()).updateCertificateOptions(any(), any(), any());
assertEquals(NEW_ARN, r.getPhysicalId());
- assertEquals(Map.of("CertificateArn", NEW_ARN), r.getAttributes());
+ assertEquals(NEW_ARN, r.getAttributes().get("CertificateArn"));
}
@Test
@@ -341,7 +342,7 @@ class AcmCfnProvisionerTest {
verify(acm).requestCertificate(eq("api.example.com"), any(), any(), isNull(), any(), isNull(),
eq(new CertificateOptions("ENABLED", "DISABLED")), any(), eq(REGION));
- verify(acm).deleteCertificate(ARN, REGION);
+ verify(acm, never()).deleteCertificate(any(), any());
assertEquals(NEW_ARN, r.getPhysicalId());
}
@@ -358,7 +359,7 @@ class AcmCfnProvisionerTest {
verify(acm).requestCertificate(eq("api.example.com"), any(), any(), isNull(), any(), isNull(),
eq(new CertificateOptions("DISABLED", "ENABLED")), any(), eq(REGION));
- verify(acm).deleteCertificate(ARN, REGION);
+ verify(acm, never()).deleteCertificate(any(), any());
verify(acm, never()).updateCertificateOptions(any(), any(), any());
}
@@ -378,7 +379,7 @@ class AcmCfnProvisionerTest {
verify(acm).requestCertificate(eq("new.example.com"), any(), any(), isNull(), any(), isNull(),
eq(new CertificateOptions("DISABLED", "DISABLED")), any(), eq(REGION));
- verify(acm).deleteCertificate(ARN, REGION);
+ verify(acm, never()).deleteCertificate(any(), any());
verify(acm, never()).updateCertificateOptions(any(), any(), any());
}
@@ -408,31 +409,79 @@ class AcmCfnProvisionerTest {
provisioner.provision(r, mapper.createObjectNode().put("DomainName", "new.example.com"), ctx(ARN));
- verify(acm).deleteCertificate(ARN, REGION);
+ verify(acm, never()).deleteCertificate(any(), any());
assertEquals(NEW_ARN, r.getPhysicalId());
- assertEquals(Map.of("CertificateArn", NEW_ARN), r.getAttributes());
+ assertEquals(NEW_ARN, r.getAttributes().get("CertificateArn"));
}
- @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.
+ private StackResource replacedCertificate() {
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);
stubRequestCertificate("new.example.com", certificate(NEW_ARN, "new.example.com"));
+ StackResource r = resource();
+ r.setPhysicalId(ARN);
+ r.getAttributes().put("CertificateArn", ARN);
+ provisioner.provision(r, mapper.createObjectNode().put("DomainName", "new.example.com"), ctx(ARN));
+ return r;
+ }
+
+ @Test
+ void replacementLeavesThePriorCertificateToTheCleanupAfterTheUpdateCommits() {
+ StackResource r = replacedCertificate();
+
+ verify(acm, never()).deleteCertificate(any(), any());
+ assertTrue(provisioner.hasReplacementUpdate(r));
+ assertEquals(ARN, provisioner.updateCleanupPhysicalId(r));
+
+ UpdateCleanupResult result = provisioner.completeUpdate(r);
+
+ verify(acm).deleteCertificate(ARN, REGION);
+ verify(acm, never()).deleteCertificate(eq(NEW_ARN), any());
+ assertTrue(result.applicable());
+ assertTrue(result.complete());
+ assertEquals(ARN, result.previousPhysicalId());
+ provisioner.clearUpdate(r);
+ assertEquals(NEW_ARN, r.getPhysicalId());
+ assertEquals(Map.of("CertificateArn", NEW_ARN), r.getAttributes());
+ }
+
+ @Test
+ void cleanupThatFindsThePriorCertificateStillInUseKeepsItOwedAndCountsTheAttempt() {
+ StackResource r = replacedCertificate();
doThrow(new AwsException("ResourceInUseException", "in use", 400))
.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)));
+ UpdateCleanupResult result = provisioner.completeUpdate(r);
+
+ assertTrue(result.applicable());
+ assertFalse(result.complete());
+ assertEquals(ARN, result.previousPhysicalId());
+ assertEquals(1, result.attempts());
+ }
+
+ @Test
+ void rollbackRestoresThePriorCertificateAndDeletesTheNewOne() {
+ StackResource r = replacedCertificate();
+
+ assertTrue(provisioner.rollbackUpdate(r));
- assertEquals("ResourceInUseException", failure.getErrorCode());
verify(acm).deleteCertificate(NEW_ARN, REGION);
- assertEquals("true", r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
- assertNull(r.getPhysicalId());
+ verify(acm, never()).deleteCertificate(eq(ARN), any());
+ assertEquals(ARN, r.getPhysicalId());
+ assertEquals(Map.of("CertificateArn", ARN), r.getAttributes());
+ }
+
+ @Test
+ void rollbackOfAnInPlaceUpdateHasNothingToUndo() {
+ when(acm.describeCertificate(ARN, REGION)).thenReturn(storedCertificate("ENABLED", "DISABLED"));
+ StackResource r = resource();
+ provisioner.provision(r, mapper.createObjectNode().put("DomainName", "api.example.com"), ctx(ARN));
+
+ assertFalse(provisioner.rollbackUpdate(r));
+ assertFalse(provisioner.hasReplacementUpdate(r));
+ verify(acm, never()).deleteCertificate(any(), any());
}
@Test
diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java
index 545d5408ba..8204a0195e 100644
--- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java
+++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CloudFrontCfnProvisionerTest.java
@@ -24,6 +24,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -249,6 +250,76 @@ class CloudFrontCfnProvisionerTest {
assertNull(sent.getValue().getConfig().getConnectionMode());
}
+ /** A minimal DistributionConfig template carrying the given ViewerCertificate object, or none when null. */
+ private JsonNode withViewerCertificate(String viewerCertificate) throws Exception {
+ String fragment = viewerCertificate == null ? "" : "\"ViewerCertificate\": " + viewerCertificate + ",";
+ return json("{\"DistributionConfig\": {" + fragment
+ + "\"Origins\": [{\"Id\": \"o1\", \"DomainName\": \"origin.example.com\","
+ + " \"CustomOriginConfig\": {\"OriginProtocolPolicy\": \"https-only\"}}],"
+ + " \"DefaultCacheBehavior\": {\"TargetOriginId\": \"o1\","
+ + " \"ViewerProtocolPolicy\": \"redirect-to-https\"}}}");
+ }
+
+ @Test
+ void copiesTheAcmViewerCertificateTheTemplateDeclares() throws Exception {
+ when(cloudFront.createDistribution(any(), any())).thenReturn(distribution("E1DIST", "d111.cloudfront.net"));
+ StackResource r = resource(DISTRIBUTION);
+
+ provisioner.provision(r, withViewerCertificate("{\"AcmCertificateArn\": \"arn:aws:acm:us-east-1:000000000000:certificate/abc\", \"SslSupportMethod\": \"sni-only\", \"MinimumProtocolVersion\": \"TLSv1.2_2021\"}"),
+ distributionCtx(null));
+
+ ArgumentCaptor sent = ArgumentCaptor.forClass(Distribution.class);
+ verify(cloudFront).createDistribution(sent.capture(), any());
+ Map expected = new LinkedHashMap<>();
+ expected.put("ACMCertificateArn", "arn:aws:acm:us-east-1:000000000000:certificate/abc");
+ expected.put("SSLSupportMethod", "sni-only");
+ expected.put("MinimumProtocolVersion", "TLSv1.2_2021");
+ assertEquals(expected, sent.getValue().getConfig().getViewerCertificate());
+ }
+
+ @Test
+ void mapsTheIamCertificateIdOntoItsApiName() throws Exception {
+ when(cloudFront.createDistribution(any(), any())).thenReturn(distribution("E1DIST", "d111.cloudfront.net"));
+ StackResource r = resource(DISTRIBUTION);
+
+ provisioner.provision(r, withViewerCertificate("{\"IamCertificateId\": \"ASCAEXAMPLE\", \"SslSupportMethod\": \"vip\", \"MinimumProtocolVersion\": \"TLSv1\"}"),
+ distributionCtx(null));
+
+ ArgumentCaptor sent = ArgumentCaptor.forClass(Distribution.class);
+ verify(cloudFront).createDistribution(sent.capture(), any());
+ Map expected = new LinkedHashMap<>();
+ expected.put("IAMCertificateId", "ASCAEXAMPLE");
+ expected.put("SSLSupportMethod", "vip");
+ expected.put("MinimumProtocolVersion", "TLSv1");
+ assertEquals(expected, sent.getValue().getConfig().getViewerCertificate());
+ }
+
+ @Test
+ void rendersTheDefaultCertificateFlagAsText() throws Exception {
+ when(cloudFront.createDistribution(any(), any())).thenReturn(distribution("E1DIST", "d111.cloudfront.net"));
+ StackResource r = resource(DISTRIBUTION);
+
+ provisioner.provision(r, withViewerCertificate("{\"CloudFrontDefaultCertificate\": true}"),
+ distributionCtx(null));
+
+ ArgumentCaptor sent = ArgumentCaptor.forClass(Distribution.class);
+ verify(cloudFront).createDistribution(sent.capture(), any());
+ assertEquals(Map.of("CloudFrontDefaultCertificate", "true"),
+ sent.getValue().getConfig().getViewerCertificate());
+ }
+
+ @Test
+ void leavesTheViewerCertificateUnsetWhenTheTemplateOmitsIt() throws Exception {
+ when(cloudFront.createDistribution(any(), any())).thenReturn(distribution("E1DIST", "d111.cloudfront.net"));
+ StackResource r = resource(DISTRIBUTION);
+
+ provisioner.provision(r, withViewerCertificate(null), distributionCtx(null));
+
+ ArgumentCaptor sent = ArgumentCaptor.forClass(Distribution.class);
+ verify(cloudFront).createDistribution(sent.capture(), any());
+ assertNull(sent.getValue().getConfig().getViewerCertificate());
+ }
+
@Test
void aNonNumericOriginConnectionSettingFailsTheStackInsteadOfAServerError() {
StackResource r = resource(DISTRIBUTION);