feat(rds-data): add RDS Data API support (#1262)

* feat(rds-data): add RDS Data API support

* fix(rds-data): harden Data API validation

* fix(rds-data): harden review findings
This commit is contained in:
devansh-jain-18 authored and GitHub committed 2026-06-12 23:39:05 -05:00
1 parent 33eac5f79e
commit e063ac18ee
29 files changed
+2339 -9

No files matched your search

@@ -321,6 +321,7 @@ public interface EmulatorConfig {
MskServiceConfig msk();
ElastiCacheServiceConfig elasticache();
RdsServiceConfig rds();
RdsDataServiceConfig rdsData();
EventBridgeServiceConfig eventbridge();
CloudMapServiceConfig cloudmap();
SchedulerServiceConfig scheduler();
@@ -533,6 +534,14 @@ public interface EmulatorConfig {
Optional<String> dockerNetwork();
}
interface RdsDataServiceConfig {
@WithDefault("true")
boolean enabled();
@WithDefault("180")
long transactionTtlSeconds();
}
interface NeptuneServiceConfig {
@WithDefault("true")
boolean enabled();
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.cloudfront.CloudFrontController;
import io.github.hectorvent.floci.services.route53.Route53Controller;
import io.github.hectorvent.floci.services.ses.SesController;
import io.github.hectorvent.floci.services.appsync.AppSyncController;
import io.github.hectorvent.floci.services.rdsdata.RdsDataController;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -89,6 +90,11 @@ public class ResolvedServiceCatalog {
5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY,
protocols(ServiceProtocol.QUERY),
Set.of(), Set.of("rds"), Set.of(), Set.of()),
descriptor("rds-data", "rds-data",
config.services().rds().enabled() && config.services().rdsData().enabled(), true,
null, null, 5000L, null, ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
Set.of(), Set.of("rds-data"), Set.of(), Set.of(RdsDataController.class)),
descriptor("neptune", "neptune", config.services().neptune().enabled(), true,
"neptune", storageMode(config.storage().services().neptune().mode(), config.storage().mode()),
5000L, AwsNamespaces.RDS, ServiceProtocol.QUERY,
@@ -116,6 +116,8 @@ public class ServiceEnabledFilter implements ContainerRequestFilter {
if (request.protocol() == ServiceProtocol.JSON || request.protocol() == ServiceProtocol.REST_JSON) {
return Response.status(400)
.type(MediaType.APPLICATION_JSON)
.header("X-Amzn-Errortype", "ServiceNotAvailableException")
.header("x-amzn-query-error", "ServiceNotAvailableException;Sender")
.entity(new AwsErrorResponse("ServiceNotAvailableException", message))
.build();
}
@@ -69,6 +69,14 @@ public class IamActionRegistry {
// ── DynamoDB (JSON 1.1, action from X-Amz-Target handled separately) ──
// Handled via Query-style action extraction in the filter
// ── RDS Data API ───────────────────────────────────────────────────────
rule("rds-data", "POST", "^/Execute/?$", "rds-data:ExecuteStatement"),
rule("rds-data", "POST", "^/ExecuteSql/?$", "rds-data:ExecuteSql"),
rule("rds-data", "POST", "^/BatchExecute/?$", "rds-data:BatchExecuteStatement"),
rule("rds-data", "POST", "^/BeginTransaction/?$", "rds-data:BeginTransaction"),
rule("rds-data", "POST", "^/CommitTransaction/?$", "rds-data:CommitTransaction"),
rule("rds-data", "POST", "^/RollbackTransaction/?$", "rds-data:RollbackTransaction"),
// ── API Gateway ────────────────────────────────────────────────────────
rule("apigateway", "GET", ".*/account$", "apigateway:GET"),
rule("apigateway", "PATCH", ".*/account$", "apigateway:PATCH"),
@@ -0,0 +1,31 @@
package io.github.hectorvent.floci.services.rdsdata;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import jakarta.enterprise.context.ApplicationScoped;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
@ApplicationScoped
class RdsDataConnectionFactory {
Connection open(RdsDataResourceResolver.DatabaseTarget target,
String username,
String password,
String database) throws SQLException {
if (target.engine() != DatabaseEngine.MYSQL && target.engine() != DatabaseEngine.MARIADB) {
throw new AwsException("BadRequestException",
"RDS Data API currently supports local MySQL and MariaDB resources only.", 400);
}
String url = "jdbc:mysql://" + target.host() + ":" + target.port() + "/" + database
+ "?useSSL=false&allowPublicKeyRetrieval=true";
Properties props = new Properties();
props.setProperty("user", username);
props.setProperty("password", password);
props.setProperty("connectTimeout", "5000");
return DriverManager.getConnection(url, props);
}
}
@@ -0,0 +1,105 @@
package io.github.hectorvent.floci.services.rdsdata;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.jboss.logging.Logger;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.WILDCARD)
public class RdsDataController {
private static final Logger LOG = Logger.getLogger(RdsDataController.class);
private final RdsDataService service;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public RdsDataController(RdsDataService service, RegionResolver regionResolver, ObjectMapper objectMapper) {
this.service = service;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
@POST
@Path("/Execute")
public Response executeStatement(@Context HttpHeaders headers, String body) {
return handle(headers, body, (request, region) -> Response.ok(service.executeStatement(request, region)).build());
}
@POST
@Path("/ExecuteSql")
public Response executeSql() {
return error(400, "BadRequestException",
"ExecuteSql is not supported by this local RDS Data API implementation.");
}
@POST
@Path("/BeginTransaction")
public Response beginTransaction(@Context HttpHeaders headers, String body) {
return handle(headers, body, (request, region) -> Response.ok(service.beginTransaction(request, region)).build());
}
@POST
@Path("/BatchExecute")
public Response batchExecuteStatement() {
return error(400, "BadRequestException",
"BatchExecuteStatement is not supported by this local RDS Data API implementation.");
}
@POST
@Path("/CommitTransaction")
public Response commitTransaction(@Context HttpHeaders headers, String body) {
return handle(headers, body, (request, region) -> Response.ok(service.commitTransaction(request)).build());
}
@POST
@Path("/RollbackTransaction")
public Response rollbackTransaction(@Context HttpHeaders headers, String body) {
return handle(headers, body, (request, region) -> Response.ok(service.rollbackTransaction(request)).build());
}
private Response handle(HttpHeaders headers, String body, Handler handler) {
try {
JsonNode request = body == null || body.isBlank()
? objectMapper.createObjectNode()
: objectMapper.readTree(body);
return handler.handle(request, regionResolver.resolveRegion(headers));
} catch (AwsException e) {
return error(e.getHttpStatus(), e.getErrorCode(), e.getMessage());
} catch (JsonProcessingException e) {
return error(400, "BadRequestException", "Malformed JSON request body.");
} catch (Exception e) {
LOG.error("Error processing RDS Data API request", e);
return error(500, "InternalFailure", e.getMessage());
}
}
private static Response error(int status, String code, String message) {
return Response.status(status)
.type(MediaType.APPLICATION_JSON)
.header("X-Amzn-Errortype", code)
.header("x-amzn-query-error", code + ";" + (status < 500 ? "Sender" : "Receiver"))
.entity(new AwsErrorResponse(code, message))
.build();
}
@FunctionalInterface
private interface Handler {
Response handle(JsonNode request, String region);
}
}
@@ -0,0 +1,126 @@
package io.github.hectorvent.floci.services.rdsdata;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
final class RdsDataFieldMapper {
private static final DateTimeFormatter TIMESTAMP_BASE_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private RdsDataFieldMapper() {
}
static ObjectNode toField(ObjectMapper objectMapper, Object value, int sqlType) throws SQLException {
ObjectNode field = objectMapper.createObjectNode();
if (value == null) {
field.put("isNull", true);
return field;
}
switch (sqlType) {
case Types.BIGINT, Types.INTEGER, Types.SMALLINT, Types.TINYINT -> {
if (value instanceof Number number) {
field.put("longValue", number.longValue());
} else {
field.put("longValue", Long.parseLong(value.toString()));
}
}
case Types.BINARY, Types.VARBINARY, Types.LONGVARBINARY, Types.BLOB -> {
if (value instanceof byte[] bytes) {
field.put("blobValue", bytes);
} else if (value instanceof Blob blob) {
field.put("blobValue", blob.getBytes(1, Math.toIntExact(blob.length())));
} else {
field.put("blobValue", value.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8));
}
}
case Types.BOOLEAN, Types.BIT -> {
if (value instanceof Boolean bool) {
field.put("booleanValue", bool);
} else if (value instanceof Number number) {
field.put("booleanValue", number.longValue() != 0);
} else {
field.put("booleanValue", Boolean.parseBoolean(value.toString()));
}
}
case Types.FLOAT, Types.REAL, Types.DOUBLE -> {
if (value instanceof Number number) {
field.put("doubleValue", number.doubleValue());
} else {
field.put("doubleValue", Double.parseDouble(value.toString()));
}
}
case Types.NUMERIC, Types.DECIMAL -> mapDecimal(field, value);
case Types.DATE -> field.put("stringValue", formatDate(value));
case Types.TIME -> field.put("stringValue", formatTime(value));
case Types.TIMESTAMP, Types.TIMESTAMP_WITH_TIMEZONE -> field.put("stringValue", formatTimestamp(value));
default -> field.put("stringValue", value.toString());
}
return field;
}
private static String formatDate(Object value) {
if (value instanceof Date date) {
return date.toLocalDate().toString();
}
if (value instanceof LocalDate localDate) {
return localDate.toString();
}
return value.toString();
}
private static String formatTime(Object value) {
if (value instanceof Time time) {
return time.toLocalTime().toString();
}
if (value instanceof LocalTime localTime) {
return localTime.toString();
}
return value.toString();
}
private static String formatTimestamp(Object value) {
if (value instanceof Timestamp timestamp) {
return formatLocalDateTime(timestamp.toLocalDateTime());
}
if (value instanceof LocalDateTime localDateTime) {
return formatLocalDateTime(localDateTime);
}
return value.toString();
}
private static String formatLocalDateTime(LocalDateTime localDateTime) {
String value = localDateTime.format(TIMESTAMP_BASE_FORMATTER);
int nanos = localDateTime.getNano();
if (nanos == 0) {
return value;
}
String fraction = String.format("%09d", nanos);
int end = fraction.length();
while (end > 0 && fraction.charAt(end - 1) == '0') {
end--;
}
return value + "." + fraction.substring(0, end);
}
private static void mapDecimal(ObjectNode field, Object value) {
if (value instanceof BigDecimal decimal) {
field.put("stringValue", decimal.toPlainString());
return;
}
field.put("stringValue", value.toString());
}
}
@@ -0,0 +1,89 @@
package io.github.hectorvent.floci.services.rdsdata;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import io.github.hectorvent.floci.services.rds.model.DbCluster;
import io.github.hectorvent.floci.services.rds.model.DbInstance;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@ApplicationScoped
class RdsDataResourceResolver {
private final RdsService rdsService;
@Inject
RdsDataResourceResolver(RdsService rdsService) {
this.rdsService = rdsService;
}
DatabaseTarget resolve(String resourceArn) {
if (resourceArn == null || resourceArn.isBlank()) {
throw new AwsException("BadRequestException", "resourceArn is required.", 400);
}
for (DbCluster cluster : rdsService.listDbClusters(null)) {
if (resourceArn.equals(cluster.getDbClusterArn())) {
return fromCluster(cluster);
}
}
for (DbInstance instance : rdsService.listDbInstances(null)) {
if (resourceArn.equals(instance.getDbInstanceArn())) {
return fromInstance(instance);
}
}
String id = identifierFromArn(resourceArn);
if (id != null) {
try {
return fromCluster(rdsService.getDbCluster(id));
} catch (AwsException ignored) {
// Try instances below.
}
try {
return fromInstance(rdsService.getDbInstance(id));
} catch (AwsException ignored) {
// Fall through to the Data API error shape.
}
}
throw new AwsException("BadRequestException",
"resourceArn does not resolve to a local RDS resource: " + resourceArn, 400);
}
private static DatabaseTarget fromCluster(DbCluster cluster) {
return target(cluster.getDbClusterArn(), cluster.getEngine(), cluster.getContainerHost(), cluster.getContainerPort(),
cluster.getMasterUsername(), cluster.getMasterPassword(), cluster.getDatabaseName());
}
private static DatabaseTarget fromInstance(DbInstance instance) {
return target(instance.getDbInstanceArn(), instance.getEngine(), instance.getContainerHost(), instance.getContainerPort(),
instance.getMasterUsername(), instance.getMasterPassword(), instance.getDbName());
}
private static DatabaseTarget target(String arn, DatabaseEngine engine, String host, int port,
String username, String password, String databaseName) {
if (host == null || host.isBlank() || port <= 0) {
throw new AwsException("BadRequestException",
"RDS resource runtime is not available for Data API execution.", 400);
}
return new DatabaseTarget(arn, engine, host, port, username, password, databaseName);
}
private static String identifierFromArn(String arn) {
int marker = arn.lastIndexOf(":cluster:");
if (marker >= 0) {
return arn.substring(marker + ":cluster:".length());
}
marker = arn.lastIndexOf(":db:");
if (marker >= 0) {
return arn.substring(marker + ":db:".length());
}
return null;
}
record DatabaseTarget(String arn, DatabaseEngine engine, String host, int port,
String username, String password, String databaseName) {
}
}
@@ -0,0 +1,447 @@
package io.github.hectorvent.floci.services.rdsdata;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ApplicationScoped
public class RdsDataService {
private static final Logger LOG = Logger.getLogger(RdsDataService.class);
private final RdsDataResourceResolver resourceResolver;
private final SecretsManagerService secretsManagerService;
private final ObjectMapper objectMapper;
private final RdsDataConnectionFactory connectionFactory;
private final Duration transactionTtl;
private final ConcurrentMap<String, TransactionContext> transactions = new ConcurrentHashMap<>();
private final ScheduledExecutorService transactionCleanupExecutor;
@Inject
public RdsDataService(RdsDataResourceResolver resourceResolver,
SecretsManagerService secretsManagerService,
ObjectMapper objectMapper,
RdsDataConnectionFactory connectionFactory,
EmulatorConfig config) {
this(resourceResolver, secretsManagerService, objectMapper, connectionFactory,
Duration.ofSeconds(config.services().rdsData().transactionTtlSeconds()));
}
RdsDataService(RdsDataResourceResolver resourceResolver,
SecretsManagerService secretsManagerService,
ObjectMapper objectMapper,
RdsDataConnectionFactory connectionFactory,
Duration transactionTtl) {
this.resourceResolver = resourceResolver;
this.secretsManagerService = secretsManagerService;
this.objectMapper = objectMapper;
this.connectionFactory = connectionFactory;
this.transactionTtl = transactionTtl;
this.transactionCleanupExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread thread = new Thread(r, "rds-data-transaction-cleanup");
thread.setDaemon(true);
return thread;
});
}
@PostConstruct
void startTransactionCleanup() {
long intervalSeconds = Math.max(1, Math.min(60, transactionTtl.toSeconds()));
transactionCleanupExecutor.scheduleAtFixedRate(this::cleanupExpiredTransactionsSafely,
intervalSeconds, intervalSeconds, TimeUnit.SECONDS);
}
@PreDestroy
void shutdown() {
transactionCleanupExecutor.shutdownNow();
transactions.forEach((id, tx) -> {
synchronized (tx) {
if (transactions.remove(id, tx)) {
rollbackQuietly(tx.connection);
closeQuietly(tx.connection);
}
}
});
}
public ObjectNode executeStatement(JsonNode request, String region) {
rejectUnsupportedOptions(request);
String sql = requiredText(request, "sql");
String resourceArn = requiredText(request, "resourceArn");
requiredText(request, "secretArn");
String transactionId = textOrNull(request, "transactionId");
boolean includeMetadata = request.path("includeResultMetadata").asBoolean(false);
try {
if (transactionId != null && !transactionId.isBlank()) {
TransactionContext tx = transaction(transactionId);
synchronized (tx) {
requireActiveTransaction(transactionId, tx);
validateTransactionIdentity(tx, request);
tx.refresh(transactionTtl);
return executeOnConnection(tx.connection, sql, includeMetadata);
}
}
RdsDataResourceResolver.DatabaseTarget target = resourceResolver.resolve(resourceArn);
Credentials credentials = credentials(request, target, region);
String database = databaseName(request, target);
try (Connection connection = connectionFactory.open(target, credentials.username(), credentials.password(), database)) {
return executeOnConnection(connection, sql, includeMetadata);
}
} catch (SQLException e) {
throw databaseError(e);
}
}
public ObjectNode beginTransaction(JsonNode request, String region) {
cleanupExpiredTransactions();
String resourceArn = requiredText(request, "resourceArn");
requiredText(request, "secretArn");
RdsDataResourceResolver.DatabaseTarget target = resourceResolver.resolve(resourceArn);
Credentials credentials = credentials(request, target, region);
String database = databaseName(request, target);
Connection connection = null;
try {
connection = connectionFactory.open(target, credentials.username(), credentials.password(), database);
connection.setAutoCommit(false);
String transactionId = UUID.randomUUID().toString();
transactions.put(transactionId, new TransactionContext(transactionId, connection, target.arn(), database, transactionTtl));
ObjectNode response = objectMapper.createObjectNode();
response.put("transactionId", transactionId);
return response;
} catch (SQLException e) {
if (connection != null) {
closeQuietly(connection);
}
throw databaseError(e);
}
}
public ObjectNode commitTransaction(JsonNode request) {
String transactionId = requiredText(request, "transactionId");
String resourceArn = requiredText(request, "resourceArn");
requiredText(request, "secretArn");
TransactionContext tx = transaction(transactionId);
synchronized (tx) {
requireActiveTransaction(transactionId, tx);
validateTransactionResource(tx, resourceArn);
if (!transactions.remove(transactionId, tx)) {
throw transactionNotFound(transactionId);
}
try {
tx.connection.commit();
} catch (SQLException e) {
throw databaseError(e);
} finally {
closeQuietly(tx.connection);
}
}
ObjectNode response = objectMapper.createObjectNode();
response.put("transactionStatus", "Transaction Committed");
return response;
}
public ObjectNode rollbackTransaction(JsonNode request) {
String transactionId = requiredText(request, "transactionId");
String resourceArn = requiredText(request, "resourceArn");
requiredText(request, "secretArn");
TransactionContext tx = transaction(transactionId);
synchronized (tx) {
requireActiveTransaction(transactionId, tx);
validateTransactionResource(tx, resourceArn);
if (!transactions.remove(transactionId, tx)) {
throw transactionNotFound(transactionId);
}
try {
tx.connection.rollback();
} catch (SQLException e) {
throw databaseError(e);
} finally {
closeQuietly(tx.connection);
}
}
ObjectNode response = objectMapper.createObjectNode();
response.put("transactionStatus", "Rollback Complete");
return response;
}
private ObjectNode executeOnConnection(Connection connection, String sql, boolean includeMetadata) throws SQLException {
try (Statement statement = connection.createStatement()) {
boolean hasResultSet = statement.execute(sql);
ObjectNode response = objectMapper.createObjectNode();
if (hasResultSet) {
try (ResultSet rs = statement.getResultSet()) {
ResultSetMetaData meta = rs.getMetaData();
if (includeMetadata) {
response.set("columnMetadata", columnMetadata(meta));
}
response.set("records", records(rs, meta));
}
response.put("numberOfRecordsUpdated", 0L);
} else {
int updateCount = statement.getUpdateCount();
response.set("records", objectMapper.createArrayNode());
response.put("numberOfRecordsUpdated", Math.max(updateCount, 0));
}
return response;
}
}
private ArrayNode columnMetadata(ResultSetMetaData meta) throws SQLException {
ArrayNode columns = objectMapper.createArrayNode();
for (int i = 1; i <= meta.getColumnCount(); i++) {
ObjectNode column = objectMapper.createObjectNode();
String name = meta.getColumnLabel(i);
if (name == null || name.isBlank()) {
name = meta.getColumnName(i);
}
column.put("name", name);
columns.add(column);
}
return columns;
}
private ArrayNode records(ResultSet rs, ResultSetMetaData meta) throws SQLException {
ArrayNode records = objectMapper.createArrayNode();
int columnCount = meta.getColumnCount();
while (rs.next()) {
ArrayNode row = objectMapper.createArrayNode();
for (int i = 1; i <= columnCount; i++) {
row.add(RdsDataFieldMapper.toField(objectMapper, rs.getObject(i), meta.getColumnType(i)));
}
records.add(row);
}
return records;
}
private Credentials credentials(JsonNode request, RdsDataResourceResolver.DatabaseTarget target, String region) {
String secretArn = textOrNull(request, "secretArn");
if (secretArn != null && !secretArn.isBlank()) {
try {
SecretVersion secret = secretsManagerService.getSecretValue(secretArn, null, null, region);
Credentials fromSecret = parseSecretCredentials(secret.getSecretString());
if (fromSecret != null) {
return fromSecret;
}
} catch (AwsException e) {
LOG.debugv("Falling back to RDS master credentials for Data API secret {0}: {1}",
secretArn, e.getMessage());
}
}
String username = target.username() != null && !target.username().isBlank() ? target.username() : "root";
return new Credentials(username, target.password());
}
private Credentials parseSecretCredentials(String secretString) {
if (secretString == null || secretString.isBlank()) {
return null;
}
try {
JsonNode secret = objectMapper.readTree(secretString);
String username = textOrNull(secret, "username");
if (username == null) {
username = textOrNull(secret, "user");
}
String password = textOrNull(secret, "password");
if (username != null && password != null) {
return new Credentials(username, password);
}
} catch (Exception e) {
LOG.debugv("Could not parse RDS Data API secret credentials: {0}", e.getMessage());
}
return null;
}
private String databaseName(JsonNode request, RdsDataResourceResolver.DatabaseTarget target) {
String database = textOrNull(request, "database");
if (database != null && !database.isBlank()) {
return database;
}
if (target.databaseName() != null && !target.databaseName().isBlank()) {
return target.databaseName();
}
throw new AwsException("BadRequestException", "database is required.", 400);
}
private TransactionContext transaction(String transactionId) {
cleanupExpiredTransactions();
TransactionContext tx = transactions.get(transactionId);
if (tx == null) {
throw transactionNotFound(transactionId);
}
return tx;
}
private static AwsException transactionNotFound(String transactionId) {
return new AwsException("TransactionNotFoundException",
"Transaction " + transactionId + " was not found.", 404);
}
private void requireActiveTransaction(String transactionId, TransactionContext tx) {
if (transactions.get(transactionId) != tx) {
throw transactionNotFound(transactionId);
}
}
private void cleanupExpiredTransactions() {
Instant now = Instant.now();
transactions.forEach((id, tx) -> {
if (tx.expiresAt.isBefore(now)) {
synchronized (tx) {
if (tx.expiresAt.isBefore(now) && transactions.remove(id, tx)) {
rollbackQuietly(tx.connection);
closeQuietly(tx.connection);
}
}
}
});
}
private void cleanupExpiredTransactionsSafely() {
try {
cleanupExpiredTransactions();
} catch (Exception e) {
LOG.warn("Failed to clean up expired RDS Data API transactions", e);
}
}
private void validateTransactionIdentity(TransactionContext tx, JsonNode request) {
validateTransactionResource(tx, requiredText(request, "resourceArn"));
String database = textOrNull(request, "database");
if (database != null && !database.isBlank() && !database.equals(tx.database)) {
throw transactionNotFound(tx.id);
}
}
private void validateTransactionResource(TransactionContext tx, String resourceArn) {
if (resourceArn.equals(tx.resourceArn)) {
return;
}
RdsDataResourceResolver.DatabaseTarget target;
try {
target = resourceResolver.resolve(resourceArn);
} catch (AwsException e) {
throw transactionNotFound(tx.id);
}
if (target == null || !target.arn().equals(tx.resourceArn)) {
throw transactionNotFound(tx.id);
}
}
private static void rollbackQuietly(Connection connection) {
try {
connection.rollback();
} catch (SQLException ignored) {
}
}
private static void closeQuietly(Connection connection) {
try {
connection.close();
} catch (SQLException ignored) {
}
}
private static void rejectUnsupportedOptions(JsonNode request) {
rejectSqlParameters(request);
rejectFormattedRecords(request);
rejectResultSetOptions(request);
}
private static void rejectSqlParameters(JsonNode request) {
JsonNode parameters = request.get("parameters");
if (parameters != null && (!parameters.isArray() || !parameters.isEmpty())) {
throw new AwsException("BadRequestException",
"SqlParameter binding is not supported by this local RDS Data API implementation.", 400);
}
}
private static void rejectFormattedRecords(JsonNode request) {
String formatRecordsAs = textOrNull(request, "formatRecordsAs");
if (formatRecordsAs != null && !formatRecordsAs.isBlank()
&& !"NONE".equalsIgnoreCase(formatRecordsAs)) {
throw new AwsException("BadRequestException",
"formattedRecords is not supported by this local RDS Data API implementation.", 400);
}
}
private static void rejectResultSetOptions(JsonNode request) {
JsonNode resultSetOptions = request.get("resultSetOptions");
if (resultSetOptions != null && !resultSetOptions.isNull()
&& (!resultSetOptions.isObject() || !resultSetOptions.isEmpty())) {
throw new AwsException("BadRequestException",
"resultSetOptions is not supported by this local RDS Data API implementation.", 400);
}
}
private static String requiredText(JsonNode request, String name) {
String value = textOrNull(request, name);
if (value == null || value.isBlank()) {
throw new AwsException("BadRequestException", name + " is required.", 400);
}
return value;
}
private static String textOrNull(JsonNode request, String name) {
JsonNode node = request.get(name);
if (node == null || node.isNull()) {
return null;
}
return node.asText();
}
private static AwsException databaseError(SQLException e) {
return new AwsException("DatabaseErrorException", e.getMessage(), 400);
}
private static final class TransactionContext {
private final String id;
private final Connection connection;
private final String resourceArn;
private final String database;
private volatile Instant expiresAt;
private TransactionContext(String id, Connection connection, String resourceArn, String database, Duration ttl) {
this.id = id;
this.connection = connection;
this.resourceArn = resourceArn;
this.database = database;
refresh(ttl);
}
private void refresh(Duration ttl) {
this.expiresAt = Instant.now().plus(ttl);
}
}
private record Credentials(String username, String password) {
}
}