mirror of
https://github.com/floci-io/floci.git
synced 2026-12-04 10:38:00 -05:00
feat(fis): fail the calls a running inject-api action impairs (#8793)
FIS's aws:fis:inject-api-internal-error, -throttle-error and -unavailable-error actions were recorded as running and never did anything. A running one now fails the calls it impairs: calls signed with a session of one of its target roles, to one of the operations it names in its service namespace, at its percentage. - FisApiFaultFilter runs after IAM enforcement and reads the operation from the route that serves the call, through RequestOperationResolver, for every protocol. Only the accounts and Regions where such an experiment runs are looked into, so any other request costs a set lookup and leaves nothing cached, whatever account ID it names. - EC2 answers with InternalError, RequestLimitExceeded or Unavailable, from its error code list. Kinesis answers with the common errors InternalFailure, ThrottlingException or ServiceUnavailable, in JSON or CBOR to match the request. - Templates must give service as ec2 or kinesis, a percentage from 1 to 100, comma-separated operations and a duration from one minute to 12 hours. A template stored before these checks is checked again when an experiment starts from it. - An inject-api action completes once its duration runs out, worked out on each read rather than on a timer, and an action that starts after it then starts. The experiment completes when every action has completed or been skipped. - floci.services.fis.inject-api-any-service, off by default, lets the actions target any namespace, named by its IAM namespace or by the name it signs under. Those services answer with the common errors in their protocol's envelope, a Query or REST-XML ErrorResponse in the service's own XML namespace; Route 53's catalog entry now carries its namespace, as its own errors do. The error bodies a filter answers with move into ProtocolErrorResponses, which IamEnforcementFilter, AwsQueryController and ServiceEnabledFilter now share instead of each building its own Query ErrorResponse. The fault injection carries over the design of dchakrav-github's #4591. Refs #4623 Co-authored-by: dchakrav-github <42748809+dchakrav-github@users.noreply.github.com>
This commit is contained in:
1 parent
5110042f6c
commit
aeba963c8a
16 files changed
+1397
-140
No files matched your search
@@ -0,0 +1,276 @@
|
||||
package io.floci.aws.services.fis;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AccountResolver;
|
||||
import io.floci.aws.core.common.AwsErrorResponse;
|
||||
import io.floci.aws.core.common.AwsNamespaces;
|
||||
import io.floci.aws.core.common.AwsProtocolClaimFilter;
|
||||
import io.floci.aws.core.common.ProtocolClaim;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import io.floci.aws.core.common.RequestOperationResolver;
|
||||
import io.floci.aws.core.common.RequestOperationResolver.ResolvedOperation;
|
||||
import io.floci.aws.core.common.ResolvedServiceCatalog;
|
||||
import io.floci.aws.core.common.WireProtocol;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.iam.IamService.CallerArns;
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.random.RandomGenerator;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link FisApiFaultFilter}: which calls a running {@code aws:fis:inject-api-*} action fails, and the error each
|
||||
* service answers with.
|
||||
*/
|
||||
class FisApiFaultFilterTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String SESSION_KEY = "ASIAFISSESSIONKEY001";
|
||||
private static final String TARGET_ROLE = "arn:aws:iam::000000000000:role/app/checkout";
|
||||
private static final double FAR_FUTURE = Double.MAX_VALUE;
|
||||
|
||||
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
private final FisService fisService = mock(FisService.class);
|
||||
private final IamService iamService = mock(IamService.class);
|
||||
private final RequestContext requestContext = mock(RequestContext.class);
|
||||
private final RequestOperationResolver operationResolver = mock(RequestOperationResolver.class);
|
||||
private final ResolvedServiceCatalog catalog = new ResolvedServiceCatalog(config);
|
||||
private int roll;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
when(config.services().fis().enabled()).thenReturn(true);
|
||||
when(requestContext.getRegion()).thenReturn(REGION);
|
||||
caller(TARGET_ROLE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTargetRolesEc2CallGetsEc2sOwnThrottlingError() {
|
||||
faults(new FisApiFault(FisApiFault.Kind.THROTTLE, "ec2", Set.of("DescribeInstances"), 100,
|
||||
Set.of(TARGET_ROLE), FAR_FUTURE));
|
||||
resolvesTo("ec2", "DescribeInstances");
|
||||
|
||||
Response response = abortedWith(request("ec2", null, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
|
||||
|
||||
assertEquals(503, response.getStatus());
|
||||
assertThat((String) response.getEntity(), containsString("<Code>RequestLimitExceeded</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKinesisJsonCallGetsTheCommonErrorInJson() {
|
||||
faults(new FisApiFault(FisApiFault.Kind.INTERNAL, "kinesis", Set.of("PutRecord"), 100,
|
||||
Set.of(TARGET_ROLE), FAR_FUTURE));
|
||||
resolvesTo("kinesis", "PutRecord");
|
||||
|
||||
Response response = abortedWith(request("kinesis", WireProtocol.AWS_JSON_1_1,
|
||||
MediaType.valueOf("application/x-amz-json-1.1")));
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(new AwsErrorResponse("InternalFailure", "The request can't be processed right now because of "
|
||||
+ "an internal server issue. Try again later. If the problem persists, contact AWS Support."),
|
||||
response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKinesisCborCallGetsTheErrorInCbor() {
|
||||
faults(new FisApiFault(FisApiFault.Kind.UNAVAILABLE, "kinesis", Set.of("GetRecords"), 100,
|
||||
Set.of(TARGET_ROLE), FAR_FUTURE));
|
||||
resolvesTo("kinesis", "GetRecords");
|
||||
ContainerRequestContext ctx = request("kinesis", WireProtocol.AWS_CBOR_TARGET,
|
||||
MediaType.valueOf("application/x-amz-cbor-1.1"));
|
||||
when(ctx.getHeaderString("Content-Type")).thenReturn("application/x-amz-cbor-1.1");
|
||||
|
||||
Response response = abortedWith(ctx);
|
||||
|
||||
assertEquals(503, response.getStatus());
|
||||
assertEquals("application/x-amz-cbor-1.1", response.getMediaType().toString());
|
||||
assertEquals("ServiceUnavailable;Receiver", response.getHeaderString("x-amzn-query-error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQueryServiceGetsAQueryErrorResponseFromTheReceiverForAServerFault() {
|
||||
faults(new FisApiFault(FisApiFault.Kind.UNAVAILABLE, "sns", Set.of("Publish"), 100,
|
||||
Set.of(TARGET_ROLE), FAR_FUTURE));
|
||||
resolvesTo("sns", "Publish");
|
||||
|
||||
Response response = abortedWith(request("sns", WireProtocol.AWS_QUERY,
|
||||
MediaType.APPLICATION_FORM_URLENCODED_TYPE));
|
||||
|
||||
assertEquals(503, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertThat(body, containsString("<ErrorResponse xmlns=\"" + AwsNamespaces.SNS + "\">"));
|
||||
assertThat(body, containsString("<Type>Receiver</Type>"));
|
||||
assertThat(body, containsString("<Code>ServiceUnavailable</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRestXmlServiceGetsItsErrorResponseInItsOwnNamespace() {
|
||||
faults(new FisApiFault(FisApiFault.Kind.THROTTLE, "route53", Set.of("ListHostedZones"), 100,
|
||||
Set.of(TARGET_ROLE), FAR_FUTURE),
|
||||
new FisApiFault(FisApiFault.Kind.THROTTLE, "cloudfront", Set.of("ListDistributions"), 100,
|
||||
Set.of(TARGET_ROLE), FAR_FUTURE));
|
||||
|
||||
resolvesTo("route53", "ListHostedZones");
|
||||
String route53 = (String) abortedWith(request("route53", WireProtocol.REST, null)).getEntity();
|
||||
resolvesTo("cloudfront", "ListDistributions");
|
||||
String cloudFront = (String) abortedWith(request("cloudfront", WireProtocol.REST, null)).getEntity();
|
||||
|
||||
assertThat(route53, containsString("<ErrorResponse xmlns=\"" + AwsNamespaces.ROUTE53 + "\">"));
|
||||
assertThat(route53, containsString("<Code>ThrottlingException</Code>"));
|
||||
assertThat(cloudFront, containsString("<ErrorResponse xmlns=\"" + AwsNamespaces.CLOUDFRONT + "\">"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceIsMatchedByItsIamNamespaceAsWellAsTheScopeItIsServedUnder() {
|
||||
faults(new FisApiFault(FisApiFault.Kind.THROTTLE, "cloudwatch", Set.of("PutMetricData"), 100,
|
||||
Set.of(TARGET_ROLE), FAR_FUTURE));
|
||||
when(operationResolver.resolve(anyString(), anyString(), any(), any())).thenReturn(
|
||||
new ResolvedOperation("monitoring", "cloudwatch:PutMetricData", "monitoring:PutMetricData"));
|
||||
|
||||
Response response = abortedWith(request("monitoring", WireProtocol.AWS_QUERY,
|
||||
MediaType.APPLICATION_FORM_URLENCODED_TYPE));
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void s3GetsItsOwnErrorEnvelope() {
|
||||
faults(new FisApiFault(FisApiFault.Kind.THROTTLE, "s3", Set.of("GetObject"), 100,
|
||||
Set.of(TARGET_ROLE), FAR_FUTURE));
|
||||
resolvesTo("s3", "GetObject");
|
||||
|
||||
Response response = abortedWith(request("s3", WireProtocol.REST, null));
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertThat(body, containsString("<Error><Code>ThrottlingException</Code>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherRolesCallIsLeftAloneWithoutWorkingOutItsOperation() {
|
||||
faults(new FisApiFault(FisApiFault.Kind.THROTTLE, "ec2", Set.of("DescribeInstances"), 100,
|
||||
Set.of(TARGET_ROLE), FAR_FUTURE));
|
||||
caller("arn:aws:iam::000000000000:role/someone-else");
|
||||
ContainerRequestContext ctx = request("ec2", null, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
|
||||
filter().filter(ctx);
|
||||
|
||||
verify(ctx, never()).abortWith(any());
|
||||
verifyNoInteractions(operationResolver);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOperationTheActionDoesNotNameIsLeftAlone() {
|
||||
faults(new FisApiFault(FisApiFault.Kind.THROTTLE, "ec2", Set.of("DescribeInstances"), 100,
|
||||
Set.of(TARGET_ROLE), FAR_FUTURE));
|
||||
resolvesTo("ec2", "RunInstances");
|
||||
ContainerRequestContext ctx = request("ec2", null, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
|
||||
filter().filter(ctx);
|
||||
|
||||
verify(ctx, never()).abortWith(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyTheActionsPercentageOfCallsFail() {
|
||||
faults(new FisApiFault(FisApiFault.Kind.THROTTLE, "ec2", Set.of("DescribeInstances"), 30,
|
||||
Set.of(TARGET_ROLE), FAR_FUTURE));
|
||||
resolvesTo("ec2", "DescribeInstances");
|
||||
|
||||
roll = 30;
|
||||
ContainerRequestContext spared = request("ec2", null, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
filter().filter(spared);
|
||||
verify(spared, never()).abortWith(any());
|
||||
|
||||
roll = 29;
|
||||
assertEquals(503, abortedWith(request("ec2", null, MediaType.APPLICATION_FORM_URLENCODED_TYPE)).getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void withNoFaultRunningTheCallIsNotExamined() {
|
||||
faults();
|
||||
ContainerRequestContext ctx = request("ec2", null, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
|
||||
|
||||
filter().filter(ctx);
|
||||
|
||||
verify(ctx, never()).abortWith(any());
|
||||
verifyNoInteractions(iamService, operationResolver);
|
||||
}
|
||||
|
||||
private void faults(FisApiFault... faults) {
|
||||
when(fisService.activeApiFaults(REGION)).thenReturn(List.of(faults));
|
||||
}
|
||||
|
||||
private void caller(String principalArn) {
|
||||
when(iamService.resolveCallerArns(SESSION_KEY)).thenReturn(Optional.of(new CallerArns(
|
||||
"arn:aws:sts::000000000000:assumed-role/checkout/s1", principalArn,
|
||||
CallerArns.TYPE_ASSUMED_ROLE, "AROAEXAMPLE:s1", null, false)));
|
||||
}
|
||||
|
||||
private void resolvesTo(String service, String operation) {
|
||||
when(operationResolver.resolve(anyString(), anyString(), any(), any()))
|
||||
.thenReturn(new ResolvedOperation(service, service + ":" + operation, service + ":" + operation));
|
||||
}
|
||||
|
||||
private FisApiFaultFilter filter() {
|
||||
return new FisApiFaultFilter(config, fisService, iamService, new AccountResolver("000000000000"),
|
||||
requestContext, operationResolver, catalog, null, fixedRoll());
|
||||
}
|
||||
|
||||
private RandomGenerator fixedRoll() {
|
||||
return new RandomGenerator() {
|
||||
@Override
|
||||
public long nextLong() {
|
||||
return roll;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int nextInt(int bound) {
|
||||
return roll;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private Response abortedWith(ContainerRequestContext ctx) {
|
||||
filter().filter(ctx);
|
||||
ArgumentCaptor<Response> response = ArgumentCaptor.forClass(Response.class);
|
||||
verify(ctx).abortWith(response.capture());
|
||||
return response.getValue();
|
||||
}
|
||||
|
||||
private static ContainerRequestContext request(String scope, WireProtocol protocol, MediaType mediaType) {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
when(ctx.getHeaderString("Authorization")).thenReturn("AWS4-HMAC-SHA256 Credential=" + SESSION_KEY
|
||||
+ "/20261117/" + REGION + "/" + scope + "/aws4_request, SignedHeaders=host, Signature=deadbeef");
|
||||
UriInfo uri = mock(UriInfo.class);
|
||||
when(uri.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
|
||||
when(ctx.getUriInfo()).thenReturn(uri);
|
||||
when(ctx.getMediaType()).thenReturn(mediaType);
|
||||
if (protocol != null) {
|
||||
when(ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY))
|
||||
.thenReturn(new ProtocolClaim(protocol, null, null, null));
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package io.floci.aws.services.fis;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.services.fis.model.ExperimentTemplate;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The {@code aws:fis:inject-api-*} actions in {@link FisService}: the parameters a template must give them, the
|
||||
* faults a running one puts in force, and how each completes once its duration runs out.
|
||||
*/
|
||||
class FisApiFaultsTest {
|
||||
|
||||
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 static final String TARGET_ROLE = "arn:aws:iam::" + ACCOUNT_ID + ":role/app/checkout";
|
||||
private static final String THROTTLE = "aws:fis:inject-api-throttle-error";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final SteppedClock clock = new SteppedClock();
|
||||
private FisStores stores;
|
||||
private FisService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = service(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceAwsDoesNotListIsRefusedUnlessAnyServiceIsOn() throws Exception {
|
||||
String action = action(THROTTLE, "s3", "GetObject", "100", "PT1M", null);
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> createTemplate(actions("api", action)));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("ec2 and kinesis"), refused.getMessage());
|
||||
|
||||
service = service(true);
|
||||
createTemplate(actions("api", action));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPercentageOutsideOneToAHundredIsRefused() {
|
||||
for (String percentage : List.of("0", "101", "50%")) {
|
||||
AwsException refused = assertThrows(AwsException.class, () -> createTemplate(
|
||||
actions("api", action(THROTTLE, "ec2", "DescribeInstances", percentage, "PT1M", null))));
|
||||
assertTrue(refused.getMessage().contains("from 1 to 100"), percentage + ": " + refused.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDurationOutsideAMinuteToTwelveHoursIsRefused() {
|
||||
for (String duration : List.of("PT59S", "PT12H1S", "1m")) {
|
||||
AwsException refused = assertThrows(AwsException.class, () -> createTemplate(
|
||||
actions("api", action(THROTTLE, "ec2", "DescribeInstances", "100", duration, null))));
|
||||
assertTrue(refused.getMessage().contains("one minute to 12 hours"), duration + ": " + refused.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyOperationBetweenCommasIsRefused() {
|
||||
AwsException refused = assertThrows(AwsException.class, () -> createTemplate(
|
||||
actions("api", action(THROTTLE, "ec2", "DescribeInstances,", "100", "PT1M", null))));
|
||||
assertTrue(refused.getMessage().contains("separated using commas"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunningActionIsAFaultOnItsTargetRolesCalls() throws Exception {
|
||||
start(createTemplate(actions("api",
|
||||
action(THROTTLE, "ec2", "DescribeInstances,RunInstances", "40", "PT5M", null))));
|
||||
|
||||
List<FisApiFault> faults = service.activeApiFaults(REGION);
|
||||
|
||||
assertEquals(1, faults.size());
|
||||
FisApiFault fault = faults.getFirst();
|
||||
assertEquals(FisApiFault.Kind.THROTTLE, fault.kind());
|
||||
assertEquals("ec2", fault.service());
|
||||
assertEquals(Set.of("DescribeInstances", "RunInstances"), fault.operations());
|
||||
assertEquals(40, fault.percentage());
|
||||
assertEquals(Set.of(TARGET_ROLE), fault.roleArns());
|
||||
assertTrue(fault.matches(TARGET_ROLE, Set.of("ec2"), "RunInstances"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theActionCompletesWhenItsDurationRunsOutAndTheExperimentWithIt() throws Exception {
|
||||
String id = start(createTemplate(actions("api",
|
||||
action(THROTTLE, "ec2", "DescribeInstances", "100", "PT1M", null))));
|
||||
double started = experiment(id).path("startTime").asDouble();
|
||||
|
||||
clock.advance(Duration.ofSeconds(59));
|
||||
assertEquals("running", experiment(id).path("actions").path("api").path("state").path("status").asText());
|
||||
assertEquals(1, service.activeApiFaults(REGION).size());
|
||||
|
||||
clock.advance(Duration.ofSeconds(30));
|
||||
JsonNode experiment = experiment(id);
|
||||
JsonNode action = experiment.path("actions").path("api");
|
||||
assertEquals("completed", action.path("state").path("status").asText());
|
||||
assertEquals(started + 60, action.path("endTime").asDouble(), 0.001);
|
||||
assertEquals("completed", experiment.path("state").path("status").asText());
|
||||
assertEquals(started + 60, experiment.path("endTime").asDouble(), 0.001);
|
||||
assertTrue(service.activeApiFaults(REGION).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActionThatStartsAfterAnotherStartsWhenThatOneCompletes() throws Exception {
|
||||
String id = start(createTemplate(actions(
|
||||
"first", action(THROTTLE, "ec2", "DescribeInstances", "100", "PT1M", null),
|
||||
"second", action("aws:fis:inject-api-internal-error", "kinesis", "PutRecord", "100", "PT2M",
|
||||
"first"))));
|
||||
double started = experiment(id).path("startTime").asDouble();
|
||||
|
||||
clock.advance(Duration.ofSeconds(90));
|
||||
JsonNode second = experiment(id).path("actions").path("second");
|
||||
assertEquals("running", second.path("state").path("status").asText());
|
||||
assertEquals(started + 60, second.path("startTime").asDouble(), 0.001);
|
||||
List<FisApiFault> faults = service.activeApiFaults(REGION);
|
||||
assertEquals(1, faults.size());
|
||||
assertEquals(FisApiFault.Kind.INTERNAL, faults.getFirst().kind());
|
||||
|
||||
clock.advance(Duration.ofSeconds(90));
|
||||
JsonNode experiment = experiment(id);
|
||||
assertEquals("completed", experiment.path("state").path("status").asText());
|
||||
assertEquals(started + 180, experiment.path("endTime").asDouble(), 0.001);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherKindOfActionKeepsTheExperimentRunning() throws Exception {
|
||||
String id = start(createTemplate(actions(
|
||||
"api", action(THROTTLE, "ec2", "DescribeInstances", "100", "PT1M", null),
|
||||
"wait", "{\"actionId\":\"aws:fis:wait\",\"parameters\":{\"duration\":\"PT1M\"}}")));
|
||||
|
||||
clock.advance(Duration.ofMinutes(5));
|
||||
|
||||
JsonNode experiment = experiment(id);
|
||||
assertEquals("completed", experiment.path("actions").path("api").path("state").path("status").asText());
|
||||
assertEquals("running", experiment.path("actions").path("wait").path("state").path("status").asText());
|
||||
assertEquals("running", experiment.path("state").path("status").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRegionOrAccountWithoutAnInjectApiExperimentKeepsNothing() throws Exception {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
assertTrue(service.activeApiFaults("xx-test-" + i).isEmpty());
|
||||
}
|
||||
assertEquals(0, service.keptApiFaultKeys());
|
||||
|
||||
start(createTemplate(actions("api",
|
||||
action(THROTTLE, "ec2", "DescribeInstances", "100", "PT1M", null))));
|
||||
assertEquals(1, service.activeApiFaults(REGION).size());
|
||||
clock.advance(Duration.ofMinutes(2));
|
||||
|
||||
assertTrue(service.activeApiFaults(REGION).isEmpty());
|
||||
assertEquals(0, service.keptApiFaultKeys());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunningExperimentIsFoundAgainAfterARestart() throws Exception {
|
||||
start(createTemplate(actions("api",
|
||||
action(THROTTLE, "ec2", "DescribeInstances", "100", "PT10M", null))));
|
||||
|
||||
RegionResolver resolver = new RegionResolver(REGION, ACCOUNT_ID);
|
||||
FisService restarted = new FisService(stores, mapper, resolver, new FisCatalog(mapper, resolver),
|
||||
new Random(), () -> false, clock);
|
||||
|
||||
assertEquals(1, restarted.activeApiFaults(REGION).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStoredTemplateWhoseDurationWasNeverCheckedIsRefusedAtStart() throws Exception {
|
||||
String templateId = createTemplate(actions("api",
|
||||
action(THROTTLE, "ec2", "DescribeInstances", "100", "PT1M", null)));
|
||||
String key = REGION + "::template::" + templateId;
|
||||
ExperimentTemplate stored = stores.templates.get(key).orElseThrow();
|
||||
stored.getActions().get("api").getParameters().put("duration", "forever");
|
||||
stores.templates.put(key, stored);
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> start(templateId));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("one minute to 12 hours"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void stoppingTheExperimentEndsItsFaults() throws Exception {
|
||||
String id = start(createTemplate(actions("api",
|
||||
action(THROTTLE, "ec2", "DescribeInstances", "100", "PT10M", null))));
|
||||
assertEquals(1, service.activeApiFaults(REGION).size());
|
||||
|
||||
service.stopExperiment(REGION, id);
|
||||
|
||||
assertTrue(service.activeApiFaults(REGION).isEmpty());
|
||||
}
|
||||
|
||||
private FisService service(boolean anyService) {
|
||||
stores = FisStores.inMemory();
|
||||
RegionResolver resolver = new RegionResolver(REGION, ACCOUNT_ID);
|
||||
return new FisService(stores, mapper, resolver, new FisCatalog(mapper, resolver), new Random(),
|
||||
() -> anyService, clock);
|
||||
}
|
||||
|
||||
private static String action(String actionId, String service, String operations, String percentage,
|
||||
String duration, String startAfter) {
|
||||
return """
|
||||
{"actionId":"%s","targets":{"Roles":"roles"},%s
|
||||
"parameters":{"service":"%s","operations":"%s","percentage":"%s","duration":"%s"}}
|
||||
""".formatted(actionId, startAfter == null ? "" : "\"startAfter\":[\"" + startAfter + "\"],",
|
||||
service, operations, percentage, duration);
|
||||
}
|
||||
|
||||
private static String actions(String... namesAndActions) {
|
||||
StringBuilder actions = new StringBuilder("{");
|
||||
for (int i = 0; i < namesAndActions.length; i += 2) {
|
||||
actions.append(i == 0 ? "" : ",").append('"').append(namesAndActions[i]).append("\":")
|
||||
.append(namesAndActions[i + 1]);
|
||||
}
|
||||
return actions.append('}').toString();
|
||||
}
|
||||
|
||||
private String createTemplate(String actions) throws Exception {
|
||||
ObjectNode template = (ObjectNode) mapper.readTree("""
|
||||
{
|
||||
"clientToken":"%s",
|
||||
"description":"inject-api template",
|
||||
"roleArn":"%s",
|
||||
"stopConditions":[{"source":"none"}],
|
||||
"targets":{"roles":{"resourceType":"aws:iam:role","resourceArns":["%s"],"selectionMode":"ALL"}},
|
||||
"actions":%s
|
||||
}
|
||||
""".formatted(UUID.randomUUID(), ROLE_ARN, TARGET_ROLE, actions));
|
||||
return service.createExperimentTemplate(REGION, template).path("experimentTemplate").path("id").asText();
|
||||
}
|
||||
|
||||
private String start(String templateId) throws Exception {
|
||||
return service.startExperiment(REGION, mapper.readTree("""
|
||||
{"clientToken":"%s","experimentTemplateId":"%s"}
|
||||
""".formatted(UUID.randomUUID(), templateId))).path("experiment").path("id").asText();
|
||||
}
|
||||
|
||||
private JsonNode experiment(String id) {
|
||||
return service.getExperiment(REGION, id).path("experiment");
|
||||
}
|
||||
|
||||
/** A clock that stands still until the test moves it on. */
|
||||
private static final class SteppedClock extends Clock {
|
||||
|
||||
private Instant instant = Instant.parse("2026-11-17T12:00:00Z");
|
||||
|
||||
void advance(Duration duration) {
|
||||
instant = instant.plus(duration);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ZoneId getZone() {
|
||||
return ZoneOffset.UTC;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Clock withZone(ZoneId zone) {
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant instant() {
|
||||
return instant;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -457,6 +457,98 @@ class FisIntegrationTest {
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRunningInjectApiActionFailsTheTargetRolesCallsUntilTheExperimentStops() {
|
||||
String account = "000000000312";
|
||||
String roleName = "fis-inject-target-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
String roleArn = "arn:aws:iam::" + account + ":role/" + roleName;
|
||||
given().header("Authorization", authorization(account, REGION, "iam"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateRole")
|
||||
.formParam("Version", "2010-05-08")
|
||||
.formParam("RoleName", roleName)
|
||||
.formParam("AssumeRolePolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}"""
|
||||
.formatted(account))
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
String sessionKey = given().header("Authorization", authorization(account, REGION, "sts"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "AssumeRole")
|
||||
.formParam("Version", "2011-06-15")
|
||||
.formParam("RoleArn", roleArn)
|
||||
.formParam("RoleSessionName", "fis-inject")
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId");
|
||||
|
||||
String templateId = awsRequest(account, REGION).contentType("application/json").body("""
|
||||
{
|
||||
"clientToken":"%s",
|
||||
"description":"throttle the checkout role's EC2 calls",
|
||||
"roleArn":"arn:aws:iam::%s:role/fis-role",
|
||||
"stopConditions":[{"source":"none"}],
|
||||
"targets":{"roles":{"resourceType":"aws:iam:role","resourceArns":["%s"],"selectionMode":"ALL"}},
|
||||
"actions":{"throttle":{
|
||||
"actionId":"aws:fis:inject-api-throttle-error",
|
||||
"targets":{"Roles":"roles"},
|
||||
"parameters":{"service":"ec2","operations":"DescribeInstances","percentage":"100",
|
||||
"duration":"PT10M"}}}
|
||||
}
|
||||
""".formatted(UUID.randomUUID(), account, roleArn))
|
||||
.post("/experimentTemplates")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().path("experimentTemplate.id");
|
||||
String experimentId = awsRequest(account, REGION).contentType("application/json").body("""
|
||||
{"clientToken":"%s","experimentTemplateId":"%s"}
|
||||
""".formatted(UUID.randomUUID(), templateId))
|
||||
.post("/experiments")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("experiment.actions.throttle.state.status", equalTo("running"))
|
||||
.extract().path("experiment.id");
|
||||
|
||||
given().header("Authorization", authorization(sessionKey, REGION, "ec2"))
|
||||
.formParam("Action", "DescribeInstances")
|
||||
.formParam("Version", "2016-11-15")
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(503)
|
||||
.body(containsString("<Code>RequestLimitExceeded</Code>"));
|
||||
// The action impairs the target role's calls only, and only the operations it names.
|
||||
given().header("Authorization", authorization(account, REGION, "ec2"))
|
||||
.formParam("Action", "DescribeInstances")
|
||||
.formParam("Version", "2016-11-15")
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
given().header("Authorization", authorization(sessionKey, REGION, "ec2"))
|
||||
.formParam("Action", "DescribeVpcs")
|
||||
.formParam("Version", "2016-11-15")
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
awsRequest(account, REGION)
|
||||
.delete("/experiments/" + experimentId)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
given().header("Authorization", authorization(sessionKey, REGION, "ec2"))
|
||||
.formParam("Action", "DescribeInstances")
|
||||
.formParam("Version", "2016-11-15")
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
awsRequest(account, REGION)
|
||||
.delete("/experimentTemplates/" + templateId)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void experimentsDoNotMutateEmulatedTargetServices() {
|
||||
String instanceId = null;
|
||||
|
||||
Reference in new issue
Block a user