From aeba963c8a5e4e83c88cc80fb3ec03ec80f5e0a4 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:20:48 -0400 Subject: [PATCH] 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> --- docs/configuration/environment-variables.md | 1 + docs/services/fis.md | 18 +- .../io/floci/aws/config/EmulatorConfig.java | 8 + .../aws/core/common/AwsQueryController.java | 26 +- .../aws/core/common/IamEnforcementFilter.java | 104 +----- .../core/common/ProtocolErrorResponses.java | 97 +++++ .../core/common/ResolvedServiceCatalog.java | 2 +- .../aws/core/common/ServiceEnabledFilter.java | 13 +- .../floci/aws/services/fis/FisApiErrors.java | 70 ++++ .../floci/aws/services/fis/FisApiFault.java | 57 +++ .../aws/services/fis/FisApiFaultFilter.java | 139 +++++++ .../io/floci/aws/services/fis/FisService.java | 348 +++++++++++++++++- src/main/resources/application.yml | 1 + .../services/fis/FisApiFaultFilterTest.java | 276 ++++++++++++++ .../aws/services/fis/FisApiFaultsTest.java | 285 ++++++++++++++ .../aws/services/fis/FisIntegrationTest.java | 92 +++++ 16 files changed, 1397 insertions(+), 140 deletions(-) create mode 100644 src/main/java/io/floci/aws/core/common/ProtocolErrorResponses.java create mode 100644 src/main/java/io/floci/aws/services/fis/FisApiErrors.java create mode 100644 src/main/java/io/floci/aws/services/fis/FisApiFault.java create mode 100644 src/main/java/io/floci/aws/services/fis/FisApiFaultFilter.java create mode 100644 src/test/java/io/floci/aws/services/fis/FisApiFaultFilterTest.java create mode 100644 src/test/java/io/floci/aws/services/fis/FisApiFaultsTest.java diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index c3e253bb6a..d964a2767a 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -693,6 +693,7 @@ See [Web Console](../ui/index.md) for running the console and swapping in a thir | `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_FIS_INJECT_API_ANY_SERVICE` | `false` | Let the FIS `aws:fis:inject-api-*` actions target any service namespace, not only `ec2` and `kinesis` | | `FLOCI_SERVICES_RESOURCEEXPLORER2_ENABLED` | `true` | Enable the Resource Explorer 2 service | | `FLOCI_SERVICES_APPCONFIG_ENABLED` | `true` | Enable the AppConfig service | | `FLOCI_SERVICES_APPCONFIGDATA_ENABLED` | `true` | Enable the AppConfig Data service | diff --git a/docs/services/fis.md b/docs/services/fis.md index 7af0a34e5c..5e378a060b 100644 --- a/docs/services/fis.md +++ b/docs/services/fis.md @@ -43,11 +43,24 @@ List operations accept AWS-compatible `maxResults` and `nextToken` parameters wh ## 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. +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. The `aws:fis:inject-api-*` actions are the exception, described below. + +### API error injection + +While an `aws:fis:inject-api-internal-error`, `aws:fis:inject-api-throttle-error` or `aws:fis:inject-api-unavailable-error` action runs, Floci fails the calls it impairs, as AWS does: + +- **Which calls.** A call is impaired when it is signed with a session of one of the action's target roles (`aws:iam:role`, resolved from `resourceArns`), and calls one of the comma-separated `operations` in the action's `service` namespace. The `percentage` parameter sets the share of those calls, from 1 to 100, that fail. Calls made with long-term credentials, other roles' sessions or other operations are left alone, and a call IAM enforcement refuses is refused first. +- **The error.** The AWS action reference says the response "depends on each service and API". EC2 answers with `InternalError` (500), `RequestLimitExceeded` (503) or `Unavailable` (503), from its error code list. Kinesis answers with the common errors `InternalFailure` (500), `ThrottlingException` (400) or `ServiceUnavailable` (503), in JSON or CBOR to match the request. +- **Parameters.** Templates must give `service` as `ec2` or `kinesis`, the two namespaces AWS supports, a `percentage` from 1 to 100, and a `duration` from one minute to 12 hours in ISO 8601 format. +- **Completion.** An inject-api action completes once its `duration` has run out, and an action that starts after it then starts. The experiment completes when every action has completed or been skipped. Other actions still run until the experiment is stopped, so an experiment that also holds one keeps running. + +Setting `FLOCI_SERVICES_FIS_INJECT_API_ANY_SERVICE` to `true` lets the inject-api actions target any namespace Floci emulates, not only `ec2` and `kinesis`. The `service` can be the IAM namespace, such as `cloudwatch`, or the name the service signs under, such as `monitoring`. Those services answer with the common errors in the envelope their protocol reads: an `ErrorResponse` in the service's own XML namespace for Query and REST-XML services, S3's `Error`, JSON or CBOR. + +A template stored before these checks existed is checked again when an experiment starts from it. 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. +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, the inject-api actions aside. 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. @@ -56,6 +69,7 @@ Regional, account-scoped limits mirror the default AWS FIS quotas for 500 experi | Variable | Default | Description | |---|---|---| | `FLOCI_SERVICES_FIS_ENABLED` | `true` | Enable or disable AWS FIS | +| `FLOCI_SERVICES_FIS_INJECT_API_ANY_SERVICE` | `false` | Let the `aws:fis:inject-api-*` actions target any service namespace, not only `ec2` and `kinesis` | | `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 | diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 51f934a9d9..d330ae6db7 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1386,6 +1386,14 @@ public interface EmulatorConfig { interface FisServiceConfig { @WithDefault("true") boolean enabled(); + + /** + * Whether the {@code aws:fis:inject-api-*} actions take any service namespace instead of only the + * {@code ec2} and {@code kinesis} ones AWS supports, so they can inject errors into the other services Floci + * emulates ({@code FLOCI_SERVICES_FIS_INJECT_API_ANY_SERVICE}). + */ + @WithDefault("false") + boolean injectApiAnyService(); } interface Route53ServiceConfig { diff --git a/src/main/java/io/floci/aws/core/common/AwsQueryController.java b/src/main/java/io/floci/aws/core/common/AwsQueryController.java index 00df07d098..a9d503df01 100644 --- a/src/main/java/io/floci/aws/core/common/AwsQueryController.java +++ b/src/main/java/io/floci/aws/core/common/AwsQueryController.java @@ -40,7 +40,6 @@ import org.jboss.logging.Logger; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -386,17 +385,8 @@ public class AwsQueryController { // Cognito is primarily JSON 1.1, but we provide a bridge for Query protocol if hit. // Convert MultivaluedMap to JsonNode if needed, but for now just return UnsupportedOperation // with Cognito namespace. - String xml = new XmlBuilder() - .start("ErrorResponse") - .start("Error") - .elem("Type", "Sender") - .elem("Code", "UnsupportedOperation") - .elem("Message", "Operation " + action + " is not supported by Cognito via Query protocol.") - .end("Error") - .elem("RequestId", UUID.randomUUID().toString()) - .end("ErrorResponse") - .build(); - return Response.status(400).entity(xml).type(MediaType.APPLICATION_XML).build(); + return xmlErrorResponse("UnsupportedOperation", + "Operation " + action + " is not supported by Cognito via Query protocol.", 400); } private static final String CLOUDWATCH_API_VERSION = "2010-08-01"; @@ -562,16 +552,6 @@ public class AwsQueryController { } private Response xmlErrorResponse(String code, String message, int status, String type) { - String xml = new XmlBuilder() - .start("ErrorResponse") - .start("Error") - .elem("Type", type) - .elem("Code", code) - .elem("Message", message) - .end("Error") - .elem("RequestId", UUID.randomUUID().toString()) - .end("ErrorResponse") - .build(); - return Response.status(status).entity(xml).type(MediaType.APPLICATION_XML).build(); + return ProtocolErrorResponses.queryXml(code, message, status, type); } } diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 2c0857a657..f90146cac1 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -1943,9 +1943,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter { private Response accessDeniedForRequest(String action, String credentialScope, ContainerRequestContext ctx, String resourceArn) { WireProtocol protocol = claimedProtocol(ctx); - if (isCbor(protocol)) { + if (ProtocolErrorResponses.isCbor(protocol)) { // 403, the status the Kinesis and CloudWatch common errors give AccessDeniedException. - return cborError(ctx, "AccessDeniedException", accessDeniedMessage(action), 403); + return ProtocolErrorResponses.cbor(ctx, "AccessDeniedException", accessDeniedMessage(action), 403); } // The route decides the envelope, not the resolved action: a request on an S3 Control // route is S3 Control's however its action reads, and only its ErrorResponse wrapper @@ -1978,7 +1978,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { String resourcePath = formatS3ResourcePath(resourceArn); return s3XmlAccessDenied(message, resourcePath); } - if (restXml || protocol == WireProtocol.AWS_QUERY || isFormEncoded(requestMediaType)) { + if (restXml || protocol == WireProtocol.AWS_QUERY + || ProtocolErrorResponses.isFormEncoded(requestMediaType)) { return queryXmlError(queryAccessDeniedCode(credentialScope), message); } int status = protocol == WireProtocol.AWS_JSON_1_0 || protocol == WireProtocol.AWS_JSON_1_1 @@ -2004,32 +2005,12 @@ public class IamEnforcementFilter implements ContainerRequestFilter { return "/" + tail; } - private static boolean isFormEncoded(MediaType mt) { - return mt != null - && "application".equalsIgnoreCase(mt.getType()) - && "x-www-form-urlencoded".equalsIgnoreCase(mt.getSubtype()); - } - private static Response queryXmlAccessDenied(String message) { return queryXmlError("AccessDenied", message); } private static Response queryXmlError(String code, String message) { - return queryXmlError(code, message, 403); - } - - private static Response queryXmlError(String code, String message, int status) { - String xml = new XmlBuilder() - .start("ErrorResponse") - .start("Error") - .elem("Type", "Sender") - .elem("Code", code) - .elem("Message", message) - .end("Error") - .elem("RequestId", UUID.randomUUID().toString()) - .end("ErrorResponse") - .build(); - return Response.status(status).type(MediaType.APPLICATION_XML).entity(xml).build(); + return ProtocolErrorResponses.queryXml(code, message, 403); } private static Response s3XmlAccessDenied(String message) { @@ -2037,11 +2018,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } private static Response s3XmlError(String code, String message, int status) { - return s3Xml(code, message, null, status); + return ProtocolErrorResponses.s3Xml(code, message, null, status); } private static Response s3XmlAccessDenied(String message, String resourcePath) { - return s3Xml("AccessDenied", message, resourcePath, 403); + return ProtocolErrorResponses.s3Xml("AccessDenied", message, resourcePath, 403); } /** @@ -2069,20 +2050,6 @@ public class IamEnforcementFilter implements ContainerRequestFilter { return Response.status(403).type(MediaType.APPLICATION_XML).entity(xml).build(); } - private static Response s3Xml(String code, String message, String resourcePath, int status) { - XmlBuilder xml = new XmlBuilder() - .raw("") - .start("Error") - .elem("Code", code) - .elem("Message", message); - if (resourcePath != null && !resourcePath.isBlank()) { - xml.elem("Resource", resourcePath); - } - xml.elem("RequestId", UUID.randomUUID().toString()) - .end("Error"); - return Response.status(status).type(MediaType.APPLICATION_XML).entity(xml.build()).build(); - } - /** * The response for an access key that exists nowhere, in each protocol's own vocabulary for * the same failure. S3 answers with {@code InvalidAccessKeyId}, as @@ -2101,8 +2068,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { if ("s3".equals(credentialScope)) { return s3XmlError("InvalidAccessKeyId", S3_INVALID_ACCESS_KEY_ID, 403); } - return protocolError(claimedProtocol(ctx), ctx, "InvalidClientTokenId", "UnrecognizedClientException", - INVALID_SECURITY_TOKEN, 403); + return ProtocolErrorResponses.of(claimedProtocol(ctx), ctx, "InvalidClientTokenId", + "UnrecognizedClientException", INVALID_SECURITY_TOKEN, 403); } /** {@link #unrecognizedClientResponse} for a caller that renders the error itself. */ @@ -2124,8 +2091,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { if ("s3".equals(credentialScope)) { return s3XmlError("ExpiredToken", S3_EXPIRED_TOKEN, 400); } - return protocolError(claimedProtocol(ctx), ctx, "ExpiredTokenException", "ExpiredTokenException", - EXPIRED_TOKEN, 403); + return ProtocolErrorResponses.of(claimedProtocol(ctx), ctx, "ExpiredTokenException", + "ExpiredTokenException", EXPIRED_TOKEN, 403); } /** {@link #expiredTokenResponse} for a caller that renders the error itself. */ @@ -2161,8 +2128,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { + "the Credential is mal-formed; expecting " + "\"/YYYYMMDD/REGION/SERVICE/aws4_request\".", 400); } - return protocolError(claimedProtocol(ctx), ctx, "IncompleteSignature", "IncompleteSignatureException", - message, 400); + return ProtocolErrorResponses.of(claimedProtocol(ctx), ctx, "IncompleteSignature", + "IncompleteSignatureException", message, 400); } /** @@ -2222,8 +2189,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { if (protocol == WireProtocol.AWS_QUERY && Ec2ErrorResponses.isEc2QueryRequest(ctx)) { return Ec2ErrorResponses.of("MissingAuthenticationToken", MISSING_AUTHENTICATION_TOKEN, 403); } - return protocolError(protocol, ctx, "MissingAuthenticationToken", "MissingAuthenticationTokenException", - MISSING_AUTHENTICATION_TOKEN, 403); + return ProtocolErrorResponses.of(protocol, ctx, "MissingAuthenticationToken", + "MissingAuthenticationTokenException", MISSING_AUTHENTICATION_TOKEN, 403); } private static WireProtocol claimedProtocol(ContainerRequestContext ctx) { @@ -2231,47 +2198,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { ? claim.protocol() : WireProtocol.REST; } - /** - * An authentication failure outside S3, in the shape the caller's protocol reads: a Query - * {@code ErrorResponse} for a form-encoded request, the request's own encoding for a CBOR - * call, and JSON otherwise. Query names some failures without the {@code Exception} suffix, and - * some differently altogether, so it takes its own code. - */ - private static Response protocolError(WireProtocol protocol, ContainerRequestContext ctx, String queryCode, - String code, String message, int status) { - if (isCbor(protocol)) { - return cborError(ctx, code, message, status); - } - if (protocol == WireProtocol.AWS_QUERY || isFormEncoded(ctx.getMediaType())) { - return queryXmlError(queryCode, message, status); - } - return jsonError(code, message, status); - } - - private static boolean isCbor(WireProtocol protocol) { - return protocol == WireProtocol.RPCV2_CBOR || protocol == WireProtocol.AWS_CBOR_TARGET; - } - - /** - * A CBOR client cannot read a JSON body, so a rejection has to arrive in the encoding the - * request used, the same shape the rpcv2 controller returns for its own errors. - */ - private static Response cborError(ContainerRequestContext ctx, String code, String message, int status) { - String requestContentType = ctx.getHeaderString(AwsCborContentTypeFilter.ORIGINAL_CONTENT_TYPE_HEADER); - if (requestContentType == null) { - requestContentType = ctx.getHeaderString("Content-Type"); - } - return CborErrorResponses.of(new AwsException(code, message, status), - CborErrorResponses.mediaTypeFor(requestContentType)); - } - private static Response jsonAccessDenied(String message, int status) { - return jsonError("AccessDeniedException", message, status); + return ProtocolErrorResponses.json("AccessDeniedException", message, status); } - /** A JSON error in the shape {@link AwsExceptionMapper} gives every other JSON failure. */ - private static Response jsonError(String code, String message, int status) { - return Response.status(status).type(MediaType.APPLICATION_JSON) - .entity(new AwsErrorResponse(code, message)).build(); - } } diff --git a/src/main/java/io/floci/aws/core/common/ProtocolErrorResponses.java b/src/main/java/io/floci/aws/core/common/ProtocolErrorResponses.java new file mode 100644 index 0000000000..51b0299c81 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/ProtocolErrorResponses.java @@ -0,0 +1,97 @@ +package io.floci.aws.core.common; + +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +import java.util.UUID; + +/** + * Error responses a filter answers with before any controller runs, built in the envelope the caller's wire protocol + * reads, since the controller that would otherwise render the error never sees the request. + */ +public final class ProtocolErrorResponses { + + private ProtocolErrorResponses() { + } + + /** + * An error outside S3 and EC2, in the shape the caller's protocol reads: a Query {@code ErrorResponse} for a + * form-encoded request, the request's own encoding for a CBOR call, and JSON otherwise. Query names some failures + * without the {@code Exception} suffix, and some differently altogether, so it takes its own code. + */ + public static Response of(WireProtocol protocol, ContainerRequestContext ctx, String queryCode, + String code, String message, int status) { + if (isCbor(protocol)) { + return cbor(ctx, code, message, status); + } + if (protocol == WireProtocol.AWS_QUERY || isFormEncoded(ctx.getMediaType())) { + return queryXml(queryCode, message, status); + } + return json(code, message, status); + } + + /** A Query {@code ErrorResponse}, which the REST-XML services other than S3 answer with too. */ + public static Response queryXml(String code, String message, int status) { + return queryXml(code, message, status, "Sender"); + } + + /** {@link #queryXml(String, String, int)} with the error's {@code Type}, {@code Receiver} for a server fault. */ + public static Response queryXml(String code, String message, int status, String type) { + String xml = new XmlBuilder() + .start("ErrorResponse") + .start("Error") + .elem("Type", type) + .elem("Code", code) + .elem("Message", message) + .end("Error") + .elem("RequestId", UUID.randomUUID().toString()) + .end("ErrorResponse") + .build(); + return Response.status(status).type(MediaType.APPLICATION_XML).entity(xml).build(); + } + + /** S3's bare {@code } body, naming the bucket or object in {@code Resource} when given one. */ + public static Response s3Xml(String code, String message, String resourcePath, int status) { + XmlBuilder xml = new XmlBuilder() + .raw("") + .start("Error") + .elem("Code", code) + .elem("Message", message); + if (resourcePath != null && !resourcePath.isBlank()) { + xml.elem("Resource", resourcePath); + } + xml.elem("RequestId", UUID.randomUUID().toString()) + .end("Error"); + return Response.status(status).type(MediaType.APPLICATION_XML).entity(xml.build()).build(); + } + + /** A JSON error in the shape {@link AwsExceptionMapper} gives every other JSON failure. */ + public static Response json(String code, String message, int status) { + return Response.status(status).type(MediaType.APPLICATION_JSON) + .entity(new AwsErrorResponse(code, message)).build(); + } + + /** + * A CBOR client cannot read a JSON body, so an error has to arrive in the encoding the request used, the same + * shape the rpcv2 controller returns for its own errors. + */ + public static Response cbor(ContainerRequestContext ctx, String code, String message, int status) { + String requestContentType = ctx.getHeaderString(AwsCborContentTypeFilter.ORIGINAL_CONTENT_TYPE_HEADER); + if (requestContentType == null) { + requestContentType = ctx.getHeaderString("Content-Type"); + } + return CborErrorResponses.of(new AwsException(code, message, status), + CborErrorResponses.mediaTypeFor(requestContentType)); + } + + public static boolean isCbor(WireProtocol protocol) { + return protocol == WireProtocol.RPCV2_CBOR || protocol == WireProtocol.AWS_CBOR_TARGET; + } + + public static boolean isFormEncoded(MediaType mediaType) { + return mediaType != null + && "application".equalsIgnoreCase(mediaType.getType()) + && "x-www-form-urlencoded".equalsIgnoreCase(mediaType.getSubtype()); + } +} diff --git a/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java b/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java index ca907e457d..ca91703a50 100644 --- a/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/floci/aws/core/common/ResolvedServiceCatalog.java @@ -664,7 +664,7 @@ public class ResolvedServiceCatalog { protocols(ServiceProtocol.JSON), Set.of("TransferService."), Set.of("transfer"), Set.of(), Set.of()), descriptor("route53", "route53", config.services().route53().enabled(), true, - "route53", config.storage().mode(), 5000L, null, ServiceProtocol.REST_XML, + "route53", config.storage().mode(), 5000L, AwsNamespaces.ROUTE53, ServiceProtocol.REST_XML, protocols(ServiceProtocol.REST_XML), Set.of(), Set.of("route53"), Set.of(), Set.of(Route53Controller.class)), descriptor("textract", "textract", config.services().textract().enabled(), true, diff --git a/src/main/java/io/floci/aws/core/common/ServiceEnabledFilter.java b/src/main/java/io/floci/aws/core/common/ServiceEnabledFilter.java index fbc9f1e0c1..cac79771f8 100644 --- a/src/main/java/io/floci/aws/core/common/ServiceEnabledFilter.java +++ b/src/main/java/io/floci/aws/core/common/ServiceEnabledFilter.java @@ -12,7 +12,6 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.ext.Provider; import java.util.Optional; -import java.util.UUID; @Provider public class ServiceEnabledFilter implements ContainerRequestFilter { @@ -106,17 +105,7 @@ public class ServiceEnabledFilter implements ContainerRequestFilter { .build(); } - String xml = new XmlBuilder() - .start("ErrorResponse") - .start("Error") - .elem("Type", "Sender") - .elem("Code", "ServiceNotAvailableException") - .elem("Message", message) - .end("Error") - .elem("RequestId", UUID.randomUUID().toString()) - .end("ErrorResponse") - .build(); - return Response.status(400).entity(xml).type(MediaType.APPLICATION_XML).build(); + return ProtocolErrorResponses.queryXml("ServiceNotAvailableException", message, 400); } private record ResolvedRequest(String serviceKey, ServiceProtocol protocol) { diff --git a/src/main/java/io/floci/aws/services/fis/FisApiErrors.java b/src/main/java/io/floci/aws/services/fis/FisApiErrors.java new file mode 100644 index 0000000000..b133c3f855 --- /dev/null +++ b/src/main/java/io/floci/aws/services/fis/FisApiErrors.java @@ -0,0 +1,70 @@ +package io.floci.aws.services.fis; + +import io.floci.aws.core.common.AwsQueryResponse; +import io.floci.aws.core.common.Ec2ErrorResponses; +import io.floci.aws.core.common.ProtocolErrorResponses; +import io.floci.aws.core.common.ServiceDescriptor; +import io.floci.aws.core.common.ServiceProtocol; +import io.floci.aws.core.common.WireProtocol; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.Response; + +/** + * The error an impaired call gets. FIS's action reference says only that "the specific response depends on each + * service and API", so each service answers with its own documented error for the failure: EC2 with the server + * errors its error code list gives, and every other service with the common errors the Kinesis and SNS API references + * list, in the envelope its protocol reads. A Query or REST-XML service's {@code ErrorResponse} carries the service's + * own XML namespace, as its own errors do. + */ +final class FisApiErrors { + + private FisApiErrors() { + } + + /** + * @param descriptor the service the call reaches, or {@code null} when the catalog has none for it + */ + static Response response(FisApiFault.Kind kind, String service, WireProtocol protocol, + ServiceDescriptor descriptor, ContainerRequestContext ctx) { + if ("ec2".equals(service)) { + return switch (kind) { + case INTERNAL -> Ec2ErrorResponses.of("InternalError", "An internal error has occurred.", 500); + case THROTTLE -> Ec2ErrorResponses.of("RequestLimitExceeded", + "The maximum request rate permitted by the Amazon EC2 APIs has been exceeded for your account.", + 503); + case UNAVAILABLE -> Ec2ErrorResponses.of("Unavailable", + "The server is overloaded and can't handle the request.", 503); + }; + } + CommonError error = CommonError.of(kind); + if ("s3".equals(service)) { + return ProtocolErrorResponses.s3Xml(error.code(), error.message(), null, error.status()); + } + if (ProtocolErrorResponses.isCbor(protocol)) { + return ProtocolErrorResponses.cbor(ctx, error.code(), error.message(), error.status()); + } + boolean restXml = descriptor != null && descriptor.supportsProtocol(ServiceProtocol.REST_XML); + if (restXml || protocol == WireProtocol.AWS_QUERY || ProtocolErrorResponses.isFormEncoded(ctx.getMediaType())) { + return AwsQueryResponse.error(error.code(), error.message(), + descriptor == null ? null : descriptor.xmlNamespace(), error.status()); + } + return ProtocolErrorResponses.json(error.code(), error.message(), error.status()); + } + + /** The common errors as the Kinesis and SNS API references word them. */ + private record CommonError(String code, String message, int status) { + + static CommonError of(FisApiFault.Kind kind) { + return switch (kind) { + case INTERNAL -> new CommonError("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.", 500); + case THROTTLE -> new CommonError("ThrottlingException", "Your request rate is too high. The AWS SDKs " + + "automatically retry requests that receive this exception. Reduce the frequency of " + + "requests.", 400); + case UNAVAILABLE -> new CommonError("ServiceUnavailable", + "The service is temporarily unavailable. Try again later.", 503); + }; + } + } +} diff --git a/src/main/java/io/floci/aws/services/fis/FisApiFault.java b/src/main/java/io/floci/aws/services/fis/FisApiFault.java new file mode 100644 index 0000000000..029af2d0a3 --- /dev/null +++ b/src/main/java/io/floci/aws/services/fis/FisApiFault.java @@ -0,0 +1,57 @@ +package io.floci.aws.services.fis; + +import java.util.Set; + +/** + * One running {@code aws:fis:inject-api-*} action: the calls it impairs, made by which roles, until when. + * + * @param kind the error the action injects + * @param service the API namespace whose calls it impairs + * @param operations the operations of that namespace it impairs + * @param percentage the share of matching calls, from 1 to 100, that fail + * @param roleArns the roles whose calls it impairs, from the action's resolved {@code Roles} target + * @param endTime when the action's duration runs out, in epoch seconds + */ +record FisApiFault(Kind kind, String service, Set operations, int percentage, Set roleArns, + double endTime) { + + static final String ACTION_PREFIX = "aws:fis:inject-api-"; + + /** The namespaces AWS lists for the {@code service} parameter. */ + static final Set AWS_SERVICES = Set.of("ec2", "kinesis"); + + static boolean isInjectApiAction(String actionId) { + return actionId != null && actionId.startsWith(ACTION_PREFIX); + } + + /** + * Whether a call to {@code operation}, made with a session of {@code roleArn}, is impaired. {@code namespaces} + * are the names of the service the call reaches: the scope it is served under and its IAM namespace, which differ + * for a few services, such as CloudWatch's {@code monitoring} and {@code cloudwatch}. + */ + boolean matches(String roleArn, Set namespaces, String operation) { + return roleArns.contains(roleArn) && namespaces.contains(service) && operations.contains(operation); + } + + /** The error an {@code aws:fis:inject-api-*} action injects, named by the suffix of its action ID. */ + enum Kind { + INTERNAL("internal-error"), + THROTTLE("throttle-error"), + UNAVAILABLE("unavailable-error"); + + private final String suffix; + + Kind(String suffix) { + this.suffix = suffix; + } + + static Kind of(String actionId) { + for (Kind kind : values()) { + if ((ACTION_PREFIX + kind.suffix).equals(actionId)) { + return kind; + } + } + throw new IllegalArgumentException("Not an inject-api action: " + actionId); + } + } +} diff --git a/src/main/java/io/floci/aws/services/fis/FisApiFaultFilter.java b/src/main/java/io/floci/aws/services/fis/FisApiFaultFilter.java new file mode 100644 index 0000000000..aa67a2cb6e --- /dev/null +++ b/src/main/java/io/floci/aws/services/fis/FisApiFaultFilter.java @@ -0,0 +1,139 @@ +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.AwsProtocolClaimFilter; +import io.floci.aws.core.common.IamEnforcementFilter; +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.SigV4CredentialScope; +import io.floci.aws.core.common.WireProtocol; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.iam.IamService.CallerArns; +import jakarta.annotation.Priority; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.Priorities; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.container.ContainerRequestFilter; +import jakarta.ws.rs.container.ResourceInfo; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.ext.Provider; + +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.random.RandomGenerator; + +/** + * Fails the calls a running {@code aws:fis:inject-api-*} action impairs: calls made with a session of one of the + * action's target roles, to one of the operations it names in the namespace it names, at the percentage it sets. + * + *

