feat(dsql): serve each cluster's database on the DSQL endpoint (#6102)

* feat(dsql): serve each cluster's database on the DSQL endpoint

Each Aurora DSQL cluster gets a PostgreSQL 16 database in a Docker container,
set up as DSQL's (the role admin owning public, repeatable read), and every
cluster is served on one TLS endpoint where the server name picks the cluster.
A connection is admitted as DSQL admits it, measured on AWS: an IAM token for
the endpoint, DbConnectAdmin for admin, 5 seconds of grace past expiry, a
long-term key only in its own account, IAM enforcement with the account's SCPs,
and DSQL's SQLSTATE, text and hint for every refusal. A role other than admin
is refused as an unmapped one, since role mappings come with AWS IAM GRANT in
the next part. The startup is read as DSQL reads it: a dotted parameter is
refused, and of options only -c name=value counts, the first for a name.

The cluster is CREATING until its database answers; a multi-Region peer is
ACTIVE after peering only once its database answers. A start that fails after
the container exists removes it, a deletion Docker cannot finish leaves the
cluster DELETING for the next start, and whether a cluster is wanted and its
route change under one lock, so a deletion racing a start leaves no route.

The data plane was first one PR; it is split by layer at the maintainer's
request: this part (transport and admin), then AWS IAM GRANT and the other
roles, then DSQL's dialect and limits.

* refactor(postgres): speak PostgreSQL's wire protocol through one shared helper

The DSQL endpoint brought a third copy of the startup parsing, message framing
and ErrorResponse building that the RDS proxy's PostgresProtocolHandler and
Redshift's PostgresWireDecoder each carried. They now go through
core.common.PostgresWire: the startup packet and its parameters, reading and
writing a message with its checked length, and the fields of an ErrorResponse
or NoticeResponse. The length refusals keep the RDS proxy's wording, which its
tests assert; Redshift's oversized-message refusal now reads the same way.

Also from the review: the DSQL integration test makes its IAM users with
EnforcementFixtures.createUser, which removes them after the test; the service
test shares one ready-at-once provision stub; and every exception the endpoint
and session swallow is named ignored, with the reason it is safe.
This commit is contained in:
Alessandro Lattao authored and GitHub committed 2026-10-21 08:54:07 -04:00
1 parent d2ee9f46a0
commit f2b62fbbec
28 files changed
+2172 -324

No files matched your search

