refactor(elasticache,memorydb): extract shared auth-proxy logic into a common base class (#3574)

ElastiCacheAuthProxy and MemoryDbAuthProxy each implemented their own copy of the
RESP AUTH handshake, accept loop, and client/backend relay, ~87 duplicated lines
flagged by CPD. MemoryDB's proxy is modeled on ElastiCache's (same wire protocol,
same IAM-auth mechanism), so both now extend AbstractRedisAuthProxy, which owns
the shared accept/handshake/relay plumbing behind two small hooks (authRequired,
authenticate) that each subclass implements against its own validators. No
behavior change: closeQuietly stays per-subclass since the two implementations
genuinely differ (ElastiCache shuts down the socket's output side and logs at
debug; MemoryDB just closes), and every other extracted method reproduces the
original logic byte for byte.

Also adds integration coverage for a path that existed before this refactor but
had no automated test either way: a client that sends an explicit AUTH command
on a connection where auth isn't required must still get +OK and stay usable,
rather than being rejected.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-13 21:05:04 -05:00
1 parent 7d6e9588cd
commit d1892e18a1
5 files changed
+279 -363

No files matched your search

@@ -0,0 +1,213 @@
package io.github.hectorvent.floci.services.elasticache.proxy;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/**
* 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.
*
* <p>Uses Java virtual threads to accept connections and run the AUTH handshake.
*/
public abstract class AbstractRedisAuthProxy {
private static final byte[] OK_RESPONSE = "+OK\r\n".getBytes(StandardCharsets.UTF_8);
private static final byte[] NOAUTH_RESPONSE =
"-NOAUTH Authentication required.\r\n".getBytes(StandardCharsets.UTF_8);
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[] WRONG_ARGS_RESPONSE =
"-ERR wrong number of arguments for 'auth' command\r\n"
.getBytes(StandardCharsets.UTF_8);
private final Logger log;
private final String serviceName;
private final String threadPrefix;
private final String resourceId;
private final String backendHost;
private final int backendPort;
private volatile boolean running;
private ServerSocket serverSocket;
protected AbstractRedisAuthProxy(Logger log, String serviceName, String threadPrefix,
String resourceId, String backendHost, int backendPort) {
this.log = log;
this.serviceName = serviceName;
this.threadPrefix = threadPrefix;
this.resourceId = resourceId;
this.backendHost = backendHost;
this.backendPort = backendPort;
}
/** Whether the {@code AUTH} command is required before bridging to the backend. */
protected abstract boolean authRequired();
/** Validates the supplied credentials. Not called when {@link #authRequired()} is false. */
protected abstract boolean authenticate(String username, String password);
/** Closes a socket, tolerating errors. Implementations may add their own logging. */
protected abstract void closeQuietly(Socket socket);
public void start(int proxyPort) throws IOException {
serverSocket = new ServerSocket(proxyPort);
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));
}
public void stop() {
running = false;
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
log.warnv("Error closing proxy server socket for {0}: {1}", resourceId, e.getMessage());
}
}
private void acceptLoop() {
while (running) {
try {
Socket client = serverSocket.accept();
Thread.ofVirtual().name(threadPrefix + "-proxy-conn-" + resourceId)
.start(() -> handleConnection(client));
} catch (IOException e) {
if (running) {
log.warnv("Accept error for {0}: {1}", resourceId, e.getMessage());
}
}
}
}
private void handleConnection(Socket client) {
try {
client.setTcpNoDelay(true);
RespReader reader = new RespReader(client.getInputStream());
String[] cmd = reader.readCommand();
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);
}
} catch (Exception e) {
log.debugv("Connection error for {0}: {1}", resourceId, e.getMessage());
closeQuietly(client);
}
}
private void handleAuth(Socket client, String[] cmd) throws IOException {
String username;
String password;
if (cmd.length == 2) {
// AUTH password
username = null;
password = cmd[1];
} else if (cmd.length == 3) {
// AUTH username password
username = cmd[1];
password = cmd[2];
} else {
client.getOutputStream().write(WRONG_ARGS_RESPONSE);
client.getOutputStream().flush();
closeQuietly(client);
return;
}
boolean authenticated = !authRequired() || authenticate(username, password);
if (!authenticated) {
client.getOutputStream().write(INVALID_AUTH_RESPONSE);
client.getOutputStream().flush();
closeQuietly(client);
return;
}
client.getOutputStream().write(OK_RESPONSE);
client.getOutputStream().flush();
Socket backend = new Socket(backendHost, backendPort);
backend.setTcpNoDelay(true);
bridge(client, backend);
}
/**
* Relay I/O runs on platform daemon threads (not virtual threads). A parent virtual thread
* from {@code handleConnection} blocks in {@code join} here; scheduling nested virtual-thread
* relays under load can stall delivery of backend responses (e.g. PING/PONG) to the client.
*/
private void bridge(Socket client, Socket backend) {
Thread t1 = Thread.ofPlatform().daemon(true).name(threadPrefix + "-relay-c2b-" + resourceId)
.start(() -> relay(client, backend));
Thread t2 = Thread.ofPlatform().daemon(true).name(threadPrefix + "-relay-b2c-" + resourceId)
.start(() -> relay(backend, client));
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
closeQuietly(client);
closeQuietly(backend);
}
}
private static void relay(Socket from, Socket to) {
byte[] buf = new byte[8192];
try {
InputStream in = from.getInputStream();
OutputStream out = to.getOutputStream();
int n;
while ((n = in.read(buf)) != -1) {
out.write(buf, 0, n);
out.flush();
}
} catch (IOException ignored) {
// Normal when either side closes the connection
}
}
private static void resendCommand(String[] args, OutputStream out) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("*").append(args.length).append("\r\n");
for (String arg : args) {
byte[] bytes = arg.getBytes(StandardCharsets.UTF_8);
sb.append("$").append(bytes.length).append("\r\n");
out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
sb.setLength(0);
out.write(bytes);
out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}
if (sb.length() > 0) {
out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
}
out.flush();
}
}
@@ -4,215 +4,49 @@ import io.github.hectorvent.floci.services.elasticache.model.AuthMode;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/**
* TCP auth proxy for a single ElastiCache replication group.
* Intercepts the Redis AUTH command, validates credentials (IAM or password),
* then becomes a transparent byte relay to the backend Valkey container.
*
* <p>Uses Java virtual threads for non-blocking I/O handling.
* Validates credentials (IAM or password) against the group's configured {@link AuthMode}.
* See {@link AbstractRedisAuthProxy} for the shared AUTH-handling and relay logic.
*/
public class ElastiCacheAuthProxy {
public class ElastiCacheAuthProxy extends AbstractRedisAuthProxy {
private static final Logger LOG = Logger.getLogger(ElastiCacheAuthProxy.class);
private static final byte[] OK_RESPONSE = "+OK\r\n".getBytes(StandardCharsets.UTF_8);
private static final byte[] NOAUTH_RESPONSE =
"-NOAUTH Authentication required.\r\n".getBytes(StandardCharsets.UTF_8);
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[] WRONG_ARGS_RESPONSE =
"-ERR wrong number of arguments for 'auth' command\r\n"
.getBytes(StandardCharsets.UTF_8);
private final String groupId;
private final AuthMode authMode;
private final String backendHost;
private final int backendPort;
private final PasswordValidator passwordValidator;
private final SigV4Validator sigV4Validator;
private volatile boolean running;
private ServerSocket serverSocket;
public ElastiCacheAuthProxy(String groupId, AuthMode authMode,
String backendHost, int backendPort,
PasswordValidator passwordValidator,
SigV4Validator sigV4Validator) {
super(LOG, "ElastiCache", "ec", groupId, backendHost, backendPort);
this.groupId = groupId;
this.authMode = authMode;
this.backendHost = backendHost;
this.backendPort = backendPort;
this.passwordValidator = passwordValidator;
this.sigV4Validator = sigV4Validator;
}
public void start(int proxyPort) throws IOException {
serverSocket = new ServerSocket(proxyPort);
running = true;
Thread.ofVirtual().name("ec-proxy-accept-" + groupId).start(this::acceptLoop);
LOG.infov("ElastiCache proxy started for group {0} on port {1} → {2}:{3}",
groupId, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort));
@Override
protected boolean authRequired() {
return authMode != AuthMode.NO_AUTH;
}
public void stop() {
running = false;
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
LOG.warnv("Error closing proxy server socket for group {0}: {1}", groupId, e.getMessage());
}
}
private void acceptLoop() {
while (running) {
try {
Socket client = serverSocket.accept();
Thread.ofVirtual().name("ec-proxy-conn-" + groupId).start(() -> handleConnection(client));
} catch (IOException e) {
if (running) {
LOG.warnv("Accept error for group {0}: {1}", groupId, e.getMessage());
}
}
}
}
private void handleConnection(Socket client) {
try {
client.setTcpNoDelay(true);
RespReader reader = new RespReader(client.getInputStream());
String[] cmd = reader.readCommand();
if (cmd.length == 0) {
closeQuietly(client);
return;
}
if (cmd[0].equalsIgnoreCase("AUTH")) {
handleAuth(client, cmd);
} else if (authMode != AuthMode.NO_AUTH) {
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);
}
} catch (Exception e) {
LOG.debugv("Connection error for group {0}: {1}", groupId, e.getMessage());
closeQuietly(client);
}
}
private void handleAuth(Socket client, String[] cmd) throws IOException {
String username;
String password;
if (cmd.length == 2) {
// AUTH password
username = null;
password = cmd[1];
} else if (cmd.length == 3) {
// AUTH username password
username = cmd[1];
password = cmd[2];
} else {
client.getOutputStream().write(WRONG_ARGS_RESPONSE);
client.getOutputStream().flush();
closeQuietly(client);
return;
}
boolean authenticated = validate(username, password);
if (!authenticated) {
client.getOutputStream().write(INVALID_AUTH_RESPONSE);
client.getOutputStream().flush();
closeQuietly(client);
return;
}
client.getOutputStream().write(OK_RESPONSE);
client.getOutputStream().flush();
Socket backend = new Socket(backendHost, backendPort);
backend.setTcpNoDelay(true);
bridge(client, backend);
}
private boolean validate(String username, String password) {
@Override
protected boolean authenticate(String username, String password) {
return switch (authMode) {
case IAM -> sigV4Validator.validate(password, groupId, username);
case PASSWORD -> passwordValidator.validatePassword(username, password);
case NO_AUTH -> true;
case NO_AUTH -> true; // unreachable: authRequired() is false for NO_AUTH
};
}
/**
* Relay I/O runs on platform daemon threads (not virtual threads). A parent virtual thread
* from {@code handleConnection} blocks in {@code join} here; scheduling nested virtual-thread
* relays under load can stall delivery of backend responses (e.g. PING/PONG) to the client.
*/
private void bridge(Socket client, Socket backend) {
Thread t1 = Thread.ofPlatform().daemon(true).name("ec-relay-c2b-" + groupId)
.start(() -> relay(client, backend));
Thread t2 = Thread.ofPlatform().daemon(true).name("ec-relay-b2c-" + groupId)
.start(() -> relay(backend, client));
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
closeQuietly(client);
closeQuietly(backend);
}
}
private static void relay(Socket from, Socket to) {
byte[] buf = new byte[8192];
try {
InputStream in = from.getInputStream();
OutputStream out = to.getOutputStream();
int n;
while ((n = in.read(buf)) != -1) {
out.write(buf, 0, n);
out.flush();
}
} catch (IOException ignored) {
// Normal when either side closes the connection
}
}
private static void resendCommand(String[] args, OutputStream out) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("*").append(args.length).append("\r\n");
for (String arg : args) {
byte[] bytes = arg.getBytes(StandardCharsets.UTF_8);
sb.append("$").append(bytes.length).append("\r\n");
out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
sb.setLength(0);
out.write(bytes);
out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}
if (sb.length() > 0) {
out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
}
out.flush();
}
private void closeQuietly(Socket s) {
@Override
protected void closeQuietly(Socket s) {
try {
if (!s.isClosed()) {
try {
@@ -1,217 +1,57 @@
package io.github.hectorvent.floci.services.memorydb.proxy;
import io.github.hectorvent.floci.services.elasticache.proxy.RespReader;
import io.github.hectorvent.floci.services.elasticache.proxy.AbstractRedisAuthProxy;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
/**
* TCP auth proxy for a single MemoryDB cluster.
* Intercepts the Redis AUTH command and delegates credential validation to an
* {@link AuthValidator}, which resolves the supplied user against the cluster's ACL
* (password or IAM). It then becomes a transparent byte relay to the backend Redis
* container.
* Delegates credential validation to an {@link AuthValidator}, which resolves the supplied
* user against the cluster's ACL (password or IAM). See {@link AbstractRedisAuthProxy} for
* the shared AUTH-handling and relay logic, reused here because MemoryDB speaks the same
* Redis wire protocol as ElastiCache.
*
* <p>Whether authentication is required at all is decided up front from the cluster's
* ACL: a cluster bound to {@code open-access} (or any ACL whose users require no
* password) is created with {@code authRequired = false}, in which case the proxy is a
* password) is created with {@code requireAuth = false}, in which case the proxy is a
* straight relay.
*
* <p>MemoryDB speaks the Redis wire protocol, so this reuses ElastiCache's
* {@link RespReader}. A future refactor should lift the shared Redis-auth pieces into a
* common package.
*/
public class MemoryDbAuthProxy {
public class MemoryDbAuthProxy extends AbstractRedisAuthProxy {
private static final Logger LOG = Logger.getLogger(MemoryDbAuthProxy.class);
private static final byte[] OK_RESPONSE = "+OK\r\n".getBytes(StandardCharsets.UTF_8);
private static final byte[] NOAUTH_RESPONSE =
"-NOAUTH Authentication required.\r\n".getBytes(StandardCharsets.UTF_8);
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[] WRONG_ARGS_RESPONSE =
"-ERR wrong number of arguments for 'auth' command\r\n"
.getBytes(StandardCharsets.UTF_8);
private final String clusterName;
private final boolean authRequired;
private final String backendHost;
private final int backendPort;
private final boolean requireAuth;
private final AuthValidator authValidator;
private volatile boolean running;
private ServerSocket serverSocket;
public MemoryDbAuthProxy(String clusterName, boolean authRequired,
String backendHost, int backendPort,
AuthValidator authValidator) {
this.clusterName = clusterName;
this.authRequired = authRequired;
this.backendHost = backendHost;
this.backendPort = backendPort;
super(LOG, "MemoryDB", "memorydb", clusterName, backendHost, backendPort);
this.requireAuth = authRequired;
this.authValidator = authValidator;
}
public void start(int proxyPort) throws IOException {
serverSocket = new ServerSocket(proxyPort);
running = true;
Thread.ofVirtual().name("memorydb-proxy-accept-" + clusterName).start(this::acceptLoop);
LOG.infov("MemoryDB proxy started for cluster {0} on port {1} → {2}:{3}",
clusterName, String.valueOf(proxyPort), backendHost, String.valueOf(backendPort));
@Override
protected boolean authRequired() {
return requireAuth;
}
public void stop() {
running = false;
try {
if (serverSocket != null) {
serverSocket.close();
}
} catch (IOException e) {
LOG.warnv("Error closing proxy server socket for cluster {0}: {1}", clusterName, e.getMessage());
}
}
private void acceptLoop() {
while (running) {
try {
Socket client = serverSocket.accept();
Thread.ofVirtual().name("memorydb-proxy-conn-" + clusterName).start(() -> handleConnection(client));
} catch (IOException e) {
if (running) {
LOG.warnv("Accept error for cluster {0}: {1}", clusterName, e.getMessage());
}
}
}
}
private void handleConnection(Socket client) {
try {
client.setTcpNoDelay(true);
RespReader reader = new RespReader(client.getInputStream());
String[] cmd = reader.readCommand();
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 {
Socket backend = new Socket(backendHost, backendPort);
backend.setTcpNoDelay(true);
resendCommand(cmd, backend.getOutputStream());
bridge(client, backend);
}
} catch (Exception e) {
LOG.debugv("Connection error for cluster {0}: {1}", clusterName, e.getMessage());
closeQuietly(client);
}
}
private void handleAuth(Socket client, String[] cmd) throws IOException {
String username;
String password;
if (cmd.length == 2) {
username = null;
password = cmd[1];
} else if (cmd.length == 3) {
username = cmd[1];
password = cmd[2];
} else {
client.getOutputStream().write(WRONG_ARGS_RESPONSE);
client.getOutputStream().flush();
closeQuietly(client);
return;
}
boolean authenticated = validate(username, password);
if (!authenticated) {
client.getOutputStream().write(INVALID_AUTH_RESPONSE);
client.getOutputStream().flush();
closeQuietly(client);
return;
}
client.getOutputStream().write(OK_RESPONSE);
client.getOutputStream().flush();
Socket backend = new Socket(backendHost, backendPort);
backend.setTcpNoDelay(true);
bridge(client, backend);
}
private boolean validate(String username, String password) {
if (!authRequired) {
return true;
}
@Override
protected boolean authenticate(String username, String password) {
return authValidator.authenticate(username, password);
}
private void bridge(Socket client, Socket backend) {
Thread t1 = Thread.ofPlatform().daemon(true).name("memorydb-relay-c2b-" + clusterName)
.start(() -> relay(client, backend));
Thread t2 = Thread.ofPlatform().daemon(true).name("memorydb-relay-b2c-" + clusterName)
.start(() -> relay(backend, client));
@Override
protected void closeQuietly(Socket s) {
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
closeQuietly(client);
closeQuietly(backend);
}
}
private static void relay(Socket from, Socket to) {
byte[] buf = new byte[8192];
try {
InputStream in = from.getInputStream();
OutputStream out = to.getOutputStream();
int n;
while ((n = in.read(buf)) != -1) {
out.write(buf, 0, n);
out.flush();
}
s.close();
} catch (IOException ignored) {
// Normal when either side closes the connection
// Normal when the peer has already closed the connection
}
}
private static void resendCommand(String[] args, OutputStream out) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("*").append(args.length).append("\r\n");
for (String arg : args) {
byte[] bytes = arg.getBytes(StandardCharsets.UTF_8);
sb.append("$").append(bytes.length).append("\r\n");
out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
sb.setLength(0);
out.write(bytes);
out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}
if (sb.length() > 0) {
out.write(sb.toString().getBytes(StandardCharsets.UTF_8));
}
out.flush();
}
private static void closeQuietly(Socket s) {
try { s.close(); } catch (IOException ignored) {}
}
/**
* Callback interface for credential validation, provided by MemoryDbService.
* Resolves the supplied {@code username}/{@code secret} against the cluster's ACL,