fix(rds): load the token role's ALTER ROLE defaults into IAM sessions (#5344)

* fix(rds): load the token role's ALTER ROLE defaults into IAM sessions

* fix(rds): open IAM sessions with the role's defaults as startup options so RESET keeps them
This commit is contained in:
David Wooldridge authored and GitHub committed 2026-10-12 10:28:06 -04:00
1 parent 1230aec424
commit e61b66fb22
4 files changed
+729 -32

No files matched your search

+1 -1
View File
@@ -690,7 +690,7 @@ On PostgreSQL, the token names a database role (`DBUser`) and the session runs a
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. 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, 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`.
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
@@ -25,6 +25,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/**
@@ -205,29 +206,22 @@ 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 with only user and database, and their
// parameters are applied once the session belongs to the role (Phase 5c).
Map<String, String> clientParameters = forwardStartupParameters && !(isIam && !isMaster)
? startup.parameters() : Map.of();
sendStartupToBackend(backendOut, backendUser, effectiveDbName, clientParameters);
backendOut.flush();
boolean backendAuthenticated = false;
byte[] backendRejection = null;
try {
backendAuthenticated = authenticateWithBackend(backendIn, backendOut, backendUser, backendPass);
} catch (BackendRejectedException e) {
backendRejection = e.errorResponse();
// 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.
boolean iamHandover = isIam && !isMaster;
Map<String, String> backendParameters;
if (!forwardStartupParameters) {
backendParameters = Map.of();
} else if (iamHandover) {
backendParameters = Map.of("client_encoding", "UTF8");
} else {
backendParameters = startup.parameters();
}
if (!backendAuthenticated) {
// PostgreSQL's own refusal, such as a missing pg_hba.conf entry for a forwarded
// replication=true, says far more than the proxy's generic error.
if (backendRejection != null) {
clientOut.write(backendRejection);
} else {
sendErrorResponse(clientOut, "FATAL", "08006",
"Backend database authentication failed");
}
byte[] backendRejection = loginToBackend(backendIn, backendOut, backendUser, backendPass,
effectiveDbName, backendParameters);
if (backendRejection != null) {
clientOut.write(backendRejection);
clientOut.flush();
closeQuietly(client);
closeQuietly(backend);
@@ -238,13 +232,66 @@ public class PostgresProtocolHandler {
List<byte[]> bufferedMessages = readUntilReadyForQuery(backendIn);
String iamRole = null;
List<SessionSetting> roleDefaultsAfterHandover = List.of();
List<byte[]> notices = new ArrayList<>();
// Phase 5a: A login as the role would load the role's own ALTER ROLE ... SET defaults,
// which SET SESSION AUTHORIZATION does not. PostgreSQL makes them the values RESET
// returns to and applies them with the authority of whoever stored them, so a
// superuser-only default set by an administrator binds a role that could not set it
// itself. Only startup parameters get both properties, so when the role has defaults
// the proxy opens the backend session again with them as -c options. Each is tried
// first, so one PostgreSQL refuses is skipped with a WARNING, as at login, instead of
// failing the startup. "role" and client_encoding wait for the handover (Phase 5b).
if (iamHandover && forwardStartupParameters && !endsWithErrorResponse(bufferedMessages)) {
RoleDefaults defaults = readRoleDefaults(backendIn, backendOut, clientUsername);
if (defaults.failure() != null) {
sendErrorResponse(clientOut, "FATAL", errorField(defaults.failure(), 'C', "XX000"),
errorField(defaults.failure(), 'M', "could not load the role's defaults"));
clientOut.flush();
closeQuietly(client);
closeQuietly(backend);
return null;
}
notices.addAll(defaults.warnings());
roleDefaultsAfterHandover = defaults.afterHandover();
if (!defaults.atStartup().isEmpty()) {
sendMessage(backendOut, 'X');
backendOut.flush();
closeQuietly(backend);
try {
backend = backendConnector.connect();
} catch (IOException e) {
sendErrorResponse(clientOut, "FATAL", "08006", "could not connect to backend database");
clientOut.flush();
closeQuietly(client);
return null;
}
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);
if (backendRejection != null) {
clientOut.write(backendRejection);
clientOut.flush();
closeQuietly(client);
closeQuietly(backend);
return null;
}
bufferedMessages = readUntilReadyForQuery(backendIn);
}
}
// 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
// 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.
if (isIam && !isMaster && !endsWithErrorResponse(bufferedMessages)) {
if (iamHandover && !endsWithErrorResponse(bufferedMessages)) {
List<byte[]> roleSwitch = assumeSessionRole(backendIn, backendOut, clientUsername);
if (endsWithErrorResponse(roleSwitch)) {
sendErrorResponse(clientOut, "FATAL", "28000",
@@ -258,6 +305,26 @@ public class PostgresProtocolHandler {
bufferedMessages = applyParameterStatusUpdates(bufferedMessages, roleSwitch);
iamRole = clientUsername;
// A "role" default is a membership claim, checked against the role as at login.
SessionSetting roleEncoding = null;
for (SessionSetting setting : roleDefaultsAfterHandover) {
if ("client_encoding".equalsIgnoreCase(setting.name())) {
roleEncoding = setting;
continue;
}
DefaultOutcome outcome = applyDefault(backendIn, backendOut, setting, clientUsername);
if (outcome.failure() != null) {
sendErrorResponse(clientOut, "FATAL", errorField(outcome.failure(), 'C', "XX000"),
errorField(outcome.failure(), 'M', "could not apply the role's defaults"));
clientOut.flush();
closeQuietly(client);
closeQuietly(backend);
return null;
}
notices.addAll(outcome.warnings());
bufferedMessages = applyParameterStatusUpdates(bufferedMessages, outcome.statuses());
}
// Phase 5c: Apply the client's startup parameters now that the session belongs to
// the role, so PostgreSQL checks each one against the role's privileges, as it
// does when the role logs in directly. A parameter PostgreSQL refuses fails the
@@ -301,6 +368,26 @@ public class PostgresProtocolHandler {
bufferedMessages = applyParameterStatusUpdates(bufferedMessages, applied);
}
}
// The role's client_encoding goes last, once the proxy sends no more SQL, and only
// if the client did not choose an encoding itself.
if (roleEncoding != null && !clientChoseEncoding(startup.parameters())) {
DefaultOutcome outcome = applyDefault(backendIn, backendOut, roleEncoding, clientUsername);
if (outcome.failure() != null) {
sendErrorResponse(clientOut, "FATAL", errorField(outcome.failure(), 'C', "XX000"),
errorField(outcome.failure(), 'M', "could not apply the role's defaults"));
clientOut.flush();
closeQuietly(client);
closeQuietly(backend);
return null;
}
notices.addAll(outcome.warnings());
bufferedMessages = applyParameterStatusUpdates(bufferedMessages, outcome.statuses());
}
}
if (!notices.isEmpty() && !endsWithErrorResponse(bufferedMessages)) {
bufferedMessages = insertBeforeStartupTrailer(bufferedMessages, notices);
}
// Phase 6: Send AuthenticationOK to client, forward buffered messages, then bridge
@@ -476,6 +563,26 @@ public class PostgresProtocolHandler {
// ── Backend auth phase ────────────────────────────────────────────────────
/**
* Sends the backend StartupMessage and authenticates. Returns {@code null} once logged in, or
* the ErrorResponse to give the client: PostgreSQL's own refusal where it gave one.
*/
private static byte[] loginToBackend(InputStream in, OutputStream out, String user, String password,
String database, Map<String, String> parameters) throws IOException {
sendStartupToBackend(out, user, database, parameters);
out.flush();
try {
if (authenticateWithBackend(in, out, user, password)) {
return null;
}
} catch (BackendRejectedException e) {
// PostgreSQL's own refusal, such as a missing pg_hba.conf entry for a forwarded
// replication=true, says far more than the proxy's generic error.
return e.errorResponse();
}
return responseMessage('E', "FATAL", "08006", "Backend database authentication failed");
}
private static boolean authenticateWithBackend(InputStream in, OutputStream out,
String username, String password) throws IOException {
int type = readAuthenticationType(in);
@@ -788,6 +895,209 @@ public class PostgresProtocolHandler {
/** One run-time parameter a client asked for at startup, by name. */
record SessionSetting(String name, String value) {}
/**
* The {@code ALTER ROLE ... SET} defaults a login as {@code role} to the current database
* loads, one row per setting: the role's own, then the ones for this database, so that, applied
* in order, a database-specific value wins as it does at login.
*/
static String roleDefaultsQuery(String role) {
return "SELECT pg_catalog.split_part(c.cfg, '=', 1), "
+ "pg_catalog.substr(c.cfg, pg_catalog.strpos(c.cfg, '=') + 1) "
+ "FROM pg_catalog.pg_db_role_setting s "
+ "JOIN pg_catalog.pg_roles r ON r.oid = s.setrole "
+ "CROSS JOIN LATERAL pg_catalog.unnest(s.setconfig) WITH ORDINALITY AS c(cfg, n) "
+ "WHERE r.rolname = " + quoteLiteral(role) + " AND s.setdatabase IN (0, "
+ "(SELECT d.oid FROM pg_catalog.pg_database d WHERE d.datname = pg_catalog.current_database())) "
+ "ORDER BY s.setdatabase = 0 DESC, c.n";
}
/** The two-column {@code name}/{@code value} rows among {@code messages}, in order. */
static List<SessionSetting> settingsFromDataRows(List<byte[]> messages) {
List<SessionSetting> settings = new ArrayList<>();
for (byte[] message : messages) {
if (message[0] != 'D') {
continue;
}
int offset = 5; // skip type byte and Int32 length
int columns = ((message[offset] & 0xFF) << 8) | (message[offset + 1] & 0xFF);
offset += 2;
String[] values = new String[columns];
for (int column = 0; column < columns; column++) {
int length = ((message[offset] & 0xFF) << 24) | ((message[offset + 1] & 0xFF) << 16)
| ((message[offset + 2] & 0xFF) << 8) | (message[offset + 3] & 0xFF);
offset += 4;
if (length >= 0) {
values[column] = new String(message, offset, length, StandardCharsets.UTF_8);
offset += length;
}
}
if (columns == 2 && values[0] != null && values[1] != null) {
settings.add(new SessionSetting(values[0], values[1]));
}
}
return settings;
}
/**
* The SQLSTATEs PostgreSQL raises when it refuses to set a parameter: unknown, an invalid
* value, or not permitted. At login these are WARNINGs and the default is skipped; anything
* else is a real failure.
*/
private static final Set<String> REFUSED_SETTING_STATES = Set.of("42704", "22023", "22P02", "42501");
/** A parameter that can be set only at connection start. */
private static final String STARTUP_ONLY_STATE = "55P02";
/**
* The token role's defaults, sorted: those for the backend StartupMessage, those that must
* wait for the handover, the WARNINGs for any PostgreSQL refused, or the ErrorResponse that
* stopped the lookup.
*/
record RoleDefaults(List<SessionSetting> atStartup, List<SessionSetting> afterHandover,
List<byte[]> warnings, byte[] failure) {}
/** What applying one default produced: ParameterStatus messages, WARNINGs, or a failure. */
record DefaultOutcome(List<byte[]> statuses, List<byte[]> warnings, byte[] failure) {}
/**
* Reads the token role's defaults on the master session and tries each one there, so that
* only those PostgreSQL accepts go into the backend StartupMessage. The session is replaced
* whenever any was accepted, so trying them leaves nothing behind that is used.
*/
private static RoleDefaults readRoleDefaults(InputStream in, OutputStream out, String role) throws IOException {
List<byte[]> lookup = runQuery(in, out, roleDefaultsQuery(role));
if (endsWithErrorResponse(lookup)) {
return new RoleDefaults(List.of(), List.of(), List.of(), lookup.get(lookup.size() - 1));
}
List<SessionSetting> atStartup = new ArrayList<>();
List<SessionSetting> afterHandover = new ArrayList<>();
List<byte[]> warnings = new ArrayList<>();
for (SessionSetting setting : settingsFromDataRows(lookup)) {
if ("session_authorization".equalsIgnoreCase(setting.name())) {
continue;
}
if ("role".equalsIgnoreCase(setting.name()) || "client_encoding".equalsIgnoreCase(setting.name())) {
afterHandover.add(setting);
continue;
}
byte[] refusal = firstErrorResponse(runQuery(in, out, setConfigStatement(List.of(setting))));
if (refusal == null || STARTUP_ONLY_STATE.equals(errorField(refusal, 'C', ""))) {
atStartup.add(setting);
} else if (REFUSED_SETTING_STATES.contains(errorField(refusal, 'C', ""))) {
warnings.add(skippedDefaultWarning(refusal, role, setting));
} else {
return new RoleDefaults(List.of(), List.of(), List.of(), refusal);
}
}
return new RoleDefaults(atStartup, afterHandover, warnings, null);
}
/** Applies one default to the session as it stands, skipping it with a WARNING if refused. */
private static DefaultOutcome applyDefault(InputStream in, OutputStream out, SessionSetting setting,
String role) throws IOException {
List<byte[]> result = runQuery(in, out, setConfigStatement(List.of(setting)));
byte[] refusal = firstErrorResponse(result);
if (refusal == null) {
return new DefaultOutcome(result, List.of(), null);
}
if (REFUSED_SETTING_STATES.contains(errorField(refusal, 'C', ""))) {
return new DefaultOutcome(List.of(), List.of(skippedDefaultWarning(refusal, role, setting)), null);
}
return new DefaultOutcome(List.of(), List.of(), refusal);
}
/** The NoticeResponse a login sends for a default PostgreSQL refused, logged here too. */
private static byte[] skippedDefaultWarning(byte[] refusal, String role, SessionSetting setting) {
String message = errorField(refusal, 'M', "invalid value for parameter \"" + setting.name() + "\"");
LOG.warnv("Skipping role {0}''s default {1}: {2}", role, setting.name(), message);
return responseMessage('N', "WARNING", errorField(refusal, 'C', "22023"), message);
}
private static byte[] firstErrorResponse(List<byte[]> messages) {
for (byte[] message : messages) {
if (message[0] == 'E') {
return message;
}
}
return null;
}
/**
* An {@code options} value carrying {@code settings} as {@code -c name=value} switches,
* escaped for {@code pg_split_opts}: a backslash before every backslash and whitespace.
*/
static String startupOptions(List<SessionSetting> settings) {
StringBuilder options = new StringBuilder();
for (SessionSetting setting : settings) {
if (options.length() > 0) {
options.append(' ');
}
options.append("-c ").append(escapeOption(setting.name())).append('=')
.append(escapeOption(setting.value()));
}
return options.toString();
}
private static String escapeOption(String text) {
StringBuilder escaped = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\\' || isAsciiSpace(c)) {
escaped.append('\\');
}
escaped.append(c);
}
return escaped.toString();
}
/** Whether the client's StartupMessage chose a client_encoding, directly or in options. */
static boolean clientChoseEncoding(Map<String, String> startupParameters) {
for (String name : startupParameters.keySet()) {
if ("client_encoding".equalsIgnoreCase(name)) {
return true;
}
}
String options = startupParameters.get("options");
if (options == null) {
return false;
}
try {
for (SessionSetting setting : parseOptions(options)) {
if ("client_encoding".equalsIgnoreCase(setting.name())) {
return true;
}
}
} catch (StartupParameterException ignored) {
// Phase 5c refuses the same options with PostgreSQL's error before this is asked.
}
return false;
}
/** Inserts {@code messages} where ParameterStatus messages end, ahead of BackendKeyData. */
static List<byte[]> insertBeforeStartupTrailer(List<byte[]> buffered, List<byte[]> messages) {
List<byte[]> merged = new ArrayList<>(buffered);
merged.addAll(startupTrailerIndex(merged), messages);
return merged;
}
/** Runs {@code sql} as a simple query and returns every message up to ReadyForQuery. */
private static List<byte[]> runQuery(InputStream in, OutputStream out, String sql) throws IOException {
sendMessage(out, 'Q', sql.getBytes(StandardCharsets.UTF_8), new byte[]{0});
out.flush();
List<byte[]> messages = new ArrayList<>();
while (true) {
int type = in.read();
if (type < 0) {
throw new EOFException("Connection closed before ReadyForQuery");
}
byte[] message = readMessage(in, type);
if (type == 'Z') {
return messages;
}
messages.add(message);
}
}
/**
* A startup parameter PostgreSQL would refuse while parsing the StartupMessage, before any
* setting is applied.
@@ -1256,18 +1566,29 @@ public class PostgresProtocolHandler {
private static void sendErrorResponse(OutputStream out, String severity, String sqlState,
String message) throws IOException {
out.write(responseMessage('E', severity, sqlState, message));
}
/** An ErrorResponse ('E') or NoticeResponse ('N') carrying severity, SQLSTATE and message. */
static byte[] responseMessage(char type, String severity, String sqlState, String message) {
byte[] sevBytes = severity.getBytes(StandardCharsets.UTF_8);
byte[] stateBytes = sqlState.getBytes(StandardCharsets.UTF_8);
byte[] msgBytes = message.getBytes(StandardCharsets.UTF_8);
// Fields: S=severity, C=sqlstate, M=message, then final null byte
ByteArrayOutputStream fields = new ByteArrayOutputStream();
fields.write('S'); fields.write(sevBytes); fields.write(0);
fields.write('C'); fields.write(stateBytes); fields.write(0);
fields.write('M'); fields.write(msgBytes); fields.write(0);
fields.write('S'); fields.writeBytes(sevBytes); fields.write(0);
fields.write('C'); fields.writeBytes(stateBytes); fields.write(0);
fields.write('M'); fields.writeBytes(msgBytes); fields.write(0);
fields.write(0); // final null
sendMessage(out, 'E', fields.toByteArray());
ByteArrayOutputStream framed = new ByteArrayOutputStream();
try {
sendMessage(framed, type, fields.toByteArray());
} catch (IOException e) {
throw new IllegalStateException("writing to memory cannot fail", e);
}
return framed.toByteArray();
}
// ── Wire helpers ──────────────────────────────────────────────────────────
@@ -32,6 +32,7 @@ import java.security.KeyStore;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
@@ -712,8 +713,9 @@ class PostgresProtocolHandlerTest {
assertEquals(false, backendThread.isAlive(), "backendThread did not terminate");
}
assertEquals(List.of("user", "database"), List.copyOf(backendStartup.get().keySet()),
assertEquals(List.of("user", "database", "client_encoding"), List.copyOf(backendStartup.get().keySet()),
"client startup parameters are not applied to the master session");
assertEquals("UTF8", backendStartup.get().get("client_encoding"));
assertEquals("SELECT pg_catalog.set_config(E'search_path', E'app', false), "
+ "pg_catalog.set_config(E'statement_timeout', E'5s', false), "
+ "pg_catalog.set_config(E'application_name', E'svc', false)",
@@ -880,6 +882,203 @@ class PostgresProtocolHandlerTest {
}
}
@Test
void iamSessionReopensTheBackendWithTheRoleDefaultsAsStartupOptions() throws Exception {
List<String> tried = new ArrayList<>();
AtomicReference<Map<String, String>> reopenedStartup = new AtomicReference<>();
AtomicReference<String> handover = new AtomicReference<>();
List<String> afterHandover = new ArrayList<>();
try (ServerSocket lookupServer = new ServerSocket(0);
ServerSocket backendServer = new ServerSocket(0);
ServerSocket clientServer = new ServerSocket(0)) {
Thread lookupThread = Thread.ofVirtual().start(() -> {
try {
mockBackendRoleDefaultsLookup(lookupServer, List.of(
new String[] {"temp_file_limit", "1GB"},
new String[] {"no_such_parameter", "on"},
new String[] {"role", "reader"},
new String[] {"session_authorization", "dbadmin"},
new String[] {"client_encoding", "LATIN1"},
new String[] {"search_path", "app, public"}), tried);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
Thread backendThread = Thread.ofVirtual().start(() -> {
try {
mockBackendRoleSwitch(backendServer, reopenedStartup, handover, "approle", true, (in, out) -> {
for (int i = 0; i < 3; i++) {
afterHandover.add(readSimpleQuery(in));
writeCommandComplete(out, "SELECT 1");
writeReadyForQuery(out);
}
});
} catch (IOException e) {
throw new RuntimeException(e);
}
});
Socket proxyClient;
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
ourClient.setSoTimeout(5_000);
proxyClient = clientServer.accept();
List<Socket> backends = new ArrayList<>(List.of(
new Socket("localhost", lookupServer.getLocalPort()),
new Socket("localhost", backendServer.getLocalPort())));
Thread authThread = startIamAuth(proxyClient, () -> backends.remove(0));
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("application_name", "svc");
writeStartup(clientOut, clientStartup);
readCleartextPasswordChallenge(clientIn);
writePassword(clientOut, rdsToken("approle"));
readAuthenticationOk(clientIn);
List<Map<Character, String>> notices = new ArrayList<>();
Map<String, String> params = readParametersAndNoticesUntilReadyForQuery(clientIn, notices);
assertEquals("approle", params.get("session_authorization"));
assertEquals(1, notices.size(), notices.toString());
assertEquals("WARNING", notices.get(0).get('S'));
assertEquals("42704", notices.get(0).get('C'));
assertEquals("unrecognized configuration parameter \"no_such_parameter\"", notices.get(0).get('M'));
ourClient.close();
proxyClient.close();
authThread.join(5_000);
lookupThread.join(5_000);
backendThread.join(5_000);
assertEquals(false, authThread.isAlive(), "authThread did not terminate");
assertEquals(false, lookupThread.isAlive(), "lookupThread did not terminate");
assertEquals(false, backendThread.isAlive(), "backendThread did not terminate");
}
}
assertEquals(List.of(
"SELECT pg_catalog.set_config(E'temp_file_limit', E'1GB', false)",
"SELECT pg_catalog.set_config(E'no_such_parameter', E'on', false)",
"SELECT pg_catalog.set_config(E'search_path', E'app, public', false)"),
tried, "each default is tried on the lookup session; role, client_encoding and session_authorization are not");
assertEquals("dbadmin", reopenedStartup.get().get("user"));
assertEquals("-c temp_file_limit=1GB -c search_path=app,\\ public", reopenedStartup.get().get("options"),
"the accepted defaults become startup options, the refused one is left out");
assertEquals("UTF8", reopenedStartup.get().get("client_encoding"));
assertEquals("SET SESSION AUTHORIZATION \"approle\"", handover.get());
assertEquals(List.of(
"SELECT pg_catalog.set_config(E'role', E'reader', false)",
"SELECT pg_catalog.set_config(E'application_name', E'svc', false)",
"SELECT pg_catalog.set_config(E'client_encoding', E'LATIN1', false)"),
afterHandover, "role as the role, then the client's settings, then the role's encoding once no proxy SQL follows");
}
@Test
void iamSessionFailsWhenARoleDefaultHitsAnErrorOtherThanARefusal() throws Exception {
try (ServerSocket lookupServer = new ServerSocket(0);
ServerSocket clientServer = new ServerSocket(0)) {
Thread lookupThread = Thread.ofVirtual().start(() -> {
try {
mockBackendRoleDefaultsLookup(lookupServer,
List.<String[]>of(new String[] {"broken_default", "on"}), new ArrayList<>());
} catch (IOException e) {
throw new RuntimeException(e);
}
});
Socket proxyClient;
try (Socket ourClient = new Socket("localhost", clientServer.getLocalPort())) {
ourClient.setSoTimeout(5_000);
proxyClient = clientServer.accept();
Socket backend = new Socket("localhost", lookupServer.getLocalPort());
Thread authThread = startIamAuth(proxyClient, backend);
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());
writeStartup(clientOut, "approle", "postgres");
readCleartextPasswordChallenge(clientIn);
writePassword(clientOut, rdsToken("approle"));
Map<Character, String> error = readErrorResponse(clientIn);
assertEquals("FATAL", error.get('S'));
assertEquals("XX000", error.get('C'));
assertEquals("could not read block 0", error.get('M'));
assertEquals(-1, clientIn.read(), "the login must fail");
authThread.join(5_000);
lookupThread.join(5_000);
assertEquals(false, authThread.isAlive(), "authThread did not terminate");
assertEquals(false, lookupThread.isAlive(), "lookupThread did not terminate");
}
}
}
@Test
void startupOptionsEscapeWhatPgSplitOptsSplitsOn() throws Exception {
String options = PostgresProtocolHandler.startupOptions(List.of(
new PostgresProtocolHandler.SessionSetting("search_path", "app, public"),
new PostgresProtocolHandler.SessionSetting("application_name", "a\\b\tc")));
assertEquals("-c search_path=app,\\ public -c application_name=a\\\\b\\\tc", options);
assertEquals(List.of(
new PostgresProtocolHandler.SessionSetting("search_path", "app, public"),
new PostgresProtocolHandler.SessionSetting("application_name", "a\\b\tc")),
PostgresProtocolHandler.parseOptions(options), "PostgreSQL reads back what was escaped");
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"client_encoding|UTF8|true",
"CLIENT_ENCODING|UTF8|true",
"options|-c client_encoding=LATIN1|true",
"options|--client-encoding=LATIN1|true",
"options|-c search_path=app|false",
"application_name|svc|false"
})
void clientChoseEncodingSeesEveryWayAClientCanAskForOne(String name, String value, boolean expected) {
assertEquals(expected, PostgresProtocolHandler.clientChoseEncoding(Map.of("user", "approle", name, value)));
}
@Test
void roleDefaultsQueryReadsTheRoleWideDefaultsBeforeTheDatabaseSpecificOnes() {
String sql = PostgresProtocolHandler.roleDefaultsQuery("o'brien");
assertEquals(true, sql.contains("r.rolname = E'o''brien'"), sql);
assertEquals(true, sql.endsWith("ORDER BY s.setdatabase = 0 DESC, c.n"), sql);
}
@Test
void settingsFromDataRowsReadsNameValueRowsAndSkipsEverythingElse() throws Exception {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buffer);
writeDataRow(out, "search_path", "app, public");
writeCommandComplete(out, "SELECT 1");
writeDataRow(out, "work_mem", "");
DataInputStream in = new DataInputStream(new ByteArrayInputStream(buffer.toByteArray()));
List<byte[]> messages = new ArrayList<>();
for (int i = 0; i < 3; i++) {
int type = in.readByte();
int length = in.readInt();
ByteArrayOutputStream message = new ByteArrayOutputStream();
DataOutputStream messageOut = new DataOutputStream(message);
messageOut.writeByte(type);
messageOut.writeInt(length);
messageOut.write(in.readNBytes(length - 4));
messages.add(message.toByteArray());
}
assertEquals(List.of(
new PostgresProtocolHandler.SessionSetting("search_path", "app, public"),
new PostgresProtocolHandler.SessionSetting("work_mem", "")),
PostgresProtocolHandler.settingsFromDataRows(messages));
}
@Test
void sessionSettingsApplyOptionsFirstThenTheOtherParametersInOrder() throws Exception {
Map<String, String> startup = new LinkedHashMap<>();
@@ -1329,6 +1528,24 @@ class PostgresProtocolHandlerTest {
return startIamAuth(proxyClient, backend, true, true);
}
private Thread startIamAuth(Socket proxyClient, PostgresProtocolHandler.BackendConnector connector) {
return Thread.ofVirtual().start(() -> {
try {
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
proxyClient, connector,
"dbadmin", "adminpass", "postgres",
true, testSigV4Validator(), testBinding(), testTlsCertificates(),
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000, true);
if (session != null) {
PostgresProtocolHandler.bridge(session);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
private Thread startIamAuth(Socket proxyClient, Socket backend,
boolean iamEnabled, boolean forwardStartupParameters) {
return Thread.ofVirtual().start(() -> {
@@ -1444,9 +1661,14 @@ class PostgresProtocolHandlerTest {
writeBackendKeyData(out);
writeReadyForQuery(out);
assertEquals('Q', in.readByte());
byte[] query = in.readNBytes(in.readInt() - 4);
backendQuery.set(new String(query, 0, query.length - 1, StandardCharsets.UTF_8));
String query = readSimpleQuery(in);
if (query.contains("pg_db_role_setting")) {
// A role with no defaults: the proxy carries on with this session.
writeCommandComplete(out, "SELECT 0");
writeReadyForQuery(out);
query = readSimpleQuery(in);
}
backendQuery.set(query);
if (!roleExists) {
writeErrorResponse(out, "ERROR", "42704", "role \"" + role + "\" does not exist");
@@ -1465,6 +1687,101 @@ class PostgresProtocolHandlerTest {
}
}
/**
* The master session the proxy reads the role's defaults on: answers the lookup with
* {@code roleDefaults}, then each default the proxy tries, recording them in {@code tried},
* until the proxy terminates the session. {@code no_such_parameter} is refused as PostgreSQL
* refuses an unknown parameter; {@code broken_default} fails with an internal error.
*/
private static void mockBackendRoleDefaultsLookup(ServerSocket server, List<String[]> roleDefaults,
List<String> tried) throws IOException {
try (Socket socket = server.accept()) {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
int length = in.readInt();
assertEquals(STARTUP_PROTOCOL_VERSION, in.readInt());
in.readNBytes(length - 8);
out.writeByte('R');
out.writeInt(8);
out.writeInt(3);
out.flush();
assertEquals('p', in.readByte());
in.readNBytes(in.readInt() - 4);
out.writeByte('R');
out.writeInt(8);
out.writeInt(0);
writeParameterStatus(out, "session_authorization", "dbadmin");
writeBackendKeyData(out);
writeReadyForQuery(out);
assertEquals(true, readSimpleQuery(in).contains("pg_db_role_setting"));
for (String[] setting : roleDefaults) {
writeDataRow(out, setting[0], setting[1]);
}
writeCommandComplete(out, "SELECT " + roleDefaults.size());
writeReadyForQuery(out);
while (true) {
int type = in.read();
if (type < 0 || type == 'X') {
return;
}
assertEquals('Q', type);
byte[] body = in.readNBytes(in.readInt() - 4);
String query = new String(body, 0, body.length - 1, StandardCharsets.UTF_8);
tried.add(query);
if (query.contains("no_such_parameter")) {
writeErrorResponse(out, "ERROR", "42704",
"unrecognized configuration parameter \"no_such_parameter\"");
} else if (query.contains("broken_default")) {
writeErrorResponse(out, "ERROR", "XX000", "could not read block 0");
} else {
writeCommandComplete(out, "SELECT 1");
}
writeReadyForQuery(out);
}
}
}
private static Map<String, String> readParametersAndNoticesUntilReadyForQuery(
DataInputStream in, List<Map<Character, String>> notices) throws IOException {
Map<String, String> params = new HashMap<>();
while (true) {
int type = in.readByte();
byte[] payload = in.readNBytes(in.readInt() - 4);
if (type == 'Z') {
return params;
}
if (type == 'N') {
Map<Character, String> fields = new HashMap<>();
int i = 0;
while (i < payload.length && payload[i] != 0) {
char field = (char) payload[i++];
int start = i;
while (payload[i] != 0) {
i++;
}
fields.put(field, new String(payload, start, i - start, StandardCharsets.UTF_8));
i++;
}
notices.add(fields);
}
if (type == 'S') {
int nameEnd = 0;
while (payload[nameEnd] != 0) {
nameEnd++;
}
int valueEnd = nameEnd + 1;
while (payload[valueEnd] != 0) {
valueEnd++;
}
params.put(new String(payload, 0, nameEnd, StandardCharsets.UTF_8),
new String(payload, nameEnd + 1, valueEnd - nameEnd - 1, StandardCharsets.UTF_8));
}
}
}
/** Drives the backend side of a bridged session, once the client is past authentication. */
@FunctionalInterface
private interface BackendScript {
@@ -1534,6 +1851,21 @@ class PostgresProtocolHandlerTest {
out.flush();
}
private static void writeDataRow(DataOutputStream out, String... values) throws IOException {
ByteArrayOutputStream row = new ByteArrayOutputStream();
DataOutputStream rowOut = new DataOutputStream(row);
rowOut.writeShort(values.length);
for (String value : values) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
rowOut.writeInt(bytes.length);
rowOut.write(bytes);
}
out.writeByte('D');
out.writeInt(4 + row.size());
row.writeTo(out);
out.flush();
}
private static void writeCommandComplete(DataOutputStream out, String tag) throws IOException {
byte[] tagBytes = tag.getBytes(StandardCharsets.UTF_8);
out.writeByte('C');
@@ -134,6 +134,50 @@ class RdsPostgresStartupParametersIntegrationTest {
}
}
@Test
void anIamSessionLoadsTheTokenRolesOwnDefaultsBeneathTheClientsParameters() throws Exception {
String dbId = "startup-params-iam-defaults-" + Long.toString(System.nanoTime(), 36);
int port = createIamInstance(dbId);
try {
asMaster(port,
"CREATE ROLE reader NOLOGIN",
"CREATE ROLE app_user LOGIN",
"GRANT reader TO app_user",
"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'");
Properties iam = iamLogin(port, "app_user");
iam.setProperty("options", "-c statement_timeout=9s");
try (Connection connection = DriverManager.getConnection(jdbcUrl(port), iam)) {
assertThat(show(connection, "work_mem"), equalTo("48MB"));
assertThat(show(connection, "statement_timeout"), equalTo("9s"));
assertThat(show(connection, "log_min_duration_statement"), equalTo("1s"));
assertThat(show(connection, "role"), equalTo("reader"));
assertThat(show(connection, "session_authorization"), equalTo("app_user"));
assertThat(show(connection, "floci.note"), equalTo("café"));
// As at login, the role's defaults are what RESET returns to, so the role cannot
// shed a superuser-only one its administrator set.
try (Statement statement = connection.createStatement()) {
statement.execute("RESET ALL");
}
assertThat(show(connection, "work_mem"), equalTo("48MB"));
assertThat(show(connection, "log_min_duration_statement"), equalTo("1s"));
assertThat(show(connection, "statement_timeout"), equalTo("7s"));
}
} finally {
deleteInstance(dbId);
}
}
/** Creates a PostgreSQL instance with IAM database authentication and returns its proxy port. */
private static int createIamInstance(String dbId) {
return rds("CreateDBInstance")