fix(rds): accept IAM auth for PostgreSQL logical replication connections (#8671)

This commit is contained in:
rajp33 authored and GitHub committed 2026-11-17 17:00:09 -04:00
1 parent 6a5a464ca8
commit d7c2616c72
8 files changed
+527 -37

No files matched your search

@@ -178,6 +178,37 @@ class RdsJdbcCompatTest {
@Test
@Order(5)
@DisplayName("Logical replication connection with IAM auth token")
void logicalReplicationConnectionWithIamAuthToken() throws Exception {
assumeInstanceCreated();
try (Connection admin = openPostgresConnection(USERNAME, PASSWORD);
Statement statement = admin.createStatement()) {
statement.execute("GRANT rds_replication TO " + IAM_USERNAME);
}
String token = rds.utilities().generateAuthenticationToken(GenerateAuthenticationTokenRequest.builder()
.hostname(TestFixtures.proxyHost())
.port(proxyPort)
.username(IAM_USERNAME)
.region(REGION)
.credentialsProvider(CREDENTIALS)
.build());
Properties properties = postgresProperties(IAM_USERNAME, token);
properties.setProperty("replication", "database");
properties.setProperty("assumeMinServerVersion", "10");
properties.setProperty("preferQueryMode", "simple");
try (Connection connection = DriverManager.getConnection(postgresUrl(proxyPort), properties);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("IDENTIFY_SYSTEM")) {
assertThat(resultSet.next()).isTrue();
assertThat(resultSet.getString("dbname")).isEqualTo(DATABASE);
}
}
@Test
@Order(6)
@DisplayName("IAM auth rejected on instance created without IAM")
void iamAuthRejectedWhenDisabledAtCreate() throws Exception {
assumeInstanceCreated();
@@ -226,7 +257,7 @@ class RdsJdbcCompatTest {
}
@Test
@Order(6)
@Order(7)
@DisplayName("Toggle IAM via modify on a running instance")
void toggleIamViaModifyOnRunningInstance() throws Exception {
assumeInstanceCreated();
@@ -313,7 +344,7 @@ class RdsJdbcCompatTest {
}
@Test
@Order(7)
@Order(8)
@DisplayName("Modify password keeps proxy reachable and delete releases port")
void modifyKeepsProxyReachableAndDeleteReleasesPort() throws Exception {
assumeInstanceCreated();
+3 -1
View File
@@ -1228,7 +1228,9 @@ 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.
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, three things differ from RDS: `options` may carry only `-c name=value` and `--name=value` switches, a parameter that can only be set at connection start is refused with `cannot be set after connection start`, and `replication` connections are refused. 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 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`.
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`.
On MySQL, `AWSAuthenticationPlugin` is proprietary to RDS and ships in no public MySQL build, so
`CREATE USER ... IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'` would fail against the container
@@ -935,6 +935,9 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'rds_iam') THEN
CREATE ROLE rds_iam;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'rds_replication') THEN
CREATE ROLE rds_replication;
END IF;
END
$$;
""";
@@ -1554,7 +1557,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
psql -v ON_ERROR_STOP=1 -U "$USER" -d postgres <<'SQL'
""" + postgresIamRoleInitSql() + "SQL\n";
}
private static void addTarEntry(
@@ -148,6 +148,8 @@ public class PostgresProtocolHandler {
* StartupMessage parameters ({@code options}, {@code application_name} and any run-time
* parameter) apply as they would on the server itself: they open the backend session, or,
* for an IAM login handed over to the token's role, are set once the role owns the session.
* {@code replication} opens the backend session in both cases, since it can only be chosen
* at connection start.
*/
public static AuthenticatedSession authenticate(Socket client, BackendConnector backendConnector,
String masterUsername, String masterPassword, String dbName,
@@ -345,14 +347,15 @@ public class PostgresProtocolHandler {
// 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=<master>" would outlive the handover and RESET ROLE
// would regain the master. Those logins open without them, and their 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.
// would regain the master. 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.
Map<String, String> backendParameters;
if (!forwardStartupParameters) {
backendParameters = Map.of();
} else if (iamHandover) {
backendParameters = Map.of("client_encoding", "UTF8");
backendParameters = handoverStartupParameters(startup.parameters(), Map.of());
} else {
backendParameters = startup.parameters();
}
@@ -434,11 +437,9 @@ public class PostgresProtocolHandler {
backend.setSoTimeout(handshakeTimeoutMillis);
backendIn = backend.getInputStream();
backendOut = backend.getOutputStream();
Map<String, String> withDefaults = new LinkedHashMap<>();
withDefaults.put("options", startupOptions(defaults.atStartup()));
withDefaults.put("client_encoding", "UTF8");
backendRejection = loginToBackend(backendIn, backendOut, backendUser, backendPass,
effectiveDbName, withDefaults);
effectiveDbName, handoverStartupParameters(startup.parameters(),
Map.of("options", startupOptions(defaults.atStartup()))));
if (backendRejection != null) {
clientOut.write(backendRejection);
clientOut.flush();
@@ -568,6 +569,17 @@ public class PostgresProtocolHandler {
: "role identity changed during handover");
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.
if (requestsReplication(startup.parameters()) && !hasReplicationPrivilege(backendIn, backendOut)) {
LOG.infov("RDS IAM replication connection refused for role {0}: replication privilege required",
SigV4RequestValidator.sanitizeForLog(clientUsername));
sendErrorResponse(clientOut, "FATAL", "42501", "permission denied to start WAL sender");
clientOut.flush();
closeQuietly(client);
closeQuietly(backend);
return null;
}
}
if (handoverOutcome != null) {
@@ -1350,7 +1362,8 @@ public class PostgresProtocolHandler {
/**
* The run-time parameters a StartupMessage asks for, in the order PostgreSQL applies them:
* the {@code -c} switches in {@code options} first, then every other parameter as sent.
* {@code user}, {@code database} and {@code _pq_.} protocol extensions are not parameters.
* {@code user}, {@code database}, {@code replication} and {@code _pq_.} protocol extensions
* are not run-time parameters.
*/
static List<SessionSetting> sessionSettings(Map<String, String> startupParameters)
throws StartupParameterException {
@@ -1362,20 +1375,7 @@ public class PostgresProtocolHandler {
for (Map.Entry<String, String> parameter : startupParameters.entrySet()) {
String name = parameter.getKey();
if ("user".equals(name) || "database".equals(name) || "options".equals(name)
|| name.startsWith("_pq_.")) {
continue;
}
if ("replication".equals(name)) {
String value = parameter.getValue();
Boolean replication = "database".equals(value) ? Boolean.TRUE : parseBool(value);
if (replication == null) {
throw new StartupParameterException("22023",
"invalid value for parameter \"replication\": \"" + value + "\"");
}
if (replication) {
throw new StartupParameterException("0A000",
"replication connections are not supported for IAM sessions through the proxy");
}
|| "replication".equals(name) || name.startsWith("_pq_.")) {
continue;
}
settings.add(new SessionSetting(name, parameter.getValue()));
@@ -1383,6 +1383,39 @@ public class PostgresProtocolHandler {
return settings;
}
/**
* The StartupMessage parameters of a backend session opened as the master 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.
*/
static Map<String, String> handoverStartupParameters(Map<String, String> clientParameters,
Map<String, String> base) {
Map<String, String> parameters = new LinkedHashMap<>(base);
parameters.put("client_encoding", "UTF8");
String replication = clientParameters.get("replication");
if (replication != null) {
parameters.put("replication", replication);
}
return parameters;
}
static boolean requestsReplication(Map<String, String> startupParameters) {
String value = startupParameters.get("replication");
return value != null && ("database".equals(value) || Boolean.TRUE.equals(parseBool(value)));
}
static String replicationPrivilegeQuery() {
return "SELECT r.oid::pg_catalog.text, r.rolsuper OR r.rolreplication OR EXISTS ("
+ "SELECT 1 FROM pg_catalog.pg_roles g WHERE g.rolname OPERATOR(pg_catalog.=) 'rds_replication' "
+ "AND pg_catalog.pg_has_role(r.oid, g.oid, 'MEMBER')) "
+ "FROM pg_catalog.pg_roles r WHERE r.rolname OPERATOR(pg_catalog.=) SESSION_USER";
}
private static boolean hasReplicationPrivilege(InputStream in, OutputStream out) throws IOException {
List<SessionSetting> rows = settingsFromDataRows(runQuery(in, out, replicationPrivilegeQuery()));
return rows.size() == 1 && "t".equals(rows.getFirst().value());
}
/**
* A boolean as PostgreSQL's {@code parse_bool} reads it: any case-insensitive prefix of
* {@code true}, {@code false}, {@code yes} or {@code no}, at least two letters of {@code on}
@@ -1663,7 +1696,10 @@ public class PostgresProtocolHandler {
closeQuietly(backend);
}
};
Thread t1 = RelayThreads.start("rds-pg-c2b", () -> relay(clientIn, backendOut, closeBoth));
boolean logicalReplication = session.iamRole() != null && requestsReplication(session.startupParameters());
Thread t1 = RelayThreads.start("rds-pg-c2b", logicalReplication
? () -> relayRefusingPhysicalReplication(clientIn, backendOut, session.iamRole(), closeBoth)
: () -> relay(clientIn, backendOut, closeBoth));
Thread t2 = RelayThreads.start("rds-pg-b2c",
() -> relayToClient(backendIn, clientOut, session.iamRole(), closeBoth));
try {
@@ -1772,6 +1808,134 @@ public class PostgresProtocolHandler {
}
}
static final String PHYSICAL_REPLICATION_REFUSAL = "DO $$BEGIN RAISE EXCEPTION "
+ "'permission denied to use physical replication' USING ERRCODE = 'insufficient_privilege'; END$$";
private static final Set<String> REPLICATION_COMMANDS = Set.of("IDENTIFY_SYSTEM", "BASE_BACKUP",
"START_REPLICATION", "CREATE_REPLICATION_SLOT", "DROP_REPLICATION_SLOT", "ALTER_REPLICATION_SLOT",
"READ_REPLICATION_SLOT", "TIMELINE_HISTORY", "UPLOAD_MANIFEST", "SHOW");
/** A WAL sender refuses the extended query protocol, so only a Query can carry a replication command. */
private static void relayRefusingPhysicalReplication(InputStream clientIn, OutputStream backendOut,
String iamRole, Runnable onDone) {
RelayInputStream from = new RelayInputStream(clientIn);
BufferedOutputStream to = new BufferedOutputStream(backendOut, 8192);
byte[] buf = new byte[8192];
try {
while (true) {
int type = from.read();
if (type < 0) {
return;
}
byte[] header = new byte[4];
PostgresWire.readFully(from, header);
int length = PostgresWire.int32(header, 0);
if (length < 4) {
return;
}
int remaining = length - 4;
if (type == 'Q') {
byte[] payload = new byte[remaining];
PostgresWire.readFully(from, payload);
if (!permittedOnLogicalReplication(PostgresWire.cString(payload, 0).value())) {
LOG.infov("RDS IAM replication session for role {0} sent a physical replication command; refused",
SigV4RequestValidator.sanitizeForLog(iamRole));
payload = PostgresWire.cStringBytes(PHYSICAL_REPLICATION_REFUSAL);
header = PostgresWire.int32(payload.length + 4);
}
to.write(type);
to.write(header);
to.write(payload);
} else {
to.write(type);
to.write(header);
while (remaining > 0) {
int n = from.read(buf, 0, Math.min(buf.length, remaining));
if (n < 0) {
return;
}
to.write(buf, 0, n);
remaining -= n;
}
}
if (from.isDrained()) {
to.flush();
}
}
} catch (IOException e) {
LOG.debugv("RDS IAM replication relay for role {0} ended: {1}", iamRole, e.getMessage());
} finally {
try {
to.flush();
} catch (IOException e) {
LOG.debugv("Backend for RDS IAM role {0} gone before the last flush: {1}", iamRole, e.getMessage());
}
onDone.run();
}
}
/**
* Keywords are matched ignoring ASCII case, which PostgreSQL does not, so a lowercase command
* PostgreSQL would run as SQL and refuse as a syntax error is refused here instead.
*/
static boolean permittedOnLogicalReplication(String query) {
List<String> words = leadingReplicationWords(query, 4);
if (words.isEmpty() || !REPLICATION_COMMANDS.contains(words.getFirst())) {
return true;
}
return switch (words.getFirst()) {
case "IDENTIFY_SYSTEM", "SHOW", "DROP_REPLICATION_SLOT", "ALTER_REPLICATION_SLOT" -> true;
case "CREATE_REPLICATION_SLOT" -> words.size() > 2 && (words.get(2).equals("LOGICAL")
|| (words.get(2).equals("TEMPORARY") && words.size() > 3 && words.get(3).equals("LOGICAL")));
case "START_REPLICATION" -> words.size() > 3 && words.get(1).equals("SLOT")
&& words.get(3).equals("LOGICAL");
default -> false;
};
}
/** A double-quoted identifier keeps its quotes, so it never reads as a keyword. */
private static List<String> leadingReplicationWords(String query, int limit) {
List<String> words = new ArrayList<>();
int i = 0;
int n = query.length();
while (words.size() < limit) {
while (i < n && " \t\n\r\f\u000b".indexOf(query.charAt(i)) >= 0) {
i++;
}
if (i == n) {
break;
}
StringBuilder word = new StringBuilder();
if (query.charAt(i) == '"') {
word.append(query.charAt(i++));
while (i < n) {
char c = query.charAt(i++);
word.append(c);
if (c == '"' && (i == n || query.charAt(i) != '"')) {
break;
}
if (c == '"') {
word.append(query.charAt(i++));
}
}
} else if (isIdentifierStart(query.charAt(i))) {
while (i < n && (isIdentifierStart(query.charAt(i))
|| (query.charAt(i) >= '0' && query.charAt(i) <= '9') || query.charAt(i) == '$')) {
char c = query.charAt(i++);
word.append(c >= 'a' && c <= 'z' ? (char) (c - 'a' + 'A') : c);
}
} else {
break;
}
words.add(word.toString());
}
return words;
}
private static boolean isIdentifierStart(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || c >= 0x80;
}
// ── Error response ────────────────────────────────────────────────────────
private static void sendErrorResponse(OutputStream out, String severity, String sqlState,
@@ -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
@@ -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 {