feat/redshift auth proxy (#2751)

* feat(redshift): add auth proxy port range and endpoint-host config

* feat(redshift): add containerHost/containerPort/proxyPort to Cluster model

* feat(redshift): add RedshiftAuthProxy reusing the RDS PostgreSQL protocol handler

* feat(redshift): add RedshiftProxyManager registry with shutdown hook

* feat(redshift): front new clusters with an auth proxy and advertise it

* feat(redshift): stop/update proxy on delete/modify, start it on snapshot restore

* feat(redshift): keep proxy port stable across reboot and adopt-on-startup

* test(redshift): integration coverage for JDBC through the auth proxy

* test(redshift): reinstate JDBC connectivity check now that the proxy exists

* docs(redshift): document the cluster auth proxy and its config

* fix(redshift): prevent minor port leak when proxy fails to start

* fix(redshift): rollback container on proxy failure and surface teardown errors

* fix(redshift): stop auth proxy on rollback to prevent listener collisions

* fix(redshift): ensure proxy shutdown failure does not abort container and port cleanup

* fix(redshift): add proper logging for intentionally ignored cleanup exceptions

* fix: Wait for Redshift database readiness before proxying

Previously, RedshiftContainerManager just slept for 3 seconds before marking the container as started. On slower CI environments, the PostgreSQL database might take longer to initialize, resulting in Connection Refused when the RedshiftAuthProxy forwards connections.
Now, RedshiftContainerManager polls the database using psql until it's ready, up to 60 seconds.

* fix(redshift): prevent proxy port reallocation on shutdown failure

Addresses a review comment indicating that if a Redshift auth proxy fails to shut down during rollback or deletion, its port must not be released into the available pool. Reassigning a still-bound port would cause subsequent cluster creations to fail with a BindException.
Instead, we now tolerate proxy shutdown errors but intentionally leak the port allocation to prevent collisions.

* fix(redshift): fix failing tests due to proxy changes

1. RedshiftOperationsTest checked for a hardcoded port 5440, but the RedshiftService now allocates dynamic proxy ports. Removed the exact port assertion.
2. RedshiftContainerManager's psql readiness check was connecting via local Unix socket, which succeeded before PostgreSQL was actually ready to accept remote TCP connections from the proxy. Added '-h 127.0.0.1' to enforce TCP readiness.

* test(redshift): use Awaitility to connect to proxy

Use Awaitility to retry the initial connection in RedshiftProxyIntegrationTest to prevent transient 'Connection attempt failed' errors on slower CI environments.

* chore(redshift): use proper imports instead of fully-qualified class names in tests

* fix(redshift): fix compiler errors introduced during import cleanup

* fix(redshift): resolve proxy lifecycle bugs and CI network issues

- Throw RuntimeException from RedshiftProxyManager.stopProxy if proxy is not found. This allows RedshiftService to catch it and intentionally leak the port, preventing port collisions if a proxy fails before registration.
- Force RedshiftProxyIntegrationTest to connect via 127.0.0.1 instead of the endpoint address, which resolves to host.docker.internal in CI environments and causes UnknownHostException.

* fix(redshift): prevent proxy port exhaustion on startup failures

Instead of blindly assuming missing proxies denote a leaked port, RedshiftProxyManager now tracks proxies that failed their socket cleanup during startup. stopProxy throws an exception only if the socket is known to be leaked. This allows RedshiftService to safely release ports after clean proxy startup failures, addressing Greptile's feedback about port exhaustion.

* fix(redshift): retain proxy reference to allow retry on close failure

As identified by Greptile, stopProxy previously removed the proxy from the registry before calling proxy.stop(). If stop() threw an exception, the proxy reference was lost, preventing any subsequent retry from ever finding it and attempting to close it again. stopProxy now only removes the proxy from the registry after stop() returns successfully. Additionally, failedCleanups is now retained instead of cleared, ensuring retries continue to safely leak the port if cleanup remains impossible.

* fix(redshift): abort cluster deletion if proxy fails to stop

As highlighted by Greptile, previously deleteCluster would swallow proxy shutdown failures and delete the cluster metadata anyway. This eliminated the retry path, stranding the unclosed proxy and its port reservation until the process exited. Now, if stopProxyAndReleasePortSafely fails, deleteCluster throws an exception to preserve the cluster metadata so the deletion can be retried.

* test(redshift): lock in proxy lifecycle failure-recovery behaviors

Bổ sung test cho ba hành vi hardening chưa được cover, để refactor sau
không âm thầm phá vỡ:

- stopProxy giữ lại proxy trong registry khi close() ném, cho phép retry
  gọi lại đúng instance và chỉ deregister sau khi stop sạch
- marker leak khi startup cleanup thất bại được retain qua mọi retry và
  chỉ bị xoá bởi một lần start mới thành công
- deleteCluster abort với InternalFailure, giữ nguyên container + metadata
  khi proxy không stop được; retry sau đó hoàn tất khi proxy stop OK

Đồng thời bỏ "-p 7100-7199:7100-7199" trong compatibility.yml: proxy bind
0.0.0.0 trong container floci và sdk-test-java chạy trên compat-net nên
JDBC đi container-to-container qua alias "floci", không cần publish port
ra host. Giữ lại FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST=floci.

* fix(redshift): keep an unclosable proxy reachable for later retry

Theo phản hồi mới của Greptile: khi start/replace proxy thất bại và
cleanupFailedStart cũng không đóng được listener, code cũ chỉ lưu relayKey
vào một Set rồi vứt object RedshiftAuthProxy. stopProxy sau đó ném vĩnh
viễn mà không còn cách nào chạm tới listener để thử đóng lại, khiến
cluster không xoá được và port bị giữ mãi trong dải hữu hạn.

Thay Set<String> failedCleanups bằng Map<String, RedshiftAuthProxy>
unclosableProxies. cleanupFailedStart giữ lại chính proxy đó; stopProxy và
stopAll thử đóng lại, chỉ gỡ entry khi stop thành công. startProxy không
còn xoá marker khi start mới — chỉ một lần stop thành công mới gỡ, vì
listener cũ có thể vẫn đang bound.

* fix(redshift): retry proxy port bind to absorb reboot rebind race

rebootCluster giữ nguyên proxy port của cluster để endpoint ổn định, nên
listener cũ bị đóng rồi bind lại đúng port đó chỉ vài ms sau. Dưới tải
(CI runner ARM) kernel có thể chưa nhả port và SO_REUSEADDR không giúp
được khi accept loop cũ đang teardown -> BindException -> RebootCluster
trả 500. Đây là nguyên nhân test RedshiftOperationsTest.
testClusterAndSnapshotLifecycle fail chập chờn.

start() giờ retry bind tối đa ~1s, chỉ nuốt BindException; IOException
khác vẫn propagate ngay. Thêm test dựng cảnh port bị chiếm tạm thời rồi
nhả, xác nhận proxy vẫn bind được.

* fix(redshift): tear down proxy and release port when rebootCluster fails

Nếu startProxy/restoreSnapshot ném sau khi proxy đã (re)start trong
rebootCluster, hai nhánh catch chỉ set status "failed" rồi rethrow —
proxy mới vẫn chạy và port vẫn nằm trong usedPorts, không nhánh nào dọn.
Giờ cả hai catch gọi stopProxyAndReleasePortSafely như createCluster và
restoreFromClusterSnapshot đã làm; proxyPort được hoist ra ngoài try với
sentinel -1 để rollback an toàn kể cả khi chưa cấp port.

Thêm test: restoreSnapshot ném -> proxy được stop lại, AwsException nổi lên.

* fix(redshift): serialize createCluster/deleteCluster/restoreFromClusterSnapshot

modifyCluster và rebootCluster đã synchronized nhưng create/delete/restore
thì không, dù cả năm method đều chạy chuỗi container + proxy + port nhiều
bước trên cùng một cluster. deleteCluster(x) chạy song song rebootCluster(x)
có thể để lại metadata mồ côi trỏ tới container/proxy đã dừng. Thêm
synchronized cho ba method còn lại để nhất quán.

* fix(rds,redshift): close backend socket when the auth handshake fails

handleConnection mở kết nối TCP tới container Postgres trước khi gọi
handleAuth. Chỉ nhánh thành công (bridge) và vài nhánh lỗi có kiểm soát
mới đóng backend; nếu handleAuth trả về sớm ở một probe trần (SSLRequest
không kèm startup) hoặc ném IOException (client ngắt giữa handshake), catch
cũ chỉ đóng client -> mỗi health-check TCP làm rò một connection tới
Postgres, ăn dần max_connections.

Chuyển việc đóng socket sang finally, đóng cả client lẫn backend
(idempotent, nhánh thành công đã đóng sẵn). Áp cho cả RdsAuthProxy vì
RedshiftAuthProxy được copy từ đó. Thêm test: client drop giữa handshake
-> backend nhận EOF.

* fix(redshift): stop replacement container and keep dump on failed reboot

Rollback của rebootCluster (b44fd1e3) mới chỉ stop proxy + release port,
để container thay thế chạy tiếp sau một cluster "failed", và finally vẫn
xoá tempDump. Vì container gốc đã stop và không có volume, tempDump là bản
sao duy nhất của data -> mất data không khôi phục được (bug có sẵn, giờ
mới lộ).

rollbackReboot() giờ stop luôn container thay thế (như createCluster/
restoreFromClusterSnapshot). tempDump chỉ bị xoá khi reboot thành công;
khi fail thì giữ lại và log đường dẫn để khôi phục thủ công.

* fix(redshift): make reboot rollback phase-aware to protect the original

Commit trước cho rollbackReboot stop container vô điều kiện. Nếu reboot
fail ngay ở takeSnapshot hoặc stopProxy — lúc container gốc (chứa data,
không volume) VẪN đang chạy — thì rollback lại force-remove chính nó, huỷ
bản sao data hoàn chỉnh duy nhất và chỉ còn dump rỗng/dở.

Thêm hai cờ:
- originalTornDown: đã stop proxy + container gốc -> rollback mới được
  đụng vào proxy/port
- replacementStarted: đã start container thay thế -> rollback mới được
  stop container
Fail trước hai mốc đó: không đụng gì, trạng thái gốc còn nguyên.

Thêm test: takeSnapshot ném -> cm.stop và stopProxy không được gọi.

* fix(redshift): clean an orphan replacement container on failed reboot

containerManager.start có thể tạo container Docker rồi mới ném ở
waitForReady, nên cờ replacementStarted (set sau khi start return) bỏ sót
trường hợp này -> orphan chạy dưới tên cluster.

Bỏ replacementStarted, gate rollback theo mỗi originalTornDown: một khi
proxy + container gốc đã stop thì container gốc chắc chắn biến mất, nên
containerManager.stop (xoá theo tên) chỉ có thể chạm replacement — kể cả
replacement do start() tạo dở rồi ném.

Thêm test: start() ném -> rollback vẫn gọi cm.stop để dọn orphan.

* fix(redshift): remove orphan cluster metadata on failed create/restore

* fix(redshift): keep failed cluster metadata if proxy stop fails

* fix(redshift): fix TooManyActualInvocations in proxy tests

* fix(redshift): clear proxyPort on reboot rollback if port is released

* fix(redshift): retain reserved port on reboot startup failure

* fix(redshift): retain proxy port in reboot rollback and teardown failed startup recovery

* fix(redshift): skip failing cluster and retaining dump if reboot fails before teardown
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-08-31 09:03:26 -04:00
1 parent f7f16cd2a3
commit 426fbcb284
20 files changed
+1771 -96

No files matched your search

@@ -0,0 +1,27 @@
package io.github.hectorvent.floci.config;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class RedshiftProxyConfigTest {
@Inject
EmulatorConfig config;
@Test
void redshiftProxyPortRangeHasDefaults() {
assertEquals(7100, config.services().redshift().proxyBasePort());
assertEquals(7199, config.services().redshift().proxyMaxPort());
}
@Test
void redshiftEndpointHostDefaultsToEmpty() {
assertEquals(Optional.empty(), config.services().redshift().endpointHost());
}
}
@@ -9,6 +9,10 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
@@ -107,10 +111,10 @@ public class RedshiftOperationsTest {
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;");
Path p = invocation.getArgument(3);
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).takeSnapshot(any(), eq("cluster-src"), eq("admin"), any(Path.class));
when(containerManager.start(any(), eq("cluster-restored"), any(), any()))
.thenReturn(new RedshiftContainerHandle("c2", "cluster-restored", "localhost", 5440));
@@ -133,7 +137,7 @@ public class RedshiftOperationsTest {
// 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)));
.thenReturn(Optional.of(new RedshiftContainerHandle("c1", "cluster-src", "localhost", 5439)));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", AUTH_HEADER)
@@ -216,8 +220,7 @@ public class RedshiftOperationsTest {
.statusCode(200)
.contentType("application/xml")
.body(containsString("<ClusterIdentifier>cluster-restored</ClusterIdentifier>"))
.body(containsString("<ClusterStatus>available</ClusterStatus>"))
.body(containsString("<Port>5440</Port>"));
.body(containsString("<ClusterStatus>available</ClusterStatus>"));
// 6. DeleteClusterSnapshot
given()
@@ -0,0 +1,127 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.Objects;
import org.awaitility.Awaitility;
import org.awaitility.core.ConditionTimeoutException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class RedshiftProxyIntegrationTest {
@Inject
RedshiftService service;
private String clusterId;
@AfterEach
void cleanUp() {
if (clusterId != null) {
service.deleteCluster(clusterId);
}
}
private static String jdbcUrl(Cluster c) {
// Use 127.0.0.1 explicitly instead of c.getEndpoint().getAddress() to avoid UnknownHostException
// in CI environments where floci.emulator.hostname is set to host.docker.internal.
return "jdbc:postgresql://127.0.0.1:" + c.getEndpoint().getPort() + "/dev";
}
private static Connection waitForConnection(Cluster cluster, String username, String password) throws SQLException {
try {
return Awaitility.await()
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofMillis(500))
.ignoreExceptions()
.until(() -> DriverManager.getConnection(jdbcUrl(cluster), username, password), Objects::nonNull);
} catch (ConditionTimeoutException e) {
return DriverManager.getConnection(jdbcUrl(cluster), username, password); // throw original
}
}
@Test
void roundTripsSqlThroughTheAdvertisedEndpoint() throws SQLException {
clusterId = "it-proxy-roundtrip";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
try (Connection conn = waitForConnection(cluster, "admin", "Secret123");
Statement st = conn.createStatement()) {
st.execute("CREATE TABLE people (name text)");
st.execute("INSERT INTO people VALUES ('Alice')");
try (ResultSet rs = st.executeQuery("SELECT count(*) FROM people")) {
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
}
}
}
@Test
void rejectsAWrongPasswordAtTheProxy() throws SQLException {
clusterId = "it-proxy-badpass";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
// Ensure it's ready first
try (Connection conn = waitForConnection(cluster, "admin", "Secret123")) {
assertTrue(conn.isValid(5));
}
assertThrows(SQLException.class, () ->
DriverManager.getConnection(jdbcUrl(cluster), "admin", "wrong-password"));
}
@Test
void reflectsAPasswordChangeForNewConnections() throws SQLException {
clusterId = "it-proxy-rotate";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
// Ensure it's ready before testing rotation
try (Connection conn = waitForConnection(cluster, "admin", "Secret123")) {
assertTrue(conn.isValid(5));
}
service.modifyCluster(clusterId, null, null, "Rotated123", null, null);
assertThrows(SQLException.class, () ->
DriverManager.getConnection(jdbcUrl(cluster), "admin", "Secret123"));
try (Connection conn = DriverManager.getConnection(jdbcUrl(cluster), "admin", "Rotated123")) {
assertTrue(conn.isValid(5));
}
}
@Test
void keepsTheEndpointStableAndDataIntactAcrossAReboot() throws SQLException {
clusterId = "it-proxy-reboot";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
int portBefore = cluster.getEndpoint().getPort();
try (Connection conn = waitForConnection(cluster, "admin", "Secret123");
Statement st = conn.createStatement()) {
st.execute("CREATE TABLE t (n int)");
st.execute("INSERT INTO t VALUES (42)");
}
Cluster rebooted = service.rebootCluster(clusterId);
assertEquals(portBefore, rebooted.getEndpoint().getPort());
try (Connection conn = waitForConnection(rebooted, "admin", "Secret123");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT n FROM t")) {
assertTrue(rs.next());
assertEquals(42, rs.getInt(1));
}
}
}
@@ -15,6 +15,11 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -35,6 +40,8 @@ class RedshiftServiceTest {
private AccountAwareStorageBackend<ClusterSubnetGroup> subnetGroupBackend;
private RedshiftContainerManager cm;
private io.github.hectorvent.floci.core.common.RegionResolver regionResolver;
private io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager proxyManager;
private io.github.hectorvent.floci.core.common.docker.DockerHostResolver dockerHostResolver;
private RedshiftService service;
@BeforeEach
@@ -47,12 +54,25 @@ class RedshiftServiceTest {
parameterGroupBackend = mock(AccountAwareStorageBackend.class);
subnetGroupBackend = mock(AccountAwareStorageBackend.class);
cm = mock(RedshiftContainerManager.class);
proxyManager = mock(io.github.hectorvent.floci.services.redshift.proxy.RedshiftProxyManager.class);
dockerHostResolver = mock(io.github.hectorvent.floci.core.common.docker.DockerHostResolver.class);
when(dockerHostResolver.resolve()).thenReturn("localhost");
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");
io.github.hectorvent.floci.config.EmulatorConfig.ServicesConfig servicesConfig =
mock(io.github.hectorvent.floci.config.EmulatorConfig.ServicesConfig.class);
io.github.hectorvent.floci.config.EmulatorConfig.RedshiftServiceConfig redshiftConfig =
mock(io.github.hectorvent.floci.config.EmulatorConfig.RedshiftServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
when(servicesConfig.redshift()).thenReturn(redshiftConfig);
when(redshiftConfig.proxyBasePort()).thenReturn(7100);
when(redshiftConfig.proxyMaxPort()).thenReturn(7199);
when(redshiftConfig.endpointHost()).thenReturn(Optional.empty());
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);
@@ -61,12 +81,12 @@ class RedshiftServiceTest {
regionResolver = new io.github.hectorvent.floci.core.common.RegionResolver("us-east-1", "111111111111");
service = new RedshiftService(sf, cm, config, regionResolver);
service = new RedshiftService(sf, cm, config, regionResolver, proxyManager, dockerHostResolver);
}
/** 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")
return Paths.get("target/test-data", "redshift-dumps", "111111111111", snapshotId + ".sql")
.toAbsolutePath().normalize().toString();
}
@@ -138,6 +158,34 @@ class RedshiftServiceTest {
assertEquals("unavailable", captor.getValue().getClusterStatus());
}
@Test
@SuppressWarnings("unchecked")
void onStartRestartsTheProxyForAnAdoptedCluster() {
Cluster persisted = new Cluster();
persisted.setClusterIdentifier("c1");
persisted.setMasterUsername("admin");
persisted.setMasterPassword("Secret123");
persisted.setClusterStatus("available");
persisted.setProxyPort(7108);
var entry = mock(AccountAwareStorageBackend.AccountEntry.class);
when(entry.value()).thenReturn(persisted);
when(entry.accountId()).thenReturn("111111111111");
when(entry.key()).thenReturn("c1");
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(entry));
when(cm.getContainer("111111111111", "c1")).thenReturn(Optional.empty());
RedshiftContainerHandle handle = mock(RedshiftContainerHandle.class);
when(handle.getHost()).thenReturn("172.17.0.12");
when(handle.getPort()).thenReturn(32830);
when(cm.adoptOrStart("111111111111", "c1", "admin", "Secret123")).thenReturn(handle);
service.onStart(null);
verify(proxyManager).startProxy(eq("111111111111:c1"), eq(7108),
eq("172.17.0.12"), eq(32830), eq("localhost"),
eq("admin"), eq("Secret123"), eq("dev"), any());
}
@Test
void testCreateCluster() {
when(clusterBackend.get(anyString())).thenReturn(Optional.empty());
@@ -163,6 +211,29 @@ class RedshiftServiceTest {
assertEquals(List.of("sg-1", "sg-2"), cluster.getVpcSecurityGroupIds());
}
@Test
void createClusterStartsAProxyAndAdvertisesTheProxyEndpoint() {
when(clusterBackend.get("c1")).thenReturn(Optional.empty());
when(clusterBackend.accountId()).thenReturn("111111111111");
RedshiftContainerHandle handle = mock(RedshiftContainerHandle.class);
when(handle.getHost()).thenReturn("172.17.0.9");
when(handle.getPort()).thenReturn(32800);
when(cm.start(eq("111111111111"), eq("c1"), eq("admin"), eq("Secret123"))).thenReturn(handle);
Cluster cluster = service.createCluster("c1", "dc2.large", "admin", "Secret123");
// Endpoint is the proxy, not the container.
assertEquals("localhost", cluster.getEndpoint().getAddress());
assertTrue(cluster.getEndpoint().getPort() >= 7100 && cluster.getEndpoint().getPort() <= 7199);
assertEquals("172.17.0.9", cluster.getContainerHost());
assertEquals(32800, cluster.getContainerPort());
assertEquals(cluster.getEndpoint().getPort(), cluster.getProxyPort());
verify(proxyManager).startProxy(eq("111111111111:c1"), eq(cluster.getProxyPort()),
eq("172.17.0.9"), eq(32800), eq("localhost"),
eq("admin"), eq("Secret123"), eq("dev"), any());
}
@Test
void testCreateClusterAlreadyExists() {
when(clusterBackend.get("existing-cluster")).thenReturn(Optional.of(new Cluster()));
@@ -171,6 +242,84 @@ class RedshiftServiceTest {
service.createCluster("existing-cluster", "dc2.large", "admin", "password123"));
}
@Test
void createClusterRemovesMetadataOnFailure() {
when(clusterBackend.accountId()).thenReturn("111111111111");
when(clusterBackend.get("c1")).thenReturn(Optional.empty());
when(cm.start(eq("111111111111"), eq("c1"), eq("admin"), eq("password123")))
.thenThrow(new RuntimeException("startup failed"));
assertThrows(AwsException.class, () ->
service.createCluster("c1", "dc2.large", "admin", "password123"));
verify(clusterBackend).delete("c1");
verify(clusterBackend, atLeastOnce()).flush();
}
@Test
void createClusterKeepsMetadataWhenProxyStopFails() {
when(clusterBackend.accountId()).thenReturn("111111111111");
when(clusterBackend.get("c1")).thenReturn(Optional.empty());
when(cm.start(eq("111111111111"), eq("c1"), eq("admin"), eq("password123")))
.thenThrow(new RuntimeException("startup failed"));
doThrow(new RuntimeException("proxy stop failed"))
.when(proxyManager).stopProxy("111111111111:c1");
assertThrows(AwsException.class, () ->
service.createCluster("c1", "dc2.large", "admin", "password123"));
verify(clusterBackend, never()).delete("c1");
verify(clusterBackend, atLeast(1)).put(eq("c1"), argThat(c -> "failed".equals(c.getClusterStatus())));
verify(clusterBackend, atLeastOnce()).flush();
}
@Test
void restoreFromClusterSnapshotRemovesMetadataOnFailure() {
when(clusterBackend.accountId()).thenReturn("111111111111");
Snapshot snapshot = new Snapshot();
snapshot.setSnapshotIdentifier("snap-1");
snapshot.setClusterIdentifier("source-c1");
snapshot.setMasterUsername("admin");
snapshot.setMasterPassword("password123");
snapshot.setSqlDump(null);
when(clusterBackend.get("c1")).thenReturn(Optional.empty());
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(snapshot));
when(cm.start(eq("111111111111"), eq("c1"), eq("admin"), eq("password123")))
.thenThrow(new RuntimeException("startup failed"));
assertThrows(AwsException.class, () ->
service.restoreFromClusterSnapshot("c1", "snap-1"));
verify(clusterBackend).delete("c1");
verify(clusterBackend, atLeastOnce()).flush();
}
@Test
void restoreFromClusterSnapshotKeepsMetadataWhenProxyStopFails() {
when(clusterBackend.accountId()).thenReturn("111111111111");
Snapshot snapshot = new Snapshot();
snapshot.setSnapshotIdentifier("snap-1");
snapshot.setClusterIdentifier("source-c1");
snapshot.setMasterUsername("admin");
snapshot.setMasterPassword("password123");
snapshot.setSqlDump(null);
when(clusterBackend.get("c1")).thenReturn(Optional.empty());
when(snapshotBackend.get("snap-1")).thenReturn(Optional.of(snapshot));
when(cm.start(eq("111111111111"), eq("c1"), eq("admin"), eq("password123")))
.thenThrow(new RuntimeException("startup failed"));
doThrow(new RuntimeException("proxy stop failed"))
.when(proxyManager).stopProxy("111111111111:c1");
assertThrows(AwsException.class, () ->
service.restoreFromClusterSnapshot("c1", "snap-1"));
verify(clusterBackend, never()).delete("c1");
verify(clusterBackend, atLeast(1)).put(eq("c1"), argThat(c -> "failed".equals(c.getClusterStatus())));
verify(clusterBackend, atLeastOnce()).flush();
}
@Test
void testDescribeClusters() {
Cluster c = new Cluster();
@@ -194,6 +343,41 @@ class RedshiftServiceTest {
verify(clusterBackend).delete("test-c");
}
@Test
void deleteClusterAbortsAndKeepsMetadataWhenTheProxyWontStop() {
Cluster c = new Cluster();
c.setClusterIdentifier("test-c");
c.setProxyPort(7107);
when(clusterBackend.get("test-c")).thenReturn(Optional.of(c));
doThrow(new RuntimeException("listener close failed"))
.when(proxyManager).stopProxy("111111111111:test-c");
AwsException ex = assertThrows(AwsException.class, () -> service.deleteCluster("test-c"));
assertEquals("InternalFailure", ex.getErrorCode());
// Container and metadata are left intact so the deletion can be retried.
verify(cm, never()).stop(anyString(), anyString());
verify(clusterBackend, never()).delete(anyString());
}
@Test
void deleteClusterRetrySucceedsOnceTheProxyStops() {
Cluster c = new Cluster();
c.setClusterIdentifier("test-c");
c.setProxyPort(7107);
when(clusterBackend.get("test-c")).thenReturn(Optional.of(c));
doThrow(new RuntimeException("listener close failed"))
.doNothing()
.when(proxyManager).stopProxy("111111111111:test-c");
assertThrows(AwsException.class, () -> service.deleteCluster("test-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();
@@ -205,18 +389,46 @@ class RedshiftServiceTest {
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");
Path dumpFile = invocation.getArgument(3);
Files.writeString(dumpFile, "-- dump");
return null;
}).when(cm).takeSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(java.nio.file.Path.class));
}).when(cm).takeSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(Path.class));
Cluster rebooted = service.rebootCluster("my-cluster");
assertEquals("available", rebooted.getClusterStatus());
assertEquals(5555, rebooted.getEndpoint().getPort());
// Endpoint now advertises the auth proxy; the restarted container is tracked separately.
assertEquals(5555, rebooted.getContainerPort());
assertTrue(rebooted.getEndpoint().getPort() >= 7100 && rebooted.getEndpoint().getPort() <= 7199);
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));
verify(cm).restoreSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(Path.class));
}
@Test
void rebootClusterRestartsTheProxyOnTheSamePort() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("c1");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("Secret123");
cluster.setProxyPort(7107);
cluster.setEndpoint(new Endpoint("localhost", 7107));
when(clusterBackend.get("c1")).thenReturn(Optional.of(cluster));
when(clusterBackend.accountId()).thenReturn("111111111111");
RedshiftContainerHandle handle = mock(RedshiftContainerHandle.class);
when(handle.getHost()).thenReturn("172.17.0.11");
when(handle.getPort()).thenReturn(32820);
when(cm.start(eq("111111111111"), eq("c1"), eq("admin"), eq("Secret123"))).thenReturn(handle);
Cluster rebooted = service.rebootCluster("c1");
assertEquals(7107, rebooted.getEndpoint().getPort());
assertEquals("localhost", rebooted.getEndpoint().getAddress());
assertEquals("172.17.0.11", rebooted.getContainerHost());
verify(proxyManager).stopProxy("111111111111:c1");
verify(proxyManager).startProxy(eq("111111111111:c1"), eq(7107),
eq("172.17.0.11"), eq(32820), eq("localhost"),
eq("admin"), eq("Secret123"), eq("dev"), any());
}
@Test
@@ -226,6 +438,94 @@ class RedshiftServiceTest {
assertThrows(AwsException.class, () -> service.rebootCluster("missing"));
}
@Test
void rebootClusterTearsDownTheProxyWhenRestoreFails() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("c1");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("Secret123");
cluster.setProxyPort(7107);
when(clusterBackend.get("c1")).thenReturn(Optional.of(cluster));
RedshiftContainerHandle handle = mock(RedshiftContainerHandle.class);
when(handle.getHost()).thenReturn("172.17.0.11");
when(handle.getPort()).thenReturn(32820);
when(cm.start(eq("111111111111"), eq("c1"), eq("admin"), eq("Secret123"))).thenReturn(handle);
doThrow(new RuntimeException("restore boom"))
.when(cm).restoreSnapshot(eq("111111111111"), eq("c1"), eq("admin"), any(Path.class));
assertThrows(AwsException.class, () -> service.rebootCluster("c1"));
// The proxy started during the reboot must be stopped again on failure, and the
// replacement container must be stopped too — once before the restart, once in
// rollback — so it is not left running behind a "failed" cluster.
verify(proxyManager).startProxy(eq("111111111111:c1"), eq(7107), any(), anyInt(),
any(), any(), any(), any(), any());
verify(proxyManager, times(2)).stopProxy("111111111111:c1");
verify(cm, times(2)).stop("111111111111", "c1");
}
@Test
void rebootClusterLeavesTheOriginalContainerAloneWhenTheDumpFails() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("c1");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("Secret123");
cluster.setProxyPort(7107);
when(clusterBackend.get("c1")).thenReturn(Optional.of(cluster));
doThrow(new RuntimeException("dump boom"))
.when(cm).takeSnapshot(eq("111111111111"), eq("c1"), eq("admin"), any(Path.class));
assertThrows(AwsException.class, () -> service.rebootCluster("c1"));
// The dump failed before the original was torn down: rollback must not stop the
// still-running original container or touch its proxy.
verify(cm, never()).stop(anyString(), anyString());
verify(proxyManager, never()).stopProxy(anyString());
}
@Test
void rebootClusterRemovesTheReplacementWhenItsStartupThrows() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("c1");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("Secret123");
cluster.setProxyPort(7107);
when(clusterBackend.get("c1")).thenReturn(Optional.of(cluster));
when(cm.start(eq("111111111111"), eq("c1"), eq("admin"), eq("Secret123")))
.thenThrow(new RuntimeException("readiness timed out"));
assertThrows(AwsException.class, () -> service.rebootCluster("c1"));
// start() can create the container before throwing (readiness check); the
// original is already gone, so rollback removes anything under the name —
// once for the original teardown, once for the possible orphan.
verify(cm, times(2)).stop("111111111111", "c1");
// The reserved port belongs to the cluster and is not released by reboot rollback;
// it is released only when the cluster is successfully deleted.
assertEquals(7107, cluster.getProxyPort());
}
@Test
void rebootClusterKeepsProxyPortWhenRollbackStopFails() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("c1");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("Secret123");
cluster.setProxyPort(7107);
when(clusterBackend.accountId()).thenReturn("111111111111");
when(clusterBackend.get("c1")).thenReturn(Optional.of(cluster));
when(cm.start(eq("111111111111"), eq("c1"), eq("admin"), eq("Secret123")))
.thenThrow(new RuntimeException("readiness timed out"));
// The first call stops the proxy during takeSnapshot; the second call happens in rollback.
doNothing().doThrow(new RuntimeException("stop failed")).when(proxyManager).stopProxy(anyString());
assertThrows(AwsException.class, () -> service.rebootCluster("c1"));
assertEquals(7107, cluster.getProxyPort());
}
@Test
void testCreateSnapshot() {
Cluster cluster = new Cluster();
@@ -236,7 +536,7 @@ class RedshiftServiceTest {
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));
doNothing().when(cm).takeSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(Path.class));
Snapshot snapshot = service.createSnapshot("my-snapshot", "my-cluster");
assertNotNull(snapshot);
@@ -252,7 +552,7 @@ class RedshiftServiceTest {
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));
verify(cm).takeSnapshot(eq("111111111111"), eq("my-cluster"), eq("admin"), any(Path.class));
}
@Test
@@ -292,7 +592,7 @@ class RedshiftServiceTest {
assertEquals("InvalidParameterValue", ex.getErrorCode(), id);
assertEquals(400, ex.getHttpStatus(), id);
}
verify(cm, never()).takeSnapshot(any(), any(), any(), any(java.nio.file.Path.class));
verify(cm, never()).takeSnapshot(any(), any(), any(), any(Path.class));
verify(snapshotBackend, never()).put(anyString(), any(Snapshot.class));
}
@@ -386,7 +686,7 @@ class RedshiftServiceTest {
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));
doNothing().when(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(Path.class));
Cluster cluster = service.restoreFromClusterSnapshot("restored-cluster", "my-snapshot", "dc2.large");
assertNotNull(cluster);
@@ -399,7 +699,7 @@ class RedshiftServiceTest {
// 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(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(Path.class));
verify(clusterBackend, times(2)).put(eq("restored-cluster"), any(Cluster.class));
verify(clusterBackend, times(2)).flush();
}
@@ -415,7 +715,7 @@ class RedshiftServiceTest {
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));
doNothing().when(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(Path.class));
Cluster cluster = service.restoreFromClusterSnapshot("restored-cluster", "my-snapshot", "dc2.large");
assertEquals("original-secret", cluster.getMasterPassword());
@@ -431,7 +731,7 @@ class RedshiftServiceTest {
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));
doNothing().when(cm).restoreSnapshot(eq("111111111111"), eq("restored-cluster"), eq("admin"), any(Path.class));
Cluster cluster = service.restoreFromClusterSnapshot("restored-cluster", "my-snapshot", "dc2.large");
assertEquals("admin", cluster.getMasterPassword());
@@ -483,6 +783,58 @@ class RedshiftServiceTest {
verify(clusterBackend, never()).put(anyString(), any(Cluster.class));
}
@Test
void deleteClusterStopsTheProxyAndReleasesThePort() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("c1");
cluster.setProxyPort(7105);
when(clusterBackend.get("c1")).thenReturn(Optional.of(cluster));
when(clusterBackend.accountId()).thenReturn("111111111111");
service.deleteCluster("c1");
verify(proxyManager).stopProxy("111111111111:c1");
}
@Test
void modifyClusterPasswordUpdatesTheProxySnapshot() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("c1");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("old");
when(clusterBackend.get("c1")).thenReturn(Optional.of(cluster));
when(clusterBackend.accountId()).thenReturn("111111111111");
service.modifyCluster("c1", null, null, "NewSecret1", null, null);
verify(proxyManager).updateMasterPassword("111111111111:c1", "NewSecret1");
}
@Test
void restoreFromSnapshotStartsAProxyForTheNewCluster() {
Snapshot snap = new Snapshot();
snap.setSnapshotIdentifier("s1");
snap.setClusterIdentifier("src");
snap.setMasterUsername("admin");
snap.setMasterPassword("Secret123");
snap.setSqlDump(null);
when(snapshotBackend.get("s1")).thenReturn(Optional.of(snap));
when(clusterBackend.get("restored")).thenReturn(Optional.empty());
when(clusterBackend.accountId()).thenReturn("111111111111");
RedshiftContainerHandle handle = mock(RedshiftContainerHandle.class);
when(handle.getHost()).thenReturn("172.17.0.10");
when(handle.getPort()).thenReturn(32810);
when(cm.start(eq("111111111111"), eq("restored"), eq("admin"), eq("Secret123"))).thenReturn(handle);
Cluster restored = service.restoreFromClusterSnapshot("restored", "s1");
assertEquals("localhost", restored.getEndpoint().getAddress());
assertEquals(restored.getEndpoint().getPort(), restored.getProxyPort());
verify(proxyManager).startProxy(eq("111111111111:restored"), anyInt(),
eq("172.17.0.10"), eq(32810), eq("localhost"),
eq("admin"), eq("Secret123"), eq("dev"), any());
}
@Test
void testCreateClusterParameterGroup() {
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.empty());
@@ -580,7 +932,7 @@ class RedshiftServiceTest {
@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"))));
group.setParameters(new ArrayList<>(List.of(new Parameter("statement_timeout", "5000"))));
when(parameterGroupBackend.get("my-pg")).thenReturn(Optional.of(group));
List<Parameter> params = service.describeClusterParameters("my-pg");
@@ -614,7 +966,7 @@ class RedshiftServiceTest {
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"));
Map.of("env", "test"));
assertEquals("test", cluster.getTags().get("env"));
verify(clusterBackend).put(eq("my-cluster"), any(Cluster.class));
@@ -624,31 +976,31 @@ class RedshiftServiceTest {
void testDeleteTagsForCluster() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
cluster.setTags(new java.util.LinkedHashMap<>(java.util.Map.of("env", "test", "team", "data")));
cluster.setTags(new LinkedHashMap<>(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"));
service.deleteTags("arn:aws:redshift:us-east-1:111111111111:cluster:my-cluster", List.of("env"));
assertEquals(java.util.Map.of("team", "data"), cluster.getTags());
assertEquals(Map.of("team", "data"), cluster.getTags());
}
@Test
void testCreateTagsRejectsNonArnResourceName() {
assertThrows(AwsException.class, () ->
service.createTags("my-cluster", java.util.Map.of("env", "test")));
service.createTags("my-cluster", 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")));
service.createTags("arn:aws:redshift:us-east-1:111111111111:reservednode:foo", 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")));
cluster.setTags(new LinkedHashMap<>(Map.of("env", "test")));
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
List<RedshiftService.TaggedResource> tagged =
@@ -664,14 +1016,14 @@ class RedshiftServiceTest {
void testDescribeTagsScansAllResourcesOfType() {
Cluster a = new Cluster();
a.setClusterIdentifier("cluster-a");
a.setTags(new java.util.LinkedHashMap<>(java.util.Map.of("env", "prod")));
a.setTags(new LinkedHashMap<>(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());
b.setTags(new LinkedHashMap<>());
when(clusterBackend.scan(any())).thenReturn(List.of(a, b));
when(snapshotBackend.scan(any())).thenReturn(List.of());
when(parameterGroupBackend.scan(any())).thenReturn(List.of());
when(subnetGroupBackend.scan(any())).thenReturn(List.of());
List<RedshiftService.TaggedResource> tagged = service.describeTags(null, "cluster", null);
@@ -23,10 +23,15 @@ import io.github.hectorvent.floci.services.redshift.model.Cluster;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import com.github.dockerjava.api.command.CopyArchiveFromContainerCmd;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -65,6 +70,28 @@ class RedshiftContainerManagerTest {
when(config.services().redshift().imageVersion()).thenReturn("postgres:16-alpine");
when(config.services().redshift().dockerNetwork()).thenReturn(Optional.empty());
// Default mock for execCreateCmd/execStartCmd/inspectExecCmd to make waitForReady succeed instantly
ExecCreateCmd defaultCreateCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
ExecCreateCmdResponse defaultCreateResponse = mock(ExecCreateCmdResponse.class);
when(defaultCreateResponse.getId()).thenReturn("exec-default");
when(defaultCreateCmd.exec()).thenReturn(defaultCreateResponse);
when(dockerClient.execCreateCmd(anyString())).thenReturn(defaultCreateCmd);
ExecStartCmd defaultStartCmd = mock(ExecStartCmd.class);
when(defaultStartCmd.exec(any())).thenAnswer(invocation -> {
@SuppressWarnings("unchecked")
ResultCallback.Adapter<Frame> adapter = invocation.getArgument(0);
adapter.onComplete();
return adapter;
});
when(dockerClient.execStartCmd(anyString())).thenReturn(defaultStartCmd);
InspectExecCmd defaultInspectCmd = mock(InspectExecCmd.class);
InspectExecResponse defaultInspectResponse = mock(InspectExecResponse.class);
when(defaultInspectResponse.getExitCodeLong()).thenReturn(0L);
when(defaultInspectCmd.exec()).thenReturn(defaultInspectResponse);
when(dockerClient.inspectExecCmd(anyString())).thenReturn(defaultInspectCmd);
manager = new RedshiftContainerManager(
containerBuilder,
lifecycleManager,
@@ -79,7 +106,7 @@ class RedshiftContainerManagerTest {
@Test
void testTakeSnapshotContainerNotFound() {
AwsException ex = assertThrows(AwsException.class, () ->
manager.takeSnapshot(ACCOUNT_ID, "non-existent-cluster", "admin", "dev", java.nio.file.Path.of("dummy.sql")));
manager.takeSnapshot(ACCOUNT_ID, "non-existent-cluster", "admin", "dev", Path.of("dummy.sql")));
assertEquals("ClusterNotFound", ex.getErrorCode());
assertEquals(404, ex.getHttpStatus());
}
@@ -87,7 +114,7 @@ class RedshiftContainerManagerTest {
@Test
void testRestoreSnapshotContainerNotFound() {
AwsException ex = assertThrows(AwsException.class, () ->
manager.restoreSnapshot(ACCOUNT_ID, "non-existent-cluster", "admin", "dev", java.nio.file.Path.of("dummy.sql")));
manager.restoreSnapshot(ACCOUNT_ID, "non-existent-cluster", "admin", "dev", Path.of("dummy.sql")));
assertEquals("ClusterNotFound", ex.getErrorCode());
assertEquals(404, ex.getHttpStatus());
}
@@ -95,7 +122,7 @@ class RedshiftContainerManagerTest {
@Test
void testCreateSnapshotNullCluster() {
AwsException ex = assertThrows(AwsException.class, () ->
manager.createSnapshot(ACCOUNT_ID, null, java.nio.file.Path.of("dummy.sql")));
manager.createSnapshot(ACCOUNT_ID, null, Path.of("dummy.sql")));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@@ -103,7 +130,7 @@ class RedshiftContainerManagerTest {
@Test
void testRestoreSnapshotNullCluster() {
AwsException ex = assertThrows(AwsException.class, () ->
manager.restoreSnapshot(ACCOUNT_ID, (Cluster) null, java.nio.file.Path.of("dummy.sql")));
manager.restoreSnapshot(ACCOUNT_ID, (Cluster) null, Path.of("dummy.sql")));
assertEquals("InvalidParameterValue", ex.getErrorCode());
assertEquals(400, ex.getHttpStatus());
}
@@ -143,9 +170,9 @@ class RedshiftContainerManagerTest {
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);
CopyArchiveFromContainerCmd copyCmd = mock(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();
ByteArrayOutputStream bos = new 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);
@@ -153,17 +180,17 @@ class RedshiftContainerManagerTest {
tar.write(tarBytes);
tar.closeArchiveEntry();
}
when(copyCmd.exec()).thenReturn(new java.io.ByteArrayInputStream(bos.toByteArray()));
when(copyCmd.exec()).thenReturn(new 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");
Path tempFile = Files.createTempFile("test-take-snapshot", ".sql");
try {
manager.takeSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",tempFile);
String dump = java.nio.file.Files.readString(tempFile);
String dump = Files.readString(tempFile);
assertTrue(dump.contains("PostgreSQL dump"));
assertTrue(dump.contains("CREATE TABLE foo"));
} finally {
java.nio.file.Files.deleteIfExists(tempFile);
Files.deleteIfExists(tempFile);
}
}
@@ -200,7 +227,7 @@ class RedshiftContainerManagerTest {
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")));
manager.takeSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",Path.of("dummy.sql")));
assertEquals("InternalFailure", ex.getErrorCode());
assertEquals(500, ex.getHttpStatus());
}
@@ -215,8 +242,8 @@ class RedshiftContainerManagerTest {
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);
manager.restoreSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",Path.of("non-existent-dump.sql"));
manager.restoreSnapshot(ACCOUNT_ID, "test-cluster", "admin", "dev",(Path) null);
}
@Test
@@ -254,13 +281,13 @@ class RedshiftContainerManagerTest {
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");
Path tempFile = 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");
verify(dockerClient, org.mockito.Mockito.times(2)).execCreateCmd("cont-123");
} finally {
java.nio.file.Files.deleteIfExists(tempFile);
Files.deleteIfExists(tempFile);
}
}
@@ -363,7 +390,7 @@ class RedshiftContainerManagerTest {
manager.alterUserPassword(ACCOUNT_ID, "test-cluster", "admin", "NewSecret1");
verify(dockerClient).execCreateCmd("cont-123");
verify(dockerClient, org.mockito.Mockito.times(2)).execCreateCmd("cont-123");
}
@Test
@@ -0,0 +1,45 @@
package io.github.hectorvent.floci.services.redshift.model;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class ClusterTest {
@Test
void proxyAndContainerFieldsDefaultToEmpty() {
Cluster cluster = new Cluster();
assertNull(cluster.getContainerHost());
assertEquals(0, cluster.getContainerPort());
assertEquals(0, cluster.getProxyPort());
}
@Test
void proxyAndContainerFieldsRoundTripThroughJackson() throws Exception {
ObjectMapper mapper = new ObjectMapper();
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("c1");
cluster.setContainerHost("172.17.0.4");
cluster.setContainerPort(32771);
cluster.setProxyPort(7100);
Cluster restored = mapper.readValue(mapper.writeValueAsString(cluster), Cluster.class);
assertEquals("172.17.0.4", restored.getContainerHost());
assertEquals(32771, restored.getContainerPort());
assertEquals(7100, restored.getProxyPort());
}
@Test
void jsonWithoutNewFieldsDeserializesWithDefaults() throws Exception {
ObjectMapper mapper = new ObjectMapper();
Cluster restored = mapper.readValue(
"{\"clusterIdentifier\":\"legacy\",\"clusterStatus\":\"available\"}", Cluster.class);
assertNull(restored.getContainerHost());
assertEquals(0, restored.getContainerPort());
assertEquals(0, restored.getProxyPort());
}
}
@@ -0,0 +1,205 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RedshiftAuthProxyTest {
@TempDir
Path tempDir;
private RedshiftAuthProxy proxy;
private ServerSocket fakeBackend;
@AfterEach
void tearDown() throws IOException {
if (proxy != null) {
proxy.stop();
}
if (fakeBackend != null && !fakeBackend.isClosed()) {
fakeBackend.close();
}
}
@Test
void bridgesClientBytesToTheBackendAfterASuccessfulPasswordAuth() throws Exception {
// The fake backend accepts one connection and records the first bytes it receives
// from the proxy (the forwarded PostgreSQL startup packet).
fakeBackend = new ServerSocket(0);
AtomicReference<byte[]> seenByBackend = new AtomicReference<>();
CountDownLatch backendDone = new CountDownLatch(1);
Thread.ofVirtual().start(() -> {
try (Socket s = fakeBackend.accept()) {
InputStream in = s.getInputStream();
byte[] buf = new byte[256];
int n = in.read(buf);
byte[] out = new byte[Math.max(n, 0)];
System.arraycopy(buf, 0, out, 0, out.length);
seenByBackend.set(out);
backendDone.countDown();
} catch (IOException ignored) {
backendDone.countDown();
}
});
int proxyPort = freePort();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true);
proxy.start(proxyPort);
try (Socket client = new Socket("localhost", proxyPort)) {
// Minimal PostgreSQL v3 startup: length(4) + protocol(4) + "user\0admin\0\0"
OutputStream out = client.getOutputStream();
byte[] params = "user\0admin\0\0".getBytes(StandardCharsets.UTF_8);
int len = 8 + params.length;
out.write(new byte[]{(byte) (len >>> 24), (byte) (len >>> 16), (byte) (len >>> 8), (byte) len});
out.write(new byte[]{0, 3, 0, 0}); // protocol 196608
out.write(params);
out.flush();
// Read the AuthenticationCleartextPassword request ('R') and reply with a password message.
InputStream in = client.getInputStream();
assertEquals('R', in.read());
in.readNBytes(7); // remaining length(4) + auth code(3 of the 4-byte int)
OutputStream pw = client.getOutputStream();
byte[] pwBytes = "Secret123\0".getBytes(StandardCharsets.UTF_8);
pw.write('p');
int pwLen = 4 + pwBytes.length;
pw.write(new byte[]{(byte) (pwLen >>> 24), (byte) (pwLen >>> 16), (byte) (pwLen >>> 8), (byte) pwLen});
pw.write(pwBytes);
pw.flush();
assertTrue(backendDone.await(5, TimeUnit.SECONDS), "backend never saw the forwarded startup packet");
byte[] forwarded = seenByBackend.get();
assertTrue(forwarded != null && forwarded.length > 0, "proxy forwarded no bytes to the backend");
}
}
@Test
void closesTheBackendConnectionWhenTheClientDropsMidHandshake() throws Exception {
fakeBackend = new ServerSocket(0);
CountDownLatch backendClosed = new CountDownLatch(1);
Thread.ofVirtual().start(() -> {
try (Socket s = fakeBackend.accept()) {
// The proxy opens this before reading the client's startup packet; if the
// client vanishes, the proxy must close this too — surfaced here as EOF.
InputStream in = s.getInputStream();
while (in.read() != -1) {
// drain until the proxy closes its end
}
backendClosed.countDown();
} catch (IOException e) {
backendClosed.countDown();
}
});
int proxyPort = freePort();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true);
proxy.start(proxyPort);
// Connect, then drop without ever sending a startup packet.
new Socket("localhost", proxyPort).close();
assertTrue(backendClosed.await(5, TimeUnit.SECONDS),
"proxy leaked the backend connection after the client dropped");
}
@Test
void startRetriesTheBindWhileThePortIsMomentarilyStillInUse() throws Exception {
fakeBackend = new ServerSocket(0);
int proxyPort = freePort();
// Hold the port, mimicking a just-closed predecessor the kernel has not released
// yet; free it shortly after so the retrying bind can finally take it.
ServerSocket squatter = new ServerSocket();
squatter.setReuseAddress(true);
squatter.bind(new java.net.InetSocketAddress(proxyPort));
Thread.ofVirtual().start(() -> {
try {
Thread.sleep(200);
squatter.close();
} catch (Exception ignored) {
}
});
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true);
proxy.start(proxyPort); // must not throw despite the port being busy at first
assertTrue(portAccepts(proxyPort), "proxy never bound the port after the squatter released it");
}
@Test
void updateMasterPasswordSwapsTheSnapshotUsedForNewConnections() throws Exception {
fakeBackend = new ServerSocket(0);
int proxyPort = freePort();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "old", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true);
proxy.start(proxyPort);
proxy.updateMasterPassword("rotated");
Field f = RedshiftAuthProxy.class.getDeclaredField("masterPassword");
f.setAccessible(true);
assertEquals("rotated", f.get(proxy));
}
private RdsProxyTlsCertificates realTls() {
// The real bean generates a self-signed cert on demand; no Docker or network needed.
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
when(storage.persistentPath()).thenReturn(tempDir.toString());
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.storage()).thenReturn(storage);
return new RdsProxyTlsCertificates(config, new CertificateGenerator());
}
private static int freePort() throws IOException {
try (ServerSocket s = new ServerSocket(0)) {
return s.getLocalPort();
}
}
private static boolean portAccepts(int port) {
for (int attempt = 0; attempt < 50; attempt++) {
try (Socket ignored = new Socket("localhost", port)) {
return true;
} catch (IOException e) {
try {
Thread.sleep(20);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return false;
}
}
}
return false;
}
}
@@ -0,0 +1,287 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class RedshiftProxyManagerTest {
private RedshiftProxyManager newManager() {
return new RedshiftProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
}
private static void start(RedshiftProxyManager manager, String key, int proxyPort) {
manager.startProxy(key, proxyPort, "localhost", 1, "localhost",
"admin", "secret", "dev", (user, password) -> true);
}
@Test
void startRegistersTheKeyAndBindsThePort() throws Exception {
RedshiftProxyManager manager = newManager();
int port = availablePort();
try {
start(manager, "111111111111:c1", port);
assertTrue(registry(manager).containsKey("111111111111:c1"));
assertPortUnavailable(port);
} finally {
manager.stopAll();
}
}
@Test
void stopProxyRemovesTheKeyAndReleasesThePort() throws Exception {
RedshiftProxyManager manager = newManager();
int port = availablePort();
start(manager, "k", port);
manager.stopProxy("k");
assertFalse(registry(manager).containsKey("k"));
assertPortAvailable(port);
}
@Test
void startingAnExistingKeyStopsTheOldProxyAndInstallsTheNewOne() throws IOException {
RedshiftProxyManager manager = newManager();
int firstPort = availablePort();
try {
start(manager, "k", firstPort);
int replacementPort = availablePort();
start(manager, "k", replacementPort);
assertPortAvailable(firstPort);
assertPortUnavailable(replacementPort);
} finally {
manager.stopAll();
}
}
@Test
void updateMasterPasswordForUnknownKeyIsANoOp() {
RedshiftProxyManager manager = newManager();
assertDoesNotThrow(() -> manager.updateMasterPassword("missing", "rotated"));
}
@Test
void updateMasterPasswordSwapsTheRunningSnapshot() throws Exception {
RedshiftProxyManager manager = newManager();
int port = availablePort();
try {
start(manager, "k", port);
manager.updateMasterPassword("k", "rotated");
assertEquals("rotated", masterPassword(registry(manager).get("k")));
} finally {
manager.stopAll();
}
}
@Test
void stopAllReleasesEveryListenerAndIsIdempotent() throws IOException {
RedshiftProxyManager manager = newManager();
int a = availablePort();
start(manager, "a", a);
int b = availablePort();
start(manager, "b", b);
manager.stopAll();
assertPortAvailable(a);
assertPortAvailable(b);
assertDoesNotThrow(manager::stopAll);
}
@Test
void failedStartOnABusyPortLeavesNoRegistryEntry() throws Exception {
RedshiftProxyManager manager = newManager();
try (ServerSocket occupied = new ServerSocket(0)) {
assertThrows(RuntimeException.class,
() -> start(manager, "k", occupied.getLocalPort()));
assertFalse(registry(manager).containsKey("k"));
} finally {
manager.stopAll();
}
}
@Test
void stopProxyRetainsTheProxyWhenItsListenerCloseFails() throws Exception {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy badProxy = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).when(badProxy).stop();
registry(manager).put("k", badProxy);
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
// Proxy stays registered so a later cleanup attempt can still reach it and retry.
assertSame(badProxy, registry(manager).get("k"));
}
@Test
void stopProxyRetryClosesTheSameProxyAndThenDeregistersIt() throws Exception {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy proxy = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).doNothing().when(proxy).stop();
registry(manager).put("k", proxy);
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
assertDoesNotThrow(() -> manager.stopProxy("k"));
assertFalse(registry(manager).containsKey("k"));
verify(proxy, times(2)).stop();
}
@Test
void stopProxyRefusesWhileAFailedStartupListenerStillCannotBeClosed() throws Exception {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy stuck = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).when(stuck).stop();
unclosable(manager).put("k", stuck);
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
// Reference retained so the next attempt can retry the close.
assertSame(stuck, unclosable(manager).get("k"));
}
@Test
void stopProxyKeepsRetryingTheSameUnclosableListenerOnEveryCall() throws Exception {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy stuck = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).when(stuck).stop();
unclosable(manager).put("k", stuck);
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
verify(stuck, times(2)).stop();
assertTrue(unclosable(manager).containsKey("k"));
}
@Test
void stopProxyRecoversTheUnclosableEntryOnceTheListenerFinallyCloses() throws Exception {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy recovering = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).doNothing().when(recovering).stop();
unclosable(manager).put("k", recovering);
assertThrows(RuntimeException.class, () -> manager.stopProxy("k"));
assertDoesNotThrow(() -> manager.stopProxy("k"));
assertFalse(unclosable(manager).containsKey("k"));
}
@Test
void startProxyLeavesAnUnclosableEntryInPlace() throws Exception {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy stuck = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).when(stuck).stop();
unclosable(manager).put("k", stuck);
int port = availablePort();
try {
// A fresh start for the same key must not silently drop the leaked listener.
start(manager, "k", port);
assertSame(stuck, unclosable(manager).get("k"));
} finally {
manager.stopAll();
}
}
@Test
void stopAllAlsoDrainsUnclosableProxies() throws Exception {
RedshiftProxyManager manager = newManager();
RedshiftAuthProxy recovered = mock(RedshiftAuthProxy.class);
RedshiftAuthProxy stillStuck = mock(RedshiftAuthProxy.class);
doThrow(new RuntimeException("close failed")).when(stillStuck).stop();
unclosable(manager).put("a", recovered);
unclosable(manager).put("b", stillStuck);
manager.stopAll();
assertFalse(unclosable(manager).containsKey("a"));
assertTrue(unclosable(manager).containsKey("b"));
}
// --- reflection + port helpers copied from RdsProxyManagerTest ---
@SuppressWarnings("unchecked")
private static ConcurrentHashMap<String, RedshiftAuthProxy> registry(RedshiftProxyManager manager)
throws Exception {
Field field = RedshiftProxyManager.class.getDeclaredField("proxies");
field.setAccessible(true);
return (ConcurrentHashMap<String, RedshiftAuthProxy>) field.get(manager);
}
@SuppressWarnings("unchecked")
private static ConcurrentHashMap<String, RedshiftAuthProxy> unclosable(RedshiftProxyManager manager)
throws Exception {
Field field = RedshiftProxyManager.class.getDeclaredField("unclosableProxies");
field.setAccessible(true);
return (ConcurrentHashMap<String, RedshiftAuthProxy>) field.get(manager);
}
private static String masterPassword(RedshiftAuthProxy proxy) throws Exception {
Field field = RedshiftAuthProxy.class.getDeclaredField("masterPassword");
field.setAccessible(true);
return (String) field.get(proxy);
}
private static int availablePort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
}
}
private static void assertPortAvailable(int port) {
IOException last = null;
for (int attempt = 0; attempt < 50; attempt++) {
try (ServerSocket ignored = reusableSocket(port)) {
return;
} catch (IOException e) {
last = e;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
fail("Interrupted waiting for port " + port, e);
}
}
fail("Proxy port " + port + " was not released", last);
}
private static void assertPortUnavailable(int port) {
assertThrows(IOException.class, () -> {
try (ServerSocket ignored = reusableSocket(port)) {
// active proxy owns this listener
}
});
}
private static ServerSocket reusableSocket(int port) throws IOException {
ServerSocket socket = new ServerSocket();
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(port));
return socket;
}
}