From 16ca3a5a7df9ea4c7623e20d7a57e262f0d832ee Mon Sep 17 00:00:00 2001 From: Jonathan Morley Date: Fri, 20 Nov 2026 21:10:47 -0500 Subject: [PATCH] fix(cloudformation): provision AWS::CodeDeploy::Application (#8882) --- docs/services/cloudformation.md | 1 + .../CodeDeployCfnProvisioner.java | 199 ++++++++ .../provisioners/ProvisionContext.java | 29 +- .../codedeploy/CodeDeployService.java | 25 + .../create-only-properties.json | 4 + .../cloudformation/CfnProvisionerFixture.java | 11 + ...deDeployApplicationCfnIntegrationTest.java | 126 +++++ .../CodeDeployCfnProvisionerTest.java | 450 ++++++++++++++++++ .../provisioners/ProvisionContextTest.java | 17 + .../codedeploy/CodeDeployServiceTest.java | 46 ++ .../cloudformation/schema-surface.tsv | 1 + .../supported-resource-types.tsv | 1 + tools/docs/cfn_resource_types.yaml | 2 + 13 files changed, 899 insertions(+), 13 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/cloudformation/provisioners/CodeDeployCfnProvisioner.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/CodeDeployApplicationCfnIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/cloudformation/provisioners/CodeDeployCfnProvisionerTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 9f6676eff2..1a8afbf0d4 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -238,6 +238,7 @@ cross-resource references. | Step Functions | `StateMachine` | | CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` | | CodeBuild | `Project` | +| CodeDeploy | `Application` | | Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` | | Cognito | `UserPool` (`ProviderURL` is the local issuer of the tokens Floci mints, `/`; `EnabledMfas` is applied with `SetUserPoolMfaConfig`, as on AWS, and once `SMS_MFA` is on only `MfaConfiguration: OFF` turns it off), `UserPoolClient`, `UserPoolDomain`, `UserPoolGroup`, `UserPoolIdentityProvider` (Ref returns the ProviderName; changing only `ProviderType` is refused, as on AWS, because the name is always the template's and the replacement would need the same address), `UserPoolResourceServer`, `UserPoolUser`, `UserPoolUserToGroupAttachment` | | ACM | `Certificate` | diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CodeDeployCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CodeDeployCfnProvisioner.java new file mode 100644 index 0000000000..4d0bd81fe8 --- /dev/null +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CodeDeployCfnProvisioner.java @@ -0,0 +1,199 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.codedeploy.CodeDeployService; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * CloudFormation provisioning for {@code AWS::CodeDeploy::Application}. Previously unhandled, so + * the type fell through to the generic stub: the stack reported CREATE_COMPLETE and no application + * existed in CodeDeploy (issue #8626). {@code Ref} is the application name; the registry schema + * declares no {@code Fn::GetAtt} attributes. + */ +@ApplicationScoped +public class CodeDeployCfnProvisioner implements CfnResourceProvisioner { + + private static final String TYPE = "AWS::CodeDeploy::Application"; + private static final int APPLICATION_NAME_MAX_LENGTH = 100; + private static final ObjectMapper MAPPER = new ObjectMapper(); + /** The tags an in-place update is about to change, for {@link #rollbackUpdate} to put back. */ + static final String SNAPSHOT_ATTR = "__FlociCodeDeployApplicationUpdateSnapshot"; + /** The tag keys the template that provisioned the application set: the next update drops the ones it omits. */ + static final String TAG_KEYS_ATTR = "__FlociCodeDeployTagKeys"; + + private final CodeDeployService codeDeployService; + + @Inject + public CodeDeployCfnProvisioner(CodeDeployService codeDeployService) { + this.codeDeployService = codeDeployService; + } + + @Override + public Set resourceTypes() { + return Set.of(TYPE); + } + + @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) { + resource.getAttributes().remove(SNAPSHOT_ATTR); + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(SNAPSHOT_ATTR); + ReplacementCleanup.clear(resource); + } + + /** + * A replacement or a stub migration is undone through the cleanup record, and an in-place update + * from the tag snapshot taken before it. The snapshot is spent only once the restore succeeded, + * so one that throws leaves it for ContinueUpdateRollback to retry. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + JsonNode snapshot = CfnRollback.updateSnapshot(resource, SNAPSHOT_ATTR); + if (snapshot == null) { + return false; + } + // An application the update created because the prior one was gone is deleted instead. + if (CfnRollback.undoCreatedByUpdate(resource, snapshot, SNAPSHOT_ATTR, null, + (createdId, region) -> delete(TYPE, createdId, region))) { + return true; + } + restoreTags(snapshot); + Ec2Tags.restoreRecord(resource, TAG_KEYS_ATTR, snapshot); + resource.getAttributes().remove(SNAPSHOT_ATTR); + return true; + } + + @Override + public void provision(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale. + r.getAttributes().remove(SNAPSHOT_ATTR); + if (ctx.isUpdate()) { + ReplacementCleanup.endRollbackRetry(r); + } + Map attributesBefore = new HashMap<>(r.getAttributes()); + String explicitName = ctx.resolveOptionalWritten(props, "ApplicationName"); + boolean hasExplicitName = explicitName != null; + String priorPhysicalId = ctx.priorPhysicalId(); + + // ApplicationName and ComputePlatform are create-only; only tags update in place. + boolean replaces = ctx.isUpdate() && ctx.changes(TYPE, props).requiresReplacement(); + if (replaces && hasExplicitName && explicitName.equals(priorPhysicalId)) { + throw CfnExceptions.customNamedReplacement(explicitName); + } + String name; + if (hasExplicitName) { + name = explicitName; + } else if (ctx.isUpdate() && !replaces) { + name = priorPhysicalId; + } else { + name = ctx.generatePhysicalName(r.getLogicalId(), APPLICATION_NAME_MAX_LENGTH, false); + } + + Map tags = ctx.resolveTags(props, "Tags"); + // A stack from before this type had a provisioner, or deployed while CodeDeploy was disabled, + // holds the dispatcher's stub, which names no application: taking over its id is a create. + boolean stub = CfnResourceDispatcher.isStub(priorPhysicalId, attributesBefore); + r.setPhysicalId(name); + boolean reuses = ctx.reusesPriorEntity(name) && !stub; + if (reuses && applicationExists(ctx.region(), name)) { + updateTagsInPlace(r, ctx, name, tags); + } else { + codeDeployService.createApplication(ctx.region(), name, ctx.resolveOptionalWritten(props, "ComputePlatform"), + toTagList(tags)); + if (reuses) { + // The application the update started from is gone, so this one is the update's to undo. + CfnRollback.recordCreatedByUpdate(r, ctx, SNAPSHOT_ATTR); + } + } + Ec2Tags.recordKeys(r, TAG_KEYS_ATTR, tags); + if (stub) { + // The type has no Arn attribute; a rollback puts the stub's back from the cleanup record. + r.getAttributes().remove("Arn"); + } + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + /** + * The update handler the registry schema gives the type: a tag change and nothing else. Only the + * keys the previous template or this one sets are the stack's to change or drop, so a tag added + * outside the stack stays, as on AWS. The tags those keys hold are snapshotted first, so a later + * resource's failure rolls them back, and a failure here puts them back before it propagates. + */ + private void updateTagsInPlace(StackResource r, ProvisionContext ctx, String name, Map desired) { + String arn = codeDeployService.applicationArn(ctx.region(), name); + Map current = new HashMap<>(); + codeDeployService.listTagsForResource(arn).forEach(t -> current.put(t.get("Key"), t.get("Value"))); + Set owned = Ec2Tags.ownedKeys(r, TAG_KEYS_ATTR, ctx); + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("name", name); + snapshot.put("region", ctx.region()); + Ec2Tags.snapshotOwned(snapshot, owned, desired, current, r.getAttributes().get(TAG_KEYS_ATTR)); + r.getAttributes().put(SNAPSHOT_ATTR, snapshot.toString()); + CfnRollback.guarded(r, ctx, false, () -> { }, () -> restoreTags(snapshot), + () -> reconcileTags(arn, Ec2Tags.touched(owned, desired), desired)); + } + + /** Whether the application an update starts from still exists; any failure but not-found propagates. */ + private boolean applicationExists(String region, String name) { + try { + codeDeployService.getApplication(region, name); + return true; + } catch (AwsException e) { + if ("ApplicationDoesNotExistException".equals(e.getErrorCode())) { + return false; + } + throw e; + } + } + + private void restoreTags(JsonNode snapshot) { + List touched = new ArrayList<>(); + snapshot.path("touched").forEach(key -> touched.add(key.asText())); + String arn = codeDeployService.applicationArn(snapshot.path("region").asText(), snapshot.path("name").asText()); + reconcileTags(arn, touched, CfnRollback.snapshotTags(snapshot)); + } + + private void reconcileTags(String arn, Collection managedKeys, Map desired) { + CfnRollback.reconcileTags(managedKeys, desired, dropped -> codeDeployService.untagResource(arn, dropped), + added -> codeDeployService.tagResource(arn, toTagList(added))); + } + + private static List> toTagList(Map tags) { + return tags.entrySet().stream().map(e -> Map.of("Key", e.getKey(), "Value", e.getValue())).toList(); + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + CfnDeletes.safeDelete("CodeDeploy application", physicalId, + () -> codeDeployService.deleteApplication(region, physicalId), "ApplicationDoesNotExistException"); + } +} diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java index bd350fc241..a07f63ffb0 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContext.java @@ -221,15 +221,24 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio } /** - * Resolves an optional integer property, or null when it is absent or explicitly null. One an - * intrinsic resolves to nothing stays null too: the engine resolves {@code AWS::NoValue} to blank, - * which is how the common {@code Fn::If [cond, value, AWS::NoValue]} drops a property. A value + * Resolves an optional property, or null when it is absent, explicitly null, or an intrinsic + * resolves it to nothing: the engine resolves {@code AWS::NoValue} to blank, which is how the + * common {@code Fn::If [cond, value, AWS::NoValue]} drops a property. A blank written into the + * template is kept, for the caller to reject as AWS would. A {@code Ref} to a parameter whose + * value is blank cannot be told apart from {@code AWS::NoValue} here, so it is null as well. + */ + public String resolveOptionalWritten(JsonNode props, String name) { + String value = resolveOptional(props, name); + return value == null || (value.isBlank() && !props.get(name).isTextual()) ? null : value; + } + + /** + * Resolves an optional integer property, or null where {@link #resolveOptionalWritten} is. A value * written into the template has to be an integer, a literal blank included, as CloudFormation's - * schema type check requires. A {@code Ref} to a parameter whose value is blank cannot be told - * apart from {@code AWS::NoValue} here, so it stays null as well. + * schema type check requires. */ public Integer resolveOptionalInt(JsonNode props, String name) { - String value = resolveOptionalNumber(props, name); + String value = resolveOptionalWritten(props, name); if (value == null) { return null; } @@ -246,7 +255,7 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio * is no integer are the same. */ public BigInteger resolveOptionalBigInteger(JsonNode props, String name) { - String value = resolveOptionalNumber(props, name); + String value = resolveOptionalWritten(props, name); if (value == null) { return null; } @@ -256,12 +265,6 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regio return new BigInteger(value.trim()); } - /** The text of an optional numeric property, or null when it counts as absent. */ - private String resolveOptionalNumber(JsonNode props, String name) { - String value = resolveOptional(props, name); - return value == null || (value.isBlank() && !props.get(name).isTextual()) ? null : value; - } - private static AwsException notAnInteger(String name) { return new AwsException("ValidationError", "Value of property " + name + " must be an integer.", 400); } diff --git a/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java b/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java index 569f16fd79..20546596a9 100644 --- a/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java +++ b/src/main/java/io/floci/aws/services/codedeploy/CodeDeployService.java @@ -39,6 +39,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; @@ -47,6 +48,7 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.regex.Pattern; import java.util.stream.Collectors; @ApplicationScoped @@ -97,6 +99,10 @@ public class CodeDeployService { } // ---- Durable (persisted) ---- + /** CreateApplication's constraints from the CodeDeploy API reference. */ + private static final Pattern APPLICATION_NAME = Pattern.compile("[A-Za-z0-9+=,.@_-]{1,100}"); + private static final Set COMPUTE_PLATFORMS = Set.of("Server", "Lambda", "ECS", "Kubernetes"); + // key: region -> name -> application private Map> applications = new ConcurrentHashMap<>(); // key: region -> appName -> groupName -> group @@ -332,6 +338,18 @@ public class CodeDeployService { public Application createApplication(String region, String name, String computePlatform, List> tags) { + if (name == null || name.isEmpty()) { + throw new AwsException("ApplicationNameRequiredException", + "The minimum number of required characters for applicationName is 1.", 400); + } + if (!APPLICATION_NAME.matcher(name).matches()) { + throw new AwsException("InvalidApplicationNameException", + "The application name was specified in an invalid format.", 400); + } + if (computePlatform != null && !COMPUTE_PLATFORMS.contains(computePlatform)) { + throw new AwsException("InvalidComputePlatformException", + "The computePlatform is invalid. The computePlatform should be Lambda, Server, or ECS.", 400); + } Map store = applicationsFor(region); if (store.containsKey(name)) { throw new AwsException("ApplicationAlreadyExistsException", @@ -395,6 +413,13 @@ public class CodeDeployService { "Application does not exist: " + name, 400); } persistRegion(applications, region); + tags.remove(applicationArn(region, name)); + // As on AWS, the application's deployment groups go with it. + Map groups = deploymentGroupsFor(region).remove(name); + if (groups != null) { + groups.keySet().forEach(group -> tags.remove(deploymentGroupArn(region, name, group))); + persistRegion(deploymentGroups, region); + } } public List listApplications(String region) { diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index d1e7dd4c4b..c1b2f013d8 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -223,6 +223,10 @@ "AWS::CodeBuild::Project": [ "Name" ], + "AWS::CodeDeploy::Application": [ + "ApplicationName", + "ComputePlatform" + ], "AWS::CodePipeline::CustomActionType": [ "Category", "ConfigurationProperties", diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java index ab4f3b6814..71fe956a75 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnProvisionerFixture.java @@ -46,6 +46,7 @@ import io.floci.aws.services.cloudformation.provisioners.CloudTrailCfnProvisione import io.floci.aws.services.cloudformation.provisioners.CloudWatchCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CloudWatchCompositeAlarmCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CloudWatchDashboardCfnProvisioner; +import io.floci.aws.services.cloudformation.provisioners.CodeDeployCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CognitoCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CognitoIdentityProviderCfnProvisioner; import io.floci.aws.services.cloudformation.provisioners.CognitoResourceServerCfnProvisioner; @@ -132,6 +133,7 @@ import io.floci.aws.services.cloudwatch.dashboards.CloudWatchDashboardsService; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsMetricFilterService; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsService; import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService; +import io.floci.aws.services.codedeploy.CodeDeployService; import io.floci.aws.services.cognito.CognitoService; import io.floci.aws.services.configservice.AwsConfigService; import io.floci.aws.services.docdb.DocDbService; @@ -274,6 +276,7 @@ final class CfnProvisionerFixture { private Route53Service route53Service; private CloudTrailService cloudTrailService; private SchedulerService schedulerService; + private CodeDeployService codeDeployService; private TransferService transferService; // Services that back a provisioner without being a constructor argument of the // dispatcher. They exist only so inferredProvisioners() can wire their provisioner. @@ -557,6 +560,9 @@ final class CfnProvisionerFixture { discovered.add(new SchedulerScheduleGroupCfnProvisioner(schedulerService)); discovered.add(new SchedulerScheduleCfnProvisioner(schedulerService)); } + if (codeDeployService != null) { + discovered.add(new CodeDeployCfnProvisioner(codeDeployService)); + } if (transferService != null) { discovered.add(new TransferCfnProvisioner(transferService)); } @@ -782,6 +788,11 @@ final class CfnProvisionerFixture { return this; } + public Builder codeDeploy(CodeDeployService v) { + this.codeDeployService = v; + return this; + } + public Builder transfer(TransferService v) { this.transferService = v; return this; diff --git a/src/test/java/io/floci/aws/services/cloudformation/CodeDeployApplicationCfnIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CodeDeployApplicationCfnIntegrationTest.java new file mode 100644 index 0000000000..869455ff32 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CodeDeployApplicationCfnIntegrationTest.java @@ -0,0 +1,126 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.testing.CfnStackWaits; +import io.floci.aws.testing.CfnTestStack; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.services.cloudformation.model.Stack; + +import static io.floci.aws.testing.CfnStackWaits.output; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Provisions {@code AWS::CodeDeploy::Application} through a stack and reads the applications back + * through CodeDeploy (issue #8626: the stack reported CREATE_COMPLETE with nothing behind it). + * {@code Ref} is the name, an update retags the same application, a later resource's failure puts + * the tags back, changing ComputePlatform replaces the unnamed application, and deleting the stack + * removes both. + */ +@QuarkusTest +class CodeDeployApplicationCfnIntegrationTest { + + private static final String CODEDEPLOY_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/codedeploy/aws4_request"; + + @RegisterExtension + final CfnTestStack stack = new CfnTestStack("codedeploy-app-cfn-it"); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void createUpdateRollBackReplaceAndDeleteApplications() { + String named = stack.name() + "-named"; + + Stack created = stack.create(template(named, "v1", "Server", false)); + String unnamed = output(created, "UnnamedRef"); + assertEquals(named, output(created, "NamedRef")); + getApplication(named).statusCode(200) + .body("application.applicationName", equalTo(named)) + .body("application.computePlatform", equalTo("Lambda")); + assertStageTag(named, "v1"); + getApplication(unnamed).statusCode(200) + .body("application.applicationName", startsWith(stack.name() + "-Unnamed-")) + .body("application.computePlatform", equalTo("Server")); + + Stack retagged = stack.update(template(named, "v2", "Server", false), "UPDATE_COMPLETE"); + assertEquals(unnamed, output(retagged, "UnnamedRef")); + assertStageTag(named, "v2"); + + stack.update(template(named, "v3", "Server", true), "UPDATE_ROLLBACK_COMPLETE"); + assertStageTag(named, "v2"); + + // ComputePlatform is create-only: changing it replaces the unnamed application under a new + // name, and the committed update deletes the old one. + Stack replaced = stack.update(template(named, "v2", "ECS", false), "UPDATE_COMPLETE"); + String replacement = output(replaced, "UnnamedRef"); + assertNotEquals(unnamed, replacement); + getApplication(replacement).statusCode(200) + .body("application.applicationName", startsWith(stack.name() + "-Unnamed-")) + .body("application.computePlatform", equalTo("ECS")); + getApplication(unnamed).statusCode(400).body("__type", equalTo("ApplicationDoesNotExistException")); + + CfnStackWaits.deleteStack(stack.name()); + + getApplication(named).statusCode(400).body("__type", equalTo("ApplicationDoesNotExistException")); + getApplication(replacement).statusCode(400).body("__type", equalTo("ApplicationDoesNotExistException")); + } + + private static String template(String named, String stage, String platform, boolean laterFails) { + return """ + { + "Resources": { + "Named": { + "Type": "AWS::CodeDeploy::Application", + "Properties": { + "ApplicationName": "%s", + "ComputePlatform": "Lambda", + "Tags": [{"Key": "stage", "Value": "%s"}] + } + }, + "Unnamed": { + "Type": "AWS::CodeDeploy::Application", + "Properties": {"ComputePlatform": "%s"} + }%s + }, + "Outputs": { + "NamedRef": {"Value": {"Ref": "Named"}}, + "UnnamedRef": {"Value": {"Ref": "Unnamed"}} + } + } + """.formatted(named, stage, platform, laterFails ? CfnStackWaits.failingResourceAfter("Named") : ""); + } + + private static void assertStageTag(String name, String value) { + codeDeploy("ListTagsForResource", + "{\"ResourceArn\":\"arn:aws:codedeploy:us-east-1:000000000000:application:" + name + "\"}") + .statusCode(200) + .body("Tags", hasSize(1)) + .body("Tags[0].Key", equalTo("stage")) + .body("Tags[0].Value", equalTo(value)); + } + + private static ValidatableResponse getApplication(String name) { + return codeDeploy("GetApplication", "{\"applicationName\":\"" + name + "\"}"); + } + + private static ValidatableResponse codeDeploy(String action, String body) { + return given() + .header("Authorization", CODEDEPLOY_AUTH) + .header("X-Amz-Target", "CodeDeploy_20141006." + action) + .contentType("application/x-amz-json-1.1") + .body(body) + .when().post("/").then(); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CodeDeployCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CodeDeployCfnProvisionerTest.java new file mode 100644 index 0000000000..ab3e34ab49 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CodeDeployCfnProvisionerTest.java @@ -0,0 +1,450 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cloudformation.model.StackResource; +import io.floci.aws.services.codedeploy.CodeDeployService; +import io.floci.aws.services.codedeploy.model.Application; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +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.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +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; + +/** {@code AWS::CodeDeploy::Application} in isolation, with only {@link CodeDeployService} mocked. */ +class CodeDeployCfnProvisionerTest { + + private static final String ARN = "arn:aws:codedeploy:us-east-1:000000000000:application:my-app"; + + private final CodeDeployService codeDeploy = mock(CodeDeployService.class); + private final CodeDeployCfnProvisioner provisioner = new CodeDeployCfnProvisioner(codeDeploy); + private final ObjectMapper mapper = new ObjectMapper(); + + private ProvisionContext ctx(String priorPhysicalId) { + return ctx(priorPhysicalId, null); + } + + private ProvisionContext ctx(String priorPhysicalId, JsonNode priorProperties) { + return new ProvisionContext(ProvisionContexts.passthroughEngine(), "us-east-1", "000000000000", "my-stack", + priorPhysicalId, event -> { }, priorProperties); + } + + private static StackResource resource() { + StackResource r = new StackResource(); + r.setLogicalId("App"); + r.setResourceType("AWS::CodeDeploy::Application"); + r.setAttributes(new HashMap<>()); + return r; + } + + /** A provisioned application whose tag keys {@code keys} the stack set. */ + private static StackResource owning(String... keys) { + StackResource r = resource(); + r.getAttributes().put(CodeDeployCfnProvisioner.TAG_KEYS_ATTR, + "[" + String.join(",", Arrays.stream(keys).map(k -> "\"" + k + "\"").toList()) + "]"); + return r; + } + + private static Application app(String name) { + Application a = new Application(); + a.setApplicationName(name); + return a; + } + + @Test + void createsTheApplicationWithItsComputePlatformAndTags() { + when(codeDeploy.createApplication(eq("us-east-1"), eq("my-app"), eq("Lambda"), any())) + .thenReturn(app("my-app")); + ObjectNode props = mapper.createObjectNode().put("ApplicationName", "my-app").put("ComputePlatform", "Lambda"); + props.putArray("Tags").add(mapper.createObjectNode().put("Key", "team").put("Value", "core")); + StackResource r = resource(); + + provisioner.provision(r, props, ctx(null)); + + verify(codeDeploy).createApplication("us-east-1", "my-app", "Lambda", + List.of(Map.of("Key", "team", "Value", "core"))); + assertEquals("my-app", r.getPhysicalId()); + } + + @Test + void anUnnamedApplicationGetsAGeneratedName() { + when(codeDeploy.createApplication(eq("us-east-1"), anyString(), eq(null), any())) + .thenAnswer(inv -> app(inv.getArgument(1))); + StackResource r = resource(); + + provisioner.provision(r, mapper.createObjectNode(), ctx(null)); + + assertTrue(r.getPhysicalId().startsWith("my-stack-App-"), r.getPhysicalId()); + } + + @Test + void aBlankWrittenIntoTheTemplateReachesCodeDeployToBeRejected() { + when(codeDeploy.createApplication(eq("us-east-1"), eq(""), any(), any())) + .thenThrow(new AwsException("ApplicationNameRequiredException", "required", 400)); + ObjectNode props = mapper.createObjectNode().put("ApplicationName", "").put("ComputePlatform", ""); + + assertThrows(AwsException.class, () -> provisioner.provision(resource(), props, ctx(null))); + + verify(codeDeploy).createApplication("us-east-1", "", "", List.of()); + } + + @Test + void aPropertyThatResolvesToNoValueIsAbsent() { + when(codeDeploy.createApplication(eq("us-east-1"), anyString(), eq(null), any())) + .thenAnswer(inv -> app(inv.getArgument(1))); + ObjectNode props = mapper.createObjectNode(); + props.putObject("ApplicationName").put("Ref", "AWS::NoValue"); + props.putObject("ComputePlatform").put("Ref", "AWS::NoValue"); + StackResource r = resource(); + + provisioner.provision(r, props, ctx(null)); + + assertTrue(r.getPhysicalId().startsWith("my-stack-App-"), r.getPhysicalId()); + } + + @Test + void anUpdateReconcilesTagsOnTheSameApplication() { + when(codeDeploy.applicationArn("us-east-1", "my-app")).thenReturn(ARN); + when(codeDeploy.listTagsForResource(ARN)).thenReturn(List.of( + Map.of("Key", "team", "Value", "core"), Map.of("Key", "owner", "Value", "alice"))); + ObjectNode props = mapper.createObjectNode().put("ApplicationName", "my-app"); + props.putArray("Tags").add(mapper.createObjectNode().put("Key", "team").put("Value", "edge")); + StackResource r = owning("team", "owner"); + + provisioner.provision(r, props, ctx("my-app")); + + verify(codeDeploy, never()).createApplication(anyString(), anyString(), any(), any()); + verify(codeDeploy).untagResource(ARN, List.of("owner")); + verify(codeDeploy).tagResource(ARN, List.of(Map.of("Key", "team", "Value", "edge"))); + assertEquals("my-app", r.getPhysicalId()); + } + + @Test + void anUnnamedApplicationKeepsItsNameAcrossUpdates() { + when(codeDeploy.applicationArn("us-east-1", "my-stack-App-0123456789ab")).thenReturn(ARN); + when(codeDeploy.listTagsForResource(ARN)).thenReturn(List.of()); + StackResource r = resource(); + + provisioner.provision(r, mapper.createObjectNode(), ctx("my-stack-App-0123456789ab")); + + verify(codeDeploy, never()).createApplication(anyString(), anyString(), any(), any()); + assertEquals("my-stack-App-0123456789ab", r.getPhysicalId()); + } + + @Test + void changingTheComputePlatformOfAnUnnamedApplicationReplacesIt() { + when(codeDeploy.createApplication(eq("us-east-1"), anyString(), eq("ECS"), any())) + .thenAnswer(inv -> app(inv.getArgument(1))); + StackResource r = resource(); + + provisioner.provision(r, mapper.createObjectNode().put("ComputePlatform", "ECS"), + ctx("my-stack-App-0123456789ab", mapper.createObjectNode().put("ComputePlatform", "Server"))); + + assertTrue(r.getPhysicalId().startsWith("my-stack-App-"), r.getPhysicalId()); + assertNotEquals("my-stack-App-0123456789ab", r.getPhysicalId()); + verify(codeDeploy).createApplication(eq("us-east-1"), eq(r.getPhysicalId()), eq("ECS"), any()); + } + + @Test + void changingTheComputePlatformOfANamedApplicationIsRefused() { + ObjectNode props = mapper.createObjectNode().put("ApplicationName", "my-app").put("ComputePlatform", "ECS"); + ObjectNode prior = mapper.createObjectNode().put("ApplicationName", "my-app").put("ComputePlatform", "Server"); + + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.provision(resource(), props, ctx("my-app", prior))); + + assertEquals("ValidationError", failure.getErrorCode()); + verify(codeDeploy, never()).createApplication(anyString(), anyString(), any(), any()); + } + + @Test + void renamingANamedApplicationCreatesTheNewName() { + when(codeDeploy.createApplication(eq("us-east-1"), eq("new-app"), any(), any())).thenReturn(app("new-app")); + StackResource r = resource(); + + provisioner.provision(r, mapper.createObjectNode().put("ApplicationName", "new-app"), + ctx("my-app", mapper.createObjectNode().put("ApplicationName", "my-app"))); + + assertEquals("new-app", r.getPhysicalId()); + verify(codeDeploy).createApplication(eq("us-east-1"), eq("new-app"), any(), any()); + } + + @Test + void droppingTheNameOfANamedApplicationGeneratesOne() { + when(codeDeploy.createApplication(eq("us-east-1"), anyString(), any(), any())) + .thenAnswer(inv -> app(inv.getArgument(1))); + StackResource r = resource(); + + provisioner.provision(r, mapper.createObjectNode(), + ctx("my-app", mapper.createObjectNode().put("ApplicationName", "my-app"))); + + assertTrue(r.getPhysicalId().startsWith("my-stack-App-"), r.getPhysicalId()); + verify(codeDeploy).createApplication(eq("us-east-1"), eq(r.getPhysicalId()), any(), any()); + } + + @Test + void removingAllTagsUntagsEveryKey() { + when(codeDeploy.applicationArn("us-east-1", "my-app")).thenReturn(ARN); + when(codeDeploy.listTagsForResource(ARN)).thenReturn(List.of( + Map.of("Key", "team", "Value", "core"), Map.of("Key", "owner", "Value", "alice"))); + StackResource r = owning("team", "owner"); + + provisioner.provision(r, mapper.createObjectNode().put("ApplicationName", "my-app"), ctx("my-app")); + + verify(codeDeploy).untagResource(eq(ARN), + argThat(keys -> keys.size() == 2 && keys.containsAll(List.of("team", "owner")))); + verify(codeDeploy, never()).tagResource(anyString(), any()); + } + + @Test + void aTagAddedOutsideTheStackStays() { + when(codeDeploy.applicationArn("us-east-1", "my-app")).thenReturn(ARN); + when(codeDeploy.listTagsForResource(ARN)).thenReturn(List.of( + Map.of("Key", "team", "Value", "core"), Map.of("Key", "outside", "Value", "kept"))); + + provisioner.provision(owning("team"), mapper.createObjectNode().put("ApplicationName", "my-app"), + ctx("my-app")); + + verify(codeDeploy).untagResource(ARN, List.of("team")); + } + + /** An in-place update of my-app from team=core, owner=alice (both the stack's) to team=edge. */ + private StackResource updatedInPlace() { + when(codeDeploy.applicationArn("us-east-1", "my-app")).thenReturn(ARN); + when(codeDeploy.listTagsForResource(ARN)).thenReturn(List.of( + Map.of("Key", "team", "Value", "core"), Map.of("Key", "owner", "Value", "alice"))); + ObjectNode props = mapper.createObjectNode().put("ApplicationName", "my-app"); + props.putArray("Tags").add(mapper.createObjectNode().put("Key", "team").put("Value", "edge")); + StackResource r = owning("owner", "team"); + provisioner.provision(r, props, ctx("my-app")); + return r; + } + + @Test + void rollingBackAnInPlaceUpdatePutsTheTagsBack() { + StackResource r = updatedInPlace(); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(codeDeploy).tagResource(eq(ARN), argThat(tags -> tags.size() == 2 + && tags.containsAll(List.of(Map.of("Key", "team", "Value", "core"), + Map.of("Key", "owner", "Value", "alice"))))); + assertEquals("[\"owner\",\"team\"]", r.getAttributes().get(CodeDeployCfnProvisioner.TAG_KEYS_ATTR)); + assertFalse(r.getAttributes().containsKey(CodeDeployCfnProvisioner.SNAPSHOT_ATTR)); + } + + @Test + void aCommittedInPlaceUpdateHasNothingToRollBack() { + StackResource r = updatedInPlace(); + + provisioner.completeUpdate(r); + + assertFalse(r.getAttributes().containsKey(CodeDeployCfnProvisioner.SNAPSHOT_ATTR)); + assertEquals("[\"team\"]", r.getAttributes().get(CodeDeployCfnProvisioner.TAG_KEYS_ATTR)); + assertFalse(provisioner.rollbackUpdate(r)); + } + + @Test + void aTagUpdateThatFailsPutsTheTagsBackBeforeFailing() { + when(codeDeploy.applicationArn("us-east-1", "my-app")).thenReturn(ARN); + when(codeDeploy.listTagsForResource(ARN)).thenReturn(List.of(Map.of("Key", "team", "Value", "core"))); + doThrow(new AwsException("InvalidTagsToAddException", "bad", 400)).doNothing() + .when(codeDeploy).tagResource(eq(ARN), any()); + ObjectNode props = mapper.createObjectNode().put("ApplicationName", "my-app"); + props.putArray("Tags") + .add(mapper.createObjectNode().put("Key", "team").put("Value", "edge")) + .add(mapper.createObjectNode().put("Key", "added").put("Value", "x")); + + assertThrows(AwsException.class, () -> provisioner.provision(owning("team"), props, ctx("my-app"))); + + verify(codeDeploy).untagResource(ARN, List.of("added")); + verify(codeDeploy).tagResource(ARN, List.of(Map.of("Key", "team", "Value", "core"))); + } + + /** Replaces an unnamed application by changing its ComputePlatform; returns the resource. */ + private StackResource replacedUnnamedApplication() { + when(codeDeploy.createApplication(eq("us-east-1"), anyString(), eq("ECS"), any())) + .thenAnswer(inv -> app(inv.getArgument(1))); + StackResource r = resource(); + provisioner.provision(r, mapper.createObjectNode().put("ComputePlatform", "ECS"), + ctx("old-app", mapper.createObjectNode().put("ComputePlatform", "Server"))); + return r; + } + + @Test + void completingAReplacementDeletesThePriorApplication() { + StackResource r = replacedUnnamedApplication(); + String replacement = r.getPhysicalId(); + + provisioner.completeUpdate(r); + + verify(codeDeploy).deleteApplication("us-east-1", "old-app"); + verify(codeDeploy, never()).deleteApplication("us-east-1", replacement); + } + + @Test + void rollingBackAReplacementDeletesTheNewApplicationAndRestoresTheOld() { + StackResource r = replacedUnnamedApplication(); + String replacement = r.getPhysicalId(); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(codeDeploy).deleteApplication("us-east-1", replacement); + verify(codeDeploy, never()).deleteApplication("us-east-1", "old-app"); + assertEquals("old-app", r.getPhysicalId()); + } + + /** The dispatcher's stub for App, as a stack created before this provisioner holds it. */ + private static StackResource stub() { + StackResource r = resource(); + r.getAttributes().put("Arn", "arn:aws:stub:::App"); + return r; + } + + @Test + void anUpdateOfAStubCreatesTheApplicationUnderTheStubsId() { + when(codeDeploy.createApplication(eq("us-east-1"), eq("App-1a2b3c4d"), eq("Lambda"), any())) + .thenReturn(app("App-1a2b3c4d")); + StackResource r = stub(); + ObjectNode props = mapper.createObjectNode().put("ComputePlatform", "Lambda"); + + provisioner.provision(r, props, ctx("App-1a2b3c4d", props.deepCopy())); + + verify(codeDeploy).createApplication(eq("us-east-1"), eq("App-1a2b3c4d"), eq("Lambda"), any()); + verify(codeDeploy, never()).tagResource(anyString(), any()); + verify(codeDeploy, never()).untagResource(anyString(), any()); + assertEquals("App-1a2b3c4d", r.getPhysicalId()); + assertFalse(r.getAttributes().containsKey("Arn"), "the stub's Arn names nothing that exists"); + } + + @Test + void rollingBackAStubMigrationDeletesTheApplicationAndRestoresTheStub() { + when(codeDeploy.createApplication(eq("us-east-1"), eq("App-1a2b3c4d"), any(), any())) + .thenReturn(app("App-1a2b3c4d")); + StackResource r = stub(); + provisioner.provision(r, mapper.createObjectNode(), ctx("App-1a2b3c4d", mapper.createObjectNode())); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(codeDeploy).deleteApplication("us-east-1", "App-1a2b3c4d"); + assertEquals("App-1a2b3c4d", r.getPhysicalId()); + assertEquals("arn:aws:stub:::App", r.getAttributes().get("Arn")); + } + + @Test + void anUpdateOfAStubThatNamesTheApplicationCreatesThatNameAndRollsItBack() { + when(codeDeploy.createApplication(eq("us-east-1"), eq("my-app"), any(), any())).thenReturn(app("my-app")); + StackResource r = stub(); + ObjectNode props = mapper.createObjectNode().put("ApplicationName", "my-app"); + + provisioner.provision(r, props, ctx("App-1a2b3c4d", props.deepCopy())); + + verify(codeDeploy).createApplication(eq("us-east-1"), eq("my-app"), any(), any()); + assertEquals("my-app", r.getPhysicalId()); + assertFalse(r.getAttributes().containsKey("Arn"), "the stub's Arn names nothing that exists"); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(codeDeploy).deleteApplication("us-east-1", "my-app"); + assertEquals("App-1a2b3c4d", r.getPhysicalId()); + assertEquals("arn:aws:stub:::App", r.getAttributes().get("Arn")); + } + + @Test + void committingAnUpdateOfAStubDeletesNothing() { + when(codeDeploy.createApplication(eq("us-east-1"), eq("my-app"), any(), any())).thenReturn(app("my-app")); + StackResource r = stub(); + ObjectNode props = mapper.createObjectNode().put("ApplicationName", "my-app"); + provisioner.provision(r, props, ctx("App-1a2b3c4d", props.deepCopy())); + + provisioner.completeUpdate(r); + + verify(codeDeploy, never()).deleteApplication(anyString(), anyString()); + } + + @Test + void clearUpdateDropsTheTagSnapshot() { + StackResource r = updatedInPlace(); + assertTrue(r.getAttributes().containsKey(CodeDeployCfnProvisioner.SNAPSHOT_ATTR)); + + provisioner.clearUpdate(r); + + assertFalse(r.getAttributes().containsKey(CodeDeployCfnProvisioner.SNAPSHOT_ATTR)); + assertFalse(provisioner.rollbackUpdate(r)); + } + + @Test + void anUpdateOverAVanishedApplicationCreatesItAndARollbackDeletesIt() { + when(codeDeploy.getApplication("us-east-1", "my-app")) + .thenThrow(new AwsException("ApplicationDoesNotExistException", "gone", 400)); + when(codeDeploy.createApplication(eq("us-east-1"), eq("my-app"), any(), any())).thenReturn(app("my-app")); + ObjectNode props = mapper.createObjectNode().put("ApplicationName", "my-app"); + props.putArray("Tags").add(mapper.createObjectNode().put("Key", "team").put("Value", "core")); + StackResource r = owning("team"); + + provisioner.provision(r, props, ctx("my-app", props.deepCopy())); + + verify(codeDeploy).createApplication("us-east-1", "my-app", null, + List.of(Map.of("Key", "team", "Value", "core"))); + verify(codeDeploy, never()).tagResource(anyString(), any()); + verify(codeDeploy, never()).untagResource(anyString(), any()); + assertEquals("my-app", r.getPhysicalId()); + + assertTrue(provisioner.rollbackUpdate(r)); + + verify(codeDeploy).deleteApplication("us-east-1", "my-app"); + assertEquals("my-app", r.getPhysicalId()); + assertFalse(r.getAttributes().containsKey(CodeDeployCfnProvisioner.SNAPSHOT_ATTR)); + } + + @Test + void aFailureReadingThePriorApplicationPropagatesAndCreatesNothing() { + when(codeDeploy.getApplication("us-east-1", "my-app")) + .thenThrow(new AwsException("ThrottlingException", "slow down", 400)); + + assertThrows(AwsException.class, () -> provisioner.provision(owning(), + mapper.createObjectNode().put("ApplicationName", "my-app"), ctx("my-app"))); + + verify(codeDeploy, never()).createApplication(anyString(), anyString(), any(), any()); + } + + @Test + void deleteRemovesTheApplication() { + provisioner.delete("AWS::CodeDeploy::Application", "my-app", "us-east-1"); + verify(codeDeploy).deleteApplication("us-east-1", "my-app"); + } + + @Test + void deletingAnApplicationThatIsAlreadyGoneSucceeds() { + doThrow(new AwsException("ApplicationDoesNotExistException", "gone", 400)) + .when(codeDeploy).deleteApplication("us-east-1", "my-app"); + assertDoesNotThrow(() -> provisioner.delete("AWS::CodeDeploy::Application", "my-app", "us-east-1")); + } + + @Test + void anyOtherDeleteFailurePropagates() { + doThrow(new AwsException("InternalFailure", "boom", 500)) + .when(codeDeploy).deleteApplication("us-east-1", "my-app"); + assertThrows(AwsException.class, + () -> provisioner.delete("AWS::CodeDeploy::Application", "my-app", "us-east-1")); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java index be9408a54b..af5a6a663c 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/ProvisionContextTest.java @@ -299,6 +299,23 @@ class ProvisionContextTest { } } + @Test + void resolveOptionalWrittenKeepsALiteralBlankButNotOneAnIntrinsicResolvesTo() { + ProvisionContext ctx = context(null); + JsonNode blankParameter = props("{\"Ref\": \"Empty\"}"); + when(engine.resolve(blankParameter)).thenReturn(""); + + assertEquals("Lambda", ctx.resolveOptionalWritten(props("{\"P\": \"Lambda\"}"), "P"), "a value"); + assertEquals("", ctx.resolveOptionalWritten(props("{\"P\": \"\"}"), "P"), "a blank written into the template"); + assertNull(ctx.resolveOptionalWritten(props("{}"), "P"), "absent"); + assertNull(ctx.resolveOptionalWritten(props("{\"P\": null}"), "P"), "explicitly null"); + assertNull(ctx.resolveOptionalWritten(null, "P"), "no properties at all"); + assertNull(ctx.resolveOptionalWritten(props("{\"P\": {\"Ref\": \"AWS::NoValue\"}}"), "P"), + "an intrinsic that resolves to blank, as AWS::NoValue does"); + assertNull(ctx.resolveOptionalWritten(props("{\"P\": {\"Ref\": \"Empty\"}}"), "P"), + "a Ref to a blank parameter, which cannot be told apart from AWS::NoValue"); + } + @Test void resolveOptionalBigIntegerReadsAnyWidthAndTakesTheAbsentRuleOfResolveOptionalInt() { ProvisionContext ctx = context(null); diff --git a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java index 8956fe3603..ac50047857 100644 --- a/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java +++ b/src/test/java/io/floci/aws/services/codedeploy/CodeDeployServiceTest.java @@ -88,6 +88,52 @@ class CodeDeployServiceTest { Map.of("type", "HOST_COUNT", "value", 1), "Server", null, null).getCreateTime()); } + @Test + void deletingAnApplicationDropsItsTags() { + String arn = service.applicationArn(REGION, "tagged-app"); + service.createApplication(REGION, "tagged-app", "Server", List.of(Map.of("Key", "team", "Value", "core"))); + + service.deleteApplication(REGION, "tagged-app"); + service.createApplication(REGION, "tagged-app", "Server", null); + + assertEquals(List.of(), service.listTagsForResource(arn)); + } + + @Test + void deletingAnApplicationDeletesItsDeploymentGroupsAndTheirTags() { + String groupArn = service.deploymentGroupArn(REGION, "grouped-app", "group"); + service.createApplication(REGION, "grouped-app", "Server", null); + service.createDeploymentGroup(REGION, "grouped-app", "group", null, ROLE_ARN, Map.of(), + List.of(Map.of("Key", "team", "Value", "core"))); + + service.deleteApplication(REGION, "grouped-app"); + service.createApplication(REGION, "grouped-app", "Server", null); + + assertEquals(List.of(), service.listDeploymentGroups(REGION, "grouped-app")); + assertEquals(List.of(), service.listTagsForResource(groupArn)); + } + + @Test + void createApplicationValidatesTheNameAndComputePlatformAsCodeDeployDoes() { + assertEquals("ApplicationNameRequiredException", assertThrows(AwsException.class, + () -> service.createApplication(REGION, null, null, null)).getErrorCode()); + assertEquals("ApplicationNameRequiredException", assertThrows(AwsException.class, + () -> service.createApplication(REGION, "", null, null)).getErrorCode()); + assertEquals("InvalidApplicationNameException", assertThrows(AwsException.class, + () -> service.createApplication(REGION, "a".repeat(101), null, null)).getErrorCode()); + assertEquals("InvalidApplicationNameException", assertThrows(AwsException.class, + () -> service.createApplication(REGION, "has space", null, null)).getErrorCode()); + assertEquals("InvalidComputePlatformException", assertThrows(AwsException.class, + () -> service.createApplication(REGION, "bad-platform", "Windows", null)).getErrorCode()); + + for (String platform : List.of("Server", "Lambda", "ECS", "Kubernetes")) { + assertEquals(platform, service.createApplication(REGION, "app-" + platform, platform, null) + .getComputePlatform()); + } + assertEquals(100, service.createApplication(REGION, "a".repeat(100), null, null) + .getApplicationName().length()); + } + @Test void onPremisesRegistrationAndDeregistrationUseTheDeploymentClock() { Clock clock = Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC); diff --git a/src/test/resources/cloudformation/schema-surface.tsv b/src/test/resources/cloudformation/schema-surface.tsv index 476403812d..423345ef27 100644 --- a/src/test/resources/cloudformation/schema-surface.tsv +++ b/src/test/resources/cloudformation/schema-surface.tsv @@ -60,6 +60,7 @@ AWS::CloudWatch::Alarm Arn ActionConfiguration,ActionsEnabled,AlarmActions,Alarm AWS::CloudWatch::CompositeAlarm Arn ActionConfiguration,ActionsEnabled,ActionsSuppressor,ActionsSuppressorExtensionPeriod,ActionsSuppressorWaitPeriod,AlarmActions,AlarmDescription,AlarmName,AlarmRule,InsufficientDataActions,OKActions,Tags AWS::CloudWatch::Dashboard DashboardBody,DashboardName,Tags AWS::CodeBuild::Project Arn Artifacts,AutoRetryLimit,BadgeEnabled,BuildBatchConfig,Cache,ConcurrentBuildLimit,Description,EncryptionKey,Environment,FileSystemLocations,LogsConfig,Name,QueuedTimeoutInMinutes,ResourceAccessRole,SecondaryArtifacts,SecondarySourceVersions,SecondarySources,ServiceRole,Source,SourceVersion,Tags,TimeoutInMinutes,Triggers,Visibility,VpcConfig +AWS::CodeDeploy::Application ApplicationName,ComputePlatform,Tags AWS::CodePipeline::CustomActionType Id Category,ConfigurationProperties,InputArtifactDetails,OutputArtifactDetails,Provider,Settings,Tags,Version AWS::CodePipeline::Pipeline Arn,Version ArtifactStore,ArtifactStores,DisableInboundStageTransitions,ExecutionMode,Name,PipelineType,RestartExecutionOnUpdate,RoleArn,Stages,Tags,Triggers,Variables AWS::CodePipeline::Webhook Id,Url Authentication,AuthenticationConfiguration,Filters,Name,RegisterWithThirdParty,Tags,TargetAction,TargetPipeline,TargetPipelineVersion diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 9d915dc189..c1b3f4885b 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -61,6 +61,7 @@ AWS::CloudWatch::Alarm CloudWatchCfnProvisioner AWS::CloudWatch::CompositeAlarm CloudWatchCompositeAlarmCfnProvisioner AWS::CloudWatch::Dashboard CloudWatchDashboardCfnProvisioner AWS::CodeBuild::Project CodeBuildCfnProvisioner +AWS::CodeDeploy::Application CodeDeployCfnProvisioner AWS::CodePipeline::CustomActionType CodePipelineCfnProvisioner AWS::CodePipeline::Pipeline CodePipelineCfnProvisioner AWS::CodePipeline::Webhook CodePipelineCfnProvisioner diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index afabdef12d..8f36cd6ba4 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -45,6 +45,7 @@ order: - AWS::StepFunctions - AWS::CodePipeline - AWS::CodeBuild + - AWS::CodeDeploy - AWS::Batch - AWS::Cognito - AWS::CertificateManager @@ -144,6 +145,7 @@ service_labels: AWS::CloudTrail: CloudTrail AWS::CloudWatch: CloudWatch AWS::CodeBuild: CodeBuild + AWS::CodeDeploy: CodeDeploy AWS::CodePipeline: CodePipeline AWS::Cognito: Cognito AWS::Config: Config