diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppConfigTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppConfigTest.java index 757afff636..777ba7cbd3 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppConfigTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/AppConfigTest.java @@ -12,6 +12,7 @@ import software.amazon.awssdk.services.appconfigdata.model.StartConfigurationSes import software.amazon.awssdk.services.appconfigdata.model.StartConfigurationSessionResponse; import java.nio.charset.StandardCharsets; +import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -611,4 +612,69 @@ class AppConfigTest { } } } + + @Test + @Order(57) + @DisplayName("Environments return their monitors and deployments their profile's name and location") + void monitorsAndDeploymentSourceRoundTrip() { + String monitoredAppId = appConfig.createApplication(CreateApplicationRequest.builder() + .name(TestFixtures.uniqueName("monitored-app")).build()).id(); + try { + Monitor withRole = Monitor.builder() + .alarmArn("arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-errors") + .alarmRoleArn("arn:aws:iam::000000000000:role/appconfig-alarm-monitor") + .build(); + Monitor withoutRole = Monitor.builder() + .alarmArn("arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-latency") + .build(); + CreateEnvironmentResponse monitored = appConfig.createEnvironment(CreateEnvironmentRequest.builder() + .applicationId(monitoredAppId).name("monitored").monitors(withRole, withoutRole).build()); + assertThat(monitored.monitors()).containsExactly(withRole, withoutRole); + assertThat(appConfig.getEnvironment(GetEnvironmentRequest.builder() + .applicationId(monitoredAppId).environmentId(monitored.id()).build()).monitors()) + .containsExactly(withRole, withoutRole); + assertThat(appConfig.createEnvironment(CreateEnvironmentRequest.builder() + .applicationId(monitoredAppId).name("unmonitored").build()).hasMonitors()).isFalse(); + + // Qualified: the imported BadRequestException is AppConfigData's, this one is AppConfig's. + assertThrows(software.amazon.awssdk.services.appconfig.model.BadRequestException.class, + () -> appConfig.createEnvironment(CreateEnvironmentRequest.builder() + .applicationId(monitoredAppId).name("refused") + .monitors(Collections.nCopies(6, withoutRole)).build())); + + String profileId = appConfig.createConfigurationProfile(CreateConfigurationProfileRequest.builder() + .applicationId(monitoredAppId) + .name("service-settings") + .locationUri("ssm-parameter://service-settings") + .type("AWS.Freeform") + .build()).id(); + StartDeploymentResponse started = appConfig.startDeployment(StartDeploymentRequest.builder() + .applicationId(monitoredAppId) + .environmentId(monitored.id()) + .configurationProfileId(profileId) + .configurationVersion("1") + .deploymentStrategyId("AppConfig.AllAtOnce") + .build()); + assertThat(started.configurationName()).isEqualTo("service-settings"); + assertThat(started.configurationLocationUri()).isEqualTo("ssm-parameter://service-settings"); + + GetDeploymentResponse deployment = appConfig.getDeployment(GetDeploymentRequest.builder() + .applicationId(monitoredAppId) + .environmentId(monitored.id()) + .deploymentNumber(started.deploymentNumber()) + .build()); + assertThat(deployment.configurationName()).isEqualTo("service-settings"); + assertThat(deployment.configurationLocationUri()).isEqualTo("ssm-parameter://service-settings"); + + // AWS documents no default Type: a profile created without one reports none. + assertThat(appConfig.createConfigurationProfile(CreateConfigurationProfileRequest.builder() + .applicationId(monitoredAppId).name("untyped").locationUri("hosted").build()).type()).isNull(); + } finally { + try { + appConfig.deleteApplication(DeleteApplicationRequest.builder().applicationId(monitoredAppId).build()); + } catch (Exception ignored) { + // Best-effort cleanup: the application name is unique, so a leftover cannot affect other tests. + } + } + } } diff --git a/docs/services/appconfig.md b/docs/services/appconfig.md index e08b4c3ce7..32fc2e6232 100644 --- a/docs/services/appconfig.md +++ b/docs/services/appconfig.md @@ -41,6 +41,15 @@ returns `ResourceNotFoundException`. Only hosted configurations are served: a deployed version with no hosted configuration version behind it, such as one from an S3 or SSM source, returns `ResourceNotFoundException`. +`CreateEnvironment` keeps up to five `Monitors`, each a CloudWatch `AlarmArn` with an optional IAM role +`AlarmRoleArn`, and environment reads return them; an environment created without monitors returns none. +Floci does not evaluate the alarms or roll a deployment back. More than five monitors, or an `AlarmRoleArn` +that is not an IAM role ARN, returns `BadRequestException`. +`StartDeployment` and `GetDeployment` return the deployed profile's name and location URI as +`ConfigurationName` and `ConfigurationLocationUri`. Deployments stored by earlier Floci versions did not +record them, so on those neither is set. +A configuration profile created without `Type` reports no type, as AWS documents no default. + ## Data Plane (AppConfigData) {#data-plane} The data plane is used by applications to retrieve the active configuration for an environment and profile. 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 62e9cf77c3..da6d8a6827 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 @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.appconfig; import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; @@ -14,6 +15,7 @@ import io.github.hectorvent.floci.services.appconfig.model.DeploymentSummary; 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.HostedConfigurationVersionSummary; +import io.github.hectorvent.floci.services.appconfig.model.Monitor; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; @@ -24,6 +26,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; @ApplicationScoped public class AppConfigService { @@ -38,6 +41,9 @@ public class AppConfigService { private final StorageBackend activeConfigStore; // envId::profileId -> versionNumber private final Map deploymentPageTokens = new ConcurrentHashMap<>(); private static final int MAX_DEPLOYMENT_PAGE_TOKENS = 1000; + private static final int MAX_MONITORS = 5; + private static final int MAX_ARN_LENGTH = 2048; + private static final Pattern ROLE_ARN = Pattern.compile("arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::\\d{12}:role/.*"); @Inject public AppConfigService(StorageFactory storageFactory, EmulatorConfig config) { @@ -85,6 +91,7 @@ public class AppConfigService { // ──────────────────────────── Environment ──────────────────────────── public Environment createEnvironment(String applicationIdentifier, Map request) { + List monitors = monitors(request.get("Monitors")); String appId = resolveApplication(applicationIdentifier).getId(); Environment env = new Environment(); env.setId(shortId(7)); @@ -92,6 +99,7 @@ public class AppConfigService { env.setName((String) request.get("Name")); env.setDescription((String) request.get("Description")); env.setState("READY"); + env.setMonitors(monitors); environmentStore.put(env.getId(), env); return env; } @@ -131,6 +139,32 @@ public class AppConfigService { .toList(); } + /** The request's Monitors, checked against the limits AWS documents for CreateEnvironment. */ + private static List monitors(Object value) { + if (value == null) { + return null; + } + if (!(value instanceof List entries) || entries.size() > MAX_MONITORS) { + throw new AwsException("BadRequestException", "Monitors must be a list of at most " + MAX_MONITORS + " monitors", 400); + } + List result = new ArrayList<>(); + for (Object entry : entries) { + if (!(entry instanceof Map monitor) + || !(monitor.get("AlarmArn") instanceof String alarmArn) + || alarmArn.isEmpty() || alarmArn.length() > MAX_ARN_LENGTH) { + throw new AwsException("BadRequestException", + "Each monitor requires a string AlarmArn of 1 to " + MAX_ARN_LENGTH + " characters", 400); + } + Object role = monitor.get("AlarmRoleArn"); + if (role != null && (!(role instanceof String roleArn) + || roleArn.length() > MAX_ARN_LENGTH || !ROLE_ARN.matcher(roleArn).matches())) { + throw new AwsException("BadRequestException", "AlarmRoleArn must be the ARN of an IAM role", 400); + } + result.add(new Monitor(alarmArn, (String) role)); + } + return result; + } + // ──────────────────────────── Configuration Profile ──────────────────────────── public ConfigurationProfile createConfigurationProfile(String applicationIdentifier, Map request) { @@ -344,8 +378,9 @@ public class AppConfigService { Map request) { String appId = resolveApplication(applicationIdentifier).getId(); String envId = resolveEnvironment(appId, environmentIdentifier).getId(); - String profileId = resolveConfigurationProfile( - appId, (String) request.get("ConfigurationProfileId")).getId(); + ConfigurationProfile profile = resolveConfigurationProfile( + appId, (String) request.get("ConfigurationProfileId")); + String profileId = profile.getId(); String version = (String) request.get("ConfigurationVersion"); String strategyId = (String) request.get("DeploymentStrategyId"); @@ -355,6 +390,8 @@ public class AppConfigService { deployment.setApplicationId(appId); deployment.setEnvironmentId(envId); deployment.setConfigurationProfileId(profileId); + deployment.setConfigurationName(profile.getName()); + deployment.setConfigurationLocationUri(profile.getLocationUri()); deployment.setConfigurationVersion(version); deployment.setDeploymentStrategyId(strategyId); int nextDeploymentNumber = deploymentStore.scan(key -> true).stream() diff --git a/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Deployment.java b/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Deployment.java index ac7abfa480..8239436a68 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Deployment.java +++ b/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Deployment.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.appconfig.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; @@ -17,6 +18,10 @@ public class Deployment { private int deploymentNumber; @JsonProperty("ConfigurationName") private String configurationName; + // Omitted rather than null on deployments stored before it was recorded, so they read back unchanged. + @JsonProperty("ConfigurationLocationUri") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String configurationLocationUri; @JsonProperty("ConfigurationVersion") private String configurationVersion; @JsonProperty("DeploymentStrategyId") @@ -43,6 +48,9 @@ public class Deployment { public String getConfigurationName() { return configurationName; } public void setConfigurationName(String configurationName) { this.configurationName = configurationName; } + public String getConfigurationLocationUri() { return configurationLocationUri; } + public void setConfigurationLocationUri(String configurationLocationUri) { this.configurationLocationUri = configurationLocationUri; } + public String getConfigurationVersion() { return configurationVersion; } public void setConfigurationVersion(String configurationVersion) { this.configurationVersion = configurationVersion; } diff --git a/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Environment.java b/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Environment.java index 6742fadf58..4b01208ab6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Environment.java +++ b/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Environment.java @@ -1,9 +1,12 @@ package io.github.hectorvent.floci.services.appconfig.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; +import java.util.List; + @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) public class Environment { @@ -17,6 +20,10 @@ public class Environment { private String description; @JsonProperty("State") private String state; // READY, DEPLOYING, ROLLING_BACK, ROLLED_BACK + // Null when the environment was created without monitors: AWS then returns no Monitors member. + @JsonProperty("Monitors") + @JsonInclude(JsonInclude.Include.NON_NULL) + private List monitors; public Environment() {} @@ -34,4 +41,7 @@ public class Environment { public String getState() { return state; } public void setState(String state) { this.state = state; } + + public List getMonitors() { return monitors; } + public void setMonitors(List monitors) { this.monitors = monitors != null ? List.copyOf(monitors) : null; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Monitor.java b/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Monitor.java new file mode 100644 index 0000000000..e6fa0a47aa --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/appconfig/model/Monitor.java @@ -0,0 +1,14 @@ +package io.github.hectorvent.floci.services.appconfig.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** A CloudWatch alarm an environment names for AppConfig to watch during deployments. */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +public record Monitor(@JsonProperty("AlarmArn") String alarmArn, + @JsonProperty("AlarmRoleArn") String alarmRoleArn) { +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigResourceFieldsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigResourceFieldsIntegrationTest.java new file mode 100644 index 0000000000..74f2a81346 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigResourceFieldsIntegrationTest.java @@ -0,0 +1,171 @@ +package io.github.hectorvent.floci.services.appconfig; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; + +@QuarkusTest +class AppConfigResourceFieldsIntegrationTest { + + private static final String ALARM_ARN = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-errors"; + private static final String SECOND_ALARM_ARN = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-latency"; + private static final String ALARM_ROLE_ARN = "arn:aws:iam::000000000000:role/appconfig-alarm-monitor"; + + @BeforeAll + static void setup() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void environmentReturnsTheMonitorsItWasCreatedWith() { + String applicationId = createApplication("monitored-app"); + String environmentId = given() + .contentType(ContentType.JSON) + .body("{\"Name\":\"monitored\",\"Monitors\":[" + + "{\"AlarmArn\":\"" + ALARM_ARN + "\",\"AlarmRoleArn\":\"" + ALARM_ROLE_ARN + "\"}," + + "{\"AlarmArn\":\"" + SECOND_ALARM_ARN + "\"}]}") + .when().post("/applications/" + applicationId + "/environments") + .then().statusCode(201) + .body("Monitors.AlarmArn", contains(ALARM_ARN, SECOND_ALARM_ARN)) + .body("Monitors[0].AlarmRoleArn", equalTo(ALARM_ROLE_ARN)) + .body("Monitors[1]", not(hasKey("AlarmRoleArn"))) + .extract().path("Id"); + + given() + .when().get("/applications/" + applicationId + "/environments/" + environmentId) + .then().statusCode(200) + .body("Monitors", equalTo(List.of( + Map.of("AlarmArn", ALARM_ARN, "AlarmRoleArn", ALARM_ROLE_ARN), + Map.of("AlarmArn", SECOND_ALARM_ARN)))); + + given() + .when().get("/applications/" + applicationId + "/environments") + .then().statusCode(200) + .body("Items.find { it.Id == '" + environmentId + "' }.Monitors.AlarmArn", + contains(ALARM_ARN, SECOND_ALARM_ARN)); + } + + @Test + void environmentCreatedWithoutMonitorsReturnsNone() { + String applicationId = createApplication("unmonitored-app"); + String environmentId = given() + .contentType(ContentType.JSON) + .body("{\"Name\":\"unmonitored\"}") + .when().post("/applications/" + applicationId + "/environments") + .then().statusCode(201) + .body("$", not(hasKey("Monitors"))) + .extract().path("Id"); + + given() + .when().get("/applications/" + applicationId + "/environments/" + environmentId) + .then().statusCode(200) + .body("$", not(hasKey("Monitors"))); + } + + @Test + void invalidMonitorsAreRefusedAndNoEnvironmentIsCreated() { + String applicationId = createApplication("refused-monitors-app"); + String monitor = "{\"AlarmArn\":\"" + ALARM_ARN + "\"}"; + List invalid = List.of( + "\"not-a-list\"", + "[" + String.join(",", Collections.nCopies(6, monitor)) + "]", + "[\"not-a-monitor\"]", + "[null]", + "[{}]", + "[{\"AlarmArn\":\"\"}]", + "[{\"AlarmArn\":1}]", + "[{\"AlarmArn\":\"" + "a".repeat(2049) + "\"}]", + "[{\"AlarmArn\":\"" + ALARM_ARN + "\",\"AlarmRoleArn\":1}]", + "[{\"AlarmArn\":\"" + ALARM_ARN + "\",\"AlarmRoleArn\":\"appconfig-alarm-monitor\"}]", + "[{\"AlarmArn\":\"" + ALARM_ARN + "\",\"AlarmRoleArn\":\"arn:aws:iam::000000000000:user/monitor\"}]", + "[{\"AlarmArn\":\"" + ALARM_ARN + "\",\"AlarmRoleArn\":\"" + ALARM_ROLE_ARN + "x".repeat(2048) + "\"}]"); + for (String monitors : invalid) { + given() + .contentType(ContentType.JSON) + .body("{\"Name\":\"refused\",\"Monitors\":" + monitors + "}") + .when().post("/applications/" + applicationId + "/environments") + .then().statusCode(400) + .body("__type", equalTo("BadRequestException")); + } + + given() + .when().get("/applications/" + applicationId + "/environments") + .then().statusCode(200) + .body("Items", empty()); + } + + @Test + void deploymentReturnsTheDeployedProfileNameAndLocation() { + String applicationId = createApplication("deployment-source-app"); + String environmentId = given() + .contentType(ContentType.JSON) + .body("{\"Name\":\"deployment-source-env\"}") + .when().post("/applications/" + applicationId + "/environments") + .then().statusCode(201) + .extract().path("Id"); + String profileId = given() + .contentType(ContentType.JSON) + .body("{\"Name\":\"service-settings\",\"LocationUri\":\"ssm-parameter://service-settings\"," + + "\"Type\":\"AWS.Freeform\"}") + .when().post("/applications/" + applicationId + "/configurationprofiles") + .then().statusCode(201) + .extract().path("Id"); + String deployments = "/applications/" + applicationId + "/environments/" + environmentId + "/deployments"; + + int deploymentNumber = given() + .contentType(ContentType.JSON) + .body("{\"ConfigurationProfileId\":\"" + profileId + "\",\"ConfigurationVersion\":\"1\"," + + "\"DeploymentStrategyId\":\"AppConfig.AllAtOnce\"}") + .when().post(deployments) + .then().statusCode(201) + .body("ConfigurationName", equalTo("service-settings")) + .body("ConfigurationLocationUri", equalTo("ssm-parameter://service-settings")) + .extract().path("DeploymentNumber"); + + given() + .when().get(deployments + "/" + deploymentNumber) + .then().statusCode(200) + .body("ConfigurationName", equalTo("service-settings")) + .body("ConfigurationLocationUri", equalTo("ssm-parameter://service-settings")); + } + + @Test + void profileCreatedWithoutTypeReturnsNoType() { + String applicationId = createApplication("untyped-profile-app"); + String profileId = given() + .contentType(ContentType.JSON) + .body("{\"Name\":\"untyped\",\"LocationUri\":\"hosted\"}") + .when().post("/applications/" + applicationId + "/configurationprofiles") + .then().statusCode(201) + .body("Type", nullValue()) + .extract().path("Id"); + + given() + .when().get("/applications/" + applicationId + "/configurationprofiles/" + profileId) + .then().statusCode(200) + .body("Type", nullValue()); + } + + private static String createApplication(String name) { + return given() + .contentType(ContentType.JSON) + .body("{\"Name\":\"" + name + "\"}") + .when().post("/applications") + .then().statusCode(201) + .extract().path("Id"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServicePersistenceTest.java new file mode 100644 index 0000000000..1927b440dc --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServicePersistenceTest.java @@ -0,0 +1,109 @@ +package io.github.hectorvent.floci.services.appconfig; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.ServiceConfigAccess; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.appconfig.model.Deployment; +import io.github.hectorvent.floci.services.appconfig.model.Environment; +import io.github.hectorvent.floci.services.appconfig.model.Monitor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class AppConfigServicePersistenceTest { + + private static final String ALARM_ARN = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-errors"; + private static final String SECOND_ALARM_ARN = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-latency"; + private static final String ALARM_ROLE_ARN = "arn:aws:iam::000000000000:role/appconfig-alarm-monitor"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @TempDir + Path dir; + + @Test + void stateStoredWithoutMonitorsOrDeploymentLocationsStillLoads() throws IOException { + // Written the way earlier builds persisted these records: no Monitors, no ConfigurationLocationUri. + Files.writeString(dir.resolve("appconfig-applications.json"), """ + {"000000000000/app1": {"Id": "app1", "Name": "stored-app", "Description": null, "tags": {}}} + """); + Files.writeString(dir.resolve("appconfig-environments.json"), """ + {"000000000000/env1": {"Id": "env1", "ApplicationId": "app1", "Name": "stored-env", + "Description": null, "State": "READY"}} + """); + Files.writeString(dir.resolve("appconfig-profiles.json"), """ + {"000000000000/prof1": {"Id": "prof1", "ApplicationId": "app1", "Name": "stored-profile", + "Description": null, "LocationUri": "hosted", "Type": null}} + """); + Files.writeString(dir.resolve("appconfig-deployments.json"), """ + {"000000000000/app1::env1::1": {"ApplicationId": "app1", "EnvironmentId": "env1", + "ConfigurationProfileId": "prof1", "DeploymentNumber": 1, "ConfigurationName": null, + "ConfigurationVersion": "1", "DeploymentStrategyId": "AppConfig.AllAtOnce", + "State": "COMPLETE", "Description": null}} + """); + + AppConfigService service = new AppConfigService(newFactory(), mock(EmulatorConfig.class)); + + Environment environment = service.getEnvironment("app1", "env1"); + assertEquals("stored-env", environment.getName()); + assertNull(environment.getMonitors()); + assertFalse(MAPPER.valueToTree(environment).has("Monitors")); + + Deployment deployment = service.getDeployment("app1", "env1", 1); + assertEquals("prof1", deployment.getConfigurationProfileId()); + assertEquals("COMPLETE", deployment.getState()); + assertNull(deployment.getConfigurationLocationUri()); + assertFalse(MAPPER.valueToTree(deployment).has("ConfigurationLocationUri")); + + assertNull(service.getConfigurationProfile("app1", "prof1").getType()); + } + + @Test + void monitorsAndDeploymentLocationsSurviveARestart() { + StorageFactory first = newFactory(); + AppConfigService service = new AppConfigService(first, mock(EmulatorConfig.class)); + String appId = service.createApplication(Map.of("Name", "restarted-app")).getId(); + String monitoredId = service.createEnvironment(appId, Map.of("Name", "monitored", "Monitors", List.of( + Map.of("AlarmArn", ALARM_ARN, "AlarmRoleArn", ALARM_ROLE_ARN), + Map.of("AlarmArn", SECOND_ALARM_ARN)))).getId(); + String unmonitoredId = service.createEnvironment(appId, Map.of("Name", "unmonitored")).getId(); + String profileId = service.createConfigurationProfile(appId, Map.of( + "Name", "service-settings", "LocationUri", "ssm-parameter://service-settings")).getId(); + int deploymentNumber = service.startDeployment(appId, monitoredId, Map.of( + "ConfigurationProfileId", profileId, + "ConfigurationVersion", "1", + "DeploymentStrategyId", "AppConfig.AllAtOnce")).getDeploymentNumber(); + first.shutdownAll(); + + AppConfigService restarted = new AppConfigService(newFactory(), mock(EmulatorConfig.class)); + + assertEquals(List.of(new Monitor(ALARM_ARN, ALARM_ROLE_ARN), new Monitor(SECOND_ALARM_ARN, null)), + restarted.getEnvironment(appId, monitoredId).getMonitors()); + assertNull(restarted.getEnvironment(appId, unmonitoredId).getMonitors()); + Deployment deployment = restarted.getDeployment(appId, monitoredId, deploymentNumber); + assertEquals("service-settings", deployment.getConfigurationName()); + assertEquals("ssm-parameter://service-settings", deployment.getConfigurationLocationUri()); + } + + private StorageFactory newFactory() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.defaultAccountId()).thenReturn("000000000000"); + when(config.storage().persistentPath()).thenReturn(dir.toString()); + ServiceConfigAccess serviceConfigAccess = mock(ServiceConfigAccess.class); + when(serviceConfigAccess.storageMode(anyString())).thenReturn("persistent"); + return new StorageFactory(config, serviceConfigAccess); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceTest.java index 9e3d6e4ec2..2c1b1ee1c2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appconfig/AppConfigServiceTest.java @@ -10,9 +10,12 @@ 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.DeploymentSummary; import io.github.hectorvent.floci.services.appconfig.model.Environment; +import io.github.hectorvent.floci.services.appconfig.model.Monitor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -27,15 +30,22 @@ import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class AppConfigServiceTest { + private static final String ALARM_ARN = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-errors"; + private static final String SECOND_ALARM_ARN = "arn:aws:cloudwatch:us-east-1:000000000000:alarm:configuration-latency"; + private static final String ALARM_ROLE_ARN = "arn:aws:iam::000000000000:role/appconfig-alarm-monitor"; + private AccountAwareStorageBackend applicationStore; private AccountAwareStorageBackend environmentStore; private AccountAwareStorageBackend deploymentStore; @@ -134,6 +144,91 @@ class AppConfigServiceTest { assertThrows(RuntimeException.class, () -> service.listDeployments("app", "env", 1, "unknown")); } + @Test + void environmentKeepsAnImmutableCopyOfItsMonitors() { + Map withRole = new HashMap<>(Map.of("AlarmArn", ALARM_ARN, "AlarmRoleArn", ALARM_ROLE_ARN)); + List monitors = new ArrayList<>(List.of(withRole, Map.of("AlarmArn", SECOND_ALARM_ARN))); + + Environment environment = service.createEnvironment("app", Map.of("Name", "monitored", "Monitors", monitors)); + monitors.clear(); + withRole.put("AlarmArn", "changed"); + + assertEquals(List.of(new Monitor(ALARM_ARN, ALARM_ROLE_ARN), new Monitor(SECOND_ALARM_ARN, null)), + environment.getMonitors()); + assertThrows(UnsupportedOperationException.class, () -> environment.getMonitors().clear()); + } + + @Test + void environmentCreatedWithoutMonitorsHasNone() { + assertNull(service.createEnvironment("app", Map.of("Name", "unmonitored")).getMonitors()); + } + + @Test + void monitorsAtTheDocumentedLimitsAreAccepted() { + String rolePrefix = "arn:aws:iam::000000000000:role/"; + List> monitors = List.of( + Map.of("AlarmArn", "a".repeat(2048)), + Map.of("AlarmArn", "a", "AlarmRoleArn", rolePrefix + "r".repeat(2048 - rolePrefix.length())), + Map.of("AlarmArn", ALARM_ARN, "AlarmRoleArn", "arn:aws-cn:iam::000000000000:role/monitor"), + Map.of("AlarmArn", ALARM_ARN, "AlarmRoleArn", "arn:aws-us-gov:iam::000000000000:role/path/monitor"), + Map.of("AlarmArn", ALARM_ARN, "AlarmRoleArn", "arn:aws-eusc:iam::000000000000:role/monitor")); + + assertEquals(5, service.createEnvironment("app", Map.of("Name", "limits", "Monitors", monitors)) + .getMonitors().size()); + assertEquals(List.of(), service.createEnvironment("app", Map.of("Name", "empty", "Monitors", List.of())) + .getMonitors()); + } + + @Test + void invalidMonitorsAreRefusedBeforeTheEnvironmentIsStored() { + clearInvocations(environmentStore); + Map monitor = Map.of("AlarmArn", ALARM_ARN); + List invalid = new ArrayList<>(List.of( + "not-a-list", + Collections.nCopies(6, monitor), + List.of("not-a-monitor"), + List.of(Map.of()), + List.of(Map.of("AlarmArn", "")), + List.of(Map.of("AlarmArn", 1)), + List.of(Map.of("AlarmArn", "a".repeat(2049))), + List.of(Map.of("AlarmArn", ALARM_ARN, "AlarmRoleArn", 1)), + List.of(Map.of("AlarmArn", ALARM_ARN, "AlarmRoleArn", "appconfig-alarm-monitor")), + List.of(Map.of("AlarmArn", ALARM_ARN, "AlarmRoleArn", "arn:aws:iam::000000000000:user/monitor")), + List.of(Map.of("AlarmArn", ALARM_ARN, "AlarmRoleArn", ALARM_ROLE_ARN + "x".repeat(2048))))); + invalid.add(Collections.singletonList(null)); + + for (Object monitors : invalid) { + AwsException refused = assertThrows(AwsException.class, + () -> service.createEnvironment("app", Map.of("Name", "refused", "Monitors", monitors))); + assertEquals("BadRequestException", refused.getErrorCode()); + assertEquals(400, refused.getHttpStatus()); + } + verify(environmentStore, never()).put(anyString(), any()); + } + + @Test + void invalidMonitorsAreRefusedBeforeTheApplicationIsLookedUp() { + AwsException refused = assertThrows(AwsException.class, () -> service.createEnvironment("missing", + Map.of("Name", "refused", "Monitors", Collections.nCopies(6, Map.of("AlarmArn", ALARM_ARN))))); + + assertEquals("BadRequestException", refused.getErrorCode()); + } + + @Test + void startDeploymentRecordsTheDeployedProfileNameAndLocation() { + ConfigurationProfile profile = service.getConfigurationProfile("app", "profile"); + profile.setName("service-settings"); + profile.setLocationUri("ssm-parameter://service-settings"); + + Deployment deployment = service.startDeployment("app", "env", Map.of( + "ConfigurationProfileId", "profile", + "ConfigurationVersion", "1", + "DeploymentStrategyId", "AppConfig.AllAtOnce")); + + assertEquals("service-settings", deployment.getConfigurationName()); + assertEquals("ssm-parameter://service-settings", deployment.getConfigurationLocationUri()); + } + @Test void deleteEnvironmentRemovesRuntimeState() { deploymentStore.put("app::env::1", deployment("app", "env", 1));