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

@@ -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;