diff --git a/docs/services/elasticache.md b/docs/services/elasticache.md index d4704ddefc..6402127fa2 100644 --- a/docs/services/elasticache.md +++ b/docs/services/elasticache.md @@ -66,6 +66,29 @@ created against a name nothing resolves.) Each record re-reserves its proxy port as it is restored, before Floci serves anything, so a create is never handed a port a surviving cluster or replication group still advertises. +#### Port, when two caches ask for the same one + +On AWS, `Port` belongs to a cache's own endpoint. 6379 is the Redis default, so nearly every +ElastiCache cluster uses it and they coexist: each cache gets a DNS name of its own, and the +port never has to tell them apart. Floci puts every cache's proxy on one host, where a TCP port +is exclusive and the port is the only thing that does tell them apart. + +So a `Port` you pass is honored when it is free and inside +`FLOCI_SERVICES_ELASTICACHE_PROXY_BASE_PORT`/`_MAX_PORT`, and otherwise the cache is served on +another port from that range, which is the port its endpoint then reports. A create is never +refused for a port that is merely taken: refusing the second cache on 6379 breaks any module +standing up two Redis clusters, and any suite running one per test in parallel. + +**The port a cache reports is always the port it is actually on.** If you pinned one Floci could +not give you, the endpoint reports the substitute rather than the port you asked for, and the +create logs a warning saying which and why. That is a visible difference: terraform treats the +port as replacement-forcing, so a pinned port that was unavailable shows up as a diff on the +next plan. It is deliberately preferred to the alternative, where a cache reports the port you +pinned while listening somewhere else, because that endpoint names a *different* cache's +listener and a client following it reads the wrong cache's data with no error. + +The only port rejection left is AWS's own: `Port` must be between 1150 and 65535. + `SnapshotRetentionLimit`, `SnapshotWindow`, `PreferredMaintenanceWindow`, `PreferredAvailabilityZone`, `SecurityGroupIds`, `NetworkType`, `IpDiscovery` and `AtRestEncryptionEnabled` (output-only on real AWS's CreateCacheCluster; accepted here leniently and echoed) are kept and echoed by `DescribeCacheClusters`, with the same defaults diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java index c513ce1ca8..6a0fa25780 100644 --- a/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java +++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheService.java @@ -1652,41 +1652,61 @@ public class ElastiCacheService implements ResourceProvider { } /** - * Honors the request's {@code Port} when it is free and inside the proxy range. AWS models - * Port as an optional input on CreateReplicationGroup ("the port number on which each member - * of the replication group accepts connections"), so a caller that pins one and reads back a - * different value sees permanent drift: Terraform treats the port as replacement-forcing. + * Honors the request's {@code Port} when it is free and inside the proxy range, and otherwise + * serves the cache on a port from that range instead of refusing it. * - *

An explicit port is therefore either honored or refused, never quietly changed. - * Substituting one reproduces the very drift honoring it was meant to remove, and the - * substitution could only ever hit a caller who did ask for a port: one who does not care - * passes null and never reaches that branch. Floci multiplexes every group's proxy onto one - * host, so two groups genuinely cannot share a port, and a caller who pinned an unavailable - * one needs to know rather than discover it as drift later. + *

On AWS, Port belongs to a cache's own endpoint. 6379 is the Redis default, so nearly + * every ElastiCache cluster in the world uses it and they coexist: AWS gives each cache a DNS + * name of its own, and the port never has to distinguish them. Floci multiplexes every + * cache's proxy onto one host, where a TCP port is exclusive and the port is the only thing + * that does distinguish them. Refusing the second cache on 6379, which is what this method + * used to do, diverges from AWS on an entirely ordinary request: any module standing up two + * Redis clusters, and any suite running one per test in parallel, failed at the second + * create. * - *

Only an unpinned create falls back through the range below. - * {@code NeptuneService.allocateProxyPort} still substitutes on this path and carries the - * same flaw. + *

Which leaves a choice about the port a caller pinned but cannot have, and only two of + * the three obvious answers are safe. Refusing is the divergence above. Reporting the pinned + * port anyway, while listening on another, is worse than it sounds: the endpoint then names + * a listener belonging to a different cache, so a client that dials it reads someone + * else's data and is told nothing. That is the failure #4094 removed on the restore path, + * where "the old endpoint then reached an unrelated cache instead of failing cleanly". + * + *

