fix(rds): forward a PostgreSQL CancelRequest to the backend (#6127)

A client cancels a running query by opening a second connection and
sending a CancelRequest: the backend's process id and secret key from
the BackendKeyData it received at login. The RDS proxy only knew
SSLRequest and StartupMessage, so it logged "Unexpected PostgreSQL
startup protocol version: 80877102" and closed the connection. The
cancel never reached PostgreSQL and the query kept running.

The client already holds the backend's own key, because the proxy
relays BackendKeyData unchanged. So the proxy now passes the 16 bytes
to the backend on a connection of its own and closes, as the server
does. A cancel of any other length is dropped with its own warning.
Redshift clusters share this handler, so they forward cancels too.
A DB proxy endpoint drops a cancel, because RDS Proxy does not support
one.

The RDS integration tests now share their Docker check and their
CreateDBInstance and DeleteDBInstance calls in RdsRequests. The Docker
check uses DockerAvailability, so only a missing daemon skips a test.

Limits: a cancel still takes one of the proxy's connection permits, so
a proxy at its connection limit refuses it, where PostgreSQL itself
would not. And on an auto-paused Aurora backend, a cancel resumes it,
as any other connection does.

Co-authored-by: Robin Baeckman <27041454+RobinBaeckman@users.noreply.github.com>
This commit is contained in:
Robin BaeckmanandRobin Baeckman authored and GitHub committed 2026-10-23 06:46:59 -04:00
1 parent 686d0b5f02
commit b806f76f1b
8 files changed
+343 -84

No files matched your search

@@ -127,7 +127,10 @@ public class PostgresProtocolHandler {
handshakeTimeoutMillis, forwardStartupParameters, true);
}
/** Standard DB Proxy IAM does not enroll the backend role in database-native IAM. */
/**
* {@code databaseIamAuthentication} is false on a standard DB Proxy endpoint, which neither
* enrolls the backend role in database-native IAM nor forwards a client's CancelRequest.
*/
public static AuthenticatedSession authenticate(Socket client, BackendConnector backendConnector,
String masterUsername, String masterPassword, String dbName,
boolean iamEnabled, RdsSigV4Validator sigV4,
@@ -140,7 +143,8 @@ public class PostgresProtocolHandler {
client.setSoTimeout(handshakeTimeoutMillis);
// Phase 1: Read client startup message (possibly preceded by SSL request)
StartupMessage startup = readStartupMessage(client, tlsCertificates, handshakeTimeoutMillis);
StartupMessage startup = readStartupMessage(client, backendConnector, databaseIamAuthentication,
tlsCertificates, handshakeTimeoutMillis);
if (startup == null) {
closeQuietly(client);
return null;
@@ -471,7 +475,8 @@ public class PostgresProtocolHandler {
// ── Startup ───────────────────────────────────────────────────────────────
private static StartupMessage readStartupMessage(Socket socket, RdsProxyTlsCertificates tlsCertificates,
private static StartupMessage readStartupMessage(Socket socket, BackendConnector backendConnector,
boolean forwardCancel, RdsProxyTlsCertificates tlsCertificates,
int handshakeTimeoutMillis) throws IOException {
Socket currentSocket = socket;
while (true) {
@@ -489,6 +494,19 @@ public class PostgresProtocolHandler {
continue;
}
if (startup.code() == PostgresWire.CANCEL_REQUEST) {
if (!forwardCancel) {
// RDS Proxy does not support a CancelRequest from a client, so it drops one.
LOG.debugv("Dropping a PostgreSQL CancelRequest sent to a DB proxy endpoint");
} else if (startup.body().length == 8) {
forwardCancelRequest(startup.body(), backendConnector);
} else {
LOG.warnv("Dropping a PostgreSQL CancelRequest of length {0}; it must be 16",
startup.body().length + 8);
}
return null;
}
if (startup.code() != PostgresWire.PROTOCOL_3) {
LOG.warnv("Unexpected PostgreSQL startup protocol version: {0}", startup.code());
return null;
@@ -502,6 +520,22 @@ public class PostgresProtocolHandler {
}
}
/**
* Relays a CancelRequest to the backend on a connection of its own, as PostgreSQL expects.
* The client holds the backend's own process id and key from its BackendKeyData, so the
* request goes through unchanged. Nothing is answered: the server never replies to one.
*/
private static void forwardCancelRequest(byte[] key, BackendConnector backendConnector)
throws IOException {
try (Socket backend = backendConnector.connect()) {
OutputStream out = backend.getOutputStream();
PostgresWire.writeInt32(out, 16);
PostgresWire.writeInt32(out, PostgresWire.CANCEL_REQUEST);
out.write(key);
out.flush();
}
}
static Socket acceptSsl(Socket socket, RdsProxyTlsCertificates tlsCertificates) throws IOException {
try {
SSLSocket sslSocket = (SSLSocket) tlsCertificates.sslContext().getSocketFactory()
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.rds.proxy;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -20,6 +21,8 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PostgresHandshakeFramingTest {
@@ -64,6 +67,81 @@ class PostgresHandshakeFramingTest {
}
}
@Test
void cancelRequestIsForwardedToTheBackendUnchanged() throws Exception {
byte[] cancel = cancelRequest(16, 4242, 0x5eed);
RecordingOutputStream clientOutput = new RecordingOutputStream();
RecordingOutputStream backendOutput = new RecordingOutputStream();
Socket client = new MemorySocket(cancel, clientOutput);
Socket backend = new MemorySocket(new byte[0], backendOutput);
AtomicInteger backendConnections = new AtomicInteger();
try (client; backend) {
PostgresProtocolHandler.AuthenticatedSession session = authenticate(client, () -> {
backendConnections.incrementAndGet();
return backend;
});
assertNull(session);
assertEquals(1, backendConnections.get());
assertArrayEquals(cancel, backendOutput.toByteArray());
assertEquals(0, clientOutput.size());
assertTrue(backend.isClosed());
}
}
@Test
void cancelRequestToADbProxyEndpointReachesNoBackend() throws Exception {
Socket client = new MemorySocket(cancelRequest(16, 4242, 0x5eed), new RecordingOutputStream());
AtomicInteger backendConnections = new AtomicInteger();
try (client) {
assertNull(PostgresProtocolHandler.authenticate(client, () -> {
backendConnections.incrementAndGet();
return new MemorySocket(new byte[0], new RecordingOutputStream());
}, "master", "password", "appdb", false, null, null, null,
(user, password) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000, true, false));
assertEquals(0, backendConnections.get());
}
}
@Test
void cancelRequestOfTheWrongLengthReachesNoBackend() throws Exception {
Socket client = new MemorySocket(cancelRequest(20, 4242, 0x5eed), new RecordingOutputStream());
AtomicInteger backendConnections = new AtomicInteger();
try (client) {
assertNull(authenticate(client, () -> {
backendConnections.incrementAndGet();
return new MemorySocket(new byte[0], new RecordingOutputStream());
}));
assertEquals(0, backendConnections.get());
}
}
@Test
void truncatedCancelRequestReachesNoBackend() throws Exception {
Socket client = new MemorySocket(Arrays.copyOf(cancelRequest(16, 4242, 0x5eed), 12),
new RecordingOutputStream());
AtomicInteger backendConnections = new AtomicInteger();
try (client) {
assertThrows(IOException.class, () -> authenticate(client, () -> {
backendConnections.incrementAndGet();
return new MemorySocket(new byte[0], new RecordingOutputStream());
}));
assertEquals(0, backendConnections.get());
}
}
private static PostgresProtocolHandler.AuthenticatedSession authenticate(
Socket client, PostgresProtocolHandler.BackendConnector backend) throws IOException {
return PostgresProtocolHandler.authenticate(client, backend, "master", "password", "appdb",
false, null, null, null, (user, password) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT,
5000);
}
private static byte[] cancelRequest(int length, int processId, int secretKey) {
return ByteBuffer.allocate(length).putInt(length).putInt(80877102)
.putInt(processId).putInt(secretKey).array();
}
private static byte[] startupAndPassword() throws IOException {
ByteArrayOutputStream input = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(input);
@@ -26,6 +26,7 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
@@ -527,6 +528,56 @@ class PostgresProtocolHandlerTest {
}
}
@Test
void cancelRequestInsideTlsIsForwardedToTheBackend() throws Exception {
try (ServerSocket backendServer = new ServerSocket(0);
ServerSocket clientServer = new ServerSocket(0);
Socket ourClient = new Socket("localhost", clientServer.getLocalPort());
Socket proxyClient = clientServer.accept()) {
RdsProxyTlsCertificates tlsCertificates = testTlsCertificates();
tlsCertificates.ensureHost("localhost");
Path trustedCaFile = Files.copy(tempDir.resolve("tls/rds-ca.crt"), tempDir.resolve("trusted-ca.crt"));
Thread authThread = Thread.ofVirtual().start(() -> {
try {
PostgresProtocolHandler.authenticate(
proxyClient, () -> new Socket("localhost", backendServer.getLocalPort()),
"dbadmin", "adminpass", "postgres",
false, testSigV4Validator(), testBinding(), tlsCertificates,
(user, pass) -> PasswordValidator.AuthResult.MASTER_EQUIVALENT, 5000);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
DataOutputStream clientOut = new DataOutputStream(ourClient.getOutputStream());
writeSslRequest(clientOut);
assertEquals('S', new DataInputStream(ourClient.getInputStream()).readUnsignedByte());
try (SSLSocket sslClient = verifyingClientSocket(ourClient, trustedCaFile, "localhost")) {
DataOutputStream tlsOut = new DataOutputStream(sslClient.getOutputStream());
tlsOut.writeInt(16);
tlsOut.writeInt(80877102);
tlsOut.writeInt(4242);
tlsOut.writeInt(0x5eed);
tlsOut.flush();
backendServer.setSoTimeout(5000);
try (Socket backend = backendServer.accept()) {
backend.setSoTimeout(5000);
DataInputStream backendIn = new DataInputStream(backend.getInputStream());
assertEquals(16, backendIn.readInt());
assertEquals(80877102, backendIn.readInt());
assertEquals(4242, backendIn.readInt());
assertEquals(0x5eed, backendIn.readInt());
assertEquals(-1, backendIn.read(), "the proxy closes the cancel connection");
}
} finally {
authThread.join(5_000);
assertFalse(authThread.isAlive(), "authThread did not terminate");
}
}
}
@Test
void closesClientWhenBackendClosesDuringBridge() throws Exception {
try (ServerSocket backendServer = new ServerSocket(0);
@@ -18,9 +18,11 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
@@ -159,6 +161,35 @@ class RdsAuthProxyBackendResolutionTest {
}
}
@Test
void onlyADatabaseEndpointForwardsACancelRequest() throws Exception {
assertTrue(cancelReachesBackend(RdsAuthProxy.EndpointKind.DATABASE));
assertFalse(cancelReachesBackend(RdsAuthProxy.EndpointKind.STANDARD_DB_PROXY));
}
private boolean cancelReachesBackend(RdsAuthProxy.EndpointKind endpointKind) throws Exception {
ServerSocket backend = backendAt(0);
AtomicInteger resolved = new AtomicInteger();
int proxyPort = FreePorts.anyInterfacePort();
proxy("db-a", backend.getLocalPort(), () -> {
resolved.incrementAndGet();
return endpoint(backend.getLocalPort());
}, DatabaseEngine.POSTGRES, endpointKind).start(proxyPort);
try (Socket client = new Socket("127.0.0.1", proxyPort)) {
client.setSoTimeout(5000);
DataOutputStream request = new DataOutputStream(client.getOutputStream());
request.writeInt(16);
request.writeInt(80877102);
request.writeInt(4242);
request.writeInt(0x5eed);
request.flush();
// The proxy closes the client only after it has forwarded or dropped the cancel.
assertEquals(-1, client.getInputStream().read());
}
return resolved.get() > 0;
}
private RdsAuthProxy proxy(String id, int initialBackendPort,
RdsAuthProxy.BackendEndpointResolver endpointResolver) {
return proxy(id, initialBackendPort, endpointResolver, DatabaseEngine.SQLSERVER);
@@ -167,12 +198,18 @@ class RdsAuthProxyBackendResolutionTest {
private RdsAuthProxy proxy(String id, int initialBackendPort,
RdsAuthProxy.BackendEndpointResolver endpointResolver,
DatabaseEngine engine) {
return proxy(id, initialBackendPort, endpointResolver, engine, RdsAuthProxy.EndpointKind.DATABASE);
}
private RdsAuthProxy proxy(String id, int initialBackendPort,
RdsAuthProxy.BackendEndpointResolver endpointResolver,
DatabaseEngine engine, RdsAuthProxy.EndpointKind endpointKind) {
RdsAuthProxy proxy = new RdsAuthProxy(
id, "127.0.0.1", initialBackendPort, endpointResolver, "runtime:" + id,
engine, false, "sa", "Secret123", null,
mock(RdsSigV4Validator.class), mock(RdsProxyTlsCertificates.class),
(user, password) -> true, 5000, 5000, 100, null,
username -> false, RdsBackendGate.OPEN, RdsAuthProxy.EndpointKind.DATABASE);
username -> false, RdsBackendGate.OPEN, endpointKind);
proxies.add(proxy);
return proxy;
}
@@ -0,0 +1,85 @@
package io.github.hectorvent.floci.services.rds.proxy;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import static io.github.hectorvent.floci.testing.RdsRequests.assumeDocker;
import static io.github.hectorvent.floci.testing.RdsRequests.createPostgresInstance;
import static io.github.hectorvent.floci.testing.RdsRequests.deleteInstance;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** A client cancels a running query through the proxy, as it does on an RDS for PostgreSQL endpoint. */
@QuarkusTest
@Tag("docker")
class RdsPostgresCancelIntegrationTest {
private static final String SLEEP = "SELECT pg_sleep(30)";
@BeforeEach
void checkDocker() throws InterruptedException {
assumeDocker();
}
@Test
void aCancelledQueryStopsOnTheInstance() throws Exception {
String dbId = "pg-cancel-" + Long.toString(System.nanoTime(), 36);
int port = createPostgresInstance(dbId, "master", "Master123!", false);
try (Connection connection = connect(port);
Statement statement = connection.createStatement();
Connection observer = connect(port)) {
long started = System.nanoTime();
CompletableFuture<Void> query = CompletableFuture.runAsync(() -> {
try {
statement.execute(SLEEP);
} catch (SQLException e) {
throw new CompletionException(e);
}
});
await().atMost(Duration.ofSeconds(10)).until(() -> sleeping(observer));
statement.cancel();
CompletionException failed = assertThrows(CompletionException.class, query::join);
assertThat(failed.getCause(), instanceOf(SQLException.class));
assertThat(((SQLException) failed.getCause()).getSQLState(), equalTo("57014"));
assertThat(TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - started), lessThan(10L));
} finally {
deleteInstance(dbId);
}
}
private static Connection connect(int port) throws SQLException {
Properties properties = new Properties();
properties.setProperty("user", "master");
properties.setProperty("password", "Master123!");
properties.setProperty("sslmode", "disable");
return DriverManager.getConnection("jdbc:postgresql://127.0.0.1:" + port + "/appdb", properties);
}
/** Whether the backend runs the sleep, so a cancel sent now has a query to stop. */
private static boolean sleeping(Connection observer) throws SQLException {
try (Statement statement = observer.createStatement();
ResultSet row = statement.executeQuery("SELECT count(*) FROM pg_stat_activity"
+ " WHERE state = 'active' AND query = '" + SLEEP + "'")) {
return row.next() && row.getInt(1) > 0;
}
}
}
@@ -24,6 +24,8 @@ import java.util.Map;
import java.util.Properties;
import static io.github.hectorvent.floci.testing.Ec2Requests.ec2;
import static io.github.hectorvent.floci.testing.RdsRequests.createPostgresInstance;
import static io.github.hectorvent.floci.testing.RdsRequests.deleteInstance;
import static io.github.hectorvent.floci.testing.RdsRequests.rds;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.*;
@@ -49,8 +51,8 @@ class RdsPostgresIamRoleIntegrationTest {
String role = id + "-policy";
List<Runnable> cleanup = new ArrayList<>();
try {
int databasePort = create(id);
cleanup.add(0, () -> delete(id));
int databasePort = createPostgresInstance(id, MASTER, PASSWORD, true);
cleanup.add(0, () -> deleteInstance(id));
asMaster(databasePort, "CREATE ROLE app_user LOGIN PASSWORD '" + APP_PASSWORD + "'");
String vpc = ec2("CreateVpc", "test", "us-east-1").formParam("CidrBlock", "10.97.0.0/16")
.post("/").then().statusCode(200).extract().xmlPath().getString("CreateVpcResponse.vpc.vpcId");
@@ -126,7 +128,7 @@ class RdsPostgresIamRoleIntegrationTest {
void iamLoginRequiresMembershipAndTheRolesOwnLoginAttribute() throws Exception {
String id = uniqueId();
try {
int port = create(id);
int port = createPostgresInstance(id, MASTER, PASSWORD, true);
asMaster(port, "CREATE ROLE app_user LOGIN PASSWORD '" + APP_PASSWORD + "'");
Properties token = token(port, "app_user");
refused(port, token);
@@ -139,7 +141,7 @@ class RdsPostgresIamRoleIntegrationTest {
asMaster(port, "ALTER ROLE app_user LOGIN");
assertUser(port, token, "app_user");
} finally {
delete(id);
deleteInstance(id);
}
}
@@ -147,7 +149,7 @@ class RdsPostgresIamRoleIntegrationTest {
void iamMembershipTakesPrecedenceOverAnApplicationPassword() throws Exception {
String id = uniqueId();
try {
int port = create(id);
int port = createPostgresInstance(id, MASTER, PASSWORD, true);
asMaster(port, "CREATE ROLE app_user LOGIN PASSWORD '" + APP_PASSWORD + "'");
Properties password = login("app_user", APP_PASSWORD);
assertUser(port, password, "app_user");
@@ -163,7 +165,7 @@ class RdsPostgresIamRoleIntegrationTest {
asMaster(port, "REVOKE rds_iam FROM app_user");
assertUser(port, password, "app_user");
} finally {
delete(id);
deleteInstance(id);
}
}
@@ -171,7 +173,7 @@ class RdsPostgresIamRoleIntegrationTest {
void theMasterNeedsAnActualGrantAndThenUsesIamInsteadOfItsPassword() throws Exception {
String id = uniqueId();
try {
int port = create(id);
int port = createPostgresInstance(id, MASTER, PASSWORD, true);
Properties iam = token(port, MASTER);
refused(port, iam);
try (Connection admin = connect(port, login(MASTER, PASSWORD));
@@ -184,7 +186,7 @@ class RdsPostgresIamRoleIntegrationTest {
}
assertUser(port, login(MASTER, PASSWORD), MASTER);
} finally {
delete(id);
deleteInstance(id);
}
}
@@ -192,7 +194,7 @@ class RdsPostgresIamRoleIntegrationTest {
void indirectMembershipWorksWithoutPrivilegeInheritance() throws Exception {
String id = uniqueId();
try {
int port = create(id);
int port = createPostgresInstance(id, MASTER, PASSWORD, true);
asMaster(port, "CREATE ROLE iam_group NOLOGIN", "GRANT rds_iam TO iam_group",
"CREATE ROLE app_user LOGIN NOINHERIT PASSWORD '" + APP_PASSWORD + "'",
"GRANT iam_group TO app_user");
@@ -203,7 +205,7 @@ class RdsPostgresIamRoleIntegrationTest {
refused(port, iam);
assertUser(port, login("app_user", APP_PASSWORD), "app_user");
} finally {
delete(id);
deleteInstance(id);
}
}
@@ -212,7 +214,7 @@ class RdsPostgresIamRoleIntegrationTest {
String id = uniqueId();
String name = "café\"reader";
try {
int port = create(id);
int port = createPostgresInstance(id, MASTER, PASSWORD, true);
asMaster(port, "CREATE ROLE \"café\"\"reader\" LOGIN PASSWORD '" + APP_PASSWORD + "'",
"GRANT rds_iam TO \"café\"\"reader\"", "CREATE SCHEMA shadow",
"CREATE TABLE shadow.pg_roles (oid oid, rolname name, rolcanlogin boolean)",
@@ -229,7 +231,7 @@ class RdsPostgresIamRoleIntegrationTest {
iam.setProperty("allowEncodingChanges", "true");
assertUser(port, iam, name);
} finally {
delete(id);
deleteInstance(id);
}
}
@@ -286,18 +288,4 @@ class RdsPostgresIamRoleIntegrationTest {
private static String uniqueId() {
return "iam-role-" + Long.toString(System.nanoTime(), 36);
}
private static int create(String id) {
return rds("CreateDBInstance").formParam("DBInstanceIdentifier", id).formParam("Engine", "postgres")
.formParam("MasterUsername", MASTER).formParam("MasterUserPassword", PASSWORD)
.formParam("DBName", "appdb").formParam("AllocatedStorage", 20)
.formParam("DBInstanceClass", "db.t3.micro").formParam("EnableIAMDatabaseAuthentication", true)
.post("/").then().statusCode(200).extract().xmlPath()
.getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port");
}
private static void delete(String id) {
rds("DeleteDBInstance").formParam("DBInstanceIdentifier", id).formParam("SkipFinalSnapshot", true)
.post("/").then().statusCode(200);
}
}
@@ -1,9 +1,7 @@
package io.github.hectorvent.floci.services.rds.proxy;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.testutil.SigV4TokenTestHelper;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@@ -16,11 +14,12 @@ import java.sql.Statement;
import java.time.Instant;
import java.util.Properties;
import static io.github.hectorvent.floci.testing.RdsRequests.rds;
import static io.github.hectorvent.floci.testing.RdsRequests.assumeDocker;
import static io.github.hectorvent.floci.testing.RdsRequests.createPostgresInstance;
import static io.github.hectorvent.floci.testing.RdsRequests.deleteInstance;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* The parameters a client puts in its PostgreSQL StartupMessage reach the instance through the
@@ -35,32 +34,15 @@ class RdsPostgresStartupParametersIntegrationTest {
private static final String MASTER_USER = "master";
private static final String MASTER_PASSWORD = "Master123!";
@Inject
DockerClient dockerClient;
@BeforeEach
void checkDocker() {
try {
dockerClient.pingCmd().exec();
} catch (Exception e) {
assumeTrue(false, "Docker is not available: " + e.getMessage());
}
void checkDocker() throws InterruptedException {
assumeDocker();
}
@Test
void clientStartupParametersApplyToTheSession() throws Exception {
String dbId = "startup-params-" + Long.toString(System.nanoTime(), 36);
int port = rds("CreateDBInstance")
.formParam("DBInstanceIdentifier", dbId)
.formParam("Engine", "postgres")
.formParam("MasterUsername", MASTER_USER)
.formParam("MasterUserPassword", MASTER_PASSWORD)
.formParam("DBName", "appdb")
.formParam("AllocatedStorage", "20")
.formParam("DBInstanceClass", "db.t3.micro")
.when().post("/").then().statusCode(200)
.extract().xmlPath()
.getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port");
int port = createPostgresInstance(dbId, MASTER_USER, MASTER_PASSWORD, false);
try {
Properties properties = new Properties();
properties.setProperty("user", MASTER_USER);
@@ -76,17 +58,14 @@ class RdsPostgresStartupParametersIntegrationTest {
assertThat(show(connection, "application_name"), equalTo("floci-startup-params"));
}
} finally {
rds("DeleteDBInstance")
.formParam("DBInstanceIdentifier", dbId)
.formParam("SkipFinalSnapshot", "true")
.when().post("/");
deleteInstance(dbId);
}
}
@Test
void clientStartupParametersApplyToAnIamSessionAsTheTokenRole() throws Exception {
String dbId = "startup-params-iam-" + Long.toString(System.nanoTime(), 36);
int port = createIamInstance(dbId);
int port = createPostgresInstance(dbId, MASTER_USER, MASTER_PASSWORD, true);
try {
asMaster(port,
"CREATE ROLE app_user LOGIN",
@@ -113,7 +92,7 @@ class RdsPostgresStartupParametersIntegrationTest {
@Test
void anIamSessionCannotTakeTheMasterIdentityThroughStartupParameters() throws Exception {
String dbId = "startup-params-iam-escalation-" + Long.toString(System.nanoTime(), 36);
int port = createIamInstance(dbId);
int port = createPostgresInstance(dbId, MASTER_USER, MASTER_PASSWORD, true);
try {
asMaster(port, "CREATE ROLE app_user LOGIN", "GRANT rds_iam TO app_user");
@@ -135,7 +114,7 @@ class RdsPostgresStartupParametersIntegrationTest {
@Test
void anIamSessionLoadsTheTokenRolesOwnDefaultsBeneathTheClientsParameters() throws Exception {
String dbId = "startup-params-iam-defaults-" + Long.toString(System.nanoTime(), 36);
int port = createIamInstance(dbId);
int port = createPostgresInstance(dbId, MASTER_USER, MASTER_PASSWORD, true);
try {
asMaster(port,
"CREATE ROLE reader NOLOGIN",
@@ -177,29 +156,6 @@ class RdsPostgresStartupParametersIntegrationTest {
}
}
/** Creates a PostgreSQL instance with IAM database authentication and returns its proxy port. */
private static int createIamInstance(String dbId) {
return rds("CreateDBInstance")
.formParam("DBInstanceIdentifier", dbId)
.formParam("Engine", "postgres")
.formParam("MasterUsername", MASTER_USER)
.formParam("MasterUserPassword", MASTER_PASSWORD)
.formParam("DBName", "appdb")
.formParam("AllocatedStorage", "20")
.formParam("DBInstanceClass", "db.t3.micro")
.formParam("EnableIAMDatabaseAuthentication", "true")
.when().post("/").then().statusCode(200)
.extract().xmlPath()
.getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port");
}
private static void deleteInstance(String dbId) {
rds("DeleteDBInstance")
.formParam("DBInstanceIdentifier", dbId)
.formParam("SkipFinalSnapshot", "true")
.when().post("/");
}
/** Runs {@code statements} in order as the master user. */
private static void asMaster(int port, String... statements) throws SQLException {
Properties master = new Properties();
@@ -12,6 +12,7 @@ import java.net.URI;
import static io.restassured.RestAssured.given;
import static io.restassured.http.ContentType.URLENC;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
public final class RdsRequests {
private RdsRequests() {}
@@ -30,4 +31,33 @@ public final class RdsRequests {
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test-secret-key")))
.build();
}
/** Skips the test when no Docker daemon answers, which a real PostgreSQL instance needs. */
public static void assumeDocker() throws InterruptedException {
assumeTrue(DockerAvailability.isAvailable(), "Docker is not available");
}
/** Creates a PostgreSQL instance with database {@code appdb} and returns its endpoint port. */
public static int createPostgresInstance(String id, String masterUsername, String masterPassword,
boolean iamDatabaseAuthentication) {
return rds("CreateDBInstance")
.formParam("DBInstanceIdentifier", id)
.formParam("Engine", "postgres")
.formParam("MasterUsername", masterUsername)
.formParam("MasterUserPassword", masterPassword)
.formParam("DBName", "appdb")
.formParam("AllocatedStorage", "20")
.formParam("DBInstanceClass", "db.t3.micro")
.formParam("EnableIAMDatabaseAuthentication", iamDatabaseAuthentication)
.when().post("/").then().statusCode(200)
.extract().xmlPath()
.getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port");
}
public static void deleteInstance(String id) {
rds("DeleteDBInstance")
.formParam("DBInstanceIdentifier", id)
.formParam("SkipFinalSnapshot", "true")
.when().post("/");
}
}