feat(redshift): wire the Simple Query DDL interceptor into the proxy (#3029)

* feat(redshift): add PostgresWireDecoder for frontend wire-message framing

* feat(redshift): intercept Simple Query DDL through RedshiftInterceptingBridge

* test(redshift): end-to-end DDL rewrite over the Simple Query protocol

* docs(redshift): document the Simple Query DDL interceptor

* fix(redshift): remove em-dashes and address review feedback on bridge

* fix(redshift): stream opaque non-query frames without size limit

* fix(redshift): stream oversized simple query frames to passthrough

* test(redshift): import stream types in RedshiftInterceptingBridgeTest

* test(rdsdata): fallback to direct H2 driver on classloader mismatch

* test(redshift): remove oversized socket test from RedshiftInterceptingBridgeTest
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-05 10:36:34 -04:00
1 parent 5512db0e05
commit 4daba7ed6a
8 files changed
+916 -5

No files matched your search

@@ -17,8 +17,10 @@ import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.time.Duration;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import org.h2.Driver;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -33,6 +35,10 @@ import static org.mockito.Mockito.when;
class RdsDataServiceTest {
static {
Driver.load();
}
private static final String RESOURCE_ARN = "arn:aws:rds:us-east-1:000000000000:cluster:test";
private static final String FALLBACK_RESOURCE_ARN = "arn:aws:rds:us-west-2:111111111111:cluster:test";
private static final String OTHER_RESOURCE_ARN = "arn:aws:rds:us-east-1:000000000000:cluster:other";
@@ -864,14 +870,29 @@ class RdsDataServiceTest {
String username,
String password,
String database) throws SQLException {
return DriverManager.getConnection(jdbcUrl, "sa", "");
return getConnection();
}
};
service = new RdsDataService(resolver, secrets, objectMapper, connectionFactory, transactionTtl);
}
private Connection getConnection() throws SQLException {
try {
return DriverManager.getConnection(jdbcUrl, "sa", "");
} catch (SQLException e) {
Properties props = new Properties();
props.setProperty("user", "sa");
props.setProperty("password", "");
Connection conn = new Driver().connect(jdbcUrl, props);
if (conn != null) {
return conn;
}
throw e;
}
}
private void createTables() throws SQLException {
try (Connection connection = DriverManager.getConnection(jdbcUrl, "sa", "");
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
statement.execute("""
create table data_api_items(
@@ -897,7 +918,7 @@ class RdsDataServiceTest {
* harnesses standing in for PostgreSQL.
*/
private void createEventsTable() throws SQLException {
try (Connection connection = DriverManager.getConnection(jdbcUrl, "sa", "");
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
statement.execute("""
create table data_api_events(
@@ -0,0 +1,109 @@
package io.github.hectorvent.floci.services.redshift;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.awaitility.Awaitility;
import org.awaitility.core.ConditionTimeoutException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.Objects;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class RedshiftInterceptorIntegrationTest {
@Inject
RedshiftService service;
private String clusterId;
@BeforeAll
static void requireDocker() {
Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available for Redshift interceptor integration tests");
}
private static boolean isDockerAvailable() {
try {
Process process = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
.redirectErrorStream(true)
.start();
int exit = process.waitFor();
return exit == 0;
} catch (Exception e) {
return false;
}
}
@AfterEach
void cleanUp() {
if (clusterId != null) {
service.deleteCluster(clusterId);
}
}
private static String jdbcUrl(Cluster c) {
// Use 127.0.0.1 explicitly instead of c.getEndpoint().getAddress() to avoid UnknownHostException
// in CI environments where floci.emulator.hostname is set to host.docker.internal.
// preferQueryMode=simple forces pgjdbc to use the simple query protocol ('Q' messages)
// rather than extended query protocol ('P'/'B'/'E'/'S' messages).
return "jdbc:postgresql://127.0.0.1:" + c.getEndpoint().getPort() + "/dev?preferQueryMode=simple";
}
private static Connection waitForConnection(Cluster cluster, String username, String password) throws SQLException {
try {
return Awaitility.await()
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofMillis(500))
.ignoreExceptions()
.until(() -> DriverManager.getConnection(jdbcUrl(cluster), username, password), Objects::nonNull);
} catch (ConditionTimeoutException e) {
return DriverManager.getConnection(jdbcUrl(cluster), username, password); // throw original
}
}
@Test
void rewritesCreateTableDdlOverSimpleQueryProtocol() throws SQLException {
clusterId = "it-interceptor-create";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
try (Connection conn = waitForConnection(cluster, "admin", "Secret123");
Statement st = conn.createStatement()) {
st.execute("CREATE TABLE sales (id int ENCODE az64, d date) DISTSTYLE KEY DISTKEY (id) COMPOUND SORTKEY (d);");
st.execute("INSERT INTO sales VALUES (1, '2026-01-01');");
try (ResultSet rs = st.executeQuery("SELECT count(*) FROM sales")) {
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
}
}
}
@Test
void rewritesAlterTableDdlOverSimpleQueryProtocol() throws SQLException {
clusterId = "it-interceptor-alter";
Cluster cluster = service.createCluster(clusterId, "dc2.large", "admin", "Secret123");
try (Connection conn = waitForConnection(cluster, "admin", "Secret123");
Statement st = conn.createStatement()) {
st.execute("CREATE TABLE t (id int)");
st.execute("ALTER TABLE t ADD COLUMN note varchar(20) ENCODE lzo;");
st.execute("INSERT INTO t VALUES (1, 'test-note');");
try (ResultSet rs = st.executeQuery("SELECT id, note FROM t WHERE id = 1")) {
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertEquals("test-note", rs.getString(2));
}
}
}
}
@@ -0,0 +1,311 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PostgresWireDecoderTest {
@Test
void decodesASimpleQueryAndThenReportsEof() throws IOException {
byte[] packet = PostgresWireDecoder.encodeQuery("SELECT 1");
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(packet));
PostgresWireDecoder.FrontendMessage msg = decoder.nextMessage();
assertNotNull(msg);
assertEquals('Q', msg.type());
assertTrue(msg.isQuery());
assertEquals("SELECT 1", msg.getSql());
assertArrayEquals(packet, msg.toPacketBytes());
assertNull(decoder.nextMessage());
}
@Test
void decodesNonQueryMessagesWithoutInterpretingThem() throws IOException {
byte[] terminate = new byte[]{'X', 0, 0, 0, 4};
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(terminate));
PostgresWireDecoder.FrontendMessage msg = decoder.nextMessage();
assertNotNull(msg);
assertEquals('X', msg.type());
assertFalse(msg.isQuery());
assertNull(msg.getSql());
assertEquals(0, msg.body().length);
assertArrayEquals(terminate, msg.toPacketBytes());
assertNull(decoder.nextMessage());
byte[] parsePayload = "stmt1\0SELECT $1\0\0\0".getBytes(StandardCharsets.UTF_8);
int length = 4 + parsePayload.length;
byte[] parsePacket = new byte[1 + length];
parsePacket[0] = 'P';
parsePacket[1] = (byte) ((length >> 24) & 0xFF);
parsePacket[2] = (byte) ((length >> 16) & 0xFF);
parsePacket[3] = (byte) ((length >> 8) & 0xFF);
parsePacket[4] = (byte) (length & 0xFF);
System.arraycopy(parsePayload, 0, parsePacket, 5, parsePayload.length);
PostgresWireDecoder.FrontendMessage parse =
new PostgresWireDecoder(new ByteArrayInputStream(parsePacket)).nextMessage();
assertNotNull(parse);
assertEquals('P', parse.type());
assertFalse(parse.isQuery());
assertArrayEquals(parsePayload, parse.body());
assertArrayEquals(parsePacket, parse.toPacketBytes());
}
@Test
void decodesSeveralMessagesFromOneStream() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(PostgresWireDecoder.encodeQuery("SELECT 1"));
out.write(PostgresWireDecoder.encodeQuery("SELECT 2"));
out.write(new byte[]{'X', 0, 0, 0, 4});
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(out.toByteArray()));
assertEquals("SELECT 1", decoder.nextMessage().getSql());
assertEquals("SELECT 2", decoder.nextMessage().getSql());
assertEquals('X', decoder.nextMessage().type());
assertNull(decoder.nextMessage());
}
@Test
void reassemblesAMessageDeliveredTwoBytesAtATime() throws IOException {
byte[] packet = PostgresWireDecoder.encodeQuery("SELECT * FROM users WHERE active = true");
InputStream drip = new InputStream() {
private int i = 0;
@Override public int read() {
if (i >= packet.length) {
return -1;
}
return packet[i++] & 0xFF;
}
@Override public int read(byte[] b, int off, int len) {
if (i >= packet.length) {
return -1;
}
int n = Math.min(Math.min(len, 2), packet.length - i);
System.arraycopy(packet, i, b, off, n);
i += n;
return n;
}
};
PostgresWireDecoder.FrontendMessage msg = new PostgresWireDecoder(drip).nextMessage();
assertEquals("SELECT * FROM users WHERE active = true", msg.getSql());
assertArrayEquals(packet, msg.toPacketBytes());
}
@Test
void returnsNullOnAnEmptyStream() throws IOException {
assertNull(new PostgresWireDecoder(new ByteArrayInputStream(new byte[0])).nextMessage());
}
@Test
void throwsEofWhenTheLengthFieldIsTruncated() {
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(new byte[]{'Q', 0, 0}));
assertThrows(EOFException.class, decoder::nextMessage);
}
@Test
void throwsEofWhenTheBodyIsTruncated() {
PostgresWireDecoder decoder =
new PostgresWireDecoder(new ByteArrayInputStream(new byte[]{'Q', 0, 0, 0, 10, 'S', 'E'}));
assertThrows(EOFException.class, decoder::nextMessage);
}
@Test
void rejectsALengthBelowFour() {
PostgresWireDecoder decoder =
new PostgresWireDecoder(new ByteArrayInputStream(new byte[]{'Q', 0, 0, 0, 2}));
assertThrows(IOException.class, decoder::nextMessage);
}
@Test
void refusesAnOversizedDeclaredLengthBeforeReadingTheBody() {
byte[] hostile = new byte[]{'Q', 0x7F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(hostile));
IOException ex = assertThrows(IOException.class, decoder::nextMessage);
assertTrue(ex.getMessage().contains("Refusing"), ex.getMessage());
}
@Test
void encodeQueryProducesAWellFormedQPacket() {
byte[] encoded = PostgresWireDecoder.encodeQuery("SHOW search_path");
assertEquals('Q', (char) encoded[0]);
int length = ((encoded[1] & 0xFF) << 24) | ((encoded[2] & 0xFF) << 16)
| ((encoded[3] & 0xFF) << 8) | (encoded[4] & 0xFF);
assertEquals(21, length); // 4 + 16 chars + 1 NUL
assertEquals(0x00, encoded[encoded.length - 1]);
}
@Test
void isBetweenMessagesIsTrueAtBoundariesAndFalseMidMessage() throws IOException {
byte[] two = new ByteArrayOutputStream() {{
try {
write(PostgresWireDecoder.encodeQuery("SELECT 1"));
write(new byte[]{'Q', 0, 0, 0, 50}); // header promises 46 body bytes that never arrive
} catch (IOException e) {
throw new RuntimeException(e);
}
}}.toByteArray();
PostgresWireDecoder decoder = new PostgresWireDecoder(new ByteArrayInputStream(two));
assertTrue(decoder.isBetweenMessages());
assertNotNull(decoder.nextMessage());
assertTrue(decoder.isBetweenMessages());
assertThrows(EOFException.class, decoder::nextMessage);
assertFalse(decoder.isBetweenMessages()); // type byte was consumed before the stream ran dry
}
@Test
void streamsOpaqueMessageLargerThanQueryLimitDirectlyToPassthroughOut() throws IOException {
int payloadSize = 17 * 1024 * 1024; // 17 MiB, exceeds MAX_MESSAGE_BYTES
int totalLength = 4 + payloadSize;
byte[] header = new byte[]{
'd', // CopyData
(byte) ((totalLength >> 24) & 0xFF),
(byte) ((totalLength >> 16) & 0xFF),
(byte) ((totalLength >> 8) & 0xFF),
(byte) (totalLength & 0xFF)
};
InputStream in = new InputStream() {
private int headerPos = 0;
private int bodyRemaining = payloadSize;
@Override
public int read() {
if (headerPos < header.length) {
return header[headerPos++] & 0xFF;
}
if (bodyRemaining > 0) {
bodyRemaining--;
return 'A';
}
return -1;
}
@Override
public int read(byte[] b, int off, int len) {
if (headerPos < header.length) {
int toCopy = Math.min(len, header.length - headerPos);
System.arraycopy(header, headerPos, b, off, toCopy);
headerPos += toCopy;
return toCopy;
}
if (bodyRemaining > 0) {
int toProvide = Math.min(len, bodyRemaining);
for (int i = 0; i < toProvide; i++) {
b[off + i] = 'A';
}
bodyRemaining -= toProvide;
return toProvide;
}
return -1;
}
};
long[] bytesWritten = new long[1];
OutputStream out = new OutputStream() {
@Override
public void write(int b) {
bytesWritten[0]++;
}
@Override
public void write(byte[] b, int off, int len) {
bytesWritten[0] += len;
}
};
PostgresWireDecoder decoder = new PostgresWireDecoder(in);
PostgresWireDecoder.FrontendMessage msg = decoder.nextMessage(out);
assertNotNull(msg);
assertEquals('d', msg.type());
assertNull(msg.body());
assertEquals(1 + (long) totalLength, bytesWritten[0]);
}
@Test
void streamsSimpleQueryLargerThanLimitDirectlyToPassthroughOut() throws IOException {
int payloadSize = 17 * 1024 * 1024; // 17 MiB, exceeds MAX_MESSAGE_BYTES
int totalLength = 4 + payloadSize;
byte[] header = new byte[]{
'Q',
(byte) ((totalLength >> 24) & 0xFF),
(byte) ((totalLength >> 16) & 0xFF),
(byte) ((totalLength >> 8) & 0xFF),
(byte) (totalLength & 0xFF)
};
InputStream in = new InputStream() {
private int headerPos = 0;
private int bodyRemaining = payloadSize;
@Override
public int read() {
if (headerPos < header.length) {
return header[headerPos++] & 0xFF;
}
if (bodyRemaining > 0) {
bodyRemaining--;
return 'A';
}
return -1;
}
@Override
public int read(byte[] b, int off, int len) {
if (headerPos < header.length) {
int toCopy = Math.min(len, header.length - headerPos);
System.arraycopy(header, headerPos, b, off, toCopy);
headerPos += toCopy;
return toCopy;
}
if (bodyRemaining > 0) {
int toProvide = Math.min(len, bodyRemaining);
for (int i = 0; i < toProvide; i++) {
b[off + i] = 'A';
}
bodyRemaining -= toProvide;
return toProvide;
}
return -1;
}
};
long[] bytesWritten = new long[1];
OutputStream out = new OutputStream() {
@Override
public void write(int b) {
bytesWritten[0]++;
}
@Override
public void write(byte[] b, int off, int len) {
bytesWritten[0] += len;
}
};
PostgresWireDecoder decoder = new PostgresWireDecoder(in);
PostgresWireDecoder.FrontendMessage msg = decoder.nextMessage(out);
assertNotNull(msg);
assertEquals('Q', msg.type());
assertFalse(msg.isQuery());
assertNull(msg.body());
assertEquals(1 + (long) totalLength, bytesWritten[0]);
}
}
@@ -0,0 +1,141 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RedshiftInterceptingBridgeTest {
private static final Logger LOG = Logger.getLogger(RedshiftInterceptingBridgeTest.class);
private ServerSocket clientListener;
private ServerSocket backendListener;
private Socket testClientEnd; // test writes client bytes here, reads pump output here
private Socket bridgeClientEnd; // the bridge's "client" socket
private Socket bridgeBackendEnd; // the bridge's "backend" socket
private Socket testBackendEnd; // test reads what the bridge forwarded, writes backend replies
private Thread bridgeThread;
private void startBridge() throws IOException {
clientListener = new ServerSocket(0);
testClientEnd = new Socket("localhost", clientListener.getLocalPort());
bridgeClientEnd = clientListener.accept();
backendListener = new ServerSocket(0);
bridgeBackendEnd = new Socket("localhost", backendListener.getLocalPort());
testBackendEnd = backendListener.accept();
RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge(bridgeClientEnd, bridgeBackendEnd);
bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run);
}
@AfterEach
void tearDown() {
for (Socket s : new Socket[]{testClientEnd, bridgeClientEnd, bridgeBackendEnd, testBackendEnd}) {
if (s != null && !s.isClosed()) {
try {
s.close();
} catch (IOException e) {
LOG.debugv(e, "Error closing socket during test cleanup");
}
}
}
for (ServerSocket ss : new ServerSocket[]{clientListener, backendListener}) {
if (ss != null && !ss.isClosed()) {
try {
ss.close();
} catch (IOException e) {
LOG.debugv(e, "Error closing server socket during test cleanup");
}
}
}
}
private PostgresWireDecoder.FrontendMessage nextForwarded() throws IOException {
return new PostgresWireDecoder(testBackendEnd.getInputStream()).nextMessage();
}
@Test
void rewritesRedshiftCreateTableBeforeForwarding() throws IOException {
startBridge();
String ddl = "CREATE TABLE sales (id int ENCODE az64, d date) "
+ "DISTSTYLE KEY DISTKEY (id) COMPOUND SORTKEY (d);";
testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeQuery(ddl));
testClientEnd.getOutputStream().flush();
PostgresWireDecoder.FrontendMessage forwarded = nextForwarded();
assertNotNull(forwarded);
assertEquals('Q', forwarded.type());
String sent = forwarded.getSql().toUpperCase();
assertFalse(sent.contains("DISTKEY"), sent);
assertFalse(sent.contains("SORTKEY"), sent);
assertFalse(sent.contains("DISTSTYLE"), sent);
assertFalse(sent.contains("ENCODE"), sent);
assertTrue(forwarded.getSql().contains("CREATE TABLE sales"), forwarded.getSql());
}
@Test
void forwardsANonDdlQueryByteForByte() throws IOException {
startBridge();
byte[] packet = PostgresWireDecoder.encodeQuery("SELECT 'DISTKEY' AS not_a_keyword");
testClientEnd.getOutputStream().write(packet);
testClientEnd.getOutputStream().flush();
assertArrayEquals(packet, nextForwarded().toPacketBytes());
}
@Test
void forwardsAnExtendedProtocolMessageOpaque() throws IOException {
startBridge();
byte[] parsePayload = "s1\0SELECT $1\0\0\0".getBytes(StandardCharsets.UTF_8);
int length = 4 + parsePayload.length;
byte[] parsePacket = new byte[1 + length];
parsePacket[0] = 'P';
parsePacket[1] = (byte) ((length >> 24) & 0xFF);
parsePacket[2] = (byte) ((length >> 16) & 0xFF);
parsePacket[3] = (byte) ((length >> 8) & 0xFF);
parsePacket[4] = (byte) (length & 0xFF);
System.arraycopy(parsePayload, 0, parsePacket, 5, parsePayload.length);
testClientEnd.getOutputStream().write(parsePacket);
testClientEnd.getOutputStream().flush();
assertArrayEquals(parsePacket, nextForwarded().toPacketBytes());
}
@Test
void pumpsBackendBytesToTheClientUnchanged() throws IOException {
startBridge();
byte[] readyForQuery = new byte[]{'Z', 0, 0, 0, 5, 'I'};
testBackendEnd.getOutputStream().write(readyForQuery);
testBackendEnd.getOutputStream().flush();
byte[] got = testClientEnd.getInputStream().readNBytes(readyForQuery.length);
assertArrayEquals(readyForQuery, got);
}
@Test
void terminateMessageIsForwardedAndEndsTheSession() throws Exception {
startBridge();
testClientEnd.getOutputStream().write(new byte[]{'X', 0, 0, 0, 4});
testClientEnd.getOutputStream().flush();
PostgresWireDecoder.FrontendMessage forwarded = nextForwarded();
assertEquals('X', forwarded.type());
bridgeThread.join(5_000);
assertFalse(bridgeThread.isAlive(), "bridge did not stop after Terminate");
assertEquals(-1, testClientEnd.getInputStream().read(), "bridge left the client socket open");
}
}