feat(dsql): back clusters with an external PostgreSQL server (#8795)

Aurora DSQL clusters needed Docker, so DSQL did not work where Floci has no Docker socket, such as ECS on Fargate. An opt-in external backend (floci.services.dsql.backend=external) now puts each cluster in a database and prefixed roles of its own on a PostgreSQL 16 or later server that is already running. Floci marks what it creates and changes nothing else, derives the backend roles' SCRAM verifiers from a per-cluster secret, and bounds every call to the server. A deleted cluster's sessions end before its roles are listed and dropped, and for both backends shutdown waits for starts and deletions still running. The differences a shared server cannot hide are listed with their reasons in the DSQL docs.

Closes #8486
This commit is contained in:
Joaquín Gamboa authored and GitHub committed 2026-11-18 15:27:20 -04:00
1 parent 0effc633eb
commit 3ebd1bc38c
29 files changed
+3351 -114

No files matched your search

@@ -2138,6 +2138,45 @@ public interface EmulatorConfig {
/** Docker network for the database containers. Defaults to Floci's own network. */
Optional<String> dockerNetwork();
/**
* Where cluster databases live: {@code docker} runs a PostgreSQL container per cluster,
* {@code external} uses one PostgreSQL server that already runs, see {@link External}. Any
* other value fails Floci's start.
*/
@WithDefault("docker")
Backend backend();
/** The PostgreSQL server of the {@code external} backend. */
External external();
/** Kinds of backend {@link #backend()} accepts. */
enum Backend { DOCKER, EXTERNAL }
interface External {
/** Host of the PostgreSQL server. Required with the {@code external} backend. */
Optional<String> host();
@WithDefault("5432")
int port();
/**
* Maintenance database Floci connects to in order to create, and later drop, each
* cluster's own database and roles.
*/
@WithDefault("postgres")
String database();
/**
* Role Floci connects as. It must be a superuser: Floci installs event triggers and
* creates each cluster's database and roles.
*/
@WithDefault("postgres")
String username();
/** Password of {@link #username()}; none when the server trusts the connection. */
Optional<String> password();
}
}
interface RdsDataServiceConfig {
@@ -32,6 +32,14 @@ public final class PostgresWire {
return "E'" + value.replace("\\", "\\\\").replace("'", "''") + "'";
}
/**
* An identifier, always quoted, with any double quote doubled, so no name needs checking
* against PostgreSQL's reserved words and its case is kept.
*/
public static String quoteIdentifier(String identifier) {
return '"' + identifier.replace("\"", "\"\"") + '"';
}
/** A message after the startup: its type byte and its body, without the length. */
public record Message(byte type, byte[] body) {
}
@@ -11,6 +11,10 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -26,6 +30,11 @@ import java.util.function.Consumer;
public class DsqlDataPlane {
private static final Logger LOG = Logger.getLogger(DsqlDataPlane.class);
/**
* How long Floci's shutdown waits for the starts and deletions still running: longer than a
* start waits for its database to answer.
*/
static final Duration WORK_AT_SHUTDOWN = Duration.ofMinutes(3);
private final boolean mock;
private final boolean memoryStorage;
@@ -33,9 +42,13 @@ public class DsqlDataPlane {
private final DsqlEndpoint endpoint;
private final Map<String, DsqlCluster> running = new ConcurrentHashMap<>();
private final Set<String> wanted = ConcurrentHashMap.newKeySet();
// The starts and deletions still running, which a shutdown waits for.
private final Set<Thread> working = 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();
// Set under routes once Floci stops, after which no start registers a route.
private boolean stopping;
@Inject
public DsqlDataPlane(EmulatorConfig config, DsqlDatabases databases, DsqlEndpoint endpoint) {
@@ -51,44 +64,76 @@ public class DsqlDataPlane {
onReady.accept(true);
return;
}
String arn = cluster.getArn();
wanted.add(arn);
Thread.ofVirtual().name("dsql-start-" + cluster.getIdentifier()).start(() -> {
DsqlDatabases.Backend backend;
wanted.add(cluster.getArn());
inBackground("dsql-start-" + cluster.getIdentifier(), () -> start(cluster, onReady));
}
/** Runs {@code work} on a thread of its own, which a shutdown waits for. */
private void inBackground(String name, Runnable work) {
Thread thread = Thread.ofVirtual().name(name).unstarted(() -> {
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;
work.run();
} finally {
working.remove(Thread.currentThread());
}
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());
}
});
working.add(thread);
thread.start();
}
private void start(DsqlCluster cluster, Consumer<Boolean> onReady) {
String arn = cluster.getArn();
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 shutDown;
boolean deleted;
boolean ready = false;
synchronized (routes) {
shutDown = stopping;
deleted = !wanted.contains(arn);
if (!deleted && !shutDown) {
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);
}
if (shutDown) {
// Floci stopped while it started: it goes as the running clusters went, and its status is
// left as it was, so the next start of Floci starts it again.
stopAtShutdown(cluster);
return;
}
if (!ready) {
// Deleted while it started, or unreachable: no database is left running for it.
if (deleted) {
drop(cluster);
} else {
stop(cluster, false);
}
onReady.accept(ready);
});
}
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.
* Stops the cluster's database and drops its data, then runs {@code onGone}. The roles the
* deletion drops are set on the cluster and handed to {@code persistPendingRoles} to be saved
* before anything is dropped, so a deletion finished later drops the same ones. When they cannot
* be found or removed, the cluster stays as it is, and the next start of Floci finishes its
* deletion; unless the cluster {@code failed} and its backend lets that deletion finish anyway,
* as AWS deletes a FAILED cluster, with a warning naming what may remain on the server.
*/
public void deprovision(DsqlCluster cluster, Runnable onGone) {
public void deprovision(DsqlCluster cluster, boolean failed, Consumer<List<String>> persistPendingRoles,
Runnable onGone) {
if (mock) {
onGone.run();
return;
@@ -98,13 +143,53 @@ public class DsqlDataPlane {
running.remove(cluster.getArn());
endpoint.unregister(cluster);
}
Thread.ofVirtual().name("dsql-stop-" + cluster.getIdentifier()).start(() -> {
if (stop(cluster, true)) {
inBackground("dsql-stop-" + cluster.getIdentifier(), () -> {
List<String> roles;
try {
roles = databases.rolesToDrop(cluster);
} catch (SQLException | RuntimeException e) {
LOG.warnv(e, "The roles of DSQL cluster {0} could not be listed", cluster.getIdentifier());
if (failed && finishesAnyway(cluster)) {
onGone.run();
}
return;
}
if (!roles.isEmpty()) {
cluster.setPendingBackendRoles(roles);
persistPendingRoles.accept(roles);
}
if (stop(cluster, true) || (failed && finishesAnyway(cluster))) {
onGone.run();
}
});
}
/** Whether a FAILED cluster's deletion finishes although its server was not cleaned up. */
private boolean finishesAnyway(DsqlCluster cluster) {
return databases.leftoversOfFailed(cluster).map(leftovers -> {
LOG.warnv("DSQL cluster {0} failed and its server could not be cleaned up; it is deleted anyway,"
+ " and its {1} may remain on the server", cluster.getIdentifier(), leftovers);
return true;
}).orElse(false);
}
/**
* Drops the cluster's database and roles, best effort, for a cluster that goes without a deletion
* of its own: one deleted while it started, or one of in-memory storage when Floci stops. With
* its roles unlisted, the backend drops the ones it always knows.
*/
private void drop(DsqlCluster cluster) {
try {
List<String> roles = databases.rolesToDrop(cluster);
if (!roles.isEmpty()) {
cluster.setPendingBackendRoles(roles);
}
} catch (SQLException | RuntimeException e) {
LOG.warnv(e, "The roles of DSQL cluster {0} could not be listed", cluster.getIdentifier());
}
stop(cluster, true);
}
private boolean stop(DsqlCluster cluster, boolean dropData) {
try {
databases.stop(cluster, dropData);
@@ -117,16 +202,46 @@ public class DsqlDataPlane {
/**
* 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.
* in memory, where the clusters themselves do not survive. A cluster still starting is never
* served once the endpoint has stopped; its start is waited for, and its database then goes as
* the others do.
*/
void onStop(@Observes ShutdownEvent ignored) {
if (mock) {
return;
}
synchronized (routes) {
stopping = true;
}
endpoint.stop();
for (DsqlCluster cluster : running.values()) {
stop(cluster, memoryStorage);
stopAtShutdown(cluster);
}
running.clear();
awaitWork();
}
private void stopAtShutdown(DsqlCluster cluster) {
if (memoryStorage) {
drop(cluster);
} else {
stop(cluster, false);
}
}
private void awaitWork() {
Instant deadline = Instant.now().plus(WORK_AT_SHUTDOWN);
for (Thread thread : List.copyOf(working)) {
Duration left = Duration.between(Instant.now(), deadline);
try {
if (left.isNegative() || !thread.join(left)) {
LOG.warnv("{0} did not finish before Floci stopped; the database of its DSQL cluster may remain",
thread.getName());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
}
@@ -150,7 +150,8 @@ public class DsqlService implements Resettable {
}
clusters.put(key(region, identifier), cluster);
LOG.infov("Created DSQL cluster {0} in {1}", identifier, region);
dataPlane.provision(cluster, ready -> markReady(accountId, region, identifier, ready));
dataPlane.provision(cluster,
ready -> markReady(accountId, region, identifier, cluster.getBackendSecret(), ready));
return cluster;
}
}
@@ -218,6 +219,7 @@ public class DsqlService implements Resettable {
public DsqlCluster deleteCluster(String region, String identifier) {
DsqlCluster cluster = getCluster(region, identifier);
String accountId = regionResolver.getAccountId();
boolean failed;
synchronized (lockFor(cluster.getArn())) {
if (cluster.isDeletionProtectionEnabled()) {
throw new AwsException("ValidationException", "Can't delete cluster: Deletion protection is enabled."
@@ -227,10 +229,11 @@ public class DsqlService implements Resettable {
if (DELETING.equals(cluster.getStatus())) {
return cluster;
}
failed = FAILED.equals(cluster.getStatus());
cluster.setStatus(DELETING);
clusters.put(key(region, identifier), cluster);
}
dataPlane.deprovision(cluster, () -> {
dataPlane.deprovision(cluster, failed, roles -> savePendingRoles(accountId, region, identifier, roles), () -> {
clusters.deleteForAccount(accountId, key(region, identifier));
locks.remove(cluster.getArn());
LOG.infov("Deleted DSQL cluster {0} in {1}", identifier, region);
@@ -376,14 +379,17 @@ public class DsqlService implements Resettable {
String region = cluster.getRegion();
String identifier = cluster.getIdentifier();
if (DELETING.equals(cluster.getStatus())) {
dataPlane.deprovision(cluster, () -> {
// Whether it had FAILED is not kept, so its deletion waits for the server as any other.
dataPlane.deprovision(cluster, false,
roles -> savePendingRoles(accountId, region, identifier, roles), () -> {
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));
dataPlane.provision(cluster,
ready -> markReady(accountId, region, identifier, cluster.getBackendSecret(), ready));
}
}
}
@@ -391,7 +397,8 @@ public class DsqlService implements Resettable {
@Override
public void clear() {
for (DsqlCluster cluster : clusters.scanAllAccounts()) {
dataPlane.deprovision(cluster, () -> { });
// The clusters go with the storage, so their roles are not saved.
dataPlane.deprovision(cluster, false, roles -> { }, () -> { });
}
clusters.clear();
locks.clear();
@@ -399,12 +406,27 @@ public class DsqlService implements Resettable {
// ── Internals ─────────────────────────────────────────────────────────────
/** Saves the roles a deletion is about to drop, with the cluster still DELETING. */
private void savePendingRoles(String accountId, String region, String identifier, List<String> roles) {
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.setPendingBackendRoles(List.copyOf(roles));
clusters.putForAccount(accountId, key(region, identifier), cluster);
}
});
}
/**
* 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) {
private void markReady(String accountId, String region, String identifier, String backendSecret,
boolean ready) {
clusters.getForAccount(accountId, key(region, identifier)).ifPresent(found -> {
synchronized (lockFor(found.getArn())) {
DsqlCluster cluster = clusters.getForAccount(accountId, key(region, identifier)).orElse(null);
@@ -412,6 +434,10 @@ public class DsqlService implements Resettable {
return;
}
cluster.setDatabaseReady(ready);
// The secret the backend generated as it started, kept so its passwords stay the same.
if (cluster.getBackendSecret() == null) {
cluster.setBackendSecret(backendSecret);
}
if (CREATING.equals(cluster.getStatus()) || (!ready && PENDING_SETUP.equals(cluster.getStatus()))) {
cluster.setStatus(ready ? ACTIVE : FAILED);
}
@@ -9,8 +9,27 @@ public interface BackendCredentials {
public String passwordFor(String backendRole) {
return null;
}
@Override
public String verifierFor(String backendRole) {
return null;
}
};
/**
* Whether the database stores only SCRAM-SHA-256 verifiers, so a login answers SCRAM alone and
* refuses a cleartext or MD5 request as a downgrade.
*/
default boolean scramOnly() {
return false;
}
/** The password Floci logs in with as a backend role, or null when the database wants none. */
String passwordFor(String backendRole);
/**
* The SCRAM-SHA-256 verifier of {@link #passwordFor}, as PostgreSQL stores it, for setting the
* password without the password itself reaching the server's logs; null when it wants none.
*/
String verifierFor(String backendRole);
}
@@ -16,7 +16,6 @@ import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
@@ -118,43 +117,39 @@ public class DockerDsqlBackend implements DsqlBackend {
}
}
@Override
public List<String> rolesToDrop(DsqlCluster cluster) {
return List.of();
}
private String containerName(DsqlCluster cluster) {
return ContainerStorageHelper.dockerName(config, "dsql-" + cluster.getIdentifier());
}
private static void awaitReady(DsqlDatabases.Backend backend) throws SQLException {
awaitReady(() -> DsqlDatabases.superuser(backend), READY_TIMEOUT);
}
/** Opens a connection to the database {@link #awaitReady(Connector, Duration)} waits for. */
@FunctionalInterface
public interface Connector {
Connection open() throws SQLException;
}
/**
* Runs {@code SELECT 1} through a connection from {@code connector} every 250 ms until it
* succeeds or {@code timeout} has passed, as a PostgreSQL that is still starting refuses
* connections. Public for the tests' throwaway PostgreSQL servers, which wait the same way.
* Waits up to 90 seconds, trying every 250 ms, until the container's PostgreSQL lets the
* superuser in and answers {@code SELECT 1}. Any failure is tried again, a refused login
* included: the container trusts its connections, so nothing about a login is configured
* that waiting could not outlast.
*/
public static void awaitReady(Connector connector, Duration timeout) throws SQLException {
Instant deadline = Instant.now().plus(timeout);
SQLException last = null;
while (Instant.now().isBefore(deadline)) {
try (Connection connection = connector.open(); 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);
}
private static void awaitReady(DsqlDatabases.Backend backend) throws SQLException {
DsqlDatabases.awaitConnection(() -> answering(DsqlDatabases.superuser(backend)), READY_TIMEOUT,
DsqlDatabases.READY_INTERVAL, false, "The database").close();
}
/** {@code connection} once it answers {@code SELECT 1}; closed, and the failure thrown, if not. */
private static Connection answering(Connection connection) throws SQLException {
try (Statement statement = connection.createStatement()) {
statement.execute("SELECT 1");
return connection;
} catch (SQLException e) {
try {
connection.close();
} catch (SQLException closing) {
e.addSuppressed(closing);
}
throw e;
}
throw new SQLException("The database did not start within " + timeout.toSeconds() + " s", last);
}
private static void bootstrap(DsqlDatabases.Backend backend) throws SQLException {
@@ -4,6 +4,8 @@ import io.floci.aws.services.dsql.model.DsqlCluster;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
/** Where a cluster's database lives, and how it is brought up and taken down. */
public interface DsqlBackend {
@@ -11,6 +13,17 @@ public interface DsqlBackend {
/** Starts the cluster's database, waits until it answers, and sets it up as DSQL's database is. */
DsqlDatabases.Backend start(DsqlCluster cluster) throws SQLException, IOException;
/** The backend roles that belong to the cluster alone and go with it. */
List<String> rolesToDrop(DsqlCluster cluster) throws SQLException;
/** Stops the cluster's database and, with {@code dropData}, removes its data. */
void stop(DsqlCluster cluster, boolean dropData);
/**
* What may stay behind when a FAILED cluster's deletion cannot clean up, if the backend lets
* such a deletion finish anyway; empty when the deletion waits and is retried instead.
*/
default Optional<String> leftoversOfFailed(DsqlCluster cluster) {
return Optional.empty();
}
}
@@ -1,5 +1,7 @@
package io.floci.aws.services.dsql.dataplane;
import io.floci.aws.core.common.PostgresWire;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
@@ -34,11 +36,11 @@ final class DsqlBootstrap {
+ rolePrefix + ", not \"" + connectRole + "\"");
}
return template()
.replace("{{database}}", identifier(database))
.replace("{{database}}", PostgresWire.quoteIdentifier(database))
.replace("{{owner_literal}}", literal(owner))
.replace("{{owner}}", identifier(owner))
.replace("{{owner}}", PostgresWire.quoteIdentifier(owner))
.replace("{{admin_literal}}", literal(admin))
.replace("{{admin}}", identifier(admin))
.replace("{{admin}}", PostgresWire.quoteIdentifier(admin))
.replace("{{connect_role_literal}}", literal(connectRole))
.replace("{{role_prefix}}", literal(rolePrefix))
.replace("{{external}}", Boolean.toString(external));
@@ -55,11 +57,6 @@ final class DsqlBootstrap {
}
}
/** Always quoted, so no name needs checking against PostgreSQL's reserved words. */
private static String identifier(String name) {
return '"' + name.replace("\"", "\"\"") + '"';
}
private static String literal(String value) {
return "'" + value.replace("'", "''") + "'";
}
@@ -1,5 +1,6 @@
package io.floci.aws.services.dsql.dataplane;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.services.dsql.model.DsqlCluster;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -8,6 +9,10 @@ import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
/**
* The database behind each cluster. Which one it is, a PostgreSQL container per cluster or a
@@ -39,8 +44,11 @@ public class DsqlDatabases {
}
@Inject
public DsqlDatabases(DockerDsqlBackend docker) {
this.strategy = docker;
public DsqlDatabases(DockerDsqlBackend docker, ExternalDsqlBackend external, EmulatorConfig config) {
this.strategy = switch (config.services().dsql().backend()) {
case DOCKER -> docker;
case EXTERNAL -> external;
};
}
/** Starts the cluster's database, waits until it answers, and sets it up as DSQL's database is. */
@@ -48,11 +56,70 @@ public class DsqlDatabases {
return strategy.start(cluster);
}
/** The backend roles that belong to the cluster alone and go with it. */
public List<String> rolesToDrop(DsqlCluster cluster) throws SQLException {
return strategy.rolesToDrop(cluster);
}
/** Stops the cluster's database and, with {@code dropData}, removes its data. */
public void stop(DsqlCluster cluster, boolean dropData) {
strategy.stop(cluster, dropData);
}
/**
* What may stay behind when a FAILED cluster's deletion cannot clean up, if the deletion
* finishes anyway; empty when it waits and is retried instead.
*/
public Optional<String> leftoversOfFailed(DsqlCluster cluster) {
return strategy.leftoversOfFailed(cluster);
}
/** How often {@link #awaitConnection} tries again. */
public static final Duration READY_INTERVAL = Duration.ofMillis(250);
/** Opens a connection to a server {@link #awaitConnection} waits for. */
@FunctionalInterface
public interface Connector {
Connection open() throws SQLException;
}
/**
* A connection from {@code connector}, tried again every {@code interval} until {@code timeout}
* has passed, so a server still starting is waited for. It is tried at least once. With
* {@code refusedLoginIsFinal}, a refused login (SQLSTATE class 28) is thrown at once, as waiting
* would not change a wrong password; otherwise it is tried again like any other failure. Past
* the deadline, the last failure is thrown, with its SQLSTATE, under {@code what}: for example
* "The database did not let Floci in within 90 s: ...". Public for the tests' throwaway
* PostgreSQL servers, which wait the same way.
*/
public static Connection awaitConnection(Connector connector, Duration timeout, Duration interval,
boolean refusedLoginIsFinal, String what) throws SQLException {
Instant deadline = Instant.now().plus(timeout);
while (true) {
SQLException last;
try {
return connector.open();
} catch (SQLException e) {
if (refusedLoginIsFinal && e.getSQLState() != null && e.getSQLState().startsWith("28")) {
throw e;
}
last = e;
}
if (Instant.now().plus(interval).isAfter(deadline)) {
throw new SQLException(what + " did not let Floci in within " + timeout.toSeconds() + " s: "
+ last.getMessage(), last.getSQLState(), last);
}
try {
Thread.sleep(interval.toMillis());
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
SQLException stopped = new SQLException("Interrupted while waiting: " + what, interrupted);
stopped.addSuppressed(last);
throw stopped;
}
}
}
/** A superuser connection to the cluster's database, for what the endpoint checks itself. */
public static Connection superuser(Backend backend) throws SQLException {
String password = backend.superuserPassword() == null ? "" : backend.superuserPassword();
@@ -39,6 +39,7 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@@ -430,18 +431,89 @@ public class DsqlEndpoint {
* superuser is never one, as DSQL never lets {@code dbowner} in.
*/
private static boolean mapped(DsqlDatabases.Backend backend, String principal, String role) throws SQLException {
// The view names roles as clients know them; the backend role is the one the session logs in as.
try (Connection connection = DsqlDatabases.superuser(backend);
PreparedStatement query = connection.prepareStatement("SELECT 1 FROM sys.iam_pg_role_mappings m"
+ " JOIN pg_roles r ON r.oid = m.pg_role_oid WHERE m.arn = ? AND m.pg_role_name = ?"
+ " AND NOT r.rolsuper")) {
+ " AND r.rolname = ? AND NOT r.rolsuper")) {
query.setString(1, principal);
query.setString(2, role);
query.setString(3, backend.roleNames().toBackend(role));
try (ResultSet rows = query.executeQuery()) {
return rows.next();
}
}
}
/**
* Gets the cluster's database ready for a session to log in as {@code backendRole}: where the
* database wants passwords, the role's password is set again, so a password changed on the
* server does not lock Floci out. False, with the cause logged, when the database could not be
* asked; a role that does not exist or cannot log in is left for the database to refuse.
*/
boolean prepareLogin(DsqlDatabases.Backend backend, String backendRole) {
if (backend.credentials().passwordFor(backendRole) == null) {
return true;
}
try {
setLoginPassword(backend, backendRole);
return true;
} catch (SQLException e) {
LOG.warnv("Could not set the password of a DSQL cluster role before a login: {0}", e.getMessage());
return false;
}
}
/**
* Sets the password of {@code backendRole}, as its SCRAM verifier so the password itself never
* reaches the server, when the role exists, can log in, is no superuser and has another
* password; true when it did. PostgreSQL aborts one of two concurrent updates of a role with
* "tuple concurrently updated", even to the same value, so a password already set is left as it
* is, and a change is made under an advisory lock on the role, checked again once it is held.
*/
static boolean setLoginPassword(DsqlDatabases.Backend backend, String backendRole) throws SQLException {
String verifier = backend.credentials().verifierFor(backendRole);
if (verifier == null) {
return false;
}
try (Connection connection = DsqlDatabases.superuser(backend)) {
if (!needsPassword(connection, backendRole, verifier)) {
return false;
}
connection.setAutoCommit(false);
try {
try (PreparedStatement lock = connection.prepareStatement("SELECT pg_advisory_xact_lock(hashtext(?))")) {
lock.setString(1, backendRole);
lock.execute();
}
boolean changed = needsPassword(connection, backendRole, verifier);
if (changed) {
try (Statement statement = connection.createStatement()) {
statement.execute("ALTER ROLE " + PostgresWire.quoteIdentifier(backendRole) + " PASSWORD "
+ PostgresWire.quoteLiteral(verifier));
}
}
connection.commit();
return changed;
} catch (SQLException e) {
connection.rollback();
throw e;
}
}
}
/** Whether {@code backendRole} exists, can log in, is no superuser, and has a password other than {@code verifier}. */
private static boolean needsPassword(Connection connection, String backendRole, String verifier)
throws SQLException {
try (PreparedStatement query = connection.prepareStatement("SELECT rolpassword FROM pg_authid"
+ " WHERE rolname = ? AND rolcanlogin AND NOT rolsuper")) {
query.setString(1, backendRole);
try (ResultSet rows = query.executeQuery()) {
return rows.next() && !verifier.equals(rows.getString(1));
}
}
}
/**
* Records who the session on backend process {@code pid} is, for {@code sys.iam_session_user()}
* and {@code sys.current_session_id()}. The superuser writes it into a table no role of the
@@ -1,8 +1,10 @@
package io.floci.aws.services.dsql.dataplane;
import io.floci.aws.config.TlsProxyServer;
import io.floci.aws.core.common.BackendAuthenticator;
import io.floci.aws.core.common.PostgresWire;
import io.floci.aws.services.dsql.DsqlIdentifiers;
import org.jboss.logging.Logger;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SNIMatcher;
@@ -13,6 +15,7 @@ import javax.net.ssl.StandardConstants;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -23,7 +26,6 @@ import java.time.Duration;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
@@ -31,6 +33,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
@@ -45,6 +48,8 @@ import java.util.stream.Stream;
*/
final class DsqlSession {
private static final Logger LOG = Logger.getLogger(DsqlSession.class);
static final Duration CONNECTION_LIFETIME = Duration.ofHours(1);
// DSQL's (measured): a startup packet of 10,000 bytes or more, and a client message over 10 MiB,
// are refused with a FATAL before the connection closes. What the database sends is not DSQL's
@@ -97,6 +102,8 @@ final class DsqlSession {
private volatile byte[] cancelKeyData;
private volatile boolean cancelledForAge;
private volatile char transactionStatus = 'I';
// How the client's role names read in the database: the same in a database of the cluster's own.
private volatile RoleNames roleNames = RoleNames.IDENTITY;
DsqlSession(Socket socket, DsqlEndpoint endpoint) {
this.socket = socket;
@@ -224,6 +231,16 @@ final class DsqlSession {
}
DsqlDatabases.Backend target = admission.route().backend();
// The client's role, admitted by its own name, logs in to the database by the backend's.
String backendUser = target.roleNames().toBackend(user);
String backendPassword = target.credentials().passwordFor(backendUser);
if (!endpoint.prepareLogin(target, backendUser)) {
refuse(out, "08006", ACCESS_DENIED, null);
return;
}
roleNames = target.roleNames();
BackendAuthenticator authenticator = backendPassword == null ? null
: new BackendAuthenticator(backendUser, backendPassword, target.credentials().scramOnly());
endpoint.opened(admission.route(), tls);
Socket backend = new Socket();
try (backend) {
@@ -232,12 +249,8 @@ final class DsqlSession {
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", target.database());
Map<String, String> backendStartup = backendStartup(startupParameters, optionSettings, backendUser,
target.database());
principalArn = admission.principalArn();
backendOut.write(PostgresWire.startupMessage(backendStartup));
backendOut.flush();
@@ -247,7 +260,7 @@ final class DsqlSession {
databaseSocket = backend;
Thread toClient = Thread.ofVirtual().name("dsql-backend-" + sessionId)
.start(() -> relayToClient(backendIn, out, admission.route(), tls));
.start(() -> relayToClient(backendIn, out, admission.route(), tls, authenticator));
Thread lifetime = Thread.ofVirtual().name("dsql-lifetime-" + sessionId).start(() -> {
try {
Thread.sleep(CONNECTION_LIFETIME.toMillis());
@@ -313,17 +326,14 @@ final class DsqlSession {
PostgresWire.write(backendOut, 'Q', PostgresWire.cStringBytes(rewriteSimpleQuery(query)));
}
case 'P' -> {
PostgresWire.CString name = PostgresWire.cString(message.body(), 0);
PostgresWire.CString query = PostgresWire.cString(message.body(), name.next());
DsqlStatements.Query rewritten = DsqlStatements.rewriteQuery(query.value());
ParseRewrite parse = rewriteParse(message, roleNames);
DsqlStatements.Query rewritten = parse.query();
String tag = rewritten.overridesTags() && rewritten.commandTags().size() == 1
? rewritten.commandTags().get(0) : null;
synchronized (batches) {
extendedBatch().parses.addLast(new Named(name.value(), tag));
extendedBatch().parses.addLast(new Named(parse.name(), tag));
}
PostgresWire.write(backendOut, 'P', PostgresWire.cStringBytes(name.value()),
PostgresWire.cStringBytes(rewritten.sql()),
Arrays.copyOfRange(message.body(), query.next(), message.body().length));
PostgresWire.write(backendOut, parse.message());
}
case 'B' -> {
PostgresWire.CString portal = PostgresWire.cString(message.body(), 0);
@@ -529,7 +539,7 @@ final class DsqlSession {
* ReadyForQuery ends: the extended-protocol messages sent since the last Sync, if any.
*/
private String rewriteSimpleQuery(String query) {
DsqlStatements.Query rewritten = DsqlStatements.rewriteQuery(query);
DsqlStatements.Query rewritten = DsqlStatements.rewriteQuery(query, roleNames);
synchronized (batches) {
Batch batch = endBatch();
rewritten.commandTags().forEach(tag -> batch.results.addLast(new Named(null, tag)));
@@ -537,6 +547,23 @@ final class DsqlSession {
return rewritten.sql();
}
/** A Parse message as the database gets it: its statement's name, its query rewritten, and the message. */
record ParseRewrite(String name, DsqlStatements.Query query, PostgresWire.Message message) {
}
/** {@code parse} with its query in the database's syntax and role names, the rest of it as it was. */
static ParseRewrite rewriteParse(PostgresWire.Message parse, RoleNames roleNames) {
byte[] body = parse.body();
PostgresWire.CString name = PostgresWire.cString(body, 0);
PostgresWire.CString query = PostgresWire.cString(body, name.next());
DsqlStatements.Query rewritten = DsqlStatements.rewriteQuery(query.value(), roleNames);
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.writeBytes(PostgresWire.cStringBytes(name.value()));
out.writeBytes(PostgresWire.cStringBytes(rewritten.sql()));
out.write(body, query.next(), body.length - query.next());
return new ParseRewrite(name.value(), rewritten, new PostgresWire.Message((byte) 'P', out.toByteArray()));
}
/**
* The batch a Query, Sync or FunctionCall ends, the extended-protocol messages since the last
* Sync included, which its ReadyForQuery answers. Called holding {@code batches}.
@@ -620,6 +647,23 @@ final class DsqlSession {
.filter(name -> name.contains(".")).findFirst().orElse(null);
}
/**
* The startup the database gets: the client's parameters, with only the {@code options} settings
* DSQL counts, logging in as {@code backendUser} to {@code database}, the cluster's own.
*/
static Map<String, String> backendStartup(Map<String, String> startupParameters,
Map<String, String> optionSettings, String backendUser,
String database) {
Map<String, String> backendStartup = new LinkedHashMap<>(startupParameters);
backendStartup.remove("options");
if (!optionSettings.isEmpty()) {
backendStartup.put("options", backendOptions(optionSettings));
}
backendStartup.put("user", backendUser);
backendStartup.put("database", database);
return backendStartup;
}
/** {@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<>();
@@ -627,17 +671,53 @@ final class DsqlSession {
return String.join(" ", words);
}
private void relayToClient(InputStream backendIn, OutputStream out, DsqlEndpoint.Route route, Socket client) {
/**
* Relays what the database sends to the client. Until its ReadyForQuery, the database's answers
* to the startup are held back, and a password it asks for is answered by {@code authenticator}
* (null where the database wants none) without the client seeing any of it.
*/
private void relayToClient(InputStream backendIn, OutputStream out, DsqlEndpoint.Route route, Socket client,
BackendAuthenticator authenticator) {
try {
List<PostgresWire.Message> startup = new ArrayList<>();
boolean started = false;
boolean authenticating = false;
while (true) {
PostgresWire.Message message = PostgresWire.read(backendIn, MAX_DATABASE_MESSAGE, "message");
if (!started) {
// DSQL refuses a connection instead of authenticating it, so what the database
// answers the startup waits for its ReadyForQuery, and a refusal takes its place.
switch (message.type()) {
case 'R' -> {
boolean ok = message.body().length >= 4 && PostgresWire.int32(message.body(), 0) == 0;
if (ok) {
// An unfinished SCRAM exchange means the server never proved it knows the password.
if (authenticator != null && !answerAuthentication(message, authenticator)) {
refuse(out, "08006", ACCESS_DENIED, null);
closeQuietly(client);
return;
}
authenticating = false;
startup.add(message);
continue;
}
authenticating = true;
if (!answerAuthentication(message, authenticator)) {
refuse(out, "08006", ACCESS_DENIED, null);
closeQuietly(client);
return;
}
continue;
}
case 'E' -> {
if (authenticating) {
// The database's own words would name the backend role.
LOG.warnv("DSQL session {0} could not log in to the cluster database: {1}",
sessionId, PostgresWire.parseFields(message.body(), 0).get('M'));
refuse(out, "08006", ACCESS_DENIED, null);
closeQuietly(client);
return;
}
startup.clear();
message = new PostgresWire.Message(message.type(), withSessionId(message.body()));
}
@@ -749,6 +829,32 @@ final class DsqlSession {
}
}
/**
* Answers the database's request for a password, never seen by the client; false, with the
* cause logged but no secret, when it cannot be answered.
*/
private boolean answerAuthentication(PostgresWire.Message request, BackendAuthenticator authenticator)
throws IOException {
if (authenticator == null) {
LOG.warnv("DSQL session {0}: the cluster database asks for a password Floci does not have", sessionId);
return false;
}
Optional<PostgresWire.Message> answer;
try {
answer = authenticator.answer(request);
} catch (IOException e) {
LOG.warnv("DSQL session {0} could not log in to the cluster database: {1}", sessionId, e.getMessage());
return false;
}
if (answer.isPresent()) {
synchronized (databaseWrites) {
PostgresWire.write(databaseOut, answer.get());
databaseOut.flush();
}
}
return true;
}
/**
* An error or notice as DSQL words it (measured on AWS). An optimistic concurrency conflict is
* DSQL's OC000. An error carries no source location, PostgreSQL's own included, while a notice
@@ -0,0 +1,662 @@
package io.floci.aws.services.dsql.dataplane;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.BackendAuthenticator;
import io.floci.aws.core.common.Digests;
import io.floci.aws.core.common.PostgresWire;
import io.floci.aws.services.dsql.model.DsqlCluster;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
/**
* Each cluster's database on one PostgreSQL server that already runs, with no Docker. A cluster has
* a database of its own, {@code dsql_<id>}, owned by the NOLOGIN role {@code dsqlowner_<id>}, and
* its backend roles carry the prefix {@code d<id>_}, starting with its admin. PUBLIC may not connect
* to the database; its roles connect as members of the NOLOGIN role {@code dsqlconnect_<id>}, which
* the bootstrap grants CONNECT and makes each recorded role a member of. Floci connects as the
* configured user, which must be able to create databases and roles, and gives each backend role a
* password derived from the cluster's secret, as the server is not assumed to trust Floci. The
* server must run PostgreSQL 16 or later, whose CREATEROLE keeps each admin to its own roles.
* The database, owner, admin and connect role carry a comment naming the cluster's ARN, so Floci
* never adopts, alters or drops a same-named object it did not create for the cluster.
*/
@ApplicationScoped
public class ExternalDsqlBackend implements DsqlBackend {
private static final Logger LOG = Logger.getLogger(ExternalDsqlBackend.class);
private static final int SECRET_BYTES = 32;
/** Before 16, CREATEROLE lets a cluster's admin alter and grant every other cluster's roles. */
static final int MIN_SERVER_VERSION = 16;
private static final int SCRAM_ITERATIONS = 4096;
private static final int SCRAM_SALT_BYTES = 16;
private static final String MARKER_PREFIX = "floci:dsql:";
/** As long as {@link DockerDsqlBackend} waits for a cluster's container. */
static final Duration READY_TIMEOUT = Duration.ofSeconds(90);
/** The longest one login to the server may take. */
static final Duration LOGIN_TIMEOUT = Duration.ofSeconds(10);
/**
* The longest Floci waits for the server to answer one call, such as the bootstrap or dropping a
* database: far longer than any of them takes on a server that works.
*/
static final Duration SOCKET_TIMEOUT = Duration.ofSeconds(120);
/** How long ending a session on a cluster's database waits for it to be gone. */
private static final Duration SESSION_END_WAIT = Duration.ofSeconds(5);
private final EmulatorConfig config;
private final Duration readyTimeout;
// One lock per cluster, so a deletion waits for a start still running, and the reverse. Nothing
// else is locked while one is held, and none is taken under DsqlService's or DsqlDataPlane's
// locks, as those call this class only from their own threads, so they cannot deadlock.
private final Map<String, ClusterLock> locks = new ConcurrentHashMap<>();
@Inject
public ExternalDsqlBackend(EmulatorConfig config) {
this(config, READY_TIMEOUT);
}
/** With how long a start waits for the server to let Floci in; for tests. */
ExternalDsqlBackend(EmulatorConfig config, Duration readyTimeout) {
this.config = config;
this.readyTimeout = readyTimeout;
}
/**
* Creates the cluster's owner, admin, connect role and database where missing, then installs
* DSQL's dialect in the database. The secret is set on {@code cluster} the first time, for the
* caller to save with it. On failure, what this attempt created is dropped again, and nothing
* else. A server older than PostgreSQL 16 is refused before anything is created, and so is a
* database, owner, admin or connect role already there without this cluster's
* {@link #marker ownership marker}: Floci adopts only what it created for the cluster.
*/
@Override
public DsqlDatabases.Backend start(DsqlCluster cluster) throws SQLException {
return underLock(cluster.getIdentifier(), () -> startLocked(cluster));
}
private DsqlDatabases.Backend startLocked(DsqlCluster cluster) throws SQLException {
if (cluster.getBackendSecret() == null) {
cluster.setBackendSecret(newSecret());
}
String secret = cluster.getBackendSecret();
Names names = new Names(cluster.getIdentifier());
String marker = marker(cluster);
boolean createdOwner = false;
boolean createdAdmin = false;
boolean createdConnect = false;
boolean createdDatabase = false;
String where = host() + ":" + external().port();
try (Connection server = DsqlDatabases.awaitConnection(() -> connect(external().database()),
readyTimeout, DsqlDatabases.READY_INTERVAL, true, "The external PostgreSQL server " + where)) {
requireSupportedVersion(server, where);
// Nothing is changed unless every object already there is one Floci created for this cluster.
Ownership owner = roleOwnership(server, names.owner(), marker);
Ownership admin = roleOwnership(server, names.admin(), marker);
Ownership connect = roleOwnership(server, names.connect(), marker);
Ownership database = databaseOwnership(server, names, marker);
refuseForeign(cluster, "role", names.owner(), owner);
refuseForeign(cluster, "role", names.admin(), admin);
refuseForeign(cluster, "role", names.connect(), connect);
refuseForeign(cluster, "database", names.database(), database);
try {
if (owner == Ownership.MISSING) {
// A role and its marker in one transaction, so no crash leaves the role unmarked.
inTransaction(server, "CREATE ROLE " + PostgresWire.quoteIdentifier(names.owner()) + " NOLOGIN",
"COMMENT ON ROLE " + PostgresWire.quoteIdentifier(names.owner()) + " IS " + PostgresWire.quoteLiteral(marker));
createdOwner = true;
}
String password = PostgresWire.quoteLiteral(verifier(secret, names.admin()));
if (admin == Ownership.OURS) {
execute(server, "ALTER ROLE " + PostgresWire.quoteIdentifier(names.admin()) + " PASSWORD " + password);
} else {
inTransaction(server,
"CREATE ROLE " + PostgresWire.quoteIdentifier(names.admin()) + " LOGIN CREATEROLE PASSWORD " + password,
"COMMENT ON ROLE " + PostgresWire.quoteIdentifier(names.admin()) + " IS " + PostgresWire.quoteLiteral(marker));
createdAdmin = true;
}
if (connect == Ownership.MISSING) {
inTransaction(server, "CREATE ROLE " + PostgresWire.quoteIdentifier(names.connect()) + " NOLOGIN",
"COMMENT ON ROLE " + PostgresWire.quoteIdentifier(names.connect()) + " IS " + PostgresWire.quoteLiteral(marker));
createdConnect = true;
}
if (database == Ownership.MISSING) {
// CREATE DATABASE cannot run in a transaction; a crash before its COMMENT leaves it
// UNSTAMPED, which the next start recognises by its marked owner and stamps.
execute(server, "CREATE DATABASE " + PostgresWire.quoteIdentifier(names.database()) + " OWNER " + PostgresWire.quoteIdentifier(names.owner()));
createdDatabase = true;
}
if (database != Ownership.OURS) {
execute(server, "COMMENT ON DATABASE " + PostgresWire.quoteIdentifier(names.database()) + " IS " + PostgresWire.quoteLiteral(marker));
}
// The bootstrap takes CONNECT from PUBLIC and gives it to the connect role's members.
try (Connection connection = connect(names.database());
Statement statement = connection.createStatement()) {
statement.execute(DsqlBootstrap.render(names.database(), names.owner(), names.admin(),
names.connect(), names.prefix(), true));
}
} catch (SQLException | RuntimeException e) {
undo(server, names, new Created(createdOwner, createdAdmin, createdConnect, createdDatabase), e);
throw e;
}
}
LOG.infov("DSQL cluster {0} serves from database {1} on {2}:{3}", cluster.getIdentifier(),
names.database(), host(), String.valueOf(external().port()));
return new DsqlDatabases.Backend(host(), external().port(), names.database(), external().username(),
external().password().orElse(null), new PrefixedRoleNames(cluster.getIdentifier()),
new DerivedCredentials(secret));
}
/**
* The cluster's recorded roles brought up to date, its own roles first, then its admin, its
* connect role, and its owner last. With the database gone, the roles an earlier deletion saved,
* or else the admin, connect role and owner, the three roles a cluster always has. Only a
* deletion asks for them, so the sessions still on the database are ended first.
*/
@Override
public List<String> rolesToDrop(DsqlCluster cluster) throws SQLException {
return underLock(cluster.getIdentifier(), () -> rolesToDropLocked(cluster));
}
private List<String> rolesToDropLocked(DsqlCluster cluster) throws SQLException {
Names names = new Names(cluster.getIdentifier());
try (Connection server = connect(external().database())) {
Ownership database = databaseOwnership(server, names, knownMarker(cluster));
if (database == Ownership.MISSING) {
return known(cluster, names);
}
if (database == Ownership.FOREIGN) {
LOG.warnv("Database {0} was not created by Floci for DSQL cluster {1}; it is left in place, and"
+ " no roles are listed from it", names.database(), cluster.getIdentifier());
return names.always();
}
// The endpoint no longer serves the cluster, so no new session reaches the database; ending
// the ones still there before the roles are read means none creates a role the list misses.
endSessions(server, names);
}
List<String> roles = new ArrayList<>();
try (Connection database = connect(names.database())) {
if (!recordsRoles(database)) {
return known(cluster, names);
}
execute(database, "CALL sys._record_backend_roles()");
try (PreparedStatement query = database.prepareStatement("SELECT backend_name FROM sys.backend_roles"
+ " ORDER BY CASE backend_name WHEN ? THEN 3 WHEN ? THEN 2 WHEN ? THEN 1 ELSE 0 END,"
+ " role_oid DESC")) {
query.setString(1, names.owner());
query.setString(2, names.connect());
query.setString(3, names.admin());
try (ResultSet rows = query.executeQuery()) {
while (rows.next()) {
roles.add(rows.getString(1));
}
}
}
}
// The admin, connect role and owner go with the cluster even when the record no longer names them.
List<String> always = names.always();
for (int i = always.size() - 1; i >= 0; i--) {
String role = always.get(i);
if (!roles.contains(role)) {
int before = i + 1 < always.size() ? roles.indexOf(always.get(i + 1)) : -1;
roles.add(before < 0 ? roles.size() : before, role);
}
}
return List.copyOf(roles);
}
/**
* With {@code dropData}, ends every session on the cluster's database, drops the database, then
* drops each role in {@link DsqlCluster#getPendingBackendRoles()}. The database, admin, connect
* role and owner are dropped only when they carry the cluster's marker; the other roles only
* with its prefix.
* What is already gone is
* passed over; anything else that fails is thrown, so the deletion is not taken for done.
* Without it nothing happens: the server keeps running for the next start. A start of the same
* cluster still running is waited for, so a deletion never drops what it is creating.
*/
@Override
public void stop(DsqlCluster cluster, boolean dropData) {
if (!dropData) {
return;
}
Names names = new Names(cluster.getIdentifier());
List<String> roles = cluster.getPendingBackendRoles() == null || cluster.getPendingBackendRoles().isEmpty()
? names.always() : cluster.getPendingBackendRoles();
try {
underLock(cluster.getIdentifier(), () -> {
String marker = knownMarker(cluster);
try (Connection server = connect(external().database())) {
Ownership database = databaseOwnership(server, names, marker);
if (database == Ownership.OURS || database == Ownership.UNSTAMPED) {
dropDatabase(server, names);
} else if (database == Ownership.FOREIGN) {
LOG.warnv("Database {0} was not created by Floci for DSQL cluster {1}; it is left in place",
names.database(), cluster.getIdentifier());
}
for (String role : roles) {
if (!names.owns(role)) {
LOG.warnv("Role {0} is not a role of DSQL cluster {1}; it is left in place", role,
cluster.getIdentifier());
continue;
}
if (names.marked(role) && roleOwnership(server, role, marker) == Ownership.FOREIGN) {
LOG.warnv("Role {0} was not created by Floci for DSQL cluster {1}; it is left in place",
role, cluster.getIdentifier());
continue;
}
execute(server, "DROP ROLE IF EXISTS " + PostgresWire.quoteIdentifier(role));
}
}
return null;
});
} catch (SQLException e) {
throw new IllegalStateException("The database and roles of DSQL cluster " + cluster.getIdentifier()
+ " could not be dropped: " + e.getMessage(), e);
}
}
/**
* A FAILED cluster's server may be one Floci cannot reach, so its deletion finishes anyway, as
* on AWS; its database and recorded roles may stay on the server.
*/
@Override
public Optional<String> leftoversOfFailed(DsqlCluster cluster) {
Names names = new Names(cluster.getIdentifier());
List<String> pending = cluster.getPendingBackendRoles();
List<String> roles = pending == null || pending.isEmpty() ? names.always() : pending;
return Optional.of("database " + names.database() + " and roles " + String.join(", ", roles));
}
/**
* Runs {@code work} holding the cluster's lock. The lock is dropped from {@link #locks} once no
* thread holds or waits for it; its count of users is only changed inside the map's atomic
* {@code compute}.
*/
<T> T underLock(String clusterId, LockedWork<T> work) throws SQLException {
ClusterLock entry = locks.compute(clusterId, (id, held) -> {
ClusterLock used = held == null ? new ClusterLock() : held;
used.users++;
return used;
});
entry.lock.lock();
try {
return work.run();
} finally {
entry.lock.unlock();
locks.computeIfPresent(clusterId, (id, held) -> --held.users == 0 ? null : held);
}
}
/** Whether another thread waits for the cluster's lock; for tests. */
boolean awaitedLock(String clusterId) {
ClusterLock entry = locks.get(clusterId);
return entry != null && entry.lock.hasQueuedThreads();
}
/** How many clusters' locks are held or awaited; for tests. */
int lockedClusters() {
return locks.size();
}
/** What runs under a cluster's lock. */
@FunctionalInterface
interface LockedWork<T> {
T run() throws SQLException;
}
private static final class ClusterLock {
private final ReentrantLock lock = new ReentrantLock();
private int users;
}
/** The password of a backend role: base64url, unpadded, of HMAC-SHA256 keyed by the cluster's secret. */
static String derive(String secret, String backendRole) {
try {
byte[] digest = BackendAuthenticator.hmac(Base64.getDecoder().decode(secret),
backendRole.getBytes(StandardCharsets.UTF_8));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("HMAC-SHA256 is not available", e);
}
}
/**
* The SCRAM-SHA-256 verifier of a backend role's derived password, in PostgreSQL's format,
* {@code SCRAM-SHA-256$<iterations>:<salt>$<StoredKey>:<ServerKey>}, which {@code PASSWORD}
* stores as it is. The salt, the first 16 bytes of HMAC-SHA256 of {@code scram-salt:<role>}
* keyed by the cluster's secret, is the same each time, so setting it again changes nothing.
*/
static String verifier(String secret, String backendRole) {
try {
byte[] salt = Arrays.copyOf(BackendAuthenticator.hmac(Base64.getDecoder().decode(secret),
("scram-salt:" + backendRole).getBytes(StandardCharsets.UTF_8)), SCRAM_SALT_BYTES);
byte[] salted = BackendAuthenticator.saltedPassword(derive(secret, backendRole), salt, SCRAM_ITERATIONS);
byte[] clientKey = BackendAuthenticator.hmac(salted, "Client Key".getBytes(StandardCharsets.UTF_8));
byte[] storedKey = Digests.sha256(clientKey);
byte[] serverKey = BackendAuthenticator.hmac(salted, "Server Key".getBytes(StandardCharsets.UTF_8));
Base64.Encoder base64 = Base64.getEncoder();
return "SCRAM-SHA-256$" + SCRAM_ITERATIONS + ":" + base64.encodeToString(salt) + "$"
+ base64.encodeToString(storedKey) + ":" + base64.encodeToString(serverKey);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("SCRAM-SHA-256 is not available", e);
}
}
/**
* Each backend role's password and its verifier, derived from the cluster's secret. A verifier
* is computed once per role, as its PBKDF2 would otherwise run on every login.
*/
private static final class DerivedCredentials implements BackendCredentials {
private final String secret;
private final Map<String, String> verifiers = new ConcurrentHashMap<>();
DerivedCredentials(String secret) {
this.secret = secret;
}
@Override
public String passwordFor(String backendRole) {
return derive(secret, backendRole);
}
@Override
public String verifierFor(String backendRole) {
return verifiers.computeIfAbsent(backendRole, role -> verifier(secret, role));
}
/** Floci sets every backend role's password as a SCRAM verifier, so nothing else is answered. */
@Override
public boolean scramOnly() {
return true;
}
@Override
public String toString() {
return "DerivedCredentials[secret=***]";
}
}
private static String newSecret() {
byte[] bytes = new byte[SECRET_BYTES];
// Not a static field, which a native image would seed at build time.
new SecureRandom().nextBytes(bytes);
return Base64.getEncoder().encodeToString(bytes);
}
private static List<String> known(DsqlCluster cluster, Names names) {
List<String> pending = cluster.getPendingBackendRoles();
if (pending != null && !pending.isEmpty()) {
return List.copyOf(pending);
}
LOG.warnv("The database of DSQL cluster {0} is gone: only its admin, connect and owner roles are known"
+ " to drop; roles created in it are left on the server", cluster.getIdentifier());
return names.always();
}
/** What one start created, which its failure drops again. */
private record Created(boolean owner, boolean admin, boolean connect, boolean database) {
}
private void undo(Connection server, Names names, Created created, Exception failure) {
try {
if (created.database()) {
dropDatabase(server, names);
} else if (created.connect() && databaseExists(server, names.database())) {
// A database this attempt did not create may keep the connect role's CONNECT, which
// would keep the role from being dropped.
execute(server, "REVOKE CONNECT ON DATABASE " + PostgresWire.quoteIdentifier(names.database()) + " FROM "
+ PostgresWire.quoteIdentifier(names.connect()));
}
if (created.admin()) {
execute(server, "DROP ROLE IF EXISTS " + PostgresWire.quoteIdentifier(names.admin()));
}
if (created.connect()) {
execute(server, "DROP ROLE IF EXISTS " + PostgresWire.quoteIdentifier(names.connect()));
}
if (created.owner()) {
execute(server, "DROP ROLE IF EXISTS " + PostgresWire.quoteIdentifier(names.owner()));
}
} catch (SQLException e) {
failure.addSuppressed(e);
}
}
private static void dropDatabase(Connection server, Names names) throws SQLException {
endSessions(server, names);
execute(server, "DROP DATABASE IF EXISTS " + PostgresWire.quoteIdentifier(names.database()) + " WITH (FORCE)");
}
/**
* Ends every other session on the cluster's database, waiting up to {@link #SESSION_END_WAIT}
* for each to be gone, so a statement it was running is rolled back or committed by then.
*/
private static void endSessions(Connection server, Names names) throws SQLException {
try (PreparedStatement terminate = server.prepareStatement("SELECT pg_terminate_backend(pid, ?)"
+ " FROM pg_stat_activity WHERE datname = ? AND pid <> pg_backend_pid()")) {
terminate.setLong(1, SESSION_END_WAIT.toMillis());
terminate.setString(2, names.database());
terminate.execute();
}
}
/**
* Refuses a server older than PostgreSQL 16. Isolating the clusters from one another rests on
* its CREATEROLE, which only lets a role alter and grant the roles it created itself.
*/
static void requireSupportedVersion(Connection server, String where) throws SQLException {
DatabaseMetaData metaData = server.getMetaData();
if (metaData.getDatabaseMajorVersion() < MIN_SERVER_VERSION) {
throw new SQLException("Floci's external DSQL backend needs PostgreSQL " + MIN_SERVER_VERSION
+ " or later; " + where + " runs " + metaData.getDatabaseProductVersion());
}
}
/**
* The ownership marker Floci comments the cluster's database, owner and admin with when it
* creates them: {@code floci:dsql:<cluster ARN>}.
*/
static String marker(DsqlCluster cluster) throws SQLException {
String marker = knownMarker(cluster);
if (marker == null) {
throw new SQLException("DSQL cluster " + cluster.getIdentifier() + " has no ARN to mark its objects with");
}
return marker;
}
/**
* The cluster's marker, or null without an ARN, when no object on the server can be shown to
* be the cluster's, so a deletion leaves the database, admin and owner in place.
*/
private static String knownMarker(DsqlCluster cluster) {
if (cluster.getArn() == null) {
LOG.warnv("DSQL cluster {0} has no ARN: none of the server's objects are taken for its own",
cluster.getIdentifier());
return null;
}
return MARKER_PREFIX + cluster.getArn();
}
/**
* Whether an object is missing, carries this cluster's marker, or is someone else's. A database
* is UNSTAMPED when it has no comment and is owned by the cluster's owner role carrying the
* marker: one a start created and could not mark before it stopped, which is the cluster's.
*/
enum Ownership { MISSING, OURS, UNSTAMPED, FOREIGN }
private static Ownership roleOwnership(Connection server, String role, String marker) throws SQLException {
try (PreparedStatement query = server.prepareStatement(
"SELECT shobj_description(oid, 'pg_authid') FROM pg_roles WHERE rolname = ?")) {
query.setString(1, role);
try (ResultSet rows = query.executeQuery()) {
if (!rows.next()) {
return Ownership.MISSING;
}
return marker != null && marker.equals(rows.getString(1)) ? Ownership.OURS : Ownership.FOREIGN;
}
}
}
private static Ownership databaseOwnership(Connection server, Names names, String marker) throws SQLException {
try (PreparedStatement query = server.prepareStatement("SELECT shobj_description(d.oid, 'pg_database'),"
+ " r.rolname, shobj_description(r.oid, 'pg_authid') FROM pg_database d"
+ " LEFT JOIN pg_roles r ON r.oid = d.datdba WHERE d.datname = ?")) {
query.setString(1, names.database());
try (ResultSet rows = query.executeQuery()) {
if (!rows.next()) {
return Ownership.MISSING;
}
if (marker == null) {
return Ownership.FOREIGN;
}
String comment = rows.getString(1);
if (marker.equals(comment)) {
return Ownership.OURS;
}
boolean ownedByOurOwner = names.owner().equals(rows.getString(2)) && marker.equals(rows.getString(3));
return comment == null && ownedByOurOwner ? Ownership.UNSTAMPED : Ownership.FOREIGN;
}
}
}
/** Runs {@code statements} in one transaction, committed together or not at all. */
private static void inTransaction(Connection connection, String... statements) throws SQLException {
connection.setAutoCommit(false);
try (Statement statement = connection.createStatement()) {
for (String sql : statements) {
statement.execute(sql);
}
connection.commit();
} catch (SQLException | RuntimeException e) {
try {
connection.rollback();
} catch (SQLException rollback) {
e.addSuppressed(rollback);
}
throw e;
} finally {
connection.setAutoCommit(true);
}
}
/** Refuses to adopt an object Floci did not create for this cluster, before anything is changed. */
private static void refuseForeign(DsqlCluster cluster, String kind, String name, Ownership ownership)
throws SQLException {
if (ownership == Ownership.FOREIGN) {
throw new SQLException("The external PostgreSQL server already has a " + kind + " \"" + name
+ "\" that Floci did not create for DSQL cluster " + cluster.getIdentifier()
+ "; Floci leaves it as it is and does not start the cluster", "42710");
}
}
private static boolean databaseExists(Connection server, String database) throws SQLException {
return exists(server, "SELECT 1 FROM pg_database WHERE datname = ?", database);
}
/** Whether the bootstrap got as far as recording the cluster's roles. */
private static boolean recordsRoles(Connection database) throws SQLException {
try (Statement statement = database.createStatement();
ResultSet row = statement.executeQuery("SELECT to_regprocedure('sys._record_backend_roles()') IS NOT NULL"
+ " AND to_regclass('sys.backend_roles') IS NOT NULL")) {
return row.next() && row.getBoolean(1);
}
}
private static boolean exists(Connection connection, String sql, String value) throws SQLException {
try (PreparedStatement query = connection.prepareStatement(sql)) {
query.setString(1, value);
try (ResultSet rows = query.executeQuery()) {
return rows.next();
}
}
}
private static void execute(Connection connection, String sql) throws SQLException {
try (Statement statement = connection.createStatement()) {
statement.execute(sql);
}
}
/**
* Opens a connection to the server. Neither the login nor any later call waits for an answer
* without limit, as the driver would by default: these calls run holding the cluster's lock,
* and at shutdown, so a server that accepts connections and never answers, as a paused sidecar
* does, would otherwise hold a start, a deletion or Floci's shutdown forever.
*/
private Connection connect(String database) throws SQLException {
String url = "jdbc:postgresql://" + host() + ":" + external().port() + "/" + database;
Properties properties = new Properties();
properties.setProperty("user", external().username());
properties.setProperty("password", external().password().orElse(""));
String login = String.valueOf(loginTimeoutSeconds(readyTimeout));
properties.setProperty("loginTimeout", login);
properties.setProperty("connectTimeout", login);
properties.setProperty("socketTimeout", String.valueOf(SOCKET_TIMEOUT.toSeconds()));
return DriverManager.getConnection(url, properties);
}
/**
* How long one login may take, in whole seconds as the driver counts them: at most
* {@link #LOGIN_TIMEOUT}, and no longer than a start waits for the server, but at least one
* second, since zero would mean no limit.
*/
static int loginTimeoutSeconds(Duration readyTimeout) {
long seconds = Math.min(LOGIN_TIMEOUT.toSeconds(), readyTimeout.toSeconds());
return (int) Math.max(1, seconds);
}
private String host() {
return external().host().orElseThrow(() -> new IllegalStateException(
"floci.services.dsql.external.host is required with the external DSQL backend"));
}
private EmulatorConfig.DsqlServiceConfig.External external() {
return config.services().dsql().external();
}
/**
* The names of one cluster's database and roles on the shared server. The owner and connect
* role are outside the prefix, so no name a client gives maps onto them.
*/
private record Names(String database, String owner, String admin, String connect, String prefix) {
Names(String clusterId) {
this("dsql_" + clusterId, "dsqlowner_" + clusterId, "d" + clusterId + "_admin",
"dsqlconnect_" + clusterId, "d" + clusterId + "_");
}
boolean owns(String role) {
return role.equals(owner) || role.equals(connect) || role.startsWith(prefix);
}
/** The roles Floci creates and marks; a client's roles carry no marker. */
boolean marked(String role) {
return role.equals(owner) || role.equals(admin) || role.equals(connect);
}
/** The roles every cluster has, in the order they are dropped. */
List<String> always() {
return List.of(admin, connect, owner);
}
}
}
@@ -32,6 +32,8 @@ public class DsqlCluster {
private String witnessRegion;
private List<String> linkedClusterArns;
private boolean databaseReady;
private String backendSecret;
private List<String> pendingBackendRoles;
public String getIdentifier() { return identifier; }
public void setIdentifier(String identifier) { this.identifier = identifier; }
@@ -70,4 +72,18 @@ public class DsqlCluster {
/** 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; }
/**
* The cluster's own secret on an external PostgreSQL server, base64 of 32 random bytes, from
* which each backend role's password is derived. Stored with the cluster; no API answer carries it.
*/
public String getBackendSecret() { return backendSecret; }
public void setBackendSecret(String backendSecret) { this.backendSecret = backendSecret; }
/**
* The backend roles a deletion drops, saved before anything is dropped, so a deletion finished
* on a later start drops the same roles once the database that recorded them is gone.
*/
public List<String> getPendingBackendRoles() { return pendingBackendRoles; }
public void setPendingBackendRoles(List<String> pendingBackendRoles) {
this.pendingBackendRoles = pendingBackendRoles;
}
}