fix(cloudformation): pass a distribution's ViewerCertificate through (#8952)

* fix(cloudformation): pass a distribution's ViewerCertificate through
* fix(cloudformation): delete a replaced ACM certificate in the update cleanup
This commit is contained in:
Joaquín Gamboa authored and GitHub committed 2026-11-19 18:26:08 -04:00
1 parent 82ac1eabaa
commit 1ffa5ed2c9
6 files changed
+370 -40

No files matched your search

@@ -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' }");
}
}
@@ -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
@@ -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<Distribution> sent = ArgumentCaptor.forClass(Distribution.class);
verify(cloudFront).createDistribution(sent.capture(), any());
Map<String, String> 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<Distribution> sent = ArgumentCaptor.forClass(Distribution.class);
verify(cloudFront).createDistribution(sent.capture(), any());
Map<String, String> 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<Distribution> 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<Distribution> sent = ArgumentCaptor.forClass(Distribution.class);
verify(cloudFront).createDistribution(sent.capture(), any());
assertNull(sent.getValue().getConfig().getViewerCertificate());
}
@Test
void aNonNumericOriginConnectionSettingFailsTheStackInsteadOfAServerError() {
StackResource r = resource(DISTRIBUTION);