From 24b152a274564616029a2202bfc0c0448501baed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:27:14 +0700 Subject: [PATCH] feat(pipes): deliver to a Redshift cluster or Serverless workgroup through the Data API (#7165) --- docs/services/pipes.md | 34 ++++ .../eventbridge/EventBridgeInvoker.java | 12 +- .../EventBridgeRedshiftTargetAuthorizer.java | 53 ------ .../floci/services/pipes/PipesService.java | 37 ++++ .../services/pipes/PipesTargetInvoker.java | 153 ++++++++++++++-- .../RedshiftTargetAuthorizer.java | 52 ++++++ ...BridgeRedshiftTargetAuthorizationTest.java | 17 +- .../PipesRedshiftTargetIntegrationTest.java | 83 +++++++++ ...tTargetRoleEnforcementIntegrationTest.java | 141 +++++++++++++++ .../services/pipes/PipesServiceTest.java | 78 ++++++++ .../pipes/PipesTargetInvokerTest.java | 168 +++++++++++++++++- .../RedshiftTargetAuthorizerTest.java} | 68 ++++--- 12 files changed, 798 insertions(+), 98 deletions(-) delete mode 100644 src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeRedshiftTargetAuthorizer.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftTargetAuthorizer.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/pipes/PipesRedshiftTargetIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/pipes/PipesRedshiftTargetRoleEnforcementIntegrationTest.java rename src/test/java/io/github/hectorvent/floci/services/{eventbridge/EventBridgeRedshiftTargetAuthorizerTest.java => redshiftdata/RedshiftTargetAuthorizerTest.java} (70%) diff --git a/docs/services/pipes.md b/docs/services/pipes.md index d5cec1e65b..a9f5cdf795 100644 --- a/docs/services/pipes.md +++ b/docs/services/pipes.md @@ -94,6 +94,40 @@ Floci emulates EventBridge Pipes with the following supported source and target - SNS topics - Kinesis streams - Step Functions state machines +- Amazon Redshift clusters and Redshift Serverless workgroups, through the Data API (see below) + +## Redshift Target + +A pipe whose target is a Redshift cluster (`arn:aws:redshift:...:cluster:`) or a Redshift Serverless +workgroup (`arn:aws:redshift-serverless:...:workgroup/`) submits its SQL to the Redshift Data API as +a `BatchExecuteStatement`, so the statements of one delivery run as a single transaction. The target +parameters follow `PipeTargetRedshiftDataParameters`: + +```bash +aws pipes create-pipe --name sqs-to-redshift --source "arn:aws:sqs:us-east-1:000000000000:events" --target "arn:aws:redshift:us-east-1:000000000000:cluster:warehouse" --role-arn "arn:aws:iam::000000000000:role/pipe-role" --target-parameters '{"RedshiftDataParameters":{"Database":"dev","DbUser":"admin","Sqls":["$.body.statement"]}}' --endpoint-url $AWS_ENDPOINT_URL +``` + +- `Sqls` is required, with 1 to 40 statements of at most 100,000 characters each; `CreatePipe` and + `UpdatePipe` reject anything else with `ValidationException`. `Database`, `DbUser`, + `SecretManagerArn`, `StatementName` and `WithEvent` are passed to the Data API. +- A parameter that is wholly a dynamic path, such as `$.body.statement`, is read from the source event as + it arrived (for SQS, the path starts at the message, so the body is `$.body`). Input transformation does + not apply to a Redshift target, and a path that resolves to nothing fails the delivery with + `ValidationException`. A path embedded in a longer string is sent as written. +- The pipe's role must trust `pipes.amazonaws.com` (an `aws:SourceArn` condition naming the pipe is + honored) and, with `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, be allowed + `redshift-data:BatchExecuteStatement` and the action that authenticates the statement + (`secretsmanager:GetSecretValue`, `redshift:GetClusterCredentials` or + `redshift-serverless:GetCredentials`). A refusal fails the delivery and the record follows the pipe's + dead-letter queue. Floci does not assume the role: the statements run with the role ARN recorded on the + pipe, and `GetClusterCredentialsWithIAM` is not supported. +- The Data API accepts the statements and the pipe does not wait for them. A statement that fails afterwards + is visible through `DescribeStatement`, but does not fail the delivery or get retried. A delivery that is + retried, because the Data API refused it or the source batch was redelivered, submits its statements + again, so write statements that tolerate being run twice. +- Each source record is a delivery of its own, as for the other non-Lambda targets, so a batch of N SQS + messages makes N `BatchExecuteStatement` calls. How AWS maps a batch onto the Data API call has not been + verified, and this is a Floci choice. ## ParallelizationFactor diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java index 638cc9bcb8..6d8563b279 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.RequestScopes; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.common.ServiceRegistry; import io.github.hectorvent.floci.core.common.SsrfProtection; import io.github.hectorvent.floci.services.batch.BatchService; @@ -30,6 +31,7 @@ import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.lambda.model.InvocationType; import io.github.hectorvent.floci.services.redshiftdata.RedshiftDataService; 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; @@ -67,6 +69,7 @@ public class EventBridgeInvoker { // AWS can't route an event from a sender bus on to a third bus; the second hop is dropped. private static final int MAX_BUS_TO_BUS_DEPTH = 1; private static final int MAX_IDLE_RATE_WINDOWS = 256; + private static final String EVENTS_PRINCIPAL = ServicePrincipals.of("events"); private static final Pattern DYNAMIC_PARAMETER_PATH = Pattern.compile("\\$(?:\\.[\\w*/-]+|\\[\\d+\\])+"); // Headers the JDK HttpClient manages itself; setting them by hand throws IllegalArgumentException. @@ -84,7 +87,7 @@ public class EventBridgeInvoker { private final EcsJsonHandler ecsJsonHandler; private final StepFunctionsService stepFunctionsService; private final RedshiftDataService redshiftDataService; - private final EventBridgeRedshiftTargetAuthorizer redshiftTargetAuthorizer; + private final RedshiftTargetAuthorizer redshiftTargetAuthorizer; private final RedshiftDataTargetSubmitter redshiftSubmitter; private final ServiceRegistry serviceRegistry; private final RegionResolver regionResolver; @@ -104,7 +107,7 @@ public class EventBridgeInvoker { EcsJsonHandler ecsJsonHandler, StepFunctionsService stepFunctionsService, RedshiftDataService redshiftDataService, - EventBridgeRedshiftTargetAuthorizer redshiftTargetAuthorizer, + RedshiftTargetAuthorizer redshiftTargetAuthorizer, ServiceRegistry serviceRegistry, RegionResolver regionResolver, ObjectMapper objectMapper, @@ -125,7 +128,7 @@ public class EventBridgeInvoker { EcsJsonHandler ecsJsonHandler, StepFunctionsService stepFunctionsService, RedshiftDataService redshiftDataService, - EventBridgeRedshiftTargetAuthorizer redshiftTargetAuthorizer, + RedshiftTargetAuthorizer redshiftTargetAuthorizer, ServiceRegistry serviceRegistry, RegionResolver regionResolver, ObjectMapper objectMapper, @@ -372,7 +375,8 @@ public class EventBridgeInvoker { redshiftSubmitter.submit(targetArn, statement, target.getRoleArn(), ruleAccount, targetRegion, value -> resolveRedshiftParameter(value, eventJson), permissions -> redshiftTargetAuthorizer == null ? Optional.empty() - : redshiftTargetAuthorizer.refusal(target.getRoleArn(), ruleAccount, ruleArn, permissions)); + : redshiftTargetAuthorizer.refusal(EVENTS_PRINCIPAL, target.getRoleArn(), ruleAccount, + ruleArn, permissions)); } private String resolveRedshiftParameter(String value, String eventJson) { diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeRedshiftTargetAuthorizer.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeRedshiftTargetAuthorizer.java deleted file mode 100644 index 73f7677934..0000000000 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeRedshiftTargetAuthorizer.java +++ /dev/null @@ -1,53 +0,0 @@ -package io.github.hectorvent.floci.services.eventbridge; - -import io.github.hectorvent.floci.config.EmulatorConfig; -import io.github.hectorvent.floci.core.common.ServicePrincipals; -import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer; -import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission; -import jakarta.enterprise.context.ApplicationScoped; -import jakarta.inject.Inject; - -import java.util.List; -import java.util.Optional; - -/** - * Decides whether the role of an EventBridge Redshift Data API target may submit its SQL. EventBridge - * assumes the target's role, so the role has to trust {@code events.amazonaws.com}, and its identity - * policies, permissions boundary and SCPs have to allow every {@link Permission} the submission needs: - * the Data API action itself and the action that authenticates it. Only active with IAM enforcement on, - * as for every other API call. A role of another account is refused, because the rule's account does - * not own it. - */ -@ApplicationScoped -public class EventBridgeRedshiftTargetAuthorizer { - - private static final String EVENTS_PRINCIPAL = ServicePrincipals.of("events"); - - private final EmulatorConfig config; - private final ServiceRoleAuthorizer authorizer; - - @Inject - public EventBridgeRedshiftTargetAuthorizer(EmulatorConfig config, ServiceRoleAuthorizer authorizer) { - this.config = config; - this.authorizer = authorizer; - } - - /** - * Returns why {@code roleArn} may not run the target, or nothing when it may. - * - * @param accountId the account that owns the rule - * @param ruleArn the rule that matched, which a trust policy may require in {@code aws:SourceArn}; without - * it such a condition does not match - * @param permissions what the submission needs, each of which has to be allowed - */ - public Optional refusal(String roleArn, String accountId, String ruleArn, - List permissions) { - if (!config.services().iam().enforcementEnabled()) { - return Optional.empty(); - } - if (roleArn == null || roleArn.isBlank()) { - return Optional.of("A Redshift target requires an IAM role, and this one names none."); - } - return authorizer.refusal(roleArn, accountId, EVENTS_PRINCIPAL, ruleArn, permissions); - } -} diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java index 3a92e93429..0e87a4b4ca 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesService.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.pipes; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.MissingNode; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; @@ -35,6 +36,9 @@ public class PipesService implements TagHandler, ResourceProvider { private static final int MIN_PARALLELIZATION_FACTOR = 1; private static final int MAX_PARALLELIZATION_FACTOR = 10; + private static final int MIN_REDSHIFT_SQLS = 1; + private static final int MAX_REDSHIFT_SQLS = 40; + private static final int MAX_REDSHIFT_SQL_LENGTH = 100_000; private final StorageBackend storage; private final RegionResolver regionResolver; @@ -82,6 +86,7 @@ public class PipesService implements TagHandler, ResourceProvider { } validateSourceConfiguration(source, sourceParameters); + validateTargetConfiguration(target, targetParameters); String key = region + "::" + name; if (storage.get(key).isPresent()) { @@ -178,6 +183,8 @@ public class PipesService implements TagHandler, ResourceProvider { if (!clearUnsetProperties) { validateSourceConfiguration(pipe.getSource(), sourceParameters != null ? sourceParameters : pipe.getSourceParameters()); + validateTargetConfiguration(target != null ? target : pipe.getTarget(), + targetParameters != null ? targetParameters : pipe.getTargetParameters()); } writeProperty(target, clearUnsetProperties, pipe::setTarget); @@ -330,6 +337,36 @@ public class PipesService implements TagHandler, ResourceProvider { "Resource " + arn + " does not exist.", 404)); } + /** + * A Redshift target runs its {@code Sqls} as one BatchExecuteStatement, which the PipeTargetRedshiftDataParameters + * reference makes required together with {@code Database}, with 1 to 40 statements of at most 100,000 + * characters each. + */ + private void validateTargetConfiguration(String target, JsonNode targetParameters) { + if (!PipesTargetInvoker.isRedshiftTarget(target)) { + return; + } + JsonNode parameters = targetParameters == null + ? MissingNode.getInstance() : targetParameters.path("RedshiftDataParameters"); + if (!parameters.path("Database").isTextual() || parameters.path("Database").asText().isBlank()) { + throw new AwsException("ValidationException", + "TargetParameters.RedshiftDataParameters.Database is required for a Redshift target.", 400); + } + JsonNode sqls = parameters.path("Sqls"); + if (!sqls.isArray() || sqls.size() < MIN_REDSHIFT_SQLS || sqls.size() > MAX_REDSHIFT_SQLS) { + throw new AwsException("ValidationException", + "TargetParameters.RedshiftDataParameters.Sqls must hold between " + MIN_REDSHIFT_SQLS + + " and " + MAX_REDSHIFT_SQLS + " statements for a Redshift target.", 400); + } + for (JsonNode sql : sqls) { + if (!sql.isTextual() || sql.asText().length() > MAX_REDSHIFT_SQL_LENGTH) { + throw new AwsException("ValidationException", + "Each entry of TargetParameters.RedshiftDataParameters.Sqls must be a string of at most " + + MAX_REDSHIFT_SQL_LENGTH + " characters.", 400); + } + } + } + private void validateSourceConfiguration(String source, JsonNode sourceParameters) { if (source == null) { return; diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java index 799a0028c2..7cedd0e241 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvoker.java @@ -3,14 +3,19 @@ package io.github.hectorvent.floci.services.pipes; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.MissingNode; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.ServicePrincipals; +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.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; @@ -21,6 +26,7 @@ import org.jboss.logging.Logger; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.util.ArrayList; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.UUID; @@ -34,13 +40,19 @@ public class PipesTargetInvoker { private static final Logger LOG = Logger.getLogger(PipesTargetInvoker.class); private static final Pattern TEMPLATE_PLACEHOLDER = Pattern.compile("<(\\$[^>]+|aws\\.pipes\\.event\\.ingestion-time)>"); - private static final Pattern ARRAY_INDEX = Pattern.compile("^(.+?)\\[(\\d+)]$"); + private static final Pattern ARRAY_INDEX = Pattern.compile("^(.*?)\\[(\\d+)]$"); + private static final String PIPES_PRINCIPAL = ServicePrincipals.of("pipes"); + private static final Pattern DYNAMIC_PARAMETER_PATH = + Pattern.compile("\\$(?:\\.[\\w*/-]+|\\[\\d+\\])+"); private final LambdaService lambdaService; private final SqsService sqsService; private final SnsService snsService; private final EventBridgeService eventBridgeService; private final StepFunctionsService stepFunctionsService; + private final RedshiftDataTargetSubmitter redshiftSubmitter; + private final RedshiftTargetAuthorizer redshiftTargetAuthorizer; + private final ServiceRegistry serviceRegistry; private final ObjectMapper objectMapper; private final String baseUrl; @@ -50,6 +62,9 @@ public class PipesTargetInvoker { SnsService snsService, EventBridgeService eventBridgeService, StepFunctionsService stepFunctionsService, + RedshiftDataTargetSubmitter redshiftSubmitter, + RedshiftTargetAuthorizer redshiftTargetAuthorizer, + ServiceRegistry serviceRegistry, ObjectMapper objectMapper, EmulatorConfig config) { this.lambdaService = lambdaService; @@ -57,13 +72,28 @@ public class PipesTargetInvoker { this.snsService = snsService; this.eventBridgeService = eventBridgeService; this.stepFunctionsService = stepFunctionsService; + this.redshiftSubmitter = redshiftSubmitter; + this.redshiftTargetAuthorizer = redshiftTargetAuthorizer; + this.serviceRegistry = serviceRegistry; this.objectMapper = objectMapper; this.baseUrl = config.effectiveBaseUrl(); } + /** Whether {@code targetArn} names a Redshift cluster or a Redshift Serverless workgroup. */ + static boolean isRedshiftTarget(String targetArn) { + return AwsArnUtils.isArnFor(targetArn, "redshift") || AwsArnUtils.isArnFor(targetArn, "redshift-serverless"); + } + public void invoke(Pipe pipe, String payload, String region) { String targetArn = pipe.getTarget(); + // A dynamic path in the Redshift parameters reads the source event as it arrived, and AWS does not + // let it name a value an input transformation produced, so this does not go through the template. + if (isRedshiftTarget(targetArn)) { + invokeRedshiftData(pipe, payload, region); + return; + } + JsonNode tp = pipe.getTargetParameters(); if (tp != null && tp.has("InputTemplate")) { payload = applyInputTemplate(tp.get("InputTemplate").asText(), payload); @@ -220,6 +250,61 @@ public class PipesTargetInvoker { LOG.debugv("Pipe delivered to Step Functions: {0}", arn); } + /** + * A Redshift target always runs its {@code Sqls} as one BatchExecuteStatement, under the pipe's role. + * The Data API accepts the statements and the pipe does not wait for them, so a statement that later + * fails does not fail the delivery or get retried: only a refusal or a rejected request does. + */ + private void invokeRedshiftData(Pipe pipe, String payload, String region) { + if (serviceRegistry != null && !serviceRegistry.isServiceEnabled("redshift-data")) { + throw new AwsException("ServiceNotAvailableException", "Service redshift-data is not enabled.", 400); + } + JsonNode targetParameters = pipe.getTargetParameters(); + JsonNode parameters = targetParameters == null + ? MissingNode.getInstance() : targetParameters.path("RedshiftDataParameters"); + JsonNode sqlNodes = parameters.path("Sqls"); + if (!sqlNodes.isArray() || sqlNodes.isEmpty()) { + throw new AwsException("ValidationException", + "Pipe " + pipe.getName() + " has a Redshift target without RedshiftDataParameters.Sqls.", 400); + } + List sqls = new ArrayList<>(); + sqlNodes.forEach(sql -> sqls.add(sql.asText())); + + String targetArn = pipe.getTarget(); + String targetRegion = extractRegionFromArn(targetArn, region); + String account = pipe.getAccountId() != null ? pipe.getAccountId() : AwsArnUtils.parse(targetArn).accountId(); + RedshiftDataTargetSubmitter.Statement statement = new RedshiftDataTargetSubmitter.Statement( + text(parameters, "Database"), text(parameters, "DbUser"), text(parameters, "SecretManagerArn"), + null, sqls, text(parameters, "StatementName"), + parameters.path("WithEvent").isBoolean() ? parameters.get("WithEvent").asBoolean() : null); + redshiftSubmitter.submit(targetArn, statement, pipe.getRoleArn(), account, targetRegion, + value -> resolveRedshiftParameter(value, payload), + permissions -> redshiftTargetAuthorizer.refusal( + PIPES_PRINCIPAL, pipe.getRoleArn(), account, pipe.getArn(), permissions)); + LOG.debugv("Pipe delivered to Redshift Data API: {0}", targetArn); + } + + private static String text(JsonNode parent, String field) { + JsonNode node = parent.path(field); + return node.isTextual() ? node.asText() : null; + } + + private String resolveRedshiftParameter(String value, String payload) { + if (value == null || !DYNAMIC_PARAMETER_PATH.matcher(value).matches()) { + return value; + } + String extracted = extractJsonPath(value, payload); + if (extracted == null) { + throw new AwsException("ValidationException", "Cannot resolve Redshift target path: " + value, 400); + } + try { + JsonNode node = objectMapper.readTree(extracted); + return node.isTextual() ? node.asText() : node.toString(); + } catch (JsonProcessingException e) { + return extracted; + } + } + String applyInputTemplate(String template, String payload) { Matcher m = TEMPLATE_PLACEHOLDER.matcher(template); String ingestionTime = objectMapper.valueToTree(Instant.now().toString()).toString(); @@ -281,7 +366,10 @@ public class PipesTargetInvoker { for (String seg : rawSegments) { Matcher am = ARRAY_INDEX.matcher(seg); if (am.matches()) { - segments.add(am.group(1)); + // A leading index such as "$[0].x" has no name before the bracket + if (!am.group(1).isEmpty()) { + segments.add(am.group(1)); + } segments.add(am.group(2)); } else if (!seg.isEmpty()) { segments.add(seg); @@ -290,12 +378,15 @@ public class PipesTargetInvoker { JsonNode current = objectMapper.readTree(json); String previousSegment = null; + JsonNode container = null; + JsonNode outer = null; boolean sourceFieldDecoded = false; for (String segment : segments) { // AWS Pipes parses an encoded source body when traversing into it. if (!sourceFieldDecoded && isEncodedSourceField(previousSegment) && current.isTextual()) { try { - JsonNode decoded = objectMapper.readTree(current.asText()); + JsonNode decoded = objectMapper.readTree( + decodedSourceText(previousSegment, current.asText(), container, outer)); if (decoded != null && (decoded.isObject() || decoded.isArray())) { current = decoded; } @@ -304,28 +395,32 @@ public class PipesTargetInvoker { return null; } } - if (current.isArray()) { - current = current.path(Integer.parseInt(segment)); - } else { - current = current.path(segment); - } - if (current.isMissingNode() || current.isNull()) { + JsonNode next = current.isArray() + ? current.path(Integer.parseInt(segment)) + : current.path(segment); + if (next.isMissingNode() || next.isNull()) { return null; } + outer = container; + container = current; + current = next; previousSegment = segment; } if (!sourceFieldDecoded && isEncodedSourceField(previousSegment) && current.isTextual()) { // SQS bodies commonly contain a JSON document as a string. Pipes input // transformation resolves that document when the body itself is selected. + String text = decodedSourceText(previousSegment, current.asText(), container, outer); try { - JsonNode decoded = objectMapper.readTree(current.asText()); - sourceFieldDecoded = true; + JsonNode decoded = objectMapper.readTree(text); if (decoded != null && (decoded.isObject() || decoded.isArray())) { return decoded.toString(); } } catch (JsonProcessingException ignored) { // Keep ordinary textual fields as JSON strings. } + if (!text.equals(current.asText())) { + return objectMapper.writeValueAsString(text); + } } if (current.isValueNode()) { return objectMapper.writeValueAsString(current); @@ -337,6 +432,42 @@ public class PipesTargetInvoker { } } + /** + * Kinesis {@code data} and Kafka {@code key} and {@code value} arrive as base64, so a path into them has to + * read the decoded bytes. Only the fields of a Kinesis or Kafka source record qualify: a field of the same + * name in an enrichment response or an SQS body is ordinary text and stays as it is, and so does text that + * is not base64. + * + * @param container the object that holds {@code field} + * @param outer the object that holds {@code container} + */ + private static String decodedSourceText(String field, String text, JsonNode container, JsonNode outer) { + if (!isBase64SourceField(field, container, outer)) { + return text; + } + try { + return new String(Base64.getDecoder().decode(text), StandardCharsets.UTF_8); + } catch (IllegalArgumentException expected) { + // Not base64, so the field holds plain text such as an inline JSON document. + return text; + } + } + + private static boolean isBase64SourceField(String field, JsonNode container, JsonNode outer) { + if ("data".equals(field)) { + return outer != null && "aws:kinesis".equals(outer.path("eventSource").asText()) + && outer.path("kinesis") == container; + } + if ("key".equals(field) || "value".equals(field)) { + return container != null && isKafkaEventSource(container.path("eventSource").asText()); + } + return false; + } + + private static boolean isKafkaEventSource(String eventSource) { + return "aws:kafka".equals(eventSource) || "SelfManagedKafka".equals(eventSource); + } + private static boolean isEncodedSourceField(String segment) { return "body".equals(segment) || "data".equals(segment) || "key".equals(segment) || "value".equals(segment); diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftTargetAuthorizer.java b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftTargetAuthorizer.java new file mode 100644 index 0000000000..02e3763b99 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftTargetAuthorizer.java @@ -0,0 +1,52 @@ +package io.github.hectorvent.floci.services.redshiftdata; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer; +import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer.Permission; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Optional; + +/** + * Decides whether the role of a Redshift Data API target may submit its SQL, for any service that + * delivers events to one (EventBridge, Pipes). The delivering service assumes the target's role, so the + * role has to trust that service's principal (with a condition on {@code aws:SourceArn} naming the rule + * or pipe, if it has one), and its identity policies, permissions boundary and SCPs have to allow every + * {@link Permission} the submission needs. Only active with IAM enforcement on, as for every other API + * call. A role of another account is refused, because the account that owns the rule or pipe does not + * own it. + */ +@ApplicationScoped +public class RedshiftTargetAuthorizer { + + private final EmulatorConfig config; + private final ServiceRoleAuthorizer authorizer; + + @Inject + public RedshiftTargetAuthorizer(EmulatorConfig config, ServiceRoleAuthorizer authorizer) { + this.config = config; + this.authorizer = authorizer; + } + + /** + * Returns why {@code roleArn} may not run the target, or nothing when it may. + * + * @param principal the service principal that assumes the role, such as {@code events.amazonaws.com} + * @param accountId the account that owns the rule or pipe + * @param sourceArn the rule or pipe, which a trust policy may require in {@code aws:SourceArn}; without + * it such a condition does not match + * @param permissions what the submission needs, each of which has to be allowed + */ + public Optional refusal(String principal, String roleArn, String accountId, String sourceArn, + List permissions) { + if (!config.services().iam().enforcementEnabled()) { + return Optional.empty(); + } + if (roleArn == null || roleArn.isBlank()) { + return Optional.of("A Redshift target requires an IAM role, and this one names none."); + } + return authorizer.refusal(roleArn, accountId, principal, sourceArn, permissions); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeRedshiftTargetAuthorizationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeRedshiftTargetAuthorizationTest.java index 75f4edbf83..164dff6ac2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeRedshiftTargetAuthorizationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeRedshiftTargetAuthorizationTest.java @@ -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 permissions() { @SuppressWarnings("unchecked") ArgumentCaptor> 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(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesRedshiftTargetIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesRedshiftTargetIntegrationTest.java new file mode 100644 index 0000000000..8b01437fae --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesRedshiftTargetIntegrationTest.java @@ -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 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); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesRedshiftTargetRoleEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesRedshiftTargetRoleEnforcementIntegrationTest.java new file mode 100644 index 0000000000..c116e417d5 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesRedshiftTargetRoleEnforcementIntegrationTest.java @@ -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; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java index e0c68dcfb2..74a30defd0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesServiceTest.java @@ -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", diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java index 5645172c1f..670f2254f4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesTargetInvokerTest.java @@ -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 statement = ArgumentCaptor.captor(); + ArgumentCaptor> resolver = ArgumentCaptor.captor(); + ArgumentCaptor 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> 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> 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> 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> 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) { diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeRedshiftTargetAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftTargetAuthorizerTest.java similarity index 70% rename from src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeRedshiftTargetAuthorizerTest.java rename to src/test/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftTargetAuthorizerTest.java index 84c02d873a..afd5d761d9 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeRedshiftTargetAuthorizerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshiftdata/RedshiftTargetAuthorizerTest.java @@ -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()); } }