mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(rds): initialize PostgreSQL as rdsadmin, with the master user in rds_superuser (#9182)
A PostgreSQL backend started with the master user as POSTGRES_USER, so the master was the bootstrap superuser and owned the system catalog: REASSIGN OWNED BY <master> failed with "required by the database system", and rds_superuser did not exist. A new backend is now initialized as rdsadmin, as RDS initializes one. A first-boot script creates the master as LOGIN NOSUPERUSER INHERIT CREATEDB CREATEROLE NOREPLICATION VALID UNTIL 'infinity' in rds_superuser (RDS User Guide, "Understanding the rds_superuser role"). The master owns postgres, template1 and the instance's database. rds_superuser holds rds_password, rds_replication and the predefined pg_* roles RDS grants it, with ADMIN OPTION, and ADMIN OPTION alone on rds_iam on PostgreSQL 16 and later, so the master can grant rds_iam without becoming an IAM-only member. The rdsadmin database is closed to PUBLIC. rdsadmin gets a random password on every start, which only the auth proxy uses: an IAM session for a role other than the master is opened as rdsadmin and handed over, since only a superuser can SET SESSION AUTHORIZATION. No client may log in as rdsadmin. The proxy's rds_iam walk skips grants of ADMIN OPTION alone, such as the one PostgreSQL 16 gives the master on each role it creates. Snapshots, restores, exports and database renames run as rdsadmin; a restore applies the RDS roles and ownership again and gives rdsadmin back its password. A data volume first initialized by an earlier Floci keeps its master as the bootstrap superuser, and a master named rdsadmin stays one. Two tests leaned on a superuser master: the IAM replication test now turns logical replication on through rds.logical_replication in a parameter group instead of ALTER SYSTEM, and the startup-parameters test stores its superuser-only role defaults as rdsadmin and gives app_user its schema with GRANT USAGE. Closes #5885
This commit is contained in:
1 parent
d63ad7c226
commit
94c0504bca
11 files changed
+779
-60
No files matched your search
@@ -331,6 +331,70 @@ class RdsContainerManagerTest {
|
||||
assertTrue(sql.contains("CREATE ROLE rds_replication"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void postgresIsInitializedAsRdsadminWithTheMasterCreatedByTheInitScript() {
|
||||
List<String> 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);
|
||||
|
||||
@@ -794,6 +794,99 @@ class PostgresProtocolHandlerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamSessionIsOpenedAsTheHandoverSuperuserWhenTheMasterIsNone() throws Exception {
|
||||
AtomicReference<Map<String, String>> backendStartup = new AtomicReference<>();
|
||||
AtomicReference<String> 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<Character, String> 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<Map<String, String>> backendStartup = new AtomicReference<>();
|
||||
|
||||
+13
-4
@@ -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("/");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+141
@@ -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);
|
||||
}
|
||||
}
|
||||
+26
-5
@@ -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";
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user