Light, fluffy, and always free - The AWS Local Emulator alternative
fix(rds): run IAM PostgreSQL sessions as the role named in the token (#3106)
Matheus Oliveirac22ded931a92
diff --git a/docs/services/rds.md b/docs/services/rds.mdindex 1419685dc9..8c9bbe61a6 100644--- a/docs/services/rds.md+++ b/docs/services/rds.md@@ -306,6 +306,10 @@ The RDS auth proxy validates the master username and password at the proxy layerIAM database authentication is also supported. Set `--enable-iam-database-authentication` at instance creation time and use `aws rds generate-db-auth-token` to obtain a token.+On PostgreSQL, the token names a database role (`DBUser`) and the session runs as that role: `current_user` and `session_user` both report it, objects it creates are owned by it, and a token naming a role the database does not have is refused with `FATAL: role "..." does not exist`. Create the role first with `CREATE ROLE <name> WITH LOGIN` as the master user, and grant it whatever the application 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.+## TLS / SSLThe RDS auth proxy terminates TLS itself (the backend container stays plaintext) using adiff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.javaindex 8f2430d35c..824d482298 100644--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandler.java@@ -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.0private 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 bridgeif (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];diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.javaindex b1bacb360a..96bf83430a 100644--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java@@ -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(diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.javaindex ba84abb089..7819377f1e 100644--- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftAuthProxy.java@@ -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());diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.javaindex dda789fca8..0a806a4ef2 100644--- a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/PostgresProtocolHandlerTest.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.rds.proxy;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.services.acm.CertificateGenerator;import io.github.hectorvent.floci.testutil.IamServiceTestHelper;+import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;import org.junit.jupiter.params.ParameterizedTest;@@ -19,6 +20,7 @@ import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.security.KeyStore;+import java.time.Instant;import java.util.HashMap;import java.util.Map;import java.util.concurrent.atomic.AtomicReference;@@ -210,13 +212,14 @@ class PostgresProtocolHandlerTest {Thread authThread = Thread.ofVirtual().start(() -> {try {- Socket activeClient = PostgresProtocolHandler.authenticate(+ PostgresProtocolHandler.AuthenticatedSession session =+ PostgresProtocolHandler.authenticate(proxyClient, backend,"dbadmin", "adminpass", "postgres",false, testSigV4Validator(), testTlsCertificates(),(user, pass) -> true);- if (activeClient != null) {- PostgresProtocolHandler.bridge(activeClient, backend);+ if (session != null) {+ PostgresProtocolHandler.bridge(session, backend);}} catch (IOException e) {throw new RuntimeException(e);@@ -267,13 +270,14 @@ class PostgresProtocolHandlerTest {Thread authThread = Thread.ofVirtual().start(() -> {try {- Socket activeClient = PostgresProtocolHandler.authenticate(+ PostgresProtocolHandler.AuthenticatedSession session =+ PostgresProtocolHandler.authenticate(proxyClient, backend,"dbadmin", "adminpass", "postgres",false, testSigV4Validator(), testTlsCertificates(),(user, pass) -> true);- if (activeClient != null) {- PostgresProtocolHandler.bridge(activeClient, backend);+ if (session != null) {+ PostgresProtocolHandler.bridge(session, backend);}} catch (IOException e) {throw new RuntimeException(e);@@ -324,13 +328,14 @@ class PostgresProtocolHandlerTest {Thread authThread = Thread.ofVirtual().start(() -> {try {- Socket activeClient = PostgresProtocolHandler.authenticate(+ PostgresProtocolHandler.AuthenticatedSession session =+ PostgresProtocolHandler.authenticate(proxyClient, backend,"dbadmin", "adminpass", "postgres",false, testSigV4Validator(), testTlsCertificates(),(user, pass) -> true);- if (activeClient != null) {- PostgresProtocolHandler.bridge(activeClient, backend);+ if (session != null) {+ PostgresProtocolHandler.bridge(session, backend);}} catch (IOException e) {throw new RuntimeException(e);@@ -390,13 +395,14 @@ class PostgresProtocolHandlerTest {Thread authThread = Thread.ofVirtual().start(() -> {try {- Socket activeClient = PostgresProtocolHandler.authenticate(+ PostgresProtocolHandler.AuthenticatedSession session =+ PostgresProtocolHandler.authenticate(proxyClient, backend,"dbadmin", "adminpass", "postgres",false, testSigV4Validator(), tlsCertificates,(user, pass) -> true);- if (activeClient != null) {- PostgresProtocolHandler.bridge(activeClient, backend);+ if (session != null) {+ PostgresProtocolHandler.bridge(session, backend);}} catch (IOException e) {throw new RuntimeException(e);@@ -443,13 +449,14 @@ class PostgresProtocolHandlerTest {Thread authThread = Thread.ofVirtual().start(() -> {try {- Socket activeClient = PostgresProtocolHandler.authenticate(+ PostgresProtocolHandler.AuthenticatedSession session =+ PostgresProtocolHandler.authenticate(proxyClient, backend,"dbadmin", "adminpass", "postgres",false, testSigV4Validator(), tlsCertificates,(user, pass) -> true);- if (activeClient != null) {- PostgresProtocolHandler.bridge(activeClient, backend);+ if (session != null) {+ PostgresProtocolHandler.bridge(session, backend);}} catch (IOException ignored) {// Client aborts the handshake below — the handler observing that is expected.@@ -492,13 +499,14 @@ class PostgresProtocolHandlerTest {Thread authThread = Thread.ofVirtual().start(() -> {try {- Socket activeClient = PostgresProtocolHandler.authenticate(+ PostgresProtocolHandler.AuthenticatedSession session =+ PostgresProtocolHandler.authenticate(proxyClient, backend,"dbadmin", "adminpass", "postgres",false, testSigV4Validator(), testTlsCertificates(),(user, pass) -> true);- if (activeClient != null) {- PostgresProtocolHandler.bridge(activeClient, backend);+ if (session != null) {+ PostgresProtocolHandler.bridge(session, backend);}} catch (IOException e) {throw new RuntimeException(e);@@ -525,6 +533,533 @@ class PostgresProtocolHandlerTest {}}+ @Test+ void iamSessionRunsAsTheRoleNamedInTheToken() throws Exception {+ AtomicReference<String> backendUser = new AtomicReference<>();+ AtomicReference<String> backendQuery = new AtomicReference<>();++ try (ServerSocket backendServer = new ServerSocket(0);+ ServerSocket clientServer = new ServerSocket(0)) {++ int backendPort = backendServer.getLocalPort();+ Thread backendThread = Thread.ofVirtual().start(() -> {+ try {+ mockBackendRoleSwitch(backendServer, backendUser, backendQuery, "approle", true);+ } 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", backendPort);++ 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"));+ readAuthenticationOk(clientIn);++ Map<String, String> params = readParametersUntilReadyForQuery(clientIn);+ assertEquals("approle", params.get("session_authorization"));+ assertEquals("off", params.get("is_superuser"));++ 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("dbadmin", backendUser.get(), "backend connection is still opened as master");+ assertEquals("SET SESSION AUTHORIZATION \"approle\"", backendQuery.get());+ }+ }++ @Test+ void iamSessionIsRejectedWhenTheTokenRoleDoesNotExist() throws Exception {+ AtomicReference<String> backendUser = new AtomicReference<>();+ AtomicReference<String> backendQuery = new AtomicReference<>();++ try (ServerSocket backendServer = new ServerSocket(0);+ ServerSocket clientServer = new ServerSocket(0)) {++ int backendPort = backendServer.getLocalPort();+ Thread backendThread = Thread.ofVirtual().start(() -> {+ try {+ mockBackendRoleSwitch(backendServer, backendUser, backendQuery, "nosuchrole", false);+ } 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", backendPort);++ Thread authThread = startIamAuth(proxyClient, backend);++ DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());+ DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());++ writeStartup(clientOut, "nosuchrole", "postgres");+ readCleartextPasswordChallenge(clientIn);+ writePassword(clientOut, rdsToken("nosuchrole"));++ Map<Character, String> error = readErrorResponse(clientIn);+ assertEquals("FATAL", error.get('S'));+ assertEquals("28000", error.get('C'));+ assertEquals("role \"nosuchrole\" does not exist", error.get('M'));++ 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("SET SESSION AUTHORIZATION \"nosuchrole\"", backendQuery.get());+ }+ }++ @Test+ void iamSessionForTheMasterUserKeepsTheMasterSession() throws Exception {+ AtomicReference<String> backendDatabase = new AtomicReference<>();++ try (ServerSocket backendServer = new ServerSocket(0);+ ServerSocket clientServer = new ServerSocket(0)) {++ int backendPort = backendServer.getLocalPort();+ Thread backendThread = Thread.ofVirtual().start(() -> {+ try {+ mockBackendStartup(backendServer, backendDatabase, false);+ } 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", backendPort);++ Thread authThread = startIamAuth(proxyClient, backend);++ DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());+ DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());++ writeStartup(clientOut, "dbadmin", "postgres");+ readCleartextPasswordChallenge(clientIn);+ writePassword(clientOut, rdsToken("dbadmin"));+ // The mock backend answers no query, so reaching ReadyForQuery proves no+ // SET SESSION AUTHORIZATION was issued for the master user.+ readAuthenticationOk(clientIn);+ readReadyForQuery(clientIn);++ 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");+ }+ }+ }++ @Test+ void iamSessionIsTerminatedWhenPostgresReportsAnotherSessionRole() throws Exception {+ AtomicReference<String> backendQuery = new AtomicReference<>();++ try (ServerSocket backendServer = new ServerSocket(0);+ ServerSocket clientServer = new ServerSocket(0)) {++ int backendPort = backendServer.getLocalPort();+ Thread backendThread = Thread.ofVirtual().start(() -> {+ try {+ mockBackendRoleSwitch(backendServer, new AtomicReference<>(), backendQuery,+ "approle", true, (in, out) -> {+ readSimpleQuery(in);+ // What PostgreSQL reports after RESET SESSION AUTHORIZATION and+ // friends hand the session back to the connection's master role.+ writeParameterStatus(out, "session_authorization", "masteruser");+ writeParameterStatus(out, "is_superuser", "on");+ writeCommandComplete(out, "RESET");+ 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();+ Socket backend = new Socket("localhost", backendPort);++ 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"));+ readAuthenticationOk(clientIn);+ readParametersUntilReadyForQuery(clientIn);++ writeSimpleQuery(clientOut, "RESET SESSION AUTHORIZATION");++ Map<Character, String> error = readErrorResponse(clientIn);+ assertEquals("FATAL", error.get('S'));+ assertEquals("42501", error.get('C'));+ assertEquals("permission denied to set session authorization", error.get('M'));+ assertEquals(-1, clientIn.read(), "session must be closed, not handed back as master");++ authThread.join(5_000);+ backendThread.join(5_000);+ assertEquals(false, authThread.isAlive(), "authThread did not terminate");+ }+ }+ }++ @Test+ void iamSessionKeepsRelayingWhenTheReportedRoleIsUnchanged() throws Exception {+ byte[] wideRow = new byte[40_000];+ java.util.Arrays.fill(wideRow, (byte) 'x');++ 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) -> {+ readSimpleQuery(in);+ writeParameterStatus(out, "session_authorization", "approle");+ writeMessage(out, 'D', wideRow);+ 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();+ Socket backend = new Socket("localhost", backendPort);++ 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"));+ readAuthenticationOk(clientIn);+ readParametersUntilReadyForQuery(clientIn);++ writeSimpleQuery(clientOut, "SET SESSION AUTHORIZATION approle");++ assertEquals('S', clientIn.readByte());+ clientIn.readNBytes(clientIn.readInt() - 4);+ assertEquals('D', clientIn.readByte());+ // A message larger than the relay buffer must arrive whole.+ assertEquals(wideRow.length, clientIn.readInt() - 4);+ assertEquals(wideRow.length, clientIn.readNBytes(wideRow.length).length);+ assertEquals('C', clientIn.readByte());+ clientIn.readNBytes(clientIn.readInt() - 4);+ readReadyForQuery(clientIn);++ ourClient.close();+ proxyClient.close();+ authThread.join(5_000);+ backendThread.join(5_000);+ }+ }+ }++ @Test+ void nonIamSessionRelaysSessionAuthorizationChanges() throws Exception {+ try (ServerSocket backendServer = new ServerSocket(0);+ ServerSocket clientServer = new ServerSocket(0)) {++ int backendPort = backendServer.getLocalPort();+ Thread backendThread = Thread.ofVirtual().start(() -> {+ try {+ mockBackendMasterSession(backendServer, (in, out) -> {+ readSimpleQuery(in);+ writeParameterStatus(out, "session_authorization", "approle");+ writeCommandComplete(out, "SET");+ 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();+ Socket backend = new Socket("localhost", backendPort);++ Thread authThread = startIamAuth(proxyClient, backend);++ DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());+ DataInputStream clientIn = new DataInputStream(ourClient.getInputStream());++ writeStartup(clientOut, "dbadmin", "postgres");+ readCleartextPasswordChallenge(clientIn);+ writePassword(clientOut, "adminpass");+ readAuthenticationOk(clientIn);+ readReadyForQuery(clientIn);++ // The master session is the backend's own identity, so switching roles is its+ // business. The guard applies only to IAM sessions.+ writeSimpleQuery(clientOut, "SET SESSION AUTHORIZATION approle");+ Map<String, String> params = readParametersUntilReadyForQuery(clientIn);+ assertEquals("approle", params.get("session_authorization"));++ ourClient.close();+ proxyClient.close();+ authThread.join(5_000);+ backendThread.join(5_000);+ }+ }+ }++ @Test+ void quotesRoleNamesContainingDoubleQuotes() {+ assertEquals("\"app\"\"role\"", PostgresProtocolHandler.quoteIdentifier("app\"role"));+ }++ private Thread startIamAuth(Socket proxyClient, Socket backend) {+ return Thread.ofVirtual().start(() -> {+ try {+ PostgresProtocolHandler.AuthenticatedSession session =+ PostgresProtocolHandler.authenticate(+ proxyClient, backend,+ "dbadmin", "adminpass", "postgres",+ true, testSigV4Validator(), testTlsCertificates(),+ (user, pass) -> true);+ if (session != null) {+ PostgresProtocolHandler.bridge(session, backend);+ }+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ });+ }++ private static String rdsToken(String dbUser) throws Exception {+ return SigV4TokenTestHelper.createRdsToken("localhost", 7001, dbUser,+ "AKIATEST", "secret", Instant.now(), 900);+ }++ /**+ * Mock backend that completes startup as master and then answers one simple query: either+ * reporting the handover to {@code role}, or replying with the ErrorResponse PostgreSQL sends+ * for a role the database does not have.+ */+ private static void mockBackendRoleSwitch(ServerSocket server, AtomicReference<String> backendUser,+ AtomicReference<String> backendQuery,+ String role, boolean roleExists) throws IOException {+ mockBackendRoleSwitch(server, backendUser, backendQuery, role, roleExists, null);+ }++ private static void mockBackendRoleSwitch(ServerSocket server, AtomicReference<String> backendUser,+ AtomicReference<String> backendQuery,+ String role, boolean roleExists,+ BackendScript afterHandover) 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());+ byte[] payload = in.readNBytes(length - 8);+ backendUser.set(parseStartupParams(payload).get("user"));++ 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");+ writeParameterStatus(out, "is_superuser", "on");+ 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));++ if (!roleExists) {+ writeErrorResponse(out, "ERROR", "42704", "role \"" + role + "\" does not exist");+ writeReadyForQuery(out);+ return;+ }++ writeParameterStatus(out, "session_authorization", role);+ writeParameterStatus(out, "is_superuser", "off");+ writeCommandComplete(out, "SET");+ writeReadyForQuery(out);++ if (afterHandover != null) {+ afterHandover.run(in, out);+ }+ }+ }++ /** Drives the backend side of a bridged session, once the client is past authentication. */+ @FunctionalInterface+ private interface BackendScript {+ void run(DataInputStream in, DataOutputStream out) throws IOException;+ }++ /** Backend that completes a plain master startup and then runs {@code script}. */+ private static void mockBackendMasterSession(ServerSocket server, BackendScript script)+ 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);+ writeReadyForQuery(out);++ script.run(in, out);+ }+ }++ private static String readSimpleQuery(DataInputStream in) throws IOException {+ assertEquals('Q', in.readByte());+ byte[] query = in.readNBytes(in.readInt() - 4);+ return new String(query, 0, query.length - 1, StandardCharsets.UTF_8);+ }++ private static void writeMessage(DataOutputStream out, char type, byte[] payload)+ throws IOException {+ out.writeByte(type);+ out.writeInt(4 + payload.length);+ out.write(payload);+ out.flush();+ }++ private static void writeParameterStatus(DataOutputStream out, String name, String value)+ throws IOException {+ byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);+ byte[] valueBytes = value.getBytes(StandardCharsets.UTF_8);+ out.writeByte('S');+ out.writeInt(4 + nameBytes.length + 1 + valueBytes.length + 1);+ out.write(nameBytes);+ out.writeByte(0);+ out.write(valueBytes);+ out.writeByte(0);+ out.flush();+ }++ private static void writeBackendKeyData(DataOutputStream out) throws IOException {+ out.writeByte('K');+ out.writeInt(12);+ out.writeInt(4242);+ out.writeInt(1234);+ out.flush();+ }++ private static void writeCommandComplete(DataOutputStream out, String tag) throws IOException {+ byte[] tagBytes = tag.getBytes(StandardCharsets.UTF_8);+ out.writeByte('C');+ out.writeInt(4 + tagBytes.length + 1);+ out.write(tagBytes);+ out.writeByte(0);+ out.flush();+ }++ private static void writeReadyForQuery(DataOutputStream out) throws IOException {+ out.writeByte('Z');+ out.writeInt(5);+ out.writeByte('I');+ out.flush();+ }++ /** Collects ParameterStatus values the client is handed, stopping at ReadyForQuery. */+ private static Map<String, String> readParametersUntilReadyForQuery(DataInputStream in)+ 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 == '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));+ }+ }+ }++ private static Map<Character, String> readErrorResponse(DataInputStream in) throws IOException {+ assertEquals('E', in.readByte());+ byte[] payload = in.readNBytes(in.readInt() - 4);+ Map<Character, String> fields = new HashMap<>();+ int i = 0;+ while (i < payload.length && payload[i] != 0) {+ char fieldType = (char) payload[i];+ i++;+ int start = i;+ while (payload[i] != 0) {+ i++;+ }+ fields.put(fieldType, new String(payload, start, i - start, StandardCharsets.UTF_8));+ i++;+ }+ return fields;+ }+private static RdsSigV4Validator testSigV4Validator() {return new RdsSigV4Validator(IamServiceTestHelper.iamServiceWithAccessKey("AKIATEST", "secret"));}