mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
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:
1 parent
ffd2488f02
commit
1987bf0c96
19 files changed
+649
-163
No files matched your search
@@ -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<String> 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 {
|
||||
|
||||
+14
-1
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
+96
-57
@@ -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<byte[]> 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<byte[]> 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<byte[]> 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<byte[]> 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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<String, RdsAuthProxy> 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) {
|
||||
|
||||
+47
-15
@@ -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) {
|
||||
|
||||
+8
-2
@@ -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<String, RedshiftAuthProxy> 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) {
|
||||
|
||||
Reference in new issue
Block a user