feat(redshift): implement snapshot copy grant lifecycle (#3628)

* feat(redshift): implement snapshot copy grant lifecycle

Terraform's aws_redshift_snapshot_copy_grant needs the full CRUD, and all
three actions returned InvalidAction. Add CreateSnapshotCopyGrant,
DescribeSnapshotCopyGrants and DeleteSnapshotCopyGrant to the Query handler,
backed by a new storage map on RedshiftService.

The grant name is the key: a duplicate create raises
SnapshotCopyGrantAlreadyExistsFault, and describe-by-name or delete of a
missing grant raises SnapshotCopyGrantNotFoundFault. Describe without a name
returns every grant. KmsKeyId is optional and defaults to the account's
AWS-managed Redshift key alias ARN, mirroring how Ec2EbsEncryptionService
stands in for a default key.

Tags ride along on create, since the CLI sends them inline as
Tags.Tag.N.Key/.Value on this action rather than via CreateTags, and
snapshotcopygrant ARNs now resolve in the tagging operations alongside the
other Redshift resource types.

* test(redshift): cover snapshot copy grants through the real SDK

* fix(redshift): paginate DescribeSnapshotCopyGrants

The action returned every grant in one page and ignored MaxRecords and
Marker, so a client with more grants than fit in a page had no way to walk
them.

Page through the shared Pagination helper, which sorts by the grant name and
encodes the last returned name as an opaque base64 cursor, so ordering is
stable and a marker stays resumable when grants are created or deleted
between pages. Marker is emitted only while further pages remain, which is
what tells a paginating client to stop.

MaxRecords follows the Redshift model: default 100, and a value outside
20 to 100 is rejected with InvalidParameterValue rather than clamped.

The model documents SnapshotCopyGrantName and Marker as mutually exclusive
but declares no error for sending both, so this filters by name and then
paginates instead of rejecting the pair. A name matches at most one grant,
which fits in any page.

* fix(redshift): enforce the SnapshotCopyGrantName contract

AWS validates SnapshotCopyGrantName as 1-63 characters, first a lowercase
letter, then lowercase letters, digits or single hyphens with no trailing
or doubled hyphen. Create accepted anything non-blank, so names Redshift
rejects (1grant, Grant, grant--copy, grant-, 64 characters) persisted
locally and diverged from AWS.

Validate in RedshiftService before persistence, matching the existing
snapshot identifier check, and answer InvalidParameterValue as the rest of
the handler does.

* fix(redshift): return 400 for SnapshotCopyGrantNotFoundFault on Describe and Delete

AWS documents SnapshotCopyGrantNotFoundFault as HTTP 400 in the error tables
for both DescribeSnapshotCopyGrants and DeleteSnapshotCopyGrant; we returned
404. Two existing wire-level assertions in RedshiftOperationsTest pinned the
wrong status, so they move with the code, and the unit tests now assert the
status alongside the error code.

The third throw site, in the tagging helper, deliberately stays 404: the
status belongs to the action rather than the fault code, and that path is
reached only from CreateTags/DeleteTags/DescribeTags, whose documented
missing-resource error is ResourceNotFoundFault at 404. A regression pins
that, and a comment says why the two differ.

Refs:
https://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeSnapshotCopyGrants.html
https://docs.aws.amazon.com/redshift/latest/APIReference/API_DeleteSnapshotCopyGrant.html
https://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateTags.html

* fix(redshift): serialize grant create/delete, and use ResourceNotFoundFault on the tag path

Two findings from the latest review round.

createSnapshotCopyGrant checked the name was free and then wrote, with nothing
between the two steps, so two concurrent creates of one name could both succeed
and the second would overwrite the first. create and delete are now synchronized,
as createCluster and modifyCluster already are. The new wire-level test holds two
threads on a latch and releases them into the same name: it fails on every run
without the keyword (3/3 locally) and passes with it, so it pins the lock rather
than describing it.

The tagging path threw SnapshotCopyGrantNotFoundFault with HTTP 404. Both halves
of that pairing cannot be right at once: botocore's Redshift model gives that
shape httpStatusCode 400, and an error shape's status is a property of the shape,
not of the calling action. But 404 is the correct status here, because
CreateTags/DeleteTags/DescribeTags do not list that fault at all -- they document
ResourceNotFoundFault, modelled at 404, for any missing resource. So the status
stays and the code changes. That also explains why the three sibling cases in the
same switch are already consistent: ClusterNotFound, ClusterSnapshotNotFound and
ClusterParameterGroupNotFound are each modelled at 404 themselves.

Describe and Delete still return SnapshotCopyGrantNotFoundFault at 400, which is
what those two actions document.

Docs gain a short section on the grant surface: the alias-ARN KmsKeyId default,
the unvalidated tag limits, and why a missing grant reports two different faults
depending on which action you reach it through.

* style(test): name the new snapshot copy grant tests without the testX prefix

AGENTS.md: "Name test methods either as a camelCase sentence or as
method_scenario_expectation. Both are established. testX names are common in
older tests and are not the pattern to copy." The 31 tests this PR adds to
src/test all used testX because the three Redshift files they landed in are
unusually full of it -- 7/7, 30/50 and 69/104 -- but that is the local exception,
not the repo convention, and the rule is explicit about not copying it.

Renames only; no test body changes. The two new tests in
compatibility-tests/sdk-test-java keep testX: that module has the opposite idiom
and AGENTS.md says to follow the module you are in, and all five methods in that
file, three of them pre-existing, are named that way.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-21 18:31:00 -04:00
1 parent 2e038b5cfb
commit 2af7ed71a7
9 files changed
+1114 -3

No files matched your search

@@ -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<String> snapshotsToCleanup = new ArrayList<>();
private static final List<String> parameterGroupsToCleanup = new ArrayList<>();
private static final List<String> subnetGroupsToCleanup = new ArrayList<>();
private static final List<String> 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<String> 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;
+19 -1
View File
@@ -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 |
<!-- floci:actions:end -->
### 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:<region>:<account>: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
@@ -608,6 +608,7 @@ public class AwsQueryController {
"CreateClusterParameterGroup", "DescribeClusterParameterGroups", "DescribeClusterParameters", "DeleteClusterParameterGroup",
"ModifyClusterParameterGroup",
"CreateClusterSubnetGroup", "DescribeClusterSubnetGroups", "ModifyClusterSubnetGroup", "DeleteClusterSubnetGroup",
"CreateSnapshotCopyGrant", "DescribeSnapshotCopyGrants", "DeleteSnapshotCopyGrant",
"CreateTags", "DeleteTags", "DescribeTags",
"GetClusterCredentials", "GetClusterCredentialsWithIAM"
);
@@ -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<SnapshotCopyGrant> 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<String, String> 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")
@@ -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<Integration> integrations;
private final AccountAwareStorageBackend<SnapshotCopyGrant> 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<Map<String, ClusterParameterGroup>>() {});
this.subnetGroups = storageFactory.create("redshift", "redshift-subnet-groups.json", new TypeReference<Map<String, ClusterSubnetGroup>>() {});
this.integrations = storageFactory.create("redshift", "redshift-integrations.json", new TypeReference<Map<String, Integration>>() {});
this.snapshotCopyGrants = storageFactory.create("redshift", "redshift-snapshot-copy-grants.json", new TypeReference<Map<String, SnapshotCopyGrant>>() {});
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<String, String> 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.
*
* <p>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<SnapshotCopyGrant> 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<SnapshotCopyGrant> 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:<region>:<account>:<type>:<id>},
* where {@code <type>} is one of {@code cluster}, {@code snapshot} (id shape
* {@code <clusterId>/<snapshotId>}), or {@code parametergroup}. Unlike RDS's tag
* {@code <clusterId>/<snapshotId>}), {@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);
};
@@ -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<String, String> 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<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
}
@@ -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("<SnapshotCopyGrantName>copy-grant-1</SnapshotCopyGrantName>"))
.body(containsString("<KmsKeyId>key-abc</KmsKeyId>"))
.body(containsString("<Key>env</Key>"));
// 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("<KmsKeyId>arn:aws:kms:us-east-1:"))
.body(containsString(":alias/aws/redshift</KmsKeyId>"));
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("<SnapshotCopyGrantName>copy-grant-1</SnapshotCopyGrantName>"))
.body(not(containsString("<SnapshotCopyGrantName>copy-grant-2</SnapshotCopyGrantName>")));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DescribeSnapshotCopyGrants")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<SnapshotCopyGrantName>copy-grant-1</SnapshotCopyGrantName>"))
.body(containsString("<SnapshotCopyGrantName>copy-grant-2</SnapshotCopyGrantName>"));
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<String> 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<String> 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("<Marker>"), "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("<SnapshotCopyGrantName>" + invalid + "</SnapshotCopyGrantName>")));
}
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("<SnapshotCopyGrantName>" + maxLength + "</SnapshotCopyGrantName>"));
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("<SnapshotCopyGrantName>race-grant</SnapshotCopyGrantName>", -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);
}
}
@@ -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<String, String> 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("<CreateSnapshotCopyGrantResult>"));
assertTrue(xml.contains("<SnapshotCopyGrantName>grant-1</SnapshotCopyGrantName>"));
assertTrue(xml.contains("<KmsKeyId>key-abc</KmsKeyId>"));
assertTrue(xml.contains("<RequestId>test-req-id</RequestId>"));
}
@Test
void createSnapshotCopyGrantAcceptsNamedMemberTags() {
// Real Redshift SDK sends "Tags.Tag.N.Key/.Value" on CreateSnapshotCopyGrant.
MultivaluedMap<String, String> 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<Map<String, String>> 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("<Key>env</Key>"));
assertTrue(xml.contains("<Value>prod</Value>"));
}
@Test
void createSnapshotCopyGrantRequiresName() {
MultivaluedMap<String, String> 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<String, String> 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("<SnapshotCopyGrants>"));
assertTrue(xml.contains("<SnapshotCopyGrantName>grant-1</SnapshotCopyGrantName>"));
assertTrue(xml.contains("</SnapshotCopyGrants>"));
assertFalse(xml.contains("<Marker>"), "a single full page must not advertise a marker");
}
@Test
void describeSnapshotCopyGrantsWithoutNameListsAll() {
MultivaluedMap<String, String> 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("<SnapshotCopyGrantName>grant-a</SnapshotCopyGrantName>"));
assertTrue(xml.contains("<SnapshotCopyGrantName>grant-b</SnapshotCopyGrantName>"));
}
@Test
void describeSnapshotCopyGrantsForwardsMaxRecordsAndMarker() {
MultivaluedMap<String, String> 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<String, String> 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("<Marker>Z3JhbnQtMjA</Marker>"));
}
@Test
void describeSnapshotCopyGrantsRejectsNonNumericMaxRecords() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("MaxRecords", "many");
AwsException ex = assertThrows(
AwsException.class,
() -> handler.handle("DescribeSnapshotCopyGrants", params));
assertEquals("InvalidParameterValue", ex.getErrorCode());
}
@Test
void deletesSnapshotCopyGrant() {
MultivaluedMap<String, String> 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("<DeleteSnapshotCopyGrantResponse>"));
}
@Test
void deleteSnapshotCopyGrantRequiresName() {
MultivaluedMap<String, String> 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<String, String> params = new MultivaluedHashMap<>();
@@ -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<String> snapshotDumpBackend;
private AccountAwareStorageBackend<ClusterParameterGroup> parameterGroupBackend;
private AccountAwareStorageBackend<ClusterSubnetGroup> subnetGroupBackend;
private AccountAwareStorageBackend<SnapshotCopyGrant> snapshotCopyGrantBackend;
private AccountAwareStorageBackend<Integration> 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.<Snapshot>create(eq("redshift"), eq("redshift-snapshots.json"), any())).thenReturn(snapshotBackend);
when(sf.<ClusterParameterGroup>create(eq("redshift"), eq("redshift-parameter-groups.json"), any())).thenReturn(parameterGroupBackend);
when(sf.<ClusterSubnetGroup>create(eq("redshift"), eq("redshift-subnet-groups.json"), any())).thenReturn(subnetGroupBackend);
when(sf.<SnapshotCopyGrant>create(eq("redshift"), eq("redshift-snapshot-copy-grants.json"), any())).thenReturn(snapshotCopyGrantBackend);
when(sf.<Integration>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<SnapshotCopyGrant> 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<SnapshotCopyGrant> 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<SnapshotCopyGrant> 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<SnapshotCopyGrant> 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<SnapshotCopyGrant> 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<SnapshotCopyGrant> 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<SnapshotCopyGrant> 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<SnapshotCopyGrant> 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;