So the port a cache reports is always the port it is actually on. A caller that pinned + * an unavailable port sees drift, which terraform surfaces as a replacement-forcing diff on + * the next plan. That is a visible, reversible failure, where the alternative is a silent + * wrong answer, and the create still succeeds. The WARN below names the port that was served + * and why the pinned one could not be. + * + *

A port outside the proxy range is substituted for the same reason rather than refused: + * the range bounds what this emulator may listen on, and never bounded what AWS accepts. The + * only rejection left is AWS's own, 1150 to 65535, which {@code RdsService.reserveProxyPort} + * applies to the same argument. */ private int allocateProxyPort(Integer requested) { int base = config.services().elasticache().proxyBasePort(); int max = config.services().elasticache().proxyMaxPort(); if (requested != null) { - if (requested < base || requested > max) { - LOG.infov("Rejecting ElastiCache port {0}: outside the proxy range {1}-{2}", - String.valueOf(requested), String.valueOf(base), String.valueOf(max)); + if (requested < 1150 || requested > 65535) { throw new AwsException("InvalidParameterValue", - "Port " + requested + " is outside the port range this emulator serves (" - + base + "-" + max + ").", 400); + "Port must be between 1150 and 65535.", 400); } - if (!usedPorts.add(requested)) { - LOG.infov("Rejecting ElastiCache port {0}: already used by another replication group", - String.valueOf(requested)); - throw new AwsException("InvalidParameterValue", - "Port " + requested + " is already in use by another replication group.", 400); + if (requested >= base && requested <= max && usedPorts.add(requested)) { + return requested; } - return requested; + int substitute = scanForFreePort(base, max); + LOG.warnv("ElastiCache port {0} could not be served: it is {1}. This cache is on {2} " + + "instead, and that is the port its endpoint reports.", + String.valueOf(requested), + requested < base || requested > max + ? "outside the proxy range " + base + "-" + max + : "already in use by another cache here", + String.valueOf(substitute)); + return substitute; } + return scanForFreePort(base, max); + } + + private int scanForFreePort(int base, int max) { for (int port = base; port <= max; port++) { if (usedPorts.add(port)) { return port; diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCachePortSharingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCachePortSharingIntegrationTest.java new file mode 100644 index 0000000000..d0ae6cf4ca --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCachePortSharingIntegrationTest.java @@ -0,0 +1,233 @@ +package io.github.hectorvent.floci.services.elasticache; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +/** + * Two caches may both ask for 6379, and each is reachable at the endpoint it reports. + * + *

6379 is the Redis default, so nearly every ElastiCache cluster uses it and on AWS they + * coexist: each cache has a DNS name of its own and the port never distinguishes them. Floci has + * one host, so the port is the only thing that does. It used to refuse the second cache, which + * fails any module standing up two Redis clusters. It now serves the second cache on a port of + * its own and reports that port. + * + *

