From 3ebd1bc38c7221b52aa330610bcd27044101d200 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20Gamboa?= Date: Wed, 18 Nov 2026 16:27:20 -0300 Subject: [PATCH] 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 --- docs/services/dsql.md | 166 ++++- .../io/floci/aws/config/EmulatorConfig.java | 39 ++ .../floci/aws/core/common/PostgresWire.java | 8 + .../aws/services/dsql/DsqlDataPlane.java | 181 ++++- .../floci/aws/services/dsql/DsqlService.java | 38 +- .../dsql/dataplane/BackendCredentials.java | 19 + .../dsql/dataplane/DockerDsqlBackend.java | 55 +- .../services/dsql/dataplane/DsqlBackend.java | 13 + .../dsql/dataplane/DsqlBootstrap.java | 13 +- .../dsql/dataplane/DsqlDatabases.java | 71 +- .../services/dsql/dataplane/DsqlEndpoint.java | 74 +- .../services/dsql/dataplane/DsqlSession.java | 140 +++- .../dsql/dataplane/ExternalDsqlBackend.java | 662 ++++++++++++++++++ .../aws/services/dsql/model/DsqlCluster.java | 16 + src/main/resources/application.yml | 7 + .../config/EmulatorConfigDsqlBackendTest.java | 63 ++ .../aws/core/common/PostgresWireTest.java | 8 + .../aws/services/dsql/DsqlClusterFixture.java | 27 +- .../aws/services/dsql/DsqlDataPlaneTest.java | 194 +++++ .../DsqlExternalBackendIntegrationTest.java | 486 +++++++++++++ .../dsql/DsqlExternalBackendProfile.java | 13 + .../aws/services/dsql/DsqlServiceTest.java | 78 ++- .../dsql/ExternalPostgresResource.java | 58 ++ .../services/dsql/ExternalPostgresServer.java | 64 +- .../dsql/dataplane/DsqlDatabasesTest.java | 91 +++ .../dsql/dataplane/DsqlSessionTest.java | 51 ++ .../ExternalDsqlBackendIntegrationTest.java | 552 +++++++++++++++ .../dataplane/ExternalDsqlBackendTest.java | 277 ++++++++ src/test/resources/application.yml | 1 + 29 files changed, 3351 insertions(+), 114 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackend.java create mode 100644 src/test/java/io/floci/aws/config/EmulatorConfigDsqlBackendTest.java create mode 100644 src/test/java/io/floci/aws/services/dsql/DsqlDataPlaneTest.java create mode 100644 src/test/java/io/floci/aws/services/dsql/DsqlExternalBackendIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/dsql/DsqlExternalBackendProfile.java create mode 100644 src/test/java/io/floci/aws/services/dsql/ExternalPostgresResource.java create mode 100644 src/test/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackendIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackendTest.java diff --git a/docs/services/dsql.md b/docs/services/dsql.md index 06286793f8..917f3eb2a2 100644 --- a/docs/services/dsql.md +++ b/docs/services/dsql.md @@ -4,9 +4,10 @@ **Endpoint:** `http://localhost:4566` (control plane), `.dsql..localhost.floci.io:5432` (clusters) -Floci runs each Aurora DSQL cluster as a real PostgreSQL 16 database in a Docker container, behind one -endpoint that admits clients the way DSQL does: TLS, an IAM token as the password, and DSQL's -dialect and limits. The answers, messages and SQLSTATEs below were measured on AWS. +Floci runs each Aurora DSQL cluster as a real PostgreSQL 16 database in a Docker container, or, with +the [external backend](#external-postgresql-backend), in a PostgreSQL server that already runs, +behind one endpoint that admits clients the way DSQL does: TLS, an IAM token as the password, and +DSQL's dialect and limits. The answers, messages and SQLSTATEs below were measured on AWS. ## Supported Actions @@ -206,6 +207,152 @@ deletion protection included, but removes the tags and the policy it no longer s template does not change keeps its version. A protected cluster makes the stack's deletion fail, as on AWS. +## External PostgreSQL backend + +With `FLOCI_SERVICES_DSQL_BACKEND=external`, every cluster lives in one PostgreSQL server that +already runs, such as a sidecar, and Floci makes no Docker calls for DSQL. Clients see no change: +TLS, IAM tokens, `admin` and `DbConnect`, and the dialect work as above. `FLOCI_SERVICES_DSQL_MOCK` +still wins over the backend. + +The server must: + +- run PostgreSQL 16 or later. Floci checks the version when a cluster starts and fails the cluster, + creating nothing, on an older server, whose `CREATEROLE` would let one cluster's `admin` alter + the roles of every other cluster; +- let the configured user in as a superuser: Floci installs event triggers, reads `pg_authid`, + runs `CREATE DATABASE ... OWNER` and ends sessions on a cluster's database when it is deleted; +- be reachable over plain TCP. Floci does not use TLS to the server, so run both on a private + network or on localhost; +- authenticate the cluster roles' TCP logins with SCRAM-SHA-256 (`scram-sha-256`, or `md5`, which + uses SCRAM for a role whose password is a SCRAM verifier, in `pg_hba.conf`), or trust them + (`trust`, as the official image does for `127.0.0.1` and `::1`), so a sidecar on `localhost` + works. Floci never sends a password any other way: a server that asks for a cleartext or MD5 + password is refused, and the client gets `08006`. + +Use a PostgreSQL server dedicated to Floci: clusters share its catalogs, and Floci's superuser +manages roles and databases on it. + +A cluster's start waits up to 90 seconds for the server to let Floci's superuser in, as a server +started alongside Floci may still be starting; a login the server refuses, such as a wrong +password, fails the cluster at once. Each login to the server may take up to 10 seconds and each +call up to 120 seconds, so a server that accepts connections but never answers, such as a paused +sidecar, fails the start, deletion or shutdown that waits for it instead of holding it. + +Each cluster gets a database `dsql_`, a role `d_` for each of its +roles (`d_admin` for `admin`), a hidden owner role `dsqlowner_`, and a +hidden role `dsqlconnect_` that holds `CONNECT` on the database. `PUBLIC` may not +connect to it; each of the cluster's roles is a member of `dsqlconnect_`, which no +client role can revoke. Clusters cannot connect to or read one another's data, and the same role +name can exist in each. +Floci signs in to the server for each client itself: role passwords are stored as SCRAM verifiers +derived from a per-cluster secret that Floci keeps with the cluster and clients never see. + +What differs from the Docker backend, each because many clusters share one server, where a +Docker cluster has a server of its own. Databases and roles are named server-wide in PostgreSQL, +so each cluster's must carry its identifier to be kept apart from the others': + +- `current_user`, `session_user`, `pg_roles` and PostgreSQL's own error messages show the backend + names (`d_app`); `sys.roles` and `sys.iam_pg_role_mappings` show the DSQL names. + Floci translates the names in the statements a client sends, but not in the values PostgreSQL + computes and returns. +- `current_database()`, the `*_catalog` columns of `information_schema` (`table_catalog` and the + like) and `pg_database` show the cluster's database as `dsql_`, while clients still + connect to `postgres`, as on DSQL. Each cluster needs a database of its own on the shared server, + and only one there can be called `postgres`. A tool that compares the catalog with the database + it was configured with should read `current_database()`. +- `admin` cannot create databases (no `CREATEDB`): a database it created would sit outside the + cluster's own, where neither the cluster's isolation nor its deletion reaches. A DSQL cluster + has the one database `postgres` in any case. +- A role name is at most 35 bytes in UTF-8, so that with the 28-byte prefix it fits PostgreSQL's + 63-byte identifier; a longer one is refused with `42602`. PostgreSQL would cut a longer name + short, and two names cut short could become the same role, so it is refused instead. A name of + multi-byte characters reaches the limit with fewer than 35 characters. The Docker backend needs + no prefix and keeps PostgreSQL's own limit. +- Floci translates role names where the SQL syntax names a role (`CREATE ROLE`, `GRANT ... TO`, + `OWNER TO`, `SET ROLE app` or `SET ROLE 'app'`, `AWS IAM GRANT` and so on), not in `LANGUAGE sql` + function bodies or in other string literals: `has_table_privilege('app', ...)`, `pg_has_role`, + `set_config('role', ...)` and `information_schema` filters on a grantee need the backend name. +- Floci's own role procedures (`sys.run_role_ddl`, `sys.drop_roles`, `sys.aws_iam_grant`, + `sys.aws_iam_revoke`) and every `sys._*` routine cannot be called by a client: a statement that + names one with `sys.`, spelled plainly or with `U&` escapes, fails with `42883`, as for a routine + that does not exist. Floci sends a client's role DDL through these routines once it has + translated the names and checked that they are the cluster's; a client calling one itself would + skip both. A call through a `search_path` that names `sys`, or from a function body, + is not caught; the role DDL it runs is not translated, but a role it makes outside the cluster's + prefix is not counted as the cluster's, and it cannot take over another cluster's roles. +- A cluster counts as its own only the roles its `admin`, or a role it created, created or granted + to it. A role with its prefix that another cluster's `admin` made, in a `LANGUAGE sql` function + body where Floci translates no name, stays out of its `sys.roles` and its deletion. +- Some errors the server sends while a connection starts may name a backend role or database. +- Clients can see the other clusters' databases, roles and sessions in `pg_database`, `pg_roles` + and `pg_stat_activity`: their names only, not their data or queries. +- A role that owns objects in another database of the same server cannot be dropped, so the + cluster stays `DELETING` until those objects are gone; Floci retries on its next start. + +Floci marks the database, owner, admin and connect role it creates for a cluster with the comment +`floci:dsql:`. A cluster whose database, owner, admin or connect role is already on the server +without that comment fails to start, `FAILED`, and Floci changes nothing on the server; the log +names the object in the way. The one exception is a database with no comment owned by the +cluster's marked owner, which a start interrupted before it could comment the database left: +Floci comments it and goes on. + +When Floci restarts with persistent storage, each cluster keeps its database and data. Deleting a +cluster drops its database and the roles it recorded, nothing else on the server: never a +database, owner, admin or connect role without the cluster's comment. A `FAILED` +cluster is deleted even when the server cannot be cleaned up; Floci then logs the database and +roles that may remain. With in-memory storage, Floci deletes its external clusters when it stops. +A cluster still starting or being deleted then is waited for, up to 3 minutes, and goes as the +others do; one still starting is never served once Floci has begun to stop. + +Docker Compose, with the server as another service: + +```yaml +services: + floci: + image: floci/floci:latest + ports: + - "4566:4566" + - "5432:5432" + environment: + FLOCI_SERVICES_DSQL_BACKEND: external + FLOCI_SERVICES_DSQL_EXTERNAL_HOST: postgres + FLOCI_SERVICES_DSQL_EXTERNAL_PASSWORD: postgres + depends_on: + - postgres + postgres: + image: postgres:17 + environment: + POSTGRES_PASSWORD: postgres +``` + +An ECS task on Fargate, where there is no Docker socket, with PostgreSQL as a sidecar on +`localhost` (excerpt of `containerDefinitions`; give the PostgreSQL container its own port, since +Floci serves clusters on `5432`): + +```json +[ + { + "name": "postgres", + "image": "postgres:17", + "essential": true, + "command": ["postgres", "-p", "5433"], + "environment": [{ "name": "POSTGRES_PASSWORD", "value": "postgres" }] + }, + { + "name": "floci", + "image": "floci/floci:latest", + "essential": true, + "dependsOn": [{ "containerName": "postgres", "condition": "START" }], + "environment": [ + { "name": "FLOCI_SERVICES_DSQL_BACKEND", "value": "external" }, + { "name": "FLOCI_SERVICES_DSQL_EXTERNAL_HOST", "value": "localhost" }, + { "name": "FLOCI_SERVICES_DSQL_EXTERNAL_PORT", "value": "5433" }, + { "name": "FLOCI_SERVICES_DSQL_EXTERNAL_PASSWORD", "value": "postgres" } + ] + } +] +``` + ## Configuration | Variable | Default | Description | @@ -216,10 +363,17 @@ on AWS. | `FLOCI_SERVICES_DSQL_ENDPOINT_SUFFIX` | `localhost.floci.io` | Domain the endpoints are named under, `.dsql..` | | `FLOCI_SERVICES_DSQL_IMAGE` | `postgres:16-alpine` | Image each cluster's database runs in | | `FLOCI_SERVICES_DSQL_DOCKER_NETWORK` | Floci's network | Docker network for the databases | +| `FLOCI_SERVICES_DSQL_BACKEND` | `docker` | `docker` (a container per cluster) or `external` (a server that already runs, see [External PostgreSQL backend](#external-postgresql-backend)) | +| `FLOCI_SERVICES_DSQL_EXTERNAL_HOST` | none | Host of the external server; required with `external` | +| `FLOCI_SERVICES_DSQL_EXTERNAL_PORT` | `5432` | Port of the external server | +| `FLOCI_SERVICES_DSQL_EXTERNAL_DATABASE` | `postgres` | Database Floci connects to on the external server to manage the clusters' databases and roles | +| `FLOCI_SERVICES_DSQL_EXTERNAL_USERNAME` | `postgres` | Superuser Floci signs in as | +| `FLOCI_SERVICES_DSQL_EXTERNAL_PASSWORD` | none | Its password, if the server asks for one | -A cluster's data lives in a Docker volume of its own, or under the host persistent path, and is -removed with the cluster under the same policy as RDS's (`prune-volumes-on-delete`). With -persistent storage a cluster comes back, with its data, when Floci restarts. +With the Docker backend, a cluster's data lives in a Docker volume of its own, or under the host +persistent path, and is removed with the cluster under the same policy as RDS's +(`prune-volumes-on-delete`). With persistent storage a cluster comes back, with its data, when +Floci restarts. See the [Aurora DSQL API Reference](https://docs.aws.amazon.com/aurora-dsql/latest/APIReference/Welcome.html) and the [Aurora DSQL User Guide](https://docs.aws.amazon.com/aurora-dsql/latest/userguide/what-is-aurora-dsql.html). diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 8f3b30d504..3ea6f4f653 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -2138,6 +2138,45 @@ public interface EmulatorConfig { /** Docker network for the database containers. Defaults to Floci's own network. */ Optional 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 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 password(); + } } interface RdsDataServiceConfig { diff --git a/src/main/java/io/floci/aws/core/common/PostgresWire.java b/src/main/java/io/floci/aws/core/common/PostgresWire.java index 8a2e6ecab5..1ba2da479b 100644 --- a/src/main/java/io/floci/aws/core/common/PostgresWire.java +++ b/src/main/java/io/floci/aws/core/common/PostgresWire.java @@ -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) { } diff --git a/src/main/java/io/floci/aws/services/dsql/DsqlDataPlane.java b/src/main/java/io/floci/aws/services/dsql/DsqlDataPlane.java index e3d90e3b76..d69a513ff8 100644 --- a/src/main/java/io/floci/aws/services/dsql/DsqlDataPlane.java +++ b/src/main/java/io/floci/aws/services/dsql/DsqlDataPlane.java @@ -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 running = new ConcurrentHashMap<>(); private final Set wanted = ConcurrentHashMap.newKeySet(); + // The starts and deletions still running, which a shutdown waits for. + private final Set 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 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> 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 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 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; + } + } } } diff --git a/src/main/java/io/floci/aws/services/dsql/DsqlService.java b/src/main/java/io/floci/aws/services/dsql/DsqlService.java index 59d97b691d..51d01e2178 100644 --- a/src/main/java/io/floci/aws/services/dsql/DsqlService.java +++ b/src/main/java/io/floci/aws/services/dsql/DsqlService.java @@ -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 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); } 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 index d179549631..ad48982ef6 100644 --- a/src/main/java/io/floci/aws/services/dsql/dataplane/BackendCredentials.java +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/BackendCredentials.java @@ -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); } 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 index 33badc9b1f..7480359d0c 100644 --- a/src/main/java/io/floci/aws/services/dsql/dataplane/DockerDsqlBackend.java +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/DockerDsqlBackend.java @@ -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 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 { 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 index 4a3dc50862..77c446fe51 100644 --- a/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBackend.java +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBackend.java @@ -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 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 leftoversOfFailed(DsqlCluster cluster) { + return Optional.empty(); + } } 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 index 86a7bdb264..4c0443dc51 100644 --- a/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBootstrap.java +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/DsqlBootstrap.java @@ -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("'", "''") + "'"; } 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 aa7b05a000..7dc549a660 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,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 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 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(); 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 3cb6eabd0f..280016a090 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 @@ -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 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 38fdaf14e1..5f9d2af38b 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 @@ -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 backendStartup = new LinkedHashMap<>(startupParameters); - backendStartup.remove("options"); - if (!optionSettings.isEmpty()) { - backendStartup.put("options", backendOptions(optionSettings)); - } - backendStartup.put("database", target.database()); + Map 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 backendStartup(Map startupParameters, + Map optionSettings, String backendUser, + String database) { + Map 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 settings) { List 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 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 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 diff --git a/src/main/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackend.java b/src/main/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackend.java new file mode 100644 index 0000000000..72c384f848 --- /dev/null +++ b/src/main/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackend.java @@ -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_}, owned by the NOLOGIN role {@code dsqlowner_}, and + * its backend roles carry the prefix {@code d_}, starting with its admin. PUBLIC may not connect + * to the database; its roles connect as members of the NOLOGIN role {@code dsqlconnect_}, 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 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 rolesToDrop(DsqlCluster cluster) throws SQLException { + return underLock(cluster.getIdentifier(), () -> rolesToDropLocked(cluster)); + } + + private List 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 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 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 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 leftoversOfFailed(DsqlCluster cluster) { + Names names = new Names(cluster.getIdentifier()); + List pending = cluster.getPendingBackendRoles(); + List 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 underLock(String clusterId, LockedWork 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 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$:$:}, which {@code PASSWORD} + * stores as it is. The salt, the first 16 bytes of HMAC-SHA256 of {@code scram-salt:} + * 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 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 known(DsqlCluster cluster, Names names) { + List 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:}. + */ + 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 always() { + return List.of(admin, connect, owner); + } + } +} diff --git a/src/main/java/io/floci/aws/services/dsql/model/DsqlCluster.java b/src/main/java/io/floci/aws/services/dsql/model/DsqlCluster.java index 21e6647864..dd7544bba3 100644 --- a/src/main/java/io/floci/aws/services/dsql/model/DsqlCluster.java +++ b/src/main/java/io/floci/aws/services/dsql/model/DsqlCluster.java @@ -32,6 +32,8 @@ public class DsqlCluster { private String witnessRegion; private List linkedClusterArns; private boolean databaseReady; + private String backendSecret; + private List 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 getPendingBackendRoles() { return pendingBackendRoles; } + public void setPendingBackendRoles(List pendingBackendRoles) { + this.pendingBackendRoles = pendingBackendRoles; + } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 2a8bda039d..64ebc6eae9 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -638,6 +638,13 @@ floci: port: 5432 # FLOCI_SERVICES_DSQL_PORT; the port every cluster endpoint is served on endpoint-suffix: localhost.floci.io # FLOCI_SERVICES_DSQL_ENDPOINT_SUFFIX; endpoints are .dsql.. image: "postgres:16-alpine" # FLOCI_SERVICES_DSQL_IMAGE + backend: docker # FLOCI_SERVICES_DSQL_BACKEND; docker (a container per cluster) or external (a PostgreSQL server that already runs) + external: + host: # FLOCI_SERVICES_DSQL_EXTERNAL_HOST; required with backend external + port: 5432 # FLOCI_SERVICES_DSQL_EXTERNAL_PORT + database: postgres # FLOCI_SERVICES_DSQL_EXTERNAL_DATABASE + username: postgres # FLOCI_SERVICES_DSQL_EXTERNAL_USERNAME + # password: # FLOCI_SERVICES_DSQL_EXTERNAL_PASSWORD; none by default redshift-data: enabled: true result-ttl-hours: 24 diff --git a/src/test/java/io/floci/aws/config/EmulatorConfigDsqlBackendTest.java b/src/test/java/io/floci/aws/config/EmulatorConfigDsqlBackendTest.java new file mode 100644 index 0000000000..d299be36b8 --- /dev/null +++ b/src/test/java/io/floci/aws/config/EmulatorConfigDsqlBackendTest.java @@ -0,0 +1,63 @@ +package io.floci.aws.config; + +import io.smallrye.config.PropertiesConfigSource; +import io.smallrye.config.SmallRyeConfig; +import io.smallrye.config.SmallRyeConfigBuilder; +import io.smallrye.config.source.yaml.YamlConfigSource; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class EmulatorConfigDsqlBackendTest { + + @Test + void theDsqlBackendDefaultsToDocker() throws IOException { + assertEquals(EmulatorConfig.DsqlServiceConfig.Backend.DOCKER, backend(Map.of())); + } + + @Test + void theDsqlBackendAcceptsLowerAndUpperCaseNames() throws IOException { + assertEquals(EmulatorConfig.DsqlServiceConfig.Backend.EXTERNAL, + backend(Map.of("floci.services.dsql.backend", "external"))); + assertEquals(EmulatorConfig.DsqlServiceConfig.Backend.EXTERNAL, + backend(Map.of("floci.services.dsql.backend", "EXTERNAL"))); + assertEquals(EmulatorConfig.DsqlServiceConfig.Backend.DOCKER, + backend(Map.of("floci.services.dsql.backend", "docker"))); + } + + @Test + void anUnknownDsqlBackendFailsNamingTheSettingAndTheValue() { + RuntimeException refused = assertThrows(RuntimeException.class, + () -> backend(Map.of("floci.services.dsql.backend", "kubernetes"))); + + String message = describe(refused); + assertTrue(message.contains("floci.services.dsql.backend"), message); + assertTrue(message.contains("kubernetes"), message); + assertTrue(message.contains("allowed values: external,docker"), message); + } + + private static EmulatorConfig.DsqlServiceConfig.Backend backend(Map overrides) + throws IOException { + SmallRyeConfig config = new SmallRyeConfigBuilder() + .addDefaultInterceptors() + .withMapping(EmulatorConfig.class) + .withSources(new YamlConfigSource(Path.of("src/main/resources/application.yml").toUri().toURL())) + .withSources(new PropertiesConfigSource(overrides, "test-overrides", 400)) + .build(); + return config.getConfigMapping(EmulatorConfig.class).services().dsql().backend(); + } + + private static String describe(Throwable failure) { + StringBuilder message = new StringBuilder(); + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + message.append(cause.getMessage()).append('\n'); + } + return message.toString(); + } +} diff --git a/src/test/java/io/floci/aws/core/common/PostgresWireTest.java b/src/test/java/io/floci/aws/core/common/PostgresWireTest.java index 225e1b47f7..2d51d464ef 100644 --- a/src/test/java/io/floci/aws/core/common/PostgresWireTest.java +++ b/src/test/java/io/floci/aws/core/common/PostgresWireTest.java @@ -25,6 +25,14 @@ class PostgresWireTest { assertEquals("E'line\nnext'", PostgresWire.quoteLiteral("line\nnext")); } + @Test + void quoteIdentifierAlwaysQuotesAndDoublesQuotes() { + assertEquals("\"admin\"", PostgresWire.quoteIdentifier("admin")); + assertEquals("\"App\"", PostgresWire.quoteIdentifier("App")); + assertEquals("\"a\"\"b\"", PostgresWire.quoteIdentifier("a\"b")); + assertEquals("\"select\"", PostgresWire.quoteIdentifier("select")); + } + @Test void aMessageIsFramedWithALengthThatCountsItself() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); diff --git a/src/test/java/io/floci/aws/services/dsql/DsqlClusterFixture.java b/src/test/java/io/floci/aws/services/dsql/DsqlClusterFixture.java index badecac822..aa06667baa 100644 --- a/src/test/java/io/floci/aws/services/dsql/DsqlClusterFixture.java +++ b/src/test/java/io/floci/aws/services/dsql/DsqlClusterFixture.java @@ -43,6 +43,14 @@ public final class DsqlClusterFixture { /** Creates the cluster and waits until it is ACTIVE; skips the test class when Docker is not there. */ public void create(DockerClient dockerClient) { + createAndAwait(dockerClient, "ACTIVE"); + } + + /** + * Creates the cluster and waits until its status is {@code status}; skips the test class when + * Docker is not there. + */ + public void createAndAwait(DockerClient dockerClient, String status) { try { dockerClient.pingCmd().exec(); } catch (Exception e) { @@ -52,7 +60,24 @@ public final class DsqlClusterFixture { .post("/cluster").then().statusCode(200).extract().path("identifier"); host = identifier + ".dsql." + REGION + ".localhost.floci.io"; await().atMost(Duration.ofMinutes(3)).pollInterval(Duration.ofMillis(500)).until(() -> - "ACTIVE".equals(dsql().get("/cluster/" + identifier).then().extract().path("status"))); + status.equals(status())); + } + + /** The cluster's status, as GetCluster reports it. */ + public String status() { + return dsql().get("/cluster/" + identifier).then().extract().path("status"); + } + + /** Asks for the cluster's deletion without waiting for it to finish. */ + public void requestDelete() { + if (identifier != null) { + dsql().delete("/cluster/" + identifier).then().statusCode(200); + } + } + + /** Lists the account's clusters in the fixture's Region; ListClusters answers 200. */ + public void listClusters() { + dsql().get("/cluster").then().statusCode(200); } public void delete() { diff --git a/src/test/java/io/floci/aws/services/dsql/DsqlDataPlaneTest.java b/src/test/java/io/floci/aws/services/dsql/DsqlDataPlaneTest.java new file mode 100644 index 0000000000..531a5b16e7 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dsql/DsqlDataPlaneTest.java @@ -0,0 +1,194 @@ +package io.floci.aws.services.dsql; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.services.dsql.dataplane.DsqlDatabases; +import io.floci.aws.services.dsql.dataplane.DsqlEndpoint; +import io.floci.aws.services.dsql.model.DsqlCluster; +import org.junit.jupiter.api.Test; + +import java.sql.SQLException; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * How the data plane treats a cluster whose database is still starting when Floci stops, and one + * whose server refuses it. + */ +class DsqlDataPlaneTest { + + private final DsqlDatabases databases = mock(DsqlDatabases.class); + private final DsqlEndpoint endpoint = mock(DsqlEndpoint.class); + private final CountDownLatch startBegun = new CountDownLatch(1); + private final CountDownLatch startMayFinish = new CountDownLatch(1); + private final List readies = new CopyOnWriteArrayList<>(); + private final AtomicReference> shutdown = new AtomicReference<>(); + private final List shutdownReturnedWhenDropped = new CopyOnWriteArrayList<>(); + + @Test + void withInMemoryStorageAClusterStillStartingAtShutdownIsDroppedAndNeverServed() throws Exception { + DsqlDataPlane plane = new DsqlDataPlane(config("memory"), databases, endpoint); + DsqlCluster cluster = cluster(); + startsSlowly(cluster); + + plane.provision(cluster, readies::add); + assertTrue(startBegun.await(10, TimeUnit.SECONDS)); + stopFlociOnceTheStartHasBegun(plane); + shutdown.get().get(10, TimeUnit.SECONDS); + + verify(databases, timeout(5_000)).stop(cluster, true); + verify(endpoint, never()).register(any(), any()); + assertEquals(List.of(), readies, "a cluster stopped with Floci is neither ready nor FAILED"); + } + + @Test + void withPersistentStorageAClusterStillStartingAtShutdownKeepsItsDataAndIsNeverServed() throws Exception { + DsqlDataPlane plane = new DsqlDataPlane(config("persistent"), databases, endpoint); + DsqlCluster cluster = cluster(); + startsSlowly(cluster); + + plane.provision(cluster, readies::add); + assertTrue(startBegun.await(10, TimeUnit.SECONDS)); + stopFlociOnceTheStartHasBegun(plane); + shutdown.get().get(10, TimeUnit.SECONDS); + + verify(databases, timeout(5_000)).stop(cluster, false); + verify(databases, never()).stop(cluster, true); + verify(endpoint, never()).register(any(), any()); + assertEquals(List.of(), readies, "so the next start of Floci starts it again"); + } + + @Test + void shutdownWaitsForAStartStillRunning() throws Exception { + DsqlDataPlane plane = new DsqlDataPlane(config("memory"), databases, endpoint); + DsqlCluster cluster = cluster(); + startsSlowly(cluster); + recordWhetherShutdownReturnedWhenDropped(cluster); + + plane.provision(cluster, readies::add); + assertTrue(startBegun.await(10, TimeUnit.SECONDS)); + stopFlociOnceTheStartHasBegun(plane); + + verify(databases, timeout(5_000)).stop(cluster, true); + shutdown.get().get(10, TimeUnit.SECONDS); + assertEquals(List.of(false), shutdownReturnedWhenDropped, "the start finished before Floci stopped"); + } + + @Test + void shutdownWaitsForADeletionStillRunning() throws Exception { + DsqlDataPlane plane = new DsqlDataPlane(config("memory"), databases, endpoint); + DsqlCluster cluster = cluster(); + when(databases.rolesToDrop(cluster)).thenAnswer(invocation -> { + startBegun.countDown(); + assertTrue(startMayFinish.await(10, TimeUnit.SECONDS)); + return List.of(); + }); + recordWhetherShutdownReturnedWhenDropped(cluster); + CountDownLatch gone = new CountDownLatch(1); + + plane.deprovision(cluster, false, roles -> { }, gone::countDown); + assertTrue(startBegun.await(10, TimeUnit.SECONDS)); + stopFlociOnceTheStartHasBegun(plane); + + shutdown.get().get(10, TimeUnit.SECONDS); + assertEquals(List.of(false), shutdownReturnedWhenDropped, "the deletion finished before Floci stopped"); + assertEquals(0, gone.getCount()); + } + + /** A start the server refuses, as it refuses a wrong superuser password, leaves the cluster not ready. */ + @Test + void aStartTheServerRefusesLeavesTheClusterNotReady() throws Exception { + DsqlDataPlane plane = new DsqlDataPlane(config("memory"), databases, endpoint); + DsqlCluster cluster = cluster(); + when(databases.start(cluster)).thenThrow(new SQLException("password authentication failed", "28P01")); + CountDownLatch reported = new CountDownLatch(1); + + plane.provision(cluster, ready -> { + readies.add(ready); + reported.countDown(); + }); + + assertTrue(reported.await(10, TimeUnit.SECONDS)); + assertEquals(List.of(false), readies, "so the cluster is FAILED"); + verify(endpoint, never()).register(any(), any()); + } + + /** + * A FAILED cluster whose server refuses the deletion is deleted anyway once its backend names + * what may remain there, as AWS deletes a FAILED cluster. + */ + @Test + void aFailedClusterWhoseServerRefusesTheDeletionIsDeletedAnyway() throws Exception { + DsqlDataPlane plane = new DsqlDataPlane(config("memory"), databases, endpoint); + DsqlCluster cluster = cluster(); + when(databases.rolesToDrop(cluster)).thenThrow(new SQLException("password authentication failed", "28P01")); + when(databases.leftoversOfFailed(cluster)).thenReturn(Optional.of("database dsql_abcdefghijklmnopqrstuvwxyz")); + CountDownLatch gone = new CountDownLatch(1); + + plane.deprovision(cluster, true, roles -> { }, gone::countDown); + + assertTrue(gone.await(10, TimeUnit.SECONDS), "the deletion finishes"); + verify(databases, never()).stop(any(), anyBoolean()); + } + + /** + * Stops Floci on another thread and lets the start or deletion go on once the shutdown has + * stopped the endpoint, so the shutdown is past its first step when the work finishes. + */ + private void stopFlociOnceTheStartHasBegun(DsqlDataPlane plane) { + doAnswer(invocation -> { + startMayFinish.countDown(); + return null; + }).when(endpoint).stop(); + shutdown.set(CompletableFuture.runAsync(() -> plane.onStop(null))); + } + + /** Records, when the cluster's data is dropped, whether the shutdown had already returned. */ + private void recordWhetherShutdownReturnedWhenDropped(DsqlCluster cluster) { + doAnswer(invocation -> { + CompletableFuture stopping = shutdown.get(); + shutdownReturnedWhenDropped.add(stopping != null && stopping.isDone()); + return null; + }).when(databases).stop(cluster, true); + } + + private void startsSlowly(DsqlCluster cluster) throws Exception { + when(databases.start(cluster)).thenAnswer(invocation -> { + startBegun.countDown(); + assertTrue(startMayFinish.await(10, TimeUnit.SECONDS)); + return null; + }); + when(databases.rolesToDrop(cluster)).thenReturn(List.of()); + } + + private static EmulatorConfig config(String storageMode) { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().dsql().mock()).thenReturn(false); + when(config.storage().mode()).thenReturn(storageMode); + return config; + } + + private static DsqlCluster cluster() { + DsqlCluster cluster = new DsqlCluster(); + cluster.setIdentifier("abcdefghijklmnopqrstuvwxyz"); + cluster.setArn("arn:aws:dsql:eu-west-1:111122223333:cluster/abcdefghijklmnopqrstuvwxyz"); + cluster.setEndpoint("abcdefghijklmnopqrstuvwxyz.dsql.eu-west-1.on.aws"); + return cluster; + } +} diff --git a/src/test/java/io/floci/aws/services/dsql/DsqlExternalBackendIntegrationTest.java b/src/test/java/io/floci/aws/services/dsql/DsqlExternalBackendIntegrationTest.java new file mode 100644 index 0000000000..ceff631911 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dsql/DsqlExternalBackendIntegrationTest.java @@ -0,0 +1,486 @@ +package io.floci.aws.services.dsql; + +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.services.dsql.dataplane.DsqlEndpoint; +import io.floci.aws.services.iam.IamService; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.postgresql.util.PSQLException; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Aurora DSQL's data plane with every cluster on one external PostgreSQL server that wants + * SCRAM-SHA-256 passwords: a client connects as DSQL's {@code admin} with an IAM token, and Floci + * logs in to the cluster's own database as the cluster's backend admin. + */ +@QuarkusTest +@TestProfile(DsqlExternalBackendProfile.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@Tag("docker") +class DsqlExternalBackendIntegrationTest { + + @Inject + DockerClient dockerClient; + + @Inject + DsqlEndpoint endpoint; + + @Inject + DsqlService service; + + @Inject + IamService iamService; + + @ConfigProperty(name = "quarkus.http.test-port", defaultValue = "0") + int httpPort; + + @ConfigProperty(name = "floci.services.dsql.external.port") + int serverPort; + + private static final String ROLE_ARN = "arn:aws:iam::" + DsqlClusterFixture.ACCOUNT + ":role/service/app-role"; + + private ExternalPostgresServer.Superuser postgres; + private DsqlClusterFixture cluster; + private final List created = new ArrayList<>(); + + @BeforeAll + void createCluster() { + postgres = new ExternalPostgresServer.Superuser(serverPort, ExternalPostgresResource.PASSWORD); + cluster = new DsqlClusterFixture(httpPort, endpoint); + cluster.create(dockerClient); + } + + @AfterAll + void deleteCluster() { + cluster.delete(); + } + + @AfterEach + void deleteCreatedClusters() { + for (DsqlClusterFixture each : created) { + each.delete(); + } + created.clear(); + } + + @Test + void adminConnectsThroughScramAuthenticatedBackend() throws Exception { + try (Connection connection = cluster.connect("admin", cluster.adminToken()); + Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("SELECT current_user, current_database(), sys.iam_session_user()")) { + assertTrue(row.next()); + assertEquals("d" + cluster.identifier() + "_admin", row.getString(1)); + assertEquals("dsql_" + cluster.identifier(), row.getString(2)); + assertEquals("arn:aws:iam::" + DsqlClusterFixture.ACCOUNT + ":root", row.getString(3)); + } + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_hba_file_rules WHERE type = 'host'" + + " AND auth_method <> 'scram-sha-256'"), "the server wants a SCRAM password of every TCP login"); + assertEquals("true", postgres.single("SELECT (rolpassword LIKE 'SCRAM-SHA-256$4096:%')::text FROM pg_authid" + + " WHERE rolname = '" + backendAdmin() + "'")); + } + + @Test + void aBackendThatRefusesTheLoginIsDsqlsAccessDenied() throws Exception { + // An expired password fails the SCRAM exchange whatever Floci sends. + postgres.execute("ALTER ROLE \"" + backendAdmin() + "\" VALID UNTIL '2000-01-01'"); + try { + PSQLException refused = assertThrows(PSQLException.class, () -> + cluster.connect("admin", cluster.adminToken()).close()); + + assertEquals("08006", refused.getSQLState()); + assertEquals("unable to accept connection, access denied", refused.getServerErrorMessage().getMessage()); + assertTrue(refused.getServerErrorMessage().getDetail().startsWith("Session Id: ")); + assertFalse(refused.getMessage().contains(cluster.identifier()), refused.getMessage()); + } finally { + postgres.execute("ALTER ROLE \"" + backendAdmin() + "\" VALID UNTIL 'infinity'"); + } + try (Connection connection = cluster.connect("admin", cluster.adminToken())) { + assertTrue(connection.isValid(5)); + } + } + + @Test + void aBackendThatAsksForACleartextPasswordIsRefused() throws Exception { + // The server asks the admin for its password in cleartext, as a peer posing as it could. + String hbaFile = postgres.single("SHOW hba_file"); + String original = postgres.single("SELECT pg_read_file('" + hbaFile + "')"); + writeHba(hbaFile, "host all " + backendAdmin() + " all password\n" + original); + try { + PSQLException refused = assertThrows(PSQLException.class, () -> + cluster.connect("admin", cluster.adminToken()).close()); + + assertEquals("08006", refused.getSQLState()); + assertEquals("unable to accept connection, access denied", refused.getServerErrorMessage().getMessage()); + } finally { + writeHba(hbaFile, original); + } + try (Connection connection = cluster.connect("admin", cluster.adminToken())) { + assertTrue(connection.isValid(5), "with SCRAM asked for again, the admin logs in"); + } + } + + @Test + void aBackendThatTrustsTheLoginLetsTheAdminIn() throws Exception { + // A trusting server asks for no password, so Floci sends none and the login goes through. + String hbaFile = postgres.single("SHOW hba_file"); + String original = postgres.single("SELECT pg_read_file('" + hbaFile + "')"); + writeHba(hbaFile, "host all " + backendAdmin() + " all trust\n" + original); + try (Connection connection = cluster.connect("admin", cluster.adminToken()); + Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("SELECT current_user")) { + assertTrue(row.next()); + assertEquals(backendAdmin(), row.getString(1)); + } finally { + writeHba(hbaFile, original); + } + } + + /** Replaces the server's pg_hba.conf with {@code content} and reloads it. */ + private void writeHba(String hbaFile, String content) throws SQLException { + try (Connection server = postgres.connect("postgres"); Statement statement = server.createStatement()) { + // CSV with a delimiter and quote no line holds writes each line as it is. + statement.execute("COPY (SELECT nullif(line, '') FROM unnest(string_to_array(rtrim($hba$" + content + + "$hba$, E'\\n'), E'\\n')) AS line) TO '" + hbaFile + + "' WITH (FORMAT csv, DELIMITER E'\\x01', QUOTE E'\\x02')"); + statement.execute("SELECT pg_reload_conf()"); + } + } + + @Test + void sixteenParallelAdminLoginsAllSucceed() throws Exception { + String verifier = postgres.single("SELECT rolpassword FROM pg_authid WHERE rolname = '" + backendAdmin() + "'"); + ExecutorService pool = Executors.newFixedThreadPool(16); + try { + List> logins = new ArrayList<>(); + for (int i = 0; i < 16; i++) { + logins.add(pool.submit(() -> { + try (Connection connection = cluster.connect("admin", cluster.adminToken()); + Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("SELECT current_user")) { + assertTrue(row.next()); + return row.getString(1); + } + })); + } + for (Future login : logins) { + assertEquals(backendAdmin(), login.get(60, TimeUnit.SECONDS)); + } + } finally { + pool.shutdownNow(); + } + assertEquals(verifier, postgres.single("SELECT rolpassword FROM pg_authid WHERE rolname = '" + backendAdmin() + + "'"), "the logins left the password as it was"); + } + + @Test + void twoClustersAreIsolated() throws Exception { + DsqlClusterFixture a = newCluster(); + DsqlClusterFixture b = newCluster(); + adminExecute(a, "CREATE TABLE a_only(x int)", "CREATE ROLE app"); + + adminExecute(b, "CREATE ROLE app"); + assertEquals(List.of("true"), adminQuery(b, "SELECT (to_regclass('a_only') IS NULL)::text")); + + assertEquals("1", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname = 'd" + a.identifier() + + "_app'")); + assertEquals("1", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname = 'd" + b.identifier() + + "_app'")); + // A password of the test's own, so the refusal below is the database's, not the login's. + String adminA = backendAdmin(a); + postgres.execute("ALTER ROLE \"" + adminA + "\" PASSWORD 'probe-password'"); + try (Connection own = DriverManager.getConnection(postgres.url("dsql_" + a.identifier()), adminA, + "probe-password")) { + assertTrue(own.isValid(5)); + } + PSQLException refused = assertThrows(PSQLException.class, () -> DriverManager.getConnection( + postgres.url("dsql_" + b.identifier()), adminA, "probe-password").close()); + assertTrue(List.of("42501", "28000").contains(refused.getSQLState()), refused.getSQLState() + ": " + + refused.getMessage()); + + // Floci sets the password it derives again on the next login. + try (Connection connection = a.connect("admin", a.adminToken())) { + assertTrue(connection.isValid(5)); + } + } + + @Test + void sysRolesShowsLogicalNames() throws Exception { + DsqlClusterFixture a = newCluster(); + DsqlClusterFixture b = newCluster(); + adminExecute(a, "CREATE ROLE app"); + adminExecute(b, "CREATE ROLE b_only"); + + assertEquals(List.of("admin", "app"), adminQuery(a, "SELECT rolname FROM sys.roles ORDER BY rolname"), + "logical names, no d_ names, no owner and nothing of the other cluster's"); + assertEquals(List.of("admin", "b_only"), adminQuery(b, "SELECT rolname FROM sys.roles ORDER BY rolname")); + + adminExecute(a, "AWS IAM GRANT app TO '" + ROLE_ARN + "'"); + assertEquals(List.of("app|admin"), adminQuery(a, + "SELECT pg_role_name || '|' || grantor_pg_role_name FROM sys.iam_pg_role_mappings")); + } + + @Test + void quotedRoleNameKeepsItsCase() throws Exception { + String prefix = "d" + cluster.identifier() + "_"; + adminExecute(cluster, "CREATE ROLE \"Reader\""); + try { + assertEquals("1", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname = '" + prefix + "Reader'")); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname = '" + prefix + "reader'")); + assertEquals(List.of("Reader"), adminQuery(cluster, + "SELECT rolname FROM sys.roles WHERE lower(rolname) = 'reader'")); + } finally { + adminExecute(cluster, "DROP ROLE \"Reader\""); + } + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname = '" + prefix + "Reader'")); + } + + @Test + void overlongRoleNameIsRefused() throws Exception { + String longest = "r".repeat(35); + String overlong = "r".repeat(36); + String prefix = "d" + cluster.identifier() + "_"; + String before = serverRolesOf(cluster); + + try (Connection admin = cluster.connect("admin", cluster.adminToken()); + Statement statement = admin.createStatement()) { + PSQLException refused = assertThrows(PSQLException.class, () -> + statement.execute("CREATE ROLE " + overlong)); + assertEquals("42602", refused.getSQLState()); + assertEquals("role name \"" + overlong + "\" is too long for Floci's external backend (max 35" + + " bytes)", refused.getServerErrorMessage().getMessage()); + } + assertEquals(before, serverRolesOf(cluster), "nothing was created"); + + adminExecute(cluster, "CREATE ROLE " + longest); + try { + assertEquals("63", postgres.single("SELECT length(rolname)::text FROM pg_roles WHERE rolname = '" + prefix + + longest + "'")); + } finally { + adminExecute(cluster, "DROP ROLE " + longest); + } + } + + @Test + void delegatedRolesAreRecordedAndDropped() throws Exception { + DsqlClusterFixture c = newCluster(); + String prefix = "d" + c.identifier() + "_"; + String accessKeyId = "ASIA" + Long.toString(System.nanoTime(), 36).toUpperCase(); + String secret = "delegate+session/secret=key"; + String sessionToken = "IQoJb3JpZ2luX2VjEJr+delegate/role+session=="; + iamService.registerLambdaExecutionRoleSession(DsqlClusterFixture.ACCOUNT, accessKeyId, secret, + sessionToken, ROLE_ARN); + try { + adminExecute(c, "CREATE ROLE b WITH LOGIN CREATEROLE", "AWS IAM GRANT b TO '" + ROLE_ARN + "'"); + try (Connection b = c.connect("b", c.token("DbConnect", accessKeyId, secret, Instant.now(), 900, + sessionToken)); Statement statement = b.createStatement()) { + statement.execute("CREATE ROLE c"); + } + } finally { + iamService.unregisterSession(DsqlClusterFixture.ACCOUNT, accessKeyId); + } + assertEquals(List.of("admin", "b", "c"), adminQuery(c, "SELECT rolname FROM sys.roles ORDER BY rolname")); + assertEquals("3", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname IN ('" + prefix + "admin', '" + + prefix + "b', '" + prefix + "c')")); + + deleteNow(c); + + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname IN ('" + prefix + "admin', '" + + prefix + "b', '" + prefix + "c', 'dsqlowner_" + c.identifier() + "', 'dsqlconnect_" + c.identifier() + + "')")); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_database WHERE datname = 'dsql_" + c.identifier() + + "'")); + } + + @Test + void aClientCannotCallFlocisRoleProceduresItself() throws Exception { + String before = serverRolesOf(cluster); + try (Connection admin = cluster.connect("admin", cluster.adminToken()); + Statement statement = admin.createStatement()) { + PSQLException refused = assertThrows(PSQLException.class, () -> + statement.execute("CALL sys.run_role_ddl('CREATE ROLE \"dother_x\"')")); + + assertEquals("42883", refused.getSQLState()); + assertEquals("procedure sys.run_role_ddl(text) does not exist", + refused.getServerErrorMessage().getMessage()); + } + assertEquals(before, serverRolesOf(cluster), "nothing was created"); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname = 'dother_x'")); + } + + @Test + void aClientsOwnTableAndFunctionNamedLikeTheRoleProceduresWork() throws Exception { + DsqlClusterFixture c = newCluster(); + adminExecute(c, "CREATE TABLE run_role_ddl (id int)", "INSERT INTO run_role_ddl (id) VALUES (1)", + "CREATE FUNCTION drop_roles(t text) RETURNS text LANGUAGE sql AS $f$ SELECT 'mine ' || t $f$"); + + assertEquals(List.of("1"), adminQuery(c, "SELECT id::text FROM run_role_ddl")); + assertEquals(List.of("mine x"), adminQuery(c, "SELECT drop_roles('x')")); + try (Connection admin = c.connect("admin", c.adminToken()); Statement statement = admin.createStatement()) { + PSQLException refused = assertThrows(PSQLException.class, () -> + statement.execute("CALL sys.run_role_ddl('CREATE ROLE x')")); + assertEquals("42883", refused.getSQLState()); + } + } + + @Test + void aRolePlantedUnderAnotherClustersPrefixIsNotItsAndDoesNotBlockItsDeletion() throws Exception { + DsqlClusterFixture a = newCluster(); + DsqlClusterFixture b = newCluster(); + String planted = "d" + a.identifier() + "_x"; + // B's admin creates a role under A's prefix in a SQL function body, where Floci translates no name, + // hands A's admin the ADMIN option on it, and gives it a privilege in B's database. + adminExecute(b, "CREATE TABLE planted_t(x int)"); + adminExecute(b, "CREATE FUNCTION plant() RETURNS void LANGUAGE sql AS $f$ CREATE ROLE \"" + planted + + "\"; GRANT \"" + planted + "\" TO \"" + backendAdmin(a) + "\" WITH ADMIN OPTION;" + + " GRANT SELECT ON planted_t TO \"" + planted + "\" $f$"); + adminExecute(b, "SELECT plant()"); + try { + assertEquals("true", postgres.single("SELECT pg_has_role('" + backendAdmin(a) + "', '" + planted + + "', 'MEMBER WITH ADMIN OPTION')::text")); + + // A records its roles again when its admin changes one. + adminExecute(a, "CREATE ROLE own"); + + assertEquals(List.of("admin", "own"), adminQuery(a, "SELECT rolname FROM sys.roles ORDER BY rolname"), + "the planted role is not one of A's"); + assertEquals("false", postgres.single("SELECT has_database_privilege('" + planted + "', 'dsql_" + + a.identifier() + "', 'CONNECT')::text")); + + deleteNow(a); + + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_database WHERE datname = 'dsql_" + + a.identifier() + "'"), "A's deletion finished"); + assertEquals("1", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname = '" + planted + "'"), + "and left the role B made"); + } finally { + try (Connection inB = postgres.connect("dsql_" + b.identifier()); + Statement statement = inB.createStatement()) { + statement.execute("DROP OWNED BY \"" + planted + "\""); + } + postgres.execute("DROP ROLE IF EXISTS \"" + planted + "\""); + } + } + + @Test + void deletionKeepsUnrelatedDatabasesAndRoles() throws Exception { + DsqlClusterFixture c = newCluster(); + String lookalike = "d" + c.identifier() + "_lookalike"; + postgres.execute("CREATE DATABASE unrelated"); + try { + postgres.execute("CREATE ROLE unrelated_role"); + postgres.execute("CREATE ROLE \"" + lookalike + "\""); + + deleteNow(c); + + assertEquals("1", postgres.single("SELECT count(*)::text FROM pg_database WHERE datname = 'unrelated'")); + assertEquals("2", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname IN ('unrelated_role', '" + + lookalike + "')")); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_database WHERE datname = 'dsql_" + + c.identifier() + "'"), "the cluster's own database is gone"); + } finally { + postgres.execute("DROP DATABASE IF EXISTS unrelated"); + postgres.execute("DROP ROLE IF EXISTS unrelated_role"); + postgres.execute("DROP ROLE IF EXISTS \"" + lookalike + "\""); + } + } + + @Test + void restartKeepsData() throws Exception { + DsqlClusterFixture c = newCluster(); + String admin = backendAdmin(c); + String database = "dsql_" + c.identifier(); + adminExecute(c, "CREATE TABLE kept(id int PRIMARY KEY, note text)"); + adminExecute(c, "INSERT INTO kept VALUES (1, 'survives')"); + String verifier = postgres.single("SELECT rolpassword FROM pg_authid WHERE rolname = '" + admin + "'"); + // Only a start's bootstrap grants it again, which tells the test when the start below has run. + postgres.execute("REVOKE \"dsqlconnect_" + c.identifier() + "\" FROM \"" + admin + "\""); + assertEquals("false", postgres.single("SELECT has_database_privilege('" + admin + "', '" + database + + "', 'CONNECT')::text")); + + // What a start of Floci does with the clusters in its storage. + service.onStart(null); + + await().atMost(Duration.ofMinutes(1)).pollInterval(Duration.ofMillis(200)).until(() -> + "true".equals(postgres.single("SELECT has_database_privilege('" + admin + "', '" + database + + "', 'CONNECT')::text"))); + await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(200)).ignoreExceptions().until(() -> + adminQuery(c, "SELECT note FROM kept WHERE id = 1").equals(List.of("survives"))); + assertEquals(verifier, postgres.single("SELECT rolpassword FROM pg_authid WHERE rolname = '" + admin + "'"), + "the cluster's saved secret gives its admin the same password"); + assertEquals("ACTIVE", c.status()); + } + + private String backendAdmin() { + return "d" + cluster.identifier() + "_admin"; + } + + private static String backendAdmin(DsqlClusterFixture fixture) { + return "d" + fixture.identifier() + "_admin"; + } + + private DsqlClusterFixture newCluster() { + DsqlClusterFixture fixture = new DsqlClusterFixture(httpPort, endpoint); + created.add(fixture); + fixture.create(dockerClient); + return fixture; + } + + /** Deletes the cluster through the API and waits until it is gone. */ + private void deleteNow(DsqlClusterFixture fixture) { + fixture.delete(); + created.remove(fixture); + } + + private static void adminExecute(DsqlClusterFixture fixture, String... statements) throws Exception { + try (Connection admin = fixture.connect("admin", fixture.adminToken()); + Statement statement = admin.createStatement()) { + for (String sql : statements) { + statement.execute(sql); + } + } + } + + private static List adminQuery(DsqlClusterFixture fixture, String sql) throws Exception { + List values = new ArrayList<>(); + try (Connection admin = fixture.connect("admin", fixture.adminToken()); + Statement statement = admin.createStatement(); ResultSet rows = statement.executeQuery(sql)) { + while (rows.next()) { + values.add(rows.getString(1)); + } + } + return values; + } + + /** The backend roles on the server that carry the cluster's prefix, in order. */ + private String serverRolesOf(DsqlClusterFixture fixture) throws SQLException { + return postgres.single("SELECT coalesce(string_agg(rolname, ',' ORDER BY rolname), '')" + + " FROM pg_roles WHERE starts_with(rolname, 'd" + fixture.identifier() + "_')"); + } +} diff --git a/src/test/java/io/floci/aws/services/dsql/DsqlExternalBackendProfile.java b/src/test/java/io/floci/aws/services/dsql/DsqlExternalBackendProfile.java new file mode 100644 index 0000000000..38f1d6ca99 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dsql/DsqlExternalBackendProfile.java @@ -0,0 +1,13 @@ +package io.floci.aws.services.dsql; + +import io.quarkus.test.junit.QuarkusTestProfile; + +import java.util.List; + +/** Clusters on one external PostgreSQL server, {@link ExternalPostgresResource}, instead of a container each. */ +public final class DsqlExternalBackendProfile implements QuarkusTestProfile { + @Override + public List testResources() { + return List.of(new TestResourceEntry(ExternalPostgresResource.class)); + } +} diff --git a/src/test/java/io/floci/aws/services/dsql/DsqlServiceTest.java b/src/test/java/io/floci/aws/services/dsql/DsqlServiceTest.java index e435beeb9e..62dda4102b 100644 --- a/src/test/java/io/floci/aws/services/dsql/DsqlServiceTest.java +++ b/src/test/java/io/floci/aws/services/dsql/DsqlServiceTest.java @@ -18,10 +18,12 @@ import java.util.Map; import java.util.function.Consumer; 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.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.doAnswer; @@ -53,9 +55,9 @@ class DsqlServiceTest { // A database that is ready at once and gone at once, as with floci.services.dsql.mock. readyAtOnce(dataPlane); doAnswer(call -> { - call.getArgument(1).run(); + call.getArgument(3).run(); return null; - }).when(dataPlane).deprovision(any(), any()); + }).when(dataPlane).deprovision(any(), anyBoolean(), any(), any()); when(principals.caller()).thenReturn(CallerArns.accountRoot(ROOT, ACCOUNT)); when(principals.exists(anyString())).thenAnswer(call -> call.getArgument(0, String.class).endsWith(":root")); } @@ -262,11 +264,81 @@ class DsqlServiceTest { after.onStart(null); verify(dataPlane).provision(argThat(cluster -> kept.getIdentifier().equals(cluster.getIdentifier())), any()); - verify(dataPlane).deprovision(argThat(cluster -> deleting.getIdentifier().equals(cluster.getIdentifier())), any()); + verify(dataPlane).deprovision(argThat(cluster -> deleting.getIdentifier().equals(cluster.getIdentifier())), + anyBoolean(), any(), any()); assertEquals(DsqlService.ACTIVE, after.getCluster(REGION, kept.getIdentifier()).getStatus()); assertThrows(AwsException.class, () -> after.getCluster(REGION, deleting.getIdentifier())); } + @Test + void getClusterResponseNeverCarriesTheBackendSecret() throws Exception { + DsqlCluster cluster = cluster(); + cluster.setBackendSecret("c2VjcmV0"); + cluster.setPendingBackendRoles(List.of("dabc_admin")); + DsqlController controller = new DsqlController(service, new RegionResolver(REGION, ACCOUNT)); + + String got = mapper.writeValueAsString(controller.getCluster(null, cluster.getIdentifier()).getEntity()); + String listed = mapper.writeValueAsString(controller.listClusters(null, null, null).getEntity()); + + for (String json : List.of(got, listed)) { + assertTrue(json.contains(cluster.getIdentifier()), json); + assertFalse(json.contains("backendSecret"), json); + assertFalse(json.contains("c2VjcmV0"), json); + assertFalse(json.contains("pendingBackendRoles"), json); + assertFalse(json.contains("dabc_admin"), json); + } + } + + /** + * Deleting a cluster saves the roles its deletion drops before any is dropped, so a deletion + * the stop interrupts drops the same roles on the next start. + */ + @Test + void aDeletionKeepsTheRolesItDropsInStorage() { + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT); + DsqlDataPlane stopping = mock(DsqlDataPlane.class); + readyAtOnce(stopping); + doAnswer(call -> { + call.>>getArgument(2).accept(List.of("dabc_app", "dabc_admin", "dsqlowner_abc")); + return null; + }).when(stopping).deprovision(any(), anyBoolean(), any(), any()); + DsqlService before = service(storage, stopping); + DsqlCluster cluster = before.createCluster(REGION, false, null, null, null, null, null, null, false); + + before.deleteCluster(REGION, cluster.getIdentifier()); + + DsqlCluster stored = storage.getForAccount(ACCOUNT, REGION + "::" + cluster.getIdentifier()).orElseThrow(); + assertEquals(List.of("dabc_app", "dabc_admin", "dsqlowner_abc"), stored.getPendingBackendRoles()); + assertEquals(DsqlService.DELETING, stored.getStatus()); + } + + /** The secret the backend generated while it started is saved with the cluster. */ + @Test + void theBackendSecretIsSavedOnceTheDatabaseStarts() { + AccountAwareStorageBackend storage = + new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, ACCOUNT); + DsqlDataPlane starting = mock(DsqlDataPlane.class); + doAnswer(call -> { + // A copy, as storage that serializes would hand back, so only an explicit save keeps it. + storage.putForAccount(ACCOUNT, REGION + "::" + call.getArgument(0).getIdentifier(), + copy(call.getArgument(0))); + call.getArgument(0).setBackendSecret("c2VjcmV0"); + call.>getArgument(1).accept(true); + return null; + }).when(starting).provision(any(), any()); + DsqlService started = service(storage, starting); + + DsqlCluster cluster = started.createCluster(REGION, false, null, null, null, null, null, null, false); + + assertEquals("c2VjcmV0", storage.getForAccount(ACCOUNT, REGION + "::" + cluster.getIdentifier()) + .orElseThrow().getBackendSecret()); + } + + private DsqlCluster copy(DsqlCluster cluster) { + return new ObjectMapper().findAndRegisterModules().convertValue(cluster, DsqlCluster.class); + } + /** Makes {@code plane} start every cluster's database at once. */ private static void readyAtOnce(DsqlDataPlane plane) { doAnswer(call -> { diff --git a/src/test/java/io/floci/aws/services/dsql/ExternalPostgresResource.java b/src/test/java/io/floci/aws/services/dsql/ExternalPostgresResource.java new file mode 100644 index 0000000000..5c4c5c60b1 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dsql/ExternalPostgresResource.java @@ -0,0 +1,58 @@ +package io.floci.aws.services.dsql; + +import io.quarkus.test.common.QuarkusTestResourceLifecycleManager; +import org.jboss.logging.Logger; + +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +/** + * A throwaway PostgreSQL 16 that wants SCRAM-SHA-256 passwords, as a shared server does, started + * before Floci boots and set as the external DSQL backend. Without Docker the overrides point at a + * port where nothing listens, and {@link DsqlClusterFixture#create} skips the test class; any other + * failure to start the server fails the boot, with its cause. + */ +public final class ExternalPostgresResource implements QuarkusTestResourceLifecycleManager { + + private static final Logger LOG = Logger.getLogger(ExternalPostgresResource.class); + + public static final String PASSWORD = "floci-test"; + + private ExternalPostgresServer server; + + @Override + public Map start() { + Map overrides = new HashMap<>(); + // A real data plane for each cluster, its endpoint on an ephemeral port. + overrides.put("floci.services.dsql.mock", "false"); + overrides.put("floci.services.dsql.port", "0"); + overrides.put("floci.services.dsql.backend", "external"); + overrides.put("floci.services.dsql.external.host", "127.0.0.1"); + overrides.put("floci.services.dsql.external.password", PASSWORD); + int port; + try { + server = ExternalPostgresServer.start("floci-dsql-external", PASSWORD, "POSTGRES_PASSWORD=" + PASSWORD, + "POSTGRES_INITDB_ARGS=--auth-host=scram-sha-256"); + port = server.port(); + } catch (ExternalPostgresServer.DockerUnavailableException e) { + LOG.warnv(e, "No external PostgreSQL for the DSQL tests; they skip"); + // Nothing listens on port 1; the tests skip before they create a cluster. + port = 1; + } catch (SQLException e) { + throw new IllegalStateException("The external PostgreSQL for the DSQL tests did not start", e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while the external PostgreSQL started", e); + } + overrides.put("floci.services.dsql.external.port", String.valueOf(port)); + return overrides; + } + + @Override + public void stop() { + if (server != null) { + server.close(); + } + } +} diff --git a/src/test/java/io/floci/aws/services/dsql/ExternalPostgresServer.java b/src/test/java/io/floci/aws/services/dsql/ExternalPostgresServer.java index 9d35e23e96..e4769582d1 100644 --- a/src/test/java/io/floci/aws/services/dsql/ExternalPostgresServer.java +++ b/src/test/java/io/floci/aws/services/dsql/ExternalPostgresServer.java @@ -7,19 +7,25 @@ import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.PortBinding; import com.github.dockerjava.api.model.Ports; -import io.floci.aws.services.dsql.dataplane.DockerDsqlBackend; +import io.floci.aws.services.dsql.dataplane.DsqlDatabases; import io.floci.aws.testing.DockerAvailability; import io.floci.aws.testing.TestDockerClients; +import org.jboss.logging.Logger; import java.io.IOException; +import java.sql.Connection; import java.sql.DriverManager; +import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * A throwaway PostgreSQL 16 in Docker for the external DSQL backend's tests, bound to a free port * on 127.0.0.1, whose superuser is {@code postgres}. {@link #close()} removes the container and @@ -27,17 +33,57 @@ import java.util.concurrent.TimeUnit; */ public final class ExternalPostgresServer implements AutoCloseable { + private static final Logger LOG = Logger.getLogger(ExternalPostgresServer.class); + public static final String IMAGE = "postgres:16-alpine"; private static final Duration READY_TIMEOUT = Duration.ofSeconds(60); private final DockerClient dockerClient; private final String containerId; private final int port; + private final String password; - private ExternalPostgresServer(DockerClient dockerClient, String containerId, int port) { + private ExternalPostgresServer(DockerClient dockerClient, String containerId, int port, String password) { this.dockerClient = dockerClient; this.containerId = containerId; this.port = port; + this.password = password; + } + + /** + * The superuser {@code postgres} of a test server on 127.0.0.1, for the SQL a test runs on it + * directly, outside Floci. + */ + public record Superuser(int port, String password) { + + public String url(String database) { + return jdbcUrl(port, database); + } + + public Connection connect(String database) throws SQLException { + return DriverManager.getConnection(url(database), "postgres", password); + } + + /** The first column of the one row {@code sql} returns in {@code database}. */ + public String single(String database, String sql) throws SQLException { + try (Connection connection = connect(database); Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery(sql)) { + assertTrue(row.next(), sql); + return row.getString(1); + } + } + + /** The first column of the one row {@code sql} returns in the database {@code postgres}. */ + public String single(String sql) throws SQLException { + return single("postgres", sql); + } + + /** Runs {@code sql} in the database {@code postgres}. */ + public void execute(String sql) throws SQLException { + try (Connection connection = connect("postgres"); Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } } /** Docker, or the image, is not there; a test skips rather than fails. Its cause says why. */ @@ -51,7 +97,7 @@ public final class ExternalPostgresServer implements AutoCloseable { * Starts a container named {@code name} plus a random suffix, with {@code env} besides * {@code POSTGRES_USER=postgres}, and waits until {@code postgres} logs in with * {@code password} (empty where the server trusts its connections), through the readiness loop - * the Docker backend waits for a cluster's database with. + * the DSQL backends wait for a server with. */ public static ExternalPostgresServer start(String name, String password, String... env) throws DockerUnavailableException, SQLException, InterruptedException { @@ -80,9 +126,9 @@ public final class ExternalPostgresServer implements AutoCloseable { InspectContainerResponse inspected = dockerClient.inspectContainerCmd(containerId).exec(); int port = Integer.parseInt( inspected.getNetworkSettings().getPorts().getBindings().get(exposed)[0].getHostPortSpec()); - DockerDsqlBackend.awaitReady(() -> DriverManager.getConnection(jdbcUrl(port, "postgres"), "postgres", - password), READY_TIMEOUT); - return new ExternalPostgresServer(dockerClient, containerId, port); + DsqlDatabases.awaitConnection(() -> DriverManager.getConnection(jdbcUrl(port, "postgres"), "postgres", + password), READY_TIMEOUT, DsqlDatabases.READY_INTERVAL, false, "The test's PostgreSQL").close(); + return new ExternalPostgresServer(dockerClient, containerId, port, password); } catch (DockerUnavailableException | SQLException | InterruptedException | RuntimeException e) { close(dockerClient, containerId, e); throw e; @@ -97,6 +143,10 @@ public final class ExternalPostgresServer implements AutoCloseable { return jdbcUrl(port, database); } + public Superuser superuser() { + return new Superuser(port, password); + } + private static String jdbcUrl(int port, String database) { return "jdbc:postgresql://127.0.0.1:" + port + "/" + database; } @@ -128,7 +178,7 @@ public final class ExternalPostgresServer implements AutoCloseable { if (failure != null) { failure.addSuppressed(e); } else { - System.err.println(what + ": " + e.getMessage()); + LOG.warnv(e, "{0}", what); } } } 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 index 4e2cbd550d..d53844e422 100644 --- a/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlDatabasesTest.java +++ b/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlDatabasesTest.java @@ -2,10 +2,19 @@ package io.floci.aws.services.dsql.dataplane; import org.junit.jupiter.api.Test; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + 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.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; class DsqlDatabasesTest { @@ -35,4 +44,86 @@ class DsqlDatabasesTest { void aTrustedDatabaseWantsNoPassword() { assertNull(BackendCredentials.TRUST.passwordFor("x")); } + + @Test + void aServerNotYetAcceptingConnectionsIsWaitedFor() throws SQLException { + Connection server = mock(Connection.class); + AtomicInteger attempts = new AtomicInteger(); + + Connection opened = DsqlDatabases.awaitConnection(() -> { + if (attempts.incrementAndGet() < 3) { + throw new SQLException("the database system is starting up", "57P03"); + } + return server; + }, Duration.ofSeconds(10), Duration.ofMillis(1), true, "The server"); + + assertSame(server, opened); + assertEquals(3, attempts.get()); + } + + @Test + void aRefusedLoginIsNotRetriedWhenItIsFinal() { + AtomicInteger attempts = new AtomicInteger(); + long started = System.nanoTime(); + + SQLException refused = assertThrows(SQLException.class, () -> DsqlDatabases.awaitConnection(() -> { + attempts.incrementAndGet(); + throw new SQLException("password authentication failed for user \"postgres\"", "28P01"); + }, Duration.ofSeconds(90), Duration.ofMillis(250), true, "The server")); + + assertEquals("28P01", refused.getSQLState()); + assertEquals(1, attempts.get()); + assertTrue(System.nanoTime() - started < TimeUnit.SECONDS.toNanos(5), "it fails at once"); + } + + @Test + void aRefusedLoginIsTriedAgainWhenItIsNotFinal() throws SQLException { + // The Docker backend's wait, which tries a refused login again as it always did. + Connection server = mock(Connection.class); + AtomicInteger attempts = new AtomicInteger(); + + Connection opened = DsqlDatabases.awaitConnection(() -> { + if (attempts.incrementAndGet() < 3) { + throw new SQLException("role \"dbowner\" does not exist", "28000"); + } + return server; + }, Duration.ofSeconds(10), Duration.ofMillis(1), false, "The database"); + + assertSame(server, opened); + assertEquals(3, attempts.get()); + } + + @Test + void aServerThatNeverAnswersFailsAtTheDeadlineWithItsLastError() { + AtomicInteger attempts = new AtomicInteger(); + SQLException last = new SQLException("Connection refused", "08001"); + + SQLException refused = assertThrows(SQLException.class, () -> DsqlDatabases.awaitConnection(() -> { + attempts.incrementAndGet(); + throw last; + }, Duration.ofMillis(100), Duration.ofMillis(10), true, "The external PostgreSQL server db.example:5432")); + + assertEquals("The external PostgreSQL server db.example:5432 did not let Floci in within 0 s: Connection" + + " refused", refused.getMessage()); + assertEquals("08001", refused.getSQLState()); + assertSame(last, refused.getCause()); + assertTrue(attempts.get() > 1, "it was tried again"); + } + + @Test + void aZeroTimeoutStillTriesOnce() { + AtomicInteger attempts = new AtomicInteger(); + + assertThrows(SQLException.class, () -> DsqlDatabases.awaitConnection(() -> { + attempts.incrementAndGet(); + throw new SQLException("Connection refused", "08001"); + }, Duration.ZERO, DsqlDatabases.READY_INTERVAL, true, "The server")); + + assertEquals(1, attempts.get()); + } + + @Test + void bothBackendsTryEvery250Milliseconds() { + assertEquals(Duration.ofMillis(250), DsqlDatabases.READY_INTERVAL); + } } diff --git a/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlSessionTest.java b/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlSessionTest.java index 1cc90f1a87..2da0a88765 100644 --- a/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlSessionTest.java +++ b/src/test/java/io/floci/aws/services/dsql/dataplane/DsqlSessionTest.java @@ -3,6 +3,8 @@ package io.floci.aws.services.dsql.dataplane; import io.floci.aws.core.common.PostgresWire; import org.junit.jupiter.api.Test; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -138,6 +140,55 @@ class DsqlSessionTest { fields.get('W')); } + @Test + void parseMessageRoleNamesAreTranslated() { + byte[] parameterTypes = {0, 1, 0, 0, 0, 23}; + ByteArrayOutputStream body = new ByteArrayOutputStream(); + body.writeBytes(PostgresWire.cStringBytes("s1")); + body.writeBytes(PostgresWire.cStringBytes("GRANT SELECT ON t TO app")); + body.writeBytes(parameterTypes); + PostgresWire.Message parse = new PostgresWire.Message((byte) 'P', body.toByteArray()); + + DsqlSession.ParseRewrite prefixed = DsqlSession.rewriteParse(parse, new PrefixedRoleNames("x")); + DsqlSession.ParseRewrite identity = DsqlSession.rewriteParse(parse, RoleNames.IDENTITY); + + assertEquals("s1", prefixed.name()); + assertEquals('P', prefixed.message().type()); + PostgresWire.CString name = PostgresWire.cString(prefixed.message().body(), 0); + PostgresWire.CString query = PostgresWire.cString(prefixed.message().body(), name.next()); + assertEquals("s1", name.value()); + assertTrue(query.value().contains("dx_app"), query.value()); + assertArrayEquals(parameterTypes, Arrays.copyOfRange(prefixed.message().body(), query.next(), + prefixed.message().body().length)); + String untranslated = PostgresWire.cString(identity.message().body(), name.next()).value(); + assertFalse(untranslated.contains("dx_app"), untranslated); + assertTrue(untranslated.contains("app"), untranslated); + } + + @Test + void backendStartupUsesTheBackendRoleAndDatabase() { + Map client = new LinkedHashMap<>(); + client.put("user", "admin"); + client.put("database", "postgres"); + client.put("application_name", "psql"); + client.put("options", "-c search_path=public --ignored=1"); + Map settings = DsqlSession.optionSettings(client.get("options")); + + Map external = DsqlSession.backendStartup(client, settings, "dx_admin", "dsql_x"); + Map docker = DsqlSession.backendStartup(client, settings, "admin", "postgres"); + + assertEquals("dx_admin", external.get("user")); + assertEquals("dsql_x", external.get("database")); + assertEquals("psql", external.get("application_name")); + assertEquals("-c search_path=public", external.get("options")); + assertEquals(List.of("user", "database", "application_name", "options"), List.copyOf(external.keySet())); + assertEquals("admin", docker.get("user")); + assertEquals("postgres", docker.get("database")); + assertEquals("admin", client.get("user"), "the client's own parameters are left as they are"); + assertEquals(Map.of("user", "admin", "database", "postgres"), + DsqlSession.backendStartup(Map.of("user", "admin"), Map.of(), "admin", "postgres")); + } + private static byte[] error(Map fields) { Map ordered = new LinkedHashMap<>(); ordered.put('S', fields.getOrDefault('S', "ERROR")); diff --git a/src/test/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackendIntegrationTest.java b/src/test/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackendIntegrationTest.java new file mode 100644 index 0000000000..9584814469 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackendIntegrationTest.java @@ -0,0 +1,552 @@ +package io.floci.aws.services.dsql.dataplane; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.services.dsql.DsqlPrincipals; +import io.floci.aws.services.dsql.ExternalPostgresServer; +import io.floci.aws.services.dsql.model.DsqlCluster; +import io.floci.aws.services.iam.IamPolicyEvaluator; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.iam.ResourcePolicyProvider; +import io.floci.aws.services.iam.ScpProvider; +import jakarta.enterprise.inject.Instance; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.opentest4j.TestAbortedException; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Clock; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Creates, starts again and deletes one cluster's database and roles on a throwaway PostgreSQL 16 + * that wants passwords, as a shared server does, through the external backend alone. + */ +@Tag("docker") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class ExternalDsqlBackendIntegrationTest { + + private static final String PASSWORD = "floci-test"; + private static final String ID = "abcdefghijklmnopqrstuvwxyz"; + private static final String DATABASE = "dsql_" + ID; + private static final String ADMIN = "d" + ID + "_admin"; + private static final String OWNER = "dsqlowner_" + ID; + private static final String CONNECT = "dsqlconnect_" + ID; + + private ExternalPostgresServer server; + private ExternalPostgresServer.Superuser postgres; + private int port; + + @BeforeAll + void startServer() throws Exception { + try { + server = ExternalPostgresServer.start("floci-dsql-external", PASSWORD, "POSTGRES_PASSWORD=" + PASSWORD); + } catch (ExternalPostgresServer.DockerUnavailableException e) { + throw new TestAbortedException(e.getMessage(), e); + } + port = server.port(); + postgres = server.superuser(); + } + + @AfterAll + void removeServer() { + if (server != null) { + server.close(); + } + } + + @Test + void aClusterIsCreatedStartedAgainAndDeletedWithItsRoles() throws Exception { + ExternalDsqlBackend backend = new ExternalDsqlBackend(config()); + DsqlCluster cluster = cluster(ID); + + DsqlDatabases.Backend first = backend.start(cluster); + String secret = cluster.getBackendSecret(); + DsqlDatabases.Backend again = backend.start(cluster); + + assertEquals(secret, cluster.getBackendSecret()); + String marker = "floci:dsql:" + cluster.getArn(); + assertEquals(marker, postgres.single("SELECT shobj_description(oid, 'pg_database') FROM pg_database" + + " WHERE datname = '" + DATABASE + "'"), "the database carries the cluster's marker"); + assertEquals(List.of(marker, marker, marker), List.of( + postgres.single("SELECT shobj_description(oid, 'pg_authid') FROM pg_roles WHERE rolname = '" + + ADMIN + "'"), + postgres.single("SELECT shobj_description(oid, 'pg_authid') FROM pg_roles WHERE rolname = '" + + CONNECT + "'"), + postgres.single("SELECT shobj_description(oid, 'pg_authid') FROM pg_roles WHERE rolname = '" + + OWNER + "'")), "so do its admin, connect role and owner, which the start again reused"); + assertEquals(DATABASE, again.database()); + assertTrue(again.credentials().scramOnly(), "logins answer SCRAM alone"); + assertEquals("postgres", again.superuser()); + assertEquals(PASSWORD, again.superuserPassword()); + assertEquals(first.credentials().passwordFor(ADMIN), again.credentials().passwordFor(ADMIN)); + try (Connection admin = DriverManager.getConnection(again.jdbcUrl(), ADMIN, + again.credentials().passwordFor(ADMIN)); Statement statement = admin.createStatement()) { + statement.execute("CALL sys.run_role_ddl($$CREATE ROLE d" + ID + "_app$$)"); + } + assertEquals("false", postgres.single("SELECT rolcreatedb::text FROM pg_roles WHERE rolname = '" + + ADMIN + "'")); + assertEquals("false", postgres.single("SELECT has_database_privilege('public', '" + DATABASE + + "', 'CONNECT')::text")); + assertEquals("true", postgres.single("SELECT (pg_has_role('d" + ID + "_app', '" + CONNECT + + "', 'USAGE') AND has_database_privilege('d" + ID + "_app', '" + DATABASE + "', 'CONNECT'))::text"), + "a role the admin created connects as a member of the connect role"); + + List roles = backend.rolesToDrop(cluster); + assertEquals(List.of("d" + ID + "_app", ADMIN, CONNECT, OWNER), roles); + cluster.setPendingBackendRoles(roles); + try (Connection open = DriverManager.getConnection(again.jdbcUrl(), ADMIN, + again.credentials().passwordFor(ADMIN))) { + // A session still open on the database does not keep it from being dropped. + backend.stop(cluster, true); + assertFalse(open.isValid(1), "the session was ended"); + } + + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_database WHERE datname = '" + + DATABASE + "'")); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname LIKE 'd" + ID + + "%' OR rolname IN ('" + OWNER + "', '" + CONNECT + "')")); + assertEquals(roles, backend.rolesToDrop(cluster), "with the database gone, the saved roles are dropped"); + backend.stop(cluster, true); + } + + @Test + void aSessionOpenWhenTheRolesAreListedCannotCreateARoleTheDeletionWouldMiss() throws Exception { + String id = "pppppqqqqqrrrrrsssssttttto"; + String admin = "d" + id + "_admin"; + ExternalDsqlBackend backend = new ExternalDsqlBackend(config()); + DsqlCluster cluster = cluster(id); + DsqlDatabases.Backend started = backend.start(cluster); + try (Connection open = DriverManager.getConnection(started.jdbcUrl(), admin, + started.credentials().passwordFor(admin)); Statement statement = open.createStatement()) { + List roles = backend.rolesToDrop(cluster); + cluster.setPendingBackendRoles(roles); + + // A statement of a session that was already open, arriving after the roles were listed. + assertThrows(SQLException.class, + () -> statement.execute("CALL sys.run_role_ddl($$CREATE ROLE d" + id + "_late$$)"), + "listing the roles ended the sessions on the database, so none can add one after it"); + } finally { + backend.stop(cluster, true); + } + + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname LIKE 'd" + id + + "%' OR rolname IN ('dsqlowner_" + id + "', 'dsqlconnect_" + id + "')"), + "no role of the cluster is left on the server"); + } + + @Test + void aFailedStartLeavesARoleItDidNotCreate() throws Exception { + String id = "zyxwvutsrqponmlkjihgfedcba"; + String owner = "dsqlowner_" + id; + DsqlCluster cluster = cluster(id); + try (Connection server = postgres.connect("postgres"); Statement statement = server.createStatement()) { + // An owner and a database an earlier start created for this cluster, so they carry its marker. + statement.execute("CREATE ROLE " + owner + " NOLOGIN"); + statement.execute("COMMENT ON ROLE " + owner + " IS '" + ExternalDsqlBackend.marker(cluster) + "'"); + // A database whose sys.backend_roles has another shape fails the bootstrap. + statement.execute("CREATE DATABASE dsql_" + id); + statement.execute("COMMENT ON DATABASE dsql_" + id + " IS '" + ExternalDsqlBackend.marker(cluster) + "'"); + } + try (Connection database = postgres.connect("dsql_" + id); Statement statement = database.createStatement()) { + statement.execute("CREATE SCHEMA sys"); + statement.execute("CREATE TABLE sys.backend_roles (unexpected int)"); + } + + boolean failed = false; + try { + new ExternalDsqlBackend(config()).start(cluster); + } catch (SQLException e) { + failed = true; + } + + assertTrue(failed, "the bootstrap fails on a sys.backend_roles of another shape"); + assertEquals("1", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname = '" + owner + "'")); + assertEquals("1", postgres.single("SELECT count(*)::text FROM pg_database WHERE datname = 'dsql_" + id + + "'")); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname IN ('d" + id + + "_admin', 'dsqlconnect_" + id + "')"), "the admin and connect role this attempt created are dropped again"); + assertFalse(cluster.getBackendSecret() == null); + } + + @Test + void passwordsAreStoredAsScramVerifiersThatALoginSetsAgain() throws Exception { + String id = "mnopqrstuvwxyzabcdefghijkl"; + String admin = "d" + id + "_admin"; + String owner = "dsqlowner_" + id; + ExternalDsqlBackend backend = new ExternalDsqlBackend(config()); + DsqlCluster cluster = cluster(id); + DsqlDatabases.Backend started = backend.start(cluster); + try { + String verifier = started.credentials().verifierFor(admin); + String password = started.credentials().passwordFor(admin); + assertFalse(DsqlEndpoint.setLoginPassword(started, admin), "a password already set is left as it is"); + assertTrue(verifier.startsWith("SCRAM-SHA-256$4096:"), verifier); + assertEquals(verifier, postgres.single("SELECT rolpassword FROM pg_authid WHERE rolname = '" + + admin + "'"), "the server keeps the verifier Floci sent, not one of its own"); + try (Connection server = postgres.connect("postgres"); Statement statement = server.createStatement()) { + statement.execute("ALTER ROLE " + admin + " PASSWORD 'changed-behind-flocis-back'"); + } + + assertTrue(DsqlEndpoint.setLoginPassword(started, admin)); + assertFalse(DsqlEndpoint.setLoginPassword(started, admin), "once set, it is not set again"); + + assertEquals(verifier, postgres.single("SELECT rolpassword FROM pg_authid WHERE rolname = '" + + admin + "'")); + try (Connection login = DriverManager.getConnection(started.jdbcUrl(), admin, password); + Statement statement = login.createStatement(); + ResultSet row = statement.executeQuery("SELECT current_user")) { + assertTrue(row.next()); + assertEquals(admin, row.getString(1)); + } + assertFalse(DsqlEndpoint.setLoginPassword(started, "d" + id + "_nosuch"), "a missing role is left alone"); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname = 'd" + id + + "_nosuch'")); + assertFalse(DsqlEndpoint.setLoginPassword(started, owner), "a role that cannot log in is left alone"); + assertEquals("true", postgres.single("SELECT (rolpassword IS NULL)::text FROM pg_authid" + + " WHERE rolname = '" + owner + "'")); + } finally { + cluster.setPendingBackendRoles(backend.rolesToDrop(cluster)); + backend.stop(cluster, true); + } + } + + @Test + void deletionFinishesFromPersistedListWhenDatabaseIsGone() throws Exception { + String id = "ghijklmnopqrstuvwxyzabcdef"; + String admin = "d" + id + "_admin"; + ExternalDsqlBackend backend = new ExternalDsqlBackend(config()); + DsqlCluster cluster = cluster(id); + DsqlDatabases.Backend started = backend.start(cluster); + try (Connection login = DriverManager.getConnection(started.jdbcUrl(), admin, + started.credentials().passwordFor(admin)); Statement statement = login.createStatement()) { + statement.execute("CALL sys.run_role_ddl($$CREATE ROLE d" + id + "_app$$)"); + } + List roles = backend.rolesToDrop(cluster); + // What DsqlDataPlane persists with the cluster before it drops anything. + cluster.setPendingBackendRoles(roles); + try (Connection server = postgres.connect("postgres"); Statement statement = server.createStatement()) { + // A deletion interrupted after its DROP DATABASE. + statement.execute("DROP DATABASE dsql_" + id + " WITH (FORCE)"); + } + assertEquals("4", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname LIKE 'd" + id + + "%' OR rolname IN ('dsqlowner_" + id + "', 'dsqlconnect_" + id + "')")); + + assertEquals(roles, backend.rolesToDrop(cluster), "with the database gone, the persisted list"); + backend.stop(cluster, true); + + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname LIKE 'd" + id + + "%' OR rolname IN ('dsqlowner_" + id + "', 'dsqlconnect_" + id + "')"), + "the role created in the cluster is dropped too"); + } + + @Test + void failedBootstrapCleansUpWhatItCreated() throws Exception { + String id = "qrstuvwxyzabcdefghijklmnop"; + String database = "dsql_" + id; + DsqlCluster cluster = cluster(id); + try (Connection server = postgres.connect("postgres"); Statement statement = server.createStatement()) { + statement.execute("CREATE ROLE someone_else NOLOGIN"); + statement.execute("CREATE DATABASE " + database + " OWNER someone_else"); + // Marked as this cluster's, so the start goes as far as the bootstrap. + statement.execute("COMMENT ON DATABASE " + database + " IS '" + ExternalDsqlBackend.marker(cluster) + "'"); + } + try { + try (Connection existing = postgres.connect(database); Statement statement = existing.createStatement()) { + statement.execute("CREATE SCHEMA sys AUTHORIZATION someone_else"); + statement.execute("CREATE TABLE sys.backend_roles (unexpected int)"); + statement.execute("ALTER TABLE sys.backend_roles OWNER TO someone_else"); + } + + boolean failed = false; + try { + new ExternalDsqlBackend(config()).start(cluster); + } catch (SQLException e) { + failed = true; + } + + assertTrue(failed, "the bootstrap fails on a sys it does not own"); + assertEquals("someone_else", postgres.single("SELECT datdba::regrole::text FROM pg_database" + + " WHERE datname = '" + database + "'"), "the database is left as it was"); + assertEquals("someone_else", postgres.single(database, "SELECT nspowner::regrole::text FROM pg_namespace" + + " WHERE nspname = 'sys'")); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname IN ('d" + id + + "_admin', 'dsqlowner_" + id + "', 'dsqlconnect_" + id + "')"), + "the admin, owner and connect role this attempt created are dropped"); + assertEquals("1", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname = 'someone_else'")); + } finally { + try (Connection server = postgres.connect("postgres"); Statement statement = server.createStatement()) { + statement.execute("DROP DATABASE IF EXISTS " + database + " WITH (FORCE)"); + statement.execute("DROP ROLE IF EXISTS someone_else"); + } + } + } + + @Test + void aLoginStillRecordsItsSessionWhenAnotherPurgesTheSameEndedOne() throws Exception { + String id = "stuvwxyzabcdefghijklmnopqr"; + String database = "dsql_" + id; + ExternalDsqlBackend backend = new ExternalDsqlBackend(config()); + DsqlCluster cluster = cluster(id); + DsqlDatabases.Backend started = backend.start(cluster); + @SuppressWarnings("unchecked") + Instance scpProvider = mock(Instance.class); + @SuppressWarnings("unchecked") + Instance resourcePolicyProviders = mock(Instance.class); + DsqlEndpoint endpoint = new DsqlEndpoint(mock(DsqlTlsCertificates.class), mock(IamService.class), + mock(IamPolicyEvaluator.class), scpProvider, resourcePolicyProviders, mock(DsqlPrincipals.class), + mock(EmulatorConfig.class, RETURNS_DEEP_STUBS), Clock.systemUTC()); + try (Connection other = postgres.connect(database); Statement statement = other.createStatement()) { + // A session that has ended, which both logins purge. + statement.execute("INSERT INTO sys.session_identity VALUES (2147483000, 'ended', 'ended')"); + other.setAutoCommit(false); + statement.execute("DELETE FROM sys.session_identity WHERE pid = 2147483000"); + + CompletableFuture recorded = CompletableFuture.supplyAsync(() -> + endpoint.recordSession(started, 2147483001, "arn:aws:iam::111122223333:root", "s1")); + await().atMost(Duration.ofSeconds(30)).until(() -> "1".equals(postgres.single("postgres", + "SELECT count(*)::text FROM pg_stat_activity WHERE datname = '" + database + + "' AND wait_event_type = 'Lock'"))); + other.commit(); + + assertTrue(recorded.get(30, TimeUnit.SECONDS), "the login's purge passes over the row already gone"); + assertEquals("s1", postgres.single(database, "SELECT session_id FROM sys.session_identity WHERE pid = 2147483001")); + } finally { + endpoint.stop(); + cluster.setPendingBackendRoles(backend.rolesToDrop(cluster)); + backend.stop(cluster, true); + } + } + + @Test + void anUnmarkedDatabaseFailsTheStartAndIsLeftUntouched() throws Exception { + String id = "aaaaabbbbbcccccdddddeeeeef"; + String database = "dsql_" + id; + postgres.execute("CREATE DATABASE " + database); + try { + DsqlCluster cluster = cluster(id); + + SQLException refused = assertThrows(SQLException.class, () -> new ExternalDsqlBackend(config()).start(cluster)); + + assertTrue(refused.getMessage().contains("database \"" + database + "\" that Floci did not create"), + refused.getMessage()); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname IN ('d" + id + + "_admin', 'dsqlowner_" + id + "', 'dsqlconnect_" + id + "')"), "no role was created"); + assertEquals("true", postgres.single("SELECT has_database_privilege('public', '" + database + + "', 'CONNECT')::text"), "its privileges are as they were"); + assertEquals("true", postgres.single("SELECT (shobj_description(oid, 'pg_database') IS NULL)::text" + + " FROM pg_database WHERE datname = '" + database + "'"), "and it is not marked"); + assertEquals("0", postgres.single(database, "SELECT count(*)::text FROM pg_namespace WHERE nspname = 'sys'"), + "nothing was bootstrapped in it"); + } finally { + postgres.execute("DROP DATABASE IF EXISTS " + database); + } + } + + @Test + void anUnmarkedOrForeignAdminFailsTheStartAndIsLeftUntouched() throws Exception { + String id = "fffffgggggbbbbbcccccdddddz"; + String admin = "d" + id + "_admin"; + for (String comment : new String[] {null, "floci:dsql:arn:aws:dsql:eu-west-1:111122223333:cluster/other"}) { + postgres.execute("CREATE ROLE " + admin + " LOGIN PASSWORD 'theirs'"); + if (comment != null) { + postgres.execute("COMMENT ON ROLE " + admin + " IS '" + comment + "'"); + } + String password = postgres.single("SELECT rolpassword FROM pg_authid WHERE rolname = '" + admin + "'"); + try { + DsqlCluster cluster = cluster(id); + + SQLException refused = assertThrows(SQLException.class, () -> + new ExternalDsqlBackend(config()).start(cluster)); + + assertTrue(refused.getMessage().contains("role \"" + admin + "\" that Floci did not create"), + refused.getMessage()); + assertEquals(password, postgres.single("SELECT rolpassword FROM pg_authid WHERE rolname = '" + + admin + "'"), "its password is as it was"); + assertEquals(String.valueOf(comment), String.valueOf(postgres.single("SELECT shobj_description(oid," + + " 'pg_authid') FROM pg_roles WHERE rolname = '" + admin + "'")), "so is its comment"); + assertEquals("false", postgres.single("SELECT rolcreaterole::text FROM pg_roles WHERE rolname = '" + + admin + "'")); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname IN ('dsqlowner_" + + id + "', 'dsqlconnect_" + id + "')"), "no owner or connect role was created"); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_database WHERE datname = 'dsql_" + + id + "'"), "no database was created"); + } finally { + postgres.execute("DROP ROLE IF EXISTS " + admin); + } + } + } + + @Test + void aForeignConnectRoleFailsTheStartAndIsLeftUntouched() throws Exception { + String id = "jjjjjkkkkklllllmmmmmnnnnno"; + String connect = "dsqlconnect_" + id; + postgres.execute("CREATE ROLE " + connect + " NOLOGIN"); + postgres.execute("COMMENT ON ROLE " + connect + " IS 'someone else''s'"); + try { + SQLException refused = assertThrows(SQLException.class, () -> + new ExternalDsqlBackend(config()).start(cluster(id))); + + assertTrue(refused.getMessage().contains("role \"" + connect + "\" that Floci did not create"), + refused.getMessage()); + assertEquals("someone else's", postgres.single("SELECT shobj_description(oid, 'pg_authid')" + + " FROM pg_roles WHERE rolname = '" + connect + "'")); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname IN ('d" + id + + "_admin', 'dsqlowner_" + id + "')"), "no other role was created"); + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_database WHERE datname = 'dsql_" + + id + "'"), "nor the database"); + } finally { + postgres.execute("DROP ROLE IF EXISTS " + connect); + } + } + + @Test + void deletionLeavesUnmarkedObjectsAlone() throws Exception { + String id = "hhhhhiiiiijjjjjkkkkklllllm"; + String database = "dsql_" + id; + String admin = "d" + id + "_admin"; + String owner = "dsqlowner_" + id; + postgres.execute("CREATE ROLE " + owner + " NOLOGIN"); + postgres.execute("CREATE ROLE " + admin + " LOGIN"); + postgres.execute("CREATE DATABASE " + database + " OWNER " + owner); + try { + ExternalDsqlBackend backend = new ExternalDsqlBackend(config()); + DsqlCluster cluster = cluster(id); + + List roles = backend.rolesToDrop(cluster); + cluster.setPendingBackendRoles(roles); + backend.stop(cluster, true); + + assertEquals(List.of(admin, "dsqlconnect_" + id, owner), roles); + assertEquals("1", postgres.single("SELECT count(*)::text FROM pg_database WHERE datname = '" + + database + "'"), "a database without the marker is left"); + assertEquals("2", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname IN ('" + admin + + "', '" + owner + "')"), "so are an admin and owner without it"); + } finally { + postgres.execute("DROP DATABASE IF EXISTS " + database); + postgres.execute("DROP ROLE IF EXISTS " + admin); + postgres.execute("DROP ROLE IF EXISTS " + owner); + } + } + + @Test + void anUnstampedDatabaseOwnedByTheMarkedOwnerIsAdoptedAndStamped() throws Exception { + String id = "sssssttttttuuuuuvvvvvwwwww"; + String database = "dsql_" + id; + String owner = "dsqlowner_" + id; + ExternalDsqlBackend backend = new ExternalDsqlBackend(config()); + DsqlCluster cluster = cluster(id); + String marker = ExternalDsqlBackend.marker(cluster); + // A start that stopped between CREATE DATABASE and its COMMENT. + postgres.execute("CREATE ROLE " + owner + " NOLOGIN"); + postgres.execute("COMMENT ON ROLE " + owner + " IS '" + marker + "'"); + postgres.execute("CREATE DATABASE " + database + " OWNER " + owner); + try { + backend.start(cluster); + + assertEquals(marker, postgres.single("SELECT shobj_description(oid, 'pg_database') FROM pg_database" + + " WHERE datname = '" + database + "'"), "the database is stamped"); + } finally { + cluster.setPendingBackendRoles(backend.rolesToDrop(cluster)); + backend.stop(cluster, true); + } + assertEquals("0", postgres.single("SELECT count(*)::text FROM pg_database WHERE datname = '" + database + + "'"), "and deleted with the cluster"); + } + + @Test + void aDatabaseOwnedByTheMarkedOwnerButCommentedOtherwiseIsStillRefused() throws Exception { + String id = "xxxxxyyyyyzzzzzaaaaabbbbbc"; + String database = "dsql_" + id; + String owner = "dsqlowner_" + id; + DsqlCluster cluster = cluster(id); + postgres.execute("CREATE ROLE " + owner + " NOLOGIN"); + postgres.execute("COMMENT ON ROLE " + owner + " IS '" + ExternalDsqlBackend.marker(cluster) + "'"); + postgres.execute("CREATE DATABASE " + database + " OWNER " + owner); + postgres.execute("COMMENT ON DATABASE " + database + " IS 'someone else''s'"); + try { + SQLException refused = assertThrows(SQLException.class, () -> + new ExternalDsqlBackend(config()).start(cluster)); + + assertTrue(refused.getMessage().contains("database \"" + database + "\""), refused.getMessage()); + assertEquals("someone else's", postgres.single("SELECT shobj_description(oid, 'pg_database')" + + " FROM pg_database WHERE datname = '" + database + "'")); + } finally { + postgres.execute("DROP DATABASE IF EXISTS " + database); + postgres.execute("DROP ROLE IF EXISTS " + owner); + } + } + + @Test + void aClusterWithoutAnArnIsDeletedWithoutDroppingWhatItCannotProveIsItsOwn() throws Exception { + String id = "cccccdddddeeeeefffffgggggh"; + ExternalDsqlBackend backend = new ExternalDsqlBackend(config()); + DsqlCluster cluster = cluster(id); + backend.start(cluster); + DsqlCluster withoutArn = new DsqlCluster(); + withoutArn.setIdentifier(id); + try { + List roles = backend.rolesToDrop(withoutArn); + withoutArn.setPendingBackendRoles(roles); + backend.stop(withoutArn, true); + + assertEquals("1", postgres.single("SELECT count(*)::text FROM pg_database WHERE datname = 'dsql_" + + id + "'"), "the database is left"); + assertEquals("3", postgres.single("SELECT count(*)::text FROM pg_roles WHERE rolname IN ('d" + id + + "_admin', 'dsqlowner_" + id + "', 'dsqlconnect_" + id + "')"), "so are the admin, owner and connect role"); + } finally { + cluster.setPendingBackendRoles(backend.rolesToDrop(cluster)); + backend.stop(cluster, true); + } + } + + @Test + void aWrongSuperuserPasswordFailsTheStartAtOnce() { + EmulatorConfig wrong = config(); + when(wrong.services().dsql().external().password()).thenReturn(Optional.of("not-the-password")); + long started = System.nanoTime(); + + SQLException refused = assertThrows(SQLException.class, () -> + new ExternalDsqlBackend(wrong).start(cluster("nnnnnooooopppppqqqqqrrrrrs"))); + + assertEquals("28P01", refused.getSQLState()); + assertTrue(System.nanoTime() - started < TimeUnit.SECONDS.toNanos(10), + "a refused login does not wait out the 90 s a starting server gets"); + } + + private static DsqlCluster cluster(String id) { + DsqlCluster cluster = new DsqlCluster(); + cluster.setIdentifier(id); + cluster.setArn("arn:aws:dsql:eu-west-1:111122223333:cluster/" + id); + return cluster; + } + + private EmulatorConfig config() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().dsql().external().host()).thenReturn(Optional.of("127.0.0.1")); + when(config.services().dsql().external().port()).thenReturn(port); + when(config.services().dsql().external().database()).thenReturn("postgres"); + when(config.services().dsql().external().username()).thenReturn("postgres"); + when(config.services().dsql().external().password()).thenReturn(Optional.of(PASSWORD)); + return config; + } +} diff --git a/src/test/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackendTest.java b/src/test/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackendTest.java new file mode 100644 index 0000000000..376d428d78 --- /dev/null +++ b/src/test/java/io/floci/aws/services/dsql/dataplane/ExternalDsqlBackendTest.java @@ -0,0 +1,277 @@ +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.services.dsql.model.DsqlCluster; +import org.junit.jupiter.api.Test; + +import javax.crypto.Mac; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.time.Duration; +import java.util.Arrays; +import java.util.Base64; +import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +class ExternalDsqlBackendTest { + + private static final String SECRET = Base64.getEncoder().encodeToString(new byte[32]); + + @Test + void trustedDatabasesAreNotScramOnly() { + assertFalse(BackendCredentials.TRUST.scramOnly()); + } + + @Test + void externalModeNeverTouchesDocker() { + ContainerBuilder builder = mock(ContainerBuilder.class); + ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class); + ContainerDetector detector = mock(ContainerDetector.class); + EmulatorConfig config = unreachableExternalServer(); + DsqlDatabases databases = new DsqlDatabases(new DockerDsqlBackend(builder, lifecycle, detector, config), + new ExternalDsqlBackend(config, Duration.ZERO), config); + DsqlCluster cluster = cluster(); + + assertThrows(SQLException.class, () -> databases.start(cluster)); + assertNotNull(cluster.getBackendSecret(), "the secret is set on the cluster for the caller to persist"); + assertThrows(SQLException.class, () -> databases.rolesToDrop(cluster)); + assertThrows(RuntimeException.class, () -> databases.stop(cluster, true)); + databases.stop(cluster, false); + + verifyNoInteractions(builder, lifecycle, detector); + } + + @Test + void derivedPasswordIsStablePerRole() { + String admin = ExternalDsqlBackend.derive(SECRET, "dabc_admin"); + + assertEquals(admin, ExternalDsqlBackend.derive(SECRET, "dabc_admin")); + assertNotEquals(admin, ExternalDsqlBackend.derive(SECRET, "dabc_app")); + assertNotEquals(admin, ExternalDsqlBackend.derive( + Base64.getEncoder().encodeToString(new byte[] {1}), "dabc_admin")); + assertTrue(admin.matches("[A-Za-z0-9_-]{43}"), admin); + assertFalse(admin.contains("=")); + } + + @Test + void verifierIsPostgresqlsScramFormatAndStablePerRole() throws Exception { + String verifier = ExternalDsqlBackend.verifier(SECRET, "dabc_admin"); + + assertEquals(verifier, ExternalDsqlBackend.verifier(SECRET, "dabc_admin")); + assertNotEquals(verifier, ExternalDsqlBackend.verifier(SECRET, "dabc_app")); + Matcher parts = Pattern.compile("SCRAM-SHA-256\\$4096:([^$]+)\\$([^:]+):(.+)").matcher(verifier); + assertTrue(parts.matches(), verifier); + byte[] salt = Base64.getDecoder().decode(parts.group(1)); + Mac saltMac = Mac.getInstance("HmacSHA256"); + saltMac.init(new SecretKeySpec(Base64.getDecoder().decode(SECRET), "HmacSHA256")); + assertArrayEquals(Arrays.copyOf(saltMac.doFinal("scram-salt:dabc_admin".getBytes(StandardCharsets.UTF_8)), 16), + salt); + // StoredKey and ServerKey as RFC 5802 defines them, from the password a client logs in with. + String password = ExternalDsqlBackend.derive(SECRET, "dabc_admin"); + byte[] salted = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") + .generateSecret(new PBEKeySpec(password.toCharArray(), salt, 4096, 256)).getEncoded(); + Mac keyMac = Mac.getInstance("HmacSHA256"); + keyMac.init(new SecretKeySpec(salted, "HmacSHA256")); + byte[] clientKey = keyMac.doFinal("Client Key".getBytes(StandardCharsets.UTF_8)); + byte[] serverKey = keyMac.doFinal("Server Key".getBytes(StandardCharsets.UTF_8)); + assertArrayEquals(MessageDigest.getInstance("SHA-256").digest(clientKey), + Base64.getDecoder().decode(parts.group(2))); + assertArrayEquals(serverKey, Base64.getDecoder().decode(parts.group(3))); + assertFalse(verifier.contains(password)); + } + + @Test + void theOwnershipMarkerNamesTheClustersArn() throws SQLException { + assertEquals("floci:dsql:arn:aws:dsql:eu-west-1:111122223333:cluster/abcdefghijklmnopqrstuvwxyz", + ExternalDsqlBackend.marker(cluster())); + DsqlCluster withoutArn = new DsqlCluster(); + withoutArn.setIdentifier("abc"); + assertThrows(SQLException.class, () -> ExternalDsqlBackend.marker(withoutArn)); + } + + @Test + void trustedDatabasesWantNeitherPasswordNorVerifier() { + assertNull(BackendCredentials.TRUST.passwordFor("admin")); + assertNull(BackendCredentials.TRUST.verifierFor("admin")); + } + + @Test + void aSecretIsGeneratedOnceAndKept() { + DsqlCluster cluster = cluster(); + cluster.setBackendSecret(SECRET); + + assertThrows(SQLException.class, () -> new ExternalDsqlBackend(unreachableExternalServer(), Duration.ZERO).start(cluster)); + + assertEquals(SECRET, cluster.getBackendSecret()); + } + + @Test + void aServerOlderThanPostgresql16IsRefusedNamingItsVersion() throws SQLException { + Connection server = serverOfVersion(15, "15.8"); + + SQLException refused = assertThrows(SQLException.class, + () -> ExternalDsqlBackend.requireSupportedVersion(server, "db.example:5433")); + + assertEquals("Floci's external DSQL backend needs PostgreSQL 16 or later; db.example:5433 runs 15.8", + refused.getMessage()); + verify(server).getMetaData(); + verifyNoMoreInteractions(server); + } + + @Test + void postgresql16AndLaterAreAccepted() throws SQLException { + ExternalDsqlBackend.requireSupportedVersion(serverOfVersion(16, "16.4"), "db.example:5432"); + ExternalDsqlBackend.requireSupportedVersion(serverOfVersion(17, "17.2"), "db.example:5432"); + } + + @Test + void aServerThatAcceptsButNeverAnswersDoesNotHoldACallForever() throws Exception { + // A listening socket that is never accepted from: TCP connects, and no reply ever comes, as from + // a paused sidecar. + try (ServerSocket silent = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) { + EmulatorConfig config = unreachableExternalServer(); + when(config.services().dsql().external().port()).thenReturn(silent.getLocalPort()); + ExternalDsqlBackend backend = new ExternalDsqlBackend(config, Duration.ofSeconds(1)); + DsqlCluster cluster = cluster(); + + assertTimeoutPreemptively(Duration.ofSeconds(30), () -> { + assertThrows(SQLException.class, () -> backend.start(cluster)); + assertThrows(SQLException.class, () -> backend.rolesToDrop(cluster)); + assertThrows(IllegalStateException.class, () -> backend.stop(cluster, true)); + }, "every call gives up on the server instead of waiting for it forever"); + assertEquals(0, backend.lockedClusters(), "and lets go of the cluster's lock"); + } + } + + @Test + void aSingleConnectionAttemptNeverOutlastsTheStartsWait() { + assertEquals(1, ExternalDsqlBackend.loginTimeoutSeconds(Duration.ZERO), "zero would mean no limit"); + assertEquals(1, ExternalDsqlBackend.loginTimeoutSeconds(Duration.ofMillis(300))); + assertEquals(5, ExternalDsqlBackend.loginTimeoutSeconds(Duration.ofSeconds(5))); + assertEquals(10, ExternalDsqlBackend.loginTimeoutSeconds(ExternalDsqlBackend.READY_TIMEOUT)); + } + + @Test + void theStartWaitsAsLongAsTheDockerBackendDoes() { + assertEquals(Duration.ofSeconds(90), ExternalDsqlBackend.READY_TIMEOUT); + } + + @Test + void aClustersWorkWaitsForTheWorkAlreadyHoldingItsLock() throws Exception { + ExternalDsqlBackend backend = new ExternalDsqlBackend(unreachableExternalServer(), Duration.ZERO); + CountDownLatch startHolds = new CountDownLatch(1); + CountDownLatch startMayFinish = new CountDownLatch(1); + AtomicBoolean deletionRan = new AtomicBoolean(); + try (ExecutorService threads = Executors.newVirtualThreadPerTaskExecutor()) { + Future start = threads.submit(() -> backend.underLock("c1", () -> { + startHolds.countDown(); + await(startMayFinish); + return null; + })); + await(startHolds); + Future deletion = threads.submit(() -> backend.underLock("c1", () -> { + deletionRan.set(true); + return null; + })); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (!backend.awaitedLock("c1") && System.nanoTime() < deadline) { + Thread.onSpinWait(); + } + + assertTrue(backend.awaitedLock("c1"), "the deletion waits for the start's lock"); + assertFalse(deletionRan.get()); + assertEquals("other", backend.underLock("c2", () -> "other"), "another cluster is not held up"); + + startMayFinish.countDown(); + start.get(10, TimeUnit.SECONDS); + deletion.get(10, TimeUnit.SECONDS); + } + + assertTrue(deletionRan.get()); + assertEquals(0, backend.lockedClusters(), "no lock is kept once nobody holds or awaits it"); + } + + @Test + void aFailureReleasesTheClustersLock() { + ExternalDsqlBackend backend = new ExternalDsqlBackend(unreachableExternalServer(), Duration.ZERO); + + assertThrows(SQLException.class, () -> backend.underLock("c1", () -> { + throw new SQLException("refused"); + })); + assertThrows(SQLException.class, () -> backend.start(cluster())); + assertThrows(IllegalStateException.class, () -> backend.stop(cluster(), true)); + + assertEquals(0, backend.lockedClusters()); + } + + private static void await(CountDownLatch latch) { + try { + assertTrue(latch.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } + + private static Connection serverOfVersion(int major, String version) throws SQLException { + Connection server = mock(Connection.class); + DatabaseMetaData metaData = mock(DatabaseMetaData.class); + when(server.getMetaData()).thenReturn(metaData); + when(metaData.getDatabaseMajorVersion()).thenReturn(major); + when(metaData.getDatabaseProductVersion()).thenReturn(version); + return server; + } + + private static EmulatorConfig unreachableExternalServer() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().dsql().backend()).thenReturn(EmulatorConfig.DsqlServiceConfig.Backend.EXTERNAL); + when(config.services().dsql().external().host()).thenReturn(Optional.of("127.0.0.1")); + // Nothing listens on port 1, so every connection is refused at once. + when(config.services().dsql().external().port()).thenReturn(1); + when(config.services().dsql().external().database()).thenReturn("postgres"); + when(config.services().dsql().external().username()).thenReturn("postgres"); + when(config.services().dsql().external().password()).thenReturn(Optional.empty()); + return config; + } + + private static DsqlCluster cluster() { + DsqlCluster cluster = new DsqlCluster(); + cluster.setIdentifier("abcdefghijklmnopqrstuvwxyz"); + cluster.setArn("arn:aws:dsql:eu-west-1:111122223333:cluster/abcdefghijklmnopqrstuvwxyz"); + return cluster; + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 79421bf9ff..b6361f069c 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -259,6 +259,7 @@ floci: enabled: true mock: true port: 0 + backend: docker redshift-data: enabled: true result-ttl-hours: 24