From 1356cbbc8478e1ed3c7ed6a33ea3fd7e6bdfefa2 Mon Sep 17 00:00:00 2001 From: Matheus Oliveira <99829531+omatheusmesmo@users.noreply.github.com> Date: Thu, 29 Oct 2026 01:20:54 -0300 Subject: [PATCH] fix(core): bind the DB proxies and EC2 port forwards with a 4096 backlog (#6744) --- docs/services/ec2.md | 2 +- .../floci/core/common/ListenBacklog.java | 50 +++++++++++++++++++ .../portforward/Ec2PortForwardManager.java | 7 ++- .../proxy/AbstractRedisAuthProxy.java | 11 +++- .../neptune/proxy/NeptuneGremlinProxy.java | 11 +++- .../services/rds/proxy/RdsAuthProxy.java | 13 +++-- .../redshift/proxy/RedshiftAuthProxy.java | 18 ++++--- .../Ec2PortForwardManagerTest.java | 6 +-- .../AbstractRedisAuthProxyRelayTest.java | 22 +++++++- .../proxy/NeptuneGremlinProxyRelayTest.java | 21 ++++++++ .../rds/proxy/RdsAuthProxyBoundsTest.java | 25 ++++++++-- .../redshift/proxy/RedshiftAuthProxyTest.java | 19 +++++++ 12 files changed, 183 insertions(+), 22 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/core/common/ListenBacklog.java diff --git a/docs/services/ec2.md b/docs/services/ec2.md index adf1c6db25..342c5f6fe4 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -143,7 +143,7 @@ With `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED=true`, Floci prepares a s Security-group permissions on a host-published port use the source visible inside Docker. Docker Desktop may replace the original external-client address. The legacy socat application publisher is disabled while enforcement is enabled because it obscures that source. SSH is published directly by the protected namespace. Application host ports remain available through the legacy publisher only when enforcement is explicitly disabled. Direct managed container traffic uses the logical ENI identity. -When enforcement is disabled, an instance's security groups can open a TCP port to a CIDR source and Floci publishes that port on the host so you can reach the app from `localhost`. For each opened port Floci starts a small `alpine/socat` sidecar container that binds an allocated host port (default range 30000–30999) and forwards it to the instance container's IP, with `TCP_NODELAY` on both sockets so a request the client sends as two small writes is not held for the first write's delayed ACK (about 40 ms per round trip otherwise). This works both for rules present at launch and for rules added later with `authorize-security-group-ingress`; revoking the rule removes the forward. The mapping (`app port -> host port`) is written to the logs: +When enforcement is disabled, an instance's security groups can open a TCP port to a CIDR source and Floci publishes that port on the host so you can reach the app from `localhost`. For each opened port Floci starts a small `alpine/socat` sidecar container that binds an allocated host port (default range 30000–30999) and forwards it to the instance container's IP, with `TCP_NODELAY` on both sockets so a request the client sends as two small writes is not held for the first write's delayed ACK (about 40 ms per round trip otherwise). The listen socket also takes a `backlog` of 4096 (socat's default is 5), so a burst of connections is queued rather than silently dropped from a full accept queue; the kernel caps the backlog at `net.core.somaxconn`. This works both for rules present at launch and for rules added later with `authorize-security-group-ingress`; revoking the rule removes the forward. The mapping (`app port -> host port`) is written to the logs: ``` Published EC2 instance i-0abc... app port 80 on host port 30000 (socat -> 172.17.0.3:80) diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ListenBacklog.java b/src/main/java/io/github/hectorvent/floci/core/common/ListenBacklog.java new file mode 100644 index 0000000000..4ce3b2d2e5 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/ListenBacklog.java @@ -0,0 +1,50 @@ +package io.github.hectorvent.floci.core.common; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; + +/** + * The accept backlog Floci's data-plane TCP listeners bind with. + * + *

A plain {@code ServerSocket} listens with a backlog of 50, socat with 5. A burst of + * connections (a pool refilling, a service fanning out) overflows an accept queue that + * small before the listener can drain it, and the kernel then silently drops the + * handshake's final ACK: the client believes it is connected, sends its first message and + * waits on retransmits, about a second for one drop, tens of seconds when the drops repeat, + * and a reset or a hang for a connection dropped half-open. + * + *

The kernel caps the backlog at {@code net.core.somaxconn}, so a value beyond what the + * host allows clamps the queue rather than failing the bind. The RDS, Redshift, ElastiCache + * (with MemoryDB) and Neptune auth proxies pass this to their {@code ServerSocket} bind, and + * the EC2 port-forward socat to its {@code backlog=} option. + */ +public final class ListenBacklog { + + /** The accept backlog of the database auth proxies and the EC2 port-forward socat. */ + public static final int ACCEPT = 4096; + + /** + * Binds the accept socket for one of Floci's data-plane listeners: reuse-address on, a + * bind at the given port with the given backlog, and the socket closed when the bind + * fails so a caller's retry cannot leak one socket per attempt. + */ + public static ServerSocket acceptSocket(int port, int backlog) throws IOException { + ServerSocket socket = new ServerSocket(); + try { + socket.setReuseAddress(true); + socket.bind(new InetSocketAddress(port), backlog); + return socket; + } catch (IOException e) { + try { + socket.close(); + } catch (IOException ignored) { + // the socket was never bound, so nothing could have been listening on it + } + throw e; + } + } + + private ListenBacklog() { + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManager.java index 76f4d1e891..e2cdadce30 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManager.java @@ -4,6 +4,7 @@ import com.github.dockerjava.api.DockerClient; import com.github.dockerjava.api.command.InspectContainerResponse; import com.github.dockerjava.api.model.ContainerNetwork; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.ListenBacklog; import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; import io.github.hectorvent.floci.core.common.docker.ContainerSpec; @@ -41,6 +42,10 @@ import java.util.function.Consumer; * with delayed ACK stretches that to roughly 40 ms on the Docker network, so a request the * client sends as two writes pays a visible stall on every round trip. * + *

The listen address also sets {@code backlog} to {@link ListenBacklog#ACCEPT}, since + * socat's default accept queue of 5 silently drops the final ACK of a burst's overflow + * connections, which the client then pays for in retransmit stalls or a reset. + * *

Because each forward is a fresh container, ports opened after launch via * {@code authorize-security-group-ingress} are handled the same way as ports present at * launch. The instance container itself is never modified. @@ -211,7 +216,7 @@ public class Ec2PortForwardManager { .withName(name) .withEntrypoint(List.of("socat")) .withCmd(List.of( - "TCP-LISTEN:" + appPort + ",fork,reuseaddr,nodelay", + "TCP-LISTEN:" + appPort + ",fork,reuseaddr,nodelay,backlog=" + ListenBacklog.ACCEPT, "TCP:" + target.ip() + ":" + appPort + ",nodelay")) .withPortBinding(appPort, hostPort) .withLogRotation(); diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxy.java index 52b8e1664e..c764464558 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxy.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxy.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.elasticache.proxy; +import io.github.hectorvent.floci.core.common.ListenBacklog; import org.jboss.logging.Logger; import java.io.IOException; @@ -118,13 +119,21 @@ public abstract class AbstractRedisAuthProxy { } public void start(int proxyPort) throws IOException { - serverSocket = new ServerSocket(proxyPort); + serverSocket = listenSocket(proxyPort, ListenBacklog.ACCEPT); running = true; Thread.ofVirtual().name(threadPrefix + "-proxy-accept-" + resourceId).start(this::acceptLoop); log.infov("{0} proxy started for {1} on port {2} → {3}:{4}", serviceName, resourceId, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort)); } + /** + * Opens the listening socket. A seam so a test can pin the accept backlog: a bound + * {@code ServerSocket} does not report the backlog it was created with. + */ + ServerSocket listenSocket(int proxyPort, int backlog) throws IOException { + return new ServerSocket(proxyPort, backlog); + } + int localPort() { return serverSocket.getLocalPort(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneGremlinProxy.java b/src/main/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneGremlinProxy.java index 2acbe85a89..4105abaf50 100644 --- a/src/main/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneGremlinProxy.java +++ b/src/main/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneGremlinProxy.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.neptune.proxy; +import io.github.hectorvent.floci.core.common.ListenBacklog; import org.jboss.logging.Logger; import java.io.IOException; @@ -37,13 +38,21 @@ public class NeptuneGremlinProxy { } public void start(int proxyPort) throws IOException { - serverSocket = new ServerSocket(proxyPort); + serverSocket = listenSocket(proxyPort, ListenBacklog.ACCEPT); running = true; Thread.ofVirtual().name("neptune-proxy-accept-" + clusterId).start(this::acceptLoop); LOG.infov("Neptune Gremlin proxy started for cluster {0} on port {1} → {2}:{3}", clusterId, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort)); } + /** + * Opens the listening socket. A seam so a test can pin the accept backlog: a bound + * {@code ServerSocket} does not report the backlog it was created with. + */ + ServerSocket listenSocket(int proxyPort, int backlog) throws IOException { + return new ServerSocket(proxyPort, backlog); + } + public void stop() { running = false; 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 57f609408d..f4c26853cf 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 @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.rds.proxy; +import io.github.hectorvent.floci.core.common.ListenBacklog; import io.github.hectorvent.floci.services.rds.container.RdsBackendGate; import io.github.hectorvent.floci.services.rds.model.DatabaseEngine; import org.jboss.logging.Logger; @@ -148,9 +149,7 @@ public class RdsAuthProxy { } public void start(int proxyPort) throws IOException { - serverSocket = new ServerSocket(); - serverSocket.setReuseAddress(true); - serverSocket.bind(new InetSocketAddress(proxyPort)); + serverSocket = listenSocket(proxyPort, ListenBacklog.ACCEPT); running = true; acceptThread = Thread.ofVirtual().name("rds-proxy-accept-" + instanceId).unstarted(this::acceptLoop); acceptThread.start(); @@ -158,6 +157,14 @@ public class RdsAuthProxy { instanceId, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort)); } + /** + * Binds the listening socket. A seam so a test can pin the accept backlog: a bound + * {@code ServerSocket} does not report the backlog it was created with. + */ + ServerSocket listenSocket(int proxyPort, int backlog) throws IOException { + return ListenBacklog.acceptSocket(proxyPort, backlog); + } + /** Swap the master-password snapshot after a rotation; new connections authenticate against it. */ public void updateMasterPassword(String newPassword) { this.masterPassword = newPassword; 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 7a3b219b53..e8de15a14d 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 @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.redshift.proxy; +import io.github.hectorvent.floci.core.common.ListenBacklog; import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.rds.proxy.PasswordValidator; import io.github.hectorvent.floci.services.rds.proxy.PostgresProtocolHandler; @@ -154,17 +155,10 @@ public class RedshiftAuthProxy { private ServerSocket bindListener(int proxyPort) throws IOException { BindException lastFailure = null; for (int attempt = 0; attempt < 40; attempt++) { - ServerSocket socket = new ServerSocket(); try { - socket.setReuseAddress(true); - socket.bind(new InetSocketAddress(proxyPort)); - return socket; + return listenSocket(proxyPort, ListenBacklog.ACCEPT); } catch (BindException e) { - closeQuietly(socket); lastFailure = e; - } catch (IOException e) { - closeQuietly(socket); - throw e; } try { Thread.sleep(25); @@ -176,6 +170,14 @@ public class RedshiftAuthProxy { throw lastFailure; } + /** + * Binds one listener attempt. A seam so a test can pin the accept backlog: a bound + * {@code ServerSocket} does not report the backlog it was created with. + */ + ServerSocket listenSocket(int proxyPort, int backlog) throws IOException { + return ListenBacklog.acceptSocket(proxyPort, backlog); + } + private static void closeQuietly(ServerSocket s) { try { s.close(); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManagerTest.java index c4d32880f9..46beeca91c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/portforward/Ec2PortForwardManagerTest.java @@ -242,7 +242,7 @@ class Ec2PortForwardManagerTest { } @Test - void publishedForwardDisablesNagleOnBothSocatSockets() { + void publishedForwardDisablesNagleAndBindsABurstTolerantAcceptBacklog() { DockerClient dockerClient = mock(DockerClient.class); when(dockerClient.inspectContainerCmd(anyString())).thenThrow(new RuntimeException("docker down")); PortAllocator portAllocator = mock(PortAllocator.class); @@ -274,8 +274,8 @@ class Ec2PortForwardManagerTest { verify(lifecycleManager).create(spec.capture()); assertEquals("alpine/socat", spec.getValue().image()); assertEquals(List.of("socat"), spec.getValue().entrypoint()); - assertEquals(List.of("TCP-LISTEN:80,fork,reuseaddr,nodelay", "TCP:172.17.0.3:80,nodelay"), - spec.getValue().cmd()); + assertEquals(List.of("TCP-LISTEN:80,fork,reuseaddr,nodelay,backlog=4096", + "TCP:172.17.0.3:80,nodelay"), spec.getValue().cmd()); assertEquals(Map.of(80, 30000), spec.getValue().portBindings()); } diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxyRelayTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxyRelayTest.java index 198d498bf1..0c15fbfa89 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxyRelayTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxyRelayTest.java @@ -7,6 +7,7 @@ import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -125,7 +126,26 @@ class AbstractRedisAuthProxyRelayTest { } } - private static final class TestProxy extends AbstractRedisAuthProxy { + @Test + void bindsWithABurstTolerantAcceptBacklog() throws Exception { + AtomicInteger acceptBacklog = new AtomicInteger(); + TestProxy proxy = new TestProxy("127.0.0.1", 1) { + @Override + ServerSocket listenSocket(int proxyPort, int backlog) throws IOException { + acceptBacklog.set(backlog); + return super.listenSocket(proxyPort, backlog); + } + }; + proxy.start(0); + try { + assertEquals(4096, acceptBacklog.get(), + "a connection burst must not overflow the proxy's accept queue"); + } finally { + proxy.stop(); + } + } + + private static class TestProxy extends AbstractRedisAuthProxy { private TestProxy(String backendHost, int backendPort) { super(org.jboss.logging.Logger.getLogger(TestProxy.class), "test", "test", "relay", backendHost, backendPort); diff --git a/src/test/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneGremlinProxyRelayTest.java b/src/test/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneGremlinProxyRelayTest.java index 5391fff7de..34c7a3327f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneGremlinProxyRelayTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/neptune/proxy/NeptuneGremlinProxyRelayTest.java @@ -2,9 +2,11 @@ package io.github.hectorvent.floci.services.neptune.proxy; import org.junit.jupiter.api.Test; +import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -126,4 +128,23 @@ class NeptuneGremlinProxyRelayTest { } } } + + @Test + void bindsWithABurstTolerantAcceptBacklog() throws Exception { + AtomicInteger acceptBacklog = new AtomicInteger(); + NeptuneGremlinProxy proxy = new NeptuneGremlinProxy("cluster", "127.0.0.1", 1) { + @Override + ServerSocket listenSocket(int proxyPort, int backlog) throws IOException { + acceptBacklog.set(backlog); + return super.listenSocket(proxyPort, backlog); + } + }; + proxy.start(0); + try { + assertEquals(4096, acceptBacklog.get(), + "a connection burst must not overflow the proxy's accept queue"); + } finally { + proxy.stop(); + } + } } 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 index c32baf6048..432203365e 100644 --- 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 @@ -18,6 +18,7 @@ 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.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -26,9 +27,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; /** - * 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}. + * Covers the connection bounds (handshake timeout, backend-connect deferral, permit pool, + * accept backlog) added to {@link RdsAuthProxy} for the POSTGRES engine, mirroring the + * equivalent coverage in {@code RedshiftAuthProxyTest}. */ class RdsAuthProxyBoundsTest { @@ -146,6 +147,24 @@ class RdsAuthProxyBoundsTest { assertTrue(released.await(5, TimeUnit.SECONDS), "the lease is released when the connection ends"); } + @Test + void bindsWithABurstTolerantAcceptBacklog() throws Exception { + AtomicInteger acceptBacklog = new AtomicInteger(); + proxy = new RdsAuthProxy("db-1", "localhost", 1, "runtime:db-1", + DatabaseEngine.POSTGRES, false, "admin", "Secret123", "dev", + mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true, + 5000, 5000, 100) { + @Override + ServerSocket listenSocket(int proxyPort, int backlog) throws IOException { + acceptBacklog.set(backlog); + return super.listenSocket(proxyPort, backlog); + } + }; + proxy.start(0); + assertEquals(4096, acceptBacklog.get(), + "a connection burst must not overflow the proxy's accept queue"); + } + private RdsAuthProxy newProxy(int handshakeTimeoutMillis, int backendConnectTimeoutMillis, int maxConnections) { return newProxy("runtime:db-1", handshakeTimeoutMillis, backendConnectTimeoutMillis, maxConnections); 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 9c15d55bb0..59274d4bdc 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 @@ -29,6 +29,7 @@ import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -306,6 +307,24 @@ class RedshiftAuthProxyTest { assertEquals("rotated", f.get(proxy)); } + @Test + void bindsWithABurstTolerantAcceptBacklog() throws Exception { + AtomicInteger acceptBacklog = new AtomicInteger(); + proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", 1, + "admin", "Secret123", "dev", + mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.REJECT, + mock(S3Service.class), mock(IamService.class), 5000, 5000, 100) { + @Override + ServerSocket listenSocket(int proxyPort, int backlog) throws IOException { + acceptBacklog.set(backlog); + return super.listenSocket(proxyPort, backlog); + } + }; + proxy.start(0); + assertEquals(4096, acceptBacklog.get(), + "a connection burst must not overflow the proxy's accept queue"); + } + private RdsProxyTlsCertificates realTls() { return new RdsProxyTlsCertificates(FlociCertificateAuthority.loadOrCreate(tempDir.resolve("tls")), new CertificateGenerator());