diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationAppConfigTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationAppConfigTest.java new file mode 100644 index 0000000000..30a8e3daec --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationAppConfigTest.java @@ -0,0 +1,210 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.appconfig.AppConfigClient; +import software.amazon.awssdk.services.appconfig.model.GetApplicationResponse; +import software.amazon.awssdk.services.appconfig.model.GetConfigurationProfileResponse; +import software.amazon.awssdk.services.appconfig.model.GetDeploymentStrategyResponse; +import software.amazon.awssdk.services.appconfig.model.GetEnvironmentResponse; +import software.amazon.awssdk.services.appconfig.model.ResourceNotFoundException; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.CloudFormationException; +import software.amazon.awssdk.services.cloudformation.model.Output; +import software.amazon.awssdk.services.cloudformation.model.Stack; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("CloudFormation AWS::AppConfig::*") +class CloudFormationAppConfigTest { + + private static final String ALARM = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-errors"; + + private static CloudFormationClient cfn; + private static AppConfigClient appConfig; + private String stackName; + private boolean stackCreated; + + @BeforeAll + static void clients() { + cfn = TestFixtures.cloudFormationClient(); + appConfig = TestFixtures.appConfigClient(); + } + + @BeforeEach + void setup() { + stackName = TestFixtures.uniqueName("compat-cfn-appconfig"); + } + + @AfterEach + void cleanup() throws InterruptedException { + deleteStack(); + } + + @AfterAll + static void closeClients() { + cfn.close(); + appConfig.close(); + } + + @Test + void createsTheFourTypesThatReadBackThroughTheAppConfigApiAndDeletesThemWithTheStack() + throws InterruptedException { + createStack(template("orders", "hosted")); + + String app = output("AppId"); + String env = output("EnvId"); + String profile = output("ProfileId"); + String strategy = output("StrategyId"); + assertThat(output("AppRef")).as("Ref is the application ID").isEqualTo(app); + assertThat(output("EnvRef")).isEqualTo(env); + assertThat(output("ProfileRef")).isEqualTo(profile); + assertThat(output("StrategyRef")).isEqualTo(strategy); + + GetApplicationResponse application = appConfig.getApplication(r -> r.applicationId(app)); + assertThat(application.name()).isEqualTo("orders"); + assertThat(appConfig.listTagsForResource(r -> r.resourceArn(applicationArn(app))).tags()) + .isEqualTo(Map.of("team", "payments")); + GetEnvironmentResponse environment = appConfig.getEnvironment(r -> r.applicationId(app).environmentId(env)); + assertThat(environment.name()).isEqualTo("beta"); + assertThat(environment.monitors()).singleElement() + .satisfies(monitor -> assertThat(monitor.alarmArn()).isEqualTo(ALARM)); + GetConfigurationProfileResponse configurationProfile = appConfig.getConfigurationProfile( + r -> r.applicationId(app).configurationProfileId(profile)); + assertThat(configurationProfile.name()).isEqualTo("settings"); + assertThat(configurationProfile.locationUri()).isEqualTo("hosted"); + assertThat(configurationProfile.type()).isEqualTo("AWS.Freeform"); + GetDeploymentStrategyResponse deploymentStrategy = appConfig.getDeploymentStrategy( + r -> r.deploymentStrategyId(strategy)); + assertThat(deploymentStrategy.name()).isEqualTo("gradual"); + assertThat(deploymentStrategy.deploymentDurationInMinutes()).isEqualTo(10); + assertThat(deploymentStrategy.growthFactor()).isEqualTo(20f); + assertThat(deploymentStrategy.growthTypeAsString()).isEqualTo("EXPONENTIAL"); + + deleteStack(); + assertThatThrownBy(() -> appConfig.getEnvironment(r -> r.applicationId(app).environmentId(env))) + .isInstanceOf(ResourceNotFoundException.class); + assertThatThrownBy(() -> appConfig.getConfigurationProfile( + r -> r.applicationId(app).configurationProfileId(profile))) + .isInstanceOf(ResourceNotFoundException.class); + assertThatThrownBy(() -> appConfig.getDeploymentStrategy(r -> r.deploymentStrategyId(strategy))) + .isInstanceOf(ResourceNotFoundException.class); + assertThatThrownBy(() -> appConfig.getApplication(r -> r.applicationId(app))) + .isInstanceOf(ResourceNotFoundException.class); + } + + @Test + void anUpdateRenamesTheApplicationInPlaceAndReplacesTheProfileWhoseLocationChanges() + throws InterruptedException { + createStack(template("orders", "hosted")); + String app = output("AppId"); + String profile = output("ProfileId"); + + cfn.updateStack(r -> r.stackName(stackName).templateBody(template("orders-v2", "ssm-parameter://settings"))); + awaitStatus("UPDATE_COMPLETE"); + + assertThat(output("AppId")).as("the application is changed in place").isEqualTo(app); + assertThat(appConfig.getApplication(r -> r.applicationId(app)).name()).isEqualTo("orders-v2"); + String replacement = output("ProfileId"); + assertThat(replacement).as("a LocationUri change replaces the profile").isNotEqualTo(profile); + assertThat(appConfig.getConfigurationProfile(r -> r.applicationId(app).configurationProfileId(replacement)) + .locationUri()).isEqualTo("ssm-parameter://settings"); + assertThatThrownBy(() -> appConfig.getConfigurationProfile( + r -> r.applicationId(app).configurationProfileId(profile))) + .as("the displaced profile is deleted once the update commits") + .isInstanceOf(ResourceNotFoundException.class); + } + + private static String template(String applicationName, String locationUri) { + return """ + { + "Resources": { + "App": {"Type": "AWS::AppConfig::Application", "Properties": { + "Name": "%s", "Tags": [{"Key": "team", "Value": "payments"}]}}, + "Env": {"Type": "AWS::AppConfig::Environment", "Properties": { + "ApplicationId": {"Ref": "App"}, "Name": "beta", + "Monitors": [{"AlarmArn": "%s"}]}}, + "Profile": {"Type": "AWS::AppConfig::ConfigurationProfile", "Properties": { + "ApplicationId": {"Ref": "App"}, "Name": "settings", "LocationUri": "%s", + "Type": "AWS.Freeform"}}, + "Strategy": {"Type": "AWS::AppConfig::DeploymentStrategy", "Properties": { + "Name": "gradual", "ReplicateTo": "NONE", "DeploymentDurationInMinutes": 10, + "GrowthFactor": 20, "GrowthType": "EXPONENTIAL"}} + }, + "Outputs": { + "AppRef": {"Value": {"Ref": "App"}}, + "AppId": {"Value": {"Fn::GetAtt": ["App", "ApplicationId"]}}, + "EnvRef": {"Value": {"Ref": "Env"}}, + "EnvId": {"Value": {"Fn::GetAtt": ["Env", "EnvironmentId"]}}, + "ProfileRef": {"Value": {"Ref": "Profile"}}, + "ProfileId": {"Value": {"Fn::GetAtt": ["Profile", "ConfigurationProfileId"]}}, + "StrategyRef": {"Value": {"Ref": "Strategy"}}, + "StrategyId": {"Value": {"Fn::GetAtt": ["Strategy", "Id"]}} + } + } + """.formatted(applicationName, ALARM, locationUri); + } + + private static String applicationArn(String applicationId) { + return "arn:aws:appconfig:" + TestFixtures.region().id() + ":000000000000:application/" + applicationId; + } + + private void createStack(String template) throws InterruptedException { + cfn.createStack(r -> r.stackName(stackName).templateBody(template)); + stackCreated = true; + awaitStatus("CREATE_COMPLETE"); + } + + private String output(String key) { + return cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0).outputs().stream() + .filter(o -> key.equals(o.outputKey())).map(Output::outputValue) + .findFirst().orElseThrow(); + } + + /** Waits for {@code expected}, failing as soon as the stack settles on any other status. */ + private void awaitStatus(String expected) throws InterruptedException { + TestFixtures.await(() -> { + Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0); + String status = stack.stackStatusAsString(); + if (!expected.equals(status) && !status.endsWith("_IN_PROGRESS")) { + throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason()); + } + return expected.equals(status); + }, stackName, expected, 60_000_000_000L, 100); + } + + private void deleteStack() throws InterruptedException { + if (!stackCreated) { + return; + } + cfn.deleteStack(r -> r.stackName(stackName)); + TestFixtures.await(() -> { + try { + List stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks(); + if (stacks.isEmpty()) { + return true; + } + Stack stack = stacks.get(0); + if ("DELETE_FAILED".equals(stack.stackStatusAsString())) { + throw new AssertionError(stackName + " deletion failed: " + stack.stackStatusReason()); + } + return "DELETE_COMPLETE".equals(stack.stackStatusAsString()); + } catch (CloudFormationException e) { + if ("ValidationError".equals(e.awsErrorDetails().errorCode()) + && e.getMessage().contains("does not exist")) { + return true; + } + throw e; + } + }, stackName, "stack deletion", 60_000_000_000L, 100); + stackCreated = false; + } +} diff --git a/docs/services/appconfig.md b/docs/services/appconfig.md index 7d4375655b..d3ef6a4914 100644 --- a/docs/services/appconfig.md +++ b/docs/services/appconfig.md @@ -80,6 +80,37 @@ as a string. Rules of the form `(eq $attribute "value")` are encoded; a profile with any other rule is returned unchanged, as JSON, and Floci logs a warning, as it does for a caller that does not accept Ion. +## CloudFormation + +Floci provisions these resource types: + +- `AWS::AppConfig::Application` +- `AWS::AppConfig::Environment` +- `AWS::AppConfig::ConfigurationProfile` +- `AWS::AppConfig::DeploymentStrategy` + +`Ref` returns the AppConfig ID of each, which `Fn::GetAtt` also returns as `ApplicationId`, `EnvironmentId`, +`ConfigurationProfileId` and `Id`. A configuration profile's `KmsKeyArn` is not set. + +An update that changes only mutable properties keeps the ID and changes the resource in place: the name and +description of an application, environment or configuration profile, an environment's `Monitors`, an application's +`Tags`, and a deployment strategy's description, duration, final bake time, growth factor and growth type. A property +the template drops is cleared, or set back to its default (`FinalBakeTimeInMinutes` 0, `GrowthType` `LINEAR`). A +change to a createOnly property (`ApplicationId` on an environment or configuration profile, `LocationUri` or `Type` +on a configuration profile, `Name` or `ReplicateTo` on a deployment strategy) replaces the resource: the new one is +created and the old one is deleted once the stack update completes. A failed stack update puts back what it changed in +place and deletes what it created. + +Deleting an environment deletes its deployments, and deleting a configuration profile deletes its hosted configuration +versions. Floci keeps tags on applications only, so `Tags` on the other three types are accepted and not stored, as +`TagResource` treats them; so are a configuration profile's `KmsKeyIdentifier`, `RetrievalRoleArn` and `Validators`, +and `DeletionProtectionCheck`. `ReplicateTo: SSM_DOCUMENT` writes no SSM document. +`AWS::AppConfig::HostedConfigurationVersion`, `Deployment`, `Extension` and `ExtensionAssociation` are not provisioned. + +A stack created before Floci provisioned these types holds stubs for them, and an update creates the real resource in +place of a stub only when it changes that resource. An update that changes an environment or configuration profile of +a stubbed application therefore fails with `ResourceNotFoundException` unless it changes the application too. + ## Configuration | Variable | Default | Description | diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 8a8f10eac0..f6d4134fac 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -198,6 +198,7 @@ cross-resource references. | API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `GatewayResponse`, `ApiKey`, `UsagePlan`, `UsagePlanKey` | | API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment`, `DomainName`, `ApiMapping`, `VpcLink` | | AppSync | `GraphQLApi`, `GraphQLSchema`, `DataSource`, `FunctionConfiguration`, `Resolver`, `ApiKey`. `Ref` on `GraphQLApi` and `ApiKey` returns the id where AWS returns the ARN. See [AppSync](appsync.md#cloudformation) for `Ref` and `Fn::GetAtt` compared with AWS. | +| AppConfig | `Application`, `Environment` (`Tags` and `DeletionProtectionCheck` are accepted and not stored), `ConfigurationProfile` (`Tags`, `KmsKeyIdentifier`, `RetrievalRoleArn`, `Validators` and `DeletionProtectionCheck` are accepted and not stored), `DeploymentStrategy` (`Tags` are accepted and not stored; `ReplicateTo: SSM_DOCUMENT` writes no SSM document). `Ref` returns the AppConfig ID of each. See [AppConfig](appconfig.md#cloudformation) for updates and replacement. | | Step Functions | `StateMachine` | | CodePipeline | `Pipeline`, `CustomActionType`, `Webhook` | | CodeBuild | `Project` | diff --git a/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java b/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java index e5597cb571..1b513783d4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java +++ b/src/main/java/io/github/hectorvent/floci/services/appconfig/AppConfigService.java @@ -23,6 +23,7 @@ import org.jboss.logging.Logger; import java.util.ArrayList; import java.util.Comparator; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -86,12 +87,46 @@ public class AppConfigService { return applicationStore.scan(k -> true); } + /** The application whose ID is exactly {@code applicationId}; GetApplication also takes a name. */ + public Optional findApplication(String applicationId) { + return applicationStore.get(applicationId); + } + + private Application requireApplicationById(String applicationId) { + return applicationStore.get(applicationId) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Application not found", 404)); + } + public synchronized void deleteApplication(String idOrName) { applicationStore.get(idOrName) .or(() -> listApplications().stream().filter(a -> idOrName.equals(a.getName())).findFirst()) .ifPresent(application -> applicationStore.delete(application.getId())); } + /** + * Deletes the application whose ID is exactly {@code applicationId}; nothing happens when there + * is no such application. Unlike {@link #deleteApplication}, it never falls back to a name, so a + * CloudFormation delete of an application already deleted through the API leaves another + * application named like its ID alone. + */ + public synchronized void deleteApplicationById(String applicationId) { + applicationStore.get(applicationId).ifPresent(application -> applicationStore.delete(applicationId)); + } + + /** + * Sets the name and description of the application whose ID is {@code applicationId}, as a + * CloudFormation update of {@code AWS::AppConfig::Application} does: both are written, so a null + * description clears it. Floci serves no UpdateApplication route; the CloudFormation provisioner + * is the only caller. + */ + public synchronized Application updateApplication(String applicationId, String name, String description) { + Application app = copy(requireApplicationById(applicationId)); + app.setName(name); + app.setDescription(description); + applicationStore.put(app.getId(), app); + return app; + } + // ──────────────────────────── Environment ──────────────────────────── public Environment createEnvironment(String applicationIdentifier, Map request) { @@ -116,9 +151,21 @@ public class AppConfigService { public synchronized void deleteEnvironment(String applicationIdentifier, String environmentIdentifier) { Application application = resolveApplication(applicationIdentifier); Environment environment = resolveEnvironment(application.getId(), environmentIdentifier); - String appId = application.getId(); - String envId = environment.getId(); + removeEnvironment(application.getId(), environment.getId()); + } + /** + * Deletes the environment whose ID is exactly {@code environmentId}, with its deployments, + * without resolving its application, which may already be deleted; nothing happens when there + * is no such environment. The CloudFormation provisioner deletes environments this way: an + * update that moves an environment to another application and removes the old one deletes that + * application before the environment it displaced. + */ + public synchronized void deleteEnvironmentById(String environmentId) { + environmentStore.get(environmentId).ifPresent(env -> removeEnvironment(env.getApplicationId(), env.getId())); + } + + private void removeEnvironment(String appId, String envId) { StorageOperations.deleteByPrefix(deploymentStore, appId + "::" + envId + "::"); StorageOperations.deleteByPrefix(activeConfigStore, envId + "::"); @@ -144,6 +191,31 @@ public class AppConfigService { .toList(); } + /** The environment whose ID is exactly {@code environmentId}, in whichever application holds it. */ + public Optional findEnvironment(String environmentId) { + return environmentStore.get(environmentId); + } + + /** + * Sets the name, description and monitors of an environment, as a CloudFormation update of + * {@code AWS::AppConfig::Environment} does: all three are written, so a null description or + * monitor list clears it. The monitors are checked as CreateEnvironment checks them, before + * anything is written. Floci serves no UpdateEnvironment route; the CloudFormation provisioner + * is the only caller. + */ + public synchronized Environment updateEnvironment(String applicationId, String environmentId, String name, + String description, Object monitors) { + List checked = monitors(monitors); + Environment env = copy(environmentStore.get(environmentId) + .filter(e -> applicationId.equals(e.getApplicationId())) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Environment not found", 404))); + env.setName(name); + env.setDescription(description); + env.setMonitors(checked); + environmentStore.put(env.getId(), env); + return env; + } + /** The request's Monitors, checked against the limits AWS documents for CreateEnvironment. */ private static List monitors(Object value) { if (value == null) { @@ -214,6 +286,28 @@ public class AppConfigService { .toList(); } + /** The configuration profile whose ID is exactly {@code profileId}, in whichever application holds it. */ + public Optional findConfigurationProfile(String profileId) { + return profileStore.get(profileId); + } + + /** + * Sets the name and description of a configuration profile, as a CloudFormation update of + * {@code AWS::AppConfig::ConfigurationProfile} does: both are written, so a null description + * clears it. Floci serves no UpdateConfigurationProfile route; the CloudFormation provisioner is + * the only caller. + */ + public synchronized ConfigurationProfile updateConfigurationProfile(String applicationId, String profileId, + String name, String description) { + ConfigurationProfile profile = copy(profileStore.get(profileId) + .filter(p -> applicationId.equals(p.getApplicationId())) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Configuration profile not found", 404))); + profile.setName(name); + profile.setDescription(description); + profileStore.put(profile.getId(), profile); + return profile; + } + public synchronized void deleteConfigurationProfile(String applicationIdentifier, String profileIdentifier) { String appId = resolveApplication(applicationIdentifier).getId(); // Unlike deleteApplication (a single, unscoped ID), a profile is nested under an @@ -235,7 +329,22 @@ public class AppConfigService { if (profile == null) { return; } - String profileId = profile.getId(); + removeConfigurationProfile(appId, profile.getId()); + } + + /** + * Deletes the configuration profile whose ID is exactly {@code profileId}, with its hosted + * configuration versions, without resolving its application, which may already be deleted; + * nothing happens when there is no such profile. The CloudFormation provisioner deletes profiles + * this way: an update that moves a profile to another application and removes the old one + * deletes that application before the profile it displaced. + */ + public synchronized void deleteConfigurationProfileById(String profileId) { + profileStore.get(profileId) + .ifPresent(profile -> removeConfigurationProfile(profile.getApplicationId(), profile.getId())); + } + + private void removeConfigurationProfile(String appId, String profileId) { // A hosted configuration version isn't independently addressable outside its profile's // lifecycle - cascade the delete so a caller can't still fetch versions for a profile // that's supposedly gone. @@ -345,6 +454,27 @@ public class AppConfigService { return result; } + /** + * Sets the mutable settings of a stored deployment strategy, as a CloudFormation update of + * {@code AWS::AppConfig::DeploymentStrategy} does; its name and {@code ReplicateTo} are + * create-only. The predefined strategies are not stored, so they are not found here. Floci + * serves no UpdateDeploymentStrategy route; the CloudFormation provisioner is the only caller. + */ + public synchronized DeploymentStrategy updateDeploymentStrategy(String id, String description, + int deploymentDurationInMinutes, + int finalBakeTimeInMinutes, float growthFactor, + String growthType) { + DeploymentStrategy strategy = copy(strategyStore.get(id) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Deployment strategy not found", 404))); + strategy.setDescription(description); + strategy.setDeploymentDurationInMinutes(deploymentDurationInMinutes); + strategy.setFinalBakeTimeInMinutes(finalBakeTimeInMinutes); + strategy.setGrowthFactor(growthFactor); + strategy.setGrowthType(growthType); + strategyStore.put(strategy.getId(), strategy); + return strategy; + } + public synchronized void deleteDeploymentStrategy(String id) { // Predefined strategies aren't real stored resources (see builtinStrategy above) - // silently no-op'ing here would report success for a delete that did nothing, and the @@ -565,6 +695,19 @@ public class AppConfigService { applicationStore.put(app.getId(), app); } + /** + * Sets the tags of the application whose ID is exactly {@code applicationId} to {@code tags}, + * removing any other key, as a CloudFormation create or update of {@code Tags} does; {@code tags} + * is not null. Unlike {@link #tagApplication} (TagResource) it never falls back to a name, so tags + * for an application already deleted through the API fail with ResourceNotFoundException rather + * than land on another named like its ID. + */ + public synchronized void setApplicationTags(String applicationId, Map tags) { + Application app = copy(requireApplicationById(applicationId)); + app.setTags(new HashMap<>(tags)); + applicationStore.put(app.getId(), app); + } + /** * A copy of a stored entity for a write to change and put back. The in-memory stores hand out the * stored instance itself, so changing it in place would change an entity a caller read earlier, diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppConfigCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppConfigCfnProvisioner.java new file mode 100644 index 0000000000..3bd8b38e8c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppConfigCfnProvisioner.java @@ -0,0 +1,492 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.appconfig.AppConfigService; +import io.github.hectorvent.floci.services.appconfig.model.Application; +import io.github.hectorvent.floci.services.appconfig.model.ConfigurationProfile; +import io.github.hectorvent.floci.services.appconfig.model.DeploymentStrategy; +import io.github.hectorvent.floci.services.appconfig.model.Environment; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.math.BigDecimal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Provisions {@code AWS::AppConfig::Application}, {@code Environment}, {@code ConfigurationProfile} + * and {@code DeploymentStrategy}. The physical id and {@code Ref} of each is the ID AppConfig gives + * it, which is also its ID attribute for {@code Fn::GetAtt}: {@code ApplicationId}, + * {@code EnvironmentId}, {@code ConfigurationProfileId} and {@code Id}. + * + *

An update that keeps every create-only property changes the entity in place. Every mutable + * property is written, so one the template drops is cleared or back at its default, and what the + * update replaces is kept on the resource so a failed stack update can put it back; an + * application's tags are driven to the template's set. An update that changes a create-only + * property (the {@code ApplicationId} of an environment or profile, a profile's {@code LocationUri} + * or {@code Type}, a strategy's {@code Name} or {@code ReplicateTo}) creates the new entity and + * leaves the displaced one to the {@link ReplacementCleanup} record. Whether one changed is judged on + * the resolved template values the entity was made from, as CloudFormation compares them. + * + *

Floci keeps AppConfig tags on applications only, so {@code Tags} on the other three types are + * accepted and not stored, as Floci's AppConfig TagResource treats them. So are a profile's + * {@code KmsKeyIdentifier}, {@code RetrievalRoleArn} and {@code Validators}, and the + * {@code DeletionProtectionCheck} of an environment or profile, which Floci's create operations do + * not keep either. + */ +@ApplicationScoped +public class AppConfigCfnProvisioner implements CfnResourceProvisioner { + + private static final String APPLICATION = "AWS::AppConfig::Application"; + private static final String ENVIRONMENT = "AWS::AppConfig::Environment"; + private static final String PROFILE = "AWS::AppConfig::ConfigurationProfile"; + private static final String STRATEGY = "AWS::AppConfig::DeploymentStrategy"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** The registry schemas' length limits. */ + private static final int NAME_MAX_LENGTH = 64; + private static final int PROFILE_NAME_MAX_LENGTH = 128; + private static final int DESCRIPTION_MAX_LENGTH = 1024; + private static final int LOCATION_URI_MAX_LENGTH = 2048; + /** The range AppConfig takes for a strategy's duration and final bake time, in minutes. */ + private static final int MAX_MINUTES = 1440; + /** The registry schemas' enums. */ + private static final List DELETION_PROTECTION_CHECKS = List.of("ACCOUNT_DEFAULT", "APPLY", "BYPASS"); + private static final List GROWTH_TYPES = List.of("EXPONENTIAL", "LINEAR"); + private static final List REPLICATE_TO = List.of("NONE", "SSM_DOCUMENT"); + + /** + * The create-only properties as resolved when the entity was made, so an update can tell + * whether one changed. Under the uses prefix, like the application ID below, so a rolled-back + * replacement puts back the values the prior entity was made from. + */ + private static final String CREATE_ONLY_ATTR = CfnRollback.USES_ATTR_PREFIX + "AppConfigCreateOnly"; + /** + * The ID of the application an environment or profile belongs to: the stack deletes a leftover + * environment or profile before an application by it. + */ + private static final String APPLICATION_ATTR = CfnRollback.USES_ATTR_PREFIX + "AppConfigApplicationId"; + + private final AppConfigService service; + + @Inject + public AppConfigCfnProvisioner(AppConfigService service) { + this.service = service; + } + + @Override + public Set resourceTypes() { + return Set.of(APPLICATION, ENVIRONMENT, PROFILE, STRATEGY); + } + + @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(CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR); + if (ctx.isUpdate()) { + // Rolling this update back undoes it alone; only ContinueUpdateRollback retries the + // delete the last rollback could not make. + ReplacementCleanup.endRollbackRetry(r); + } + Map attributesBefore = new HashMap<>(r.getAttributes()); + // A stack from before these types had a provisioner holds the dispatcher's stub here, which + // names nothing, so the entity is created as on a first deploy. + boolean updating = ctx.isUpdate() && !CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore); + switch (r.getResourceType()) { + case APPLICATION -> provisionApplication(r, props, ctx, updating); + case ENVIRONMENT -> provisionEnvironment(r, props, ctx, updating); + case PROFILE -> provisionProfile(r, props, ctx, updating); + case STRATEGY -> provisionStrategy(r, props, ctx, updating); + default -> throw new IllegalArgumentException("Unsupported AppConfig resource type " + r.getResourceType()); + } + ReplacementCleanup.record(r, ctx, attributesBefore); + } + + /** + * An application has no create-only property, so an update always changes it in place. Its tags + * are applied once it exists, and a create whose tagging fails deletes it again. + */ + private void provisionApplication(StackResource r, JsonNode props, ProvisionContext ctx, boolean updating) { + String name = requiredText(APPLICATION, props, "Name", NAME_MAX_LENGTH, ctx); + String description = optionalText(APPLICATION, props, "Description", DESCRIPTION_MAX_LENGTH, ctx); + Map tags = ctx.resolveTags(props, "Tags"); + if (updating) { + String id = ctx.priorPhysicalId(); + snapshotBeforeUpdate(r, application(id)); + CfnRollback.guarded(r, ctx, false, () -> { }, () -> restoreSnapshot(r), () -> { + service.updateApplication(id, name, description); + service.setApplicationTags(id, tags); + }); + return; + } + Map request = new HashMap<>(); + request.put("Name", name); + request.put("Description", description); + Application app = service.createApplication(request); + r.setPhysicalId(app.getId()); + r.getAttributes().put("ApplicationId", app.getId()); + CfnRollback.guarded(r, ctx, true, () -> service.deleteApplicationById(app.getId()), () -> { }, () -> { + if (!tags.isEmpty()) { + service.setApplicationTags(app.getId(), tags); + } + }); + } + + private void provisionEnvironment(StackResource r, JsonNode props, ProvisionContext ctx, boolean updating) { + String applicationId = requiredText(ENVIRONMENT, props, "ApplicationId", 0, ctx); + String name = requiredText(ENVIRONMENT, props, "Name", NAME_MAX_LENGTH, ctx); + String description = optionalText(ENVIRONMENT, props, "Description", DESCRIPTION_MAX_LENGTH, ctx); + Object monitors = jsonValue(resolved(props, "Monitors", ctx)); + allowed(ENVIRONMENT, "DeletionProtectionCheck", text(props, "DeletionProtectionCheck", ctx), + DELETION_PROTECTION_CHECKS); + ObjectNode createOnly = MAPPER.createObjectNode().put("ApplicationId", applicationId); + if (updating && madeFrom(r, createOnly)) { + Environment current = service.findEnvironment(ctx.priorPhysicalId()) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Environment not found", 404)); + snapshotBeforeUpdate(r, current); + service.updateEnvironment(current.getApplicationId(), current.getId(), name, description, monitors); + return; + } + Map request = new HashMap<>(); + request.put("Name", name); + request.put("Description", description); + request.put("Monitors", monitors); + Environment env = service.createEnvironment(applicationId, request); + r.setPhysicalId(env.getId()); + r.getAttributes().put("EnvironmentId", env.getId()); + r.getAttributes().put(APPLICATION_ATTR, env.getApplicationId()); + r.getAttributes().put(CREATE_ONLY_ATTR, createOnly.toString()); + } + + private void provisionProfile(StackResource r, JsonNode props, ProvisionContext ctx, boolean updating) { + String applicationId = requiredText(PROFILE, props, "ApplicationId", 0, ctx); + String name = requiredText(PROFILE, props, "Name", PROFILE_NAME_MAX_LENGTH, ctx); + String locationUri = requiredText(PROFILE, props, "LocationUri", LOCATION_URI_MAX_LENGTH, ctx); + String type = text(props, "Type", ctx); + String description = optionalText(PROFILE, props, "Description", DESCRIPTION_MAX_LENGTH, ctx); + allowed(PROFILE, "DeletionProtectionCheck", text(props, "DeletionProtectionCheck", ctx), + DELETION_PROTECTION_CHECKS); + ObjectNode createOnly = MAPPER.createObjectNode() + .put("ApplicationId", applicationId) + .put("LocationUri", locationUri) + .put("Type", type); + if (updating && madeFrom(r, createOnly)) { + ConfigurationProfile current = service.findConfigurationProfile(ctx.priorPhysicalId()) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Configuration profile not found", 404)); + snapshotBeforeUpdate(r, current); + service.updateConfigurationProfile(current.getApplicationId(), current.getId(), name, description); + return; + } + Map request = new HashMap<>(); + request.put("Name", name); + request.put("Description", description); + request.put("LocationUri", locationUri); + request.put("Type", type); + ConfigurationProfile profile = service.createConfigurationProfile(applicationId, request); + r.setPhysicalId(profile.getId()); + r.getAttributes().put("ConfigurationProfileId", profile.getId()); + r.getAttributes().put(APPLICATION_ATTR, profile.getApplicationId()); + r.getAttributes().put(CREATE_ONLY_ATTR, createOnly.toString()); + } + + /** + * A strategy's {@code FinalBakeTimeInMinutes} and {@code GrowthType} take AppConfig's defaults, + * 0 and {@code LINEAR}, when the template gives none. + */ + private void provisionStrategy(StackResource r, JsonNode props, ProvisionContext ctx, boolean updating) { + String name = requiredText(STRATEGY, props, "Name", NAME_MAX_LENGTH, ctx); + String replicateTo = allowed(STRATEGY, "ReplicateTo", requiredText(STRATEGY, props, "ReplicateTo", 0, ctx), + REPLICATE_TO); + Integer duration = minutes(props, "DeploymentDurationInMinutes", ctx); + if (duration == null) { + throw new AwsException("ValidationError", STRATEGY + " requires DeploymentDurationInMinutes", 400); + } + Integer finalBake = minutes(props, "FinalBakeTimeInMinutes", ctx); + int finalBakeMinutes = finalBake == null ? 0 : finalBake; + float growthFactor = growthFactor(props, ctx); + String growthType = allowed(STRATEGY, "GrowthType", text(props, "GrowthType", ctx), GROWTH_TYPES); + String effectiveGrowthType = growthType == null ? "LINEAR" : growthType; + String description = optionalText(STRATEGY, props, "Description", DESCRIPTION_MAX_LENGTH, ctx); + ObjectNode createOnly = MAPPER.createObjectNode().put("Name", name).put("ReplicateTo", replicateTo); + if (updating && madeFrom(r, createOnly)) { + String id = ctx.priorPhysicalId(); + snapshotBeforeUpdate(r, service.getDeploymentStrategy(id)); + service.updateDeploymentStrategy(id, description, duration, finalBakeMinutes, growthFactor, + effectiveGrowthType); + return; + } + Map request = new HashMap<>(); + request.put("Name", name); + request.put("Description", description); + request.put("DeploymentDurationInMinutes", duration); + request.put("FinalBakeTimeInMinutes", finalBakeMinutes); + request.put("GrowthFactor", growthFactor); + request.put("GrowthType", effectiveGrowthType); + request.put("ReplicateTo", replicateTo); + DeploymentStrategy strategy = service.createDeploymentStrategy(request); + r.setPhysicalId(strategy.getId()); + r.getAttributes().put("Id", strategy.getId()); + r.getAttributes().put(CREATE_ONLY_ATTR, createOnly.toString()); + } + + /** The application whose ID is exactly {@code id}: GetApplication also takes a name. */ + private Application application(String id) { + return service.findApplication(id) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", "Application not found", 404)); + } + + /** + * Whether the entity the resource holds was made from these create-only values. A resource + * that recorded none, or none this can read, was not, so it is replaced rather than changed. + */ + private static boolean madeFrom(StackResource r, ObjectNode createOnly) { + String recorded = r.getAttributes().get(CREATE_ONLY_ATTR); + if (recorded == null) { + return false; + } + try { + return MAPPER.readTree(recorded).equals(createOnly); + } catch (JsonProcessingException e) { + return false; + } + } + + /** Keeps the entity as it is before an in-place update, so {@link #rollbackUpdate} can put it back. */ + private static void snapshotBeforeUpdate(StackResource r, Object current) { + r.getAttributes().put(CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR, MAPPER.valueToTree(current).toString()); + } + + /** + * The resolved property, or null when it is absent or {@code AWS::NoValue}, directly or as the + * {@code Fn::If} branch its condition chooses. Every other value is kept as resolved, so a blank + * string a parameter supplies is a value, as the same string written literally is. The stack + * engine already leaves such properties out before provisioning; omitting them here as well keeps + * the same answer for callers that hand over properties directly. + */ + private static JsonNode resolved(JsonNode props, String name, ProvisionContext ctx) { + if (props == null || !props.has(name)) { + return null; + } + JsonNode resolved = ctx.engine().resolveNodeOmittingNoValue(props.get(name)); + return resolved == null || resolved.isNull() || resolved.isMissingNode() ? null : resolved; + } + + private static String text(JsonNode props, String name, ProvisionContext ctx) { + JsonNode value = resolved(props, name, ctx); + return value == null ? null : value.asText(); + } + + /** A required string; {@code maxLength} 0 means the schema sets no limit. */ + private static String requiredText(String type, JsonNode props, String name, int maxLength, ProvisionContext ctx) { + String value = text(props, name, ctx); + if (value == null || value.isEmpty()) { + throw new AwsException("ValidationError", type + " requires " + name, 400); + } + return withinLength(type, name, value, maxLength); + } + + private static String optionalText(String type, JsonNode props, String name, int maxLength, ProvisionContext ctx) { + String value = text(props, name, ctx); + return value == null ? null : withinLength(type, name, value, maxLength); + } + + private static String withinLength(String type, String name, String value, int maxLength) { + if (maxLength > 0 && value.length() > maxLength) { + throw new AwsException("ValidationError", + type + " " + name + " must be at most " + maxLength + " characters", 400); + } + return value; + } + + /** {@code value} when the schema allows it, or null when it is absent. */ + private static String allowed(String type, String name, String value, List values) { + if (value != null && !values.contains(value)) { + throw new AwsException("ValidationError", + type + " " + name + " must be one of " + String.join(", ", values) + ", got '" + value + "'", 400); + } + return value; + } + + /** A resolved list or object as the plain values a service request carries. */ + private static Object jsonValue(JsonNode value) { + return value == null ? null : MAPPER.convertValue(value, Object.class); + } + + /** + * A whole number of minutes from 0 to 1440, as AppConfig takes it, or null when absent. The + * schema types it as a number, and a parameter supplies it as a string. + */ + private static Integer minutes(JsonNode props, String name, ProvisionContext ctx) { + JsonNode value = resolved(props, name, ctx); + if (value == null) { + return null; + } + BigDecimal number = number(value); + if (number == null || number.signum() < 0 || number.compareTo(BigDecimal.valueOf(MAX_MINUTES)) > 0 + || number.stripTrailingZeros().scale() > 0) { + throw new AwsException("ValidationError", STRATEGY + " " + name + + " must be a whole number of minutes from 0 to " + MAX_MINUTES + ", got " + value.asText(), 400); + } + return number.intValueExact(); + } + + /** The percentage of targets per interval, from 1 to 100, as AppConfig takes it. */ + private static float growthFactor(JsonNode props, ProvisionContext ctx) { + JsonNode value = resolved(props, "GrowthFactor", ctx); + if (value == null) { + throw new AwsException("ValidationError", STRATEGY + " requires GrowthFactor", 400); + } + BigDecimal number = number(value); + if (number == null || number.compareTo(BigDecimal.ONE) < 0 || number.compareTo(BigDecimal.valueOf(100)) > 0) { + throw new AwsException("ValidationError", + STRATEGY + " GrowthFactor must be a number from 1 to 100, got " + value.asText(), 400); + } + return number.floatValue(); + } + + private static BigDecimal number(JsonNode value) { + if (value.isNumber()) { + return value.decimalValue(); + } + try { + return new BigDecimal(value.asText().trim()); + } catch (NumberFormatException e) { + return null; + } + } + + /** A stub left from before these types had a provisioner names nothing, so nothing is deleted. */ + @Override + public void delete(StackResource resource, String region) { + if (CfnResourceDispatcher.isStub(resource.getPhysicalId(), resource.getAttributes())) { + return; + } + delete(resource.getResourceType(), resource.getPhysicalId(), region); + } + + /** + * Deletes the entity whose ID is exactly {@code physicalId}, so a name AppConfig would also take + * never selects another one, and the displaced entity of a replacement is found by its ID alone. + * An environment or profile is deleted without looking up its application, which the stack may + * already have deleted: an update that moves them to a new application and removes the old one + * deletes that application before the entities it displaced. One already gone counts as + * deleted. An environment takes its + * deployments with it, and a profile its hosted configuration versions. + */ + @Override + public void delete(String resourceType, String physicalId, String region) { + if (physicalId == null || physicalId.isBlank()) { + return; + } + switch (resourceType) { + case APPLICATION -> service.deleteApplicationById(physicalId); + case ENVIRONMENT -> service.deleteEnvironmentById(physicalId); + case PROFILE -> service.deleteConfigurationProfileById(physicalId); + case STRATEGY -> service.deleteDeploymentStrategy(physicalId); + default -> throw new IllegalArgumentException("Unsupported AppConfig resource type " + resourceType); + } + } + + @Override + public boolean hasReplacementUpdate(StackResource resource) { + return ReplacementCleanup.hasReplacement(resource); + } + + @Override + public String updateCleanupPhysicalId(StackResource resource) { + return ReplacementCleanup.cleanupPhysicalId(resource); + } + + @Override + public UpdateCleanupResult completeUpdate(StackResource resource) { + return ReplacementCleanup.complete(resource, this::delete); + } + + @Override + public void clearUpdate(StackResource resource) { + resource.getAttributes().remove(CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR); + ReplacementCleanup.clear(resource); + } + + /** + * Keeps the snapshot of an in-place update whose own undo did not complete. The engine restores + * the previous resource and reports the rollback failure once; with the snapshot of the state + * the update started from, a ContinueUpdateRollback restores that state, instead of finding + * nothing to undo or an older snapshot a committed update left on the previous resource. + */ + @Override + public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) { + String snapshot = attempted.getAttributes().get(CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR); + if (snapshot != null && attempted.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR)) { + previous.getAttributes().put(CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR, snapshot); + } + } + + /** + * A replacement is undone through the cleanup record and an in-place update from the snapshot + * taken before it, which every mutable property is written back from. With neither on the + * resource the provision failed before it changed anything, so there is nothing to undo. + */ + @Override + public boolean rollbackUpdate(StackResource resource) { + if (ReplacementCleanup.rollback(resource, this::delete)) { + return true; + } + restoreSnapshot(resource); + return true; + } + + /** + * Writes back what the snapshot holds, if the resource carries one. It is spent only once the + * restore succeeded: a restore that throws leaves it in place for the next attempt instead of + * reporting a rollback that never happened. + */ + private void restoreSnapshot(StackResource resource) { + JsonNode snapshot = CfnRollback.updateSnapshot(resource, CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR); + if (snapshot == null) { + return; + } + try { + restore(resource.getResourceType(), snapshot); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not read the AppConfig update snapshot for " + + resource.getLogicalId(), e); + } + resource.getAttributes().remove(CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR); + } + + private void restore(String resourceType, JsonNode snapshot) throws JsonProcessingException { + switch (resourceType) { + case APPLICATION -> { + Application prior = MAPPER.treeToValue(snapshot, Application.class); + service.updateApplication(prior.getId(), prior.getName(), prior.getDescription()); + service.setApplicationTags(prior.getId(), prior.getTags()); + } + case ENVIRONMENT -> { + Environment prior = MAPPER.treeToValue(snapshot, Environment.class); + service.updateEnvironment(prior.getApplicationId(), prior.getId(), prior.getName(), + prior.getDescription(), jsonValue(snapshot.get("Monitors"))); + } + case PROFILE -> { + ConfigurationProfile prior = MAPPER.treeToValue(snapshot, ConfigurationProfile.class); + service.updateConfigurationProfile(prior.getApplicationId(), prior.getId(), prior.getName(), + prior.getDescription()); + } + case STRATEGY -> { + DeploymentStrategy prior = MAPPER.treeToValue(snapshot, DeploymentStrategy.class); + service.updateDeploymentStrategy(prior.getId(), prior.getDescription(), + prior.getDeploymentDurationInMinutes(), prior.getFinalBakeTimeInMinutes(), + prior.getGrowthFactor(), prior.getGrowthType()); + } + default -> throw new IllegalArgumentException("Unsupported AppConfig resource type " + resourceType); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java index 00044c8082..57713518fa 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java @@ -190,6 +190,16 @@ public final class CfnRollback { */ public static final String GUARDDUTY_PLAN_UPDATE_SNAPSHOT_ATTR = "__FlociGuardDutyPlanUpdateSnapshot"; + /** + * Holds what an AppConfig application, environment, configuration profile or deployment + * strategy carried before an in-place update changed it, with the IDs that address it, so a + * failed stack update can put it back. Written by {@code AppConfigCfnProvisioner} before its + * update call and spent by its {@code rollbackUpdate}; when its own undo did not complete, the + * provisioner carries it onto the restored resource through + * {@code mergeFailedUpdateResourceTracking}. + */ + public static final String APPCONFIG_UPDATE_SNAPSHOT_ATTR = "__FlociAppConfigUpdateSnapshot"; + /** * Holds the name and tags an API Gateway V2 VPC link carried before an in-place update changed * them, so a failed stack update can put them back. Written by {@code ApiGatewayV2CfnProvisioner} diff --git a/src/main/resources/cloudformation/create-only-properties.json b/src/main/resources/cloudformation/create-only-properties.json index a79905d050..2818e46bc3 100644 --- a/src/main/resources/cloudformation/create-only-properties.json +++ b/src/main/resources/cloudformation/create-only-properties.json @@ -73,6 +73,19 @@ "SecurityGroupIds", "SubnetIds" ], + "AWS::AppConfig::Application": [], + "AWS::AppConfig::ConfigurationProfile": [ + "ApplicationId", + "LocationUri", + "Type" + ], + "AWS::AppConfig::DeploymentStrategy": [ + "Name", + "ReplicateTo" + ], + "AWS::AppConfig::Environment": [ + "ApplicationId" + ], "AWS::AppSync::ApiKey": [ "ApiId" ], diff --git a/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceUpdateIsolationTest.java b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceUpdateIsolationTest.java new file mode 100644 index 0000000000..1a82746731 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceUpdateIsolationTest.java @@ -0,0 +1,100 @@ +package io.github.hectorvent.floci.services.appconfig; + +import io.github.hectorvent.floci.services.appconfig.model.Application; +import io.github.hectorvent.floci.services.appconfig.model.ConfigurationProfile; +import io.github.hectorvent.floci.services.appconfig.model.DeploymentStrategy; +import io.github.hectorvent.floci.services.appconfig.model.Environment; +import io.github.hectorvent.floci.services.appconfig.model.Monitor; +import io.github.hectorvent.floci.testing.InMemoryStorageFactory; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * The update methods CloudFormation uses write a new copy of the entity rather than change the + * stored one field by field. The in-memory stores hand out the stored instance itself, so a caller + * that read an entity before the update, such as a ListDeployments building a summary from a + * strategy, must keep seeing all of its prior values rather than a mix of old and new. + */ +class AppConfigServiceUpdateIsolationTest { + + private static final String ALARM = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-errors"; + + private final AppConfigService service = new AppConfigService(new InMemoryStorageFactory("000000000000"), null); + + @Test + void aStrategyReadBeforeAnUpdateKeepsItsPriorSettings() { + DeploymentStrategy created = service.createDeploymentStrategy(Map.of("Name", "gradual", + "DeploymentDurationInMinutes", 10, "FinalBakeTimeInMinutes", 5, "GrowthFactor", 25, + "GrowthType", "EXPONENTIAL", "ReplicateTo", "NONE")); + DeploymentStrategy before = service.getDeploymentStrategy(created.getId()); + + service.updateDeploymentStrategy(created.getId(), "faster", 1, 0, 100f, "LINEAR"); + + assertEquals(10, before.getDeploymentDurationInMinutes()); + assertEquals(5, before.getFinalBakeTimeInMinutes()); + assertEquals(25f, before.getGrowthFactor()); + assertEquals("EXPONENTIAL", before.getGrowthType()); + assertNull(before.getDescription()); + DeploymentStrategy after = service.getDeploymentStrategy(created.getId()); + assertEquals(1, after.getDeploymentDurationInMinutes()); + assertEquals(100f, after.getGrowthFactor()); + assertEquals("faster", after.getDescription()); + assertEquals("gradual", after.getName()); + assertEquals("NONE", after.getReplicateTo()); + } + + @Test + void anApplicationReadBeforeAnUpdateKeepsItsPriorNameAndTags() { + Application created = service.createApplication(Map.of("Name", "orders", "Description", "First")); + service.tagApplication(created.getId(), Map.of("team", "payments")); + Application before = service.getApplication(created.getId()); + + service.updateApplication(created.getId(), "orders-v2", null); + + assertEquals("orders", before.getName()); + assertEquals("First", before.getDescription()); + Application after = service.getApplication(created.getId()); + assertEquals("orders-v2", after.getName()); + assertNull(after.getDescription()); + assertEquals(Map.of("team", "payments"), after.getTags(), "an update keeps the application's tags"); + } + + @Test + void anEnvironmentReadBeforeAnUpdateKeepsItsPriorMonitors() { + String appId = service.createApplication(Map.of("Name", "orders")).getId(); + Environment created = service.createEnvironment(appId, Map.of("Name", "beta", + "Monitors", List.of(Map.of("AlarmArn", ALARM)))); + Environment before = service.getEnvironment(appId, created.getId()); + + service.updateEnvironment(appId, created.getId(), "gamma", "Second", null); + + assertEquals("beta", before.getName()); + assertEquals(List.of(new Monitor(ALARM, null)), before.getMonitors()); + Environment after = service.getEnvironment(appId, created.getId()); + assertEquals("gamma", after.getName()); + assertNull(after.getMonitors()); + assertEquals("READY", after.getState(), "an update keeps the environment's state"); + } + + @Test + void aProfileReadBeforeAnUpdateKeepsItsPriorName() { + String appId = service.createApplication(Map.of("Name", "orders")).getId(); + ConfigurationProfile created = service.createConfigurationProfile(appId, + Map.of("Name", "settings", "LocationUri", "hosted", "Type", "AWS.Freeform")); + ConfigurationProfile before = service.getConfigurationProfile(appId, created.getId()); + + service.updateConfigurationProfile(appId, created.getId(), "renamed", "Now described"); + + assertEquals("settings", before.getName()); + assertNull(before.getDescription()); + ConfigurationProfile after = service.getConfigurationProfile(appId, created.getId()); + assertEquals("renamed", after.getName()); + assertEquals("hosted", after.getLocationUri()); + assertEquals("AWS.Freeform", after.getType()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceUpdateRaceTest.java b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceUpdateRaceTest.java new file mode 100644 index 0000000000..4195b78ee2 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceUpdateRaceTest.java @@ -0,0 +1,146 @@ +package io.github.hectorvent.floci.services.appconfig; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.core.storage.WriteProfile; +import io.github.hectorvent.floci.services.appconfig.model.Application; +import io.github.hectorvent.floci.services.appconfig.model.ConfigurationProfile; +import io.github.hectorvent.floci.services.appconfig.model.DeploymentStrategy; +import io.github.hectorvent.floci.services.appconfig.model.Environment; +import io.github.hectorvent.floci.testing.ParkingStore; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The update methods CloudFormation uses read an entity, change it and write it back. A delete the + * AppConfig API runs on another thread in between must wait for the write and then remove the + * entity, not finish first and have the update store it again. Each case parks the update inside + * its write to the store and must see the delete waiting on the service. + */ +class AppConfigServiceUpdateRaceTest { + + private static final String ACCOUNT = "000000000000"; + private static final String APPLICATIONS = "appconfig-applications.json"; + private static final String ENVIRONMENTS = "appconfig-environments.json"; + private static final String PROFILES = "appconfig-profiles.json"; + private static final String STRATEGIES = "appconfig-strategies.json"; + + @Test + void anApplicationDeletedDuringItsUpdateStaysDeleted() throws Exception { + ParkingStore store = new ParkingStore<>(); + AppConfigService service = serviceWithStore(APPLICATIONS, store); + Application app = service.createApplication(Map.of("Name", "orders")); + + deleteWaitsForTheWrite(store, + () -> service.updateApplication(app.getId(), "orders-v2", null), + () -> service.deleteApplication(app.getId())); + + assertTrue(service.findApplication(app.getId()).isEmpty(), "the entity outlived its delete"); + } + + @Test + void aStrategyDeletedDuringItsUpdateStaysDeleted() throws Exception { + ParkingStore store = new ParkingStore<>(); + AppConfigService service = serviceWithStore(STRATEGIES, store); + DeploymentStrategy strategy = service.createDeploymentStrategy(Map.of("Name", "gradual", + "DeploymentDurationInMinutes", 0, "GrowthFactor", 100, "ReplicateTo", "NONE")); + + deleteWaitsForTheWrite(store, + () -> service.updateDeploymentStrategy(strategy.getId(), "slower", 1, 0, 50f, "LINEAR"), + () -> service.deleteDeploymentStrategy(strategy.getId())); + + assertTrue(service.listDeploymentStrategies().stream() + .noneMatch(listed -> listed.getId().equals(strategy.getId())), "the strategy outlived its delete"); + } + + @Test + void aProfileDeletedDuringItsUpdateStaysDeleted() throws Exception { + ParkingStore store = new ParkingStore<>(); + AppConfigService service = serviceWithStore(PROFILES, store); + Application app = service.createApplication(Map.of("Name", "orders")); + ConfigurationProfile profile = service.createConfigurationProfile(app.getId(), + Map.of("Name", "settings", "LocationUri", "hosted")); + + deleteWaitsForTheWrite(store, + () -> service.updateConfigurationProfile(app.getId(), profile.getId(), "renamed", null), + () -> service.deleteConfigurationProfile(app.getId(), profile.getId())); + + assertTrue(service.findConfigurationProfile(profile.getId()).isEmpty(), "the entity outlived its delete"); + } + + @Test + void anEnvironmentDeletedDuringItsUpdateStaysDeleted() throws Exception { + ParkingStore store = new ParkingStore<>(); + AppConfigService service = serviceWithStore(ENVIRONMENTS, store); + Application app = service.createApplication(Map.of("Name", "orders")); + Environment env = service.createEnvironment(app.getId(), Map.of("Name", "beta")); + + deleteWaitsForTheWrite(store, + () -> service.updateEnvironment(app.getId(), env.getId(), "gamma", null, List.of()), + () -> service.deleteEnvironment(app.getId(), env.getId())); + + assertTrue(service.findEnvironment(env.getId()).isEmpty(), "the entity outlived its delete"); + } + + /** + * Parks {@code write} in its next write to {@code store}, starts {@code delete}, and requires + * the delete to be unfinished and blocked on the service's monitor until the write is released; + * then both finish. + */ + private static void deleteWaitsForTheWrite(ParkingStore store, Runnable write, Runnable delete) + throws Exception { + store.parkNextWrite(); + ExecutorService pool = Executors.newFixedThreadPool(2); + try { + Future writing = pool.submit(write); + assertTrue(store.awaitParked(), "the write must reach the store"); + AtomicReference deleteThread = new AtomicReference<>(); + Future deleting = pool.submit(() -> { + deleteThread.set(Thread.currentThread()); + delete.run(); + }); + awaitBlockedOrDone(deleteThread, deleting); + assertFalse(deleting.isDone(), "the delete ran while a write of the same entity was mid-flight"); + assertEquals(Thread.State.BLOCKED, deleteThread.get().getState(), + "the delete waits on the service's monitor"); + + store.release(); + writing.get(2, TimeUnit.SECONDS); + deleting.get(2, TimeUnit.SECONDS); + } catch (ExecutionException e) { + throw new AssertionError(e.getCause()); + } finally { + store.release(); + pool.shutdownNow(); + } + } + + /** An AppConfig service whose {@code fileName} store is {@code store} and every other store in memory. */ + private static AppConfigService serviceWithStore(String fileName, StorageBackend store) { + return new AppConfigService(new StorageFactory(null, null) { + @Override + @SuppressWarnings("unchecked") + public AccountAwareStorageBackend create(String serviceName, String file, + TypeReference> typeReference, WriteProfile profile) { + return file.equals(fileName) + ? new AccountAwareStorageBackend<>((StorageBackend) (Object) store, null, ACCOUNT) + : AccountAwareStorageBackend.inMemory(ACCOUNT); + } + }, null); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java index c313e39abf..f51ffca346 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnCreateOnlyPropertiesTest.java @@ -94,6 +94,19 @@ class CfnCreateOnlyPropertiesTest { assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Comment")); } + @Test + void isCreateOnly_appConfigReplacesOnlyOnItsSchemaProperties() { + assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::Application", "Name")); + assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::Environment", "ApplicationId")); + assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::Environment", "Name")); + assertEquals(Set.of("ApplicationId", "LocationUri", "Type"), + CfnCreateOnlyProperties.getCreateOnlyProperties("AWS::AppConfig::ConfigurationProfile")); + assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::ConfigurationProfile", "Name")); + assertEquals(Set.of("Name", "ReplicateTo"), + CfnCreateOnlyProperties.getCreateOnlyProperties("AWS::AppConfig::DeploymentStrategy")); + assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::AppConfig::DeploymentStrategy", "GrowthFactor")); + } + @Test void isCreateOnly_treatsEmptySchemaListAsAuthoritative() { assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name")); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java index a2c275a1ce..480b3e7e2d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint; import io.github.hectorvent.floci.services.acm.AcmService; import io.github.hectorvent.floci.services.apigateway.ApiGatewayService; import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service; +import io.github.hectorvent.floci.services.appconfig.AppConfigService; import io.github.hectorvent.floci.services.applicationautoscaling.ApplicationAutoScalingService; import io.github.hectorvent.floci.services.appsync.AppSyncService; import io.github.hectorvent.floci.services.autoscaling.AutoScalingService; @@ -23,6 +24,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayUsagePlanCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2CfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2DomainCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.AppConfigCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.AppSyncCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.ApplicationAutoScalingCfnProvisioner; import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingGroupCfnProvisioner; @@ -205,6 +207,7 @@ final class CfnProvisionerFixture { private DynamoDbService dynamoDbService; private LambdaService lambdaService; private AppSyncService appSyncService; + private AppConfigService appConfigService; private IamService iamService; private SsmService ssmService; private KmsService kmsService; @@ -417,6 +420,9 @@ final class CfnProvisionerFixture { if (appSyncService != null) { discovered.add(new AppSyncCfnProvisioner(appSyncService)); } + if (appConfigService != null) { + discovered.add(new AppConfigCfnProvisioner(appConfigService)); + } if (lambdaService != null) { discovered.add(new LambdaAddressingCfnProvisioner(lambdaService)); discovered.add(new LambdaEventInvokeConfigCfnProvisioner(lambdaService)); @@ -564,6 +570,11 @@ final class CfnProvisionerFixture { return this; } + public Builder appConfig(AppConfigService v) { + this.appConfigService = v; + return this; + } + public Builder iam(IamService v) { this.iamService = v; return this; diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAppConfigIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAppConfigIntegrationTest.java new file mode 100644 index 0000000000..6d95472fb3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAppConfigIntegrationTest.java @@ -0,0 +1,343 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.testing.CfnStackWaits; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import io.restassured.path.json.JsonPath; +import io.restassured.path.xml.XmlPath; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static io.github.hectorvent.floci.testing.CfnRequests.cfn; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * {@code AWS::AppConfig::Application}, {@code Environment}, {@code ConfigurationProfile} and + * {@code DeploymentStrategy} through real stack operations, read back through the AppConfig API. + * {@code Ref} and the ID attribute of each are the AppConfig ID; an update changes mutable + * properties in place and replaces a profile whose {@code LocationUri} changes; a failed update puts + * the in-place changes back and deletes the replacement; and the stack delete removes everything, + * hosted configuration versions and deployments included. A failing operation ends in a Secrets + * Manager secret that cannot be created. + */ +@QuarkusTest +class CloudFormationAppConfigIntegrationTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String ALARM = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-errors"; + private static final List RESOURCES = List.of("App", "Env", "Profile", "Strategy"); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aStackCreatesTheFourTypesAndItsDeleteRemovesThemWithTheirVersionsAndDeployments() throws Exception { + String stack = unique("cfn-appconfig-create"); + Map resources = first(); + resources.put("Untyped", Map.of("Type", "AWS::AppConfig::ConfigurationProfile", "Properties", + Map.of("ApplicationId", ref("App"), "Name", "untyped", "LocationUri", "hosted"))); + deploy("CreateStack", stack, template(resources, false)); + assertStatus(stack, "CREATE_COMPLETE"); + + Map outputs = outputs(stack); + Map physicalIds = physicalIds(stack); + for (String resource : RESOURCES) { + assertEquals(outputs.get(resource + "Ref"), outputs.get(resource + "Id"), resource); + assertEquals(physicalIds.get(resource), outputs.get(resource + "Ref"), resource); + } + String app = outputs.get("AppRef"); + String env = outputs.get("EnvRef"); + String profile = outputs.get("ProfileRef"); + String strategy = outputs.get("StrategyRef"); + String envPath = "/applications/" + app + "/environments/" + env; + String profilePath = "/applications/" + app + "/configurationprofiles/" + profile; + + appconfig().get("/applications/" + app).then().statusCode(200) + .body("Name", equalTo("orders"), "Description", equalTo("Order service")); + assertEquals(Map.of("team", "payments", "tier", "gold"), applicationTags(app)); + appconfig().get(envPath).then().statusCode(200) + .body("Name", equalTo("beta"), "Monitors[0].AlarmArn", equalTo(ALARM)) + .body("Monitors[0]", not(hasKey("AlarmRoleArn"))); + appconfig().get(profilePath).then().statusCode(200) + .body("Name", equalTo("settings"), "LocationUri", equalTo("hosted"), "Type", equalTo("AWS.Freeform")); + appconfig().get("/applications/" + app + "/configurationprofiles/" + physicalIds.get("Untyped")) + .then().statusCode(200).body("Type", nullValue()); + appconfig().get("/deploymentstrategies/" + strategy).then().statusCode(200) + .body("Name", equalTo("gradual"), "DeploymentDurationInMinutes", equalTo(0), + "FinalBakeTimeInMinutes", equalTo(0), "GrowthFactor", equalTo(100f), + "GrowthType", equalTo("LINEAR"), "ReplicateTo", equalTo("NONE")); + + // The stack's resources work together: a hosted version deploys with the stack's strategy. + appconfig().body("{\"enabled\":true}").post(profilePath + "/hostedconfigurationversions") + .then().statusCode(201).header("Version-Number", equalTo("1")); + int deployment = appconfig().body(Map.of("ConfigurationProfileId", profile, "ConfigurationVersion", "1", + "DeploymentStrategyId", strategy)) + .post(envPath + "/deployments").then().statusCode(201) + .body("ConfigurationName", equalTo("settings"), "ConfigurationLocationUri", equalTo("hosted")) + .extract().path("DeploymentNumber"); + + deleteStack(stack); + appconfig().get(envPath + "/deployments/" + deployment).then().statusCode(404); + appconfig().get(envPath).then().statusCode(404); + appconfig().get(profilePath + "/hostedconfigurationversions/1").then().statusCode(404); + appconfig().get(profilePath).then().statusCode(404); + appconfig().get("/deploymentstrategies/" + strategy).then().statusCode(404); + appconfig().get("/applications/" + app).then().statusCode(404); + } + + @Test + void anUpdateChangesMutablePropertiesInPlaceAndReplacesAProfileWhoseLocationChanges() throws Exception { + String stack = unique("cfn-appconfig-update"); + deploy("CreateStack", stack, template(first(), false)); + assertStatus(stack, "CREATE_COMPLETE"); + Map before = outputs(stack); + + deploy("UpdateStack", stack, template(second(), false)); + assertStatus(stack, "UPDATE_COMPLETE"); + + Map after = outputs(stack); + String app = after.get("AppRef"); + for (String kept : List.of("App", "Env", "Strategy")) { + assertEquals(before.get(kept + "Ref"), after.get(kept + "Ref"), kept + " is changed in place"); + } + String oldProfile = before.get("ProfileRef"); + String newProfile = after.get("ProfileRef"); + assertNotEquals(oldProfile, newProfile, "a LocationUri change replaces the profile"); + assertEquals(newProfile, after.get("ProfileId")); + + appconfig().get("/applications/" + app).then().statusCode(200) + .body("Name", equalTo("orders-v2"), "Description", nullValue()); + assertEquals(Map.of("team", "billing", "owner", "ops"), applicationTags(app)); + appconfig().get("/applications/" + app + "/environments/" + after.get("EnvRef")).then().statusCode(200) + .body("Name", equalTo("gamma"), "Description", equalTo("Second stage")) + .body("$", not(hasKey("Monitors"))); + appconfig().get("/applications/" + app + "/configurationprofiles/" + newProfile).then().statusCode(200) + .body("Name", equalTo("settings"), "LocationUri", equalTo("ssm-parameter://orders-settings")); + appconfig().get("/applications/" + app + "/configurationprofiles/" + oldProfile).then().statusCode(404); + appconfig().get("/deploymentstrategies/" + after.get("StrategyRef")).then().statusCode(200) + .body("Description", equalTo("Ten minutes"), "DeploymentDurationInMinutes", equalTo(10), + "GrowthFactor", equalTo(20f), "GrowthType", equalTo("EXPONENTIAL")); + assertTrue(hasEvent(stack, "Profile", oldProfile, "DELETE_COMPLETE"), + "the update's cleanup reports the displaced profile deleted"); + + deleteStack(stack); + appconfig().get("/applications/" + app).then().statusCode(404); + } + + @Test + void aFailedUpdatePutsTheInPlaceChangesBackAndDeletesTheReplacement() throws Exception { + String stack = unique("cfn-appconfig-rollback"); + deploy("CreateStack", stack, template(first(), false)); + assertStatus(stack, "CREATE_COMPLETE"); + Map before = outputs(stack); + String app = before.get("AppRef"); + + deploy("UpdateStack", stack, template(second(), true)); + assertStatus(stack, "UPDATE_ROLLBACK_COMPLETE"); + + assertEquals(before, outputs(stack)); + appconfig().get("/applications/" + app).then().statusCode(200) + .body("Name", equalTo("orders"), "Description", equalTo("Order service")); + assertEquals(Map.of("team", "payments", "tier", "gold"), applicationTags(app)); + appconfig().get("/applications/" + app + "/environments/" + before.get("EnvRef")).then().statusCode(200) + .body("Name", equalTo("beta"), "Monitors[0].AlarmArn", equalTo(ALARM)); + List profiles = appconfig().get("/applications/" + app + "/configurationprofiles") + .then().statusCode(200).extract().jsonPath().getList("Items.Id", String.class); + assertEquals(List.of(before.get("ProfileRef")), profiles, "the replacement profile is deleted"); + appconfig().get("/deploymentstrategies/" + before.get("StrategyRef")).then().statusCode(200) + .body("Description", equalTo("Immediate"), "DeploymentDurationInMinutes", equalTo(0), + "GrowthFactor", equalTo(100f), "GrowthType", equalTo("LINEAR")); + + deleteStack(stack); + appconfig().get("/applications/" + app).then().statusCode(404); + } + + @Test + void aChangeSetReportsReplacementForCreateOnlyChangesOnly() throws Exception { + String stack = unique("cfn-appconfig-change-set"); + deploy("CreateStack", stack, template(first(), false)); + assertStatus(stack, "CREATE_COMPLETE"); + + Map renamed = first(); + properties(renamed, "App").put("Name", "orders-v2"); + properties(renamed, "Env").put("Name", "gamma"); + properties(renamed, "Profile").put("Name", "renamed"); + properties(renamed, "Strategy").put("GrowthFactor", 50); + assertEquals(Map.of("App", "False", "Env", "False", "Profile", "False", "Strategy", "False"), + replacements(stack, "renamed", template(renamed, false))); + + Map moved = first(); + properties(moved, "Profile").put("LocationUri", "ssm-parameter://orders-settings"); + properties(moved, "Strategy").put("Name", "immediate"); + assertEquals(Map.of("Profile", "True", "Strategy", "True"), + replacements(stack, "moved", template(moved, false))); + + deleteStack(stack); + } + + /** The first version of the four resources. */ + private static Map first() { + Map resources = new LinkedHashMap<>(); + resources.put("App", resource("Application", props("Name", "orders", "Description", "Order service", + "Tags", tags("team", "payments", "tier", "gold")))); + resources.put("Env", resource("Environment", props("ApplicationId", ref("App"), "Name", "beta", + "Monitors", List.of(Map.of("AlarmArn", ALARM))))); + resources.put("Profile", resource("ConfigurationProfile", props("ApplicationId", ref("App"), + "Name", "settings", "LocationUri", "hosted", "Type", "AWS.Freeform"))); + resources.put("Strategy", resource("DeploymentStrategy", props("Name", "gradual", "ReplicateTo", "NONE", + "DeploymentDurationInMinutes", 0, "FinalBakeTimeInMinutes", 0, "GrowthFactor", 100, + "Description", "Immediate"))); + return resources; + } + + /** + * The second version: the application renamed, its description dropped and its tags changed, + * the environment renamed with its monitors dropped, the profile moved to another location, and + * the strategy slowed down. + */ + private static Map second() { + Map resources = new LinkedHashMap<>(); + resources.put("App", resource("Application", props("Name", "orders-v2", + "Tags", tags("team", "billing", "owner", "ops")))); + resources.put("Env", resource("Environment", props("ApplicationId", ref("App"), "Name", "gamma", + "Description", "Second stage"))); + resources.put("Profile", resource("ConfigurationProfile", props("ApplicationId", ref("App"), + "Name", "settings", "LocationUri", "ssm-parameter://orders-settings", "Type", "AWS.Freeform"))); + resources.put("Strategy", resource("DeploymentStrategy", props("Name", "gradual", "ReplicateTo", "NONE", + "DeploymentDurationInMinutes", 10, "GrowthFactor", 20, "GrowthType", "EXPONENTIAL", + "Description", "Ten minutes"))); + return resources; + } + + private static String template(Map resources, boolean failAfter) throws JsonProcessingException { + Map all = new LinkedHashMap<>(resources); + if (failAfter) { + all.put("Failure", Map.of("Type", "AWS::SecretsManager::Secret", "DependsOn", RESOURCES, + "Properties", Map.of("SecretString", "explicit", + "GenerateSecretString", Map.of("PasswordLength", 32)))); + } + Map outputs = new LinkedHashMap<>(); + Map idAttributes = Map.of("App", "ApplicationId", "Env", "EnvironmentId", + "Profile", "ConfigurationProfileId", "Strategy", "Id"); + for (String resource : RESOURCES) { + outputs.put(resource + "Ref", Map.of("Value", ref(resource))); + outputs.put(resource + "Id", Map.of("Value", + Map.of("Fn::GetAtt", List.of(resource, idAttributes.get(resource))))); + } + return MAPPER.writeValueAsString(Map.of("Resources", all, "Outputs", outputs)); + } + + private static Map resource(String type, Map properties) { + Map resource = new LinkedHashMap<>(); + resource.put("Type", "AWS::AppConfig::" + type); + resource.put("Properties", properties); + return resource; + } + + @SuppressWarnings("unchecked") + private static Map properties(Map resources, String logicalId) { + return (Map) ((Map) resources.get(logicalId)).get("Properties"); + } + + /** Alternating property names and values, in order, in a map a test can change. */ + private static Map props(Object... namesAndValues) { + Map properties = new LinkedHashMap<>(); + for (int i = 0; i < namesAndValues.length; i += 2) { + properties.put((String) namesAndValues[i], namesAndValues[i + 1]); + } + return properties; + } + + private static List> tags(String... keysAndValues) { + List> tags = new ArrayList<>(); + for (int i = 0; i < keysAndValues.length; i += 2) { + tags.add(Map.of("Key", keysAndValues[i], "Value", keysAndValues[i + 1])); + } + return tags; + } + + private static Map ref(String logicalId) { + return Map.of("Ref", logicalId); + } + + private static String unique(String prefix) { + return prefix + "-" + Long.toString(System.nanoTime(), 36); + } + + private static void deploy(String action, String stack, String template) { + cfn(action, stack).formParam("TemplateBody", template).post("/").then().statusCode(200); + } + + private static void assertStatus(String stack, String expected) { + CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack); + assertEquals(expected, state.status(), state.reason()); + } + + private static void deleteStack(String stack) { + cfn("DeleteStack", stack).post("/").then().statusCode(200); + CfnStackWaits.awaitStackDeleted(stack); + } + + private static Map outputs(String stack) { + String body = cfn("DescribeStacks", stack).post("/").then().statusCode(200).extract().asString(); + return XmlParser.extractPairs(body, "Outputs", "OutputKey", "OutputValue"); + } + + private static Map physicalIds(String stack) { + String body = cfn("DescribeStackResources", stack).post("/").then().statusCode(200).extract().asString(); + return XmlParser.extractPairs(body, "StackResources", "LogicalResourceId", "PhysicalResourceId"); + } + + private static boolean hasEvent(String stack, String logicalId, String physicalId, String status) { + String body = cfn("DescribeStackEvents", stack).post("/").then().statusCode(200).extract().asString(); + return XmlParser.extractGroups(body, "member").stream() + .anyMatch(event -> logicalId.equals(event.get("LogicalResourceId")) + && physicalId.equals(event.get("PhysicalResourceId")) + && status.equals(event.get("ResourceStatus"))); + } + + /** The {@code Replacement} a change set to {@code template} reports, by logical id. */ + private static Map replacements(String stack, String changeSet, String template) { + cfn("CreateChangeSet", stack).formParam("ChangeSetName", changeSet).formParam("ChangeSetType", "UPDATE") + .formParam("TemplateBody", template).post("/").then().statusCode(200); + XmlPath body = cfn("DescribeChangeSet", stack).formParam("ChangeSetName", changeSet).post("/") + .then().statusCode(200).extract().xmlPath(); + List logicalIds = body.getList( + "**.findAll { it.name() == 'ResourceChange' }.LogicalResourceId", String.class); + List values = body.getList("**.findAll { it.name() == 'ResourceChange' }.Replacement", String.class); + Map replacements = new LinkedHashMap<>(); + for (int i = 0; i < logicalIds.size(); i++) { + replacements.put(logicalIds.get(i), values.get(i)); + } + return replacements; + } + + private static RequestSpecification appconfig() { + return given().contentType(ContentType.JSON); + } + + private static Map applicationTags(String applicationId) { + JsonPath body = appconfig().get("/tags/arn:aws:appconfig:us-east-1:000000000000:application/" + applicationId) + .then().statusCode(200).extract().jsonPath(); + return body.getMap("Tags", String.class, String.class); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAppConfigLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAppConfigLifecycleTest.java new file mode 100644 index 0000000000..4681c870ae --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAppConfigLifecycleTest.java @@ -0,0 +1,199 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.services.appconfig.AppConfigService; +import io.github.hectorvent.floci.services.appconfig.model.Application; +import io.github.hectorvent.floci.services.appconfig.model.Deployment; +import io.github.hectorvent.floci.services.appconfig.model.DeploymentSummary; +import io.github.hectorvent.floci.services.appconfig.model.HostedConfigurationVersion; +import io.github.hectorvent.floci.services.cloudformation.model.Stack; +import io.github.hectorvent.floci.services.cloudformation.provisioners.AppConfigCfnProvisioner; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnDynamicReferences; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnResourceDispatcher; +import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.ssm.SsmService; +import io.github.hectorvent.floci.testing.InMemoryStorageFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +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.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doCallRealMethod; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +/** + * AppConfig resources through the real stack engine, for the paths that need it: the order the + * engine deletes a removed application and its displaced children in, a ContinueUpdateRollback + * after an in-place undo that failed, and what earlier deployments report once stack updates change + * or replace the strategy and profile they used. The AppConfig service runs on in-memory storage, whose stores + * the test also reads directly to see what the API can no longer reach. + */ +class CloudFormationAppConfigLifecycleTest { + + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private InMemoryStorageFactory storage; + private AppConfigService appConfig; + private CloudFormationService cfn; + private int changeSets; + + @BeforeEach + void setUp() { + storage = new InMemoryStorageFactory(ACCOUNT); + appConfig = spy(new AppConfigService(storage, null)); + CfnResourceDispatcher dispatcher = new CfnResourceDispatcher(MAPPER, + new CloudFormationResourceRegistry(List.of(new AppConfigCfnProvisioner(appConfig))), null, null); + RegionResolver regionResolver = mock(RegionResolver.class); + when(regionResolver.getAccountId()).thenReturn(ACCOUNT); + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.defaultAccountId()).thenReturn(ACCOUNT); + cfn = new CloudFormationService(dispatcher, mock(S3Service.class), mock(SsmService.class), + mock(GetStackOutputRoleAuthorizer.class), new CfnDynamicReferences(null, null, MAPPER), MAPPER, + config, regionResolver, Clock.systemUTC(), new InMemoryStorageFactory(ACCOUNT)); + } + + /** + * Renaming the application's logical id replaces the environment and profile that refer to it. + * The engine deletes the removed application before the displaced children, so their deletes + * must not depend on finding it. + */ + @Test + void childrenMovedToANewApplicationAreDeletedAfterTheOldApplicationIsRemoved() throws Exception { + String children = """ + "Env":{"Type":"AWS::AppConfig::Environment","Properties":{"ApplicationId":{"Ref":"%1$s"},"Name":"beta"}}, + "Profile":{"Type":"AWS::AppConfig::ConfigurationProfile","Properties":{ + "ApplicationId":{"Ref":"%1$s"},"Name":"settings","LocationUri":"hosted"}}"""; + deploy("moved", "CREATE", "{\"Resources\":{\"AppA\":{\"Type\":\"AWS::AppConfig::Application\"," + + "\"Properties\":{\"Name\":\"orders\"}}," + children.formatted("AppA") + "}}"); + Stack stack = stack("moved"); + String oldApp = stack.getResources().get("AppA").getPhysicalId(); + String oldEnv = stack.getResources().get("Env").getPhysicalId(); + String oldProfile = stack.getResources().get("Profile").getPhysicalId(); + appConfig.createHostedConfigurationVersion(oldApp, oldProfile, "{}".getBytes(StandardCharsets.UTF_8), + "application/json", null); + appConfig.startDeployment(oldApp, oldEnv, Map.of("ConfigurationProfileId", oldProfile, + "ConfigurationVersion", "1", "DeploymentStrategyId", "AppConfig.AllAtOnce")); + + deploy("moved", "UPDATE", "{\"Resources\":{\"AppB\":{\"Type\":\"AWS::AppConfig::Application\"," + + "\"Properties\":{\"Name\":\"orders\"}}," + children.formatted("AppB") + "}}"); + + stack = stack("moved"); + assertEquals("UPDATE_COMPLETE", stack.getStatus(), stack.getStatusReason()); + assertNotEquals(oldEnv, stack.getResources().get("Env").getPhysicalId()); + assertTrue(appConfig.listApplications().stream().noneMatch(app -> app.getId().equals(oldApp))); + assertTrue(appConfig.findEnvironment(oldEnv).isEmpty(), "the displaced environment is deleted"); + assertTrue(appConfig.findConfigurationProfile(oldProfile).isEmpty(), "the displaced profile is deleted"); + assertTrue(store("appconfig-deployments.json", new TypeReference>() {}) + .scan(key -> key.startsWith(oldApp + "::")).isEmpty(), "with its deployments"); + assertTrue(store("appconfig-versions.json", new TypeReference>() {}) + .scan(key -> key.startsWith(oldApp + "::")).isEmpty(), "and its hosted configuration versions"); + } + + /** + * An in-place update whose undo fails ends the stack in UPDATE_ROLLBACK_FAILED. The + * ContinueUpdateRollback that follows must put back the state the update started from, the + * last committed one, not an older state an earlier committed update had replaced. + */ + @Test + void continueUpdateRollbackAfterAFailedUndoRestoresTheLastCommittedState() throws Exception { + String template = "{\"Resources\":{\"App\":{\"Type\":\"AWS::AppConfig::Application\",\"Properties\":" + + "{\"Name\":\"%s\",\"Tags\":[{\"Key\":\"stage\",\"Value\":\"%s\"}]}}}}"; + deploy("retried", "CREATE", template.formatted("first", "1")); + String app = stack("retried").getResources().get("App").getPhysicalId(); + deploy("retried", "UPDATE", template.formatted("second", "2")); + assertEquals("UPDATE_COMPLETE", stack("retried").getStatus()); + + doThrow(new AwsException("InternalServerException", "tag store down", 500)) + .when(appConfig).setApplicationTags(anyString(), any()); + deploy("retried", "UPDATE", template.formatted("third", "3")); + assertEquals("UPDATE_ROLLBACK_FAILED", stack("retried").getStatus()); + + doCallRealMethod().when(appConfig).setApplicationTags(anyString(), any()); + cfn.continueUpdateRollback("retried", List.of(), false, REGION).get(30, TimeUnit.SECONDS); + + assertEquals("UPDATE_ROLLBACK_COMPLETE", stack("retried").getStatus(), stack("retried").getStatusReason()); + Application restored = appConfig.getApplication(app); + assertEquals("second", restored.getName()); + assertEquals(Map.of("stage", "2"), restored.getTags()); + } + + /** + * A deployment reports the profile name and strategy settings it started with: an in-place stack + * update that renames the profile and slows the strategy leaves it as it was, and so does a + * replacement that deletes the strategy, after which ListDeployments still answers. + */ + @Test + void earlierDeploymentsKeepTheirSettingsThroughInPlaceUpdatesAndAStrategyReplacement() throws Exception { + String template = """ + {"Resources":{ + "App":{"Type":"AWS::AppConfig::Application","Properties":{"Name":"orders"}}, + "Env":{"Type":"AWS::AppConfig::Environment","Properties":{"ApplicationId":{"Ref":"App"},"Name":"beta"}}, + "Profile":{"Type":"AWS::AppConfig::ConfigurationProfile","Properties":{ + "ApplicationId":{"Ref":"App"},"Name":"%s","LocationUri":"hosted"}}, + "Strategy":{"Type":"AWS::AppConfig::DeploymentStrategy","Properties":{ + "Name":"%s","ReplicateTo":"NONE","DeploymentDurationInMinutes":%d,"GrowthFactor":%d}} + }}"""; + deploy("history", "CREATE", template.formatted("settings", "gradual", 0, 100)); + Stack stack = stack("history"); + String app = stack.getResources().get("App").getPhysicalId(); + String env = stack.getResources().get("Env").getPhysicalId(); + String profile = stack.getResources().get("Profile").getPhysicalId(); + String strategy = stack.getResources().get("Strategy").getPhysicalId(); + appConfig.createHostedConfigurationVersion(app, profile, "{}".getBytes(StandardCharsets.UTF_8), + "application/json", null); + appConfig.startDeployment(app, env, Map.of("ConfigurationProfileId", profile, "ConfigurationVersion", "1", + "DeploymentStrategyId", strategy)); + + deploy("history", "UPDATE", template.formatted("renamed", "gradual", 10, 20)); + assertEquals("UPDATE_COMPLETE", stack("history").getStatus(), stack("history").getStatusReason()); + assertEquals(strategy, stack("history").getResources().get("Strategy").getPhysicalId(), "changed in place"); + assertStartedWith(app, env); + + deploy("history", "UPDATE", template.formatted("renamed", "faster", 10, 20)); + assertEquals("UPDATE_COMPLETE", stack("history").getStatus(), stack("history").getStatusReason()); + assertNotEquals(strategy, stack("history").getResources().get("Strategy").getPhysicalId(), "replaced"); + assertStartedWith(app, env); + } + + private void assertStartedWith(String app, String env) { + DeploymentSummary deployment = appConfig.listDeployments(app, env, null, null).items().getFirst(); + assertEquals("settings", deployment.getConfigurationName()); + assertEquals(0, deployment.getDeploymentDurationInMinutes()); + assertEquals(100f, deployment.getGrowthFactor()); + } + + private StorageBackend store(String fileName, TypeReference> type) { + return storage.create("appconfig", fileName, type); + } + + private void deploy(String name, String type, String template) throws Exception { + String changeSet = "change-" + (++changeSets); + cfn.createChangeSet(name, changeSet, type, template, null, Map.of(), List.of(), Map.of(), REGION, ACCOUNT); + cfn.executeChangeSet(name, changeSet, REGION, ACCOUNT).get(30, TimeUnit.SECONDS); + } + + private Stack stack(String name) { + return cfn.describeStacks(name, REGION, ACCOUNT).getFirst(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppConfigCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppConfigCfnProvisionerTest.java new file mode 100644 index 0000000000..bdf8437623 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AppConfigCfnProvisionerTest.java @@ -0,0 +1,669 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.appconfig.AppConfigService; +import io.github.hectorvent.floci.services.appconfig.model.Application; +import io.github.hectorvent.floci.services.appconfig.model.ConfigurationProfile; +import io.github.hectorvent.floci.services.appconfig.model.Deployment; +import io.github.hectorvent.floci.services.appconfig.model.DeploymentStrategy; +import io.github.hectorvent.floci.services.appconfig.model.Environment; +import io.github.hectorvent.floci.services.appconfig.model.HostedConfigurationVersion; +import io.github.hectorvent.floci.services.appconfig.model.Monitor; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +import io.github.hectorvent.floci.services.cloudformation.model.StackResource; +import io.github.hectorvent.floci.testing.InMemoryStorageFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.LinkedHashMap; +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.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +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.Mockito.doAnswer; +import static org.mockito.Mockito.doCallRealMethod; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +/** + * {@code AWS::AppConfig::*} against a real AppConfig service on in-memory storage: the physical id + * is the AppConfig ID and the ID attribute, mutable properties change in place and roll back from + * the snapshot, a create-only change replaces the entity, and deletes go by exact ID. + */ +class AppConfigCfnProvisionerTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final String STACK = "configuration"; + private static final String APPLICATION = "AWS::AppConfig::Application"; + private static final String ENVIRONMENT = "AWS::AppConfig::Environment"; + private static final String PROFILE = "AWS::AppConfig::ConfigurationProfile"; + private static final String STRATEGY = "AWS::AppConfig::DeploymentStrategy"; + private static final String ALARM = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-errors"; + private static final String ALARM_ROLE = "arn:aws:iam::000000000000:role/appconfig-monitor"; + + private InMemoryStorageFactory storage; + private AppConfigService service; + private AppConfigCfnProvisioner provisioner; + private CloudFormationTemplateEngine engine; + + @BeforeEach + void setUp() { + storage = new InMemoryStorageFactory(ACCOUNT); + service = spy(new AppConfigService(storage, null)); + provisioner = new AppConfigCfnProvisioner(service); + engine = CloudFormationTemplateEngine.standalone(ACCOUNT, REGION, STACK, MAPPER, value -> value); + } + + @Test + void anApplicationIsCreatedWithItsTagsAndItsIdIsTheRefAndTheAttribute() { + StackResource app = create(APPLICATION, props("Name", "orders", "Description", "Order service", + "Tags", List.of(tag("team", "payments")))); + + Application stored = service.getApplication(app.getPhysicalId()); + assertEquals(app.getPhysicalId(), app.getAttributes().get("ApplicationId")); + assertEquals("orders", stored.getName()); + assertEquals("Order service", stored.getDescription()); + assertEquals(Map.of("team", "payments"), stored.getTags()); + } + + @Test + void anApplicationUpdateChangesItInPlaceAndARollbackPutsItBack() { + StackResource app = create(APPLICATION, props("Name", "orders", "Description", "Order service", + "Tags", List.of(tag("team", "payments"), tag("tier", "gold")))); + String id = app.getPhysicalId(); + + update(app, props("Name", "orders-v2", "Tags", List.of(tag("team", "billing"), tag("owner", "ops")))); + + assertEquals(id, app.getPhysicalId()); + Application updated = service.getApplication(id); + assertEquals("orders-v2", updated.getName()); + assertNull(updated.getDescription(), "a Description the template drops is cleared"); + assertEquals(Map.of("team", "billing", "owner", "ops"), updated.getTags(), "tags follow the template"); + + assertTrue(provisioner.rollbackUpdate(app)); + Application restored = service.getApplication(id); + assertEquals("orders", restored.getName()); + assertEquals("Order service", restored.getDescription()); + assertEquals(Map.of("team", "payments", "tier", "gold"), restored.getTags()); + assertFalse(app.getAttributes().containsKey(CfnRollback.APPCONFIG_UPDATE_SNAPSHOT_ATTR)); + } + + @Test + void aCreateWhoseTaggingFailsDeletesTheApplication() { + doThrow(new AwsException("InternalServerException", "tagging failed", 500)) + .when(service).setApplicationTags(anyString(), any()); + StackResource app = resource(APPLICATION); + + AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(app, + MAPPER.valueToTree(props("Name", "orders", "Tags", List.of(tag("team", "payments")))), context(null))); + + assertEquals("tagging failed", failure.getMessage()); + assertTrue(service.listApplications().isEmpty(), "the application the failed create made is deleted"); + assertFalse(app.getAttributes().containsKey(CfnRollback.ROLLBACK_OWNED_ATTR)); + } + + @Test + void anUpdateWhoseTaggingFailsPutsTheNameBack() { + StackResource app = create(APPLICATION, props("Name", "orders", "Tags", List.of(tag("team", "payments")))); + // Only the update's own tag call fails; the undo's succeeds. + doThrow(new AwsException("InternalServerException", "tagging failed", 500)).doCallRealMethod() + .when(service).setApplicationTags(anyString(), any()); + + assertThrows(AwsException.class, () -> update(app, props("Name", "orders-v2", + "Tags", List.of(tag("team", "billing"))))); + + Application restored = service.getApplication(app.getPhysicalId()); + assertEquals("orders", restored.getName()); + assertEquals(Map.of("team", "payments"), restored.getTags()); + assertFalse(app.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR), + "the undo completed, so the stack can report the prior application intact"); + } + + @Test + void anUndoThatFailsTooIsRecordedForTheRollback() { + StackResource app = create(APPLICATION, props("Name", "orders", "Tags", List.of(tag("team", "payments")))); + doThrow(new AwsException("InternalServerException", "tagging failed", 500)) + .when(service).setApplicationTags(anyString(), any()); + + AwsException failure = assertThrows(AwsException.class, () -> update(app, props("Name", "orders-v2", + "Tags", List.of(tag("team", "billing"))))); + + assertEquals("tagging failed", failure.getMessage(), "the stack reports the update's own failure"); + assertTrue(app.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR) + .startsWith("Could not restore " + app.getPhysicalId())); + } + + /** + * The engine puts the previous resource back over an attempt whose undo failed; that resource + * then carries the attempt's snapshot, the state the update started from, in place of the one an + * earlier committed update left on it, so a ContinueUpdateRollback restores the right state. + */ + @Test + void anUndoThatFailedLeavesItsSnapshotOnTheRestoredResource() { + StackResource app = create(APPLICATION, props("Name", "first", "Tags", List.of(tag("stage", "1")))); + update(app, props("Name", "second", "Tags", List.of(tag("stage", "2")))); + StackResource committed = copy(app); + StackResource attempt = copy(committed); + doThrow(new AwsException("InternalServerException", "tagging failed", 500)) + .when(service).setApplicationTags(anyString(), any()); + assertThrows(AwsException.class, () -> update(attempt, props("Name", "third", + "Tags", List.of(tag("stage", "3"))))); + + provisioner.mergeFailedUpdateResourceTracking(committed, attempt); + doCallRealMethod().when(service).setApplicationTags(anyString(), any()); + assertTrue(provisioner.rollbackUpdate(committed)); + + Application restored = service.getApplication(app.getPhysicalId()); + assertEquals("second", restored.getName()); + assertEquals(Map.of("stage", "2"), restored.getTags()); + } + + @Test + void anUndoThatCompletedLeavesTheRestoredResourceAlone() { + StackResource app = create(APPLICATION, props("Name", "first")); + StackResource committed = copy(app); + StackResource attempt = copy(committed); + update(attempt, props("Name", "second")); + + provisioner.mergeFailedUpdateResourceTracking(committed, attempt); + + assertEquals(app.getAttributes(), committed.getAttributes()); + } + + @Test + void anEnvironmentKeepsItsMonitorsAndChangesInPlace() { + String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + StackResource env = create(ENVIRONMENT, props("ApplicationId", appId, "Name", "beta", + "Monitors", List.of(Map.of("AlarmArn", ALARM, "AlarmRoleArn", ALARM_ROLE)))); + String id = env.getPhysicalId(); + assertEquals(id, env.getAttributes().get("EnvironmentId")); + assertEquals(List.of(new Monitor(ALARM, ALARM_ROLE)), service.getEnvironment(appId, id).getMonitors()); + + update(env, props("ApplicationId", appId, "Name", "gamma", "Description", "Second stage")); + + assertEquals(id, env.getPhysicalId()); + Environment updated = service.getEnvironment(appId, id); + assertEquals("gamma", updated.getName()); + assertEquals("Second stage", updated.getDescription()); + assertNull(updated.getMonitors(), "Monitors the template drops are cleared"); + + provisioner.rollbackUpdate(env); + Environment restored = service.getEnvironment(appId, id); + assertEquals("beta", restored.getName()); + assertNull(restored.getDescription()); + assertEquals(List.of(new Monitor(ALARM, ALARM_ROLE)), restored.getMonitors()); + } + + @Test + void invalidMonitorsAreRefusedBeforeTheEnvironmentChanges() { + String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + StackResource env = create(ENVIRONMENT, props("ApplicationId", appId, "Name", "beta")); + + AwsException failure = assertThrows(AwsException.class, () -> update(env, props("ApplicationId", appId, + "Name", "gamma", "Monitors", List.of(Map.of("AlarmArn", ALARM, "AlarmRoleArn", "not-a-role"))))); + + assertEquals("BadRequestException", failure.getErrorCode()); + assertEquals("beta", service.getEnvironment(appId, env.getPhysicalId()).getName()); + } + + @Test + void movingAnEnvironmentToAnotherApplicationReplacesItAndTheCommittedUpdateDeletesTheOldOne() { + String first = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + String second = create(APPLICATION, props("Name", "billing")).getPhysicalId(); + StackResource env = create(ENVIRONMENT, props("ApplicationId", first, "Name", "beta")); + String oldId = env.getPhysicalId(); + + update(env, props("ApplicationId", second, "Name", "beta")); + + String newId = env.getPhysicalId(); + assertNotEquals(oldId, newId); + assertEquals(second, service.getEnvironment(second, newId).getApplicationId()); + assertTrue(provisioner.hasReplacementUpdate(env)); + assertEquals(oldId, provisioner.updateCleanupPhysicalId(env)); + assertTrue(service.findEnvironment(oldId).isPresent(), "the displaced environment stays until the update commits"); + + assertTrue(provisioner.completeUpdate(env).complete()); + assertTrue(service.findEnvironment(oldId).isEmpty()); + provisioner.clearUpdate(env); + assertFalse(provisioner.hasReplacementUpdate(env)); + } + + @Test + void aRolledBackReplacementDeletesTheNewProfileAndNamesThePriorOneAgain() { + String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + StackResource profile = create(PROFILE, props("ApplicationId", appId, "Name", "settings", + "LocationUri", "hosted", "Type", "AWS.Freeform")); + String oldId = profile.getPhysicalId(); + Map before = Map.copyOf(profile.getAttributes()); + + update(profile, props("ApplicationId", appId, "Name", "settings", "LocationUri", "ssm-parameter://settings", + "Type", "AWS.Freeform")); + String newId = profile.getPhysicalId(); + assertNotEquals(oldId, newId); + assertEquals("ssm-parameter://settings", service.getConfigurationProfile(appId, newId).getLocationUri()); + + assertTrue(provisioner.rollbackUpdate(profile)); + + assertEquals(oldId, profile.getPhysicalId()); + assertEquals(before, profile.getAttributes(), "the prior profile's ID and create-only values are back"); + assertTrue(service.findConfigurationProfile(newId).isEmpty(), "the replacement is deleted"); + assertEquals("hosted", service.getConfigurationProfile(appId, oldId).getLocationUri()); + } + + @Test + void aProfileWithoutTypeHasNoneAndAddingOneReplacesIt() { + String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + StackResource profile = create(PROFILE, props("ApplicationId", appId, "Name", "settings", + "LocationUri", "hosted")); + String oldId = profile.getPhysicalId(); + assertEquals(oldId, profile.getAttributes().get("ConfigurationProfileId")); + assertNull(service.getConfigurationProfile(appId, oldId).getType()); + + update(profile, props("ApplicationId", appId, "Name", "flags", "LocationUri", "hosted", + "Type", "AWS.AppConfig.FeatureFlags")); + + assertNotEquals(oldId, profile.getPhysicalId()); + ConfigurationProfile replacement = service.getConfigurationProfile(appId, profile.getPhysicalId()); + assertEquals("AWS.AppConfig.FeatureFlags", replacement.getType()); + assertEquals("flags", replacement.getName()); + } + + @Test + void aProfileNameAndDescriptionChangeInPlace() { + String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + StackResource profile = create(PROFILE, props("ApplicationId", appId, "Name", "settings", + "LocationUri", "hosted", "Description", "First")); + String id = profile.getPhysicalId(); + + update(profile, props("ApplicationId", appId, "Name", "renamed", "LocationUri", "hosted")); + + assertEquals(id, profile.getPhysicalId()); + assertFalse(provisioner.hasReplacementUpdate(profile)); + ConfigurationProfile updated = service.getConfigurationProfile(appId, id); + assertEquals("renamed", updated.getName()); + assertNull(updated.getDescription()); + provisioner.rollbackUpdate(profile); + assertEquals("settings", service.getConfigurationProfile(appId, id).getName()); + assertEquals("First", service.getConfigurationProfile(appId, id).getDescription()); + } + + @Test + void aStrategyChangesInPlaceAndPropertiesTheTemplateDropsGoBackToTheirDefaults() { + StackResource strategy = create(STRATEGY, props("Name", "gradual", "ReplicateTo", "NONE", + "DeploymentDurationInMinutes", 10, "FinalBakeTimeInMinutes", 5, "GrowthFactor", 25, + "GrowthType", "EXPONENTIAL", "Description", "Slow")); + String id = strategy.getPhysicalId(); + assertEquals(id, strategy.getAttributes().get("Id")); + + update(strategy, props("Name", "gradual", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", "20", + "GrowthFactor", 12.5)); + + assertEquals(id, strategy.getPhysicalId()); + DeploymentStrategy updated = service.getDeploymentStrategy(id); + assertEquals(20, updated.getDeploymentDurationInMinutes(), "a parameter supplies a number as a string"); + assertEquals(0, updated.getFinalBakeTimeInMinutes()); + assertEquals(12.5f, updated.getGrowthFactor()); + assertEquals("LINEAR", updated.getGrowthType()); + assertNull(updated.getDescription()); + + provisioner.rollbackUpdate(strategy); + DeploymentStrategy restored = service.getDeploymentStrategy(id); + assertEquals(10, restored.getDeploymentDurationInMinutes()); + assertEquals(5, restored.getFinalBakeTimeInMinutes()); + assertEquals(25f, restored.getGrowthFactor()); + assertEquals("EXPONENTIAL", restored.getGrowthType()); + assertEquals("Slow", restored.getDescription()); + } + + @Test + void renamingAStrategyReplacesIt() { + StackResource strategy = create(STRATEGY, props("Name", "gradual", "ReplicateTo", "NONE", + "DeploymentDurationInMinutes", 0, "GrowthFactor", 100)); + String oldId = strategy.getPhysicalId(); + + update(strategy, props("Name", "immediate", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 0, + "GrowthFactor", 100)); + + assertNotEquals(oldId, strategy.getPhysicalId()); + assertEquals("immediate", service.getDeploymentStrategy(strategy.getPhysicalId()).getName()); + assertEquals(oldId, provisioner.updateCleanupPhysicalId(strategy)); + provisioner.completeUpdate(strategy); + assertThrows(AwsException.class, () -> service.getDeploymentStrategy(oldId)); + } + + @Test + void invalidStrategyNumbersAndEnumsAreRefusedBeforeAnythingIsCreated() { + List> invalid = List.of( + props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1.5, "GrowthFactor", 10), + props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", -1, "GrowthFactor", 10), + props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1441, "GrowthFactor", 10), + props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", "soon", "GrowthFactor", 10), + props("Name", "s", "ReplicateTo", "NONE", "GrowthFactor", 10), + props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1, + "FinalBakeTimeInMinutes", 2000, "GrowthFactor", 10), + props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1, "GrowthFactor", 0.5), + props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1, "GrowthFactor", 101), + props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1), + props("Name", "s", "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1, "GrowthFactor", 10, + "GrowthType", "QUADRATIC"), + props("Name", "s", "ReplicateTo", "S3", "DeploymentDurationInMinutes", 1, "GrowthFactor", 10), + props("Name", "s", "DeploymentDurationInMinutes", 1, "GrowthFactor", 10), + props("ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1, "GrowthFactor", 10), + props("Name", "s".repeat(65), "ReplicateTo", "NONE", "DeploymentDurationInMinutes", 1, + "GrowthFactor", 10)); + for (Map properties : invalid) { + AwsException failure = assertThrows(AwsException.class, + () -> provisioner.provision(resource(STRATEGY), MAPPER.valueToTree(properties), context(null)), + properties.toString()); + assertEquals("ValidationError", failure.getErrorCode(), properties.toString()); + } + verify(service, never()).createDeploymentStrategy(any()); + } + + @Test + void requiredPropertiesAndLimitsAreCheckedBeforeAnythingIsCreated() { + String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + Map> invalid = new LinkedHashMap<>(); + invalid.put(APPLICATION, props("Description", "no name")); + invalid.put(APPLICATION + " long name", props("Name", "a".repeat(65))); + invalid.put(APPLICATION + " long description", props("Name", "orders", "Description", "d".repeat(1025))); + invalid.put(ENVIRONMENT, props("Name", "beta")); + invalid.put(ENVIRONMENT + " no name", props("ApplicationId", appId)); + invalid.put(ENVIRONMENT + " deletion protection", props("ApplicationId", appId, "Name", "beta", + "DeletionProtectionCheck", "SOMETIMES")); + invalid.put(PROFILE, props("ApplicationId", appId, "Name", "settings")); + invalid.put(PROFILE + " long name", props("ApplicationId", appId, "Name", "p".repeat(129), + "LocationUri", "hosted")); + invalid.put(PROFILE + " no application", props("Name", "settings", "LocationUri", "hosted")); + for (Map.Entry> entry : invalid.entrySet()) { + String type = entry.getKey().split(" ")[0]; + AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(resource(type), + MAPPER.valueToTree(entry.getValue()), context(null)), entry.getKey()); + assertEquals("ValidationError", failure.getErrorCode(), entry.getKey()); + } + assertEquals(1, service.listApplications().size()); + assertTrue(service.listEnvironments(appId).isEmpty()); + assertTrue(service.listConfigurationProfiles(appId).isEmpty()); + } + + @Test + void noValueLeavesAnOptionalPropertyOut() { + StackResource app = create(APPLICATION, props("Name", "orders", + "Description", Map.of("Ref", "AWS::NoValue"))); + + assertNull(service.getApplication(app.getPhysicalId()).getDescription()); + } + + @Test + void aStubFromBeforeTheProvisionerIsReplacedByARealEntityAndARollbackPutsTheStubBack() { + StackResource app = resource(APPLICATION); + String stubId = "App-0a1b2c3d"; + app.setPhysicalId(stubId); + app.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + "App"); + + provisioner.provision(app, MAPPER.valueToTree(props("Name", "orders")), context(stubId)); + + String created = app.getPhysicalId(); + assertNotEquals(stubId, created); + assertEquals("orders", service.getApplication(created).getName()); + assertTrue(provisioner.rollbackUpdate(app)); + assertEquals(stubId, app.getPhysicalId()); + assertTrue(service.listApplications().isEmpty(), "the rollback deletes what the migration created"); + } + + @Test + void deletesGoByExactIdAndCountAnEntityAlreadyGoneAsDeleted() { + StackResource app = create(APPLICATION, props("Name", "orders")); + StackResource env = create(ENVIRONMENT, props("ApplicationId", app.getPhysicalId(), "Name", "beta")); + StackResource profile = create(PROFILE, props("ApplicationId", app.getPhysicalId(), "Name", "settings", + "LocationUri", "hosted")); + StackResource strategy = create(STRATEGY, props("Name", "now", "ReplicateTo", "NONE", + "DeploymentDurationInMinutes", 0, "GrowthFactor", 100)); + // An application named like a gone application's ID must survive that ID's delete. + Application namedLikeAnId = service.createApplication(Map.of("Name", "gone123")); + + for (StackResource resource : List.of(env, profile, strategy, app)) { + provisioner.delete(resource, REGION); + assertDoesNotThrow(() -> provisioner.delete(resource, REGION), resource.getResourceType()); + } + provisioner.delete(APPLICATION, "gone123", REGION); + + assertTrue(service.findEnvironment(env.getPhysicalId()).isEmpty()); + assertTrue(service.findConfigurationProfile(profile.getPhysicalId()).isEmpty()); + assertThrows(AwsException.class, () -> service.getDeploymentStrategy(strategy.getPhysicalId())); + assertEquals(List.of(namedLikeAnId.getId()), service.listApplications().stream().map(Application::getId).toList()); + } + + /** + * DeleteApplication takes a name as well as an ID, so a delete that first looks the application + * up and then deletes it through that API removes another application named like its ID when + * the API deletes the first in between. A stack's delete is one exact-ID call; this pins that + * it neither calls DeleteApplication's lookup nor looks the application up first. + */ + @Test + void anApplicationDeletedThroughTheApiMidDeleteLeavesOneNamedLikeItsIdAlone() { + String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + Application namedLikeTheId = service.createApplication(Map.of("Name", appId)); + doAnswer(invocation -> { + Object found = invocation.callRealMethod(); + service.deleteApplication(appId); + return found; + }).when(service).findApplication(appId); + + provisioner.delete(APPLICATION, appId, REGION); + + verify(service).deleteApplicationById(appId); + verify(service, never()).deleteApplication(anyString()); + assertEquals(List.of(namedLikeTheId.getId()), + service.listApplications().stream().map(Application::getId).toList()); + } + + @Test + void aFailedCreateUndoesOnlyItsOwnApplication() { + StackResource app = resource(APPLICATION); + doAnswer(invocation -> { + String appId = invocation.getArgument(0); + service.deleteApplication(appId); + service.createApplication(Map.of("Name", appId)); + throw new AwsException("InternalServerException", "tagging failed", 500); + }).when(service).setApplicationTags(anyString(), any()); + + assertThrows(AwsException.class, () -> provisioner.provision(app, + MAPPER.valueToTree(props("Name", "orders", "Tags", List.of(tag("team", "payments")))), context(null))); + + assertEquals(List.of(app.getPhysicalId()), + service.listApplications().stream().map(Application::getName).toList(), + "the application named like the undone one's ID is not the stack's"); + } + + /** + * Tags, like deletes, go by exact ID: an application the API deletes while the stack writes its + * tags fails the stack, and the tags never land on another application named like its ID. + */ + @Test + void anUpdateWhoseApplicationTheApiDeletedLeavesOneNamedLikeItsIdUntagged() { + StackResource app = create(APPLICATION, props("Name", "orders", "Tags", List.of(tag("team", "payments")))); + String appId = app.getPhysicalId(); + Application namedLikeTheId = service.createApplication(Map.of("Name", appId)); + service.tagApplication(namedLikeTheId.getId(), Map.of("owner", "billing")); + doAnswer(invocation -> { + Object updated = invocation.callRealMethod(); + service.deleteApplication(appId); + return updated; + }).when(service).updateApplication(anyString(), any(), any()); + + AwsException failure = assertThrows(AwsException.class, () -> update(app, props("Name", "orders-v2", + "Tags", List.of(tag("team", "checkout"))))); + + assertEquals("ResourceNotFoundException", failure.getErrorCode()); + assertEquals(Map.of("owner", "billing"), service.getApplication(namedLikeTheId.getId()).getTags()); + } + + @Test + void aCreateWhoseApplicationTheApiDeletedLeavesOneNamedLikeItsIdUntagged() { + doAnswer(invocation -> { + Application created = (Application) invocation.callRealMethod(); + service.deleteApplication(created.getId()); + service.createApplication(Map.of("Name", created.getId())); + return created; + }).doCallRealMethod().when(service).createApplication(any()); + StackResource app = resource(APPLICATION); + + AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(app, + MAPPER.valueToTree(props("Name", "orders", "Tags", List.of(tag("team", "payments")))), context(null))); + + assertEquals("ResourceNotFoundException", failure.getErrorCode()); + Application namedLikeTheId = service.getApplication(app.getPhysicalId()); + assertNotEquals(app.getPhysicalId(), namedLikeTheId.getId()); + assertTrue(namedLikeTheId.getTags().isEmpty(), "the stack's tags are not written to another application"); + } + + /** + * {@code ApplicationId} is the application's ID or name, as on AWS: an environment and a profile + * whose {@code ApplicationId} names an existing application are created under it. + */ + @Test + void anEnvironmentAndAProfileCanNameTheirApplication() { + String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + + StackResource env = create(ENVIRONMENT, props("ApplicationId", "orders", "Name", "beta")); + StackResource profile = create(PROFILE, props("ApplicationId", "orders", "Name", "settings", + "LocationUri", "hosted")); + + assertEquals(appId, service.findEnvironment(env.getPhysicalId()).orElseThrow().getApplicationId()); + assertEquals(appId, service.findConfigurationProfile(profile.getPhysicalId()).orElseThrow().getApplicationId()); + String recordedApplication = CfnRollback.USES_ATTR_PREFIX + "AppConfigApplicationId"; + assertEquals(appId, env.getAttributes().get(recordedApplication), "the stack records the application's ID"); + assertEquals(appId, profile.getAttributes().get(recordedApplication)); + } + + @Test + void anUpdateThatDropsTagsClearsThem() { + StackResource app = create(APPLICATION, props("Name", "orders", "Tags", List.of(tag("team", "payments")))); + + update(app, props("Name", "orders")); + + assertTrue(service.getApplication(app.getPhysicalId()).getTags().isEmpty()); + } + + /** + * An update that moves an environment and a profile to another application can delete the old + * application first, so their deletes must not depend on it; they still take their deployments + * and hosted configuration versions with them. + */ + @Test + void anEnvironmentAndAProfileWhoseApplicationIsGoneAreStillDeleted() { + String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + StackResource env = create(ENVIRONMENT, props("ApplicationId", appId, "Name", "beta")); + StackResource profile = create(PROFILE, props("ApplicationId", appId, "Name", "settings", + "LocationUri", "hosted")); + service.createHostedConfigurationVersion(appId, profile.getPhysicalId(), "{}".getBytes(), "application/json", + null); + service.startDeployment(appId, env.getPhysicalId(), Map.of("ConfigurationProfileId", profile.getPhysicalId(), + "ConfigurationVersion", "1", "DeploymentStrategyId", "AppConfig.AllAtOnce")); + service.deleteApplication(appId); + + provisioner.delete(ENVIRONMENT, env.getPhysicalId(), REGION); + provisioner.delete(PROFILE, profile.getPhysicalId(), REGION); + + assertTrue(service.findEnvironment(env.getPhysicalId()).isEmpty()); + assertTrue(service.findConfigurationProfile(profile.getPhysicalId()).isEmpty()); + assertTrue(storage.create("appconfig", "appconfig-deployments.json", + new TypeReference>() {}).scan(key -> key.startsWith(appId + "::")).isEmpty()); + assertTrue(storage.create("appconfig", "appconfig-versions.json", + new TypeReference>() {}) + .scan(key -> key.startsWith(appId + "::")).isEmpty()); + } + + @Test + void aDeleteFailureOtherThanNotFoundPropagates() { + String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + StackResource env = create(ENVIRONMENT, props("ApplicationId", appId, "Name", "beta")); + AwsException storage = new AwsException("InternalServerException", "storage failed", 500); + doThrow(storage).when(service).deleteEnvironmentById(env.getPhysicalId()); + + assertSame(storage, assertThrows(AwsException.class, () -> provisioner.delete(env, REGION))); + } + + @Test + void aStubIsNotDeleted() { + StackResource stub = resource(ENVIRONMENT); + stub.setPhysicalId("Env-0a1b2c3d"); + stub.getAttributes().put("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + "Env"); + + provisioner.delete(stub, REGION); + + verify(service, never()).deleteEnvironmentById(anyString()); + verify(service, never()).deleteEnvironment(anyString(), anyString()); + } + + @Test + void anUpdateOfAnEnvironmentDeletedOutsideTheStackFails() { + String appId = create(APPLICATION, props("Name", "orders")).getPhysicalId(); + StackResource env = create(ENVIRONMENT, props("ApplicationId", appId, "Name", "beta")); + service.deleteEnvironment(appId, env.getPhysicalId()); + + AwsException failure = assertThrows(AwsException.class, + () -> update(env, props("ApplicationId", appId, "Name", "gamma"))); + + assertEquals("ResourceNotFoundException", failure.getErrorCode()); + } + + private StackResource create(String type, Map properties) { + StackResource resource = resource(type); + provisioner.provision(resource, MAPPER.valueToTree(properties), context(null)); + return resource; + } + + /** Provisions {@code resource} again with {@code properties}, as an UpdateStack does. */ + private void update(StackResource resource, Map properties) { + provisioner.provision(resource, MAPPER.valueToTree(properties), context(resource.getPhysicalId())); + } + + /** The resource as the stack stores it, so a provision of the copy leaves the original alone. */ + private static StackResource copy(StackResource resource) { + StackResource copy = resource(resource.getResourceType()); + copy.setPhysicalId(resource.getPhysicalId()); + copy.getAttributes().putAll(resource.getAttributes()); + return copy; + } + + private static StackResource resource(String type) { + StackResource resource = new StackResource(); + resource.setLogicalId(type.substring(type.lastIndexOf(':') + 1)); + resource.setResourceType(type); + return resource; + } + + private ProvisionContext context(String priorPhysicalId) { + return new ProvisionContext(engine, REGION, ACCOUNT, STACK, priorPhysicalId); + } + + /** Alternating property names and values, in order. */ + private static Map props(Object... namesAndValues) { + Map properties = new LinkedHashMap<>(); + for (int i = 0; i < namesAndValues.length; i += 2) { + properties.put((String) namesAndValues[i], namesAndValues[i + 1]); + } + return properties; + } + + private static Map tag(String key, String value) { + return Map.of("Key", key, "Value", value); + } +} diff --git a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv index 8850e1f6b6..98590fd322 100644 --- a/src/test/resources/cloudformation/getatt-attribute-gaps.tsv +++ b/src/test/resources/cloudformation/getatt-attribute-gaps.tsv @@ -1,3 +1,4 @@ +AWS::AppConfig::ConfigurationProfile KmsKeyArn Floci's AppConfig keeps no KMS key on a profile, so KmsKeyIdentifier is accepted and not stored AWS::AppSync::GraphQLApi GraphQLEndpointArn the private-endpoint ARN of the GraphQL endpoint; Floci serves one public endpoint and has no private-endpoint model AWS::BedrockAgentCore::Runtime WorkloadIdentityDetails the dotted WorkloadIdentityDetails.WorkloadIdentityArn is set instead, the form AWS's GetAtt exposes for the nested object AWS::CodeBuild::Project Id schema gives no description; AWS's Id may differ from the project name Floci uses diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index 619cebec3e..4b27821d27 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -20,6 +20,10 @@ AWS::ApiGatewayV2::Integration ApiGatewayV2CfnProvisioner AWS::ApiGatewayV2::Route ApiGatewayV2CfnProvisioner AWS::ApiGatewayV2::Stage ApiGatewayV2CfnProvisioner AWS::ApiGatewayV2::VpcLink ApiGatewayV2CfnProvisioner +AWS::AppConfig::Application AppConfigCfnProvisioner +AWS::AppConfig::ConfigurationProfile AppConfigCfnProvisioner +AWS::AppConfig::DeploymentStrategy AppConfigCfnProvisioner +AWS::AppConfig::Environment AppConfigCfnProvisioner AWS::AppSync::ApiKey AppSyncCfnProvisioner AWS::AppSync::DataSource AppSyncCfnProvisioner AWS::AppSync::FunctionConfiguration AppSyncCfnProvisioner diff --git a/tools/docs/cfn_resource_types.yaml b/tools/docs/cfn_resource_types.yaml index 6214d9a750..958fa19236 100644 --- a/tools/docs/cfn_resource_types.yaml +++ b/tools/docs/cfn_resource_types.yaml @@ -39,6 +39,7 @@ order: - AWS::ApiGateway - AWS::ApiGatewayV2 - AWS::AppSync + - AWS::AppConfig - AWS::StepFunctions - AWS::CodePipeline - AWS::CodeBuild @@ -110,6 +111,7 @@ type_order: AWS::ApiGateway: [RestApi, Resource, Authorizer, Method, Deployment, Stage, Account, DomainName, BasePathMapping, GatewayResponse] AWS::ApiGatewayV2: [Api, Authorizer, Route, Integration, Stage, Deployment, DomainName, ApiMapping] AWS::AppSync: [GraphQLApi, GraphQLSchema, DataSource, FunctionConfiguration, Resolver, ApiKey] + AWS::AppConfig: [Application, Environment, ConfigurationProfile, DeploymentStrategy] AWS::CodePipeline: [Pipeline, CustomActionType, Webhook] AWS::Batch: [ComputeEnvironment, JobQueue, JobDefinition] AWS::Cognito: [UserPool, UserPoolClient] @@ -121,6 +123,7 @@ type_order: service_labels: AWS::ApiGateway: API Gateway (v1) AWS::ApiGatewayV2: API Gateway v2 + AWS::AppConfig: AppConfig AWS::AppSync: AppSync AWS::ApplicationAutoScaling: Application Auto Scaling AWS::AutoScaling: Auto Scaling @@ -210,6 +213,9 @@ notes: AWS::Cognito::UserPool: '`ProviderURL` is the local issuer of the tokens Floci mints, `/`' AWS::SES::EmailIdentity: 'BYODKIM is not supported by this resource; Easy DKIM DNS attributes use the shared emulator signing zone `dkim.amazonses.com` rather than AWS''s region- and identity-specific zone assignment' AWS::Events::Archive: '`KmsKeyIdentifier` is ignored' + AWS::AppConfig::Environment: '`Tags` and `DeletionProtectionCheck` are accepted and not stored' + AWS::AppConfig::ConfigurationProfile: '`Tags`, `KmsKeyIdentifier`, `RetrievalRoleArn`, `Validators` and `DeletionProtectionCheck` are accepted and not stored' + AWS::AppConfig::DeploymentStrategy: '`Tags` are accepted and not stored; `ReplicateTo: SSM_DOCUMENT` writes no SSM document' AWS::CloudFront::Function: '`KeyValueStoreAssociations` is ignored' AWS::GuardDuty::MalwareProtectionPlan: 'management plane only: no scan runs, so the plan stays ACTIVE; Ref returns the plan id; a BucketName change is rejected' AWS::BedrockAgentCore::Runtime: 'Ref returns the AgentRuntimeId; CapacityProviderConfiguration, FilesystemConfigurations, LifecycleConfiguration, PlatformVersion and RequestHeaderConfiguration are accepted and not stored' @@ -223,6 +229,9 @@ row_notes: AWS::CloudWatch: >- Composite alarms have backing definitions with name Ref and Arn GetAtt, rollback, and replacement cleanup. Composite actions are stored only; suppression properties are rejected. + AWS::AppConfig: >- + `Ref` returns the AppConfig ID of each. See [AppConfig](appconfig.md#cloudformation) for updates + and replacement. AWS::AppSync: >- `Ref` on `GraphQLApi` and `ApiKey` returns the id where AWS returns the ARN. See [AppSync](appsync.md#cloudformation) for `Ref` and `Fn::GetAtt` compared with AWS.