fix(rds-data): refuse a database name that would change the JDBC URL (#8927)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-18 21:24:10 -04:00
1 parent 563de77b1e
commit fa965882ca
5 files changed
+145 -3

No files matched your search

@@ -4,6 +4,8 @@ import io.floci.aws.core.common.docker.ContainerLifecycleManager.EndpointInfo;
import io.floci.aws.services.rds.model.DatabaseEngine;
import jakarta.enterprise.context.ApplicationScoped;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
@@ -31,11 +33,22 @@ class RdsDataConnectionFactory {
return DriverManager.getConnection(url, props);
}
/** The longest database name the RDS Data API accepts ({@code DbName}, at most 64 characters). */
static final int MAX_DATABASE_NAME_LENGTH = 64;
/**
* The JDBC URL for {@code database}, the name percent-encoded so that both drivers read back exactly
* the name given and nothing in it can start, add or override a connection property, as AWS passes
* the name to the engine as an identifier. A name the engine does not know is then the engine's
* error. {@link URLEncoder} writes a literal {@code +} as {@code %2B} and a space as {@code +}, which
* is replaced by {@code %20}: both drivers decode a bare {@code +} in the path as a space.
*/
static String buildUrl(DatabaseEngine engine, String host, int port, String database) {
String path = URLEncoder.encode(database, StandardCharsets.UTF_8).replace("+", "%20");
return switch (engine) {
case MYSQL, MARIADB -> "jdbc:mysql://" + host + ":" + port + "/" + database
case MYSQL, MARIADB -> "jdbc:mysql://" + host + ":" + port + "/" + path
+ "?useSSL=false&allowPublicKeyRetrieval=true";
case POSTGRES -> "jdbc:postgresql://" + host + ":" + port + "/" + database
case POSTGRES -> "jdbc:postgresql://" + host + ":" + port + "/" + path
+ "?sslmode=disable";
case SQLSERVER -> throw new IllegalArgumentException(
"RDS Data API is not supported for SQL Server");
@@ -190,6 +190,7 @@ public class RdsDataService implements Resettable {
}
public ObjectNode executeStatement(JsonNode request, String region) {
validateRequestDatabase(request);
rejectUnsupportedOptions(request);
String sql = requiredText(request, "sql");
@@ -205,6 +206,7 @@ public class RdsDataService implements Resettable {
}
public ObjectNode batchExecuteStatement(JsonNode request, String region) {
validateRequestDatabase(request);
String sql = requiredText(request, "sql");
List<Map<String, JsonNode>> parameterSets = parseParameterSets(request);
@@ -217,6 +219,7 @@ public class RdsDataService implements Resettable {
}
public ObjectNode beginTransaction(JsonNode request, String region) {
validateRequestDatabase(request);
cleanupExpiredTransactions();
String resourceArn = requiredText(request, "resourceArn");
requiredText(request, "secretArn");
@@ -699,7 +702,7 @@ public class RdsDataService implements Resettable {
private String databaseName(JsonNode request, RdsDataResourceResolver.DatabaseTarget target) {
String database = textOrNull(request, "database");
if (database != null && !database.isBlank()) {
if (database != null && !database.isEmpty()) {
return database;
}
if (target.databaseName() != null && !target.databaseName().isBlank()) {
@@ -708,6 +711,23 @@ public class RdsDataService implements Resettable {
throw new AwsException("BadRequestException", "database is required.", 400);
}
/**
* Refuses a request's {@code database} longer than the model's {@code DbName} allows. Runs first, as
* AWS checks the request's shape before it looks up the resource. Any other name is the engine's to
* judge: {@link RdsDataConnectionFactory#buildUrl} encodes it so it cannot change the connection.
*/
private static void validateRequestDatabase(JsonNode request) {
String database = textOrNull(request, "database");
// Only an absent or empty name means "the resource's"; one of spaces is checked like any other.
if (database == null || database.isEmpty()) {
return;
}
if (database.length() > RdsDataConnectionFactory.MAX_DATABASE_NAME_LENGTH) {
throw new AwsException("BadRequestException", "database must be at most "
+ RdsDataConnectionFactory.MAX_DATABASE_NAME_LENGTH + " characters.", 400);
}
}
private TransactionContext transaction(String transactionId) {
cleanupExpiredTransactions();
TransactionContext tx = transactions.get(transactionId);
@@ -1,9 +1,15 @@
package io.floci.aws.services.rdsdata;
import com.mysql.cj.conf.ConnectionUrl;
import io.floci.aws.services.rds.model.DatabaseEngine;
import org.junit.jupiter.api.Test;
import org.postgresql.Driver;
import java.util.List;
import java.util.Properties;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class RdsDataConnectionFactoryTest {
@@ -27,4 +33,25 @@ class RdsDataConnectionFactoryTest {
"jdbc:postgresql://127.0.0.1:5432/app?sslmode=disable",
RdsDataConnectionFactory.buildUrl(DatabaseEngine.POSTGRES, "127.0.0.1", 5432, "app"));
}
// Catches the connection-property injection: a database name going into the URL as written let
// `app?allowLoadLocalInfile=true` add a driver property. Each driver must read back the exact name
// and nothing else.
@Test
void everyDriverReadsBackTheExactDatabaseNameAndNoAddedProperty() throws Exception {
for (String database : List.of("app?allowLoadLocalInfile=true&autoDeserialize=true", "app&sslmode=require",
"my db", "a+b", "a%b", "other/app", "a#b", "user@app", "app;x=1", "app:1", "a\\b", "caf\u00e9")) {
ConnectionUrl mysql = ConnectionUrl.getConnectionUrlInstance(
RdsDataConnectionFactory.buildUrl(DatabaseEngine.MYSQL, "127.0.0.1", 3306, database), new Properties());
assertEquals(database, mysql.getDatabase(), "MySQL " + database);
assertNull(mysql.getMainHost().getHostProperties().get("allowLoadLocalInfile"), "MySQL " + database);
assertEquals("false", mysql.getMainHost().getHostProperties().get("useSSL"), "MySQL " + database);
Properties postgres = Driver.parseURL(
RdsDataConnectionFactory.buildUrl(DatabaseEngine.POSTGRES, "127.0.0.1", 5432, database),
new Properties());
assertEquals(database, postgres.getProperty("PGDBNAME"), "PostgreSQL " + database);
assertEquals("disable", postgres.getProperty("sslmode"), "PostgreSQL " + database);
}
}
}
@@ -92,6 +92,30 @@ class RdsDataControllerIntegrationTest {
.body("__type", equalTo("BadRequestException"));
}
// Catches: the model's 64-character limit on database checked only after the resource lookup;
// AWS checks the request's shape first, so a missing resource does not hide it.
@Test
void executeRefusesADatabaseNameLongerThanTheModelAllows() {
given()
.contentType("application/json")
.body("""
{
"resourceArn": "arn:aws:rds:us-east-1:000000000000:cluster:missing",
"secretArn": "arn:aws:secretsmanager:us-east-1:000000000000:secret:missing",
"database": "%s",
"sql": "select 1"
}
""".formatted("d".repeat(65)))
.when()
.post("/Execute")
.then()
.statusCode(400)
.contentType("application/json")
.header("X-Amzn-Errortype", "BadRequestException")
.body("__type", equalTo("BadRequestException"))
.body("message", equalTo("database must be at most 64 characters."));
}
@Test
void commitUnknownTransactionReturnsTypedJsonError() {
given()
@@ -78,6 +78,62 @@ class RdsDataServiceTest {
assertEquals(Types.INTEGER, response.path("columnMetadata").get(0).path("arrayBaseColumnType").asInt());
}
// Catches the connection-property injection at the service: the name reaches the connection as the
// caller wrote it (the factory encodes it), neither refused nor swapped for the resource's database.
@Test
void aDatabaseNameIsPassedToTheConnectionAsWritten() throws Exception {
TestHarness harness = new TestHarness(DatabaseEngine.MYSQL);
String injected = "app?allowLoadLocalInfile=true&autoDeserialize=true";
ObjectNode request = harness.request("select 1");
request.put("database", injected);
harness.service.executeStatement(request, REGION);
assertEquals(List.of(injected), harness.databasesOpened);
}
@Test
void aDatabaseNameLongerThanTheModelAllowsIsRefused() throws Exception {
TestHarness harness = new TestHarness(DatabaseEngine.POSTGRES);
ObjectNode request = harness.request("select 1");
request.put("database", "d".repeat(65));
AwsException error = assertThrows(AwsException.class, () -> harness.service.executeStatement(request, REGION));
assertEquals("BadRequestException", error.getErrorCode());
assertEquals("database must be at most 64 characters.", error.getMessage());
assertEquals(0, harness.connectionsOpened.get());
}
// Catches: a name of only spaces read as "no database", so it ran against the resource's database
// even at a length the model refuses.
@Test
void aDatabaseNameOfSpacesIsANameRatherThanTheResourcesDatabase() throws Exception {
TestHarness harness = new TestHarness(DatabaseEngine.MYSQL);
ObjectNode spaces = harness.request("select 1");
spaces.put("database", " ");
ObjectNode tooLong = harness.request("select 1");
tooLong.put("database", " ".repeat(65));
harness.service.executeStatement(spaces, REGION);
AwsException lengthError = assertThrows(AwsException.class,
() -> harness.service.executeStatement(tooLong, REGION));
assertEquals(List.of(" "), harness.databasesOpened);
assertEquals("database must be at most 64 characters.", lengthError.getMessage());
}
@Test
void anOrdinaryDatabaseNameWithAHyphenStillConnects() throws Exception {
TestHarness harness = new TestHarness(DatabaseEngine.POSTGRES);
ObjectNode request = harness.request("select 1");
request.put("database", "orders-db_2");
harness.service.executeStatement(request, REGION);
assertEquals(1, harness.connectionsOpened.get());
}
@Test
void rejectsMultidimensionalArrayResultsThroughTheJdbcExecutionPath() throws Exception {
TestHarness harness = new TestHarness(DatabaseEngine.POSTGRES);
@@ -1302,6 +1358,7 @@ class RdsDataServiceTest {
private final AtomicInteger endpointsResolved = new AtomicInteger();
private final AtomicReference<EndpointInfo> currentEndpoint = new AtomicReference<>();
private final List<EndpointInfo> endpointsOpened = new CopyOnWriteArrayList<>();
private final List<String> databasesOpened = new CopyOnWriteArrayList<>();
private volatile RuntimeException endpointFailure;
private final RdsDataService service;
@@ -1360,6 +1417,7 @@ class RdsDataServiceTest {
String password,
String database) throws SQLException {
endpointsOpened.add(endpoint);
databasesOpened.add(database);
connectionsOpened.incrementAndGet();
return getConnection();
}