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

@@ -16,26 +16,56 @@ import software.amazon.awssdk.services.dsql.model.GetClusterResponse;
import software.amazon.awssdk.services.dsql.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dsql.model.ValidationException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
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.Map;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* Aurora DSQL's control plane through the real AWS SDK and its waiters: a cluster created,
* described, listed, tagged, protected from deletion, given a policy and deleted.
* Aurora DSQL through the real AWS SDK: the control plane and its waiters, cluster policies, and a JDBC connection
* to the cluster with a token from {@code DsqlUtilities}, the SDK's own signer. The connection goes
* to Floci's address with the cluster's endpoint as the TLS server name, which is how Floci picks
* the cluster, and the certificate is verified for that name against Floci's CA.
*
* Requires Docker (each cluster's database is a real PostgreSQL container).
*/
@DisplayName("Aurora DSQL")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class DsqlCompatTest {
private static final Region REGION = TestFixtures.region();
private static final Duration WAIT_TIMEOUT =
TestFixtures.isRealAws() ? Duration.ofMinutes(10) : Duration.ofSeconds(10);
/** A cluster is ACTIVE once its database answers: a container start on Floci, minutes on AWS. */
private static final Duration ACTIVE_TIMEOUT =
TestFixtures.isRealAws() ? Duration.ofMinutes(10) : Duration.ofMinutes(3);
private static final Duration DELETE_TIMEOUT =
TestFixtures.isRealAws() ? Duration.ofMinutes(10) : Duration.ofMinutes(1);
private static final String SERVER_NAME_PROPERTY = "dsqlServerName";
private static DsqlClient dsql;
private static String identifier;
private static String endpoint;
@BeforeAll
static void createCluster() {
@@ -46,7 +76,10 @@ class DsqlCompatTest {
identifier = created.identifier();
assertThat(created.status()).isEqualTo(ClusterStatus.CREATING);
dsql.waiter().waitUntilClusterActive(b -> b.identifier(identifier), w -> w.waitTimeout(WAIT_TIMEOUT));
GetClusterResponse active = dsql.waiter()
.waitUntilClusterActive(b -> b.identifier(identifier), w -> w.waitTimeout(ACTIVE_TIMEOUT))
.matched().response().orElseThrow();
endpoint = active.endpoint();
}
@AfterAll
@@ -55,7 +88,7 @@ class DsqlCompatTest {
return;
}
dsql.deleteCluster(b -> b.identifier(identifier));
dsql.waiter().waitUntilClusterNotExists(b -> b.identifier(identifier), w -> w.waitTimeout(WAIT_TIMEOUT));
dsql.waiter().waitUntilClusterNotExists(b -> b.identifier(identifier), w -> w.waitTimeout(DELETE_TIMEOUT));
dsql.close();
}
@@ -107,4 +140,121 @@ class DsqlCompatTest {
assertThatThrownBy(() -> dsql.getClusterPolicy(b -> b.identifier(identifier)))
.isInstanceOf(ResourceNotFoundException.class);
}
@Test
@Order(4)
void adminSignsInWithTheSdksToken() throws Exception {
String token = dsql.utilities().generateDbConnectAdminAuthToken(b -> b.hostname(endpoint).region(REGION));
try (Connection connection = connect("admin", token); Statement statement = connection.createStatement()) {
try (ResultSet row = statement.executeQuery("SELECT current_user, current_setting('transaction_isolation')")) {
assertThat(row.next()).isTrue();
assertThat(row.getString(1)).isEqualTo("admin");
assertThat(row.getString(2)).isEqualTo("repeatable read");
}
statement.execute("CREATE TABLE compat_orders (id int PRIMARY KEY, n int)");
statement.execute("INSERT INTO compat_orders VALUES (1, 7)");
try (ResultSet row = statement.executeQuery("SELECT n FROM compat_orders WHERE id = 1")) {
assertThat(row.next()).isTrue();
assertThat(row.getInt(1)).isEqualTo(7);
}
}
}
@Test
@Order(5)
void adminIsRefusedATokenForAnotherRole() {
String token = dsql.utilities().generateDbConnectAuthToken(b -> b.hostname(endpoint).region(REGION));
assertThatThrownBy(() -> connect("admin", token).close())
.isInstanceOf(SQLException.class)
.hasMessageContaining("unable to accept connection, access denied")
.hasMessageContaining("Wrong user to action mapping. user: admin, action: DbConnect");
}
private static Connection connect(String user, String token) throws SQLException {
Properties properties = new Properties();
properties.setProperty("user", user);
properties.setProperty("password", token);
properties.setProperty("sslmode", "require");
properties.setProperty("sslfactory", ServerNameSocketFactory.class.getName());
properties.setProperty(SERVER_NAME_PROPERTY, endpoint);
String host = TestFixtures.endpoint().getHost();
return DriverManager.getConnection("jdbc:postgresql://" + host + ":" + dsqlPort() + "/postgres", properties);
}
/** DSQL's port, 5432, unless the Floci under test serves it elsewhere (FLOCI_SERVICES_DSQL_PORT). */
private static int dsqlPort() {
String port = System.getenv("FLOCI_DSQL_PORT");
return port == null || port.isBlank() ? 5432 : Integer.parseInt(port);
}
/**
* Opens TLS to whatever pgjdbc dialled, naming the cluster's endpoint and verifying the
* certificate for it against Floci's CA. pgjdbc builds it from the connection's properties.
*/
public static final class ServerNameSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory delegate;
private final String serverName;
public ServerNameSocketFactory(Properties info) throws Exception {
this.serverName = info.getProperty(SERVER_NAME_PROPERTY);
HttpResponse<String> ca = TestFixtures.emulatorHttpClient().send(
HttpRequest.newBuilder(TestFixtures.endpoint().resolve("/_floci/ca.pem")).build(),
HttpResponse.BodyHandlers.ofString());
KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
trusted.load(null, null);
int index = 0;
for (Certificate certificate : CertificateFactory.getInstance("X.509").generateCertificates(
new ByteArrayInputStream(ca.body().getBytes(StandardCharsets.US_ASCII)))) {
trusted.setCertificateEntry("floci-" + index++, certificate);
}
TrustManagerFactory trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trust.init(trusted);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trust.getTrustManagers(), null);
this.delegate = context.getSocketFactory();
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
SSLSocket tls = (SSLSocket) delegate.createSocket(socket, serverName, port, autoClose);
SSLParameters parameters = tls.getSSLParameters();
parameters.setEndpointIdentificationAlgorithm("HTTPS");
tls.setSSLParameters(parameters);
return tls;
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket(String host, int port) throws IOException {
return delegate.createSocket(host, port);
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
return delegate.createSocket(host, port, localHost, localPort);
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return delegate.createSocket(host, port);
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
throws IOException {
return delegate.createSocket(address, port, localAddress, localPort);
}
}
}