feat(pipes): deliver to a Redshift cluster or Serverless workgroup through the Data API (#7165)

This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-01 11:27:14 -04:00
1 parent 5556bbae58
commit 24b152a274
12 files changed
+798 -98

No files matched your search

@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.eventbridge.model.Target;
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftTargetAuthorizer;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import org.junit.jupiter.api.BeforeEach;
@@ -41,14 +42,14 @@ class EventBridgeRedshiftTargetAuthorizationTest {
private static final String EVENT = "{\"id\":\"event-1\"}";
private RedshiftDataService redshiftDataService;
private EventBridgeRedshiftTargetAuthorizer authorizer;
private RedshiftTargetAuthorizer authorizer;
private EventBridgeInvoker invoker;
@BeforeEach
void setUp() {
redshiftDataService = mock(RedshiftDataService.class);
authorizer = mock(EventBridgeRedshiftTargetAuthorizer.class);
when(authorizer.refusal(any(), any(), any(), anyList())).thenReturn(Optional.empty());
authorizer = mock(RedshiftTargetAuthorizer.class);
when(authorizer.refusal(any(), any(), any(), any(), anyList())).thenReturn(Optional.empty());
ServiceRegistry serviceRegistry = mock(ServiceRegistry.class);
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(true);
RegionResolver resolver = mock(RegionResolver.class);
@@ -196,7 +197,7 @@ class EventBridgeRedshiftTargetAuthorizationTest {
@Test
void refusedRoleIsAccessDeniedAndNothingIsSubmitted() {
when(authorizer.refusal(any(), any(), any(), anyList())).thenReturn(Optional.of("not authorized"));
when(authorizer.refusal(any(), any(), any(), any(), anyList())).thenReturn(Optional.of("not authorized"));
RedshiftDataParameters parameters = parameters("dev");
parameters.setSql("select 1");
@@ -211,7 +212,7 @@ class EventBridgeRedshiftTargetAuthorizationTest {
@Test
void refusedRoleIsReportedBeforeABadPathInTheSql() {
when(authorizer.refusal(any(), any(), any(), anyList())).thenReturn(Optional.of("not authorized"));
when(authorizer.refusal(any(), any(), any(), any(), anyList())).thenReturn(Optional.of("not authorized"));
RedshiftDataParameters parameters = parameters("dev");
parameters.setSql("$.detail.missing");
@@ -242,7 +243,7 @@ class EventBridgeRedshiftTargetAuthorizationTest {
invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1", ruleArn);
verify(authorizer).refusal(eq(ROLE_ARN), eq(ACCOUNT), eq(ruleArn), anyList());
verify(authorizer).refusal(eq("events.amazonaws.com"), eq(ROLE_ARN), eq(ACCOUNT), eq(ruleArn), anyList());
}
@Test
@@ -252,13 +253,13 @@ class EventBridgeRedshiftTargetAuthorizationTest {
invoker.invokeTarget(target(CLUSTER_ARN, parameters), EVENT, "us-east-1");
verify(authorizer).refusal(eq(ROLE_ARN), eq(ACCOUNT), isNull(), anyList());
verify(authorizer).refusal(eq("events.amazonaws.com"), eq(ROLE_ARN), eq(ACCOUNT), isNull(), anyList());
}
private List<Permission> permissions() {
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Permission>> captor = ArgumentCaptor.forClass(List.class);
verify(authorizer).refusal(eq(ROLE_ARN), eq(ACCOUNT), any(), captor.capture());
verify(authorizer).refusal(eq("events.amazonaws.com"), eq(ROLE_ARN), eq(ACCOUNT), any(), captor.capture());
return captor.getValue();
}
@@ -0,0 +1,83 @@
package io.github.hectorvent.floci.services.pipes;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* A pipe from SQS to a Redshift cluster hands each message to the Data API as a BatchExecuteStatement
* of its {@code Sqls}, with the paths in them read from the message, and the message is consumed.
* The Data API itself is mocked here; {@code RedshiftDataApiIntegrationTest} covers it against a cluster.
*/
@QuarkusTest
class PipesRedshiftTargetIntegrationTest {
private static final String SQS_CONTENT_TYPE = "application/x-www-form-urlencoded";
private static final String QUEUE_URL = "http://localhost:4566/000000000000/pipe-redshift-source";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/pipe-role";
@InjectMock
RedshiftDataService redshiftDataService;
@Test
void sqsMessageReachesTheDataApiAsABatch() {
when(redshiftDataService.batchExecuteStatement(any(), any(), any()))
.thenReturn(JsonNodeFactory.instance.objectNode());
given().contentType(SQS_CONTENT_TYPE).formParam("Action", "CreateQueue")
.formParam("QueueName", "pipe-redshift-source").when().post("/").then().statusCode(200);
given().contentType("application/json").body("""
{
"Source": "arn:aws:sqs:us-east-1:000000000000:pipe-redshift-source",
"Target": "arn:aws:redshift:us-east-1:000000000000:cluster:warehouse",
"RoleArn": "%s",
"TargetParameters": {"RedshiftDataParameters": {
"Database": "dev", "DbUser": "admin", "StatementName": "load",
"Sqls": ["$.body.insert", "COMMIT"]}}
}
""".formatted(ROLE_ARN))
.when().post("/v1/pipes/sqs-to-redshift-pipe")
.then().statusCode(200).body("CurrentState", equalTo("RUNNING"));
given().contentType(SQS_CONTENT_TYPE).formParam("Action", "SendMessage").formParam("QueueUrl", QUEUE_URL)
.formParam("MessageBody", "{\"insert\":\"INSERT INTO events VALUES (1)\"}")
.when().post("/").then().statusCode(200);
ArgumentCaptor<JsonNode> request = ArgumentCaptor.captor();
verify(redshiftDataService, timeout(10_000)).batchExecuteStatement(request.capture(), eq("us-east-1"),
eq(ROLE_ARN));
assertEquals("warehouse", request.getValue().path("ClusterIdentifier").asText());
assertEquals("dev", request.getValue().path("Database").asText());
assertEquals("load", request.getValue().path("StatementName").asText());
assertEquals("INSERT INTO events VALUES (1)", request.getValue().path("Sqls").path(0).asText());
assertEquals("COMMIT", request.getValue().path("Sqls").path(1).asText());
given().when().delete("/v1/pipes/sqs-to-redshift-pipe").then().statusCode(200);
}
@Test
void aPipeWithoutSqlsIsRejectedWhenItIsCreated() {
given().contentType("application/json").body("""
{
"Source": "arn:aws:sqs:us-east-1:000000000000:pipe-redshift-source",
"Target": "arn:aws:redshift:us-east-1:000000000000:cluster:warehouse",
"RoleArn": "%s",
"TargetParameters": {"RedshiftDataParameters": {"Database": "dev"}}
}
""".formatted(ROLE_ARN))
.when().post("/v1/pipes/no-sqls-redshift-pipe")
.then().statusCode(400);
}
}
@@ -0,0 +1,141 @@
package io.github.hectorvent.floci.services.pipes;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.pipes.model.DesiredState;
import io.github.hectorvent.floci.services.pipes.model.Pipe;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService;
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.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.Mockito.clearInvocations;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* With IAM enforcement on, a pipe's Redshift target runs only when the pipe's role trusts
* pipes.amazonaws.com and may call the Data API and authenticate to the cluster.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class PipesRedshiftTargetRoleEnforcementIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String CLUSTER_ARN = "arn:aws:redshift:us-east-1:" + ACCOUNT + ":cluster:warehouse";
private static final String PIPES_TRUST = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"pipes.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
private static final String EVENTS_TRUST = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
private static final String DATA_API_AND_CREDENTIALS = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"redshift-data:BatchExecuteStatement","Resource":"%s"},
{"Effect":"Allow","Action":"redshift:GetClusterCredentials","Resource":"*"}]}""".formatted(CLUSTER_ARN);
@Inject
PipesTargetInvoker invoker;
@Inject
IamService iamService;
@InjectMock
RedshiftDataService redshiftDataService;
@BeforeEach
void setUp() {
clearInvocations(redshiftDataService);
when(redshiftDataService.batchExecuteStatement(any(), any(), any()))
.thenReturn(JsonNodeFactory.instance.objectNode());
}
@Test
void roleThatTrustsPipesAndHoldsThePermissionsRunsTheBatch() throws Exception {
String roleArn = role("pipes-redshift-allowed", PIPES_TRUST, DATA_API_AND_CREDENTIALS);
invoker.invoke(pipe("allowed", roleArn), "{\"messageId\":\"m1\"}", "us-east-1");
verify(redshiftDataService).batchExecuteStatement(any(JsonNode.class), eq("us-east-1"), eq(roleArn));
}
@Test
void roleThatDoesNotTrustPipesIsRefused() throws Exception {
String roleArn = role("pipes-redshift-untrusted", EVENTS_TRUST, DATA_API_AND_CREDENTIALS);
AwsException failure = assertThrows(AwsException.class,
() -> invoker.invoke(pipe("untrusted", roleArn), "{\"messageId\":\"m1\"}", "us-east-1"));
assertEquals("AccessDeniedException", failure.getErrorCode());
assertTrue(failure.getMessage().contains("does not trust pipes.amazonaws.com"), failure.getMessage());
verify(redshiftDataService, never()).batchExecuteStatement(any(), any(), any());
}
@Test
void roleWithoutTheBatchPermissionIsRefused() throws Exception {
String roleArn = role("pipes-redshift-no-batch", PIPES_TRUST, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"redshift-data:ExecuteStatement","Resource":"*"},
{"Effect":"Allow","Action":"redshift:GetClusterCredentials","Resource":"*"}]}""");
AwsException failure = assertThrows(AwsException.class,
() -> invoker.invoke(pipe("no-batch", roleArn), "{\"messageId\":\"m1\"}", "us-east-1"));
assertEquals(403, failure.getHttpStatus());
assertTrue(failure.getMessage().contains("redshift-data:BatchExecuteStatement"), failure.getMessage());
verify(redshiftDataService, never()).batchExecuteStatement(any(), any(), any());
}
@Test
void trustConditionOnThePipeArnIsMatched() throws Exception {
Pipe matching = pipe("source-arn", null);
String roleArn = role("pipes-redshift-source-arn", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"pipes.amazonaws.com"},"Action":"sts:AssumeRole",
"Condition":{"ArnEquals":{"aws:SourceArn":"%s"}}}]}""".formatted(matching.getArn()),
DATA_API_AND_CREDENTIALS);
matching.setRoleArn(roleArn);
invoker.invoke(matching, "{\"messageId\":\"m1\"}", "us-east-1");
verify(redshiftDataService).batchExecuteStatement(any(JsonNode.class), eq("us-east-1"), eq(roleArn));
clearInvocations(redshiftDataService);
Pipe other = pipe("other-pipe", roleArn);
assertThrows(AwsException.class, () -> invoker.invoke(other, "{\"messageId\":\"m2\"}", "us-east-1"));
verify(redshiftDataService, never()).batchExecuteStatement(any(), any(), any());
}
private String role(String name, String trust, String policy) {
String arn = iamService.createRole(name, "/", trust, null, 3600, Map.of()).getArn();
iamService.putRolePolicy(name, "redshift", policy);
return arn;
}
private static Pipe pipe(String name, String roleArn) throws Exception {
Pipe pipe = new Pipe();
pipe.setName(name);
pipe.setArn("arn:aws:pipes:us-east-1:" + ACCOUNT + ":pipe/" + name);
pipe.setAccountId(ACCOUNT);
pipe.setSource("arn:aws:sqs:us-east-1:" + ACCOUNT + ":source");
pipe.setTarget(CLUSTER_ARN);
pipe.setRoleArn(roleArn);
pipe.setDesiredState(DesiredState.RUNNING);
pipe.setTargetParameters(new ObjectMapper().readTree("""
{"RedshiftDataParameters":{"Database":"dev","DbUser":"admin","Sqls":["select 1"]}}"""));
return pipe;
}
}
@@ -267,6 +267,84 @@ class PipesServiceTest {
pipesService.describePipe("legacy-pipe", "us-east-1").getSourceParameters());
}
private static final String REDSHIFT_CLUSTER = "arn:aws:redshift:us-east-1:000000000000:cluster:analytics";
private Pipe createRedshiftPipe(String name, JsonNode targetParameters) {
return pipesService.createPipe(name, "arn:aws:sqs:us-east-1:000000000000:source", REDSHIFT_CLUSTER,
"arn:aws:iam::000000000000:role/role", null, null, null, null, targetParameters, null, null,
"us-east-1");
}
@Test
void createPipeWithARedshiftTargetKeepsItsSqls() {
JsonNode parameters = sourceParameters(
"{\"RedshiftDataParameters\":{\"Database\":\"dev\",\"Sqls\":[\"SELECT 1\"]}}");
Pipe pipe = createRedshiftPipe("redshift-pipe", parameters);
assertEquals(parameters, pipesService.describePipe("redshift-pipe", "us-east-1").getTargetParameters());
assertEquals(REDSHIFT_CLUSTER, pipe.getTarget());
}
@Test
void createPipeWithARedshiftTargetRequiresBetweenOneAndFortySqls() {
for (String parameters : List.of(
"null",
"{}",
"{\"RedshiftDataParameters\":{\"Database\":\"dev\"}}",
"{\"RedshiftDataParameters\":{\"Database\":\"dev\",\"Sqls\":[]}}",
"{\"RedshiftDataParameters\":{\"Database\":\"dev\",\"Sqls\":["
+ "\"SELECT 1\",".repeat(40) + "\"SELECT 1\"]}}",
"{\"RedshiftDataParameters\":{\"Database\":\"dev\",\"Sqls\":[1]}}")) {
AwsException error = assertThrows(AwsException.class,
() -> createRedshiftPipe("bad-redshift-pipe", sourceParameters(parameters)),
parameters);
assertEquals("ValidationException", error.getErrorCode());
}
assertThrows(AwsException.class, () -> pipesService.describePipe("bad-redshift-pipe", "us-east-1"));
}
@Test
void createPipeWithARedshiftTargetRequiresADatabase() {
for (String parameters : List.of(
"{\"RedshiftDataParameters\":{\"Sqls\":[\"SELECT 1\"]}}",
"{\"RedshiftDataParameters\":{\"Database\":\"\",\"Sqls\":[\"SELECT 1\"]}}",
"{\"RedshiftDataParameters\":{\"Database\":1,\"Sqls\":[\"SELECT 1\"]}}")) {
AwsException error = assertThrows(AwsException.class,
() -> createRedshiftPipe("no-database-pipe", sourceParameters(parameters)),
parameters);
assertEquals("ValidationException", error.getErrorCode());
assertTrue(error.getMessage().contains("Database"), parameters);
}
}
@Test
void createPipeRefusesARedshiftSqlOverTheLengthLimit() {
JsonNode parameters = sourceParameters("{\"RedshiftDataParameters\":{\"Database\":\"dev\",\"Sqls\":[\""
+ "x".repeat(100_001) + "\"]}}");
AwsException error = assertThrows(AwsException.class, () -> createRedshiftPipe("long-sql-pipe", parameters));
assertEquals("ValidationException", error.getErrorCode());
}
@Test
void updatePipeValidatesTheRedshiftTargetItWillHave() {
createRedshiftPipe("update-redshift-pipe", sourceParameters(
"{\"RedshiftDataParameters\":{\"Database\":\"dev\",\"Sqls\":[\"SELECT 1\"]}}"));
AwsException error = assertThrows(AwsException.class, () -> pipesService.updatePipe("update-redshift-pipe",
null, null, null, null, null, null,
sourceParameters("{\"RedshiftDataParameters\":{\"Database\":\"dev\",\"Sqls\":[]}}"),
null, "us-east-1"));
assertEquals("ValidationException", error.getErrorCode());
// Leaving the target parameters out keeps the valid ones.
pipesService.updatePipe("update-redshift-pipe", null, null, "now described", null, null, null, null, null,
"us-east-1");
assertEquals("now described", pipesService.describePipe("update-redshift-pipe", "us-east-1").getDescription());
}
@Test
void deletePipe() {
pipesService.createPipe("del-pipe",
@@ -4,12 +4,16 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.ServiceRegistry;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.pipes.model.DesiredState;
import io.github.hectorvent.floci.services.pipes.model.Pipe;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataTargetSubmitter;
import io.github.hectorvent.floci.services.redshiftdata.RedshiftTargetAuthorizer;
import io.github.hectorvent.floci.services.sns.SnsService;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.services.stepfunctions.StepFunctionsService;
@@ -22,9 +26,11 @@ import org.mockito.junit.jupiter.MockitoExtension;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.UnaryOperator;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
@@ -40,6 +46,9 @@ class PipesTargetInvokerTest {
@Mock private SnsService snsService;
@Mock private EventBridgeService eventBridgeService;
@Mock private StepFunctionsService stepFunctionsService;
@Mock private RedshiftDataTargetSubmitter redshiftSubmitter;
@Mock private RedshiftTargetAuthorizer redshiftAuthorizer;
@Mock private ServiceRegistry serviceRegistry;
@Mock private EmulatorConfig config;
private PipesTargetInvoker invoker;
@@ -48,7 +57,164 @@ class PipesTargetInvokerTest {
void setUp() {
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
invoker = new PipesTargetInvoker(lambdaService, sqsService, snsService,
eventBridgeService, stepFunctionsService, MAPPER, config);
eventBridgeService, stepFunctionsService, redshiftSubmitter, redshiftAuthorizer, serviceRegistry,
MAPPER, config);
}
private static final String CLUSTER = "arn:aws:redshift:us-east-1:000000000000:cluster:analytics";
private static final String PIPE_ROLE = "arn:aws:iam::000000000000:role/PipeRole";
private Pipe redshiftPipe(String targetParametersJson) throws Exception {
Pipe pipe = createPipe(CLUSTER, (ObjectNode) MAPPER.readTree(targetParametersJson));
pipe.setRoleArn(PIPE_ROLE);
pipe.setAccountId("000000000000");
return pipe;
}
@Test
void redshiftTarget_submitsTheSqlsUnderThePipeRoleAndReadsPathsFromTheSourceEvent() throws Exception {
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(true);
Pipe pipe = redshiftPipe("""
{"InputTemplate":"{\\"ignored\\": <$.messageId>}",
"RedshiftDataParameters":{"Database":"dev","DbUser":"admin","StatementName":"load",
"Sqls":["$.body.first","INSERT INTO t VALUES (2)"],"WithEvent":true}}""");
String event = "{\"messageId\":\"m1\",\"body\":\"{\\\"first\\\":\\\"INSERT INTO t VALUES (1)\\\"}\"}";
invoker.invoke(pipe, event, "us-east-1");
ArgumentCaptor<RedshiftDataTargetSubmitter.Statement> statement = ArgumentCaptor.captor();
ArgumentCaptor<UnaryOperator<String>> resolver = ArgumentCaptor.captor();
ArgumentCaptor<RedshiftDataTargetSubmitter.RoleCheck> roleCheck = ArgumentCaptor.captor();
verify(redshiftSubmitter).submit(eq(CLUSTER), statement.capture(), eq(PIPE_ROLE), eq("000000000000"),
eq("us-east-1"), resolver.capture(), roleCheck.capture());
assertEquals("dev", statement.getValue().database());
assertEquals("admin", statement.getValue().dbUser());
assertEquals("load", statement.getValue().statementName());
assertEquals(List.of("$.body.first", "INSERT INTO t VALUES (2)"), statement.getValue().sqls());
assertNull(statement.getValue().sql());
assertEquals(Boolean.TRUE, statement.getValue().withEvent());
// The path reads the event as it arrived, not what InputTemplate made of it.
assertEquals("INSERT INTO t VALUES (1)", resolver.getValue().apply("$.body.first"));
assertEquals("INSERT INTO t VALUES (2)", resolver.getValue().apply("INSERT INTO t VALUES (2)"));
roleCheck.getValue().refusal(List.of());
verify(redshiftAuthorizer).refusal("pipes.amazonaws.com", PIPE_ROLE, "000000000000", pipe.getArn(), List.of());
verifyNoInteractions(lambdaService, sqsService, snsService, eventBridgeService, stepFunctionsService);
}
@Test
void redshiftTarget_readsPathsFromAnArrayEnrichmentResponse() throws Exception {
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(true);
Pipe pipe = redshiftPipe("{\"RedshiftDataParameters\":{\"Database\":\"dev\",\"Sqls\":[\"$[0].statement\"]}}");
invoker.invoke(pipe, "[{\"statement\":\"INSERT INTO t VALUES (1)\"}]", "us-east-1");
ArgumentCaptor<UnaryOperator<String>> resolver = ArgumentCaptor.captor();
verify(redshiftSubmitter).submit(any(), any(), any(), any(), any(), resolver.capture(), any());
assertEquals("INSERT INTO t VALUES (1)", resolver.getValue().apply("$[0].statement"));
}
@Test
void redshiftTarget_readsPathsFromAKafkaValueDeliveredAsBase64() throws Exception {
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(true);
Pipe pipe = redshiftPipe("{\"RedshiftDataParameters\":{\"Database\":\"dev\","
+ "\"Sqls\":[\"$.value.statement\",\"$.key\"]}}");
String value = Base64.getEncoder().encodeToString(
"{\"statement\":\"INSERT INTO t VALUES (1)\"}".getBytes(StandardCharsets.UTF_8));
String key = Base64.getEncoder().encodeToString(
"order-1".getBytes(StandardCharsets.UTF_8));
String event = "{\"eventSource\":\"SelfManagedKafka\",\"topic\":\"orders\",\"key\":\"" + key
+ "\",\"value\":\"" + value + "\"}";
invoker.invoke(pipe, event, "us-east-1");
ArgumentCaptor<UnaryOperator<String>> resolver = ArgumentCaptor.captor();
verify(redshiftSubmitter).submit(any(), any(), any(), any(), any(), resolver.capture(), any());
assertEquals("INSERT INTO t VALUES (1)", resolver.getValue().apply("$.value.statement"));
assertEquals("order-1", resolver.getValue().apply("$.key"));
}
@Test
void redshiftTarget_readsPathsFromAKinesisDataDeliveredAsBase64() throws Exception {
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(true);
Pipe pipe = redshiftPipe("{\"RedshiftDataParameters\":{\"Database\":\"dev\","
+ "\"Sqls\":[\"$[0].kinesis.data.statement\",\"$[0].kinesis.data\"]}}");
String data = Base64.getEncoder().encodeToString(
"{\"statement\":\"INSERT INTO t VALUES (1)\"}".getBytes(StandardCharsets.UTF_8));
String event = "[{\"eventSource\":\"aws:kinesis\",\"kinesis\":{\"partitionKey\":\"p\",\"data\":\""
+ data + "\"}}]";
invoker.invoke(pipe, event, "us-east-1");
ArgumentCaptor<UnaryOperator<String>> resolver = ArgumentCaptor.captor();
verify(redshiftSubmitter).submit(any(), any(), any(), any(), any(), resolver.capture(), any());
assertEquals("INSERT INTO t VALUES (1)", resolver.getValue().apply("$[0].kinesis.data.statement"));
assertEquals("{\"statement\":\"INSERT INTO t VALUES (1)\"}", resolver.getValue().apply("$[0].kinesis.data"));
}
@Test
void extractJsonPath_decodesBase64OnlyInKafkaAndKinesisSourceRecords() {
String encoded = Base64.getEncoder().encodeToString("hello".getBytes(StandardCharsets.UTF_8));
String kafka = "{\"eventSource\":\"aws:kafka\",\"key\":\"" + encoded + "\",\"value\":\"" + encoded + "\"}";
String kinesis = "{\"eventSource\":\"aws:kinesis\",\"kinesis\":{\"data\":\"" + encoded + "\"}}";
assertEquals("\"hello\"", invoker.extractJsonPath("$.key", kafka));
assertEquals("\"hello\"", invoker.extractJsonPath("$.value", kafka));
assertEquals("\"hello\"", invoker.extractJsonPath("$.kinesis.data", kinesis));
}
@Test
void extractJsonPath_leavesFieldsOfAnEnrichmentResponseOrAnSqsBodyUnchanged() {
String encoded = Base64.getEncoder().encodeToString("hello".getBytes(StandardCharsets.UTF_8));
String enriched = "{\"data\":\"" + encoded + "\",\"key\":\"" + encoded + "\",\"value\":\"" + encoded
+ "\",\"body\":\"" + encoded + "\",\"kinesis\":{\"data\":\"" + encoded + "\"}}";
for (String path : List.of("$.data", "$.key", "$.value", "$.body", "$.kinesis.data")) {
assertEquals("\"" + encoded + "\"", invoker.extractJsonPath(path, enriched), path);
}
assertEquals("\"" + encoded + "\"", invoker.extractJsonPath("$.key", "{\"key\":\"" + encoded + "\"}"));
}
@Test
void inputTemplate_readsAFieldOfBase64KinesisData() {
String data = Base64.getEncoder().encodeToString("{\"id\":7}".getBytes(StandardCharsets.UTF_8));
String event = "{\"eventSource\":\"aws:kinesis\",\"kinesis\":{\"data\":\"" + data + "\"}}";
assertEquals("{\"id\": 7}", invoker.applyInputTemplate("{\"id\": <$.kinesis.data.id>}", event));
}
@Test
void redshiftTarget_aPathThatResolvesToNothingIsAValidationError() throws Exception {
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(true);
Pipe pipe = redshiftPipe("{\"RedshiftDataParameters\":{\"Database\":\"dev\",\"Sqls\":[\"$.body.missing\"]}}");
invoker.invoke(pipe, "{\"messageId\":\"m1\",\"body\":\"{}\"}", "us-east-1");
ArgumentCaptor<UnaryOperator<String>> resolver = ArgumentCaptor.captor();
verify(redshiftSubmitter).submit(any(), any(), any(), any(), any(), resolver.capture(), any());
AwsException error = assertThrows(AwsException.class, () -> resolver.getValue().apply("$.body.missing"));
assertEquals("ValidationException", error.getErrorCode());
}
@Test
void redshiftTarget_withoutSqlsIsRejectedBeforeSubmitting() throws Exception {
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(true);
Pipe pipe = redshiftPipe("{\"RedshiftDataParameters\":{\"Database\":\"dev\"}}");
AwsException error = assertThrows(AwsException.class, () -> invoker.invoke(pipe, "{}", "us-east-1"));
assertEquals("ValidationException", error.getErrorCode());
verifyNoInteractions(redshiftSubmitter);
}
@Test
void redshiftTarget_isNotDeliveredWhenTheDataApiIsDisabled() throws Exception {
when(serviceRegistry.isServiceEnabled("redshift-data")).thenReturn(false);
Pipe pipe = redshiftPipe("{\"RedshiftDataParameters\":{\"Sqls\":[\"SELECT 1\"]}}");
AwsException error = assertThrows(AwsException.class, () -> invoker.invoke(pipe, "{}", "us-east-1"));
assertEquals("ServiceNotAvailableException", error.getErrorCode());
verifyNoInteractions(redshiftSubmitter);
}
private Pipe createPipe(String targetArn, ObjectNode targetParameters) {
@@ -1,4 +1,4 @@
package io.github.hectorvent.floci.services.eventbridge;
package io.github.hectorvent.floci.services.redshiftdata;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.config.EmulatorConfig;
@@ -24,7 +24,7 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class EventBridgeRedshiftTargetAuthorizerTest {
class RedshiftTargetAuthorizerTest {
private static final String ACCOUNT_ID = "123456789012";
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT_ID + ":role/events-redshift";
private static final String CLUSTER = "arn:aws:redshift:us-east-1:" + ACCOUNT_ID + ":cluster:warehouse";
@@ -35,13 +35,16 @@ class EventBridgeRedshiftTargetAuthorizerTest {
private static final String ALLOW_EXECUTE = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"redshift-data:ExecuteStatement","Resource":"*"}]}""";
private static final String EVENTS = "events.amazonaws.com";
private static final String PIPES = "pipes.amazonaws.com";
private static final String PIPE_ARN = "arn:aws:pipes:us-east-1:" + ACCOUNT_ID + ":pipe/load";
private static final String RULE_ARN = "arn:aws:events:us-east-1:" + ACCOUNT_ID + ":rule/refresh";
private static final Permission EXECUTE = new Permission("redshift-data:ExecuteStatement", CLUSTER);
private EmulatorConfig config;
private IamService iamService;
private ScpProvider scps;
private EventBridgeRedshiftTargetAuthorizer authorizer;
private RedshiftTargetAuthorizer authorizer;
@BeforeEach
@SuppressWarnings("unchecked")
@@ -56,7 +59,7 @@ class EventBridgeRedshiftTargetAuthorizerTest {
when(scpProvider.get()).thenReturn(scps);
ServiceRoleAuthorizer serviceRoleAuthorizer = new ServiceRoleAuthorizer(config, iamService, evaluator,
new AssumeRolePolicyEvaluator(new ObjectMapper(), evaluator), scpProvider);
authorizer = new EventBridgeRedshiftTargetAuthorizer(config, serviceRoleAuthorizer);
authorizer = new RedshiftTargetAuthorizer(config, serviceRoleAuthorizer);
}
private void role(String trust, String... policies) {
@@ -69,14 +72,14 @@ class EventBridgeRedshiftTargetAuthorizerTest {
void trustedRoleWithThePermissionIsAllowed() {
role(TRUST, ALLOW_EXECUTE);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isEmpty());
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isEmpty());
}
@Test
void nothingIsCheckedWhileIamEnforcementIsOff() {
when(config.services().iam().enforcementEnabled()).thenReturn(false);
assertTrue(authorizer.refusal("not-an-arn", ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isEmpty());
assertTrue(authorizer.refusal(EVENTS, "not-an-arn", ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isEmpty());
verifyNoInteractions(iamService);
}
@@ -84,19 +87,19 @@ class EventBridgeRedshiftTargetAuthorizerTest {
void missingRoleIsRefused() {
when(iamService.findRole(ACCOUNT_ID, "events-redshift")).thenReturn(Optional.empty());
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
.contains("does not exist"));
}
@Test
void roleWithoutAnArnIsRefused() {
assertTrue(authorizer.refusal(null, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
assertTrue(authorizer.refusal(EVENTS, null, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
.contains("requires an IAM role"));
}
@Test
void roleOfAnotherAccountIsRefused() {
assertTrue(authorizer.refusal("arn:aws:iam::999999999999:role/events-redshift", ACCOUNT_ID, RULE_ARN,
assertTrue(authorizer.refusal(EVENTS, "arn:aws:iam::999999999999:role/events-redshift", ACCOUNT_ID, RULE_ARN,
List.of(EXECUTE)).orElseThrow().contains("belongs to another account"));
}
@@ -106,7 +109,7 @@ class EventBridgeRedshiftTargetAuthorizerTest {
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}""", ALLOW_EXECUTE);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
.contains("does not trust events.amazonaws.com"));
}
@@ -118,7 +121,7 @@ class EventBridgeRedshiftTargetAuthorizerTest {
assertEquals("The role " + ROLE_ARN + " is not authorized to perform redshift-data:ExecuteStatement on "
+ CLUSTER + ".",
authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow());
authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow());
}
@Test
@@ -126,7 +129,7 @@ class EventBridgeRedshiftTargetAuthorizerTest {
role(TRUST, ALLOW_EXECUTE);
Permission secret = new Permission("secretsmanager:GetSecretValue", SECRET);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE, secret)).orElseThrow()
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE, secret)).orElseThrow()
.contains("secretsmanager:GetSecretValue on " + SECRET));
}
@@ -136,7 +139,7 @@ class EventBridgeRedshiftTargetAuthorizerTest {
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"secretsmanager:GetSecretValue","Resource":"%s"}]}""".formatted(SECRET));
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN,
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN,
List.of(EXECUTE, new Permission("secretsmanager:GetSecretValue", SECRET))).isEmpty());
}
@@ -147,7 +150,7 @@ class EventBridgeRedshiftTargetAuthorizerTest {
"Action":"redshift-data:ExecuteStatement",
"Resource":"arn:aws:redshift:us-east-1:%s:cluster:other"}]}""".formatted(ACCOUNT_ID));
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
}
@Test
@@ -156,7 +159,7 @@ class EventBridgeRedshiftTargetAuthorizerTest {
{"Version":"2012-10-17","Statement":[{"Effect":"Deny",
"Action":"redshift-data:ExecuteStatement","Resource":"*"}]}""");
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
}
@Test
@@ -166,7 +169,7 @@ class EventBridgeRedshiftTargetAuthorizerTest {
{"Version":"2012-10-17","Statement":[{"Effect":"Deny",
"Action":"redshift-data:ExecuteStatement","Resource":"*"}]}""")));
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
}
@Test
@@ -177,21 +180,21 @@ class EventBridgeRedshiftTargetAuthorizerTest {
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":"s3:*","Resource":"*"}]}"""));
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
}
@Test
void trustPolicyNamingTheMatchedRuleInSourceArnIsAllowed() {
role(sourceArnTrust(RULE_ARN), ALLOW_EXECUTE);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isEmpty());
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isEmpty());
}
@Test
void trustPolicyNamingAnotherRuleInSourceArnIsRefused() {
role(sourceArnTrust("arn:aws:events:us-east-1:" + ACCOUNT_ID + ":rule/other"), ALLOW_EXECUTE);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).orElseThrow()
.contains("does not trust events.amazonaws.com"));
}
@@ -199,7 +202,7 @@ class EventBridgeRedshiftTargetAuthorizerTest {
void sourceArnConditionDoesNotMatchWhenTheRuleIsUnknown() {
role(sourceArnTrust(RULE_ARN), ALLOW_EXECUTE);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, null, List.of(EXECUTE)).isPresent());
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, null, List.of(EXECUTE)).isPresent());
}
private static String sourceArnTrust(String ruleArn) {
@@ -216,6 +219,29 @@ class EventBridgeRedshiftTargetAuthorizerTest {
"Principal":{"Service":"events.amazonaws.com"},"Action":"sts:AssumeRole",
"Condition":{"StringEquals":{"aws:SourceAccount":"999999999999"}}}]}""", ALLOW_EXECUTE);
assertTrue(authorizer.refusal(ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
}
@Test
void theRoleHasToTrustThePrincipalOfTheServiceThatDelivers() {
role(TRUST, ALLOW_EXECUTE);
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isEmpty());
assertTrue(authorizer.refusal(PIPES, ROLE_ARN, ACCOUNT_ID, PIPE_ARN, List.of(EXECUTE)).orElseThrow()
.contains("does not trust pipes.amazonaws.com"));
role(TRUST.replace(EVENTS, PIPES), ALLOW_EXECUTE);
assertTrue(authorizer.refusal(PIPES, ROLE_ARN, ACCOUNT_ID, PIPE_ARN, List.of(EXECUTE)).isEmpty());
assertTrue(authorizer.refusal(EVENTS, ROLE_ARN, ACCOUNT_ID, RULE_ARN, List.of(EXECUTE)).isPresent());
}
@Test
void trustPolicyNamingThePipeInSourceArnIsAllowedForPipes() {
role(sourceArnTrust(PIPE_ARN).replace(EVENTS, PIPES), ALLOW_EXECUTE);
assertTrue(authorizer.refusal(PIPES, ROLE_ARN, ACCOUNT_ID, PIPE_ARN, List.of(EXECUTE)).isEmpty());
assertTrue(authorizer.refusal(PIPES, ROLE_ARN, ACCOUNT_ID, PIPE_ARN + "-other", List.of(EXECUTE))
.isPresent());
}
}