Light, fluffy, and always free - The AWS Local Emulator alternative
feat(fis): add AWS FIS support (#2435)
Alex Banna04d120fdd5f0
diff --git a/README.md b/README.mdindex 45cc35805a..1579f253b7 100644--- a/README.md+++ b/README.md@@ -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 LRRouter["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"]endsubgraph 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 |diff --git a/compatibility-tests/sdk-test-awscli/test/fis.bats b/compatibility-tests/sdk-test-awscli/test/fis.batsnew file mode 100644index 0000000000..b5033e6387--- /dev/null+++ b/compatibility-tests/sdk-test-awscli/test/fis.bats@@ -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=""+}diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xmlindex 98ca85b817..ad5872292d 100644--- a/compatibility-tests/sdk-test-java/pom.xml+++ b/compatibility-tests/sdk-test-java/pom.xml@@ -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>diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.javaindex 7063e5b814..44c8a6d25a 100644--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java@@ -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)diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FisTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FisTest.javanew file mode 100644index 0000000000..61933b3e5c--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/FisTest.java@@ -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);+ }+ }+ }+}diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.mdindex 4dac5fddbe..0834e20350 100644--- a/docs/configuration/advanced/application-yml.md+++ b/docs/configuration/advanced/application-yml.md@@ -76,6 +76,8 @@ floci:flush-interval-ms: 5000opensearch:flush-interval-ms: 5000+ fis:+ flush-interval-ms: 5000dns:# 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: trueregistry-image: "registry:2"diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.mdindex a08ca653bb..a246ef8890 100644--- a/docs/configuration/environment-variables.md+++ b/docs/configuration/environment-variables.md@@ -78,7 +78,7 @@ FLOCI_STORAGE_SERVICES_<SERVICE>_MODE=hybridFLOCI_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 |diff --git a/docs/index.md b/docs/index.mdindex 9bd266b971..f61e7b0ec7 100644--- a/docs/index.md+++ b/docs/index.md@@ -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 -daws --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 }diff --git a/docs/services/fis.md b/docs/services/fis.mdnew file mode 100644index 0000000000..7af0a34e5c--- /dev/null+++ b/docs/services/fis.md@@ -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.diff --git a/docs/services/index.md b/docs/services/index.mdindex ca94de370c..8b69f3f346 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -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 |diff --git a/mkdocs.yml b/mkdocs.ymlindex c5dffe8f84..cc4925c3d9 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -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.mddiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex ca13b50e79..d6ef0b2241 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -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();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsRestJsonErrorHeaderFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsRestJsonErrorHeaderFilter.javanew file mode 100644index 0000000000..f954851bb6--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsRestJsonErrorHeaderFilter.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex 6006db8887..ca6ee2b7ca 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.bedrockruntime.BedrockRuntimeControllimport 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),diff --git a/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java b/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.javaindex 1010cbdbee..e3525b238d 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java@@ -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);}diff --git a/src/main/java/io/github/hectorvent/floci/core/common/TagHandler.java b/src/main/java/io/github/hectorvent/floci/core/common/TagHandler.javaindex b88923d5d8..fb9c80223e 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/TagHandler.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/TagHandler.java@@ -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);diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/FisCatalog.java b/src/main/java/io/github/hectorvent/floci/services/fis/FisCatalog.javanew file mode 100644index 0000000000..2f57fdbf41--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/FisCatalog.java@@ -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) {}+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/FisController.java b/src/main/java/io/github/hectorvent/floci/services/fis/FisController.javanew file mode 100644index 0000000000..a89258d5ef--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/FisController.java@@ -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);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/FisService.java b/src/main/java/io/github/hectorvent/floci/services/fis/FisService.javanew file mode 100644index 0000000000..0488fc0c3b--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/FisService.java@@ -0,0 +1,1727 @@+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.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.TagHandler;+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 jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;++import java.math.BigInteger;+import java.nio.charset.StandardCharsets;+import java.time.Instant;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Base64;+import java.util.Collections;+import java.util.Comparator;+import java.util.HashMap;+import java.util.HashSet;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Random;+import java.util.Set;+import java.util.UUID;+import java.util.function.Function;+import java.util.random.RandomGenerator;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++/**+ * Stateful AWS Fault Injection Service control plane.+ *+ * <p>Experiments are intentionally management-plane only: Floci records valid FIS state+ * transitions and resolved target snapshots without applying faults to local resources.</p>+ */+@ApplicationScoped+public class FisService implements TagHandler {++ private static final String SERVICE = "fis";+ private static final int MAX_PAGE_SIZE = 100;+ private static final int MAX_TAGS = 50;+ private static final int MAX_ACTIONS = 20;+ private static final int MAX_PARALLEL_ACTIONS = 10;+ private static final int MAX_STOP_CONDITIONS = 5;+ private static final int MAX_TARGET_ACCOUNTS = 40;+ private static final int MAX_EXPERIMENT_TEMPLATES = 500;+ private static final int MAX_ACTIVE_EXPERIMENTS = 5;+ private static final Set<String> TERMINAL_EXPERIMENT_STATES =+ Set.of("completed", "stopped", "failed", "cancelled");+ private static final Set<String> TEMPLATE_OPTION_FIELDS =+ Set.of("accountTargeting", "emptyTargetResolutionMode");+ private static final Set<String> UPDATE_TEMPLATE_FIELDS = Set.of(+ "actions", "description", "experimentOptions", "experimentReportConfiguration",+ "logConfiguration", "roleArn", "stopConditions", "targets");+ private static final Pattern COUNT_SELECTION = Pattern.compile("COUNT\\(([1-9][0-9]*)\\)");+ private static final Pattern PERCENT_SELECTION = Pattern.compile("PERCENT\\(([1-9][0-9]?|100)\\)");+ private static final Pattern TARGET_PARAMETER_VALUE =+ Pattern.compile("^[\\p{L}\\p{Z}\\p{N}_.:/=+\\-@]+$");+ private static final Pattern TAG_VALUE = Pattern.compile("^[A-Za-z0-9 _.:/=+\\-@]*$");++ private final FisStores stores;+ private final ObjectMapper mapper;+ private final RegionResolver regionResolver;+ private final FisCatalog catalog;+ private final RandomGenerator random;++ @Inject+ public FisService(StorageFactory storageFactory, ObjectMapper mapper,+ RegionResolver regionResolver, FisCatalog catalog) {+ this(new FisStores(storageFactory), mapper, regionResolver, catalog, new Random());+ }++ FisService(FisStores stores, ObjectMapper mapper,+ RegionResolver regionResolver, FisCatalog catalog) {+ this(stores, mapper, regionResolver, catalog, new Random());+ }++ FisService(FisStores stores, ObjectMapper mapper,+ RegionResolver regionResolver, FisCatalog catalog, RandomGenerator random) {+ this.stores = stores;+ this.mapper = mapper;+ this.regionResolver = regionResolver;+ this.catalog = catalog;+ this.random = random;+ }++ public synchronized ObjectNode createExperimentTemplate(String region, JsonNode request) {+ ObjectNode input = requireRequest(request);+ String clientToken = requireToken(input, "clientToken");+ ObjectNode existing = idempotentResponse(region, "create-template", clientToken, input);+ if (existing != null) {+ return existing;+ }+ validateCreateTemplate(input);+ if (copiedScan(stores.templates, templatePrefix(region)).size() >= MAX_EXPERIMENT_TEMPLATES) {+ throw new AwsException("ServiceQuotaExceededException",+ "The experiment template quota has been exceeded.", 402);+ }++ String id = newId(region, "template", "EXT");+ double timestamp = now();+ ObjectNode template = mapper.createObjectNode();+ template.put("id", id);+ template.put("arn", regionResolver.buildArn(SERVICE, region, "experiment-template/" + id));+ template.put("description", input.path("description").asText());+ template.set("targets", copyObject(input.path("targets")));+ template.set("actions", input.path("actions").deepCopy());+ template.set("stopConditions", input.path("stopConditions").deepCopy());+ template.put("creationTime", timestamp);+ template.put("lastUpdateTime", timestamp);+ template.put("roleArn", input.path("roleArn").asText());+ template.set("tags", tagsNode(readTagsInput(input.path("tags"))));+ template.set("experimentOptions", templateOptions(input.path("experimentOptions")));+ template.put("targetAccountConfigurationsCount", 0L);+ copyIfPresent(input, template, "logConfiguration");+ copyIfPresent(input, template, "experimentReportConfiguration");++ putTemplate(region, id, template);+ ObjectNode response = wrap("experimentTemplate", template);+ saveIdempotentResponse(region, "create-template", clientToken, input, response);+ return response;+ }++ public synchronized ObjectNode createTargetAccountConfiguration(+ String region, String experimentTemplateId, String accountId, JsonNode request) {+ ObjectNode input = requireRequest(request);+ requireAccountId(accountId);+ String token = optionalToken(input, "clientToken");+ String operation = "create-target-account:" + experimentTemplateId + ":" + accountId;+ ObjectNode existing = idempotentResponse(region, operation, token, input);+ if (existing != null) {+ return existing;+ }+ ObjectNode template = requireTemplate(region, experimentTemplateId);+ if (!"multi-account".equals(template.path("experimentOptions").path("accountTargeting").asText())) {+ throw conflict("Target account configurations require accountTargeting to be multi-account.");+ }+ if (stores.targetAccounts.get(targetAccountKey(region, experimentTemplateId, accountId)).isPresent()) {+ throw conflict("A target account configuration already exists for account " + accountId + ".");+ }+ if (targetAccountConfigurations(region, experimentTemplateId).size() >= MAX_TARGET_ACCOUNTS) {+ throw new AwsException("ServiceQuotaExceededException",+ "The target account configuration quota has been exceeded.", 402);+ }+ String roleArn = requireArn(input, "roleArn");+ if (input.has("description")) {+ validateOptionalDescription(input, "description", true);+ }++ ObjectNode configuration = mapper.createObjectNode();+ configuration.put("accountId", accountId);+ configuration.put("roleArn", roleArn);+ if (input.has("description")) {+ configuration.put("description", input.path("description").asText());+ }+ putTargetAccountConfiguration(+ targetAccountKey(region, experimentTemplateId, accountId), configuration);+ updateTemplateTargetAccountCount(region, experimentTemplateId);+ ObjectNode response = wrap("targetAccountConfiguration", configuration);+ saveIdempotentResponse(region, operation, token, input, response);+ return response;+ }++ public synchronized ObjectNode deleteExperimentTemplate(String region, String id) {+ ObjectNode template = requireTemplate(region, id);+ stores.templates.delete(templateKey(region, id));+ deleteByPrefix(stores.targetAccounts, targetAccountPrefix(region, id));+ return wrap("experimentTemplate", template);+ }++ public synchronized ObjectNode deleteTargetAccountConfiguration(+ String region, String experimentTemplateId, String accountId) {+ requireTemplate(region, experimentTemplateId);+ ObjectNode configuration = requireTargetAccountConfiguration(region, experimentTemplateId, accountId);+ stores.targetAccounts.delete(targetAccountKey(region, experimentTemplateId, accountId));+ updateTemplateTargetAccountCount(region, experimentTemplateId);+ return wrap("targetAccountConfiguration", configuration);+ }++ public ObjectNode getAction(String region, String id) {+ ObjectNode action = catalog.action(region, id);+ if (action == null) {+ throw notFound("Action", id);+ }+ action.set("tags", actionTags(region, id));+ return wrap("action", action);+ }++ public ObjectNode getExperiment(String region, String id) {+ return wrap("experiment", requireExperiment(region, id));+ }++ public ObjectNode getExperimentTargetAccountConfiguration(+ String region, String experimentId, String accountId) {+ requireExperiment(region, experimentId);+ ObjectNode configuration = stores.targetAccounts+ .get(experimentTargetAccountKey(region, experimentId, accountId))+ .map(this::toObjectNode)+ .orElseThrow(() -> notFound("Experiment target account configuration", accountId));+ return wrap("targetAccountConfiguration", configuration);+ }++ public ObjectNode getExperimentTemplate(String region, String id) {+ return wrap("experimentTemplate", requireTemplate(region, id));+ }++ public synchronized ObjectNode getSafetyLever(String region, String id) {+ return wrap("safetyLever", requireSafetyLever(region, id));+ }++ public ObjectNode getTargetAccountConfiguration(+ String region, String experimentTemplateId, String accountId) {+ requireTemplate(region, experimentTemplateId);+ return wrap("targetAccountConfiguration",+ requireTargetAccountConfiguration(region, experimentTemplateId, accountId));+ }++ public ObjectNode getTargetResourceType(String region, String resourceType) {+ ObjectNode targetResourceType = catalog.targetResourceType(resourceType);+ if (targetResourceType == null) {+ throw notFound("Target resource type", resourceType);+ }+ return wrap("targetResourceType", targetResourceType);+ }++ public ObjectNode listActions(String region, Integer maxResults, String nextToken) {+ List<ObjectNode> actions = catalog.actionSummaries(region);+ actions.forEach(action -> action.set("tags", actionTags(region, action.path("id").asText())));+ return page("actions", actions, maxResults, nextToken, scope(region, "actions"),+ node -> node.path("id").asText());+ }++ public ObjectNode listExperimentResolvedTargets(+ String region, String experimentId, Integer maxResults, String nextToken, String targetName) {+ requireExperiment(region, experimentId);+ if (targetName != null) {+ validateName(targetName, "targetName");+ }+ List<ObjectNode> resolvedTargets =+ copiedScan(stores.resolvedTargets, resolvedTargetPrefix(region, experimentId));+ if (targetName != null) {+ resolvedTargets.removeIf(target -> !targetName.equals(target.path("targetName").asText()));+ }+ String filter = targetName == null ? "" : targetName;+ return page("resolvedTargets", resolvedTargets, maxResults, nextToken,+ scope(region, "resolved-targets:" + experimentId + ":" + filter), this::resolvedTargetCursor);+ }++ public ObjectNode listExperimentTargetAccountConfigurations(+ String region, String experimentId, String nextToken) {+ requireExperiment(region, experimentId);+ List<ObjectNode> configurations =+ copiedScan(stores.targetAccounts, experimentTargetAccountPrefix(region, experimentId));+ return page("targetAccountConfigurations", configurations, null, nextToken,+ scope(region, "experiment-target-accounts:" + experimentId),+ node -> node.path("accountId").asText());+ }++ public ObjectNode listExperimentTemplates(String region, Integer maxResults, String nextToken) {+ List<ObjectNode> summaries = copiedScan(stores.templates, templatePrefix(region)).stream()+ .map(this::templateSummary).toList();+ return page("experimentTemplates", summaries, maxResults, nextToken,+ scope(region, "templates"), node -> node.path("id").asText());+ }++ public ObjectNode listExperiments(+ String region, Integer maxResults, String nextToken, String experimentTemplateId) {+ List<ObjectNode> experiments = copiedScan(stores.experiments, experimentPrefix(region));+ if (experimentTemplateId != null) {+ validateName(experimentTemplateId, "experimentTemplateId");+ experiments.removeIf(experiment ->+ !experimentTemplateId.equals(experiment.path("experimentTemplateId").asText()));+ }+ List<ObjectNode> summaries = experiments.stream().map(this::experimentSummary).toList();+ String filter = experimentTemplateId == null ? "" : experimentTemplateId;+ return page("experiments", summaries, maxResults, nextToken,+ scope(region, "experiments:" + filter), node -> node.path("id").asText());+ }++ public ObjectNode listTargetAccountConfigurations(+ String region, String experimentTemplateId, Integer maxResults, String nextToken) {+ requireTemplate(region, experimentTemplateId);+ return page("targetAccountConfigurations", targetAccountConfigurations(region, experimentTemplateId),+ maxResults, nextToken, scope(region, "target-accounts:" + experimentTemplateId),+ node -> node.path("accountId").asText());+ }++ public ObjectNode listTargetResourceTypes(String region, Integer maxResults, String nextToken) {+ return page("targetResourceTypes", catalog.targetResourceTypeSummaries(), maxResults, nextToken,+ scope(region, "target-resource-types"), node -> node.path("resourceType").asText());+ }++ public synchronized ObjectNode startExperiment(String region, JsonNode request) {+ ObjectNode input = requireRequest(request);+ String clientToken = requireToken(input, "clientToken");+ ObjectNode existing = idempotentResponse(region, "start-experiment", clientToken, input);+ if (existing != null) {+ return existing;+ }+ String templateId = requireText(input, "experimentTemplateId", 64);+ ObjectNode template = requireTemplate(region, templateId);+ List<ObjectNode> configurations = targetAccountConfigurations(region, templateId);+ if ("multi-account".equals(template.path("experimentOptions").path("accountTargeting").asText())+ && configurations.isEmpty()) {+ throw validation("A multi-account experiment requires at least one target account configuration.");+ }+ Map<String, String> tags = readTagsInput(input.path("tags"));+ String actionsMode = validateActionsMode(input.path("experimentOptions"));+ if (activeExperimentCount(region) >= MAX_ACTIVE_EXPERIMENTS) {+ throw new AwsException("ServiceQuotaExceededException",+ "The active experiment quota has been exceeded.", 402);+ }++ String id = newId(region, "experiment", "EXP");+ double timestamp = now();+ ObjectNode experiment = mapper.createObjectNode();+ experiment.put("id", id);+ experiment.put("arn", regionResolver.buildArn(SERVICE, region, "experiment/" + id));+ experiment.put("experimentTemplateId", templateId);+ experiment.put("roleArn", template.path("roleArn").asText());+ experiment.put("creationTime", timestamp);+ experiment.set("targets", copyObject(template.path("targets")));+ experiment.set("stopConditions", template.path("stopConditions").deepCopy());+ experiment.set("tags", tagsNode(tags));+ ObjectNode options = copyObject(template.path("experimentOptions"));+ options.put("actionsMode", actionsMode);+ experiment.set("experimentOptions", options);+ copyIfPresent(template, experiment, "logConfiguration");+ copyIfPresent(template, experiment, "experimentReportConfiguration");++ experiment.put("targetAccountConfigurationsCount", configurations.size());+ configurations.forEach(configuration -> putTargetAccountConfiguration(+ experimentTargetAccountKey(region, id, configuration.path("accountId").asText()),+ configuration));+ Set<String> unresolvedTargets = persistResolvedTargets(region, id, experiment.path("targets"));++ ObjectNode safetyLever = requireSafetyLever(region, "default");+ boolean cancelled = "engaged".equals(safetyLever.path("state").path("status").asText());+ boolean skipAll = "skip-all".equals(actionsMode);+ boolean unresolvedUniqueIdentifier = unresolvedTargets.stream()+ .anyMatch(name -> experiment.path("targets").path(name).path("resourceArns").isArray());+ boolean failedResolution = !unresolvedTargets.isEmpty()+ && (unresolvedUniqueIdentifier+ || "fail".equals(options.path("emptyTargetResolutionMode").asText()));+ ObjectNode experimentActions = experiment.putObject("actions");+ template.path("actions").fields().forEachRemaining(entry -> {+ ObjectNode action = entry.getValue().deepCopy();+ boolean unresolvedActionTarget = usesTarget(action, unresolvedTargets);+ String status;+ String reason;+ if (cancelled) {+ status = "cancelled";+ reason = "The experiment was cancelled because the safety lever is engaged.";+ } else if (failedResolution) {+ status = unresolvedActionTarget ? "failed" : "cancelled";+ reason = unresolvedActionTarget+ ? "The action target did not resolve to any resources."+ : "The action was cancelled because target resolution failed.";+ } else if (skipAll) {+ status = "skipped";+ reason = "The action was skipped by the skip-all experiment option.";+ } else if (unresolvedActionTarget) {+ status = "skipped";+ reason = "The action was skipped because its target did not resolve to any resources.";+ } else if (action.path("startAfter").isArray() && !action.path("startAfter").isEmpty()) {+ status = "pending";+ reason = "The action is waiting for its dependencies.";+ } else {+ status = "running";+ reason = "The action is running in safe emulation mode.";+ }+ action.set("state", state(status, reason));+ if (!"pending".equals(status)) {+ action.put("startTime", timestamp);+ }+ if (cancelled || failedResolution || skipAll || unresolvedActionTarget) {+ action.put("endTime", timestamp);+ }+ experimentActions.set(entry.getKey(), action);+ });++ if (cancelled) {+ experiment.set("state", state("cancelled",+ "The experiment was cancelled because the safety lever is engaged."));+ experiment.put("endTime", timestamp);+ } else if (failedResolution) {+ experiment.set("state", state("failed",+ "The experiment failed because one or more targets did not resolve to any resources."));+ experiment.put("startTime", timestamp);+ experiment.put("endTime", timestamp);+ } else if (skipAll || allActionsHaveStatus(experimentActions, "skipped")) {+ experiment.set("state", state("completed",+ "The experiment completed with every action skipped."));+ experiment.put("startTime", timestamp);+ experiment.put("endTime", timestamp);+ } else {+ experiment.set("state", state("running", "The experiment is running in safe emulation mode."));+ experiment.put("startTime", timestamp);+ }++ putExperiment(region, id, experiment);+ ObjectNode response = wrap("experiment", experiment);+ saveIdempotentResponse(region, "start-experiment", clientToken, input, response);+ return response;+ }++ public synchronized ObjectNode stopExperiment(String region, String id) {+ ObjectNode experiment = requireExperiment(region, id);+ String current = experiment.path("state").path("status").asText();+ if (!TERMINAL_EXPERIMENT_STATES.contains(current)) {+ stopExperimentNode(experiment, "The experiment was stopped by the user.");+ putExperiment(region, id, experiment);+ }+ return wrap("experiment", experiment);+ }++ public synchronized ObjectNode updateExperimentTemplate(String region, String id, JsonNode request) {+ ObjectNode input = requireRequest(request);+ ObjectNode template = requireTemplate(region, id);+ if (input.has("logConfiguration")) {+ validateLogConfiguration(input.path("logConfiguration"), false);+ }+ if (input.hasNonNull("experimentReportConfiguration")) {+ validateExperimentReportConfiguration(input.path("experimentReportConfiguration"));+ }+ boolean changed = false;+ for (String field : UPDATE_TEMPLATE_FIELDS) {+ if (!input.has(field)) {+ continue;+ }+ changed = true;+ if ("experimentOptions".equals(field)) {+ ObjectNode patch = requireObject(input.path(field), field);+ ObjectNode options = copyObject(template.path(field));+ patch.fields().forEachRemaining(entry -> {+ if (!"emptyTargetResolutionMode".equals(entry.getKey())) {+ throw validation("Only emptyTargetResolutionMode can be updated in experimentOptions.");+ }+ options.set(entry.getKey(), entry.getValue().deepCopy());+ });+ template.set(field, options);+ } else {+ template.set(field, input.path(field).deepCopy());+ }+ }+ if (!changed) {+ throw validation("At least one experiment template field must be supplied.");+ }+ validateStoredTemplate(template);+ template.put("lastUpdateTime", now());+ putTemplate(region, id, template);+ return wrap("experimentTemplate", template);+ }++ public synchronized ObjectNode updateSafetyLeverState(String region, String id, JsonNode request) {+ ObjectNode input = requireRequest(request);+ requireSafetyLever(region, id);+ ObjectNode stateInput = requireObject(input.path("state"), "state");+ String status = requireText(stateInput, "status", 64);+ JsonNode reasonNode = stateInput.path("reason");+ if (!reasonNode.isTextual()) {+ throw validation("reason must be a string.");+ }+ String reason = reasonNode.asText();+ if (!Set.of("engaged", "disengaged").contains(status)) {+ throw validation("Safety lever status must be engaged or disengaged.");+ }+ if ("engaged".equals(status)) {+ for (ObjectNode experiment : copiedScan(stores.experiments, experimentPrefix(region))) {+ String experimentStatus = experiment.path("state").path("status").asText();+ if (!TERMINAL_EXPERIMENT_STATES.contains(experimentStatus)) {+ stopExperimentNode(experiment, "The experiment was stopped because the safety lever was engaged.");+ putExperiment(region, experiment.path("id").asText(), experiment);+ }+ }+ }+ ObjectNode lever = safetyLever(region, status, reason);+ putSafetyLever(region, id, lever);+ return wrap("safetyLever", lever);+ }++ public synchronized ObjectNode updateTargetAccountConfiguration(+ String region, String experimentTemplateId, String accountId, JsonNode request) {+ ObjectNode input = requireRequest(request);+ requireTemplate(region, experimentTemplateId);+ ObjectNode configuration = requireTargetAccountConfiguration(region, experimentTemplateId, accountId);+ boolean changed = false;+ if (input.has("description")) {+ validateOptionalDescription(input, "description", true);+ configuration.put("description", input.path("description").asText());+ changed = true;+ }+ if (input.has("roleArn")) {+ configuration.put("roleArn", requireArn(input, "roleArn"));+ changed = true;+ }+ if (!changed) {+ throw validation("description or roleArn must be supplied.");+ }+ putTargetAccountConfiguration(+ targetAccountKey(region, experimentTemplateId, accountId), configuration);+ return wrap("targetAccountConfiguration", configuration);+ }++ @Override+ public String serviceKey() {+ return SERVICE;+ }++ @Override+ public boolean strictTagValidation() {+ return true;+ }++ @Override+ public boolean allowEmptyTagKeys() {+ return true;+ }++ @Override+ public int tagResourceSuccessStatus() {+ return 200;+ }++ @Override+ public int untagResourceSuccessStatus() {+ return 200;+ }++ @Override+ public Map<String, String> listTags(String region, String arn) {+ ResourceRef resource = parseTaggableArn(region, arn);+ return switch (resource.type()) {+ case "action" -> tagsMap(actionTags(region, resource.id()));+ case "experiment" -> tagsMap(requireExperiment(region, resource.id()).path("tags"));+ case "experiment-template" -> tagsMap(requireTemplate(region, resource.id()).path("tags"));+ default -> throw validation("The ARN does not identify a taggable AWS FIS resource.");+ };+ }++ @Override+ public synchronized void tagResource(String region, String arn, Map<String, String> tags) {+ validateTags(tags);+ ResourceRef resource = parseTaggableArn(region, arn);+ ObjectNode current = switch (resource.type()) {+ case "action" -> actionTags(region, resource.id());+ case "experiment" -> copyObject(requireExperiment(region, resource.id()).path("tags"));+ case "experiment-template" -> copyObject(requireTemplate(region, resource.id()).path("tags"));+ default -> throw validation("The ARN does not identify a taggable AWS FIS resource.");+ };+ tags.forEach(current::put);+ if (current.size() > MAX_TAGS) {+ throw validation("A resource can have at most 50 tags.");+ }+ saveResourceTags(region, resource, current);+ }++ @Override+ public synchronized void untagResource(String region, String arn, List<String> tagKeys) {+ ResourceRef resource = parseTaggableArn(region, arn);+ ObjectNode current = switch (resource.type()) {+ case "action" -> actionTags(region, resource.id());+ case "experiment" -> copyObject(requireExperiment(region, resource.id()).path("tags"));+ case "experiment-template" -> copyObject(requireTemplate(region, resource.id()).path("tags"));+ default -> throw validation("The ARN does not identify a taggable AWS FIS resource.");+ };+ if (tagKeys == null || tagKeys.isEmpty()) {+ return;+ }+ tagKeys.forEach(this::validateTagKey);+ tagKeys.forEach(current::remove);+ saveResourceTags(region, resource, current);+ }++ private void validateCreateTemplate(ObjectNode input) {+ requireToken(input, "clientToken");+ validateOptionalDescription(input, "description", false);+ requireArn(input, "roleArn");+ readTagsInput(input.path("tags"));+ templateOptions(input.path("experimentOptions"));+ if (input.has("logConfiguration")) {+ validateLogConfiguration(input.path("logConfiguration"), true);+ }+ if (input.hasNonNull("experimentReportConfiguration")) {+ validateExperimentReportConfiguration(input.path("experimentReportConfiguration"));+ }+ ObjectNode candidate = mapper.createObjectNode();+ candidate.set("actions", input.path("actions").deepCopy());+ candidate.set("targets", copyObject(input.path("targets")));+ candidate.set("stopConditions", input.path("stopConditions").deepCopy());+ candidate.put("description", input.path("description").asText());+ candidate.put("roleArn", input.path("roleArn").asText());+ candidate.set("experimentOptions", templateOptions(input.path("experimentOptions")));+ validateStoredTemplate(candidate);+ }++ private void validateStoredTemplate(ObjectNode template) {+ validateOptionalDescription(template, "description", false);+ requireArn(template, "roleArn");+ ObjectNode targets = requireObject(template.path("targets"), "targets");+ validateTargets(targets);+ ObjectNode actions = requireObject(template.path("actions"), "actions");+ if (actions.isEmpty()) {+ throw validation("actions must contain at least one action.");+ }+ if (actions.size() > MAX_ACTIONS) {+ throw new AwsException("ServiceQuotaExceededException",+ "An experiment template can contain at most 20 actions.", 402);+ }+ validateActions(actions, targets);+ JsonNode stopConditions = template.path("stopConditions");+ if (!stopConditions.isArray() || stopConditions.isEmpty()) {+ throw validation("stopConditions must contain at least one stop condition.");+ }+ if (stopConditions.size() > MAX_STOP_CONDITIONS) {+ throw new AwsException("ServiceQuotaExceededException",+ "An experiment template can contain at most 5 stop conditions.", 402);+ }+ for (JsonNode condition : stopConditions) {+ if (!condition.isObject()) {+ throw validation("Each stop condition must be an object.");+ }+ String source = requireText((ObjectNode) condition, "source", 64);+ if (!Set.of("none", "aws:cloudwatch:alarm").contains(source)) {+ throw validation("Unsupported stop condition source: " + source + ".");+ }+ if ("aws:cloudwatch:alarm".equals(source)) {+ if (!condition.hasNonNull("value")) {+ throw validation("CloudWatch alarm stop conditions require a value.");+ }+ }+ if (condition.hasNonNull("value")) {+ JsonNode value = condition.path("value");+ if (!value.isTextual() || value.asText().length() < 20 || value.asText().length() > 2048) {+ throw validation("Stop condition values must contain between 20 and 2048 characters.");+ }+ }+ }+ templateOptions(template.path("experimentOptions"));+ }++ private void validateTargets(ObjectNode targets) {+ targets.fields().forEachRemaining(entry -> {+ validateName(entry.getKey(), "target name");+ ObjectNode target = requireObject(entry.getValue(), "target " + entry.getKey());+ String resourceType = requireText(target, "resourceType", 128);+ ObjectNode resourceTypeDefinition = catalog.targetResourceType(resourceType);+ if (resourceTypeDefinition == null) {+ throw validation("Unsupported target resource type: " + resourceType + ".");+ }+ String selectionMode = requireText(target, "selectionMode", 64);+ validateSelectionMode(selectionMode);+ boolean arns = target.hasNonNull("resourceArns");+ boolean tags = target.hasNonNull("resourceTags");+ boolean filters = target.hasNonNull("filters");+ ObjectNode parameters = target.hasNonNull("parameters")+ ? requireObject(target.path("parameters"), "target parameters")+ : mapper.createObjectNode();+ boolean parameterSelector = !parameters.isEmpty();+ if (arns && tags) {+ throw validation("A target cannot specify both resourceArns and resourceTags.");+ }+ if (!arns && !tags && !filters && !parameterSelector) {+ throw validation(+ "Each target must specify resourceArns, resourceTags, resource filters, or resource parameters.");+ }+ if ("aws:eks:pod".equals(resourceType) && (arns || tags || filters)) {+ throw validation("Targets of type aws:eks:pod must use resource parameters and do not support "+ + "resourceArns, resourceTags, or filters.");+ }+ if (arns) {+ JsonNode resourceArns = target.path("resourceArns");+ if (!resourceArns.isArray() || resourceArns.isEmpty() || resourceArns.size() > 5) {+ throw validation("resourceArns must contain between 1 and 5 ARNs.");+ }+ resourceArns.forEach(arn -> {+ if (!arn.isTextual()+ || arn.asText().length() < 20+ || arn.asText().length() > 2048+ || arn.asText().chars().anyMatch(Character::isWhitespace)) {+ throw validation("Every resource ARN must contain between 20 and 2048 "+ + "non-whitespace characters.");+ }+ });+ if (filters) {+ throw validation("A target cannot specify both resourceArns and filters.");+ }+ } else if (tags) {+ ObjectNode resourceTags = requireObject(target.path("resourceTags"), "resourceTags");+ if (resourceTags.isEmpty() || resourceTags.size() > 50) {+ throw validation("resourceTags must contain between 1 and 50 tags.");+ }+ resourceTags.fields().forEachRemaining(tag -> {+ if (tag.getKey().isEmpty() || tag.getKey().length() > 128+ || !tag.getValue().isTextual() || tag.getValue().asText().length() > 256) {+ throw validation("Resource tags must be string-to-string entries.");+ }+ });+ }++ ObjectNode parameterDefinitions = (ObjectNode) resourceTypeDefinition.path("parameters");+ parameters.fields().forEachRemaining(parameter -> {+ if (!parameterDefinitions.has(parameter.getKey())) {+ throw validation("Unsupported target parameter " + parameter.getKey()+ + " for resource type " + resourceType + ".");+ }+ if (parameter.getKey().length() > 64 || !parameter.getValue().isTextual()) {+ throw validation("Target parameters must be string-to-string entries.");+ }+ String value = parameter.getValue().asText();+ if (value.length() > 1024 || !TARGET_PARAMETER_VALUE.matcher(value).matches()) {+ throw validation("Target parameter values must contain between 1 and 1024 valid characters.");+ }+ });+ parameterDefinitions.fields().forEachRemaining(parameter -> {+ if (parameter.getValue().path("required").asBoolean()+ && !parameters.hasNonNull(parameter.getKey())) {+ throw validation("Target resource type " + resourceType+ + " requires parameter " + parameter.getKey() + ".");+ }+ });++ if (filters) {+ validateTargetFilters(target.path("filters"));+ }+ });+ }++ private void validateTargetFilters(JsonNode filters) {+ if (!filters.isArray() || filters.isEmpty()) {+ throw validation("filters must contain at least one filter.");+ }+ for (JsonNode filterNode : filters) {+ ObjectNode filter = requireObject(filterNode, "target filter");+ String path = requireText(filter, "path", 256);+ if (path.chars().anyMatch(Character::isWhitespace)) {+ throw validation("Filter paths must not contain whitespace.");+ }+ JsonNode values = filter.path("values");+ if (!values.isArray() || values.isEmpty()) {+ throw validation("Filter values must contain at least one value.");+ }+ values.forEach(value -> {+ if (!value.isTextual() || value.asText().isEmpty() || value.asText().length() > 128+ || value.asText().chars().anyMatch(Character::isWhitespace)) {+ throw validation("Filter values must be non-whitespace strings of at most 128 characters.");+ }+ });+ }+ }++ private void validateActions(ObjectNode actions, ObjectNode targets) {+ actions.fields().forEachRemaining(entry -> {+ String actionName = entry.getKey();+ validateName(actionName, "action name");+ ObjectNode action = requireObject(entry.getValue(), "action " + actionName);+ String actionId = requireText(action, "actionId", 128);+ ObjectNode actionDefinition = catalog.action(regionResolver.getRegion(), actionId);+ if (actionDefinition == null) {+ throw validation("Unsupported action ID: " + actionId + ".");+ }+ if (action.hasNonNull("description")) {+ JsonNode description = action.path("description");+ if (!description.isTextual()+ || description.asText().isEmpty()+ || description.asText().length() > 512) {+ throw validation("Action descriptions must contain between 1 and 512 characters.");+ }+ }+ ObjectNode parameters = action.has("parameters")+ ? requireObject(action.path("parameters"), "action parameters")+ : mapper.createObjectNode();+ parameters.fields().forEachRemaining(parameter -> {+ validateName(parameter.getKey(), "action parameter name");+ if (!parameter.getValue().isTextual()+ || parameter.getValue().asText().isEmpty()+ || parameter.getValue().asText().length() > 1024+ || parameter.getValue().asText().chars().anyMatch(Character::isWhitespace)) {+ throw validation("Action parameters must contain between 1 and 1024 "+ + "non-whitespace characters.");+ }+ if (!actionDefinition.path("parameters").has(parameter.getKey())) {+ throw validation("Unsupported parameter " + parameter.getKey()+ + " for action " + actionId + ".");+ }+ });+ actionDefinition.path("parameters").fields().forEachRemaining(parameter -> {+ if (parameter.getValue().path("required").asBoolean()+ && !parameters.hasNonNull(parameter.getKey())) {+ throw validation("Action " + actionId + " requires parameter " + parameter.getKey() + ".");+ }+ });+ ObjectNode actionTargets = action.has("targets")+ ? requireObject(action.path("targets"), "action targets")+ : mapper.createObjectNode();+ actionDefinition.path("targets").fields().forEachRemaining(target -> {+ String slot = target.getKey();+ if (!actionTargets.hasNonNull(slot) || !actionTargets.path(slot).isTextual()) {+ throw validation("Action " + actionId + " requires target " + slot + ".");+ }+ String targetName = actionTargets.path(slot).asText();+ validateName(targetName, "action target reference");+ if (!targets.has(targetName)) {+ throw validation("Action target " + targetName + " is not defined.");+ }+ String expectedType = target.getValue().path("resourceType").asText();+ if (!expectedType.equals(targets.path(targetName).path("resourceType").asText())) {+ throw validation("Action target " + targetName + " must use resource type " + expectedType + ".");+ }+ });+ actionTargets.fields().forEachRemaining(target -> {+ validateName(target.getKey(), "action target name");+ if (!target.getValue().isTextual()) {+ throw validation("Action target references must be strings.");+ }+ validateName(target.getValue().asText(), "action target reference");+ if (!targets.has(target.getValue().asText())) {+ throw validation("Action target " + target.getValue().asText() + " is not defined.");+ }+ if (!actionDefinition.path("targets").has(target.getKey())) {+ throw validation("Unsupported target " + target.getKey() + " for action " + actionId + ".");+ }+ });+ validateActionTargetRestrictions(actionId, actionTargets, targets);+ if (action.has("startAfter")) {+ JsonNode startAfter = action.path("startAfter");+ if (!startAfter.isArray()) {+ throw validation("startAfter must be an array.");+ }+ startAfter.forEach(dependency -> {+ if (!dependency.isTextual()) {+ throw validation("startAfter entries must be strings.");+ }+ validateName(dependency.asText(), "startAfter action name");+ if (!actions.has(dependency.asText()) || actionName.equals(dependency.asText())) {+ throw validation("Invalid startAfter dependency for action " + actionName + ".");+ }+ });+ }+ });+ validateAcyclicActions(actions);+ validateParallelActionQuota(actions);+ }++ private void validateParallelActionQuota(ObjectNode actions) {+ List<String> names = new ArrayList<>();+ actions.fieldNames().forEachRemaining(names::add);+ Map<String, Integer> indexes = new HashMap<>();+ for (int index = 0; index < names.size(); index++) {+ indexes.put(names.get(index), index);+ }++ boolean[][] precedes = new boolean[names.size()][names.size()];+ for (int actionIndex = 0; actionIndex < names.size(); actionIndex++) {+ JsonNode dependencies = actions.path(names.get(actionIndex)).path("startAfter");+ if (dependencies.isArray()) {+ for (JsonNode dependency : dependencies) {+ precedes[indexes.get(dependency.asText())][actionIndex] = true;+ }+ }+ }+ for (int intermediate = 0; intermediate < names.size(); intermediate++) {+ for (int before = 0; before < names.size(); before++) {+ for (int after = 0; after < names.size(); after++) {+ precedes[before][after] = precedes[before][after]+ || (precedes[before][intermediate] && precedes[intermediate][after]);+ }+ }+ }++ int[] matchedBefore = new int[names.size()];+ Arrays.fill(matchedBefore, -1);+ int matches = 0;+ for (int before = 0; before < names.size(); before++) {+ if (augmentPrecedenceMatching(before, precedes, new boolean[names.size()], matchedBefore)) {+ matches++;+ }+ }+ if (names.size() - matches > MAX_PARALLEL_ACTIONS) {+ throw new AwsException("ServiceQuotaExceededException",+ "An experiment can run at most 10 actions in parallel.", 402);+ }+ }++ private boolean augmentPrecedenceMatching(+ int before, boolean[][] precedes, boolean[] visitedAfter, int[] matchedBefore) {+ for (int after = 0; after < precedes.length; after++) {+ if (!precedes[before][after] || visitedAfter[after]) {+ continue;+ }+ visitedAfter[after] = true;+ if (matchedBefore[after] == -1+ || augmentPrecedenceMatching(matchedBefore[after], precedes, visitedAfter, matchedBefore)) {+ matchedBefore[after] = before;+ return true;+ }+ }+ return false;+ }++ private void validateActionTargetRestrictions(+ String actionId, ObjectNode actionTargets, ObjectNode targets) {+ if ("aws:ec2:api-insufficient-instance-capacity-error".equals(actionId)) {+ JsonNode target = targets.path(actionTargets.path("Roles").asText());+ JsonNode arns = target.path("resourceArns");+ if (!arns.isArray() || arns.isEmpty()+ || target.hasNonNull("resourceTags")+ || target.hasNonNull("filters")+ || target.hasNonNull("parameters")) {+ throw validation("Action " + actionId+ + " requires resource ARNs and does not support resource tags, filters, or parameters.");+ }+ }+ if ("aws:eks:inject-kubernetes-custom-resource".equals(actionId)) {+ JsonNode target = targets.path(actionTargets.path("Cluster").asText());+ JsonNode arns = target.path("resourceArns");+ if (!arns.isArray() || arns.size() != 1+ || target.hasNonNull("resourceTags")+ || target.hasNonNull("filters")+ || target.hasNonNull("parameters")) {+ throw validation("Action " + actionId+ + " requires exactly one resource ARN and does not support resource tags, filters, or parameters.");+ }+ }+ if ("aws:s3:bucket-pause-replication".equals(actionId)) {+ JsonNode target = targets.path(actionTargets.path("Buckets").asText());+ if (!target.path("resourceTags").isObject() || target.path("resourceTags").isEmpty()+ || target.hasNonNull("resourceArns")+ || target.hasNonNull("filters")+ || target.hasNonNull("parameters")) {+ throw validation("Action " + actionId + " supports targeting by resource tags only.");+ }+ }+ }++ private void validateAcyclicActions(ObjectNode actions) {+ Map<String, Integer> states = new HashMap<>();+ actions.fieldNames().forEachRemaining(name -> visitAction(actions, name, states));+ }++ private void visitAction(ObjectNode actions, String name, Map<String, Integer> states) {+ int state = states.getOrDefault(name, 0);+ if (state == 1) {+ throw validation("Action startAfter dependencies must not contain a cycle.");+ }+ if (state == 2) {+ return;+ }+ states.put(name, 1);+ JsonNode dependencies = actions.path(name).path("startAfter");+ if (dependencies.isArray()) {+ dependencies.forEach(dependency -> visitAction(actions, dependency.asText(), states));+ }+ states.put(name, 2);+ }++ private ObjectNode templateOptions(JsonNode input) {+ ObjectNode options = mapper.createObjectNode();+ options.put("accountTargeting", "single-account");+ options.put("emptyTargetResolutionMode", "fail");+ if (input == null || input.isMissingNode() || input.isNull()) {+ return options;+ }+ ObjectNode supplied = requireObject(input, "experimentOptions");+ supplied.fields().forEachRemaining(entry -> {+ if (!TEMPLATE_OPTION_FIELDS.contains(entry.getKey()) || !entry.getValue().isTextual()) {+ throw validation("Invalid experiment option: " + entry.getKey() + ".");+ }+ options.put(entry.getKey(), entry.getValue().asText());+ });+ if (!Set.of("single-account", "multi-account").contains(options.path("accountTargeting").asText())) {+ throw validation("accountTargeting must be single-account or multi-account.");+ }+ if (!Set.of("fail", "skip").contains(options.path("emptyTargetResolutionMode").asText())) {+ throw validation("emptyTargetResolutionMode must be fail or skip.");+ }+ return options;+ }++ private void validateLogConfiguration(JsonNode input, boolean requireSchemaVersion) {+ ObjectNode configuration = requireObject(input, "logConfiguration");+ if (requireSchemaVersion && !configuration.hasNonNull("logSchemaVersion")) {+ throw validation("logConfiguration.logSchemaVersion is required.");+ }+ if (configuration.has("logSchemaVersion")) {+ JsonNode version = configuration.path("logSchemaVersion");+ if (!version.isIntegralNumber() || !version.canConvertToInt()) {+ throw validation("logConfiguration.logSchemaVersion must be an integer.");+ }+ }+ if (configuration.has("cloudWatchLogsConfiguration")) {+ ObjectNode cloudWatch = requireObject(+ configuration.path("cloudWatchLogsConfiguration"),+ "logConfiguration.cloudWatchLogsConfiguration");+ requireNonWhitespaceText(+ cloudWatch, "logGroupArn", 20, 2048,+ "logConfiguration.cloudWatchLogsConfiguration.logGroupArn");+ }+ if (configuration.has("s3Configuration")) {+ ObjectNode s3 = requireObject(+ configuration.path("s3Configuration"),+ "logConfiguration.s3Configuration");+ requireNonWhitespaceText(+ s3, "bucketName", 3, 63,+ "logConfiguration.s3Configuration.bucketName");+ if (s3.has("prefix")) {+ JsonNode prefix = s3.path("prefix");+ if (!prefix.isTextual() || prefix.asText().isEmpty() || prefix.asText().length() > 700) {+ throw validation("logConfiguration.s3Configuration.prefix must contain between 1 and 700 "+ + "characters.");+ }+ }+ }+ }++ private void validateExperimentReportConfiguration(JsonNode input) {+ ObjectNode configuration = requireObject(input, "experimentReportConfiguration");+ if (configuration.hasNonNull("preExperimentDuration")) {+ requireNonWhitespaceText(+ configuration, "preExperimentDuration", 1, 32,+ "experimentReportConfiguration.preExperimentDuration");+ }+ if (configuration.hasNonNull("postExperimentDuration")) {+ requireNonWhitespaceText(+ configuration, "postExperimentDuration", 1, 32,+ "experimentReportConfiguration.postExperimentDuration");+ }+ if (configuration.hasNonNull("outputs")) {+ ObjectNode outputs = requireObject(+ configuration.path("outputs"), "experimentReportConfiguration.outputs");+ if (outputs.hasNonNull("s3Configuration")) {+ ObjectNode s3 = requireObject(+ outputs.path("s3Configuration"),+ "experimentReportConfiguration.outputs.s3Configuration");+ if (s3.hasNonNull("bucketName")) {+ requireNonWhitespaceText(+ s3, "bucketName", 3, 63,+ "experimentReportConfiguration.outputs.s3Configuration.bucketName");+ }+ if (s3.hasNonNull("prefix")) {+ requireNonWhitespaceText(+ s3, "prefix", 1, 256,+ "experimentReportConfiguration.outputs.s3Configuration.prefix");+ }+ }+ }+ if (configuration.hasNonNull("dataSources")) {+ ObjectNode dataSources = requireObject(+ configuration.path("dataSources"), "experimentReportConfiguration.dataSources");+ if (dataSources.hasNonNull("cloudWatchDashboards")) {+ JsonNode dashboards = dataSources.path("cloudWatchDashboards");+ if (!dashboards.isArray()) {+ throw validation("experimentReportConfiguration.dataSources.cloudWatchDashboards "+ + "must be an array.");+ }+ for (JsonNode dashboardNode : dashboards) {+ ObjectNode dashboard = requireObject(+ dashboardNode,+ "experimentReportConfiguration.dataSources.cloudWatchDashboards entry");+ if (dashboard.hasNonNull("dashboardIdentifier")) {+ requireNonWhitespaceText(+ dashboard, "dashboardIdentifier", 1, 512,+ "experimentReportConfiguration.dataSources.cloudWatchDashboards.dashboardIdentifier");+ }+ }+ }+ }+ }++ private void requireNonWhitespaceText(+ ObjectNode input, String field, int minimumLength, int maximumLength, String displayName) {+ JsonNode value = input.path(field);+ if (!value.isTextual()+ || value.asText().length() < minimumLength+ || value.asText().length() > maximumLength+ || value.asText().chars().anyMatch(Character::isWhitespace)) {+ throw validation(displayName + " must contain between " + minimumLength + " and "+ + maximumLength + " non-whitespace characters.");+ }+ }++ private String validateActionsMode(JsonNode input) {+ if (input == null || input.isMissingNode() || input.isNull()) {+ return "run-all";+ }+ ObjectNode options = requireObject(input, "experimentOptions");+ options.fieldNames().forEachRemaining(name -> {+ if (!"actionsMode".equals(name)) {+ throw validation("Invalid start experiment option: " + name + ".");+ }+ });+ String mode = options.path("actionsMode").asText("run-all");+ if (!Set.of("run-all", "skip-all").contains(mode)) {+ throw validation("actionsMode must be run-all or skip-all.");+ }+ return mode;+ }++ private Set<String> persistResolvedTargets(String region, String experimentId, JsonNode targets) {+ Set<String> unresolvedTargets = new HashSet<>();+ int index = 0;+ for (var iterator = targets.fields(); iterator.hasNext();) {+ var entry = iterator.next();+ String targetName = entry.getKey();+ JsonNode target = entry.getValue();+ String resourceType = target.path("resourceType").asText();+ int resolvedBeforeTarget = index;+ if (target.path("resourceArns").isArray()) {+ List<String> arns = new ArrayList<>();+ target.path("resourceArns").forEach(arn -> arns.add(arn.asText()));+ int count = selectedCount(target.path("selectionMode").asText(), arns.size());+ if (count < arns.size()) {+ shuffle(arns);+ }+ for (String arn : arns.subList(0, Math.min(count, arns.size()))) {+ ObjectNode resolved = resolvedTarget(targetName, resourceType);+ resolved.putObject("targetInformation").put("arn", arn);+ putResolvedTarget(region, experimentId, index++, resolved);+ }+ }+ if (index == resolvedBeforeTarget) {+ unresolvedTargets.add(targetName);+ }+ }+ return unresolvedTargets;+ }++ private void shuffle(List<String> values) {+ for (int index = values.size() - 1; index > 0; index--) {+ Collections.swap(values, index, random.nextInt(index + 1));+ }+ }++ private boolean usesTarget(ObjectNode action, Set<String> targetNames) {+ if (targetNames.isEmpty() || !action.path("targets").isObject()) {+ return false;+ }+ for (JsonNode targetName : action.path("targets")) {+ if (targetNames.contains(targetName.asText())) {+ return true;+ }+ }+ return false;+ }++ private boolean allActionsHaveStatus(ObjectNode actions, String status) {+ for (JsonNode action : actions) {+ if (!status.equals(action.path("state").path("status").asText())) {+ return false;+ }+ }+ return !actions.isEmpty();+ }++ private int selectedCount(String selectionMode, int total) {+ if ("ALL".equals(selectionMode)) {+ return total;+ }+ Matcher count = COUNT_SELECTION.matcher(selectionMode);+ if (count.matches()) {+ return Math.min(total, countSelectionValue(selectionMode, count));+ }+ Matcher percent = PERCENT_SELECTION.matcher(selectionMode);+ if (percent.matches()) {+ return Math.min(total, total * Integer.parseInt(percent.group(1)) / 100);+ }+ return total;+ }++ private void validateSelectionMode(String selectionMode) {+ if ("ALL".equals(selectionMode) || PERCENT_SELECTION.matcher(selectionMode).matches()) {+ return;+ }+ Matcher count = COUNT_SELECTION.matcher(selectionMode);+ if (count.matches()) {+ countSelectionValue(selectionMode, count);+ return;+ }+ throw validation("Invalid target selectionMode: " + selectionMode + ".");+ }++ private int countSelectionValue(String selectionMode, Matcher count) {+ BigInteger value = new BigInteger(count.group(1));+ if (value.compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {+ throw validation("Invalid target selectionMode: " + selectionMode + ".");+ }+ return value.intValue();+ }++ private ObjectNode resolvedTarget(String targetName, String resourceType) {+ ObjectNode target = mapper.createObjectNode();+ target.put("targetName", targetName);+ target.put("resourceType", resourceType);+ return target;+ }++ private void stopExperimentNode(ObjectNode experiment, String reason) {+ double timestamp = now();+ experiment.set("state", state("stopped", reason));+ experiment.put("endTime", timestamp);+ experiment.path("actions").forEach(actionNode -> {+ ObjectNode action = (ObjectNode) actionNode;+ String current = action.path("state").path("status").asText();+ if (Set.of("running", "initiating", "stopping").contains(current)) {+ action.set("state", state("stopped", reason));+ action.put("endTime", timestamp);+ } else if ("pending".equals(current)) {+ action.set("state", state("cancelled", reason));+ action.put("endTime", timestamp);+ }+ });+ }++ private synchronized ObjectNode requireSafetyLever(String region, String id) {+ if (!"default".equals(id)) {+ throw notFound("Safety lever", id);+ }+ return stores.safetyLevers.get(safetyLeverKey(region, id)).map(this::toObjectNode).orElseGet(() -> {+ ObjectNode lever = safetyLever(region, "disengaged", "The safety lever is disengaged.");+ putSafetyLever(region, id, lever);+ return lever;+ });+ }++ private ObjectNode safetyLever(String region, String status, String reason) {+ ObjectNode lever = mapper.createObjectNode();+ lever.put("id", "default");+ lever.put("arn", regionResolver.buildArn(SERVICE, region, "safety-lever/default"));+ lever.set("state", state(status, reason));+ return lever;+ }++ private ObjectNode state(String status, String reason) {+ ObjectNode state = mapper.createObjectNode();+ state.put("status", status);+ state.put("reason", reason);+ return state;+ }++ private ObjectNode templateSummary(ObjectNode template) {+ return select(template, "id", "arn", "description", "creationTime", "lastUpdateTime", "tags");+ }++ private ObjectNode experimentSummary(ObjectNode experiment) {+ return select(experiment, "id", "arn", "experimentTemplateId", "creationTime",+ "state", "tags", "experimentOptions");+ }++ private ObjectNode select(ObjectNode source, String... fields) {+ ObjectNode selected = mapper.createObjectNode();+ for (String field : fields) {+ if (source.has(field)) {+ selected.set(field, source.path(field).deepCopy());+ }+ }+ return selected;+ }++ private ObjectNode page(String field, List<ObjectNode> all, Integer maxResults, String nextToken,+ String scope, Function<ObjectNode, String> cursorFunction) {+ if (maxResults != null && (maxResults < 1 || maxResults > MAX_PAGE_SIZE)) {+ throw validation("maxResults must be between 1 and 100.");+ }+ int limit = maxResults == null ? MAX_PAGE_SIZE : maxResults;+ String after = decodeToken(nextToken, scope);+ List<ObjectNode> sorted = new ArrayList<>(all);+ sorted.sort(Comparator.comparing(cursorFunction));+ int start = 0;+ if (after != null) {+ while (start < sorted.size() && cursorFunction.apply(sorted.get(start)).compareTo(after) <= 0) {+ start++;+ }+ }+ int end = Math.min(sorted.size(), start + limit);+ ObjectNode response = mapper.createObjectNode();+ ArrayNode values = response.putArray(field);+ for (int i = start; i < end; i++) {+ values.add(sorted.get(i).deepCopy());+ }+ if (end < sorted.size() && end > start) {+ response.put("nextToken", encodeToken(scope, cursorFunction.apply(sorted.get(end - 1))));+ }+ return response;+ }++ private String encodeToken(String scope, String cursor) {+ String raw = scope + "\n" + cursor;+ return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));+ }++ private String decodeToken(String token, String expectedScope) {+ if (token == null) {+ return null;+ }+ if (token.length() > 1024 || token.chars().anyMatch(Character::isWhitespace)) {+ throw validation("Invalid nextToken.");+ }+ try {+ String raw = new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8);+ int separator = raw.indexOf('\n');+ if (separator < 0 || !expectedScope.equals(raw.substring(0, separator))+ || separator == raw.length() - 1) {+ throw validation("Invalid nextToken.");+ }+ return raw.substring(separator + 1);+ } catch (IllegalArgumentException e) {+ throw validation("Invalid nextToken.");+ }+ }++ private String scope(String region, String operation) {+ return regionResolver.getAccountId() + ":" + region + ":" + operation;+ }++ private String resolvedTargetCursor(ObjectNode target) {+ return target.path("targetName").asText() + "|" + target.path("resourceType").asText()+ + "|" + target.path("targetInformation").toString();+ }++ private ObjectNode idempotentResponse(String region, String operation, String token, ObjectNode request) {+ if (token == null) {+ return null;+ }+ IdempotencyRecord record = stores.idempotency+ .get(idempotencyKey(region, operation, token)).orElse(null);+ if (record == null) {+ return null;+ }+ if (!record.getRequest().equals(request)) {+ throw conflict("The clientToken was already used with different request parameters.");+ }+ return record.getResponse().deepCopy();+ }++ private void saveIdempotentResponse(String region, String operation, String token,+ ObjectNode request, ObjectNode response) {+ if (token == null) {+ return;+ }+ IdempotencyRecord record = new IdempotencyRecord(request.deepCopy(), response.deepCopy());+ stores.idempotency.put(idempotencyKey(region, operation, token), record);+ }++ private ResourceRef parseTaggableArn(String region, String arn) {+ AwsArnUtils.Arn parsed;+ try {+ parsed = AwsArnUtils.parse(arn);+ } catch (IllegalArgumentException e) {+ throw validation("Invalid resource ARN: " + arn + ".");+ }+ if (!SERVICE.equals(parsed.service()) || !region.equals(parsed.region())+ || !regionResolver.getAccountId().equals(parsed.accountId())) {+ throw validation("The resource ARN does not belong to this AWS FIS account and region.");+ }+ int separator = parsed.resource().indexOf('/');+ if (separator <= 0 || separator == parsed.resource().length() - 1) {+ throw validation("Invalid AWS FIS resource ARN: " + arn + ".");+ }+ String type = parsed.resource().substring(0, separator);+ String id = parsed.resource().substring(separator + 1);+ if (!Set.of("action", "experiment", "experiment-template").contains(type)) {+ throw validation("The ARN does not identify a taggable AWS FIS resource.");+ }+ if ("action".equals(type) && !catalog.containsAction(id)) {+ throw notFound("Action", id);+ }+ return new ResourceRef(type, id);+ }++ private void saveResourceTags(String region, ResourceRef resource, ObjectNode tags) {+ switch (resource.type()) {+ case "action" -> {+ stores.actionTags.put(actionTagsKey(region, resource.id()), tagsMap(tags));+ }+ case "experiment" -> {+ ObjectNode experiment = requireExperiment(region, resource.id());+ experiment.set("tags", tags.deepCopy());+ putExperiment(region, resource.id(), experiment);+ }+ case "experiment-template" -> {+ ObjectNode template = requireTemplate(region, resource.id());+ template.set("tags", tags.deepCopy());+ template.put("lastUpdateTime", now());+ putTemplate(region, resource.id(), template);+ }+ default -> throw validation("The ARN does not identify a taggable AWS FIS resource.");+ }+ }++ private ObjectNode actionTags(String region, String actionId) {+ return stores.actionTags.get(actionTagsKey(region, actionId))+ .map(this::tagsNode).orElseGet(mapper::createObjectNode);+ }++ private Map<String, String> readTagsInput(JsonNode tags) {+ if (tags == null || tags.isMissingNode() || tags.isNull()) {+ return Map.of();+ }+ if (!tags.isObject()) {+ throw validation("tags must be a string-to-string map.");+ }+ Map<String, String> result = new LinkedHashMap<>();+ tags.fields().forEachRemaining(entry -> {+ if (!entry.getValue().isTextual()) {+ throw validation("Tag values must be strings.");+ }+ result.put(entry.getKey(), entry.getValue().asText());+ });+ validateTags(result);+ return result;+ }++ private void validateTags(Map<String, String> tags) {+ if (tags == null) {+ throw validation("tags must be supplied.");+ }+ if (tags.size() > MAX_TAGS) {+ throw validation("A resource can have at most 50 tags.");+ }+ tags.forEach((key, value) -> {+ validateTagKey(key);+ if (value == null || value.length() > 256) {+ throw validation("Tag values can contain at most 256 characters.");+ }+ if (!TAG_VALUE.matcher(value).matches()) {+ throw validation("Tag values contain invalid characters.");+ }+ });+ }++ private void validateTagKey(String key) {+ if (key == null || key.isEmpty() || key.length() > 128) {+ throw validation("Tag keys must contain between 1 and 128 characters.");+ }+ if (key.regionMatches(true, 0, "aws:", 0, 4)) {+ throw validation("Tag keys must not use the reserved aws: prefix.");+ }+ if (!TAG_VALUE.matcher(key).matches()) {+ throw validation("Tag keys contain invalid characters.");+ }+ }++ private ObjectNode tagsNode(Map<String, String> tags) {+ ObjectNode node = mapper.createObjectNode();+ tags.forEach(node::put);+ return node;+ }++ private Map<String, String> tagsMap(JsonNode tags) {+ Map<String, String> result = new LinkedHashMap<>();+ if (tags != null && tags.isObject()) {+ tags.fields().forEachRemaining(entry -> result.put(entry.getKey(), entry.getValue().asText()));+ }+ return result;+ }++ private ObjectNode requireTemplate(String region, String id) {+ return stores.templates.get(templateKey(region, id)).map(this::toObjectNode)+ .orElseThrow(() -> notFound("Experiment template", id));+ }++ private ObjectNode requireExperiment(String region, String id) {+ return stores.experiments.get(experimentKey(region, id)).map(this::toObjectNode)+ .orElseThrow(() -> notFound("Experiment", id));+ }++ private ObjectNode requireTargetAccountConfiguration(String region, String templateId, String accountId) {+ return stores.targetAccounts.get(targetAccountKey(region, templateId, accountId))+ .map(this::toObjectNode)+ .orElseThrow(() -> notFound("Target account configuration", accountId));+ }++ private List<ObjectNode> targetAccountConfigurations(String region, String templateId) {+ return copiedScan(stores.targetAccounts, targetAccountPrefix(region, templateId));+ }++ private long activeExperimentCount(String region) {+ return copiedScan(stores.experiments, experimentPrefix(region)).stream()+ .filter(experiment -> !TERMINAL_EXPERIMENT_STATES.contains(+ experiment.path("state").path("status").asText()))+ .count();+ }++ private <T> List<ObjectNode> copiedScan(StorageBackend<String, T> store, String prefix) {+ List<ObjectNode> result = new ArrayList<>();+ store.scan(key -> key.startsWith(prefix)).forEach(value -> result.add(toObjectNode(value)));+ return result;+ }++ private void updateTemplateTargetAccountCount(String region, String templateId) {+ ObjectNode template = requireTemplate(region, templateId);+ template.put("targetAccountConfigurationsCount", targetAccountConfigurations(region, templateId).size());+ template.put("lastUpdateTime", now());+ putTemplate(region, templateId, template);+ }++ private <T> void deleteByPrefix(StorageBackend<String, T> store, String prefix) {+ for (String key : new HashSet<>(store.keys())) {+ if (key.startsWith(prefix)) {+ store.delete(key);+ }+ }+ }++ private String newId(String region, String type, String prefix) {+ String id;+ do {+ id = prefix + UUID.randomUUID().toString().replace("-", "").substring(0, 17);+ } while (resourceIdExists(region, type, id));+ return id;+ }++ private boolean resourceIdExists(String region, String type, String id) {+ return switch (type) {+ case "template" -> stores.templates.get(templateKey(region, id)).isPresent();+ case "experiment" -> stores.experiments.get(experimentKey(region, id)).isPresent();+ default -> throw new IllegalArgumentException("Unsupported FIS resource type: " + type);+ };+ }++ private void putTemplate(String region, String id, ObjectNode template) {+ stores.templates.put(templateKey(region, id),+ mapper.convertValue(template, ExperimentTemplate.class));+ }++ private void putExperiment(String region, String id, ObjectNode experiment) {+ stores.experiments.put(experimentKey(region, id), mapper.convertValue(experiment, Experiment.class));+ }++ private void putTargetAccountConfiguration(String key, ObjectNode configuration) {+ stores.targetAccounts.put(key, mapper.convertValue(configuration, TargetAccountConfiguration.class));+ }++ private void putResolvedTarget(String region, String experimentId, int index, ObjectNode resolvedTarget) {+ stores.resolvedTargets.put(resolvedTargetKey(region, experimentId, index),+ mapper.convertValue(resolvedTarget, ResolvedTarget.class));+ }++ private void putSafetyLever(String region, String id, ObjectNode safetyLever) {+ stores.safetyLevers.put(safetyLeverKey(region, id),+ mapper.convertValue(safetyLever, SafetyLever.class));+ }++ private ObjectNode toObjectNode(Object value) {+ return mapper.valueToTree(value);+ }++ private ObjectNode requireRequest(JsonNode request) {+ if (request == null || !request.isObject()) {+ throw validation("Request body must be a JSON object.");+ }+ return (ObjectNode) request;+ }++ private ObjectNode requireObject(JsonNode node, String name) {+ if (node == null || !node.isObject()) {+ throw validation(name + " must be an object.");+ }+ return (ObjectNode) node;+ }++ private ObjectNode copyObject(JsonNode node) {+ if (node == null || node.isMissingNode() || node.isNull()) {+ return mapper.createObjectNode();+ }+ return requireObject(node, "value").deepCopy();+ }++ private String requireText(ObjectNode input, String field, int maximumLength) {+ JsonNode value = input.path(field);+ if (!value.isTextual() || value.asText().isBlank() || value.asText().length() > maximumLength) {+ throw validation(field + " must be a non-empty string no longer than " + maximumLength + " characters.");+ }+ return value.asText();+ }++ private String requireToken(ObjectNode input, String field) {+ String token = requireText(input, field, 1024);+ if (token.chars().anyMatch(Character::isWhitespace)) {+ throw validation(field + " must contain between 1 and 1024 non-whitespace characters.");+ }+ return token;+ }++ private String optionalToken(ObjectNode input, String field) {+ return input.has(field) ? requireToken(input, field) : null;+ }++ private String requireArn(ObjectNode input, String field) {+ String arn = requireText(input, field, 2048);+ if (arn.length() < 20 || arn.chars().anyMatch(Character::isWhitespace)) {+ throw validation(field + " must be a valid ARN.");+ }+ try {+ AwsArnUtils.parse(arn);+ } catch (IllegalArgumentException e) {+ throw validation(field + " must be a valid ARN.");+ }+ return arn;+ }++ private void validateOptionalDescription(ObjectNode input, String field, boolean allowEmpty) {+ if (!input.has(field) && allowEmpty) {+ return;+ }+ JsonNode value = input.path(field);+ if (!value.isTextual() || value.asText().length() > 512+ || (!allowEmpty && value.asText().isEmpty())) {+ throw validation(field + " must be a " + (allowEmpty ? "" : "non-empty ")+ + "string no longer than 512 characters.");+ }+ }++ private void validateName(String name, String field) {+ if (name == null || name.isEmpty() || name.length() > 64+ || name.chars().anyMatch(Character::isWhitespace)) {+ throw validation(field + " must contain between 1 and 64 non-whitespace characters.");+ }+ }++ private void requireAccountId(String accountId) {+ if (accountId == null || !accountId.matches("\\S{12,48}")) {+ throw validation("accountId must contain between 12 and 48 non-whitespace characters.");+ }+ }++ private void copyIfPresent(JsonNode source, ObjectNode target, String field) {+ if (source.has(field) && !source.path(field).isNull()) {+ target.set(field, source.path(field).deepCopy());+ }+ }++ private ObjectNode wrap(String field, JsonNode value) {+ ObjectNode response = mapper.createObjectNode();+ response.set(field, value.deepCopy());+ return response;+ }++ private AwsException validation(String message) {+ return new AwsException("ValidationException", message, 400);+ }++ private AwsException conflict(String message) {+ return new AwsException("ConflictException", message, 409);+ }++ private AwsException notFound(String resource, String id) {+ return new AwsException("ResourceNotFoundException", resource + " " + id + " was not found.", 404);+ }++ private double now() {+ return Instant.now().toEpochMilli() / 1000.0;+ }++ private String key(String region, String type, String id) {+ return region + "::" + type + "::" + id;+ }++ private String templateKey(String region, String id) {+ return key(region, "template", id);+ }++ private String templatePrefix(String region) {+ return key(region, "template", "");+ }++ private String experimentKey(String region, String id) {+ return key(region, "experiment", id);+ }++ private String experimentPrefix(String region) {+ return key(region, "experiment", "");+ }++ private String targetAccountKey(String region, String templateId, String accountId) {+ return key(region, "target-account", templateId + "::" + accountId);+ }++ private String targetAccountPrefix(String region, String templateId) {+ return key(region, "target-account", templateId + "::");+ }++ private String experimentTargetAccountKey(String region, String experimentId, String accountId) {+ return key(region, "experiment-target-account", experimentId + "::" + accountId);+ }++ private String experimentTargetAccountPrefix(String region, String experimentId) {+ return key(region, "experiment-target-account", experimentId + "::");+ }++ private String resolvedTargetKey(String region, String experimentId, int index) {+ return key(region, "resolved-target", experimentId + "::" + String.format("%08d", index));+ }++ private String resolvedTargetPrefix(String region, String experimentId) {+ return key(region, "resolved-target", experimentId + "::");+ }++ private String actionTagsKey(String region, String actionId) {+ return key(region, "action-tags", actionId);+ }++ private String safetyLeverKey(String region, String id) {+ return key(region, "safety-lever", id);+ }++ private String idempotencyKey(String region, String operation, String token) {+ String encoded = Base64.getUrlEncoder().withoutPadding()+ .encodeToString(token.getBytes(StandardCharsets.UTF_8));+ return key(region, "idempotency", operation + "::" + encoded);+ }++ private record ResourceRef(String type, String id) {}+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/FisStores.java b/src/main/java/io/github/hectorvent/floci/services/fis/FisStores.javanew file mode 100644index 0000000000..985c471769--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/FisStores.java@@ -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<>());+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/Experiment.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/Experiment.javanew file mode 100644index 0000000000..72c28a877e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/Experiment.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentAction.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentAction.javanew file mode 100644index 0000000000..7655e819c4--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentAction.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentActionState.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentActionState.javanew file mode 100644index 0000000000..e8379fe003--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentActionState.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentOptions.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentOptions.javanew file mode 100644index 0000000000..5a068e5b11--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentOptions.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentState.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentState.javanew file mode 100644index 0000000000..23e802d4ca--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentState.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTarget.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTarget.javanew file mode 100644index 0000000000..948c0e02b6--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTarget.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplate.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplate.javanew file mode 100644index 0000000000..989ef602a4--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplate.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplateAction.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplateAction.javanew file mode 100644index 0000000000..30dd598666--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplateAction.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplateOptions.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplateOptions.javanew file mode 100644index 0000000000..861b8ad986--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplateOptions.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplateTarget.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplateTarget.javanew file mode 100644index 0000000000..288387967e--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/ExperimentTemplateTarget.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/IdempotencyRecord.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/IdempotencyRecord.javanew file mode 100644index 0000000000..212a9b55fb--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/IdempotencyRecord.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/ResolvedTarget.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/ResolvedTarget.javanew file mode 100644index 0000000000..ffcf3d11c9--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/ResolvedTarget.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/SafetyLever.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/SafetyLever.javanew file mode 100644index 0000000000..cf63984f4c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/SafetyLever.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/SafetyLeverState.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/SafetyLeverState.javanew file mode 100644index 0000000000..e10fffa367--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/SafetyLeverState.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/StopCondition.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/StopCondition.javanew file mode 100644index 0000000000..b3cc81afd6--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/StopCondition.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/TargetAccountConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/TargetAccountConfiguration.javanew file mode 100644index 0000000000..6886324300--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/TargetAccountConfiguration.java@@ -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;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/fis/model/TargetFilter.java b/src/main/java/io/github/hectorvent/floci/services/fis/model/TargetFilter.javanew file mode 100644index 0000000000..fbc3e10e67--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/fis/model/TargetFilter.java@@ -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;+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex b1ecd608c6..110e7158e7 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -157,6 +157,8 @@ floci:flush-interval-ms: 5000rum:flush-interval-ms: 5000+ fis:+ flush-interval-ms: 5000guardduty:flush-interval-ms: 5000emrserverless:@@ -477,6 +479,8 @@ floci:backup:enabled: truejob-completion-delay-seconds: 3+ fis:+ enabled: trueroute53:enabled: truetransfer:diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AwsRestJsonErrorHeaderFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AwsRestJsonErrorHeaderFilterTest.javanew file mode 100644index 0000000000..422a4bb1a5--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/core/common/AwsRestJsonErrorHeaderFilterTest.java@@ -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();+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.javaindex b32e8ce80b..519384e825 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/ServiceCatalogRoutingIntegrationTest.java@@ -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));+ }+@Testvoid unknownTargetsRemainUnresolved() {assertTrue(catalog.matchTarget("UnknownService.DoThing").isEmpty());diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ServiceEnablementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ServiceEnablementIntegrationTest.javaindex 78fc053ceb..24de93b4ce 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/ServiceEnablementIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/ServiceEnablementIntegrationTest.java@@ -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."));+ }+@Testvoid 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",diff --git a/src/test/java/io/github/hectorvent/floci/services/fis/FisCatalogTargetValidationTest.java b/src/test/java/io/github/hectorvent/floci/services/fis/FisCatalogTargetValidationTest.javanew file mode 100644index 0000000000..328943d4e0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/fis/FisCatalogTargetValidationTest.java@@ -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;+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/fis/FisIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/fis/FisIntegrationTest.javanew file mode 100644index 0000000000..70a51a2ee0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/fis/FisIntegrationTest.java@@ -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";+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/fis/FisModelSerializationTest.java b/src/test/java/io/github/hectorvent/floci/services/fis/FisModelSerializationTest.javanew file mode 100644index 0000000000..28ac4087b0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/fis/FisModelSerializationTest.java@@ -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"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/fis/FisServicePersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/fis/FisServicePersistenceTest.javanew file mode 100644index 0000000000..c5acbdd773--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/fis/FisServicePersistenceTest.java@@ -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());+ });+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetV1IntegrationTest.javaindex 7dd905bcd5..08cbecf3e2 100644--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetV1IntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesConfigurationSetV1IntegrationTest.java@@ -46,6 +46,7 @@ class SesConfigurationSetV1IntegrationTest {.post("/").then().statusCode(400)+ .header("X-Amzn-Errortype", (String) null).body(containsString("<Code>ConfigurationSetAlreadyExists</Code>"));}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex 5457c7ed3d..f5b984b689 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -73,6 +73,8 @@ floci:flush-interval-ms: 60000rum:flush-interval-ms: 60000+ fis:+ flush-interval-ms: 60000guardduty:flush-interval-ms: 60000emrserverless:@@ -277,6 +279,8 @@ floci:backup:enabled: truejob-completion-delay-seconds: 1+ fis:+ enabled: trueroute53:enabled: truetextract:diff --git a/tools/docs/services.yaml b/tools/docs/services.yamlindex 849835257d..5137da976a 100644--- a/tools/docs/services.yaml+++ b/tools/docs/services.yaml@@ -54,6 +54,19 @@ services:doc: docs/services/firehose.mdsources:- { 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: kinesisdoc: docs/services/kinesis.mdsources: