From d7797bf56dacca4cf399c62dab41edeafdba0ff4 Mon Sep 17 00:00:00 2001 From: "Ovidiu (Ovi)" <163712869+ovi-fabric@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:27:03 +0200 Subject: [PATCH] feat(redshift): add PutResourcePolicy, GetResourcePolicy and DeleteResourcePolicy (#7361) * feat(redshift): add PutResourcePolicy, GetResourcePolicy and DeleteResourcePolicy aws_redshift_resource_policy could not be created: the provisioned Redshift API had none of the three operations. They now take the ARN of a Redshift Serverless namespace or a provisioned cluster, the targets of a zero-ETL integration, matched exactly in the caller's account and Region. The policy is kept on its namespace or cluster, so it goes with the resource, and is stored and echoed, not evaluated. * feat(redshift): return resource policies and their errors as AWS does Checked against AWS with read-only GetResourcePolicy calls: a stored policy comes back with Version and Statement first and each statement's Effect, Principal, Action, Resource and Condition first, pretty-printed, so it is now stored in that form. A namespace that does not exist answers "The requested namespace doesn't exist."; an ARN in another Region, a namespace id that is not a UUID and an ARN of any other resource type are InvalidParameterValue with AWS's messages, not UnsupportedOperation. Adds an SDK compatibility test for the three operations. * fix(redshift): keep a namespace's resource policy across updates The Namespace copy constructor, used by tagging, untagging and UpdateNamespace, did not copy the resource policy, so any of them dropped it. findClusterByArn now reads the ARN through AwsArnUtils. Without a Version, GetResourcePolicy reached Elastic Load Balancing, which defines the name but does not serve it; it now goes to Redshift. * fix(redshift): refuse an empty resource policy before looking the resource up --- .../test/RedshiftResourcePolicyTest.java | 116 +++++++++ docs/services/index.md | 2 +- docs/services/redshift.md | 29 +++ .../floci/core/common/AwsQueryController.java | 4 +- .../redshift/RedshiftQueryHandler.java | 43 +++- .../redshift/RedshiftResourcePolicies.java | 224 ++++++++++++++++++ .../services/redshift/RedshiftService.java | 23 ++ .../services/redshift/model/Cluster.java | 6 + .../RedshiftServerlessService.java | 14 ++ .../redshiftserverless/model/Namespace.java | 12 + ...RedshiftResourcePolicyIntegrationTest.java | 186 +++++++++++++++ .../redshift/RedshiftServiceTest.java | 17 ++ 12 files changed, 672 insertions(+), 4 deletions(-) create mode 100644 compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftResourcePolicyTest.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftResourcePolicies.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftResourcePolicyIntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftResourcePolicyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftResourcePolicyTest.java new file mode 100644 index 0000000000..1e317abc8e --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftResourcePolicyTest.java @@ -0,0 +1,116 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.redshift.RedshiftClient; +import software.amazon.awssdk.services.redshift.model.InvalidPolicyException; +import software.amazon.awssdk.services.redshift.model.RedshiftException; +import software.amazon.awssdk.services.redshift.model.ResourceNotFoundException; +import software.amazon.awssdk.services.redshift.model.ResourcePolicy; +import software.amazon.awssdk.services.redshiftserverless.RedshiftServerlessClient; + +import java.net.URI; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** A Redshift resource policy on a Redshift Serverless namespace, through the AWS SDK for Java v2. */ +@DisplayName("Redshift resource policies") +class RedshiftResourcePolicyTest { + + private static final String NAMESPACE_NAME = "rp-" + UUID.randomUUID().toString().substring(0, 8); + private static final String POLICY = "{\"Statement\":[{\"Action\":\"redshift:AuthorizeInboundIntegration\"," + + "\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"redshift.amazonaws.com\"},\"Resource\":\"*\"}]," + + "\"Version\":\"2012-10-17\"}"; + private static final String STORED_POLICY = """ + { + "Version" : "2012-10-17", + "Statement" : [ { + "Effect" : "Allow", + "Principal" : { + "Service" : "redshift.amazonaws.com" + }, + "Action" : "redshift:AuthorizeInboundIntegration", + "Resource" : "*" + } ] + }"""; + + private static RedshiftClient redshift; + private static RedshiftServerlessClient serverless; + private static String namespaceArn; + + @BeforeAll + static void setUp() { + String endpoint = System.getenv("FLOCI_ENDPOINT"); + if (endpoint == null || endpoint.isBlank()) { + endpoint = "http://localhost:4566"; + } + if (!endpoint.startsWith("http")) { + endpoint = "http://" + endpoint; + } + StaticCredentialsProvider credentials = + StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")); + redshift = RedshiftClient.builder().endpointOverride(URI.create(endpoint)) + .region(Region.US_EAST_1).credentialsProvider(credentials).build(); + serverless = RedshiftServerlessClient.builder().endpointOverride(URI.create(endpoint)) + .region(Region.US_EAST_1).credentialsProvider(credentials).build(); + namespaceArn = serverless.createNamespace(r -> r.namespaceName(NAMESPACE_NAME)).namespace().namespaceArn(); + } + + @AfterAll + static void cleanup() { + try { + serverless.deleteNamespace(r -> r.namespaceName(NAMESPACE_NAME)); + } catch (Exception ignored) { + // Best effort: the test may have failed before creating it. + } + redshift.close(); + serverless.close(); + } + + @Test + void aNamespacePolicyIsPutReadAndDeleted() { + ResourcePolicy put = redshift.putResourcePolicy(r -> r.resourceArn(namespaceArn).policy(POLICY)) + .resourcePolicy(); + assertThat(put.resourceArn()).isEqualTo(namespaceArn); + assertThat(put.policy()).isEqualTo(STORED_POLICY); + + ResourcePolicy got = redshift.getResourcePolicy(r -> r.resourceArn(namespaceArn)).resourcePolicy(); + assertThat(got.resourceArn()).isEqualTo(namespaceArn); + assertThat(got.policy()).isEqualTo(STORED_POLICY); + + redshift.deleteResourcePolicy(r -> r.resourceArn(namespaceArn)); + assertThatThrownBy(() -> redshift.getResourcePolicy(r -> r.resourceArn(namespaceArn))) + .isInstanceOf(ResourceNotFoundException.class); + } + + @Test + void refusalsMapToTheSdksExceptions() { + assertThatThrownBy(() -> redshift.putResourcePolicy(r -> r.resourceArn(namespaceArn).policy("[]"))) + .isInstanceOf(InvalidPolicyException.class); + + String unknown = namespaceArn.substring(0, namespaceArn.lastIndexOf('/') + 1) + + "00000000-0000-0000-0000-000000000000"; + // An empty policy is refused before the missing namespace is looked up; a valid one is not. + assertThatThrownBy(() -> redshift.putResourcePolicy(r -> r.resourceArn(unknown).policy("{}"))) + .isInstanceOf(InvalidPolicyException.class); + assertThatThrownBy(() -> redshift.putResourcePolicy(r -> r.resourceArn(unknown).policy(POLICY))) + .isInstanceOf(ResourceNotFoundException.class); + assertThatThrownBy(() -> redshift.getResourcePolicy(r -> r.resourceArn(unknown))) + .isInstanceOf(ResourceNotFoundException.class) + .hasMessageContaining("The requested namespace doesn't exist."); + + String workgroup = namespaceArn.replace(":namespace/", ":workgroup/"); + assertThatThrownBy(() -> redshift.getResourcePolicy(r -> r.resourceArn(workgroup))) + .isInstanceOfSatisfying(RedshiftException.class, e -> { + assertThat(e.statusCode()).isEqualTo(400); + assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterValue"); + }); + } +} diff --git a/docs/services/index.md b/docs/services/index.md index da9116fb4b..37424285d1 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -78,7 +78,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 | | [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 13 | | [DMS](dms.md) | `POST /` + `X-Amz-Target: AmazonDMSv20160101.*` | JSON 1.1 | 20 | -| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 52 | +| [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 55 | | [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 | | [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 55 | | [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 40 | diff --git a/docs/services/redshift.md b/docs/services/redshift.md index e659548fed..a3e2aed56e 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -143,6 +143,9 @@ The attributes follow the [CloudFormation resource schema](https://docs.aws.amaz | `CreateIntegration` | Create a DynamoDB zero-ETL integration from a table (or a stream) to a Redshift Serverless namespace (or a provisioned cluster). Accepts `Description`, `KMSKeyId`, `AdditionalEncryptionContext` and `TagList` | | `DescribeIntegrations` | List integrations with `Filters`, `MaxRecords` and `Marker` pagination, or the one an `IntegrationArn` names | | `DeleteIntegration` | Remove a zero-ETL integration | +| `PutResourcePolicy` | Set the resource policy of a Redshift Serverless namespace or a provisioned cluster, see [Resource policies](#resource-policies) | +| `GetResourcePolicy` | Return the resource policy of a namespace or cluster | +| `DeleteResourcePolicy` | Remove the resource policy of a namespace or cluster | | `DescribeClusterSubnetGroups` | List subnet groups, optionally filtered by name | | `ModifyClusterSubnetGroup` | Update a subnet group's description or subnet list | | `DeleteClusterSubnetGroup` | Remove a subnet group | @@ -415,6 +418,32 @@ approximation to indicate that initial backfill is in progress); it becomes `act exhausted. The landing table is an append-only log, so an item changed while its table is still being backfilled can appear twice: once from the scan and once from the stream. +### Resource policies + +A zero-ETL integration needs a resource policy on its target that lets the source in. +`PutResourcePolicy`, `GetResourcePolicy` and `DeleteResourcePolicy` take the ARN of a Redshift +Serverless namespace or of a provisioned cluster, so `aws_redshift_resource_policy` applies as it +does on AWS: + +- The policy must be a nonempty JSON object, or the call is refused with `InvalidPolicyFault` before + the resource is looked up. +- The policy is stored the way AWS returns it: `Version` and `Statement` first, each statement's + `Effect`, `Principal`, `Action`, `Resource` and `Condition` first, other keys after them in the + order sent, pretty-printed. The provider compares policies by content, so this causes no drift. +- A namespace that does not exist is `ResourceNotFoundFault` ("The requested namespace doesn't + exist."), as is a cluster that does not exist, or a resource without a policy on + `GetResourcePolicy` and `DeleteResourcePolicy`. +- An ARN in another Region, a namespace id that is not a UUID, and an ARN of any other resource type + (a workgroup, a snapshot) are `InvalidParameterValue`, with AWS's messages. +- Deleting the namespace or cluster deletes its policy. +- Floci does not evaluate the policy: `CreateIntegration` does not require one. + +```bash +aws --endpoint-url http://localhost:4566 redshift put-resource-policy \ + --resource-arn arn:aws:redshift-serverless:us-east-1:000000000000:namespace/ \ + --policy '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"redshift.amazonaws.com"},"Action":"redshift:AuthorizeInboundIntegration","Resource":"*"}]}' +``` + ### EventBridge events As an integration changes state, Floci sends `aws.redshift` events to the default EventBridge bus diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index 64594ce404..c9bdaa3c8b 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -492,7 +492,9 @@ public class AwsQueryController { Map.entry("DescribeAccountLimits", "elasticloadbalancing"), Map.entry("CreateIntegration", "redshift"), Map.entry("DeleteIntegration", "redshift"), - Map.entry("DescribeIntegrations", "redshift")); + Map.entry("DescribeIntegrations", "redshift"), + // Elastic Load Balancing v2 defines it too, but Floci's ELB does not serve it. + Map.entry("GetResourcePolicy", "redshift")); /** * The service a Query request goes to when its credential scope does not name one. diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java index 9198eb31ef..29bf565ba6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandler.java @@ -63,13 +63,15 @@ public class RedshiftQueryHandler { private final RegionResolver regionResolver; private final RedshiftDynamoDbZeroEtlConsumer zeroEtlConsumer; private final IamEnforcementFilter iamEnforcementFilter; + private final RedshiftResourcePolicies resourcePolicies; @Inject public RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker, EmulatorConfig config, RedshiftIamDbUserResolver iamDbUserResolver, RegionResolver regionResolver, RedshiftDynamoDbZeroEtlConsumer zeroEtlConsumer, - IamEnforcementFilter iamEnforcementFilter) { + IamEnforcementFilter iamEnforcementFilter, + RedshiftResourcePolicies resourcePolicies) { this.service = service; this.credentialBroker = credentialBroker; this.config = config; @@ -77,12 +79,13 @@ public class RedshiftQueryHandler { this.regionResolver = regionResolver; this.zeroEtlConsumer = zeroEtlConsumer; this.iamEnforcementFilter = iamEnforcementFilter; + this.resourcePolicies = resourcePolicies; } RedshiftQueryHandler(RedshiftService service, RedshiftCredentialBroker credentialBroker, EmulatorConfig config, RedshiftIamDbUserResolver iamDbUserResolver, RegionResolver regionResolver) { - this(service, credentialBroker, config, iamDbUserResolver, regionResolver, null, null); + this(service, credentialBroker, config, iamDbUserResolver, regionResolver, null, null, null); } public Response handle(String action, MultivaluedMap params) { @@ -522,6 +525,25 @@ public class RedshiftQueryHandler { .build(); return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); } + case "PutResourcePolicy" -> { + RedshiftResourcePolicies.ResourcePolicy stored = resourcePolicies.put( + params.getFirst("ResourceArn"), params.getFirst("Policy")); + return resourcePolicyResponse("PutResourcePolicy", stored); + } + case "GetResourcePolicy" -> { + return resourcePolicyResponse("GetResourcePolicy", resourcePolicies.get(params.getFirst("ResourceArn"))); + } + case "DeleteResourcePolicy" -> { + resourcePolicies.delete(params.getFirst("ResourceArn")); + String xml = new XmlBuilder() + .start("DeleteResourcePolicyResponse") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end("DeleteResourcePolicyResponse") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } case "DescribeClusterSubnetGroups" -> { String name = params.getFirst("ClusterSubnetGroupName"); List groups = service.describeClusterSubnetGroups(name); @@ -991,6 +1013,23 @@ public class RedshiftQueryHandler { } } + private static Response resourcePolicyResponse(String operation, RedshiftResourcePolicies.ResourcePolicy policy) { + String xml = new XmlBuilder() + .start(operation + "Response") + .start(operation + "Result") + .start("ResourcePolicy") + .elem("ResourceArn", policy.resourceArn()) + .elem("Policy", policy.policy()) + .end("ResourcePolicy") + .end(operation + "Result") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end(operation + "Response") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } + /** * Authorizes the actions GetClusterCredentials needs besides redshift:GetClusterCredentials, which * the API reference lists for its options: redshift:JoinGroup on each group in {@code DbGroups}, diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftResourcePolicies.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftResourcePolicies.java new file mode 100644 index 0000000000..8ef2246f4c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftResourcePolicies.java @@ -0,0 +1,224 @@ +package io.github.hectorvent.floci.services.redshift; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.util.DefaultIndenter; +import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectReader; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +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.services.redshift.model.Cluster; +import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService; +import io.github.hectorvent.floci.services.redshiftserverless.model.Namespace; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Redshift resource policies, which authorize the sources of zero-ETL integrations into a Redshift + * Serverless namespace or a provisioned cluster. A policy is stored and echoed, not evaluated. It is + * kept on the namespace or cluster it belongs to, so deleting the resource deletes its policy. + */ +@ApplicationScoped +public class RedshiftResourcePolicies { + + /** A resource and its policy, as the {@code ResourcePolicy} shape carries them. */ + public record ResourcePolicy(String resourceArn, String policy) {} + + /** The keys AWS writes first, in its order, when it returns a stored policy. */ + private static final List POLICY_KEY_ORDER = List.of("Version", "Statement"); + private static final List STATEMENT_KEY_ORDER = + List.of("Effect", "Principal", "Action", "Resource", "Condition"); + + private static final Pattern NAMESPACE_ID = + Pattern.compile("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"); + + private final RedshiftService redshift; + private final RedshiftServerlessService serverless; + private final RegionResolver regionResolver; + private final ObjectReader strictPolicyReader; + private final ObjectWriter policyWriter; + + @Inject + public RedshiftResourcePolicies(RedshiftService redshift, RedshiftServerlessService serverless, + RegionResolver regionResolver, ObjectMapper objectMapper) { + this.redshift = redshift; + this.serverless = serverless; + this.regionResolver = regionResolver; + this.strictPolicyReader = objectMapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + this.policyWriter = objectMapper.writer( + new DefaultPrettyPrinter().withObjectIndenter(new DefaultIndenter(" ", "\n"))); + } + + /** Replaces the policy of the resource an ARN names, stored in the form AWS returns it in. */ + public synchronized ResourcePolicy put(String resourceArn, String policy) { + requireParameter("ResourceArn", resourceArn); + requireParameter("Policy", policy); + String normalized = normalized(requireJsonObject(policy)); + Kind kind = kind(resourceArn); + boolean stored = switch (kind) { + case NAMESPACE -> serverless.setNamespaceResourcePolicy(resourceArn, regionResolver.getRegion(), + normalized).isPresent(); + case CLUSTER -> redshift.setClusterResourcePolicy(resourceArn, normalized).isPresent(); + }; + if (!stored) { + throw resourceNotFound(kind); + } + return new ResourcePolicy(resourceArn, normalized); + } + + /** The policy of the resource an ARN names. */ + public synchronized ResourcePolicy get(String resourceArn) { + requireParameter("ResourceArn", resourceArn); + return new ResourcePolicy(resourceArn, currentPolicy(resourceArn)); + } + + /** Removes the policy of the resource an ARN names. */ + public synchronized void delete(String resourceArn) { + requireParameter("ResourceArn", resourceArn); + currentPolicy(resourceArn); + switch (kind(resourceArn)) { + case NAMESPACE -> serverless.setNamespaceResourcePolicy(resourceArn, regionResolver.getRegion(), null); + case CLUSTER -> redshift.setClusterResourcePolicy(resourceArn, null); + } + } + + private enum Kind { NAMESPACE, CLUSTER } + + /** + * Which resource an ARN names. Zero-ETL integrations target a Serverless namespace or a + * provisioned cluster, and those are the resources that take a policy, in the caller's Region. + */ + private Kind kind(String resourceArn) { + if (!AwsArnUtils.looksLikeArn(resourceArn)) { + throw resourceNotFound(null); + } + AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn); + if (!regionResolver.getRegion().equals(arn.region())) { + throw new AwsException("InvalidParameterValue", "The Region in the ARN doesn't match the current " + + "Region. Change your current Region to the same Region in your resource ARN.", 400); + } + if ("redshift-serverless".equals(arn.service()) && arn.resource().startsWith("namespace/")) { + if (!NAMESPACE_ID.matcher(arn.resource().substring("namespace/".length())).matches()) { + throw new AwsException("InvalidParameterValue", + "The format of the provided identifier is invalid.", 400); + } + return Kind.NAMESPACE; + } + if ("redshift".equals(arn.service()) && arn.resource().startsWith("cluster:")) { + return Kind.CLUSTER; + } + throw new AwsException("InvalidParameterValue", "Resource type " + resourceType(arn.resource()) + + " isn't supported for the resource policy. Choose another resource type.", 400); + } + + /** The resource type of an ARN's resource part, such as {@code workgroup} in {@code workgroup/}. */ + private static String resourceType(String resource) { + int end = resource.length(); + for (char separator : new char[] {'/', ':'}) { + int at = resource.indexOf(separator); + if (at >= 0 && at < end) { + end = at; + } + } + return resource.substring(0, end); + } + + /** The resource's policy; a missing resource and a resource without a policy are both not found. */ + private String currentPolicy(String resourceArn) { + Kind kind = kind(resourceArn); + String policy = switch (kind) { + case NAMESPACE -> serverless.findNamespaceByArn(resourceArn, regionResolver.getRegion()) + .orElseThrow(() -> resourceNotFound(kind)) + .getResourcePolicy(); + case CLUSTER -> redshift.findClusterByArn(resourceArn) + .orElseThrow(() -> resourceNotFound(kind)) + .getResourcePolicy(); + }; + if (policy == null) { + throw resourceNotFound(null); + } + return policy; + } + + /** The policy as a nonempty JSON object; anything else is {@code InvalidPolicyFault}. */ + private ObjectNode requireJsonObject(String policy) { + JsonNode parsed; + try { + parsed = strictPolicyReader.readTree(policy); + } catch (IOException e) { + throw invalidPolicy(); + } + // AWS refuses an empty object too, before it looks the resource up. + if (!(parsed instanceof ObjectNode object) || object.isEmpty()) { + throw invalidPolicy(); + } + return object; + } + + /** + * The policy as AWS returns a stored one: {@code Version} and {@code Statement} first, each + * statement's {@code Effect}, {@code Principal}, {@code Action}, {@code Resource} and + * {@code Condition} first, any other keys after them in request order, pretty-printed. + */ + private String normalized(ObjectNode policy) { + ObjectNode ordered = reordered(policy, POLICY_KEY_ORDER); + JsonNode statements = ordered.get("Statement"); + if (statements instanceof ObjectNode statement) { + ordered.set("Statement", reordered(statement, STATEMENT_KEY_ORDER)); + } else if (statements instanceof ArrayNode array) { + for (int i = 0; i < array.size(); i++) { + if (array.get(i) instanceof ObjectNode statement) { + array.set(i, reordered(statement, STATEMENT_KEY_ORDER)); + } + } + } + try { + return policyWriter.writeValueAsString(ordered); + } catch (JsonProcessingException e) { + throw invalidPolicy(); + } + } + + private static ObjectNode reordered(ObjectNode node, List leadingKeys) { + ObjectNode ordered = node.objectNode(); + for (String key : leadingKeys) { + if (node.has(key)) { + ordered.set(key, node.get(key)); + } + } + for (Map.Entry property : node.properties()) { + if (!ordered.has(property.getKey())) { + ordered.set(property.getKey(), property.getValue()); + } + } + return ordered; + } + + private static void requireParameter(String name, String value) { + if (value == null || value.isEmpty()) { + throw new AwsException("InvalidParameterValue", name + " is required", 400); + } + } + + /** Not found; a missing namespace has the message AWS answers with. */ + private static AwsException resourceNotFound(Kind kind) { + String message = kind == Kind.NAMESPACE ? "The requested namespace doesn't exist." + : "The resource could not be found."; + return new AwsException("ResourceNotFoundFault", message, 404); + } + + private static AwsException invalidPolicy() { + return new AwsException("InvalidPolicyFault", "The resource policy isn't valid.", 400); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java index f4d97aec38..4ecddca446 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/RedshiftService.java @@ -968,6 +968,29 @@ public class RedshiftService implements ManagedSecretRotator { return clusters.scan(k -> true); } + /** The caller's cluster an ARN names, when the ARN is exactly that cluster's in this Region. */ + public Optional findClusterByArn(String clusterArn) { + if (!AwsArnUtils.looksLikeArn(clusterArn)) { + return Optional.empty(); + } + AwsArnUtils.Arn arn = AwsArnUtils.parse(clusterArn); + if (!"redshift".equals(arn.service()) || !arn.resource().startsWith("cluster:")) { + return Optional.empty(); + } + String identifier = arn.resource().substring("cluster:".length()); + return clusters.get(identifier).filter(cluster -> clusterArn.equals(clusterArn(identifier))); + } + + /** Sets, or with {@code null} removes, the resource policy of the caller's cluster an ARN names. */ + public synchronized Optional setClusterResourcePolicy(String clusterArn, String policy) { + Optional cluster = findClusterByArn(clusterArn); + cluster.ifPresent(found -> { + found.setResourcePolicy(policy); + clusters.put(found.getClusterIdentifier(), found); + }); + return cluster; + } + public List describeClustersForAccount(String accountId, String identifier) { if (identifier != null) { Optional cluster = clusters.getForAccount(accountId, identifier); diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/model/Cluster.java b/src/main/java/io/github/hectorvent/floci/services/redshift/model/Cluster.java index c0b18f60cc..12ec34c5e3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/model/Cluster.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/model/Cluster.java @@ -149,4 +149,10 @@ public class Cluster { public Map getTags() { return tags; } public void setTags(Map tags) { this.tags = tags; } + + /** The resource policy {@code PutResourcePolicy} set, kept with the cluster so it goes with it. */ + private String resourcePolicy; + + public String getResourcePolicy() { return resourcePolicy; } + public void setResourcePolicy(String resourcePolicy) { this.resourcePolicy = resourcePolicy; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java index 2afe91784a..b31270a903 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/RedshiftServerlessService.java @@ -1255,6 +1255,20 @@ public class RedshiftServerlessService implements Resettable { return getWorkgroupTarget(workgroup.getWorkgroupName(), region); } + /** + * Sets, or with {@code null} removes, the Redshift resource policy of the namespace an ARN names, + * and returns the namespace; empty when the Region holds no such namespace. + */ + public synchronized Optional setNamespaceResourcePolicy(String namespaceArn, String region, + String policy) { + Optional namespace = findNamespaceByArn(namespaceArn, region); + namespace.ifPresent(found -> { + found.setResourcePolicy(policy); + namespaces.put(storageKey(region, found.getNamespaceName()), found); + }); + return namespace; + } + /** The workgroup a workgroup name or ARN names in the Region, as the Data API reads either; empty when none. */ public Optional findWorkgroupByNameOrArn(String nameOrArn, String region) { return AwsArnUtils.looksLikeArn(nameOrArn) ? workgroupByArn(nameOrArn, region) diff --git a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/model/Namespace.java b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/model/Namespace.java index 14377a3ba5..86534e2fb5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/model/Namespace.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshiftserverless/model/Namespace.java @@ -57,6 +57,7 @@ public class Namespace { this.status = other.status; this.creationDate = other.creationDate; this.tags = new LinkedHashMap<>(other.tags); + this.resourcePolicy = other.resourcePolicy; } public String getNamespaceName() { @@ -178,4 +179,15 @@ public class Namespace { public void setTags(Map tags) { this.tags = tags; } + + /** The Redshift resource policy {@code PutResourcePolicy} set, kept with the namespace so it goes with it. */ + private String resourcePolicy; + + public String getResourcePolicy() { + return resourcePolicy; + } + + public void setResourcePolicy(String resourcePolicy) { + this.resourcePolicy = resourcePolicy; + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftResourcePolicyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftResourcePolicyIntegrationTest.java new file mode 100644 index 0000000000..20892a881d --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftResourcePolicyIntegrationTest.java @@ -0,0 +1,186 @@ +package io.github.hectorvent.floci.services.redshift; + +import io.github.hectorvent.floci.services.redshiftserverless.RedshiftServerlessService; +import io.github.hectorvent.floci.testing.QueryRequests; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; + +/** + * {@code PutResourcePolicy}, {@code GetResourcePolicy} and {@code DeleteResourcePolicy} on a Redshift + * Serverless namespace, the target {@code aws_redshift_resource_policy} authorizes zero-ETL + * integrations into. + */ +@QuarkusTest +class RedshiftResourcePolicyIntegrationTest { + + private static final String REGION = "us-east-1"; + /** A policy as Terraform's {@code jsonencode} sends it: compact, keys sorted. */ + private static final String POLICY = "{\"Statement\":[{\"Action\":\"redshift:AuthorizeInboundIntegration\"," + + "\"Condition\":{\"StringEquals\":{\"aws:SourceArn\":\"arn:aws:dynamodb:us-east-1:000000000000:table/orders\"}}," + + "\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"redshift.amazonaws.com\"},\"Resource\":\"*\"}]," + + "\"Version\":\"2012-10-17\"}"; + /** The same policy as AWS returns it: its key order, pretty-printed. */ + private static final String STORED_POLICY = """ + { + "Version" : "2012-10-17", + "Statement" : [ { + "Effect" : "Allow", + "Principal" : { + "Service" : "redshift.amazonaws.com" + }, + "Action" : "redshift:AuthorizeInboundIntegration", + "Resource" : "*", + "Condition" : { + "StringEquals" : { + "aws:SourceArn" : "arn:aws:dynamodb:us-east-1:000000000000:table/orders" + } + } + } ] + }"""; + + @Inject + RedshiftServerlessService serverless; + + private String namespaceName; + private String namespaceArn; + + @BeforeEach + void createNamespace() { + namespaceName = "policy-" + UUID.randomUUID().toString().substring(0, 8); + namespaceArn = serverless.createNamespace(namespaceName, "admin", "dev", null, null, List.of(), List.of(), + Map.of(), REGION).getNamespaceArn(); + } + + @AfterEach + void deleteNamespace() { + if (namespaceName != null) { + try { + serverless.deleteNamespace(namespaceName, REGION); + } catch (RuntimeException ignored) { + // Safe to ignore: the test deleted the namespace itself. + } + } + } + + @Test + void aNamespacePolicyIsPutReadReplacedAndDeleted() { + redshift("PutResourcePolicy", "ResourceArn", namespaceArn, "Policy", POLICY) + .statusCode(200) + .body("PutResourcePolicyResponse.PutResourcePolicyResult.ResourcePolicy.ResourceArn", + equalTo(namespaceArn)) + .body("PutResourcePolicyResponse.PutResourcePolicyResult.ResourcePolicy.Policy", + equalTo(STORED_POLICY)); + redshift("GetResourcePolicy", "ResourceArn", namespaceArn) + .statusCode(200) + .body("GetResourcePolicyResponse.GetResourcePolicyResult.ResourcePolicy.ResourceArn", + equalTo(namespaceArn)) + .body("GetResourcePolicyResponse.GetResourcePolicyResult.ResourcePolicy.Policy", + equalTo(STORED_POLICY)); + + redshift("PutResourcePolicy", "ResourceArn", namespaceArn, "Policy", + POLICY.replace("AuthorizeInboundIntegration", "CreateInboundIntegration")).statusCode(200); + redshift("GetResourcePolicy", "ResourceArn", namespaceArn) + .statusCode(200) + .body("GetResourcePolicyResponse.GetResourcePolicyResult.ResourcePolicy.Policy", + equalTo(STORED_POLICY.replace("AuthorizeInboundIntegration", "CreateInboundIntegration"))); + + redshift("DeleteResourcePolicy", "ResourceArn", namespaceArn) + .statusCode(200) + .body(containsString("ResourceNotFoundFault")); + redshift("DeleteResourcePolicy", "ResourceArn", namespaceArn) + .statusCode(404) + .body(containsString("ResourceNotFoundFault")); + } + + @Test + void tagsAndUpdatesOnTheNamespaceKeepItsPolicy() { + redshift("PutResourcePolicy", "ResourceArn", namespaceArn, "Policy", POLICY).statusCode(200); + + serverless.tagResource(namespaceArn, Map.of("team", "data"), REGION); + serverless.untagResource(namespaceArn, List.of("team"), REGION); + serverless.updateNamespace(namespaceName, null, null, null, null, List.of("userlog"), REGION); + + redshift("GetResourcePolicy", "ResourceArn", namespaceArn) + .statusCode(200) + .body("GetResourcePolicyResponse.GetResourcePolicyResult.ResourcePolicy.Policy", + equalTo(STORED_POLICY)); + } + + @Test + void deletingTheNamespaceDeletesItsPolicy() { + redshift("PutResourcePolicy", "ResourceArn", namespaceArn, "Policy", POLICY).statusCode(200); + + serverless.deleteNamespace(namespaceName, REGION); + + redshift("GetResourcePolicy", "ResourceArn", namespaceArn) + .statusCode(404) + .body(containsString("ResourceNotFoundFault")); + } + + @Test + void invalidPoliciesUnknownResourcesAndOtherResourceTypesAreRefused() { + redshift("PutResourcePolicy", "ResourceArn", namespaceArn, "Policy", "not json") + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidPolicyFault")); + redshift("PutResourcePolicy", "ResourceArn", namespaceArn, "Policy", "[]") + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidPolicyFault")); + + String namespaces = namespaceArn.substring(0, namespaceArn.lastIndexOf('/') + 1); + String unknownNamespace = namespaces + "00000000-0000-0000-0000-000000000000"; + // An empty policy is refused before the resource is looked up, as AWS does; a valid policy on + // the same missing namespace is the control. + redshift("PutResourcePolicy", "ResourceArn", unknownNamespace, "Policy", "{}") + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidPolicyFault")); + redshift("PutResourcePolicy", "ResourceArn", namespaceArn, "Policy", " { } ") + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidPolicyFault")); + refused("PutResourcePolicy", unknownNamespace, 404, + "ResourceNotFoundFault", "The requested namespace doesn't exist."); + refused("GetResourcePolicy", unknownNamespace, 404, + "ResourceNotFoundFault", "The requested namespace doesn't exist."); + refused("PutResourcePolicy", namespaces + "not-a-uuid", 400, + "InvalidParameterValue", "The format of the provided identifier is invalid."); + refused("GetResourcePolicy", namespaceArn.replace(REGION, "eu-west-1"), 400, "InvalidParameterValue", + "The Region in the ARN doesn't match the current Region. Change your current Region to the same " + + "Region in your resource ARN."); + refused("PutResourcePolicy", "arn:aws:redshift:us-east-1:000000000000:cluster:no-such-cluster", 404, + "ResourceNotFoundFault", "The resource could not be found."); + + refused("GetResourcePolicy", namespaceArn.replace(":namespace/", ":workgroup/"), 400, + "InvalidParameterValue", + "Resource type workgroup isn't supported for the resource policy. Choose another resource type."); + refused("PutResourcePolicy", "arn:aws:redshift:us-east-1:000000000000:snapshot:warehouse/nightly", 400, + "InvalidParameterValue", + "Resource type snapshot isn't supported for the resource policy. Choose another resource type."); + } + + private static void refused(String action, String resourceArn, int status, String code, String message) { + redshift(action, "ResourceArn", resourceArn, "Policy", POLICY) + .statusCode(status) + .body("ErrorResponse.Error.Code", equalTo(code)) + .body("ErrorResponse.Error.Message", equalTo(message)); + } + + private static ValidatableResponse redshift(String action, String... params) { + return QueryRequests.request("test", "redshift", action, params) + .formParam("Version", "2012-12-01") + .when().post("/") + .then(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java index c0f7e916e5..641eae1a7b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftServiceTest.java @@ -344,6 +344,23 @@ class RedshiftServiceTest { verifyNoInteractions(cm); } + @Test + void aClusterIsFoundOnlyByItsOwnArnAndKeepsTheResourcePolicySetOnIt() { + Cluster cluster = lifecycleCluster("available"); + String arn = "arn:aws:redshift:us-east-1:111111111111:cluster:warehouse"; + + assertTrue(service.findClusterByArn(arn).isPresent()); + for (String other : List.of("arn:aws:redshift:us-east-1:222222222222:cluster:warehouse", + "arn:aws:redshift:eu-west-1:111111111111:cluster:warehouse", + "arn:aws:redshift:us-east-1:111111111111:snapshot:warehouse/nightly")) { + assertTrue(service.findClusterByArn(other).isEmpty(), other); + } + + service.setClusterResourcePolicy(arn, "{\"Version\":\"2012-10-17\"}"); + assertEquals("{\"Version\":\"2012-10-17\"}", cluster.getResourcePolicy()); + verify(clusterBackend).put("warehouse", cluster); + } + private Cluster lifecycleCluster(String status) { Cluster cluster = new Cluster(); cluster.setClusterIdentifier("warehouse");