fix(rds): bound RDS/Redshift auth proxy connections and handshakes (#3545)

Cap concurrent proxy connections with a per-proxy semaphore, apply
configurable handshake and backend-connect timeouts to both the
client and backend sockets, and defer backend PostgreSQL connects
until after client auth completes. Close leaked backend sockets
defensively on every exit path, including a RuntimeException thrown
between authenticate() returning a session and the bridge finishing
its own cleanup, and bound backend-side reads during the handshake
so a silent backend that accepts TCP but never answers cannot pin a
handler thread and its connection permit forever.

New EmulatorConfig keys under services.rds and services.redshift:
proxy-handshake-timeout-millis (default 10000),
proxy-backend-connect-timeout-millis (default 5000),
proxy-max-connections (default 100).
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-14 10:48:48 -04:00
1 parent ffd2488f02
commit 1987bf0c96
19 files changed
+649 -163

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 static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class RdsProxyConfigTest {
@Inject
EmulatorConfig config;
@Test
void rdsProxyPortRangeHasDefaults() {
assertEquals(7001, config.services().rds().proxyBasePort());
assertEquals(7099, config.services().rds().proxyMaxPort());
}
@Test
void rdsProxyBoundsHaveDefaults() {
assertEquals(10000, config.services().rds().proxyHandshakeTimeoutMillis());
assertEquals(5000, config.services().rds().proxyBackendConnectTimeoutMillis());
assertEquals(100, config.services().rds().proxyMaxConnections());
}
}
@@ -24,4 +24,11 @@ class RedshiftProxyConfigTest {
void redshiftEndpointHostDefaultsToEmpty() {
assertEquals(Optional.empty(), config.services().redshift().endpointHost());
}
@Test
void redshiftProxyBoundsHaveDefaults() {
assertEquals(10000, config.services().redshift().proxyHandshakeTimeoutMillis());
assertEquals(5000, config.services().redshift().proxyBackendConnectTimeoutMillis());
assertEquals(100, config.services().redshift().proxyMaxConnections());
}
}
@@ -66,7 +66,7 @@ class MySqlProtocolHandlerTest {
MySqlProtocolHandler.handleAuth(
proxyClient, backend, "admin", "secret",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -128,7 +128,7 @@ class MySqlProtocolHandlerTest {
MySqlProtocolHandler.handleAuth(
proxyClient, backend, "admin", "secret",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -184,7 +184,7 @@ class MySqlProtocolHandlerTest {
MySqlProtocolHandler.handleAuth(
proxyClient, backend, "admin", "secret",
false, testSigV4Validator(), tlsCertificates,
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -282,7 +282,7 @@ class MySqlProtocolHandlerTest {
MySqlProtocolHandler.handleAuth(
proxyClient, backend, "admin", "secret",
false, testSigV4Validator(), tlsCertificates,
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -328,6 +328,41 @@ class MySqlProtocolHandlerTest {
}
}
@Test
void silentBackendHandshakeFailsWithinTheConfiguredTimeoutInsteadOfHanging() throws Exception {
try (ServerSocket silentBackend = new ServerSocket(0);
ServerSocket clientServer = new ServerSocket(0)) {
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
Socket proxyClient = clientServer.accept();
Socket backend = new Socket("localhost", silentBackend.getLocalPort());
AtomicReference<IOException> authFailure = new AtomicReference<>();
Thread authThread = Thread.ofVirtual().start(() -> {
try {
MySqlProtocolHandler.handleAuth(
proxyClient, backend, "admin", "secret",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 200);
} catch (IOException e) {
authFailure.set(e);
}
});
// The silent backend accepts the TCP connection but never sends its Handshake V10;
// the backend-side handshake read deadline must fire well within the 5s join instead
// of hanging forever.
authThread.join(5_000);
assertEquals(false, authThread.isAlive(), "authThread did not terminate");
assertNotNull(authFailure.get(),
"expected handleAuth to fail once the backend stayed silent");
ourClient.close();
proxyClient.close();
}
}
}
private RdsProxyTlsCertificates testTlsCertificates() {
EmulatorConfig.StorageConfig storage = mock(EmulatorConfig.StorageConfig.class);
when(storage.persistentPath()).thenReturn(tempDir.toString());
@@ -36,6 +36,7 @@ import java.security.cert.X509Certificate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
@@ -46,6 +47,11 @@ class PostgresProtocolHandlerTest {
private static final int SSL_REQUEST_CODE = 80877103;
private static final int STARTUP_PROTOCOL_VERSION = 196608;
/** Fails the test if the backend is ever contacted; the client fails validation first. */
private static final PostgresProtocolHandler.BackendConnector NEVER_CONNECT = () -> {
throw new AssertionError("backend must not be contacted before the client is authenticated");
};
@TempDir
Path tempDir;
@@ -57,10 +63,10 @@ class PostgresProtocolHandlerTest {
out.writeInt(STARTUP_PROTOCOL_VERSION);
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
new MemorySocket(input.toByteArray()), mock(Socket.class),
new MemorySocket(input.toByteArray()), NEVER_CONNECT,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
assertEquals("PostgreSQL startup message length exceeds the 1048576 byte limit: 1048577",
error.getMessage());
@@ -78,10 +84,10 @@ class PostgresProtocolHandlerTest {
MemorySocket client = new MemorySocket(startup);
assertNull(PostgresProtocolHandler.authenticate(
client, new MemorySocket(new byte[0]),
client, NEVER_CONNECT,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
}
@Test
@@ -92,10 +98,10 @@ class PostgresProtocolHandlerTest {
out.writeInt(STARTUP_PROTOCOL_VERSION);
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
new MemorySocket(input.toByteArray()), new MemorySocket(new byte[0]),
new MemorySocket(input.toByteArray()), NEVER_CONNECT,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
assertEquals("PostgreSQL startup message length is below the 8 byte minimum: -1",
error.getMessage());
@@ -110,10 +116,10 @@ class PostgresProtocolHandlerTest {
out.writeInt(4);
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
new MemorySocket(input.toByteArray()), new MemorySocket(new byte[0]),
new MemorySocket(input.toByteArray()), NEVER_CONNECT,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
assertEquals("PostgreSQL password message length is below the 5 byte minimum: 4",
error.getMessage());
@@ -127,10 +133,10 @@ class PostgresProtocolHandlerTest {
backendOut.writeInt(1_048_577);
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
new MemorySocket(startupAndPassword()), new MemorySocket(backendInput.toByteArray()),
new MemorySocket(startupAndPassword()), () -> new MemorySocket(backendInput.toByteArray()),
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
assertEquals("PostgreSQL backend authentication message length exceeds the 1048576 byte limit: 1048577",
error.getMessage());
@@ -147,10 +153,10 @@ class PostgresProtocolHandlerTest {
backendOut.writeInt(1_048_577);
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
new MemorySocket(startupAndPassword()), new MemorySocket(backendInput.toByteArray()),
new MemorySocket(startupAndPassword()), () -> new MemorySocket(backendInput.toByteArray()),
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
assertEquals("PostgreSQL backend message length exceeds the 1048576 byte limit: 1048577",
error.getMessage());
@@ -167,10 +173,10 @@ class PostgresProtocolHandlerTest {
backendOut.writeInt(1_048_577);
IOException error = assertThrows(IOException.class, () -> PostgresProtocolHandler.authenticate(
new MemorySocket(startupAndPassword()), new MemorySocket(backendInput.toByteArray()),
new MemorySocket(startupAndPassword()), () -> new MemorySocket(backendInput.toByteArray()),
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT));
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000));
assertEquals("PostgreSQL SASL continue message length exceeds the 1048576 byte limit: 1048577",
error.getMessage());
@@ -214,12 +220,12 @@ class PostgresProtocolHandlerTest {
try {
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
proxyClient, backend,
proxyClient, () -> backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
PostgresProtocolHandler.bridge(session);
}
} catch (IOException e) {
throw new RuntimeException(e);
@@ -272,12 +278,12 @@ class PostgresProtocolHandlerTest {
try {
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
proxyClient, backend,
proxyClient, () -> backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
PostgresProtocolHandler.bridge(session);
}
} catch (IOException e) {
throw new RuntimeException(e);
@@ -330,12 +336,12 @@ class PostgresProtocolHandlerTest {
try {
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
proxyClient, backend,
proxyClient, () -> backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
PostgresProtocolHandler.bridge(session);
}
} catch (IOException e) {
throw new RuntimeException(e);
@@ -397,12 +403,12 @@ class PostgresProtocolHandlerTest {
try {
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
proxyClient, backend,
proxyClient, () -> backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), tlsCertificates,
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
PostgresProtocolHandler.bridge(session);
}
} catch (IOException e) {
throw new RuntimeException(e);
@@ -451,12 +457,12 @@ class PostgresProtocolHandlerTest {
try {
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
proxyClient, backend,
proxyClient, () -> backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), tlsCertificates,
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
PostgresProtocolHandler.bridge(session);
}
} catch (IOException ignored) {
// Client aborts the handshake below — the handler observing that is expected.
@@ -501,12 +507,12 @@ class PostgresProtocolHandlerTest {
try {
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
proxyClient, backend,
proxyClient, () -> backend,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
PostgresProtocolHandler.bridge(session);
}
} catch (IOException e) {
throw new RuntimeException(e);
@@ -848,17 +854,62 @@ class PostgresProtocolHandlerTest {
assertEquals("\"app\"\"role\"", PostgresProtocolHandler.quoteIdentifier("app\"role"));
}
@Test
void backendThatAcceptsButNeverAnswersFailsWithinTheHandshakeTimeout() throws Exception {
try (ServerSocket silentBackend = new ServerSocket(0);
ServerSocket clientServer = new ServerSocket(0)) {
PostgresProtocolHandler.BackendConnector connector =
() -> new Socket("localhost", silentBackend.getLocalPort());
Socket proxyClient;
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
proxyClient = clientServer.accept();
AtomicReference<IOException> authFailure = new AtomicReference<>();
Thread authThread = Thread.ofVirtual().start(() -> {
try {
PostgresProtocolHandler.authenticate(
proxyClient, connector,
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 200);
} catch (IOException e) {
authFailure.set(e);
}
});
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
writeStartup(clientOut, "dbadmin", "postgres");
readCleartextPasswordChallenge(clientIn);
writePassword(clientOut, "adminpass");
// The silent backend accepts the TCP connection but never answers; the backend-side
// handshake read deadline must fire well within the 5s join instead of hanging.
authThread.join(5_000);
assertEquals(false, authThread.isAlive(), "authThread did not terminate");
assertNotNull(authFailure.get(),
"expected authenticate to fail once the backend stayed silent");
ourClient.close();
proxyClient.close();
}
}
}
private Thread startIamAuth(Socket proxyClient, Socket backend) {
return Thread.ofVirtual().start(() -> {
try {
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
proxyClient, backend,
proxyClient, () -> backend,
"dbadmin", "adminpass", "postgres",
true, testSigV4Validator(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT);
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
PostgresProtocolHandler.bridge(session);
}
} catch (IOException e) {
throw new RuntimeException(e);
@@ -0,0 +1,126 @@
package io.github.hectorvent.floci.services.rds.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
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.lang.reflect.Field;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.file.Path;
import java.util.concurrent.Semaphore;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Covers the connection bounds (handshake timeout, backend-connect deferral, permit pool) added
* to {@link RdsAuthProxy} for the POSTGRES engine, mirroring the equivalent coverage in
* {@code RedshiftAuthProxyTest}.
*/
class RdsAuthProxyBoundsTest {
@TempDir
Path tempDir;
private RdsAuthProxy proxy;
private ServerSocket fakeBackend;
@AfterEach
void tearDown() throws IOException {
if (proxy != null) {
proxy.stop();
}
if (fakeBackend != null && !fakeBackend.isClosed()) {
fakeBackend.close();
}
}
@Test
void neverConnectsToTheBackendWhenTheClientDropsBeforeSendingAStartupPacket() throws Exception {
// Postgres startup is client-first: the backend connection is opened only after the
// client's startup message has been validated, so a client that vanishes beforehand
// must never cause a backend connection.
fakeBackend = new ServerSocket(0);
fakeBackend.setSoTimeout(500);
int proxyPort = freePort();
proxy = newProxy(5000, 5000, 100);
proxy.start(proxyPort);
new Socket("localhost", proxyPort).close();
assertThrows(SocketTimeoutException.class, fakeBackend::accept,
"proxy connected to the backend before validating the client's startup message");
}
@Test
void idleClientIsDroppedAfterTheConfiguredHandshakeTimeout() throws Exception {
fakeBackend = new ServerSocket(0);
int proxyPort = freePort();
proxy = newProxy(200, 5000, 100);
proxy.start(proxyPort);
try (Socket client = new Socket("localhost", proxyPort)) {
client.setSoTimeout(5000);
// Send nothing; the proxy must drop the connection once the handshake timeout
// elapses. The client observes this as EOF once the proxy closes its end.
int result = client.getInputStream().read();
assertEquals(-1, result, "proxy did not drop an idle client after the handshake timeout");
}
}
@Test
void refusesAConnectionBeyondTheConfiguredLimit() throws Exception {
fakeBackend = new ServerSocket(0);
int proxyPort = freePort();
proxy = newProxy(5000, 5000, 1);
proxy.start(proxyPort);
// Hold the proxy's single connection permit from the test thread itself, so the
// refusal below is deterministic rather than a race against a real first connection.
Field permitsField = RdsAuthProxy.class.getDeclaredField("connectionPermits");
permitsField.setAccessible(true);
Semaphore permits = (Semaphore) permitsField.get(proxy);
assertTrue(permits.tryAcquire(), "expected the single configured permit to be available");
try (Socket client = new Socket("localhost", proxyPort)) {
int result = client.getInputStream().read();
assertEquals(-1, result, "connection was not refused once the connection limit was reached");
} finally {
permits.release();
}
}
private RdsAuthProxy newProxy(int handshakeTimeoutMillis, int backendConnectTimeoutMillis,
int maxConnections) {
return new RdsAuthProxy("db-1", "localhost", fakeBackend.getLocalPort(),
DatabaseEngine.POSTGRES, false,
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true,
handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections);
}
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();
}
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.rds.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import org.junit.jupiter.api.Test;
@@ -18,13 +19,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class RdsProxyManagerTest {
@Test
void replacingProxyStopsPreviousListenerAndKeepsReplacementOwned() throws IOException {
RdsProxyManager manager = new RdsProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig());
int firstPort = availablePort();
try {
start(manager, "proxy", firstPort);
@@ -44,7 +46,7 @@ class RdsProxyManagerTest {
@Test
void registrationFailureAfterBindReleasesCandidateListener() throws IOException {
RdsProxyManager manager = new RdsProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig());
int proxyPort = availablePort();
try {
assertThrows(RuntimeException.class, () -> start(manager, null, proxyPort));
@@ -58,7 +60,7 @@ class RdsProxyManagerTest {
@Test
void failedReplacementPreservesOriginalRegistryEntry() throws IOException {
RdsProxyManager manager = new RdsProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig());
int originalPort = availablePort();
try {
start(manager, "proxy", originalPort);
@@ -78,7 +80,7 @@ class RdsProxyManagerTest {
@Test
void updateMasterPasswordSwapsTheRunningProxySnapshotWithoutARestart() throws Exception {
RdsProxyManager manager = new RdsProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig());
int proxyPort = availablePort();
try {
start(manager, "proxy", proxyPort);
@@ -95,7 +97,7 @@ class RdsProxyManagerTest {
@Test
void updateMasterPasswordForUnknownInstanceIsANoOp() {
RdsProxyManager manager = new RdsProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig());
assertDoesNotThrow(() -> manager.updateMasterPassword("missing", "rotated"));
}
@@ -103,7 +105,7 @@ class RdsProxyManagerTest {
@Test
void stopAllReleasesEveryListenerAndIsIdempotent() throws IOException {
RdsProxyManager manager = new RdsProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig());
int firstPort = availablePort();
start(manager, "first", firstPort);
int secondPort = availablePort();
@@ -119,7 +121,7 @@ class RdsProxyManagerTest {
@Test
void closeFailurePropagatesAndManagerRetainsOwnership() throws Exception {
RdsProxyManager manager = new RdsProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig());
RdsAuthProxy proxy = authProxy("proxy");
ServerSocket serverSocket = mock(ServerSocket.class);
IOException closeFailure = new IOException("simulated close failure");
@@ -139,7 +141,7 @@ class RdsProxyManagerTest {
@Test
void failedPreviousStopRestoresMappingAndReleasesCandidate() throws Exception {
RdsProxyManager manager = new RdsProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig());
RdsAuthProxy previous = mock(RdsAuthProxy.class);
doThrow(new IllegalStateException("simulated previous stop failure"))
.when(previous).stop();
@@ -157,7 +159,7 @@ class RdsProxyManagerTest {
@Test
void stopAllContinuesAndRetainsOnlyFailedListenerOwnership() throws Exception {
RdsProxyManager manager = new RdsProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class));
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig());
int successfulPort = availablePort();
start(manager, "successful", successfulPort);
RdsAuthProxy failed = mock(RdsAuthProxy.class);
@@ -182,7 +184,20 @@ class RdsProxyManagerTest {
private static RdsAuthProxy authProxy(String key) {
return new RdsAuthProxy(key, "localhost", 1, DatabaseEngine.POSTGRES, false,
"admin", "secret", "app", mock(RdsSigV4Validator.class),
mock(RdsProxyTlsCertificates.class), (user, password) -> true);
mock(RdsProxyTlsCertificates.class), (user, password) -> true,
5000, 5000, 100);
}
private static EmulatorConfig testConfig() {
EmulatorConfig.RdsServiceConfig rdsConfig = mock(EmulatorConfig.RdsServiceConfig.class);
when(rdsConfig.proxyHandshakeTimeoutMillis()).thenReturn(5000);
when(rdsConfig.proxyBackendConnectTimeoutMillis()).thenReturn(5000);
when(rdsConfig.proxyMaxConnections()).thenReturn(100);
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
when(servicesConfig.rds()).thenReturn(rdsConfig);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.services()).thenReturn(servicesConfig);
return config;
}
private static String masterPassword(RdsAuthProxy proxy) throws Exception {
@@ -17,13 +17,16 @@ import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -71,7 +74,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class));
mock(S3Service.class), 5000, 5000, 100);
proxy.start(proxyPort);
try (Socket client = new Socket("localhost", proxyPort)) {
@@ -104,35 +107,68 @@ class RedshiftAuthProxyTest {
}
@Test
void closesTheBackendConnectionWhenTheClientDropsMidHandshake() throws Exception {
void neverConnectsToTheBackendWhenTheClientDropsBeforeSendingAStartupPacket() throws Exception {
// The backend connection is opened only after the client's startup message has been
// validated; a client that vanishes beforehand must never cause a backend connection.
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();
}
});
fakeBackend.setSoTimeout(500);
int proxyPort = freePort();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class));
mock(S3Service.class), 5000, 5000, 100);
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");
assertThrows(SocketTimeoutException.class, fakeBackend::accept,
"proxy connected to the backend before validating the client's startup message");
}
@Test
void idleClientIsDroppedAfterTheConfiguredHandshakeTimeout() throws Exception {
fakeBackend = new ServerSocket(0);
int proxyPort = freePort();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class), 200, 5000, 100);
proxy.start(proxyPort);
try (Socket client = new Socket("localhost", proxyPort)) {
client.setSoTimeout(5000);
// Send nothing; the proxy must drop the connection once the handshake timeout
// elapses. The client observes this as EOF once the proxy closes its end.
int result = client.getInputStream().read();
assertEquals(-1, result, "proxy did not drop an idle client after the handshake timeout");
}
}
@Test
void refusesAConnectionBeyondTheConfiguredLimit() throws Exception {
fakeBackend = new ServerSocket(0);
int proxyPort = freePort();
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class), 5000, 5000, 1);
proxy.start(proxyPort);
// Hold the proxy's single connection permit from the test thread itself, so the
// refusal below is deterministic rather than a race against a real first connection.
Field permitsField = RedshiftAuthProxy.class.getDeclaredField("connectionPermits");
permitsField.setAccessible(true);
Semaphore permits = (Semaphore) permitsField.get(proxy);
assertTrue(permits.tryAcquire(), "expected the single configured permit to be available");
try (Socket client = new Socket("localhost", proxyPort)) {
int result = client.getInputStream().read();
assertEquals(-1, result, "connection was not refused once the connection limit was reached");
} finally {
permits.release();
}
}
@Test
@@ -156,7 +192,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "Secret123", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class));
mock(S3Service.class), 5000, 5000, 100);
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");
@@ -169,7 +205,7 @@ class RedshiftAuthProxyTest {
proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(),
"admin", "old", "dev",
mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
mock(S3Service.class));
mock(S3Service.class), 5000, 5000, 100);
proxy.start(proxyPort);
proxy.updateMasterPassword("rotated");
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyTlsCertificates;
import io.github.hectorvent.floci.services.rds.proxy.RdsSigV4Validator;
@@ -24,13 +25,26 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RedshiftProxyManagerTest {
private RedshiftProxyManager newManager() {
return new RedshiftProxyManager(
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class),
mock(S3Service.class));
mock(S3Service.class), testConfig());
}
private static EmulatorConfig testConfig() {
EmulatorConfig.RedshiftServiceConfig redshiftConfig = mock(EmulatorConfig.RedshiftServiceConfig.class);
when(redshiftConfig.proxyHandshakeTimeoutMillis()).thenReturn(5000);
when(redshiftConfig.proxyBackendConnectTimeoutMillis()).thenReturn(5000);
when(redshiftConfig.proxyMaxConnections()).thenReturn(100);
EmulatorConfig.ServicesConfig servicesConfig = mock(EmulatorConfig.ServicesConfig.class);
when(servicesConfig.redshift()).thenReturn(redshiftConfig);
EmulatorConfig config = mock(EmulatorConfig.class);
when(config.services()).thenReturn(servicesConfig);
return config;
}
private static void start(RedshiftProxyManager manager, String key, int proxyPort) {