Light, fluffy, and always free - The AWS Local Emulator alternative
fix(elasticache): support HELLO AUTH handshakes (#4476)
XuJianc530d1f7051d
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.javaindex 66a6f0dc4a..0a83d1c2e4 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@@ -1584,7 +1584,7 @@ public class ElastiCacheService implements ResourceProvider {return false;}- if (username == null || username.isEmpty()) {+ if (username == null || username.isEmpty() || "default".equals(username)) {// AUTH password form: check group-level authToken firstif (group.getAuthToken() != null && password.equals(group.getAuthToken())) {return true;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.javaindex 52e204a4fb..5399be01a5 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@@ -8,18 +8,24 @@ import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;import java.nio.charset.StandardCharsets;+import java.util.ArrayList;+import java.util.List;+import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.CountDownLatch;/*** Shared TCP auth-proxy skeleton for the Redis (RESP) wire protocol. Intercepts the- * {@code AUTH} command, validates credentials through the subclass, then becomes a- * transparent byte relay to the backend container. Used by both the ElastiCache and- * MemoryDB proxies, since MemoryDB's real AWS design is explicitly modeled on- * ElastiCache: same Redis-compatible wire protocol, same IAM-auth mechanism.+ * {@code AUTH} command or the {@code AUTH} option in {@code HELLO}, validates credentials+ * through the subclass, then becomes a transparent byte relay to the backend container.+ * Used by both the ElastiCache and MemoryDB proxies, since MemoryDB's real AWS design is+ * explicitly modeled on ElastiCache: same Redis-compatible wire protocol, same IAM-auth+ * mechanism.** <p>Uses Java virtual threads to accept connections and run the AUTH handshake.*/public abstract class AbstractRedisAuthProxy {+ private static final int HANDSHAKE_TIMEOUT_MILLIS = 10_000;private static final long RELAY_JOIN_TIMEOUT_MILLIS = 1_000;private static final byte[] OK_RESPONSE = "+OK\r\n".getBytes(StandardCharsets.UTF_8);@@ -28,9 +34,25 @@ public abstract class AbstractRedisAuthProxy {private static final byte[] INVALID_AUTH_RESPONSE ="-ERR invalid username-password pair or user is disabled.\r\n".getBytes(StandardCharsets.UTF_8);+ private static final byte[] WRONGPASS_RESPONSE =+ "-WRONGPASS invalid username-password pair or user is disabled.\r\n"+ .getBytes(StandardCharsets.UTF_8);private static final byte[] WRONG_ARGS_RESPONSE ="-ERR wrong number of arguments for 'auth' command\r\n".getBytes(StandardCharsets.UTF_8);+ private static final byte[] HELLO_NOAUTH_RESPONSE =+ ("-NOAUTH HELLO must be called with the client already authenticated, otherwise the "+ + "HELLO <proto> AUTH <user> <pass> option can be used to authenticate the client "+ + "and select the RESP protocol version at the same time\r\n")+ .getBytes(StandardCharsets.UTF_8);+ private static final byte[] HELLO_PROTOCOL_ERROR_RESPONSE =+ "-ERR Protocol version is not an integer or out of range\r\n"+ .getBytes(StandardCharsets.UTF_8);+ private static final byte[] HELLO_UNSUPPORTED_PROTOCOL_RESPONSE =+ "-NOPROTO unsupported protocol version\r\n".getBytes(StandardCharsets.UTF_8);+ private static final byte[] INVALID_CLIENT_NAME_RESPONSE =+ "-ERR Client names cannot contain spaces, newlines or special characters.\r\n"+ .getBytes(StandardCharsets.UTF_8);private final Logger log;private final String serviceName;@@ -38,18 +60,28 @@ public abstract class AbstractRedisAuthProxy {private final String resourceId;private final String backendHost;private final int backendPort;+ private final int handshakeTimeoutMillis;+ private final Set<Socket> handshakingClients = ConcurrentHashMap.newKeySet();private volatile boolean running;private ServerSocket serverSocket;protected AbstractRedisAuthProxy(Logger log, String serviceName, String threadPrefix,String resourceId, String backendHost, int backendPort) {+ this(log, serviceName, threadPrefix, resourceId, backendHost, backendPort,+ HANDSHAKE_TIMEOUT_MILLIS);+ }++ protected AbstractRedisAuthProxy(Logger log, String serviceName, String threadPrefix,+ String resourceId, String backendHost, int backendPort,+ int handshakeTimeoutMillis) {this.log = log;this.serviceName = serviceName;this.threadPrefix = threadPrefix;this.resourceId = resourceId;this.backendHost = backendHost;this.backendPort = backendPort;+ this.handshakeTimeoutMillis = handshakeTimeoutMillis;}/** Whether the {@code AUTH} command is required before bridging to the backend. */@@ -78,12 +110,22 @@ public abstract class AbstractRedisAuthProxy {} catch (IOException e) {log.warnv("Error closing proxy server socket for {0}: {1}", resourceId, e.getMessage());}+ for (Socket client : handshakingClients) {+ closeQuietly(client);+ }+ handshakingClients.clear();}private void acceptLoop() {while (running) {try {Socket client = serverSocket.accept();+ handshakingClients.add(client);+ if (!running) {+ handshakingClients.remove(client);+ closeQuietly(client);+ continue;+ }Thread.ofVirtual().name(threadPrefix + "-proxy-conn-" + resourceId).start(() -> handleConnection(client));} catch (IOException e) {@@ -97,31 +139,44 @@ public abstract class AbstractRedisAuthProxy {private void handleConnection(Socket client) {try {client.setTcpNoDelay(true);+ client.setSoTimeout(handshakeTimeoutMillis);RespReader reader = new RespReader(client.getInputStream());- String[] cmd = reader.readCommand();+ while (true) {+ String[] cmd = reader.readCommand();- if (cmd.length == 0) {- closeQuietly(client);- return;- }+ if (cmd.length == 0) {+ closeQuietly(client);+ return;+ }- if (cmd[0].equalsIgnoreCase("AUTH")) {- handleAuth(client, cmd);- } else if (authRequired()) {- client.getOutputStream().write(NOAUTH_RESPONSE);- client.getOutputStream().flush();- closeQuietly(client);- } else {- // No auth required and no AUTH command: bridge immediately.- // First re-send the already-read command to the backend.- Socket backend = new Socket(backendHost, backendPort);- backend.setTcpNoDelay(true);- resendCommand(cmd, backend.getOutputStream());- bridge(client, backend);+ if (cmd[0].equalsIgnoreCase("AUTH")) {+ handleAuth(client, cmd);+ return;+ }+ if (cmd[0].equalsIgnoreCase("HELLO")) {+ if (authRequired()) {+ if (handleHello(client, cmd)) {+ return;+ }+ continue;+ }+ bridgeCommand(client, cmd);+ return;+ }+ if (authRequired()) {+ writeResponse(client, NOAUTH_RESPONSE);+ closeQuietly(client);+ return;+ }++ bridgeCommand(client, cmd);+ return;}} catch (Exception e) {log.debugv("Connection error for {0}: {1}", resourceId, e.getMessage());closeQuietly(client);+ } finally {+ handshakingClients.remove(client);}}@@ -146,18 +201,117 @@ public abstract class AbstractRedisAuthProxy {boolean authenticated = !authRequired() || authenticate(username, password);if (!authenticated) {- client.getOutputStream().write(INVALID_AUTH_RESPONSE);- client.getOutputStream().flush();+ writeResponse(client, INVALID_AUTH_RESPONSE);closeQuietly(client);return;}- client.getOutputStream().write(OK_RESPONSE);- client.getOutputStream().flush();+ writeResponse(client, OK_RESPONSE);+ bridgeCommand(client, null);+ }++ private boolean handleHello(Socket client, String[] cmd) throws IOException {+ if (cmd.length > 1) {+ long protocolVersion;+ try {+ protocolVersion = Long.parseLong(cmd[1]);+ } catch (NumberFormatException e) {+ writeResponse(client, HELLO_PROTOCOL_ERROR_RESPONSE);+ return false;+ }+ if (protocolVersion < 2 || protocolVersion > 3) {+ writeResponse(client, HELLO_UNSUPPORTED_PROTOCOL_RESPONSE);+ return false;+ }+ }+ List<String> forwarded = new ArrayList<>();+ forwarded.add(cmd[0]);+ if (cmd.length > 1) {+ forwarded.add(cmd[1]);+ }++ String username = null;+ String password = null;+ String clientName = null;+ boolean authProvided = false;+ boolean clientNameProvided = false;+ int optionIndex = 2;+ while (optionIndex < cmd.length) {+ String option = cmd[optionIndex];+ if (option.equalsIgnoreCase("AUTH") && optionIndex + 2 < cmd.length) {+ username = cmd[optionIndex + 1];+ password = cmd[optionIndex + 2];+ authProvided = true;+ optionIndex += 3;+ } else if (option.equalsIgnoreCase("SETNAME") && optionIndex + 1 < cmd.length) {+ clientName = cmd[optionIndex + 1];+ if (!isValidClientName(clientName)) {+ writeResponse(client, INVALID_CLIENT_NAME_RESPONSE);+ return false;+ }+ clientNameProvided = true;+ optionIndex += 2;+ } else {+ writeHelloSyntaxError(client, option);+ return false;+ }+ }++ if (clientNameProvided) {+ forwarded.add("SETNAME");+ forwarded.add(clientName);+ }++ if (authRequired() && !authProvided) {+ writeResponse(client, HELLO_NOAUTH_RESPONSE);+ return false;+ }+ if (authRequired() && !authenticate(username, password)) {+ writeResponse(client, WRONGPASS_RESPONSE);+ return false;+ }++ bridgeCommand(client, forwarded.toArray(String[]::new));+ return true;+ }++ private static void writeHelloSyntaxError(Socket client, String option) throws IOException {+ String sanitizedOption = option.replace('\r', ' ').replace('\n', ' ');+ byte[] response = ("-ERR Syntax error in HELLO option '" + sanitizedOption + "'\r\n")+ .getBytes(StandardCharsets.UTF_8);+ writeResponse(client, response);+ }++ private static boolean isValidClientName(String clientName) {+ for (int index = 0; index < clientName.length(); index++) {+ char character = clientName.charAt(index);+ if (character <= ' ' || character > '~') {+ return false;+ }+ }+ return true;+ }++ private void bridgeCommand(Socket client, String[] command) throws IOException {Socket backend = new Socket(backendHost, backendPort);- backend.setTcpNoDelay(true);- bridge(client, backend);+ try {+ backend.setTcpNoDelay(true);+ if (command != null) {+ resendCommand(command, backend.getOutputStream());+ }+ client.setSoTimeout(0);+ handshakingClients.remove(client);+ bridge(client, backend);+ } catch (IOException e) {+ closeQuietly(backend);+ throw e;+ }+ }++ private static void writeResponse(Socket client, byte[] response) throws IOException {+ client.getOutputStream().write(response);+ client.getOutputStream().flush();}/**diff --git a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/RespReader.java b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/RespReader.javaindex 538fd3dfda..5ecd6b50dc 100644--- a/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/RespReader.java+++ b/src/main/java/io/github/hectorvent/floci/services/elasticache/proxy/RespReader.java@@ -5,8 +5,8 @@ import java.io.InputStream;import java.nio.charset.StandardCharsets;/**- * Minimal Redis RESP protocol parser for reading the first command from a socket InputStream.- * Only parses the AUTH command — after that, the connection is relayed verbatim.+ * Minimal Redis RESP protocol parser for reading authentication-handshake commands from a+ * socket InputStream. After authentication, the connection is relayed verbatim.*/public class RespReader {diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheIntegrationTest.javaindex 3f84653b66..508cd875c5 100644--- a/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/ElastiCacheIntegrationTest.java@@ -24,6 +24,7 @@ import static org.hamcrest.Matchers.equalTo;import static org.hamcrest.Matchers.not;import static org.hamcrest.Matchers.notNullValue;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;@QuarkusTest@TestMethodOrder(MethodOrderer.OrderAnnotation.class)@@ -143,13 +144,25 @@ class ElastiCacheIntegrationTest {@Test@Order(5)+ void groupAuthTokenWorksWithHelloAuth() throws Exception {+ try (Socket socket = openSocket(firstProxyPort)) {+ write(socket, respArray("HELLO", "3", "AUTH", "default", GROUP_AUTH_TOKEN));+ assertTrue(readRespValue(socket).startsWith("%"));++ write(socket, respArray("PING"));+ assertEquals("+PONG\r\n", readLine(socket));+ }+ }++ @Test+ @Order(6)void wrongPasswordIsRejected() throws Exception {String reply = sendCommand(firstProxyPort, respArray("AUTH", "wrong-password"));assertEquals("-ERR invalid username-password pair or user is disabled.\r\n", reply);}@Test- @Order(6)+ @Order(7)void createUser() {given().formParam("Action", "CreateUser")@@ -170,7 +183,7 @@ class ElastiCacheIntegrationTest {}@Test- @Order(7)+ @Order(8)void unassociatedUserIsRejected() throws Exception {// Before associating the user with the group, auth should failString reply = sendCommand(firstProxyPort, respArray("AUTH", USER_NAME, INITIAL_PASSWORD));@@ -178,7 +191,7 @@ class ElastiCacheIntegrationTest {}@Test- @Order(8)+ @Order(9)void associateUserWithGroup() {given().formParam("Action", "ModifyReplicationGroup")@@ -193,7 +206,7 @@ class ElastiCacheIntegrationTest {}@Test- @Order(9)+ @Order(10)void describeUsersIncludesCreatedUser() {given().formParam("Action", "DescribeUsers")@@ -207,7 +220,7 @@ class ElastiCacheIntegrationTest {}@Test- @Order(10)+ @Order(11)void crossGroupAuthIsRejected() throws Exception {// Ensure user exists if this test is run in isolationtry {@@ -264,7 +277,7 @@ class ElastiCacheIntegrationTest {}@Test- @Order(11)+ @Order(12)void userPasswordAuthWorks() throws Exception {try (Socket socket = openSocket(firstProxyPort)) {write(socket, respArray("AUTH", USER_NAME, INITIAL_PASSWORD));@@ -276,7 +289,7 @@ class ElastiCacheIntegrationTest {}@Test- @Order(12)+ @Order(13)void modifyUserPasswordInvalidatesOldPasswordAndAcceptsNewPassword() throws Exception {given().formParam("Action", "ModifyUser")@@ -303,7 +316,7 @@ class ElastiCacheIntegrationTest {}@Test- @Order(13)+ @Order(14)void deleteUserRemovesUserFromDescribeUsers() {given().formParam("Action", "DeleteUser")@@ -326,7 +339,7 @@ class ElastiCacheIntegrationTest {}@Test- @Order(14)+ @Order(15)void deleteReplicationGroupReleasesProxyPortForReuse() {given().formParam("Action", "DeleteReplicationGroup")@@ -445,6 +458,51 @@ class ElastiCacheIntegrationTest {return new String(buffer, 0, offset, StandardCharsets.UTF_8);}+ private static String readRespValue(Socket socket) throws IOException {+ String header = readLine(socket);+ if (header.length() < 3) {+ throw new IOException("Invalid RESP value header: " + header);+ }++ char type = header.charAt(0);+ return switch (type) {+ case '$', '!', '=' -> {+ int count = parseRespLength(header);+ if (count >= 0) {+ byte[] payload = socket.getInputStream().readNBytes(count + 2);+ if (payload.length != count + 2+ || payload[count] != '\r' || payload[count + 1] != '\n') {+ throw new IOException("Incomplete RESP bulk payload");+ }+ }+ yield header;+ }+ case '*', '~', '>' -> {+ int count = parseRespLength(header);+ for (int index = 0; index < count; index++) {+ readRespValue(socket);+ }+ yield header;+ }+ case '%', '|' -> {+ int count = parseRespLength(header);+ for (int index = 0; index < count * 2; index++) {+ readRespValue(socket);+ }+ yield header;+ }+ default -> header;+ };+ }++ private static int parseRespLength(String header) throws IOException {+ try {+ return Integer.parseInt(header.substring(1, header.length() - 2));+ } catch (NumberFormatException e) {+ throw new IOException("Invalid RESP length: " + header, e);+ }+ }+private static String respArray(String... parts) {StringBuilder sb = new StringBuilder();sb.append("*").append(parts.length).append("\r\n");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.javaindex c7d576d8c8..aabdf9c2e6 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@@ -187,6 +187,7 @@ class ElastiCacheServiceTest {// Single-arg AUTH with group auth token should succeedassertTrue(service.validatePassword("grp", null, "group-token"));+ assertTrue(service.validatePassword("grp", "default", "group-token"));// Single-arg AUTH with wrong password should failassertFalse(service.validatePassword("grp", null, "wrong-token"));diff --git a/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxyHandshakeTest.java b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxyHandshakeTest.javanew file mode 100644index 0000000000..5b20422c99--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/elasticache/proxy/AbstractRedisAuthProxyHandshakeTest.java@@ -0,0 +1,362 @@+package io.github.hectorvent.floci.services.elasticache.proxy;++import org.jboss.logging.Logger;+import org.junit.jupiter.api.Test;++import java.io.IOException;+import java.io.InputStream;+import java.net.ServerSocket;+import java.net.Socket;+import java.net.SocketTimeoutException;+import java.nio.charset.StandardCharsets;+import java.util.Objects;+import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicInteger;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;++class AbstractRedisAuthProxyHandshakeTest {++ private static final int SOCKET_TIMEOUT_MILLIS = 2_000;+ private static final String USERNAME = "app";+ private static final String PASSWORD = "secret";++ @Test+ void helloAuthStripsCredentialsBeforeForwardingToBackend() throws Exception {+ try (ServerSocket backendServer = new ServerSocket(0)) {+ TestProxy proxy = startProxy(backendServer, true, USERNAME, PASSWORD);+ try (Socket client = openClient(proxy.proxyPort())) {+ write(client, respArray("HELLO", "3", "AUTH", USERNAME, PASSWORD,+ "SETNAME", "test-client"));++ try (Socket backend = acceptBackend(backendServer)) {+ byte[] expected = respArray("HELLO", "3", "SETNAME", "test-client");+ assertArrayEquals(expected, backend.getInputStream().readNBytes(expected.length));++ write(backend, "+HELLO\r\n".getBytes(StandardCharsets.US_ASCII));+ assertEquals("+HELLO\r\n", readLine(client));+ }+ } finally {+ proxy.stop();+ }+ }+ }++ @Test+ void helloAuthPreservesDefaultUsernameForValidator() throws Exception {+ try (ServerSocket backendServer = new ServerSocket(0)) {+ TestProxy proxy = startProxy(backendServer, true, "default", PASSWORD);+ try (Socket client = openClient(proxy.proxyPort())) {+ write(client, respArray("HELLO", "2", "AUTH", "default", PASSWORD));++ try (Socket backend = acceptBackend(backendServer)) {+ byte[] expected = respArray("HELLO", "2");+ assertArrayEquals(expected, backend.getInputStream().readNBytes(expected.length));++ write(backend, "+HELLO\r\n".getBytes(StandardCharsets.US_ASCII));+ assertEquals("+HELLO\r\n", readLine(client));+ }+ } finally {+ proxy.stop();+ }+ }+ }++ @Test+ void invalidClientNameIsRejectedBeforeAuthenticationAndAllowsRetry() throws Exception {+ try (ServerSocket backendServer = new ServerSocket(0)) {+ TestProxy proxy = startProxy(backendServer, true, USERNAME, PASSWORD);+ try (Socket client = openClient(proxy.proxyPort())) {+ write(client, respArray("HELLO", "3", "AUTH", USERNAME, PASSWORD,+ "SETNAME", "bad name"));++ assertEquals("-ERR Client names cannot contain spaces, newlines or special characters.\r\n",+ readLine(client));+ assertEquals(0, proxy.authenticationAttempts());+ backendServer.setSoTimeout(200);+ assertThrows(SocketTimeoutException.class, backendServer::accept);++ write(client, respArray("HELLO", "3", "AUTH", USERNAME, PASSWORD,+ "SETNAME", "good-name"));+ try (Socket backend = acceptBackend(backendServer)) {+ byte[] expected = respArray("HELLO", "3", "SETNAME", "good-name");+ assertArrayEquals(expected, backend.getInputStream().readNBytes(expected.length));++ write(backend, "+HELLO\r\n".getBytes(StandardCharsets.US_ASCII));+ assertEquals("+HELLO\r\n", readLine(client));+ }+ assertEquals(1, proxy.authenticationAttempts());+ } finally {+ proxy.stop();+ }+ }+ }++ @Test+ void helloSyntaxErrorSanitizesNewlinesAndAllowsRetry() throws Exception {+ try (ServerSocket backendServer = new ServerSocket(0)) {+ TestProxy proxy = startProxy(backendServer, true, USERNAME, PASSWORD);+ try (Socket client = openClient(proxy.proxyPort())) {+ write(client, respArray("HELLO", "3", "BAD\r\n+INJECTED"));+ assertEquals("-ERR Syntax error in HELLO option 'BAD +INJECTED'\r\n",+ readLine(client));++ write(client, respArray("HELLO", "3", "AUTH", USERNAME, PASSWORD));+ try (Socket backend = acceptBackend(backendServer)) {+ byte[] expected = respArray("HELLO", "3");+ assertArrayEquals(expected, backend.getInputStream().readNBytes(expected.length));++ write(backend, "+HELLO\r\n".getBytes(StandardCharsets.US_ASCII));+ assertEquals("+HELLO\r\n", readLine(client));+ }+ } finally {+ proxy.stop();+ }+ }+ }++ @Test+ void helloWithoutAuthReturnsNoAuthAndAllowsRetry() throws Exception {+ try (ServerSocket backendServer = new ServerSocket(0)) {+ TestProxy proxy = startProxy(backendServer, true, USERNAME, PASSWORD);+ try (Socket client = openClient(proxy.proxyPort())) {+ write(client, respArray("HELLO", "3"));+ assertEquals("-NOAUTH HELLO must be called with the client already authenticated, "+ + "otherwise the HELLO <proto> AUTH <user> <pass> option can be used to "+ + "authenticate the client and select the RESP protocol version at the same time\r\n",+ readLine(client));++ write(client, respArray("HELLO", "3", "AUTH", USERNAME, PASSWORD));+ try (Socket backend = acceptBackend(backendServer)) {+ byte[] expected = respArray("HELLO", "3");+ assertArrayEquals(expected, backend.getInputStream().readNBytes(expected.length));++ write(backend, "+HELLO\r\n".getBytes(StandardCharsets.US_ASCII));+ assertEquals("+HELLO\r\n", readLine(client));+ }+ } finally {+ proxy.stop();+ }+ }+ }++ @Test+ void wrongHelloPasswordReturnsWrongPassAndAllowsRetry() throws Exception {+ try (ServerSocket backendServer = new ServerSocket(0)) {+ TestProxy proxy = startProxy(backendServer, true, USERNAME, PASSWORD);+ try (Socket client = openClient(proxy.proxyPort())) {+ write(client, respArray("HELLO", "3", "AUTH", USERNAME, "wrong"));+ assertEquals("-WRONGPASS invalid username-password pair or user is disabled.\r\n",+ readLine(client));++ write(client, respArray("HELLO", "3", "AUTH", USERNAME, PASSWORD));+ try (Socket backend = acceptBackend(backendServer)) {+ byte[] expected = respArray("HELLO", "3");+ assertArrayEquals(expected, backend.getInputStream().readNBytes(expected.length));++ write(backend, "+HELLO\r\n".getBytes(StandardCharsets.US_ASCII));+ assertEquals("+HELLO\r\n", readLine(client));+ }+ } finally {+ proxy.stop();+ }+ }+ }++ @Test+ void invalidHelloRetryIsClosedAfterHandshakeTimeout() throws Exception {+ try (ServerSocket backendServer = new ServerSocket(0)) {+ TestProxy proxy = startProxy(backendServer, true, USERNAME, PASSWORD, 200);+ try (Socket client = openClient(proxy.proxyPort())) {+ write(client, respArray("HELLO", "3", "AUTH", USERNAME, "wrong"));+ assertEquals("-WRONGPASS invalid username-password pair or user is disabled.\r\n",+ readLine(client));++ assertEquals(-1, client.getInputStream().read());+ } finally {+ proxy.stop();+ }+ }+ }++ @Test+ void stopClosesClientWaitingForHelloRetry() throws Exception {+ try (ServerSocket backendServer = new ServerSocket(0)) {+ TestProxy proxy = startProxy(backendServer, true, USERNAME, PASSWORD, 5_000);+ try (Socket client = openClient(proxy.proxyPort())) {+ write(client, respArray("HELLO", "3", "AUTH", USERNAME, "wrong"));+ assertEquals("-WRONGPASS invalid username-password pair or user is disabled.\r\n",+ readLine(client));++ proxy.stop();+ assertEquals(-1, client.getInputStream().read());+ } finally {+ proxy.stop();+ }+ }+ }++ @Test+ void successfulHelloRetryClearsHandshakeTimeout() throws Exception {+ try (ServerSocket backendServer = new ServerSocket(0)) {+ TestProxy proxy = startProxy(backendServer, true, USERNAME, PASSWORD, 200);+ try (Socket client = openClient(proxy.proxyPort())) {+ write(client, respArray("HELLO", "3", "AUTH", USERNAME, "wrong"));+ assertEquals("-WRONGPASS invalid username-password pair or user is disabled.\r\n",+ readLine(client));++ write(client, respArray("HELLO", "3", "AUTH", USERNAME, PASSWORD));+ try (Socket backend = acceptBackend(backendServer)) {+ byte[] hello = respArray("HELLO", "3");+ assertArrayEquals(hello, backend.getInputStream().readNBytes(hello.length));+ write(backend, "+HELLO\r\n".getBytes(StandardCharsets.US_ASCII));+ assertEquals("+HELLO\r\n", readLine(client));++ TimeUnit.MILLISECONDS.sleep(300);+ byte[] ping = respArray("PING");+ write(client, ping);+ assertArrayEquals(ping, backend.getInputStream().readNBytes(ping.length));+ write(backend, "+PONG\r\n".getBytes(StandardCharsets.US_ASCII));+ assertEquals("+PONG\r\n", readLine(client));+ }+ } finally {+ proxy.stop();+ }+ }+ }++ @Test+ void helloOnOpenCacheIsForwardedVerbatim() throws Exception {+ try (ServerSocket backendServer = new ServerSocket(0)) {+ TestProxy proxy = startProxy(backendServer, false, USERNAME, PASSWORD);+ try (Socket client = openClient(proxy.proxyPort())) {+ byte[] command = respArray("HELLO", "3", "AUTH", "unused", "unused");+ write(client, command);++ try (Socket backend = acceptBackend(backendServer)) {+ assertArrayEquals(command, backend.getInputStream().readNBytes(command.length));++ write(backend, "+HELLO\r\n".getBytes(StandardCharsets.US_ASCII));+ assertEquals("+HELLO\r\n", readLine(client));+ }+ assertEquals(0, proxy.authenticationAttempts());+ } finally {+ proxy.stop();+ }+ }+ }++ private static TestProxy startProxy(ServerSocket backendServer, boolean authRequired,+ String username, String password) throws IOException {+ return startProxy(backendServer, authRequired, username, password,+ SOCKET_TIMEOUT_MILLIS);+ }++ private static TestProxy startProxy(ServerSocket backendServer, boolean authRequired,+ String username, String password,+ int handshakeTimeoutMillis) throws IOException {+ int proxyPort;+ try (ServerSocket freePort = new ServerSocket(0)) {+ proxyPort = freePort.getLocalPort();+ }+ TestProxy proxy = new TestProxy("127.0.0.1", backendServer.getLocalPort(), proxyPort,+ authRequired, username, password, handshakeTimeoutMillis);+ proxy.start(proxyPort);+ return proxy;+ }++ private static Socket openClient(int port) throws IOException {+ Socket client = new Socket("127.0.0.1", port);+ client.setSoTimeout(SOCKET_TIMEOUT_MILLIS);+ return client;+ }++ private static Socket acceptBackend(ServerSocket backendServer) throws IOException {+ backendServer.setSoTimeout(SOCKET_TIMEOUT_MILLIS);+ Socket backend = backendServer.accept();+ backend.setSoTimeout(SOCKET_TIMEOUT_MILLIS);+ return backend;+ }++ private static void write(Socket socket, byte[] bytes) throws IOException {+ socket.getOutputStream().write(bytes);+ socket.getOutputStream().flush();+ }++ private static String readLine(Socket socket) throws IOException {+ InputStream input = socket.getInputStream();+ StringBuilder line = new StringBuilder();+ int current;+ while ((current = input.read()) != -1) {+ line.append((char) current);+ if (line.length() >= 2+ && line.charAt(line.length() - 2) == '\r'+ && line.charAt(line.length() - 1) == '\n') {+ return line.toString();+ }+ }+ return line.toString();+ }++ private static byte[] respArray(String... parts) {+ StringBuilder command = new StringBuilder();+ command.append('*').append(parts.length).append("\r\n");+ for (String part : parts) {+ byte[] bytes = part.getBytes(StandardCharsets.UTF_8);+ command.append('$').append(bytes.length).append("\r\n");+ command.append(part).append("\r\n");+ }+ return command.toString().getBytes(StandardCharsets.UTF_8);+ }++ private static final class TestProxy extends AbstractRedisAuthProxy {+ private static final Logger LOG = Logger.getLogger(TestProxy.class);++ private final int proxyPort;+ private final boolean authRequired;+ private final String expectedUsername;+ private final String expectedPassword;+ private final AtomicInteger authenticationAttempts = new AtomicInteger();++ private TestProxy(String backendHost, int backendPort, int proxyPort,+ boolean authRequired, String expectedUsername, String expectedPassword,+ int handshakeTimeoutMillis) {+ super(LOG, "test", "test", "handshake", backendHost, backendPort,+ handshakeTimeoutMillis);+ this.proxyPort = proxyPort;+ this.authRequired = authRequired;+ this.expectedUsername = expectedUsername;+ this.expectedPassword = expectedPassword;+ }++ private int proxyPort() {+ return proxyPort;+ }++ private int authenticationAttempts() {+ return authenticationAttempts.get();+ }++ @Override+ protected boolean authRequired() {+ return authRequired;+ }++ @Override+ protected boolean authenticate(String username, String password) {+ authenticationAttempts.incrementAndGet();+ return Objects.equals(expectedUsername, username) && expectedPassword.equals(password);+ }++ @Override+ protected void closeQuietly(Socket socket) {+ try {+ socket.close();+ } catch (IOException ignored) {+ // The peer may already have closed the socket.+ }+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbIntegrationTest.javaindex 192f8cec71..f8b2b8e5c1 100644--- a/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/memorydb/MemoryDbIntegrationTest.java@@ -24,6 +24,7 @@ import static org.hamcrest.Matchers.equalTo;import static org.hamcrest.Matchers.hasItems;import static org.hamcrest.Matchers.notNullValue;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;/*** End-to-end MemoryDB test: JSON 1.1 control plane (CreateCluster/DescribeClusters/@@ -195,13 +196,25 @@ class MemoryDbIntegrationTest {@Test@Order(9)+ void aclUserCredentialsWorkWithHelloAuth() throws Exception {+ try (Socket socket = openSocket(authPort)) {+ write(socket, respArray("HELLO", "3", "AUTH", AUTH_USER, AUTH_PASSWORD));+ assertTrue(readRespValue(socket).startsWith("%"));++ write(socket, respArray("PING"));+ assertEquals("+PONG\r\n", readLine(socket));+ }+ }++ @Test+ @Order(10)void wrongPasswordRejected() throws Exception {assertEquals("-ERR invalid username-password pair or user is disabled.\r\n",sendCommand(authPort, respArray("AUTH", AUTH_USER, "wrong-password")));}@Test- @Order(10)+ @Order(11)void deleteClusterReleasesProxyPortForReuse() {deleteCluster(OPEN_CLUSTER).then()@@ -307,6 +320,51 @@ class MemoryDbIntegrationTest {return new String(buffer, 0, offset, StandardCharsets.UTF_8);}+ private static String readRespValue(Socket socket) throws IOException {+ String header = readLine(socket);+ if (header.length() < 3) {+ throw new IOException("Invalid RESP value header: " + header);+ }++ char type = header.charAt(0);+ return switch (type) {+ case '$', '!', '=' -> {+ int count = parseRespLength(header);+ if (count >= 0) {+ byte[] payload = socket.getInputStream().readNBytes(count + 2);+ if (payload.length != count + 2+ || payload[count] != '\r' || payload[count + 1] != '\n') {+ throw new IOException("Incomplete RESP bulk payload");+ }+ }+ yield header;+ }+ case '*', '~', '>' -> {+ int count = parseRespLength(header);+ for (int index = 0; index < count; index++) {+ readRespValue(socket);+ }+ yield header;+ }+ case '%', '|' -> {+ int count = parseRespLength(header);+ for (int index = 0; index < count * 2; index++) {+ readRespValue(socket);+ }+ yield header;+ }+ default -> header;+ };+ }++ private static int parseRespLength(String header) throws IOException {+ try {+ return Integer.parseInt(header.substring(1, header.length() - 2));+ } catch (NumberFormatException e) {+ throw new IOException("Invalid RESP length: " + header, e);+ }+ }+private static String respArray(String... parts) {StringBuilder sb = new StringBuilder();sb.append("*").append(parts.length).append("\r\n");