fix(rds): run IAM PostgreSQL sessions as the role named in the token (#3106)

* fix(rds): run IAM PostgreSQL sessions as the role named in the token

The proxy validated the token and then connected as master. It now hands
the session over with SET SESSION AUTHORIZATION, so the role's own
privileges apply and an unknown role is refused.

Closes #3087

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(rds): keep IAM PostgreSQL sessions from switching back to master

The backend connection is master underneath, so RESET SESSION AUTHORIZATION
regained superuser. The proxy now watches PostgreSQL's own
session_authorization report and terminates the session when it changes.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-09-05 21:24:39 -04:00
1 parent 5719e65c3c
commit c22ded931a
5 files changed
+811 -33

No files matched your search

@@ -7,6 +7,7 @@ import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLSocket;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
@@ -34,7 +35,9 @@ import java.util.concurrent.atomic.AtomicBoolean;
* <li>Validate (IAM SigV4 or plain password)
* <li>Connect to backend with MD5 or SCRAM-SHA-256 auth
* <li>Buffer backend messages until ReadyForQuery
* <li>Send AuthOK + buffered messages to client, then bridge
* <li>For IAM logins, hand the session over to the role named in the token
* <li>Send AuthOK + buffered messages to client, then bridge, guarding an IAM
* session against being handed back to the master role
* </ol>
*/
public class PostgresProtocolHandler {
@@ -45,7 +48,13 @@ public class PostgresProtocolHandler {
private static final int STARTUP_PROTOCOL_VERSION = 196608; // v3.0
private static final int MAX_HANDSHAKE_PACKET_LENGTH = 1_048_576;
public static Socket authenticate(Socket client, Socket backend,
/**
* An authenticated client connection ready to be bridged. {@code iamRole} is the role an IAM
* token named and the session was handed over to, or {@code null} for every other login.
*/
public record AuthenticatedSession(Socket client, String iamRole) {}
public static AuthenticatedSession authenticate(Socket client, Socket backend,
String masterUsername, String masterPassword, String dbName,
boolean iamEnabled, RdsSigV4Validator sigV4,
RdsProxyTlsCertificates tlsCertificates,
@@ -126,6 +135,27 @@ public class PostgresProtocolHandler {
// Buffer all backend messages until ReadyForQuery ('Z')
List<byte[]> bufferedMessages = readUntilReadyForQuery(backendIn);
String iamRole = null;
// 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)) {
List<byte[]> roleSwitch = assumeSessionRole(backendIn, backendOut, clientUsername);
if (endsWithErrorResponse(roleSwitch)) {
sendErrorResponse(clientOut, "FATAL", "28000",
errorMessage(roleSwitch.get(roleSwitch.size() - 1),
"role \"" + clientUsername + "\" does not exist"));
clientOut.flush();
closeQuietly(client);
closeQuietly(backend);
return null;
}
bufferedMessages = applyParameterStatusUpdates(bufferedMessages, roleSwitch);
iamRole = clientUsername;
}
// Phase 6: Send AuthenticationOK to client, forward buffered messages, then bridge
if (endsWithErrorResponse(bufferedMessages)) {
for (byte[] msg : bufferedMessages) {
@@ -143,7 +173,7 @@ public class PostgresProtocolHandler {
}
clientOut.flush();
return client;
return new AuthenticatedSession(client, iamRole);
}
// ── Startup ───────────────────────────────────────────────────────────────
@@ -534,7 +564,132 @@ public class PostgresProtocolHandler {
return messages;
}
public static void bridge(Socket client, Socket backend) {
// ── IAM session role ──────────────────────────────────────────────────────
/**
* Hands the backend session over to {@code role} so {@code current_user} and
* {@code session_user} both report the role named in the IAM token and the session carries
* only that role's privileges.
*
* @return the backend messages the statement produced, up to ReadyForQuery or ErrorResponse
*/
private static List<byte[]> assumeSessionRole(InputStream in, OutputStream out, String role)
throws IOException {
String sql = "SET SESSION AUTHORIZATION " + quoteIdentifier(role);
sendMessage(out, 'Q', sql.getBytes(StandardCharsets.UTF_8), new byte[]{0});
out.flush();
return readUntilReadyForQuery(in);
}
static String quoteIdentifier(String identifier) {
return "\"" + identifier.replace("\"", "\"\"") + "\"";
}
/**
* Folds the ParameterStatus messages a statement produced into the buffered startup messages,
* so the client's view of parameters such as {@code session_authorization} and
* {@code is_superuser} matches the session it is handed. Same-named entries are replaced;
* new ones are inserted ahead of BackendKeyData/ReadyForQuery.
*/
static List<byte[]> applyParameterStatusUpdates(List<byte[]> buffered, List<byte[]> updates) {
List<byte[]> merged = new ArrayList<>(buffered);
for (byte[] update : updates) {
String name = parameterStatusName(update);
if (name == null) {
continue;
}
int existing = indexOfParameterStatus(merged, name);
if (existing >= 0) {
merged.set(existing, update);
} else {
merged.add(startupTrailerIndex(merged), update);
}
}
return merged;
}
private static int indexOfParameterStatus(List<byte[]> messages, String name) {
for (int i = 0; i < messages.size(); i++) {
if (name.equals(parameterStatusName(messages.get(i)))) {
return i;
}
}
return -1;
}
/** Index of the first BackendKeyData/ReadyForQuery: where ParameterStatus messages end. */
private static int startupTrailerIndex(List<byte[]> messages) {
for (int i = 0; i < messages.size(); i++) {
char type = (char) messages.get(i)[0];
if (type == 'K' || type == 'Z') {
return i;
}
}
return messages.size();
}
/** Name carried by a ParameterStatus message, or {@code null} for any other message. */
private static String parameterStatusName(byte[] message) {
if (message.length < 6 || message[0] != 'S') {
return null;
}
String[] status = parameterStatus(message, 5);
return status == null ? null : status[0];
}
/**
* Splits the {@code name}/{@code value} pair a ParameterStatus carries, reading from
* {@code offset}, or {@code null} when the message is truncated.
*/
private static String[] parameterStatus(byte[] message, int offset) {
int nameEnd = offset;
while (nameEnd < message.length && message[nameEnd] != 0) {
nameEnd++;
}
if (nameEnd >= message.length) {
return null;
}
int valueEnd = nameEnd + 1;
while (valueEnd < message.length && message[valueEnd] != 0) {
valueEnd++;
}
return new String[] {
new String(message, offset, nameEnd - offset, StandardCharsets.UTF_8),
new String(message, nameEnd + 1, valueEnd - nameEnd - 1, StandardCharsets.UTF_8)
};
}
/** Human-readable 'M' field of an ErrorResponse, or {@code fallback} when it carries none. */
static String errorMessage(byte[] errorResponse, String fallback) {
int i = 5; // skip type byte and Int32 length
while (i < errorResponse.length && errorResponse[i] != 0) {
char fieldType = (char) errorResponse[i];
i++;
int start = i;
while (i < errorResponse.length && errorResponse[i] != 0) {
i++;
}
if (fieldType == 'M') {
return new String(errorResponse, start, i - start, StandardCharsets.UTF_8);
}
i++; // skip the field's null terminator
}
return fallback;
}
/**
* Relays the authenticated session until either side closes.
*
* <p>An IAM session gets its backend→client direction read message by message so the proxy
* sees PostgreSQL report the session's identity. The backend connection underneath is the
* master one, so a client that talks the session back to the master role, via {@code RESET
* SESSION AUTHORIZATION} and its variants, would otherwise regain superuser, which the
* token never granted. Watching the server's own {@code session_authorization} report catches
* that whatever SQL produced it; the session is then terminated, since a handover that already
* happened cannot be taken back.
*/
public static void bridge(AuthenticatedSession session, Socket backend) {
Socket client = session.client();
InputStream clientIn, backendIn;
OutputStream clientOut, backendOut;
try {
@@ -557,7 +712,7 @@ public class PostgresProtocolHandler {
Thread t1 = Thread.ofVirtual().name("rds-pg-c2b")
.start(() -> relay(clientIn, backendOut, closeBoth));
Thread t2 = Thread.ofVirtual().name("rds-pg-b2c")
.start(() -> relay(backendIn, clientOut, closeBoth));
.start(() -> relayToClient(backendIn, clientOut, session.iamRole(), closeBoth));
try {
t1.join();
t2.join();
@@ -569,6 +724,88 @@ public class PostgresProtocolHandler {
}
}
private static void relayToClient(InputStream from, OutputStream to, String iamRole,
Runnable onDone) {
if (iamRole == null) {
relay(from, to, onDone);
return;
}
BufferedOutputStream buffered = new BufferedOutputStream(to, 8192);
try {
relayGuardingSessionRole(from, buffered, iamRole);
} catch (IOException e) {
// Either side closing mid-relay is the normal way a session ends, so this stays at
// debug: it is one line per connection teardown, not per message.
LOG.debugv("RDS IAM session relay for role {0} ended: {1}", iamRole, e.getMessage());
} finally {
try {
buffered.flush();
} catch (IOException e) {
LOG.debugv("Client for RDS IAM role {0} gone before the last flush: {1}",
iamRole, e.getMessage());
}
onDone.run();
}
}
/**
* Copies framed backend messages, stopping the session if PostgreSQL ever reports a
* {@code session_authorization} other than {@code iamRole}.
*/
private static void relayGuardingSessionRole(InputStream from, OutputStream to, String iamRole)
throws IOException {
byte[] buf = new byte[8192];
while (true) {
int type = from.read();
if (type < 0) {
return;
}
byte[] header = new byte[4];
readFully(from, header);
int length = ((header[0] & 0xFF) << 24) | ((header[1] & 0xFF) << 16)
| ((header[2] & 0xFF) << 8) | (header[3] & 0xFF);
if (length < 4) {
return;
}
int remaining = length - 4;
if (type == 'S') {
// ParameterStatus is always small, so reading it whole to inspect costs nothing.
byte[] payload = new byte[remaining];
readFully(from, payload);
String[] status = parameterStatus(payload, 0);
if (status != null && "session_authorization".equals(status[0])
&& !iamRole.equals(status[1])) {
LOG.warnv("RDS IAM session for role {0} tried to switch to {1}; terminating",
iamRole, status[1]);
sendErrorResponse(to, "FATAL", "42501",
"permission denied to set session authorization");
to.flush();
return;
}
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;
}
}
// Batch while the backend keeps talking, flush as soon as it pauses.
if (from.available() == 0) {
to.flush();
}
}
}
private static void relay(InputStream from, OutputStream to, Runnable onDone) {
try {
byte[] buf = new byte[8192];
@@ -101,11 +101,12 @@ public class RdsAuthProxy {
switch (engine) {
case POSTGRES -> {
Socket activeClient = PostgresProtocolHandler.authenticate(
client, backend, masterUsername, masterPassword, dbName,
iamEnabled, sigV4, tlsCertificates, passwordValidator::validate);
if (activeClient != null) {
PostgresProtocolHandler.bridge(activeClient, backend);
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
client, backend, masterUsername, masterPassword, dbName,
iamEnabled, sigV4, tlsCertificates, passwordValidator::validate);
if (session != null) {
PostgresProtocolHandler.bridge(session, backend);
}
}
case MYSQL, MARIADB -> MySqlProtocolHandler.handleAuth(
@@ -138,13 +138,14 @@ public class RedshiftAuthProxy {
backend = new Socket(backendHost, backendPort);
backend.setTcpNoDelay(true);
// iamEnabled = false: the SigV4 branch inside authenticate is never taken.
Socket activeClient = PostgresProtocolHandler.authenticate(
client, backend, masterUsername, masterPassword, dbName,
false, sigV4, tlsCertificates, passwordValidator::validate);
if (activeClient != null) {
PostgresProtocolHandler.AuthenticatedSession session =
PostgresProtocolHandler.authenticate(
client, backend, masterUsername, masterPassword, dbName,
false, sigV4, tlsCertificates, passwordValidator::validate);
if (session != null) {
// Redshift-only DDL (DISTKEY/SORTKEY/ENCODE/...) is rewritten for the plain
// PostgreSQL backend on the way through; every other message is relayed verbatim.
new RedshiftInterceptingBridge(activeClient, backend).run();
new RedshiftInterceptingBridge(session.client(), backend).run();
}
} catch (Exception e) {
LOG.debugv("Redshift connection error for cluster {0}: {1}", clusterKey, e.getMessage());