feat(fis): add AWS FIS support (#2435)

* feat(fis): add AWS FIS support

* refactor: add typed FIS persistence models

* ci(fis): retrigger timed-out build

* fix(fis): reject trailing JSON request bodies
This commit is contained in:
Alex Banna authored and GitHub committed 2026-08-21 00:09:04 -04:00
1 parent d0a96d87b1
commit 04d120fdd5
48 files changed
+6225 -13

No files matched your search

@@ -0,0 +1,33 @@
package io.github.hectorvent.floci.core.common;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import org.junit.jupiter.api.Test;
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 AwsRestJsonErrorHeaderFilterTest {
@Test
void doesNotAddRestJsonHeaderToJsonProtocolErrorForDualProtocolService() {
ResolvedServiceCatalog catalog = mock(ResolvedServiceCatalog.class);
ServiceDescriptor dualProtocolService = mock(ServiceDescriptor.class);
when(dualProtocolService.supportsProtocol(ServiceProtocol.REST_JSON)).thenReturn(true);
ContainerRequestContext request = mock(ContainerRequestContext.class);
when(request.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY)).thenReturn(
new ProtocolClaim(WireProtocol.AWS_JSON_1_1, dualProtocolService, "Operation", null));
ContainerResponseContext response = mock(ContainerResponseContext.class);
when(response.getStatus()).thenReturn(400);
when(response.getHeaderString("X-Amzn-Errortype")).thenReturn(null);
new AwsRestJsonErrorHeaderFilter(catalog).filter(request, response);
verify(response, never()).getEntity();
verify(response, never()).getHeaders();
}
}
@@ -64,6 +64,16 @@ class ServiceCatalogRoutingIntegrationTest {
assertTrue(descriptor.supportsProtocol(ServiceProtocol.REST_JSON));
}
@Test
void fisResolvesAsRestJsonByCredentialScope() {
ServiceDescriptor descriptor = catalog.byCredentialScope("fis").orElseThrow();
assertEquals("fis", descriptor.externalKey());
assertEquals("fis", descriptor.storageKey());
assertEquals(ServiceProtocol.REST_JSON, descriptor.defaultProtocol());
assertTrue(descriptor.supportsProtocol(ServiceProtocol.REST_JSON));
}
@Test
void unknownTargetsRemainUnresolved() {
assertTrue(catalog.matchTarget("UnknownService.DoThing").isEmpty());
@@ -156,6 +156,20 @@ class ServiceEnablementIntegrationTest {
.body("message", equalTo("Service es is not enabled."));
}
@Test
void signedFisGetRequestsReturnJsonWhenServiceDisabled() {
given()
.header("Authorization", authorization("fis"))
.when()
.get("/actions")
.then()
.statusCode(400)
.contentType("application/json")
.header("X-Amzn-Errortype", "ServiceNotAvailableException")
.body("__type", equalTo("ServiceNotAvailableException"))
.body("message", equalTo("Service fis is not enabled."));
}
@Test
void signedRdsDataExecuteRequestsReturnJsonWhenServiceDisabled() {
given()
@@ -191,6 +205,7 @@ class ServiceEnablementIntegrationTest {
"floci.services.acm.enabled", "false",
"floci.services.dynamodb.enabled", "false",
"floci.services.ecs.enabled", "false",
"floci.services.fis.enabled", "false",
"floci.services.lambda.enabled", "false",
"floci.services.opensearch.enabled", "false",
"floci.services.rds-data.enabled", "false",
@@ -0,0 +1,813 @@
package io.github.hectorvent.floci.services.fis;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class FisCatalogTargetValidationTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT_ID = "000000000000";
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/fis-role";
private ObjectMapper mapper;
private FisCatalog catalog;
private FisService service;
@BeforeEach
void setUp() {
mapper = new ObjectMapper();
RegionResolver resolver = new RegionResolver(REGION, ACCOUNT_ID);
catalog = new FisCatalog(mapper, resolver);
service = new FisService(FisStores.inMemory(), mapper, resolver, catalog);
}
@Test
void exposesOfficialActionSlotsAndRequiredParameterMetadata() {
assertEquals(50, catalog.actionIds().size());
catalog.actionIds().forEach(id -> {
ObjectNode action = catalog.action(REGION, id);
assertEquals(id, action.path("id").asText());
assertFalse(action.path("description").asText().isBlank());
assertTrue(action.path("targets").isObject());
assertTrue(action.path("parameters").isObject());
});
ObjectNode customResource = catalog.action(REGION, "aws:eks:inject-kubernetes-custom-resource");
assertTrue(customResource.path("targets").has("Cluster"));
assertFalse(customResource.path("targets").has("Clusters"));
assertRequired(customResource, "kubernetesApiVersion", true);
assertRequired(customResource, "kubernetesKind", true);
assertRequired(customResource, "kubernetesNamespace", true);
assertRequired(customResource, "kubernetesSpec", true);
assertRequired(customResource, "maxDuration", true);
ObjectNode vpcEndpoint = catalog.action(REGION, "aws:network:disrupt-vpc-endpoint");
assertTrue(vpcEndpoint.path("targets").has("VPCEndpoints"));
assertFalse(vpcEndpoint.path("targets").has("VpcEndpoints"));
ObjectNode injectApi = catalog.action(REGION, "aws:fis:inject-api-internal-error");
assertRequired(injectApi, "duration", true);
assertRequired(injectApi, "service", true);
assertRequired(injectApi, "percentage", true);
assertRequired(injectApi, "operations", true);
ObjectNode zonalAutoshift = catalog.action(REGION, "aws:arc:start-zonal-autoshift");
assertRequired(zonalAutoshift, "duration", true);
assertRequired(zonalAutoshift, "availabilityZoneIdentifier", true);
assertRequired(zonalAutoshift, "managedResourceTypes", false);
assertRequired(zonalAutoshift, "zonalAutoshiftStatus", false);
ObjectNode podCpu = catalog.action(REGION, "aws:eks:pod-cpu-stress");
assertRequired(podCpu, "duration", true);
assertRequired(podCpu, "kubernetesServiceAccount", true);
assertRequired(podCpu, "percent", false);
assertRequired(podCpu, "workers", false);
assertRequired(podCpu, "fisPodSecurityPolicy", false);
ObjectNode pod = catalog.targetResourceType("aws:eks:pod");
assertRequired(pod, "availabilityZoneIdentifier", false);
assertRequired(pod, "clusterIdentifier", true);
assertRequired(pod, "namespace", true);
assertRequired(pod, "selectorType", true);
assertRequired(pod, "selectorValue", true);
assertRequired(pod, "targetContainerName", false);
}
@Test
void acceptsParameterOnlyTargetsAndHonorsEmptyTargetSkip() throws Exception {
ObjectNode request = eksPodTemplate();
String templateId = service.createExperimentTemplate(REGION, request)
.path("experimentTemplate").path("id").asText();
ObjectNode started = service.startExperiment(REGION, mapper.readTree("""
{
"clientToken":"%s",
"experimentTemplateId":"%s",
"experimentOptions":{"actionsMode":"skip-all"}
}
""".formatted(UUID.randomUUID(), templateId)))
.path("experiment").deepCopy();
String experimentId = started.path("id").asText();
JsonNode resolved = service.listExperimentResolvedTargets(REGION, experimentId, 100, null, null)
.path("resolvedTargets");
assertTrue(resolved.isEmpty());
assertEquals("completed", started.path("state").path("status").asText());
assertEquals("skipped", started.path("actions").path("delete")
.path("state").path("status").asText());
}
@Test
void failsExperimentWhenSelectorTargetDoesNotResolveByDefault() throws Exception {
ObjectNode request = ec2Template("ALL");
ObjectNode target = (ObjectNode) request.path("targets").path("instances");
target.remove("resourceArns");
target.putObject("resourceTags").put("environment", "missing");
String templateId = service.createExperimentTemplate(REGION, request)
.path("experimentTemplate").path("id").asText();
ObjectNode experiment = service.startExperiment(REGION, mapper.readTree("""
{"clientToken":"%s","experimentTemplateId":"%s"}
""".formatted(UUID.randomUUID(), templateId)))
.path("experiment").deepCopy();
assertEquals("failed", experiment.path("state").path("status").asText());
assertEquals("failed", experiment.path("actions").path("stop")
.path("state").path("status").asText());
assertTrue(service.listExperimentResolvedTargets(REGION, experiment.path("id").asText(),
100, null, null).path("resolvedTargets").isEmpty());
}
@Test
void validatesFiltersAndRejectsUnsupportedParameters() throws Exception {
ObjectNode filterOnly = ec2Template("ALL");
ObjectNode filterOnlyTarget = (ObjectNode) filterOnly.path("targets").path("instances");
filterOnlyTarget.remove("resourceArns");
filterOnlyTarget.set("filters", mapper.readTree("""
[{"path":"State.Name","values":["running"]}]
"""));
String filterOnlyId = service.createExperimentTemplate(REGION, filterOnly)
.path("experimentTemplate").path("id").asText();
assertEquals(1, service.getExperimentTemplate(REGION, filterOnlyId)
.path("experimentTemplate").path("targets").path("instances").path("filters").size());
ObjectNode valid = ec2Template("PERCENT(50)");
ObjectNode validTarget = (ObjectNode) valid.path("targets").path("instances");
validTarget.remove("resourceArns");
validTarget.putObject("resourceTags").put("environment", "test");
validTarget.set("filters", mapper.readTree("""
[{"path":"State.Name","values":["running","stopped"]}]
"""));
service.createExperimentTemplate(REGION, valid);
ObjectNode missingFilterPath = ec2Template("ALL");
ObjectNode missingPathTarget = (ObjectNode) missingFilterPath.path("targets").path("instances");
missingPathTarget.remove("resourceArns");
missingPathTarget.putObject("resourceTags").put("environment", "test");
missingPathTarget.set("filters", mapper.readTree("""
[{"values":["running"]}]
"""));
assertValidation(() -> service.createExperimentTemplate(REGION, missingFilterPath));
ObjectNode unknownActionParameter = ec2Template("ALL");
((ObjectNode) unknownActionParameter.path("actions").path("stop"))
.putObject("parameters").put("notSupported", "value");
assertValidation(() -> service.createExperimentTemplate(REGION, unknownActionParameter));
ObjectNode unknownTargetParameter = ec2Template("ALL");
((ObjectNode) unknownTargetParameter.path("targets").path("instances"))
.putObject("parameters").put("notSupported", "value");
assertValidation(() -> service.createExperimentTemplate(REGION, unknownTargetParameter));
ObjectNode arnsAndFilters = ec2Template("ALL");
((ObjectNode) arnsAndFilters.path("targets").path("instances")).set("filters", mapper.readTree("""
[{"path":"State.Name","values":["running"]}]
"""));
assertValidation(() -> service.createExperimentTemplate(REGION, arnsAndFilters));
}
@Test
void percentSelectionRoundsDown() throws Exception {
ObjectNode request = ec2Template("PERCENT(50)");
String templateId = service.createExperimentTemplate(REGION, request)
.path("experimentTemplate").path("id").asText();
String experimentId = service.startExperiment(REGION, mapper.readTree("""
{"clientToken":"%s","experimentTemplateId":"%s","experimentOptions":{"actionsMode":"skip-all"}}
""".formatted(UUID.randomUUID(), templateId)))
.path("experiment").path("id").asText();
assertEquals(2, service.listExperimentResolvedTargets(REGION, experimentId, 100, null, null)
.path("resolvedTargets").size());
}
@Test
void countSelectionSamplesArnsInsteadOfTakingRequestOrder() throws Exception {
RegionResolver resolver = new RegionResolver(REGION, ACCOUNT_ID);
service = new FisService(
FisStores.inMemory(), mapper, resolver, catalog, new Random(12345L));
ObjectNode request = ec2Template("COUNT(1)");
String firstArn = request.path("targets").path("instances")
.path("resourceArns").path(0).asText();
String templateId = service.createExperimentTemplate(REGION, request)
.path("experimentTemplate").path("id").asText();
String experimentId = service.startExperiment(REGION, mapper.readTree("""
{"clientToken":"%s","experimentTemplateId":"%s","experimentOptions":{"actionsMode":"skip-all"}}
""".formatted(UUID.randomUUID(), templateId)))
.path("experiment").path("id").asText();
JsonNode resolved = service.listExperimentResolvedTargets(
REGION, experimentId, 100, null, "instances").path("resolvedTargets");
assertEquals(1, resolved.size());
assertNotEquals(firstArn, resolved.path(0).path("targetInformation").path("arn").asText());
}
@Test
void rejectsOversizedCountAndFailsUnresolvedArnTargetsEvenInSkipMode() throws Exception {
ObjectNode oversizedCount = ec2Template("COUNT(99999999999999999999)");
assertValidation(() -> service.createExperimentTemplate(REGION, oversizedCount));
ObjectNode unresolvedArn = ec2Template("PERCENT(5)");
unresolvedArn.putObject("experimentOptions").put("emptyTargetResolutionMode", "skip");
String templateId = service.createExperimentTemplate(REGION, unresolvedArn)
.path("experimentTemplate").path("id").asText();
ObjectNode experiment = service.startExperiment(REGION, mapper.readTree("""
{"clientToken":"%s","experimentTemplateId":"%s"}
""".formatted(UUID.randomUUID(), templateId)))
.path("experiment").deepCopy();
assertEquals("failed", experiment.path("state").path("status").asText());
assertEquals("failed", experiment.path("actions").path("stop")
.path("state").path("status").asText());
assertTrue(service.listExperimentResolvedTargets(REGION, experiment.path("id").asText(),
100, null, null).path("resolvedTargets").isEmpty());
}
@Test
void enforcesActionSpecificTargetSelectionMethods() throws Exception {
ObjectNode podArns = eksPodTemplate();
((ObjectNode) podArns.path("targets").path("pods"))
.putArray("resourceArns")
.add("arn:aws:eks:us-east-1:000000000000:pod/test");
assertValidation(() -> service.createExperimentTemplate(REGION, podArns));
ObjectNode podTags = eksPodTemplate();
((ObjectNode) podTags.path("targets").path("pods"))
.putObject("resourceTags").put("environment", "test");
assertValidation(() -> service.createExperimentTemplate(REGION, podTags));
ObjectNode podFilters = eksPodTemplate();
((ObjectNode) podFilters.path("targets").path("pods")).set("filters", mapper.readTree("""
[{"path":"Status.Phase","values":["Running"]}]
"""));
assertValidation(() -> service.createExperimentTemplate(REGION, podFilters));
service.createExperimentTemplate(REGION, eksCustomResourceTemplate(false));
ObjectNode multipleClusters = eksCustomResourceTemplate(false);
((ArrayNode) multipleClusters.path("targets").path("cluster").path("resourceArns"))
.add("arn:aws:eks:us-east-1:000000000000:cluster/second");
assertValidation(() -> service.createExperimentTemplate(REGION, multipleClusters));
ObjectNode clusterTags = eksCustomResourceTemplate(true);
assertValidation(() -> service.createExperimentTemplate(REGION, clusterTags));
service.createExperimentTemplate(REGION, s3PauseReplicationTemplate(true));
ObjectNode bucketArn = s3PauseReplicationTemplate(false);
assertValidation(() -> service.createExperimentTemplate(REGION, bucketArn));
ObjectNode bucketFilters = s3PauseReplicationTemplate(true);
((ObjectNode) bucketFilters.path("targets").path("buckets")).set("filters", mapper.readTree("""
[{"path":"Name","values":["source-bucket"]}]
"""));
assertValidation(() -> service.createExperimentTemplate(REGION, bucketFilters));
service.createExperimentTemplate(REGION, ec2InsufficientCapacityTemplate(false));
ObjectNode roleTags = ec2InsufficientCapacityTemplate(true);
assertValidation(() -> service.createExperimentTemplate(REGION, roleTags));
}
@Test
void validatesLogConfigurationSmithyShapes() throws Exception {
ObjectNode missingVersion = waitTemplate(false);
missingVersion.putObject("logConfiguration");
assertValidation(() -> service.createExperimentTemplate(REGION, missingVersion));
ObjectNode fractionalVersion = waitTemplate(false);
fractionalVersion.putObject("logConfiguration").put("logSchemaVersion", 1.5);
assertValidation(() -> service.createExperimentTemplate(REGION, fractionalVersion));
ObjectNode valid = waitTemplate(false);
ObjectNode validLogConfiguration = valid.putObject("logConfiguration");
validLogConfiguration.put("logSchemaVersion", 2);
validLogConfiguration.putObject("cloudWatchLogsConfiguration")
.put("logGroupArn", "arn:aws:logs:us-east-1:000000000000:log-group:fis-logs");
validLogConfiguration.putObject("s3Configuration")
.put("bucketName", "fis-log-bucket")
.put("prefix", "experiment logs/");
String templateId = service.createExperimentTemplate(REGION, valid)
.path("experimentTemplate").path("id").asText();
ObjectNode emptyUpdate = mapper.createObjectNode();
emptyUpdate.putObject("logConfiguration");
assertTrue(service.updateExperimentTemplate(REGION, templateId, emptyUpdate)
.path("experimentTemplate").path("logConfiguration").isEmpty());
ObjectNode missingLogGroupArn = mapper.createObjectNode();
missingLogGroupArn.putObject("logConfiguration").putObject("cloudWatchLogsConfiguration");
assertValidation(() -> service.updateExperimentTemplate(REGION, templateId, missingLogGroupArn));
ObjectNode emptyPrefix = mapper.createObjectNode();
emptyPrefix.putObject("logConfiguration").putObject("s3Configuration")
.put("bucketName", "fis-log-bucket")
.put("prefix", "");
assertValidation(() -> service.updateExperimentTemplate(REGION, templateId, emptyPrefix));
}
@Test
void validatesExperimentReportConfigurationSmithyShapes() throws Exception {
ObjectNode valid = waitTemplate(false);
ObjectNode report = valid.putObject("experimentReportConfiguration");
report.put("preExperimentDuration", "PT5M");
report.put("postExperimentDuration", "PT10M");
report.putObject("outputs").putObject("s3Configuration")
.put("bucketName", "fis-report-bucket")
.put("prefix", "reports/fis");
report.putObject("dataSources").putArray("cloudWatchDashboards")
.addObject().put("dashboardIdentifier",
"arn:aws:cloudwatch::000000000000:dashboard/fis-dashboard");
String templateId = service.createExperimentTemplate(REGION, valid)
.path("experimentTemplate").path("id").asText();
assertEquals("PT5M", service.getExperimentTemplate(REGION, templateId)
.path("experimentTemplate").path("experimentReportConfiguration")
.path("preExperimentDuration").asText());
ObjectNode validUpdate = mapper.createObjectNode();
validUpdate.putObject("experimentReportConfiguration")
.put("postExperimentDuration", "PT15M")
.putObject("dataSources").putArray("cloudWatchDashboards").addObject();
assertEquals("PT15M", service.updateExperimentTemplate(REGION, templateId, validUpdate)
.path("experimentTemplate").path("experimentReportConfiguration")
.path("postExperimentDuration").asText());
ObjectNode spacedDuration = waitTemplate(false);
spacedDuration.putObject("experimentReportConfiguration")
.put("preExperimentDuration", "PT1 M");
assertValidation(() -> service.createExperimentTemplate(REGION, spacedDuration));
ObjectNode longDuration = waitTemplate(false);
longDuration.putObject("experimentReportConfiguration")
.put("postExperimentDuration", "x".repeat(33));
assertValidation(() -> service.createExperimentTemplate(REGION, longDuration));
ObjectNode shortBucket = waitTemplate(false);
shortBucket.putObject("experimentReportConfiguration")
.putObject("outputs").putObject("s3Configuration").put("bucketName", "ab");
assertValidation(() -> service.createExperimentTemplate(REGION, shortBucket));
ObjectNode emptyPrefix = waitTemplate(false);
emptyPrefix.putObject("experimentReportConfiguration")
.putObject("outputs").putObject("s3Configuration").put("prefix", "");
assertValidation(() -> service.createExperimentTemplate(REGION, emptyPrefix));
ObjectNode dashboardsObject = waitTemplate(false);
dashboardsObject.putObject("experimentReportConfiguration")
.putObject("dataSources").putObject("cloudWatchDashboards");
assertValidation(() -> service.createExperimentTemplate(REGION, dashboardsObject));
ObjectNode dashboardString = waitTemplate(false);
dashboardString.putObject("experimentReportConfiguration")
.putObject("dataSources").putArray("cloudWatchDashboards").add("not-an-object");
assertValidation(() -> service.createExperimentTemplate(REGION, dashboardString));
}
@Test
void validatesModeledActionNameArnAndStopConditionStrings() throws Exception {
ObjectNode spacedParameter = waitTemplate(false);
((ObjectNode) spacedParameter.path("actions").path("wait"))
.putObject("parameters").put("duration", "PT1 M");
assertValidation(() -> service.createExperimentTemplate(REGION, spacedParameter));
ObjectNode oversizedParameter = waitTemplate(false);
((ObjectNode) oversizedParameter.path("actions").path("wait"))
.putObject("parameters").put("duration", "x".repeat(1025));
assertValidation(() -> service.createExperimentTemplate(REGION, oversizedParameter));
ObjectNode emptyDescription = waitTemplate(false);
((ObjectNode) emptyDescription.path("actions").path("wait")).put("description", "");
assertValidation(() -> service.createExperimentTemplate(REGION, emptyDescription));
ObjectNode spacedActionName = waitTemplate(false);
ObjectNode spacedActions = (ObjectNode) spacedActionName.path("actions");
spacedActions.set("wait action", spacedActions.remove("wait"));
assertValidation(() -> service.createExperimentTemplate(REGION, spacedActionName));
ObjectNode spacedTargetName = ec2Template("ALL");
ObjectNode spacedTargets = (ObjectNode) spacedTargetName.path("targets");
spacedTargets.set("target one", spacedTargets.remove("instances"));
((ObjectNode) spacedTargetName.path("actions").path("stop").path("targets"))
.put("Instances", "target one");
assertValidation(() -> service.createExperimentTemplate(REGION, spacedTargetName));
ObjectNode shortArn = ec2Template("ALL");
((ArrayNode) shortArn.path("targets").path("instances").path("resourceArns"))
.removeAll().add("x".repeat(19));
assertValidation(() -> service.createExperimentTemplate(REGION, shortArn));
ObjectNode spacedArn = ec2Template("ALL");
((ArrayNode) spacedArn.path("targets").path("instances").path("resourceArns"))
.removeAll().add("arn:aws:ec2:us-east-1:000000000000:instance/i bad");
assertValidation(() -> service.createExperimentTemplate(REGION, spacedArn));
ObjectNode shortStopValue = waitTemplate(false);
((ObjectNode) shortStopValue.path("stopConditions").path(0)).put("value", "x".repeat(19));
assertValidation(() -> service.createExperimentTemplate(REGION, shortStopValue));
}
@Test
void validatesRoleArnAndUsesModeledSafetyReasonShape() throws Exception {
ObjectNode spacedRoleArn = waitTemplate(false);
spacedRoleArn.put("roleArn", "arn:aws:iam::000000000000:role/fis role");
assertValidation(() -> service.createExperimentTemplate(REGION, spacedRoleArn));
ObjectNode emptyReason = service.updateSafetyLeverState(REGION, "default", mapper.readTree("""
{"state":{"status":"engaged","reason":""}}
"""));
assertEquals("", emptyReason.path("safetyLever").path("state").path("reason").asText());
String longReason = "x".repeat(1024);
ObjectNode longReasonResponse = service.updateSafetyLeverState(REGION, "default", mapper.readTree("""
{"state":{"status":"disengaged","reason":"%s"}}
""".formatted(longReason)));
assertEquals(longReason, longReasonResponse.path("safetyLever").path("state").path("reason").asText());
assertValidation(() -> service.updateSafetyLeverState(
REGION, "default", mapper.readTree("""
{"state":{"status":"engaged"}}
""")));
assertValidation(() -> service.updateSafetyLeverState(
REGION, "default", mapper.readTree("""
{"state":{"status":"engaged","reason":1}}
""")));
}
@Test
void validatesModeledTokensAndListFilters() throws Exception {
ObjectNode spacedToken = waitTemplate(false);
spacedToken.put("clientToken", "token with spaces");
assertValidation(() -> service.createExperimentTemplate(REGION, spacedToken));
assertValidation(() -> service.listActions(REGION, 100, ""));
assertValidation(() -> service.listExperiments(REGION, 100, null, "template id"));
String templateId = service.createExperimentTemplate(REGION, waitTemplate(false))
.path("experimentTemplate").path("id").asText();
String experimentId = service.startExperiment(REGION, mapper.readTree("""
{"clientToken":"%s","experimentTemplateId":"%s","experimentOptions":{"actionsMode":"skip-all"}}
""".formatted(UUID.randomUUID(), templateId)))
.path("experiment").path("id").asText();
assertValidation(() -> service.listExperimentResolvedTargets(
REGION, experimentId, 100, null, "target name"));
}
@Test
void enforcesTemplateAndTargetAccountQuotasAndMultiAccountStartRequirement() throws Exception {
ObjectNode tooManyActions = waitTemplate(false);
ObjectNode actions = (ObjectNode) tooManyActions.path("actions");
actions.removeAll();
for (int index = 0; index < 21; index++) {
ObjectNode action = actions.putObject("wait" + index);
action.put("actionId", "aws:fis:wait");
action.putObject("parameters").put("duration", "PT1M");
}
assertQuota(() -> service.createExperimentTemplate(REGION, tooManyActions));
ObjectNode tooManyStopConditions = waitTemplate(false);
ArrayNode stopConditions = (ArrayNode) tooManyStopConditions.path("stopConditions");
stopConditions.removeAll();
for (int index = 0; index < 6; index++) {
stopConditions.addObject().put("source", "none");
}
assertQuota(() -> service.createExperimentTemplate(REGION, tooManyStopConditions));
ObjectNode noTargetAccount = waitTemplate(true);
String noTargetAccountId = service.createExperimentTemplate(REGION, noTargetAccount)
.path("experimentTemplate").path("id").asText();
assertValidation(() -> service.startExperiment(REGION, mapper.readTree("""
{"clientToken":"%s","experimentTemplateId":"%s"}
""".formatted(UUID.randomUUID(), noTargetAccountId))));
ObjectNode targetAccountQuota = waitTemplate(true);
String templateId = service.createExperimentTemplate(REGION, targetAccountQuota)
.path("experimentTemplate").path("id").asText();
for (int index = 0; index < 40; index++) {
String accountId = "%012d".formatted(index + 1L);
service.createTargetAccountConfiguration(REGION, templateId, accountId, mapper.readTree("""
{"roleArn":"arn:aws:iam::%s:role/fis-target-role"}
""".formatted(accountId)));
}
AwsException quota = assertThrows(AwsException.class,
() -> service.createTargetAccountConfiguration(
REGION, templateId, "000000000041", mapper.readTree("""
{"roleArn":"arn:aws:iam::000000000041:role/fis-target-role"}
""")));
assertEquals("ServiceQuotaExceededException", quota.getErrorCode());
assertEquals(402, quota.getHttpStatus());
}
@Test
void enforcesExperimentTemplateQuotaWithoutBreakingIdempotency() throws Exception {
ObjectNode firstRequest = waitTemplate(false);
ObjectNode firstResponse = service.createExperimentTemplate(REGION, firstRequest);
String firstId = firstResponse.path("experimentTemplate").path("id").asText();
for (int index = 1; index < 500; index++) {
service.createExperimentTemplate(REGION, waitTemplate(false));
}
assertEquals(firstId, service.createExperimentTemplate(REGION, firstRequest)
.path("experimentTemplate").path("id").asText());
ObjectNode rejected = waitTemplate(false);
assertQuota(() -> service.createExperimentTemplate(REGION, rejected));
service.deleteExperimentTemplate(REGION, firstId);
service.createExperimentTemplate(REGION, rejected);
}
@Test
void enforcesActiveExperimentQuotaAndReleasesStoppedCapacity() throws Exception {
String templateId = service.createExperimentTemplate(REGION, ec2Template("ALL"))
.path("experimentTemplate").path("id").asText();
List<String> experimentIds = new ArrayList<>();
for (int index = 0; index < 5; index++) {
ObjectNode experiment = service.startExperiment(REGION, mapper.readTree("""
{"clientToken":"%s","experimentTemplateId":"%s"}
""".formatted(UUID.randomUUID(), templateId))).path("experiment").deepCopy();
assertEquals("running", experiment.path("state").path("status").asText());
experimentIds.add(experiment.path("id").asText());
}
ObjectNode rejected = (ObjectNode) mapper.readTree("""
{"clientToken":"%s","experimentTemplateId":"%s"}
""".formatted(UUID.randomUUID(), templateId));
assertQuota(() -> service.startExperiment(REGION, rejected));
service.stopExperiment(REGION, experimentIds.getFirst());
assertEquals("running", service.startExperiment(REGION, rejected)
.path("experiment").path("state").path("status").asText());
}
@Test
void enforcesMaximumAntichainForParallelActionQuota() throws Exception {
ObjectNode tenIndependent = waitTemplate(false);
setWaitActions(tenIndependent, 10, false);
String validTemplateId = service.createExperimentTemplate(REGION, tenIndependent)
.path("experimentTemplate").path("id").asText();
ObjectNode elevenIndependent = waitTemplate(false);
setWaitActions(elevenIndependent, 11, false);
assertQuota(() -> service.createExperimentTemplate(REGION, elevenIndependent));
ObjectNode overwideUpdate = mapper.createObjectNode();
overwideUpdate.set("actions", elevenIndependent.path("actions").deepCopy());
assertQuota(() -> service.updateExperimentTemplate(REGION, validTemplateId, overwideUpdate));
assertEquals(10, service.getExperimentTemplate(REGION, validTemplateId)
.path("experimentTemplate").path("actions").size());
ObjectNode twentySequential = waitTemplate(false);
setWaitActions(twentySequential, 20, true);
service.createExperimentTemplate(REGION, twentySequential);
ObjectNode staggered = waitTemplate(false);
ObjectNode staggeredActions = (ObjectNode) staggered.path("actions");
staggeredActions.removeAll();
addWaitAction(staggeredActions, "a");
for (int index = 1; index <= 9; index++) {
addWaitAction(staggeredActions, "d" + index);
}
addWaitAction(staggeredActions, "b", "a");
addWaitAction(staggeredActions, "c", "a");
assertQuota(() -> service.createExperimentTemplate(REGION, staggered));
}
private ObjectNode ec2Template(String selectionMode) throws Exception {
return (ObjectNode) mapper.readTree("""
{
"clientToken":"%s",
"description":"EC2 target template",
"roleArn":"%s",
"stopConditions":[{"source":"none"}],
"targets":{
"instances":{
"resourceType":"aws:ec2:instance",
"resourceArns":[
"arn:aws:ec2:us-east-1:000000000000:instance/i-00000000000000001",
"arn:aws:ec2:us-east-1:000000000000:instance/i-00000000000000002",
"arn:aws:ec2:us-east-1:000000000000:instance/i-00000000000000003",
"arn:aws:ec2:us-east-1:000000000000:instance/i-00000000000000004",
"arn:aws:ec2:us-east-1:000000000000:instance/i-00000000000000005"
],
"selectionMode":"%s"
}
},
"actions":{
"stop":{
"actionId":"aws:ec2:stop-instances",
"targets":{"Instances":"instances"}
}
}
}
""".formatted(UUID.randomUUID(), ROLE_ARN, selectionMode));
}
private ObjectNode eksPodTemplate() throws Exception {
return (ObjectNode) mapper.readTree("""
{
"clientToken":"%s",
"description":"parameter target",
"roleArn":"%s",
"stopConditions":[{"source":"none"}],
"targets":{
"pods":{
"resourceType":"aws:eks:pod",
"parameters":{
"clusterIdentifier":"cluster-one",
"namespace":"default",
"selectorType":"labelSelector",
"selectorValue":"app=test"
},
"selectionMode":"COUNT(1)"
}
},
"actions":{
"delete":{
"actionId":"aws:eks:pod-delete",
"parameters":{"kubernetesServiceAccount":"fis-service-account"},
"targets":{"Pods":"pods"}
}
},
"experimentOptions":{"emptyTargetResolutionMode":"skip"}
}
""".formatted(UUID.randomUUID(), ROLE_ARN));
}
private ObjectNode waitTemplate(boolean multiAccount) throws Exception {
String options = multiAccount
? ",\"experimentOptions\":{\"accountTargeting\":\"multi-account\"}"
: "";
return (ObjectNode) mapper.readTree("""
{
"clientToken":"%s",
"description":"wait template",
"roleArn":"%s",
"stopConditions":[{"source":"none"}],
"targets":{},
"actions":{"wait":{"actionId":"aws:fis:wait","parameters":{"duration":"PT1M"}}}%s
}
""".formatted(UUID.randomUUID(), ROLE_ARN, options));
}
private ObjectNode eksCustomResourceTemplate(boolean tags) throws Exception {
ObjectNode request = (ObjectNode) mapper.readTree("""
{
"clientToken":"%s",
"description":"EKS custom resource template",
"roleArn":"%s",
"stopConditions":[{"source":"none"}],
"targets":{
"cluster":{
"resourceType":"aws:eks:cluster",
"resourceArns":["arn:aws:eks:us-east-1:000000000000:cluster/test"],
"selectionMode":"ALL"
}
},
"actions":{
"custom":{
"actionId":"aws:eks:inject-kubernetes-custom-resource",
"parameters":{
"kubernetesApiVersion":"chaos-mesh.org/v1alpha1",
"kubernetesKind":"AWSChaos",
"kubernetesNamespace":"default",
"kubernetesSpec":"{}",
"maxDuration":"PT1M"
},
"targets":{"Cluster":"cluster"}
}
}
}
""".formatted(UUID.randomUUID(), ROLE_ARN));
if (tags) {
ObjectNode target = (ObjectNode) request.path("targets").path("cluster");
target.remove("resourceArns");
target.putObject("resourceTags").put("environment", "test");
}
return request;
}
private ObjectNode s3PauseReplicationTemplate(boolean tags) throws Exception {
ObjectNode request = (ObjectNode) mapper.readTree("""
{
"clientToken":"%s",
"description":"S3 replication template",
"roleArn":"%s",
"stopConditions":[{"source":"none"}],
"targets":{
"buckets":{
"resourceType":"aws:s3:bucket",
"resourceArns":["arn:aws:s3:::source-bucket"],
"selectionMode":"ALL"
}
},
"actions":{
"pause":{
"actionId":"aws:s3:bucket-pause-replication",
"parameters":{"duration":"PT1M","region":"us-east-1"},
"targets":{"Buckets":"buckets"}
}
}
}
""".formatted(UUID.randomUUID(), ROLE_ARN));
if (tags) {
ObjectNode target = (ObjectNode) request.path("targets").path("buckets");
target.remove("resourceArns");
target.putObject("resourceTags").put("environment", "test");
}
return request;
}
private ObjectNode ec2InsufficientCapacityTemplate(boolean tags) throws Exception {
ObjectNode request = (ObjectNode) mapper.readTree("""
{
"clientToken":"%s",
"description":"EC2 insufficient capacity template",
"roleArn":"%s",
"stopConditions":[{"source":"none"}],
"targets":{
"roles":{
"resourceType":"aws:iam:role",
"resourceArns":["%s"],
"selectionMode":"ALL"
}
},
"actions":{
"inject":{
"actionId":"aws:ec2:api-insufficient-instance-capacity-error",
"parameters":{
"duration":"PT1M",
"availabilityZoneIdentifiers":"us-east-1a",
"percentage":"100"
},
"targets":{"Roles":"roles"}
}
}
}
""".formatted(UUID.randomUUID(), ROLE_ARN, ROLE_ARN));
if (tags) {
ObjectNode target = (ObjectNode) request.path("targets").path("roles");
target.remove("resourceArns");
target.putObject("resourceTags").put("environment", "test");
}
return request;
}
private void setWaitActions(ObjectNode request, int count, boolean sequential) {
ObjectNode actions = (ObjectNode) request.path("actions");
actions.removeAll();
for (int index = 0; index < count; index++) {
if (sequential && index > 0) {
addWaitAction(actions, "wait" + index, "wait" + (index - 1));
} else {
addWaitAction(actions, "wait" + index);
}
}
}
private void addWaitAction(ObjectNode actions, String name, String... startAfter) {
ObjectNode action = actions.putObject(name);
action.put("actionId", "aws:fis:wait");
action.putObject("parameters").put("duration", "PT1M");
if (startAfter.length > 0) {
ArrayNode dependencies = action.putArray("startAfter");
for (String dependency : startAfter) {
dependencies.add(dependency);
}
}
}
private void assertRequired(ObjectNode catalogEntry, String parameter, boolean expected) {
assertEquals(expected,
catalogEntry.path("parameters").path(parameter).path("required").asBoolean(),
parameter);
assertFalse(catalogEntry.path("parameters").path(parameter).path("description").asText().isBlank());
}
private void assertValidation(ThrowingOperation operation) {
AwsException exception = assertThrows(AwsException.class, operation::run);
assertEquals("ValidationException", exception.getErrorCode());
assertEquals(400, exception.getHttpStatus());
}
private void assertQuota(ThrowingOperation operation) {
AwsException exception = assertThrows(AwsException.class, operation::run);
assertEquals("ServiceQuotaExceededException", exception.getErrorCode());
assertEquals(402, exception.getHttpStatus());
}
@FunctionalInterface
private interface ThrowingOperation {
void run() throws Exception;
}
}
@@ -0,0 +1,591 @@
package io.github.hectorvent.floci.services.fis;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
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.assertTrue;
@QuarkusTest
class FisIntegrationTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT_ID = "000000000310";
private static final String TARGET_ACCOUNT_ID = "000000000311";
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/fis-role";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void allAwsFisOperationsUseTheRestJsonWireContract() {
String token = UUID.randomUUID().toString();
String createBody = templateBody(token, "FIS integration template");
Response created = jsonRequest(createBody)
.post("/experimentTemplates")
.then()
.statusCode(200)
.body("experimentTemplate.description", equalTo("FIS integration template"))
.body("experimentTemplate.experimentOptions.accountTargeting", equalTo("multi-account"))
.body("experimentTemplate.creationTime", notNullValue())
.extract().response();
String templateId = created.path("experimentTemplate.id");
String templateArn = created.path("experimentTemplate.arn");
assertTrue(templateArn.endsWith("experiment-template/" + templateId));
String idempotentId = jsonRequest(createBody)
.post("/experimentTemplates")
.then()
.statusCode(200)
.extract().path("experimentTemplate.id");
assertEquals(templateId, idempotentId);
jsonRequest(templateBody(token, "conflicting payload"))
.post("/experimentTemplates")
.then()
.statusCode(409)
.body("__type", equalTo("ConflictException"));
awsRequest()
.get("/experimentTemplates/" + templateId)
.then()
.statusCode(200)
.body("experimentTemplate.id", equalTo(templateId));
awsRequest()
.queryParam("maxResults", 1)
.get("/experimentTemplates")
.then()
.statusCode(200)
.body("experimentTemplates.id", hasItem(templateId));
jsonRequest("{\"description\":\"updated template\"}")
.patch("/experimentTemplates/" + templateId)
.then()
.statusCode(200)
.body("experimentTemplate.id", equalTo(templateId))
.body("experimentTemplate.description", equalTo("updated template"));
jsonRequest("""
{"clientToken":"%s","roleArn":"arn:aws:iam::%s:role/target-role","description":"target account"}
""".formatted(UUID.randomUUID(), TARGET_ACCOUNT_ID))
.post("/experimentTemplates/" + templateId
+ "/targetAccountConfigurations/" + TARGET_ACCOUNT_ID)
.then()
.statusCode(200)
.body("targetAccountConfiguration.accountId", equalTo(TARGET_ACCOUNT_ID));
awsRequest()
.get("/experimentTemplates/" + templateId
+ "/targetAccountConfigurations/" + TARGET_ACCOUNT_ID)
.then()
.statusCode(200)
.body("targetAccountConfiguration.description", equalTo("target account"));
awsRequest()
.queryParam("maxResults", 1)
.get("/experimentTemplates/" + templateId + "/targetAccountConfigurations")
.then()
.statusCode(200)
.body("targetAccountConfigurations", hasSize(1))
.body("targetAccountConfigurations[0].accountId", equalTo(TARGET_ACCOUNT_ID));
jsonRequest("{\"description\":\"updated target account\"}")
.patch("/experimentTemplates/" + templateId
+ "/targetAccountConfigurations/" + TARGET_ACCOUNT_ID)
.then()
.statusCode(200)
.body("targetAccountConfiguration.description", equalTo("updated target account"));
awsRequest()
.queryParam("maxResults", 1)
.get("/actions")
.then()
.statusCode(200)
.body("actions", hasSize(1))
.body("nextToken", notNullValue());
awsRequest()
.get("/actions/aws:fis:wait")
.then()
.statusCode(200)
.body("action.id", equalTo("aws:fis:wait"))
.body("action.parameters.duration.required", equalTo(true));
Response resourceTypes = awsRequest()
.queryParam("maxResults", 1)
.get("/targetResourceTypes")
.then()
.statusCode(200)
.body("targetResourceTypes", hasSize(1))
.body("nextToken", notNullValue())
.extract().response();
String resourceType = resourceTypes.path("targetResourceTypes[0].resourceType");
awsRequest()
.get("/targetResourceTypes/" + resourceType)
.then()
.statusCode(200)
.body("targetResourceType.resourceType", equalTo(resourceType));
jsonRequest("{\"tags\":{\"team\":\"resilience\"}}")
.post("/tags/" + templateArn)
.then()
.statusCode(200);
jsonRequest("{\"tags\":{\"invalid\":1}}")
.post("/tags/" + templateArn)
.then()
.statusCode(400)
.header("X-Amzn-Errortype", "ValidationException")
.body("__type", equalTo("ValidationException"));
jsonRequest("{\"tags\":{\"aws:reserved\":\"value\"}}")
.post("/tags/" + templateArn)
.then()
.statusCode(400)
.header("X-Amzn-Errortype", "ValidationException");
jsonRequest("{\"tags\":{\"invalid#key\":\"value\"}}")
.post("/tags/" + templateArn)
.then()
.statusCode(400)
.header("X-Amzn-Errortype", "ValidationException");
awsRequest()
.get("/tags/" + templateArn)
.then()
.statusCode(200)
.body("tags.team", equalTo("resilience"));
awsRequest()
.delete("/tags/" + templateArn)
.then()
.statusCode(200);
awsRequest()
.get("/tags/" + templateArn)
.then()
.statusCode(200)
.body("tags.team", equalTo("resilience"));
awsRequest()
.queryParam("tagKeys", "team")
.delete("/tags/" + templateArn)
.then()
.statusCode(200);
awsRequest()
.get("/tags/" + templateArn)
.then()
.statusCode(200)
.body("tags.team", equalTo(null));
String experimentId = jsonRequest("""
{"clientToken":"%s","experimentTemplateId":"%s","experimentOptions":{"actionsMode":"run-all"},"tags":{"purpose":"compat"}}
""".formatted(UUID.randomUUID(), templateId))
.post("/experiments")
.then()
.statusCode(200)
.body("experiment.experimentTemplateId", equalTo(templateId))
.body("experiment.state.status", equalTo("running"))
.extract().path("experiment.id");
awsRequest()
.get("/experiments/" + experimentId)
.then()
.statusCode(200)
.body("experiment.id", equalTo(experimentId));
awsRequest()
.queryParam("experimentTemplateId", templateId)
.queryParam("maxResults", 100)
.get("/experiments")
.then()
.statusCode(200)
.body("experiments.id", hasItem(experimentId));
awsRequest()
.queryParam("maxResults", 100)
.get("/experiments/" + experimentId + "/resolvedTargets")
.then()
.statusCode(200)
.body("resolvedTargets", hasSize(0));
awsRequest()
.get("/experiments/" + experimentId + "/targetAccountConfigurations")
.then()
.statusCode(200)
.body("targetAccountConfigurations.accountId", hasItem(TARGET_ACCOUNT_ID));
awsRequest()
.get("/experiments/" + experimentId
+ "/targetAccountConfigurations/" + TARGET_ACCOUNT_ID)
.then()
.statusCode(200)
.body("targetAccountConfiguration.accountId", equalTo(TARGET_ACCOUNT_ID));
awsRequest()
.delete("/experiments/" + experimentId)
.then()
.statusCode(200)
.body("experiment.state.status", equalTo("stopped"));
awsRequest()
.get("/safetyLevers/default")
.then()
.statusCode(200)
.body("safetyLever.id", equalTo("default"))
.body("safetyLever.state.status", equalTo("disengaged"));
jsonRequest("{\"state\":{\"status\":\"engaged\",\"reason\":\"integration test\"}}")
.patch("/safetyLevers/default/state")
.then()
.statusCode(200)
.body("safetyLever.state.status", equalTo("engaged"));
String cancelledId = jsonRequest("""
{"clientToken":"%s","experimentTemplateId":"%s","experimentOptions":{"actionsMode":"skip-all"}}
""".formatted(UUID.randomUUID(), templateId))
.post("/experiments")
.then()
.statusCode(200)
.body("experiment.state.status", equalTo("cancelled"))
.extract().path("experiment.id");
assertNotEquals(experimentId, cancelledId);
jsonRequest("{\"state\":{\"status\":\"disengaged\",\"reason\":\"integration complete\"}}")
.patch("/safetyLevers/default/state")
.then()
.statusCode(200)
.body("safetyLever.state.status", equalTo("disengaged"));
awsRequest()
.delete("/experimentTemplates/" + templateId
+ "/targetAccountConfigurations/" + TARGET_ACCOUNT_ID)
.then()
.statusCode(200)
.body("targetAccountConfiguration.accountId", equalTo(TARGET_ACCOUNT_ID));
awsRequest()
.delete("/experimentTemplates/" + templateId)
.then()
.statusCode(200)
.body("experimentTemplate.id", equalTo(templateId));
awsRequest()
.get("/experimentTemplates/" + templateId)
.then()
.statusCode(404)
.header("X-Amzn-Errortype", "ResourceNotFoundException")
.body("__type", equalTo("ResourceNotFoundException"))
.body("message", containsString(templateId));
}
@Test
void paginationAndValidationFailuresUseAwsErrors() {
Response first = awsRequest()
.queryParam("maxResults", 1)
.get("/actions")
.then()
.statusCode(200)
.body("actions", hasSize(1))
.extract().response();
String nextToken = first.path("nextToken");
assertFalse(nextToken.isBlank());
Response second = awsRequest()
.queryParam("maxResults", 1)
.queryParam("nextToken", nextToken)
.get("/actions")
.then()
.statusCode(200)
.body("actions", hasSize(1))
.extract().response();
assertNotEquals(
first.<String>path("actions[0].id"),
second.<String>path("actions[0].id"));
awsRequest()
.queryParam("maxResults", 0)
.get("/actions")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
awsRequest()
.queryParam("nextToken", "not-a-token")
.get("/actions")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
jsonRequest("[]")
.post("/experimentTemplates")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
jsonRequest(templateBody(UUID.randomUUID().toString(), "trailing JSON value") + "\n{}")
.post("/experimentTemplates")
.then()
.statusCode(400)
.header("X-Amzn-Errortype", "ValidationException")
.body("__type", equalTo("ValidationException"));
jsonRequest("{}")
.post("/experimentTemplates")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"));
String filterOnlyTemplateId = jsonRequest("""
{
"clientToken":"%s",
"description":"filter-only target",
"roleArn":"%s",
"stopConditions":[{"source":"none"}],
"targets":{
"instances":{
"resourceType":"aws:ec2:instance",
"filters":[{"path":"State.Name","values":["running"]}],
"selectionMode":"ALL"
}
},
"actions":{
"stop":{
"actionId":"aws:ec2:stop-instances",
"targets":{"Instances":"instances"}
}
}
}
""".formatted(UUID.randomUUID(), ROLE_ARN))
.post("/experimentTemplates")
.then()
.statusCode(200)
.body("experimentTemplate.targets.instances.filters[0].path", equalTo("State.Name"))
.extract().path("experimentTemplate.id");
awsRequest()
.delete("/experimentTemplates/" + filterOnlyTemplateId)
.then()
.statusCode(200);
jsonRequest("""
{
"clientToken":"%s",
"description":"invalid logging template",
"roleArn":"%s",
"stopConditions":[{"source":"none"}],
"targets":{},
"actions":{"wait":{"actionId":"aws:fis:wait","parameters":{"duration":"PT1M"}}},
"logConfiguration":{}
}
""".formatted(UUID.randomUUID(), ROLE_ARN))
.post("/experimentTemplates")
.then()
.statusCode(400)
.header("X-Amzn-Errortype", "ValidationException")
.body("__type", equalTo("ValidationException"));
awsRequest()
.get("/actions/aws:fis:not-real")
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
String missingTemplateArn = "arn:aws:fis:" + REGION + ":" + ACCOUNT_ID
+ ":experiment-template/EXTdoesnotexist";
awsRequest()
.get("/tags/" + missingTemplateArn)
.then()
.statusCode(404)
.header("X-Amzn-Errortype", "ResourceNotFoundException")
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void templatesAreIsolatedByAccountAndRegion() {
String token = UUID.randomUUID().toString();
String body = """
{
"clientToken":"%s",
"description":"isolation template",
"roleArn":"%s",
"stopConditions":[{"source":"none"}],
"targets":{},
"actions":{"wait":{"actionId":"aws:fis:wait","parameters":{"duration":"PT1M"}}}
}
""".formatted(token, ROLE_ARN);
String templateId = jsonRequest(body)
.post("/experimentTemplates")
.then()
.statusCode(200)
.extract().path("experimentTemplate.id");
awsRequest(ACCOUNT_ID, "us-west-2")
.get("/experimentTemplates/" + templateId)
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
awsRequest("000000000399", REGION)
.get("/experimentTemplates/" + templateId)
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
awsRequest()
.delete("/experimentTemplates/" + templateId)
.then()
.statusCode(200);
}
@Test
void experimentsDoNotMutateEmulatedTargetServices() {
String instanceId = null;
String templateId = null;
String experimentId = null;
try {
instanceId = ec2Request()
.formParam("Action", "RunInstances")
.formParam("ImageId", "ami-fis-safety-test")
.formParam("InstanceType", "t3.micro")
.formParam("MinCount", "1")
.formParam("MaxCount", "1")
.post("/")
.then()
.statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
ec2Request()
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", instanceId)
.post("/")
.then()
.statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name",
equalTo("running"));
templateId = jsonRequest("""
{
"clientToken":"%s",
"description":"cross-service safety proof",
"roleArn":"%s",
"stopConditions":[{"source":"none"}],
"targets":{
"instances":{
"resourceType":"aws:ec2:instance",
"resourceArns":["arn:aws:ec2:%s:%s:instance/%s"],
"selectionMode":"ALL"
}
},
"actions":{
"stop":{
"actionId":"aws:ec2:stop-instances",
"targets":{"Instances":"instances"}
}
}
}
""".formatted(UUID.randomUUID(), ROLE_ARN, REGION, ACCOUNT_ID, instanceId))
.post("/experimentTemplates")
.then()
.statusCode(200)
.extract().path("experimentTemplate.id");
experimentId = jsonRequest("""
{"clientToken":"%s","experimentTemplateId":"%s","experimentOptions":{"actionsMode":"run-all"}}
""".formatted(UUID.randomUUID(), templateId))
.post("/experiments")
.then()
.statusCode(200)
.body("experiment.state.status", equalTo("running"))
.body("experiment.state.reason", containsString("safe emulation mode"))
.body("experiment.actions.stop.state.status", equalTo("running"))
.body("experiment.actions.stop.state.reason",
equalTo("The action is running in safe emulation mode."))
.extract().path("experiment.id");
ec2Request()
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", instanceId)
.post("/")
.then()
.statusCode(200)
.body("DescribeInstancesResponse.reservationSet.item.instancesSet.item.instanceState.name",
equalTo("running"));
} finally {
if (experimentId != null) {
awsRequest().delete("/experiments/" + experimentId);
}
if (templateId != null) {
awsRequest().delete("/experimentTemplates/" + templateId);
}
if (instanceId != null) {
ec2Request()
.formParam("Action", "TerminateInstances")
.formParam("InstanceId.1", instanceId)
.post("/");
}
}
}
private static io.restassured.specification.RequestSpecification awsRequest() {
return awsRequest(ACCOUNT_ID, REGION);
}
private static io.restassured.specification.RequestSpecification awsRequest(String accountId, String region) {
return given().header("Authorization", authorization(accountId, region));
}
private static io.restassured.specification.RequestSpecification ec2Request() {
return given().header("Authorization", authorization(ACCOUNT_ID, REGION, "ec2"));
}
private static io.restassured.specification.RequestSpecification jsonRequest(String body) {
return awsRequest().contentType("application/json").body(body);
}
private static String templateBody(String token, String description) {
return """
{
"clientToken":"%s",
"description":"%s",
"roleArn":"%s",
"stopConditions":[{"source":"none"}],
"targets":{},
"actions":{"wait":{"actionId":"aws:fis:wait","parameters":{"duration":"PT1M"}}},
"tags":{"environment":"test"},
"experimentOptions":{"accountTargeting":"multi-account","emptyTargetResolutionMode":"skip"}
}
""".formatted(token, description, ROLE_ARN);
}
private static String authorization() {
return authorization(ACCOUNT_ID, REGION);
}
private static String authorization(String accountId, String region) {
return authorization(accountId, region, "fis");
}
private static String authorization(String accountId, String region, String service) {
return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260820/" + region
+ "/" + service + "/aws4_request";
}
}
@@ -0,0 +1,100 @@
package io.github.hectorvent.floci.services.fis;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.fis.model.Experiment;
import io.github.hectorvent.floci.services.fis.model.ExperimentTemplate;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
class FisModelSerializationTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
void experimentTemplateRoundTripsAwsMemberNamesAndNestedTypes() throws Exception {
JsonNode expected = mapper.readTree("""
{
"id":"EXT123",
"arn":"arn:aws:fis:us-east-1:000000000000:experiment-template/EXT123",
"description":"typed template",
"targets":{"instances":{
"resourceType":"aws:ec2:instance",
"resourceArns":["arn:aws:ec2:us-east-1:000000000000:instance/i-123"],
"resourceTags":{"environment":"test"},
"filters":[{"path":"State.Name","values":["running"]}],
"selectionMode":"ALL",
"parameters":{"availabilityZoneIdentifier":"us-east-1a"}
}},
"actions":{"stop":{
"actionId":"aws:ec2:stop-instances",
"description":"stop one instance",
"parameters":{"startInstancesAfterDuration":"PT1M"},
"targets":{"Instances":"instances"},
"startAfter":["wait"]
}},
"stopConditions":[{"source":"none"}],
"creationTime":1.25,
"lastUpdateTime":2.5,
"roleArn":"arn:aws:iam::000000000000:role/fis-role",
"tags":{"owner":"test"},
"experimentOptions":{
"accountTargeting":"single-account",
"emptyTargetResolutionMode":"fail"
},
"targetAccountConfigurationsCount":0
}
""");
ExperimentTemplate model = mapper.treeToValue(expected, ExperimentTemplate.class);
JsonNode actual = mapper.valueToTree(model);
assertEquals(mapper.writeValueAsString(expected), mapper.writeValueAsString(actual));
assertInstanceOf(
io.github.hectorvent.floci.services.fis.model.ExperimentTemplateTarget.class,
model.getTargets().get("instances"));
assertFalse(actual.has("logConfiguration"));
assertFalse(actual.has("experimentReportConfiguration"));
}
@Test
void experimentRoundTripsRuntimeStateWithoutNullOptionalMembers() throws Exception {
JsonNode expected = mapper.readTree("""
{
"id":"EXP123",
"arn":"arn:aws:fis:us-east-1:000000000000:experiment/EXP123",
"experimentTemplateId":"EXT123",
"roleArn":"arn:aws:iam::000000000000:role/fis-role",
"state":{"status":"running","reason":"safe emulation"},
"targets":{},
"actions":{"wait":{
"actionId":"aws:fis:wait",
"parameters":{"duration":"PT1M"},
"state":{"status":"running","reason":"safe emulation"},
"startTime":3.75
}},
"stopConditions":[{"source":"none"}],
"creationTime":3.5,
"startTime":3.75,
"tags":{},
"experimentOptions":{
"accountTargeting":"single-account",
"emptyTargetResolutionMode":"fail",
"actionsMode":"run-all"
},
"targetAccountConfigurationsCount":0
}
""");
Experiment model = mapper.treeToValue(expected, Experiment.class);
JsonNode actual = mapper.valueToTree(model);
assertEquals(mapper.writeValueAsString(expected), mapper.writeValueAsString(actual));
assertFalse(actual.has("endTime"));
assertFalse(actual.path("state").has("error"));
assertFalse(actual.has("experimentReport"));
}
}
@@ -0,0 +1,245 @@
package io.github.hectorvent.floci.services.fis;
import com.fasterxml.jackson.core.type.TypeReference;
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.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.fis.model.Experiment;
import io.github.hectorvent.floci.services.fis.model.ExperimentTemplate;
import io.github.hectorvent.floci.services.fis.model.IdempotencyRecord;
import io.github.hectorvent.floci.services.fis.model.ResolvedTarget;
import io.github.hectorvent.floci.services.fis.model.SafetyLever;
import io.github.hectorvent.floci.services.fis.model.TargetAccountConfiguration;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.lang.reflect.Proxy;
import java.nio.file.Path;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class FisServicePersistenceTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT_ID = "000000000000";
private static final String ACCOUNT_A = "111111111111";
private static final String ACCOUNT_B = "222222222222";
@Test
void templatesExperimentsAndSafetyLeverSurviveRestart(@TempDir Path directory) throws Exception {
FisService first = newService(directory);
ObjectMapper mapper = new ObjectMapper();
ObjectNode createdTemplate = first.createExperimentTemplate(REGION, mapper.readTree("""
{
"clientToken":"persistence-template-token",
"description":"persistent FIS template",
"roleArn":"arn:aws:iam::000000000000:role/fis-role",
"stopConditions":[{"source":"none"}],
"targets":{"instances":{
"resourceType":"aws:ec2:instance",
"resourceArns":["arn:aws:ec2:us-east-1:000000000000:instance/i-00000000000000001"],
"selectionMode":"ALL"
}},
"actions":{"stop":{
"actionId":"aws:ec2:stop-instances",
"targets":{"Instances":"instances"}
}},
"tags":{"environment":"persistence"},
"experimentOptions":{"accountTargeting":"multi-account"}
}
"""));
String templateId = createdTemplate.path("experimentTemplate").path("id").asText();
String templateArn = createdTemplate.path("experimentTemplate").path("arn").asText();
String targetAccountId = "111111111111";
first.createTargetAccountConfiguration(REGION, templateId, targetAccountId, mapper.readTree("""
{
"roleArn":"arn:aws:iam::111111111111:role/fis-target-role",
"description":"persistent target account"
}
"""));
String actionArn = first.getAction(REGION, "aws:ec2:stop-instances")
.path("action").path("arn").asText();
first.tagResource(REGION, actionArn, Map.of("owner", "persistence-test"));
ObjectNode startedExperiment = first.startExperiment(REGION, mapper.readTree("""
{
"clientToken":"persistence-experiment-token",
"experimentTemplateId":"%s",
"experimentOptions":{"actionsMode":"skip-all"},
"tags":{"purpose":"restart-test"}
}
""".formatted(templateId)));
String experimentId = startedExperiment.path("experiment").path("id").asText();
first.updateSafetyLeverState(REGION, "default", mapper.readTree("""
{"state":{"status":"engaged","reason":"persistence test"}}
"""));
FisStores restartedStores = load(directory, null, ACCOUNT_ID);
FisService restarted = newService(restartedStores, ACCOUNT_ID);
assertInstanceOf(ExperimentTemplate.class, restartedStores.templates.scan(key -> true).get(0));
assertInstanceOf(Experiment.class, restartedStores.experiments.scan(key -> true).get(0));
assertInstanceOf(
TargetAccountConfiguration.class, restartedStores.targetAccounts.scan(key -> true).get(0));
assertInstanceOf(ResolvedTarget.class, restartedStores.resolvedTargets.scan(key -> true).get(0));
assertInstanceOf(SafetyLever.class, restartedStores.safetyLevers.scan(key -> true).get(0));
assertInstanceOf(IdempotencyRecord.class, restartedStores.idempotency.scan(key -> true).get(0));
assertEquals(templateId,
restarted.getExperimentTemplate(REGION, templateId)
.path("experimentTemplate").path("id").asText());
assertEquals("persistence",
restarted.listTags(REGION, templateArn).get("environment"));
assertEquals("persistent target account",
restarted.getTargetAccountConfiguration(REGION, templateId, targetAccountId)
.path("targetAccountConfiguration").path("description").asText());
assertEquals(targetAccountId,
restarted.getExperimentTargetAccountConfiguration(REGION, experimentId, targetAccountId)
.path("targetAccountConfiguration").path("accountId").asText());
assertEquals(1, restarted.listExperimentResolvedTargets(
REGION, experimentId, null, null, null).path("resolvedTargets").size());
assertEquals("persistence-test", restarted.listTags(REGION, actionArn).get("owner"));
assertEquals("completed",
restarted.getExperiment(REGION, experimentId)
.path("experiment").path("state").path("status").asText());
assertEquals("engaged",
restarted.getSafetyLever(REGION, "default")
.path("safetyLever").path("state").path("status").asText());
}
@Test
void templatesTagsAndIdempotencyRemainAccountIsolatedAcrossRestart(
@TempDir Path directory) throws Exception {
ObjectMapper mapper = new ObjectMapper();
RequestContext requestContext = new RequestContext();
requestContext.setRegion(REGION);
Instance<RequestContext> requestContextInstance = requestContextInstance(requestContext);
FisStores firstStores = load(directory, requestContextInstance, ACCOUNT_ID);
FisService firstAccountA = newService(firstStores, ACCOUNT_A);
FisService firstAccountB = newService(firstStores, ACCOUNT_B);
ObjectNode accountARequest = templateRequest(mapper, ACCOUNT_A, "account-a-template");
ObjectNode accountBRequest = templateRequest(mapper, ACCOUNT_B, "account-b-template");
requestContext.setAccountId(ACCOUNT_A);
ObjectNode accountACreated = firstAccountA.createExperimentTemplate(REGION, accountARequest);
String accountATemplateId = accountACreated.path("experimentTemplate").path("id").asText();
String accountATemplateArn = accountACreated.path("experimentTemplate").path("arn").asText();
firstAccountA.tagResource(REGION, accountATemplateArn, Map.of("owner", "account-a"));
requestContext.setAccountId(ACCOUNT_B);
ObjectNode accountBCreated = firstAccountB.createExperimentTemplate(REGION, accountBRequest);
String accountBTemplateId = accountBCreated.path("experimentTemplate").path("id").asText();
String accountBTemplateArn = accountBCreated.path("experimentTemplate").path("arn").asText();
firstAccountB.tagResource(REGION, accountBTemplateArn, Map.of("owner", "account-b"));
assertNotEquals(accountATemplateId, accountBTemplateId);
FisStores restartedStores = load(directory, requestContextInstance, ACCOUNT_ID);
FisService restartedAccountA = newService(restartedStores, ACCOUNT_A);
FisService restartedAccountB = newService(restartedStores, ACCOUNT_B);
requestContext.setAccountId(ACCOUNT_A);
assertEquals(accountATemplateId,
restartedAccountA.createExperimentTemplate(REGION, accountARequest)
.path("experimentTemplate").path("id").asText());
assertEquals("account-a", restartedAccountA.listTags(REGION, accountATemplateArn).get("owner"));
assertEquals(1, restartedAccountA.listExperimentTemplates(REGION, null, null)
.path("experimentTemplates").size());
assertThrows(AwsException.class,
() -> restartedAccountA.getExperimentTemplate(REGION, accountBTemplateId));
requestContext.setAccountId(ACCOUNT_B);
assertEquals(accountBTemplateId,
restartedAccountB.createExperimentTemplate(REGION, accountBRequest)
.path("experimentTemplate").path("id").asText());
assertEquals("account-b", restartedAccountB.listTags(REGION, accountBTemplateArn).get("owner"));
assertEquals(1, restartedAccountB.listExperimentTemplates(REGION, null, null)
.path("experimentTemplates").size());
assertThrows(AwsException.class,
() -> restartedAccountB.getExperimentTemplate(REGION, accountATemplateId));
}
private FisService newService(Path directory) {
return newService(load(directory, null, ACCOUNT_ID), ACCOUNT_ID);
}
private FisService newService(FisStores stores, String accountId) {
ObjectMapper mapper = new ObjectMapper();
RegionResolver regionResolver = new RegionResolver(REGION, accountId);
FisCatalog catalog = new FisCatalog(mapper, regionResolver);
return new FisService(stores, mapper, regionResolver, catalog);
}
private ObjectNode templateRequest(ObjectMapper mapper, String accountId, String description)
throws Exception {
return (ObjectNode) mapper.readTree("""
{
"clientToken":"shared-account-token",
"description":"%s",
"roleArn":"arn:aws:iam::%s:role/fis-role",
"stopConditions":[{"source":"none"}],
"targets":{},
"actions":{"wait":{"actionId":"aws:fis:wait","parameters":{"duration":"PT1M"}}},
"tags":{"createdBy":"persistence-test"}
}
""".formatted(description, accountId));
}
private FisStores load(
Path directory, Instance<RequestContext> requestContextInstance, String defaultAccountId) {
return new FisStores(
load(directory.resolve("fis-experiment-templates.json"),
new TypeReference<Map<String, ExperimentTemplate>>() {},
requestContextInstance, defaultAccountId),
load(directory.resolve("fis-experiments.json"),
new TypeReference<Map<String, Experiment>>() {},
requestContextInstance, defaultAccountId),
load(directory.resolve("fis-target-account-configurations.json"),
new TypeReference<Map<String, TargetAccountConfiguration>>() {},
requestContextInstance, defaultAccountId),
load(directory.resolve("fis-resolved-targets.json"),
new TypeReference<Map<String, ResolvedTarget>>() {},
requestContextInstance, defaultAccountId),
load(directory.resolve("fis-safety-levers.json"),
new TypeReference<Map<String, SafetyLever>>() {},
requestContextInstance, defaultAccountId),
load(directory.resolve("fis-action-tags.json"),
new TypeReference<Map<String, Map<String, String>>>() {},
requestContextInstance, defaultAccountId),
load(directory.resolve("fis-idempotency.json"),
new TypeReference<Map<String, IdempotencyRecord>>() {},
requestContextInstance, defaultAccountId));
}
private <T> StorageBackend<String, T> load(
Path file, TypeReference<Map<String, T>> typeReference,
Instance<RequestContext> requestContextInstance, String defaultAccountId) {
PersistentStorage<String, T> backend = new PersistentStorage<>(file, typeReference);
backend.load();
return new AccountAwareStorageBackend<>(backend, requestContextInstance, defaultAccountId);
}
@SuppressWarnings("unchecked")
private Instance<RequestContext> requestContextInstance(RequestContext requestContext) {
return (Instance<RequestContext>) Proxy.newProxyInstance(
Instance.class.getClassLoader(), new Class<?>[] { Instance.class },
(proxy, method, args) -> {
if ("get".equals(method.getName())) {
return requestContext;
}
throw new UnsupportedOperationException(method.getName());
});
}
}
@@ -46,6 +46,7 @@ class SesConfigurationSetV1IntegrationTest {
.post("/")
.then()
.statusCode(400)
.header("X-Amzn-Errortype", (String) null)
.body(containsString("<Code>ConfigurationSetAlreadyExists</Code>"));
}