diff --git a/docs/services/rds.md b/docs/services/rds.md index f74991dbac..154810de58 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -1199,6 +1199,38 @@ FLOCI_STORAGE_HOST_PERSISTENT_PATH=/absolute/host/path/data !!! note "Docker Desktop on macOS" Named volumes work correctly on Docker Desktop for macOS. Bind mounts to paths inside the Floci container are not supported — use named volumes (the default). +## PostgreSQL master user + +A PostgreSQL instance or cluster is initialized as RDS initializes one. The bootstrap superuser is `rdsadmin`, the +role RDS keeps for its own management tasks, and the master user is an ordinary role created as RDS creates it: +`LOGIN NOSUPERUSER INHERIT CREATEDB CREATEROLE NOREPLICATION VALID UNTIL 'infinity'`, a member of `rds_superuser` +(RDS User Guide, [Understanding the rds_superuser role](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Appendix.PostgreSQL.CommonDBATasks.Roles.rds_superuser.html)). +The master owns the `postgres` and `template1` databases and the instance's own database, so the objects it +owns can be handed to another role with `REASSIGN OWNED BY TO ` once the master is a member of +that role, as on RDS. `rds_superuser` holds, with ADMIN OPTION, `rds_password`, `rds_replication` and the +predefined roles `pg_checkpoint`, `pg_create_subscription`, `pg_maintain`, `pg_monitor`, `pg_read_all_data`, +`pg_signal_backend`, `pg_use_reserved_connections` and `pg_write_all_data` where the server has them, so the +master can grant `rds_replication` and `rds_password` to other roles. It can grant `rds_iam` too. No client logs +in as `rdsadmin`, and the `rdsadmin` database refuses everyone else, as on RDS. + +On RDS, `rds_superuser` can do some things that stock PostgreSQL leaves to a superuser alone. In Floci the master +cannot: + +- create an extension PostgreSQL does not mark trusted, such as `pg_stat_statements`, `postgres_fdw`, `dblink` or + `postgis`. An image's init scripts still install theirs in the instance's database, as PostGIS's do; +- run `CREATE PUBLICATION ... FOR ALL TABLES` or `ALTER SYSTEM`. Turn logical replication on with + `rds.logical_replication` in the DB parameter group, as on RDS; +- open a replication connection with its password, or call the replication slot functions. A role in + `rds_replication` can open a logical replication connection with an IAM token (see + [Authentication](#authentication)). + +Like any role that is not a superuser, it also cannot set a parameter PostgreSQL leaves to superusers, such as +`log_min_duration_statement`, nor store a custom placeholder parameter as a role default. + +A data volume first initialized by an earlier Floci keeps the master user it was initialized with, as its +bootstrap superuser. A snapshot of such an instance restores with the master user as described above. A master +user named `rdsadmin` stays the bootstrap superuser. + ## Authentication The RDS auth proxy checks the master username and password at the proxy layer. Other database users authenticate against the backend engine. For PostgreSQL instances with IAM database authentication enabled, the database role's `rds_iam` membership also determines which authentication method it can use. @@ -1279,9 +1311,9 @@ report it, and objects it creates belong to it. A missing role or a role without require `rds_iam` membership. Grant the application any additional database privileges it needs. -Underneath, the proxy reaches the container as the master user and hands the session over to the token's role, so an IAM session that talks its way back to the master role, via `RESET SESSION AUTHORIZATION` and its variants, is terminated with `FATAL: permission denied to set session authorization` rather than being allowed to regain superuser. `SET ROLE` is untouched: PostgreSQL still permission-checks it against the token's role, exactly as on RDS. One difference from RDS: the proxy learns of the switch from PostgreSQL's own report, so when several statements are batched into a single query after the switch, their results are returned before the session is closed. +Underneath, the proxy reaches the container as `rdsadmin` and hands the session over to the token's role, since only a superuser can do that. On a data volume whose master user is the bootstrap superuser (see [PostgreSQL master user](#postgresql-master-user)) it reaches it as the master user. An IAM session that talks its way back to that role, via `RESET SESSION AUTHORIZATION` and its variants, is terminated with `FATAL: permission denied to set session authorization` rather than being allowed to regain superuser. `SET ROLE` is untouched: PostgreSQL still permission-checks it against the token's role, exactly as on RDS. One difference from RDS: the proxy learns of the switch from PostgreSQL's own report, so when several statements are batched into a single query after the switch, their results are returned before the session is closed. -The parameters a PostgreSQL client sends when it connects (`options` such as `-c search_path=app`, `application_name`, and any other run-time parameter) apply to the session as they do on RDS. An IAM session for a role other than the master gets them once the session has been handed over to the token's role, applied with `set_config()` so PostgreSQL checks each one against that role's privileges, and a parameter PostgreSQL refuses fails the login with PostgreSQL's own error, as it would at startup. The role's own `ALTER ROLE ... SET` defaults load as they do at login: the role-wide ones, then those for the database. They are the values `RESET` returns to, and they apply with the authority of whoever stored them, so a superuser-only default set by an administrator binds the role even after `RESET ALL`. To get this, a role with defaults has its backend session opened a second time, with the defaults as startup options. A default PostgreSQL refuses is skipped with a `WARNING`, as at login. A `role` default is checked against the role's memberships, and a `client_encoding` default applies unless the client chose an encoding; both are set once the session is the role's, so `RESET` does not return to them. Defaults stored on the master role itself are not undone for these sessions. A `session_authorization` naming any other role is refused with `permission denied to set session authorization` before anything is applied, since PostgreSQL would authorize it against the master the proxy connected as. Because those sessions have already started, two things differ from RDS: `options` may carry only `-c name=value` and `--name=value` switches, and a parameter that can only be set at connection start is refused with `cannot be set after connection start`. And because the values are set with `set_config()` rather than at startup, `RESET` (and `RESET ALL`) takes such a parameter back to the server default, not to the value the client connected with: after `-c search_path=app`, `RESET search_path` gives `"$user", public` where RDS keeps `app`. +The parameters a PostgreSQL client sends when it connects (`options` such as `-c search_path=app`, `application_name`, and any other run-time parameter) apply to the session as they do on RDS. An IAM session for a role other than the master gets them once the session has been handed over to the token's role, applied with `set_config()` so PostgreSQL checks each one against that role's privileges, and a parameter PostgreSQL refuses fails the login with PostgreSQL's own error, as it would at startup. The role's own `ALTER ROLE ... SET` defaults load as they do at login: the role-wide ones, then those for the database. They are the values `RESET` returns to, and they apply with the authority of whoever stored them, so a superuser-only default set by an administrator binds the role even after `RESET ALL`. To get this, a role with defaults has its backend session opened a second time, with the defaults as startup options. A default PostgreSQL refuses is skipped with a `WARNING`, as at login. A `role` default is checked against the role's memberships, and a `client_encoding` default applies unless the client chose an encoding; both are set once the session is the role's, so `RESET` does not return to them. Defaults stored on the role the proxy connects as are not undone for these sessions. A `session_authorization` naming any other role is refused with `permission denied to set session authorization` before anything is applied, since PostgreSQL would authorize it against the superuser the proxy connected as. Because those sessions have already started, two things differ from RDS: `options` may carry only `-c name=value` and `--name=value` switches, and a parameter that can only be set at connection start is refused with `cannot be set after connection start`. And because the values are set with `set_config()` rather than at startup, `RESET` (and `RESET ALL`) takes such a parameter back to the server default, not to the value the client connected with: after `-c search_path=app`, `RESET search_path` gives `"$user", public` where RDS keeps `app`. A logical replication connection (`replication=database`) can log in with an IAM token when the token's role may replicate: it is a member of `rds_replication`, directly or through another role, or has the `REPLICATION` attribute. Any other role is refused with `FATAL: permission denied to start WAL sender`. A physical replication connection (`replication=true`) is refused by the instance, as it is for a password login. On a logical replication connection, physical replication commands are refused, as on RDS, where `rds_replication` covers logical replication only: `BASE_BACKUP`, `START_REPLICATION` other than `START_REPLICATION SLOT ... LOGICAL`, `CREATE_REPLICATION_SLOT` other than a `LOGICAL` slot, `READ_REPLICATION_SLOT`, `TIMELINE_HISTORY` and `UPLOAD_MANIFEST` fail with `ERROR: permission denied to use physical replication` (SQLSTATE `42501`) and the session stays open. PostgreSQL raises that error from PL/pgSQL, so it carries a `CONTEXT` line. Two things differ from RDS. RDS accepts these logins only once `rds.iam_auth_for_replication` and `rds.logical_replication` are both set to 1 in the parameter group; Floci accepts them whenever IAM database authentication is enabled. And `rds_replication` is an ordinary role here, so it lets a role start a replication connection but not call the SQL slot functions such as `pg_create_logical_replication_slot()`, which PostgreSQL allows only to a role with the `REPLICATION` attribute; create slots with `CREATE_REPLICATION_SLOT` over the replication connection, or give the role `REPLICATION`. diff --git a/src/main/java/io/floci/aws/services/rds/container/RdsContainerHandle.java b/src/main/java/io/floci/aws/services/rds/container/RdsContainerHandle.java index 21cec97e6d..57efbc7890 100644 --- a/src/main/java/io/floci/aws/services/rds/container/RdsContainerHandle.java +++ b/src/main/java/io/floci/aws/services/rds/container/RdsContainerHandle.java @@ -7,6 +7,17 @@ import java.io.Closeable; */ public class RdsContainerHandle { + /** + * A PostgreSQL backend's superuser, and the password Floci set for it when this container started. The password + * is null when the superuser is the master user, which logs in with the master's own password. + */ + public record PostgresSuperuser(String user, String password) { + @Override + public String toString() { + return "PostgresSuperuser[user=" + user + "]"; + } + } + private final String containerId; private final String runtimeId; private final String instanceId; @@ -15,6 +26,7 @@ public class RdsContainerHandle { private final String storageKey; private final String containerKey; private Closeable logStream; + private volatile PostgresSuperuser postgresSuperuser; public RdsContainerHandle(String containerId, String instanceId, String host, int port) { this(containerId, instanceId, instanceId, host, port, null); @@ -52,4 +64,6 @@ public class RdsContainerHandle { public String getContainerKey() { return containerKey; } public Closeable getLogStream() { return logStream; } public void setLogStream(Closeable logStream) { this.logStream = logStream; } + public PostgresSuperuser getPostgresSuperuser() { return postgresSuperuser; } + public void setPostgresSuperuser(PostgresSuperuser postgresSuperuser) { this.postgresSuperuser = postgresSuperuser; } } diff --git a/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java b/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java index dfec680509..c096d3f472 100644 --- a/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java +++ b/src/main/java/io/floci/aws/services/rds/container/RdsContainerManager.java @@ -34,9 +34,11 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.security.SecureRandom; import java.time.Clock; import java.time.Duration; import java.util.ArrayList; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -80,6 +82,15 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe private static final Map MYSQL_OPTION_NAMES = Map.of("time_zone", "default-time-zone"); /** How long a server started with a parameter group's options gets to start listening. */ private static final int PARAMETER_GROUP_START_SECONDS = 120; + /** + * The role RDS for PostgreSQL runs its own management tasks as ("rdsadmin – A role that's created to handle + * many of the management tasks that the administrator with superuser privileges would perform on a + * standalone PostgreSQL database", RDS User Guide, "Understanding the rds_superuser role"). A PostgreSQL + * backend is initialized as this role, and the master user is created as an ordinary role beside it. + */ + static final String POSTGRES_ADMIN_ROLE = "rdsadmin"; + /** The bootstrap superuser of a PostgreSQL cluster, whatever initdb named it. */ + private static final String POSTGRES_SUPERUSER_SQL = "SELECT rolname FROM pg_catalog.pg_roles WHERE oid = 10"; private final ContainerBuilder containerBuilder; private final ContainerLifecycleManager lifecycleManager; @@ -412,6 +423,9 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe if (needsMasterGrant(engine, masterUsername)) { installMasterGrantInitScript(createdContainerId, masterUsername); } + if (engine == DatabaseEngine.POSTGRES && bootstrapsAsAdminRole(masterUsername)) { + installPostgresMasterInitScript(createdContainerId, masterUsername, masterPassword, dbName); + } ContainerInfo info = lifecycleManager.startCreated(createdContainerId, spec); EndpointInfo endpoint = info.getEndpoint(enginePort); @@ -419,11 +433,13 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe if (!engineParameterOptions(engine, engineParameters).isEmpty()) { awaitServerWithParameterGroup(containerName, info.containerId(), enginePort); } - initializeEngine(containerName, info.containerId(), engine, masterUsername, masterPassword, dbName); + RdsContainerHandle.PostgresSuperuser postgresSuperuser = initializeEngine( + containerName, info.containerId(), engine, masterUsername, masterPassword, dbName); handle = new RdsContainerHandle( info.containerId(), effectiveRuntimeId, instanceId, endpoint.host(), endpoint.port(), storageKey, containerKey); + handle.setPostgresSuperuser(postgresSuperuser); // Attach log streaming if (!ephemeral) { @@ -634,6 +650,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe newInstanceId, handle.getHost(), handle.getPort(), handle.getStorageKey(), handle.getContainerKey()); moved.setLogStream(handle.getLogStream()); + moved.setPostgresSuperuser(handle.getPostgresSuperuser()); activeContainers.put(newRuntimeId, moved); } activeStorageOwners.replaceAll((key, owner) -> owner.equals(oldRuntimeId) ? newRuntimeId : owner); @@ -879,15 +896,127 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe return Integer.parseInt(tag.substring(0, end)); } - private void initializeEngine(String containerName, String containerId, DatabaseEngine engine, - String masterUsername, String masterPassword, String dbName) { + /** Returns a PostgreSQL backend's superuser, and null for the other engines. */ + private RdsContainerHandle.PostgresSuperuser initializeEngine(String containerName, String containerId, + DatabaseEngine engine, String masterUsername, + String masterPassword, String dbName) { switch (engine) { - case POSTGRES -> initializePostgresIamRole(containerName, containerId, masterUsername); + case POSTGRES -> { + return initializePostgres(containerName, containerId, masterUsername); + } case SQLSERVER -> initializeSqlServerMaster(containerName, containerId, masterUsername, masterPassword); case MYSQL, MARIADB -> { } } + return null; + } + + /** The master user a PostgreSQL backend is created with: the requested one, else {@code postgres}. */ + static String effectivePostgresMaster(String masterUsername) { + return (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres"; + } + + /** + * Whether a new PostgreSQL backend is initialized as {@link #POSTGRES_ADMIN_ROLE} with the master user created + * beside it, as on RDS. A master user that is itself named after that role stays the bootstrap superuser. + */ + static boolean bootstrapsAsAdminRole(String masterUsername) { + return !POSTGRES_ADMIN_ROLE.equals(effectivePostgresMaster(masterUsername)); + } + + /** + * What a new PostgreSQL backend runs once, as {@link #POSTGRES_ADMIN_ROLE}, while its data directory is + * initialized: the master user, created as RDS creates it, then {@link #postgresRdsRolesSql}, then the + * requested database handed to the master. The image creates that database, so an image's own init scripts + * (PostGIS installs its extension) still run in it. One requested under the name {@code rdsadmin} is the + * master's too, so the master can open it although the role setup closes it to everyone else. + */ + static String postgresMasterInitSql(String masterUsername, String masterPassword, String dbName) { + String master = effectivePostgresMaster(masterUsername); + String database = (dbName != null && !dbName.isBlank()) ? dbName : master; + StringBuilder sql = new StringBuilder() + .append("CREATE ROLE ").append(quotePostgresIdentifier(master)).append(" WITH LOGIN PASSWORD ") + .append(postgresLiteral(masterPassword == null ? "" : masterPassword)).append(";\n") + .append(postgresRdsRolesSql(master)); + if (!Set.of("postgres", "template0", "template1").contains(database)) { + sql.append("ALTER DATABASE ").append(quotePostgresIdentifier(database)) + .append(" OWNER TO ").append(quotePostgresIdentifier(master)).append(";\n"); + } + return sql.toString(); + } + + /** + * The roles and ownership RDS gives an instance, applied as {@link #POSTGRES_ADMIN_ROLE} when a backend is + * initialized and again after a snapshot is restored into one; it may run any number of times. A psql + * script, not one statement: it creates the {@code rdsadmin} database with {@code \gexec} when it is missing. + * + *
    + *
  • The master user is {@code LOGIN NOSUPERUSER INHERIT CREATEDB CREATEROLE NOREPLICATION VALID UNTIL + * 'infinity'} and a member of {@code rds_superuser} (RDS User Guide, "Understanding the rds_superuser + * role"), and owns the {@code postgres} and {@code template1} databases.
  • + *
  • {@code rds_superuser} holds, with ADMIN OPTION, the predefined roles an RDS instance grants it, where + * the server has them, and {@code rds_password} and {@code rds_replication}, which the master can + * therefore grant to other users. {@code rds_iam} is granted to it with ADMIN OPTION alone on + * PostgreSQL 16 and later, so the master can grant it without becoming a member, which would make the + * master an IAM-only role; before 16 {@code CREATEROLE} already lets it.
  • + *
  • The {@code rdsadmin} database is closed to everyone but its owner.
  • + *
