feat(eventbridge): deliver AppSync mutation targets (#7488)

This commit is contained in:
Aniket Shukla authored and GitHub committed 2026-11-05 04:58:24 -04:00
1 parent 50aef92124
commit ca854a4194
25 files changed
+1406 -39

No files matched your search

+6 -4
View File
@@ -507,13 +507,18 @@ Floci provisions these AppSync resource types:
| Type | `Ref` returns | `Fn::GetAtt` attributes Floci serves |
|---|---|---|
| `AWS::AppSync::GraphQLApi` | the API id (AWS: the API ARN) | `ApiId`, `Arn`, `GraphQLUrl`, `GraphQLDns`, `RealtimeUrl`, `RealtimeDns` |
| `AWS::AppSync::GraphQLApi` | the API id (AWS: the API ARN) | `ApiId`, `Arn`, `GraphQLEndpointArn`, `GraphQLUrl`, `GraphQLDns`, `RealtimeUrl`, `RealtimeDns` |
| `AWS::AppSync::GraphQLSchema` | `<ApiId>GraphQLSchema` | `Id` (AWS rejects it, see below) |
| `AWS::AppSync::DataSource` | the data source ARN | `DataSourceArn`, `Name` |
| `AWS::AppSync::FunctionConfiguration` | the function ARN | `FunctionArn`, `FunctionId`, `Name`, `DataSourceName` |
| `AWS::AppSync::Resolver` | the resolver ARN | `ResolverArn`, `TypeName`, `FieldName` |
| `AWS::AppSync::ApiKey` | the key id, `da2-...` (AWS: the key ARN) | `ApiKey`, `ApiKeyId`, `Arn` |
`GraphQLEndpointArn` returns
`arn:<partition>:appsync:<region>:<account>:endpoints/graphql-api/<apiId>`. Use it to
configure an [EventBridge AppSync target](eventbridge.md#appsync-targets); the API's `Arn`
continues to identify `apis/<apiId>` for IAM permissions.
One template with all six types (an API with `API_KEY` plus `AWS_IAM` auth, `LogConfig`,
`XrayEnabled`, an inline schema, an `AWS_LAMBDA` data source, a direct Lambda resolver, an
`APPSYNC_JS` resolver, a function and an API key) was deployed to AWS and to Floci, and so was a
@@ -527,9 +532,6 @@ differences:
- `Ref` on an `ApiKey` returns the key id. AWS returns the key ARN,
`arn:<partition>:appsync:<region>:<account>:apis/<apiId>/apikeys/<keyId>`, the value of
`Fn::GetAtt Arn`. `ApiKey` and `ApiKeyId` are the same `da2-` string on both.
- `GraphQLEndpointArn` is not modeled. `Fn::GetAtt` on it resolves to the literal string
`<LogicalId>.GraphQLEndpointArn` and the stack still completes. AWS returns
`arn:<partition>:appsync:<region>:<account>:endpoints/graphql-api/<id>`.
- `GraphQLUrl` and `RealtimeUrl` point at Floci: `<base-url>/v1/apis/<apiId>/graphql` and the
matching WebSocket URL ending in `/graphql/realtime`. `GraphQLDns` and `RealtimeDns` are the
host of `base-url`. AWS returns `https://<id>.appsync-api.<region>.amazonaws.com/graphql` and
+66 -6
View File
@@ -152,6 +152,65 @@ the state machine from the account and region in its ARN.
State machine aliases and versions are not supported as EventBridge targets.
## AppSync Targets
A rule can invoke a mutation on a public AppSync GraphQL API configured for `AWS_IAM`,
either as its default or an additional authorization mode. Schema authorization directives
still apply. Set the target `Arn` to the GraphQL **endpoint ARN**,
`arn:aws:appsync:us-east-1:000000000000:endpoints/graphql-api/<api-id>`.
CloudFormation exposes this through `Fn::GetAtt: [Api, GraphQLEndpointArn]`.
```bash
aws events put-targets \
--rule order-placed-rule \
--targets '[{
"Id": "publish-order",
"Arn": "arn:aws:appsync:us-east-1:000000000000:endpoints/graphql-api/example",
"RoleArn": "arn:aws:iam::000000000000:role/EventBridgeAppSyncRole",
"AppSyncParameters": {
"GraphQLOperation": "mutation Publish($id: ID!) { publish(id: $id) { id } }"
},
"InputTransformer": {
"InputPathsMap": {"id": "$.detail.orderId"},
"InputTemplate": "{\"id\": <id>}"
}
}]' \
--endpoint-url $AWS_ENDPOINT_URL
```
The delivered input must be a JSON object containing the mutation's variables. `Input`,
`InputPath`, and `InputTransformer` work as for other targets; with none, the full event is
the variables object. `PutTargets`, `ListTargetsByRule`, persisted target settings, and
`AWS::Events::Rule` preserve `AppSyncParameters.GraphQLOperation`. Endpoint targets require
these settings and a parsed document containing exactly one mutation operation, with 1 to
1,048,576 characters. `PutTargets` validates the whole batch before storage, so a rejected
replacement preserves the previous targets. Validation errors omit the operation's sensitive
contents. Parsing uses the GraphQL sidecar and requires Docker; it does not require the target
API to exist or validate its schema fields during `PutTargets`.
CloudFormation rollback restores previously accepted targets without requiring the GraphQL
sidecar to be available.
With IAM enforcement enabled, the target role must exist and trust `events.amazonaws.com`,
including any trust conditions on the rule's `aws:SourceArn` and `aws:SourceAccount`. Its
policies, permissions boundary, and SCPs must allow `appsync:GraphQL` on the selected API
fields. The permission resources use `apis/<api-id>/...`, rather than the endpoint ARN;
`arn:aws:appsync:us-east-1:000000000000:apis/<api-id>/*` covers all fields of one API.
Resolvers receive the target role's identity, and their data sources retain their own
service-role authorization.
With IAM enforcement off, target role existence, trust and permission checks are skipped,
matching the other service-role integrations.
Only mutations are delivered. Private APIs and cross-account or cross-partition targets
are refused. The target ARN selects the API's region; an API with the same ID in another
region is not used. AppSync must be enabled. This target does not add realtime subscription
support to Floci's AppSync endpoint.
Pre-execution validation and authorization failures use the target's dead-letter handling;
retryable transport failures use its retry policy. Floci treats a returned GraphQL execution
result, including field errors and partial data, as delivered so it does not retry a mutation
that may have already written data. A GraphQL request error with no `data` member is a failed
delivery. This error mapping has integration coverage but has not been compared with live AWS.
## Redshift Data API Targets
A matching rule can submit one SQL statement to the Redshift Data API for a provisioned cluster, or
@@ -215,11 +274,12 @@ role update replaces the stored value. Omitting the role on an existing
cross-account event-bus target with the same ID and ARN retains its previous
role, as documented by AWS.
The value must be between 1 and 1600 characters when supplied. Floci stores
the role as configuration; target delivery does not assume it. Only Redshift
Data API targets check the role's trust and permissions (see
[Redshift Data API Targets](#redshift-data-api-targets)); no other target
enforces its role's IAM policies.
The value must be between 1 and 1600 characters when supplied.
With IAM enforcement on, [AppSync targets](#appsync-targets) and
[Redshift Data API targets](#redshift-data-api-targets) check the role's existence,
trust and permissions, including source-rule conditions. With enforcement off,
these checks are skipped. Other target types store the role as
configuration without assuming it or enforcing its IAM policies.
## API Destination Targets
@@ -300,7 +360,7 @@ aws events put-targets \
- A retry uses the target's current definition, so `PutTargets` changes apply to pending retries, and a target removed with `RemoveTargets` stops being retried.
- An accepted asynchronous Lambda invocation counts as delivered. A later function error is handled by Lambda's own retry and destination settings, not by the rule.
- Pending retries are kept in memory and are dropped by an emulator reset or restart.
- An `AWS::Events::Rule` target in a CloudFormation template keeps its `RetryPolicy`, `DeadLetterConfig`, `RoleArn` and `EcsParameters`, which reach the rule as `PutTargets` would set them. A value of another type than the resource schema declares for them fails the rule before it is created, with the message CloudFormation gives.
- An `AWS::Events::Rule` target in a CloudFormation template keeps its `RetryPolicy`, `DeadLetterConfig`, `RoleArn`, `EcsParameters` and `AppSyncParameters`, which reach the rule as `PutTargets` would set them. A value of another type than the resource schema declares for them fails the rule before it is created, with the message CloudFormation gives.
## Current Behavior
@@ -21,6 +21,7 @@ import io.github.hectorvent.floci.services.appsync.graphql.auth.SidecarFieldAuth
import io.github.hectorvent.floci.services.appsync.graphql.resolver.AppSyncResolverError;
import io.github.hectorvent.floci.services.appsync.graphql.resolver.AppSyncResolverExecutor;
import io.github.hectorvent.floci.services.appsync.graphql.resolver.ResolverCallbackSessions;
import io.github.hectorvent.floci.services.appsync.model.AuthenticationType;
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
import jakarta.inject.Inject;
import jakarta.ws.rs.POST;
@@ -43,6 +44,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;
/**
* AppSync GraphQL data-plane HTTP endpoint (separate from management {@code AppSyncController}).
@@ -167,6 +169,31 @@ public class AppSyncExecutionController {
}
}
/**
* Internal service delivery, after the adapter has resolved and checked the target role.
* Authorization failures reject the complete plan before any mutation can have side effects.
*/
public Map<String, Object> executeServiceMutation(String apiId, String query, Map<String, Object> variables,
AppSyncAuthContext auth, Predicate<PlannedField> permission) {
if (auth == null || auth.authenticationType() != AuthenticationType.AWS_IAM
|| auth.graphqlApi() == null || !apiId.equals(auth.graphqlApi().getApiId())) {
throw new AwsException("AccessDeniedException", "A service mutation requires an IAM identity.", 403);
}
String sdl = schemaRegistry.getSdl(apiId).orElseThrow(() -> new AppSyncTransportException(
502, "GraphQLSchemaException", AppSyncErrorFormatter.MSG_NO_SCHEMA));
String preparedSdl = schemaCompiler.withDirectivesAndScalars(sdl);
Map<String, String> scalars = schemaCompiler.scalarKindMapping();
PlanResult plan = sidecarClient.plan(preparedSdl, scalars, query, null);
if (!"MUTATION".equals(plan.operationType())) {
throw new AwsException("ValidationException", "An AppSync target requires a mutation operation.", 400);
}
List<DenyField> denied = fieldAuthorizationPlanner.planDenyFields(plan, auth, permission);
if (!denied.isEmpty()) {
throw new AwsException("AccessDeniedException", "The target role may not access every selected field.", 403);
}
return executeQuery(apiId, preparedSdl, scalars, new ParsedRequest(query, variables, null), denied, plan, auth);
}
/**
* Runs the query on the sidecar, wiring the resolver callback when any field the query touches
* actually has a resolver. Without one, the sidecar resolves every field over a null root value
@@ -122,7 +122,7 @@ public class AuthMiddleware {
identity, authType, authenticationType, deniedFields, api, accessKeyId, info.region(), info.accountId());
}
static Set<AuthenticationType> configuredModes(GraphqlApi api) {
public static Set<AuthenticationType> configuredModes(GraphqlApi api) {
Set<AuthenticationType> modes = new HashSet<>();
if (api.getAuthenticationType() != null) {
modes.add(api.getAuthenticationType());
@@ -324,7 +324,7 @@ public class IamAuthValidator {
return appsyncArn(region, accountId, "apis/" + apiId + "/*");
}
static String fieldArn(String region, String accountId, String apiId, String typeName, String fieldName) {
public static String fieldArn(String region, String accountId, String apiId, String typeName, String fieldName) {
return appsyncArn(region, accountId, "apis/" + apiId + "/types/" + typeName + "/fields/" + fieldName);
}
@@ -12,6 +12,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
/**
* Precomputes which {@code (typeName, fieldName)} coordinates a query must have redacted
@@ -34,12 +35,20 @@ public class SidecarFieldAuthorizationPlanner {
/** Empty when nothing needs redacting (including when {@code auth} carries no API context, same as the live path). */
public List<DenyField> planDenyFields(PlanResult plan, AppSyncAuthContext auth) {
return planDenyFields(plan, auth, field -> !iamAuthValidator.isFieldDenied(auth.accessKeyId(),
IamAuthValidator.fieldArn(auth.region(), auth.accountId(), auth.graphqlApi().getApiId(),
field.typeName(), field.fieldName())));
}
/** Service-role calls use the same directive checks with their own IAM principal evaluator. */
public List<DenyField> planDenyFields(PlanResult plan, AppSyncAuthContext auth,
Predicate<PlannedField> iamPermission) {
if (auth == null || auth.graphqlApi() == null) {
return List.of();
}
List<DenyField> denied = new ArrayList<>();
for (PlannedField field : plan.fields()) {
if (isDenied(field, auth)) {
if (isDenied(field, auth, iamPermission)) {
denied.add(new DenyField(field.typeName(), field.fieldName(),
AppSyncAuth.FIELD_UNAUTHORIZED_TYPE,
AppSyncAuth.fieldUnauthorizedMessage(field.fieldName(), field.typeName())));
@@ -48,21 +57,14 @@ public class SidecarFieldAuthorizationPlanner {
return denied;
}
private boolean isDenied(PlannedField field, AppSyncAuthContext auth) {
private boolean isDenied(PlannedField field, AppSyncAuthContext auth, Predicate<PlannedField> iamPermission) {
if (isDeniedField(field, auth)) {
return true;
}
if (!modeAllowed(field, auth)) {
return true;
}
if (auth.authenticationType() == AuthenticationType.AWS_IAM) {
String fieldArn = IamAuthValidator.fieldArn(
auth.region(), auth.accountId(), auth.graphqlApi().getApiId(), field.typeName(), field.fieldName());
if (iamAuthValidator.isFieldDenied(auth.accessKeyId(), fieldArn)) {
return true;
}
}
return false;
return auth.authenticationType() == AuthenticationType.AWS_IAM && !iamPermission.test(field);
}
private boolean isDeniedField(PlannedField field, AppSyncAuthContext auth) {
@@ -241,6 +241,9 @@ public class AppSyncCfnProvisioner implements CfnResourceProvisioner {
r.setPhysicalId(api.getApiId());
r.getAttributes().put("ApiId", api.getApiId());
r.getAttributes().put("Arn", api.getArn());
AwsArnUtils.Arn apiArn = AwsArnUtils.parse(api.getArn());
r.getAttributes().put("GraphQLEndpointArn", new AwsArnUtils.Arn(apiArn.partition(), apiArn.service(),
apiArn.region(), apiArn.accountId(), "endpoints/graphql-api/" + api.getApiId()).toString());
Map<String, String> uris = api.getUris() == null ? Map.of() : api.getUris();
String graphqlUrl = uris.get("GRAPHQL");
String realtimeUrl = uris.get("REALTIME");
@@ -231,6 +231,10 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
target.setBatchParameters(batchParameters);
}
target.setRoleArn(resolved.path("RoleArn").asText(null));
JsonNode appSyncParamsNode = resolved.path("AppSyncParameters");
if (appSyncParamsNode.isObject()) {
target.setAppSyncParameters(MAPPER.convertValue(appSyncParamsNode, Target.AppSyncParameters.class));
}
JsonNode ecsParamsNode = resolved.path("EcsParameters");
if (ecsParamsNode.isObject()) {
target.setEcsParameters(MAPPER.convertValue(
@@ -347,7 +351,7 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner {
eventBridgeService.removeTargets(ruleName, busName, added, region);
}
if (!restored.isEmpty()) {
eventBridgeService.putTargets(ruleName, busName, restored, region);
eventBridgeService.restoreAcceptedTargets(ruleName, busName, restored, region);
}
resource.getAttributes().remove(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR);
}
@@ -0,0 +1,146 @@
package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncExecutionController;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncAuth;
import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncAuthContext;
import io.github.hectorvent.floci.services.appsync.graphql.auth.AuthMiddleware;
import io.github.hectorvent.floci.services.appsync.graphql.auth.IamAuthValidator;
import io.github.hectorvent.floci.services.appsync.graphql.auth.IdentityBuilder;
import io.github.hectorvent.floci.services.appsync.model.AuthenticationType;
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer;
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Delivers to an AppSync API through its execution engine, never through a caller-supplied URL. */
@ApplicationScoped
public class AppSyncTargetInvoker {
private static final String EVENTS = ServicePrincipals.of("events");
private final AppSyncService appSync;
private final AppSyncExecutionController execution;
private final ServiceRoleAuthorizer authorizer;
private final ServiceRegistry registry;
private final RegionResolver regionResolver;
private final ObjectMapper mapper;
@Inject
public AppSyncTargetInvoker(AppSyncService appSync, AppSyncExecutionController execution,
ServiceRoleAuthorizer authorizer, ServiceRegistry registry,
RegionResolver regionResolver, ObjectMapper mapper) {
this.appSync = appSync;
this.execution = execution;
this.authorizer = authorizer;
this.registry = registry;
this.regionResolver = regionResolver;
this.mapper = mapper;
}
public void invoke(Target target, String payload, String ruleArn, String accountId) {
if (!registry.isServiceEnabled("appsync")) {
throw new AwsException("ServiceNotAvailableException", "Service appsync is not enabled.", 400);
}
AwsArnUtils.Arn endpoint = endpoint(target.getArn());
if (!endpoint.accountId().equals(accountId)) {
throw new AwsException("AccessDeniedException", "Cross-account AppSync targets are not supported.", 403);
}
if (ruleArn != null) {
if (!AwsArnUtils.isArn(ruleArn)) {
throw new AwsException("AccessDeniedException", "Invalid AppSync target source rule.", 403);
}
AwsArnUtils.Arn source = AwsArnUtils.parse(ruleArn);
if (!endpoint.partition().equals(source.partition()) || !accountId.equals(source.accountId())) {
throw new AwsException("AccessDeniedException", "The AppSync target must share the rule's account and partition.", 403);
}
}
Target.AppSyncParameters parameters = target.getAppSyncParameters();
String operation = parameters == null ? null : parameters.graphQLOperation();
if (operation == null || operation.isBlank() || operation.codePointCount(0, operation.length()) > 1048576) {
throw new AwsException("ValidationException", "An AppSync target requires GraphQLOperation of length 1-1048576.", 400);
}
Map<String, Object> variables = variables(payload);
RequestScopes.runAs(accountId, endpoint.region(), () -> {
String apiId = endpoint.resource().substring("endpoints/graphql-api/".length());
GraphqlApi api = appSync.getGraphqlApi(apiId);
String expected = new AwsArnUtils.Arn(endpoint.partition(), "appsync", endpoint.region(), accountId,
"apis/" + apiId).toString();
if (!expected.equals(api.getArn())) {
throw new AwsException("NotFoundException", "GraphQL API not found in the target region.", 404);
}
boolean iamConfigured = AuthMiddleware.configuredModes(api).contains(AuthenticationType.AWS_IAM);
if (!iamConfigured || !"GLOBAL".equals(api.getVisibility())) {
throw new AwsException("AccessDeniedException", "AppSync targets require a public API with AWS_IAM authorization.", 403);
}
authorizer.refusal(target.getRoleArn(), accountId, EVENTS, ruleArn, List.of()).ifPresent(reason -> {
throw new AwsException("AccessDeniedException", reason, 403);
});
String roleName = target.getRoleArn() == null ? null
: target.getRoleArn().substring(target.getRoleArn().lastIndexOf('/') + 1);
String callerArn = roleName == null ? null : AwsArnUtils.Arn.global(endpoint.partition(), "sts", accountId,
"assumed-role/" + roleName + "/EventBridge").toString();
AppSyncAuthContext auth = new AppSyncAuthContext(
IdentityBuilder.iam(accountId, null, roleName, callerArn, List.of()),
AppSyncAuth.AUTH_TYPE_IAM, AuthenticationType.AWS_IAM, Set.of(), api, null, endpoint.region(), accountId);
try {
Map<String, Object> result = execution.executeServiceMutation(apiId, operation, variables, auth,
field -> authorizer.refusal(
target.getRoleArn(), accountId, EVENTS, ruleArn, List.of(new Permission("appsync:GraphQL",
IamAuthValidator.fieldArn(endpoint.region(), accountId, apiId,
field.typeName(), field.fieldName())))).isEmpty());
// GraphQL request errors omit data; execution results include it even when null
// (spec section 7.1.3). Never retry a returned execution result after partial mutations.
if (!result.containsKey("data")) {
if (result.get("errors") instanceof List<?> errors && !errors.isEmpty()) {
throw new AwsException("ValidationException", "AppSync rejected the mutation before execution.", 400);
}
throw new AwsException("InternalFailure", "Invalid AppSync execution response.", 502);
}
} catch (AppSyncTransportException e) {
throw new AwsException(e.getErrorType(), e.getMessage(), e.getHttpStatus());
}
});
}
private AwsArnUtils.Arn endpoint(String value) {
if (!AwsArnUtils.isArn(value)) {
throw new AwsException("ValidationException", "Invalid AppSync GraphQL endpoint ARN.", 400);
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(value);
if (!"appsync".equals(arn.service()) || !arn.accountId().matches("[0-9]{12}")
|| !RegionResolver.isKnownRegion(arn.region()) || !regionResolver.partitionForRegion(arn.region()).equals(arn.partition())
|| !arn.resource().matches("endpoints/graphql-api/[A-Za-z0-9_-]+")) {
throw new AwsException("ValidationException", "Invalid AppSync GraphQL endpoint ARN.", 400);
}
return arn;
}
private Map<String, Object> variables(String payload) {
try {
JsonNode node = mapper.readTree(payload);
if (node == null || !node.isObject()) {
throw new AwsException("ValidationException", "AppSync target input must be a JSON object of variables.", 400);
}
return mapper.convertValue(node, new TypeReference<Map<String, Object>>() { });
} catch (JsonProcessingException e) {
throw new AwsException("ValidationException", "AppSync target input must be valid JSON.", 400);
}
}
}
@@ -0,0 +1,54 @@
package io.github.hectorvent.floci.services.eventbridge;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.Map;
/** Checks an endpoint target's document before any targets in the request are stored. */
@ApplicationScoped
public class AppSyncTargetValidator {
// Planning parses the document without executing it. A placeholder schema deliberately
// avoids requiring an existing API or checking its fields during PutTargets.
private static final String SDL = "type Query { _eventBridge: Boolean } type Mutation { _eventBridge: Boolean }";
private final GraphqlSidecarClient sidecar;
@Inject
public AppSyncTargetValidator(GraphqlSidecarClient sidecar) {
this.sidecar = sidecar;
}
public void validate(Target target) {
if (!AwsArnUtils.isArnFor(target.getArn(), "appsync")
|| !AwsArnUtils.parse(target.getArn()).resource().startsWith("endpoints/graphql-api/")) {
return;
}
String operation = target.getAppSyncParameters() == null
? null : target.getAppSyncParameters().graphQLOperation();
if (operation == null) {
throw invalidOperation();
}
try {
// No operationName: the sidecar rejects documents with multiple operations.
if (!"MUTATION".equals(sidecar.plan(SDL, Map.of(), operation, null).operationType())) {
throw invalidOperation();
}
} catch (AppSyncTransportException e) {
if (e.getHttpStatus() == 400) {
throw invalidOperation();
}
throw new AwsException("InternalFailure", "Unable to validate the AppSync target operation.", 500);
}
}
private static AwsException invalidOperation() {
return new AwsException("ValidationException",
"AppSyncParameters.GraphQLOperation must contain exactly one mutation operation.", 400);
}
}
@@ -302,6 +302,10 @@ public class EventBridgeHandler {
if (!httpParamsNode.isMissingNode() && httpParamsNode.isObject()) {
target.setHttpParameters(objectMapper.convertValue(httpParamsNode, HttpParameters.class));
}
JsonNode appSyncParamsNode = t.path("AppSyncParameters");
if (appSyncParamsNode.isObject()) {
target.setAppSyncParameters(objectMapper.convertValue(appSyncParamsNode, Target.AppSyncParameters.class));
}
targets.add(target);
}
}
@@ -380,6 +384,9 @@ public class EventBridgeHandler {
if (t.getHttpParameters() != null) {
node.set("HttpParameters", objectMapper.valueToTree(t.getHttpParameters()));
}
if (t.getAppSyncParameters() != null) {
node.set("AppSyncParameters", objectMapper.valueToTree(t.getAppSyncParameters()));
}
targetsArray.add(node);
}
return Response.ok(response).build();
@@ -89,6 +89,7 @@ public class EventBridgeInvoker {
private final RedshiftDataService redshiftDataService;
private final RedshiftTargetAuthorizer redshiftTargetAuthorizer;
private final RedshiftDataTargetSubmitter redshiftSubmitter;
private final AppSyncTargetInvoker appSyncTargetInvoker;
private final ServiceRegistry serviceRegistry;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@@ -97,6 +98,19 @@ public class EventBridgeInvoker {
private final Map<String, RateWindow> rateWindows = new ConcurrentHashMap<>();
@Inject
public EventBridgeInvoker(LambdaService lambdaService, SqsService sqsService, SnsService snsService,
BatchService batchService, FirehoseService firehoseService,
EventBridgeService eventBridgeService, EcsService ecsService,
EcsJsonHandler ecsJsonHandler, StepFunctionsService stepFunctionsService,
RedshiftDataService redshiftDataService, RedshiftTargetAuthorizer redshiftTargetAuthorizer,
ServiceRegistry serviceRegistry, RegionResolver regionResolver, ObjectMapper objectMapper,
EmulatorConfig config, AppSyncTargetInvoker appSyncTargetInvoker) {
this(lambdaService, sqsService, snsService, batchService, firehoseService, eventBridgeService,
ecsService, ecsJsonHandler, stepFunctionsService, redshiftDataService, redshiftTargetAuthorizer,
serviceRegistry, regionResolver, objectMapper, config,
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(), appSyncTargetInvoker);
}
public EventBridgeInvoker(LambdaService lambdaService,
SqsService sqsService,
SnsService snsService,
@@ -114,8 +128,7 @@ public class EventBridgeInvoker {
EmulatorConfig config) {
this(lambdaService, sqsService, snsService, batchService, firehoseService, eventBridgeService,
ecsService, ecsJsonHandler, stepFunctionsService, redshiftDataService, redshiftTargetAuthorizer,
serviceRegistry, regionResolver, objectMapper, config,
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build());
serviceRegistry, regionResolver, objectMapper, config, (AppSyncTargetInvoker) null);
}
EventBridgeInvoker(LambdaService lambdaService,
@@ -134,6 +147,18 @@ public class EventBridgeInvoker {
ObjectMapper objectMapper,
EmulatorConfig config,
HttpClient httpClient) {
this(lambdaService, sqsService, snsService, batchService, firehoseService, eventBridgeService,
ecsService, ecsJsonHandler, stepFunctionsService, redshiftDataService, redshiftTargetAuthorizer,
serviceRegistry, regionResolver, objectMapper, config, httpClient, null);
}
private EventBridgeInvoker(LambdaService lambdaService, SqsService sqsService, SnsService snsService,
BatchService batchService, FirehoseService firehoseService,
EventBridgeService eventBridgeService, EcsService ecsService,
EcsJsonHandler ecsJsonHandler, StepFunctionsService stepFunctionsService,
RedshiftDataService redshiftDataService, RedshiftTargetAuthorizer redshiftTargetAuthorizer,
ServiceRegistry serviceRegistry, RegionResolver regionResolver, ObjectMapper objectMapper,
EmulatorConfig config, HttpClient httpClient, AppSyncTargetInvoker appSyncTargetInvoker) {
this.lambdaService = lambdaService;
this.sqsService = sqsService;
this.snsService = snsService;
@@ -146,6 +171,7 @@ public class EventBridgeInvoker {
this.redshiftDataService = redshiftDataService;
this.redshiftTargetAuthorizer = redshiftTargetAuthorizer;
this.redshiftSubmitter = new RedshiftDataTargetSubmitter(redshiftDataService, objectMapper);
this.appSyncTargetInvoker = appSyncTargetInvoker;
this.serviceRegistry = serviceRegistry;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
@@ -344,6 +370,11 @@ public class EventBridgeInvoker {
}
} else if (arn.contains(":events:") && arn.contains(":api-destination/")) {
deliverToApiDestination(target, payload, region);
} else if (arn.contains(":appsync:")) {
if (appSyncTargetInvoker == null) {
throw new AwsException("ServiceNotAvailableException", "AppSync delivery is not available.", 400);
}
appSyncTargetInvoker.invoke(target, payload, ruleArn, regionResolver.getAccountId());
} else {
LOG.warnv("EventBridge: unsupported target ARN type: {0}", arn);
}
@@ -84,6 +84,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
private final TargetDispatcher dispatcher;
private final ResourceGroupsTaggingService resourceGroupsTaggingService;
private final ReplayDispatcher replayDispatcher;
private final AppSyncTargetValidator appSyncTargetValidator;
@Inject
public EventBridgeService(StorageFactory storageFactory,
@@ -93,7 +94,8 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
RuleScheduler ruleScheduler,
TargetDispatcher dispatcher,
ReplayDispatcher replayDispatcher,
ResourceGroupsTaggingService resourceGroupsTaggingService) {
ResourceGroupsTaggingService resourceGroupsTaggingService,
AppSyncTargetValidator appSyncTargetValidator) {
this(
storageFactory.create("eventbridge", "eventbridge-buses.json",
new TypeReference<Map<String, EventBus>>() {}),
@@ -112,7 +114,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
storageFactory.create("eventbridge", "eventbridge-api-destinations.json",
new TypeReference<Map<String, ApiDestination>>() {}),
regionResolver, objectMapper, ruleScheduler, dispatcher, replayDispatcher,
resourceGroupsTaggingService
resourceGroupsTaggingService, appSyncTargetValidator
);
}
@@ -129,7 +131,8 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
RuleScheduler ruleScheduler,
TargetDispatcher dispatcher,
ReplayDispatcher replayDispatcher,
ResourceGroupsTaggingService resourceGroupsTaggingService) {
ResourceGroupsTaggingService resourceGroupsTaggingService,
AppSyncTargetValidator appSyncTargetValidator) {
this.busStore = busStore;
this.ruleStore = ruleStore;
this.targetStore = targetStore;
@@ -144,6 +147,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
this.dispatcher = dispatcher;
this.replayDispatcher = replayDispatcher;
this.resourceGroupsTaggingService = resourceGroupsTaggingService;
this.appSyncTargetValidator = appSyncTargetValidator;
}
@PostConstruct
@@ -488,6 +492,20 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
public int putTargets(String ruleName, String busName, List<Target> newTargets, String region) {
validateTargetSettings(newTargets);
newTargets.forEach(appSyncTargetValidator::validate);
return upsertTargets(ruleName, busName, newTargets, region);
}
/**
* Internal rollback path for previously accepted targets. Local shape checks still apply,
* but restoring a snapshot must not depend on the GraphQL sidecar being available.
*/
public int restoreAcceptedTargets(String ruleName, String busName, List<Target> targets, String region) {
validateTargetSettings(targets);
return upsertTargets(ruleName, busName, targets, region);
}
private int upsertTargets(String ruleName, String busName, List<Target> newTargets, String region) {
String effectiveBus = resolvedBusName(busName);
String key = ruleKey(region, effectiveBus, ruleName);
Rule rule = ruleStore.get(key)
@@ -527,6 +545,15 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
private static void validateTargetSettings(List<Target> targets) {
for (int i = 0; i < targets.size(); i++) {
Target target = targets.get(i);
String operation = target.getAppSyncParameters() == null
? null : target.getAppSyncParameters().graphQLOperation();
if (operation != null) {
String violation = SmithyValidationErrors.Violations.WITHOUT_VALUES.lengthOutOfRange(
"targets." + (i + 1) + ".member.appSyncParameters.graphQLOperation", operation, 1, 1048576);
if (violation != null) {
throw SmithyValidationErrors.validationException(violation);
}
}
Integer attempts = target.getRetryPolicy() != null ? target.getRetryPolicy().maximumRetryAttempts() : null;
Integer age = target.getRetryPolicy() != null ? target.getRetryPolicy().maximumEventAgeInSeconds() : null;
String arn = target.getDeadLetterConfig() != null ? target.getDeadLetterConfig().arn() : null;
@@ -22,6 +22,7 @@ public class Target {
private RetryPolicy retryPolicy;
private DeadLetterConfig deadLetterConfig;
private HttpParameters httpParameters;
private AppSyncParameters appSyncParameters;
public Target() {}
@@ -73,6 +74,14 @@ public class Target {
public HttpParameters getHttpParameters() { return httpParameters; }
public void setHttpParameters(HttpParameters httpParameters) { this.httpParameters = httpParameters; }
public AppSyncParameters getAppSyncParameters() { return appSyncParameters; }
public void setAppSyncParameters(AppSyncParameters appSyncParameters) { this.appSyncParameters = appSyncParameters; }
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record AppSyncParameters(@JsonProperty("GraphQLOperation") String graphQLOperation) {}
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@@ -186,6 +186,8 @@ class AppSyncCfnProvisionerTest {
assertEquals(API_ID, r.getPhysicalId());
assertEquals(API_ID, r.getAttributes().get("ApiId"));
assertEquals("arn:aws:appsync:eu-west-1:000000000000:apis/" + API_ID, r.getAttributes().get("Arn"));
assertEquals("arn:aws:appsync:eu-west-1:000000000000:endpoints/graphql-api/" + API_ID,
r.getAttributes().get("GraphQLEndpointArn"));
assertEquals("http://localhost:4566/v1/apis/" + API_ID + "/graphql",
r.getAttributes().get("GraphQLUrl"));
assertEquals("ws://localhost:4566/v1/apis/" + API_ID + "/graphql/realtime",
@@ -548,7 +548,7 @@ class EventsCfnProvisionerTest {
assertTrue(provisioner.rollbackUpdate(r));
assertEquals(List.of("keep", "gone"), idsOfPutTargets(2).get(1));
assertEquals(List.of("keep", "gone"), idsOfWrittenTargets().get(1));
assertNull(r.getAttributes().get(RULE_TARGETS_SNAPSHOT_ATTR));
}
@@ -566,7 +566,7 @@ class EventsCfnProvisionerTest {
ArgumentCaptor<List<String>> removed = ArgumentCaptor.forClass(List.class);
verify(events).removeTargets(eq("orders"), any(), removed.capture(), anyString());
assertEquals(List.of("added"), removed.getValue());
assertEquals(List.of("keep"), idsOfPutTargets(2).get(1));
assertEquals(List.of("keep"), idsOfWrittenTargets().get(1));
}
@Test
@@ -579,6 +579,7 @@ class EventsCfnProvisionerTest {
assertFalse(provisioner.rollbackUpdate(r));
verify(events, never()).putTargets(anyString(), any(), any(), anyString());
verify(events, never()).restoreAcceptedTargets(anyString(), any(), any(), anyString());
verify(events, never()).removeTargets(anyString(), any(), any(), anyString());
}
@@ -588,14 +589,14 @@ class EventsCfnProvisionerTest {
stubTargetSequence(List.of(storedTarget("keep"), storedTarget("gone")),
List.of(storedTarget("keep"), storedTarget("gone")));
AwsException putFailure = new AwsException("ValidationException", "Too many targets", 400);
when(events.putTargets(anyString(), any(), any(), anyString())).thenThrow(putFailure).thenReturn(1);
when(events.putTargets(anyString(), any(), any(), anyString())).thenThrow(putFailure);
StackResource r = resource("AWS::Events::Rule", "Rule");
AwsException thrown = assertThrows(AwsException.class,
() -> provisioner.provision(r, ruleProps("keep"), ctx("orders")));
assertSame(putFailure, thrown);
assertEquals(List.of("keep", "gone"), idsOfPutTargets(2).get(1));
assertEquals(List.of("keep", "gone"), idsOfWrittenTargets().get(1));
assertNull(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
assertNull(r.getAttributes().get(RULE_TARGETS_SNAPSHOT_ATTR));
}
@@ -610,6 +611,7 @@ class EventsCfnProvisionerTest {
List.of(storedTarget("keep"), storedTarget("gone")));
AwsException putFailure = new AwsException("ValidationException", "Too many targets", 400);
doThrow(putFailure).when(events).putTargets(anyString(), any(), any(), anyString());
doThrow(putFailure).when(events).restoreAcceptedTargets(anyString(), any(), any(), anyString());
StackResource r = resource("AWS::Events::Rule", "Rule");
assertThrows(AwsException.class, () -> provisioner.provision(r, ruleProps("keep"), ctx("orders")));
@@ -653,10 +655,11 @@ class EventsCfnProvisionerTest {
}
}
/** The target ids of each PutTargets call, in order, asserting there were exactly {@code n}. */
private List<List<String>> idsOfPutTargets(int n) {
/** The target ids of the update and snapshot restore, asserting exactly one of each. */
private List<List<String>> idsOfWrittenTargets() {
ArgumentCaptor<List<Target>> put = ArgumentCaptor.forClass(List.class);
verify(events, times(n)).putTargets(eq("orders"), any(), put.capture(), anyString());
verify(events).putTargets(eq("orders"), any(), put.capture(), anyString());
verify(events).restoreAcceptedTargets(eq("orders"), any(), put.capture(), anyString());
return put.getAllValues().stream().map(call -> call.stream().map(Target::getId).toList()).toList();
}
@@ -781,6 +784,27 @@ class EventsCfnProvisionerTest {
verify(events, never()).restoreApiDestination(any(), any(), any(), any(), any(), any(), any());
}
@Test
void aRuleTargetKeepsItsAppSyncParameters() {
stubPutRule();
when(events.listTargetsByRule(anyString(), any(), anyString())).thenReturn(List.of());
ObjectNode appSyncTarget = target("appsync",
"arn:aws:appsync:us-east-1:000000000000:endpoints/graphql-api/example");
String operation = "mutation Publish($id: ID!) { publish(id: $id) { id } }";
appSyncTarget.putObject("AppSyncParameters").put("GraphQLOperation", operation);
appSyncTarget.put("RoleArn", "arn:aws:iam::000000000000:role/events-appsync");
ObjectNode props = mapper.createObjectNode().put("Name", "orders");
props.putArray("Targets").add(appSyncTarget);
provisioner.provision(resource("AWS::Events::Rule", "Rule"), props, ctx("orders"));
ArgumentCaptor<List<Target>> put = ArgumentCaptor.forClass(List.class);
verify(events).putTargets(eq("orders"), any(), put.capture(), anyString());
JsonNode stored = mapper.valueToTree(put.getValue().getFirst());
assertEquals(operation, stored.path("appSyncParameters").path("GraphQLOperation").asText());
assertEquals("arn:aws:iam::000000000000:role/events-appsync", stored.path("roleArn").asText());
}
@Test
void aRuleTargetKeepsItsHttpParameters() {
stubPutRule();
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.eventbridge.AppSyncTargetValidator;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.eventbridge.TargetDispatcher;
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
@@ -68,7 +69,8 @@ class EcsEventBridgeIntegrationTest {
null,
dispatcher,
null,
null
null,
mock(AppSyncTargetValidator.class)
);
EcsEventPublisher eventPublisher = new EcsEventPublisher(eventBridgeService, regionResolver, objectMapper);
@@ -0,0 +1,69 @@
package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlanResult;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlannedField;
import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry;
import io.github.hectorvent.floci.services.appsync.graphql.resolver.AppSyncResolverExecutor;
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
import io.github.hectorvent.floci.services.appsync.model.Resolver;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
final class EventBridgeAppSyncFixtures {
private static final ObjectMapper MAPPER = new ObjectMapper();
private EventBridgeAppSyncFixtures() {}
static GraphqlApi createApi(AppSyncService appSync, SchemaRegistry schemas,
String account, String region, String schema) {
return RequestScopes.callAs(account, region, () -> {
GraphqlApi api = appSync.createGraphqlApi(Map.of("name", "target-" + UUID.randomUUID(),
"authenticationType", "AWS_IAM"), region);
schemas.register(api.getApiId(), schema);
return api;
});
}
static void stubMutation(GraphqlSidecarClient sidecar, AppSyncResolverExecutor resolvers, PlannedField... fields) {
when(sidecar.plan(any(), any(), any(), any()))
.thenReturn(new PlanResult("MUTATION", List.of(fields)));
when(resolvers.findResolver(any(), any(), any())).thenReturn(new Resolver());
}
static Target target(GraphqlApi api, String account, String region, String roleArn, String operation) {
Target target = new Target("appsync", "arn:aws:appsync:" + region + ":" + account
+ ":endpoints/graphql-api/" + api.getApiId(), null, null);
target.setRoleArn(roleArn);
target.setAppSyncParameters(new Target.AppSyncParameters(operation));
return target;
}
static String policy(String effect, String resource) {
return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"" + effect
+ "\",\"Action\":\"appsync:GraphQL\",\"Resource\":\"" + resource + "\"}]}";
}
static String trust(String service, String sourceArn, String account) {
ObjectNode statement = MAPPER.createObjectNode().put("Effect", "Allow").put("Action", "sts:AssumeRole");
statement.putObject("Principal").put("Service", service + ".amazonaws.com");
statement.putObject("Condition").putObject("StringEquals").put("aws:SourceAccount", account);
if (sourceArn != null) {
((ObjectNode) statement.path("Condition")).putObject("ArnEquals").put("aws:SourceArn", sourceArn);
}
ObjectNode document = MAPPER.createObjectNode().put("Version", "2012-10-17");
document.putArray("Statement").add(statement);
return document.toString();
}
}
@@ -0,0 +1,98 @@
package io.github.hectorvent.floci.services.eventbridge;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlannedField;
import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry;
import io.github.hectorvent.floci.services.appsync.graphql.resolver.AppSyncResolverExecutor;
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.iam.IamService;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@QuarkusTest
class EventBridgeAppSyncRoleResolutionIntegrationTest {
private static final String ACCOUNT = "725018800006";
private static final String REGION = "us-east-1";
private static final String RULE = "arn:aws:events:" + REGION + ":" + ACCOUNT + ":rule/publish";
@Inject
AppSyncTargetInvoker invoker;
@Inject
IamService iam;
@Inject
EmulatorConfig config;
@Inject
AppSyncService appSync;
@Inject
SchemaRegistry schemas;
@InjectMock
GraphqlSidecarClient sidecar;
@InjectMock
AppSyncResolverExecutor resolvers;
private GraphqlApi api;
@BeforeEach
void createApi() {
reset(sidecar, resolvers);
api = EventBridgeAppSyncFixtures.createApi(appSync, schemas, ACCOUNT, REGION,
"type Query { unused: String } type Mutation { publish: String }");
EventBridgeAppSyncFixtures.stubMutation(sidecar, resolvers,
new PlannedField("Mutation", "publish", List.of(), List.of()));
when(sidecar.execute(any(), any(), any(), any(), any(), any(), any()))
.thenReturn(Map.of("data", Map.of("publish", "delivered")));
}
@AfterEach
void deleteApi() {
RequestScopes.runAs(ACCOUNT, REGION, () -> appSync.deleteGraphqlApi(api.getApiId()));
reset(sidecar, resolvers);
}
@Test
void aNonexistentRoleDoesNotBlockDeliveryWithIamEnforcementDisabled() {
assertFalse(config.services().iam().enforcementEnabled());
assertDelivered("arn:aws:iam::" + ACCOUNT + ":role/missing-" + UUID.randomUUID());
}
@Test
void roleTrustDoesNotBlockDeliveryWithIamEnforcementDisabled() {
assertFalse(config.services().iam().enforcementEnabled());
RequestScopes.runAs(ACCOUNT, REGION, () -> {
String name = "appsync-untrusted-" + UUID.randomUUID();
String roleArn = iam.createRole(name, "/", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",
"Principal":{"Service":"lambda.amazonaws.com"}}]}""", null, 3600, Map.of()).getArn();
try {
assertDelivered(roleArn);
} finally {
iam.deleteRole(name);
}
});
}
private void assertDelivered(String roleArn) {
Target target = EventBridgeAppSyncFixtures.target(api, ACCOUNT, REGION, roleArn, "mutation { publish }");
invoker.invoke(target, "{}", RULE, ACCOUNT);
verify(sidecar).execute(any(), any(), any(), any(), any(), any(), any());
}
}
@@ -0,0 +1,255 @@
package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.SidecarContainersProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
import software.amazon.awssdk.services.eventbridge.model.AppSyncParameters;
import software.amazon.awssdk.services.eventbridge.model.EventBridgeException;
import software.amazon.awssdk.services.eventbridge.model.InputTransformer;
import software.amazon.awssdk.services.eventbridge.model.Target;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.Message;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static io.github.hectorvent.floci.services.eventbridge.EventBridgeAppSyncFixtures.policy;
import static io.github.hectorvent.floci.services.eventbridge.EventBridgeAppSyncFixtures.trust;
import static io.github.hectorvent.floci.testing.CfnRequests.cfn;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Real SDK delivery through a CFN rule, GraphQL sidecar, resolver callback and DynamoDB. */
@QuarkusTest
@TestProfile(EventBridgeAppSyncSidecarIntegrationTest.EnforcedSidecars.class)
class EventBridgeAppSyncSidecarIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-west-2";
private static final String AUTH = "AWS4-HMAC-SHA256 Credential=test/20261104/" + REGION + "/cloudformation/aws4_request";
private static final String OPERATION = "mutation Publish($id: ID!) { publish(id: $id) { id caller } }";
private static final String SCHEMA = "type Message { id: ID! caller: String } type Query { unused: String } "
+ "type Mutation { publish(id: ID!): Message }";
private static final ObjectMapper MAPPER = new ObjectMapper();
public static class EnforcedSidecars extends SidecarContainersProfile {
@Override
public Map<String, String> getConfigOverrides() {
Map<String, String> overrides = new HashMap<>(super.getConfigOverrides());
overrides.put("floci.services.iam.enforcement-enabled", "true");
return overrides;
}
}
@Inject
IamService iam;
@Inject
GraphqlSidecarClient sidecar;
private String stack;
private String rule;
private String table;
private String targetRoleName;
private String dataRoleName;
private EventBridgeClient events;
private DynamoDbClient dynamo;
private SqsClient sqs;
private boolean stackCreated;
@BeforeAll
static void requireSidecar() {
SidecarContainersProfile.requireDockerAndImage("floci.services.appsync.graphql-image");
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void createStack() throws Exception {
sidecar.validateSchema(SCHEMA, Map.of());
String suffix = UUID.randomUUID().toString();
stack = "eb-appsync-" + suffix;
rule = stack + "-rule";
table = stack + "-items";
targetRoleName = stack + "-target";
dataRoleName = stack + "-data";
events = AwsTestClients.create(EventBridgeClient.builder(), "test", Region.of(REGION));
dynamo = AwsTestClients.create(DynamoDbClient.builder(), "test", Region.of(REGION));
sqs = AwsTestClients.create(SqsClient.builder(), "test", Region.of(REGION));
RequestScopes.runAs(ACCOUNT, REGION, () -> {
iam.createRole(targetRoleName, "/", trust("events", "arn:aws:events:" + REGION + ":" + ACCOUNT + ":rule/" + rule, ACCOUNT),
null, 3600, Map.of());
iam.putRolePolicy(targetRoleName, "invoke", policy("Allow", "arn:aws:appsync:" + REGION + ":" + ACCOUNT + ":apis/*"));
iam.createRole(dataRoleName, "/", trust("appsync", null, ACCOUNT), null, 3600, Map.of());
iam.putRolePolicy(dataRoleName, "invoke", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"dynamodb:PutItem",
"Resource":"arn:aws:dynamodb:%s:%s:table/%s"}]}""".formatted(REGION, ACCOUNT, table));
});
ObjectNode template = (ObjectNode) MAPPER.readTree(TEMPLATE);
ObjectNode resolver = (ObjectNode) template.path("Resources").path("Resolver").path("Properties");
resolver.put("RequestMappingTemplate", """
{"version":"2018-05-29","operation":"PutItem",
"key":{"id":$util.dynamodb.toDynamoDBJson($ctx.args.id)},
"attributeValues":{"caller":$util.dynamodb.toDynamoDBJson($ctx.identity.userArn)}}""");
ObjectNode target = (ObjectNode) template.path("Resources").path("Rule").path("Properties").path("Targets").get(0);
target.putObject("AppSyncParameters").put("GraphQLOperation", OPERATION);
target.putObject("InputTransformer").putObject("InputPathsMap").put("id", "$.detail.id");
((ObjectNode) target.path("InputTransformer")).put("InputTemplate", "{\"id\":<id>}");
cfn("CreateStack", stack).header("Authorization", AUTH).formParam("TemplateBody", MAPPER.writeValueAsString(template))
.formParam("Parameters.member.1.ParameterKey", "RuleName").formParam("Parameters.member.1.ParameterValue", rule)
.formParam("Parameters.member.2.ParameterKey", "TableName").formParam("Parameters.member.2.ParameterValue", table)
.formParam("Parameters.member.3.ParameterKey", "TargetRole").formParam("Parameters.member.3.ParameterValue", roleArn(targetRoleName))
.formParam("Parameters.member.4.ParameterKey", "DataRole").formParam("Parameters.member.4.ParameterValue", roleArn(dataRoleName))
.when().post("/").then().statusCode(200);
stackCreated = true;
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack, AUTH);
assertEquals("CREATE_COMPLETE", state.status(), state.reason());
}
@AfterEach
void cleanUp() {
try {
if (stackCreated) {
cfn("DeleteStack", stack).header("Authorization", AUTH).post("/").then().statusCode(200);
CfnStackWaits.awaitStackDeleted(stack, AUTH);
}
} finally {
if (targetRoleName != null) {
RequestScopes.runAs(ACCOUNT, REGION, () -> {
iam.deleteRolePolicy(targetRoleName, "invoke");
iam.deleteRole(targetRoleName);
iam.deleteRolePolicy(dataRoleName, "invoke");
iam.deleteRole(dataRoleName);
});
}
if (events != null) { events.close(); }
if (dynamo != null) { dynamo.close(); }
if (sqs != null) { sqs.close(); }
}
}
@Test
void sdkEventRunsTheCfnMutationAndPersistsTheTargetRoleIdentity() {
Target target = events.listTargetsByRule(request -> request.rule(rule)).targets().getFirst();
assertTrue(target.arn().startsWith("arn:aws:appsync:" + REGION + ":" + ACCOUNT + ":endpoints/graphql-api/"));
assertEquals(OPERATION, target.appSyncParameters().graphQLOperation());
assertEquals(roleArn(targetRoleName), target.roleArn());
send("delivered");
Map<String, AttributeValue> item = item("delivered");
assertNotNull(item.get("id"));
assertEquals("delivered", item.get("id").s());
assertEquals("arn:aws:sts::" + ACCOUNT + ":assumed-role/" + targetRoleName + "/EventBridge", item.get("caller").s());
}
@Test
void aDeniedTargetRoleDeadLettersTheEventWithoutWriting() {
RequestScopes.runAs(ACCOUNT, REGION, () -> iam.putRolePolicy(targetRoleName, "invoke",
policy("Deny", "arn:aws:appsync:" + REGION + ":" + ACCOUNT + ":apis/*")));
send("denied");
assertTrue(item("denied").isEmpty());
assertEquals("NO_PERMISSIONS", deadLetter().messageAttributes().get("ERROR_CODE").stringValue());
}
@Test
void realVariableCoercionFailureIsDeadLetteredInsteadOfAcknowledged() {
Target target = events.listTargetsByRule(request -> request.rule(rule)).targets().getFirst();
events.putTargets(request -> request.rule(rule).targets(target.toBuilder()
.inputTransformer((InputTransformer) null).input("{}").build()));
send("invalid");
assertTrue(item("invalid").isEmpty());
assertEquals("INVALID_PARAMETER", deadLetter().messageAttributes().get("ERROR_CODE").stringValue());
}
@Test
void realParserRejectsInvalidSettingsBeforeReplacingTheStoredTarget() {
Target original = events.listTargetsByRule(request -> request.rule(rule)).targets().getFirst();
List<Target> invalid = List.of(
original.toBuilder().appSyncParameters((AppSyncParameters) null).build(),
original.toBuilder().appSyncParameters(AppSyncParameters.builder().build()).build(),
original.toBuilder().appSyncParameters(p -> p.graphQLOperation("mutation {")).build(),
original.toBuilder().appSyncParameters(p -> p.graphQLOperation("query { unused }")).build(),
original.toBuilder().appSyncParameters(p -> p.graphQLOperation(
"mutation First { one } mutation Second { two }")).build());
for (Target replacement : invalid) {
EventBridgeException error = assertThrows(EventBridgeException.class,
() -> events.putTargets(request -> request.rule(rule).targets(replacement)));
assertEquals("ValidationException", error.awsErrorDetails().errorCode());
assertEquals(400, error.statusCode());
assertEquals(List.of(original), events.listTargetsByRule(request -> request.rule(rule)).targets());
}
String operation = """
# A keyword in a comment or string is not another operation.
mutation Publish { publish(id: "mutation { ignored }") { ...MessageFields } }
fragment MessageFields on Message { id }
""";
assertEquals(0, events.putTargets(request -> request.rule(rule).targets(original.toBuilder()
.appSyncParameters(p -> p.graphQLOperation(operation)).build())).failedEntryCount());
assertEquals(operation, events.listTargetsByRule(request -> request.rule(rule))
.targets().getFirst().appSyncParameters().graphQLOperation());
String maximum = OPERATION + "#" + "x".repeat(1048576 - OPERATION.length() - 1);
assertEquals(0, events.putTargets(request -> request.rule(rule).targets(original.toBuilder()
.appSyncParameters(p -> p.graphQLOperation(maximum)).build())).failedEntryCount());
assertEquals(maximum, events.listTargetsByRule(request -> request.rule(rule))
.targets().getFirst().appSyncParameters().graphQLOperation());
}
private void send(String id) {
assertEquals(0, events.putEvents(request -> request.entries(entry -> entry.source("test.appsync")
.detailType("publish").detail("{\"id\":\"" + id + "\"}"))).failedEntryCount());
}
private Map<String, AttributeValue> item(String id) {
return dynamo.getItem(request -> request.tableName(table).key(Map.of("id", AttributeValue.fromS(id)))).item();
}
private Message deadLetter() {
String url = sqs.getQueueUrl(request -> request.queueName(rule + "-dlq")).queueUrl();
List<Message> messages = sqs.receiveMessage(request -> request.queueUrl(url).messageAttributeNames("All")).messages();
assertEquals(1, messages.size());
return messages.getFirst();
}
private static String roleArn(String name) {
return "arn:aws:iam::" + ACCOUNT + ":role/" + name;
}
private static final String TEMPLATE = """
{"Parameters":{"RuleName":{"Type":"String"},"TableName":{"Type":"String"},
"TargetRole":{"Type":"String"},"DataRole":{"Type":"String"}},
"Resources":{
"Api":{"Type":"AWS::AppSync::GraphQLApi","Properties":{"Name":{"Ref":"RuleName"},"AuthenticationType":"AWS_IAM"}},
"Schema":{"Type":"AWS::AppSync::GraphQLSchema","Properties":{"ApiId":{"Fn::GetAtt":["Api","ApiId"]},
"Definition":"type Message { id: ID! caller: String } type Query { unused: String } type Mutation { publish(id: ID!): Message }"}},
"Table":{"Type":"AWS::DynamoDB::Table","Properties":{"TableName":{"Ref":"TableName"},"BillingMode":"PAY_PER_REQUEST",
"AttributeDefinitions":[{"AttributeName":"id","AttributeType":"S"}],"KeySchema":[{"AttributeName":"id","KeyType":"HASH"}]}},
"Data":{"Type":"AWS::AppSync::DataSource","DependsOn":"Schema","Properties":{"ApiId":{"Fn::GetAtt":["Api","ApiId"]},
"Name":"items","Type":"AMAZON_DYNAMODB","ServiceRoleArn":{"Ref":"DataRole"},
"DynamoDBConfig":{"AwsRegion":{"Ref":"AWS::Region"},"TableName":{"Ref":"Table"}}}},
"Resolver":{"Type":"AWS::AppSync::Resolver","DependsOn":"Schema","Properties":{"ApiId":{"Fn::GetAtt":["Api","ApiId"]},
"TypeName":"Mutation","FieldName":"publish","Kind":"UNIT","DataSourceName":{"Fn::GetAtt":["Data","Name"]},
"ResponseMappingTemplate":"$util.toJson($ctx.result)"}},
"Queue":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":{"Fn::Sub":"${RuleName}-dlq"}}},
"Rule":{"Type":"AWS::Events::Rule","DependsOn":"Resolver","Properties":{"Name":{"Ref":"RuleName"},
"EventPattern":{"source":["test.appsync"]},"Targets":[{"Id":"mutation","Arn":{"Fn::GetAtt":["Api","GraphQLEndpointArn"]},
"RoleArn":{"Ref":"TargetRole"},"DeadLetterConfig":{"Arn":{"Fn::GetAtt":["Queue","Arn"]}}}]}}}}
""";
}
@@ -0,0 +1,261 @@
package io.github.hectorvent.floci.services.eventbridge;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlanResult;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlannedDirective;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlannedField;
import io.github.hectorvent.floci.services.appsync.graphql.SchemaRegistry;
import io.github.hectorvent.floci.services.appsync.graphql.resolver.AppSyncResolverExecutor;
import io.github.hectorvent.floci.services.appsync.graphql.resolver.ResolverCallbackSessions;
import io.github.hectorvent.floci.services.appsync.model.GraphqlApi;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import static io.github.hectorvent.floci.services.eventbridge.EventBridgeAppSyncFixtures.policy;
import static io.github.hectorvent.floci.services.eventbridge.EventBridgeAppSyncFixtures.trust;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class EventBridgeAppSyncTargetIntegrationTest {
private static final String ACCOUNT = "725018800005";
private static final String REGION = "us-east-1";
private static final String RULE = "arn:aws:events:" + REGION + ":" + ACCOUNT + ":rule/publish";
private static final String OPERATION = "mutation Publish($id: ID!) { publish(id: $id) { id } }";
@Inject
EventBridgeInvoker invoker;
@Inject
AppSyncService appSync;
@Inject
SchemaRegistry schemas;
@Inject
IamService iam;
@Inject
ResolverCallbackSessions sessions;
@InjectMock
GraphqlSidecarClient sidecar;
@InjectMock
AppSyncResolverExecutor resolvers;
private GraphqlApi api;
private String roleName;
private String roleArn;
private Target target;
private final AtomicReference<Map<String, Object>> variables = new AtomicReference<>();
private final AtomicReference<Object> identity = new AtomicReference<>();
@BeforeEach
void setUp() {
reset(sidecar, resolvers);
variables.set(null);
identity.set(null);
api = EventBridgeAppSyncFixtures.createApi(appSync, schemas, ACCOUNT, REGION,
"type Query { unused: String } type Mutation { publish(id: ID!): Result } type Result { id: ID }");
RequestScopes.runAs(ACCOUNT, REGION, () -> {
roleName = "appsync-target-" + UUID.randomUUID();
roleArn = iam.createRole(roleName, "/", trust("events", RULE, ACCOUNT), null, 3600, Map.of()).getArn();
iam.putRolePolicy(roleName, "invoke", policy("Allow", api.getArn() + "/*"));
});
target = EventBridgeAppSyncFixtures.target(api, ACCOUNT, REGION, roleArn, OPERATION);
EventBridgeAppSyncFixtures.stubMutation(sidecar, resolvers,
new PlannedField("Mutation", "publish", List.of(), List.of()),
new PlannedField("Result", "id", List.of(), List.of()));
lenient().when(sidecar.execute(any(), any(), any(), any(), any(), any(), any())).thenAnswer(call -> {
variables.set(call.getArgument(3));
GraphqlSidecarClient.ResolveSpec spec = call.getArgument(6);
ResolverCallbackSessions.Session session = sessions.find(spec.token()).orElseThrow();
identity.set(session.identity());
assertEquals(ACCOUNT, session.accountId());
assertEquals(REGION, session.region());
return Map.of("data", Map.of("publish", Map.of("id", "delivered")));
});
}
@AfterEach
void cleanUp() {
RequestScopes.runAs(ACCOUNT, REGION, () -> {
appSync.deleteGraphqlApi(api.getApiId());
iam.deleteRolePolicy(roleName, "invoke");
iam.deleteRole(roleName);
});
reset(sidecar, resolvers);
}
@Test
void transformedInputRunsAMutationAsTheTargetRole() {
target.setInputPath("$.detail");
invoke("{\"detail\":{\"id\":\"event-1\",\"optional\":null}}");
assertNotNull(variables.get());
assertEquals("event-1", variables.get().get("id"));
assertEquals(true, variables.get().containsKey("optional"));
assertNotNull(identity.get());
Map<?, ?> caller = (Map<?, ?>) identity.get();
assertEquals(ACCOUNT, caller.get("accountId"));
assertEquals("arn:aws:sts::" + ACCOUNT + ":assumed-role/" + roleName + "/EventBridge", caller.get("userArn"));
}
@Test
void aRuleInAnotherPartitionCannotUseTheApiEvenWithAnUnconditionalTrustPolicy() {
RequestScopes.runAs(ACCOUNT, REGION, () -> iam.updateAssumeRolePolicy(roleName, """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",
"Principal":{"Service":"events.amazonaws.com"}}]}"""));
AwsException error = assertThrows(AwsException.class, () -> RequestScopes.runAs(ACCOUNT, REGION,
() -> invoker.invokeTarget(target, "{}", REGION,
"arn:aws-cn:events:cn-north-1:" + ACCOUNT + ":rule/publish")));
assertEquals("AccessDeniedException", error.getErrorCode());
assertEquals(null, variables.get());
}
@Test
void anImplicitFieldPermissionDenialCannotExecuteTheMutation() {
RequestScopes.runAs(ACCOUNT, REGION,
() -> iam.putRolePolicy(roleName, "invoke", policy("Allow", api.getArn() + "/unrelated/*")));
assertRefused("AccessDeniedException");
}
@Test
void additionalIamAuthorizationRequiresIamDirectivesOnTheSelectedFields() {
RequestScopes.runAs(ACCOUNT, REGION, () -> appSync.updateGraphqlApi(api.getApiId(),
Map.of("name", api.getName(), "authenticationType", "API_KEY", "additionalAuthenticationProviders",
List.of(Map.of("authenticationType", "AWS_IAM"))), REGION));
assertRefused("AccessDeniedException");
PlannedDirective iamDirective = new PlannedDirective("aws_iam", Map.of());
lenient().when(sidecar.plan(any(), any(), any(), any())).thenReturn(new PlanResult("MUTATION", List.of(
new PlannedField("Mutation", "publish", List.of(iamDirective), List.of()),
new PlannedField("Result", "id", List.of(), List.of(iamDirective)))));
invoke("{\"id\":\"allowed\"}");
assertNotNull(variables.get());
assertEquals("allowed", variables.get().get("id"));
}
@Test
void aPrivateApiIsRejectedBeforePlanning() {
GraphqlApi privateApi = RequestScopes.callAs(ACCOUNT, REGION, () -> appSync.createGraphqlApi(
Map.of("name", "private-" + UUID.randomUUID(), "authenticationType", "AWS_IAM", "visibility", "PRIVATE"), REGION));
try {
target.setArn("arn:aws:appsync:" + REGION + ":" + ACCOUNT + ":endpoints/graphql-api/" + privateApi.getApiId());
assertRefused("AccessDeniedException");
verify(sidecar, never()).plan(any(), any(), any(), any());
} finally {
RequestScopes.runAs(ACCOUNT, REGION, () -> appSync.deleteGraphqlApi(privateApi.getApiId()));
}
}
@Test
void aRoleWithoutTheFieldPermissionCannotExecuteTheMutation() {
RequestScopes.runAs(ACCOUNT, REGION,
() -> iam.putRolePolicy(roleName, "invoke", policy("Deny", api.getArn() + "/*")));
assertRefused("AccessDeniedException");
}
@Test
void aTrustConditionOnAnotherRuleRefusesDelivery() {
AwsException failure = assertThrows(AwsException.class, () -> RequestScopes.runAs(ACCOUNT, REGION,
() -> invoker.invokeTarget(target, "{}", REGION, RULE + "-other")));
assertEquals(403, failure.getHttpStatus());
assertEquals(null, variables.get());
}
@Test
void aMissingRoleCannotExecuteTheMutation() {
target.setRoleArn(null);
assertRefused("AccessDeniedException");
}
@Test
void aMissingRoleCannotBypassEnforcementWithAnEmptyFieldPlan() {
target.setRoleArn(null);
lenient().when(sidecar.plan(any(), any(), any(), any())).thenReturn(new PlanResult("MUTATION", List.of()));
assertRefused("AccessDeniedException");
}
@Test
void anEndpointInAnotherRegionDoesNotResolveAnApiWithTheSameId() {
target.setArn(target.getArn().replace(REGION, "us-west-2"));
assertRefused("NotFoundException");
}
@Test
void queryOperationsCannotExecuteAsEventBridgeMutations() {
lenient().when(sidecar.plan(any(), any(), any(), any())).thenReturn(new PlanResult("QUERY", List.of()));
assertRefused("ValidationException");
}
@Test
void anApiWithoutIamAuthorizationCannotExecuteTheMutation() {
RequestScopes.runAs(ACCOUNT, REGION, () -> appSync.updateGraphqlApi(api.getApiId(),
Map.of("name", api.getName(), "authenticationType", "API_KEY"), REGION));
assertRefused("AccessDeniedException");
}
@Test
void requestValidationErrorsAreReportedAsFailedDelivery() {
doReturn(Map.of("errors", List.of(Map.of("message", "Variable id is required", "errorType", "ValidationError"))))
.when(sidecar).execute(any(), any(), any(), any(), any(), any(), any());
assertRefused("ValidationException");
}
@Test
void anInvalidExecutionEnvelopeIsNotAcknowledgedAsDelivery() {
doReturn(Map.of()).when(sidecar).execute(any(), any(), any(), any(), any(), any(), any());
assertRefused("InternalFailure");
}
@Test
void anExecutionErrorWithNullDataDoesNotRetryAPossiblyCompletedMutation() {
Map<String, Object> result = new LinkedHashMap<>();
result.put("data", null);
result.put("errors", List.of(Map.of("message", "output failed", "path", List.of("publish"))));
doAnswer(call -> {
variables.set(call.getArgument(3));
return result;
}).when(sidecar).execute(any(), any(), any(), any(), any(), any(), any());
invoke("{\"id\":\"event-1\"}");
assertNotNull(variables.get());
}
@Test
void nonObjectVariablesCannotExecuteTheMutation() {
target.setInput("[]");
assertRefused("ValidationException");
}
private void invoke(String event) {
RequestScopes.runAs(ACCOUNT, REGION, () -> invoker.invokeTarget(target, event, REGION, RULE));
}
private void assertRefused(String code) {
AwsException failure = assertThrows(AwsException.class, () -> invoke("{}"));
assertEquals(code, failure.getErrorCode());
assertEquals(null, variables.get());
}
}
@@ -0,0 +1,283 @@
package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient;
import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient.PlanResult;
import io.github.hectorvent.floci.services.appsync.graphql.AppSyncTransportException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CfnRollback;
import io.github.hectorvent.floci.services.cloudformation.provisioners.EventsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ProvisionContext;
import io.github.hectorvent.floci.testing.AwsTestClients;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
import software.amazon.awssdk.services.eventbridge.model.AppSyncParameters;
import software.amazon.awssdk.services.eventbridge.model.EventBridgeException;
import software.amazon.awssdk.services.eventbridge.model.RuleState;
import software.amazon.awssdk.services.eventbridge.model.Target;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@QuarkusTest
class EventBridgeAppSyncTargetSettingsIntegrationTest {
private static final String ACCOUNT = "725018800001";
private static final String ENDPOINT = "arn:aws:appsync:us-east-1:" + ACCOUNT + ":endpoints/graphql-api/example";
private static final String ROLE = "arn:aws:iam::" + ACCOUNT + ":role/events-appsync";
private static final String OPERATION = "mutation Publish($id: ID!) { publish(id: $id) { id } }";
@InjectMock
GraphqlSidecarClient sidecar;
@Inject
EventsCfnProvisioner provisioner;
private EventBridgeClient client;
private String rule;
@BeforeEach
void createRule() {
reset(sidecar);
when(sidecar.plan(any(), any(), any(), any())).thenReturn(new PlanResult("MUTATION", List.of()));
client = client(ACCOUNT);
rule = "appsync-settings-" + UUID.randomUUID();
client.putRule(request -> request.name(rule).eventPattern("{}").state(RuleState.DISABLED));
}
@AfterEach
void deleteRule() {
try {
client.removeTargets(request -> request.rule(rule).ids("appsync", "bad"));
client.deleteRule(request -> request.name(rule));
} finally {
client.close();
}
}
@Test
void theModelMaximumGraphqlOperationLengthIsAccepted() {
String operation = OPERATION + "#" + "x".repeat(1048576 - OPERATION.length() - 1);
putTarget(operation);
assertEquals(operation, listedTarget().appSyncParameters().graphQLOperation());
}
@ParameterizedTest
@ValueSource(ints = {0, 1048577})
void invalidOperationLengthsRejectTheRequestWithoutEchoingSensitiveContent(int length) {
putTarget(OPERATION);
String value = length == 0 ? "" : "SENSITIVE-MUTATION-" + "x".repeat(length - "SENSITIVE-MUTATION-".length());
EventBridgeException error = assertThrows(EventBridgeException.class, () -> client.putTargets(request -> request.rule(rule)
.targets(Target.builder().id("appsync").arn(ENDPOINT).roleArn(ROLE)
.appSyncParameters(p -> p.graphQLOperation("mutation { replacement }")).build(),
Target.builder().id("bad").arn(ENDPOINT).roleArn(ROLE)
.appSyncParameters(p -> p.graphQLOperation(value)).build())));
assertEquals("ValidationException", error.awsErrorDetails().errorCode());
assertTrue(error.getMessage().contains("targets.2.member.appSyncParameters.graphQLOperation"));
assertFalse(error.getMessage().contains("SENSITIVE-MUTATION-"));
assertEquals(OPERATION, listedTarget().appSyncParameters().graphQLOperation());
assertEquals(1, client.listTargetsByRule(request -> request.rule(rule)).targets().size());
}
@Test
void sdkRoundTripsTheGraphqlOperationAndTargetRole() {
putTarget(OPERATION);
Target target = listedTarget();
assertNotNull(target.appSyncParameters());
assertEquals(OPERATION, target.appSyncParameters().graphQLOperation());
assertEquals(ROLE, target.roleArn());
assertEquals(ENDPOINT, target.arn());
}
@Test
void replacementUpdatesOrRemovesAppSyncParameters() {
putTarget(OPERATION);
String replacement = "mutation { publish(id: \"replacement\") { id } }";
putTarget(replacement);
assertNotNull(listedTarget().appSyncParameters());
assertEquals(replacement, listedTarget().appSyncParameters().graphQLOperation());
client.putTargets(request -> request.rule(rule).targets(Target.builder().id("appsync")
.arn("arn:aws:sqs:us-east-1:" + ACCOUNT + ":queue").roleArn(ROLE).build()));
assertNull(listedTarget().appSyncParameters());
}
@ParameterizedTest
@ValueSource(strings = {"missing", "empty", "malformed", "query", "two mutations"})
void invalidAppSyncSettingsCannotReplaceStoredTargets(String scenario) {
putTarget(OPERATION);
Target original = listedTarget();
Target.Builder invalid = original.toBuilder().appSyncParameters((AppSyncParameters) null);
if ("empty".equals(scenario)) {
invalid.appSyncParameters(AppSyncParameters.builder().build());
} else if (!"missing".equals(scenario)) {
String operation = switch (scenario) {
case "malformed" -> "mutation SENSITIVE {";
case "query" -> "query SENSITIVE { publish { id } }";
default -> "mutation SENSITIVE { first } mutation Other { second }";
};
invalid.appSyncParameters(p -> p.graphQLOperation(operation));
if ("two mutations".equals(scenario)) {
when(sidecar.plan(any(), any(), eq(operation), isNull())).thenThrow(
new AppSyncTransportException(400, "BadRequestException", "SENSITIVE ambiguous operation"));
} else {
when(sidecar.plan(any(), any(), eq(operation), isNull())).thenReturn(
new PlanResult("query".equals(scenario) ? "QUERY" : null, List.of()));
}
}
EventBridgeException error = assertThrows(EventBridgeException.class,
() -> client.putTargets(request -> request.rule(rule).targets(
original.toBuilder().id("bad").build(), invalid.build())));
assertEquals("ValidationException", error.awsErrorDetails().errorCode());
assertEquals(400, error.statusCode());
assertFalse(error.getMessage().contains("SENSITIVE"));
assertEquals(List.of(original), client.listTargetsByRule(request -> request.rule(rule)).targets());
}
@Test
void parserOutageDoesNotOverwriteTargetsOrBecomeAValidationError() {
putTarget(OPERATION);
Target original = listedTarget();
when(sidecar.plan(any(), any(), any(), any())).thenThrow(
new AppSyncTransportException(500, "InternalFailureException", "SENSITIVE transport failure"));
EventBridgeException error = assertThrows(EventBridgeException.class, () -> putTarget("mutation { replacement }"));
assertEquals("InternalFailure", error.awsErrorDetails().errorCode());
assertEquals(500, error.statusCode());
assertFalse(error.getMessage().contains("SENSITIVE"));
assertEquals(List.of(original), client.listTargetsByRule(request -> request.rule(rule)).targets());
}
@Test
void cloudFormationRollbackRestoresAcceptedTargetsWhileTheParserIsUnavailable() {
putTarget(OPERATION);
Target original = listedTarget();
StackResource resource = ruleResource();
ObjectNode props = new ObjectMapper().createObjectNode().put("Name", rule).put("State", "DISABLED");
props.putObject("EventPattern");
props.putArray("Targets");
RequestScopes.runAs(ACCOUNT, "us-east-1", () -> provisioner.provision(resource, props, updateContext()));
assertTrue(client.listTargetsByRule(request -> request.rule(rule)).targets().isEmpty());
when(sidecar.plan(any(), any(), any(), any())).thenThrow(
new AppSyncTransportException(500, "InternalFailureException", "Parser unavailable"));
clearInvocations(sidecar);
RequestScopes.runAs(ACCOUNT, "us-east-1", () -> assertTrue(provisioner.rollbackUpdate(resource)));
assertEquals(List.of(original), client.listTargetsByRule(request -> request.rule(rule)).targets());
assertNull(resource.getAttributes().get(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR));
verifyNoInteractions(sidecar);
}
@Test
void failedCloudFormationUpdateRestoresItsSnapshotWithoutRetryingTheParser() {
putTarget(OPERATION);
Target original = listedTarget();
StackResource resource = ruleResource();
ObjectNode props = new ObjectMapper().createObjectNode().put("Name", rule).put("State", "DISABLED");
props.putObject("EventPattern");
props.putArray("Targets").addObject().put("Id", "appsync").put("Arn", ENDPOINT).put("RoleArn", ROLE)
.putObject("AppSyncParameters").put("GraphQLOperation", "mutation { replacement }");
when(sidecar.plan(any(), any(), any(), any())).thenThrow(
new AppSyncTransportException(500, "InternalFailureException", "Parser unavailable"));
clearInvocations(sidecar);
RequestScopes.runAs(ACCOUNT, "us-east-1", () -> assertThrows(AwsException.class,
() -> provisioner.provision(resource, props, updateContext())));
assertEquals(List.of(original), client.listTargetsByRule(request -> request.rule(rule)).targets());
assertNull(resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
assertNull(resource.getAttributes().get(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR));
verify(sidecar, times(1)).plan(any(), any(), any(), any());
}
private StackResource ruleResource() {
StackResource resource = new StackResource();
resource.setResourceType("AWS::Events::Rule");
resource.setLogicalId("Rule");
resource.setPhysicalId(rule);
resource.setAttributes(new HashMap<>());
return resource;
}
private ProvisionContext updateContext() {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(call -> {
JsonNode node = call.getArgument(0);
return node == null ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(call -> call.getArgument(0));
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(call -> call.getArgument(0));
when(engine.omitNoValue(any())).thenAnswer(call -> call.getArgument(0));
return new ProvisionContext(engine, "us-east-1", ACCOUNT, "rollback-stack", rule);
}
@Test
void identicalRuleNamesInAnotherAccountCannotReplaceTheOperation() {
putTarget(OPERATION);
try (EventBridgeClient other = client("725018800002")) {
other.putRule(request -> request.name(rule).eventPattern("{}").state(RuleState.DISABLED));
try {
other.putTargets(request -> request.rule(rule).targets(Target.builder().id("appsync")
.arn(ENDPOINT).appSyncParameters(p -> p.graphQLOperation("mutation { other }")).build()));
assertNotNull(listedTarget().appSyncParameters());
assertEquals(OPERATION, listedTarget().appSyncParameters().graphQLOperation());
assertEquals("mutation { other }", other.listTargetsByRule(request -> request.rule(rule))
.targets().getFirst().appSyncParameters().graphQLOperation());
} finally {
other.removeTargets(request -> request.rule(rule).ids("appsync"));
other.deleteRule(request -> request.name(rule));
}
}
}
@Test
void storedTargetSerializationRetainsTheExactOperation() throws Exception {
ObjectMapper mapper = new ObjectMapper();
String stored = "{\"id\":\"appsync\",\"arn\":\"" + ENDPOINT
+ "\",\"appSyncParameters\":{\"GraphQLOperation\":\"mutation { publish { id } }\"}}";
// The persisted model and the SDK wire model both have the name Target.
io.github.hectorvent.floci.services.eventbridge.model.Target target = mapper.readValue(stored,
io.github.hectorvent.floci.services.eventbridge.model.Target.class);
JsonNode restored = mapper.readTree(mapper.writeValueAsBytes(target));
assertEquals("mutation { publish { id } }", restored.path("appSyncParameters").path("GraphQLOperation").asText());
}
private void putTarget(String operation) {
assertEquals(0, client.putTargets(request -> request.rule(rule).targets(Target.builder().id("appsync")
.arn(ENDPOINT).roleArn(ROLE).appSyncParameters(p -> p.graphQLOperation(operation)).build())).failedEntryCount());
}
private Target listedTarget() {
return client.listTargetsByRule(request -> request.rule(rule)).targets().getFirst();
}
private static EventBridgeClient client(String account) {
return AwsTestClients.create(EventBridgeClient.builder(), account, Region.US_EAST_1);
}
}
@@ -25,6 +25,7 @@ import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
class EventBridgeSchedulerIntegrationTest {
@@ -53,7 +54,7 @@ class EventBridgeSchedulerIntegrationTest {
new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver(REGION, ACCOUNT),
new ObjectMapper(), scheduler, dispatcher, replayDispatcher,
new ResourceGroupsTaggingService(null));
new ResourceGroupsTaggingService(null), mock(AppSyncTargetValidator.class));
}
@AfterEach
@@ -77,7 +77,8 @@ class EventBridgeServiceTest {
null,
dispatcherMock,
replayDispatcherMock,
new ResourceGroupsTaggingService(null)
new ResourceGroupsTaggingService(null),
mock(AppSyncTargetValidator.class)
);
}
@@ -1,5 +1,4 @@
AWS::AppConfig::ConfigurationProfile KmsKeyArn Floci's AppConfig keeps no KMS key on a profile, so KmsKeyIdentifier is accepted and not stored
AWS::AppSync::GraphQLApi GraphQLEndpointArn the private-endpoint ARN of the GraphQL endpoint; Floci serves one public endpoint and has no private-endpoint model
AWS::BedrockAgentCore::Runtime WorkloadIdentityDetails the dotted WorkloadIdentityDetails.WorkloadIdentityArn is set instead, the form AWS's GetAtt exposes for the nested object
AWS::CodePipeline::CustomActionType Id schema gives no description; the custom action has no separate id in Floci
AWS::CodePipeline::Webhook Id schema gives no description; Floci keys webhooks by name
Can't render this file because it contains an unexpected character in line 6 and column 144.