Light, fluffy, and always free - The AWS Local Emulator alternative
feat(acm): map CertificateExport and CertificateTransparencyLoggingPreference onto the certificate options (#3111)
Mario Toffia615056999e3c
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationAcmCertificateTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationAcmCertificateTest.javanew file mode 100644index 0000000000..313525fdcb--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationAcmCertificateTest.java@@ -0,0 +1,192 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.acm.AcmClient;+import software.amazon.awssdk.services.acm.model.CertificateDetail;+import software.amazon.awssdk.services.acm.model.CertificateExport;+import software.amazon.awssdk.services.acm.model.CertificateStatus;+import software.amazon.awssdk.services.acm.model.CertificateTransparencyLoggingPreference;+import software.amazon.awssdk.services.acm.model.ResourceNotFoundException;+import software.amazon.awssdk.services.cloudformation.CloudFormationClient;+import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;+import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;+import software.amazon.awssdk.services.cloudformation.model.Output;+import software.amazon.awssdk.services.cloudformation.model.Parameter;+import software.amazon.awssdk.services.cloudformation.model.Stack;++import java.util.List;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++/**+ * Drives {@code CertificateExport} and {@code CertificateTransparencyLoggingPreference} on an+ * {@code AWS::CertificateManager::Certificate} through the CloudFormation SDK and reads the result+ * back through the ACM SDK: the logging preference changes in place, the export setting replaces+ * the certificate, and the stack delete removes it.+ */+@DisplayName("CloudFormation AWS::CertificateManager::Certificate")+class CloudFormationAcmCertificateTest {++ private static CloudFormationClient cloudFormation;+ private static AcmClient acm;+ private static String stackName;+ private static String domainName;++ @BeforeAll+ static void setup() {+ cloudFormation = TestFixtures.cloudFormationClient();+ acm = TestFixtures.acmClient();+ stackName = TestFixtures.uniqueName("compat-cfn-acm");+ domainName = TestFixtures.uniqueName("cert") + ".example.com";+ }++ @AfterAll+ static void cleanup() {+ if (cloudFormation != null) {+ try {+ cloudFormation.deleteStack(r -> r.stackName(stackName));+ } catch (Exception e) {+ System.err.println("CloudFormation ACM cleanup skipped: " + e.getMessage());+ }+ cloudFormation.close();+ }+ if (acm != null) {+ acm.close();+ }+ }++ @Test+ void certificateOptionsFollowTheTemplateThroughCreateAndUpdate() throws InterruptedException {+ cloudFormation.createStack(r -> r+ .stackName(stackName)+ .templateBody(template())+ .parameters(options("ENABLED", "DISABLED")));+ assertThat(waitForTerminal(stackName, 60)).isEqualTo("CREATE_COMPLETE");++ String arn = output("CertArn");+ assertThat(arn).startsWith("arn:aws:acm:us-east-1:");+ CertificateDetail created = describe(arn);+ assertThat(created.domainName()).isEqualTo(domainName);+ assertThat(created.status()).isEqualTo(CertificateStatus.ISSUED);+ assertThat(created.options().export()).isEqualTo(CertificateExport.ENABLED);+ assertThat(created.options().certificateTransparencyLoggingPreference())+ .isEqualTo(CertificateTransparencyLoggingPreference.DISABLED);++ cloudFormation.updateStack(r -> r+ .stackName(stackName)+ .templateBody(template())+ .parameters(options("ENABLED", "ENABLED")));+ assertThat(waitForTerminal(stackName, 60)).isEqualTo("UPDATE_COMPLETE");+ assertThat(output("CertArn"))+ .as("a transparency logging change updates the certificate in place")+ .isEqualTo(arn);+ assertThat(describe(arn).options().certificateTransparencyLoggingPreference())+ .isEqualTo(CertificateTransparencyLoggingPreference.ENABLED);++ cloudFormation.updateStack(r -> r+ .stackName(stackName)+ .templateBody(template())+ .parameters(options("DISABLED", "ENABLED")));+ assertThat(waitForTerminal(stackName, 60)).isEqualTo("UPDATE_COMPLETE");+ String replacement = output("CertArn");+ assertThat(replacement).as("an export change replaces the certificate").isNotEqualTo(arn);+ assertThatThrownBy(() -> describe(arn)).isInstanceOf(ResourceNotFoundException.class);+ CertificateDetail replaced = describe(replacement);+ assertThat(replaced.domainName()).isEqualTo(domainName);+ assertThat(replaced.options().export()).isEqualTo(CertificateExport.DISABLED);+ assertThat(replaced.options().certificateTransparencyLoggingPreference())+ .isEqualTo(CertificateTransparencyLoggingPreference.ENABLED);++ cloudFormation.deleteStack(r -> r.stackName(stackName));+ waitForDeleted(stackName, 60);+ assertThatThrownBy(() -> describe(replacement)).isInstanceOf(ResourceNotFoundException.class);+ }++ private static String template() {+ return """+ {+ "Parameters": {+ "Export": {"Type": "String"},+ "TransparencyLogging": {"Type": "String"}+ },+ "Resources": {+ "Cert": {+ "Type": "AWS::CertificateManager::Certificate",+ "Properties": {+ "DomainName": "%s",+ "ValidationMethod": "DNS",+ "CertificateExport": {"Ref": "Export"},+ "CertificateTransparencyLoggingPreference": {"Ref": "TransparencyLogging"}+ }+ }+ },+ "Outputs": {+ "CertArn": {"Value": {"Fn::GetAtt": ["Cert", "CertificateArn"]}}+ }+ }+ """.formatted(domainName);+ }++ private static List<Parameter> options(String export, String transparencyLogging) {+ return List.of(+ Parameter.builder().parameterKey("Export").parameterValue(export).build(),+ Parameter.builder().parameterKey("TransparencyLogging").parameterValue(transparencyLogging).build());+ }++ private static CertificateDetail describe(String arn) {+ return acm.describeCertificate(r -> r.certificateArn(arn)).certificate();+ }++ private static String output(String key) {+ Stack stack = cloudFormation.describeStacks(+ DescribeStacksRequest.builder().stackName(stackName).build()).stacks().get(0);+ return stack.outputs().stream()+ .filter(o -> key.equals(o.outputKey()))+ .map(Output::outputValue)+ .findFirst()+ .orElseThrow(() -> new AssertionError("stack " + stackName + " has no output " + key));+ }++ private static String waitForTerminal(String name, int maxSeconds) throws InterruptedException {+ long deadline = System.currentTimeMillis() + maxSeconds * 1000L;+ while (System.currentTimeMillis() < deadline) {+ List<Stack> stacks = cloudFormation.describeStacks(+ DescribeStacksRequest.builder().stackName(name).build()).stacks();+ if (!stacks.isEmpty()) {+ String status = stacks.get(0).stackStatusAsString();+ if (!status.endsWith("_IN_PROGRESS")) {+ return status;+ }+ }+ Thread.sleep(500);+ }+ throw new AssertionError(+ "Stack " + name + " did not reach a terminal state within " + maxSeconds + "s");+ }++ private static void waitForDeleted(String name, int maxSeconds) throws InterruptedException {+ long deadline = System.currentTimeMillis() + maxSeconds * 1000L;+ while (System.currentTimeMillis() < deadline) {+ try {+ List<Stack> stacks = cloudFormation.describeStacks(+ DescribeStacksRequest.builder().stackName(name).build()).stacks();+ if (stacks.isEmpty()+ || "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString())) {+ return;+ }+ } catch (CloudFormationException e) {+ if (e.getMessage() != null && e.getMessage().contains("does not exist")) {+ return;+ }+ throw e;+ }+ Thread.sleep(500);+ }+ throw new AssertionError(+ "Stack " + name + " was not deleted within " + maxSeconds + "s");+ }+}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.javaindex 33ebf1e5fb..74d9b9912d 100644--- 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@@ -4,6 +4,7 @@ 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.CertificateOptions;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;@@ -21,11 +22,17 @@ import java.util.Set;* <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.+ *+ * <p>{@code CertificateExport} and {@code CertificateTransparencyLoggingPreference} become the+ * 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.*/@ApplicationScopedpublic class AcmCfnProvisioner implements CfnResourceProvisioner {private static final Logger LOG = Logger.getLogger(AcmCfnProvisioner.class);+ private static final Set<String> OPTION_VALUES = Set.of("ENABLED", "DISABLED");private final AcmService acmService;@@ -42,25 +49,30 @@ public class AcmCfnProvisioner implements CfnResourceProvisioner {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");+ throw new AwsException("ValidationError", "AWS::CertificateManager::Certificate requires DomainName", 400);}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");+ String export = optionValue(ctx, props, "CertificateExport", "DISABLED");+ String transparencyLogging = optionValue(ctx, props, "CertificateTransparencyLoggingPreference", "ENABLED");+ CertificateOptions options = new CertificateOptions(transparencyLogging, export);- // 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.+ // 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.Certificate existing = ctx.isUpdate() ? findExisting(ctx.priorPhysicalId(), ctx.region()) : null;String arn;- if (existing != null && sameCreateOnlyProperties(existing, domainName, sans, keyAlgorithm)) {+ if (existing != null && sameCreateOnlyProperties(existing, domainName, sans, keyAlgorithm, export)) {arn = existing.getArn();reconcileTags(arn, tags, ctx.region());+ reconcileTransparencyLogging(existing, transparencyLogging, ctx.region());} else {arn = acmService.requestCertificate(domainName, sans, validationMethod, null,- keyAlgorithm, null, null, tags, ctx.region()).getArn();+ keyAlgorithm, null, options, tags, ctx.region()).getArn();if (existing != null) {deletePriorOrUnwind(r, existing.getArn(), arn, ctx.region());}@@ -106,7 +118,8 @@ public class AcmCfnProvisioner implements CfnResourceProvisioner {}private static boolean sameCreateOnlyProperties(Certificate existing, String domainName,- List<String> sans, KeyAlgorithm keyAlgorithm) {+ List<String> sans, KeyAlgorithm keyAlgorithm,+ String export) {Set<String> desiredNames = new LinkedHashSet<>();desiredNames.add(domainName);desiredNames.addAll(sans);@@ -115,7 +128,40 @@ public class AcmCfnProvisioner implements CfnResourceProvisioner {: new LinkedHashSet<>(existing.getSubjectAlternativeNames());return domainName.equals(existing.getDomainName())&& desiredNames.equals(storedNames)- && keyAlgorithm == existing.getKeyAlgorithm();+ && keyAlgorithm == existing.getKeyAlgorithm()+ && export.equals(storedOptions(existing).export());+ }++ /**+ * An ENABLED or DISABLED option, defaulted the way CloudFormation documents when absent. Blank+ * counts as absent: the engine resolves {@code AWS::NoValue} to an empty string.+ */+ private static String optionValue(ProvisionContext ctx, JsonNode props, String name, String defaultValue) {+ String value = ctx.resolveOptional(props, name);+ if (value == null || value.isBlank()) {+ return defaultValue;+ }+ if (!OPTION_VALUES.contains(value)) {+ throw new AwsException("ValidationError", "AWS::CertificateManager::Certificate " + name+ + " must be ENABLED or DISABLED, not " + value, 400);+ }+ return value;+ }++ /** An imported certificate carries no options; the service reads that as the defaults, so this does too. */+ private static CertificateOptions storedOptions(Certificate existing) {+ return existing.getCertOptions() != null ? existing.getCertOptions() : CertificateOptions.defaultOptions();+ }++ /**+ * Runs after the tag reconcile, which carries the validation: this call can only fail when the+ * certificate is gone, so a rejected tag never leaves the option changed on a rolled-back update.+ * Export is never sent here: ACM refuses to change it, so a changed value replaces the certificate.+ */+ private void reconcileTransparencyLogging(Certificate existing, String desired, String region) {+ if (!desired.equals(storedOptions(existing).certificateTransparencyLoggingPreference())) {+ acmService.updateCertificateOptions(existing.getArn(), new CertificateOptions(desired, null), region);+ }}private void reconcileTags(String arn, Map<String, String> desired, String 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.javaindex c717c6e17e..e354a43a49 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/AcmCfnIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AcmCfnIntegrationTest.java@@ -3,20 +3,31 @@ 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 io.restassured.response.Response;+import io.restassured.specification.RequestSpecification;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;+import java.util.Map;+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.assertNotEquals;import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.junit.jupiter.api.Assertions.fail;/*** 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}.+ *+ * <p>The second stack drives {@code CertificateExport} and+ * {@code CertificateTransparencyLoggingPreference} through create and update: the logging+ * preference changes in place, the export setting replaces the certificate, and both read back+ * from {@code DescribeCertificate}.*/@QuarkusTestclass AcmCfnIntegrationTest {@@ -25,6 +36,7 @@ class AcmCfnIntegrationTest {"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 OPTIONS_STACK = "acm-cfn-options-it";private static final String TEMPLATE = """{@@ -49,30 +61,40 @@ class AcmCfnIntegrationTest {}""";+ /** Both options are parameters so one template drives the create and both kinds of update. */+ private static final String OPTIONS_TEMPLATE = """+ {+ "Parameters": {+ "Export": {"Type": "String"},+ "TransparencyLogging": {"Type": "String"}+ },+ "Resources": {+ "Cert": {+ "Type": "AWS::CertificateManager::Certificate",+ "Properties": {+ "DomainName": "options.cfn-it.example.com",+ "ValidationMethod": "DNS",+ "CertificateExport": {"Ref": "Export"},+ "CertificateTransparencyLoggingPreference": {"Ref": "TransparencyLogging"}+ }+ }+ },+ "Outputs": {+ "CertArn": {"Value": {"Fn::GetAtt": ["Cert", "CertificateArn"]}}+ }+ }+ """;+@BeforeAllstatic 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();+ void certificateStackExposesAnArnThatDescribeCertificateFinds() throws InterruptedException {+ cloudFormation(STACK, "CreateStack", TEMPLATE, Map.of());+ String stacks = describeStacks(STACK, "CREATE_COMPLETE");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"));@@ -81,21 +103,111 @@ class AcmCfnIntegrationTest {.statusCode(200).body("Certificate.CertificateArn", equalTo(arn)).body("Certificate.DomainName", equalTo("api.cfn-it.example.com"))- .body("Certificate.Status", equalTo("ISSUED"));+ .body("Certificate.Status", equalTo("ISSUED"))+ .body("Certificate.Options.Export", equalTo("DISABLED"))+ .body("Certificate.Options.CertificateTransparencyLoggingPreference", equalTo("ENABLED"));- given()- .contentType("application/x-www-form-urlencoded")- .header("Authorization", CFN_AUTH)- .formParam("Action", "DeleteStack")- .formParam("StackName", STACK)- .when().post("/").then().statusCode(200);+ cloudFormation(STACK, "DeleteStack", null, Map.of());+ awaitStackDeleted(STACK);describeCertificate(arn).then().statusCode(404).body("__type", equalTo("ResourceNotFoundException"));}- private static io.restassured.response.Response describeCertificate(String arn) {+ @Test+ void certificateOptionsFollowTheTemplateThroughCreateAndUpdate() throws InterruptedException {+ cloudFormation(OPTIONS_STACK, "CreateStack", OPTIONS_TEMPLATE, options("ENABLED", "DISABLED"));+ String arn = outputValue(describeStacks(OPTIONS_STACK, "CREATE_COMPLETE"), "CertArn");+ describeCertificate(arn).then()+ .statusCode(200)+ .body("Certificate.Status", equalTo("ISSUED"))+ .body("Certificate.Options.Export", equalTo("ENABLED"))+ .body("Certificate.Options.CertificateTransparencyLoggingPreference", equalTo("DISABLED"));++ cloudFormation(OPTIONS_STACK, "UpdateStack", OPTIONS_TEMPLATE, options("ENABLED", "ENABLED"));+ assertEquals(arn, outputValue(describeStacks(OPTIONS_STACK, "UPDATE_COMPLETE"), "CertArn"),+ "a transparency logging change updates the certificate in place");+ describeCertificate(arn).then()+ .statusCode(200)+ .body("Certificate.Options.Export", equalTo("ENABLED"))+ .body("Certificate.Options.CertificateTransparencyLoggingPreference", equalTo("ENABLED"));++ cloudFormation(OPTIONS_STACK, "UpdateStack", OPTIONS_TEMPLATE, options("DISABLED", "ENABLED"));+ String replacement = outputValue(describeStacks(OPTIONS_STACK, "UPDATE_COMPLETE"), "CertArn");+ assertNotEquals(arn, replacement, "an export change replaces the certificate");+ describeCertificate(arn).then()+ .statusCode(404)+ .body("__type", equalTo("ResourceNotFoundException"));+ describeCertificate(replacement).then()+ .statusCode(200)+ .body("Certificate.DomainName", equalTo("options.cfn-it.example.com"))+ .body("Certificate.Options.Export", equalTo("DISABLED"))+ .body("Certificate.Options.CertificateTransparencyLoggingPreference", equalTo("ENABLED"));++ cloudFormation(OPTIONS_STACK, "DeleteStack", null, Map.of());+ awaitStackDeleted(OPTIONS_STACK);++ describeCertificate(replacement).then()+ .statusCode(404)+ .body("__type", equalTo("ResourceNotFoundException"));+ }++ private static Map<String, String> options(String export, String transparencyLogging) {+ return Map.of("Export", export, "TransparencyLogging", transparencyLogging);+ }++ private static void cloudFormation(String stack, String action, String templateBody,+ Map<String, String> parameters) {+ RequestSpecification request = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", action)+ .formParam("StackName", stack);+ if (templateBody != null) {+ request.formParam("TemplateBody", templateBody);+ }+ int index = 1;+ for (Map.Entry<String, String> parameter : parameters.entrySet()) {+ request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());+ request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());+ index++;+ }+ request.when().post("/").then().statusCode(200);+ }++ private static String describeStacks(String stack, String expectedStatus) {+ return 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>" + expectedStatus + "</StackStatus>"))+ .extract().asString();+ }++ /** DeleteStack runs asynchronously; a successful delete removes the stack entirely. */+ private static void awaitStackDeleted(String stack) throws InterruptedException {+ for (int i = 0; i < 100; i++) {+ String body = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stack)+ .when().post("/").then().extract().asString();+ if (body.contains("does not exist")) {+ return;+ }+ if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {+ fail("stack delete failed: " + body);+ }+ Thread.sleep(50);+ }+ fail("stack " + stack + " was not deleted within the timeout");+ }++ private static Response describeCertificate(String arn) {return given().header("X-Amz-Target", "CertificateManager.DescribeCertificate").contentType(ACM_CONTENT_TYPE)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.javaindex ca377466ea..e31716d9fb 100644--- 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@@ -6,6 +6,7 @@ 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.CertificateOptions;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;@@ -20,6 +21,7 @@ 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.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;import static org.mockito.ArgumentMatchers.isNull;@@ -27,6 +29,7 @@ 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.verifyNoInteractions;import static org.mockito.Mockito.when;/**@@ -38,6 +41,7 @@ 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 static final String NEW_ARN = "arn:aws:acm:us-east-1:000000000000:certificate/99999999-2222-3333-4444-555555555555";private final AcmService acm = mock(AcmService.class);private final AcmCfnProvisioner provisioner = new AcmCfnProvisioner(acm);@@ -75,10 +79,23 @@ class AcmCfnProvisionerTest {return cert;}+ /** What the store holds for {@code api.example.com} after a plain create, options included. */+ private static Certificate storedCertificate(String transparencyLogging, String export) {+ Certificate stored = certificate(ARN, "api.example.com");+ stored.setSubjectAlternativeNames(List.of("api.example.com"));+ stored.setKeyAlgorithm(KeyAlgorithm.RSA_2048);+ stored.setCertOptions(new CertificateOptions(transparencyLogging, export));+ return stored;+ }++ private void stubRequestCertificate(String domainName, Certificate result) {+ when(acm.requestCertificate(eq(domainName), any(), any(), isNull(), any(), isNull(), any(), any(), eq(REGION)))+ .thenReturn(result);+ }+@Testvoid certificateSetsArnAsPhysicalIdAndCertificateArnAttribute() {- when(acm.requestCertificate(eq("api.example.com"), any(), any(), isNull(), any(), isNull(), any(), any(), eq(REGION)))- .thenReturn(certificate(ARN, "api.example.com"));+ stubRequestCertificate("api.example.com", certificate(ARN, "api.example.com"));StackResource r = resource();ObjectNode props = mapper.createObjectNode().put("DomainName", "api.example.com");@@ -90,8 +107,7 @@ class AcmCfnProvisionerTest {@Testvoid certificatePassesTemplatePropertiesToRequestCertificate() {- when(acm.requestCertificate(any(), any(), any(), isNull(), any(), isNull(), any(), any(), eq(REGION)))- .thenReturn(certificate(ARN, "api.example.com"));+ stubRequestCertificate("api.example.com", certificate(ARN, "api.example.com"));StackResource r = resource();ObjectNode props = mapper.createObjectNode().put("DomainName", "api.example.com")@@ -102,19 +118,78 @@ class AcmCfnProvisionerTest {provisioner.provision(r, props, ctx());+ // No CertificateExport or CertificateTransparencyLoggingPreference: the CloudFormation defaults apply.verify(acm).requestCertificate("api.example.com", List.of("www.example.com"), ValidationMethod.EMAIL,- null, KeyAlgorithm.EC_prime256v1, null, null, Map.of("env", "test"), REGION);+ null, KeyAlgorithm.EC_prime256v1, null, new CertificateOptions("ENABLED", "DISABLED"),+ Map.of("env", "test"), REGION);}@Testvoid validationMethodDefaultsToDns() {- when(acm.requestCertificate(any(), any(), any(), isNull(), any(), isNull(), any(), any(), eq(REGION)))- .thenReturn(certificate(ARN, "api.example.com"));+ stubRequestCertificate("api.example.com", 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));+ eq(KeyAlgorithm.RSA_2048), isNull(), any(), eq(Map.of()), eq(REGION));+ }++ @Test+ void certificateOptionsFromTheTemplateReachRequestCertificate() {+ stubRequestCertificate("api.example.com", certificate(ARN, "api.example.com"));+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateExport", "ENABLED")+ .put("CertificateTransparencyLoggingPreference", "DISABLED");++ provisioner.provision(resource(), props, ctx());++ verify(acm).requestCertificate(eq("api.example.com"), any(), any(), isNull(), any(), isNull(),+ eq(new CertificateOptions("DISABLED", "ENABLED")), any(), eq(REGION));+ }++ @Test+ void blankCertificateOptionValuesFallBackToTheDefaults() {+ // The engine resolves {"Ref": "AWS::NoValue"} to "", so an Fn::If that omits a property+ // arrives blank and must mean "absent", as it does on AWS.+ stubRequestCertificate("api.example.com", certificate(ARN, "api.example.com"));+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateExport", "")+ .put("CertificateTransparencyLoggingPreference", "");++ provisioner.provision(resource(), props, ctx());++ verify(acm).requestCertificate(eq("api.example.com"), any(), any(), isNull(), any(), isNull(),+ eq(new CertificateOptions("ENABLED", "DISABLED")), any(), eq(REGION));+ }++ @Test+ void invalidCertificateExportIsRejectedBeforeAnyServiceCall() {+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateExport", "yes");++ AwsException failure = assertThrows(AwsException.class,+ () -> provisioner.provision(resource(), props, ctx()));++ assertEquals("ValidationError", failure.getErrorCode());+ assertTrue(failure.getMessage().contains("CertificateExport"), failure.getMessage());+ verifyNoInteractions(acm);+ }++ @Test+ void invalidTransparencyLoggingPreferenceIsRejectedBeforeThePriorCertificateIsLookedUp() {+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateTransparencyLoggingPreference", "enabled");++ AwsException failure = assertThrows(AwsException.class,+ () -> provisioner.provision(resource(), props, ctx(ARN)));++ assertEquals("ValidationError", failure.getErrorCode());+ assertTrue(failure.getMessage().contains("CertificateTransparencyLoggingPreference"), failure.getMessage());+ verifyNoInteractions(acm);}@Test@@ -133,41 +208,220 @@ class AcmCfnProvisionerTest {verify(acm, never()).requestCertificate(any(), any(), any(), any(), any(), any(), any(), any(), any());verify(acm, never()).deleteCertificate(any(), any());+ verify(acm, never()).updateCertificateOptions(any(), 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 updateWithUnchangedOptionsLeavesTheCertificateOptionsAlone() {+ when(acm.describeCertificate(ARN, REGION)).thenReturn(storedCertificate("ENABLED", "DISABLED"));+ StackResource r = resource();++ provisioner.provision(r, mapper.createObjectNode().put("DomainName", "api.example.com"), ctx(ARN));++ verify(acm, never()).updateCertificateOptions(any(), any(), any());+ 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 updateChangingTransparencyLoggingPreferenceUpdatesTheCertificateInPlace() {+ // Mutable in the registry schema; CloudFormation calls UpdateCertificateOptions on the+ // existing certificate rather than replacing it.+ when(acm.describeCertificate(ARN, REGION)).thenReturn(storedCertificate("ENABLED", "DISABLED"));+ StackResource r = resource();+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateTransparencyLoggingPreference", "DISABLED");++ provisioner.provision(r, props, ctx(ARN));++ verify(acm).updateCertificateOptions(ARN, new CertificateOptions("DISABLED", null), REGION);+ verify(acm, never()).requestCertificate(any(), any(), any(), any(), any(), any(), any(), any(), any());+ verify(acm, never()).deleteCertificate(any(), any());+ assertEquals(ARN, r.getPhysicalId());+ assertEquals(Map.of("CertificateArn", ARN), r.getAttributes());+ }++ @Test+ void updateAppliesTagsAndLoggingPreferenceTogether() {+ when(acm.describeCertificate(ARN, REGION)).thenReturn(storedCertificate("ENABLED", "DISABLED"));+ when(acm.listTagsForCertificate(ARN, REGION)).thenReturn(Map.of());+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateTransparencyLoggingPreference", "DISABLED");+ props.putArray("Tags").addObject().put("Key", "env").put("Value", "test");++ provisioner.provision(resource(), props, ctx(ARN));++ verify(acm).updateCertificateOptions(ARN, new CertificateOptions("DISABLED", null), REGION);+ verify(acm).addTagsToCertificate(ARN, Map.of("env", "test"), REGION);+ verify(acm, never()).requestCertificate(any(), any(), any(), any(), any(), any(), any(), any(), any());+ }++ @Test+ void updateReconcilesTagsBeforeTheLoggingPreferenceSoATagFailureLeavesTheOptionUntouched() {+ // The tag calls carry the validation (reserved prefixes, limits); UpdateCertificateOptions can+ // only fail when the certificate is gone. Running it last keeps a failed update from leaving+ // the certificate with an option the rolled-back template does not have.+ when(acm.describeCertificate(ARN, REGION)).thenReturn(storedCertificate("ENABLED", "DISABLED"));+ when(acm.listTagsForCertificate(ARN, REGION)).thenReturn(Map.of());+ doThrow(new AwsException("ValidationException", "reserved prefix", 400))+ .when(acm).addTagsToCertificate(any(), any(), any());+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateTransparencyLoggingPreference", "DISABLED");+ props.putArray("Tags").addObject().put("Key", "aws:reserved").put("Value", "x");++ assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, ctx(ARN)));++ verify(acm, never()).updateCertificateOptions(any(), any(), any());+ }++ @Test+ void updateWhoseOptionsChangeFailsPropagatesWithoutReplacingTheCertificate() {+ when(acm.describeCertificate(ARN, REGION)).thenReturn(storedCertificate("ENABLED", "DISABLED"));+ doThrow(new AwsException("ResourceNotFoundException", "gone", 404))+ .when(acm).updateCertificateOptions(any(), any(), any());+ StackResource r = resource();+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateTransparencyLoggingPreference", "DISABLED");++ AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx(ARN)));++ assertEquals("ResourceNotFoundException", failure.getErrorCode());+ verify(acm, never()).requestCertificate(any(), any(), any(), any(), any(), any(), any(), any(), any());+ verify(acm, never()).deleteCertificate(any(), any());+ assertNull(r.getPhysicalId());+ }++ @Test+ void updateRemovingTransparencyLoggingPreferenceRestoresTheDefault() {+ when(acm.describeCertificate(ARN, REGION)).thenReturn(storedCertificate("DISABLED", "DISABLED"));++ provisioner.provision(resource(), mapper.createObjectNode().put("DomainName", "api.example.com"), ctx(ARN));++ verify(acm).updateCertificateOptions(ARN, new CertificateOptions("ENABLED", null), REGION);+ verify(acm, never()).requestCertificate(any(), any(), any(), any(), any(), any(), any(), any(), any());+ }++ @Test+ void updateEnablingCertificateExportReplacesTheCertificate() {+ // CertificateExport is createOnly in the registry schema, and ACM refuses to change+ // Export after issuance, so the change is a replacement carrying the new options.+ when(acm.describeCertificate(ARN, REGION)).thenReturn(storedCertificate("ENABLED", "DISABLED"));+ stubRequestCertificate("api.example.com", certificate(NEW_ARN, "api.example.com"));+ StackResource r = resource();+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateExport", "ENABLED");++ provisioner.provision(r, props, ctx(ARN));++ 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()).updateCertificateOptions(any(), any(), any());+ assertEquals(NEW_ARN, r.getPhysicalId());+ assertEquals(Map.of("CertificateArn", NEW_ARN), r.getAttributes());+ }++ @Test+ void updateRemovingCertificateExportReplacesTheCertificate() {+ when(acm.describeCertificate(ARN, REGION)).thenReturn(storedCertificate("ENABLED", "ENABLED"));+ stubRequestCertificate("api.example.com", certificate(NEW_ARN, "api.example.com"));+ StackResource r = resource();++ provisioner.provision(r, mapper.createObjectNode().put("DomainName", "api.example.com"), ctx(ARN));++ 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);+ assertEquals(NEW_ARN, r.getPhysicalId());+ }++ @Test+ void updateChangingBothOptionsReplacesWithTheNewTransparencyLoggingPreference() {+ when(acm.describeCertificate(ARN, REGION)).thenReturn(storedCertificate("ENABLED", "DISABLED"));+ stubRequestCertificate("api.example.com", certificate(NEW_ARN, "api.example.com"));+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateExport", "ENABLED")+ .put("CertificateTransparencyLoggingPreference", "DISABLED");++ provisioner.provision(resource(), props, ctx(ARN));++ 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()).updateCertificateOptions(any(), any(), any());+ }++ @Test+ void updateChangingDomainNameAndLoggingPreferenceReplacesWithTheNewOptions() {+ Certificate stored = certificate(ARN, "old.example.com");+ stored.setSubjectAlternativeNames(List.of("old.example.com"));+ stored.setKeyAlgorithm(KeyAlgorithm.RSA_2048);+ stored.setCertOptions(new CertificateOptions("ENABLED", "DISABLED"));+ when(acm.describeCertificate(ARN, REGION)).thenReturn(stored);+ stubRequestCertificate("new.example.com", certificate(NEW_ARN, "new.example.com"));+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "new.example.com")+ .put("CertificateTransparencyLoggingPreference", "DISABLED");++ provisioner.provision(resource(), props, ctx(ARN));++ 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()).updateCertificateOptions(any(), any(), any());+ }++ @Test+ void updateOfACertificateStoredWithoutOptionsUpdatesAChangedLoggingPreference() {+ Certificate stored = storedCertificate("ENABLED", "DISABLED");+ stored.setCertOptions(null);+ when(acm.describeCertificate(ARN, REGION)).thenReturn(stored);+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateTransparencyLoggingPreference", "DISABLED");++ provisioner.provision(resource(), props, ctx(ARN));++ verify(acm).updateCertificateOptions(ARN, new CertificateOptions("DISABLED", null), REGION);+ verify(acm, never()).requestCertificate(any(), any(), any(), any(), any(), any(), any(), any(), any());+ }+@Testvoid 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"));+ stubRequestCertificate("new.example.com", certificate(NEW_ARN, "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());+ assertEquals(NEW_ARN, r.getPhysicalId());+ assertEquals(Map.of("CertificateArn", NEW_ARN), r.getAttributes());}@Testvoid 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"));+ stubRequestCertificate("new.example.com", certificate(NEW_ARN, "new.example.com"));doThrow(new AwsException("ResourceInUseException", "in use", 409)).when(acm).deleteCertificate(ARN, REGION);StackResource r = resource();@@ -176,7 +430,7 @@ class AcmCfnProvisionerTest {r, mapper.createObjectNode().put("DomainName", "new.example.com"), ctx(ARN)));assertEquals("ResourceInUseException", failure.getErrorCode());- verify(acm).deleteCertificate(newArn, REGION);+ verify(acm).deleteCertificate(NEW_ARN, REGION);assertEquals("true", r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));assertNull(r.getPhysicalId());}@@ -207,12 +461,16 @@ class AcmCfnProvisionerTest {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"));+ stubRequestCertificate("api.example.com", certificate(ARN, "api.example.com"));StackResource r = resource();+ ObjectNode props = mapper.createObjectNode()+ .put("DomainName", "api.example.com")+ .put("CertificateExport", "ENABLED");- provisioner.provision(r, mapper.createObjectNode().put("DomainName", "api.example.com"), ctx(ARN));+ provisioner.provision(r, props, ctx(ARN));+ verify(acm).requestCertificate(eq("api.example.com"), any(), any(), isNull(), any(), isNull(),+ eq(new CertificateOptions("ENABLED", "ENABLED")), any(), eq(REGION));verify(acm, never()).deleteCertificate(any(), any());assertEquals(ARN, r.getPhysicalId());}