diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerTest.java index 09deb260da..8ed748ad39 100644 --- a/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerTest.java +++ b/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerTest.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.config; +import io.github.hectorvent.floci.testutil.FreePorts; import io.vertx.core.Vertx; import io.vertx.core.net.NetServer; import org.junit.jupiter.api.AfterEach; @@ -12,7 +13,6 @@ import java.net.Inet4Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; -import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.nio.charset.StandardCharsets; @@ -97,7 +97,7 @@ class TlsProxyServerTest { void bindsTheConfiguredHost_notEveryInterface() throws Exception { InetAddress external = nonLoopbackIpv4(); assumeTrue(external != null, "needs a non-loopback IPv4 interface"); - int publicPort = freePort(); + int publicPort = FreePorts.anyInterfacePort(); proxy = new TlsProxyServer(vertx, configWith(true, publicPort, 0), "127.0.0.1", 4510, 4511); @@ -109,7 +109,7 @@ class TlsProxyServerTest { @Test @Timeout(20) void nonLoopbackHostWithoutConsent_refusesToListen() throws Exception { - int publicPort = freePort(); + int publicPort = FreePorts.anyInterfacePort(); IllegalStateException e = assertThrows(IllegalStateException.class, () -> new TlsProxyServer(vertx, configWith(true, publicPort, 0), "0.0.0.0", 4510, 4511)); @@ -121,7 +121,7 @@ class TlsProxyServerTest { @Test @Timeout(20) void nonLoopbackHostWithConsent_listens() throws Exception { - int publicPort = freePort(); + int publicPort = FreePorts.anyInterfacePort(); EmulatorConfig config = configWith(true, publicPort, 0); when(config.security().allowUnsafeNetworkExposure()).thenReturn(true); @@ -133,10 +133,10 @@ class TlsProxyServerTest { @Test @Timeout(20) void bindsBothPorts_andRoutesByFirstByte() throws Exception { - int httpBe = freePort(); - int httpsBe = freePort(); - int publicPort = freePort(); - int awsHttpsPort = freePort(); + int httpBe = FreePorts.anyInterfacePort(); + int httpsBe = FreePorts.anyInterfacePort(); + int publicPort = FreePorts.anyInterfacePort(); + int awsHttpsPort = FreePorts.anyInterfacePort(); httpBackend = startMarkerBackend(httpBe, "PLAIN"); httpsBackend = startMarkerBackend(httpsBe, "TLS"); @@ -153,7 +153,7 @@ class TlsProxyServerTest { @Test @Timeout(20) void tlsDisabled_bindsNothing() throws Exception { - int publicPort = freePort(); + int publicPort = FreePorts.anyInterfacePort(); proxy = new TlsProxyServer(vertx, configWith(false, publicPort, 443), "127.0.0.1", 4510, 4511); assertFalse(portAccepts(publicPort), "no proxy should listen when TLS is disabled"); } @@ -237,10 +237,4 @@ class TlsProxyServerTest { server.close(); } } - - 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/ecs/EcsImagePullDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsImagePullDockerIntegrationTest.java index de354a1e8b..384c2065d3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsImagePullDockerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsImagePullDockerIntegrationTest.java @@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.ecs.model.EcsTask; import io.github.hectorvent.floci.services.ecs.model.NetworkMode; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; import io.github.hectorvent.floci.testing.TestImages; +import io.github.hectorvent.floci.testutil.FreePorts; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.QuarkusTestProfile; import io.quarkus.test.junit.TestProfile; @@ -25,8 +26,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; -import java.net.InetAddress; -import java.net.ServerSocket; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -178,7 +177,7 @@ class EcsImagePullDockerIntegrationTest { private String startRegistry() throws InterruptedException, IOException { pull(TestImages.REGISTRY); ExposedPort registryPort = ExposedPort.tcp(5000); - int hostPort = freeLoopbackPort(); + int hostPort = FreePorts.loopbackIpv4Port(); registryContainerId = dockerClient.createContainerCmd(TestImages.REGISTRY) .withExposedPorts(registryPort) .withHostConfig(HostConfig.newHostConfig().withPortBindings(new PortBinding( @@ -236,16 +235,6 @@ class EcsImagePullDockerIntegrationTest { assertNull(pushError.get(), "the push to " + repository + " must succeed"); } - /** - * A port named in the binding, not one the daemon picks: Docker Desktop allocates an unnamed - * port on the host side only, where the daemon that pushes and pulls cannot reach it. - */ - private static int freeLoopbackPort() throws IOException { - try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { - return socket.getLocalPort(); - } - } - private boolean isDockerAvailable() { try { dockerClient.pingCmd().exec(); diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerDeviceVerificationTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerDeviceVerificationTest.java index 5eda9573fe..71028f7b9e 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerDeviceVerificationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerDeviceVerificationTest.java @@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.acm.CertificateGenerator; import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm; import io.github.hectorvent.floci.services.iot.IotService.RegisteredDevice; import io.github.hectorvent.floci.services.iot.model.IotCertificate; +import io.github.hectorvent.floci.testutil.FreePorts; import io.quarkus.tls.TlsConfiguration; import io.quarkus.tls.TlsConfigurationRegistry; import io.vertx.core.Vertx; @@ -30,7 +31,6 @@ import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import java.io.IOException; -import java.net.ServerSocket; import java.nio.file.Path; import java.security.KeyStore; import java.security.cert.Certificate; @@ -93,9 +93,9 @@ class IotMqttBrokerDeviceVerificationTest { @BeforeEach void brokerWithTlsOn() throws IOException { - plainPort = freePort(); + plainPort = FreePorts.anyInterfacePort(); do { - tlsPort = freePort(); + tlsPort = FreePorts.anyInterfacePort(); } while (tlsPort == plainPort); when(config.services().iot().enabled()).thenReturn(true); when(config.services().iot().mqtt().enabled()).thenReturn(true); @@ -340,10 +340,4 @@ class IotMqttBrokerDeviceVerificationTest { kmf.init(keys, new char[0]); return kmf.getKeyManagers(); } - - private static int freePort() throws IOException { - try (ServerSocket socket = new ServerSocket(0)) { - return socket.getLocalPort(); - } - } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerServiceTest.java index 616207b751..037850daf6 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iot/IotMqttBrokerServiceTest.java @@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.lambda.LambdaService; import io.github.hectorvent.floci.services.s3.S3Service; import io.github.hectorvent.floci.services.sns.SnsService; import io.github.hectorvent.floci.services.sqs.SqsService; +import io.github.hectorvent.floci.testutil.FreePorts; import io.netty.handler.codec.mqtt.MqttQoS; import io.quarkus.tls.CertificateUpdatedEvent; import io.quarkus.tls.TlsConfiguration; @@ -154,9 +155,9 @@ class IotMqttBrokerServiceTest { @BeforeEach void brokerWithTlsOn() throws IOException { - plainPort = freePort(); + plainPort = FreePorts.anyInterfacePort(); do { - tlsPort = freePort(); + tlsPort = FreePorts.anyInterfacePort(); } while (tlsPort == plainPort); when(config.services().iot().enabled()).thenReturn(true); when(config.services().iot().mqtt().enabled()).thenReturn(true); @@ -879,12 +880,6 @@ class IotMqttBrokerServiceTest { } } - private static int freePort() throws IOException { - try (ServerSocket socket = new ServerSocket(0)) { - return socket.getLocalPort(); - } - } - /** A client key manager with no certificate that records whether the server asked for one. */ private static final class RecordingKeyManager extends X509ExtendedKeyManager { final AtomicBoolean asked = new AtomicBoolean(); 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 9823ad7acf..66d4349834 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 @@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.services.acm.CertificateGenerator; import io.github.hectorvent.floci.services.rds.container.RdsBackendGate; import io.github.hectorvent.floci.services.rds.model.DatabaseEngine; +import io.github.hectorvent.floci.testutil.FreePorts; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -55,7 +56,7 @@ class RdsAuthProxyBoundsTest { fakeBackend = new ServerSocket(0); fakeBackend.setSoTimeout(500); - int proxyPort = freePort(); + int proxyPort = FreePorts.anyInterfacePort(); proxy = newProxy(5000, 5000, 100); proxy.start(proxyPort); @@ -68,7 +69,7 @@ class RdsAuthProxyBoundsTest { @Test void idleClientIsDroppedAfterTheConfiguredHandshakeTimeout() throws Exception { fakeBackend = new ServerSocket(0); - int proxyPort = freePort(); + int proxyPort = FreePorts.anyInterfacePort(); proxy = newProxy(200, 5000, 100); proxy.start(proxyPort); @@ -84,7 +85,7 @@ class RdsAuthProxyBoundsTest { @Test void refusesAConnectionBeyondTheConfiguredLimit() throws Exception { fakeBackend = new ServerSocket(0); - int proxyPort = freePort(); + int proxyPort = FreePorts.anyInterfacePort(); proxy = newProxy(5000, 5000, 1); proxy.start(proxyPort); @@ -113,7 +114,7 @@ class RdsAuthProxyBoundsTest { admit.await(); return released::countDown; }; - int proxyPort = freePort(); + int proxyPort = FreePorts.anyInterfacePort(); proxy = new RdsAuthProxy("db-1", "localhost", fakeBackend.getLocalPort(), DatabaseEngine.SQLSERVER, false, "sa", "Secret123", null, mock(RdsSigV4Validator.class), realTls(), (user, pw) -> true, @@ -151,10 +152,4 @@ class RdsAuthProxyBoundsTest { 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 6c4ec65a4c..e0ea049820 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 @@ -2,6 +2,7 @@ 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 io.github.hectorvent.floci.testutil.FreePorts; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -27,10 +28,10 @@ class RdsProxyManagerTest { void replacingProxyStopsPreviousListenerAndKeepsReplacementOwned() throws IOException { RdsProxyManager manager = new RdsProxyManager( mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig()); - int firstPort = availablePort(); + int firstPort = FreePorts.anyInterfacePort(); try { start(manager, "proxy", firstPort); - int replacementPort = availablePort(); + int replacementPort = FreePorts.anyInterfacePort(); start(manager, "proxy", replacementPort); @@ -47,7 +48,7 @@ class RdsProxyManagerTest { void registrationFailureAfterBindReleasesCandidateListener() throws IOException { RdsProxyManager manager = new RdsProxyManager( mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig()); - int proxyPort = availablePort(); + int proxyPort = FreePorts.anyInterfacePort(); try { assertThrows(RuntimeException.class, () -> start(manager, null, proxyPort)); @@ -61,7 +62,7 @@ class RdsProxyManagerTest { void failedReplacementPreservesOriginalRegistryEntry() throws IOException { RdsProxyManager manager = new RdsProxyManager( mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig()); - int originalPort = availablePort(); + int originalPort = FreePorts.anyInterfacePort(); try { start(manager, "proxy", originalPort); try (ServerSocket occupied = new ServerSocket(0)) { @@ -81,7 +82,7 @@ class RdsProxyManagerTest { void updateMasterPasswordSwapsTheRunningProxySnapshotWithoutARestart() throws Exception { RdsProxyManager manager = new RdsProxyManager( mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig()); - int proxyPort = availablePort(); + int proxyPort = FreePorts.anyInterfacePort(); try { start(manager, "proxy", proxyPort); @@ -106,9 +107,9 @@ class RdsProxyManagerTest { void stopAllReleasesEveryListenerAndIsIdempotent() throws IOException { RdsProxyManager manager = new RdsProxyManager( mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig()); - int firstPort = availablePort(); + int firstPort = FreePorts.anyInterfacePort(); start(manager, "first", firstPort); - int secondPort = availablePort(); + int secondPort = FreePorts.anyInterfacePort(); start(manager, "second", secondPort); manager.stopAll(); @@ -147,7 +148,7 @@ class RdsProxyManagerTest { .when(previous).stop(); ConcurrentHashMap registry = registry(manager); registry.put("proxy", previous); - int candidatePort = availablePort(); + int candidatePort = FreePorts.anyInterfacePort(); assertThrows(RuntimeException.class, () -> start(manager, "proxy", candidatePort)); @@ -160,7 +161,7 @@ class RdsProxyManagerTest { void stopAllContinuesAndRetainsOnlyFailedListenerOwnership() throws Exception { RdsProxyManager manager = new RdsProxyManager( mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class), testConfig()); - int successfulPort = availablePort(); + int successfulPort = FreePorts.anyInterfacePort(); start(manager, "successful", successfulPort); RdsAuthProxy failed = mock(RdsAuthProxy.class); doThrow(new IllegalStateException("simulated shutdown stop failure")) @@ -221,12 +222,6 @@ class RdsProxyManagerTest { return (ConcurrentHashMap) field.get(manager); } - private static int availablePort() throws IOException { - try (ServerSocket socket = new ServerSocket(0)) { - return socket.getLocalPort(); - } - } - private static void assertPortAvailable(int port) { IOException lastFailure = null; for (int attempt = 0; attempt < 50; attempt++) { 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 9998be6fc9..97cd0d3233 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 @@ -7,6 +7,7 @@ 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; import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.testutil.FreePorts; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -71,7 +72,7 @@ class RedshiftAuthProxyTest { } }); - int proxyPort = freePort(); + int proxyPort = FreePorts.anyInterfacePort(); proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(), "admin", "Secret123", "dev", mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, @@ -114,7 +115,7 @@ class RedshiftAuthProxyTest { fakeBackend = new ServerSocket(0); fakeBackend.setSoTimeout(500); - int proxyPort = freePort(); + int proxyPort = FreePorts.anyInterfacePort(); proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(), "admin", "Secret123", "dev", mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, @@ -131,7 +132,7 @@ class RedshiftAuthProxyTest { @Test void idleClientIsDroppedAfterTheConfiguredHandshakeTimeout() throws Exception { fakeBackend = new ServerSocket(0); - int proxyPort = freePort(); + int proxyPort = FreePorts.anyInterfacePort(); proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(), "admin", "Secret123", "dev", mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, @@ -150,7 +151,7 @@ class RedshiftAuthProxyTest { @Test void refusesAConnectionBeyondTheConfiguredLimit() throws Exception { fakeBackend = new ServerSocket(0); - int proxyPort = freePort(); + int proxyPort = FreePorts.anyInterfacePort(); proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(), "admin", "Secret123", "dev", mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, @@ -175,7 +176,7 @@ class RedshiftAuthProxyTest { @Test void startRetriesTheBindWhileThePortIsMomentarilyStillInUse() throws Exception { fakeBackend = new ServerSocket(0); - int proxyPort = freePort(); + int proxyPort = FreePorts.anyInterfacePort(); // Hold the port, mimicking a just-closed predecessor the kernel has not released // yet; free it shortly after so the retrying bind can finally take it. @@ -202,7 +203,7 @@ class RedshiftAuthProxyTest { @Test void updateMasterPasswordSwapsTheSnapshotUsedForNewConnections() throws Exception { fakeBackend = new ServerSocket(0); - int proxyPort = freePort(); + int proxyPort = FreePorts.anyInterfacePort(); proxy = new RedshiftAuthProxy("111111111111:c1", "localhost", fakeBackend.getLocalPort(), "admin", "old", "dev", mock(RdsSigV4Validator.class), realTls(), (user, pw) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, @@ -225,12 +226,6 @@ class RedshiftAuthProxyTest { return new RdsProxyTlsCertificates(config, new CertificateGenerator()); } - private static int freePort() throws IOException { - try (ServerSocket s = new ServerSocket(0)) { - return s.getLocalPort(); - } - } - private static boolean portAccepts(int port) { for (int attempt = 0; attempt < 50; attempt++) { try (Socket ignored = new Socket("localhost", port)) { 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 58869aa73f..9ba61ad272 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 @@ -6,6 +6,7 @@ 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; import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.testutil.FreePorts; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -60,7 +61,7 @@ class RedshiftProxyManagerTest { @Test void startRegistersTheKeyAndBindsThePort() throws Exception { RedshiftProxyManager manager = newManager(); - int port = availablePort(); + int port = FreePorts.anyInterfacePort(); try { start(manager, KEY, port); assertTrue(registry(manager).containsKey(KEY)); @@ -73,7 +74,7 @@ class RedshiftProxyManagerTest { @Test void stopProxyRemovesTheKeyAndReleasesThePort() throws Exception { RedshiftProxyManager manager = newManager(); - int port = availablePort(); + int port = FreePorts.anyInterfacePort(); start(manager, KEY, port); manager.stopProxy(KEY); @@ -85,10 +86,10 @@ class RedshiftProxyManagerTest { @Test void startingAnExistingKeyStopsTheOldProxyAndInstallsTheNewOne() throws IOException { RedshiftProxyManager manager = newManager(); - int firstPort = availablePort(); + int firstPort = FreePorts.anyInterfacePort(); try { start(manager, KEY, firstPort); - int replacementPort = availablePort(); + int replacementPort = FreePorts.anyInterfacePort(); start(manager, KEY, replacementPort); @@ -99,11 +100,10 @@ class RedshiftProxyManagerTest { } } - @Test void updateIamRolesSwapsTheRunningSnapshotWithoutARestart() throws Exception { RedshiftProxyManager manager = newManager(); - int port = availablePort(); + int port = FreePorts.anyInterfacePort(); try { start(manager, KEY, port); manager.updateIamRoles(KEY, List.of("arn:aws:iam::111111111111:role/copy")); @@ -129,7 +129,7 @@ class RedshiftProxyManagerTest { @Test void updateMasterPasswordSwapsTheRunningSnapshot() throws Exception { RedshiftProxyManager manager = newManager(); - int port = availablePort(); + int port = FreePorts.anyInterfacePort(); try { start(manager, KEY, port); manager.updateMasterPassword(KEY, "rotated"); @@ -142,9 +142,9 @@ class RedshiftProxyManagerTest { @Test void stopAllReleasesEveryListenerAndIsIdempotent() throws IOException { RedshiftProxyManager manager = newManager(); - int a = availablePort(); + int a = FreePorts.anyInterfacePort(); start(manager, KEY, a); - int b = availablePort(); + int b = FreePorts.anyInterfacePort(); start(manager, SECOND_KEY, b); manager.stopAll(); @@ -239,7 +239,7 @@ class RedshiftProxyManagerTest { RedshiftAuthProxy stuck = mock(RedshiftAuthProxy.class); doThrow(new RuntimeException("close failed")).when(stuck).stop(); unclosable(manager).put(KEY, stuck); - int port = availablePort(); + int port = FreePorts.anyInterfacePort(); try { // A fresh start for the same key must not silently drop the leaked listener. start(manager, KEY, port); @@ -295,11 +295,6 @@ class RedshiftProxyManagerTest { return (List) field.get(proxy); } - private static int availablePort() throws IOException { - try (ServerSocket socket = new ServerSocket(0)) { - return socket.getLocalPort(); - } - } private static void assertPortAvailable(int port) { IOException last = null; diff --git a/src/test/java/io/github/hectorvent/floci/testing/SidecarContainersProfile.java b/src/test/java/io/github/hectorvent/floci/testing/SidecarContainersProfile.java index 7c1c8a9c5e..9c154afe18 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/SidecarContainersProfile.java +++ b/src/test/java/io/github/hectorvent/floci/testing/SidecarContainersProfile.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.testing; +import io.github.hectorvent.floci.testutil.FreePorts; import io.quarkus.test.junit.QuarkusTestProfile; import org.eclipse.microprofile.config.ConfigProvider; import org.junit.jupiter.api.Assumptions; @@ -7,7 +8,6 @@ import org.junit.jupiter.api.Assumptions; import java.io.IOException; import java.io.UncheckedIOException; import java.net.InetAddress; -import java.net.ServerSocket; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -92,8 +92,8 @@ public class SidecarContainersProfile implements QuarkusTestProfile { } private static int freePort() { - try (ServerSocket socket = new ServerSocket(0)) { - return socket.getLocalPort(); + try { + return FreePorts.anyInterfacePort(); } catch (IOException e) { throw new UncheckedIOException("No free port for the sidecar test application", e); } diff --git a/src/test/java/io/github/hectorvent/floci/testutil/FreePorts.java b/src/test/java/io/github/hectorvent/floci/testutil/FreePorts.java new file mode 100644 index 0000000000..27ea8f4bc3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testutil/FreePorts.java @@ -0,0 +1,30 @@ +package io.github.hectorvent.floci.testutil; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; + +/** Helpers for choosing ports in tests that bind their own servers. */ +public final class FreePorts { + + private FreePorts() { + } + + /** Returns a port selected by binding on any local interface. */ + public static int anyInterfacePort() throws IOException { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + } + } + + /** + * Returns a port selected by binding to IPv4 loopback, for host-side Docker bindings. + * Docker Desktop needs this host port named explicitly: a daemon-picked host port is allocated + * on the host side only, where the daemon that pushes and pulls cannot reach it. + */ + public static int loopbackIpv4Port() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + return socket.getLocalPort(); + } + } +}