Post-matching, so the operation is read from the route that will serve the call, as IAM enforcement reads it, + * whatever protocol the call uses. It runs after {@link IamEnforcementFilter}, so a call IAM refuses is refused + * whatever an experiment does. Until an experiment is running in the caller's account and Region, a request costs + * one lookup of an empty list. + */ +@Provider +@ApplicationScoped +@Priority(Priorities.USER + 100) +public class FisApiFaultFilter implements ContainerRequestFilter { + + private final EmulatorConfig config; + private final FisService fisService; + private final IamService iamService; + private final AccountResolver accountResolver; + private final RequestContext requestContext; + private final RequestOperationResolver operationResolver; + private final ResolvedServiceCatalog catalog; + private final ResourceInfo resourceInfo; + /** An instance field, not a static one, so the native image needs no run-time initialization for it. */ + private final RandomGenerator random; + + @Inject + public FisApiFaultFilter(EmulatorConfig config, FisService fisService, IamService iamService, + AccountResolver accountResolver, RequestContext requestContext, + RequestOperationResolver operationResolver, ResolvedServiceCatalog catalog, + @Context ResourceInfo resourceInfo) { + this(config, fisService, iamService, accountResolver, requestContext, operationResolver, catalog, + resourceInfo, new Random()); + } + + FisApiFaultFilter(EmulatorConfig config, FisService fisService, IamService iamService, + AccountResolver accountResolver, RequestContext requestContext, + RequestOperationResolver operationResolver, ResolvedServiceCatalog catalog, + ResourceInfo resourceInfo, RandomGenerator random) { + this.config = config; + this.fisService = fisService; + this.iamService = iamService; + this.accountResolver = accountResolver; + this.requestContext = requestContext; + this.operationResolver = operationResolver; + this.catalog = catalog; + this.resourceInfo = resourceInfo; + this.random = random; + } + + @Override + public void filter(ContainerRequestContext ctx) { + if (!config.services().fis().enabled()) { + return; + } + String region = requestContext.getRegion() == null ? config.defaultRegion() : requestContext.getRegion(); + List faults = fisService.activeApiFaults(region); + if (faults.isEmpty()) { + return; + } + String auth = IamEnforcementFilter.requestAuthorization(ctx.getHeaderString("Authorization"), + ctx.getUriInfo().getQueryParameters()); + String accessKeyId = auth == null ? null : accountResolver.extractAccessKeyId(auth); + String scope = auth == null ? null : SigV4CredentialScope.serviceName(auth).orElse(null); + if (accessKeyId == null || scope == null) { + return; + } + String roleArn = iamService.resolveCallerArns(accessKeyId).map(CallerArns::principalArn).orElse(null); + if (roleArn == null || faults.stream().noneMatch(fault -> fault.roleArns().contains(roleArn))) { + return; + } + ResolvedOperation resolved = operationResolver.resolve(auth, catalog.canonicalCredentialScope(scope), ctx, + resourceInfo); + String operation = afterNamespace(resolved.operation()); + if (operation == null) { + return; + } + String iamNamespace = resolved.action() == null ? null : beforeColon(resolved.action()); + Set namespaces = iamNamespace == null || iamNamespace.equals(resolved.credentialScope()) + ? Set.of(resolved.credentialScope()) + : Set.of(resolved.credentialScope(), iamNamespace); + for (FisApiFault fault : faults) { + if (fault.matches(roleArn, namespaces, operation) && random.nextInt(100) < fault.percentage()) { + ctx.abortWith(FisApiErrors.response(fault.kind(), resolved.credentialScope(), claimedProtocol(ctx), + catalog.byCredentialScope(resolved.credentialScope()).orElse(null), ctx)); + return; + } + } + } + + /** An operation's own name, without the {@code :} the resolver puts before it. */ + private static String afterNamespace(String operation) { + if (operation == null) { + return null; + } + int colon = operation.indexOf(':'); + return colon < 0 ? operation : operation.substring(colon + 1); + } + + /** The IAM namespace an action is in, the {@code } of {@code :}. */ + private static String beforeColon(String action) { + int colon = action.indexOf(':'); + return colon < 0 ? action : action.substring(0, colon); + } + + private static WireProtocol claimedProtocol(ContainerRequestContext ctx) { + return ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim + ? claim.protocol() : null; + } +} diff --git a/src/main/java/io/floci/aws/services/fis/FisService.java b/src/main/java/io/floci/aws/services/fis/FisService.java index d8bff404df..51f84fa665 100644 --- a/src/main/java/io/floci/aws/services/fis/FisService.java +++ b/src/main/java/io/floci/aws/services/fis/FisService.java @@ -4,12 +4,14 @@ 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.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.Base64Url; import io.floci.aws.core.common.EpochSeconds; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.TagHandler; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.core.storage.StorageOperations; @@ -23,7 +25,9 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.math.BigInteger; -import java.time.Instant; +import java.time.Clock; +import java.time.Duration; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -34,9 +38,12 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.OptionalDouble; import java.util.Random; import java.util.Set; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BooleanSupplier; import java.util.function.Function; import java.util.random.RandomGenerator; import java.util.regex.Matcher; @@ -45,8 +52,10 @@ import java.util.regex.Pattern; /** * Stateful AWS Fault Injection Service control plane. * - *

Experiments are intentionally management-plane only: Floci records valid FIS state - * transitions and resolved target snapshots without applying faults to local resources.

+ *

Experiments are management-plane only, recording valid FIS state transitions and resolved + * target snapshots without applying faults to local resources, except for the + * {@code aws:fis:inject-api-*} actions: {@link FisApiFaultFilter} fails the calls a running one + * impairs, and each completes once its duration runs out.

*/ @ApplicationScoped public class FisService implements TagHandler { @@ -72,17 +81,32 @@ public class FisService implements TagHandler { 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 static final Duration MIN_ACTION_DURATION = Duration.ofMinutes(1); + private static final Duration MAX_ACTION_DURATION = Duration.ofHours(12); + private static final String ACTION_RUNNING = "The action is running in safe emulation mode."; private final FisStores stores; private final ObjectMapper mapper; private final RegionResolver regionResolver; private final FisCatalog catalog; private final RandomGenerator random; + private final BooleanSupplier injectApiAnyService; + private final Clock clock; + /** + * The accounts and Regions, by {@link #apiFaultKey}, where an experiment holding an inject-api action runs. Only + * these are looked into for faults, so a request from any other account, whatever account ID it names, is answered + * without a scan and leaves nothing behind. + */ + private final Set apiFaultKeys = ConcurrentHashMap.newKeySet(); + private volatile boolean apiFaultKeysLoaded; + /** The faults running in each of {@link #apiFaultKeys}, until the first of them ends. */ + private final Map apiFaults = new ConcurrentHashMap<>(); @Inject public FisService(StorageFactory storageFactory, ObjectMapper mapper, - RegionResolver regionResolver, FisCatalog catalog) { - this(new FisStores(storageFactory), mapper, regionResolver, catalog, new Random()); + RegionResolver regionResolver, FisCatalog catalog, EmulatorConfig config) { + this(new FisStores(storageFactory), mapper, regionResolver, catalog, new Random(), + () -> config.services().fis().injectApiAnyService(), Clock.systemUTC()); } FisService(FisStores stores, ObjectMapper mapper, @@ -92,11 +116,18 @@ public class FisService implements TagHandler { FisService(FisStores stores, ObjectMapper mapper, RegionResolver regionResolver, FisCatalog catalog, RandomGenerator random) { + this(stores, mapper, regionResolver, catalog, random, () -> false, Clock.systemUTC()); + } + + FisService(FisStores stores, ObjectMapper mapper, RegionResolver regionResolver, FisCatalog catalog, + RandomGenerator random, BooleanSupplier injectApiAnyService, Clock clock) { this.stores = stores; this.mapper = mapper; this.regionResolver = regionResolver; this.catalog = catalog; this.random = random; + this.injectApiAnyService = injectApiAnyService; + this.clock = clock; } public synchronized ObjectNode createExperimentTemplate(String region, JsonNode request) { @@ -201,8 +232,8 @@ public class FisService implements TagHandler { return wrap("action", action); } - public ObjectNode getExperiment(String region, String id) { - return wrap("experiment", requireExperiment(region, id)); + public synchronized ObjectNode getExperiment(String region, String id) { + return wrap("experiment", progressed(region, requireExperiment(region, id))); } public ObjectNode getExperimentTargetAccountConfiguration( @@ -278,9 +309,9 @@ public class FisService implements TagHandler { scope(region, "templates"), node -> node.path("id").asText()); } - public ObjectNode listExperiments( + public synchronized ObjectNode listExperiments( String region, Integer maxResults, String nextToken, String experimentTemplateId) { - List experiments = copiedScan(stores.experiments, experimentPrefix(region)); + List experiments = progressedExperiments(region); if (experimentTemplateId != null) { validateName(experimentTemplateId, "experimentTemplateId"); experiments.removeIf(experiment -> @@ -314,6 +345,13 @@ public class FisService implements TagHandler { } String templateId = requireText(input, "experimentTemplateId", 64); ObjectNode template = requireTemplate(region, templateId); + // A template stored before its inject-api parameters were checked is checked before it runs. + template.path("actions").forEach(action -> { + String actionId = action.path("actionId").asText(); + if (FisApiFault.isInjectApiAction(actionId)) { + validateInjectApiParameters(actionId, action.path("parameters")); + } + }); List configurations = targetAccountConfigurations(region, templateId); if ("multi-account".equals(template.path("experimentOptions").path("accountTargeting").asText()) && configurations.isEmpty()) { @@ -382,7 +420,7 @@ public class FisService implements TagHandler { reason = "The action is waiting for its dependencies."; } else { status = "running"; - reason = "The action is running in safe emulation mode."; + reason = ACTION_RUNNING; } action.set("state", state(status, reason)); if (!"pending".equals(status)) { @@ -414,17 +452,22 @@ public class FisService implements TagHandler { } putExperiment(region, id, experiment); + if (holdsInjectApiAction(experiment)) { + apiFaultKeys.add(apiFaultKey(region)); + } + apiFaults.clear(); 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); + ObjectNode experiment = progressed(region, 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); + apiFaults.clear(); } return wrap("experiment", experiment); } @@ -481,7 +524,8 @@ public class FisService implements TagHandler { throw validation("Safety lever status must be engaged or disengaged."); } if ("engaged".equals(status)) { - for (ObjectNode experiment : copiedScan(stores.experiments, experimentPrefix(region))) { + apiFaults.clear(); + for (ObjectNode experiment : progressedExperiments(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."); @@ -805,6 +849,9 @@ public class FisService implements TagHandler { throw validation("Action " + actionId + " requires parameter " + parameter.getKey() + "."); } }); + if (FisApiFault.isInjectApiAction(actionId)) { + validateInjectApiParameters(actionId, parameters); + } ObjectNode actionTargets = action.has("targets") ? requireObject(action.path("targets"), "action targets") : mapper.createObjectNode(); @@ -1209,6 +1256,279 @@ public class FisService implements TagHandler { return target; } + /** + * The parameters AWS's action reference gives the {@code aws:fis:inject-api-*} actions: a {@code service} it + * supports ({@code ec2} or {@code kinesis}, or any while {@code inject-api-any-service} is on), a + * {@code percentage} from 1 to 100, comma-separated {@code operations}, and a {@code duration} from one minute + * to 12 hours in ISO 8601 format. + */ + private void validateInjectApiParameters(String actionId, JsonNode parameters) { + String service = parameters.path("service").asText(); + if (!injectApiAnyService.getAsBoolean() && !FisApiFault.AWS_SERVICES.contains(service)) { + throw validation("Action " + actionId + " supports the services ec2 and kinesis, not " + service + "."); + } + int percentage = percentage(parameters); + if (percentage < 1 || percentage > 100) { + throw validation("The percentage of action " + actionId + " must be a whole number from 1 to 100."); + } + if (operations(parameters).isEmpty()) { + throw validation("Action " + actionId + " requires the operations to inject the fault into, " + + "separated using commas."); + } + Duration duration = actionDuration(parameters); + if (duration == null + || duration.compareTo(MIN_ACTION_DURATION) < 0 || duration.compareTo(MAX_ACTION_DURATION) > 0) { + throw validation("The duration of action " + actionId + + " must be from one minute to 12 hours in ISO 8601 format, such as PT1M."); + } + } + + /** An inject-api action's {@code percentage}, or 0 when it is not a whole number. */ + private static int percentage(JsonNode parameters) { + try { + return Integer.parseInt(parameters.path("percentage").asText()); + } catch (NumberFormatException e) { + return 0; + } + } + + /** The operations an inject-api action names, or none when an entry between its commas is empty. */ + private static Set operations(JsonNode parameters) { + String[] names = parameters.path("operations").asText().split(",", -1); + Set operations = new HashSet<>(); + for (String name : names) { + if (name.isEmpty()) { + return Set.of(); + } + operations.add(name); + } + return operations; + } + + /** An action's {@code duration} parameter, or null when it has none or it is not an ISO 8601 duration. */ + private static Duration actionDuration(JsonNode parameters) { + try { + return Duration.parse(parameters.path("duration").asText()); + } catch (DateTimeParseException e) { + return null; + } + } + + /** + * The inject-api faults running now in the caller's account and {@code region}. The answer is kept until the + * first of them runs out, or until an experiment starts or stops; an account and Region where none runs is + * answered from {@link #apiFaultKeys} alone, so a request made there costs a set lookup. + */ + public List activeApiFaults(String region) { + if (!apiFaultKeysLoaded) { + loadApiFaultKeys(); + } + String key = apiFaultKey(region); + if (!apiFaultKeys.contains(key)) { + return List.of(); + } + ApiFaultSnapshot snapshot = apiFaults.get(key); + if (snapshot != null && now() < snapshot.validUntil()) { + return snapshot.faults(); + } + return refreshApiFaults(region, key); + } + + /** Finds, once, the experiments with inject-api actions that were running when Floci last stopped. */ + private synchronized void loadApiFaultKeys() { + if (apiFaultKeysLoaded) { + return; + } + List experiments = stores.experiments instanceof AccountAwareStorageBackend accounts + ? accounts.scanAllAccounts() + : stores.experiments.scan(key -> true); + for (Experiment stored : experiments) { + ObjectNode experiment = toObjectNode(stored); + if (holdsInjectApiAction(experiment)) { + AwsArnUtils.Arn arn = AwsArnUtils.parse(experiment.path("arn").asText()); + apiFaultKeys.add(arn.accountId() + "::" + arn.region()); + } + } + apiFaultKeysLoaded = true; + } + + private synchronized List refreshApiFaults(String region, String key) { + // Requests that found the answer out of date queue here; the first works it out for the rest. + ApiFaultSnapshot current = apiFaults.get(key); + if (current != null && now() < current.validUntil()) { + return current.faults(); + } + List faults = new ArrayList<>(); + double validUntil = Double.POSITIVE_INFINITY; + boolean held = false; + for (ObjectNode experiment : progressedExperiments(region)) { + if (!holdsInjectApiAction(experiment)) { + continue; + } + held = true; + Map> resolvedArns = null; + for (JsonNode action : experiment.path("actions")) { + String actionId = action.path("actionId").asText(); + if (!FisApiFault.isInjectApiAction(actionId) + || !"running".equals(action.path("state").path("status").asText())) { + continue; + } + if (resolvedArns == null) { + resolvedArns = resolvedArnsByTarget(region, experiment.path("id").asText()); + } + JsonNode parameters = action.path("parameters"); + double endTime = action.path("startTime").asDouble() + durationSeconds(parameters); + validUntil = Math.min(validUntil, endTime); + String service = parameters.path("service").asText(); + if (injectApiAnyService.getAsBoolean() || FisApiFault.AWS_SERVICES.contains(service)) { + // An experiment started before its parameters were checked can still name a service out of + // scope; it impairs nothing then, as its percentage of 0 would not either. + faults.add(new FisApiFault(FisApiFault.Kind.of(actionId), service, + Set.copyOf(operations(parameters)), percentage(parameters), + resolvedArns.getOrDefault(action.path("targets").path("Roles").asText(), Set.of()), + endTime)); + } + } + } + if (!held) { + apiFaultKeys.remove(key); + apiFaults.remove(key); + return List.of(); + } + ApiFaultSnapshot snapshot = new ApiFaultSnapshot(List.copyOf(faults), validUntil); + apiFaults.put(key, snapshot); + return snapshot.faults(); + } + + /** Whether a running experiment holds an inject-api action that is running or still to start. */ + private static boolean holdsInjectApiAction(ObjectNode experiment) { + if (!"running".equals(experiment.path("state").path("status").asText())) { + return false; + } + for (JsonNode action : experiment.path("actions")) { + String status = action.path("state").path("status").asText(); + if (FisApiFault.isInjectApiAction(action.path("actionId").asText()) + && ("running".equals(status) || "pending".equals(status))) { + return true; + } + } + return false; + } + + /** The number of accounts and Regions whose faults are kept, for tests. */ + int keptApiFaultKeys() { + return apiFaultKeys.size() + apiFaults.size(); + } + + private Map> resolvedArnsByTarget(String region, String experimentId) { + Map> arns = new HashMap<>(); + for (ObjectNode resolved : copiedScan(stores.resolvedTargets, resolvedTargetPrefix(region, experimentId))) { + arns.computeIfAbsent(resolved.path("targetName").asText(), name -> new HashSet<>()) + .add(resolved.path("targetInformation").path("arn").asText()); + } + return arns; + } + + private String apiFaultKey(String region) { + return regionResolver.getAccountId() + "::" + region; + } + + private record ApiFaultSnapshot(List faults, double validUntil) { + } + + private List progressedExperiments(String region) { + List experiments = copiedScan(stores.experiments, experimentPrefix(region)); + experiments.forEach(experiment -> progressed(region, experiment)); + return experiments; + } + + /** The experiment as it stands now, stored again when time has moved it on. */ + private ObjectNode progressed(String region, ObjectNode experiment) { + if (advance(experiment)) { + putExperiment(region, experiment.path("id").asText(), experiment); + } + return experiment; + } + + /** + * Moves a running experiment on to now: an inject-api action completes once its duration has run out, a pending + * action starts when the last of the actions it starts after completes, and the experiment completes once every + * action has completed or been skipped. Nothing runs on a timer, so each read works out what has happened since + * the last one, at the times it happened. The other actions run until the experiment is stopped, as before. + * + * @return whether anything changed + */ + private boolean advance(ObjectNode experiment) { + if (!"running".equals(experiment.path("state").path("status").asText()) + || !(experiment.path("actions") instanceof ObjectNode actions)) { + return false; + } + double now = now(); + boolean changed = false; + boolean moved = true; + while (moved) { + moved = false; + for (JsonNode node : actions) { + ObjectNode action = (ObjectNode) node; + String status = action.path("state").path("status").asText(); + if ("pending".equals(status)) { + OptionalDouble start = dependenciesCompleted(actions, action); + if (start.isPresent() && start.getAsDouble() <= now) { + action.set("state", state("running", ACTION_RUNNING)); + action.put("startTime", start.getAsDouble()); + moved = true; + } + } else if ("running".equals(status) + && FisApiFault.isInjectApiAction(action.path("actionId").asText())) { + double end = action.path("startTime").asDouble() + durationSeconds(action.path("parameters")); + if (end <= now) { + action.set("state", state("completed", "The action completed.")); + action.put("endTime", end); + moved = true; + } + } + } + changed |= moved; + } + if (changed && allActionsFinished(actions)) { + double end = 0; + for (JsonNode action : actions) { + end = Math.max(end, action.path("endTime").asDouble()); + } + experiment.set("state", state("completed", "The experiment completed.")); + experiment.put("endTime", end); + } + return changed; + } + + /** When the last of the actions {@code action} starts after completed, or empty while one has not. */ + private static OptionalDouble dependenciesCompleted(ObjectNode actions, ObjectNode action) { + double start = 0; + for (JsonNode dependency : action.path("startAfter")) { + JsonNode before = actions.path(dependency.asText()); + if (!"completed".equals(before.path("state").path("status").asText())) { + return OptionalDouble.empty(); + } + start = Math.max(start, before.path("endTime").asDouble()); + } + return OptionalDouble.of(start); + } + + private static boolean allActionsFinished(ObjectNode actions) { + for (JsonNode action : actions) { + String status = action.path("state").path("status").asText(); + if (!"completed".equals(status) && !"skipped".equals(status)) { + return false; + } + } + return true; + } + + private static double durationSeconds(JsonNode parameters) { + Duration duration = actionDuration(parameters); + return duration == null ? Double.POSITIVE_INFINITY : duration.toMillis() / 1000.0; + } + private void stopExperimentNode(ObjectNode experiment, String reason) { double timestamp = now(); experiment.set("state", state("stopped", reason)); @@ -1490,7 +1810,7 @@ public class FisService implements TagHandler { } private long activeExperimentCount(String region) { - return copiedScan(stores.experiments, experimentPrefix(region)).stream() + return progressedExperiments(region).stream() .filter(experiment -> !TERMINAL_EXPERIMENT_STATES.contains( experiment.path("state").path("status").asText())) .count(); @@ -1656,7 +1976,7 @@ public class FisService implements TagHandler { } private double now() { - return EpochSeconds.fromInstant(Instant.now()); + return EpochSeconds.fromInstant(clock.instant()); } private String key(String region, String type, String id) { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index de85e6501a..f21cefa66c 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -994,6 +994,7 @@ floci: job-completion-delay-seconds: 3 fis: enabled: true + inject-api-any-service: false # Let the aws:fis:inject-api-* actions target any service, not only ec2 and kinesis route53: enabled: true vpc-association-control-plane-delay-ms: 0 diff --git a/src/test/java/io/floci/aws/services/fis/FisApiFaultFilterTest.java b/src/test/java/io/floci/aws/services/fis/FisApiFaultFilterTest.java new file mode 100644 index 0000000000..2c57d527c4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/fis/FisApiFaultFilterTest.java @@ -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("RequestLimitExceeded")); + } + + @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("")); + assertThat(body, containsString("Receiver")); + assertThat(body, containsString("ServiceUnavailable")); + } + + @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("")); + assertThat(route53, containsString("ThrottlingException")); + assertThat(cloudFront, containsString("")); + } + + @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("ThrottlingException")); + } + + @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 = 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; + } +} diff --git a/src/test/java/io/floci/aws/services/fis/FisApiFaultsTest.java b/src/test/java/io/floci/aws/services/fis/FisApiFaultsTest.java new file mode 100644 index 0000000000..3127af3ed6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/fis/FisApiFaultsTest.java @@ -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 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 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; + } + } +} diff --git a/src/test/java/io/floci/aws/services/fis/FisIntegrationTest.java b/src/test/java/io/floci/aws/services/fis/FisIntegrationTest.java index bb0fe9b691..c468b044b1 100644 --- a/src/test/java/io/floci/aws/services/fis/FisIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/fis/FisIntegrationTest.java @@ -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("RequestLimitExceeded")); + // 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;