mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(eventbridge): deliver AppSync mutation targets (#7488)
This commit is contained in:
1 parent
50aef92124
commit
ca854a4194
25 files changed
+1406
-39
No files matched your search
+2
@@ -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",
|
||||
|
||||
+31
-7
@@ -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();
|
||||
|
||||
+3
-1
@@ -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);
|
||||
|
||||
+69
@@ -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();
|
||||
}
|
||||
}
|
||||
+98
@@ -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());
|
||||
}
|
||||
}
|
||||
+255
@@ -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"]}}}]}}}}
|
||||
""";
|
||||
}
|
||||
+261
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
+283
@@ -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);
|
||||
}
|
||||
}
|
||||
+2
-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
|
||||
|
||||
+2
-1
@@ -77,7 +77,8 @@ class EventBridgeServiceTest {
|
||||
null,
|
||||
dispatcherMock,
|
||||
replayDispatcherMock,
|
||||
new ResourceGroupsTaggingService(null)
|
||||
new ResourceGroupsTaggingService(null),
|
||||
mock(AppSyncTargetValidator.class)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user