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

+4 -3
View File
@@ -178,7 +178,7 @@ LocalStack's community edition [sunset in March 2026](https://blog.localstack.cl
| CodeBuild | Real Docker execution | No |
| Native binary | ~40 MB | No |
**69 AWS services. Broad coverage. Free forever.**
**72 AWS services. Broad coverage. Free forever.**
## Architecture Overview
@@ -190,7 +190,7 @@ flowchart LR
Router["HTTP Router\nJAX-RS / Vert.x"]
subgraph Stateless ["Stateless Services"]
A["SSM · SQS · SNS\nIAM · STS · KMS\nSecrets Manager · SES\nCognito · Kinesis\nEventBridge · Scheduler · AppConfig\nCloudWatch · Step Functions\nCloudFormation · ACM · Config · CloudTrail\nAPI Gateway · AppSync · ELB v2 · Auto Scaling\nElastic Beanstalk · CodeDeploy · CodePipeline · Backup · Bedrock Runtime · Route53 · Transfer"]
A["SSM · SQS · SNS\nIAM · STS · KMS\nSecrets Manager · SES\nCognito · Kinesis\nEventBridge · Scheduler · AppConfig\nCloudWatch · Step Functions\nCloudFormation · ACM · Config · CloudTrail\nAPI Gateway · AppSync · ELB v2 · Auto Scaling\nElastic Beanstalk · CodeDeploy · CodePipeline · Backup · FIS · Bedrock Runtime · Route53 · Transfer"]
end
subgraph Stateful ["Stateful Services"]
@@ -228,7 +228,7 @@ Floci supports local emulation for application services, data services, eventing
| Messaging and transfer | SES, Kinesis, MSK, Amazon MQ, Transfer Family, IoT Core |
| Security and governance | WAF v2, CloudTrail, CloudFront, Resource Groups Tagging API, CloudHSM v2 |
| Cost and billing | Pricing, Cost Explorer, Cost and Usage Reports, BCM Data Exports |
| Backup and config | AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |
| Resilience, backup, and config | AWS FIS, AWS Backup, AWS Config, AppConfig, AppConfigData, CloudFormation, Cloud Control API |
For operation-level compatibility, see the [Services Overview](https://floci.io/floci/services/).
@@ -295,6 +295,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/
| Application Auto Scaling | In-process | Scalable targets, target-tracking and step scaling policies, CloudWatch alarm creation, tagging (policies are stored but inert) |
| Elastic Beanstalk | In-process | Applications, application versions, environments, configuration templates, platform and solution stack metadata |
| AWS Backup | In-process | Vaults, backup plans, selections, simulated job lifecycle, recovery points |
| AWS FIS | In-process | All 26 management APIs for templates, experiments, target accounts, action and target discovery, safety lever, tagging, and pagination; experiment execution is a safe control-plane simulation and does not inject faults into other services |
| AWS Config | In-process | Config rules, configuration recorders, delivery channels, conformance packs, tagging |
| CloudTrail | In-process | Trails, event selectors (S3 data events with bucket/prefix matching), `StartLogging`/`StopLogging`, scheduled gzipped log file emission to the destination bucket at AWS-shaped key paths, IAM-deny path emits `AccessDenied` records |
| CloudFront | In-process | Distributions, origins, cache behaviors, invalidations, tagging |
@@ -0,0 +1,240 @@
#!/usr/bin/env bats
# AWS Fault Injection Service compatibility tests
setup() {
load 'test_helper/common-setup'
TEMPLATE_ID=""
TEMPLATE_ARN=""
EXPERIMENT_ID=""
TARGET_ACCOUNT_CONFIGURATION_EXISTS="false"
}
teardown() {
# The safety lever is account-global, so always restore its safe default even
# when an assertion aborts the lifecycle halfway through.
aws_cmd fis update-safety-lever-state \
--id default \
--state '{"status":"disengaged","reason":"AWS CLI compatibility cleanup"}' \
>/dev/null 2>&1 || true
if [ -n "$EXPERIMENT_ID" ]; then
aws_cmd fis stop-experiment --id "$EXPERIMENT_ID" >/dev/null 2>&1 || true
fi
if [ -n "$TEMPLATE_ID" ] && [ "$TARGET_ACCOUNT_CONFIGURATION_EXISTS" = "true" ]; then
aws_cmd fis delete-target-account-configuration \
--experiment-template-id "$TEMPLATE_ID" \
--account-id 111122223333 >/dev/null 2>&1 || true
fi
if [ -n "$TEMPLATE_ID" ]; then
aws_cmd fis delete-experiment-template --id "$TEMPLATE_ID" >/dev/null 2>&1 || true
fi
}
# This safe lifecycle invokes every AWS FIS management operation. It uses only
# the built-in wait action and starts the experiment with actionsMode=skip-all.
@test "FIS: all management operations use AWS CLI v2 wire shapes" {
local action_id target_resource_type client_token target_account_token
local next_token state template_listed account_listed owner experiment_status
local experiment_listed account_snapshot_listed
action_id="aws:fis:wait"
target_resource_type="aws:ec2:instance"
run aws_cmd fis get-action --id "$action_id"
assert_success
[ "$(json_get "$output" '.action.id')" = "$action_id" ]
[[ "$(json_get "$output" '.action.arn')" =~ :action/aws:fis:wait$ ]]
run aws_cmd fis list-actions --max-results 1
assert_success
[ "$(json_get "$output" '.actions | length')" = "1" ]
next_token=$(json_get "$output" '.nextToken')
[ -n "$next_token" ]
[ "$next_token" != "null" ]
run aws_cmd fis list-actions --max-results 1 --next-token "$next_token"
assert_success
[ "$(json_get "$output" '.actions | length')" = "1" ]
run aws_cmd fis get-target-resource-type --resource-type "$target_resource_type"
assert_success
[ "$(json_get "$output" '.targetResourceType.resourceType')" = "$target_resource_type" ]
run aws_cmd fis list-target-resource-types --max-results 1
assert_success
[ "$(json_get "$output" '.targetResourceTypes | length')" = "1" ]
next_token=$(json_get "$output" '.nextToken')
[ -n "$next_token" ]
[ "$next_token" != "null" ]
run aws_cmd fis list-target-resource-types --max-results 1 --next-token "$next_token"
assert_success
[ "$(json_get "$output" '.targetResourceTypes | length')" = "1" ]
run aws_cmd fis get-safety-lever --id default
assert_success
[ "$(json_get "$output" '.safetyLever.id')" = "default" ]
run aws_cmd fis update-safety-lever-state \
--id default \
--state '{"status":"engaged","reason":"AWS CLI compatibility test"}'
assert_success
[ "$(json_get "$output" '.safetyLever.state.status')" = "engaged" ]
run aws_cmd fis update-safety-lever-state \
--id default \
--state '{"status":"disengaged","reason":"AWS CLI compatibility test ready"}'
assert_success
[ "$(json_get "$output" '.safetyLever.state.status')" = "disengaged" ]
client_token=$(unique_name fis-cli-template)
run aws_cmd fis create-experiment-template \
--client-token "$client_token" \
--description "AWS CLI compatibility template" \
--stop-conditions '[{"source":"none"}]' \
--actions '{"wait":{"actionId":"aws:fis:wait","parameters":{"duration":"PT1M"}}}' \
--role-arn "arn:aws:iam::000000000000:role/fis-cli-role" \
--tags '{"suite":"awscli"}' \
--experiment-options '{"accountTargeting":"multi-account","emptyTargetResolutionMode":"skip"}'
assert_success
TEMPLATE_ID=$(json_get "$output" '.experimentTemplate.id')
TEMPLATE_ARN=$(json_get "$output" '.experimentTemplate.arn')
[ -n "$TEMPLATE_ID" ]
[[ "$TEMPLATE_ARN" =~ :experiment-template/${TEMPLATE_ID}$ ]]
[ "$(json_get "$output" '.experimentTemplate.tags.suite')" = "awscli" ]
run aws_cmd fis get-experiment-template --id "$TEMPLATE_ID"
assert_success
[ "$(json_get "$output" '.experimentTemplate.id')" = "$TEMPLATE_ID" ]
run aws_cmd fis update-experiment-template \
--id "$TEMPLATE_ID" \
--description "Updated through AWS CLI v2"
assert_success
[ "$(json_get "$output" '.experimentTemplate.description')" = "Updated through AWS CLI v2" ]
run aws_cmd fis list-experiment-templates --max-results 100
assert_success
template_listed=$(echo "$output" | jq --arg id "$TEMPLATE_ID" \
'.experimentTemplates | any(.id == $id)')
[ "$template_listed" = "true" ]
target_account_token=$(unique_name fis-cli-account)
run aws_cmd fis create-target-account-configuration \
--client-token "$target_account_token" \
--experiment-template-id "$TEMPLATE_ID" \
--account-id 111122223333 \
--role-arn "arn:aws:iam::111122223333:role/fis-cli-target-role" \
--description "AWS CLI target account"
assert_success
TARGET_ACCOUNT_CONFIGURATION_EXISTS="true"
[ "$(json_get "$output" '.targetAccountConfiguration.accountId')" = "111122223333" ]
run aws_cmd fis get-target-account-configuration \
--experiment-template-id "$TEMPLATE_ID" \
--account-id 111122223333
assert_success
[ "$(json_get "$output" '.targetAccountConfiguration.description')" = "AWS CLI target account" ]
run aws_cmd fis update-target-account-configuration \
--experiment-template-id "$TEMPLATE_ID" \
--account-id 111122223333 \
--role-arn "arn:aws:iam::111122223333:role/fis-cli-target-role" \
--description "Updated AWS CLI target account"
assert_success
[ "$(json_get "$output" '.targetAccountConfiguration.description')" = \
"Updated AWS CLI target account" ]
run aws_cmd fis list-target-account-configurations \
--experiment-template-id "$TEMPLATE_ID" \
--max-results 100
assert_success
account_listed=$(echo "$output" | jq \
'.targetAccountConfigurations | any(.accountId == "111122223333")')
[ "$account_listed" = "true" ]
run aws_cmd fis tag-resource \
--resource-arn "$TEMPLATE_ARN" \
--tags '{"owner":"compatibility"}'
assert_success
run aws_cmd fis list-tags-for-resource --resource-arn "$TEMPLATE_ARN"
assert_success
[ "$(json_get "$output" '.tags.suite')" = "awscli" ]
[ "$(json_get "$output" '.tags.owner')" = "compatibility" ]
run aws_cmd fis untag-resource \
--resource-arn "$TEMPLATE_ARN" \
--tag-keys owner
assert_success
run aws_cmd fis list-tags-for-resource --resource-arn "$TEMPLATE_ARN"
assert_success
owner=$(json_get "$output" '.tags.owner // empty')
[ -z "$owner" ]
[ "$(json_get "$output" '.tags.suite')" = "awscli" ]
run aws_cmd fis start-experiment \
--client-token "$(unique_name fis-cli-experiment)" \
--experiment-template-id "$TEMPLATE_ID" \
--experiment-options '{"actionsMode":"skip-all"}' \
--tags '{"mode":"safe-preview"}'
assert_success
EXPERIMENT_ID=$(json_get "$output" '.experiment.id')
[ -n "$EXPERIMENT_ID" ]
[ "$(json_get "$output" '.experiment.experimentTemplateId')" = "$TEMPLATE_ID" ]
[ "$(json_get "$output" '.experiment.experimentOptions.actionsMode')" = "skip-all" ]
experiment_status=$(json_get "$output" '.experiment.state.status')
[[ "$experiment_status" = "running" || "$experiment_status" = "completed" ]]
run aws_cmd fis get-experiment --id "$EXPERIMENT_ID"
assert_success
[ "$(json_get "$output" '.experiment.id')" = "$EXPERIMENT_ID" ]
[ "$(json_get "$output" '.experiment.tags.mode')" = "safe-preview" ]
run aws_cmd fis list-experiments \
--experiment-template-id "$TEMPLATE_ID" \
--max-results 100
assert_success
experiment_listed=$(echo "$output" | jq --arg id "$EXPERIMENT_ID" \
'.experiments | any(.id == $id)')
[ "$experiment_listed" = "true" ]
run aws_cmd fis list-experiment-resolved-targets \
--experiment-id "$EXPERIMENT_ID" \
--max-results 100
assert_success
[ "$(json_get "$output" '.resolvedTargets | length')" = "0" ]
run aws_cmd fis get-experiment-target-account-configuration \
--experiment-id "$EXPERIMENT_ID" \
--account-id 111122223333
assert_success
[ "$(json_get "$output" '.targetAccountConfiguration.accountId')" = "111122223333" ]
run aws_cmd fis list-experiment-target-account-configurations \
--experiment-id "$EXPERIMENT_ID"
assert_success
account_snapshot_listed=$(echo "$output" | jq \
'.targetAccountConfigurations | any(.accountId == "111122223333")')
[ "$account_snapshot_listed" = "true" ]
run aws_cmd fis stop-experiment --id "$EXPERIMENT_ID"
assert_success
state=$(json_get "$output" '.experiment.state.status')
[[ "$state" = "stopped" || "$state" = "completed" ]]
EXPERIMENT_ID=""
run aws_cmd fis delete-target-account-configuration \
--experiment-template-id "$TEMPLATE_ID" \
--account-id 111122223333
assert_success
[ "$(json_get "$output" '.targetAccountConfiguration.accountId')" = "111122223333" ]
TARGET_ACCOUNT_CONFIGURATION_EXISTS="false"
run aws_cmd fis delete-experiment-template --id "$TEMPLATE_ID"
assert_success
[ "$(json_get "$output" '.experimentTemplate.id')" = "$TEMPLATE_ID" ]
TEMPLATE_ID=""
TEMPLATE_ARN=""
}
@@ -258,6 +258,10 @@
<groupId>software.amazon.awssdk</groupId>
<artifactId>rum</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>fis</artifactId>
</dependency>
<!-- GuardDuty client -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
@@ -27,6 +27,7 @@ import software.amazon.awssdk.services.opensearch.OpenSearchClient;
import software.amazon.awssdk.services.neptune.NeptuneClient;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.guardduty.GuardDutyClient;
import software.amazon.awssdk.services.fis.FisClient;
import software.amazon.awssdk.services.rum.RumClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.endpoints.Endpoint;
@@ -720,6 +721,14 @@ public final class TestFixtures {
.build();
}
public static FisClient fisClient() {
return FisClient.builder()
.endpointOverride(ENDPOINT)
.region(REGION)
.credentialsProvider(CREDENTIALS)
.build();
}
public static GuardDutyClient guardDutyClient() {
return GuardDutyClient.builder()
.endpointOverride(ENDPOINT)
@@ -0,0 +1,327 @@
package com.floci.test;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.fis.FisClient;
import software.amazon.awssdk.services.fis.model.AccountTargeting;
import software.amazon.awssdk.services.fis.model.ActionsMode;
import software.amazon.awssdk.services.fis.model.CreateExperimentTemplateActionInput;
import software.amazon.awssdk.services.fis.model.CreateExperimentTemplateStopConditionInput;
import software.amazon.awssdk.services.fis.model.CreateExperimentTemplateTargetInput;
import software.amazon.awssdk.services.fis.model.EmptyTargetResolutionMode;
import software.amazon.awssdk.services.fis.model.ExperimentStatus;
import software.amazon.awssdk.services.fis.model.ResourceNotFoundException;
import software.amazon.awssdk.services.fis.model.SafetyLeverStatus;
import software.amazon.awssdk.services.fis.model.SafetyLeverStatusInput;
import software.amazon.awssdk.services.fis.model.ServiceQuotaExceededException;
import software.amazon.awssdk.services.fis.model.ValidationException;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("AWS Fault Injection Service")
class FisTest {
private static final String ACCOUNT_ID = "111122223333";
private static final String ROLE_ARN =
"arn:aws:iam::000000000000:role/fis-compat-role";
private static final String TARGET_ROLE_ARN =
"arn:aws:iam::" + ACCOUNT_ID + ":role/fis-target-role";
private static final String INSTANCE_ARN =
"arn:aws:ec2:us-east-1:000000000000:instance/i-0123456789abcdef0";
private static final String ACTION_ID = "aws:ec2:stop-instances";
private static final String RESOURCE_TYPE = "aws:ec2:instance";
@Test
void controlPlaneLifecycleUsesAwsSdkWireShapes() {
String templateId = null;
boolean targetAccountConfigurationExists = false;
try (FisClient fis = TestFixtures.fisClient()) {
var action = fis.getAction(request -> request.id(ACTION_ID)).action();
assertThat(action.id()).isEqualTo(ACTION_ID);
assertThat(action.arn()).endsWith("action/" + ACTION_ID);
assertThat(action.targets()).containsKey("Instances");
var firstActionsPage = fis.listActions(request -> request.maxResults(1));
assertThat(firstActionsPage.actions()).hasSize(1);
assertThat(firstActionsPage.nextToken()).isNotBlank();
assertThat(fis.listActions(request -> request
.maxResults(1)
.nextToken(firstActionsPage.nextToken())).actions()).hasSize(1);
Map<String, CreateExperimentTemplateActionInput> overwideActions = new LinkedHashMap<>();
for (int index = 0; index < 11; index++) {
overwideActions.put("wait" + index, CreateExperimentTemplateActionInput.builder()
.actionId("aws:fis:wait")
.parameters(Map.of("duration", "PT1M"))
.build());
}
assertThatThrownBy(() -> fis.createExperimentTemplate(request -> request
.clientToken(TestFixtures.uniqueName("fis-quota"))
.description("FIS parallel action quota")
.roleArn(ROLE_ARN)
.stopConditions(CreateExperimentTemplateStopConditionInput.builder()
.source("none")
.build())
.actions(overwideActions)))
.isInstanceOfSatisfying(ServiceQuotaExceededException.class,
exception -> assertThat(exception.statusCode()).isEqualTo(402));
assertThatThrownBy(() -> fis.createExperimentTemplate(request -> request
.clientToken(TestFixtures.uniqueName("fis-report-validation"))
.description("FIS report validation")
.roleArn(ROLE_ARN)
.stopConditions(CreateExperimentTemplateStopConditionInput.builder()
.source("none")
.build())
.actions(Map.of("wait", CreateExperimentTemplateActionInput.builder()
.actionId("aws:fis:wait")
.parameters(Map.of("duration", "PT1M"))
.build()))
.experimentReportConfiguration(report -> report.outputs(outputs -> outputs
.s3Configuration(s3 -> s3.bucketName("ab"))))))
.isInstanceOfSatisfying(ValidationException.class,
exception -> assertThat(exception.statusCode()).isEqualTo(400));
var targetResourceType = fis.getTargetResourceType(request -> request
.resourceType(RESOURCE_TYPE)).targetResourceType();
assertThat(targetResourceType.resourceType()).isEqualTo(RESOURCE_TYPE);
var firstResourceTypesPage = fis.listTargetResourceTypes(request -> request.maxResults(1));
assertThat(firstResourceTypesPage.targetResourceTypes()).hasSize(1);
assertThat(firstResourceTypesPage.nextToken()).isNotBlank();
assertThat(fis.listTargetResourceTypes(request -> request
.maxResults(1)
.nextToken(firstResourceTypesPage.nextToken())).targetResourceTypes()).hasSize(1);
var initialLever = fis.getSafetyLever(request -> request.id("default")).safetyLever();
assertThat(initialLever.id()).isEqualTo("default");
assertThat(initialLever.arn()).endsWith("safety-lever/default");
var engagedLever = fis.updateSafetyLeverState(request -> request
.id("default")
.state(state -> state
.status(SafetyLeverStatusInput.ENGAGED)
.reason("SDK compatibility test"))).safetyLever();
assertThat(engagedLever.state().status()).isEqualTo(SafetyLeverStatus.ENGAGED);
var disengagedLever = fis.updateSafetyLeverState(request -> request
.id("default")
.state(state -> state
.status(SafetyLeverStatusInput.DISENGAGED)
.reason("SDK compatibility test complete"))).safetyLever();
assertThat(disengagedLever.state().status()).isEqualTo(SafetyLeverStatus.DISENGAGED);
String clientToken = TestFixtures.uniqueName("fis-template");
var createRequest = software.amazon.awssdk.services.fis.model.CreateExperimentTemplateRequest
.builder()
.clientToken(clientToken)
.description("FIS SDK compatibility template")
.roleArn(ROLE_ARN)
.stopConditions(CreateExperimentTemplateStopConditionInput.builder()
.source("none")
.build())
.targets(Map.of("instances", CreateExperimentTemplateTargetInput.builder()
.resourceType(RESOURCE_TYPE)
.resourceArns(INSTANCE_ARN)
.selectionMode("ALL")
.build()))
.actions(Map.of("stopInstances", CreateExperimentTemplateActionInput.builder()
.actionId(ACTION_ID)
.targets(Map.of("Instances", "instances"))
.build()))
.tags(Map.of("suite", "sdk-compat"))
.logConfiguration(log -> log
.logSchemaVersion(2)
.s3Configuration(s3 -> s3
.bucketName("fis-sdk-log-bucket")
.prefix("logs/fis")))
.experimentOptions(options -> options
.accountTargeting(AccountTargeting.MULTI_ACCOUNT)
.emptyTargetResolutionMode(EmptyTargetResolutionMode.SKIP))
.experimentReportConfiguration(report -> report
.preExperimentDuration("PT5M")
.postExperimentDuration("PT10M")
.outputs(outputs -> outputs.s3Configuration(s3 -> s3
.bucketName("fis-sdk-report-bucket")
.prefix("reports/fis")))
.dataSources(dataSources -> dataSources.cloudWatchDashboards(dashboard -> dashboard
.dashboardIdentifier(
"arn:aws:cloudwatch::000000000000:dashboard/fis-sdk"))))
.build();
var createdTemplate = fis.createExperimentTemplate(createRequest).experimentTemplate();
templateId = createdTemplate.id();
String activeTemplateId = templateId;
assertThat(activeTemplateId).isNotBlank();
assertThat(createdTemplate.arn()).endsWith("experiment-template/" + activeTemplateId);
assertThat(createdTemplate.actions()).containsKey("stopInstances");
assertThat(createdTemplate.targets()).containsKey("instances");
assertThat(createdTemplate.tags()).containsEntry("suite", "sdk-compat");
assertThat(createdTemplate.experimentOptions().accountTargeting())
.isEqualTo(AccountTargeting.MULTI_ACCOUNT);
assertThat(createdTemplate.logConfiguration().logSchemaVersion()).isEqualTo(2);
assertThat(createdTemplate.experimentReportConfiguration().preExperimentDuration())
.isEqualTo("PT5M");
assertThat(createdTemplate.experimentReportConfiguration().outputs()
.s3Configuration().bucketName()).isEqualTo("fis-sdk-report-bucket");
assertThat(fis.createExperimentTemplate(createRequest).experimentTemplate().id())
.isEqualTo(activeTemplateId);
var fetchedTemplate = fis.getExperimentTemplate(request -> request.id(activeTemplateId))
.experimentTemplate();
assertThat(fetchedTemplate.id()).isEqualTo(activeTemplateId);
assertThat(fetchedTemplate.creationTime()).isNotNull();
var updatedTemplate = fis.updateExperimentTemplate(request -> request
.id(activeTemplateId)
.description("Updated through the AWS SDK")).experimentTemplate();
assertThat(updatedTemplate.description()).isEqualTo("Updated through the AWS SDK");
assertThat(fis.listExperimentTemplates(request -> request.maxResults(100))
.experimentTemplates())
.anyMatch(template -> activeTemplateId.equals(template.id()));
var createdTargetAccount = fis.createTargetAccountConfiguration(request -> request
.clientToken(TestFixtures.uniqueName("fis-account"))
.experimentTemplateId(activeTemplateId)
.accountId(ACCOUNT_ID)
.roleArn(TARGET_ROLE_ARN)
.description("compatibility target account"))
.targetAccountConfiguration();
targetAccountConfigurationExists = true;
assertThat(createdTargetAccount.accountId()).isEqualTo(ACCOUNT_ID);
assertThat(createdTargetAccount.roleArn()).isEqualTo(TARGET_ROLE_ARN);
var fetchedTargetAccount = fis.getTargetAccountConfiguration(request -> request
.experimentTemplateId(activeTemplateId)
.accountId(ACCOUNT_ID)).targetAccountConfiguration();
assertThat(fetchedTargetAccount.description()).isEqualTo("compatibility target account");
var updatedTargetAccount = fis.updateTargetAccountConfiguration(request -> request
.experimentTemplateId(activeTemplateId)
.accountId(ACCOUNT_ID)
.roleArn(TARGET_ROLE_ARN)
.description("updated compatibility target account"))
.targetAccountConfiguration();
assertThat(updatedTargetAccount.description())
.isEqualTo("updated compatibility target account");
assertThat(fis.listTargetAccountConfigurations(request -> request
.experimentTemplateId(activeTemplateId)
.maxResults(100)).targetAccountConfigurations())
.anyMatch(configuration -> ACCOUNT_ID.equals(configuration.accountId()));
String templateArn = createdTemplate.arn();
fis.tagResource(request -> request
.resourceArn(templateArn)
.tags(Map.of("owner", "compatibility")));
assertThat(fis.listTagsForResource(request -> request.resourceArn(templateArn)).tags())
.containsEntry("suite", "sdk-compat")
.containsEntry("owner", "compatibility");
fis.untagResource(request -> request.resourceArn(templateArn));
assertThat(fis.listTagsForResource(request -> request.resourceArn(templateArn)).tags())
.containsEntry("owner", "compatibility");
fis.untagResource(request -> request.resourceArn(templateArn).tagKeys("owner"));
assertThat(fis.listTagsForResource(request -> request.resourceArn(templateArn)).tags())
.containsEntry("suite", "sdk-compat")
.doesNotContainKey("owner");
var startedExperiment = fis.startExperiment(request -> request
.clientToken(TestFixtures.uniqueName("fis-experiment"))
.experimentTemplateId(activeTemplateId)
.experimentOptions(options -> options.actionsMode(ActionsMode.SKIP_ALL))
.tags(Map.of("mode", "safe-preview"))).experiment();
String experimentId = startedExperiment.id();
assertThat(experimentId).isNotBlank();
assertThat(startedExperiment.experimentTemplateId()).isEqualTo(activeTemplateId);
assertThat(startedExperiment.experimentOptions().actionsMode())
.isEqualTo(ActionsMode.SKIP_ALL);
assertThat(startedExperiment.state().status())
.isIn(ExperimentStatus.RUNNING, ExperimentStatus.COMPLETED);
var fetchedExperiment = fis.getExperiment(request -> request.id(experimentId)).experiment();
assertThat(fetchedExperiment.id()).isEqualTo(experimentId);
assertThat(fetchedExperiment.tags()).containsEntry("mode", "safe-preview");
assertThat(fis.listExperiments(request -> request
.experimentTemplateId(activeTemplateId)
.maxResults(100)).experiments())
.anyMatch(experiment -> experimentId.equals(experiment.id()));
var resolvedTargets = fis.listExperimentResolvedTargets(request -> request
.experimentId(experimentId)
.targetName("instances")
.maxResults(100)).resolvedTargets();
assertThat(resolvedTargets)
.anyMatch(target -> "instances".equals(target.targetName())
&& RESOURCE_TYPE.equals(target.resourceType()));
var experimentTargetAccount = fis.getExperimentTargetAccountConfiguration(request -> request
.experimentId(experimentId)
.accountId(ACCOUNT_ID)).targetAccountConfiguration();
assertThat(experimentTargetAccount.accountId()).isEqualTo(ACCOUNT_ID);
assertThat(experimentTargetAccount.roleArn()).isEqualTo(TARGET_ROLE_ARN);
assertThat(fis.listExperimentTargetAccountConfigurations(request -> request
.experimentId(experimentId)).targetAccountConfigurations())
.anyMatch(configuration -> ACCOUNT_ID.equals(configuration.accountId()));
var stoppedExperiment = fis.stopExperiment(request -> request.id(experimentId)).experiment();
assertThat(stoppedExperiment.id()).isEqualTo(experimentId);
assertThat(stoppedExperiment.state().status())
.isIn(ExperimentStatus.STOPPED, ExperimentStatus.COMPLETED);
fis.deleteTargetAccountConfiguration(request -> request
.experimentTemplateId(activeTemplateId)
.accountId(ACCOUNT_ID));
targetAccountConfigurationExists = false;
String deletedTemplateId = activeTemplateId;
assertThat(fis.deleteExperimentTemplate(request -> request.id(deletedTemplateId))
.experimentTemplate().id()).isEqualTo(deletedTemplateId);
templateId = null;
assertThatThrownBy(() -> fis.getExperimentTemplate(request -> request.id(deletedTemplateId)))
.isInstanceOf(ResourceNotFoundException.class);
} finally {
cleanup(templateId, targetAccountConfigurationExists);
}
}
private static void cleanup(String templateId, boolean targetAccountConfigurationExists) {
try (FisClient fis = TestFixtures.fisClient()) {
try {
fis.updateSafetyLeverState(request -> request
.id("default")
.state(state -> state
.status(SafetyLeverStatusInput.DISENGAGED)
.reason("SDK compatibility cleanup")));
} catch (RuntimeException e) {
System.err.println("Unable to disengage the FIS safety lever during cleanup: " + e);
}
if (templateId == null) {
return;
}
if (targetAccountConfigurationExists) {
try {
fis.deleteTargetAccountConfiguration(request -> request
.experimentTemplateId(templateId)
.accountId(ACCOUNT_ID));
} catch (RuntimeException e) {
System.err.println("Unable to delete the FIS target account configuration during cleanup: " + e);
}
}
try {
fis.deleteExperimentTemplate(request -> request.id(templateId));
} catch (RuntimeException e) {
System.err.println("Unable to delete the FIS experiment template during cleanup: " + e);
}
}
}
}
@@ -76,6 +76,8 @@ floci:
flush-interval-ms: 5000
opensearch:
flush-interval-ms: 5000
fis:
flush-interval-ms: 5000
dns:
# Extra hostname suffixes resolved to Floci's container IP by the embedded DNS server.
@@ -244,6 +246,9 @@ floci:
appconfigdata:
enabled: true
fis:
enabled: true
ecr:
enabled: true
registry-image: "registry:2"
+2 -1
View File
@@ -78,7 +78,7 @@ FLOCI_STORAGE_SERVICES_<SERVICE>_MODE=hybrid
FLOCI_STORAGE_SERVICES_<SERVICE>_FLUSH_INTERVAL_MS=5000
```
Available service names: `SSM`, `SQS`, `S3`, `DYNAMODB`, `SNS`, `LAMBDA`, `CLOUDWATCHLOGS`, `CLOUDWATCHMETRICS`, `SECRETSMANAGER`, `ACM`, `OPENSEARCH`, `RDS`, `ELASTICACHE`, `APPCONFIG`, `APPCONFIGDATA`, `BACKUP`.
Available service names: `SSM`, `SQS`, `S3`, `DYNAMODB`, `SNS`, `LAMBDA`, `CLOUDWATCHLOGS`, `CLOUDWATCHMETRICS`, `SECRETSMANAGER`, `ACM`, `OPENSEARCH`, `RDS`, `ELASTICACHE`, `APPCONFIG`, `APPCONFIGDATA`, `BACKUP`, `FIS`.
See [Storage Modes](./storage.md) for a full explanation of each mode.
@@ -455,5 +455,6 @@ These services spawn Docker containers. They require access to the Docker socket
| `FLOCI_SERVICES_CODEDEPLOY_ENABLED` | `true` | Enable the CodeDeploy service |
| `FLOCI_SERVICES_BACKUP_ENABLED` | `true` | Enable the AWS Backup service |
| `FLOCI_SERVICES_BACKUP_JOB_COMPLETION_DELAY_SECONDS` | `3` | Simulated delay before backup jobs transition to `COMPLETED` |
| `FLOCI_SERVICES_FIS_ENABLED` | `true` | Enable the AWS Fault Injection Service management API |
| `FLOCI_SERVICES_APPCONFIG_ENABLED` | `true` | Enable the AppConfig service |
| `FLOCI_SERVICES_APPCONFIGDATA_ENABLED` | `true` | Enable the AppConfig Data service |
+3 -2
View File
@@ -12,7 +12,7 @@ Floci is a fast, free, and open-source local AWS service emulator built for deve
## Supported Services
Floci emulates 69 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.
Floci emulates 72 AWS services. See the [Services Overview](services/index.md) for per-service operation counts, endpoints, and full protocol details.
| Service | Protocol |
|---|---|
@@ -67,6 +67,7 @@ Floci emulates 69 AWS services. See the [Services Overview](services/index.md) f
| CodeDeploy | JSON 1.1 |
| CodePipeline | JSON 1.1 |
| AWS Backup | REST JSON |
| AWS FIS | REST JSON |
| CloudFront | REST XML |
| Route53 | REST XML |
| Cloud Map | JSON 1.1 |
@@ -113,7 +114,7 @@ docker compose up -d
aws --endpoint-url http://localhost:4566 s3 mb s3://my-bucket
```
All 69 AWS services are immediately available at `http://localhost:4566`.
All 72 AWS services are immediately available at `http://localhost:4566`.
[Get started →](getting-started/quick-start.md){ .md-button .md-button--primary }
[View services →](services/index.md){ .md-button }
+113
View File
@@ -0,0 +1,113 @@
# AWS Fault Injection Service (FIS)
- **Protocol:** REST JSON
- **Endpoint:** `http://localhost:4566/`
- **Credential scope:** `fis`
Floci implements the AWS FIS management API for local SDK, CLI, infrastructure-as-code, and resilience-workflow tests. Templates, experiments, target-account configurations, tags, and safety-lever state are isolated by account and region and use the configured Floci storage mode.
## Supported Actions
<!-- floci:actions:start -->
| Action | Description |
| --- | --- |
| `CreateExperimentTemplate` | Creates a template (`POST /experimentTemplates`) |
| `CreateTargetAccountConfiguration` | Adds an account to a multi-account template (`POST /experimentTemplates/{experimentTemplateId}/targetAccountConfigurations/{accountId}`) |
| `DeleteExperimentTemplate` | Deletes a template (`DELETE /experimentTemplates/{id}`) |
| `DeleteTargetAccountConfiguration` | Removes a template target-account configuration (`DELETE /experimentTemplates/{experimentTemplateId}/targetAccountConfigurations/{accountId}`) |
| `GetAction` | Gets an AWS FIS action definition (`GET /actions/{id}`) |
| `GetExperiment` | Gets experiment configuration and state (`GET /experiments/{id}`) |
| `GetExperimentTargetAccountConfiguration` | Gets an experiment target-account snapshot (`GET /experiments/{experimentId}/targetAccountConfigurations/{accountId}`) |
| `GetExperimentTemplate` | Gets a template (`GET /experimentTemplates/{id}`) |
| `GetSafetyLever` | Gets safety-lever state (`GET /safetyLevers/{id}`) |
| `GetTargetAccountConfiguration` | Gets a template target-account configuration (`GET /experimentTemplates/{experimentTemplateId}/targetAccountConfigurations/{accountId}`) |
| `GetTargetResourceType` | Gets a target resource-type definition (`GET /targetResourceTypes/{resourceType}`) |
| `ListActions` | Lists AWS FIS action definitions (`GET /actions`) |
| `ListExperimentResolvedTargets` | Lists resources resolved for an experiment target (`GET /experiments/{experimentId}/resolvedTargets`) |
| `ListExperimentTargetAccountConfigurations` | Lists target-account snapshots used by an experiment (`GET /experiments/{experimentId}/targetAccountConfigurations`) |
| `ListExperimentTemplates` | Lists experiment-template summaries (`GET /experimentTemplates`) |
| `ListExperiments` | Lists experiments, optionally filtered by template (`GET /experiments`) |
| `ListTargetAccountConfigurations` | Lists template target-account configurations (`GET /experimentTemplates/{experimentTemplateId}/targetAccountConfigurations`) |
| `ListTargetResourceTypes` | Lists target resource types (`GET /targetResourceTypes`) |
| `StartExperiment` | Starts a locally simulated experiment (`POST /experiments`) |
| `StopExperiment` | Stops an experiment (`DELETE /experiments/{id}`) |
| `UpdateExperimentTemplate` | Updates supplied template fields (`PATCH /experimentTemplates/{id}`) |
| `UpdateSafetyLeverState` | Engages or disengages a safety lever (`PATCH /safetyLevers/{id}/state`) |
| `UpdateTargetAccountConfiguration` | Updates a target-account role or description (`PATCH /experimentTemplates/{experimentTemplateId}/targetAccountConfigurations/{accountId}`) |
| `ListTagsForResource` | Lists tags on an FIS resource (`GET /tags/{resourceArn}`) |
| `TagResource` | Adds or replaces tags on an FIS resource (`POST /tags/{resourceArn}`) |
| `UntagResource` | Removes tag keys from an FIS resource (`DELETE /tags/{resourceArn}`) |
<!-- floci:actions:end -->
List operations accept AWS-compatible `maxResults` and `nextToken` parameters where the AWS API defines them. `ListExperimentTargetAccountConfigurations` follows AWS and accepts `nextToken` without a `maxResults` parameter.
## Local Experiment Semantics
Experiment execution is a safe local simulation. Starting or stopping an experiment creates and updates AWS-shaped FIS control-plane state, including action state, resolved targets, timestamps, target-account snapshots, and safety-lever effects. Floci does **not** inject latency, terminate resources, interrupt networking, or otherwise mutate resources in other emulated services.
Explicit resource ARNs are sampled at random according to the target selection mode and recorded as locally resolved targets. Floci does not query other emulated services to resolve tag, filter, or parameter selectors, so those selectors resolve to an empty set. The template's `emptyTargetResolutionMode` then follows AWS behavior: `fail` fails the experiment, while `skip` skips actions whose selector-based targets are empty. Targets defined by unique identifiers such as ARNs cannot be skipped and fail the experiment if their selection resolves to nothing. Selector criteria are never reported as if they were resolved resources.
The action and target-resource catalogs let clients discover and validate AWS-defined action IDs and target shapes. Floci validates the Smithy-modeled string shapes, known and required parameters, target slots and resource types, plus documented selector restrictions. It does not yet enforce every action-specific parameter range, enum, or conditional rule that AWS defines only in the FIS actions user guide. The catalogs are metadata used by the local simulation, not adapters that execute the corresponding faults.
Regional, account-scoped limits mirror the default AWS FIS quotas for 500 experiment templates, 5 active experiments, 20 actions per template, 10 actions that can run in parallel, 5 stop conditions, and 40 target-account configurations per template. Quota violations use the modeled `ServiceQuotaExceededException` response.
## Configuration
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_FIS_ENABLED` | `true` | Enable or disable AWS FIS |
| `FLOCI_STORAGE_SERVICES_FIS_MODE` | *(inherits global)* | Optional FIS storage-mode override |
| `FLOCI_STORAGE_SERVICES_FIS_FLUSH_INTERVAL_MS` | `5000` | Hybrid storage flush interval in milliseconds |
Unless the FIS-specific override is set, FIS state follows the global `FLOCI_STORAGE_MODE` setting. Persistent, hybrid, and write-ahead-log modes restore FIS resources after restart.
## Example
Create `template.json`:
```json
{
"description": "Local stop-instance experiment",
"roleArn": "arn:aws:iam::000000000000:role/fis-role",
"stopConditions": [
{ "source": "none" }
],
"targets": {
"instances": {
"resourceType": "aws:ec2:instance",
"selectionMode": "ALL",
"resourceArns": [
"arn:aws:ec2:us-east-1:000000000000:instance/i-local"
]
}
},
"actions": {
"stopInstances": {
"actionId": "aws:ec2:stop-instances",
"targets": {
"Instances": "instances"
}
}
},
"tags": {
"environment": "test"
}
}
```
Then use the AWS CLI against Floci:
```bash
export AWS_ENDPOINT_URL=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
aws fis create-experiment-template --cli-input-json file://template.json
aws fis list-experiment-templates
aws fis start-experiment --experiment-template-id <template-id>
aws fis list-experiments
aws fis get-safety-lever --id default
```
The commands exercise the AWS-compatible management workflow only; the example EC2 instance is not stopped.
+2 -1
View File
@@ -1,6 +1,6 @@
# Services Overview
Floci emulates 71 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.
Floci emulates 72 AWS services on a single port (`4566`). All services use the real AWS wire protocol, your existing AWS CLI commands and SDK clients work without modification.
This page is the canonical reference for supported service and operation counts. Some services expose separate control-plane and data-plane rows below. Other docs (and the README) should link here rather than duplicating the table.
@@ -76,6 +76,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [CodeDeploy](codedeploy.md) | `POST /` + `X-Amz-Target: CodeDeploy_20141006.*` | JSON 1.1 | 30 |
| [CodePipeline](codepipeline.md) | `POST /` + `X-Amz-Target: CodePipeline_20150709.*` | JSON 1.1 | 44 |
| [AWS Backup](backup.md) | `/backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 20 |
| [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 |
| [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 |
| [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*` | REST XML | 17 |
| [Cloud Map](cloudmap.md) | `POST /` + `X-Amz-Target: Route53AutoNaming_v20170314.*` | JSON 1.1 | 22 |
+1
View File
@@ -135,6 +135,7 @@ nav:
- CodeDeploy: services/codedeploy.md
- CodePipeline: services/codepipeline.md
- AWS Backup: services/backup.md
- AWS FIS: services/fis.md
- CloudTrail: services/cloudtrail.md
- CloudFront: services/cloudfront.md
- Route53: services/route53.md
@@ -266,6 +266,7 @@ public interface EmulatorConfig {
Ec2StorageConfig ec2();
NeptuneStorageConfig neptune();
BackupStorageConfig backup();
FisStorageConfig fis();
CloudFrontStorageConfig cloudfront();
AppSyncStorageConfig appsync();
BatchStorageConfig batch();
@@ -404,6 +405,13 @@ public interface EmulatorConfig {
long flushIntervalMs();
}
interface FisStorageConfig {
Optional<String> mode();
@WithDefault("5000")
long flushIntervalMs();
}
interface CloudFrontStorageConfig {
Optional<String> mode();
}
@@ -601,6 +609,7 @@ public interface EmulatorConfig {
ApplicationAutoScalingServiceConfig applicationautoscaling();
ElasticBeanstalkServiceConfig elasticbeanstalk();
BackupServiceConfig backup();
FisServiceConfig fis();
NeptuneServiceConfig neptune();
DocDbServiceConfig docdb();
Route53ServiceConfig route53();
@@ -703,6 +712,11 @@ public interface EmulatorConfig {
int jobCompletionDelaySeconds();
}
interface FisServiceConfig {
@WithDefault("true")
boolean enabled();
}
interface Route53ServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -0,0 +1,80 @@
package io.github.hectorvent.floci.core.common;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.container.ResourceInfo;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.ext.Provider;
import java.util.Optional;
/** Adds the modeled AWS error type header to REST JSON error responses. */
@Provider
public class AwsRestJsonErrorHeaderFilter implements ContainerResponseFilter {
private static final String ERROR_TYPE_HEADER = "X-Amzn-Errortype";
@Context
ResourceInfo resourceInfo;
private final ResolvedServiceCatalog catalog;
@Inject
public AwsRestJsonErrorHeaderFilter(ResolvedServiceCatalog catalog) {
this.catalog = catalog;
}
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
if (response.getStatus() < 400 || response.getHeaderString(ERROR_TYPE_HEADER) != null) {
return;
}
Object claimValue = request.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY);
if (claimValue instanceof ProtocolClaim claim && claim.protocol() != WireProtocol.REST) {
return;
}
if (resolveDescriptor(request)
.filter(descriptor -> descriptor.supportsProtocol(ServiceProtocol.REST_JSON))
.isEmpty()) {
return;
}
errorType(response.getEntity()).ifPresent(type ->
response.getHeaders().putSingle(ERROR_TYPE_HEADER, normalize(type)));
}
private Optional<ServiceDescriptor> resolveDescriptor(ContainerRequestContext request) {
Object claimValue = request.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY);
if (claimValue instanceof ProtocolClaim claim && claim.service() != null) {
return Optional.of(claim.service());
}
if (resourceInfo != null && resourceInfo.getResourceClass() != null) {
Optional<ServiceDescriptor> descriptor = catalog.byResourceClass(resourceInfo.getResourceClass());
if (descriptor.isPresent()) {
return descriptor;
}
}
return SigV4CredentialScope.serviceName(request.getHeaderString("Authorization"))
.flatMap(catalog::byCredentialScope);
}
private Optional<String> errorType(Object entity) {
if (entity instanceof AwsErrorResponse error) {
return Optional.ofNullable(error.type());
}
if (entity instanceof JsonNode node && node.hasNonNull("__type")) {
return Optional.of(node.path("__type").asText());
}
return Optional.empty();
}
private String normalize(String type) {
int hash = type.lastIndexOf('#');
String normalized = hash >= 0 ? type.substring(hash + 1) : type;
int colon = normalized.indexOf(':');
return colon >= 0 ? normalized.substring(0, colon) : normalized;
}
}
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.bedrockruntime.BedrockRuntimeControll
import io.github.hectorvent.floci.services.cognito.CognitoOAuthController;
import io.github.hectorvent.floci.services.cognito.CognitoWellKnownController;
import io.github.hectorvent.floci.services.eks.EksController;
import io.github.hectorvent.floci.services.fis.FisController;
import io.github.hectorvent.floci.services.mwaa.MwaaController;
import io.github.hectorvent.floci.services.iot.IotController;
import io.github.hectorvent.floci.services.iot.IotDataController;
@@ -395,6 +396,11 @@ public class ResolvedServiceCatalog {
config.storage().services().backup().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("backup"), Set.of(), Set.of(BackupController.class)),
descriptor("fis", "fis", config.services().fis().enabled(), true,
"fis", storageMode(config.storage().services().fis().mode(), config.storage().mode()),
config.storage().services().fis().flushIntervalMs(), null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("fis"), Set.of(), Set.of(FisController.class)),
descriptor("ec2messages", "ec2messages", config.services().ssm().enabled(), false,
null, null, 5000L, null, ServiceProtocol.JSON,
protocols(ServiceProtocol.JSON),
@@ -101,7 +101,8 @@ public class SharedTagsController {
throw new AwsException("MethodNotAllowedException",
"POST is not supported for " + handler.serviceKey() + " tag resources; use PUT.", 405);
}
return doTagResource(headers, handler, arn, body, Response.noContent().build());
return doTagResource(headers, handler, arn, body,
Response.status(handler.tagResourceSuccessStatus()).build());
}
@PUT
@@ -115,7 +116,8 @@ public class SharedTagsController {
throw new AwsException("MethodNotAllowedException",
"PUT is not supported for " + handler.serviceKey() + " tag resources; use POST.", 405);
}
return doTagResource(headers, handler, arn, body, Response.noContent().build());
return doTagResource(headers, handler, arn, body,
Response.status(handler.tagResourceSuccessStatus()).build());
}
private Response doTagResource(HttpHeaders headers, TagHandler handler, String arn, String body, Response successResponse) {
@@ -146,11 +148,17 @@ public class SharedTagsController {
public Response untagResource(@Context HttpHeaders headers,
@Context UriInfo uriInfo,
@PathParam("arn") String arn) {
return untagResourceForArn(headers, uriInfo, arn, Response.noContent().build());
TagHandler handler = resolveHandler(arn);
return untagResourceForArn(headers, uriInfo, arn,
Response.status(handler.untagResourceSuccessStatus()).build(), handler);
}
private Response untagResourceForArn(HttpHeaders headers, UriInfo uriInfo, String arn, Response successResponse) {
TagHandler handler = resolveHandler(arn);
return untagResourceForArn(headers, uriInfo, arn, successResponse, resolveHandler(arn));
}
private Response untagResourceForArn(HttpHeaders headers, UriInfo uriInfo, String arn,
Response successResponse, TagHandler handler) {
String region = regionResolver.resolveRegion(headers);
List<String> tagKeys = readTagKeys(handler, uriInfo);
handler.untagResource(region, arn, tagKeys);
@@ -207,6 +215,11 @@ public class SharedTagsController {
}
continue;
}
if (handler.strictTagValidation() && (!k.isTextual() || !v.isTextual())) {
throw new AwsException("ValidationException",
"1 validation error detected: Tag entries at '" + key
+ "' must contain string Key and Value members", 400);
}
tags.put(k.asText(), v.asText());
}
} else {
@@ -217,7 +230,13 @@ public class SharedTagsController {
}
return tags;
}
tagNode.fields().forEachRemaining(e -> tags.put(e.getKey(), e.getValue().asText()));
tagNode.fields().forEachRemaining(e -> {
if (handler.strictTagValidation() && !e.getValue().isTextual()) {
throw new AwsException("ValidationException",
"1 validation error detected: Tag values at '" + key + "' must be strings", 400);
}
tags.put(e.getKey(), e.getValue().asText());
});
}
return tags;
}
@@ -225,7 +244,8 @@ public class SharedTagsController {
private List<String> readTagKeys(TagHandler handler, UriInfo uriInfo) {
String paramName = handler.tagKeysQueryName();
List<String> values = uriInfo.getQueryParameters().get(paramName);
if (handler.strictTagValidation() && (values == null || values.isEmpty())) {
if (handler.strictTagValidation() && !handler.allowEmptyTagKeys()
&& (values == null || values.isEmpty())) {
throw new AwsException("ValidationException",
"1 validation error detected: Value null at '" + paramName + "' failed to satisfy constraint: Member must not be null", 400);
}
@@ -76,6 +76,14 @@ public interface TagHandler {
return false;
}
/**
* Whether an {@code UntagResource} request may omit the tag-key query parameter.
* Defaults to {@code false} so strict handlers retain their existing validation.
*/
default boolean allowEmptyTagKeys() {
return false;
}
/**
* Query parameter name for {@code UntagResource}. Defaults to lowercase
* {@code "tagKeys"}, which matches the great majority of AWS services — including
@@ -98,6 +106,16 @@ public interface TagHandler {
return false;
}
/** HTTP status for successful path-based TagResource requests. */
default int tagResourceSuccessStatus() {
return 204;
}
/** HTTP status for successful path-based UntagResource requests. */
default int untagResourceSuccessStatus() {
return 204;
}
Map<String, String> listTags(String region, String arn);
void tagResource(String region, String arn, Map<String, String> tags);
@@ -0,0 +1,491 @@
package io.github.hectorvent.floci.services.fis;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RegionResolver;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Static AWS FIS action and target-resource-type catalog. */
@ApplicationScoped
public class FisCatalog {
private static final String WAIT_DESCRIPTION = "Runs the AWS FIS wait action.";
private static final String STOP_INSTANCES_DESCRIPTION =
"Runs the Amazon EC2 API action StopInstances on the target EC2 instances.";
private static final String DURATION_DESCRIPTION = "The action duration in ISO 8601 format.";
private static final String KUBERNETES_SERVICE_ACCOUNT_DESCRIPTION =
"The Kubernetes service account used by the fault injection pod.";
private static final Map<String, ActionDefinition> ACTIONS = buildActions();
private static final Map<String, TargetResourceTypeDefinition> RESOURCE_TYPES = buildResourceTypes();
private final ObjectMapper mapper;
private final RegionResolver regionResolver;
@Inject
public FisCatalog(ObjectMapper mapper, RegionResolver regionResolver) {
this.mapper = mapper;
this.regionResolver = regionResolver;
}
public boolean containsAction(String actionId) {
return actionId != null && ACTIONS.containsKey(actionId);
}
public Set<String> actionIds() {
return ACTIONS.keySet();
}
public ObjectNode action(String region, String actionId) {
ActionDefinition definition = ACTIONS.get(actionId);
if (definition == null) {
return null;
}
ObjectNode action = actionSummary(region, actionId, definition);
action.set("parameters", parameterNodes(definition.parameters()));
return action;
}
public List<ObjectNode> actionSummaries(String region) {
List<ObjectNode> result = new ArrayList<>(ACTIONS.size());
ACTIONS.forEach((id, definition) -> result.add(actionSummary(region, id, definition)));
return result;
}
public boolean containsTargetResourceType(String resourceType) {
return resourceType != null && RESOURCE_TYPES.containsKey(resourceType);
}
public ObjectNode targetResourceType(String resourceType) {
TargetResourceTypeDefinition definition = RESOURCE_TYPES.get(resourceType);
if (definition == null) {
return null;
}
ObjectNode node = targetResourceTypeSummary(resourceType, definition.description());
node.set("parameters", parameterNodes(definition.parameters()));
return node;
}
public List<ObjectNode> targetResourceTypeSummaries() {
List<ObjectNode> result = new ArrayList<>(RESOURCE_TYPES.size());
RESOURCE_TYPES.forEach((resourceType, definition) ->
result.add(targetResourceTypeSummary(resourceType, definition.description())));
return result;
}
private ObjectNode parameterNodes(Map<String, ParameterDefinition> definitions) {
ObjectNode parameters = mapper.createObjectNode();
definitions.forEach((name, parameter) -> {
ObjectNode value = parameters.putObject(name);
value.put("description", parameter.description());
value.put("required", parameter.required());
});
return parameters;
}
private ObjectNode actionSummary(String region, String actionId, ActionDefinition definition) {
ObjectNode action = mapper.createObjectNode();
action.put("id", actionId);
action.put("arn", regionResolver.buildArn("fis", region, "action/" + actionId));
action.put("description", definition.description());
ObjectNode targets = action.putObject("targets");
definition.targets().forEach((name, resourceType) ->
targets.putObject(name).put("resourceType", resourceType));
action.putObject("tags");
return action;
}
private ObjectNode targetResourceTypeSummary(String resourceType, String description) {
ObjectNode node = mapper.createObjectNode();
node.put("resourceType", resourceType);
node.put("description", description);
return node;
}
private static Map<String, ActionDefinition> buildActions() {
Map<String, ActionDefinition> actions = new LinkedHashMap<>();
Map<String, ParameterDefinition> injectApiParameters = parameters(
required("duration", DURATION_DESCRIPTION),
required("service", "The target AWS API namespace."),
required("percentage", "The percentage of API calls to impair."),
required("operations", "The comma-separated API operations to impair."));
add(actions, "aws:fis:inject-api-internal-error",
"Injects internal errors into supported AWS API calls.",
target("Roles", "aws:iam:role"), injectApiParameters);
add(actions, "aws:fis:inject-api-throttle-error",
"Injects throttling errors into supported AWS API calls.",
target("Roles", "aws:iam:role"), injectApiParameters);
add(actions, "aws:fis:inject-api-unavailable-error",
"Injects unavailable errors into supported AWS API calls.",
target("Roles", "aws:iam:role"), injectApiParameters);
add(actions, "aws:arc:start-zonal-autoshift",
"Starts an ARC zonal autoshift for the target managed resources.",
target("ManagedResources", "aws:arc:zonal-shift-managed-resource"), parameters(
required("duration", DURATION_DESCRIPTION),
required("availabilityZoneIdentifier", "The Availability Zone to shift traffic away from."),
optional("managedResourceTypes", "The comma-separated managed resource types to shift."),
optional("zonalAutoshiftStatus", "The zonal autoshift status used to select resources.")));
add(actions, "aws:fis:wait", WAIT_DESCRIPTION, Map.of(),
parameters(required("duration",
"The duration, from one minute to 12 hours, in ISO 8601 format.")));
add(actions, "aws:cloudwatch:assert-alarm-state",
"Verifies that the specified alarms are in the specified alarm states.", Map.of(), parameters(
required("alarmArns", "The comma-separated ARNs of up to five CloudWatch alarms."),
required("alarmStates", "The comma-separated alarm states to assert.")));
add(actions, "aws:dynamodb:global-table-pause-replication",
"Pauses replication for the target DynamoDB global table.",
target("Tables", "aws:dynamodb:global-table"), durationParameters());
add(actions, "aws:dsql:cluster-connection-failure",
"Injects connection failures into the target Amazon Aurora DSQL clusters.",
target("Clusters", "aws:dsql:cluster"), parameters(
required("duration", DURATION_DESCRIPTION),
required("percentage", "The percentage of calls to impair.")));
add(actions, "aws:ebs:pause-volume-io", "Pauses I/O operations on the target EBS volumes.",
target("Volumes", "aws:ec2:ebs-volume"), durationParameters());
add(actions, "aws:ebs:volume-io-latency", "Injects I/O latency into the target EBS volumes.",
target("Volumes", "aws:ec2:ebs-volume"), parameters(
optional("readIOPercentage", "The percentage of read I/O operations to impair."),
optional("readIOLatencyMilliseconds", "The latency added to read I/O operations."),
optional("writeIOPercentage", "The percentage of write I/O operations to impair."),
optional("writeIOLatencyMilliseconds", "The latency added to write I/O operations."),
required("duration", DURATION_DESCRIPTION)));
add(actions, "aws:ec2:api-insufficient-instance-capacity-error",
"Injects insufficient instance capacity errors into EC2 API calls.",
target("Roles", "aws:iam:role"), parameters(
required("duration", DURATION_DESCRIPTION),
required("availabilityZoneIdentifiers", "The comma-separated Availability Zones to impair."),
required("percentage", "The percentage of calls to impair.")));
add(actions, "aws:ec2:asg-insufficient-instance-capacity-error",
"Injects insufficient instance capacity errors for target Auto Scaling groups.",
target("AutoScalingGroups", "aws:ec2:autoscaling-group"), parameters(
required("duration", DURATION_DESCRIPTION),
required("availabilityZoneIdentifiers", "The comma-separated Availability Zones to impair."),
optional("percentage", "The percentage of launch requests to impair.")));
add(actions, "aws:ec2:reboot-instances",
"Runs the Amazon EC2 API action RebootInstances on the target EC2 instances.",
target("Instances", "aws:ec2:instance"), Map.of());
add(actions, "aws:ec2:send-spot-instance-interruptions",
"Sends Spot Instance interruption notices to the target EC2 Spot Instances.",
target("SpotInstances", "aws:ec2:spot-instance"), parameters(
required("durationBeforeInterruption", "The delay before interruption in ISO 8601 format.")));
add(actions, "aws:ec2:stop-instances", STOP_INSTANCES_DESCRIPTION,
target("Instances", "aws:ec2:instance"), parameters(
optional("startInstancesAfterDuration", "The delay before restarting the instances."),
optional("completeIfInstancesTerminated",
"Whether the action completes if target instances were terminated.")));
add(actions, "aws:ec2:terminate-instances",
"Runs the Amazon EC2 API action TerminateInstances on the target EC2 instances.",
target("Instances", "aws:ec2:instance"), Map.of());
add(actions, "aws:ecs:drain-container-instances",
"Drains container instances in the target ECS clusters.",
target("Clusters", "aws:ecs:cluster"), parameters(
required("drainagePercentage", "The percentage of container instances to drain."),
required("duration", DURATION_DESCRIPTION)));
add(actions, "aws:ecs:stop-task", "Stops the target Amazon ECS tasks.",
target("Tasks", "aws:ecs:task"), Map.of());
add(actions, "aws:ecs:task-cpu-stress", "Runs CPU stress on the target Amazon ECS tasks.",
target("Tasks", "aws:ecs:task"), parameters(
required("duration", DURATION_DESCRIPTION),
optional("percent", "The target CPU load percentage."),
optional("workers", "The number of CPU stress workers."),
optional("installDependencies", "Whether to install required dependencies.")));
add(actions, "aws:ecs:task-io-stress", "Runs I/O stress on the target Amazon ECS tasks.",
target("Tasks", "aws:ecs:task"), parameters(
required("duration", DURATION_DESCRIPTION),
optional("percent", "The percentage of free file-system space to use."),
optional("workers", "The number of I/O stress workers."),
optional("installDependencies", "Whether to install required dependencies.")));
add(actions, "aws:ecs:task-kill-process", "Kills a process in the target Amazon ECS tasks.",
target("Tasks", "aws:ecs:task"), parameters(
required("processName", "The process name to stop."),
optional("signal", "The signal to send to the process."),
optional("installDependencies", "Whether to install required dependencies.")));
add(actions, "aws:ecs:task-network-blackhole-port",
"Drops network traffic on a port in the target Amazon ECS tasks.",
target("Tasks", "aws:ecs:task"), parameters(
required("duration", DURATION_DESCRIPTION),
required("port", "The port number to impair."),
required("trafficType", "The ingress or egress traffic direction."),
optional("protocol", "The tcp or udp protocol."),
optional("installDependencies", "Whether to install required dependencies."),
optional("useEcsFaultInjectionEndpoints", "Whether to use ECS fault injection endpoints.")));
add(actions, "aws:ecs:task-network-latency",
"Injects network latency into the target Amazon ECS tasks.",
target("Tasks", "aws:ecs:task"), parameters(
required("duration", DURATION_DESCRIPTION),
optional("delayMilliseconds", "The network delay in milliseconds."),
optional("jitterMilliseconds", "The network jitter in milliseconds."),
optional("flowsPercent", "The percentage of network flows to impair."),
optional("sources", "The comma-separated traffic sources to impair."),
optional("installDependencies", "Whether to install required dependencies."),
optional("useEcsFaultInjectionEndpoints", "Whether to use ECS fault injection endpoints.")));
add(actions, "aws:ecs:task-network-packet-loss",
"Injects network packet loss into the target Amazon ECS tasks.",
target("Tasks", "aws:ecs:task"), parameters(
required("duration", DURATION_DESCRIPTION),
optional("lossPercent", "The packet loss percentage."),
optional("flowsPercent", "The percentage of network flows to impair."),
optional("sources", "The comma-separated traffic sources to impair."),
optional("installDependencies", "Whether to install required dependencies."),
optional("useEcsFaultInjectionEndpoints", "Whether to use ECS fault injection endpoints.")));
add(actions, "aws:eks:inject-kubernetes-custom-resource",
"Injects a Kubernetes custom resource into the target EKS cluster.",
target("Cluster", "aws:eks:cluster"), parameters(
required("kubernetesApiVersion", "The Kubernetes custom resource API version."),
required("kubernetesKind", "The Kubernetes custom resource kind."),
required("kubernetesNamespace", "The Kubernetes namespace."),
required("kubernetesSpec", "The custom resource spec in JSON format."),
required("maxDuration", "The maximum automation duration in ISO 8601 format.")));
add(actions, "aws:eks:pod-cpu-stress", "Runs CPU stress on the target Kubernetes pods.",
target("Pods", "aws:eks:pod"), eksPodParameters(true,
required("duration", DURATION_DESCRIPTION),
optional("percent", "The target CPU load percentage."),
optional("workers", "The number of CPU stress workers.")));
add(actions, "aws:eks:pod-delete", "Deletes the target Kubernetes pods.",
target("Pods", "aws:eks:pod"), eksPodParameters(true,
optional("gracePeriodSeconds", "The graceful pod termination period in seconds.")));
add(actions, "aws:eks:pod-io-stress", "Runs I/O stress on the target Kubernetes pods.",
target("Pods", "aws:eks:pod"), eksPodParameters(true,
required("duration", DURATION_DESCRIPTION),
optional("workers", "The number of I/O stress workers."),
optional("percent", "The percentage of free file-system space to use.")));
add(actions, "aws:eks:pod-memory-stress", "Runs memory stress on the target Kubernetes pods.",
target("Pods", "aws:eks:pod"), eksPodParameters(true,
required("duration", DURATION_DESCRIPTION),
optional("workers", "The number of memory stress workers."),
optional("percent", "The percentage of virtual memory to use.")));
add(actions, "aws:eks:pod-network-blackhole-port",
"Drops network traffic on a port in the target Kubernetes pods.",
target("Pods", "aws:eks:pod"), eksPodParameters(false,
required("duration", DURATION_DESCRIPTION),
required("protocol", "The tcp or udp protocol."),
required("trafficType", "The ingress or egress traffic direction."),
required("port", "The port number to impair.")));
add(actions, "aws:eks:pod-network-latency",
"Injects network latency into the target Kubernetes pods.",
target("Pods", "aws:eks:pod"), eksPodParameters(false,
required("duration", DURATION_DESCRIPTION),
optional("interface", "The network interfaces to impair."),
optional("delayMilliseconds", "The network delay in milliseconds."),
optional("jitterMilliseconds", "The network jitter in milliseconds."),
optional("flowsPercent", "The percentage of network flows to impair."),
optional("sources", "The comma-separated traffic sources to impair.")));
add(actions, "aws:eks:pod-network-packet-loss",
"Injects network packet loss into the target Kubernetes pods.",
target("Pods", "aws:eks:pod"), eksPodParameters(false,
required("duration", DURATION_DESCRIPTION),
optional("interface", "The network interfaces to impair."),
optional("lossPercent", "The packet loss percentage."),
optional("flowsPercent", "The percentage of network flows to impair."),
optional("sources", "The comma-separated traffic sources to impair.")));
add(actions, "aws:eks:terminate-nodegroup-instances",
"Terminates instances in the target Amazon EKS node groups.",
target("Nodegroups", "aws:eks:nodegroup"), parameters(
required("instanceTerminationPercentage", "The percentage of instances to terminate.")));
add(actions, "aws:elasticache:replicationgroup-interrupt-az-power",
"Interrupts Availability Zone power for the target ElastiCache replication groups.",
target("ReplicationGroups", "aws:elasticache:replicationgroup"), durationParameters());
add(actions, "aws:kinesis:stream-provisioned-throughput-exception",
"Injects ProvisionedThroughputExceededException errors into target Kinesis streams.",
target("KinesisStreams", "aws:kinesis:stream"), parameters(
required("duration", DURATION_DESCRIPTION),
required("percentage", "The percentage of calls to impair.")));
add(actions, "aws:kinesis:stream-expired-iterator-exception",
"Injects ExpiredIteratorException errors into target Kinesis streams.",
target("KinesisStreams", "aws:kinesis:stream"), parameters(
required("duration", DURATION_DESCRIPTION),
required("percentage", "The percentage of calls to impair.")));
add(actions, "aws:lambda:invocation-add-delay",
"Adds a delay to invocations of the target Lambda functions.",
target("Functions", "aws:lambda:function"), parameters(
required("duration", DURATION_DESCRIPTION),
optional("invocationPercentage", "The percentage of function invocations to impair."),
optional("startupDelayMilliseconds", "The invocation delay in milliseconds.")));
add(actions, "aws:lambda:invocation-error",
"Injects errors into invocations of the target Lambda functions.",
target("Functions", "aws:lambda:function"), parameters(
required("duration", DURATION_DESCRIPTION),
optional("invocationPercentage", "The percentage of function invocations to impair."),
required("preventExecution", "Whether to return the error without executing the function.")));
add(actions, "aws:lambda:invocation-http-integration-response",
"Injects HTTP integration responses into invocations of the target Lambda functions.",
target("Functions", "aws:lambda:function"), parameters(
required("contentTypeHeader", "The HTTP content type header to return."),
required("duration", DURATION_DESCRIPTION),
optional("invocationPercentage", "The percentage of function invocations to impair."),
required("preventExecution", "Whether to return without executing the function."),
required("statusCode", "The HTTP status code to return.")));
add(actions, "aws:memorydb:multi-region-cluster-pause-replication",
"Pauses replication for the target MemoryDB multi-Region clusters.",
target("MultiRegionClusters", "aws:memorydb:multi-region-cluster"), durationParameters());
add(actions, "aws:network:disrupt-connectivity", "Disrupts network connectivity for the target subnets.",
target("Subnets", "aws:ec2:subnet"), parameters(
required("scope", "The type of traffic to deny."),
required("duration", DURATION_DESCRIPTION),
optional("prefixListIdentifier", "The prefix list used when scope is prefix-list.")));
add(actions, "aws:network:route-table-disrupt-cross-region-connectivity",
"Disrupts cross-Region connectivity for the target subnets using route tables.",
target("Subnets", "aws:ec2:subnet"), parameters(
required("region", "The Region to isolate."),
required("duration", DURATION_DESCRIPTION)));
add(actions, "aws:network:transit-gateway-disrupt-cross-region-connectivity",
"Disrupts cross-Region connectivity for the target transit gateways.",
target("TransitGateways", "aws:ec2:transit-gateway"), parameters(
required("region", "The Region to isolate."),
required("duration", DURATION_DESCRIPTION)));
add(actions, "aws:network:disrupt-vpc-endpoint",
"Disrupts connectivity for the target VPC endpoints.",
target("VPCEndpoints", "aws:ec2:vpc-endpoint"), durationParameters());
add(actions, "aws:rds:failover-db-cluster", "Fails over the target Amazon RDS DB clusters.",
target("Clusters", "aws:rds:cluster"), Map.of());
add(actions, "aws:rds:reboot-db-instances", "Reboots the target Amazon RDS DB instances.",
target("DBInstances", "aws:rds:db"), parameters(
optional("forceFailover", "Whether to force a Multi-AZ failover.")));
add(actions, "aws:s3:bucket-pause-replication",
"Pauses replication for the target Amazon S3 buckets.",
target("Buckets", "aws:s3:bucket"), parameters(
required("duration", DURATION_DESCRIPTION),
required("region", "The Region containing destination buckets."),
optional("destinationBuckets", "The comma-separated destination bucket names."),
optional("prefixes", "The comma-separated replication rule prefixes.")));
add(actions, "aws:ssm:send-command", "Runs an Amazon Systems Manager command on the target resources.",
target("Instances", "aws:ec2:instance"), parameters(
required("documentArn", "The ARN of the Systems Manager document to run."),
optional("documentVersion", "The Systems Manager document version."),
optional("documentParameters", "The parameters accepted by the document."),
required("duration", DURATION_DESCRIPTION)));
add(actions, "aws:ssm:start-automation-execution",
"Starts an Amazon Systems Manager automation execution.", Map.of(), parameters(
required("documentArn", "The ARN of the Systems Manager automation document to run."),
optional("documentVersion", "The Systems Manager automation document version."),
optional("documentParameters", "The parameters accepted by the document."),
required("maxDuration", "The maximum automation duration in ISO 8601 format.")));
add(actions, "aws:directconnect:virtual-interface-disconnect",
"Disconnects the target Direct Connect virtual interfaces.",
target("VirtualInterfaces", "aws:directconnect:virtual-interface"), durationParameters());
if (actions.size() != 50) {
throw new IllegalStateException("The AWS FIS action catalog must contain exactly 50 actions");
}
return Collections.unmodifiableMap(actions);
}
private static Map<String, TargetResourceTypeDefinition> buildResourceTypes() {
Map<String, TargetResourceTypeDefinition> types = new LinkedHashMap<>();
resourceType(types, "aws:arc:zonal-shift-managed-resource", "An ARC zonal shift managed resource.");
resourceType(types, "aws:directconnect:virtual-interface", "A Direct Connect virtual interface.");
resourceType(types, "aws:dsql:cluster", "An Amazon Aurora DSQL cluster.");
resourceType(types, "aws:dynamodb:global-table", "A DynamoDB multi-Region global table.");
resourceType(types, "aws:ec2:autoscaling-group", "An EC2 Auto Scaling group.");
resourceType(types, "aws:ec2:ebs-volume", "An Amazon EBS volume.", parameters(
optional("availabilityZoneIdentifier", "The Availability Zone containing the target volumes.")));
resourceType(types, "aws:ec2:instance", "An Amazon EC2 instance.");
resourceType(types, "aws:ec2:spot-instance", "An Amazon EC2 Spot Instance.");
resourceType(types, "aws:ec2:subnet", "An Amazon VPC subnet.", parameters(
optional("availabilityZoneIdentifier", "The Availability Zone containing the target subnets."),
optional("vpc", "The VPC containing the target subnets.")));
resourceType(types, "aws:ec2:transit-gateway", "An Amazon VPC transit gateway.");
resourceType(types, "aws:ec2:vpc-endpoint", "An Amazon VPC endpoint.");
resourceType(types, "aws:ecs:cluster", "An Amazon ECS cluster.");
resourceType(types, "aws:ecs:task", "An Amazon ECS task.", parameters(
optional("cluster", "The cluster containing the target tasks."),
optional("service", "The service containing the target tasks.")));
resourceType(types, "aws:eks:cluster", "An Amazon EKS cluster.");
resourceType(types, "aws:eks:nodegroup", "An Amazon EKS node group.");
resourceType(types, "aws:eks:pod", "A Kubernetes pod.", parameters(
optional("availabilityZoneIdentifier", "The Availability Zone containing the target pods."),
required("clusterIdentifier", "The name or ARN of the target EKS cluster."),
required("namespace", "The Kubernetes namespace of the target pods."),
required("selectorType", "The selector type used to identify target pods."),
required("selectorValue", "The selector value used to identify target pods."),
optional("targetContainerName", "The target container name from the pod spec.")));
resourceType(types, "aws:elasticache:replicationgroup", "An ElastiCache replication group.", parameters(
required("availabilityZoneIdentifier", "The Availability Zone containing the target nodes.")));
resourceType(types, "aws:iam:role", "An IAM role.");
resourceType(types, "aws:kinesis:stream", "An Amazon Kinesis data stream.");
resourceType(types, "aws:lambda:function", "An AWS Lambda function.", parameters(
optional("functionQualifier", "The version or alias of the function to target.")));
resourceType(types, "aws:memorydb:multi-region-cluster", "A MemoryDB multi-Region cluster.");
resourceType(types, "aws:rds:cluster", "An Amazon Aurora DB cluster.", parameters(
optional("writerAvailabilityZoneIdentifiers", "The Availability Zones of the DB cluster writer.")));
resourceType(types, "aws:rds:db", "An Amazon RDS DB instance.", parameters(
optional("availabilityZoneIdentifiers", "The Availability Zones of the DB instance.")));
resourceType(types, "aws:s3:bucket", "An Amazon S3 bucket.");
return Collections.unmodifiableMap(types);
}
private static Map<String, ParameterDefinition> eksPodParameters(
boolean includeSecurityPolicy, NamedParameter... actionParameters) {
List<NamedParameter> definitions = new ArrayList<>(List.of(actionParameters));
definitions.add(required("kubernetesServiceAccount", KUBERNETES_SERVICE_ACCOUNT_DESCRIPTION));
definitions.add(optional("fisPodContainerImage", "The fault injector pod container image."));
definitions.add(optional("maxErrorsPercent", "The percentage of targets that may fail."));
definitions.add(optional("fisPodLabels", "Labels applied to the fault orchestration pod."));
definitions.add(optional("fisPodAnnotations", "Annotations applied to the fault orchestration pod."));
if (includeSecurityPolicy) {
definitions.add(optional("fisPodSecurityPolicy",
"The Kubernetes security policy for the fault orchestration pod."));
}
return parameters(definitions.toArray(NamedParameter[]::new));
}
private static void resourceType(Map<String, TargetResourceTypeDefinition> types,
String resourceType, String description) {
resourceType(types, resourceType, description, Map.of());
}
private static void resourceType(Map<String, TargetResourceTypeDefinition> types,
String resourceType, String description,
Map<String, ParameterDefinition> parameters) {
types.put(resourceType, new TargetResourceTypeDefinition(description, parameters));
}
private static void add(Map<String, ActionDefinition> actions, String id, String description,
Map<String, String> targets, Map<String, ParameterDefinition> parameters) {
actions.put(id, new ActionDefinition(description, targets, parameters));
}
private static Map<String, String> target(String name, String resourceType) {
return Map.of(name, resourceType);
}
private static Map<String, ParameterDefinition> durationParameters() {
return parameters(required("duration", DURATION_DESCRIPTION));
}
private static Map<String, ParameterDefinition> parameters(NamedParameter... definitions) {
Map<String, ParameterDefinition> parameters = new LinkedHashMap<>();
for (NamedParameter definition : definitions) {
parameters.put(definition.name(),
new ParameterDefinition(definition.description(), definition.required()));
}
return Collections.unmodifiableMap(parameters);
}
private static NamedParameter required(String name, String description) {
return new NamedParameter(name, description, true);
}
private static NamedParameter optional(String name, String description) {
return new NamedParameter(name, description, false);
}
private record ActionDefinition(String description, Map<String, String> targets,
Map<String, ParameterDefinition> parameters) {}
private record TargetResourceTypeDefinition(String description,
Map<String, ParameterDefinition> parameters) {}
private record NamedParameter(String name, String description, boolean required) {}
private record ParameterDefinition(String description, boolean required) {}
}
@@ -0,0 +1,272 @@
package io.github.hectorvent.floci.services.fis;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class FisController {
private final FisService service;
private final ObjectMapper objectMapper;
private final ObjectReader requestReader;
private final RegionResolver regionResolver;
@Inject
public FisController(FisService service, ObjectMapper objectMapper, RegionResolver regionResolver) {
this.service = service;
this.objectMapper = objectMapper;
this.requestReader = objectMapper.reader()
.with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
this.regionResolver = regionResolver;
}
@POST
@Path("/experimentTemplates")
public Response createExperimentTemplate(@Context HttpHeaders headers, String body) {
return ok(service.createExperimentTemplate(region(headers), parse(body)));
}
@POST
@Path("/experimentTemplates/{experimentTemplateId}/targetAccountConfigurations/{accountId}")
public Response createTargetAccountConfiguration(
@Context HttpHeaders headers,
@PathParam("experimentTemplateId") String experimentTemplateId,
@PathParam("accountId") String accountId,
String body) {
return ok(service.createTargetAccountConfiguration(
region(headers), experimentTemplateId, accountId, parse(body)));
}
@DELETE
@Path("/experimentTemplates/{id}")
public Response deleteExperimentTemplate(
@Context HttpHeaders headers, @PathParam("id") String id) {
return ok(service.deleteExperimentTemplate(region(headers), id));
}
@DELETE
@Path("/experimentTemplates/{experimentTemplateId}/targetAccountConfigurations/{accountId}")
public Response deleteTargetAccountConfiguration(
@Context HttpHeaders headers,
@PathParam("experimentTemplateId") String experimentTemplateId,
@PathParam("accountId") String accountId) {
return ok(service.deleteTargetAccountConfiguration(region(headers), experimentTemplateId, accountId));
}
@GET
@Path("/actions/{id}")
public Response getAction(@Context HttpHeaders headers, @PathParam("id") String id) {
return ok(service.getAction(region(headers), id));
}
@GET
@Path("/experiments/{id}")
public Response getExperiment(@Context HttpHeaders headers, @PathParam("id") String id) {
return ok(service.getExperiment(region(headers), id));
}
@GET
@Path("/experiments/{experimentId}/targetAccountConfigurations/{accountId}")
public Response getExperimentTargetAccountConfiguration(
@Context HttpHeaders headers,
@PathParam("experimentId") String experimentId,
@PathParam("accountId") String accountId) {
return ok(service.getExperimentTargetAccountConfiguration(region(headers), experimentId, accountId));
}
@GET
@Path("/experimentTemplates/{id}")
public Response getExperimentTemplate(
@Context HttpHeaders headers, @PathParam("id") String id) {
return ok(service.getExperimentTemplate(region(headers), id));
}
@GET
@Path("/safetyLevers/{id}")
public Response getSafetyLever(@Context HttpHeaders headers, @PathParam("id") String id) {
return ok(service.getSafetyLever(region(headers), id));
}
@GET
@Path("/experimentTemplates/{experimentTemplateId}/targetAccountConfigurations/{accountId}")
public Response getTargetAccountConfiguration(
@Context HttpHeaders headers,
@PathParam("experimentTemplateId") String experimentTemplateId,
@PathParam("accountId") String accountId) {
return ok(service.getTargetAccountConfiguration(region(headers), experimentTemplateId, accountId));
}
@GET
@Path("/targetResourceTypes/{resourceType}")
public Response getTargetResourceType(
@Context HttpHeaders headers, @PathParam("resourceType") String resourceType) {
return ok(service.getTargetResourceType(region(headers), resourceType));
}
@GET
@Path("/actions")
public Response listActions(
@Context HttpHeaders headers,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken) {
return ok(service.listActions(region(headers), parseMaxResults(maxResults), nextToken));
}
@GET
@Path("/experiments/{experimentId}/resolvedTargets")
public Response listExperimentResolvedTargets(
@Context HttpHeaders headers,
@PathParam("experimentId") String experimentId,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken,
@QueryParam("targetName") String targetName) {
return ok(service.listExperimentResolvedTargets(
region(headers), experimentId, parseMaxResults(maxResults), nextToken, targetName));
}
@GET
@Path("/experiments/{experimentId}/targetAccountConfigurations")
public Response listExperimentTargetAccountConfigurations(
@Context HttpHeaders headers,
@PathParam("experimentId") String experimentId,
@QueryParam("nextToken") String nextToken) {
return ok(service.listExperimentTargetAccountConfigurations(region(headers), experimentId, nextToken));
}
@GET
@Path("/experimentTemplates")
public Response listExperimentTemplates(
@Context HttpHeaders headers,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken) {
return ok(service.listExperimentTemplates(region(headers), parseMaxResults(maxResults), nextToken));
}
@GET
@Path("/experiments")
public Response listExperiments(
@Context HttpHeaders headers,
@QueryParam("experimentTemplateId") String experimentTemplateId,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken) {
return ok(service.listExperiments(
region(headers), parseMaxResults(maxResults), nextToken, experimentTemplateId));
}
@GET
@Path("/experimentTemplates/{experimentTemplateId}/targetAccountConfigurations")
public Response listTargetAccountConfigurations(
@Context HttpHeaders headers,
@PathParam("experimentTemplateId") String experimentTemplateId,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken) {
return ok(service.listTargetAccountConfigurations(
region(headers), experimentTemplateId, parseMaxResults(maxResults), nextToken));
}
@GET
@Path("/targetResourceTypes")
public Response listTargetResourceTypes(
@Context HttpHeaders headers,
@QueryParam("maxResults") String maxResults,
@QueryParam("nextToken") String nextToken) {
return ok(service.listTargetResourceTypes(region(headers), parseMaxResults(maxResults), nextToken));
}
@POST
@Path("/experiments")
public Response startExperiment(@Context HttpHeaders headers, String body) {
return ok(service.startExperiment(region(headers), parse(body)));
}
@DELETE
@Path("/experiments/{id}")
public Response stopExperiment(@Context HttpHeaders headers, @PathParam("id") String id) {
return ok(service.stopExperiment(region(headers), id));
}
@PATCH
@Path("/experimentTemplates/{id}")
public Response updateExperimentTemplate(
@Context HttpHeaders headers, @PathParam("id") String id, String body) {
return ok(service.updateExperimentTemplate(region(headers), id, parse(body)));
}
@PATCH
@Path("/safetyLevers/{id}/state")
public Response updateSafetyLeverState(
@Context HttpHeaders headers, @PathParam("id") String id, String body) {
return ok(service.updateSafetyLeverState(region(headers), id, parse(body)));
}
@PATCH
@Path("/experimentTemplates/{experimentTemplateId}/targetAccountConfigurations/{accountId}")
public Response updateTargetAccountConfiguration(
@Context HttpHeaders headers,
@PathParam("experimentTemplateId") String experimentTemplateId,
@PathParam("accountId") String accountId,
String body) {
return ok(service.updateTargetAccountConfiguration(
region(headers), experimentTemplateId, accountId, parse(body)));
}
private JsonNode parse(String body) {
if (body == null || body.isBlank()) {
return objectMapper.createObjectNode();
}
try {
JsonNode request = requestReader.readTree(body);
if (request == null || !request.isObject()) {
throw validation("Request body must be a JSON object.");
}
return request;
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw validation("Request body is not valid JSON.");
}
}
private Integer parseMaxResults(String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return Integer.valueOf(value);
} catch (NumberFormatException e) {
throw validation("maxResults must be an integer between 1 and 100.");
}
}
private String region(HttpHeaders headers) {
return regionResolver.resolveRegion(headers);
}
private Response ok(JsonNode entity) {
return Response.ok(entity).build();
}
private AwsException validation(String message) {
return new AwsException("ValidationException", message, 400);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,70 @@
package io.github.hectorvent.floci.services.fis;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
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 java.util.Map;
final class FisStores {
final StorageBackend<String, ExperimentTemplate> templates;
final StorageBackend<String, Experiment> experiments;
final StorageBackend<String, TargetAccountConfiguration> targetAccounts;
final StorageBackend<String, ResolvedTarget> resolvedTargets;
final StorageBackend<String, SafetyLever> safetyLevers;
final StorageBackend<String, Map<String, String>> actionTags;
final StorageBackend<String, IdempotencyRecord> idempotency;
FisStores(StorageFactory storageFactory) {
this(
storageFactory.create("fis", "fis-experiment-templates.json",
new TypeReference<Map<String, ExperimentTemplate>>() {}),
storageFactory.create("fis", "fis-experiments.json",
new TypeReference<Map<String, Experiment>>() {}),
storageFactory.create("fis", "fis-target-account-configurations.json",
new TypeReference<Map<String, TargetAccountConfiguration>>() {}),
storageFactory.create("fis", "fis-resolved-targets.json",
new TypeReference<Map<String, ResolvedTarget>>() {}),
storageFactory.create("fis", "fis-safety-levers.json",
new TypeReference<Map<String, SafetyLever>>() {}),
storageFactory.create("fis", "fis-action-tags.json",
new TypeReference<Map<String, Map<String, String>>>() {}),
storageFactory.create("fis", "fis-idempotency.json",
new TypeReference<Map<String, IdempotencyRecord>>() {}));
}
FisStores(
StorageBackend<String, ExperimentTemplate> templates,
StorageBackend<String, Experiment> experiments,
StorageBackend<String, TargetAccountConfiguration> targetAccounts,
StorageBackend<String, ResolvedTarget> resolvedTargets,
StorageBackend<String, SafetyLever> safetyLevers,
StorageBackend<String, Map<String, String>> actionTags,
StorageBackend<String, IdempotencyRecord> idempotency) {
this.templates = templates;
this.experiments = experiments;
this.targetAccounts = targetAccounts;
this.resolvedTargets = resolvedTargets;
this.safetyLevers = safetyLevers;
this.actionTags = actionTags;
this.idempotency = idempotency;
}
static FisStores inMemory() {
return new FisStores(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new InMemoryStorage<>());
}
}
@@ -0,0 +1,169 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Experiment {
private String id;
private String arn;
private String experimentTemplateId;
private String roleArn;
private ExperimentState state;
private Map<String, ExperimentTarget> targets;
private Map<String, ExperimentAction> actions;
private List<StopCondition> stopConditions;
private double creationTime;
private Double startTime;
private Double endTime;
private Map<String, String> tags;
private JsonNode logConfiguration;
private ExperimentOptions experimentOptions;
private long targetAccountConfigurationsCount;
private JsonNode experimentReportConfiguration;
private JsonNode experimentReport;
public Experiment() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getArn() {
return arn;
}
public void setArn(String arn) {
this.arn = arn;
}
public String getExperimentTemplateId() {
return experimentTemplateId;
}
public void setExperimentTemplateId(String experimentTemplateId) {
this.experimentTemplateId = experimentTemplateId;
}
public String getRoleArn() {
return roleArn;
}
public void setRoleArn(String roleArn) {
this.roleArn = roleArn;
}
public ExperimentState getState() {
return state;
}
public void setState(ExperimentState state) {
this.state = state;
}
public Map<String, ExperimentTarget> getTargets() {
return targets;
}
public void setTargets(Map<String, ExperimentTarget> targets) {
this.targets = targets;
}
public Map<String, ExperimentAction> getActions() {
return actions;
}
public void setActions(Map<String, ExperimentAction> actions) {
this.actions = actions;
}
public List<StopCondition> getStopConditions() {
return stopConditions;
}
public void setStopConditions(List<StopCondition> stopConditions) {
this.stopConditions = stopConditions;
}
public double getCreationTime() {
return creationTime;
}
public void setCreationTime(double creationTime) {
this.creationTime = creationTime;
}
public Double getStartTime() {
return startTime;
}
public void setStartTime(Double startTime) {
this.startTime = startTime;
}
public Double getEndTime() {
return endTime;
}
public void setEndTime(Double endTime) {
this.endTime = endTime;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public JsonNode getLogConfiguration() {
return logConfiguration;
}
public void setLogConfiguration(JsonNode logConfiguration) {
this.logConfiguration = logConfiguration;
}
public ExperimentOptions getExperimentOptions() {
return experimentOptions;
}
public void setExperimentOptions(ExperimentOptions experimentOptions) {
this.experimentOptions = experimentOptions;
}
public long getTargetAccountConfigurationsCount() {
return targetAccountConfigurationsCount;
}
public void setTargetAccountConfigurationsCount(long targetAccountConfigurationsCount) {
this.targetAccountConfigurationsCount = targetAccountConfigurationsCount;
}
public JsonNode getExperimentReportConfiguration() {
return experimentReportConfiguration;
}
public void setExperimentReportConfiguration(JsonNode experimentReportConfiguration) {
this.experimentReportConfiguration = experimentReportConfiguration;
}
public JsonNode getExperimentReport() {
return experimentReport;
}
public void setExperimentReport(JsonNode experimentReport) {
this.experimentReport = experimentReport;
}
}
@@ -0,0 +1,87 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ExperimentAction {
private String actionId;
private String description;
private Map<String, String> parameters;
private Map<String, String> targets;
private List<String> startAfter;
private ExperimentActionState state;
private Double startTime;
private Double endTime;
public ExperimentAction() {
}
public String getActionId() {
return actionId;
}
public void setActionId(String actionId) {
this.actionId = actionId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public Map<String, String> getTargets() {
return targets;
}
public void setTargets(Map<String, String> targets) {
this.targets = targets;
}
public List<String> getStartAfter() {
return startAfter;
}
public void setStartAfter(List<String> startAfter) {
this.startAfter = startAfter;
}
public ExperimentActionState getState() {
return state;
}
public void setState(ExperimentActionState state) {
this.state = state;
}
public Double getStartTime() {
return startTime;
}
public void setStartTime(Double startTime) {
this.startTime = startTime;
}
public Double getEndTime() {
return endTime;
}
public void setEndTime(Double endTime) {
this.endTime = endTime;
}
}
@@ -0,0 +1,30 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ExperimentActionState {
private String status;
private String reason;
public ExperimentActionState() {
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
}
@@ -0,0 +1,39 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ExperimentOptions {
private String accountTargeting;
private String emptyTargetResolutionMode;
private String actionsMode;
public ExperimentOptions() {
}
public String getAccountTargeting() {
return accountTargeting;
}
public void setAccountTargeting(String accountTargeting) {
this.accountTargeting = accountTargeting;
}
public String getEmptyTargetResolutionMode() {
return emptyTargetResolutionMode;
}
public void setEmptyTargetResolutionMode(String emptyTargetResolutionMode) {
this.emptyTargetResolutionMode = emptyTargetResolutionMode;
}
public String getActionsMode() {
return actionsMode;
}
public void setActionsMode(String actionsMode) {
this.actionsMode = actionsMode;
}
}
@@ -0,0 +1,40 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ExperimentState {
private String status;
private String reason;
private JsonNode error;
public ExperimentState() {
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public JsonNode getError() {
return error;
}
public void setError(JsonNode error) {
this.error = error;
}
}
@@ -0,0 +1,69 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ExperimentTarget {
private String resourceType;
private List<String> resourceArns;
private Map<String, String> resourceTags;
private List<TargetFilter> filters;
private String selectionMode;
private Map<String, String> parameters;
public ExperimentTarget() {
}
public String getResourceType() {
return resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public List<String> getResourceArns() {
return resourceArns;
}
public void setResourceArns(List<String> resourceArns) {
this.resourceArns = resourceArns;
}
public Map<String, String> getResourceTags() {
return resourceTags;
}
public void setResourceTags(Map<String, String> resourceTags) {
this.resourceTags = resourceTags;
}
public List<TargetFilter> getFilters() {
return filters;
}
public void setFilters(List<TargetFilter> filters) {
this.filters = filters;
}
public String getSelectionMode() {
return selectionMode;
}
public void setSelectionMode(String selectionMode) {
this.selectionMode = selectionMode;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
}
@@ -0,0 +1,142 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ExperimentTemplate {
private String id;
private String arn;
private String description;
private Map<String, ExperimentTemplateTarget> targets;
private Map<String, ExperimentTemplateAction> actions;
private List<StopCondition> stopConditions;
private double creationTime;
private double lastUpdateTime;
private String roleArn;
private Map<String, String> tags;
private JsonNode logConfiguration;
private ExperimentTemplateOptions experimentOptions;
private long targetAccountConfigurationsCount;
private JsonNode experimentReportConfiguration;
public ExperimentTemplate() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getArn() {
return arn;
}
public void setArn(String arn) {
this.arn = arn;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Map<String, ExperimentTemplateTarget> getTargets() {
return targets;
}
public void setTargets(Map<String, ExperimentTemplateTarget> targets) {
this.targets = targets;
}
public Map<String, ExperimentTemplateAction> getActions() {
return actions;
}
public void setActions(Map<String, ExperimentTemplateAction> actions) {
this.actions = actions;
}
public List<StopCondition> getStopConditions() {
return stopConditions;
}
public void setStopConditions(List<StopCondition> stopConditions) {
this.stopConditions = stopConditions;
}
public double getCreationTime() {
return creationTime;
}
public void setCreationTime(double creationTime) {
this.creationTime = creationTime;
}
public double getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(double lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public String getRoleArn() {
return roleArn;
}
public void setRoleArn(String roleArn) {
this.roleArn = roleArn;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(Map<String, String> tags) {
this.tags = tags;
}
public JsonNode getLogConfiguration() {
return logConfiguration;
}
public void setLogConfiguration(JsonNode logConfiguration) {
this.logConfiguration = logConfiguration;
}
public ExperimentTemplateOptions getExperimentOptions() {
return experimentOptions;
}
public void setExperimentOptions(ExperimentTemplateOptions experimentOptions) {
this.experimentOptions = experimentOptions;
}
public long getTargetAccountConfigurationsCount() {
return targetAccountConfigurationsCount;
}
public void setTargetAccountConfigurationsCount(long targetAccountConfigurationsCount) {
this.targetAccountConfigurationsCount = targetAccountConfigurationsCount;
}
public JsonNode getExperimentReportConfiguration() {
return experimentReportConfiguration;
}
public void setExperimentReportConfiguration(JsonNode experimentReportConfiguration) {
this.experimentReportConfiguration = experimentReportConfiguration;
}
}
@@ -0,0 +1,60 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ExperimentTemplateAction {
private String actionId;
private String description;
private Map<String, String> parameters;
private Map<String, String> targets;
private List<String> startAfter;
public ExperimentTemplateAction() {
}
public String getActionId() {
return actionId;
}
public void setActionId(String actionId) {
this.actionId = actionId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
public Map<String, String> getTargets() {
return targets;
}
public void setTargets(Map<String, String> targets) {
this.targets = targets;
}
public List<String> getStartAfter() {
return startAfter;
}
public void setStartAfter(List<String> startAfter) {
this.startAfter = startAfter;
}
}
@@ -0,0 +1,30 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ExperimentTemplateOptions {
private String accountTargeting;
private String emptyTargetResolutionMode;
public ExperimentTemplateOptions() {
}
public String getAccountTargeting() {
return accountTargeting;
}
public void setAccountTargeting(String accountTargeting) {
this.accountTargeting = accountTargeting;
}
public String getEmptyTargetResolutionMode() {
return emptyTargetResolutionMode;
}
public void setEmptyTargetResolutionMode(String emptyTargetResolutionMode) {
this.emptyTargetResolutionMode = emptyTargetResolutionMode;
}
}
@@ -0,0 +1,69 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
import java.util.Map;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ExperimentTemplateTarget {
private String resourceType;
private List<String> resourceArns;
private Map<String, String> resourceTags;
private List<TargetFilter> filters;
private String selectionMode;
private Map<String, String> parameters;
public ExperimentTemplateTarget() {
}
public String getResourceType() {
return resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public List<String> getResourceArns() {
return resourceArns;
}
public void setResourceArns(List<String> resourceArns) {
this.resourceArns = resourceArns;
}
public Map<String, String> getResourceTags() {
return resourceTags;
}
public void setResourceTags(Map<String, String> resourceTags) {
this.resourceTags = resourceTags;
}
public List<TargetFilter> getFilters() {
return filters;
}
public void setFilters(List<TargetFilter> filters) {
this.filters = filters;
}
public String getSelectionMode() {
return selectionMode;
}
public void setSelectionMode(String selectionMode) {
this.selectionMode = selectionMode;
}
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
}
@@ -0,0 +1,36 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class IdempotencyRecord {
private ObjectNode request;
private ObjectNode response;
public IdempotencyRecord() {
}
public IdempotencyRecord(ObjectNode request, ObjectNode response) {
this.request = request;
this.response = response;
}
public ObjectNode getRequest() {
return request;
}
public void setRequest(ObjectNode request) {
this.request = request;
}
public ObjectNode getResponse() {
return response;
}
public void setResponse(ObjectNode response) {
this.response = response;
}
}
@@ -0,0 +1,41 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.Map;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResolvedTarget {
private String resourceType;
private String targetName;
private Map<String, String> targetInformation;
public ResolvedTarget() {
}
public String getResourceType() {
return resourceType;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public String getTargetName() {
return targetName;
}
public void setTargetName(String targetName) {
this.targetName = targetName;
}
public Map<String, String> getTargetInformation() {
return targetInformation;
}
public void setTargetInformation(Map<String, String> targetInformation) {
this.targetInformation = targetInformation;
}
}
@@ -0,0 +1,39 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SafetyLever {
private String id;
private String arn;
private SafetyLeverState state;
public SafetyLever() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getArn() {
return arn;
}
public void setArn(String arn) {
this.arn = arn;
}
public SafetyLeverState getState() {
return state;
}
public void setState(SafetyLeverState state) {
this.state = state;
}
}
@@ -0,0 +1,30 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SafetyLeverState {
private String status;
private String reason;
public SafetyLeverState() {
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
}
@@ -0,0 +1,30 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class StopCondition {
private String source;
private String value;
public StopCondition() {
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
@@ -0,0 +1,39 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class TargetAccountConfiguration {
private String roleArn;
private String accountId;
private String description;
public TargetAccountConfiguration() {
}
public String getRoleArn() {
return roleArn;
}
public void setRoleArn(String roleArn) {
this.roleArn = roleArn;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
@@ -0,0 +1,32 @@
package io.github.hectorvent.floci.services.fis.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.List;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class TargetFilter {
private String path;
private List<String> values;
public TargetFilter() {
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public List<String> getValues() {
return values;
}
public void setValues(List<String> values) {
this.values = values;
}
}
+4
View File
@@ -157,6 +157,8 @@ floci:
flush-interval-ms: 5000
rum:
flush-interval-ms: 5000
fis:
flush-interval-ms: 5000
guardduty:
flush-interval-ms: 5000
emrserverless:
@@ -477,6 +479,8 @@ floci:
backup:
enabled: true
job-completion-delay-seconds: 3
fis:
enabled: true
route53:
enabled: true
transfer:
@@ -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>"));
}
+4
View File
@@ -73,6 +73,8 @@ floci:
flush-interval-ms: 60000
rum:
flush-interval-ms: 60000
fis:
flush-interval-ms: 60000
guardduty:
flush-interval-ms: 60000
emrserverless:
@@ -277,6 +279,8 @@ floci:
backup:
enabled: true
job-completion-delay-seconds: 1
fis:
enabled: true
route53:
enabled: true
textract:
+13
View File
@@ -54,6 +54,19 @@ services:
doc: docs/services/firehose.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/firehose/FirehoseJsonHandler.java, mode: switch }
- service: fis
doc: docs/services/fis.md
sources:
- { path: src/main/java/io/github/hectorvent/floci/services/fis/FisController.java, mode: rest }
- { path: src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java, mode: rest }
rename_actions:
ListTags: ListTagsForResource
TagResourcePost: TagResource
exclude_actions:
- ListTagsByQuery
- TagResourceByBody
- TagResourcePut
- UntagResourceByQuery
- service: kinesis
doc: docs/services/kinesis.md
sources: