diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftOperationsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftOperationsTest.java index 77b45fd550..8e07d449eb 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftOperationsTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RedshiftOperationsTest.java @@ -17,11 +17,14 @@ import software.amazon.awssdk.services.redshift.model.CreateClusterResponse; import software.amazon.awssdk.services.redshift.model.CreateClusterSnapshotRequest; import software.amazon.awssdk.services.redshift.model.CreateClusterSnapshotResponse; import software.amazon.awssdk.services.redshift.model.CreateClusterSubnetGroupRequest; +import software.amazon.awssdk.services.redshift.model.CreateSnapshotCopyGrantRequest; +import software.amazon.awssdk.services.redshift.model.CreateSnapshotCopyGrantResponse; import software.amazon.awssdk.services.redshift.model.CreateTagsRequest; import software.amazon.awssdk.services.redshift.model.DeleteClusterParameterGroupRequest; import software.amazon.awssdk.services.redshift.model.DeleteClusterRequest; import software.amazon.awssdk.services.redshift.model.DeleteClusterSnapshotRequest; import software.amazon.awssdk.services.redshift.model.DeleteClusterSubnetGroupRequest; +import software.amazon.awssdk.services.redshift.model.DeleteSnapshotCopyGrantRequest; import software.amazon.awssdk.services.redshift.model.DeleteTagsRequest; import software.amazon.awssdk.services.redshift.model.DescribeClusterParameterGroupsRequest; import software.amazon.awssdk.services.redshift.model.DescribeClusterParameterGroupsResponse; @@ -30,6 +33,8 @@ import software.amazon.awssdk.services.redshift.model.DescribeClusterSnapshotsRe import software.amazon.awssdk.services.redshift.model.DescribeClusterSubnetGroupsRequest; import software.amazon.awssdk.services.redshift.model.DescribeClustersRequest; import software.amazon.awssdk.services.redshift.model.DescribeClustersResponse; +import software.amazon.awssdk.services.redshift.model.DescribeSnapshotCopyGrantsRequest; +import software.amazon.awssdk.services.redshift.model.DescribeSnapshotCopyGrantsResponse; import software.amazon.awssdk.services.redshift.model.DescribeOrderableClusterOptionsRequest; import software.amazon.awssdk.services.redshift.model.DescribeTagsRequest; import software.amazon.awssdk.services.redshift.model.ModifyClusterIamRolesRequest; @@ -39,6 +44,9 @@ import software.amazon.awssdk.services.redshift.model.RebootClusterRequest; import software.amazon.awssdk.services.redshift.model.RestoreFromClusterSnapshotRequest; import software.amazon.awssdk.services.redshift.model.RestoreFromClusterSnapshotResponse; import software.amazon.awssdk.services.redshift.model.Snapshot; +import software.amazon.awssdk.services.redshift.model.SnapshotCopyGrant; +import software.amazon.awssdk.services.redshift.model.SnapshotCopyGrantAlreadyExistsException; +import software.amazon.awssdk.services.redshift.model.SnapshotCopyGrantNotFoundException; import software.amazon.awssdk.services.redshift.model.Tag; import java.sql.Connection; @@ -55,6 +63,7 @@ import java.util.logging.Level; import java.util.logging.Logger; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @DisplayName("Redshift Operations") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @@ -71,6 +80,7 @@ class RedshiftOperationsTest { private static final List snapshotsToCleanup = new ArrayList<>(); private static final List parameterGroupsToCleanup = new ArrayList<>(); private static final List subnetGroupsToCleanup = new ArrayList<>(); + private static final List snapshotCopyGrantsToCleanup = new ArrayList<>(); @BeforeAll static void setup() { @@ -116,6 +126,15 @@ class RedshiftOperationsTest { LOG.log(Level.WARNING, "Failed to clean up Redshift cluster subnet group " + subnetGroupName, e); } } + for (String grantName : snapshotCopyGrantsToCleanup) { + try { + client.deleteSnapshotCopyGrant(DeleteSnapshotCopyGrantRequest.builder() + .snapshotCopyGrantName(grantName) + .build()); + } catch (Exception e) { + LOG.log(Level.WARNING, "Failed to clean up Redshift snapshot copy grant " + grantName, e); + } + } client.close(); } } @@ -339,6 +358,104 @@ class RedshiftOperationsTest { assertThat(rebooted.cluster().clusterStatus()).isEqualTo("available"); } + @Test + @Order(4) + void testSnapshotCopyGrantLifecycle() { + String grantName = TestFixtures.uniqueName("rs-copy-grant"); + String otherGrantName = TestFixtures.uniqueName("rs-copy-grant-other"); + + CreateSnapshotCopyGrantResponse created = client.createSnapshotCopyGrant( + CreateSnapshotCopyGrantRequest.builder() + .snapshotCopyGrantName(grantName) + .kmsKeyId("key-abc") + .tags(Tag.builder().key("env").value("test").build()) + .build()); + snapshotCopyGrantsToCleanup.add(grantName); + + assertThat(created.snapshotCopyGrant().snapshotCopyGrantName()).isEqualTo(grantName); + assertThat(created.snapshotCopyGrant().kmsKeyId()).isEqualTo("key-abc"); + assertThat(created.snapshotCopyGrant().tags()) + .anyMatch(t -> "env".equals(t.key()) && "test".equals(t.value())); + + // KmsKeyId is optional: AWS substitutes the account's default Redshift key. + CreateSnapshotCopyGrantResponse withDefaultKey = client.createSnapshotCopyGrant( + CreateSnapshotCopyGrantRequest.builder() + .snapshotCopyGrantName(otherGrantName) + .build()); + snapshotCopyGrantsToCleanup.add(otherGrantName); + assertThat(withDefaultKey.snapshotCopyGrant().kmsKeyId()).isNotBlank(); + + assertThatThrownBy(() -> client.createSnapshotCopyGrant(CreateSnapshotCopyGrantRequest.builder() + .snapshotCopyGrantName(grantName) + .build())) + .isInstanceOf(SnapshotCopyGrantAlreadyExistsException.class); + + // Filtered describe returns only the named grant, with its fields intact through + // the real unmarshaller. + DescribeSnapshotCopyGrantsResponse filtered = client.describeSnapshotCopyGrants( + DescribeSnapshotCopyGrantsRequest.builder() + .snapshotCopyGrantName(grantName) + .build()); + assertThat(filtered.snapshotCopyGrants()).hasSize(1); + SnapshotCopyGrant found = filtered.snapshotCopyGrants().get(0); + assertThat(found.snapshotCopyGrantName()).isEqualTo(grantName); + assertThat(found.kmsKeyId()).isEqualTo("key-abc"); + assertThat(found.tags()).anyMatch(t -> "env".equals(t.key()) && "test".equals(t.value())); + + DescribeSnapshotCopyGrantsResponse all = client.describeSnapshotCopyGrants( + DescribeSnapshotCopyGrantsRequest.builder().build()); + assertThat(all.snapshotCopyGrants()) + .extracting(SnapshotCopyGrant::snapshotCopyGrantName) + .contains(grantName, otherGrantName); + + client.deleteSnapshotCopyGrant(DeleteSnapshotCopyGrantRequest.builder() + .snapshotCopyGrantName(grantName) + .build()); + snapshotCopyGrantsToCleanup.remove(grantName); + + assertThatThrownBy(() -> client.describeSnapshotCopyGrants(DescribeSnapshotCopyGrantsRequest.builder() + .snapshotCopyGrantName(grantName) + .build())) + .isInstanceOf(SnapshotCopyGrantNotFoundException.class); + + assertThatThrownBy(() -> client.deleteSnapshotCopyGrant(DeleteSnapshotCopyGrantRequest.builder() + .snapshotCopyGrantName(grantName) + .build())) + .isInstanceOf(SnapshotCopyGrantNotFoundException.class); + } + + @Test + @Order(5) + void testSnapshotCopyGrantPaginator() { + String prefix = TestFixtures.uniqueName("rs-page-grant"); + int total = 21; + for (int i = 1; i <= total; i++) { + String name = String.format("%s-%02d", prefix, i); + client.createSnapshotCopyGrant(CreateSnapshotCopyGrantRequest.builder() + .snapshotCopyGrantName(name) + .build()); + snapshotCopyGrantsToCleanup.add(name); + } + + // MaxRecords below the number of grants forces the SDK's paginator to follow a + // Marker, which is the only way to prove the continuation token round-trips. + int pages = 0; + List paged = new ArrayList<>(); + for (DescribeSnapshotCopyGrantsResponse page : client.describeSnapshotCopyGrantsPaginator( + DescribeSnapshotCopyGrantsRequest.builder().maxRecords(20).build())) { + pages++; + page.snapshotCopyGrants().stream() + .map(SnapshotCopyGrant::snapshotCopyGrantName) + .filter(name -> name.startsWith(prefix)) + .forEach(paged::add); + } + + assertThat(pages).isGreaterThan(1); + assertThat(paged).hasSize(total); + assertThat(paged).doesNotHaveDuplicates(); + assertThat(paged).isSorted(); + } + private static Connection awaitPostgresConnection(String host, int port, String username, String password) throws Exception { Instant deadline = Instant.now().plus(Duration.ofSeconds(60)); SQLException last = null; diff --git a/docs/services/redshift.md b/docs/services/redshift.md index acfcf4000b..af0dd94123 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -29,7 +29,7 @@ For running SQL without a PostgreSQL wire connection (the way Lambda and Step Fu | `DescribeClusterParameters` | Return the parameters of a group, with any values set by `ModifyClusterParameterGroup` | | `ModifyClusterParameterGroup` | Update parameter values on a group | | `DeleteClusterParameterGroup` | Remove a parameter group | -| `CreateTags` | Add or overwrite tags on a cluster, snapshot, subnet group or parameter group | +| `CreateTags` | Add or overwrite tags on a cluster, snapshot, subnet group, parameter group or snapshot copy grant | | `DeleteTags` | Remove tags by key from a resource | | `DescribeTags` | List tagged resources and their tags | | `CreateClusterSubnetGroup` | Register a cluster subnet group (metadata only) | @@ -39,6 +39,9 @@ For running SQL without a PostgreSQL wire connection (the way Lambda and Step Fu | `DescribeClusterSubnetGroups` | List subnet groups, optionally filtered by name | | `ModifyClusterSubnetGroup` | Update a subnet group's description or subnet list | | `DeleteClusterSubnetGroup` | Remove a subnet group | +| `CreateSnapshotCopyGrant` | Register a snapshot copy grant, defaulting `KmsKeyId` to the AWS-managed Redshift key. `SnapshotCopyGrantName` must be 1-63 characters, start with a lowercase letter, and contain only lowercase letters, digits and non-consecutive hyphens | +| `DescribeSnapshotCopyGrants` | List snapshot copy grants, optionally filtered by name, paged with `MaxRecords` and `Marker` | +| `DeleteSnapshotCopyGrant` | Remove a snapshot copy grant | | `ModifyCluster` | Update node type, parameter group, security groups, or the master password | | `DescribeClusterVersions` | Return the single emulated engine version and its parameter group family | | `DescribeOrderableClusterOptions` | Return the static node types and cluster types, optionally filtered by `NodeType` or `ClusterVersion` | @@ -48,6 +51,21 @@ For running SQL without a PostgreSQL wire connection (the way Lambda and Step Fu | `GetClusterCredentialsWithIAM` | Issue short-lived credentials with the DbUser derived from the caller's IAM identity | +### Snapshot copy grants + +- **`KmsKeyId` defaults to an alias ARN.** Floci has no per-account AWS-managed key, so + `CreateSnapshotCopyGrant` without `KmsKeyId` stores + `arn:aws:kms:::alias/aws/redshift` where AWS would store the key ARN it + resolves to. The value only has to round-trip through `DescribeSnapshotCopyGrants`, which is + what Terraform reads back. +- **Tag limits are not validated.** The 50-tag count and the AWS key/value length limits are not + enforced on grants, as elsewhere in Floci's Redshift tagging. +- **A missing grant reports different faults on different actions**, because AWS models them + that way. `DescribeSnapshotCopyGrants` and `DeleteSnapshotCopyGrant` return + `SnapshotCopyGrantNotFoundFault`, which the Redshift model pins at HTTP 400. + `CreateTags`/`DeleteTags`/`DescribeTags` do not list that fault at all and return + `ResourceNotFoundFault` (HTTP 404) for any missing resource, grants included. + ## DynamoDB zero-ETL The supported zero-ETL path is DynamoDB Streams to a provisioned Redshift cluster. The source ARN 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 f7b494e003..3f98365fc0 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 @@ -608,6 +608,7 @@ public class AwsQueryController { "CreateClusterParameterGroup", "DescribeClusterParameterGroups", "DescribeClusterParameters", "DeleteClusterParameterGroup", "ModifyClusterParameterGroup", "CreateClusterSubnetGroup", "DescribeClusterSubnetGroups", "ModifyClusterSubnetGroup", "DeleteClusterSubnetGroup", + "CreateSnapshotCopyGrant", "DescribeSnapshotCopyGrants", "DeleteSnapshotCopyGrant", "CreateTags", "DeleteTags", "DescribeTags", "GetClusterCredentials", "GetClusterCredentialsWithIAM" ); 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 6a13d58ae8..97ab0adcc7 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 @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshift; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.XmlBuilder; import io.github.hectorvent.floci.services.redshift.model.Cluster; @@ -10,6 +11,7 @@ import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup; import io.github.hectorvent.floci.services.redshift.model.Integration; import io.github.hectorvent.floci.services.redshift.model.Parameter; import io.github.hectorvent.floci.services.redshift.model.Snapshot; +import io.github.hectorvent.floci.services.redshift.model.SnapshotCopyGrant; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.MediaType; @@ -490,6 +492,67 @@ public class RedshiftQueryHandler { .build(); return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); } + case "CreateSnapshotCopyGrant" -> { + String name = params.getFirst("SnapshotCopyGrantName"); + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterValue", "SnapshotCopyGrantName is required", 400); + } + String kmsKeyId = params.getFirst("KmsKeyId"); + SnapshotCopyGrant grant = service.createSnapshotCopyGrant(name, kmsKeyId, parseTags(params)); + String xml = new XmlBuilder() + .start("CreateSnapshotCopyGrantResponse") + .start("CreateSnapshotCopyGrantResult") + .raw(buildSnapshotCopyGrantXml(grant)) + .end("CreateSnapshotCopyGrantResult") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end("CreateSnapshotCopyGrantResponse") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } + case "DescribeSnapshotCopyGrants" -> { + String name = params.getFirst("SnapshotCopyGrantName"); + Integer maxRecords = parseOptionalInteger(params, "MaxRecords"); + String marker = params.getFirst("Marker"); + PaginatedResult page = service.describeSnapshotCopyGrants(name, maxRecords, marker); + XmlBuilder xmlBuilder = new XmlBuilder() + .start("DescribeSnapshotCopyGrantsResponse") + .start("DescribeSnapshotCopyGrantsResult"); + // AWS returns Marker only while further pages remain, and a paginating client + // stops when it is absent. + if (page.nextToken() != null) { + xmlBuilder.elem("Marker", page.nextToken()); + } + xmlBuilder.start("SnapshotCopyGrants"); + for (SnapshotCopyGrant grant : page.items()) { + xmlBuilder.raw(buildSnapshotCopyGrantXml(grant)); + } + String xml = xmlBuilder + .end("SnapshotCopyGrants") + .end("DescribeSnapshotCopyGrantsResult") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end("DescribeSnapshotCopyGrantsResponse") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } + case "DeleteSnapshotCopyGrant" -> { + String name = params.getFirst("SnapshotCopyGrantName"); + if (name == null || name.isBlank()) { + throw new AwsException("InvalidParameterValue", "SnapshotCopyGrantName is required", 400); + } + service.deleteSnapshotCopyGrant(name); + String xml = new XmlBuilder() + .start("DeleteSnapshotCopyGrantResponse") + .start("ResponseMetadata") + .elem("RequestId", "test-req-id") + .end("ResponseMetadata") + .end("DeleteSnapshotCopyGrantResponse") + .build(); + return Response.ok(xml).type(MediaType.APPLICATION_XML).build(); + } case "ModifyCluster" -> { String clusterIdentifier = params.getFirst("ClusterIdentifier"); if (clusterIdentifier == null || clusterIdentifier.isBlank()) { @@ -809,6 +872,26 @@ public class RedshiftQueryHandler { return builder.end("Subnets").end("ClusterSubnetGroup").build(); } + private String buildSnapshotCopyGrantXml(SnapshotCopyGrant grant) { + XmlBuilder builder = new XmlBuilder() + .start("SnapshotCopyGrant") + .elem("SnapshotCopyGrantName", grant.getSnapshotCopyGrantName()) + .elem("KmsKeyId", grant.getKmsKeyId()); + + if (grant.getTags() != null && !grant.getTags().isEmpty()) { + builder.start("Tags"); + for (Map.Entry tag : grant.getTags().entrySet()) { + builder.start("Tag") + .elem("Key", tag.getKey()) + .elem("Value", tag.getValue()) + .end("Tag"); + } + builder.end("Tags"); + } + + return builder.end("SnapshotCopyGrant").build(); + } + private String buildParameterXml(Parameter param) { XmlBuilder builder = new XmlBuilder() .start("Parameter") 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 8876548bb2..6ee8a0c0e2 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 @@ -4,6 +4,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; 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.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; @@ -23,6 +25,7 @@ import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup; import io.github.hectorvent.floci.services.redshift.model.Endpoint; import io.github.hectorvent.floci.services.redshift.model.Parameter; import io.github.hectorvent.floci.services.redshift.model.Snapshot; +import io.github.hectorvent.floci.services.redshift.model.SnapshotCopyGrant; import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager; import io.github.hectorvent.floci.services.secretsmanager.RandomPasswordGenerator; import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService; @@ -68,6 +71,7 @@ public class RedshiftService { private static final Pattern INTEGRATION_NAME = Pattern.compile(INTEGRATION_NAME_PATTERN); private final AccountAwareStorageBackend integrations; + private final AccountAwareStorageBackend snapshotCopyGrants; private final RedshiftContainerManager containerManager; private final EmulatorConfig config; private final RegionResolver regionResolver; @@ -92,6 +96,7 @@ public class RedshiftService { this.parameterGroups = storageFactory.create("redshift", "redshift-parameter-groups.json", new TypeReference>() {}); this.subnetGroups = storageFactory.create("redshift", "redshift-subnet-groups.json", new TypeReference>() {}); this.integrations = storageFactory.create("redshift", "redshift-integrations.json", new TypeReference>() {}); + this.snapshotCopyGrants = storageFactory.create("redshift", "redshift-snapshot-copy-grants.json", new TypeReference>() {}); this.containerManager = containerManager; this.config = config; this.regionResolver = regionResolver; @@ -1139,6 +1144,95 @@ public class RedshiftService { return group; } + // ── Snapshot Copy Grant Operations ─────────────────────────────────────── + + /** + * AWS-managed Redshift key an account gets when CreateSnapshotCopyGrant omits KmsKeyId. + * Floci has no per-account default key, so the alias ARN stands in for it: the value only + * has to round-trip through Describe, which is what Terraform reads back. + */ + private String defaultSnapshotCopyGrantKey() { + return regionResolver.buildArn("kms", regionResolver.getRegion(), "alias/aws/redshift"); + } + + /** + * AWS constrains a snapshot copy grant name to 1-63 characters, first a lowercase letter, + * then lowercase letters, digits or single hyphens (no trailing or doubled hyphen). Names + * Redshift rejects must not create here either, or Terraform sees a grant that cannot + * exist upstream. + */ + private static void validateSnapshotCopyGrantName(String name) { + if (name == null || !name.matches("[a-z][a-z0-9-]{0,62}") + || name.contains("--") || name.endsWith("-")) { + throw new AwsException("InvalidParameterValue", + "SnapshotCopyGrantName must be 1-63 characters, start with a lowercase letter, " + + "and contain only lowercase letters, digits and non-consecutive hyphens", 400); + } + } + + // synchronized like createCluster: the free-name check and the write must not interleave, + // or two concurrent creates of the same name both succeed and the second overwrites the first. + public synchronized SnapshotCopyGrant createSnapshotCopyGrant(String name, String kmsKeyId, Map tags) { + validateSnapshotCopyGrantName(name); + if (snapshotCopyGrants.get(name).isPresent()) { + throw new AwsException("SnapshotCopyGrantAlreadyExistsFault", + "Snapshot copy grant " + name + " already exists", 400); + } + String effectiveKey = (kmsKeyId != null && !kmsKeyId.isBlank()) ? kmsKeyId : defaultSnapshotCopyGrantKey(); + SnapshotCopyGrant grant = new SnapshotCopyGrant(name, effectiveKey); + if (tags != null && !tags.isEmpty()) { + grant.setTags(new LinkedHashMap<>(tags)); + } + snapshotCopyGrants.put(name, grant); + snapshotCopyGrants.flush(); + return grant; + } + + /** Default and maximum page size AWS documents for DescribeSnapshotCopyGrants. */ + private static final int SNAPSHOT_COPY_GRANT_PAGE_DEFAULT = 100; + private static final int SNAPSHOT_COPY_GRANT_PAGE_MAX = 100; + private static final int SNAPSHOT_COPY_GRANT_PAGE_MIN = 20; + + /** + * Pages grants by name, which is their primary key, so the order is stable across calls + * and a marker stays resumable when grants are created or deleted between pages. + * + *

AWS documents SnapshotCopyGrantName and Marker as mutually exclusive, but models no + * error for sending both, so this filters first and then paginates rather than rejecting + * the combination: a name matches at most one grant, which fits in any page. + */ + public PaginatedResult describeSnapshotCopyGrants(String name, Integer maxRecords, String marker) { + if (maxRecords != null + && (maxRecords < SNAPSHOT_COPY_GRANT_PAGE_MIN || maxRecords > SNAPSHOT_COPY_GRANT_PAGE_MAX)) { + throw new AwsException("InvalidParameterValue", + "MaxRecords must be between " + SNAPSHOT_COPY_GRANT_PAGE_MIN + + " and " + SNAPSHOT_COPY_GRANT_PAGE_MAX + ".", 400); + } + + List matching; + if (name != null && !name.isBlank()) { + SnapshotCopyGrant grant = snapshotCopyGrants.get(name) + .orElseThrow(() -> new AwsException("SnapshotCopyGrantNotFoundFault", + "Snapshot copy grant " + name + " not found", 400)); + matching = List.of(grant); + } else { + matching = snapshotCopyGrants.scan(k -> true); + } + + return Pagination.paginate(matching, SnapshotCopyGrant::getSnapshotCopyGrantName, + maxRecords, marker, SNAPSHOT_COPY_GRANT_PAGE_DEFAULT, SNAPSHOT_COPY_GRANT_PAGE_MAX, + "InvalidParameterValue"); + } + + public synchronized SnapshotCopyGrant deleteSnapshotCopyGrant(String name) { + SnapshotCopyGrant grant = snapshotCopyGrants.get(name) + .orElseThrow(() -> new AwsException("SnapshotCopyGrantNotFoundFault", + "Snapshot copy grant " + name + " not found", 400)); + snapshotCopyGrants.delete(name); + snapshotCopyGrants.flush(); + return grant; + } + // ── Tagging Operations ─────────────────────────────────────────────────── /** A resolved tag target: its current tags plus a sink that persists an updated map. */ @@ -1195,6 +1289,12 @@ public class RedshiftService { "subnetgroup", g.getTags(), tagKeysFilter); } } + if (resourceType == null || "snapshotcopygrant".equalsIgnoreCase(resourceType)) { + for (SnapshotCopyGrant g : snapshotCopyGrants.scan(k -> true)) { + addTaggedResources(result, snapshotCopyGrantArn(g.getSnapshotCopyGrantName()), + "snapshotcopygrant", g.getTags(), tagKeysFilter); + } + } return result; } @@ -1232,12 +1332,17 @@ public class RedshiftService { return regionResolver.buildArn("redshift", regionResolver.getRegion(), "subnetgroup:" + name); } + private String snapshotCopyGrantArn(String name) { + return regionResolver.buildArn("redshift", regionResolver.getRegion(), "snapshotcopygrant:" + name); + } + /** * Resolves a tagging ResourceName to its backing resource. * * Redshift ARNs have the shape {@code arn:aws:redshift::::}, * where {@code } is one of {@code cluster}, {@code snapshot} (id shape - * {@code /}), or {@code parametergroup}. Unlike RDS's tag + * {@code /}), {@code parametergroup}, {@code subnetgroup} or + * {@code snapshotcopygrant}. Unlike RDS's tag * resolution, there is no bare-name fallback — Redshift tagging is new, so there is no * existing caller to stay backward compatible with. */ @@ -1303,6 +1408,23 @@ public class RedshiftService { subnetGroups.flush(); }); } + case "snapshotcopygrant" -> { + // ResourceNotFoundFault, not SnapshotCopyGrantNotFoundFault: this path is only + // reached from CreateTags/DeleteTags/DescribeTags, and those three list + // ResourceNotFoundFault (404) for a missing resource and do not list the + // grant-specific fault at all. The three sibling cases above are consistent + // for the same reason -- ClusterNotFound, ClusterSnapshotNotFound and + // ClusterParameterGroupNotFound are each modelled at 404. The grant fault is + // modelled at 400, so emitting it here would pair a code with a status the + // model never gives it. + SnapshotCopyGrant grant = snapshotCopyGrants.get(id) + .orElseThrow(() -> new AwsException("ResourceNotFoundFault", "Snapshot copy grant " + id + " not found", 404)); + yield new TagHandle(grant.getTags(), updated -> { + grant.setTags(updated); + snapshotCopyGrants.put(id, grant); + snapshotCopyGrants.flush(); + }); + } default -> throw new AwsException("InvalidParameterValue", "Tagging for resource type '" + type + "' is not supported: " + resourceName, 400); }; diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/model/SnapshotCopyGrant.java b/src/main/java/io/github/hectorvent/floci/services/redshift/model/SnapshotCopyGrant.java new file mode 100644 index 0000000000..c149677bae --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/model/SnapshotCopyGrant.java @@ -0,0 +1,27 @@ +package io.github.hectorvent.floci.services.redshift.model; + +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.LinkedHashMap; +import java.util.Map; + +@RegisterForReflection +public class SnapshotCopyGrant { + private String snapshotCopyGrantName; + private String kmsKeyId; + private Map tags = new LinkedHashMap<>(); + + public SnapshotCopyGrant() {} + + public SnapshotCopyGrant(String snapshotCopyGrantName, String kmsKeyId) { + this.snapshotCopyGrantName = snapshotCopyGrantName; + this.kmsKeyId = kmsKeyId; + } + + public String getSnapshotCopyGrantName() { return snapshotCopyGrantName; } + public void setSnapshotCopyGrantName(String snapshotCopyGrantName) { this.snapshotCopyGrantName = snapshotCopyGrantName; } + public String getKmsKeyId() { return kmsKeyId; } + public void setKmsKeyId(String kmsKeyId) { this.kmsKeyId = kmsKeyId; } + public Map getTags() { return tags; } + public void setTags(Map tags) { this.tags = tags; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java index 58ce508562..efbfe27366 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftOperationsTest.java @@ -4,6 +4,7 @@ import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerH import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager; import io.quarkus.test.InjectMock; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; @@ -11,11 +12,21 @@ import org.junit.jupiter.api.TestMethodOrder; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -28,6 +39,11 @@ public class RedshiftOperationsTest { private static final String AUTH_HEADER = "AWS4-HMAC-SHA256 Credential=test/20260822/us-east-1/redshift/aws4_request"; + private static final String GRANT_NAMES_PATH = "DescribeSnapshotCopyGrantsResponse" + + ".DescribeSnapshotCopyGrantsResult.SnapshotCopyGrants.SnapshotCopyGrant.SnapshotCopyGrantName"; + private static final String MARKER_PATH = + "DescribeSnapshotCopyGrantsResponse.DescribeSnapshotCopyGrantsResult.Marker"; + @InjectMock RedshiftContainerManager containerManager; @@ -356,6 +372,268 @@ public class RedshiftOperationsTest { .statusCode(200); } + @Test + @Order(5) + void snapshotCopyGrantLifecycle() { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "CreateSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", "copy-grant-1") + .formParam("KmsKeyId", "key-abc") + .formParam("Tags.Tag.1.Key", "env") + .formParam("Tags.Tag.1.Value", "test") + .when() + .post("/") + .then() + .statusCode(200) + .contentType("application/xml") + .body(containsString("copy-grant-1")) + .body(containsString("key-abc")) + .body(containsString("env")); + + // A grant created without KmsKeyId gets the account's AWS-managed Redshift key. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "CreateSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", "copy-grant-2") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("arn:aws:kms:us-east-1:")) + .body(containsString(":alias/aws/redshift")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "CreateSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", "copy-grant-1") + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("SnapshotCopyGrantAlreadyExistsFault")); + + // Name filter selects one grant, and omitting it returns both. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DescribeSnapshotCopyGrants") + .formParam("SnapshotCopyGrantName", "copy-grant-1") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("copy-grant-1")) + .body(not(containsString("copy-grant-2"))); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DescribeSnapshotCopyGrants") + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("copy-grant-1")) + .body(containsString("copy-grant-2")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DeleteSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", "copy-grant-1") + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DescribeSnapshotCopyGrants") + .formParam("SnapshotCopyGrantName", "copy-grant-1") + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("SnapshotCopyGrantNotFoundFault")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DeleteSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", "copy-grant-1") + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("SnapshotCopyGrantNotFoundFault")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DeleteSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", "copy-grant-2") + .when() + .post("/") + .then() + .statusCode(200); + } + + @Test + @Order(6) + void snapshotCopyGrantPagination() { + // AWS constrains MaxRecords to 20-100, so a two-page walk needs more than 20 grants. + int total = 21; + for (int i = 1; i <= total; i++) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "CreateSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", String.format("pg-grant-%02d", i)) + .when() + .post("/") + .then() + .statusCode(200); + } + + String firstPage = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DescribeSnapshotCopyGrants") + .formParam("MaxRecords", "20") + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + + List firstNames = new XmlPath(firstPage).getList(GRANT_NAMES_PATH); + String marker = new XmlPath(firstPage).getString(MARKER_PATH); + assertEquals(20, firstNames.size()); + assertEquals("pg-grant-01", firstNames.get(0)); + assertEquals("pg-grant-20", firstNames.get(19)); + assertNotNull(marker); + assertFalse(marker.isBlank(), "a non-final page must carry a Marker"); + + String secondPage = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DescribeSnapshotCopyGrants") + .formParam("MaxRecords", "20") + .formParam("Marker", marker) + .when() + .post("/") + .then() + .statusCode(200) + .extract().asString(); + + List secondNames = new XmlPath(secondPage).getList(GRANT_NAMES_PATH); + assertEquals(List.of("pg-grant-21"), secondNames); + // Asserted on the raw body: an absent GPath node can read back as "" rather than null. + assertFalse(secondPage.contains(""), "the final page must not carry a Marker"); + + // Out-of-range MaxRecords is rejected rather than silently clamped. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DescribeSnapshotCopyGrants") + .formParam("MaxRecords", "19") + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("InvalidParameterValue")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DescribeSnapshotCopyGrants") + .formParam("MaxRecords", "101") + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("InvalidParameterValue")); + + for (int i = 1; i <= total; i++) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DeleteSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", String.format("pg-grant-%02d", i)) + .when() + .post("/") + .then() + .statusCode(200); + } + } + + @Test + @Order(7) + void snapshotCopyGrantNameContract() { + String tooLong = "g123456789012345678901234567890123456789012345678901234567890123"; + for (String invalid : List.of("1grant", "Grant", "grant--copy", "grant-", tooLong)) { + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "CreateSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", invalid) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("InvalidParameterValue")); + + // A rejected name must leave nothing behind, read back through Describe. + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DescribeSnapshotCopyGrants") + .formParam("SnapshotCopyGrantName", invalid) + .when() + .post("/") + .then() + .body(not(containsString("" + invalid + ""))); + } + + String maxLength = "g12345678901234567890123456789012345678901234567890123456789012"; + assertEquals(63, maxLength.length()); + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "CreateSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", maxLength) + .when() + .post("/") + .then() + .statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DescribeSnapshotCopyGrants") + .formParam("SnapshotCopyGrantName", maxLength) + .when() + .post("/") + .then() + .statusCode(200) + .body(containsString("" + maxLength + "")); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DeleteSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", maxLength) + .when() + .post("/") + .then() + .statusCode(200); + } + @Test @Order(3) void testTagLifecycle() { @@ -423,4 +701,77 @@ public class RedshiftOperationsTest { .then() .statusCode(200); } + + /** + * CreateSnapshotCopyGrant checks the name is free and then writes. Both steps run under the + * service lock, so of two concurrent creates of one name exactly one wins and the other sees + * SnapshotCopyGrantAlreadyExistsFault -- the loser must not overwrite the winner's grant. + */ + @Test + @Order(8) + void concurrentCreatesOfOneGrantNameLeaveExactlyOneGrant() throws Exception { + int threads = 2; + CountDownLatch release = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(threads); + AtomicInteger created = new AtomicInteger(); + AtomicInteger rejected = new AtomicInteger(); + ExecutorService pool = Executors.newFixedThreadPool(threads); + + try { + for (int i = 0; i < threads; i++) { + pool.execute(() -> { + try { + release.await(); + int status = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "CreateSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", "race-grant") + .when() + .post("/") + .then() + .extract().statusCode(); + if (status == 200) { + created.incrementAndGet(); + } else if (status == 400) { + rejected.incrementAndGet(); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } finally { + done.countDown(); + } + }); + } + release.countDown(); + assertTrue(done.await(30, TimeUnit.SECONDS), "concurrent creates did not finish"); + } finally { + pool.shutdownNow(); + } + + assertEquals(1, created.get(), "exactly one create should succeed"); + assertEquals(1, rejected.get(), "the losing create should be rejected, not silently accepted"); + + String names = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DescribeSnapshotCopyGrants") + .when() + .post("/") + .then() + .statusCode(200) + .extract().body().asString(); + assertEquals(1, names.split("race-grant", -1).length - 1, + "the grant should be stored once"); + + given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", AUTH_HEADER) + .formParam("Action", "DeleteSnapshotCopyGrant") + .formParam("SnapshotCopyGrantName", "race-grant") + .when() + .post("/") + .then() + .statusCode(200); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java index 7b938d8f12..6071d5c8c4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftQueryHandlerTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.redshift; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.redshift.model.Cluster; import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup; @@ -9,6 +10,7 @@ import io.github.hectorvent.floci.services.redshift.model.ClusterSubnetGroup; import io.github.hectorvent.floci.services.redshift.model.Endpoint; import io.github.hectorvent.floci.services.redshift.model.Parameter; import io.github.hectorvent.floci.services.redshift.model.Snapshot; +import io.github.hectorvent.floci.services.redshift.model.SnapshotCopyGrant; import jakarta.ws.rs.core.MultivaluedHashMap; import jakarta.ws.rs.core.MultivaluedMap; import jakarta.ws.rs.core.Response; @@ -428,6 +430,61 @@ class RedshiftQueryHandlerTest { assertEquals("InvalidParameterValue", ex.getErrorCode()); } + @Test + void createsSnapshotCopyGrant() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("SnapshotCopyGrantName", "grant-1"); + params.putSingle("KmsKeyId", "key-abc"); + + when(service.createSnapshotCopyGrant(eq("grant-1"), eq("key-abc"), any())) + .thenReturn(new SnapshotCopyGrant("grant-1", "key-abc")); + + Response response = handler.handle("CreateSnapshotCopyGrant", params); + + assertEquals(200, response.getStatus()); + String xml = (String) response.getEntity(); + assertTrue(xml.contains("")); + assertTrue(xml.contains("grant-1")); + assertTrue(xml.contains("key-abc")); + assertTrue(xml.contains("test-req-id")); + } + + @Test + void createSnapshotCopyGrantAcceptsNamedMemberTags() { + // Real Redshift SDK sends "Tags.Tag.N.Key/.Value" on CreateSnapshotCopyGrant. + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("SnapshotCopyGrantName", "grant-1"); + params.putSingle("Tags.Tag.1.Key", "env"); + params.putSingle("Tags.Tag.1.Value", "prod"); + + SnapshotCopyGrant grant = new SnapshotCopyGrant("grant-1", "key-abc"); + grant.setTags(Map.of("env", "prod")); + when(service.createSnapshotCopyGrant(any(), any(), any())).thenReturn(grant); + + Response response = handler.handle("CreateSnapshotCopyGrant", params); + assertEquals(200, response.getStatus()); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Map.class); + verify(service).createSnapshotCopyGrant(eq("grant-1"), isNull(), captor.capture()); + assertEquals(Map.of("env", "prod"), captor.getValue()); + + String xml = (String) response.getEntity(); + assertTrue(xml.contains("env")); + assertTrue(xml.contains("prod")); + } + + @Test + void createSnapshotCopyGrantRequiresName() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("KmsKeyId", "key-abc"); + + AwsException ex = assertThrows( + AwsException.class, + () -> handler.handle("CreateSnapshotCopyGrant", params)); + assertEquals("InvalidParameterValue", ex.getErrorCode()); + } + @Test void modifyClusterIamRolesAcceptsNamedMemberForm() { // Real Redshift SDK sends "AddIamRoles.IamRoleArn.N" and "RemoveIamRoles.IamRoleArn.N". @@ -496,6 +553,109 @@ class RedshiftQueryHandlerTest { assertEquals("InvalidParameterValue", ex.getErrorCode()); } + @Test + void describesSnapshotCopyGrants() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("SnapshotCopyGrantName", "grant-1"); + + when(service.describeSnapshotCopyGrants(eq("grant-1"), isNull(), isNull())) + .thenReturn(new PaginatedResult<>(List.of(new SnapshotCopyGrant("grant-1", "key-abc")), null)); + + Response response = handler.handle("DescribeSnapshotCopyGrants", params); + + assertEquals(200, response.getStatus()); + String xml = (String) response.getEntity(); + assertTrue(xml.contains("")); + assertTrue(xml.contains("grant-1")); + assertTrue(xml.contains("")); + assertFalse(xml.contains(""), "a single full page must not advertise a marker"); + } + + @Test + void describeSnapshotCopyGrantsWithoutNameListsAll() { + MultivaluedMap params = new MultivaluedHashMap<>(); + + when(service.describeSnapshotCopyGrants(isNull(), isNull(), isNull())) + .thenReturn(new PaginatedResult<>(List.of( + new SnapshotCopyGrant("grant-a", "key-a"), + new SnapshotCopyGrant("grant-b", "key-b")), null)); + + Response response = handler.handle("DescribeSnapshotCopyGrants", params); + + assertEquals(200, response.getStatus()); + String xml = (String) response.getEntity(); + assertTrue(xml.contains("grant-a")); + assertTrue(xml.contains("grant-b")); + } + + @Test + void describeSnapshotCopyGrantsForwardsMaxRecordsAndMarker() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("MaxRecords", "20"); + params.putSingle("Marker", "Z3JhbnQtMjA"); + + when(service.describeSnapshotCopyGrants(isNull(), eq(20), eq("Z3JhbnQtMjA"))) + .thenReturn(new PaginatedResult<>(List.of(new SnapshotCopyGrant("grant-21", "key-a")), null)); + + Response response = handler.handle("DescribeSnapshotCopyGrants", params); + + assertEquals(200, response.getStatus()); + verify(service).describeSnapshotCopyGrants(isNull(), eq(20), eq("Z3JhbnQtMjA")); + } + + @Test + void describeSnapshotCopyGrantsEmitsMarkerWhenMorePagesRemain() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("MaxRecords", "20"); + + when(service.describeSnapshotCopyGrants(isNull(), eq(20), isNull())) + .thenReturn(new PaginatedResult<>( + List.of(new SnapshotCopyGrant("grant-01", "key-a")), "Z3JhbnQtMjA")); + + Response response = handler.handle("DescribeSnapshotCopyGrants", params); + + String xml = (String) response.getEntity(); + assertTrue(xml.contains("Z3JhbnQtMjA")); + } + + @Test + void describeSnapshotCopyGrantsRejectsNonNumericMaxRecords() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("MaxRecords", "many"); + + AwsException ex = assertThrows( + AwsException.class, + () -> handler.handle("DescribeSnapshotCopyGrants", params)); + assertEquals("InvalidParameterValue", ex.getErrorCode()); + } + + @Test + void deletesSnapshotCopyGrant() { + MultivaluedMap params = new MultivaluedHashMap<>(); + params.putSingle("SnapshotCopyGrantName", "grant-1"); + + when(service.deleteSnapshotCopyGrant("grant-1")) + .thenReturn(new SnapshotCopyGrant("grant-1", "key-abc")); + + Response response = handler.handle("DeleteSnapshotCopyGrant", params); + + assertEquals(200, response.getStatus()); + verify(service).deleteSnapshotCopyGrant("grant-1"); + String xml = (String) response.getEntity(); + assertTrue(xml.contains("")); + } + + @Test + void deleteSnapshotCopyGrantRequiresName() { + MultivaluedMap params = new MultivaluedHashMap<>(); + + AwsException ex = assertThrows( + AwsException.class, + () -> handler.handle("DeleteSnapshotCopyGrant", params)); + assertEquals("InvalidParameterValue", ex.getErrorCode()); + verify(service, never()).deleteSnapshotCopyGrant(any()); + } + @Test void testBuildClusterXmlIncludesParameterGroupAndTags() { MultivaluedMap params = new MultivaluedHashMap<>(); 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 dda3f10593..0da8c123a0 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 @@ -2,10 +2,12 @@ package io.github.hectorvent.floci.services.redshift; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator; import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamService; import io.github.hectorvent.floci.services.dynamodb.model.StreamDescription; import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle; @@ -17,12 +19,14 @@ import io.github.hectorvent.floci.services.redshift.model.Endpoint; import io.github.hectorvent.floci.services.redshift.model.Integration; import io.github.hectorvent.floci.services.redshift.model.Parameter; import io.github.hectorvent.floci.services.redshift.model.Snapshot; -import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator; +import io.github.hectorvent.floci.services.redshift.model.SnapshotCopyGrant; import io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager; import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService; import io.github.hectorvent.floci.services.secretsmanager.model.Secret; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import java.nio.file.Files; @@ -50,6 +54,7 @@ class RedshiftServiceTest { private AccountAwareStorageBackend snapshotDumpBackend; private AccountAwareStorageBackend parameterGroupBackend; private AccountAwareStorageBackend subnetGroupBackend; + private AccountAwareStorageBackend snapshotCopyGrantBackend; private AccountAwareStorageBackend integrationBackend; private RedshiftContainerManager cm; private RegionResolver regionResolver; @@ -69,6 +74,7 @@ class RedshiftServiceTest { snapshotDumpBackend = mock(AccountAwareStorageBackend.class); parameterGroupBackend = mock(AccountAwareStorageBackend.class); subnetGroupBackend = mock(AccountAwareStorageBackend.class); + snapshotCopyGrantBackend = mock(AccountAwareStorageBackend.class); integrationBackend = mock(AccountAwareStorageBackend.class); cm = mock(RedshiftContainerManager.class); proxyManager = mock(RedshiftProxyManager.class); @@ -94,6 +100,7 @@ class RedshiftServiceTest { when(sf.create(eq("redshift"), eq("redshift-snapshots.json"), any())).thenReturn(snapshotBackend); when(sf.create(eq("redshift"), eq("redshift-parameter-groups.json"), any())).thenReturn(parameterGroupBackend); when(sf.create(eq("redshift"), eq("redshift-subnet-groups.json"), any())).thenReturn(subnetGroupBackend); + when(sf.create(eq("redshift"), eq("redshift-snapshot-copy-grants.json"), any())).thenReturn(snapshotCopyGrantBackend); when(sf.create(eq("redshift"), eq("redshift-integrations.json"), any())).thenReturn(integrationBackend); when(clusterBackend.accountId()).thenReturn("111111111111"); @@ -1320,6 +1327,231 @@ class RedshiftServiceTest { assertThrows(AwsException.class, () -> service.deleteClusterSubnetGroup("missing")); } + @Test + void createsSnapshotCopyGrant() { + when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.empty()); + + SnapshotCopyGrant grant = service.createSnapshotCopyGrant("my-grant", "key-abc", Map.of()); + + assertEquals("my-grant", grant.getSnapshotCopyGrantName()); + assertEquals("key-abc", grant.getKmsKeyId()); + verify(snapshotCopyGrantBackend).put(eq("my-grant"), any(SnapshotCopyGrant.class)); + verify(snapshotCopyGrantBackend).flush(); + } + + @Test + void createSnapshotCopyGrantDefaultsKmsKeyId() { + when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.empty()); + + SnapshotCopyGrant grant = service.createSnapshotCopyGrant("my-grant", null, Map.of()); + + assertEquals("arn:aws:kms:us-east-1:111111111111:alias/aws/redshift", grant.getKmsKeyId()); + } + + @Test + void createSnapshotCopyGrantStoresTags() { + when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.empty()); + + SnapshotCopyGrant grant = service.createSnapshotCopyGrant("my-grant", "key-abc", Map.of("env", "prod")); + + assertEquals(Map.of("env", "prod"), grant.getTags()); + } + + @Test + void createSnapshotCopyGrantRejectsDuplicateName() { + when(snapshotCopyGrantBackend.get("existing")).thenReturn(Optional.of(new SnapshotCopyGrant())); + + AwsException ex = assertThrows(AwsException.class, () -> + service.createSnapshotCopyGrant("existing", "key-abc", Map.of())); + assertEquals("SnapshotCopyGrantAlreadyExistsFault", ex.getErrorCode()); + verify(snapshotCopyGrantBackend, never()).put(any(), any()); + } + + @ParameterizedTest + @ValueSource(strings = { + "1grant", // must start with a letter + "Grant", // no uppercase + "grant--copy", // no consecutive hyphens + "grant-", // no trailing hyphen + "g123456789012345678901234567890123456789012345678901234567890123" // 64 characters + }) + void createSnapshotCopyGrantRejectsNamesRedshiftRejects(String name) { + when(snapshotCopyGrantBackend.get(name)).thenReturn(Optional.empty()); + + AwsException ex = assertThrows(AwsException.class, () -> + service.createSnapshotCopyGrant(name, "key-abc", Map.of())); + + assertEquals("InvalidParameterValue", ex.getErrorCode()); + assertEquals(400, ex.getHttpStatus()); + verify(snapshotCopyGrantBackend, never()).put(any(), any()); + verify(snapshotCopyGrantBackend, never()).flush(); + } + + @Test + void createSnapshotCopyGrantAcceptsMaximumLengthName() { + String name = "g12345678901234567890123456789012345678901234567890123456789012"; + assertEquals(63, name.length()); + when(snapshotCopyGrantBackend.get(name)).thenReturn(Optional.empty()); + + SnapshotCopyGrant grant = service.createSnapshotCopyGrant(name, "key-abc", Map.of()); + + assertEquals(name, grant.getSnapshotCopyGrantName()); + verify(snapshotCopyGrantBackend).put(eq(name), any(SnapshotCopyGrant.class)); + verify(snapshotCopyGrantBackend).flush(); + } + + @Test + void describeSnapshotCopyGrantsByName() { + SnapshotCopyGrant grant = new SnapshotCopyGrant("my-grant", "key-abc"); + when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.of(grant)); + + List list = service.describeSnapshotCopyGrants("my-grant", null, null).items(); + + assertEquals(1, list.size()); + assertEquals("my-grant", list.get(0).getSnapshotCopyGrantName()); + verify(snapshotCopyGrantBackend, never()).scan(any()); + } + + @Test + void describeSnapshotCopyGrantsReturnsAllWhenNameOmitted() { + when(snapshotCopyGrantBackend.scan(any())).thenReturn(List.of( + new SnapshotCopyGrant("grant-a", "key-a"), + new SnapshotCopyGrant("grant-b", "key-b"))); + + PaginatedResult page = service.describeSnapshotCopyGrants(null, null, null); + + assertEquals(2, page.items().size()); + assertNull(page.nextToken()); + } + + @Test + void describeSnapshotCopyGrantsRejectsMissingGrant() { + when(snapshotCopyGrantBackend.get("missing")).thenReturn(Optional.empty()); + + AwsException ex = assertThrows(AwsException.class, + () -> service.describeSnapshotCopyGrants("missing", null, null)); + assertEquals("SnapshotCopyGrantNotFoundFault", ex.getErrorCode()); + // DescribeSnapshotCopyGrants documents this fault as 400, not 404. + assertEquals(400, ex.getHttpStatus()); + } + + @Test + void describeSnapshotCopyGrantsPagesInNameOrder() { + // 25 grants created out of order: paging must follow name order, not insertion order. + List stored = new ArrayList<>(); + for (int i = 25; i >= 1; i--) { + stored.add(new SnapshotCopyGrant(String.format("grant-%02d", i), "key-" + i)); + } + when(snapshotCopyGrantBackend.scan(any())).thenReturn(stored); + + PaginatedResult first = service.describeSnapshotCopyGrants(null, 20, null); + + assertEquals(20, first.items().size()); + assertEquals("grant-01", first.items().get(0).getSnapshotCopyGrantName()); + assertEquals("grant-20", first.items().get(19).getSnapshotCopyGrantName()); + assertNotNull(first.nextToken()); + + PaginatedResult second = + service.describeSnapshotCopyGrants(null, 20, first.nextToken()); + + assertEquals(5, second.items().size()); + assertEquals("grant-21", second.items().get(0).getSnapshotCopyGrantName()); + assertEquals("grant-25", second.items().get(4).getSnapshotCopyGrantName()); + assertNull(second.nextToken(), "last page must not carry a marker"); + } + + @Test + void describeSnapshotCopyGrantsOmitsMarkerWhenPageExactlyFits() { + List stored = new ArrayList<>(); + for (int i = 1; i <= 20; i++) { + stored.add(new SnapshotCopyGrant(String.format("grant-%02d", i), "key-" + i)); + } + when(snapshotCopyGrantBackend.scan(any())).thenReturn(stored); + + PaginatedResult page = service.describeSnapshotCopyGrants(null, 20, null); + + assertEquals(20, page.items().size()); + assertNull(page.nextToken()); + } + + @Test + void describeSnapshotCopyGrantsRejectsMaxRecordsBelowMinimum() { + AwsException ex = assertThrows(AwsException.class, + () -> service.describeSnapshotCopyGrants(null, 19, null)); + assertEquals("InvalidParameterValue", ex.getErrorCode()); + verify(snapshotCopyGrantBackend, never()).scan(any()); + } + + @Test + void describeSnapshotCopyGrantsRejectsMaxRecordsAboveMaximum() { + AwsException ex = assertThrows(AwsException.class, + () -> service.describeSnapshotCopyGrants(null, 101, null)); + assertEquals("InvalidParameterValue", ex.getErrorCode()); + } + + @Test + void describeSnapshotCopyGrantsAcceptsMarkerAlongsideName() { + // AWS documents the two as mutually exclusive but models no error, so Floci filters + // by name and then paginates rather than rejecting the pair. + SnapshotCopyGrant grant = new SnapshotCopyGrant("my-grant", "key-abc"); + when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.of(grant)); + + PaginatedResult page = + service.describeSnapshotCopyGrants("my-grant", null, null); + + assertEquals(1, page.items().size()); + assertNull(page.nextToken()); + } + + @Test + void deletesSnapshotCopyGrant() { + SnapshotCopyGrant grant = new SnapshotCopyGrant("my-grant", "key-abc"); + when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.of(grant)); + + SnapshotCopyGrant deleted = service.deleteSnapshotCopyGrant("my-grant"); + + assertEquals("my-grant", deleted.getSnapshotCopyGrantName()); + verify(snapshotCopyGrantBackend).delete("my-grant"); + verify(snapshotCopyGrantBackend).flush(); + } + + @Test + void deleteSnapshotCopyGrantRejectsMissingGrant() { + when(snapshotCopyGrantBackend.get("missing")).thenReturn(Optional.empty()); + + AwsException ex = assertThrows(AwsException.class, () -> service.deleteSnapshotCopyGrant("missing")); + assertEquals("SnapshotCopyGrantNotFoundFault", ex.getErrorCode()); + // DeleteSnapshotCopyGrant documents this fault as 400, not 404. + assertEquals(400, ex.getHttpStatus()); + verify(snapshotCopyGrantBackend, never()).delete(any()); + } + + @Test + void createTagsOnSnapshotCopyGrant() { + SnapshotCopyGrant grant = new SnapshotCopyGrant("my-grant", "key-abc"); + when(snapshotCopyGrantBackend.get("my-grant")).thenReturn(Optional.of(grant)); + + service.createTags("arn:aws:redshift:us-east-1:111111111111:snapshotcopygrant:my-grant", + Map.of("env", "prod")); + + assertEquals(Map.of("env", "prod"), + service.listTagsForResource("arn:aws:redshift:us-east-1:111111111111:snapshotcopygrant:my-grant")); + } + + @Test + void createTagsOnMissingSnapshotCopyGrantIsNotFound() { + when(snapshotCopyGrantBackend.get("missing")).thenReturn(Optional.empty()); + + AwsException ex = assertThrows(AwsException.class, + () -> service.createTags("arn:aws:redshift:us-east-1:111111111111:snapshotcopygrant:missing", + Map.of("env", "prod"))); + // ResourceNotFoundFault, not the grant-specific fault: CreateTags/DeleteTags/ + // DescribeTags list ResourceNotFoundFault (404) for a missing resource and never + // list SnapshotCopyGrantNotFoundFault, which the model pins at 400. + assertEquals("ResourceNotFoundFault", ex.getErrorCode()); + assertEquals(404, ex.getHttpStatus()); + } + private static String extractResourceId(String arn) { String resource = arn.substring(arn.lastIndexOf(':') + 1); return resource.contains("/") ? resource.substring(resource.lastIndexOf('/') + 1) : resource;