@@ -1776,13 +1776,32 @@ public interface EmulatorConfig {
@WithDefault("true")
boolean enabled();
/** When true, clusters have no database and are ACTIVE at once, without Docker. */
@WithDefault("false")
boolean mock();
/**
* Port every cluster endpoint is served on, as on AWS, where a DSQL endpoint is always
* reached on 5432. Clients connect to {@code <id>.dsql.<region>.<endpoint-suffix>} with TLS,
* and the server name they send picks the cluster.
*/
@WithDefault("5432")
int port();
/**
* Domain under which cluster endpoints are named, {@code <id>.dsql.<region>.<suffix>}. The
* default resolves to the loopback address on the host and to Floci inside its Docker
* network.
* network, so an endpoint works unchanged in both.
*/
@WithDefault("localhost.floci.io")
String endpointSuffix();
/** PostgreSQL image each cluster's database runs in. DSQL is PostgreSQL 16 compatible. */
@WithDefault("postgres:16-alpine")
String image();
/** Docker network for the database containers. Defaults to Floci's own network. */
Optional<String> dockerNetwork();
}
interface RdsDataServiceConfig {
@@ -0,0 +1,215 @@
package io.github.hectorvent.floci.core.common;
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 java.util.LinkedHashMap;
import java.util.Map;
/**
* PostgreSQL's frontend/backend protocol, version 3, as every PostgreSQL endpoint in Floci reads
* and writes it (the RDS proxy, Redshift's bridge, Aurora DSQL's endpoint): a message's framing,
* the startup packet and its parameters, and the fields of an ErrorResponse or NoticeResponse.
*/
public final class PostgresWire {
public static final int PROTOCOL_3 = 196608;
public static final int SSL_REQUEST = 80877103;
public static final int GSSENC_REQUEST = 80877104;
public static final int CANCEL_REQUEST = 80877102;
private PostgresWire() {
}
/** A message after the startup: its type byte and its body, without the length. */
public record Message(byte type, byte[] body) {
}
/** A startup-phase packet, which has no type byte: its code and the rest of its body. */
public record Startup(int code, byte[] body) {
}
/** The NUL-terminated string at an offset, and where the next field starts. */
public record CString(String value, int next) {
}
// ── Framing ───────────────────────────────────────────────────────────────
/** Reads a startup-phase packet: its length, refused outside 8 to {@code maxLength}, code and body. */
public static Startup readStartup(InputStream in, int maxLength, String packetName) throws IOException {
int length = checkedLength(readInt32(in), 8, maxLength, packetName);
int code = readInt32(in);
byte[] body = new byte[length - 8];
readFully(in, body);
return new Startup(code, body);
}
/** Reads one message, or throws {@link EOFException} at the end of the stream. */
public static Message read(InputStream in, int maxLength, String packetName) throws IOException {
int type = in.read();
if (type < 0) {
throw new EOFException("Connection closed before a " + packetName);
}
return new Message((byte) type, readBody(in, 4, maxLength, packetName));
}
/** The body of a message whose type byte was read already: its length, checked, then the rest. */
public static byte[] readBody(InputStream in, int minLength, int maxLength, String packetName) throws IOException {
byte[] body = new byte[checkedLength(readInt32(in), minLength, maxLength, packetName) - 4];
readFully(in, body);
return body;
}
/** Writes a message of {@code type} whose body is {@code parts} one after the other. */
public static void write(OutputStream out, int type, byte[]... parts) throws IOException {
int length = 4;
for (byte[] part : parts) {
length += part.length;
}
out.write(type);
writeInt32(out, length);
for (byte[] part : parts) {
out.write(part);
}
}
public static void write(OutputStream out, Message message) throws IOException {
write(out, message.type(), message.body());
}
/** A whole message, its type, length and body, as bytes. */
public static byte[] frame(int type, byte[] body) {
ByteArrayOutputStream out = new ByteArrayOutputStream(body.length + 5);
out.write(type);
out.writeBytes(int32(body.length + 4));
out.writeBytes(body);
return out.toByteArray();
}
/** {@code length}, refused when below {@code minimum} or above {@code maximum}. */
public static int checkedLength(int length, int minimum, int maximum, String packetName) throws IOException {
if (length < minimum) {
throw new IOException("PostgreSQL " + packetName + " length is below the "
+ minimum + " byte minimum: " + length);
}
if (length > maximum) {
throw new IOException("PostgreSQL " + packetName + " length exceeds the "
+ maximum + " byte limit: " + length);
}
return length;
}
public static int readInt32(InputStream in) throws IOException {
int b0 = in.read();
int b1 = in.read();
int b2 = in.read();
int b3 = in.read();
if ((b0 | b1 | b2 | b3) < 0) {
throw new EOFException("Connection closed while reading Int32");
}
return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
}
public static void readFully(InputStream in, byte[] buffer) throws IOException {
int offset = 0;
while (offset < buffer.length) {
int read = in.read(buffer, offset, buffer.length - offset);
if (read < 0) {
throw new EOFException("Connection closed while reading " + buffer.length + " bytes");
}
offset += read;
}
}
public static void writeInt32(OutputStream out, int value) throws IOException {
out.write(int32(value));
}
public static byte[] int32(int value) {
return new byte[]{(byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value};
}
public static int int32(byte[] bytes, int offset) {
return ((bytes[offset] & 0xFF) << 24) | ((bytes[offset + 1] & 0xFF) << 16)
| ((bytes[offset + 2] & 0xFF) << 8) | (bytes[offset + 3] & 0xFF);
}
// ── Strings ───────────────────────────────────────────────────────────────
public static CString cString(byte[] body, int offset) {
int end = offset;
while (end < body.length && body[end] != 0) {
end++;
}
return new CString(new String(body, offset, end - offset, StandardCharsets.UTF_8), end + 1);
}
public static byte[] cStringBytes(String value) {
byte[] text = value.getBytes(StandardCharsets.UTF_8);
byte[] bytes = new byte[text.length + 1];
System.arraycopy(text, 0, bytes, 0, text.length);
return bytes;
}
// ── Startup ───────────────────────────────────────────────────────────────
/** The {@code name=value} pairs of a StartupMessage body, in the order the client sent them. */
public static Map<String, String> startupParameters(byte[] body) {
Map<String, String> parameters = new LinkedHashMap<>();
int offset = 0;
while (offset < body.length) {
CString name = cString(body, offset);
if (name.value().isEmpty() || name.next() > body.length) {
break;
}
CString value = cString(body, name.next());
parameters.put(name.value(), value.value());
offset = value.next();
}
return parameters;
}
/** A whole StartupMessage for protocol 3 carrying {@code parameters} in their order. */
public static byte[] startupMessage(Map<String, String> parameters) {
ByteArrayOutputStream body = new ByteArrayOutputStream();
body.writeBytes(int32(PROTOCOL_3));
parameters.forEach((name, value) -> {
body.writeBytes(cStringBytes(name));
body.writeBytes(cStringBytes(value));
});
body.write(0);
ByteArrayOutputStream packet = new ByteArrayOutputStream(body.size() + 4);
packet.writeBytes(int32(body.size() + 4));
packet.writeBytes(body.toByteArray());
return packet.toByteArray();
}
// ── ErrorResponse and NoticeResponse ──────────────────────────────────────
/** The body of an ErrorResponse ({@code E}) or NoticeResponse ({@code N}) from its fields, in order. */
public static byte[] fields(Map<Character, String> fields) {
ByteArrayOutputStream body = new ByteArrayOutputStream();
fields.forEach((code, value) -> {
body.write(code);
body.writeBytes(cStringBytes(value));
});
body.write(0);
return body.toByteArray();
}
/** The fields of an ErrorResponse or NoticeResponse whose first field starts at {@code offset}. */
public static Map<Character, String> parseFields(byte[] bytes, int offset) {
Map<Character, String> fields = new LinkedHashMap<>();
int i = offset;
while (i < bytes.length && bytes[i] != 0) {
char code = (char) bytes[i];
CString value = cString(bytes, i + 1);
fields.put(code, value.value());
i = value.next();
}
return fields;
}
}
@@ -9,6 +9,7 @@ import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@@ -88,6 +89,21 @@ public final class SigV4RequestValidator {
public boolean validate(String rawQuery, String canonicalHostHeaderValue, String identityParamName,
boolean identityRequired, String expectedIdentityValue, String logLabel,
String ownerAccountId) {
return validate(rawQuery, canonicalHostHeaderValue, "connect", identityParamName, identityRequired,
expectedIdentityValue, logLabel, ownerAccountId, Duration.ZERO);
}
/**
* As above, for a token whose {@code Action} is not {@code connect} and whose service accepts
* it for a while after it expires: Aurora DSQL signs {@code DbConnect} and
* {@code DbConnectAdmin}, and takes a token up to 5 seconds past its expiry.
*
* @param expectedAction the {@code Action} the token must carry
* @param expiryGrace how long after its expiry the token is still accepted
*/
public boolean validate(String rawQuery, String canonicalHostHeaderValue, String expectedAction,
String identityParamName, boolean identityRequired, String expectedIdentityValue,
String logLabel, String ownerAccountId, Duration expiryGrace) {
try {
List<QueryParameter> parameters = decodeQuery(rawQuery);
String action = findParam(parameters, "Action");
@@ -98,7 +114,7 @@ public final class SigV4RequestValidator {
String signedHeaders = findParam(parameters, "X-Amz-SignedHeaders");
String signature = findParam(parameters, "X-Amz-Signature");
if (!"connect".equals(action) || (identityRequired && identity == null) || dateTime == null
if (!expectedAction.equals(action) || (identityRequired && identity == null) || dateTime == null
|| expires == null || credential == null || signedHeaders == null || signature == null) {
LOG.debugv("{0} missing required SigV4 parameters", logLabel);
return false;
@@ -112,7 +128,7 @@ public final class SigV4RequestValidator {
Instant tokenTime = Instant.from(DATETIME_FMT.parse(dateTime));
int expirySeconds = Integer.parseInt(expires);
if (Instant.now().isAfter(tokenTime.plusSeconds(expirySeconds))) {
if (Instant.now().minus(expiryGrace).isAfter(tokenTime.plusSeconds(expirySeconds))) {
LOG.debugv("{0} expired", logLabel);
return false;
}
@@ -1,24 +1,132 @@
package io.github.hectorvent.floci.services.dsql;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.dsql.dataplane.DsqlDatabases;
import io.github.hectorvent.floci.services.dsql.dataplane.DsqlEndpoint;
import io.github.hectorvent.floci.services.dsql.model.DsqlCluster;
import io.quarkus.runtime.ShutdownEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
/**
* The databases behind the clusters. A cluster has none here: it is ready as soon as it is
* created, and its endpoint is named but not served.
* Runs each cluster's database and serves it on the DSQL endpoint. A cluster's database starts in
* the background, and the cluster becomes ACTIVE once it answers, as on AWS. With
* {@code floci.services.dsql.mock} on, a cluster has none and is ready at once, which is enough
* for the control plane and CloudFormation.
*/
@ApplicationScoped
public class DsqlDataPlane {
/** Starts the cluster's database, then reports whether it is ready to serve. */
public void provision(DsqlCluster cluster, Consumer<Boolean> onReady) {
onReady.accept(true);
private static final Logger LOG = Logger.getLogger(DsqlDataPlane.class);
private final boolean mock;
private final boolean memoryStorage;
private final DsqlDatabases databases;
private final DsqlEndpoint endpoint;
private final Map<String, DsqlCluster> running = new ConcurrentHashMap<>();
private final Set<String> wanted = ConcurrentHashMap.newKeySet();
// Whether a cluster is still wanted and its route are changed together, so a deletion during a
// start never leaves the route of a database already gone.
private final Object routes = new Object();
@Inject
public DsqlDataPlane(EmulatorConfig config, DsqlDatabases databases, DsqlEndpoint endpoint) {
this.mock = config.services().dsql().mock();
this.memoryStorage = "memory".equals(config.storage().mode());
this.databases = databases;
this.endpoint = endpoint;
}
/** Stops the cluster's database and drops its data, then runs {@code onGone}. */
/** Starts the cluster's database, then reports whether it is ready to serve. */
public void provision(DsqlCluster cluster, Consumer<Boolean> onReady) {
if (mock) {
onReady.accept(true);
return;
}
String arn = cluster.getArn();
wanted.add(arn);
Thread.ofVirtual().name("dsql-start-" + cluster.getIdentifier()).start(() -> {
DsqlDatabases.Backend backend;
try {
backend = databases.start(cluster);
} catch (Exception e) {
LOG.warnv(e, "The database of DSQL cluster {0} did not start", cluster.getIdentifier());
onReady.accept(false);
return;
}
boolean deleted;
boolean ready = false;
synchronized (routes) {
deleted = !wanted.contains(arn);
if (!deleted) {
try {
endpoint.register(cluster, backend);
running.put(arn, cluster);
ready = true;
} catch (IOException e) {
LOG.warnv(e, "The DSQL endpoint cannot serve cluster {0}", cluster.getIdentifier());
}
}
}
if (!ready) {
// Deleted while it started, or unreachable: no database is left running for it.
stop(cluster, deleted);
}
onReady.accept(ready);
});
}
/**
* Stops the cluster's database and drops its data, then runs {@code onGone}. When Docker cannot
* remove them, the cluster stays as it is, and the next start of Floci finishes its deletion.
*/
public void deprovision(DsqlCluster cluster, Runnable onGone) {
onGone.run();
if (mock) {
onGone.run();
return;
}
synchronized (routes) {
wanted.remove(cluster.getArn());
running.remove(cluster.getArn());
endpoint.unregister(cluster);
}
Thread.ofVirtual().name("dsql-stop-" + cluster.getIdentifier()).start(() -> {
if (stop(cluster, true)) {
onGone.run();
}
});
}
private boolean stop(DsqlCluster cluster, boolean dropData) {
try {
databases.stop(cluster, dropData);
return true;
} catch (RuntimeException e) {
LOG.warnv(e, "The database of DSQL cluster {0} could not be removed", cluster.getIdentifier());
return false;
}
}
/**
* Stops every database when Floci stops. Their data stays for the next start, unless storage is
* in memory, where the clusters themselves do not survive.
*/
void onStop(@Observes ShutdownEvent ignored) {
if (mock) {
return;
}
endpoint.stop();
for (DsqlCluster cluster : running.values()) {
stop(cluster, memoryStorage);
}
running.clear();
}
}
@@ -16,7 +16,9 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
import io.github.hectorvent.floci.services.iam.IamService.CallerArns;
import io.github.hectorvent.floci.services.iam.RequestPrincipal;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -30,7 +32,6 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@@ -72,6 +73,7 @@ public class DsqlService implements Resettable {
private final DsqlPrincipals principals;
private final IamPolicyEvaluator policyEvaluator;
private final ObjectMapper objectMapper;
private final boolean enabled;
private final Map<String, Object> locks = new ConcurrentHashMap<>();
@Inject
@@ -79,12 +81,13 @@ public class DsqlService implements Resettable {
DsqlDataPlane dataPlane, DsqlPrincipals principals, IamPolicyEvaluator policyEvaluator,
ObjectMapper objectMapper) {
this(storageFactory.create("dsql", "dsql-clusters.json", new TypeReference<>() {}), regionResolver,
config.services().dsql().endpointSuffix(), dataPlane, principals, policyEvaluator, objectMapper);
config.services().dsql().endpointSuffix(), dataPlane, principals, policyEvaluator, objectMapper,
config.services().dsql().enabled());
}
DsqlService(AccountAwareStorageBackend<DsqlCluster> clusters, RegionResolver regionResolver,
String endpointSuffix, DsqlDataPlane dataPlane, DsqlPrincipals principals,
IamPolicyEvaluator policyEvaluator, ObjectMapper objectMapper) {
IamPolicyEvaluator policyEvaluator, ObjectMapper objectMapper, boolean enabled) {
this.clusters = clusters;
this.regionResolver = regionResolver;
this.endpointSuffix = endpointSuffix;
@@ -92,6 +95,7 @@ public class DsqlService implements Resettable {
this.principals = principals;
this.policyEvaluator = policyEvaluator;
this.objectMapper = objectMapper;
this.enabled = enabled;
}
// ── Clusters ──────────────────────────────────────────────────────────────
@@ -233,22 +237,6 @@ public class DsqlService implements Resettable {
return cluster;
}
/** The cluster whose endpoint is {@code host}, in any account: what the data plane serves. */
public Optional<DsqlCluster> clusterForEndpoint(String host) {
if (host == null) {
return Optional.empty();
}
String wanted = host.toLowerCase(Locale.ROOT);
return clusters.scanAllAccounts().stream()
.filter(cluster -> wanted.equals(cluster.getEndpoint()))
.findFirst();
}
/** Every cluster in every account, for the data plane to bring back after a restart. */
public List<DsqlCluster> allClusters() {
return clusters.scanAllAccounts();
}
// ── VPC endpoint service ──────────────────────────────────────────────────
public String vpcEndpointServiceName(String region, String identifier) {
@@ -378,6 +366,31 @@ public class DsqlService implements Resettable {
}
}
/**
* Brings every cluster's database back when Floci starts with clusters in its storage, and
* finishes a deletion that a stop interrupted.
*/
void onStart(@Observes StartupEvent ignored) {
if (!enabled) {
return;
}
for (DsqlCluster cluster : clusters.scanAllAccounts()) {
String accountId = cluster.getAccountId();
String region = cluster.getRegion();
String identifier = cluster.getIdentifier();
if (DELETING.equals(cluster.getStatus())) {
dataPlane.deprovision(cluster, () -> {
clusters.deleteForAccount(accountId, key(region, identifier));
locks.remove(cluster.getArn());
});
} else if (!FAILED.equals(cluster.getStatus())) {
cluster.setDatabaseReady(false);
clusters.putForAccount(accountId, key(region, identifier), cluster);
dataPlane.provision(cluster, ready -> markReady(accountId, region, identifier, ready));
}
}
}
@Override
public void clear() {
for (DsqlCluster cluster : clusters.scanAllAccounts()) {
@@ -389,10 +402,22 @@ public class DsqlService implements Resettable {
// ── Internals ─────────────────────────────────────────────────────────────
/**
* Records whether the cluster's database came up. A cluster being created becomes ACTIVE or
* FAILED; one still waiting for its peers stays PENDING_SETUP until peering, unless its database
* failed.
*/
private void markReady(String accountId, String region, String identifier, boolean ready) {
clusters.getForAccount(accountId, key(region, identifier)).ifPresent(cluster -> {
if (CREATING.equals(cluster.getStatus())) {
cluster.setStatus(ready ? ACTIVE : FAILED);
clusters.getForAccount(accountId, key(region, identifier)).ifPresent(found -> {
synchronized (lockFor(found.getArn())) {
DsqlCluster cluster = clusters.getForAccount(accountId, key(region, identifier)).orElse(null);
if (cluster == null) {
return;
}
cluster.setDatabaseReady(ready);
if (CREATING.equals(cluster.getStatus()) || (!ready && PENDING_SETUP.equals(cluster.getStatus()))) {
cluster.setStatus(ready ? ACTIVE : FAILED);
}
clusters.putForAccount(accountId, key(region, identifier), cluster);
}
});
@@ -416,8 +441,9 @@ public class DsqlService implements Resettable {
/**
* Brings out of {@code PENDING_SETUP} every cluster of {@code cluster}'s group once each names
* every other, as DSQL does when the last peer is updated (measured: both ACTIVE after about
* 100 s; here at once).
* every other, as DSQL does when the last peer is updated (measured: CREATING, then both ACTIVE
* after about 100 s; here ACTIVE at once if the cluster's database answers, else CREATING until
* it does).
*/
private void completePeering(DsqlCluster cluster) {
if (cluster.getLinkedClusterArns() == null) {
@@ -439,7 +465,7 @@ public class DsqlService implements Resettable {
for (DsqlCluster member : group) {
synchronized (lockFor(member.getArn())) {
if (PENDING_SETUP.equals(member.getStatus())) {
member.setStatus(ACTIVE);
member.setStatus(member.isDatabaseReady() ? ACTIVE : CREATING);
clusters.put(key(member.getRegion(), member.getIdentifier()), member);
}
}
@@ -0,0 +1,168 @@
package io.github.hectorvent.floci.services.dsql.dataplane;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.services.dsql.model.DsqlCluster;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
/**
* The PostgreSQL 16 container behind each cluster, set up as DSQL's database is. The data is
* kept as RDS keeps an instance's (a Docker volume of its own, or a directory under the host
* persistent path), so a cluster survives a restart of Floci when its storage does, and is removed
* with the cluster under the same policy. The database trusts its connections, as ElastiCache's
* backends do behind their proxy: its port is published on the loopback address only, or, when
* Floci runs in Docker, reached on Floci's Docker network without being published. Clients reach
* it through Floci's endpoint, which authenticates every one with its IAM token.
*/
@ApplicationScoped
public class DsqlDatabases {
private static final Logger LOG = Logger.getLogger(DsqlDatabases.class);
private static final int PORT = 5432;
private static final Duration READY_TIMEOUT = Duration.ofSeconds(90);
private static final String DATA_PATH = "/var/lib/postgresql/data";
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final ContainerDetector containerDetector;
private final EmulatorConfig config;
/** Where a cluster's database answers. */
public record Backend(String host, int port) {
public String jdbcUrl() {
return "jdbc:postgresql://" + host + ":" + port + "/postgres";
}
}
@Inject
public DsqlDatabases(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager,
ContainerDetector containerDetector, EmulatorConfig config) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.containerDetector = containerDetector;
this.config = config;
}
/** Starts the cluster's database, waits until it answers, and sets it up as DSQL's database is. */
public Backend start(DsqlCluster cluster) throws SQLException, IOException {
String name = containerName(cluster);
Map<String, String> labels = ContainerStorageHelper.resourceIdentityLabels(
"dsql", cluster.getIdentifier(), cluster.getAccountId(), cluster.getRegion());
lifecycleManager.removeIfExistsStrict(name);
ContainerBuilder.Builder spec = containerBuilder.newContainer(config.services().dsql().image())
.withName(name)
.withEnv(List.of("POSTGRES_USER=dbowner", "POSTGRES_DB=postgres", "POSTGRES_HOST_AUTH_METHOD=trust"))
.withDockerNetwork(config.services().dsql().dockerNetwork())
.withLogRotation()
.withLabels(labels);
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
lifecycleManager.ensureVolume(name, labels);
spec.withNamedVolume(name, DATA_PATH);
} else {
String hostPath = ContainerStorageHelper.hostResourcePath(config, "dsql", cluster.getIdentifier()).toString();
if (!containerDetector.isRunningInContainer()) {
ContainerStorageHelper.ensureHostDir(hostPath);
}
spec.withBind(hostPath, DATA_PATH);
}
if (containerDetector.isRunningInContainer()) {
spec.withExposedPort(PORT);
} else {
spec.withLoopbackPortBinding(PORT, 0);
}
ContainerSpec built = spec.build();
String containerId = lifecycleManager.create(built);
try {
ContainerLifecycleManager.EndpointInfo endpoint =
lifecycleManager.startCreated(containerId, built).getEndpoint(PORT);
Backend backend = new Backend(endpoint.host(), endpoint.port());
awaitReady(backend);
bootstrap(backend);
LOG.infov("DSQL cluster {0} serves from {1}:{2}", cluster.getIdentifier(), backend.host(),
String.valueOf(backend.port()));
return backend;
} catch (SQLException | IOException | RuntimeException e) {
// A database that never served does not keep running: its cluster is FAILED, and deleting
// the cluster removes its data.
try {
lifecycleManager.removeIfExistsStrict(name);
} catch (RuntimeException removal) {
e.addSuppressed(removal);
}
throw e;
}
}
/**
* Stops the cluster's database and, with {@code dropData}, removes its volume as Floci removes
* a deleted resource's: always with in-memory storage, otherwise when
* {@code prune-volumes-on-delete} is on. A host directory is left in place, as RDS leaves it.
* Throws when Docker cannot remove either, so a deletion is not taken for done.
*/
public void stop(DsqlCluster cluster, boolean dropData) {
String name = containerName(cluster);
lifecycleManager.removeIfExistsStrict(name);
if (dropData && ContainerStorageHelper.isNamedVolumeMode(config)) {
ContainerStorageHelper.removeNamedVolumeStrict(config, lifecycleManager, name);
}
}
private static Connection superuser(Backend backend) throws SQLException {
return DriverManager.getConnection(backend.jdbcUrl(), "dbowner", "");
}
private String containerName(DsqlCluster cluster) {
return ContainerStorageHelper.dockerName(config, "dsql-" + cluster.getIdentifier());
}
private static void awaitReady(Backend backend) throws SQLException {
Instant deadline = Instant.now().plus(READY_TIMEOUT);
SQLException last = null;
while (Instant.now().isBefore(deadline)) {
try (Connection connection = superuser(backend); Statement statement = connection.createStatement()) {
statement.execute("SELECT 1");
return;
} catch (SQLException e) {
last = e;
try {
Thread.sleep(250);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new SQLException("Interrupted while the database started", interrupted);
}
}
}
throw new SQLException("The database did not start within " + READY_TIMEOUT.toSeconds() + " s", last);
}
private static void bootstrap(Backend backend) throws SQLException, IOException {
String script;
try (InputStream in = DsqlDatabases.class.getResourceAsStream("/dsql/bootstrap.sql")) {
if (in == null) {
throw new IOException("dsql/bootstrap.sql is missing from the classpath");
}
script = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
try (Connection connection = superuser(backend); Statement statement = connection.createStatement()) {
statement.execute(script);
}
}
}
@@ -0,0 +1,353 @@
package io.github.hectorvent.floci.services.dsql.dataplane;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import io.github.hectorvent.floci.services.dsql.model.DsqlCluster;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* The address every DSQL cluster is reached at: one port, as on AWS, where the server name a client
* sends picks the cluster. A connection is admitted as Aurora DSQL admits it (measured on AWS,
* eu-west-1, 2026-10-16): the password is a SigV4 token for the endpoint's host, {@code admin}
* signs {@code DbConnectAdmin} and every other role {@code DbConnect}, a token is taken up to 5
* seconds past its expiry, and a role other than {@code admin} logs in only for an IAM role mapped
* to it, which Floci does not map yet. Every refusal is the same {@code access denied}, with a hint
* only where DSQL gives one. DSQL lets clients in while a cluster is still CREATING; Floci's
* clusters are CREATING only while their database starts, and serve once it answers.
*/
@ApplicationScoped
public class DsqlEndpoint {
private static final Logger LOG = Logger.getLogger(DsqlEndpoint.class);
private static final DateTimeFormatter AMZ_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
static final Duration EXPIRY_GRACE = Duration.ofSeconds(5);
private static final int HANDSHAKE_TIMEOUT_MILLIS = 30_000;
private static final String ADMIN = "admin";
private final DsqlTlsCertificates certificates;
private final IamService iamService;
private final IamPolicyEvaluator policyEvaluator;
private final Instance<ScpProvider> scpProvider;
private final SigV4RequestValidator validator;
private final boolean enforcement;
private final int configuredPort;
private final Map<String, Route> routes = new ConcurrentHashMap<>();
private final Map<Long, DsqlDatabases.Backend> cancelKeys = new ConcurrentHashMap<>();
private final Map<String, Set<Socket>> connections = new ConcurrentHashMap<>();
private volatile ServerSocket server;
/** A cluster being served, and where its database answers. */
record Route(String host, String arn, String region, String accountId, DsqlDatabases.Backend backend) {
}
/**
* Whether a connection may go on, and to which cluster; when it may not, the SQLSTATE DSQL
* answers ({@code 08006} for the token, {@code 28000} for the role it would log in as) and its
* hint.
*/
record Admission(boolean allowed, String state, String hint, Route route) {
static Admission refused(String hint) {
return new Admission(false, "08006", hint, null);
}
static Admission unauthorized() {
return new Admission(false, "28000", null, null);
}
}
@Inject
public DsqlEndpoint(DsqlTlsCertificates certificates, IamService iamService, IamPolicyEvaluator policyEvaluator,
Instance<ScpProvider> scpProvider, EmulatorConfig config) {
this.certificates = certificates;
this.iamService = iamService;
this.policyEvaluator = policyEvaluator;
this.scpProvider = scpProvider;
this.validator = new SigV4RequestValidator(iamService);
this.enforcement = config.services().iam().enforcementEnabled();
this.configuredPort = config.services().dsql().port();
}
/** Serves {@code cluster} from {@code backend}, opening the endpoint's port on first use. */
public void register(DsqlCluster cluster, DsqlDatabases.Backend backend) throws IOException {
listen();
String host = cluster.getEndpoint().toLowerCase(Locale.ROOT);
routes.put(host, new Route(host, cluster.getArn(), cluster.getRegion(), cluster.getAccountId(), backend));
}
/** Stops serving {@code cluster} and closes its connections, as deleting a cluster does. */
public void unregister(DsqlCluster cluster) {
String host = cluster.getEndpoint().toLowerCase(Locale.ROOT);
routes.remove(host);
Set<Socket> open = connections.remove(host);
if (open != null) {
open.forEach(DsqlEndpoint::closeQuietly);
}
}
/** The port the endpoint listens on, once it does: the configured one, or the one picked for 0. */
public int port() {
ServerSocket listening = server;
return listening == null ? configuredPort : listening.getLocalPort();
}
@PreDestroy
public synchronized void stop() {
ServerSocket listening = server;
server = null;
if (listening != null) {
closeQuietly(listening);
}
connections.values().forEach(open -> open.forEach(DsqlEndpoint::closeQuietly));
connections.clear();
routes.clear();
}
private synchronized void listen() throws IOException {
if (server != null) {
return;
}
ServerSocket listening = new ServerSocket();
listening.setReuseAddress(true);
listening.bind(new InetSocketAddress(configuredPort));
server = listening;
Thread.ofVirtual().name("dsql-endpoint-accept").start(() -> accept(listening));
LOG.infov("DSQL endpoint listening on port {0}", String.valueOf(listening.getLocalPort()));
}
private void accept(ServerSocket listening) {
while (!listening.isClosed()) {
try {
Socket client = listening.accept();
Thread.ofVirtual().name("dsql-endpoint-connection").start(() -> {
try {
new DsqlSession(client, this).serve();
} catch (IOException | RuntimeException e) {
LOG.debugv("DSQL connection ended: {0}", e.getMessage());
} finally {
closeQuietly(client);
}
});
} catch (IOException e) {
if (!listening.isClosed()) {
LOG.warnv("DSQL endpoint accept failed: {0}", e.getMessage());
}
}
}
}
SSLContext sslContext() {
return certificates.sslContext();
}
int handshakeTimeoutMillis() {
return HANDSHAKE_TIMEOUT_MILLIS;
}
/**
* Whether {@code token} lets {@code user} in, checked in the order DSQL reports: the cluster
* the client asked for by name (or, without a name, the one the token is for), the action
* the user needs, the token's expiry, then its signature and, for a role other than
* {@code admin}, the IAM role mapped to it: DSQL refuses a role no IAM role is mapped to, and
* Floci maps none yet, so only {@code admin} signs in.
*/
Admission admit(String token, String user, String serverName) {
URI uri;
try {
uri = URI.create("https://" + token);
} catch (IllegalArgumentException ignored) {
// A password that is no token is refused without a hint, as DSQL refuses one.
return Admission.refused(null);
}
String host = uri.getHost();
String rawQuery = uri.getRawQuery();
if (host == null || rawQuery == null || uri.getPort() != -1) {
return Admission.refused(null);
}
host = host.toLowerCase(Locale.ROOT);
String target = serverName == null ? host : serverName.toLowerCase(Locale.ROOT);
Route route = routes.get(target);
if (route == null || !route.host().equals(host)) {
return Admission.refused(null);
}
String action = SigV4RequestValidator.queryParameter(rawQuery, "Action");
String needed = ADMIN.equals(user) ? "DbConnectAdmin" : "DbConnect";
if (!needed.equals(action)) {
boolean dsqlAction = "DbConnectAdmin".equals(action) || "DbConnect".equals(action);
return Admission.refused(dsqlAction
? "Wrong user to action mapping. user: " + user + ", action: " + action : null);
}
String expiredHint = expiredHint(rawQuery);
if (expiredHint != null) {
return Admission.refused(expiredHint);
}
String[] scope = credentialScope(rawQuery);
if (scope == null || !route.region().equals(scope[2]) || !"dsql".equals(scope[3])) {
return Admission.refused(null);
}
// The endpoint checks tokens outside any request, so the key is looked up in the account
// that owns the cluster, as ElastiCache's proxy does: a long-term key of another account
// never signs in, and one of the cluster's own account does whichever account is Floci's default.
if (!validator.validate(rawQuery, host, needed, "DBUser", false, null, "DSQL IAM token", route.accountId(),
EXPIRY_GRACE)) {
return Admission.refused(null);
}
String accessKeyId = scope[0];
// DSQL takes no cross-account access yet (its resource-based policy guide), so credentials of
// another account are refused like any other token, a session's included.
if (!route.accountId().equals(iamService.resolveAccountId(accessKeyId).orElse(route.accountId()))) {
return Admission.refused(null);
}
// The endpoint runs outside any request: the caller's policies are read in the cluster's
// account, as the enforcement filter reads them in the request's.
if (enforcement && !RequestScopes.callAs(route.accountId(), route.region(),
() -> allowedByIam(accessKeyId, "dsql:" + needed, route))) {
return Admission.refused(null);
}
if (!ADMIN.equals(user)) {
return Admission.unauthorized();
}
return new Admission(true, null, null, route);
}
/**
* DSQL's hint for a token past its expiry and the 5 seconds of grace after it:
* {@code Signature expired: <expiry> is now earlier than <now - 5 s> (<now> - 0 min.)}.
*/
private static String expiredHint(String rawQuery) {
String date = SigV4RequestValidator.queryParameter(rawQuery, "X-Amz-Date");
String expires = SigV4RequestValidator.queryParameter(rawQuery, "X-Amz-Expires");
if (date == null || expires == null) {
return null;
}
Instant expiry;
try {
expiry = Instant.from(AMZ_DATE.parse(date)).plusSeconds(Long.parseLong(expires));
} catch (RuntimeException ignored) {
// A date or expiry that does not parse gets no hint here: the signature check that
// follows refuses the token without one, as DSQL does.
return null;
}
Instant now = Instant.now();
Instant earliest = now.minus(EXPIRY_GRACE);
if (!expiry.isBefore(earliest)) {
return null;
}
return "Signature expired: " + AMZ_DATE.format(expiry) + " is now earlier than " + AMZ_DATE.format(earliest)
+ " (" + AMZ_DATE.format(now) + " - 0 min.)";
}
/**
* Whether the caller's policies let it {@code action} the cluster, under its organization's
* service control policies as the enforcement filter applies them. A known credential with no
* policies to evaluate is let through, as the filter lets it.
*/
private boolean allowedByIam(String accessKeyId, String action, Route route) {
CallerContext caller = iamService.resolveCallerContext(accessKeyId);
if (caller == null) {
return true;
}
List<List<String>> scpLevels = scpProvider.isResolvable()
? scpProvider.get().effectiveScpLevels(route.accountId()) : null;
if (scpLevels != null) {
caller = caller.withScpLevels(scpLevels);
}
return policyEvaluator.simulatePrincipalPolicy(caller, action, route.arn(), Map.of())
== IamPolicyEvaluator.SimulationDecision.ALLOWED;
}
private static String[] credentialScope(String rawQuery) {
String credential = SigV4RequestValidator.queryParameter(rawQuery, "X-Amz-Credential");
if (credential == null) {
return null;
}
String[] parts = credential.split("/");
return parts.length >= 5 ? parts : null;
}
void opened(Route route, Socket socket) {
connections.computeIfAbsent(route.host(), host -> ConcurrentHashMap.newKeySet()).add(socket);
if (!routes.containsKey(route.host())) {
closeQuietly(socket);
}
}
void closed(Route route, Socket socket) {
Set<Socket> open = connections.get(route.host());
if (open != null) {
open.remove(socket);
}
}
/** Remembers which database a BackendKeyData came from, so a CancelRequest can reach it. */
long registerCancelKey(byte[] keyData, DsqlDatabases.Backend backend) {
long key = ByteBuffer.wrap(keyData).getLong(0);
cancelKeys.put(key, backend);
return key;
}
void forgetCancelKey(long key) {
cancelKeys.remove(key);
}
/** Hands a CancelRequest's process id and secret to the database that issued them. */
void forwardCancel(byte[] keyData) {
if (keyData.length < 8) {
return;
}
DsqlDatabases.Backend backend = cancelKeys.get(ByteBuffer.wrap(keyData).getLong(0));
if (backend == null) {
return;
}
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(backend.host(), backend.port()), 5_000);
OutputStream out = socket.getOutputStream();
out.write(ByteBuffer.allocate(16).putInt(16).putInt(PostgresWire.CANCEL_REQUEST)
.put(keyData, 0, 8).array());
out.flush();
} catch (IOException e) {
LOG.debugv("Could not forward a DSQL cancel request: {0}", e.getMessage());
}
}
private static void closeQuietly(AutoCloseable closing) {
try {
closing.close();
} catch (Exception ignored) {
// Already closed.
}
}
}
@@ -0,0 +1,303 @@
package io.github.hectorvent.floci.services.dsql.dataplane;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.services.dsql.DsqlIdentifiers;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SNIMatcher;
import javax.net.ssl.SNIServerName;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.StandardConstants;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* One client connection to a DSQL endpoint, as Aurora DSQL serves it (measured on AWS, eu-west-1,
* 2026-10-16): TLS is mandatory, the password is an IAM token for the endpoint, the startup is read
* as DSQL reads it, and a connection lives an hour.
*/
final class DsqlSession {
static final Duration CONNECTION_LIFETIME = Duration.ofHours(1);
// A startup packet is refused above PostgreSQL's own limit, 10,000 bytes, and a message above 64 MB.
private static final int MAX_STARTUP = 10_000;
private static final int MAX_MESSAGE = 64 * 1024 * 1024;
private static final String ACCESS_DENIED = "unable to accept connection, access denied";
private final Socket socket;
private final DsqlEndpoint endpoint;
private final String sessionId = DsqlIdentifiers.newId();
private volatile long cancelKey;
DsqlSession(Socket socket, DsqlEndpoint endpoint) {
this.socket = socket;
this.endpoint = endpoint;
}
void serve() throws IOException {
socket.setTcpNoDelay(true);
socket.setSoTimeout(endpoint.handshakeTimeoutMillis());
InputStream rawIn = socket.getInputStream();
OutputStream rawOut = socket.getOutputStream();
PostgresWire.Startup first = PostgresWire.readStartup(rawIn, MAX_STARTUP, "startup message");
if (first.code() == PostgresWire.CANCEL_REQUEST) {
endpoint.forwardCancel(first.body());
return;
}
if (first.code() == PostgresWire.GSSENC_REQUEST) {
rawOut.write('N');
rawOut.flush();
first = PostgresWire.readStartup(rawIn, MAX_STARTUP, "startup message");
}
if (first.code() != PostgresWire.SSL_REQUEST) {
refuse(rawOut, "08P01", "unable to accept connection, SSL is mandatory. AWS Authentication is required.",
null);
return;
}
rawOut.write('S');
rawOut.flush();
String[] serverName = new String[1];
SSLSocket tls = (SSLSocket) endpoint.sslContext().getSocketFactory().createSocket(socket, null, true);
SSLParameters parameters = tls.getSSLParameters();
parameters.setSNIMatchers(List.of(new SNIMatcher(StandardConstants.SNI_HOST_NAME) {
@Override
public boolean matches(SNIServerName name) {
if (name instanceof SNIHostName host) {
serverName[0] = host.getAsciiName().toLowerCase(Locale.ROOT);
}
return true;
}
}));
tls.setSSLParameters(parameters);
tls.setUseClientMode(false);
tls.startHandshake();
InputStream in = new BufferedInputStream(tls.getInputStream());
OutputStream out = new BufferedOutputStream(tls.getOutputStream());
PostgresWire.Startup startup = PostgresWire.readStartup(in, MAX_STARTUP, "startup message");
if (startup.code() == PostgresWire.CANCEL_REQUEST) {
endpoint.forwardCancel(startup.body());
return;
}
if (startup.code() != PostgresWire.PROTOCOL_3) {
refuse(out, "08P01", "unsupported frontend protocol", null);
return;
}
Map<String, String> startupParameters = PostgresWire.startupParameters(startup.body());
String user = startupParameters.getOrDefault("user", "");
String database = startupParameters.getOrDefault("database", user);
PostgresWire.write(out, (byte) 'R', PostgresWire.int32(3));
out.flush();
PostgresWire.Message password = PostgresWire.read(in, MAX_MESSAGE, "message");
if (password.type() != 'p') {
refuse(out, "08006", ACCESS_DENIED, null);
return;
}
String token = PostgresWire.cString(password.body(), 0).value();
DsqlEndpoint.Admission admission = endpoint.admit(token, user, serverName[0]);
if (!admission.allowed()) {
refuse(out, admission.state(), ACCESS_DENIED, admission.hint());
return;
}
if (!"postgres".equals(database)) {
refuse(out, "55000", "database \"" + database + "\" is not currently accepting connections", null);
return;
}
Map<String, String> optionSettings = optionSettings(startupParameters.get("options"));
String custom = customParameter(optionSettings, startupParameters);
if (custom != null) {
refuse(out, "42704", "unrecognized configuration parameter \"" + custom + "\"", null);
return;
}
DsqlDatabases.Backend target = admission.route().backend();
endpoint.opened(admission.route(), tls);
Socket backend = new Socket();
try (backend) {
backend.connect(new InetSocketAddress(target.host(), target.port()), 5_000);
backend.setTcpNoDelay(true);
socket.setSoTimeout(0);
InputStream backendIn = new BufferedInputStream(backend.getInputStream());
OutputStream backendOut = new BufferedOutputStream(backend.getOutputStream());
Map<String, String> backendStartup = new LinkedHashMap<>(startupParameters);
backendStartup.remove("options");
if (!optionSettings.isEmpty()) {
backendStartup.put("options", backendOptions(optionSettings));
}
backendStartup.put("database", "postgres");
backendOut.write(PostgresWire.startupMessage(backendStartup));
backendOut.flush();
Thread toClient = Thread.ofVirtual().name("dsql-backend-" + sessionId)
.start(() -> relayToClient(backendIn, out, target, tls));
Thread lifetime = Thread.ofVirtual().name("dsql-lifetime-" + sessionId).start(() -> {
try {
Thread.sleep(CONNECTION_LIFETIME.toMillis());
closeQuietly(tls);
closeQuietly(backend);
} catch (InterruptedException ignored) {
// The connection ended first.
}
});
try {
relayToBackend(in, backendOut);
} finally {
lifetime.interrupt();
closeQuietly(backend);
toClient.interrupt();
}
} finally {
endpoint.closed(admission.route(), tls);
if (cancelKey != 0) {
endpoint.forgetCancelKey(cancelKey);
}
}
}
private static void relayToBackend(InputStream in, OutputStream backendOut) throws IOException {
while (true) {
PostgresWire.Message message = PostgresWire.read(in, MAX_MESSAGE, "message");
PostgresWire.write(backendOut, message);
if (message.type() == 'X') {
backendOut.flush();
return;
}
if (in.available() == 0) {
backendOut.flush();
}
}
}
/**
* The settings a client's startup {@code options} make, as DSQL reads them (measured, eu-west-1,
* 2026-10-20): words split on white space, with no escapes, of which only {@code -c name=value}
* counts, the first for a name winning. DSQL ignores every other word, {@code --name=value}
* included, so none of them may reach the database.
*/
static Map<String, String> optionSettings(String options) {
Map<String, String> settings = new LinkedHashMap<>();
Set<String> seen = new HashSet<>();
String[] words = options == null ? new String[0] : options.strip().split("\\s+");
for (int i = 0; i + 1 < words.length; i++) {
if ("-c".equals(words[i])) {
String setting = words[++i];
int equals = setting.indexOf('=');
if (equals > 0 && seen.add(setting.substring(0, equals).toLowerCase(Locale.ROOT))) {
settings.put(setting.substring(0, equals), setting.substring(equals + 1));
}
}
}
return settings;
}
/**
* The first custom (dotted) parameter a startup sets, in its {@code options} or on its own: DSQL
* refuses the connection for one (measured, eu-west-1, 2026-10-20), {@code dsql.} or not.
*/
static String customParameter(Map<String, String> optionSettings, Map<String, String> startupParameters) {
return Stream.concat(optionSettings.keySet().stream(), startupParameters.keySet().stream())
.filter(name -> name.contains(".")).findFirst().orElse(null);
}
/** {@code settings} as PostgreSQL's {@code options}, whose backslash escapes the next character. */
static String backendOptions(Map<String, String> settings) {
List<String> words = new ArrayList<>();
settings.forEach((name, value) -> words.add("-c " + (name + "=" + value).replace("\\", "\\\\")));
return String.join(" ", words);
}
private void relayToClient(InputStream backendIn, OutputStream out, DsqlDatabases.Backend backend, Socket client) {
try {
PostgresWire.Message authenticated = null;
boolean started = false;
while (true) {
PostgresWire.Message message = PostgresWire.read(backendIn, MAX_MESSAGE, "message");
if (!started) {
// DSQL refuses a connection instead of authenticating it, so the database's
// AuthenticationOk waits for what follows it, and a refusal takes its place.
if (message.type() == 'R' && authenticated == null) {
authenticated = message;
continue;
}
if (message.type() == 'E') {
message = new PostgresWire.Message(message.type(), withSessionId(message.body()));
} else if (authenticated != null) {
PostgresWire.write(out, authenticated);
}
authenticated = null;
started = message.type() == 'Z';
}
if (message.type() == 'K') {
cancelKey = endpoint.registerCancelKey(message.body(), backend);
}
PostgresWire.write(out, message);
if (backendIn.available() == 0) {
out.flush();
}
}
} catch (IOException ignored) {
// The database or the client ended the connection: the client's side is closed with it.
closeQuietly(client);
}
}
/**
* A refusal of the database's as DSQL words every one: the session's id as its detail, and no
* source location.
*/
private byte[] withSessionId(byte[] body) {
Map<Character, String> fields = PostgresWire.parseFields(body, 0);
fields.remove('F');
fields.remove('L');
fields.remove('R');
fields.putIfAbsent('D', "Session Id: " + sessionId);
return PostgresWire.fields(fields);
}
/** An ErrorResponse body of {@code severity} (FATAL, ERROR), as DSQL orders its fields. */
static byte[] error(String severity, String state, String message, String detail, String hint) {
Map<Character, String> fields = new LinkedHashMap<>();
fields.put('S', severity);
fields.put('V', severity);
fields.put('C', state);
fields.put('M', message);
if (detail != null) {
fields.put('D', detail);
}
if (hint != null) {
fields.put('H', hint);
}
return PostgresWire.fields(fields);
}
/** A refusal as DSQL words every one: FATAL, with the session's id as its detail. */
private void refuse(OutputStream out, String state, String message, String hint) throws IOException {
PostgresWire.write(out, (byte) 'E', error("FATAL", state, message, "Session Id: " + sessionId, hint));
out.flush();
}
private static void closeQuietly(Socket closing) {
try {
closing.close();
} catch (IOException ignored) {
// Already closed.
}
}
}
@@ -0,0 +1,67 @@
package io.github.hectorvent.floci.services.dsql.dataplane;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.Pem;
import io.github.hectorvent.floci.services.acm.CertificateGenerator;
import io.github.hectorvent.floci.services.acm.model.KeyAlgorithm;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import javax.net.ssl.SSLContext;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
/**
* The certificate every DSQL endpoint presents: one leaf, signed by Floci's root CA, naming
* {@code *.dsql.<region>.<endpoint-suffix>} for every Region Floci knows, so a client verifying
* the endpoint's name (sslmode=verify-full, as DSQL's own connectors do) only has to trust
* Floci's CA, the one every launched container already trusts.
*/
@ApplicationScoped
public class DsqlTlsCertificates {
private final FlociCertificateAuthority certificateAuthority;
private final String endpointSuffix;
private volatile SSLContext context;
@Inject
public DsqlTlsCertificates(FlociCertificateAuthority certificateAuthority, EmulatorConfig config) {
this(certificateAuthority, config.services().dsql().endpointSuffix());
}
DsqlTlsCertificates(FlociCertificateAuthority certificateAuthority, String endpointSuffix) {
this.certificateAuthority = certificateAuthority;
this.endpointSuffix = endpointSuffix;
}
public SSLContext sslContext() {
SSLContext current = context;
if (current == null) {
synchronized (this) {
if (context == null) {
context = build();
}
current = context;
}
}
return current;
}
private SSLContext build() {
try {
List<String> sans = new ArrayList<>();
for (String region : new TreeSet<>(AwsRegions.KNOWN_IDS)) {
sans.add("*.dsql." + region + "." + endpointSuffix);
}
CertificateGenerator.GeneratedCertificate generated = certificateAuthority.issueServerCertificate(
"dsql." + endpointSuffix, sans, KeyAlgorithm.RSA_2048, null);
return certificateAuthority.serverSslContext(Pem.parseCertificate(generated.certificatePem()),
Pem.parsePrivateKey(generated.privateKeyPem()));
} catch (Exception e) {
throw new IllegalStateException("Failed to issue the DSQL endpoint certificate", e);
}
}
}
@@ -31,6 +31,7 @@ public class DsqlCluster {
private String policyVersion;
private String witnessRegion;
private List<String> linkedClusterArns;
private boolean databaseReady;
public String getIdentifier() { return identifier; }
public void setIdentifier(String identifier) { this.identifier = identifier; }
@@ -66,4 +67,7 @@ public class DsqlCluster {
public void setWitnessRegion(String witnessRegion) { this.witnessRegion = witnessRegion; }
public List<String> getLinkedClusterArns() { return linkedClusterArns; }
public void setLinkedClusterArns(List<String> linkedClusterArns) { this.linkedClusterArns = linkedClusterArns; }
/** Whether the cluster's database answers, which a multi-Region cluster waits for after peering. */
public boolean isDatabaseReady() { return databaseReady; }
public void setDatabaseReady(boolean databaseReady) { this.databaseReady = databaseReady; }
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.rds.proxy;
import io.github.hectorvent.floci.core.common.Digests;
import io.github.hectorvent.floci.core.common.PostgresWire;
import io.github.hectorvent.floci.core.common.auth.SigV4RequestValidator;
import org.jboss.logging.Logger;
@@ -52,8 +53,6 @@ public class PostgresProtocolHandler {
private static final Logger LOG = Logger.getLogger(PostgresProtocolHandler.class);
private static final int SSL_REQUEST_CODE = 80877103;
private static final int STARTUP_PROTOCOL_VERSION = 196608; // v3.0
private static final int MAX_HANDSHAKE_PACKET_LENGTH = 1_048_576;
/**
@@ -154,7 +153,7 @@ public class PostgresProtocolHandler {
OutputStream clientOut = new BufferedOutputStream(client.getOutputStream());
// Phase 2: Challenge client with cleartext password request
sendMessage(clientOut, 'R', intBytes(3)); // AuthenticationCleartextPassword
PostgresWire.write(clientOut, 'R', PostgresWire.int32(3)); // AuthenticationCleartextPassword
clientOut.flush();
// Phase 3: Read client password
@@ -294,7 +293,7 @@ public class PostgresProtocolHandler {
notices.addAll(defaults.warnings());
roleDefaultsAfterHandover = defaults.afterHandover();
if (!defaults.atStartup().isEmpty()) {
sendMessage(backendOut, 'X');
PostgresWire.write(backendOut, 'X');
backendOut.flush();
closeQuietly(backend);
try {
@@ -455,7 +454,7 @@ public class PostgresProtocolHandler {
return null;
}
sendMessage(clientOut, 'R', intBytes(0)); // AuthenticationOK
PostgresWire.write(clientOut, 'R', PostgresWire.int32(0)); // AuthenticationOK
for (byte[] msg : bufferedMessages) {
clientOut.write(msg);
}
@@ -478,10 +477,9 @@ public class PostgresProtocolHandler {
while (true) {
InputStream in = currentSocket.getInputStream();
OutputStream out = currentSocket.getOutputStream();
int length = checkedPacketLength(readInt32(in), 8, "startup message");
int proto = readInt32(in);
PostgresWire.Startup startup = PostgresWire.readStartup(in, MAX_HANDSHAKE_PACKET_LENGTH, "startup message");
if (proto == SSL_REQUEST_CODE) {
if (startup.code() == PostgresWire.SSL_REQUEST) {
out.write('S');
out.flush();
currentSocket = acceptSsl(currentSocket, tlsCertificates);
@@ -491,14 +489,12 @@ public class PostgresProtocolHandler {
continue;
}
if (proto != STARTUP_PROTOCOL_VERSION) {
LOG.warnv("Unexpected PostgreSQL startup protocol version: {0}", proto);
if (startup.code() != PostgresWire.PROTOCOL_3) {
LOG.warnv("Unexpected PostgreSQL startup protocol version: {0}", startup.code());
return null;
}
byte[] payload = new byte[length - 8];
readFully(in, payload);
Map<String, String> params = parseStartupParams(payload);
Map<String, String> params = PostgresWire.startupParameters(startup.body());
return new StartupMessage(currentSocket,
params.getOrDefault("user", "postgres"),
params.get("database"),
@@ -535,33 +531,6 @@ public class PostgresProtocolHandler {
return !messages.isEmpty() && messages.get(messages.size() - 1)[0] == 'E';
}
static Map<String, String> parseStartupParams(byte[] data) {
Map<String, String> params = new LinkedHashMap<>();
int i = 0;
while (i < data.length) {
int keyStart = i;
while (i < data.length && data[i] != 0) {
i++;
}
if (i >= data.length) {
break;
}
String key = new String(data, keyStart, i - keyStart, StandardCharsets.UTF_8);
i++; // skip null
if (key.isEmpty()) {
break; // final null terminator
}
int valStart = i;
while (i < data.length && data[i] != 0) {
i++;
}
String value = new String(data, valStart, i - valStart, StandardCharsets.UTF_8);
i++; // skip null
params.put(key, value);
}
return params;
}
/**
* Writes the backend StartupMessage: the proxy's own {@code user} and {@code database}, then
* the client's other parameters in the order the client sent them. {@code _pq_.} names request
@@ -569,28 +538,16 @@ public class PostgresProtocolHandler {
*/
private static void sendStartupToBackend(OutputStream out, String username, String dbName,
Map<String, String> clientParameters) throws IOException {
ByteArrayOutputStream parameters = new ByteArrayOutputStream();
writeStartupParameter(parameters, "user", username);
writeStartupParameter(parameters, "database", dbName);
Map<String, String> parameters = new LinkedHashMap<>();
parameters.put("user", username);
parameters.put("database", dbName);
for (Map.Entry<String, String> parameter : clientParameters.entrySet()) {
String name = parameter.getKey();
if (!"user".equals(name) && !"database".equals(name) && !name.startsWith("_pq_.")) {
writeStartupParameter(parameters, name, parameter.getValue());
parameters.put(name, parameter.getValue());
}
}
parameters.write(0); // final null
writeInt32(out, 4 + 4 + parameters.size());
writeInt32(out, STARTUP_PROTOCOL_VERSION);
parameters.writeTo(out);
}
private static void writeStartupParameter(ByteArrayOutputStream out, String name, String value)
throws IOException {
out.write(name.getBytes(StandardCharsets.UTF_8));
out.write(0);
out.write(value.getBytes(StandardCharsets.UTF_8));
out.write(0);
out.write(PostgresWire.startupMessage(parameters));
}
// ── Client auth phase ─────────────────────────────────────────────────────
@@ -604,9 +561,9 @@ public class PostgresProtocolHandler {
LOG.warnv("Expected PasswordMessage ('p'), got {0}", (char) type);
return null;
}
int length = checkedPacketLength(readInt32(in), 5, "password message");
int length = PostgresWire.checkedLength(PostgresWire.readInt32(in), 5, MAX_HANDSHAKE_PACKET_LENGTH, "password message");
byte[] data = new byte[length - 4];
readFully(in, data);
PostgresWire.readFully(in, data);
// Strip trailing null terminator
int end = data.length;
while (end > 0 && data[end - 1] == 0) {
@@ -645,8 +602,8 @@ public class PostgresProtocolHandler {
return false;
}
int length = checkedPacketLength(readInt32(in), 8, "backend authentication message");
int authType = readInt32(in);
int length = PostgresWire.checkedLength(PostgresWire.readInt32(in), 8, MAX_HANDSHAKE_PACKET_LENGTH, "backend authentication message");
int authType = PostgresWire.readInt32(in);
if (authType == 0) {
// Trust auth — no password needed
@@ -663,7 +620,7 @@ public class PostgresProtocolHandler {
if (authType == 5) {
// MD5Password — read 4-byte salt
byte[] salt = new byte[4];
readFully(in, salt);
PostgresWire.readFully(in, salt);
String md5pw = computeMd5Password(password, username, salt);
sendPasswordMessage(out, md5pw);
out.flush();
@@ -673,14 +630,14 @@ public class PostgresProtocolHandler {
if (authType == 10) {
// SCRAM-SHA-256 — drain the mechanisms list and perform SCRAM handshake
byte[] mechanismsBytes = new byte[length - 8];
readFully(in, mechanismsBytes);
PostgresWire.readFully(in, mechanismsBytes);
return performScramSha256(in, out, username, password);
}
LOG.warnv("Unsupported backend PostgreSQL auth type: {0}", authType);
if (length > 8) {
byte[] extra = new byte[length - 8];
readFully(in, extra);
PostgresWire.readFully(in, extra);
}
return false;
}
@@ -731,19 +688,19 @@ public class PostgresProtocolHandler {
saslInit.write((firstMsgBytes.length >> 8) & 0xFF);
saslInit.write(firstMsgBytes.length & 0xFF);
saslInit.write(firstMsgBytes);
sendMessage(out, 'p', saslInit.toByteArray());
PostgresWire.write(out, 'p', saslInit.toByteArray());
out.flush();
// Step 2: Read AuthenticationSASLContinue (authType=11)
if (readAuthenticationType(in) != 'R') {
return false;
}
int len2 = checkedPacketLength(readInt32(in), 8, "SASL continue message");
if (readInt32(in) != 11) {
int len2 = PostgresWire.checkedLength(PostgresWire.readInt32(in), 8, MAX_HANDSHAKE_PACKET_LENGTH, "SASL continue message");
if (PostgresWire.readInt32(in) != 11) {
return false;
}
byte[] serverFirstBytes = new byte[len2 - 8];
readFully(in, serverFirstBytes);
PostgresWire.readFully(in, serverFirstBytes);
String serverFirstMessage = new String(serverFirstBytes, StandardCharsets.UTF_8);
// Parse server-first-message: r=<nonce>,s=<base64-salt>,i=<iterations>
@@ -772,19 +729,19 @@ public class PostgresProtocolHandler {
+ ",p=" + Base64.getEncoder().encodeToString(clientProof);
// Send SASLResponse: just the final message bytes
sendMessage(out, 'p', clientFinalMessage.getBytes(StandardCharsets.UTF_8));
PostgresWire.write(out, 'p', clientFinalMessage.getBytes(StandardCharsets.UTF_8));
out.flush();
// Step 4: Read AuthenticationSASLFinal (authType=12) — server signature (ignored)
if (readAuthenticationType(in) != 'R') {
return false;
}
int len3 = checkedPacketLength(readInt32(in), 8, "SASL final message");
if (readInt32(in) != 12) {
int len3 = PostgresWire.checkedLength(PostgresWire.readInt32(in), 8, MAX_HANDSHAKE_PACKET_LENGTH, "SASL final message");
if (PostgresWire.readInt32(in) != 12) {
return false;
}
byte[] serverFinalBytes = new byte[len3 - 8];
readFully(in, serverFinalBytes);
PostgresWire.readFully(in, serverFinalBytes);
// Step 5: Read final AuthenticationOK
return readAuthOk(in);
@@ -847,11 +804,11 @@ public class PostgresProtocolHandler {
LOG.warnv("Expected AuthenticationOK from backend, got type={0}", type);
return false;
}
int length = checkedPacketLength(readInt32(in), 8, "authentication response");
int authType = readInt32(in);
int length = PostgresWire.checkedLength(PostgresWire.readInt32(in), 8, MAX_HANDSHAKE_PACKET_LENGTH, "authentication response");
int authType = PostgresWire.readInt32(in);
if (length > 8) {
byte[] extra = new byte[length - 8];
readFully(in, extra);
PostgresWire.readFully(in, extra);
}
return authType == 0;
}
@@ -859,7 +816,7 @@ public class PostgresProtocolHandler {
private static void sendPasswordMessage(OutputStream out, String password) throws IOException {
byte[] pwBytes = password.getBytes(StandardCharsets.UTF_8);
// 'p' + Int32(4 + pwLen + 1) + password + null
sendMessage(out, 'p', pwBytes, new byte[]{0});
PostgresWire.write(out, 'p', pwBytes, new byte[]{0});
}
private static String computeMd5Password(String password, String username, byte[] salt) {
@@ -902,19 +859,7 @@ public class PostgresProtocolHandler {
/** Reads the rest of a backend message whose type byte was {@code type}, returning it whole. */
private static byte[] readMessage(InputStream in, int type) throws IOException {
int length = checkedPacketLength(readInt32(in), 4, "backend message");
byte[] payload = new byte[length - 4];
readFully(in, payload);
// Reconstruct full message: type + length(4) + payload
byte[] full = new byte[1 + 4 + payload.length];
full[0] = (byte) type;
full[1] = (byte) ((length >> 24) & 0xFF);
full[2] = (byte) ((length >> 16) & 0xFF);
full[3] = (byte) ((length >> 8) & 0xFF);
full[4] = (byte) (length & 0xFF);
System.arraycopy(payload, 0, full, 5, payload.length);
return full;
return PostgresWire.frame(type, PostgresWire.readBody(in, 4, MAX_HANDSHAKE_PACKET_LENGTH, "backend message"));
}
// ── IAM session role ──────────────────────────────────────────────────────
@@ -929,7 +874,7 @@ public class PostgresProtocolHandler {
private static List<byte[]> assumeSessionRole(InputStream in, OutputStream out, String role)
throws IOException {
String sql = "SET SESSION AUTHORIZATION " + quoteIdentifier(role);
sendMessage(out, 'Q', sql.getBytes(StandardCharsets.UTF_8), new byte[]{0});
PostgresWire.write(out, 'Q', sql.getBytes(StandardCharsets.UTF_8), new byte[]{0});
out.flush();
return readUntilReadyForQuery(in);
}
@@ -1211,7 +1156,7 @@ public class PostgresProtocolHandler {
/** Runs {@code sql} as a simple query and returns every message up to ReadyForQuery. */
private static List<byte[]> runQuery(InputStream in, OutputStream out, String sql) throws IOException {
sendMessage(out, 'Q', sql.getBytes(StandardCharsets.UTF_8), new byte[]{0});
PostgresWire.write(out, 'Q', sql.getBytes(StandardCharsets.UTF_8), new byte[]{0});
out.flush();
List<byte[]> messages = new ArrayList<>();
while (true) {
@@ -1422,7 +1367,7 @@ public class PostgresProtocolHandler {
*/
private static List<byte[]> applySessionSettings(InputStream in, OutputStream out,
List<SessionSetting> settings) throws IOException {
sendMessage(out, 'Q', setConfigStatement(settings).getBytes(StandardCharsets.UTF_8), new byte[]{0});
PostgresWire.write(out, 'Q', setConfigStatement(settings).getBytes(StandardCharsets.UTF_8), new byte[]{0});
out.flush();
return readUntilReadyForQuery(in);
}
@@ -1531,20 +1476,8 @@ public class PostgresProtocolHandler {
/** The {@code field} of an ErrorResponse, such as 'C' for SQLSTATE, or {@code fallback}. */
static String errorField(byte[] errorResponse, char field, String fallback) {
int i = 5; // skip type byte and Int32 length
while (i < errorResponse.length && errorResponse[i] != 0) {
char fieldType = (char) errorResponse[i];
i++;
int start = i;
while (i < errorResponse.length && errorResponse[i] != 0) {
i++;
}
if (fieldType == field) {
return new String(errorResponse, start, i - start, StandardCharsets.UTF_8);
}
i++; // skip the field's null terminator
}
return fallback;
// The fields start after the type byte and the Int32 length.
return PostgresWire.parseFields(errorResponse, 5).getOrDefault(field, fallback);
}
/**
@@ -1632,9 +1565,8 @@ public class PostgresProtocolHandler {
return;
}
byte[] header = new byte[4];
readFully(from, header);
int length = ((header[0] & 0xFF) << 24) | ((header[1] & 0xFF) << 16)
| ((header[2] & 0xFF) << 8) | (header[3] & 0xFF);
PostgresWire.readFully(from, header);
int length = PostgresWire.int32(header, 0);
if (length < 4) {
return;
}
@@ -1643,7 +1575,7 @@ public class PostgresProtocolHandler {
if (type == 'S') {
// ParameterStatus is always small, so reading it whole to inspect costs nothing.
byte[] payload = new byte[remaining];
readFully(from, payload);
PostgresWire.readFully(from, payload);
String[] status = parameterStatus(payload, 0);
if (status != null && "session_authorization".equals(status[0])
&& !iamRole.equals(status[1])) {
@@ -1700,90 +1632,15 @@ public class PostgresProtocolHandler {
/** An ErrorResponse ('E') or NoticeResponse ('N') carrying severity, SQLSTATE and message. */
static byte[] responseMessage(char type, String severity, String sqlState, String message) {
byte[] sevBytes = severity.getBytes(StandardCharsets.UTF_8);
byte[] stateBytes = sqlState.getBytes(StandardCharsets.UTF_8);
byte[] msgBytes = message.getBytes(StandardCharsets.UTF_8);
// Fields: S=severity, C=sqlstate, M=message, then final null byte
ByteArrayOutputStream fields = new ByteArrayOutputStream();
fields.write('S'); fields.writeBytes(sevBytes); fields.write(0);
fields.write('C'); fields.writeBytes(stateBytes); fields.write(0);
fields.write('M'); fields.writeBytes(msgBytes); fields.write(0);
fields.write(0); // final null
ByteArrayOutputStream framed = new ByteArrayOutputStream();
try {
sendMessage(framed, type, fields.toByteArray());
} catch (IOException e) {
throw new IllegalStateException("writing to memory cannot fail", e);
}
return framed.toByteArray();
Map<Character, String> fields = new LinkedHashMap<>();
fields.put('S', severity);
fields.put('C', sqlState);
fields.put('M', message);
return PostgresWire.frame(type, PostgresWire.fields(fields));
}
// ── Wire helpers ──────────────────────────────────────────────────────────
private static void sendMessage(OutputStream out, char type, byte[]... parts) throws IOException {
int totalPayload = 0;
for (byte[] p : parts) {
totalPayload += p.length;
}
out.write((byte) type);
writeInt32(out, 4 + totalPayload); // length includes itself
for (byte[] p : parts) {
out.write(p);
}
}
private static byte[] intBytes(int value) {
return new byte[]{
(byte) ((value >> 24) & 0xFF),
(byte) ((value >> 16) & 0xFF),
(byte) ((value >> 8) & 0xFF),
(byte) (value & 0xFF)
};
}
private static void writeInt32(OutputStream out, int value) throws IOException {
out.write((value >> 24) & 0xFF);
out.write((value >> 16) & 0xFF);
out.write((value >> 8) & 0xFF);
out.write(value & 0xFF);
}
private static int readInt32(InputStream in) throws IOException {
int b0 = in.read();
int b1 = in.read();
int b2 = in.read();
int b3 = in.read();
if ((b0 | b1 | b2 | b3) < 0) {
throw new EOFException("Connection closed while reading Int32");
}
return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
}
private static int checkedPacketLength(int length, int minimum, String packetName) throws IOException {
if (length < minimum) {
throw new IOException("PostgreSQL " + packetName + " length is below the "
+ minimum + " byte minimum: " + length);
}
if (length > MAX_HANDSHAKE_PACKET_LENGTH) {
throw new IOException("PostgreSQL " + packetName + " length exceeds the "
+ MAX_HANDSHAKE_PACKET_LENGTH + " byte limit: " + length);
}
return length;
}
private static void readFully(InputStream in, byte[] buf) throws IOException {
int offset = 0;
while (offset < buf.length) {
int n = in.read(buf, offset, buf.length - offset);
if (n < 0) {
throw new EOFException("Connection closed while reading " + buf.length + " bytes");
}
offset += n;
}
}
private static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.redshift.proxy;
import io.github.hectorvent.floci.core.common.PostgresWire;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
@@ -95,14 +97,8 @@ public class PostgresWireDecoder {
char type = (char) typeByte;
byte[] lengthBytes = readFully(4);
int length = ((lengthBytes[0] & 0xFF) << 24)
| ((lengthBytes[1] & 0xFF) << 16)
| ((lengthBytes[2] & 0xFF) << 8)
| (lengthBytes[3] & 0xFF);
if (length < 4) {
throw new IOException("Invalid message length: " + length);
}
int length = PostgresWire.checkedLength(PostgresWire.int32(lengthBytes, 0), 4, Integer.MAX_VALUE,
"frontend message");
if (passthroughOut != null && (!inspectType.test(type) || length > MAX_MESSAGE_BYTES)) {
passthroughOut.write(typeByte);
@@ -126,10 +122,7 @@ public class PostgresWireDecoder {
return new FrontendMessage(type, null);
}
if (length > MAX_MESSAGE_BYTES) {
throw new IOException("Refusing PostgreSQL message of " + length
+ " bytes (limit " + MAX_MESSAGE_BYTES + ")");
}
PostgresWire.checkedLength(length, 4, MAX_MESSAGE_BYTES, "frontend message");
byte[] body = (length == 4) ? new byte[0] : readFully(length - 4);
betweenMessages = true;
@@ -190,23 +183,13 @@ public class PostgresWireDecoder {
}
ByteArrayOutputStream body = new ByteArrayOutputStream();
writeCString(body, statementName);
writeCString(body, rewrittenSql);
body.writeBytes(PostgresWire.cStringBytes(statementName));
body.writeBytes(PostgresWire.cStringBytes(rewrittenSql));
writeInt16(body, parameterTypeOids.size());
for (Integer oid : parameterTypeOids) {
writeInt32(body, Objects.requireNonNull(oid, "parameter type OID must not be null"));
body.writeBytes(PostgresWire.int32(Objects.requireNonNull(oid, "parameter type OID must not be null")));
}
byte[] bodyBytes = body.toByteArray();
int length = bodyBytes.length + 4;
byte[] packet = new byte[bodyBytes.length + 5];
packet[0] = 'P';
packet[1] = (byte) ((length >> 24) & 0xFF);
packet[2] = (byte) ((length >> 16) & 0xFF);
packet[3] = (byte) ((length >> 8) & 0xFF);
packet[4] = (byte) (length & 0xFF);
System.arraycopy(bodyBytes, 0, packet, 5, bodyBytes.length);
return packet;
return PostgresWire.frame('P', body.toByteArray());
}
private TargetMessage decodeTarget(FrontendMessage message, char expectedType) throws IOException {
@@ -234,35 +217,15 @@ public class PostgresWireDecoder {
return new BodyCursor(message.body());
}
private static void writeCString(ByteArrayOutputStream out, String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
out.writeBytes(bytes);
out.write(0);
}
private static void writeInt16(ByteArrayOutputStream out, int value) {
out.write((value >> 8) & 0xFF);
out.write(value & 0xFF);
}
private static void writeInt32(ByteArrayOutputStream out, int value) {
out.write((value >> 24) & 0xFF);
out.write((value >> 16) & 0xFF);
out.write((value >> 8) & 0xFF);
out.write(value & 0xFF);
}
/** Read exactly {@code n} bytes or throw {@link EOFException}. */
private byte[] readFully(int n) throws IOException {
byte[] buf = new byte[n];
int off = 0;
while (off < n) {
int read = in.read(buf, off, n - off);
if (read == -1) {
throw new EOFException("Unexpected EOF (expected " + n + " bytes, got " + off + ")");
}
off += read;
}
PostgresWire.readFully(in, buf);
return buf;
}
@@ -324,22 +287,7 @@ public class PostgresWireDecoder {
/** Encode an SQL string as a Simple Query ({@code 'Q'}) packet with a NUL-terminated body. */
public static byte[] encodeQuery(String sql) {
if (sql == null) {
sql = "";
}
byte[] sqlBytes = sql.getBytes(StandardCharsets.UTF_8);
int bodyLength = sqlBytes.length + 1;
int totalLength = 4 + bodyLength;
byte[] packet = new byte[1 + 4 + bodyLength];
packet[0] = 'Q';
packet[1] = (byte) ((totalLength >> 24) & 0xFF);
packet[2] = (byte) ((totalLength >> 16) & 0xFF);
packet[3] = (byte) ((totalLength >> 8) & 0xFF);
packet[4] = (byte) (totalLength & 0xFF);
System.arraycopy(sqlBytes, 0, packet, 5, sqlBytes.length);
packet[packet.length - 1] = 0x00;
return packet;
return PostgresWire.frame('Q', PostgresWire.cStringBytes(sql == null ? "" : sql));
}
/** A single PostgreSQL wire message from the client. */
@@ -366,18 +314,7 @@ public class PostgresWireDecoder {
if (body == null) {
throw new IllegalStateException("Message body was streamed to passthrough output and not retained");
}
int bodyLen = body.length;
int lengthField = 4 + bodyLen;
byte[] packet = new byte[1 + 4 + bodyLen];
packet[0] = (byte) type;
packet[1] = (byte) ((lengthField >> 24) & 0xFF);
packet[2] = (byte) ((lengthField >> 16) & 0xFF);
packet[3] = (byte) ((lengthField >> 8) & 0xFF);
packet[4] = (byte) (lengthField & 0xFF);
if (bodyLen > 0) {
System.arraycopy(body, 0, packet, 5, bodyLen);
}
return packet;
return PostgresWire.frame(type, body);
}
}