+ */ + static String postgresRdsRolesSql(String masterUsername) { + String master = quotePostgresIdentifier(effectivePostgresMaster(masterUsername)); + return """ + DO $floci$ + DECLARE + predefined text; + BEGIN + FOREACH predefined IN ARRAY ARRAY['rds_superuser', 'rds_password', 'rds_replication', 'rds_iam'] + LOOP + IF NOT EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = predefined) THEN + EXECUTE pg_catalog.format('CREATE ROLE %I', predefined); + END IF; + END LOOP; + FOREACH predefined IN ARRAY ARRAY['pg_checkpoint', 'pg_create_subscription', 'pg_maintain', + 'pg_monitor', 'pg_read_all_data', 'pg_signal_backend', 'pg_use_reserved_connections', + 'pg_write_all_data', 'rds_password', 'rds_replication'] + LOOP + IF EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = predefined) THEN + EXECUTE pg_catalog.format('GRANT %I TO rds_superuser WITH ADMIN OPTION', predefined); + END IF; + END LOOP; + IF pg_catalog.current_setting('server_version_num')::int >= 160000 THEN + EXECUTE 'GRANT rds_iam TO rds_superuser WITH ADMIN OPTION, INHERIT FALSE, SET FALSE'; + END IF; + END + $floci$; + """ + + "ALTER ROLE " + master + " WITH LOGIN NOSUPERUSER INHERIT CREATEDB CREATEROLE NOREPLICATION" + + " NOBYPASSRLS VALID UNTIL 'infinity';\n" + + "GRANT rds_superuser TO " + master + ";\n" + + "ALTER DATABASE postgres OWNER TO " + master + ";\n" + + "ALTER DATABASE template1 OWNER TO " + master + ";\n" + + "SELECT 'CREATE DATABASE " + POSTGRES_ADMIN_ROLE + "' WHERE NOT EXISTS " + + "(SELECT 1 FROM pg_catalog.pg_database WHERE datname = '" + POSTGRES_ADMIN_ROLE + "')\n" + + "\\gexec\n" + + "REVOKE ALL ON DATABASE " + POSTGRES_ADMIN_ROLE + " FROM PUBLIC;\n"; + } + + /** A PostgreSQL string literal: wrapped in single quotes, with each embedded one doubled. */ + static String postgresLiteral(String value) { + return "'" + value.replace("'", "''") + "'"; + } + + /** + * Delivered as a {@code /docker-entrypoint-initdb.d} script, as {@link #installMasterGrantInitScript} is, so + * it runs only against an empty data directory: a volume the backend has used before keeps the roles it + * has, including one whose master user is still the bootstrap superuser. + */ + private void installPostgresMasterInitScript(String containerId, String masterUsername, String masterPassword, + String dbName) { + byte[] sql = postgresMasterInitSql(masterUsername, masterPassword, dbName).getBytes(StandardCharsets.UTF_8); + RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, + "/docker-entrypoint-initdb.d", "floci-rds-master.sql", sql, 0644, + RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, uploadBackoffMillis); } private void initializeSqlServerMaster(String containerName, String containerId, @@ -960,23 +1089,85 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe * temporary server that listens only on the Unix socket, so a socket connection can succeed * before the final server is up. Loopback is trusted by the generated pg_hba.conf. */ - private void initializePostgresIamRole(String containerName, String containerId, String masterUsername) { - String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres"; + private RdsContainerHandle.PostgresSuperuser initializePostgres(String containerName, String containerId, + String masterUsername) { + String master = effectivePostgresMaster(masterUsername); + String[] lookup = { + "psql", + "-h", "127.0.0.1", + "-X", "-q", "-A", "-t", + "-v", "ON_ERROR_STOP=1", + "-U", master, + "-d", "postgres", + "-c", POSTGRES_SUPERUSER_SQL + }; + PostgresStartupSignal startup = new PostgresStartupSignal(); + String superuser = master; + // This path receives a newly created container, so replay cannot include a prior start. + try (Closeable observation = logStreamer.observe(containerId, startup)) { + String found = execUntilSuccess(containerName, containerId, lookup, "PostgreSQL superuser lookup", + startup.signal).trim(); + if (!found.isEmpty()) { + superuser = found; + } + } catch (IOException e) { + LOG.warnv(e, "Could not close PostgreSQL startup observation for {0}", containerName); + } + // A backend Floci initialized as rdsadmin gets a password for this start only, which the proxy alone + // knows; one whose master user is the bootstrap superuser keeps logging in with the master's password. + String password = superuser.equals(master) ? null : randomPostgresPassword(); + String sql = postgresIamRoleInitSql() + (password == null ? "" + : "ALTER ROLE " + quotePostgresIdentifier(superuser) + " WITH PASSWORD " + postgresLiteral(password) + + ";\n"); String[] cmd = { "psql", "-h", "127.0.0.1", "-v", "ON_ERROR_STOP=1", - "-U", effectiveUser, + "-U", superuser, "-d", "postgres", - "-c", postgresIamRoleInitSql() + "-c", sql }; - PostgresStartupSignal startup = new PostgresStartupSignal(); - // This path receives a newly created container, so replay cannot include a prior start. - try (Closeable observation = logStreamer.observe(containerId, startup)) { - execUntilSuccess(containerName, containerId, cmd, "PostgreSQL IAM role", startup.signal); - } catch (IOException e) { - LOG.warnv(e, "Could not close PostgreSQL startup observation for {0}", containerName); + execUntilSuccess(containerName, containerId, cmd, "PostgreSQL IAM role"); + return new RdsContainerHandle.PostgresSuperuser(superuser, password); + } + + private static String randomPostgresPassword() { + byte[] bytes = new byte[24]; + new SecureRandom().nextBytes(bytes); + return HexFormat.of().formatHex(bytes); + } + + /** + * The superuser Floci runs its own SQL in a PostgreSQL backend as: {@link #POSTGRES_ADMIN_ROLE} for a backend + * initialized as it, the master user for one whose master is the bootstrap superuser, as found when the + * container started, and the master user for a container this manager did not start. + */ + String postgresSuperuser(String containerId, String masterUsername) { + RdsContainerHandle handle = activeHandleOfContainer(containerId); + RdsContainerHandle.PostgresSuperuser superuser = handle == null ? null : handle.getPostgresSuperuser(); + return superuser != null ? superuser.user() : effectivePostgresMaster(masterUsername); + } + + /** + * The login the auth proxy hands an IAM session over through: the {@link #POSTGRES_ADMIN_ROLE} superuser + * with this start's password, or null when the runtime has none, so the master user's login serves. + */ + public RdsContainerHandle.PostgresSuperuser postgresHandoverLogin(String runtimeId) { + RdsContainerHandle handle = runtimeId == null ? null : activeContainers.get(runtimeId); + RdsContainerHandle.PostgresSuperuser superuser = handle == null ? null : handle.getPostgresSuperuser(); + return superuser == null || superuser.password() == null ? null : superuser; + } + + private RdsContainerHandle activeHandleOfContainer(String containerId) { + if (containerId == null) { + return null; } + for (RdsContainerHandle handle : activeContainers.values()) { + if (containerId.equals(handle.getContainerId())) { + return handle; + } + } + return null; } /** @@ -1074,12 +1265,13 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe RetryingTarCopier.DEFAULT_MAX_ATTEMPTS, uploadBackoffMillis); } - private void execUntilSuccess(String containerName, String containerId, String[] cmd, String description) { - execUntilSuccess(containerName, containerId, cmd, description, new Semaphore(0)); + private String execUntilSuccess(String containerName, String containerId, String[] cmd, String description) { + return execUntilSuccess(containerName, containerId, cmd, description, new Semaphore(0)); } - private void execUntilSuccess(String containerName, String containerId, String[] cmd, String description, - Semaphore startupSignal) { + /** Runs {@code cmd} until it exits 0, for up to a minute, and returns what it wrote to stdout. */ + private String execUntilSuccess(String containerName, String containerId, String[] cmd, String description, + Semaphore startupSignal) { String lastOutput = ""; for (int attempt = 1; attempt <= 60; attempt++) { try { @@ -1087,7 +1279,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe lastOutput = result.stdout() + (result.stderr().isEmpty() ? "" : "\n" + result.stderr()); if (result.exitCode() == 0) { LOG.infov("Initialized {0} in RDS container {1}", description, containerName); - return; + return result.stdout(); } } catch (Exception e) { lastOutput = e.getMessage(); @@ -1219,7 +1411,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe } public String createPostgresSnapshot(String containerId, String masterUsername) { - String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres"; + String effectiveUser = postgresSuperuser(containerId, masterUsername); String[] cmd = { "pg_dumpall", "-U", effectiveUser @@ -1236,8 +1428,8 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe } /** - * Runs one query as the master user and returns its rows, one per line, unaligned and without - * headers. The session uses ISO dates in UTC, so a value's text output does not depend on the + * Runs one query as the backend's superuser ({@link #postgresSuperuser}) and returns its rows, one per + * line, unaligned and without headers. The session uses ISO dates in UTC, so a value's text output does not depend on the * image's defaults. */ public String queryPostgres(String containerId, String masterUsername, String database, String sql) { @@ -1252,7 +1444,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe */ public void queryPostgres(String containerId, String masterUsername, String database, String sql, OutputStream rows, int timeoutSeconds) { - String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres"; + String effectiveUser = postgresSuperuser(containerId, masterUsername); String[] cmd = { "env", "PGOPTIONS=-c DateStyle=ISO -c TimeZone=UTC -c IntervalStyle=postgres", "psql", "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", @@ -1269,13 +1461,32 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe } } + /** + * Replays a {@link #createPostgresSnapshot} dump as the backend's superuser. In a backend initialized as + * {@link #POSTGRES_ADMIN_ROLE}, the roles and ownership RDS gives an instance are applied again afterwards, + * so a dump of an older backend, whose master user was the bootstrap superuser, restores with the master + * as RDS has it, and that role gets back the password of this start, which the dump replaced. + */ public void restorePostgresSnapshot(String containerId, String masterUsername, String sqlDump) { - String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres"; + String master = effectivePostgresMaster(masterUsername); + String superuser = postgresSuperuser(containerId, master); + boolean adminBackend = !superuser.equals(master); Map files = new LinkedHashMap<>(); files.put("dump.sql", sqlDump); - files.put("restore.sh", postgresRestoreScript()); + files.put("restore.sh", postgresRestoreScript( + adminBackend ? postgresRdsRolesSql(master) : postgresIamRoleInitSql())); runSnapshotScript(containerId, "postgres-restore", files, - new String[]{"sh", "/tmp/restore.sh", effectiveUser}, List.of(), 60, 120, "psql restore"); + new String[]{"sh", "/tmp/restore.sh", superuser}, List.of(), 60, 120, "psql restore"); + RdsContainerHandle handle = activeHandleOfContainer(containerId); + RdsContainerHandle.PostgresSuperuser login = handle == null ? null : handle.getPostgresSuperuser(); + if (adminBackend && login != null && login.password() != null) { + String[] cmd = {"psql", "-v", "ON_ERROR_STOP=1", "-U", superuser, "-d", "postgres", "-c", + "ALTER ROLE " + quotePostgresIdentifier(superuser) + " WITH PASSWORD " + + postgresLiteral(login.password()) + ";"}; + try (Lease _ = holdContainer(containerId)) { + execUntilSuccess(containerId, containerId, cmd, "PostgreSQL superuser password"); + } + } } /** @@ -1495,7 +1706,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe * template1, so it also works when {@code from} is {@code postgres}. */ public void renamePostgresDatabase(String containerId, String masterUsername, String from, String to) { - String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres"; + String effectiveUser = postgresSuperuser(containerId, masterUsername); String sql = "ALTER DATABASE " + quotePostgresIdentifier(from) + " RENAME TO " + quotePostgresIdentifier(to); String[] cmd = {"psql", "-v", "ON_ERROR_STOP=1", "-U", effectiveUser, "-d", "template1", "-c", sql}; try (Lease _ = holdContainer(containerId)) { @@ -1517,6 +1728,14 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe } static String postgresRestoreScript() { + return postgresRestoreScript(postgresIamRoleInitSql()); + } + + /** + * The restore script, run as the backend's superuser, ending with {@code closingSql}, a psql script run once + * the dump is replayed. + */ + static String postgresRestoreScript(String closingSql) { return """ #!/bin/sh set -e @@ -1541,6 +1760,11 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe mv /tmp/dump_filtered.sql /tmp/dump.sql chmod 600 /tmp/dump.sql + # The databases kept above may belong to a role dropped below, as postgres and template1 + # belong to the master user of an instance initialized as rdsadmin + psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres -c "ALTER DATABASE postgres OWNER TO CURRENT_USER" + psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres -c "ALTER DATABASE template1 OWNER TO CURRENT_USER" + # Drop all non-current-user, non-system roles psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres -tAc \\ "SELECT rolname FROM pg_roles WHERE rolname <> current_user AND rolname NOT LIKE 'pg_%'" \\ @@ -1552,9 +1776,10 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe # Replay the dump connected to postgres psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres -f /tmp/dump.sql - # A dump taken before Floci created a predefined role does not recreate it + # What a dump does not bring back: the predefined roles of a dump taken before Floci created + # them, and in an instance initialized as rdsadmin the roles and ownership RDS gives it psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres <<'SQL' - """ + postgresIamRoleInitSql() + "SQL\n"; + """ + closingSql + "SQL\n"; } private static void addTarEntry( @@ -1638,16 +1863,19 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe return value; } - private List buildEnvVars(DatabaseEngine engine, String masterUsername, - String masterPassword, String dbName) { + static List buildEnvVars(DatabaseEngine engine, String masterUsername, + String masterPassword, String dbName) { String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres"; String effectiveDb = (dbName != null && !dbName.isBlank()) ? dbName : effectiveUser; List envs = new ArrayList<>(); switch (engine) { case POSTGRES -> { - envs.add("POSTGRES_USER=" + effectiveUser); - envs.add("POSTGRES_PASSWORD=" + masterPassword); + // Initialized as rdsadmin, whose password Floci sets again on every start; the master user is + // created by the init script installPostgresMasterInitScript adds. + boolean adminBootstrap = bootstrapsAsAdminRole(masterUsername); + envs.add("POSTGRES_USER=" + (adminBootstrap ? POSTGRES_ADMIN_ROLE : effectiveUser)); + envs.add("POSTGRES_PASSWORD=" + (adminBootstrap ? randomPostgresPassword() : masterPassword)); envs.add("POSTGRES_DB=" + effectiveDb); envs.add("POSTGRES_HOST_AUTH_METHOD=md5"); } diff --git a/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java b/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java index 39071b8dd3..738d5ec368 100644 --- a/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java +++ b/src/main/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandler.java @@ -41,7 +41,7 @@ import java.util.function.BiConsumer; *
  • For IAM logins, hand the session over to the role named in the token, then apply the * client's startup parameters as that role *
  • Send AuthOK + buffered messages to client, then bridge, guarding an IAM - * session against being handed back to the master role + * session against being handed back to the role the proxy connected as * */ public class PostgresProtocolHandler { @@ -91,7 +91,12 @@ public class PostgresProtocolHandler { } /** The username/password the proxy opens the backend PostgreSQL connection with. */ - record BackendLogin(String user, String password) {} + public record BackendLogin(String user, String password) { + @Override + public String toString() { + return "BackendLogin[user=" + user + "]"; + } + } /** * Opens the backend connection. Called only once the client's startup message and credentials @@ -223,6 +228,27 @@ public class PostgresProtocolHandler { StartupObserver startupObserver, SessionRoleHandover roleHandover, boolean requireSsl) throws IOException { + return authenticate(client, backendConnector, masterUsername, masterPassword, dbName, + iamEnabled, sigV4, binding, tlsCertificates, passwordValidator, handshakeTimeoutMillis, + forwardStartupParameters, databaseIamAuthentication, startupObserver, roleHandover, requireSsl, + null); + } + + /** + * {@code handoverLogin} is the superuser an IAM session for a role other than the master is opened as and + * handed over from, {@code rdsadmin} in an instance initialized as RDS initializes one, since only a + * superuser may {@code SET SESSION AUTHORIZATION}; null when the master user is that superuser. No client + * may log in as it. + */ + public static AuthenticatedSession authenticate(Socket client, BackendConnector backendConnector, + String masterUsername, String masterPassword, String dbName, + boolean iamEnabled, RdsSigV4Validator sigV4, + RdsProxyBinding binding, RdsProxyTlsCertificates tlsCertificates, + PasswordValidator passwordValidator, int handshakeTimeoutMillis, + boolean forwardStartupParameters, boolean databaseIamAuthentication, + StartupObserver startupObserver, + SessionRoleHandover roleHandover, + boolean requireSsl, BackendLogin handoverLogin) throws IOException { client.setSoTimeout(handshakeTimeoutMillis); @@ -263,6 +289,17 @@ public class PostgresProtocolHandler { boolean isIam = iamEnabled && clientPassword.contains("X-Amz-Signature"); boolean isMaster = masterUsername.equals(clientUsername); + // The superuser IAM sessions are handed over from is RDS's own role, which no client logs in as. + if (handoverLogin != null && !isMaster && handoverLogin.user().equals(clientUsername)) { + LOG.infov("RDS login refused for the internal superuser {0}", + SigV4RequestValidator.sanitizeForLog(clientUsername)); + sendErrorResponse(clientOut, "FATAL", "28P01", + "password authentication failed for user \"" + clientUsername + "\""); + clientOut.flush(); + closeQuietly(client); + return null; + } + PasswordValidator.AuthResult authResult = PasswordValidator.AuthResult.PASSTHROUGH; if (isIam) { if (!sigV4.validate(clientPassword, clientUsername, binding)) { @@ -350,11 +387,15 @@ public class PostgresProtocolHandler { backendUser = handoverOutcome.databaseRole(); backendPass = handoverOutcome.backendPassword() != null ? handoverOutcome.backendPassword() : masterPassword; + } else if (iamHandover && handoverLogin != null) { + backendUser = handoverLogin.user(); + backendPass = handoverLogin.password(); } - // An IAM login for any role but the master runs on a session opened as the master and - // handed over below, so PostgreSQL would apply the client's parameters with the - // master's privileges: a "-c role=" would outlive the handover and RESET ROLE - // would regain the master. Those logins open with only "replication", which cannot be + // An IAM login for any role but the master runs on a session opened as a superuser + // (rdsadmin, or the master where it is the bootstrap superuser) and handed over below, so + // PostgreSQL would apply the client's parameters with that superuser's privileges: a + // "-c role=" would outlive the handover and RESET ROLE would regain it. + // Those logins open with only "replication", which cannot be // chosen later, and their other parameters are applied once the session belongs to the // role (Phase 5c). The proxy reads that session's results and sends it SQL of its own, // so it fixes the encoding to UTF-8. @@ -459,7 +500,7 @@ public class PostgresProtocolHandler { } // Phase 5b: An IAM token is issued for one specific database role, so the session must - // run as that role even though the backend connection was opened as master. Handing it + // run as that role even though the backend connection was opened as a superuser. Handing it // over gives the session the role's own privileges and object ownership, and refuses a // token naming a role the database does not have instead of silently granting a master // session. @@ -502,7 +543,7 @@ public class PostgresProtocolHandler { // does when the role logs in directly. A parameter PostgreSQL refuses fails the // login with PostgreSQL's own reason, as it would at startup. One check cannot be // left to PostgreSQL: it authorizes session_authorization against the user the - // backend connection authenticated as, the superuser master, so a change of it is + // backend connection authenticated as, a superuser, so a change of it is // refused here before anything is applied, and the outcome is checked again below. if (forwardStartupParameters) { List settings; @@ -577,7 +618,7 @@ public class PostgresProtocolHandler { return null; } // PostgreSQL checks the replication privilege only when the WAL sender starts, - // which it did as the master, and never again for replication commands. + // which it did as the superuser, and never again for replication commands. if (requestsReplication(startup.parameters()) && !hasReplicationPrivilege(backendIn, backendOut)) { LOG.infov("RDS IAM replication connection refused for role {0}: replication privilege required", SigV4RequestValidator.sanitizeForLog(clientUsername)); @@ -897,9 +938,22 @@ public class PostgresProtocolHandler { /** * Follow catalog membership edges, including indirect grants. pg_has_role treats a * superuser as privileged without a grant, which is not an IAM authentication opt-in. + * A grant of ADMIN OPTION alone (PostgreSQL 16 and later), such as the one a role gets on each + * role it creates, or rds_superuser's on rds_iam, which lets the master grant it, makes no + * member, so it is not followed; servers before 16 record no such grant. * All SQL is ASCII even when the client selected a non-UTF8 encoding, and catalog * objects and operators are qualified independently of the client's search_path. */ + /** + * Whether a {@code pg_auth_members} row {@code a} makes its member a member of its role: a grant with INHERIT + * or SET. The options are read through {@code to_jsonb}, so the query also runs on a server before 16, whose + * rows have neither column and are memberships. + */ + private static final String MAKES_MEMBER = "(COALESCE((pg_catalog.to_jsonb(a) " + + "OPERATOR(pg_catalog.->>) 'inherit_option')::pg_catalog.bool, true) " + + "OR COALESCE((pg_catalog.to_jsonb(a) OPERATOR(pg_catalog.->>) 'set_option')" + + "::pg_catalog.bool, true))"; + static String databaseRoleQuery(String role, boolean iam, boolean sessionRole) { return databaseRoleQuery(role, iam, sessionRole, true); } @@ -920,8 +974,9 @@ public class PostgresProtocolHandler { return "WITH RECURSIVE memberships(oid) AS (" + "SELECT a.roleid FROM pg_catalog.pg_auth_members a JOIN pg_catalog.pg_roles r " + "ON r.oid OPERATOR(pg_catalog.=) a.member WHERE r.rolname OPERATOR(pg_catalog.=) " + name + + " AND " + MAKES_MEMBER + " UNION SELECT a.roleid FROM pg_catalog.pg_auth_members a JOIN memberships m " - + "ON a.member OPERATOR(pg_catalog.=) m.oid) " + + "ON a.member OPERATOR(pg_catalog.=) m.oid WHERE " + MAKES_MEMBER + ") " + "SELECT r.oid::pg_catalog.text, " + admission + " FROM pg_catalog.pg_roles r WHERE r.rolname OPERATOR(pg_catalog.=) " + name; } @@ -1226,7 +1281,7 @@ public class PostgresProtocolHandler { } /** - * The StartupMessage parameters of a backend session opened as the master for a handover: + * The StartupMessage parameters of a backend session opened as a superuser for a handover: * {@code base}, UTF-8 for the proxy's own queries, and the client's {@code replication}, * which can only be chosen at connection start. */ @@ -1293,7 +1348,7 @@ public class PostgresProtocolHandler { /** * Refuses a {@code session_authorization} setting naming anyone but {@code role}. PostgreSQL * would authorize it against the superuser the backend connection authenticated as, not the - * token's role, so it would hand the session back to the master. + * token's role, so it would hand the session back to that superuser. */ static void refuseSessionAuthorizationChange(List settings, String role) throws StartupParameterException { @@ -1509,8 +1564,8 @@ public class PostgresProtocolHandler { * Relays the authenticated session until either side closes. * *

    An IAM session gets its backend→client direction read message by message so the proxy - * sees PostgreSQL report the session's identity. The backend connection underneath is the - * master one, so a client that talks the session back to the master role, via {@code RESET + * sees PostgreSQL report the session's identity. The backend connection underneath is a + * superuser's, so a client that talks the session back to that role, via {@code RESET * SESSION AUTHORIZATION} and its variants, would otherwise regain superuser, which the * token never granted. Watching the server's own {@code session_authorization} report catches * that whatever SQL produced it; the session is then terminated, since a handover that already diff --git a/src/main/java/io/floci/aws/services/rds/proxy/RdsAuthProxy.java b/src/main/java/io/floci/aws/services/rds/proxy/RdsAuthProxy.java index 60c2662340..931b0be058 100644 --- a/src/main/java/io/floci/aws/services/rds/proxy/RdsAuthProxy.java +++ b/src/main/java/io/floci/aws/services/rds/proxy/RdsAuthProxy.java @@ -47,6 +47,7 @@ public class RdsAuthProxy { private final Semaphore connectionPermits; private final RdsBackendGate backendGate; private final BooleanSupplier forceSsl; + private final HandoverLoginResolver handoverLoginResolver; private volatile boolean running; private ServerSocket serverSocket; @@ -143,6 +144,24 @@ public class RdsAuthProxy { MySqlProtocolHandler.IamUserChecker iamUserChecker, RdsBackendGate backendGate, EndpointKind endpointKind, BooleanSupplier forceSsl) { + this(instanceId, backendHost, backendPort, backendEndpointResolver, backendRuntimeId, + engine, iamEnabled, masterUsername, masterPassword, dbName, sigV4, + tlsCertificates, passwordValidator, handshakeTimeoutMillis, + backendConnectTimeoutMillis, maxConnections, binding, iamUserChecker, + backendGate, endpointKind, forceSsl, () -> null); + } + + public RdsAuthProxy(String instanceId, String backendHost, int backendPort, + BackendEndpointResolver backendEndpointResolver, String backendRuntimeId, + DatabaseEngine engine, boolean iamEnabled, + String masterUsername, String masterPassword, String dbName, + RdsSigV4Validator sigV4, RdsProxyTlsCertificates tlsCertificates, + MasterPasswordCheck passwordValidator, + int handshakeTimeoutMillis, int backendConnectTimeoutMillis, + int maxConnections, RdsProxyBinding binding, + MySqlProtocolHandler.IamUserChecker iamUserChecker, + RdsBackendGate backendGate, EndpointKind endpointKind, + BooleanSupplier forceSsl, HandoverLoginResolver handoverLoginResolver) { if (backendRuntimeId == null || backendRuntimeId.isBlank()) { throw new IllegalArgumentException("RDS backend runtime ID is required"); } @@ -167,6 +186,7 @@ public class RdsAuthProxy { this.connectionPermits = new Semaphore(Math.max(1, maxConnections)); this.backendGate = backendGate; this.forceSsl = forceSsl; + this.handoverLoginResolver = handoverLoginResolver; } public void start(int proxyPort) throws IOException { @@ -290,7 +310,8 @@ public class RdsAuthProxy { client, connector, masterUsername, masterPassword, dbName, iamEnabled, sigV4, binding, tlsCertificates, authAdapter, handshakeTimeoutMillis, true, endpointKind == EndpointKind.DATABASE, - (user, database, parameters) -> { }, null, forceSsl.getAsBoolean()); + (user, database, parameters) -> { }, null, forceSsl.getAsBoolean(), + handoverLoginResolver.resolve()); if (session != null) { PostgresProtocolHandler.bridge(session); } @@ -359,4 +380,13 @@ public class RdsAuthProxy { public interface MasterPasswordCheck { boolean validate(String username, String password); } + + /** + * The login a PostgreSQL IAM session is opened as before it is handed over to the token's role, read for each + * connection since the backend may have restarted since; null to use the master user's. + */ + @FunctionalInterface + public interface HandoverLoginResolver { + PostgresProtocolHandler.BackendLogin resolve(); + } } diff --git a/src/main/java/io/floci/aws/services/rds/proxy/RdsProxyManager.java b/src/main/java/io/floci/aws/services/rds/proxy/RdsProxyManager.java index 31f6ca6469..b479d524f0 100644 --- a/src/main/java/io/floci/aws/services/rds/proxy/RdsProxyManager.java +++ b/src/main/java/io/floci/aws/services/rds/proxy/RdsProxyManager.java @@ -3,6 +3,7 @@ package io.floci.aws.services.rds.proxy; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo; import io.floci.aws.services.rds.container.RdsBackendGate; +import io.floci.aws.services.rds.container.RdsContainerHandle; import io.floci.aws.services.rds.container.RdsContainerManager; import io.floci.aws.services.rds.model.DatabaseEngine; import jakarta.enterprise.context.ApplicationScoped; @@ -86,6 +87,18 @@ public class RdsProxyManager { masterPassword, dbName, passwordValidator, binding, endpointKind); } + /** + * The rdsadmin login of the runtime's current PostgreSQL container, which an IAM session is handed over from, + * or null where the master user is the container's superuser. + */ + private RdsAuthProxy.HandoverLoginResolver handoverLogin(String backendRuntimeId) { + return () -> { + RdsContainerHandle.PostgresSuperuser superuser = containerManager.postgresHandoverLogin(backendRuntimeId); + return superuser == null ? null + : new PostgresProtocolHandler.BackendLogin(superuser.user(), superuser.password()); + }; + } + private void startProxy(String instanceId, String backendRuntimeId, DatabaseEngine engine, boolean iamEnabled, int proxyPort, String backendHost, int backendPort, @@ -110,7 +123,7 @@ public class RdsProxyManager { tlsCertificates, passwordValidator, rdsConfig.proxyHandshakeTimeoutMillis(), rdsConfig.proxyBackendConnectTimeoutMillis(), rdsConfig.proxyMaxConnections(), binding, username -> binding != null, backendGate, endpointKind, - () -> forceSsl.test(instanceId)); + () -> forceSsl.test(instanceId), handoverLogin(backendRuntimeId)); try { proxy.start(proxyPort); } catch (IOException e) { diff --git a/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerTest.java b/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerTest.java index 7ab60f1862..4c3628ae8a 100644 --- a/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerTest.java +++ b/src/test/java/io/floci/aws/services/rds/container/RdsContainerManagerTest.java @@ -331,6 +331,70 @@ class RdsContainerManagerTest { assertTrue(sql.contains("CREATE ROLE rds_replication")); } + @Test + void postgresIsInitializedAsRdsadminWithTheMasterCreatedByTheInitScript() { + List env = RdsContainerManager.buildEnvVars(DatabaseEngine.POSTGRES, "admin", "Secret1!", "appdb"); + + assertTrue(env.contains("POSTGRES_USER=rdsadmin")); + assertTrue(env.contains("POSTGRES_DB=appdb")); + assertFalse(env.contains("POSTGRES_PASSWORD=Secret1!"), "rdsadmin must not get the master user's password"); + assertTrue(env.stream().anyMatch(variable -> variable.matches("POSTGRES_PASSWORD=[0-9a-f]{48}"))); + } + + @Test + void postgresMasterNamedRdsadminStaysTheBootstrapSuperuser() { + assertFalse(RdsContainerManager.bootstrapsAsAdminRole("rdsadmin")); + assertTrue(RdsContainerManager.bootstrapsAsAdminRole("admin")); + assertTrue(RdsContainerManager.bootstrapsAsAdminRole(null)); + assertEquals(List.of("POSTGRES_USER=rdsadmin", "POSTGRES_PASSWORD=Secret1!", "POSTGRES_DB=rdsadmin", + "POSTGRES_HOST_AUTH_METHOD=md5"), + RdsContainerManager.buildEnvVars(DatabaseEngine.POSTGRES, "rdsadmin", "Secret1!", null)); + } + + @Test + void postgresMasterInitSqlCreatesTheMasterAsAnOrdinaryRoleThatOwnsItsDatabases() { + String sql = RdsContainerManager.postgresMasterInitSql("ad\"min", "it's", "appdb"); + + assertTrue(sql.startsWith("CREATE ROLE \"ad\"\"min\" WITH LOGIN PASSWORD 'it''s';\n")); + assertTrue(sql.contains("ALTER ROLE \"ad\"\"min\" WITH LOGIN NOSUPERUSER INHERIT CREATEDB CREATEROLE" + + " NOREPLICATION NOBYPASSRLS VALID UNTIL 'infinity';")); + assertTrue(sql.contains("GRANT rds_superuser TO \"ad\"\"min\";")); + assertTrue(sql.contains("ALTER DATABASE postgres OWNER TO \"ad\"\"min\";")); + assertTrue(sql.contains("ALTER DATABASE template1 OWNER TO \"ad\"\"min\";")); + assertTrue(sql.endsWith("ALTER DATABASE \"appdb\" OWNER TO \"ad\"\"min\";\n")); + assertFalse(RdsContainerManager.postgresMasterInitSql("admin", "pw", "postgres") + .contains("ALTER DATABASE \"postgres\"")); + assertTrue(RdsContainerManager.postgresMasterInitSql("admin", "pw", "rdsadmin") + .endsWith("ALTER DATABASE \"rdsadmin\" OWNER TO \"admin\";\n"), + "A database requested as rdsadmin must be the master's, which the role setup closes to others"); + } + + @Test + void postgresRdsRolesSqlGrantsRdsSuperuserWhatRdsGrantsIt() { + String sql = RdsContainerManager.postgresRdsRolesSql("admin"); + + assertTrue(sql.contains("ARRAY['rds_superuser', 'rds_password', 'rds_replication', 'rds_iam']")); + assertTrue(sql.contains("'pg_monitor', 'pg_read_all_data', 'pg_signal_backend'")); + assertTrue(sql.contains("GRANT %I TO rds_superuser WITH ADMIN OPTION")); + assertTrue(sql.contains("GRANT rds_iam TO rds_superuser WITH ADMIN OPTION, INHERIT FALSE, SET FALSE"), + "The master must be able to grant rds_iam without becoming an IAM-only member of it"); + assertTrue(sql.contains("SELECT 'CREATE DATABASE rdsadmin' WHERE NOT EXISTS")); + assertTrue(sql.contains("\n\\gexec\n")); + assertTrue(sql.endsWith("REVOKE ALL ON DATABASE rdsadmin FROM PUBLIC;\n")); + } + + @Test + void restoreScriptTakesTheKeptDatabasesFromTheRolesItDropsAndEndsWithTheClosingSql() { + String script = RdsContainerManager.postgresRestoreScript("SELECT 'closing';\n"); + + int owners = script.indexOf("ALTER DATABASE template1 OWNER TO CURRENT_USER"); + int drops = script.indexOf("DROP ROLE IF EXISTS"); + int replay = script.indexOf("-f /tmp/dump.sql"); + assertTrue(script.contains("ALTER DATABASE postgres OWNER TO CURRENT_USER")); + assertTrue(owners >= 0 && owners < drops, "A kept database must not keep a role from being dropped"); + assertTrue(script.indexOf("SELECT 'closing';") > replay); + } + @Test void mysqlMasterGrantSqlGrantsGlobalPrivilegesWithGrantOption() { String sql = RdsContainerManager.mysqlMasterGrantSql("admin"); @@ -847,6 +911,25 @@ class RdsContainerManagerTest { assertTrue(manager.isDockerReachable()); } + @Test + void aRenamedRuntimeKeepsItsPostgresSuperuserLogin() { + ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class); + stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo( + "blue-container", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("blue", 3306)))); + RdsContainerManager manager = daemonlessCapableManager(lifecycleManager); + String blue = "arn:aws:rds:us-east-1:000000000000:db:blue"; + String green = "arn:aws:rds:us-east-1:000000000000:db:green"; + manager.start(blue, "blue", null, DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"); + RdsContainerHandle.PostgresSuperuser login = new RdsContainerHandle.PostgresSuperuser("rdsadmin", "secret"); + manager.getActiveHandle(blue).setPostgresSuperuser(login); + + manager.renameRuntime(blue, green, "green"); + + assertSame(login, manager.postgresHandoverLogin(green)); + assertEquals("rdsadmin", manager.postgresSuperuser("blue-container", "admin")); + assertNull(manager.postgresHandoverLogin(blue)); + } + @Test void tryStartSucceedsForTheSameRuntimeOnceADaemonAppears() { ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class); diff --git a/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java b/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java index 5d0c567301..f669bc6d30 100644 --- a/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java +++ b/src/test/java/io/floci/aws/services/rds/proxy/PostgresProtocolHandlerTest.java @@ -794,6 +794,99 @@ class PostgresProtocolHandlerTest { } } + @Test + void iamSessionIsOpenedAsTheHandoverSuperuserWhenTheMasterIsNone() throws Exception { + AtomicReference> backendStartup = new AtomicReference<>(); + AtomicReference backendQuery = new AtomicReference<>(); + + try (ServerSocket backendServer = new ServerSocket(0); + ServerSocket clientServer = new ServerSocket(0)) { + + int backendPort = backendServer.getLocalPort(); + Thread backendThread = Thread.ofVirtual().start(() -> { + try { + mockBackendRoleSwitch(backendServer, backendStartup, backendQuery, "approle", true); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + + try (Socket ourClient = connectTestSocket("localhost", clientServer.getLocalPort())) { + ourClient.setSoTimeout(5_000); + Socket proxyClient = acceptTestSocket(clientServer); + Socket backend = connectTestSocket("localhost", backendPort); + Thread authThread = Thread.ofVirtual().start(() -> { + try { + PostgresProtocolHandler.AuthenticatedSession session = PostgresProtocolHandler.authenticate( + proxyClient, () -> backend, "dbadmin", "adminpass", "postgres", + true, testSigV4Validator(), testBinding(), testTlsCertificates(), + (user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000, true, true, + (user, database, parameters) -> { }, null, false, + new PostgresProtocolHandler.BackendLogin("rdsadmin", "start-secret")); + if (session != null) { + PostgresProtocolHandler.bridge(session); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + + DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream()); + DataInputStream clientIn = new DataInputStream(ourClient.getInputStream()); + writeStartup(clientOut, "approle", "postgres"); + readCleartextPasswordChallenge(clientIn); + writePassword(clientOut, rdsToken("approle")); + readAuthenticationOk(clientIn); + assertEquals("approle", readParametersUntilReadyForQuery(clientIn).get("session_authorization")); + + ourClient.close(); + proxyClient.close(); + authThread.join(5_000); + backendThread.join(5_000); + assertFalse(authThread.isAlive(), "authThread did not terminate"); + assertFalse(backendThread.isAlive(), "backendThread did not terminate"); + } + + assertEquals("rdsadmin", backendStartup.get().get("user")); + assertEquals("SET SESSION AUTHORIZATION \"approle\"", backendQuery.get()); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void noClientLogsInAsTheHandoverSuperuser(boolean iam) throws Exception { + ByteArrayOutputStream input = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(input); + writeStartup(out, "rdsadmin", "postgres"); + writePassword(out, iam ? rdsToken("rdsadmin") : "start-secret"); + MemorySocket client = new MemorySocket(input.toByteArray()); + + assertNull(PostgresProtocolHandler.authenticate( + client, NEVER_CONNECT, "dbadmin", "adminpass", "postgres", + true, testSigV4Validator(), testBinding(), testTlsCertificates(), + (user, pass) -> PasswordValidator.AuthResult.PASSTHROUGH, 5000, true, true, + (user, database, parameters) -> { }, null, false, + new PostgresProtocolHandler.BackendLogin("rdsadmin", "start-secret"))); + + DataInputStream clientIn = new DataInputStream( + new ByteArrayInputStream(client.getOutputStream().toByteArray())); + readCleartextPasswordChallenge(clientIn); + Map error = readErrorResponse(clientIn); + assertEquals("FATAL", error.get('S')); + assertEquals("28P01", error.get('C')); + assertEquals("password authentication failed for user \"rdsadmin\"", error.get('M')); + } + + @Test + void roleQueryFollowsOnlyTheGrantsThatMakeAMember() { + String query = PostgresProtocolHandler.databaseRoleQuery("app_user", true, false); + + assertTrue(query.contains("'inherit_option')::pg_catalog.bool, true) OR COALESCE(")); + assertTrue(query.contains("'set_option')::pg_catalog.bool, true))")); + assertEquals(2, query.split("pg_catalog.to_jsonb\\(a\\) OPERATOR\\(pg_catalog.->>\\) 'inherit_option'", + -1).length - 1, "Both the first grant and every indirect one must make a member"); + } + @Test void iamSessionAppliesClientStartupParametersAsTheTokenRole() throws Exception { AtomicReference> backendStartup = new AtomicReference<>(); diff --git a/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresIamRoleIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresIamRoleIntegrationTest.java index f6d03926b8..985bde6d65 100644 --- a/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresIamRoleIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresIamRoleIntegrationTest.java @@ -218,11 +218,19 @@ class RdsPostgresIamRoleIntegrationTest { @Test void iamLogicalReplicationConnectionRequiresTheReplicationPrivilege() throws Exception { String id = uniqueId(); + String group = id + "-logical"; try { - int port = createPostgresInstance(id, MASTER, PASSWORD, true); - asMaster(port, "CREATE ROLE app_user LOGIN", "GRANT rds_iam TO app_user", - "ALTER SYSTEM SET wal_level = logical", "CREATE TABLE events (id int)"); - rds("RebootDBInstance").formParam("DBInstanceIdentifier", id).when().post("/").then().statusCode(200); + // The master user is no superuser, so logical replication comes from the parameter group, as on RDS. + rds("CreateDBParameterGroup").formParam("DBParameterGroupName", group) + .formParam("DBParameterGroupFamily", "postgres16").formParam("Description", "logical replication") + .when().post("/").then().statusCode(200); + rds("ModifyDBParameterGroup").formParam("DBParameterGroupName", group) + .formParam("Parameters.member.1.ParameterName", "rds.logical_replication") + .formParam("Parameters.member.1.ParameterValue", "1") + .formParam("Parameters.member.1.ApplyMethod", "pending-reboot") + .when().post("/").then().statusCode(200); + int port = createPostgresInstance(id, MASTER, PASSWORD, true, group); + asMaster(port, "CREATE ROLE app_user LOGIN", "GRANT rds_iam TO app_user", "CREATE TABLE events (id int)"); Properties replication = token(port, "app_user"); replication.setProperty("replication", "database"); replication.setProperty("assumeMinServerVersion", "10"); @@ -260,6 +268,7 @@ class RdsPostgresIamRoleIntegrationTest { assertUser(port, replication, "app_user"); } finally { deleteInstance(id); + rds("DeleteDBParameterGroup").formParam("DBParameterGroupName", group).when().post("/"); } } diff --git a/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresMasterRoleIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresMasterRoleIntegrationTest.java new file mode 100644 index 0000000000..4fd7f90ca3 --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresMasterRoleIntegrationTest.java @@ -0,0 +1,141 @@ +package io.floci.aws.services.rds.proxy; + +import io.floci.aws.testutil.SigV4TokenTestHelper; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.xml.XmlPath; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Instant; +import java.util.Properties; + +import static io.floci.aws.testing.RdsRequests.createPostgresInstance; +import static io.floci.aws.testing.RdsRequests.deleteInstance; +import static io.floci.aws.testing.RdsRequests.rds; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * A PostgreSQL instance is initialized as RDS initializes one: {@code rdsadmin} is the bootstrap superuser and the + * master user is an ordinary role in {@code rds_superuser} (RDS User Guide, "Understanding the rds_superuser + * role"), so the master's objects can be reassigned, and IAM sessions are still handed over to their roles. + */ +@QuarkusTest +@Tag("docker") +class RdsPostgresMasterRoleIntegrationTest { + private static final String MASTER = "master"; + private static final String PASSWORD = "Master123!"; + + @Test + void theMasterIsAnOrdinaryRoleInRdsSuperuserAndKeepsItThroughASnapshot() throws Exception { + String suffix = Long.toString(System.nanoTime(), 36); + String id = "master-role-" + suffix; + String snapshot = id + "-snap"; + String restored = id + "-restored"; + try { + int port = createPostgresInstance(id, MASTER, PASSWORD, true); + try (Connection connection = connect(port, "appdb", login(MASTER, PASSWORD)); + Statement sql = connection.createStatement()) { + assertEquals("false|true|true|false|false|infinity", row(sql, "SELECT rolsuper || '|' || " + + "rolcreaterole || '|' || rolcreatedb || '|' || rolreplication || '|' || rolbypassrls " + + "|| '|' || rolvaliduntil FROM pg_roles WHERE rolname = current_user")); + assertEquals("true|true", row(sql, "SELECT pg_has_role(current_user, 'rds_superuser', 'member') || '|' " + + "|| pg_has_role('rds_superuser', 'rds_replication', 'member')")); + assertEquals("rdsadmin", row(sql, "SELECT rolname FROM pg_roles WHERE oid = 10")); + assertEquals("appdb=master,postgres=master,rdsadmin=rdsadmin,template1=master", row(sql, + "SELECT string_agg(datname || '=' || pg_get_userbyid(datdba), ',' ORDER BY datname) " + + "FROM pg_database WHERE datname <> 'template0'")); + + sql.execute("CREATE TABLE owned (id int)"); + sql.execute("CREATE ROLE app_rw"); + sql.execute("GRANT app_rw TO master"); + sql.execute("REASSIGN OWNED BY master TO app_rw"); + assertEquals("app_rw", row(sql, "SELECT tableowner FROM pg_tables WHERE tablename = 'owned'")); + + sql.execute("CREATE ROLE cdc LOGIN"); + sql.execute("GRANT rds_replication TO cdc"); + sql.execute("CREATE ROLE app_user LOGIN"); + sql.execute("GRANT rds_iam TO app_user"); + } + assertSessionUser(port, login(MASTER, PASSWORD), MASTER); + assertSessionUser(port, token(port, "app_user"), "app_user"); + assertRefused(port, "appdb", login("rdsadmin", PASSWORD), "28P01"); + assertRefused(port, "appdb", token(port, "rdsadmin"), "28P01"); + assertRefused(port, "rdsadmin", login(MASTER, PASSWORD), "42501"); + + rds("CreateDBSnapshot").formParam("DBInstanceIdentifier", id) + .formParam("DBSnapshotIdentifier", snapshot).when().post("/").then().statusCode(200); + rds("RestoreDBInstanceFromDBSnapshot").formParam("DBInstanceIdentifier", restored) + .formParam("DBSnapshotIdentifier", snapshot).formParam("EnableIAMDatabaseAuthentication", true) + .when().post("/").then().statusCode(200); + int restoredPort = availablePort(restored); + try (Connection connection = connect(restoredPort, "appdb", login(MASTER, PASSWORD)); + Statement sql = connection.createStatement()) { + assertEquals("false|rdsadmin|app_rw", row(sql, "SELECT (SELECT rolsuper::text FROM pg_roles " + + "WHERE rolname = current_user) || '|' || (SELECT rolname FROM pg_roles WHERE oid = 10) " + + "|| '|' || (SELECT tableowner FROM pg_tables WHERE tablename = 'owned')")); + } + assertSessionUser(restoredPort, token(restoredPort, "app_user"), "app_user"); + } finally { + deleteInstance(restored); + rds("DeleteDBSnapshot").formParam("DBSnapshotIdentifier", snapshot).when().post("/"); + deleteInstance(id); + } + } + + private static String row(Statement sql, String query) throws SQLException { + try (ResultSet rows = sql.executeQuery(query)) { + rows.next(); + return rows.getString(1); + } + } + + private static void assertSessionUser(int port, Properties properties, String user) throws SQLException { + try (Connection connection = connect(port, "appdb", properties); + Statement sql = connection.createStatement()) { + assertEquals(user + "|off", row(sql, "SELECT session_user || '|' || current_setting('is_superuser')")); + } + } + + /** Polls the instance until it is available and returns its endpoint port. */ + private static int availablePort(String id) throws InterruptedException { + String path = "DescribeDBInstancesResponse.DescribeDBInstancesResult.DBInstances.DBInstance."; + for (int attempt = 0; attempt < 120; attempt++) { + XmlPath instance = rds("DescribeDBInstances").formParam("DBInstanceIdentifier", id) + .when().post("/").then().statusCode(200).extract().xmlPath(); + if ("available".equals(instance.getString(path + "DBInstanceStatus"))) { + return instance.getInt(path + "Endpoint.Port"); + } + Thread.sleep(500); + } + throw new AssertionError("DB instance " + id + " did not become available"); + } + + private static void assertRefused(int port, String database, Properties properties, String sqlState) { + SQLException refusal = assertThrows(SQLException.class, () -> connect(port, database, properties).close()); + assertEquals(sqlState, refusal.getSQLState(), refusal.getMessage()); + } + + private static Properties login(String user, String password) { + Properties properties = new Properties(); + properties.setProperty("user", user); + properties.setProperty("password", password); + properties.setProperty("sslmode", "disable"); + properties.setProperty("connectTimeout", "5"); + return properties; + } + + private static Properties token(int port, String user) throws Exception { + return login(user, SigV4TokenTestHelper.createRdsToken("localhost", port, user, + "test", "test", Instant.now(), 900)); + } + + private static Connection connect(int port, String database, Properties properties) throws SQLException { + return DriverManager.getConnection("jdbc:postgresql://localhost:" + port + "/" + database, properties); + } +} diff --git a/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresStartupParametersIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresStartupParametersIntegrationTest.java index 78df4ce70b..a799d5a0a1 100644 --- a/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresStartupParametersIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/proxy/RdsPostgresStartupParametersIntegrationTest.java @@ -1,7 +1,11 @@ package io.floci.aws.services.rds.proxy; +import com.github.dockerjava.api.DockerClient; +import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.services.rds.RdsService; import io.floci.aws.testutil.SigV4TokenTestHelper; import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -34,6 +38,12 @@ class RdsPostgresStartupParametersIntegrationTest { private static final String MASTER_USER = "master"; private static final String MASTER_PASSWORD = "Master123!"; + @Inject + RdsService rdsService; + + @Inject + DockerClient dockerClient; + @BeforeEach void checkDocker() throws InterruptedException { assumeDocker(); @@ -79,7 +89,8 @@ class RdsPostgresStartupParametersIntegrationTest { asMaster(port, "CREATE ROLE app_user LOGIN", "GRANT rds_iam TO app_user", - "CREATE SCHEMA floci_opts AUTHORIZATION app_user", + "CREATE SCHEMA floci_opts", + "GRANT USAGE ON SCHEMA floci_opts TO app_user", // A database that refuses \' in string literals must still accept the parameters. "ALTER DATABASE appdb SET backslash_quote = off"); @@ -133,12 +144,14 @@ class RdsPostgresStartupParametersIntegrationTest { "ALTER ROLE app_user SET work_mem = '32MB'", "ALTER ROLE app_user IN DATABASE appdb SET work_mem = '48MB'", "ALTER ROLE app_user SET statement_timeout = '7s'", - // Superuser-only: applies at login although app_user could not set it itself. - "ALTER ROLE app_user SET log_min_duration_statement = '1s'", "ALTER ROLE app_user SET role = 'reader'", - // Read on a session whose encoding the master's default would otherwise set. - "ALTER ROLE app_user SET floci.note = 'café'", "ALTER ROLE " + MASTER_USER + " SET client_encoding = 'LATIN1'"); + // Superuser-only, so set by the instance's superuser, which the master user is not: it applies at + // login although app_user could not set it itself. + asSuperuser(dbId, "ALTER ROLE app_user SET log_min_duration_statement = '1s'"); + // Read on a session whose encoding the master's default would otherwise set. A placeholder + // parameter is the superuser's to store as a role default since PostgreSQL 15. + asSuperuser(dbId, "ALTER ROLE app_user SET floci.note = 'café'"); Properties iam = iamLogin(port, "app_user"); iam.setProperty("options", "-c statement_timeout=9s"); @@ -179,6 +192,14 @@ class RdsPostgresStartupParametersIntegrationTest { } } + /** Runs {@code sql} in the instance's database as rdsadmin, its superuser. */ + private void asSuperuser(String dbId, String sql) { + String[] psql = {"psql", "-v", "ON_ERROR_STOP=1", "-U", "rdsadmin", "-d", "appdb", "-c", sql}; + ContainerExec.Result result = ContainerExec.run(dockerClient, + rdsService.getDbInstance(dbId).getContainerId(), psql, 30); + assertThat(result.stderr(), result.exitCode(), equalTo(0L)); + } + private static String jdbcUrl(int port) { return "jdbc:postgresql://localhost:" + port + "/appdb"; }