From faf228743398d8e3d23e08ea793f11b84db06507 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20Gamboa?= Date: Mon, 16 Nov 2026 15:21:57 -0300 Subject: [PATCH] refactor(dsql): put the cluster database behind a backend strategy (#8595) --- .../dsql/dataplane/BackendCredentials.java | 16 ++ .../dsql/dataplane/DockerDsqlBackend.java | 151 +++++++++++++++++ .../services/dsql/dataplane/DsqlBackend.java | 16 ++ .../dsql/dataplane/DsqlBootstrap.java | 50 ++++++ .../dsql/dataplane/DsqlDatabases.java | 158 +++--------------- .../services/dsql/dataplane/DsqlEndpoint.java | 2 +- .../services/dsql/dataplane/DsqlSession.java | 2 +- .../services/dsql/dataplane/RoleNames.java | 30 ++++ src/main/resources/application.yml | 4 +- src/main/resources/dsql/bootstrap.sql | 20 +-- .../dsql/dataplane/DsqlBootstrapTest.java | 50 ++++++ .../dsql/dataplane/DsqlDatabasesTest.java | 38 +++++ .../DsqlSessionRecordIntegrationTest.java | 3 +- 13 files changed, 394 insertions(+), 146 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/dsql/dataplane/BackendCredentials.java create mode 100644 src/main/java/io/floci/aws/services/dsql/dataplane/DockerDsqlBackend.java create mode 100644 src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBackend.java create mode 100644 src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBootstrap.java create mode 100644 src/main/java/io/floci/aws/services/dsql/dataplane/RoleNames.java create mode 100644 src/test/java/io/floci/aws/services/dsql/dataplane/DsqlBootstrapTest.java create mode 100644 src/test/java/io/floci/aws/services/dsql/dataplane/DsqlDatabasesTest.java diff --git a/src/main/java/io/floci/aws/services/dsql/dataplane/BackendCredentials.java b/src/main/java/io/floci/aws/services/dsql/dataplane/BackendCredentials.java new file mode 100644 index 0000000000..d179549631 --- /dev/null +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/BackendCredentials.java @@ -0,0 +1,16 @@ +package io.floci.aws.services.dsql.dataplane; + +/** The passwords the database expects of the roles Floci connects as. */ +public interface BackendCredentials { + + /** A database that trusts its connections wants no password. */ + BackendCredentials TRUST = new BackendCredentials() { + @Override + public String passwordFor(String backendRole) { + return null; + } + }; + + /** The password Floci logs in with as a backend role, or null when the database wants none. */ + String passwordFor(String backendRole); +} diff --git a/src/main/java/io/floci/aws/services/dsql/dataplane/DockerDsqlBackend.java b/src/main/java/io/floci/aws/services/dsql/dataplane/DockerDsqlBackend.java new file mode 100644 index 0000000000..6e194163be --- /dev/null +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/DockerDsqlBackend.java @@ -0,0 +1,151 @@ +package io.floci.aws.services.dsql.dataplane; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.common.docker.ContainerBuilder; +import io.floci.aws.core.common.docker.ContainerDetector; +import io.floci.aws.core.common.docker.ContainerLifecycleManager; +import io.floci.aws.core.common.docker.ContainerSpec; +import io.floci.aws.core.common.docker.ContainerStorageHelper; +import io.floci.aws.services.dsql.model.DsqlCluster; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +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; + +/** + * 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 DockerDsqlBackend implements DsqlBackend { + + private static final Logger LOG = Logger.getLogger(DockerDsqlBackend.class); + private static final int PORT = 5432; + private static final String DATABASE = "postgres"; + private static final String SUPERUSER = "dbowner"; + 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; + + @Inject + public DockerDsqlBackend(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. */ + @Override + public DsqlDatabases.Backend start(DsqlCluster cluster) throws SQLException, IOException { + String name = containerName(cluster); + Map 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=" + SUPERUSER, "POSTGRES_DB=" + DATABASE, "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(); + ContainerStorageHelper.ensureHostDir(containerDetector, 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); + DsqlDatabases.Backend backend = new DsqlDatabases.Backend(endpoint.host(), endpoint.port(), DATABASE, + SUPERUSER, null, RoleNames.IDENTITY, BackendCredentials.TRUST); + 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 | 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. + */ + @Override + 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 String containerName(DsqlCluster cluster) { + return ContainerStorageHelper.dockerName(config, "dsql-" + cluster.getIdentifier()); + } + + private static void awaitReady(DsqlDatabases.Backend backend) throws SQLException { + Instant deadline = Instant.now().plus(READY_TIMEOUT); + SQLException last = null; + while (Instant.now().isBefore(deadline)) { + try (Connection connection = DsqlDatabases.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(DsqlDatabases.Backend backend) throws SQLException { + String script = DsqlBootstrap.render(DATABASE, SUPERUSER, DsqlEndpoint.ADMIN); + try (Connection connection = DsqlDatabases.superuser(backend); Statement statement = connection.createStatement()) { + statement.execute(script); + } + } +} diff --git a/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBackend.java b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBackend.java new file mode 100644 index 0000000000..4a3dc50862 --- /dev/null +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBackend.java @@ -0,0 +1,16 @@ +package io.floci.aws.services.dsql.dataplane; + +import io.floci.aws.services.dsql.model.DsqlCluster; + +import java.io.IOException; +import java.sql.SQLException; + +/** Where a cluster's database lives, and how it is brought up and taken down. */ +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; + + /** Stops the cluster's database and, with {@code dropData}, removes its data. */ + void stop(DsqlCluster cluster, boolean dropData); +} diff --git a/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBootstrap.java b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBootstrap.java new file mode 100644 index 0000000000..5ecfb4c3f9 --- /dev/null +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBootstrap.java @@ -0,0 +1,50 @@ +package io.floci.aws.services.dsql.dataplane; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; + +/** + * Renders the DSQL bootstrap script for the database, owner role and admin role of one cluster. + * The script's placeholders: {@code {{database}}}, {@code {{owner}}} and {@code {{admin}}} as + * identifiers, always quoted; {@code {{owner_literal}}} and {@code {{admin_literal}}} + * as SQL string literals. + */ +final class DsqlBootstrap { + + private static final String RESOURCE = "/dsql/bootstrap.sql"; + + private DsqlBootstrap() { + } + + /** The script for one cluster's database. */ + static String render(String database, String owner, String admin) { + return template() + .replace("{{database}}", identifier(database)) + .replace("{{owner_literal}}", literal(owner)) + .replace("{{owner}}", identifier(owner)) + .replace("{{admin_literal}}", literal(admin)) + .replace("{{admin}}", identifier(admin)); + } + + private static String template() { + try (InputStream in = DsqlBootstrap.class.getResourceAsStream(RESOURCE)) { + if (in == null) { + throw new IllegalStateException("dsql/bootstrap.sql is missing from the classpath"); + } + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** 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("'", "''") + "'"; + } +} diff --git a/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlDatabases.java b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlDatabases.java index 192b5285db..aa7b05a000 100644 --- a/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlDatabases.java +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlDatabases.java @@ -1,167 +1,61 @@ package io.floci.aws.services.dsql.dataplane; -import io.floci.aws.config.EmulatorConfig; -import io.floci.aws.core.common.docker.ContainerBuilder; -import io.floci.aws.core.common.docker.ContainerDetector; -import io.floci.aws.core.common.docker.ContainerLifecycleManager; -import io.floci.aws.core.common.docker.ContainerSpec; -import io.floci.aws.core.common.docker.ContainerStorageHelper; import io.floci.aws.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. + * The database behind each cluster. Which one it is, a PostgreSQL container per cluster or a + * server that already runs, is the configured backend's concern; this class hands every call to it. */ @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 DsqlBackend strategy; - 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) { + /** + * Where a cluster's database answers, who Floci connects as, and how role names map. + * + * @param superuserPassword null when the database trusts the connection + */ + public record Backend(String host, int port, String database, String superuser, String superuserPassword, + RoleNames roleNames, BackendCredentials credentials) { public String jdbcUrl() { - return "jdbc:postgresql://" + host + ":" + port + "/postgres"; + return "jdbc:postgresql://" + host + ":" + port + "/" + database; + } + + /** Never shows the password, which a logged route would otherwise carry. */ + @Override + public String toString() { + return "Backend[host=" + host + ", port=" + port + ", database=" + database + ", superuser=" + superuser + + ", superuserPassword=" + (superuserPassword == null ? "null" : "***") + ", roleNames=" + + roleNames + ", credentials=" + credentials + "]"; } } @Inject - public DsqlDatabases(ContainerBuilder containerBuilder, ContainerLifecycleManager lifecycleManager, - ContainerDetector containerDetector, EmulatorConfig config) { - this.containerBuilder = containerBuilder; - this.lifecycleManager = lifecycleManager; - this.containerDetector = containerDetector; - this.config = config; + public DsqlDatabases(DockerDsqlBackend docker) { + this.strategy = docker; } /** 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 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(); - ContainerStorageHelper.ensureHostDir(containerDetector, 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; - } + return strategy.start(cluster); } - /** - * 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. - */ + /** Stops the cluster's database and, with {@code dropData}, removes its data. */ public void stop(DsqlCluster cluster, boolean dropData) { - String name = containerName(cluster); - lifecycleManager.removeIfExistsStrict(name); - if (dropData && ContainerStorageHelper.isNamedVolumeMode(config)) { - ContainerStorageHelper.removeNamedVolumeStrict(config, lifecycleManager, name); - } + strategy.stop(cluster, dropData); } /** A superuser connection to the cluster's database, for what the endpoint checks itself. */ public 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); - } + String password = backend.superuserPassword() == null ? "" : backend.superuserPassword(); + return DriverManager.getConnection(backend.jdbcUrl(), backend.superuser(), password); } } diff --git a/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlEndpoint.java b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlEndpoint.java index c1ce260aff..3cb6eabd0f 100644 --- a/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlEndpoint.java +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlEndpoint.java @@ -77,7 +77,7 @@ public class DsqlEndpoint { 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"; + static final String ADMIN = "admin"; private final DsqlTlsCertificates certificates; private final IamService iamService; diff --git a/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlSession.java b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlSession.java index eb477ea4c4..38fdaf14e1 100644 --- a/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlSession.java +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlSession.java @@ -237,7 +237,7 @@ final class DsqlSession { if (!optionSettings.isEmpty()) { backendStartup.put("options", backendOptions(optionSettings)); } - backendStartup.put("database", "postgres"); + backendStartup.put("database", target.database()); principalArn = admission.principalArn(); backendOut.write(PostgresWire.startupMessage(backendStartup)); backendOut.flush(); diff --git a/src/main/java/io/floci/aws/services/dsql/dataplane/RoleNames.java b/src/main/java/io/floci/aws/services/dsql/dataplane/RoleNames.java new file mode 100644 index 0000000000..587e69603c --- /dev/null +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/RoleNames.java @@ -0,0 +1,30 @@ +package io.floci.aws.services.dsql.dataplane; + +/** Maps the role names clients see to the ones the cluster's database has, and back. */ +public interface RoleNames { + + /** Names are the same on both sides, as with a database of the cluster's own. */ + RoleNames IDENTITY = new RoleNames() { + @Override + public String toBackend(String logical) { + return logical; + } + + @Override + public String toLogical(String backend) { + return backend; + } + + @Override + public boolean isIdentity() { + return true; + } + }; + + /** The backend name of the role called {@code logical}: a role's exact name, never a specifier. */ + String toBackend(String logical); + + String toLogical(String backend); + + boolean isIdentity(); +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index a8b8c83fbe..060c90d879 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -68,7 +68,8 @@ quarkus: # (bedrock/model-catalog.yaml), AppSync's GraphQL # parser reads its message bundles, Lambda Web Functions copy their # runtime (lambdaweb/index.mjs) into each environment, EMR writes its S3DistCp program - # (emr/s3-dist-cp.py) into a step's container, EC2 security group enforcement builds + # (emr/s3-dist-cp.py) into a step's container, DSQL renders its bootstrap + # (dsql/bootstrap.sql) for each cluster, EC2 security group enforcement builds # its helper image from docker/*.Dockerfile, and API Gateway's Velocity # engine reads its default properties at runtime via # ClassLoader#getResourceAsStream. Quarkus's static resource analysis @@ -96,6 +97,7 @@ quarkus: - iam/service-linked-roles.tsv - cloudformation/*.json - redshift/*.sql + - dsql/*.sql - i18n/*.properties - floci/version.properties - org/apache/velocity/runtime/defaults/*.properties diff --git a/src/main/resources/dsql/bootstrap.sql b/src/main/resources/dsql/bootstrap.sql index 91a7e62439..3df832cc58 100644 --- a/src/main/resources/dsql/bootstrap.sql +++ b/src/main/resources/dsql/bootstrap.sql @@ -1,4 +1,4 @@ --- Aurora DSQL's dialect inside a cluster's PostgreSQL, installed by Floci as the superuser dbowner +-- Aurora DSQL's dialect inside a cluster's PostgreSQL, installed by Floci as the superuser {{owner}} -- every time the database starts. Every statement is idempotent. What DSQL answers was measured on -- AWS (eu-west-1, 2026-10-16); the messages and SQLSTATEs below are its own. Event triggers do not -- fire for a session in the replica role, so the dialect's own DDL is not checked against it. @@ -6,16 +6,16 @@ SET session_replication_role = replica; DO $$ BEGIN - IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'admin') THEN - CREATE ROLE admin WITH LOGIN CREATEROLE CREATEDB; + IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = {{admin_literal}}) THEN + CREATE ROLE {{admin}} WITH LOGIN CREATEROLE CREATEDB; END IF; END $$; -GRANT CREATE ON DATABASE postgres TO admin; -ALTER SCHEMA public OWNER TO admin; -ALTER DATABASE postgres SET default_transaction_isolation TO 'repeatable read'; +GRANT CREATE ON DATABASE {{database}} TO {{admin}}; +ALTER SCHEMA public OWNER TO {{admin}}; +ALTER DATABASE {{database}} SET default_transaction_isolation TO 'repeatable read'; -CREATE SCHEMA IF NOT EXISTS sys AUTHORIZATION dbowner; +CREATE SCHEMA IF NOT EXISTS sys AUTHORIZATION {{owner}}; GRANT USAGE ON SCHEMA sys TO PUBLIC; -- ── Identifiers: a UUID as 26 characters of lowercase base32 ────────────────── @@ -102,7 +102,7 @@ CREATE OR REPLACE FUNCTION sys.cluster_size_limit() RETURNS bigint LANGUAGE sql IMMUTABLE AS $$ SELECT 10995116277760::bigint $$; CREATE OR REPLACE FUNCTION sys.cluster_size() RETURNS bigint -LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ SELECT pg_database_size('postgres') $$; +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ SELECT pg_database_size(current_database()) $$; CREATE OR REPLACE VIEW sys.roles AS SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication, @@ -367,7 +367,7 @@ SELECT sys.uuid_to_base32_str(job_id) AS job_id, FROM sys.job; GRANT SELECT ON sys.jobs TO PUBLIC; --- The job and the invalid index below are written as dbowner, so each first checks that the caller +-- The job and the invalid index below are written as {{owner}}, so each first checks that the caller -- owns the index it names: a client can record or invalidate only what it built itself. CREATE OR REPLACE FUNCTION sys._require_index_owner(index_oid oid) RETURNS void LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ @@ -488,7 +488,7 @@ LEFT JOIN pg_authid b ON b.oid = m.grantor; GRANT SELECT ON sys.iam_pg_role_mappings TO PUBLIC; -- The role an IAM role may be trusted with: one that exists, is no superuser, and on which the caller --- holds the ADMIN option, which admin holds on every role it created and on none other, itself +-- holds the ADMIN option, which {{admin}} holds on every role it created and on none other, itself -- included. CREATE OR REPLACE FUNCTION sys._trusted_role(role_name text, verb text, preposition text) RETURNS oid LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ diff --git a/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlBootstrapTest.java b/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlBootstrapTest.java new file mode 100644 index 0000000000..e84c017ec4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlBootstrapTest.java @@ -0,0 +1,50 @@ +package io.floci.aws.services.dsql.dataplane; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DsqlBootstrapTest { + + private static String docker() { + return DsqlBootstrap.render("postgres", "dbowner", "admin"); + } + + @Test + void noRenderingLeavesAPlaceholderBehind() { + assertFalse(docker().contains("{{")); + assertFalse(DsqlBootstrap.render("dsql_abc", "dsqlowner_abc", "dabc_admin").contains("{{")); + assertFalse(DsqlBootstrap.render("My-Db", "o\"w", "it's").contains("{{")); + } + + @Test + void dockerRenderingNamesTheDatabaseAndRolesQuoted() { + String script = docker(); + assertTrue(script.contains("WHERE rolname = 'admin') THEN")); + assertTrue(script.contains("CREATE ROLE \"admin\" WITH LOGIN CREATEROLE CREATEDB")); + assertTrue(script.contains("GRANT CREATE ON DATABASE \"postgres\" TO \"admin\"")); + assertTrue(script.contains("ALTER DATABASE \"postgres\" SET default_transaction_isolation")); + assertTrue(script.contains("CREATE SCHEMA IF NOT EXISTS sys AUTHORIZATION \"dbowner\"")); + assertTrue(script.contains("pg_database_size(current_database())")); + } + + @Test + void anotherRenderingNamesItsOwnDatabaseAndRoles() { + String script = DsqlBootstrap.render("dsql_abc", "dsqlowner_abc", "dabc_admin"); + assertTrue(script.contains("GRANT CREATE ON DATABASE \"dsql_abc\" TO \"dabc_admin\"")); + assertTrue(script.contains("AUTHORIZATION \"dsqlowner_abc\"")); + assertFalse(script.contains("'admin'")); + assertFalse(script.contains("\"postgres\"")); + } + + @Test + void everyIdentifierIsQuotedAndLiteralsEscaped() { + String script = DsqlBootstrap.render("My-Db", "o\"w", "it's"); + assertTrue(script.contains("GRANT CREATE ON DATABASE \"My-Db\" TO \"it's\"")); + assertTrue(script.contains("AUTHORIZATION \"o\"\"w\"")); + assertTrue(script.contains("rolname = 'it''s'")); + assertTrue(DsqlBootstrap.render("user", "table", "select") + .contains("GRANT CREATE ON DATABASE \"user\" TO \"select\"")); + } +} diff --git a/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlDatabasesTest.java b/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlDatabasesTest.java new file mode 100644 index 0000000000..4e2cbd550d --- /dev/null +++ b/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlDatabasesTest.java @@ -0,0 +1,38 @@ +package io.floci.aws.services.dsql.dataplane; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DsqlDatabasesTest { + + @Test + void dockerBackendDescribesTodaysDatabase() { + DsqlDatabases.Backend backend = new DsqlDatabases.Backend("h", 1, "postgres", "dbowner", null, + RoleNames.IDENTITY, BackendCredentials.TRUST); + + assertEquals("jdbc:postgresql://h:1/postgres", backend.jdbcUrl()); + assertEquals("admin", RoleNames.IDENTITY.toBackend("admin")); + assertEquals("admin", RoleNames.IDENTITY.toLogical("admin")); + assertTrue(RoleNames.IDENTITY.isIdentity()); + } + + @Test + void backendDescriptionHidesTheSuperuserPassword() { + DsqlDatabases.Backend backend = new DsqlDatabases.Backend("h", 1, "postgres", "floci", "s3cr3t-Pa55", + RoleNames.IDENTITY, BackendCredentials.TRUST); + + assertFalse(backend.toString().contains("s3cr3t-Pa55"), backend.toString()); + assertTrue(backend.toString().contains("superuserPassword=***"), backend.toString()); + DsqlEndpoint.Route route = new DsqlEndpoint.Route("c.dsql", "arn", "us-east-1", "000000000000", backend); + assertFalse(route.toString().contains("s3cr3t-Pa55"), route.toString()); + } + + @Test + void aTrustedDatabaseWantsNoPassword() { + assertNull(BackendCredentials.TRUST.passwordFor("x")); + } +} diff --git a/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlSessionRecordIntegrationTest.java b/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlSessionRecordIntegrationTest.java index c8f0f08daf..c29286e06e 100644 --- a/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlSessionRecordIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlSessionRecordIntegrationTest.java @@ -113,7 +113,8 @@ class DsqlSessionRecordIntegrationTest { String network = containerBuilder.resolveDockerNetwork(config.services().dsql().dockerNetwork()).orElse(null); ContainerLifecycleManager.EndpointInfo address = lifecycleManager.resolveEndpoint(containers.get(0).getId(), PORT, network); - return new DsqlDatabases.Backend(address.host(), address.port()); + return new DsqlDatabases.Backend(address.host(), address.port(), "postgres", "dbowner", null, + RoleNames.IDENTITY, BackendCredentials.TRUST); } private String single(String sql) throws SQLException {