feat(redshift): implement Redshift emulation with snapshot and parameter group support (#2472)

* feat: add redshift domain models

* feat: add redshift service and test

* feat: add redshift query handler and routing

* feat(redshift): implement data plane container manager and wire storage

This commit implements Redshift Container Manager, wires the StorageFactory into RedshiftService, uses AwsException for error handling, implements Describe/Delete Clusters, and adds integration tests with AWS SDK in the compatibility tests project.

* feat: add redshift operations models and service logic

* fix: correct yaml indentation for redshift storage config

* fix: remove invalid redshift storage properties

* feat: implement pg_dump and psql for redshift snapshots

* feat: add redshift core operations query actions

* test: add redshift operations integration test

* fix(redshift): Write snapshot SQL dumps to file storage and add Parameter model

* docs: add redshift implementation plan, design spec, and PR description

* chore: remove superpowers working files

* fix(redshift): scope snapshots and cluster recovery per account, restore original password

- Scope snapshot SQL dump files under redshift-dumps/{accountId}/ so
  same-identifier snapshots from different accounts no longer collide,
  overwrite, or delete each other's data.
- Restore uses the source cluster's real master password instead of a
  hardcoded value, falling back to "admin" only when the source cluster
  no longer exists.
- Recreate Docker containers for all persisted "available" clusters on
  startup, across every account (not just the default), fixing clusters
  that were reloaded with stale endpoints but no running container.
- Add AccountAwareStorageBackend.accountId() accessor needed for the
  account-scoped dump path.

* fix(redshift): add logging for cleanup failures in RedshiftOperationsTest

* fix(redshift): scope container identity per account, persist snapshot password

- RedshiftContainerManager now keys its in-memory container map and Docker
  container name by accountId + clusterIdentifier, instead of just the
  cluster identifier. Previously two accounts creating a cluster with the
  same identifier would share (and clobber) the same Docker container,
  so startup recovery for the second account silently skipped its own
  cluster and left it advertised with a stale endpoint.
- Snapshot now captures masterPassword at snapshot-creation time, so
  restoreFromClusterSnapshot can recover the original credential even
  after the source cluster has been deleted, instead of falling back to
  "admin".
- Clean up fully-qualified java.nio.file / commons-compress references in
  RedshiftContainerManager in favor of imports.

* feat(redshift): implement adoptOrStart method to reuse existing containers

* chore: gitignore subagent-driven-development scratch workspace

* feat(redshift): add tagging support to RedshiftService

- Add tags field to Cluster, Snapshot, and ClusterParameterGroup models
- Inject RegionResolver into RedshiftService constructor
- Implement tag CRUD methods: createTags, deleteTags, describeTags, listTagsForResource
- Add resolveTagHandle ARN resolver for tagging operations
- Add 6 new unit tests covering tag operations and error cases

* feat(redshift): wire CreateTags/DeleteTags/DescribeTags into the query handler

* feat(redshift): store real parameter values on ClusterParameterGroup

* fix(redshift): use proper imports and preserve parameter metadata on modify

* feat(redshift): wire ModifyClusterParameterGroup, return real DescribeClusterParameters values

* feat(redshift): add ClusterSubnetGroup model and CRUD

* feat(redshift): wire ClusterSubnetGroup CRUD into the query handler

* feat(redshift): add ClusterSubnetGroupName/VpcSecurityGroupIds metadata to Cluster

* feat(redshift): add RedshiftContainerManager.alterUserPassword

* fix(redshift): prevent SQL injection in alterUserPassword via username validation

* feat(redshift): add RedshiftService.modifyCluster

* feat(redshift): add RedshiftService.rebootCluster (dump/restore based, no data loss)

* feat(redshift): wire ModifyCluster/RebootCluster into the query handler

* test(redshift): add compatibility coverage for tagging, subnet groups, modify/reboot

* fix(redshift): use imports and unique names in compatibility test

Follow this file's established conventions: proper imports instead of
fully-qualified SDK types, and TestFixtures.uniqueName() instead of
hardcoded resource names, matching the pattern used by the sibling
test methods.

* fix(redshift): address final whole-branch review findings

* fix(redshift): address PR review feedback and green the CI

Review comments:
- Translate three Vietnamese comments in RedshiftContainerManager and
  RedshiftService to English (repo is English-only).
- alterUserPassword: reword the single-quote guard to cite the AWS
  ModifyCluster MasterUserPassword constraint rather than the psql SQL
  literal, and enforce the full documented set for parity — reject
  ' " \ / @, require length 8-64 and at least one upper/lower/digit.
- adoptOrStart: LOG.warnv on the container-gone branch so a fresh empty
  cluster after a lost container is a searchable line, not a silent one.
- Move the .superpowers/ scratch ignore from the shared .gitignore to
  .git/info/exclude (local tooling, not project output).

CI failures:
- Register redshift.model.Parameter for reflection so
  PersistedModelReflectionTest passes and native-image persistence works
  (fixes CI shard 3 and the native sdk-test-java compat run).
- Convert RedshiftQueryHandler.handle() from an if/else chain to
  switch (action) so the docs action-table generator can extract the
  action list, matching every other Query handler. Bodies unchanged.
- Register redshift in tools/docs/services.yaml, add docs/services/redshift.md
  with the generated action table, and add the Service Matrix row in
  docs/services/index.md (fixes Docs Action Tables / Action tables in sync).

* fix(redshift): reject path traversal in SnapshotIdentifier

createSnapshot spliced the request's SnapshotIdentifier straight into a
host path (<persistentPath>/redshift-dumps/<accountId>/<id>.sql). A value
with traversal segments or an absolute prefix escaped the account dump
directory: snapshot creation would write pg_dump output over an arbitrary
host file, and the resulting absolute path was persisted so a later
restore (arbitrary read into an attacker-controlled DB) or delete
(arbitrary unlink) trusted it.

- validateSnapshotIdentifier: enforce AWS's format (1-255 chars, leading
  letter, letters/digits/non-consecutive hyphens) — rejects '.', '/', '\'
  so no separator can appear.
- Keep a normalise + startsWith(dumpDir) containment check as defence in
  depth.
- restore/delete now verify the stored sqlDump path still resolves inside
  the account dump dir before touching it, so a path written by the
  pre-fix code can't be acted on.

Also replace inline java.* fully-qualified names in RedshiftService and
RedshiftQueryHandler with top-of-file imports.

* fix(redshift): validate snapshot dump path before restore provisioning

The trusted-dump-path check added in the previous commit ran inside the
try block, after restoreFromClusterSnapshot had already persisted the
target cluster as "creating" and started its container. Rejecting an
untrusted path then left the container running and a "failed" cluster
record behind, blocking a retry with the same identifier
(ClusterAlreadyExists).

Move the check ahead of all provisioning — right after the snapshot is
loaded, before clusters.put and containerManager.start — so a rejected
restore creates no resources.

---------

Signed-off-by: Vũ Thế Huy <31652864+vuthehuyht@users.noreply.github.com>
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-08-29 15:25:02 -04:00
1 parent 08e532ab1a
commit a1383fdd3d
29 files changed
+4600

No files matched your search

