diff --git a/docs/services/rds.md b/docs/services/rds.md index 4f0dc3a3d7..857edb3342 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -86,6 +86,9 @@ checked against the instance's other window. Modifications apply immediately — | `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Docker image for PostgreSQL instances | | `FLOCI_SERVICES_RDS_DEFAULT_MYSQL_IMAGE` | `mysql:8.0` | Docker image for MySQL instances | | `FLOCI_SERVICES_RDS_DEFAULT_MARIADB_IMAGE` | `mariadb:11` | Docker image for MariaDB instances | +| `FLOCI_SERVICES_RDS_PROXY_HANDSHAKE_TIMEOUT_MILLIS` | `10000` | Max time a client has to complete the startup/auth handshake before the proxy drops it | +| `FLOCI_SERVICES_RDS_PROXY_BACKEND_CONNECT_TIMEOUT_MILLIS` | `5000` | Max time the proxy waits for the backend TCP connect | +| `FLOCI_SERVICES_RDS_PROXY_MAX_CONNECTIONS` | `100` | Max concurrent connections per proxy before new ones are refused | ### Docker Compose diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 8a92d5f7ff..7416e14803 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -81,6 +81,9 @@ For `AWS::Redshift::ClusterParameterGroup`, `Parameters` is applied via `ModifyC | `FLOCI_SERVICES_REDSHIFT_PROXY_BASE_PORT` | `7100` | Lowest host port the per-cluster auth proxies bind | | `FLOCI_SERVICES_REDSHIFT_PROXY_MAX_PORT` | `7199` | Highest host port the per-cluster auth proxies bind | | `FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST` | _(unset)_ | Hostname advertised in `DescribeClusters`; unset resolves from the Docker host | +| `FLOCI_SERVICES_REDSHIFT_PROXY_HANDSHAKE_TIMEOUT_MILLIS` | `10000` | Max time a client has to complete the startup/auth handshake before the proxy drops it | +| `FLOCI_SERVICES_REDSHIFT_PROXY_BACKEND_CONNECT_TIMEOUT_MILLIS` | `5000` | Max time the proxy waits for the backend TCP connect | +| `FLOCI_SERVICES_REDSHIFT_PROXY_MAX_CONNECTIONS` | `100` | Max concurrent connections per proxy before new ones are refused | Redshift needs the Docker socket so it can launch PostgreSQL containers. Each cluster's container is published on a dynamically assigned host port, returned by `DescribeClusters`. diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 745373b938..e706677b48 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -1338,6 +1338,16 @@ public interface EmulatorConfig { // DurationSeconds is omitted. AWS allows 900 to 3600. @WithDefault("900") int defaultCredentialDurationSeconds(); + + // Bounds for the per-cluster auth proxy: how long a client has to complete the + // startup/auth handshake, how long a backend connect attempt may take, and how many + // concurrent connections the proxy accepts before refusing new ones. + @WithDefault("10000") + int proxyHandshakeTimeoutMillis(); + @WithDefault("5000") + int proxyBackendConnectTimeoutMillis(); + @WithDefault("100") + int proxyMaxConnections(); } interface RdsServiceConfig { @@ -1374,6 +1384,16 @@ public interface EmulatorConfig { /** Docker network to attach DB containers to. Empty = default bridge. */ Optional dockerNetwork(); + + // Bounds for the per-instance auth proxy: how long a client has to complete the + // startup/auth handshake, how long a backend connect attempt may take, and how many + // concurrent connections the proxy accepts before refusing new ones. + @WithDefault("10000") + int proxyHandshakeTimeoutMillis(); + @WithDefault("5000") + int proxyBackendConnectTimeoutMillis(); + @WithDefault("100") + int proxyMaxConnections(); } interface RdsDataServiceConfig { diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java index a4fed16bdf..1e5c4eca04 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandler.java @@ -79,7 +79,14 @@ public class MySqlProtocolHandler { String masterUsername, String masterPassword, boolean iamEnabled, RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates, - PasswordValidator passwordValidator) throws IOException { + PasswordValidator passwordValidator, + int handshakeTimeoutMillis) throws IOException { + + client.setSoTimeout(handshakeTimeoutMillis); + // The backend accepted the TCP connection but may never answer (or answer only + // partially); bound every blocking backend read during the handshake so a silent + // backend cannot pin this handler thread and its connection permit forever. + backend.setSoTimeout(handshakeTimeoutMillis); InputStream backendIn = backend.getInputStream(); OutputStream backendOut = backend.getOutputStream(); @@ -130,6 +137,9 @@ public class MySqlProtocolHandler { return; } client = sslSocket; + // upgradeToTls wraps the socket in a new SSLSocket; re-apply the handshake timeout + // since it is not guaranteed to be inherited from the underlying socket. + client.setSoTimeout(handshakeTimeoutMillis); clientIn = sslSocket.getInputStream(); clientOut = sslSocket.getOutputStream(); @@ -206,6 +216,9 @@ public class MySqlProtocolHandler { return; } + // Authenticated: clear the handshake deadline so a long-lived idle session is never killed. + client.setSoTimeout(0); + backend.setSoTimeout(0); bridge(client, backend); } diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java index 60972bcbda..476b9b2e06 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java @@ -13,6 +13,7 @@ import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -52,11 +53,21 @@ public class PostgresProtocolHandler { * An authenticated client connection ready to be bridged. {@code iamRole} is the role an IAM * token named and the session was handed over to, or {@code null} for every other login. */ - public record AuthenticatedSession(Socket client, String iamRole) {} + public record AuthenticatedSession(Socket client, Socket backend, String iamRole) {} /** The username/password the proxy opens the backend PostgreSQL connection with. */ record BackendLogin(String user, String password) {} + /** + * Opens the backend connection. Called only once the client's startup message and credentials + * have been validated, so an unauthenticated or malformed client never causes a backend + * connection attempt. + */ + @FunctionalInterface + public interface BackendConnector { + Socket connect() throws IOException; + } + /** * Picks the backend login: the cluster master whenever the proxy is the authority for this * connection (an IAM token, the master user itself, or a client the validator vouched for), @@ -74,14 +85,17 @@ public class PostgresProtocolHandler { return new BackendLogin(clientUsername, clientPassword); } - public static AuthenticatedSession authenticate(Socket client, Socket backend, + public static AuthenticatedSession authenticate(Socket client, BackendConnector backendConnector, String masterUsername, String masterPassword, String dbName, boolean iamEnabled, RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates, - PasswordValidator passwordValidator) throws IOException { + PasswordValidator passwordValidator, + int handshakeTimeoutMillis) throws IOException { + + client.setSoTimeout(handshakeTimeoutMillis); // Phase 1: Read client startup message (possibly preceded by SSL request) - StartupMessage startup = readStartupMessage(client, tlsCertificates); + StartupMessage startup = readStartupMessage(client, tlsCertificates, handshakeTimeoutMillis); if (startup == null) { closeQuietly(client); return null; @@ -119,7 +133,6 @@ public class PostgresProtocolHandler { "password authentication failed for user \"" + clientUsername + "\""); clientOut.flush(); closeQuietly(client); - closeQuietly(backend); return null; } } else { @@ -129,84 +142,106 @@ public class PostgresProtocolHandler { "password authentication failed for user \"" + clientUsername + "\""); clientOut.flush(); closeQuietly(client); - closeQuietly(backend); return null; } } - // Phase 5: Connect to backend PostgreSQL. - // IAM and master: use master credentials — the backend has the original container password - // and is never updated directly, so the proxy always authenticates as master. - // Non-master: forward the client's own credentials so the backend enforces its own ACLs, - // unless the proxy vouched for the client (MASTER_EQUIVALENT). - InputStream backendIn = backend.getInputStream(); - OutputStream backendOut = backend.getOutputStream(); - - String effectiveDbName = resolveEffectiveDbName(startup.database(), dbName); - BackendLogin backendLogin = resolveBackendLogin(isMaster, isIam, authResult, - masterUsername, masterPassword, clientUsername, clientPassword); - String backendUser = backendLogin.user(); - String backendPass = backendLogin.password(); - sendStartupToBackend(backendOut, backendUser, effectiveDbName); - backendOut.flush(); - - if (!authenticateWithBackend(backendIn, backendOut, backendUser, backendPass)) { - sendErrorResponse(clientOut, "FATAL", "08006", - "Backend database authentication failed"); + // Phase 5: Connect to backend PostgreSQL, now that the client's startup message and + // credentials have been validated. IAM and master: use master credentials. The backend + // has the original container password and is never updated directly, so the proxy always + // authenticates as master. Non-master: forward the client's own credentials so the backend + // enforces its own ACLs, unless the proxy vouched for the client (MASTER_EQUIVALENT). + Socket backend; + try { + backend = backendConnector.connect(); + } catch (IOException e) { + sendErrorResponse(clientOut, "FATAL", "08006", "could not connect to backend database"); clientOut.flush(); closeQuietly(client); - closeQuietly(backend); return null; } - // Buffer all backend messages until ReadyForQuery ('Z') - List bufferedMessages = readUntilReadyForQuery(backendIn); + try { + // The backend accepted the TCP connection but may never answer (or answer only + // partially); bound every blocking backend read during the handshake so a silent + // backend cannot pin this handler thread and its connection permit forever. + backend.setSoTimeout(handshakeTimeoutMillis); - String iamRole = null; + InputStream backendIn = backend.getInputStream(); + OutputStream backendOut = backend.getOutputStream(); - // Phase 5b: An IAM token is issued for one specific database role, so the session must run - // as that role even though the backend connection was opened as master. Handing it over - // gives the session the role's own privileges and object ownership, and refuses a token - // naming a role the database does not have instead of silently granting a master session. - if (isIam && !isMaster && !endsWithErrorResponse(bufferedMessages)) { - List roleSwitch = assumeSessionRole(backendIn, backendOut, clientUsername); - if (endsWithErrorResponse(roleSwitch)) { - sendErrorResponse(clientOut, "FATAL", "28000", - errorMessage(roleSwitch.get(roleSwitch.size() - 1), - "role \"" + clientUsername + "\" does not exist")); + String effectiveDbName = resolveEffectiveDbName(startup.database(), dbName); + BackendLogin backendLogin = resolveBackendLogin(isMaster, isIam, authResult, + masterUsername, masterPassword, clientUsername, clientPassword); + String backendUser = backendLogin.user(); + String backendPass = backendLogin.password(); + sendStartupToBackend(backendOut, backendUser, effectiveDbName); + backendOut.flush(); + + if (!authenticateWithBackend(backendIn, backendOut, backendUser, backendPass)) { + sendErrorResponse(clientOut, "FATAL", "08006", + "Backend database authentication failed"); clientOut.flush(); closeQuietly(client); closeQuietly(backend); return null; } - bufferedMessages = applyParameterStatusUpdates(bufferedMessages, roleSwitch); - iamRole = clientUsername; - } - // Phase 6: Send AuthenticationOK to client, forward buffered messages, then bridge - if (endsWithErrorResponse(bufferedMessages)) { + // Buffer all backend messages until ReadyForQuery ('Z') + List bufferedMessages = readUntilReadyForQuery(backendIn); + + String iamRole = null; + + // Phase 5b: An IAM token is issued for one specific database role, so the session must + // run as that role even though the backend connection was opened as master. Handing it + // over gives the session the role's own privileges and object ownership, and refuses a + // token naming a role the database does not have instead of silently granting a master + // session. + if (isIam && !isMaster && !endsWithErrorResponse(bufferedMessages)) { + List roleSwitch = assumeSessionRole(backendIn, backendOut, clientUsername); + if (endsWithErrorResponse(roleSwitch)) { + sendErrorResponse(clientOut, "FATAL", "28000", + errorMessage(roleSwitch.get(roleSwitch.size() - 1), + "role \"" + clientUsername + "\" does not exist")); + clientOut.flush(); + closeQuietly(client); + closeQuietly(backend); + return null; + } + bufferedMessages = applyParameterStatusUpdates(bufferedMessages, roleSwitch); + iamRole = clientUsername; + } + + // Phase 6: Send AuthenticationOK to client, forward buffered messages, then bridge + if (endsWithErrorResponse(bufferedMessages)) { + for (byte[] msg : bufferedMessages) { + clientOut.write(msg); + } + clientOut.flush(); + closeQuietly(client); + closeQuietly(backend); + return null; + } + + sendMessage(clientOut, 'R', intBytes(0)); // AuthenticationOK for (byte[] msg : bufferedMessages) { clientOut.write(msg); } clientOut.flush(); - closeQuietly(client); + + client.setSoTimeout(0); + backend.setSoTimeout(0); + return new AuthenticatedSession(client, backend, iamRole); + } catch (IOException | RuntimeException e) { closeQuietly(backend); - return null; + throw e; } - - sendMessage(clientOut, 'R', intBytes(0)); // AuthenticationOK - for (byte[] msg : bufferedMessages) { - clientOut.write(msg); - } - clientOut.flush(); - - return new AuthenticatedSession(client, iamRole); } // ── Startup ─────────────────────────────────────────────────────────────── - private static StartupMessage readStartupMessage(Socket socket, RdsProxyTlsCertificates tlsCertificates) - throws IOException { + private static StartupMessage readStartupMessage(Socket socket, RdsProxyTlsCertificates tlsCertificates, + int handshakeTimeoutMillis) throws IOException { Socket currentSocket = socket; while (true) { InputStream in = currentSocket.getInputStream(); @@ -218,6 +253,9 @@ public class PostgresProtocolHandler { out.write('S'); out.flush(); currentSocket = acceptSsl(currentSocket, tlsCertificates); + // acceptSsl wraps the socket in a new SSLSocket; re-apply the handshake timeout + // since it is not guaranteed to be inherited from the underlying socket. + currentSocket.setSoTimeout(handshakeTimeoutMillis); continue; } @@ -715,8 +753,9 @@ public class PostgresProtocolHandler { * that whatever SQL produced it; the session is then terminated, since a handover that already * happened cannot be taken back. */ - public static void bridge(AuthenticatedSession session, Socket backend) { + public static void bridge(AuthenticatedSession session) { Socket client = session.client(); + Socket backend = session.backend(); InputStream clientIn, backendIn; OutputStream clientOut, backendOut; try { diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java index 205ba02f70..38412fd467 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java @@ -7,6 +7,7 @@ import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; +import java.util.concurrent.Semaphore; /** * TCP auth proxy for a single RDS DB instance or cluster. @@ -28,6 +29,9 @@ public class RdsAuthProxy { private final RdsSigV4Validator sigV4; private final RdsProxyTlsCertificates tlsCertificates; private final MasterPasswordCheck passwordValidator; + private final int handshakeTimeoutMillis; + private final int backendConnectTimeoutMillis; + private final Semaphore connectionPermits; private volatile boolean running; private ServerSocket serverSocket; @@ -36,7 +40,9 @@ public class RdsAuthProxy { DatabaseEngine engine, boolean iamEnabled, String masterUsername, String masterPassword, String dbName, RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates, - MasterPasswordCheck passwordValidator) { + MasterPasswordCheck passwordValidator, + int handshakeTimeoutMillis, int backendConnectTimeoutMillis, + int maxConnections) { this.instanceId = instanceId; this.backendHost = backendHost; this.backendPort = backendPort; @@ -48,6 +54,9 @@ public class RdsAuthProxy { this.sigV4 = sigV4; this.tlsCertificates = tlsCertificates; this.passwordValidator = passwordValidator; + this.handshakeTimeoutMillis = handshakeTimeoutMillis; + this.backendConnectTimeoutMillis = backendConnectTimeoutMillis; + this.connectionPermits = new Semaphore(Math.max(1, maxConnections)); } public void start(int proxyPort) throws IOException { @@ -82,8 +91,20 @@ public class RdsAuthProxy { while (running) { try { Socket client = serverSocket.accept(); + if (!connectionPermits.tryAcquire()) { + LOG.warnv("Refusing RDS connection for instance {0}: connection limit reached", + instanceId); + closeQuietly(client); + continue; + } Thread.ofVirtual().name("rds-proxy-conn-" + instanceId) - .start(() -> handleConnection(client)); + .start(() -> { + try { + handleConnection(client); + } finally { + connectionPermits.release(); + } + }); } catch (IOException e) { if (running) { LOG.warnv("Accept error for RDS instance {0}: {1}", instanceId, e.getMessage()); @@ -94,10 +115,9 @@ public class RdsAuthProxy { private void handleConnection(Socket client) { Socket backend = null; + PostgresProtocolHandler.AuthenticatedSession session = null; try { client.setTcpNoDelay(true); - backend = new Socket(backendHost, backendPort); - backend.setTcpNoDelay(true); // RDS only proxy-validates the master user; a non-master user passes through so the // backend enforces its own credentials. @@ -112,32 +132,52 @@ public class RdsAuthProxy { switch (engine) { case POSTGRES -> { - PostgresProtocolHandler.AuthenticatedSession session = - PostgresProtocolHandler.authenticate( - client, backend, masterUsername, masterPassword, dbName, - iamEnabled, sigV4, tlsCertificates, authAdapter); + PostgresProtocolHandler.BackendConnector connector = () -> { + Socket backendSocket = new Socket(); + backendSocket.connect(new InetSocketAddress(backendHost, backendPort), + backendConnectTimeoutMillis); + backendSocket.setTcpNoDelay(true); + return backendSocket; + }; + session = PostgresProtocolHandler.authenticate( + client, connector, masterUsername, masterPassword, dbName, + iamEnabled, sigV4, tlsCertificates, authAdapter, + handshakeTimeoutMillis); if (session != null) { - PostgresProtocolHandler.bridge(session, backend); + PostgresProtocolHandler.bridge(session); } } - case MYSQL, MARIADB -> MySqlProtocolHandler.handleAuth( - client, backend, masterUsername, masterPassword, - iamEnabled, sigV4, tlsCertificates, authAdapter); + case MYSQL, MARIADB -> { + backend = new Socket(); + backend.connect(new InetSocketAddress(backendHost, backendPort), + backendConnectTimeoutMillis); + backend.setTcpNoDelay(true); + MySqlProtocolHandler.handleAuth( + client, backend, masterUsername, masterPassword, + iamEnabled, sigV4, tlsCertificates, authAdapter, + handshakeTimeoutMillis); + } } } catch (Exception e) { LOG.debugv("RDS connection error for instance {0}: {1}", instanceId, e.getMessage()); } finally { // A handler's success path bridges then closes both sockets; every other path // (early return on a bare probe, auth failure, thrown IOException) can leave the - // backend DB connection open. Closing here is idempotent. + // backend DB connection open. Closing here is idempotent, and also covers a + // RuntimeException thrown between authenticate() returning a session and bridge() + // finishing its own cleanup, which would otherwise leak session.backend(). closeQuietly(client); - if (backend != null) { - closeQuietly(backend); + closeQuietly(backend); + if (session != null) { + closeQuietly(session.backend()); } } } private static void closeQuietly(Socket s) { + if (s == null) { + return; + } try { s.close(); } catch (IOException e) { diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java index 778d1c35ae..e1adbc0e34 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java @@ -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 jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -18,12 +19,15 @@ public class RdsProxyManager { private final RdsSigV4Validator sigV4Validator; private final RdsProxyTlsCertificates tlsCertificates; + private final EmulatorConfig config; private final ConcurrentHashMap proxies = new ConcurrentHashMap<>(); @Inject - public RdsProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates) { + public RdsProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates, + EmulatorConfig config) { this.sigV4Validator = sigV4Validator; this.tlsCertificates = tlsCertificates; + this.config = config; } public synchronized void startProxy(String instanceId, DatabaseEngine engine, boolean iamEnabled, @@ -32,9 +36,12 @@ public class RdsProxyManager { String masterUsername, String masterPassword, String dbName, RdsAuthProxy.MasterPasswordCheck passwordValidator) { tlsCertificates.ensureHost(advertisedHost); + EmulatorConfig.RdsServiceConfig rdsConfig = config.services().rds(); RdsAuthProxy proxy = new RdsAuthProxy( instanceId, backendHost, backendPort, engine, iamEnabled, - masterUsername, masterPassword, dbName, sigV4Validator, tlsCertificates, passwordValidator); + masterUsername, masterPassword, dbName, sigV4Validator, tlsCertificates, passwordValidator, + rdsConfig.proxyHandshakeTimeoutMillis(), rdsConfig.proxyBackendConnectTimeoutMillis(), + rdsConfig.proxyMaxConnections()); try { proxy.start(proxyPort); } catch (IOException e) { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java index dec3429c19..6dab1791a3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java @@ -12,6 +12,7 @@ import java.net.BindException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; +import java.util.concurrent.Semaphore; /** * TCP auth proxy for a single Redshift cluster's backing PostgreSQL container. @@ -34,6 +35,9 @@ public class RedshiftAuthProxy { private final RdsProxyTlsCertificates tlsCertificates; private final PasswordValidator passwordValidator; private final S3Service s3Service; + private final int handshakeTimeoutMillis; + private final int backendConnectTimeoutMillis; + private final Semaphore connectionPermits; private volatile boolean running; private ServerSocket serverSocket; @@ -42,7 +46,9 @@ public class RedshiftAuthProxy { String masterUsername, String masterPassword, String dbName, RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates, PasswordValidator passwordValidator, - S3Service s3Service) { + S3Service s3Service, + int handshakeTimeoutMillis, int backendConnectTimeoutMillis, + int maxConnections) { this.clusterKey = clusterKey; this.backendHost = backendHost; this.backendPort = backendPort; @@ -53,6 +59,9 @@ public class RedshiftAuthProxy { this.tlsCertificates = tlsCertificates; this.passwordValidator = passwordValidator; this.s3Service = s3Service; + this.handshakeTimeoutMillis = handshakeTimeoutMillis; + this.backendConnectTimeoutMillis = backendConnectTimeoutMillis; + this.connectionPermits = new Semaphore(Math.max(1, maxConnections)); } public void start(int proxyPort) throws IOException { @@ -125,8 +134,20 @@ public class RedshiftAuthProxy { while (running) { try { Socket client = serverSocket.accept(); + if (!connectionPermits.tryAcquire()) { + LOG.warnv("Refusing Redshift connection for cluster {0}: connection limit reached", + clusterKey); + closeQuietly(client); + continue; + } Thread.ofVirtual().name("redshift-proxy-conn-" + clusterKey) - .start(() -> handleConnection(client)); + .start(() -> { + try { + handleConnection(client); + } finally { + connectionPermits.release(); + } + }); } catch (IOException e) { if (running) { LOG.warnv("Accept error for Redshift cluster {0}: {1}", clusterKey, e.getMessage()); @@ -136,35 +157,46 @@ public class RedshiftAuthProxy { } private void handleConnection(Socket client) { - Socket backend = null; + PostgresProtocolHandler.AuthenticatedSession session = null; try { client.setTcpNoDelay(true); - backend = new Socket(backendHost, backendPort); - backend.setTcpNoDelay(true); + PostgresProtocolHandler.BackendConnector connector = () -> { + Socket backendSocket = new Socket(); + backendSocket.connect(new InetSocketAddress(backendHost, backendPort), + backendConnectTimeoutMillis); + backendSocket.setTcpNoDelay(true); + return backendSocket; + }; // iamEnabled = false: the SigV4 branch inside authenticate is never taken. - PostgresProtocolHandler.AuthenticatedSession session = - PostgresProtocolHandler.authenticate( - client, backend, masterUsername, masterPassword, dbName, - false, sigV4, tlsCertificates, passwordValidator); + session = PostgresProtocolHandler.authenticate( + client, connector, masterUsername, masterPassword, dbName, + false, sigV4, tlsCertificates, passwordValidator, + handshakeTimeoutMillis); if (session != null) { // Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain // PostgreSQL backend on the way through; every other message is relayed verbatim. - new RedshiftInterceptingBridge(session.client(), backend, s3Service).run(); + new RedshiftInterceptingBridge(session.client(), session.backend(), s3Service).run(); } } catch (Exception e) { LOG.debugv("Redshift connection error for cluster {0}: {1}", clusterKey, e.getMessage()); } finally { - // authenticate's success path returns the client to bridge; every other path - // (early return on a bare probe, auth failure, thrown IOException) can leave the - // backend connection to Postgres open. Closing here is idempotent. + // authenticate's success path hands both sockets to the bridge, which closes both + // itself; every other path (early return on a bare probe, auth failure, thrown + // IOException) never had a backend connection to begin with. Closing here is + // idempotent, and also covers a RuntimeException thrown between authenticate() + // returning a session and the bridge finishing its own cleanup, which would + // otherwise leak session.backend(). closeQuietly(client); - if (backend != null) { - closeQuietly(backend); + if (session != null) { + closeQuietly(session.backend()); } } } private static void closeQuietly(Socket s) { + if (s == null) { + return; + } try { s.close(); } catch (IOException e) { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java index 630a91b4e7..3f8e06d092 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManager.java @@ -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; @@ -26,6 +27,7 @@ public class RedshiftProxyManager { private final RdsSigV4Validator sigV4Validator; private final RdsProxyTlsCertificates tlsCertificates; private final S3Service s3Service; + private final EmulatorConfig config; private final ConcurrentHashMap proxies = new ConcurrentHashMap<>(); /** * Proxies whose listener could not be closed during a failed start or replace. The @@ -37,10 +39,11 @@ public class RedshiftProxyManager { @Inject public RedshiftProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates, - S3Service s3Service) { + S3Service s3Service, EmulatorConfig config) { this.sigV4Validator = sigV4Validator; this.tlsCertificates = tlsCertificates; this.s3Service = s3Service; + this.config = config; } public synchronized void startProxy(String relayKey, int proxyPort, @@ -52,9 +55,12 @@ public class RedshiftProxyManager { // Make sure the self-signed proxy certificate covers the host clients will connect to, // so sslmode=prefer/require handshakes succeed. tlsCertificates.ensureHost(advertisedHost); + EmulatorConfig.RedshiftServiceConfig redshiftConfig = config.services().redshift(); RedshiftAuthProxy proxy = new RedshiftAuthProxy( relayKey, backendHost, backendPort, masterUsername, masterPassword, dbName, - sigV4Validator, tlsCertificates, passwordValidator, s3Service); + sigV4Validator, tlsCertificates, passwordValidator, s3Service, + redshiftConfig.proxyHandshakeTimeoutMillis(), redshiftConfig.proxyBackendConnectTimeoutMillis(), + redshiftConfig.proxyMaxConnections()); try { proxy.start(proxyPort); } catch (IOException | RuntimeException e) { diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index bae0e9db5d..f6d371a5bc 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -369,6 +369,9 @@ floci: proxy-max-port: 7199 default-credential-duration-seconds: 900 # GetClusterCredentials default lifetime (900-3600) # endpoint-host: localhost # Hostname clients use; empty -> DockerHostResolver + proxy-handshake-timeout-millis: 10000 # Max time a client has to complete the startup/auth handshake + proxy-backend-connect-timeout-millis: 5000 # Max time to wait for the backend TCP connect + proxy-max-connections: 100 # Max concurrent proxy connections before new ones are refused rds: enabled: true mock: false # FLOCI_SERVICES_RDS_MOCK — true = metadata only, no Docker (useful for CI) @@ -380,6 +383,9 @@ floci: # default-postgres-image: "registry.example.com/postgres:16-alpine" # default-mysql-image: "registry.example.com/mysql:8.0" # default-mariadb-image: "registry.example.com/mariadb:11" + proxy-handshake-timeout-millis: 10000 # Max time a client has to complete the startup/auth handshake + proxy-backend-connect-timeout-millis: 5000 # Max time to wait for the backend TCP connect + proxy-max-connections: 100 # Max concurrent proxy connections before new ones are refused rds-data: enabled: true transaction-ttl-seconds: 180 diff --git a/src/test/java/io/github/hectorvent/floci/config/RdsProxyConfigTest.java b/src/test/java/io/github/hectorvent/floci/config/RdsProxyConfigTest.java new file mode 100644 index 0000000000..a8917988af --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/config/RdsProxyConfigTest.java @@ -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()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/config/RedshiftProxyConfigTest.java b/src/test/java/io/github/hectorvent/floci/config/RedshiftProxyConfigTest.java index 2bb3a8c0c3..94be59c2fa 100644 --- a/src/test/java/io/github/hectorvent/floci/config/RedshiftProxyConfigTest.java +++ b/src/test/java/io/github/hectorvent/floci/config/RedshiftProxyConfigTest.java @@ -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()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java index 05469b8680..ddffe49c4a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/MySqlProtocolHandlerTest.java @@ -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 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()); diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java index bb89291a49..5de53e18c8 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java @@ -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 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); diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxyBoundsTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxyBoundsTest.java new file mode 100644 index 0000000000..ed758a7fde --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxyBoundsTest.java @@ -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(); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java index e55b3342ea..c11f831d37 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java @@ -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 { diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java index fb52b55aee..da27d39748 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxyTest.java @@ -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"); diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.java index b477fb201a..6830b41dd0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftProxyManagerTest.java @@ -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) { diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index f50f1cb183..935df9dc17 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -174,11 +174,17 @@ floci: proxy-base-port: 7100 proxy-max-port: 7199 default-credential-duration-seconds: 900 + proxy-handshake-timeout-millis: 10000 + proxy-backend-connect-timeout-millis: 5000 + proxy-max-connections: 100 rds: enabled: true mock: false proxy-base-port: 7001 proxy-max-port: 7099 + proxy-handshake-timeout-millis: 10000 + proxy-backend-connect-timeout-millis: 5000 + proxy-max-connections: 100 rds-data: enabled: true transaction-ttl-seconds: 180