mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(rds): accept IAM auth for PostgreSQL logical replication connections (#8671)
This commit is contained in:
1 parent
6a5a464ca8
commit
d7c2616c72
8 files changed
+527
-37
No files matched your search
@@ -112,6 +112,9 @@ class RdsContainerManagerPostgresTest {
|
||||
"SELECT value FROM probe WHERE id = 1");
|
||||
assertEquals("round-trip-test", result.trim(),
|
||||
"Restored database should contain the probe row");
|
||||
assertEquals("rds_iam\nrds_replication", queryPsql(targetContainerId, MASTER_USER, DB_NAME,
|
||||
"SELECT rolname FROM pg_roles WHERE rolname IN ('rds_iam', 'rds_replication') ORDER BY 1").trim(),
|
||||
"A dump without the predefined roles should restore with them");
|
||||
}
|
||||
|
||||
private String startPostgresContainer(String name) {
|
||||
|
||||
@@ -323,6 +323,14 @@ class RdsContainerManagerTest {
|
||||
assertTrue(sql.contains("CREATE ROLE rds_iam"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void postgresInitSqlCreatesRdsReplicationRoleWhenMissing() {
|
||||
String sql = RdsContainerManager.postgresIamRoleInitSql();
|
||||
|
||||
assertTrue(sql.contains("rolname = 'rds_replication'"));
|
||||
assertTrue(sql.contains("CREATE ROLE rds_replication"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlMasterGrantSqlGrantsGlobalPrivilegesWithGrantOption() {
|
||||
String sql = RdsContainerManager.mysqlMasterGrantSql("admin");
|
||||
@@ -1550,6 +1558,15 @@ class RdsContainerManagerTest {
|
||||
"Script must not drop system roles");
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreScriptCreatesThePredefinedRolesAfterReplayingTheDump() {
|
||||
String script = RdsContainerManager.postgresRestoreScript();
|
||||
|
||||
int replay = script.indexOf("-f /tmp/dump.sql");
|
||||
int roles = script.indexOf(RdsContainerManager.postgresIamRoleInitSql());
|
||||
assertTrue(replay >= 0 && roles > replay, "Roles a dump lacks must be created after it is replayed");
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreScriptInterpolatesUser() {
|
||||
String script = RdsContainerManager.postgresRestoreScript();
|
||||
|
||||
@@ -42,6 +42,7 @@ import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.logging.LogRecord;
|
||||
|
||||
@@ -749,6 +750,154 @@ class PostgresProtocolHandlerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void iamReplicationSessionNeedsTheTokenRolesReplicationPrivilege(boolean privileged) throws Exception {
|
||||
AtomicReference<Map<String, String>> backendStartup = new AtomicReference<>();
|
||||
AtomicReference<String> privilegeQuery = 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, new AtomicReference<>(),
|
||||
"approle", true, (in, out) -> {
|
||||
answerRoleAdmission(in, out, "approle", true, true);
|
||||
privilegeQuery.set(readSimpleQuery(in));
|
||||
writeDataRow(out, "100", privileged ? "t" : "f");
|
||||
writeCommandComplete(out, "SELECT 1");
|
||||
writeReadyForQuery(out);
|
||||
if (!privileged) {
|
||||
assertEquals(-1, in.read(), "refusal must close the backend");
|
||||
}
|
||||
});
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
});
|
||||
|
||||
Socket proxyClient;
|
||||
try (Socket ourClient = connectTestSocket("localhost", clientServer.getLocalPort())) {
|
||||
ourClient.setSoTimeout(5_000);
|
||||
proxyClient = acceptTestSocket(clientServer);
|
||||
Socket backend = connectTestSocket("localhost", backendPort);
|
||||
|
||||
Thread authThread = startIamAuth(proxyClient, backend);
|
||||
|
||||
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
|
||||
DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
|
||||
|
||||
Map<String, String> clientStartup = new LinkedHashMap<>();
|
||||
clientStartup.put("user", "approle");
|
||||
clientStartup.put("database", "postgres");
|
||||
clientStartup.put("replication", "database");
|
||||
writeStartup(clientOut, clientStartup);
|
||||
readCleartextPasswordChallenge(clientIn);
|
||||
writePassword(clientOut, rdsToken("approle"));
|
||||
|
||||
if (privileged) {
|
||||
readAuthenticationOk(clientIn);
|
||||
assertEquals("approle", readParametersUntilReadyForQuery(clientIn).get("session_authorization"));
|
||||
} else {
|
||||
Map<Character, String> refusal = readErrorResponse(clientIn);
|
||||
assertEquals("FATAL", refusal.get('S'));
|
||||
assertEquals("42501", refusal.get('C'));
|
||||
assertEquals("permission denied to start WAL sender", refusal.get('M'));
|
||||
assertEquals(-1, clientIn.read());
|
||||
}
|
||||
|
||||
ourClient.close();
|
||||
proxyClient.close();
|
||||
authThread.join(5_000);
|
||||
backendThread.join(5_000);
|
||||
assertEquals(false, authThread.isAlive(), "authThread did not terminate");
|
||||
assertEquals(false, backendThread.isAlive(), "backendThread did not terminate");
|
||||
}
|
||||
|
||||
assertEquals(List.of("user", "database", "client_encoding", "replication"),
|
||||
List.copyOf(backendStartup.get().keySet()));
|
||||
assertEquals("database", backendStartup.get().get("replication"));
|
||||
assertEquals(PostgresProtocolHandler.replicationPrivilegeQuery(), privilegeQuery.get());
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void iamReplicationSessionHandsPhysicalReplicationCommandsToPostgresAsAPermissionError(boolean replication)
|
||||
throws Exception {
|
||||
List<String> relayed = new CopyOnWriteArrayList<>();
|
||||
|
||||
try (ServerSocket backendServer = new ServerSocket(0);
|
||||
ServerSocket clientServer = new ServerSocket(0)) {
|
||||
|
||||
int backendPort = backendServer.getLocalPort();
|
||||
Thread backendThread = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
mockBackendRoleSwitch(backendServer, new AtomicReference<>(), new AtomicReference<>(),
|
||||
"approle", true, (in, out) -> {
|
||||
answerRoleAdmission(in, out, "approle", true, true);
|
||||
if (replication) {
|
||||
readSimpleQuery(in);
|
||||
writeDataRow(out, "100", "t");
|
||||
writeCommandComplete(out, "SELECT 1");
|
||||
writeReadyForQuery(out);
|
||||
}
|
||||
for (int i = 0; i < 2; i++) {
|
||||
relayed.add(readSimpleQuery(in));
|
||||
writeCommandComplete(out, "OK");
|
||||
writeReadyForQuery(out);
|
||||
}
|
||||
});
|
||||
} 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 = startIamAuth(proxyClient, backend);
|
||||
|
||||
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
|
||||
DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
|
||||
|
||||
Map<String, String> clientStartup = new LinkedHashMap<>();
|
||||
clientStartup.put("user", "approle");
|
||||
clientStartup.put("database", "postgres");
|
||||
if (replication) {
|
||||
clientStartup.put("replication", "database");
|
||||
}
|
||||
writeStartup(clientOut, clientStartup);
|
||||
readCleartextPasswordChallenge(clientIn);
|
||||
writePassword(clientOut, rdsToken("approle"));
|
||||
readAuthenticationOk(clientIn);
|
||||
readParametersUntilReadyForQuery(clientIn);
|
||||
|
||||
writeSimpleQuery(clientOut, "BASE_BACKUP");
|
||||
writeSimpleQuery(clientOut, "IDENTIFY_SYSTEM");
|
||||
for (int i = 0; i < 2; i++) {
|
||||
assertEquals('C', clientIn.readByte());
|
||||
clientIn.readNBytes(clientIn.readInt() - 4);
|
||||
readReadyForQuery(clientIn);
|
||||
}
|
||||
|
||||
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(List.of(replication ? PostgresProtocolHandler.PHYSICAL_REPLICATION_REFUSAL : "BASE_BACKUP",
|
||||
"IDENTIFY_SYSTEM"), relayed);
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamSessionIsRefusedWhenPostgresRefusesAStartupParameterForTheTokenRole() throws Exception {
|
||||
try (ServerSocket backendServer = new ServerSocket(0);
|
||||
@@ -1125,19 +1274,73 @@ class PostgresProtocolHandlerTest {
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"f", "FALSE", "n", "no", "of", "OFF", "0"})
|
||||
void sessionSettingsTreatEveryFalseReplicationValueAsAnOrdinaryConnection(String value) throws Exception {
|
||||
@ValueSource(strings = {"f", "OFF", "0", "database", "true", "on", "maybe"})
|
||||
void sessionSettingsLeaveReplicationToTheBackendStartup(String value) throws Exception {
|
||||
assertEquals(List.of(), PostgresProtocolHandler.sessionSettings(
|
||||
Map.of("user", "approle", "replication", value)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"database,0A000", "true,0A000", "t,0A000", "on,0A000", "1,0A000", "o,22023", "maybe,22023"})
|
||||
void sessionSettingsRefuseAReplicationConnectionOrAValuePostgresCannotRead(String value, String sqlState) {
|
||||
PostgresProtocolHandler.StartupParameterException e = assertThrows(
|
||||
PostgresProtocolHandler.StartupParameterException.class,
|
||||
() -> PostgresProtocolHandler.sessionSettings(Map.of("user", "approle", "replication", value)));
|
||||
assertEquals(sqlState, e.sqlState());
|
||||
@CsvSource({"database,true", "true,true", "t,true", "on,true", "1,true",
|
||||
"false,false", "off,false", "0,false", "DATABASE,false", "o,false", "maybe,false"})
|
||||
void requestsReplicationReadsTheValuesPostgresStartsAWalSenderFor(String value, boolean expected) {
|
||||
assertEquals(expected, PostgresProtocolHandler.requestsReplication(Map.of("replication", value)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"BASE_BACKUP",
|
||||
"BASE_BACKUP (LABEL 'x', CHECKPOINT 'fast')",
|
||||
" \t\r\n\fBASE_BACKUP LABEL 'x'",
|
||||
"base_backup",
|
||||
"START_REPLICATION 0/0",
|
||||
"START_REPLICATION PHYSICAL 0/0 TIMELINE 1",
|
||||
"START_REPLICATION SLOT s 0/0",
|
||||
"START_REPLICATION SLOT s PHYSICAL 0/0",
|
||||
"START_REPLICATION SLOT \"LOGICAL\" 0/0",
|
||||
"START_REPLICATION SLOT s /* LOGICAL */ 0/0",
|
||||
"START_REPLICATION SLOT LOGICAL 0/0",
|
||||
"CREATE_REPLICATION_SLOT s PHYSICAL",
|
||||
"CREATE_REPLICATION_SLOT s TEMPORARY PHYSICAL RESERVE_WAL",
|
||||
"CREATE_REPLICATION_SLOT \"LOGICAL\" PHYSICAL",
|
||||
"CREATE_REPLICATION_SLOT s TEMPORARY \"LOGICAL\" x",
|
||||
"CREATE_REPLICATION_SLOT s (LOGICAL) PHYSICAL",
|
||||
"CREATE_REPLICATION_SLOT",
|
||||
"READ_REPLICATION_SLOT s",
|
||||
"TIMELINE_HISTORY 1",
|
||||
"UPLOAD_MANIFEST"})
|
||||
void physicalReplicationCommandsAreNotPermittedOnLogicalReplication(String command) {
|
||||
assertFalse(PostgresProtocolHandler.permittedOnLogicalReplication(command));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"IDENTIFY_SYSTEM",
|
||||
"IDENTIFY_SYSTEM;",
|
||||
"SHOW wal_level",
|
||||
"CREATE_REPLICATION_SLOT s LOGICAL pgoutput",
|
||||
"CREATE_REPLICATION_SLOT \"s\" TEMPORARY LOGICAL pgoutput (SNAPSHOT 'nothing')",
|
||||
"\n CREATE_REPLICATION_SLOT logical LOGICAL test_decoding EXPORT_SNAPSHOT",
|
||||
"DROP_REPLICATION_SLOT s WAIT",
|
||||
"ALTER_REPLICATION_SLOT s (FAILOVER true)",
|
||||
"START_REPLICATION SLOT s LOGICAL 0/0",
|
||||
"START_REPLICATION SLOT \"s\" LOGICAL 16/B374D848 (\"proto_version\" '1', \"publication_names\" 'pub')",
|
||||
"SELECT 1",
|
||||
"BEGIN; SELECT pg_catalog.pg_current_wal_lsn()",
|
||||
"",
|
||||
"/* c */ BASE_BACKUP",
|
||||
"SELECT 1; BASE_BACKUP"})
|
||||
void logicalReplicationCommandsAndSqlArePermittedOnLogicalReplication(String command) {
|
||||
assertTrue(PostgresProtocolHandler.permittedOnLogicalReplication(command));
|
||||
}
|
||||
|
||||
@Test
|
||||
void handoverStartupParametersCarryTheClientsReplicationChoice() {
|
||||
assertEquals(Map.of("client_encoding", "UTF8"),
|
||||
PostgresProtocolHandler.handoverStartupParameters(Map.of("application_name", "svc"), Map.of()));
|
||||
assertEquals(List.of("options", "client_encoding", "replication"), List.copyOf(
|
||||
PostgresProtocolHandler.handoverStartupParameters(
|
||||
Map.of("replication", "database"), Map.of("options", "-c work_mem=8MB")).keySet()));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
|
||||
+65
-1
@@ -11,7 +11,12 @@ import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.postgresql.PGConnection;
|
||||
import org.postgresql.replication.LogSequenceNumber;
|
||||
import org.postgresql.replication.PGReplicationStream;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
@@ -210,6 +215,54 @@ class RdsPostgresIamRoleIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamLogicalReplicationConnectionRequiresTheReplicationPrivilege() throws Exception {
|
||||
String id = uniqueId();
|
||||
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);
|
||||
Properties replication = token(port, "app_user");
|
||||
replication.setProperty("replication", "database");
|
||||
replication.setProperty("assumeMinServerVersion", "10");
|
||||
replication.setProperty("preferQueryMode", "simple");
|
||||
refused(port, replication, "42501");
|
||||
|
||||
asMaster(port, "GRANT rds_replication TO app_user");
|
||||
try (Connection connection = connect(port, replication);
|
||||
Statement statement = connection.createStatement()) {
|
||||
try (ResultSet rows = statement.executeQuery("IDENTIFY_SYSTEM")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals("appdb", rows.getString("dbname"));
|
||||
}
|
||||
physicalReplicationRefused(statement, "CREATE_REPLICATION_SLOT app_physical TEMPORARY PHYSICAL");
|
||||
physicalReplicationRefused(statement, "BASE_BACKUP");
|
||||
String startPoint;
|
||||
try (ResultSet rows = statement.executeQuery(
|
||||
"CREATE_REPLICATION_SLOT app_slot TEMPORARY LOGICAL test_decoding")) {
|
||||
assertTrue(rows.next());
|
||||
assertEquals("app_slot", rows.getString("slot_name"));
|
||||
startPoint = rows.getString("consistent_point");
|
||||
}
|
||||
|
||||
PGReplicationStream stream = connection.unwrap(PGConnection.class).getReplicationAPI()
|
||||
.replicationStream().logical().withSlotName("app_slot")
|
||||
.withStartPosition(LogSequenceNumber.valueOf(startPoint)).start();
|
||||
asMaster(port, "INSERT INTO events VALUES (42)");
|
||||
String change;
|
||||
do {
|
||||
ByteBuffer message = stream.read();
|
||||
change = StandardCharsets.UTF_8.decode(message).toString();
|
||||
} while (!change.contains("INSERT"));
|
||||
assertEquals("table public.events: INSERT: id[integer]:42", change);
|
||||
}
|
||||
assertUser(port, replication, "app_user");
|
||||
} finally {
|
||||
deleteInstance(id);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void roleLookupIgnoresClientEncodingAndCatalogShadows() throws Exception {
|
||||
String id = uniqueId();
|
||||
@@ -245,8 +298,19 @@ class RdsPostgresIamRoleIntegrationTest {
|
||||
}
|
||||
|
||||
private static void refused(int port, Properties properties) {
|
||||
refused(port, properties, "28P01");
|
||||
}
|
||||
|
||||
private static void refused(int port, Properties properties, String sqlState) {
|
||||
SQLException exception = assertThrows(SQLException.class, () -> connect(port, properties).close());
|
||||
assertEquals("28P01", exception.getSQLState());
|
||||
assertEquals(sqlState, exception.getSQLState());
|
||||
}
|
||||
|
||||
private static void physicalReplicationRefused(Statement statement, String command) {
|
||||
SQLException exception = assertThrows(SQLException.class, () -> statement.execute(command));
|
||||
assertEquals("42501", exception.getSQLState());
|
||||
assertTrue(exception.getMessage().startsWith("ERROR: permission denied to use physical replication"),
|
||||
exception.getMessage());
|
||||
}
|
||||
|
||||
private static void assertUser(int port, Properties properties, String user) throws SQLException {
|
||||
|
||||
Reference in new issue
Block a user