@@ -12,6 +12,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class AccountAwareStorageBackendTest {
@Test
void accountIdReturnsDefaultOutsideRequestScope() {
AccountAwareStorageBackend<String> storage =
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, "111111111111");
assertEquals("111111111111", storage.accountId());
}
@Test
void guardedLegacyLookupMigratesMatchingRawValue() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
@@ -0,0 +1,371 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class RedshiftOperationsTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260822/us-east-1/redshift/aws4_request";
@InjectMock
RedshiftContainerManager containerManager;
@Test
@Order(1)
void testParameterGroupLifecycle() {
// 1. CreateClusterParameterGroup
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "CreateClusterParameterGroup")
.formParam("ParameterGroupName", "pg-test-1")
.formParam("ParameterGroupFamily", "redshift-1.0")
.formParam("Description", "Test Redshift Parameter Group")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<ParameterGroupName>pg-test-1</ParameterGroupName>"))
.body(containsString("<ParameterGroupFamily>redshift-1.0</ParameterGroupFamily>"));
// 2. DescribeClusterParameterGroups
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DescribeClusterParameterGroups")
.formParam("ParameterGroupName", "pg-test-1")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<ParameterGroupName>pg-test-1</ParameterGroupName>"));
// 2b. ModifyClusterParameterGroup
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "ModifyClusterParameterGroup")
.formParam("ParameterGroupName", "pg-test-1")
.formParam("Parameters.member.1.ParameterName", "statement_timeout")
.formParam("Parameters.member.1.ParameterValue", "5000")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<ParameterGroupName>pg-test-1</ParameterGroupName>"));
// 3. DescribeClusterParameters
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DescribeClusterParameters")
.formParam("ParameterGroupName", "pg-test-1")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<DescribeClusterParametersResponse>"))
.body(containsString("<ParameterName>statement_timeout</ParameterName>"))
.body(containsString("<ParameterValue>5000</ParameterValue>"));
// 4. DeleteClusterParameterGroup
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DeleteClusterParameterGroup")
.formParam("ParameterGroupName", "pg-test-1")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<DeleteClusterParameterGroupResponse>"));
}
@Test
@Order(2)
void testClusterAndSnapshotLifecycle() {
when(containerManager.start(any(), eq("cluster-src"), any(), any()))
.thenReturn(new RedshiftContainerHandle("c1", "cluster-src", "localhost", 5439));
org.mockito.Mockito.doAnswer(invocation -> {
java.nio.file.Path p = invocation.getArgument(3);
java.nio.file.Files.writeString(p, "-- dump sql table test_data;");
return null;
}).when(containerManager).takeSnapshot(any(), eq("cluster-src"), eq("admin"), any(java.nio.file.Path.class));
when(containerManager.start(any(), eq("cluster-restored"), any(), any()))
.thenReturn(new RedshiftContainerHandle("c2", "cluster-restored", "localhost", 5440));
// 1. CreateCluster
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "CreateCluster")
.formParam("ClusterIdentifier", "cluster-src")
.formParam("NodeType", "dc2.large")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "password123")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<ClusterIdentifier>cluster-src</ClusterIdentifier>"))
.body(containsString("<ClusterStatus>available</ClusterStatus>"));
// 1b. RebootCluster — must preserve data (no Docker volume backs this container)
when(containerManager.getContainer(any(), eq("cluster-src")))
.thenReturn(java.util.Optional.of(new RedshiftContainerHandle("c1", "cluster-src", "localhost", 5439)));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "RebootCluster")
.formParam("ClusterIdentifier", "cluster-src")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<ClusterIdentifier>cluster-src</ClusterIdentifier>"))
.body(containsString("<ClusterStatus>available</ClusterStatus>"));
// 1c. ModifyCluster
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "ModifyCluster")
.formParam("ClusterIdentifier", "cluster-src")
.formParam("NodeType", "ra3.xlplus")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<NodeType>ra3.xlplus</NodeType>"));
// 2. CreateClusterSnapshot
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "CreateClusterSnapshot")
.formParam("SnapshotIdentifier", "snap-test-1")
.formParam("ClusterIdentifier", "cluster-src")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<SnapshotIdentifier>snap-test-1</SnapshotIdentifier>"))
.body(containsString("<ClusterIdentifier>cluster-src</ClusterIdentifier>"));
// 3. DescribeClusterSnapshots
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DescribeClusterSnapshots")
.formParam("SnapshotIdentifier", "snap-test-1")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<SnapshotIdentifier>snap-test-1</SnapshotIdentifier>"));
// 4. DeleteCluster
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DeleteCluster")
.formParam("ClusterIdentifier", "cluster-src")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<ClusterIdentifier>cluster-src</ClusterIdentifier>"))
.body(containsString("<ClusterStatus>deleting</ClusterStatus>"));
// 5. RestoreFromClusterSnapshot
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "RestoreFromClusterSnapshot")
.formParam("ClusterIdentifier", "cluster-restored")
.formParam("SnapshotIdentifier", "snap-test-1")
.formParam("NodeType", "dc2.large")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<ClusterIdentifier>cluster-restored</ClusterIdentifier>"))
.body(containsString("<ClusterStatus>available</ClusterStatus>"))
.body(containsString("<Port>5440</Port>"));
// 6. DeleteClusterSnapshot
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DeleteClusterSnapshot")
.formParam("SnapshotIdentifier", "snap-test-1")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<SnapshotIdentifier>snap-test-1</SnapshotIdentifier>"))
.body(containsString("<Status>deleted</Status>"));
// 7. Delete restored cluster
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DeleteCluster")
.formParam("ClusterIdentifier", "cluster-restored")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<ClusterIdentifier>cluster-restored</ClusterIdentifier>"));
}
@Test
@Order(4)
void testClusterSubnetGroupLifecycle() {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "CreateClusterSubnetGroup")
.formParam("ClusterSubnetGroupName", "subnet-group-1")
.formParam("Description", "Test subnet group")
.formParam("SubnetIds.member.1", "subnet-aaa")
.formParam("SubnetIds.member.2", "subnet-bbb")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml")
.body(containsString("<ClusterSubnetGroupName>subnet-group-1</ClusterSubnetGroupName>"))
.body(containsString("<SubnetIdentifier>subnet-aaa</SubnetIdentifier>"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DescribeClusterSubnetGroups")
.formParam("ClusterSubnetGroupName", "subnet-group-1")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<ClusterSubnetGroupName>subnet-group-1</ClusterSubnetGroupName>"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "ModifyClusterSubnetGroup")
.formParam("ClusterSubnetGroupName", "subnet-group-1")
.formParam("Description", "Updated")
.formParam("SubnetIds.member.1", "subnet-ccc")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<SubnetIdentifier>subnet-ccc</SubnetIdentifier>"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DeleteClusterSubnetGroup")
.formParam("ClusterSubnetGroupName", "subnet-group-1")
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
@Order(3)
void testTagLifecycle() {
when(containerManager.start(any(), eq("cluster-tags"), any(), any()))
.thenReturn(new RedshiftContainerHandle("c3", "cluster-tags", "localhost", 5441));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "CreateCluster")
.formParam("ClusterIdentifier", "cluster-tags")
.formParam("NodeType", "dc2.large")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "password123")
.when()
.post("/")
.then()
.statusCode(200);
String clusterArn = "arn:aws:redshift:us-east-1:000000000000:cluster:cluster-tags";
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "CreateTags")
.formParam("ResourceName", clusterArn)
.formParam("Tags.member.1.Key", "env")
.formParam("Tags.member.1.Value", "test")
.when()
.post("/")
.then()
.statusCode(200)
.contentType("application/xml");
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DescribeTags")
.formParam("ResourceName", clusterArn)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<Key>env</Key>"))
.body(containsString("<Value>test</Value>"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DeleteTags")
.formParam("ResourceName", clusterArn)
.formParam("TagKeys.member.1", "env")
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
.formParam("Action", "DeleteCluster")
.formParam("ClusterIdentifier", "cluster-tags")
.when()
.post("/")
.then()
.statusCode(200);
}
}
@@ -0,0 +1,329 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
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 jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
class RedshiftQueryHandlerTest {
private RedshiftQueryHandler handler;
private RedshiftService service;
@BeforeEach
void setUp() {
service = mock(RedshiftService.class);
handler = new RedshiftQueryHandler(service);
}
@Test
void testCreateClusterAction() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "test-cluster");
params.putSingle("NodeType", "dc2.large");
params.putSingle("MasterUsername", "admin");
params.putSingle("MasterUserPassword", "password123");
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("test-cluster");
cluster.setClusterStatus("available");
when(service.createCluster(any(), any(), any(), any(), any(), any())).thenReturn(cluster);
Response response = handler.handle("CreateCluster", params);
assertEquals(200, response.getStatus());
assertNotNull(response.getEntity());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<ClusterIdentifier>test-cluster</ClusterIdentifier>"));
assertTrue(xml.contains("<ClusterStatus>available</ClusterStatus>"));
assertTrue(xml.contains("<RequestId>test-req-id</RequestId>"));
}
@Test
void testDescribeClusters() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "test-cluster");
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("test-cluster");
cluster.setClusterStatus("available");
when(service.describeClusters(any())).thenReturn(List.of(cluster));
Response response = handler.handle("DescribeClusters", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<ClusterIdentifier>test-cluster</ClusterIdentifier>"));
}
@Test
void testDeleteCluster() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "test-cluster");
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("test-cluster");
cluster.setClusterStatus("deleting");
when(service.deleteCluster(any())).thenReturn(cluster);
Response response = handler.handle("DeleteCluster", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<ClusterIdentifier>test-cluster</ClusterIdentifier>"));
assertTrue(xml.contains("<ClusterStatus>deleting</ClusterStatus>"));
}
@Test
void testCreateClusterSnapshot() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("SnapshotIdentifier", "test-snapshot");
params.putSingle("ClusterIdentifier", "test-cluster");
Snapshot snapshot = new Snapshot("test-snapshot", "test-cluster", "available", 5439, "admin");
when(service.createSnapshot("test-snapshot", "test-cluster")).thenReturn(snapshot);
Response response = handler.handle("CreateClusterSnapshot", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<SnapshotIdentifier>test-snapshot</SnapshotIdentifier>"));
assertTrue(xml.contains("<ClusterIdentifier>test-cluster</ClusterIdentifier>"));
assertTrue(xml.contains("<Status>available</Status>"));
assertTrue(xml.contains("<Port>5439</Port>"));
assertTrue(xml.contains("<MasterUsername>admin</MasterUsername>"));
assertTrue(xml.contains("<RequestId>test-req-id</RequestId>"));
}
@Test
void testDescribeClusterSnapshots() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("SnapshotIdentifier", "test-snapshot");
params.putSingle("ClusterIdentifier", "test-cluster");
Snapshot snapshot = new Snapshot("test-snapshot", "test-cluster", "available", 5439, "admin");
when(service.describeSnapshots("test-snapshot", "test-cluster")).thenReturn(List.of(snapshot));
Response response = handler.handle("DescribeClusterSnapshots", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<Snapshots>"));
assertTrue(xml.contains("<SnapshotIdentifier>test-snapshot</SnapshotIdentifier>"));
assertTrue(xml.contains("</Snapshots>"));
}
@Test
void testDeleteClusterSnapshot() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("SnapshotIdentifier", "test-snapshot");
Snapshot snapshot = new Snapshot("test-snapshot", "test-cluster", "deleted", 5439, "admin");
when(service.deleteSnapshot("test-snapshot")).thenReturn(snapshot);
Response response = handler.handle("DeleteClusterSnapshot", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<SnapshotIdentifier>test-snapshot</SnapshotIdentifier>"));
assertTrue(xml.contains("<Status>deleted</Status>"));
}
@Test
void testRestoreFromClusterSnapshot() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "restored-cluster");
params.putSingle("SnapshotIdentifier", "test-snapshot");
params.putSingle("NodeType", "dc2.large");
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("restored-cluster");
cluster.setNodeType("dc2.large");
cluster.setMasterUsername("admin");
cluster.setClusterStatus("available");
cluster.setEndpoint(new Endpoint("localhost", 5439));
when(service.restoreFromClusterSnapshot("restored-cluster", "test-snapshot", "dc2.large")).thenReturn(cluster);
Response response = handler.handle("RestoreFromClusterSnapshot", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<ClusterIdentifier>restored-cluster</ClusterIdentifier>"));
assertTrue(xml.contains("<ClusterStatus>available</ClusterStatus>"));
assertTrue(xml.contains("<Address>localhost</Address>"));
assertTrue(xml.contains("<Port>5439</Port>"));
}
@Test
void testCreateClusterParameterGroup() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ParameterGroupName", "test-pg");
params.putSingle("ParameterGroupFamily", "redshift-1.0");
params.putSingle("Description", "custom redshift param group");
ClusterParameterGroup group = new ClusterParameterGroup("test-pg", "redshift-1.0", "custom redshift param group");
when(service.createClusterParameterGroup("test-pg", "redshift-1.0", "custom redshift param group")).thenReturn(group);
Response response = handler.handle("CreateClusterParameterGroup", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<ParameterGroupName>test-pg</ParameterGroupName>"));
assertTrue(xml.contains("<ParameterGroupFamily>redshift-1.0</ParameterGroupFamily>"));
assertTrue(xml.contains("<Description>custom redshift param group</Description>"));
}
@Test
void testDescribeClusterParameterGroups() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ParameterGroupName", "test-pg");
ClusterParameterGroup group = new ClusterParameterGroup("test-pg", "redshift-1.0", "custom redshift param group");
when(service.describeClusterParameterGroups("test-pg")).thenReturn(List.of(group));
Response response = handler.handle("DescribeClusterParameterGroups", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<ParameterGroups>"));
assertTrue(xml.contains("<ParameterGroupName>test-pg</ParameterGroupName>"));
assertTrue(xml.contains("</ParameterGroups>"));
}
@Test
void testDescribeClusterParameters() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ParameterGroupName", "test-pg");
ClusterParameterGroup group = new ClusterParameterGroup("test-pg", "redshift-1.0", "custom redshift param group");
when(service.describeClusterParameterGroups("test-pg")).thenReturn(List.of(group));
Response response = handler.handle("DescribeClusterParameters", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<Parameters>"));
assertTrue(xml.contains("</Parameters>"));
}
@Test
void testDeleteClusterParameterGroup() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ParameterGroupName", "test-pg");
ClusterParameterGroup group = new ClusterParameterGroup("test-pg", "redshift-1.0", "custom redshift param group");
when(service.deleteClusterParameterGroup("test-pg")).thenReturn(group);
Response response = handler.handle("DeleteClusterParameterGroup", params);
assertEquals(200, response.getStatus());
String xml = (String) response.getEntity();
assertTrue(xml.contains("<DeleteClusterParameterGroupResponse>"));
}
@Test
void testCreateTagsAcceptsNamedMemberForm() {
// Real Redshift SDK sends "Tags.Tag.N.Key/.Value", không phải "Tags.member.N...".
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ResourceName", "arn:aws:redshift:us-east-1:000000000000:cluster:test-cluster");
params.putSingle("Tags.Tag.1.Key", "env");
params.putSingle("Tags.Tag.1.Value", "prod");
Response response = handler.handle("CreateTags", params);
assertEquals(200, response.getStatus());
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, String>> captor = ArgumentCaptor.forClass(Map.class);
verify(service).createTags(eq("arn:aws:redshift:us-east-1:000000000000:cluster:test-cluster"), captor.capture());
assertEquals(Map.of("env", "prod"), captor.getValue());
}
@Test
void testCreateClusterSubnetGroupAcceptsNamedMemberForm() {
// Real Redshift SDK sends "SubnetIds.SubnetIdentifier.N", không phải "SubnetIds.member.N".
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterSubnetGroupName", "test-sng");
params.putSingle("Description", "desc");
params.putSingle("SubnetIds.SubnetIdentifier.1", "subnet-aaa");
params.putSingle("SubnetIds.SubnetIdentifier.2", "subnet-bbb");
ClusterSubnetGroup group = new ClusterSubnetGroup("test-sng", "desc", null, List.of("subnet-aaa", "subnet-bbb"));
when(service.createClusterSubnetGroup(any(), any(), any(), any())).thenReturn(group);
Response response = handler.handle("CreateClusterSubnetGroup", params);
assertEquals(200, response.getStatus());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> captor = ArgumentCaptor.forClass(List.class);
verify(service).createClusterSubnetGroup(eq("test-sng"), eq("desc"), any(), captor.capture());
assertEquals(List.of("subnet-aaa", "subnet-bbb"), captor.getValue());
}
@Test
void testModifyClusterParameterGroupAcceptsNamedMemberForm() {
// Real Redshift SDK sends "Parameters.Parameter.N.ParameterName/.ParameterValue".
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ParameterGroupName", "test-pg");
params.putSingle("Parameters.Parameter.1.ParameterName", "statement_timeout");
params.putSingle("Parameters.Parameter.1.ParameterValue", "5000");
Response response = handler.handle("ModifyClusterParameterGroup", params);
assertEquals(200, response.getStatus());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Parameter>> captor = ArgumentCaptor.forClass(List.class);
verify(service).modifyClusterParameterGroup(eq("test-pg"), captor.capture());
assertEquals(1, captor.getValue().size());
assertEquals("statement_timeout", captor.getValue().get(0).getParameterName());
assertEquals("5000", captor.getValue().get(0).getParameterValue());
}
@Test
void testCreateClusterSubnetGroupRequiresName() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("Description", "desc");
io.github.hectorvent.floci.core.common.AwsException ex = org.junit.jupiter.api.Assertions.assertThrows(
io.github.hectorvent.floci.core.common.AwsException.class,
() -> handler.handle("CreateClusterSubnetGroup", params));
assertEquals("InvalidParameterValue", ex.getErrorCode());
}
@Test
void testModifyClusterRequiresClusterIdentifier() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("NodeType", "dc2.large");
io.github.hectorvent.floci.core.common.AwsException ex = org.junit.jupiter.api.Assertions.assertThrows(
io.github.hectorvent.floci.core.common.AwsException.class,
() -> handler.handle("ModifyCluster", params));
assertEquals("InvalidParameterValue", ex.getErrorCode());
}
@Test
void testBuildClusterXmlIncludesParameterGroupAndTags() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "test-cluster");
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("test-cluster");
cluster.setClusterStatus("available");
cluster.setClusterParameterGroupName("test-pg");
cluster.setTags(Map.of("env", "prod"));
when(service.describeClusters(any())).thenReturn(List.of(cluster));
Response response = handler.handle("DescribeClusters", params);
String xml = (String) response.getEntity();
assertTrue(xml.contains("<ClusterParameterGroups>"));
assertTrue(xml.contains("<ParameterGroupName>test-pg</ParameterGroupName>"));
assertTrue(xml.contains("<ParameterApplyStatus>in-sync</ParameterApplyStatus>"));
assertTrue(xml.contains("<Tags>"));
assertTrue(xml.contains("<Key>env</Key>"));
assertTrue(xml.contains("<Value>prod</Value>"));
}
}
@@ -0,0 +1,748 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerHandle;
import io.github.hectorvent.floci.services.redshift.container.RedshiftContainerManager;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
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 org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;
class RedshiftServiceTest {
private StorageFactory sf;
private AccountAwareStorageBackend<Cluster> clusterBackend;
private AccountAwareStorageBackend<Snapshot> snapshotBackend;
private AccountAwareStorageBackend<String> snapshotDumpBackend;
private AccountAwareStorageBackend<ClusterParameterGroup> parameterGroupBackend;
private AccountAwareStorageBackend<ClusterSubnetGroup> subnetGroupBackend;
private RedshiftContainerManager cm;
private io.github.hectorvent.floci.core.common.RegionResolver regionResolver;
private RedshiftService service;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
sf = mock(StorageFactory.class);
clusterBackend = mock(AccountAwareStorageBackend.class);
snapshotBackend = mock(AccountAwareStorageBackend.class);
snapshotDumpBackend = mock(AccountAwareStorageBackend.class);
parameterGroupBackend = mock(AccountAwareStorageBackend.class);
subnetGroupBackend = mock(AccountAwareStorageBackend.class);
cm = mock(RedshiftContainerManager.class);
io.github.hectorvent.floci.config.EmulatorConfig config = mock(io.github.hectorvent.floci.config.EmulatorConfig.class);
io.github.hectorvent.floci.config.EmulatorConfig.StorageConfig storageConfig = mock(io.github.hectorvent.floci.config.EmulatorConfig.StorageConfig.class);
when(config.storage()).thenReturn(storageConfig);
when(storageConfig.persistentPath()).thenReturn("target/test-data");
when(sf.<Cluster>create(eq("redshift"), eq("redshift-clusters.json"), any())).thenReturn(clusterBackend);
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(clusterBackend.accountId()).thenReturn("111111111111");
regionResolver = new io.github.hectorvent.floci.core.common.RegionResolver("us-east-1", "111111111111");
service = new RedshiftService(sf, cm, config, regionResolver);
}
/** Absolute dump path as {@code createSnapshot} now stores it: under {@code <persistentPath>/redshift-dumps/<accountId>}. */
private static String dumpPath(String snapshotId) {
return java.nio.file.Paths.get("target/test-data", "redshift-dumps", "111111111111", snapshotId + ".sql")
.toAbsolutePath().normalize().toString();
}
@Test
void testOnStartRecreatesContainersAcrossAccounts() {
Cluster clusterA = new Cluster();
clusterA.setClusterIdentifier("cluster-a");
clusterA.setMasterUsername("admin");
clusterA.setMasterPassword("pw-a");
clusterA.setClusterStatus("available");
Cluster clusterB = new Cluster();
clusterB.setClusterIdentifier("cluster-b");
clusterB.setMasterUsername("admin");
clusterB.setMasterPassword("pw-b");
clusterB.setClusterStatus("available");
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "cluster-a", clusterA),
new AccountAwareStorageBackend.AccountEntry<>("222222222222", "cluster-b", clusterB)));
when(cm.getContainer(anyString(), anyString())).thenReturn(Optional.empty());
when(cm.adoptOrStart(eq("111111111111"), eq("cluster-a"), eq("admin"), eq("pw-a")))
.thenReturn(new RedshiftContainerHandle("c-a", "cluster-a", "localhost", 5432));
when(cm.adoptOrStart(eq("222222222222"), eq("cluster-b"), eq("admin"), eq("pw-b")))
.thenReturn(new RedshiftContainerHandle("c-b", "cluster-b", "localhost", 5433));
service.onStart(null);
// Cluster owned by a second, non-default account must also be recovered
verify(cm).adoptOrStart("111111111111", "cluster-a", "admin", "pw-a");
verify(cm).adoptOrStart("222222222222", "cluster-b", "admin", "pw-b");
verify(clusterBackend).putForAccount(eq("111111111111"), eq("cluster-a"), any(Cluster.class));
verify(clusterBackend).putForAccount(eq("222222222222"), eq("cluster-b"), any(Cluster.class));
verify(clusterBackend).flush();
}
@Test
void testOnStartSkipsClusterWithRunningContainer() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("cluster-a");
cluster.setClusterStatus("available");
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "cluster-a", cluster)));
when(cm.getContainer("111111111111", "cluster-a"))
.thenReturn(Optional.of(new RedshiftContainerHandle("c-a", "cluster-a", "localhost", 5432)));
service.onStart(null);
verify(cm, never()).adoptOrStart(any(), any(), any(), any());
verify(clusterBackend, never()).putForAccount(any(), any(), any());
}
@Test
void testOnStartMarksClusterUnavailableOnStartFailure() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("cluster-a");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("pw-a");
cluster.setClusterStatus("available");
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "cluster-a", cluster)));
when(cm.getContainer("111111111111", "cluster-a")).thenReturn(Optional.empty());
when(cm.adoptOrStart(eq("111111111111"), eq("cluster-a"), eq("admin"), eq("pw-a"))).thenThrow(new RuntimeException("docker down"));
service.onStart(null);
ArgumentCaptor<Cluster> captor = ArgumentCaptor.forClass(Cluster.class);
verify(clusterBackend).putForAccount(eq("111111111111"), eq("cluster-a"), captor.capture());
assertEquals("unavailable", captor.getValue().getClusterStatus());
}
@Test
void testCreateCluster() {
when(clusterBackend.get(anyString())).thenReturn(Optional.empty());
when(cm.start(any(), any(), any(), any())).thenReturn(new RedshiftContainerHandle("c1", "my-cluster", "localhost", 5432));
Cluster cluster = service.createCluster("my-cluster", "dc2.large", "admin", "password123");
assertNotNull(cluster);
assertEquals("my-cluster", cluster.getClusterIdentifier());
assertEquals("available", cluster.getClusterStatus());
assertEquals("localhost", cluster.getEndpoint().getAddress());
verify(clusterBackend, times(2)).put(eq("my-cluster"), any(Cluster.class));
}
@Test
void testCreateClusterWithVpcMetadata() {
when(clusterBackend.get(anyString())).thenReturn(Optional.empty());
when(cm.start(any(), any(), any(), any())).thenReturn(new RedshiftContainerHandle("c1", "my-cluster", "localhost", 5432));
Cluster cluster = service.createCluster("my-cluster", "dc2.large", "admin", "password123",
"my-subnet-group", List.of("sg-1", "sg-2"));
assertEquals("my-subnet-group", cluster.getClusterSubnetGroupName());
assertEquals(List.of("sg-1", "sg-2"), cluster.getVpcSecurityGroupIds());
}
@Test
void testCreateClusterAlreadyExists() {
when(clusterBackend.get("existing-cluster")).thenReturn(Optional.of(new Cluster()));
assertThrows(AwsException.class, () ->
service.createCluster("existing-cluster", "dc2.large", "admin", "password123"));
}
@Test
void testDescribeClusters() {
Cluster c = new Cluster();
c.setClusterIdentifier("test-c");
when(clusterBackend.get("test-c")).thenReturn(Optional.of(c));
List<Cluster> list = service.describeClusters("test-c");
assertEquals(1, list.size());
assertEquals("test-c", list.get(0).getClusterIdentifier());
}
@Test
void testDeleteCluster() {
Cluster c = new Cluster();
c.setClusterIdentifier("test-c");
when(clusterBackend.get("test-c")).thenReturn(Optional.of(c));
Cluster deleted = service.deleteCluster("test-c");
assertEquals("deleting", deleted.getClusterStatus());
verify(cm).stop("111111111111", "test-c");
verify(clusterBackend).delete("test-c");
}
@Test
void testRebootClusterDumpsAndRestoresData() throws Exception {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("pw");
cluster.setClusterStatus("available");
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
when(cm.start(eq("111111111111"), eq("my-cluster"), eq("admin"), eq("pw")))
.thenReturn(new RedshiftContainerHandle("c-rebooted", "my-cluster", "localhost", 5555));
doAnswer(invocation -> {
java.nio.file.Path dumpFile = invocation.getArgument(3);
java.nio.file.Files.writeString(dumpFile, "-- dump");
return null;
}).when(cm).takeSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(java.nio.file.Path.class));
Cluster rebooted = service.rebootCluster("my-cluster");
assertEquals("available", rebooted.getClusterStatus());
assertEquals(5555, rebooted.getEndpoint().getPort());
verify(cm).stop("111111111111", "my-cluster");
verify(cm).start("111111111111", "my-cluster", "admin", "pw");
verify(cm).restoreSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(java.nio.file.Path.class));
}
@Test
void testRebootClusterNotFound() {
when(clusterBackend.get("missing")).thenReturn(Optional.empty());
assertThrows(AwsException.class, () -> service.rebootCluster("missing"));
}
@Test
void testCreateSnapshot() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("secret-pw");
cluster.setEndpoint(new Endpoint("localhost", 5439));
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.empty());
doNothing().when(cm).takeSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(java.nio.file.Path.class));
Snapshot snapshot = service.createSnapshot("my-snapshot", "my-cluster");
assertNotNull(snapshot);
assertEquals("my-snapshot", snapshot.getSnapshotIdentifier());
assertEquals("my-cluster", snapshot.getClusterIdentifier());
assertEquals("available", snapshot.getStatus());
assertEquals("admin", snapshot.getMasterUsername());
// Password captured at snapshot time so restore can recover it after the source cluster is gone
assertEquals("secret-pw", snapshot.getMasterPassword());
assertEquals(5439, snapshot.getPort());
// sqlDump is now an absolute path scoped by account to avoid collisions across accounts
assertTrue(snapshot.getSqlDump().contains("111111111111"));
assertTrue(snapshot.getSqlDump().endsWith("my-snapshot.sql"));
verify(snapshotBackend).put(eq("my-snapshot"), any(Snapshot.class));
verify(snapshotBackend).flush();
verify(cm).takeSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(java.nio.file.Path.class));
}
@Test
void testCreateSnapshotClusterNotFound() {
when(clusterBackend.get("missing-cluster")).thenReturn(Optional.empty());
assertThrows(AwsException.class, () ->
service.createSnapshot("snap-1", "missing-cluster"));
}
@Test
void testCreateSnapshotAlreadyExists() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(new Snapshot()));
assertThrows(AwsException.class, () ->
service.createSnapshot("snap-1", "my-cluster"));
}
@Test
void testCreateSnapshotRejectsTraversalOrMalformedIdentifier() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
cluster.setMasterUsername("admin");
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
when(snapshotBackend.get(anyString())).thenReturn(Optional.empty());
String[] bad = {
"../evil", "../../etc/cron.d/x", "/etc/passwd", "a/b", "a\\b",
"foo/../bar", "-leading", "trailing-", "double--hyphen", "1startsdigit", "", "has space",
};
for (String id : bad) {
AwsException ex = assertThrows(AwsException.class,
() -> service.createSnapshot(id, "my-cluster"), "expected rejection for: " + id);
assertEquals("InvalidParameterValue", ex.getErrorCode(), id);
assertEquals(400, ex.getHttpStatus(), id);
}
verify(cm, never()).takeSnapshot(any(), any(), any(), any(java.nio.file.Path.class));
verify(snapshotBackend, never()).put(anyString(), any(Snapshot.class));
}
@Test
void testModifyClusterUpdatesMetadataAndPassword() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
cluster.setNodeType("dc2.large");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("old-pw");
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
Cluster updated = service.modifyCluster("my-cluster", "ra3.xlplus", null, "new-pw", null, null);
assertEquals("ra3.xlplus", updated.getNodeType());
assertEquals("new-pw", updated.getMasterPassword());
verify(cm).alterUserPassword("111111111111", "my-cluster", "admin", "new-pw");
verify(clusterBackend).put(eq("my-cluster"), any(Cluster.class));
verify(clusterBackend).flush();
}
@Test
void testModifyClusterUpdatesVpcSecurityGroups() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
cluster.setMasterUsername("admin");
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
Cluster updated = service.modifyCluster("my-cluster", null, null, null, "custom-pg", List.of("sg-9"));
assertEquals("custom-pg", updated.getClusterParameterGroupName());
assertEquals(List.of("sg-9"), updated.getVpcSecurityGroupIds());
verify(cm, never()).alterUserPassword(any(), any(), any(), any());
}
@Test
void testModifyClusterNotFound() {
when(clusterBackend.get("missing")).thenReturn(Optional.empty());
assertThrows(AwsException.class, () ->
service.modifyCluster("missing", "ra3.xlplus", null, null, null, null));
}
@Test
void testDescribeSnapshots() {
Snapshot s = new Snapshot("snap-1", "my-cluster", "available", 5439, "admin");
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(s));
List<Snapshot> list = service.describeSnapshots("snap-1");
assertEquals(1, list.size());
assertEquals("snap-1", list.get(0).getSnapshotIdentifier());
}
@Test
void testDescribeSnapshotsNotFound() {
when(snapshotBackend.get("missing-snap")).thenReturn(Optional.empty());
assertThrows(AwsException.class, () -> service.describeSnapshots("missing-snap"));
}
@Test
void testDeleteSnapshot() {
Snapshot s = new Snapshot("snap-1", "my-cluster", "available", 5439, "admin");
s.setSqlDump(dumpPath("snap-1"));
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(s));
Snapshot deleted = service.deleteSnapshot("snap-1");
assertNotNull(deleted);
assertEquals("deleted", deleted.getStatus());
verify(snapshotBackend).delete("snap-1");
verify(snapshotBackend).flush();
}
@Test
void testDeleteSnapshotNotFound() {
when(snapshotBackend.get("missing-snap")).thenReturn(Optional.empty());
assertThrows(AwsException.class, () -> service.deleteSnapshot("missing-snap"));
}
@Test
void testRestoreFromClusterSnapshot() {
Cluster sourceCluster = new Cluster();
sourceCluster.setClusterIdentifier("source-cluster");
sourceCluster.setMasterPassword("password123");
Snapshot snapshot = new Snapshot("my-snapshot", "source-cluster", "available", 5439, "admin");
snapshot.setSqlDump(dumpPath("my-snapshot"));
when(clusterBackend.get("restored-cluster")).thenReturn(Optional.empty());
when(clusterBackend.get("source-cluster")).thenReturn(Optional.of(sourceCluster));
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.of(snapshot));
when(cm.start(eq("111111111111"), eq("restored-cluster"), eq("admin"), eq("password123")))
.thenReturn(new RedshiftContainerHandle("c-new", "restored-cluster", "localhost", 5432));
doNothing().when(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(java.nio.file.Path.class));
Cluster cluster = service.restoreFromClusterSnapshot("restored-cluster", "my-snapshot", "dc2.large");
assertNotNull(cluster);
assertEquals("restored-cluster", cluster.getClusterIdentifier());
assertEquals("available", cluster.getClusterStatus());
assertEquals("admin", cluster.getMasterUsername());
assertEquals("password123", cluster.getMasterPassword());
assertEquals("dc2.large", cluster.getNodeType());
assertEquals("localhost", cluster.getEndpoint().getAddress());
// Restore must use the source cluster's actual password, not a hardcoded one
verify(cm).start("111111111111", "restored-cluster", "admin", "password123");
verify(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(java.nio.file.Path.class));
verify(clusterBackend, times(2)).put(eq("restored-cluster"), any(Cluster.class));
verify(clusterBackend, times(2)).flush();
}
@Test
void testRestoreFromClusterSnapshotUsesStoredPasswordAfterSourceClusterDeleted() {
Snapshot snapshot = new Snapshot("my-snapshot", "deleted-source", "available", 5439, "admin");
snapshot.setMasterPassword("original-secret");
snapshot.setSqlDump(dumpPath("my-snapshot"));
when(clusterBackend.get("restored-cluster")).thenReturn(Optional.empty());
// Source cluster no longer exists, but the snapshot itself still carries the original password
when(clusterBackend.get("deleted-source")).thenReturn(Optional.empty());
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.of(snapshot));
when(cm.start(eq("111111111111"), eq("restored-cluster"), eq("admin"), eq("original-secret")))
.thenReturn(new RedshiftContainerHandle("c-new", "restored-cluster", "localhost", 5432));
doNothing().when(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(java.nio.file.Path.class));
Cluster cluster = service.restoreFromClusterSnapshot("restored-cluster", "my-snapshot", "dc2.large");
assertEquals("original-secret", cluster.getMasterPassword());
verify(cm).start("111111111111", "restored-cluster", "admin", "original-secret");
}
@Test
void testRestoreFromClusterSnapshotFallsBackToAdminWhenSourceClusterGone() {
Snapshot snapshot = new Snapshot("my-snapshot", "deleted-source", "available", 5439, "admin");
snapshot.setSqlDump(dumpPath("my-snapshot"));
when(clusterBackend.get("restored-cluster")).thenReturn(Optional.empty());
when(clusterBackend.get("deleted-source")).thenReturn(Optional.empty());
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.of(snapshot));
when(cm.start(eq("111111111111"), eq("restored-cluster"), eq("admin"), eq("admin")))
.thenReturn(new RedshiftContainerHandle("c-new", "restored-cluster", "localhost", 5432));
doNothing().when(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(java.nio.file.Path.class));
Cluster cluster = service.restoreFromClusterSnapshot("restored-cluster", "my-snapshot", "dc2.large");
assertEquals("admin", cluster.getMasterPassword());
verify(cm).start("111111111111", "restored-cluster", "admin", "admin");
}
@Test
void testRestoreFromClusterSnapshotAlreadyExists() {
when(clusterBackend.get("existing-cluster")).thenReturn(Optional.of(new Cluster()));
assertThrows(AwsException.class, () ->
service.restoreFromClusterSnapshot("existing-cluster", "my-snapshot"));
}
@Test
void testRestoreFromClusterSnapshotNotFound() {
when(clusterBackend.get("new-cluster")).thenReturn(Optional.empty());
when(snapshotBackend.get("missing-snapshot")).thenReturn(Optional.empty());
assertThrows(AwsException.class, () ->
service.restoreFromClusterSnapshot("new-cluster", "missing-snapshot"));
}
@Test
void testRestoreFromClusterSnapshotFailure() {
Snapshot snapshot = new Snapshot("my-snapshot", "source-cluster", "available", 5439, "admin", dumpPath("my-snapshot"));
when(clusterBackend.get("failed-cluster")).thenReturn(Optional.empty());
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.of(snapshot));
when(cm.start(any(), any(), any(), any())).thenThrow(new RuntimeException("Docker error"));
assertThrows(AwsException.class, () ->
service.restoreFromClusterSnapshot("failed-cluster", "my-snapshot"));
}
@Test
void testRestoreFromClusterSnapshotRejectsUntrustedDumpPathBeforeProvisioning() {
// A dump path persisted outside the account dir (e.g. by pre-validation code) must be
// rejected up front — no cluster record, no container.
Snapshot snapshot = new Snapshot("my-snapshot", "source-cluster", "available", 5439, "admin", "/etc/shadow");
when(clusterBackend.get("restored-cluster")).thenReturn(Optional.empty());
when(snapshotBackend.get("my-snapshot")).thenReturn(Optional.of(snapshot));
AwsException ex = assertThrows(AwsException.class, () ->
service.restoreFromClusterSnapshot("restored-cluster", "my-snapshot", "dc2.large"));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
verify(cm, never()).start(any(), any(), any(), any());
verify(cm, never()).restoreSnapshot(any(), any(), any(), any());
verify(clusterBackend, never()).put(anyString(), any(Cluster.class));
}
@Test
void testCreateClusterParameterGroup() {
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.empty());
ClusterParameterGroup pg = service.createClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
assertNotNull(pg);
assertEquals("my-pg", pg.getParameterGroupName());
assertEquals("redshift-1.0", pg.getParameterGroupFamily());
assertEquals("custom pg", pg.getDescription());
verify(parameterGroupBackend).put(eq("my-pg"), any(ClusterParameterGroup.class));
verify(parameterGroupBackend).flush();
}
@Test
void testCreateClusterParameterGroupAlreadyExists() {
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(new ClusterParameterGroup()));
assertThrows(AwsException.class, () ->
service.createClusterParameterGroup("my-pg", "redshift-1.0", "custom pg"));
}
@Test
void testDescribeClusterParameterGroups() {
ClusterParameterGroup pg = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(pg));
List<ClusterParameterGroup> list = service.describeClusterParameterGroups("my-pg");
assertEquals(1, list.size());
assertEquals("my-pg", list.get(0).getParameterGroupName());
}
@Test
void testDescribeClusterParameterGroupsNotFound() {
when(parameterGroupBackend.get("missing-pg")).thenReturn(Optional.empty());
assertThrows(AwsException.class, () ->
service.describeClusterParameterGroups("missing-pg"));
}
@Test
void testDeleteClusterParameterGroup() {
ClusterParameterGroup pg = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(pg));
ClusterParameterGroup deleted = service.deleteClusterParameterGroup("my-pg");
assertNotNull(deleted);
assertEquals("my-pg", deleted.getParameterGroupName());
verify(parameterGroupBackend).delete("my-pg");
verify(parameterGroupBackend).flush();
}
@Test
void testDeleteClusterParameterGroupNotFound() {
when(parameterGroupBackend.get("missing-pg")).thenReturn(Optional.empty());
assertThrows(AwsException.class, () ->
service.deleteClusterParameterGroup("missing-pg"));
}
@Test
void testModifyClusterParameterGroup() {
ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group));
ClusterParameterGroup updated = service.modifyClusterParameterGroup("my-pg",
List.of(new Parameter("max_cursor_result_set_size", "1000")));
assertEquals("1000", updated.getParameters().stream()
.filter(p -> "max_cursor_result_set_size".equals(p.getParameterName()))
.findFirst().orElseThrow().getParameterValue());
verify(parameterGroupBackend).put(eq("my-pg"), any(ClusterParameterGroup.class));
verify(parameterGroupBackend).flush();
}
@Test
void testModifyClusterParameterGroupAppendsUnknownParameter() {
ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group));
ClusterParameterGroup updated = service.modifyClusterParameterGroup("my-pg",
List.of(new Parameter("statement_timeout", "5000")));
assertTrue(updated.getParameters().stream()
.anyMatch(p -> "statement_timeout".equals(p.getParameterName()) && "5000".equals(p.getParameterValue())));
}
@Test
void testModifyClusterParameterGroupNotFound() {
when(parameterGroupBackend.get("missing")).thenReturn(Optional.empty());
assertThrows(AwsException.class, () ->
service.modifyClusterParameterGroup("missing", List.of(new Parameter("x", "y"))));
}
@Test
void testDescribeClusterParametersReturnsStoredValues() {
ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
group.setParameters(new java.util.ArrayList<>(List.of(new Parameter("statement_timeout", "5000"))));
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group));
List<Parameter> params = service.describeClusterParameters("my-pg");
assertEquals(1, params.size());
assertEquals("statement_timeout", params.get(0).getParameterName());
assertEquals("5000", params.get(0).getParameterValue());
}
@Test
void testModifyClusterParameterGroupPreservesMetadata() {
ClusterParameterGroup group = new ClusterParameterGroup("my-pg", "redshift-1.0", "custom pg");
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group));
// Modify using 2-arg constructor (only name and value) - should preserve description and dataType
ClusterParameterGroup updated = service.modifyClusterParameterGroup("my-pg",
List.of(new Parameter("max_cursor_result_set_size", "1000")));
Parameter modified = updated.getParameters().stream()
.filter(p -> "max_cursor_result_set_size".equals(p.getParameterName()))
.findFirst().orElseThrow();
assertEquals("1000", modified.getParameterValue());
assertEquals("Maximum cursor result set size", modified.getDescription());
assertEquals("integer", modified.getDataType());
}
@Test
void testCreateAndListTagsForCluster() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
service.createTags("arn:aws:redshift:us-east-1:111111111111:cluster:my-cluster",
java.util.Map.of("env", "test"));
assertEquals("test", cluster.getTags().get("env"));
verify(clusterBackend).put(eq("my-cluster"), any(Cluster.class));
}
@Test
void testDeleteTagsForCluster() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
cluster.setTags(new java.util.LinkedHashMap<>(java.util.Map.of("env", "test", "team", "data")));
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
service.deleteTags("arn:aws:redshift:us-east-1:111111111111:cluster:my-cluster", java.util.List.of("env"));
assertEquals(java.util.Map.of("team", "data"), cluster.getTags());
}
@Test
void testCreateTagsRejectsNonArnResourceName() {
assertThrows(AwsException.class, () ->
service.createTags("my-cluster", java.util.Map.of("env", "test")));
}
@Test
void testCreateTagsRejectsUnknownResourceType() {
assertThrows(AwsException.class, () ->
service.createTags("arn:aws:redshift:us-east-1:111111111111:reservednode:foo", java.util.Map.of("env", "test")));
}
@Test
void testDescribeTagsForSpecificResource() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
cluster.setTags(new java.util.LinkedHashMap<>(java.util.Map.of("env", "test")));
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
List<RedshiftService.TaggedResource> tagged =
service.describeTags("arn:aws:redshift:us-east-1:111111111111:cluster:my-cluster", null, null);
assertEquals(1, tagged.size());
assertEquals("cluster", tagged.get(0).resourceType());
assertEquals("env", tagged.get(0).tagKey());
assertEquals("test", tagged.get(0).tagValue());
}
@Test
void testDescribeTagsScansAllResourcesOfType() {
Cluster a = new Cluster();
a.setClusterIdentifier("cluster-a");
a.setTags(new java.util.LinkedHashMap<>(java.util.Map.of("env", "prod")));
Cluster b = new Cluster();
b.setClusterIdentifier("cluster-b");
b.setTags(new java.util.LinkedHashMap<>());
when(clusterBackend.scan(any())).thenReturn(java.util.List.of(a, b));
when(snapshotBackend.scan(any())).thenReturn(java.util.List.of());
when(parameterGroupBackend.scan(any())).thenReturn(java.util.List.of());
when(subnetGroupBackend.scan(any())).thenReturn(java.util.List.of());
List<RedshiftService.TaggedResource> tagged = service.describeTags(null, "cluster", null);
assertEquals(1, tagged.size());
assertEquals("cluster-a", extractResourceId(tagged.get(0).resourceName()));
}
@Test
void testCreateClusterSubnetGroup() {
when(subnetGroupBackend.get("my-subnet-group")).thenReturn(Optional.empty());
ClusterSubnetGroup group = service.createClusterSubnetGroup(
"my-subnet-group", "test group", "vpc-123", List.of("subnet-1", "subnet-2"));
assertEquals("my-subnet-group", group.getClusterSubnetGroupName());
assertEquals(List.of("subnet-1", "subnet-2"), group.getSubnetIds());
verify(subnetGroupBackend).put(eq("my-subnet-group"), any(ClusterSubnetGroup.class));
verify(subnetGroupBackend).flush();
}
@Test
void testCreateClusterSubnetGroupAlreadyExists() {
when(subnetGroupBackend.get("existing")).thenReturn(Optional.of(new ClusterSubnetGroup()));
assertThrows(AwsException.class, () ->
service.createClusterSubnetGroup("existing", "d", "vpc-1", List.of("subnet-1")));
}
@Test
void testDescribeClusterSubnetGroups() {
ClusterSubnetGroup group = new ClusterSubnetGroup("my-group", "d", "vpc-1", List.of("subnet-1"));
when(subnetGroupBackend.get("my-group")).thenReturn(Optional.of(group));
List<ClusterSubnetGroup> list = service.describeClusterSubnetGroups("my-group");
assertEquals(1, list.size());
assertEquals("my-group", list.get(0).getClusterSubnetGroupName());
}
@Test
void testModifyClusterSubnetGroup() {
ClusterSubnetGroup group = new ClusterSubnetGroup("my-group", "old", "vpc-1", List.of("subnet-1"));
when(subnetGroupBackend.get("my-group")).thenReturn(Optional.of(group));
ClusterSubnetGroup updated = service.modifyClusterSubnetGroup("my-group", "new", List.of("subnet-2", "subnet-3"));
assertEquals("new", updated.getDescription());
assertEquals(List.of("subnet-2", "subnet-3"), updated.getSubnetIds());
}
@Test
void testDeleteClusterSubnetGroup() {
ClusterSubnetGroup group = new ClusterSubnetGroup("my-group", "d", "vpc-1", List.of("subnet-1"));
when(subnetGroupBackend.get("my-group")).thenReturn(Optional.of(group));
ClusterSubnetGroup deleted = service.deleteClusterSubnetGroup("my-group");
assertEquals("my-group", deleted.getClusterSubnetGroupName());
verify(subnetGroupBackend).delete("my-group");
verify(subnetGroupBackend).flush();
}
@Test
void testDeleteClusterSubnetGroupNotFound() {
when(subnetGroupBackend.get("missing")).thenReturn(Optional.empty());
assertThrows(AwsException.class, () -> service.deleteClusterSubnetGroup("missing"));
}
private static String extractResourceId(String arn) {
String resource = arn.substring(arn.lastIndexOf(':') + 1);
return resource.contains("/") ? resource.substring(resource.lastIndexOf('/') + 1) : resource;
}
}
@@ -0,0 +1,467 @@
package io.github.hectorvent.floci.services.redshift.container;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.ExecStartCmd;
import com.github.dockerjava.api.command.InspectExecCmd;
import com.github.dockerjava.api.command.InspectExecResponse;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.StreamType;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.Closeable;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RedshiftContainerManagerTest {
private ContainerBuilder containerBuilder;
private ContainerLifecycleManager lifecycleManager;
private ContainerLogStreamer logStreamer;
private ContainerDetector containerDetector;
private EmulatorConfig config;
private DockerClient dockerClient;
private RedshiftContainerManager manager;
@BeforeEach
void setUp() {
containerBuilder = mock(ContainerBuilder.class);
lifecycleManager = mock(ContainerLifecycleManager.class);
logStreamer = mock(ContainerLogStreamer.class);
containerDetector = mock(ContainerDetector.class);
config = mock(EmulatorConfig.class, org.mockito.Mockito.RETURNS_DEEP_STUBS);
dockerClient = mock(DockerClient.class);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(config.services().redshift().imageVersion()).thenReturn("postgres:16-alpine");
when(config.services().redshift().dockerNetwork()).thenReturn(Optional.empty());
manager = new RedshiftContainerManager(
containerBuilder,
lifecycleManager,
logStreamer,
containerDetector,
config
);
}
private static final String ACCOUNT_ID = "111111111111";
@Test
void testTakeSnapshotContainerNotFound() {
AwsException ex = assertThrows(AwsException.class, () ->
manager.takeSnapshot(ACCOUNT_ID, "non-existent-cluster", "admin", "dev", java.nio.file.Path.of("dummy.sql")));
assertEquals("ClusterNotFound", ex.getErrorCode());
assertEquals(404, ex.getHttpStatus());
}
@Test
void testRestoreSnapshotContainerNotFound() {
AwsException ex = assertThrows(AwsException.class, () ->
manager.restoreSnapshot(ACCOUNT_ID, "non-existent-cluster", "admin", "dev", java.nio.file.Path.of("dummy.sql")));
assertEquals("ClusterNotFound", ex.getErrorCode());
assertEquals(404, ex.getHttpStatus());
}
@Test
void testCreateSnapshotNullCluster() {
AwsException ex = assertThrows(AwsException.class, () ->
manager.createSnapshot(ACCOUNT_ID, null, java.nio.file.Path.of("dummy.sql")));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void testRestoreSnapshotNullCluster() {
AwsException ex = assertThrows(AwsException.class, () ->
manager.restoreSnapshot(ACCOUNT_ID, (Cluster) null, java.nio.file.Path.of("dummy.sql")));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void testTakeSnapshotSuccess() throws Exception {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
RedshiftContainerHandle handle = manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertNotNull(handle);
assertEquals("cont-123", handle.getContainerId());
assertTrue(manager.getContainer(ACCOUNT_ID, "test-cluster").isPresent());
// Mock docker exec for pg_dump
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
when(createResponse.getId()).thenReturn("exec-1");
when(createCmd.exec()).thenReturn(createResponse);
when(dockerClient.execCreateCmd("cont-123")).thenReturn(createCmd);
ExecStartCmd startCmd = mock(ExecStartCmd.class);
when(startCmd.exec(any())).thenAnswer(invocation -> {
@SuppressWarnings("unchecked")
ResultCallback.Adapter<Frame> adapter = invocation.getArgument(0);
adapter.onComplete();
return adapter;
});
when(dockerClient.execStartCmd("exec-1")).thenReturn(startCmd);
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
when(inspectResponse.getExitCodeLong()).thenReturn(0L);
when(inspectCmd.exec()).thenReturn(inspectResponse);
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectCmd);
// mock copyArchiveFromContainerCmd
com.github.dockerjava.api.command.CopyArchiveFromContainerCmd copyCmd = mock(com.github.dockerjava.api.command.CopyArchiveFromContainerCmd.class, org.mockito.Mockito.RETURNS_SELF);
byte[] tarBytes = "-- PostgreSQL dump\nCREATE TABLE foo (id int);\n".getBytes(StandardCharsets.UTF_8);
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
try (org.apache.commons.compress.archivers.tar.TarArchiveOutputStream tar = new org.apache.commons.compress.archivers.tar.TarArchiveOutputStream(bos)) {
org.apache.commons.compress.archivers.tar.TarArchiveEntry entry = new org.apache.commons.compress.archivers.tar.TarArchiveEntry("dump.sql");
entry.setSize(tarBytes.length);
tar.putArchiveEntry(entry);
tar.write(tarBytes);
tar.closeArchiveEntry();
}
when(copyCmd.exec()).thenReturn(new java.io.ByteArrayInputStream(bos.toByteArray()));
when(dockerClient.copyArchiveFromContainerCmd("cont-123", "/tmp/dump.sql")).thenReturn(copyCmd);
java.nio.file.Path tempFile = java.nio.file.Files.createTempFile("test-take-snapshot", ".sql");
try {
manager.takeSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",tempFile);
String dump = java.nio.file.Files.readString(tempFile);
assertTrue(dump.contains("PostgreSQL dump"));
assertTrue(dump.contains("CREATE TABLE foo"));
} finally {
java.nio.file.Files.deleteIfExists(tempFile);
}
}
@Test
void testTakeSnapshotFailureExitCode() throws Exception {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
when(createResponse.getId()).thenReturn("exec-fail");
when(createCmd.exec()).thenReturn(createResponse);
when(dockerClient.execCreateCmd("cont-123")).thenReturn(createCmd);
ExecStartCmd startCmd = mock(ExecStartCmd.class);
when(startCmd.exec(any())).thenAnswer(invocation -> {
@SuppressWarnings("unchecked")
ResultCallback.Adapter<Frame> adapter = invocation.getArgument(0);
byte[] err = "pg_dump: error: connection failed".getBytes(StandardCharsets.UTF_8);
adapter.onNext(new Frame(StreamType.STDERR, err));
adapter.onComplete();
return adapter;
});
when(dockerClient.execStartCmd("exec-fail")).thenReturn(startCmd);
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
when(inspectResponse.getExitCodeLong()).thenReturn(1L);
when(inspectCmd.exec()).thenReturn(inspectResponse);
when(dockerClient.inspectExecCmd("exec-fail")).thenReturn(inspectCmd);
AwsException ex = assertThrows(AwsException.class, () ->
manager.takeSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",java.nio.file.Path.of("dummy.sql")));
assertEquals("InternalFailure", ex.getErrorCode());
assertEquals(500, ex.getHttpStatus());
}
@Test
void testRestoreSnapshotEmptyDump() {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
// Should return cleanly without touching dockerClient
manager.restoreSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",java.nio.file.Path.of("non-existent-dump.sql"));
manager.restoreSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",(java.nio.file.Path) null);
}
@Test
void testRestoreSnapshotSuccess() throws Exception {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
// Mock copyArchiveToContainerCmd
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, org.mockito.Mockito.RETURNS_SELF);
when(dockerClient.copyArchiveToContainerCmd("cont-123")).thenReturn(copyCmd);
// Mock docker exec for psql
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
when(createResponse.getId()).thenReturn("exec-restore");
when(createCmd.exec()).thenReturn(createResponse);
when(dockerClient.execCreateCmd("cont-123")).thenReturn(createCmd);
ExecStartCmd startCmd = mock(ExecStartCmd.class);
when(startCmd.exec(any())).thenAnswer(invocation -> {
@SuppressWarnings("unchecked")
ResultCallback.Adapter<Frame> adapter = invocation.getArgument(0);
adapter.onComplete();
return adapter;
});
when(dockerClient.execStartCmd("exec-restore")).thenReturn(startCmd);
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
when(inspectResponse.getExitCodeLong()).thenReturn(0L);
when(inspectCmd.exec()).thenReturn(inspectResponse);
when(dockerClient.inspectExecCmd("exec-restore")).thenReturn(inspectCmd);
java.nio.file.Path tempFile = java.nio.file.Files.createTempFile("test-restore-snapshot", ".sql");
try {
manager.restoreSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",tempFile);
verify(dockerClient).copyArchiveToContainerCmd("cont-123");
verify(dockerClient).execCreateCmd("cont-123");
} finally {
java.nio.file.Files.deleteIfExists(tempFile);
}
}
@Test
void testStopRemovesContainer() {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertTrue(manager.getContainer(ACCOUNT_ID, "test-cluster").isPresent());
manager.stop(ACCOUNT_ID, "test-cluster");
assertTrue(manager.getContainer(ACCOUNT_ID, "test-cluster").isEmpty());
verify(lifecycleManager).removeIfExists("floci-redshift-" + ACCOUNT_ID + "-test-cluster");
}
@Test
void testSameClusterIdentifierAcrossAccountsDoesNotCollide() {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo infoA = new ContainerInfo("cont-account-a", Map.of(5432, new EndpointInfo("localhost", 5432)));
ContainerInfo infoB = new ContainerInfo("cont-account-b", Map.of(5432, new EndpointInfo("localhost", 5433)));
when(lifecycleManager.createAndStart(any())).thenReturn(infoA, infoB);
String otherAccountId = "222222222222";
manager.start(ACCOUNT_ID, "shared-id", "admin", "pass");
manager.start(otherAccountId, "shared-id", "admin", "pass");
// Both accounts keep their own running container despite the shared cluster identifier
assertTrue(manager.getContainer(ACCOUNT_ID, "shared-id").isPresent());
assertTrue(manager.getContainer(otherAccountId, "shared-id").isPresent());
assertEquals("cont-account-a", manager.getContainer(ACCOUNT_ID, "shared-id").get().getContainerId());
assertEquals("cont-account-b", manager.getContainer(otherAccountId, "shared-id").get().getContainerId());
}
@Test
void testAdoptOrStartAdoptsExistingContainerInsteadOfRecreatingIt() {
String containerName = "floci-redshift-" + ACCOUNT_ID + "-test-cluster";
Container existing = mock(Container.class);
when(existing.getId()).thenReturn("cont-existing");
when(lifecycleManager.findByName(containerName)).thenReturn(Optional.of(existing));
ContainerInfo adopted = new ContainerInfo("cont-existing", Map.of(5432, new EndpointInfo("localhost", 6000)));
when(lifecycleManager.adopt(eq("cont-existing"), any())).thenReturn(adopted);
RedshiftContainerHandle handle = manager.adoptOrStart(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertEquals("cont-existing", handle.getContainerId());
assertEquals(6000, handle.getPort());
assertTrue(manager.getContainer(ACCOUNT_ID, "test-cluster").isPresent());
// Data lives only in the container's writable layer (no volume) — recreating it
// would silently discard it, so a container found by name must never be recreated.
verify(lifecycleManager, never()).createAndStart(any());
}
@Test
void testAdoptOrStartFallsBackToStartWhenNoExistingContainer() {
String containerName = "floci-redshift-" + ACCOUNT_ID + "-test-cluster";
when(lifecycleManager.findByName(containerName)).thenReturn(Optional.empty());
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-fresh", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
RedshiftContainerHandle handle = manager.adoptOrStart(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertEquals("cont-fresh", handle.getContainerId());
verify(lifecycleManager, never()).adopt(any(), any());
}
@Test
void testAlterUserPasswordSuccess() throws Exception {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
when(createResponse.getId()).thenReturn("exec-alter");
when(createCmd.exec()).thenReturn(createResponse);
when(dockerClient.execCreateCmd("cont-123")).thenReturn(createCmd);
ExecStartCmd startCmd = mock(ExecStartCmd.class);
when(startCmd.exec(any())).thenAnswer(invocation -> {
@SuppressWarnings("unchecked")
ResultCallback.Adapter<Frame> adapter = invocation.getArgument(0);
adapter.onComplete();
return adapter;
});
when(dockerClient.execStartCmd("exec-alter")).thenReturn(startCmd);
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
when(inspectResponse.getExitCodeLong()).thenReturn(0L);
when(inspectCmd.exec()).thenReturn(inspectResponse);
when(dockerClient.inspectExecCmd("exec-alter")).thenReturn(inspectCmd);
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin", "NewSecret1");
verify(dockerClient).execCreateCmd("cont-123");
}
@Test
void testAlterUserPasswordContainerNotFound() {
AwsException ex = assertThrows(AwsException.class, () ->
manager.alterUserPassword(ACCOUNT_ID, "non-existent-cluster", "admin", "new-secret"));
assertEquals("ClusterNotFound", ex.getErrorCode());
assertEquals(404, ex.getHttpStatus());
}
@Test
void testAlterUserPasswordInvalidUsername() throws Exception {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
// Test SQL injection attempt with semicolon
AwsException ex = assertThrows(AwsException.class, () ->
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "postgres; DROP TABLE some_table; --", "new-secret"));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
// Test SQL injection attempt with space
ex = assertThrows(AwsException.class, () ->
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin user", "new-secret"));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@Test
void testAlterUserPasswordInvalidPassword() throws Exception {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
// Forbidden characters: ', ", \, / and @ (AWS ModifyCluster rejects the same set)
for (String bad : new String[]{"Pass'word1", "Pass\"word1", "Pass\\word1", "Pass/word1", "Pass@word1"}) {
AwsException ex = assertThrows(AwsException.class, () ->
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin", bad));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
// Too short (< 8) and too long (> 64)
for (String bad : new String[]{"Ab1cde", "A1" + "a".repeat(63)}) {
AwsException ex = assertThrows(AwsException.class, () ->
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin", bad));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
// Missing a required class: no uppercase, no lowercase, no digit
for (String bad : new String[]{"lowercase1", "UPPERCASE1", "NoDigitsHere"}) {
AwsException ex = assertThrows(AwsException.class, () ->
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin", bad));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
}
@Test
void testAlterUserPasswordExecFailure() throws Exception {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
when(createResponse.getId()).thenReturn("exec-fail");
when(createCmd.exec()).thenReturn(createResponse);
when(dockerClient.execCreateCmd("cont-123")).thenReturn(createCmd);
ExecStartCmd startCmd = mock(ExecStartCmd.class);
when(startCmd.exec(any())).thenAnswer(invocation -> {
@SuppressWarnings("unchecked")
ResultCallback.Adapter<Frame> adapter = invocation.getArgument(0);
byte[] err = "ERROR: role \"admin\" does not exist".getBytes(StandardCharsets.UTF_8);
adapter.onNext(new Frame(StreamType.STDERR, err));
adapter.onComplete();
return adapter;
});
when(dockerClient.execStartCmd("exec-fail")).thenReturn(startCmd);
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
when(inspectResponse.getExitCodeLong()).thenReturn(1L);
when(inspectCmd.exec()).thenReturn(inspectResponse);
when(dockerClient.inspectExecCmd("exec-fail")).thenReturn(inspectCmd);
AwsException ex = assertThrows(AwsException.class, () ->
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin", "NewSecret1"));
assertEquals("InternalFailure", ex.getErrorCode());
assertEquals(500, ex.getHttpStatus());
}
}