The assertion that matters is the last one, and it is at the data plane rather than the + * control plane: writing through each cache's own advertised endpoint and reading it back must + * return that cache's value. Reporting the pinned port while listening elsewhere would satisfy + * every field check in this class and still send the second cache's client to the first cache's + * data. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class ElastiCachePortSharingIntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=test/20260412/us-east-1/elasticache/aws4_request"; + + /** The Redis default, and the port every module in the corpus pins. */ + private static final int SHARED_PORT = 6379; + + private static final String FIRST_GROUP = "it-ec-share-a"; + private static final String SECOND_GROUP = "it-ec-share-b"; + + private static final String CREATED_PORT = + "CreateReplicationGroupResponse.CreateReplicationGroupResult.ReplicationGroup" + + ".NodeGroups.NodeGroup.PrimaryEndpoint.Port"; + private static final String DESCRIBED_PORT = + "DescribeReplicationGroupsResponse.DescribeReplicationGroupsResult.ReplicationGroups" + + ".ReplicationGroup.NodeGroups.NodeGroup.PrimaryEndpoint.Port"; + private static final String MEMBER_NODE_PORT = + "DescribeCacheClustersResponse.DescribeCacheClustersResult.CacheClusters.CacheCluster" + + ".CacheNodes.CacheNode.Endpoint.Port"; + + private static int firstPort; + private static int secondPort; + + @BeforeAll + static void requireDocker() { + Assumptions.assumeTrue(isDockerAvailable(), + "Docker must be available: the data-plane assertion needs real caches behind the proxies"); + } + + @AfterAll + static void cleanup() { + for (String groupId : List.of(FIRST_GROUP, SECOND_GROUP)) { + try { + given() + .formParam("Action", "DeleteReplicationGroup") + .formParam("ReplicationGroupId", groupId) + .header("Authorization", AUTH_HEADER) + .post("/"); + } catch (Exception ignored) { + // Best effort: a group a test never created has nothing to tear down. + } + } + } + + @Test + @Order(1) + void firstGroupIsServedOnThePortItAskedFor() { + firstPort = createGroup(FIRST_GROUP, SHARED_PORT) + .statusCode(200) + .body(CREATED_PORT, equalTo(String.valueOf(SHARED_PORT))) + .extract().xmlPath().getInt(CREATED_PORT); + } + + /** The bug: AWS creates this group, and Floci answered InvalidParameterValue. */ + @Test + @Order(2) + void secondGroupOnTheSamePortIsCreatedRatherThanRefused() { + secondPort = createGroup(SECOND_GROUP, SHARED_PORT) + .statusCode(200) + .extract().xmlPath().getInt(CREATED_PORT); + + assertNotEquals(firstPort, secondPort, + "The second group must be served somewhere of its own, not on the first's port"); + } + + @Test + @Order(3) + void eachGroupKeepsReportingThePortItIsOn() { + assertEquals(firstPort, describeGroup(FIRST_GROUP).extract().xmlPath().getInt(DESCRIBED_PORT)); + assertEquals(secondPort, describeGroup(SECOND_GROUP).extract().xmlPath().getInt(DESCRIBED_PORT)); + } + + /** The terraform provider reads a member's port out of DescribeCacheClusters. */ + @Test + @Order(4) + void memberCacheClustersAgreeWithTheGroupEndpoint() { + assertEquals(secondPort, + describeMember(SECOND_GROUP + "-001").extract().xmlPath().getInt(MEMBER_NODE_PORT)); + } + + /** AWS's own rule, and the only rejection left. */ + @Test + @Order(5) + void aPortOutsideTheRangeAwsAcceptsIsStillRefused() { + given() + .formParam("Action", "CreateReplicationGroup") + .formParam("ReplicationGroupId", "it-ec-share-bad-port") + .formParam("ReplicationGroupDescription", "port sharing test") + .formParam("Engine", "redis") + .formParam("NumCacheClusters", "1") + .formParam("Port", "80") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("")); + } + + /** + * The one that would have caught the wrong answer. Each cache is written through the endpoint + * it advertises and read back through the same one: if either endpoint named the other + * cache's listener, the second read would return the first cache's value and every assertion + * above would still have passed. + */ + @Test + @Order(6) + void eachAdvertisedEndpointReachesItsOwnCache() throws Exception { + send(firstPort, resp("SET", "who", "first")); + send(secondPort, resp("SET", "who", "second")); + + assertEquals("first", bulkString(send(firstPort, resp("GET", "who"))), + "The first group's endpoint must reach the first group"); + assertEquals("second", bulkString(send(secondPort, resp("GET", "who"))), + "and the second group's endpoint must reach the second group, not the first"); + } + + private static ValidatableResponse createGroup(String groupId, int port) { + return given() + .formParam("Action", "CreateReplicationGroup") + .formParam("ReplicationGroupId", groupId) + .formParam("ReplicationGroupDescription", "port sharing test") + .formParam("Engine", "redis") + .formParam("NumCacheClusters", "1") + .formParam("Port", String.valueOf(port)) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then(); + } + + private static ValidatableResponse describeGroup(String groupId) { + return given() + .formParam("Action", "DescribeReplicationGroups") + .formParam("ReplicationGroupId", groupId) + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + } + + private static ValidatableResponse describeMember(String cacheClusterId) { + return given() + .formParam("Action", "DescribeCacheClusters") + .formParam("CacheClusterId", cacheClusterId) + .formParam("ShowCacheNodeInfo", "true") + .header("Authorization", AUTH_HEADER) + .when() + .post("/") + .then() + .statusCode(200); + } + + private static String resp(String... args) { + StringBuilder sb = new StringBuilder("*").append(args.length).append("\r\n"); + for (String arg : args) { + sb.append('$').append(arg.length()).append("\r\n").append(arg).append("\r\n"); + } + return sb.toString(); + } + + /** Reads one RESP reply; enough for the +OK and $-prefixed bulk strings these commands give. */ + private static String send(int port, String command) throws IOException { + try (Socket socket = new Socket("localhost", port)) { + socket.setSoTimeout(10_000); + OutputStream out = socket.getOutputStream(); + out.write(command.getBytes(StandardCharsets.UTF_8)); + out.flush(); + InputStream in = socket.getInputStream(); + byte[] buffer = new byte[256]; + int read = in.read(buffer); + return read < 0 ? "" : new String(buffer, 0, read, StandardCharsets.UTF_8); + } + } + + private static String bulkString(String reply) { + String[] lines = reply.split("\r\n"); + return lines.length > 1 ? lines[1] : reply; + } + + private static boolean isDockerAvailable() { + try { + return new ProcessBuilder("docker", "info").start().waitFor() == 0; + } catch (Exception e) { + return false; + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java index aabdf9c2e6..d28cc7f912 100644 --- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheServiceTest.java @@ -268,6 +268,7 @@ class ElastiCacheServiceTest { assertEquals(16390, group.getProxyPort(), "A free, in-range requested Port must be the port the group reports"); + assertEquals(16390, group.getConfigurationEndpoint().port()); } @Test @@ -279,31 +280,43 @@ class ElastiCacheServiceTest { } @Test - void requestedPortAlreadyInUseIsRejected() { - // floci multiplexes every group's proxy onto one host, so two groups cannot share a port. - // Substituting a different one would hand back the drift honoring Port exists to remove, - // and it could only ever hit a caller who did pin a port. + void aSecondGroupOnATakenPortIsServedElsewhereRatherThanRefused() { + // AWS gives each cache a DNS name of its own, so 6379 is shared routinely and two groups + // on it coexist. Floci has one host and one port namespace, so the second group cannot + // have the port; refusing it diverged from AWS on an ordinary request, and reporting the + // pinned port while listening elsewhere would point its endpoint at the FIRST group's + // listener. It is served on a port of its own, and reports that port. service.createReplicationGroup(singleNodeRequest("grp1", 16390)); - AwsException thrown = assertThrows(AwsException.class, - () -> service.createReplicationGroup(singleNodeRequest("grp2", 16390))); + ReplicationGroup second = service.createReplicationGroup(singleNodeRequest("grp2", 16390)); - assertEquals("InvalidParameterValue", thrown.getErrorCode()); - assertTrue(thrown.getMessage().contains("16390")); + assertEquals(16379, second.getProxyPort(), + "The second group takes a free port rather than being refused"); + assertEquals(second.getProxyPort(), second.getConfigurationEndpoint().port(), + "and its endpoint reports the port it is actually on, never the other group's"); } @Test - void requestedPortOutsideTheProxyRangeIsRejected() { + void aPortOutsideTheProxyRangeIsServedElsewhereRatherThanRefused() { + // The range bounds what Floci may listen on. It never bounded what AWS accepts. + ReplicationGroup group = service.createReplicationGroup(singleNodeRequest("grp", 9999)); + + assertEquals(16379, group.getProxyPort()); + assertEquals(16379, group.getConfigurationEndpoint().port(), + "An endpoint never advertises a port nothing is listening on"); + } + + @Test + void aPortOutsideTheRangeAwsAcceptsIsStillRejected() { AwsException thrown = assertThrows(AwsException.class, - () -> service.createReplicationGroup(singleNodeRequest("grp", 9999))); + () -> service.createReplicationGroup(singleNodeRequest("grp", 80))); assertEquals("InvalidParameterValue", thrown.getErrorCode()); - assertTrue(thrown.getMessage().contains("9999")); + assertTrue(thrown.getMessage().contains("1150")); } @Test void anUnpinnedCreateStillFallsBackWhenTheBasePortIsTaken() { - // The fallback survives for callers that named no port: only an explicit one is refused. service.createReplicationGroup(singleNodeRequest("grp1", 16379)); ReplicationGroup second = service.createReplicationGroup(singleNodeRequest("grp2", null));