feat(rds): model DB proxies and their target groups (#1813)

* feat(rds): model DB proxies and their target groups

Add DB proxies as first-class RDS resources for both the RDS Query API
and CloudFormation:

- RdsService: two persisted stores plus the proxy lifecycle
  (create/register-targets/describe/delete). A proxy exposes a bare-host
  endpoint on the engine family's default port; in non-mock mode
  registering a target starts an auth relay (via RdsProxyManager) that
  forwards 1:1 to the target cluster/instance, re-armed on restart.
- RdsQueryHandler: CreateDBProxy, DeleteDBProxy, RegisterDBProxyTargets,
  DescribeDBProxyTargetGroups, DescribeDBProxyTargets, and a real
  DescribeDBProxies listing (2014-10-31 XML shapes).
- AwsQueryController: route the six DBProxy actions to RDS.
- CloudFormation: provision/delete AWS::RDS::DBProxy and
  AWS::RDS::DBProxyTargetGroup.

This models DB proxies for provisioning and discovery; it does not add
real connection pooling (the relay forwards 1:1), so it does not close
#1679.

* fix(rds): reserve DB proxy port so same-engine proxies get distinct ports

createDbProxy used the engine family's default port (5432/3306/1433)
directly without reserving it, so two proxies for the same engine got
the identical port and the second relay failed to bind in non-mock
mode. Reserve the default port via reserveOrAllocateProxyPort, falling
back to an allocated pool port when it is already taken — the first
proxy keeps the clean bare-host default port, later ones get a distinct
port, and the persisted port stays canonical across restarts.

* fix(rds): harden DB proxy lifecycle compatibility

* fix(rds): complete DB proxy compatibility hardening

* fix(rds): make DB proxy lifecycle rollback-safe

* fix(rds): default omitted proxy target group

* test(dynamodb): retain Quarkus port for cleanup

---------

Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
This commit is contained in:
Alex BannaandAlexander Banna authored and GitHub committed 2026-08-14 23:34:56 -05:00
1 parent 42a79a7fd7
commit e4010ec12f
38 files changed
+9734 -546

No files matched your search

@@ -4,28 +4,39 @@ import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.DescribeSubnetsResponse;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.ConnectionPoolConfigurationInfo;
import software.amazon.awssdk.services.rds.model.CreateDbProxyResponse;
import software.amazon.awssdk.services.rds.model.CreateDbSubnetGroupResponse;
import software.amazon.awssdk.services.rds.model.DBProxyTarget;
import software.amazon.awssdk.services.rds.model.DescribeDbSubnetGroupsResponse;
import software.amazon.awssdk.services.rds.model.DescribeOrderableDbInstanceOptionsResponse;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("RDS Control Plane")
class RdsControlPlaneTest {
private static final Logger LOG = Logger.getLogger(RdsControlPlaneTest.class.getName());
private static RdsClient rds;
private static String subnetGroupName;
private static String proxyName;
private static List<String> subnetIds;
@BeforeAll
static void setup() {
rds = TestFixtures.rdsClient();
subnetGroupName = TestFixtures.uniqueName("rds-subnets");
proxyName = TestFixtures.uniqueName("rds-proxy");
try (Ec2Client ec2 = TestFixtures.ec2Client()) {
DescribeSubnetsResponse response = ec2.describeSubnets();
subnetIds = response.subnets().stream()
@@ -40,9 +51,15 @@ class RdsControlPlaneTest {
@AfterAll
static void cleanup() {
if (rds != null) {
try {
rds.deleteDBProxy(b -> b.dbProxyName(proxyName));
} catch (Exception e) {
LOG.log(Level.WARNING, "Failed to clean up RDS DB proxy " + proxyName, e);
}
try {
rds.deleteDBSubnetGroup(b -> b.dbSubnetGroupName(subnetGroupName));
} catch (Exception ignored) {
} catch (Exception e) {
LOG.log(Level.WARNING, "Failed to clean up RDS subnet group " + subnetGroupName, e);
}
rds.close();
}
@@ -80,4 +97,319 @@ class RdsControlPlaneTest {
assertThat(response.orderableDBInstanceOptions().get(0).engineVersion()).isEqualTo("16.14");
assertThat(response.orderableDBInstanceOptions().get(0).dbInstanceClass()).isEqualTo("db.t4g.small");
}
@Test
void sdkRoundTripsDbProxyAndItsDefaultTargetGroup() {
var created = rds.createDBProxy(b -> b
.dbProxyName(proxyName)
.engineFamily("POSTGRESQL")
.roleArn("arn:aws:iam::000000000000:role/rds-proxy-test")
.vpcSubnetIds(subnetIds)
.vpcSecurityGroupIds("sg-proxy-test")
.endpointNetworkType("IPV4")
.targetConnectionNetworkType("IPV4")
.requireTLS(true)
.debugLogging(true)
.idleClientTimeout(120)
.auth(a -> a.authScheme("SECRETS")
.secretArn("arn:aws:secretsmanager:us-east-1:000000000000:secret:rds-proxy-test")
.iamAuth("DISABLED")
.clientPasswordAuthType("POSTGRES_SCRAM_SHA_256")
.description("compatibility credentials"))
.tags(t -> t.key("owner").value("compatibility")));
assertThat(created.dbProxy().dbProxyName()).isEqualTo(proxyName);
assertThat(created.dbProxy().engineFamily()).hasToString("POSTGRESQL");
assertThat(created.dbProxy().requireTLS()).isTrue();
assertThat(created.dbProxy().debugLogging()).isTrue();
assertThat(created.dbProxy().idleClientTimeout()).isEqualTo(120);
assertThat(created.dbProxy().endpointNetworkTypeAsString()).isEqualTo("IPV4");
assertThat(created.dbProxy().targetConnectionNetworkTypeAsString()).isEqualTo("IPV4");
assertThat(created.dbProxy().vpcId()).isNotBlank();
assertThat(created.dbProxy().vpcSecurityGroupIds()).containsExactly("sg-proxy-test");
assertThat(created.dbProxy().auth()).singleElement().satisfies(auth -> {
assertThat(auth.clientPasswordAuthTypeAsString()).isEqualTo("POSTGRES_SCRAM_SHA_256");
assertThat(auth.description()).isEqualTo("compatibility credentials");
});
var targetGroups = rds.describeDBProxyTargetGroups(b -> b.dbProxyName(proxyName));
assertThat(targetGroups.targetGroups()).singleElement().satisfies(targetGroup -> {
assertThat(targetGroup.targetGroupName()).isEqualTo("default");
assertThat(targetGroup.isDefault()).isTrue();
assertThat(targetGroup.targetGroupArn()).contains(":target-group:prx-tg-");
});
var tags = rds.listTagsForResource(b -> b.resourceName(created.dbProxy().dbProxyArn()));
assertThat(tags.tagList()).singleElement().satisfies(tag -> {
assertThat(tag.key()).isEqualTo("owner");
assertThat(tag.value()).isEqualTo("compatibility");
});
}
@Test
void sdkRoundTripsIamDefaultAuthAndProxyUpdates() {
String mutableProxyName = TestFixtures.uniqueName("rds-proxy-mutable");
try {
var created = rds.createDBProxy(b -> b
.dbProxyName(mutableProxyName)
.engineFamily("MYSQL")
.roleArn("arn:aws:iam::000000000000:role/rds-proxy-initial")
.vpcSubnetIds(subnetIds)
.vpcSecurityGroupIds("sg-proxy-initial")
.defaultAuthScheme("IAM_AUTH")
.requireTLS(true)
.debugLogging(false)
.idleClientTimeout(300));
assertThat(created.dbProxy().defaultAuthScheme()).isEqualTo("IAM_AUTH");
assertThat(created.dbProxy().auth()).isEmpty();
var modified = rds.modifyDBProxy(b -> b
.dbProxyName(mutableProxyName)
.roleArn("arn:aws:iam::000000000000:role/rds-proxy-updated")
.securityGroups("sg-proxy-updated-a", "sg-proxy-updated-b")
.requireTLS(false)
.debugLogging(true)
.idleClientTimeout(600));
assertThat(modified.dbProxy().dbProxyName()).isEqualTo(mutableProxyName);
assertThat(modified.dbProxy().defaultAuthScheme()).isEqualTo("IAM_AUTH");
assertThat(modified.dbProxy().roleArn())
.isEqualTo("arn:aws:iam::000000000000:role/rds-proxy-updated");
assertThat(modified.dbProxy().vpcSecurityGroupIds())
.containsExactly("sg-proxy-updated-a", "sg-proxy-updated-b");
assertThat(modified.dbProxy().requireTLS()).isFalse();
assertThat(modified.dbProxy().debugLogging()).isTrue();
assertThat(modified.dbProxy().idleClientTimeout()).isEqualTo(600);
assertThat(modified.dbProxy().updatedDate()).isAfterOrEqualTo(created.dbProxy().updatedDate());
var described = rds.describeDBProxies(b -> b.dbProxyName(mutableProxyName));
assertThat(described.dbProxies()).singleElement().satisfies(proxy -> {
assertThat(proxy.defaultAuthScheme()).isEqualTo("IAM_AUTH");
assertThat(proxy.auth()).isEmpty();
assertThat(proxy.roleArn())
.isEqualTo("arn:aws:iam::000000000000:role/rds-proxy-updated");
assertThat(proxy.vpcSecurityGroupIds())
.containsExactly("sg-proxy-updated-a", "sg-proxy-updated-b");
assertThat(proxy.requireTLS()).isFalse();
assertThat(proxy.debugLogging()).isTrue();
assertThat(proxy.idleClientTimeout()).isEqualTo(600);
});
var modifiedTargetGroup = rds.modifyDBProxyTargetGroup(b -> b
.dbProxyName(mutableProxyName)
.targetGroupName("default")
.connectionPoolConfig(pool -> pool
.maxConnectionsPercent(73)
.maxIdleConnectionsPercent(41)
.connectionBorrowTimeout(37)
.initQuery("SET sql_mode='STRICT_ALL_TABLES'")
.sessionPinningFilters("EXCLUDE_VARIABLE_SETS")));
assertPoolConfiguration(modifiedTargetGroup.dbProxyTargetGroup().connectionPoolConfig());
var describedTargetGroups = rds.describeDBProxyTargetGroups(b -> b
.dbProxyName(mutableProxyName)
.targetGroupName("default"));
assertThat(describedTargetGroups.targetGroups()).singleElement().satisfies(targetGroup ->
assertPoolConfiguration(targetGroup.connectionPoolConfig()));
} finally {
deleteProxy(rds, mutableProxyName);
}
}
@Test
void sdkScopesTheSameDbProxyNameBySignedRegion() {
String regionalProxyName = TestFixtures.uniqueName("rds-proxy-regional");
try (RdsClient east = rdsClient(Region.US_EAST_1);
RdsClient west = rdsClient(Region.US_WEST_2)) {
var eastProxy = createIamProxy(east, regionalProxyName);
var westProxy = createIamProxy(west, regionalProxyName);
assertThat(eastProxy.dbProxy().dbProxyArn()).contains(":rds:us-east-1:");
assertThat(westProxy.dbProxy().dbProxyArn()).contains(":rds:us-west-2:");
assertThat(westProxy.dbProxy().dbProxyArn()).isNotEqualTo(eastProxy.dbProxy().dbProxyArn());
assertThat(east.describeDBProxies(b -> b.dbProxyName(regionalProxyName)).dbProxies())
.singleElement()
.satisfies(proxy -> assertThat(proxy.dbProxyArn()).contains(":rds:us-east-1:"));
assertThat(west.describeDBProxies(b -> b.dbProxyName(regionalProxyName)).dbProxies())
.singleElement()
.satisfies(proxy -> assertThat(proxy.dbProxyArn()).contains(":rds:us-west-2:"));
} finally {
try (RdsClient east = rdsClient(Region.US_EAST_1);
RdsClient west = rdsClient(Region.US_WEST_2)) {
deleteProxy(east, regionalProxyName);
deleteProxy(west, regionalProxyName);
}
}
}
@Test
void sdkScopesTheSameDbInstanceNameBySignedRegion() {
String regionalInstanceName = TestFixtures.uniqueName("rds-db-regional");
try (RdsClient east = rdsClient(Region.US_EAST_1);
RdsClient west = rdsClient(Region.US_WEST_2)) {
var eastInstance = createDbInstance(east, regionalInstanceName, "east-secret");
var westInstance = createDbInstance(west, regionalInstanceName, "west-secret");
assertThat(eastInstance.dbInstance().dbInstanceArn()).contains(":rds:us-east-1:");
assertThat(westInstance.dbInstance().dbInstanceArn()).contains(":rds:us-west-2:");
assertThat(westInstance.dbInstance().dbInstanceArn())
.isNotEqualTo(eastInstance.dbInstance().dbInstanceArn());
east.modifyDBInstance(b -> b
.dbInstanceIdentifier(regionalInstanceName)
.masterUserPassword("east-updated"));
assertThat(east.describeDBInstances(b -> b
.dbInstanceIdentifier(regionalInstanceName)).dbInstances())
.singleElement()
.satisfies(instance -> assertThat(instance.dbInstanceArn())
.contains(":rds:us-east-1:"));
assertThat(west.describeDBInstances(b -> b
.dbInstanceIdentifier(regionalInstanceName)).dbInstances())
.singleElement()
.satisfies(instance -> assertThat(instance.dbInstanceArn())
.contains(":rds:us-west-2:"));
east.deleteDBInstance(b -> b
.dbInstanceIdentifier(regionalInstanceName)
.skipFinalSnapshot(true));
assertThat(east.describeDBInstances().dbInstances())
.noneMatch(instance -> regionalInstanceName.equals(
instance.dbInstanceIdentifier()));
assertThat(west.describeDBInstances(b -> b
.dbInstanceIdentifier(regionalInstanceName)).dbInstances())
.singleElement();
} finally {
try (RdsClient east = rdsClient(Region.US_EAST_1);
RdsClient west = rdsClient(Region.US_WEST_2)) {
deleteDbInstance(east, regionalInstanceName);
deleteDbInstance(west, regionalInstanceName);
}
}
}
@Test
void sdkRegistersDescribesAndDeregistersDbProxyInstanceTarget() {
String targetProxyName = TestFixtures.uniqueName("rds-proxy-target");
String targetInstanceName = TestFixtures.uniqueName("rds-db-target");
boolean registered = false;
try {
var instance = createDbInstance(rds, targetInstanceName, "target-secret");
rds.createDBProxy(b -> b
.dbProxyName(targetProxyName)
.engineFamily("POSTGRESQL")
.roleArn("arn:aws:iam::000000000000:role/rds-proxy-target")
.vpcSubnetIds(subnetIds)
.auth(a -> a.authScheme("SECRETS")
.secretArn("arn:aws:secretsmanager:us-east-1:000000000000:secret:rds-proxy-target")
.iamAuth("DISABLED")));
var registerResponse = rds.registerDBProxyTargets(b -> b
.dbProxyName(targetProxyName)
.dbInstanceIdentifiers(targetInstanceName));
registered = true;
assertThat(registerResponse.dbProxyTargets()).singleElement().satisfies(target ->
assertInstanceProxyTarget(target, targetInstanceName,
instance.dbInstance().dbInstanceArn()));
var described = rds.describeDBProxyTargets(b -> b
.dbProxyName(targetProxyName));
assertThat(described.targets()).singleElement().satisfies(target ->
assertInstanceProxyTarget(target, targetInstanceName,
instance.dbInstance().dbInstanceArn()));
rds.deregisterDBProxyTargets(b -> b
.dbProxyName(targetProxyName)
.dbInstanceIdentifiers(targetInstanceName));
registered = false;
assertThat(rds.describeDBProxyTargets(b -> b
.dbProxyName(targetProxyName)).targets()).isEmpty();
} finally {
if (registered) {
deregisterProxyTarget(rds, targetProxyName, targetInstanceName);
}
deleteProxy(rds, targetProxyName);
deleteDbInstance(rds, targetInstanceName);
}
}
private static CreateDbProxyResponse createIamProxy(RdsClient client, String name) {
return client.createDBProxy(b -> b
.dbProxyName(name)
.engineFamily("POSTGRESQL")
.roleArn("arn:aws:iam::000000000000:role/rds-proxy-regional")
.vpcSubnetIds(subnetIds)
.defaultAuthScheme("IAM_AUTH"));
}
private static software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse createDbInstance(
RdsClient client, String name, String password) {
return client.createDBInstance(b -> b
.dbInstanceIdentifier(name)
.engine("postgres")
.engineVersion("16.3")
.masterUsername("admin")
.masterUserPassword(password)
.dbName("app")
.dbInstanceClass("db.t3.micro")
.allocatedStorage(20));
}
private static RdsClient rdsClient(Region region) {
return RdsClient.builder()
.endpointOverride(TestFixtures.endpoint())
.region(region)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("test", "test")))
.build();
}
private static void deleteProxy(RdsClient client, String name) {
try {
client.deleteDBProxy(b -> b.dbProxyName(name));
} catch (Exception e) {
LOG.log(Level.WARNING, "Failed to clean up RDS DB proxy " + name, e);
}
}
private static void deleteDbInstance(RdsClient client, String name) {
try {
client.deleteDBInstance(b -> b
.dbInstanceIdentifier(name)
.skipFinalSnapshot(true));
} catch (Exception e) {
LOG.log(Level.FINE, "RDS DB instance already absent during cleanup " + name, e);
}
}
private static void deregisterProxyTarget(
RdsClient client, String proxyName, String instanceName) {
try {
client.deregisterDBProxyTargets(b -> b
.dbProxyName(proxyName)
.targetGroupName("default")
.dbInstanceIdentifiers(instanceName));
} catch (Exception e) {
LOG.log(Level.FINE,
"RDS DB proxy target already absent during cleanup " + proxyName, e);
}
}
private static void assertInstanceProxyTarget(
DBProxyTarget target, String instanceName, String instanceArn) {
assertThat(target.typeAsString()).isEqualTo("RDS_INSTANCE");
assertThat(target.rdsResourceId()).isEqualTo(instanceName);
assertThat(target.targetArn()).isEqualTo(instanceArn);
assertThat(target.targetHealth().stateAsString()).isEqualTo("AVAILABLE");
}
private static void assertPoolConfiguration(ConnectionPoolConfigurationInfo pool) {
assertThat(pool.maxConnectionsPercent()).isEqualTo(73);
assertThat(pool.maxIdleConnectionsPercent()).isEqualTo(41);
assertThat(pool.connectionBorrowTimeout()).isEqualTo(37);
assertThat(pool.initQuery()).isEqualTo("SET sql_mode='STRICT_ALL_TABLES'");
assertThat(pool.sessionPinningFilters()).containsExactly("EXCLUDE_VARIABLE_SETS");
}
}
+31 -2
View File
@@ -38,7 +38,15 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou
| `ModifyDBClusterParameterGroup` | - |
| `DescribeDBClusterParameters` | - |
| `DescribeDBSnapshots` | - |
| `DescribeDBProxies` | - |
| `DescribeDBProxies` | List DB proxies |
| `CreateDBProxy` | Create a DB proxy |
| `ModifyDBProxy` | Update mutable DB proxy authentication, logging, timeout, TLS, role, and security-group settings |
| `DeleteDBProxy` | Delete a DB proxy |
| `RegisterDBProxyTargets` | Register a cluster or instance as a proxy target |
| `DeregisterDBProxyTargets` | Remove a cluster or instance from a proxy target group |
| `DescribeDBProxyTargetGroups` | List a proxy's target groups |
| `ModifyDBProxyTargetGroup` | Update target-group connection-pool configuration |
| `DescribeDBProxyTargets` | List a proxy target group's registered targets |
| `DescribeDBClusterSnapshots` | - |
| `AddTagsToResource` | Add tags to a DB resource |
| `ListTagsForResource` | List tags for a DB resource |
@@ -51,7 +59,7 @@ RDS Data API (`rds-data`) is documented separately because it uses REST JSON rou
|---|---|---|
| `FLOCI_SERVICES_RDS_ENABLED` | `true` | Enable or disable the service |
| `FLOCI_SERVICES_RDS_MOCK` | `false` | `true` = metadata only (no Docker container or auth proxy) |
| `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7000` | First host port in the RDS proxy range |
| `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7001` | First host port in the RDS proxy range |
| `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last host port in the RDS proxy range |
| `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port |
| `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Docker image for PostgreSQL instances |
@@ -102,6 +110,27 @@ services:
deleted under mock leave their containers and volumes behind, and resources created in mock
mode are restored with fresh, empty containers when loaded in real mode.
!!! warning "DB proxy endpoint routing"
DB proxy control-plane resources and target registration are modeled, but Floci's current
single-host TCP relay cannot expose multiple same-engine DB proxies as distinct AWS-style bare
hostnames on the same engine-default port. The standard Docker Compose mapping also exposes
only the `7001-7099` instance/cluster proxy range, not `1433`, `3306`, or `5432`. Use mock mode
for DB proxy provisioning workflows until a dedicated endpoint-routing design is implemented.
!!! note "DB proxy control-plane settings"
Proxy and target-group settings are persisted and round-trip through the RDS Query API and
CloudFormation. Pool sizing, borrow timeout, idle timeout, TLS, init-query, and session-pinning
settings are currently control-plane metadata; the TCP relay does not yet implement those data-plane
behaviors. `DefaultAuthScheme=IAM_AUTH` is supported for control-plane workflows, but a real-mode
proxy using that scheme cannot register a target until backend IAM authentication is implemented.
Requests to `RegisterDBProxyTargets`, `DeregisterDBProxyTargets`, and
`DescribeDBProxyTargets` use the `default` target group when `TargetGroupName` is omitted,
matching the RDS API contract.
DB proxies currently support `IPV4` for both endpoint and target connections; `IPV6` and `DUAL`
endpoint networking require additional listener and Docker-network support.
## Examples
```bash
@@ -368,7 +368,10 @@ public class AwsQueryController {
"AddTagsToResource", "ListTagsForResource", "RemoveTagsFromResource",
"CreateDBCluster", "DescribeDBClusters", "DeleteDBCluster", "ModifyDBCluster",
"CreateDBParameterGroup", "DescribeDBParameterGroups",
"DeleteDBParameterGroup", "ModifyDBParameterGroup", "DescribeDBParameters"
"DeleteDBParameterGroup", "ModifyDBParameterGroup", "DescribeDBParameters",
"DescribeDBProxies", "CreateDBProxy", "ModifyDBProxy", "DeleteDBProxy",
"RegisterDBProxyTargets", "DeregisterDBProxyTargets",
"DescribeDBProxyTargetGroups", "ModifyDBProxyTargetGroup", "DescribeDBProxyTargets"
);
private static final Set<String> CLOUDFORMATION_ACTIONS = Set.of(
@@ -221,6 +221,50 @@ public class ContainerLifecycleManager {
}
}
/**
* Stops and removes a container, failing when Docker cannot confirm removal.
*
* <p>Most emulator shutdown paths intentionally use best-effort cleanup through
* {@link #stopAndRemove(String, Closeable)}. Resource-deletion paths that must retain their
* persisted record for a retry use this stricter variant instead.
*/
public void stopAndRemoveStrict(String containerId, Closeable logStream) {
LOG.infov("Stopping container {0}", containerId);
if (logStream != null) {
try {
logStream.close();
} catch (Exception e) {
LOG.debugv("Error closing log stream: {0}", e.getMessage());
}
}
Exception stopFailure = null;
try {
dockerClient.stopContainerCmd(containerId).withTimeout(5).exec();
} catch (NotFoundException e) {
LOG.debugv("Container {0} not found (already removed)", containerId);
return;
} catch (Exception e) {
stopFailure = e;
LOG.warnv("Error stopping container {0}: {1}", containerId, e.getMessage());
}
try {
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
LOG.debugv("Removed container {0}", containerId);
} catch (NotFoundException e) {
// Already gone, so cleanup succeeded.
} catch (Exception e) {
IllegalStateException cleanupFailure = new IllegalStateException(
"Failed to remove container " + containerId, e);
if (stopFailure != null) {
cleanupFailure.addSuppressed(stopFailure);
}
throw cleanupFailure;
}
}
/**
* Creates a named volume if it does not already exist. Idempotent — safe to call on every
* container start. Labels the volume {@code floci=true} so
@@ -359,6 +403,18 @@ public class ContainerLifecycleManager {
}
}
/** Removes a named Docker volume and propagates failures so callers can retry safely. */
public void removeVolumeStrict(String volumeName) {
try {
dockerClient.removeVolumeCmd(volumeName).exec();
LOG.debugv("Removed volume {0}", volumeName);
} catch (NotFoundException e) {
// Already gone — nothing to do.
} catch (Exception e) {
throw new IllegalStateException("Failed to remove volume " + volumeName, e);
}
}
/**
* Finds an existing container by name.
*
@@ -459,6 +515,25 @@ public class ContainerLifecycleManager {
}
}
/**
* Removes a container by name, failing when Docker cannot confirm removal.
*
* <p>Callers that are about to reuse a fixed container name must use this variant so a
* daemon failure cannot be mistaken for successful stale-container cleanup.
*
* @param name the container name to remove
*/
public void removeIfExistsStrict(String name) {
try {
dockerClient.removeContainerCmd(name).withForce(true).exec();
LOG.infov("Removed stale container {0}", name);
} catch (NotFoundException e) {
// Not found means the fixed name is available.
} catch (Exception e) {
throw new IllegalStateException("Failed to remove stale container " + name, e);
}
}
/**
* Returns whether the container is currently running. A missing container is treated as
* not-running; any other Docker error (e.g. an inspect timeout under daemon overload) is also
@@ -65,7 +65,14 @@ public class ContainerLogStreamer {
*/
public Closeable attach(String containerId, String logGroup, String logStream,
String region, String logPrefix) {
ensureLogGroupAndStream(logGroup, logStream, region);
return attachForAccount(
null, containerId, logGroup, logStream, region, logPrefix);
}
public Closeable attachForAccount(
String accountId, String containerId, String logGroup, String logStream,
String region, String logPrefix) {
ensureLogGroupAndStreamForAccount(accountId, logGroup, logStream, region);
// Trim trailing whitespace and drop blank lines, then fan each reassembled line out to the
// console logger and CloudWatch Logs.
@@ -73,7 +80,7 @@ public class ContainerLogStreamer {
String trimmed = line.stripTrailing();
if (!trimmed.isEmpty()) {
LOG.infov("[{0}] {1}", logPrefix, trimmed);
forwardToCloudWatchLogs(logGroup, logStream, region, trimmed);
forwardToCloudWatchLogs(accountId, logGroup, logStream, region, trimmed);
}
};
@@ -111,12 +118,17 @@ public class ContainerLogStreamer {
*/
public ResultCallback.Adapter<Frame> execLogCallback(String logGroup, String logStream,
String region, String logPrefix) {
return frameCallback(logGroup, logStream, region, logPrefix);
return frameCallback(null, logGroup, logStream, region, logPrefix);
}
/** Shared frame handling for both the container log stream and exec streams. */
private ResultCallback.Adapter<Frame> frameCallback(String logGroup, String logStream,
String region, String logPrefix) {
/**
* Shared frame handling for both the container log stream and exec streams.
*
* @param accountId account that owns the destination log stream, or {@code null} for the
* default account
*/
private ResultCallback.Adapter<Frame> frameCallback(String accountId, String logGroup, String logStream,
String region, String logPrefix) {
return new ResultCallback.Adapter<>() {
@Override
public void onNext(Frame frame) {
@@ -126,7 +138,7 @@ public class ContainerLogStreamer {
String line = new String(frame.getPayload(), StandardCharsets.UTF_8).stripTrailing();
if (!line.isEmpty()) {
LOG.infov("[{0}] {1}", logPrefix, line);
forwardToCloudWatchLogs(logGroup, logStream, region, line);
forwardToCloudWatchLogs(accountId, logGroup, logStream, region, line);
}
}
};
@@ -136,8 +148,14 @@ public class ContainerLogStreamer {
* Creates a CloudWatch log group and stream if they don't already exist.
*/
public void ensureLogGroupAndStream(String logGroup, String logStream, String region) {
ensureLogGroupAndStreamForAccount(null, logGroup, logStream, region);
}
public void ensureLogGroupAndStreamForAccount(
String accountId, String logGroup, String logStream, String region) {
try {
cloudWatchLogsService.createLogGroup(logGroup, null, null, region);
cloudWatchLogsService.createLogGroupForAccount(
accountId, logGroup, null, null, region);
} catch (AwsException ignored) {
// Already exists
} catch (Exception e) {
@@ -145,7 +163,8 @@ public class ContainerLogStreamer {
}
try {
cloudWatchLogsService.createLogStream(logGroup, logStream, region);
cloudWatchLogsService.createLogStreamForAccount(
accountId, logGroup, logStream, region);
} catch (AwsException ignored) {
// Already exists
} catch (Exception e) {
@@ -164,15 +183,17 @@ public class ContainerLogStreamer {
}
public void streamToCloudWatchLogs(String logGroup, String logStream, String region, String line) {
forwardToCloudWatchLogs(logGroup, logStream, region, line);
forwardToCloudWatchLogs(null, logGroup, logStream, region, line);
}
private void forwardToCloudWatchLogs(String logGroup, String logStream, String region, String line) {
private void forwardToCloudWatchLogs(
String accountId, String logGroup, String logStream, String region, String line) {
try {
Map<String, Object> event = new HashMap<>();
event.put("timestamp", System.currentTimeMillis());
event.put("message", line);
cloudWatchLogsService.putLogEvents(logGroup, logStream, List.of(event), region);
cloudWatchLogsService.putLogEventsForAccount(
accountId, logGroup, logStream, List.of(event), region);
} catch (Exception e) {
LOG.debugv("Could not forward log line to CloudWatch Logs: {0}", e.getMessage());
}
@@ -102,6 +102,15 @@ public final class ContainerStorageHelper {
String fallbackId,
String internalMount) {
String volumeName = resourceName(config, service, volumeId, fallbackId);
applyNamedVolume(builder, lifecycleManager, volumeName, internalMount);
}
/** Mounts a persisted, exact Docker volume name without applying namespace rules again. */
public static void applyNamedVolume(
ContainerBuilder.Builder builder,
ContainerLifecycleManager lifecycleManager,
String volumeName,
String internalMount) {
lifecycleManager.ensureVolume(volumeName);
builder.withNamedVolume(volumeName, internalMount);
}
@@ -121,6 +130,14 @@ public final class ContainerStorageHelper {
String volumeId,
String fallbackId) {
String volumeName = resourceName(config, service, volumeId, fallbackId);
removeNamedVolume(config, lifecycleManager, volumeName);
}
/** Removes or retains a persisted, exact Docker volume name according to storage policy. */
public static void removeNamedVolume(
EmulatorConfig config,
ContainerLifecycleManager lifecycleManager,
String volumeName) {
boolean isMemory = "memory".equals(config.storage().mode());
if (isMemory || config.storage().pruneVolumesOnDelete()) {
lifecycleManager.removeVolume(volumeName);
@@ -129,6 +146,22 @@ public final class ContainerStorageHelper {
}
}
/**
* Removes an exact named volume according to storage policy and propagates Docker failures.
*/
public static void removeNamedVolumeStrict(
EmulatorConfig config,
ContainerLifecycleManager lifecycleManager,
String volumeName) {
boolean isMemory = "memory".equals(config.storage().mode());
if (isMemory || config.storage().pruneVolumesOnDelete()) {
lifecycleManager.removeVolumeStrict(volumeName);
} else {
LOG.infov("Retained Docker volume {0}. Remove manually: docker volume rm {0}",
volumeName);
}
}
/**
* Ensures the host data directory exists for host-path mode (absolute paths only).
* Called by managers in their legacy host-path code paths.
@@ -6,6 +6,7 @@ import jakarta.enterprise.inject.Instance;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -113,6 +114,21 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
return delegate.scan(k -> true);
}
/**
* Returns every stored entry with its raw delegate key intact.
*
* <p>Startup migrations use this form when the key itself is part of a resource's identity.
* Keeping the account prefix prevents a value stored under a corrupt or foreign key from
* being re-keyed solely from mutable fields in the value.
*/
public Map<String, V> scanAllAccountsWithRawKeys() {
Map<String, V> result = new LinkedHashMap<>();
for (String rawKey : delegate.keys()) {
delegate.get(rawKey).ifPresent(value -> result.put(rawKey, value));
}
return result;
}
/**
* Returns all entries across every account as a map of logical-key (account prefix stripped)
* to value. Entries without a slash-prefixed account segment are skipped.
@@ -171,6 +187,97 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
return delegate.get(accountId + "/" + key);
}
/**
* Returns an explicitly scoped entry, or safely migrates a matching legacy unscoped entry.
*
* <p>The caller-supplied predicate must establish that the legacy value belongs to the
* destination account. This opt-in path avoids {@link #get(String)}'s request-context fallback,
* which cannot validate ownership before migrating old data.
*/
public synchronized Optional<V> getForAccountMigratingLegacy(
String accountId, String key, Predicate<V> legacyOwner) {
Optional<V> scoped = getForAccount(accountId, key);
if (scoped.isPresent()) {
return scoped;
}
Optional<V> legacy = delegate.get(key).filter(legacyOwner);
if (legacy.isEmpty()) {
return Optional.empty();
}
delegate.put(accountId + "/" + key, legacy.get());
delegate.delete(key);
return legacy;
}
/**
* Returns an explicitly scoped entry, or safely migrates one of several older key shapes.
*
* <p>This is intended for resources whose logical key gained another scope component after
* account isolation was already deployed. Both account-prefixed legacy keys and older
* unprefixed keys are considered, but only when {@code legacyOwner} proves that the stored
* value belongs to the requested destination scope. The destination is written before the
* source is removed so a failed write cannot orphan the legacy value.
*/
public synchronized Optional<V> getForAccountMigratingLegacyKeys(
String accountId, String key, List<String> legacyKeys,
Predicate<V> legacyOwner) {
return getForAccountMigratingLegacyKeys(
accountId, key, legacyKeys, legacyOwner, true);
}
/**
* Variant of {@link #getForAccountMigratingLegacyKeys(String, String, List, Predicate)} that
* can exclude unprefixed legacy keys when the value cannot prove account ownership.
*/
public synchronized Optional<V> getForAccountMigratingLegacyKeys(
String accountId, String key, List<String> legacyKeys,
Predicate<V> legacyOwner, boolean includeUnscopedLegacyKeys) {
String destinationKey = accountId + "/" + key;
Set<String> candidates = new LinkedHashSet<>();
if (includeUnscopedLegacyKeys) {
candidates.add(key);
}
if (legacyKeys != null) {
for (String legacyKey : legacyKeys) {
if (legacyKey == null || legacyKey.isBlank()) {
continue;
}
candidates.add(accountId + "/" + legacyKey);
if (includeUnscopedLegacyKeys) {
candidates.add(legacyKey);
}
}
}
candidates.remove(destinationKey);
Optional<V> scoped = delegate.get(destinationKey);
if (scoped.isPresent()) {
if (scoped.filter(legacyOwner).isEmpty()) {
// A value under the destination key that does not belong to the requested
// scope is corrupt. Preserve both it and every legacy candidate so the
// caller fails closed without deleting the recoverable owned value.
return Optional.empty();
}
for (String candidateKey : candidates) {
if (delegate.get(candidateKey).filter(legacyOwner).isPresent()) {
delegate.delete(candidateKey);
}
}
return scoped;
}
for (String candidateKey : candidates) {
Optional<V> legacy = delegate.get(candidateKey).filter(legacyOwner);
if (legacy.isEmpty()) {
continue;
}
delegate.put(destinationKey, legacy.get());
delegate.delete(candidateKey);
return legacy;
}
return Optional.empty();
}
public void putForAccount(String accountId, String key, V value) {
delegate.put(accountId + "/" + key, value);
}
@@ -184,6 +291,13 @@ public class AccountAwareStorageBackend<V> implements StorageBackend<String, V>
return delegate.scan(k -> k.startsWith(prefix) && keyFilter.test(k.substring(prefix.length())));
}
/** Returns unprefixed pre-account values that satisfy an ownership predicate. */
public List<V> scanUnscopedLegacy(Predicate<V> legacyOwner) {
return delegate.scan(k -> !k.contains("/")).stream()
.filter(legacyOwner)
.toList();
}
public Set<String> keysForAccount(String accountId) {
String prefix = accountId + "/";
return delegate.keys().stream()
@@ -43,6 +43,7 @@ import io.github.hectorvent.floci.services.ecs.EcsService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
import io.github.hectorvent.floci.services.eks.EksService;
import io.github.hectorvent.floci.services.eks.model.CreateClusterRequest;
import io.github.hectorvent.floci.services.eks.model.Nodegroup;
@@ -400,11 +401,16 @@ public class CloudFormationResourceProvisioner {
case "AWS::EC2::Instance" -> provisionEc2Instance(resource, properties, engine, region);
// RDS. DBInstance/DBCluster start real RDS containers (same as the direct API).
case "AWS::RDS::DBSubnetGroup" -> provisionDbSubnetGroup(resource, properties, engine, stackName, region);
case "AWS::RDS::DBParameterGroup" -> provisionDbParameterGroup(resource, properties, engine, stackName);
case "AWS::RDS::DBParameterGroup" ->
provisionDbParameterGroup(resource, properties, engine, stackName, region);
case "AWS::RDS::DBClusterParameterGroup" ->
provisionDbClusterParameterGroup(resource, properties, engine, stackName);
provisionDbClusterParameterGroup(
resource, properties, engine, stackName, region);
case "AWS::RDS::DBInstance" -> provisionDbInstance(resource, properties, engine, stackName, region);
case "AWS::RDS::DBCluster" -> provisionDbCluster(resource, properties, engine, stackName, region);
case "AWS::RDS::DBProxy" -> provisionDbProxy(resource, properties, engine, region);
case "AWS::RDS::DBProxyTargetGroup" ->
provisionDbProxyTargetGroup(resource, properties, engine, region);
case "AWS::EKS::Cluster" -> provisionEksCluster(resource, properties, engine, stackName);
case "AWS::EKS::Nodegroup" -> provisionEksNodegroup(resource, properties, engine, stackName);
case "AWS::Logs::LogGroup" -> provisionLogGroup(resource, properties, engine, region, accountId, stackName);
@@ -614,11 +620,16 @@ public class CloudFormationResourceProvisioner {
case "AWS::KinesisFirehose::DeliveryStream" -> firehoseService.deleteDeliveryStream(physicalId);
case "AWS::EC2::SecurityGroup" -> ec2Service.deleteSecurityGroup(region, physicalId);
case "AWS::EC2::Instance" -> ec2Service.terminateInstances(region, List.of(physicalId));
case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId);
case "AWS::RDS::DBCluster" -> rdsService.deleteDbCluster(physicalId);
case "AWS::RDS::DBSubnetGroup" -> rdsService.deleteDbSubnetGroup(physicalId);
case "AWS::RDS::DBParameterGroup" -> rdsService.deleteDbParameterGroup(physicalId);
case "AWS::RDS::DBClusterParameterGroup" -> rdsService.deleteDbClusterParameterGroup(physicalId);
case "AWS::RDS::DBInstance" -> rdsService.deleteDbInstance(physicalId, region);
case "AWS::RDS::DBCluster" -> rdsService.deleteDbCluster(physicalId, region);
case "AWS::RDS::DBProxy" -> deleteDbProxySafe(physicalId, region);
case "AWS::RDS::DBProxyTargetGroup" -> clearDbProxyTargetGroupSafe(physicalId, region);
case "AWS::RDS::DBSubnetGroup" ->
rdsService.deleteDbSubnetGroup(physicalId, region);
case "AWS::RDS::DBParameterGroup" ->
rdsService.deleteDbParameterGroup(physicalId, region);
case "AWS::RDS::DBClusterParameterGroup" ->
rdsService.deleteDbClusterParameterGroup(physicalId, region);
case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId);
case "AWS::Logs::LogGroup" -> logsService.deleteLogGroup(physicalId, region);
case "AWS::Kinesis::Stream" -> kinesisService.deleteStream(physicalId, region);
@@ -1339,7 +1350,7 @@ public class CloudFormationResourceProvisioner {
}
private void provisionDbParameterGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String stackName) {
String stackName, String region) {
String name = resolveOptional(props, "DBParameterGroupName", engine);
if (name == null || name.isBlank()) {
name = generatePhysicalName(stackName, r.getLogicalId(), 60, true);
@@ -1347,13 +1358,15 @@ public class CloudFormationResourceProvisioner {
String family = resolveOptional(props, "Family", engine);
String description = firstNonBlank(resolveOptional(props, "Description", engine),
"Managed by CloudFormation");
var group = rdsService.createDbParameterGroup(name, family, description);
var group = rdsService.createDbParameterGroup(
name, family, description, region);
r.setPhysicalId(group.getDbParameterGroupName());
r.getAttributes().put("DBParameterGroupName", group.getDbParameterGroupName());
}
private void provisionDbClusterParameterGroup(StackResource r, JsonNode props,
CloudFormationTemplateEngine engine, String stackName) {
CloudFormationTemplateEngine engine,
String stackName, String region) {
String name = resolveOptional(props, "DBClusterParameterGroupName", engine);
if (name == null || name.isBlank()) {
name = generatePhysicalName(stackName, r.getLogicalId(), 60, true);
@@ -1361,7 +1374,8 @@ public class CloudFormationResourceProvisioner {
String family = resolveOptional(props, "Family", engine);
String description = firstNonBlank(resolveOptional(props, "Description", engine),
"Managed by CloudFormation");
var group = rdsService.createDbClusterParameterGroup(name, family, description);
var group = rdsService.createDbClusterParameterGroup(
name, family, description, region);
r.setPhysicalId(group.getDbClusterParameterGroupName());
r.getAttributes().put("DBClusterParameterGroupName", group.getDbClusterParameterGroupName());
}
@@ -1427,6 +1441,184 @@ public class CloudFormationResourceProvisioner {
}
}
private void provisionDbProxy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
String region) {
String name = resolveOptional(props, "DBProxyName", engine);
String engineFamily = resolveOptional(props, "EngineFamily", engine);
String defaultAuthScheme = resolveOptional(props, "DefaultAuthScheme", engine);
if (defaultAuthScheme == null) {
defaultAuthScheme = "NONE";
} else if (defaultAuthScheme.isBlank()) {
throw new AwsException("InvalidParameterValue",
"DefaultAuthScheme must be NONE or IAM_AUTH.", 400);
}
String endpointNetworkType = resolveOptional(props, "EndpointNetworkType", engine);
String targetConnectionNetworkType = resolveOptional(
props, "TargetConnectionNetworkType", engine);
validateIpv4DbProxyNetworkType(endpointNetworkType,
"EndpointNetworkType", true, "IPV4, IPV6, or DUAL");
validateIpv4DbProxyNetworkType(targetConnectionNetworkType,
"TargetConnectionNetworkType", false, "IPV4 or IPV6");
boolean requireTls = parseBoolProp(props, "RequireTLS", engine);
boolean debugLogging = parseBoolProp(props, "DebugLogging", engine);
Integer configuredIdleClientTimeout = parseOptionalIntProp(props, "IdleClientTimeout", engine);
int idleClientTimeout = configuredIdleClientTimeout != null ? configuredIdleClientTimeout : 1800;
String roleArn = resolveOptional(props, "RoleArn", engine);
List<String> subnetIds = resolveStringList(props, "VpcSubnetIds", engine);
if (subnetIds.stream().distinct().count() < 2) {
throw new AwsException("InvalidParameterValue",
"AWS::RDS::DBProxy VpcSubnetIds must contain at least two distinct subnet IDs.", 400);
}
List<String> sgIds = resolveStringList(props, "VpcSecurityGroupIds", engine);
List<DbProxyAuth> auth = parseProxyAuth(props, engine);
boolean iamAuth = "IAM_AUTH".equalsIgnoreCase(defaultAuthScheme)
|| auth.stream().anyMatch(a ->
"REQUIRED".equalsIgnoreCase(a.getIamAuth())
|| "ENABLED".equalsIgnoreCase(a.getIamAuth()));
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
var proxy = r.getPhysicalId() == null
? rdsService.createDbProxy(name, engineFamily, requireTls, iamAuth,
defaultAuthScheme, roleArn, subnetIds, sgIds, auth, idleClientTimeout,
debugLogging, tags, region)
: updateDbProxy(r, name, engineFamily, defaultAuthScheme, requireTls,
idleClientTimeout, debugLogging, roleArn, subnetIds, sgIds, auth, tags, region);
r.setPhysicalId(proxy.getDbProxyName()); // Ref -> DBProxyName
r.getAttributes().put("Endpoint", proxy.getEndpoint()); // GetAtt "Endpoint" (bare host)
r.getAttributes().put("DBProxyArn", proxy.getDbProxyArn());
if (proxy.getVpcId() != null) {
r.getAttributes().put("VpcId", proxy.getVpcId());
}
}
private io.github.hectorvent.floci.services.rds.model.DbProxy updateDbProxy(
StackResource resource, String name, String engineFamily, String defaultAuthScheme,
boolean requireTls, int idleClientTimeout, boolean debugLogging, String roleArn,
List<String> subnetIds, List<String> securityGroupIds, List<DbProxyAuth> auth,
Map<String, String> tags, String region) {
var existing = rdsService.getDbProxy(resource.getPhysicalId(), region);
if (!Objects.equals(existing.getDbProxyName(), name)
|| engineFamily == null
|| !existing.getEngineFamily().equalsIgnoreCase(engineFamily)
|| !Set.copyOf(existing.getVpcSubnetIds()).equals(Set.copyOf(subnetIds))) {
throw new AwsException("UnsupportedOperation",
"Changing DBProxyName, EngineFamily, or VpcSubnetIds requires CloudFormation "
+ "replacement, which is not yet supported by Floci.", 400);
}
return rdsService.modifyDbProxy(existing.getDbProxyName(), defaultAuthScheme, auth,
requireTls, idleClientTimeout, debugLogging, roleArn,
securityGroupIds, tags, region);
}
private void provisionDbProxyTargetGroup(StackResource r, JsonNode props,
CloudFormationTemplateEngine engine, String region) {
String dbProxyName = resolveOptional(props, "DBProxyName", engine);
String targetGroupName = resolveOptional(props, "TargetGroupName", engine);
if (!"default".equals(targetGroupName)) {
throw new AwsException("InvalidParameterValue",
"AWS::RDS::DBProxyTargetGroup TargetGroupName must be default.", 400);
}
List<String> clusterIds = resolveStringList(props, "DBClusterIdentifiers", engine);
List<String> instanceIds = resolveStringList(props, "DBInstanceIdentifiers", engine);
Integer maxConn = null;
Integer maxIdle = null;
Integer connectionBorrowTimeout = null;
String initQuery = null;
List<String> sessionPinningFilters = List.of();
if (props != null && props.has("ConnectionPoolConfigurationInfo")) {
JsonNode cpc = props.get("ConnectionPoolConfigurationInfo");
maxConn = parseOptionalIntProp(cpc, "MaxConnectionsPercent", engine);
maxIdle = parseOptionalIntProp(cpc, "MaxIdleConnectionsPercent", engine);
connectionBorrowTimeout = parseOptionalIntProp(cpc, "ConnectionBorrowTimeout", engine);
initQuery = resolveOptional(cpc, "InitQuery", engine);
sessionPinningFilters = resolveStringList(cpc, "SessionPinningFilters", engine);
}
if (maxIdle != null && maxConn == null) {
throw new AwsException("InvalidParameterValue",
"MaxConnectionsPercent is required when MaxIdleConnectionsPercent is specified.",
400);
}
if (r.getPhysicalId() != null) {
var existing = rdsService.getDbProxyTargetGroupByArn(r.getPhysicalId(), region);
if (!Objects.equals(existing.getDbProxyName(), dbProxyName)
|| !Objects.equals(existing.getTargetGroupName(), targetGroupName)) {
throw new AwsException("UnsupportedOperation",
"Changing DBProxyName or TargetGroupName requires CloudFormation replacement.",
400);
}
}
var proxy = rdsService.getDbProxy(dbProxyName, region);
int effectiveMaxConnections = maxConn != null ? maxConn
: ("SQLSERVER".equals(proxy.getEngineFamily()) ? 10 : 100);
int effectiveMaxIdle = maxIdle != null ? maxIdle : effectiveMaxConnections / 2;
int effectiveBorrowTimeout = connectionBorrowTimeout != null ? connectionBorrowTimeout : 120;
var tg = rdsService.reconcileDbProxyTargetGroup(
dbProxyName, targetGroupName, clusterIds, instanceIds,
effectiveMaxConnections, effectiveMaxIdle, effectiveBorrowTimeout,
initQuery, sessionPinningFilters, region);
r.setPhysicalId(tg.getTargetGroupArn()); // Ref -> TargetGroupArn
r.getAttributes().put("TargetGroupArn", tg.getTargetGroupArn());
r.getAttributes().put("DBProxyName", tg.getDbProxyName());
}
private List<DbProxyAuth> parseProxyAuth(JsonNode props, CloudFormationTemplateEngine engine) {
List<DbProxyAuth> auth = new ArrayList<>();
if (props != null && props.has("Auth") && props.get("Auth").isArray()) {
for (JsonNode a : props.get("Auth")) {
DbProxyAuth entry = new DbProxyAuth();
entry.setAuthScheme(resolveOptional(a, "AuthScheme", engine));
entry.setSecretArn(resolveOptional(a, "SecretArn", engine));
entry.setIamAuth(resolveOptional(a, "IAMAuth", engine));
entry.setClientPasswordAuthType(resolveOptional(a, "ClientPasswordAuthType", engine));
entry.setDescription(resolveOptional(a, "Description", engine));
entry.setUserName(resolveOptional(a, "UserName", engine));
auth.add(entry);
}
}
return auth;
}
private void validateIpv4DbProxyNetworkType(
String value, String propertyName, boolean dualAllowed, String validValues) {
if (value == null) {
return;
}
if ("IPV4".equalsIgnoreCase(value)) {
return;
}
boolean supportedAwsValue = "IPV6".equalsIgnoreCase(value)
|| (dualAllowed && "DUAL".equalsIgnoreCase(value));
if (value.isBlank() || !supportedAwsValue) {
throw new AwsException("InvalidParameterValue",
propertyName + " must be " + validValues + ".", 400);
}
throw new AwsException("UnsupportedOperation",
propertyName + " " + value.toUpperCase()
+ " is not supported because Floci currently exposes IPv4 proxy networking only.",
400);
}
private void deleteDbProxySafe(String name, String region) {
try {
rdsService.deleteDbProxy(name, region);
} catch (AwsException e) {
if (!"DBProxyNotFoundFault".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("DB proxy already gone, treating as deleted: {0}", name);
}
}
private void clearDbProxyTargetGroupSafe(String targetGroupArn, String region) {
try {
rdsService.clearDbProxyTargetGroupByArn(targetGroupArn, region);
} catch (AwsException e) {
if (!"DBProxyTargetGroupNotFoundFault".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("DB proxy target group already gone, treating as deleted: {0}", targetGroupArn);
}
}
private static String firstNonBlank(String value, String fallback) {
return (value == null || value.isBlank()) ? fallback : value;
}
@@ -1443,6 +1635,18 @@ public class CloudFormationResourceProvisioner {
}
}
private Integer parseOptionalIntProp(JsonNode props, String name, CloudFormationTemplateEngine engine) {
String value = resolveOptional(props, name, engine);
if (value == null || value.isBlank()) {
return null;
}
try {
return Integer.valueOf(value.trim());
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue", name + " must be an integer.", 400);
}
}
private boolean parseBoolProp(JsonNode props, String name, CloudFormationTemplateEngine engine) {
return Boolean.parseBoolean(resolveOptional(props, name, engine));
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
@@ -21,6 +22,7 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongSupplier;
@@ -131,11 +133,23 @@ public class CloudWatchLogsService {
public void createLogGroup(String name, Integer retentionInDays, Map<String, String> tags,
boolean deletionProtectionEnabled, String region) {
createLogGroupForAccount(null, name, retentionInDays, tags, deletionProtectionEnabled, region);
}
public void createLogGroupForAccount(
String accountId, String name, Integer retentionInDays,
Map<String, String> tags, String region) {
createLogGroupForAccount(accountId, name, retentionInDays, tags, false, region);
}
public void createLogGroupForAccount(
String accountId, String name, Integer retentionInDays,
Map<String, String> tags, boolean deletionProtectionEnabled, String region) {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidParameterException", "logGroupName is required.", 400);
}
String key = groupKey(region, name);
if (groupStore.get(key).isPresent()) {
if (getForAccount(groupStore, accountId, key).isPresent()) {
throw new AwsException("ResourceAlreadyExistsException",
"The specified log group already exists: " + name, 400);
}
@@ -147,7 +161,7 @@ public class CloudWatchLogsService {
if (tags != null) {
group.setTags(new HashMap<>(tags));
}
groupStore.put(key, group);
putForAccount(groupStore, accountId, key, group);
LOG.infov("Created log group: {0} in region {1}", name, region);
}
@@ -255,13 +269,18 @@ public class CloudWatchLogsService {
// ──────────────────────────── Log Streams ────────────────────────────
public void createLogStream(String groupName, String streamName, String region) {
createLogStreamForAccount(null, groupName, streamName, region);
}
public void createLogStreamForAccount(
String accountId, String groupName, String streamName, String region) {
String groupKey = groupKey(region, groupName);
groupStore.get(groupKey)
getForAccount(groupStore, accountId, groupKey)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"The specified log group does not exist: " + groupName, 400));
String streamKey = streamKey(region, groupName, streamName);
if (streamStore.get(streamKey).isPresent()) {
if (getForAccount(streamStore, accountId, streamKey).isPresent()) {
throw new AwsException("ResourceAlreadyExistsException",
"The specified log stream already exists: " + streamName, 400);
}
@@ -271,7 +290,7 @@ public class CloudWatchLogsService {
stream.setLogStreamName(streamName);
stream.setCreatedTime(System.currentTimeMillis());
stream.setUploadSequenceToken(UUID.randomUUID().toString());
streamStore.put(streamKey, stream);
putForAccount(streamStore, accountId, streamKey, stream);
LOG.infov("Created log stream: {0}/{1}", groupName, streamName);
}
@@ -311,8 +330,14 @@ public class CloudWatchLogsService {
public String putLogEvents(String groupName, String streamName,
List<Map<String, Object>> events, String region) {
return putLogEventsForAccount(null, groupName, streamName, events, region);
}
public String putLogEventsForAccount(
String accountId, String groupName, String streamName,
List<Map<String, Object>> events, String region) {
String streamKey = streamKey(region, groupName, streamName);
LogStream stream = streamStore.get(streamKey)
LogStream stream = getForAccount(streamStore, accountId, streamKey)
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
"The specified log stream does not exist: " + streamName, 400));
@@ -333,7 +358,7 @@ public class CloudWatchLogsService {
logEvent.setSequence(ingestionSequence.incrementAndGet());
String eventKey = eventKey(region, groupName, streamName, ts, logEvent.getEventId());
eventStore.put(eventKey, logEvent);
putForAccount(eventStore, accountId, eventKey, logEvent);
totalBytes += msg.getBytes().length + 26; // approx overhead
if (minTs == null || ts < minTs) { minTs = ts; }
@@ -353,11 +378,32 @@ public class CloudWatchLogsService {
stream.setStoredBytes(stream.getStoredBytes() + totalBytes);
String nextToken = UUID.randomUUID().toString();
stream.setUploadSequenceToken(nextToken);
streamStore.put(streamKey, stream);
putForAccount(streamStore, accountId, streamKey, stream);
return nextToken;
}
private <V> Optional<V> getForAccount(
StorageBackend<String, V> store, String accountId, String key) {
if (accountId != null && store instanceof AccountAwareStorageBackend<?> rawAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<V> aware = (AccountAwareStorageBackend<V>) rawAware;
return aware.getForAccount(accountId, key);
}
return store.get(key);
}
private <V> void putForAccount(
StorageBackend<String, V> store, String accountId, String key, V value) {
if (accountId != null && store instanceof AccountAwareStorageBackend<?> rawAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<V> aware = (AccountAwareStorageBackend<V>) rawAware;
aware.putForAccount(accountId, key, value);
return;
}
store.put(key, value);
}
public record LogEventsResult(List<LogEvent> events, String nextForwardToken, String nextBackwardToken) {}
public LogEventsResult getLogEvents(String groupName, String streamName,
@@ -11,6 +11,10 @@ import io.github.hectorvent.floci.services.rds.model.DbEndpoint;
import io.github.hectorvent.floci.services.rds.model.DbInstance;
import io.github.hectorvent.floci.services.rds.model.DbInstanceStatus;
import io.github.hectorvent.floci.services.rds.model.DbParameterGroup;
import io.github.hectorvent.floci.services.rds.model.DbProxy;
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
import io.github.hectorvent.floci.services.rds.model.DbProxyTarget;
import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -50,35 +54,43 @@ public class RdsQueryHandler {
try {
return switch (action) {
case "CreateDBInstance" -> handleCreateDbInstance(params, region);
case "DescribeDBInstances" -> handleDescribeDbInstances(params);
case "DeleteDBInstance" -> handleDeleteDbInstance(params);
case "ModifyDBInstance" -> handleModifyDbInstance(params);
case "RebootDBInstance" -> handleRebootDbInstance(params);
case "DescribeDBInstances" -> handleDescribeDbInstances(params, region);
case "DeleteDBInstance" -> handleDeleteDbInstance(params, region);
case "ModifyDBInstance" -> handleModifyDbInstance(params, region);
case "RebootDBInstance" -> handleRebootDbInstance(params, region);
case "DescribeOrderableDBInstanceOptions" -> handleDescribeOrderableDbInstanceOptions(params);
case "CreateDBSubnetGroup" -> handleCreateDbSubnetGroup(params, region);
case "DescribeDBSubnetGroups" -> handleDescribeDbSubnetGroups(params, region);
case "ModifyDBSubnetGroup" -> handleModifyDbSubnetGroup(params, region);
case "DeleteDBSubnetGroup" -> handleDeleteDbSubnetGroup(params);
case "DeleteDBSubnetGroup" -> handleDeleteDbSubnetGroup(params, region);
case "CreateDBCluster" -> handleCreateDbCluster(params, region);
case "DescribeDBClusters" -> handleDescribeDbClusters(params);
case "DeleteDBCluster" -> handleDeleteDbCluster(params);
case "ModifyDBCluster" -> handleModifyDbCluster(params);
case "CreateDBParameterGroup" -> handleCreateDbParameterGroup(params);
case "DescribeDBParameterGroups" -> handleDescribeDbParameterGroups(params);
case "DeleteDBParameterGroup" -> handleDeleteDbParameterGroup(params);
case "ModifyDBParameterGroup" -> handleModifyDbParameterGroup(params);
case "DescribeDBParameters" -> handleDescribeDbParameters(params);
case "CreateDBClusterParameterGroup" -> handleCreateDbClusterParameterGroup(params);
case "DescribeDBClusterParameterGroups" -> handleDescribeDbClusterParameterGroups(params);
case "DeleteDBClusterParameterGroup" -> handleDeleteDbClusterParameterGroup(params);
case "ModifyDBClusterParameterGroup" -> handleModifyDbClusterParameterGroup(params);
case "DescribeDBClusterParameters" -> handleDescribeDbClusterParameters(params);
case "DescribeDBClusters" -> handleDescribeDbClusters(params, region);
case "DeleteDBCluster" -> handleDeleteDbCluster(params, region);
case "ModifyDBCluster" -> handleModifyDbCluster(params, region);
case "CreateDBParameterGroup" -> handleCreateDbParameterGroup(params, region);
case "DescribeDBParameterGroups" -> handleDescribeDbParameterGroups(params, region);
case "DeleteDBParameterGroup" -> handleDeleteDbParameterGroup(params, region);
case "ModifyDBParameterGroup" -> handleModifyDbParameterGroup(params, region);
case "DescribeDBParameters" -> handleDescribeDbParameters(params, region);
case "CreateDBClusterParameterGroup" -> handleCreateDbClusterParameterGroup(params, region);
case "DescribeDBClusterParameterGroups" -> handleDescribeDbClusterParameterGroups(params, region);
case "DeleteDBClusterParameterGroup" -> handleDeleteDbClusterParameterGroup(params, region);
case "ModifyDBClusterParameterGroup" -> handleModifyDbClusterParameterGroup(params, region);
case "DescribeDBClusterParameters" -> handleDescribeDbClusterParameters(params, region);
case "DescribeDBSnapshots" -> handleDescribeDbSnapshots(params);
case "DescribeDBProxies" -> handleDescribeDbProxies(params);
case "DescribeDBProxies" -> handleDescribeDbProxies(params, region);
case "CreateDBProxy" -> handleCreateDbProxy(params, region);
case "ModifyDBProxy" -> handleModifyDbProxy(params, region);
case "DeleteDBProxy" -> handleDeleteDbProxy(params, region);
case "RegisterDBProxyTargets" -> handleRegisterDbProxyTargets(params, region);
case "DeregisterDBProxyTargets" -> handleDeregisterDbProxyTargets(params, region);
case "DescribeDBProxyTargetGroups" -> handleDescribeDbProxyTargetGroups(params, region);
case "ModifyDBProxyTargetGroup" -> handleModifyDbProxyTargetGroup(params, region);
case "DescribeDBProxyTargets" -> handleDescribeDbProxyTargets(params, region);
case "DescribeDBClusterSnapshots" -> handleDescribeDbClusterSnapshots(params);
case "AddTagsToResource" -> handleAddTagsToResource(params);
case "ListTagsForResource" -> handleListTagsForResource(params);
case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(params);
case "AddTagsToResource" -> handleAddTagsToResource(params, region);
case "ListTagsForResource" -> handleListTagsForResource(params, region);
case "RemoveTagsFromResource" -> handleRemoveTagsFromResource(params, region);
default -> AwsQueryResponse.error("UnsupportedOperation",
"Operation " + action + " is not supported.", AwsNamespaces.RDS, 400);
};
@@ -137,7 +149,8 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbInstances(MultivaluedMap<String, String> params) {
private Response handleDescribeDbInstances(
MultivaluedMap<String, String> params, String region) {
String identifier = params.getFirst("DBInstanceIdentifier");
String filterId = identifier;
if (filterId == null || filterId.isBlank()) {
@@ -146,12 +159,12 @@ public class RdsQueryHandler {
try {
Collection<DbInstance> result;
if (filterId != null && !filterId.isBlank()) {
result = service.listDbInstances(filterId);
result = service.listDbInstances(filterId, region);
} else {
List<String> resourceIds = extractRdsFilterValues(params, "dbi-resource-id");
result = resourceIds.isEmpty()
? service.listDbInstances(null)
: service.listDbInstancesByDbiResourceIds(resourceIds);
? service.listDbInstances(null, region)
: service.listDbInstancesByDbiResourceIds(resourceIds, region);
}
// AWS parity: the DBInstanceIdentifier PARAMETER faults with
// DBInstanceNotFound when no instance matches, while the
@@ -171,14 +184,15 @@ public class RdsQueryHandler {
}
}
private Response handleDeleteDbInstance(MultivaluedMap<String, String> params) {
private Response handleDeleteDbInstance(
MultivaluedMap<String, String> params, String region) {
String id = params.getFirst("DBInstanceIdentifier");
if (id == null || id.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400);
}
try {
DbInstance instance = service.getDbInstance(id);
service.deleteDbInstance(id);
DbInstance instance = service.getDbInstance(id, region);
service.deleteDbInstance(id, region);
String result = dbInstanceXml(instance);
return Response.ok(AwsQueryResponse.envelope("DeleteDBInstance", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -186,7 +200,8 @@ public class RdsQueryHandler {
}
}
private Response handleModifyDbInstance(MultivaluedMap<String, String> params) {
private Response handleModifyDbInstance(
MultivaluedMap<String, String> params, String region) {
String id = params.getFirst("DBInstanceIdentifier");
if (id == null || id.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400);
@@ -198,7 +213,8 @@ public class RdsQueryHandler {
try {
List<String> vpcSecurityGroupIds = vpcSecurityGroupIds(params);
DbInstance instance = service.modifyDbInstance(
id, newPassword, iamEnabled, dbSubnetGroupName, vpcSecurityGroupIds);
id, newPassword, iamEnabled, dbSubnetGroupName,
vpcSecurityGroupIds, region);
String result = dbInstanceXml(instance);
return Response.ok(AwsQueryResponse.envelope("ModifyDBInstance", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -230,21 +246,21 @@ public class RdsQueryHandler {
AwsNamespaces.RDS, xml.build())).build();
}
private Response handleAddTagsToResource(MultivaluedMap<String, String> params) {
private Response handleAddTagsToResource(MultivaluedMap<String, String> params, String region) {
String resourceName = params.getFirst("ResourceName");
try {
service.addTagsToResource(resourceName, parseTags(params));
service.addTagsToResource(resourceName, parseTags(params), region);
return Response.ok(AwsQueryResponse.envelope("AddTagsToResource", AwsNamespaces.RDS, "")).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
}
}
private Response handleListTagsForResource(MultivaluedMap<String, String> params) {
private Response handleListTagsForResource(MultivaluedMap<String, String> params, String region) {
String resourceName = params.getFirst("ResourceName");
try {
XmlBuilder xml = new XmlBuilder().start("TagList");
writeTags(xml, service.listTagsForResource(resourceName));
writeTags(xml, service.listTagsForResource(resourceName, region));
xml.end("TagList");
return Response.ok(AwsQueryResponse.envelope("ListTagsForResource", AwsNamespaces.RDS, xml.build())).build();
} catch (AwsException e) {
@@ -252,10 +268,10 @@ public class RdsQueryHandler {
}
}
private Response handleRemoveTagsFromResource(MultivaluedMap<String, String> params) {
private Response handleRemoveTagsFromResource(MultivaluedMap<String, String> params, String region) {
String resourceName = params.getFirst("ResourceName");
try {
service.removeTagsFromResource(resourceName, memberList(params, "TagKeys"));
service.removeTagsFromResource(resourceName, memberList(params, "TagKeys"), region);
return Response.ok(AwsQueryResponse.envelope("RemoveTagsFromResource", AwsNamespaces.RDS, "")).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
@@ -310,27 +326,29 @@ public class RdsQueryHandler {
}
}
private Response handleDeleteDbSubnetGroup(MultivaluedMap<String, String> params) {
private Response handleDeleteDbSubnetGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBSubnetGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue",
"DBSubnetGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
service.deleteDbSubnetGroup(name);
service.deleteDbSubnetGroup(name, region);
return Response.ok(AwsQueryResponse.envelope("DeleteDBSubnetGroup", AwsNamespaces.RDS, "")).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
}
}
private Response handleRebootDbInstance(MultivaluedMap<String, String> params) {
private Response handleRebootDbInstance(
MultivaluedMap<String, String> params, String region) {
String id = params.getFirst("DBInstanceIdentifier");
if (id == null || id.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBInstanceIdentifier is required.", AwsNamespaces.RDS, 400);
}
try {
DbInstance instance = service.rebootDbInstance(id);
DbInstance instance = service.rebootDbInstance(id, region);
String result = dbInstanceXml(instance);
return Response.ok(AwsQueryResponse.envelope("RebootDBInstance", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -372,14 +390,15 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbClusters(MultivaluedMap<String, String> params) {
private Response handleDescribeDbClusters(
MultivaluedMap<String, String> params, String region) {
String identifier = params.getFirst("DBClusterIdentifier");
String filterId = identifier;
if (filterId == null || filterId.isBlank()) {
filterId = extractRdsFilterValue(params, "db-cluster-id");
}
try {
Collection<DbCluster> result = service.listDbClusters(filterId);
Collection<DbCluster> result = service.listDbClusters(filterId, region);
// AWS parity: the DBClusterIdentifier PARAMETER faults with
// DBClusterNotFoundFault when no cluster matches, while the
// db-cluster-id Filters form returns an empty list.
@@ -398,14 +417,15 @@ public class RdsQueryHandler {
}
}
private Response handleDeleteDbCluster(MultivaluedMap<String, String> params) {
private Response handleDeleteDbCluster(
MultivaluedMap<String, String> params, String region) {
String id = params.getFirst("DBClusterIdentifier");
if (id == null || id.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400);
}
try {
DbCluster cluster = service.getDbCluster(id);
service.deleteDbCluster(id);
DbCluster cluster = service.getDbCluster(id, region);
service.deleteDbCluster(id, region);
String result = dbClusterXml(cluster);
return Response.ok(AwsQueryResponse.envelope("DeleteDBCluster", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -413,7 +433,8 @@ public class RdsQueryHandler {
}
}
private Response handleModifyDbCluster(MultivaluedMap<String, String> params) {
private Response handleModifyDbCluster(
MultivaluedMap<String, String> params, String region) {
String id = params.getFirst("DBClusterIdentifier");
if (id == null || id.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterIdentifier is required.", AwsNamespaces.RDS, 400);
@@ -422,7 +443,7 @@ public class RdsQueryHandler {
String iamStr = params.getFirst("EnableIAMDatabaseAuthentication");
Boolean iamEnabled = iamStr != null ? Boolean.parseBoolean(iamStr) : null;
try {
DbCluster cluster = service.modifyDbCluster(id, newPassword, iamEnabled);
DbCluster cluster = service.modifyDbCluster(id, newPassword, iamEnabled, region);
String result = dbClusterXml(cluster);
return Response.ok(AwsQueryResponse.envelope("ModifyDBCluster", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -432,7 +453,8 @@ public class RdsQueryHandler {
// ── Parameter Groups ──────────────────────────────────────────────────────
private Response handleCreateDbParameterGroup(MultivaluedMap<String, String> params) {
private Response handleCreateDbParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBParameterGroupName");
String family = params.getFirst("DBParameterGroupFamily");
String description = params.getFirst("Description");
@@ -440,7 +462,8 @@ public class RdsQueryHandler {
return AwsQueryResponse.error("InvalidParameterValue", "DBParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
DbParameterGroup group = service.createDbParameterGroup(name, family, description);
DbParameterGroup group = service.createDbParameterGroup(
name, family, description, region);
String result = paramGroupXml(group);
return Response.ok(AwsQueryResponse.envelope("CreateDBParameterGroup", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -448,10 +471,11 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbParameterGroups(MultivaluedMap<String, String> params) {
private Response handleDescribeDbParameterGroups(
MultivaluedMap<String, String> params, String region) {
String filterName = params.getFirst("DBParameterGroupName");
try {
Collection<DbParameterGroup> result = service.listDbParameterGroups(filterName);
Collection<DbParameterGroup> result = service.listDbParameterGroups(filterName, region);
XmlBuilder xml = new XmlBuilder().start("DBParameterGroups");
for (DbParameterGroup g : result) {
xml.start("DBParameterGroup").raw(paramGroupInnerXml(g)).end("DBParameterGroup");
@@ -463,20 +487,22 @@ public class RdsQueryHandler {
}
}
private Response handleDeleteDbParameterGroup(MultivaluedMap<String, String> params) {
private Response handleDeleteDbParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
service.deleteDbParameterGroup(name);
service.deleteDbParameterGroup(name, region);
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteDBParameterGroup", AwsNamespaces.RDS)).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
}
}
private Response handleModifyDbParameterGroup(MultivaluedMap<String, String> params) {
private Response handleModifyDbParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBParameterGroupName is required.", AwsNamespaces.RDS, 400);
@@ -493,7 +519,7 @@ public class RdsQueryHandler {
}
}
try {
DbParameterGroup group = service.modifyDbParameterGroup(name, parameters);
DbParameterGroup group = service.modifyDbParameterGroup(name, parameters, region);
String result = new XmlBuilder()
.elem("DBParameterGroupName", group.getDbParameterGroupName())
.build();
@@ -503,13 +529,14 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbParameters(MultivaluedMap<String, String> params) {
private Response handleDescribeDbParameters(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
DbParameterGroup group = service.getDbParameterGroup(name);
DbParameterGroup group = service.getDbParameterGroup(name, region);
XmlBuilder xml = new XmlBuilder().start("Parameters");
for (Map.Entry<String, String> entry : group.getParameters().entrySet()) {
xml.start("member")
@@ -527,7 +554,8 @@ public class RdsQueryHandler {
// ── Cluster Parameter Groups ──────────────────────────────────────────────
private Response handleCreateDbClusterParameterGroup(MultivaluedMap<String, String> params) {
private Response handleCreateDbClusterParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBClusterParameterGroupName");
String family = params.getFirst("DBParameterGroupFamily");
String description = params.getFirst("Description");
@@ -535,7 +563,8 @@ public class RdsQueryHandler {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
DbClusterParameterGroup group = service.createDbClusterParameterGroup(name, family, description);
DbClusterParameterGroup group = service.createDbClusterParameterGroup(
name, family, description, region);
String result = clusterParamGroupXml(group);
return Response.ok(AwsQueryResponse.envelope("CreateDBClusterParameterGroup", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -543,10 +572,12 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbClusterParameterGroups(MultivaluedMap<String, String> params) {
private Response handleDescribeDbClusterParameterGroups(
MultivaluedMap<String, String> params, String region) {
String filterName = params.getFirst("DBClusterParameterGroupName");
try {
Collection<DbClusterParameterGroup> result = service.listDbClusterParameterGroups(filterName);
Collection<DbClusterParameterGroup> result =
service.listDbClusterParameterGroups(filterName, region);
XmlBuilder xml = new XmlBuilder().start("DBClusterParameterGroups");
for (DbClusterParameterGroup g : result) {
xml.start("DBClusterParameterGroup").raw(clusterParamGroupInnerXml(g)).end("DBClusterParameterGroup");
@@ -558,20 +589,22 @@ public class RdsQueryHandler {
}
}
private Response handleDeleteDbClusterParameterGroup(MultivaluedMap<String, String> params) {
private Response handleDeleteDbClusterParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBClusterParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
service.deleteDbClusterParameterGroup(name);
service.deleteDbClusterParameterGroup(name, region);
return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteDBClusterParameterGroup", AwsNamespaces.RDS)).build();
} catch (AwsException e) {
return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus());
}
}
private Response handleModifyDbClusterParameterGroup(MultivaluedMap<String, String> params) {
private Response handleModifyDbClusterParameterGroup(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBClusterParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterParameterGroupName is required.", AwsNamespaces.RDS, 400);
@@ -588,7 +621,8 @@ public class RdsQueryHandler {
}
}
try {
DbClusterParameterGroup group = service.modifyDbClusterParameterGroup(name, parameters);
DbClusterParameterGroup group = service.modifyDbClusterParameterGroup(
name, parameters, region);
String result = new XmlBuilder()
.elem("DBClusterParameterGroupName", group.getDbClusterParameterGroupName())
.build();
@@ -598,13 +632,14 @@ public class RdsQueryHandler {
}
}
private Response handleDescribeDbClusterParameters(MultivaluedMap<String, String> params) {
private Response handleDescribeDbClusterParameters(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBClusterParameterGroupName");
if (name == null || name.isBlank()) {
return AwsQueryResponse.error("InvalidParameterValue", "DBClusterParameterGroupName is required.", AwsNamespaces.RDS, 400);
}
try {
DbClusterParameterGroup group = service.getDbClusterParameterGroup(name);
DbClusterParameterGroup group = service.getDbClusterParameterGroup(name, region);
XmlBuilder xml = new XmlBuilder().start("Parameters");
for (Map.Entry<String, String> entry : group.getParameters().entrySet()) {
xml.start("member")
@@ -630,12 +665,292 @@ public class RdsQueryHandler {
return Response.ok(AwsQueryResponse.envelope("DescribeDBSnapshots", AwsNamespaces.RDS, result)).build();
}
private Response handleDescribeDbProxies(MultivaluedMap<String, String> params) {
// DB proxies are not modeled; return the RDS Query API's wire-accurate empty
// result (empty <DBProxies> wrapper, no <Marker>) so SDK clients complete the
// read instead of failing with UnsupportedOperation.
String result = new XmlBuilder().start("DBProxies").end("DBProxies").build();
return Response.ok(AwsQueryResponse.envelope("DescribeDBProxies", AwsNamespaces.RDS, result)).build();
private Response handleDescribeDbProxies(MultivaluedMap<String, String> params, String region) {
XmlBuilder xml = new XmlBuilder().start("DBProxies");
for (DbProxy p : service.listDbProxies(params.getFirst("DBProxyName"), region)) {
xml.start("member").raw(dbProxyInnerXml(p)).end("member");
}
xml.end("DBProxies");
return Response.ok(AwsQueryResponse.envelope("DescribeDBProxies", AwsNamespaces.RDS, xml.build())).build();
}
private Response handleCreateDbProxy(MultivaluedMap<String, String> params, String region) {
validateIpv4NetworkType(params.getFirst("EndpointNetworkType"),
"EndpointNetworkType", true, "IPV4, IPV6, or DUAL");
validateIpv4NetworkType(params.getFirst("TargetConnectionNetworkType"),
"TargetConnectionNetworkType", false, "IPV4 or IPV6");
String name = params.getFirst("DBProxyName");
String engineFamily = params.getFirst("EngineFamily");
boolean requireTls = "true".equalsIgnoreCase(params.getFirst("RequireTLS"));
boolean debugLogging = "true".equalsIgnoreCase(params.getFirst("DebugLogging"));
int idleClientTimeout = 1800;
String idleClientTimeoutValue = params.getFirst("IdleClientTimeout");
if (idleClientTimeoutValue != null) {
try {
idleClientTimeout = Integer.parseInt(idleClientTimeoutValue);
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue", "IdleClientTimeout must be an integer.", 400);
}
}
String roleArn = params.getFirst("RoleArn");
List<String> subnetIds = memberList(params, "VpcSubnetIds");
List<String> sgIds = memberList(params, "VpcSecurityGroupIds");
List<DbProxyAuth> auth = parseProxyAuth(params);
String defaultAuthScheme = params.getFirst("DefaultAuthScheme");
boolean iamEnabled = auth.stream().anyMatch(a ->
"REQUIRED".equalsIgnoreCase(a.getIamAuth())
|| "ENABLED".equalsIgnoreCase(a.getIamAuth()));
iamEnabled = iamEnabled || "IAM_AUTH".equalsIgnoreCase(defaultAuthScheme);
DbProxy proxy = service.createDbProxy(
name, engineFamily, requireTls, iamEnabled, defaultAuthScheme, roleArn,
subnetIds, sgIds, auth, idleClientTimeout, debugLogging, parseTags(params), region);
String result = new XmlBuilder().start("DBProxy").raw(dbProxyInnerXml(proxy)).end("DBProxy").build();
return Response.ok(AwsQueryResponse.envelope("CreateDBProxy", AwsNamespaces.RDS, result)).build();
}
private Response handleModifyDbProxy(MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBProxyName");
String newName = params.getFirst("NewDBProxyName");
if (newName != null && !newName.isBlank()) {
throw new AwsException("UnsupportedOperation",
"NewDBProxyName is not supported; renaming a persisted proxy requires "
+ "an atomic storage-key migration.", 400);
}
List<DbProxyAuth> auth = hasProxyAuthKeys(params) ? parseProxyAuth(params) : null;
List<String> securityGroups = hasMemberKeys(params, "SecurityGroups")
? memberList(params, "SecurityGroups")
: (hasMemberKeys(params, "VpcSecurityGroupIds")
? vpcSecurityGroupIds(params) : null);
DbProxy proxy = service.modifyDbProxy(
name,
params.getFirst("DefaultAuthScheme"),
auth,
parseOptionalBoolean(params, "RequireTLS"),
parseOptionalInteger(params, "IdleClientTimeout"),
parseOptionalBoolean(params, "DebugLogging"),
params.getFirst("RoleArn"),
securityGroups,
null,
region);
String result = new XmlBuilder().start("DBProxy")
.raw(dbProxyInnerXml(proxy)).end("DBProxy").build();
return Response.ok(AwsQueryResponse.envelope(
"ModifyDBProxy", AwsNamespaces.RDS, result)).build();
}
private Response handleDeleteDbProxy(MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBProxyName");
DbProxy proxy = service.getDbProxy(name, region);
String result = new XmlBuilder().start("DBProxy").raw(dbProxyInnerXml(proxy)).end("DBProxy").build();
service.deleteDbProxy(name, region);
return Response.ok(AwsQueryResponse.envelope("DeleteDBProxy", AwsNamespaces.RDS, result)).build();
}
private Response handleRegisterDbProxyTargets(MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBProxyName");
String tgName = params.getFirst("TargetGroupName");
validateOptionalTargetGroupName(tgName);
List<String> clusterIds = memberList(params, "DBClusterIdentifiers");
List<String> instanceIds = memberList(params, "DBInstanceIdentifiers");
DbProxyTargetGroup tg = service.registerDbProxyTargets(
name, tgName, clusterIds, instanceIds, 0, 0, region);
XmlBuilder xml = new XmlBuilder().start("DBProxyTargets");
for (DbProxyTarget t : tg.getTargets()) {
xml.start("member").raw(dbProxyTargetInnerXml(t)).end("member");
}
xml.end("DBProxyTargets");
return Response.ok(AwsQueryResponse.envelope("RegisterDBProxyTargets", AwsNamespaces.RDS, xml.build())).build();
}
private Response handleDeregisterDbProxyTargets(MultivaluedMap<String, String> params, String region) {
String targetGroupName = params.getFirst("TargetGroupName");
validateOptionalTargetGroupName(targetGroupName);
service.deregisterDbProxyTargets(params.getFirst("DBProxyName"), targetGroupName,
memberList(params, "DBClusterIdentifiers"), memberList(params, "DBInstanceIdentifiers"), region);
return Response.ok(AwsQueryResponse.envelope("DeregisterDBProxyTargets", AwsNamespaces.RDS, "")).build();
}
private Response handleDescribeDbProxyTargetGroups(
MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBProxyName");
XmlBuilder xml = new XmlBuilder().start("TargetGroups");
for (DbProxyTargetGroup tg : service.describeDbProxyTargetGroups(
name, params.getFirst("TargetGroupName"), region)) {
xml.start("member").raw(dbProxyTargetGroupInnerXml(tg)).end("member");
}
xml.end("TargetGroups");
return Response.ok(AwsQueryResponse.envelope("DescribeDBProxyTargetGroups", AwsNamespaces.RDS, xml.build())).build();
}
private Response handleModifyDbProxyTargetGroup(
MultivaluedMap<String, String> params, String region) {
String targetGroupName = params.getFirst("TargetGroupName");
if (targetGroupName == null || targetGroupName.isBlank()) {
throw new AwsException("InvalidParameterValue",
"TargetGroupName is required.", 400);
}
String newName = params.getFirst("NewName");
if (newName != null && !newName.isBlank()) {
throw new AwsException("UnsupportedOperation",
"The default DB proxy target group cannot be renamed.", 400);
}
String poolPrefix = "ConnectionPoolConfig.";
List<String> pinningFilters = hasMemberKeys(
params, poolPrefix + "SessionPinningFilters")
? memberList(params, poolPrefix + "SessionPinningFilters") : null;
DbProxyTargetGroup targetGroup = service.configureDbProxyTargetGroup(
params.getFirst("DBProxyName"),
targetGroupName,
parseOptionalInteger(params, poolPrefix + "MaxConnectionsPercent"),
parseOptionalInteger(params, poolPrefix + "MaxIdleConnectionsPercent"),
parseOptionalInteger(params, poolPrefix + "ConnectionBorrowTimeout"),
params.containsKey(poolPrefix + "InitQuery")
? params.getFirst(poolPrefix + "InitQuery") : null,
pinningFilters,
region);
String result = new XmlBuilder().start("DBProxyTargetGroup")
.raw(dbProxyTargetGroupInnerXml(targetGroup)).end("DBProxyTargetGroup").build();
return Response.ok(AwsQueryResponse.envelope(
"ModifyDBProxyTargetGroup", AwsNamespaces.RDS, result)).build();
}
private Response handleDescribeDbProxyTargets(MultivaluedMap<String, String> params, String region) {
String name = params.getFirst("DBProxyName");
String tgName = params.getFirst("TargetGroupName");
validateOptionalTargetGroupName(tgName);
XmlBuilder xml = new XmlBuilder().start("Targets");
for (DbProxyTarget t : service.describeDbProxyTargets(name, tgName, region)) {
xml.start("member").raw(dbProxyTargetInnerXml(t)).end("member");
}
xml.end("Targets");
return Response.ok(AwsQueryResponse.envelope("DescribeDBProxyTargets", AwsNamespaces.RDS, xml.build())).build();
}
private void validateOptionalTargetGroupName(String targetGroupName) {
if (targetGroupName != null && targetGroupName.isBlank()) {
throw new AwsException("InvalidParameterValue",
"TargetGroupName must be at least 1 character.", 400);
}
}
private String dbProxyInnerXml(DbProxy p) {
XmlBuilder xml = new XmlBuilder()
.elem("DBProxyName", p.getDbProxyName())
.elem("DBProxyArn", p.getDbProxyArn())
.elem("Status", p.getStatus())
.elem("EngineFamily", p.getEngineFamily())
.elem("Endpoint", p.getEndpoint())
.elem("RequireTLS", String.valueOf(p.isRequireTls()))
.elem("DefaultAuthScheme", p.getDefaultAuthScheme())
.elem("EndpointNetworkType", p.getEndpointNetworkType() != null
? p.getEndpointNetworkType() : "IPV4")
.elem("TargetConnectionNetworkType", p.getTargetConnectionNetworkType() != null
? p.getTargetConnectionNetworkType() : "IPV4")
.elem("IdleClientTimeout", p.getIdleClientTimeout())
.elem("DebugLogging", String.valueOf(p.isDebugLogging()));
if (p.getVpcId() != null) {
xml.elem("VpcId", p.getVpcId());
}
if (p.getRoleArn() != null) {
xml.elem("RoleArn", p.getRoleArn());
}
xml.start("Auth");
for (DbProxyAuth a : p.getAuth()) {
xml.start("member")
.elem("AuthScheme", a.getAuthScheme())
.elem("SecretArn", a.getSecretArn())
.elem("IAMAuth", a.getIamAuth());
if (a.getClientPasswordAuthType() != null) {
xml.elem("ClientPasswordAuthType", a.getClientPasswordAuthType());
}
if (a.getDescription() != null) {
xml.elem("Description", a.getDescription());
}
if (a.getUserName() != null) {
xml.elem("UserName", a.getUserName());
}
xml.end("member");
}
xml.end("Auth");
xml.start("VpcSubnetIds");
for (String s : p.getVpcSubnetIds()) {
xml.elem("member", s);
}
xml.end("VpcSubnetIds");
xml.start("VpcSecurityGroupIds");
for (String securityGroupId : p.getVpcSecurityGroupIds()) {
xml.elem("member", securityGroupId);
}
xml.end("VpcSecurityGroupIds");
if (p.getCreatedAt() != null) {
xml.elem("CreatedDate", p.getCreatedAt().toString());
}
if (p.getUpdatedAt() != null) {
xml.elem("UpdatedDate", p.getUpdatedAt().toString());
}
return xml.build();
}
private static void validateIpv4NetworkType(
String value, String parameterName, boolean dualAllowed, String validValues) {
if (value == null) {
return;
}
if ("IPV4".equalsIgnoreCase(value)) {
return;
}
boolean supportedAwsValue = "IPV6".equalsIgnoreCase(value)
|| (dualAllowed && "DUAL".equalsIgnoreCase(value));
if (value.isBlank() || !supportedAwsValue) {
throw new AwsException("InvalidParameterValue",
parameterName + " must be " + validValues + ".", 400);
}
throw new AwsException("UnsupportedOperation",
parameterName + " " + value.toUpperCase()
+ " is not supported because Floci currently exposes IPv4 proxy networking only.",
400);
}
private String dbProxyTargetGroupInnerXml(DbProxyTargetGroup tg) {
XmlBuilder xml = new XmlBuilder()
.elem("DBProxyName", tg.getDbProxyName())
.elem("TargetGroupName", tg.getTargetGroupName())
.elem("TargetGroupArn", tg.getTargetGroupArn())
.elem("Status", tg.getStatus())
.elem("IsDefault", String.valueOf(tg.isDefaultTargetGroup()))
.start("ConnectionPoolConfig")
.elem("MaxConnectionsPercent", tg.getMaxConnectionsPercent())
.elem("MaxIdleConnectionsPercent", tg.getMaxIdleConnectionsPercent())
.elem("ConnectionBorrowTimeout", tg.getConnectionBorrowTimeout());
if (tg.getInitQuery() != null) {
xml.elem("InitQuery", tg.getInitQuery());
}
xml.start("SessionPinningFilters");
for (String filter : tg.getSessionPinningFilters()) {
xml.elem("member", filter);
}
xml.end("SessionPinningFilters")
.end("ConnectionPoolConfig");
if (tg.getCreatedAt() != null) {
xml.elem("CreatedDate", tg.getCreatedAt().toString());
}
if (tg.getUpdatedAt() != null) {
xml.elem("UpdatedDate", tg.getUpdatedAt().toString());
}
return xml.build();
}
private String dbProxyTargetInnerXml(DbProxyTarget t) {
XmlBuilder xml = new XmlBuilder()
.elem("Type", t.getType())
.elem("RdsResourceId", t.getRdsResourceId())
.elem("Endpoint", t.getEndpoint())
.elem("Port", t.getPort())
.start("TargetHealth").elem("State", t.getTargetHealth()).end("TargetHealth");
if (t.getTargetArn() != null) {
xml.elem("TargetArn", t.getTargetArn());
}
return xml.build();
}
private Response handleDescribeDbClusterSnapshots(MultivaluedMap<String, String> params) {
@@ -864,7 +1179,17 @@ public class RdsQueryHandler {
if (groupName == null || groupName.isBlank() || "default".equalsIgnoreCase(groupName)) {
return fallbackSubnetGroup(instance, "default", "default subnet group");
}
return service.getDbSubnetGroup(groupName);
return service.getDbSubnetGroup(
groupName, regionFromRdsArn(instance.getDbInstanceArn()));
}
private String regionFromRdsArn(String arn) {
if (arn == null || arn.isBlank()) {
return config.defaultRegion();
}
String[] parts = arn.split(":", 6);
return parts.length == 6 && !parts[3].isBlank()
? parts[3] : config.defaultRegion();
}
private DbSubnetGroup fallbackSubnetGroup(DbInstance instance, String name, String description) {
@@ -924,6 +1249,7 @@ public class RdsQueryHandler {
case DELETING -> "deleting";
case REBOOTING -> "rebooting";
case MODIFYING -> "modifying";
case FAILED -> "failed";
};
}
@@ -998,6 +1324,62 @@ public class RdsQueryHandler {
}
}
private static List<DbProxyAuth> parseProxyAuth(MultivaluedMap<String, String> params) {
List<DbProxyAuth> auth = new java.util.ArrayList<>();
for (int index = 1; ; index++) {
String prefix = "Auth.member." + index + ".";
String authScheme = params.getFirst(prefix + "AuthScheme");
String secretArn = params.getFirst(prefix + "SecretArn");
String iamAuth = params.getFirst(prefix + "IAMAuth");
String passwordType = params.getFirst(prefix + "ClientPasswordAuthType");
String description = params.getFirst(prefix + "Description");
String userName = params.getFirst(prefix + "UserName");
if (authScheme == null && secretArn == null && iamAuth == null
&& passwordType == null && description == null && userName == null) {
break;
}
DbProxyAuth entry = new DbProxyAuth(
authScheme, secretArn, iamAuth, passwordType, description);
entry.setUserName(userName);
auth.add(entry);
}
return auth;
}
private static boolean hasProxyAuthKeys(MultivaluedMap<String, String> params) {
return params.keySet().stream().anyMatch(key -> key.startsWith("Auth.member."));
}
private static Boolean parseOptionalBoolean(
MultivaluedMap<String, String> params, String parameterName) {
String value = params.getFirst(parameterName);
if (value == null) {
return null;
}
if ("true".equalsIgnoreCase(value)) {
return true;
}
if ("false".equalsIgnoreCase(value)) {
return false;
}
throw new AwsException("InvalidParameterValue",
parameterName + " must be true or false.", 400);
}
private static Integer parseOptionalInteger(
MultivaluedMap<String, String> params, String parameterName) {
String value = params.getFirst(parameterName);
if (value == null) {
return null;
}
try {
return Integer.valueOf(value);
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue",
parameterName + " must be an integer.", 400);
}
}
private static Map<String, String> parseTags(MultivaluedMap<String, String> params) {
Map<String, String> tags = new LinkedHashMap<>();
readTags(params, "Tags.member", tags);
File diff suppressed because it is too large. Load diff
@@ -8,22 +8,48 @@ import java.io.Closeable;
public class RdsContainerHandle {
private final String containerId;
private final String runtimeId;
private final String instanceId;
private final String host;
private final int port;
private final String storageKey;
private final String containerKey;
private Closeable logStream;
public RdsContainerHandle(String containerId, String instanceId, String host, int port) {
this(containerId, instanceId, instanceId, host, port, null);
}
public RdsContainerHandle(
String containerId, String runtimeId, String instanceId, String host, int port) {
this(containerId, runtimeId, instanceId, host, port, null);
}
public RdsContainerHandle(
String containerId, String runtimeId, String instanceId,
String host, int port, String storageKey) {
this(containerId, runtimeId, instanceId, host, port, storageKey, null);
}
public RdsContainerHandle(
String containerId, String runtimeId, String instanceId,
String host, int port, String storageKey, String containerKey) {
this.containerId = containerId;
this.runtimeId = runtimeId == null || runtimeId.isBlank() ? instanceId : runtimeId;
this.instanceId = instanceId;
this.host = host;
this.port = port;
this.storageKey = storageKey;
this.containerKey = containerKey;
}
public String getContainerId() { return containerId; }
public String getRuntimeId() { return runtimeId; }
public String getInstanceId() { return instanceId; }
public String getHost() { return host; }
public int getPort() { return port; }
public String getStorageKey() { return storageKey; }
public String getContainerKey() { return containerKey; }
public Closeable getLogStream() { return logStream; }
public void setLogStream(Closeable logStream) { this.logStream = logStream; }
}
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.rds.container;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Frame;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ServiceConfigAccess;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -26,9 +27,11 @@ import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* Manages backend Docker container lifecycle for RDS DB instances and clusters.
@@ -38,6 +41,7 @@ import java.util.concurrent.TimeUnit;
public class RdsContainerManager {
private static final Logger LOG = Logger.getLogger(RdsContainerManager.class);
private static final Pattern SAFE_STORAGE_COMPONENT = Pattern.compile("[A-Za-z0-9._-]+");
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -47,6 +51,8 @@ public class RdsContainerManager {
private final RegionResolver regionResolver;
private final ServiceConfigAccess serviceConfigAccess;
private final Map<String, RdsContainerHandle> activeContainers = new ConcurrentHashMap<>();
private final Map<String, String> activeStorageOwners = new ConcurrentHashMap<>();
private final Set<String> claimedRuntimes = ConcurrentHashMap.newKeySet();
@Inject
public RdsContainerManager(ContainerBuilder containerBuilder,
@@ -68,75 +74,212 @@ public class RdsContainerManager {
public RdsContainerHandle start(String instanceId, String volumeId, DatabaseEngine engine,
String image, String masterUsername,
String masterPassword, String dbName) {
return start(instanceId, instanceId, volumeId, engine, image,
masterUsername, masterPassword, dbName);
}
public RdsContainerHandle start(
String runtimeId, String instanceId, String volumeId, DatabaseEngine engine,
String image, String masterUsername, String masterPassword, String dbName) {
String exactVolumeName = ContainerStorageHelper.resourceName(
config, "rds", volumeId, instanceId);
return start(runtimeId, instanceId, instanceId, exactVolumeName,
engine, image, masterUsername, masterPassword, dbName);
}
public RdsContainerHandle start(
String runtimeId, String instanceId, String containerStorageResourceId,
String dockerVolumeName, DatabaseEngine engine, String image,
String masterUsername, String masterPassword, String dbName) {
LOG.infov("Starting RDS backend container for instance: {0} engine={1}", instanceId, engine);
String effectiveRuntimeId = runtimeId == null || runtimeId.isBlank()
? instanceId : runtimeId;
String storageResourceId = requireSafeStorageComponent(
containerStorageResourceId, "container storage resource ID");
String exactVolumeName = requireSafeStorageComponent(
dockerVolumeName, "Docker volume name");
int enginePort = engine.defaultPort();
String containerName = ContainerStorageHelper.resourceName(config, "rds", volumeId, instanceId);
String containerName = exactVolumeName;
String storageKey = storageKey(storageResourceId, exactVolumeName);
String containerKey = "container:" + containerName;
if (!claimedRuntimes.add(effectiveRuntimeId)) {
throw new IllegalStateException(
"RDS runtime " + effectiveRuntimeId + " already has an active container");
}
try {
claimStorage(storageKey, effectiveRuntimeId);
} catch (RuntimeException | Error e) {
claimedRuntimes.remove(effectiveRuntimeId);
throw e;
}
try {
claimStorage(containerKey, effectiveRuntimeId);
} catch (RuntimeException | Error e) {
releaseOwnership(storageKey, null, effectiveRuntimeId);
throw e;
}
// Remove any stale container with the same name
lifecycleManager.removeIfExists(containerName);
String cleanupContainerId = containerName;
RdsContainerHandle handle = null;
try {
// Remove any stale container with the same name only after storage ownership is secured.
lifecycleManager.removeIfExistsStrict(containerName);
cleanupContainerId = null;
// Build environment variables
List<String> envVars = buildEnvVars(engine, masterUsername, masterPassword, dbName);
// Build environment variables
List<String> envVars = buildEnvVars(engine, masterUsername, masterPassword, dbName);
// Build container spec with bind mounts for persistence. Publish the
// engine port to the host only in native mode; in Docker mode the auth
// proxy reaches the DB via the container network.
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
.withEnv(envVars)
.withDockerNetwork(config.services().rds().dockerNetwork())
.withLogRotation();
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(containerName)
.withEnv(envVars)
.withDockerNetwork(config.services().rds().dockerNetwork())
.withLogRotation();
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(enginePort);
} else {
specBuilder.withExposedPort(enginePort);
}
if (!containerDetector.isRunningInContainer()) {
specBuilder.withDynamicPort(enginePort);
} else {
specBuilder.withExposedPort(enginePort);
}
// Handle persistence mounting
addPersistenceMounts(specBuilder, instanceId, volumeId, engine, image);
addPersistenceMounts(
specBuilder, storageResourceId, exactVolumeName, engine, image);
// Add engine-specific command
List<String> cmd = buildContainerCmd(engine);
if (!cmd.isEmpty()) {
specBuilder.withCmd(cmd);
}
List<String> cmd = buildContainerCmd(engine);
if (!cmd.isEmpty()) {
specBuilder.withCmd(cmd);
}
ContainerSpec spec = specBuilder.build();
ContainerSpec spec = specBuilder.build();
// Create and start container
ContainerInfo info = lifecycleManager.createAndStart(spec);
EndpointInfo endpoint = info.getEndpoint(enginePort);
// Create and start container separately so a failed start retains the cleanup identity.
// The fixed name remains a valid cleanup identity if create succeeds but its response
// is lost before Docker returns the generated ID.
cleanupContainerId = containerName;
String createdContainerId = lifecycleManager.create(spec);
cleanupContainerId = createdContainerId;
ContainerInfo info = lifecycleManager.startCreated(createdContainerId, spec);
EndpointInfo endpoint = info.getEndpoint(enginePort);
LOG.infov("RDS backend for instance {0}: {1}", instanceId, endpoint);
initializeEngine(containerName, info.containerId(), engine, masterUsername);
LOG.infov("RDS backend for instance {0}: {1}", instanceId, endpoint);
initializeEngine(containerName, info.containerId(), engine, masterUsername);
RdsContainerHandle handle = new RdsContainerHandle(
info.containerId(), instanceId, endpoint.host(), endpoint.port());
activeContainers.put(instanceId, handle);
handle = new RdsContainerHandle(
info.containerId(), effectiveRuntimeId, instanceId,
endpoint.host(), endpoint.port(), storageKey, containerKey);
// Attach log streaming
String shortId = info.containerId().length() >= 8
? info.containerId().substring(0, 8)
: info.containerId();
String logGroup = "/aws/rds/instance/" + instanceId + "/error";
String logStream = logStreamer.generateLogStreamName(shortId);
String region = regionResolver.getDefaultRegion();
String shortId = info.containerId().length() >= 8
? info.containerId().substring(0, 8)
: info.containerId();
String logGroup = "/aws/rds/instance/" + instanceId + "/error";
String logStream = logStreamer.generateLogStreamName(shortId);
String region = regionResolver.getDefaultRegion();
String accountId = null;
try {
AwsArnUtils.Arn runtimeArn = AwsArnUtils.parse(effectiveRuntimeId);
if ("rds".equals(runtimeArn.service())) {
if (!runtimeArn.region().isBlank()) {
region = runtimeArn.region();
}
if (!runtimeArn.accountId().isBlank()) {
accountId = runtimeArn.accountId();
}
}
} catch (IllegalArgumentException ignored) {
LOG.debugv("Using legacy RDS runtime identity for log routing: {0}",
effectiveRuntimeId);
}
Closeable logHandle = logStreamer.attach(
info.containerId(), logGroup, logStream, region, "rds:" + instanceId);
handle.setLogStream(logHandle);
Closeable logHandle = accountId != null
? logStreamer.attachForAccount(
accountId, info.containerId(), logGroup, logStream, region,
"rds:" + effectiveRuntimeId)
: logStreamer.attach(
info.containerId(), logGroup, logStream, region,
"rds:" + effectiveRuntimeId);
handle.setLogStream(logHandle);
activeContainers.put(effectiveRuntimeId, handle);
return handle;
return handle;
} catch (RuntimeException | Error e) {
if (handle != null) {
activeContainers.remove(effectiveRuntimeId, handle);
}
boolean cleaned = cleanupContainerId == null;
if (cleanupContainerId != null) {
try {
lifecycleManager.stopAndRemoveStrict(
cleanupContainerId,
handle != null ? handle.getLogStream() : null);
cleaned = true;
} catch (RuntimeException | Error cleanupFailure) {
e.addSuppressed(cleanupFailure);
RdsContainerHandle retained = handle != null ? handle
: new RdsContainerHandle(
cleanupContainerId, effectiveRuntimeId, instanceId,
null, 0, storageKey, containerKey);
activeContainers.put(effectiveRuntimeId, retained);
LOG.errorv(cleanupFailure,
"Failed to clean up RDS container {0}; retaining storage ownership for {1}",
cleanupContainerId, effectiveRuntimeId);
}
}
if (cleaned) {
releaseOwnership(storageKey, containerKey, effectiveRuntimeId);
}
throw e;
}
}
public void stop(RdsContainerHandle handle) {
if (handle == null) {
return;
}
activeContainers.remove(handle.getInstanceId());
lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream());
RdsContainerHandle active = activeContainers.get(handle.getRuntimeId());
RdsContainerHandle effectiveHandle = active != null ? active : handle;
try {
lifecycleManager.stopAndRemoveStrict(
effectiveHandle.getContainerId(), effectiveHandle.getLogStream());
} catch (RuntimeException | Error e) {
activeContainers.putIfAbsent(effectiveHandle.getRuntimeId(), effectiveHandle);
claimedRuntimes.add(effectiveHandle.getRuntimeId());
throw e;
}
activeContainers.remove(effectiveHandle.getRuntimeId(), effectiveHandle);
releaseOwnership(
effectiveHandle.getStorageKey(), effectiveHandle.getContainerKey(),
effectiveHandle.getRuntimeId());
}
/**
* Retries cleanup for a runtime retained after an earlier stop failure.
*
* <p>The persisted RDS model intentionally clears stale Docker endpoint fields after a failed
* restore. The runtime ARN remains stable and is therefore the safe lookup key for a later
* delete retry.
*/
public void stopByRuntimeId(String runtimeId) {
if (runtimeId == null || runtimeId.isBlank()) {
return;
}
RdsContainerHandle active = activeContainers.get(runtimeId);
if (active != null) {
stop(active);
}
}
/** Returns the retained runtime handle used to persist cleanup identity after a failed start. */
public RdsContainerHandle getActiveHandle(String runtimeId) {
if (runtimeId == null || runtimeId.isBlank()) {
return null;
}
return activeContainers.get(runtimeId);
}
public void stopAll() {
@@ -145,21 +288,28 @@ public class RdsContainerManager {
LOG.infov("Stopping {0} RDS container(s) on shutdown", handles.size());
}
for (RdsContainerHandle handle : handles) {
stop(handle);
try {
stop(handle);
} catch (RuntimeException | Error e) {
LOG.warnv(e, "Failed to stop RDS container {0} during shutdown; continuing",
handle.getContainerId());
}
}
}
private void addPersistenceMounts(ContainerBuilder.Builder specBuilder, String instanceId,
String volumeId, DatabaseEngine engine, String image) {
private void addPersistenceMounts(
ContainerBuilder.Builder specBuilder, String storageResourceId,
String exactVolumeName, DatabaseEngine engine, String image) {
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
ContainerStorageHelper.applyStorage(
specBuilder, lifecycleManager, config, "rds", volumeId, instanceId,
ContainerStorageHelper.applyNamedVolume(
specBuilder, lifecycleManager, exactVolumeName,
engineDefaultDataPath(engine, image));
return;
}
// Legacy host-path mode: host-persistent-path is an absolute path
String hostDataPath = ContainerStorageHelper.hostResourcePath(config, "rds", instanceId).toString();
String hostDataPath = ContainerStorageHelper.hostResourcePath(
config, "rds", storageResourceId).toString();
if (!containerDetector.isRunningInContainer()) {
ContainerStorageHelper.ensureHostDir(hostDataPath);
}
@@ -303,12 +453,66 @@ public class RdsContainerManager {
record ContainerExecResult(long exitCode, String output) {}
public void removeVolume(String instanceId, String volumeId) {
removeVolume(instanceId, instanceId,
ContainerStorageHelper.resourceName(config, "rds", volumeId, instanceId));
}
public void removeVolume(
String runtimeId, String containerStorageResourceId, String dockerVolumeName) {
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
ContainerStorageHelper.removeStorage(config, lifecycleManager, "rds", volumeId, instanceId);
requireSafeStorageComponent(
containerStorageResourceId, "container storage resource ID");
String exactVolumeName = requireSafeStorageComponent(
dockerVolumeName, "Docker volume name");
String key = "volume:" + exactVolumeName;
String owner = activeStorageOwners.get(key);
if (owner != null) {
throw new IllegalStateException(
"Refusing to remove active RDS storage " + exactVolumeName
+ ", owned by " + owner);
}
ContainerStorageHelper.removeNamedVolumeStrict(
config, lifecycleManager, exactVolumeName);
}
// host-path mode: host directories are not removed automatically
}
private String storageKey(String storageResourceId, String exactVolumeName) {
if (ContainerStorageHelper.isNamedVolumeMode(config)) {
return "volume:" + exactVolumeName;
}
Path hostPath = ContainerStorageHelper.hostResourcePath(
config, "rds", storageResourceId).toAbsolutePath().normalize();
return "path:" + hostPath;
}
private void claimStorage(String storageKey, String runtimeId) {
String existingOwner = activeStorageOwners.putIfAbsent(storageKey, runtimeId);
if (existingOwner != null && !existingOwner.equals(runtimeId)) {
throw new IllegalStateException(
"RDS storage " + storageKey + " is already owned by " + existingOwner);
}
}
private void releaseOwnership(String storageKey, String containerKey, String runtimeId) {
if (storageKey != null) {
activeStorageOwners.remove(storageKey, runtimeId);
}
if (containerKey != null) {
activeStorageOwners.remove(containerKey, runtimeId);
}
claimedRuntimes.remove(runtimeId);
}
private static String requireSafeStorageComponent(String value, String label) {
if (value == null || value.isBlank()
|| ".".equals(value) || "..".equals(value)
|| !SAFE_STORAGE_COMPONENT.matcher(value).matches()) {
throw new IllegalArgumentException("Invalid " + label + ": " + value);
}
return value;
}
private List<String> buildEnvVars(DatabaseEngine engine, String masterUsername,
String masterPassword, String dbName) {
String effectiveUser = (masterUsername != null && !masterUsername.isBlank()) ? masterUsername : "postgres";
@@ -36,6 +36,7 @@ public class DbCluster {
private String dockerVolumeName;
private String volumeId;
private String containerStorageResourceId;
// Transient — not persisted
private transient String containerId;
@@ -143,6 +144,11 @@ public class DbCluster {
public String getVolumeId() { return volumeId; }
public void setVolumeId(String volumeId) { this.volumeId = volumeId; }
public String getContainerStorageResourceId() { return containerStorageResourceId; }
public void setContainerStorageResourceId(String containerStorageResourceId) {
this.containerStorageResourceId = containerStorageResourceId;
}
public String getContainerId() { return containerId; }
public void setContainerId(String containerId) { this.containerId = containerId; }
@@ -11,6 +11,7 @@ public class DbClusterParameterGroup {
private String dbClusterParameterGroupName;
private String dbParameterGroupFamily;
private String description;
private String region;
private Map<String, String> parameters = new HashMap<>();
public DbClusterParameterGroup() {}
@@ -31,6 +32,9 @@ public class DbClusterParameterGroup {
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public Map<String, String> getParameters() { return parameters; }
public void setParameters(Map<String, String> parameters) { this.parameters = parameters; }
}
@@ -41,6 +41,7 @@ public class DbInstance {
private String dockerVolumeName;
private String volumeId;
private String containerStorageResourceId;
private transient String containerId;
private transient String containerHost;
@@ -166,6 +167,11 @@ public class DbInstance {
public String getVolumeId() { return volumeId; }
public void setVolumeId(String volumeId) { this.volumeId = volumeId; }
public String getContainerStorageResourceId() { return containerStorageResourceId; }
public void setContainerStorageResourceId(String containerStorageResourceId) {
this.containerStorageResourceId = containerStorageResourceId;
}
public String getContainerId() { return containerId; }
public void setContainerId(String containerId) { this.containerId = containerId; }
@@ -4,5 +4,5 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public enum DbInstanceStatus {
CREATING, AVAILABLE, DELETING, REBOOTING, MODIFYING
CREATING, AVAILABLE, DELETING, REBOOTING, MODIFYING, FAILED
}
@@ -11,6 +11,7 @@ public class DbParameterGroup {
private String dbParameterGroupName;
private String dbParameterGroupFamily;
private String description;
private String region;
private Map<String, String> parameters = new HashMap<>();
public DbParameterGroup() {}
@@ -31,6 +32,9 @@ public class DbParameterGroup {
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public Map<String, String> getParameters() { return parameters; }
public void setParameters(Map<String, String> parameters) { this.parameters = parameters; }
}
@@ -0,0 +1,127 @@
package io.github.hectorvent.floci.services.rds.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* An {@code AWS::RDS::DBProxy}. In real AWS a DB Proxy fronts a target DB cluster/instance behind a
* pooled endpoint. Floci models the control-plane resource and can attach a second auth relay (see
* {@code RdsProxyManager}) that forwards to the registered target's backend container. Distinct
* externally reachable same-engine proxy endpoints require endpoint routing beyond this model.
*/
@RegisterForReflection
public class DbProxy {
private String dbProxyName; // physical id + Ref return value
private String dbProxyArn; // GetAtt "DBProxyArn"
private String dbProxyResourceId; // "prx-XXXX..."
private String endpointHost; // proxy endpoint hostname
private int proxyPort; // relay port (engine family default, or a pool port if taken)
private String engineFamily; // POSTGRESQL | MYSQL | SQLSERVER (as sent by the client)
private boolean requireTls = true;
private boolean iamAuth; // effective relay auth from DefaultAuthScheme/Auth[]
private String defaultAuthScheme = "NONE"; // NONE | IAM_AUTH
private String roleArn;
private int idleClientTimeout = 1800;
private boolean debugLogging;
private String status = "available";
private Instant createdAt;
private Instant updatedAt;
private String vpcId;
private String endpointNetworkType = "IPV4";
private String targetConnectionNetworkType = "IPV4";
private List<String> vpcSubnetIds = new ArrayList<>();
private List<String> vpcSecurityGroupIds = new ArrayList<>();
private List<DbProxyAuth> auth = new ArrayList<>();
private Map<String, String> tags = new LinkedHashMap<>();
public DbProxy() {}
/** AWS RDS Proxy exposes a bare hostname and clients connect on the engine's default port. */
public String getEndpoint() {
return endpointHost;
}
public String getDbProxyName() { return dbProxyName; }
public void setDbProxyName(String dbProxyName) { this.dbProxyName = dbProxyName; }
public String getDbProxyArn() { return dbProxyArn; }
public void setDbProxyArn(String dbProxyArn) { this.dbProxyArn = dbProxyArn; }
public String getDbProxyResourceId() { return dbProxyResourceId; }
public void setDbProxyResourceId(String dbProxyResourceId) { this.dbProxyResourceId = dbProxyResourceId; }
public String getEndpointHost() { return endpointHost; }
public void setEndpointHost(String endpointHost) { this.endpointHost = endpointHost; }
public int getProxyPort() { return proxyPort; }
public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; }
public String getEngineFamily() { return engineFamily; }
public void setEngineFamily(String engineFamily) { this.engineFamily = engineFamily; }
public boolean isRequireTls() { return requireTls; }
public void setRequireTls(boolean requireTls) { this.requireTls = requireTls; }
public boolean isIamAuth() { return iamAuth; }
public void setIamAuth(boolean iamAuth) { this.iamAuth = iamAuth; }
public String getDefaultAuthScheme() { return defaultAuthScheme; }
public void setDefaultAuthScheme(String defaultAuthScheme) {
this.defaultAuthScheme = defaultAuthScheme;
}
public String getRoleArn() { return roleArn; }
public void setRoleArn(String roleArn) { this.roleArn = roleArn; }
public int getIdleClientTimeout() { return idleClientTimeout; }
public void setIdleClientTimeout(int idleClientTimeout) { this.idleClientTimeout = idleClientTimeout; }
public boolean isDebugLogging() { return debugLogging; }
public void setDebugLogging(boolean debugLogging) { this.debugLogging = debugLogging; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
public Instant getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; }
public String getVpcId() { return vpcId; }
public void setVpcId(String vpcId) { this.vpcId = vpcId; }
public String getEndpointNetworkType() { return endpointNetworkType; }
public void setEndpointNetworkType(String endpointNetworkType) {
this.endpointNetworkType = endpointNetworkType;
}
public String getTargetConnectionNetworkType() { return targetConnectionNetworkType; }
public void setTargetConnectionNetworkType(String targetConnectionNetworkType) {
this.targetConnectionNetworkType = targetConnectionNetworkType;
}
public List<String> getVpcSubnetIds() { return vpcSubnetIds; }
public void setVpcSubnetIds(List<String> vpcSubnetIds) {
this.vpcSubnetIds = vpcSubnetIds != null ? new ArrayList<>(vpcSubnetIds) : new ArrayList<>();
}
public List<String> getVpcSecurityGroupIds() { return vpcSecurityGroupIds; }
public void setVpcSecurityGroupIds(List<String> vpcSecurityGroupIds) {
this.vpcSecurityGroupIds = vpcSecurityGroupIds != null ? new ArrayList<>(vpcSecurityGroupIds) : new ArrayList<>();
}
public List<DbProxyAuth> getAuth() { return auth; }
public void setAuth(List<DbProxyAuth> auth) {
this.auth = auth != null ? new ArrayList<>(auth) : new ArrayList<>();
}
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>(); }
}
@@ -0,0 +1,44 @@
package io.github.hectorvent.floci.services.rds.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/** One entry of an {@code AWS::RDS::DBProxy} {@code Auth} array (a secret-based auth descriptor). */
@RegisterForReflection
public class DbProxyAuth {
private String authScheme; // "SECRETS"
private String secretArn;
private String iamAuth; // "REQUIRED" | "DISABLED"
private String clientPasswordAuthType; // nullable
private String description; // nullable
private String userName; // nullable; used by end-to-end IAM authentication
public DbProxyAuth() {}
public DbProxyAuth(String authScheme, String secretArn, String iamAuth,
String clientPasswordAuthType, String description) {
this.authScheme = authScheme;
this.secretArn = secretArn;
this.iamAuth = iamAuth;
this.clientPasswordAuthType = clientPasswordAuthType;
this.description = description;
}
public String getAuthScheme() { return authScheme; }
public void setAuthScheme(String authScheme) { this.authScheme = authScheme; }
public String getSecretArn() { return secretArn; }
public void setSecretArn(String secretArn) { this.secretArn = secretArn; }
public String getIamAuth() { return iamAuth; }
public void setIamAuth(String iamAuth) { this.iamAuth = iamAuth; }
public String getClientPasswordAuthType() { return clientPasswordAuthType; }
public void setClientPasswordAuthType(String clientPasswordAuthType) { this.clientPasswordAuthType = clientPasswordAuthType; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; }
}
@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.services.rds.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
/** A registered target of an {@code AWS::RDS::DBProxyTargetGroup} (a DB cluster or instance). */
@RegisterForReflection
public class DbProxyTarget {
private String type; // "TRACKED_CLUSTER" | "RDS_INSTANCE"
private String rdsResourceId; // the cluster/instance identifier
private String targetArn;
private String endpoint; // target backend host
private int port;
private String targetHealth = "AVAILABLE";
public DbProxyTarget() {}
public DbProxyTarget(String type, String rdsResourceId, String targetArn, String endpoint, int port) {
this.type = type;
this.rdsResourceId = rdsResourceId;
this.targetArn = targetArn;
this.endpoint = endpoint;
this.port = port;
}
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getRdsResourceId() { return rdsResourceId; }
public void setRdsResourceId(String rdsResourceId) { this.rdsResourceId = rdsResourceId; }
public String getTargetArn() { return targetArn; }
public void setTargetArn(String targetArn) { this.targetArn = targetArn; }
public String getEndpoint() { return endpoint; }
public void setEndpoint(String endpoint) { this.endpoint = endpoint; }
public int getPort() { return port; }
public void setPort(int port) { this.port = port; }
public String getTargetHealth() { return targetHealth; }
public void setTargetHealth(String targetHealth) { this.targetHealth = targetHealth; }
}
@@ -0,0 +1,77 @@
package io.github.hectorvent.floci.services.rds.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
* The (single, always named {@code "default"}) target group of an {@code AWS::RDS::DBProxy}. Holds
* the registered targets and the connection-pool configuration.
*/
@RegisterForReflection
public class DbProxyTargetGroup {
private String dbProxyName; // owner + physical id
private String targetGroupName = "default";
private String targetGroupArn;
private String status = "available";
private boolean defaultTargetGroup = true;
private Instant createdAt;
private Instant updatedAt;
private int maxConnectionsPercent = 100;
private int maxIdleConnectionsPercent = 50;
private int connectionBorrowTimeout = 120;
private String initQuery;
private List<String> sessionPinningFilters = new ArrayList<>();
private List<DbProxyTarget> targets = new ArrayList<>();
public DbProxyTargetGroup() {}
public String getDbProxyName() { return dbProxyName; }
public void setDbProxyName(String dbProxyName) { this.dbProxyName = dbProxyName; }
public String getTargetGroupName() { return targetGroupName; }
public void setTargetGroupName(String targetGroupName) { this.targetGroupName = targetGroupName; }
public String getTargetGroupArn() { return targetGroupArn; }
public void setTargetGroupArn(String targetGroupArn) { this.targetGroupArn = targetGroupArn; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public boolean isDefaultTargetGroup() { return defaultTargetGroup; }
public void setDefaultTargetGroup(boolean defaultTargetGroup) { this.defaultTargetGroup = defaultTargetGroup; }
public Instant getCreatedAt() { return createdAt; }
public void setCreatedAt(Instant createdAt) { this.createdAt = createdAt; }
public Instant getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(Instant updatedAt) { this.updatedAt = updatedAt; }
public int getMaxConnectionsPercent() { return maxConnectionsPercent; }
public void setMaxConnectionsPercent(int maxConnectionsPercent) { this.maxConnectionsPercent = maxConnectionsPercent; }
public int getMaxIdleConnectionsPercent() { return maxIdleConnectionsPercent; }
public void setMaxIdleConnectionsPercent(int maxIdleConnectionsPercent) { this.maxIdleConnectionsPercent = maxIdleConnectionsPercent; }
public int getConnectionBorrowTimeout() { return connectionBorrowTimeout; }
public void setConnectionBorrowTimeout(int connectionBorrowTimeout) {
this.connectionBorrowTimeout = connectionBorrowTimeout;
}
public String getInitQuery() { return initQuery; }
public void setInitQuery(String initQuery) { this.initQuery = initQuery; }
public List<String> getSessionPinningFilters() { return sessionPinningFilters; }
public void setSessionPinningFilters(List<String> sessionPinningFilters) {
this.sessionPinningFilters = sessionPinningFilters != null
? new ArrayList<>(sessionPinningFilters) : new ArrayList<>();
}
public List<DbProxyTarget> getTargets() { return targets; }
public void setTargets(List<DbProxyTarget> targets) {
this.targets = targets != null ? new ArrayList<>(targets) : new ArrayList<>();
}
}
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
@@ -47,7 +48,9 @@ public class RdsAuthProxy {
}
public void start(int proxyPort) throws IOException {
serverSocket = new ServerSocket(proxyPort);
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(proxyPort));
running = true;
Thread.ofVirtual().name("rds-proxy-accept-" + instanceId).start(this::acceptLoop);
LOG.infov("RDS proxy started for instance {0} on port {1} → {2}:{3}",
@@ -61,8 +64,9 @@ public class RdsAuthProxy {
serverSocket.close();
}
} catch (IOException e) {
LOG.warnv("Error closing RDS proxy server socket for instance {0}: {1}",
instanceId, e.getMessage());
LOG.warnv(e, "Error closing RDS proxy server socket for instance {0}", instanceId);
throw new RuntimeException(
"Failed to stop RDS proxy for instance " + instanceId, e);
}
}
@@ -101,7 +105,11 @@ public class RdsAuthProxy {
}
private static void closeQuietly(Socket s) {
try { s.close(); } catch (IOException ignored) {}
try {
s.close();
} catch (IOException e) {
LOG.debugv(e, "Error closing RDS proxy client socket");
}
}
/**
@@ -24,33 +24,78 @@ public class RdsProxyManager {
this.sigV4Validator = sigV4Validator;
}
public void startProxy(String instanceId, DatabaseEngine engine, boolean iamEnabled,
int proxyPort, String backendHost, int backendPort,
String masterUsername, String masterPassword, String dbName,
RdsAuthProxy.PasswordValidator passwordValidator) {
public synchronized void startProxy(String instanceId, DatabaseEngine engine, boolean iamEnabled,
int proxyPort, String backendHost, int backendPort,
String masterUsername, String masterPassword, String dbName,
RdsAuthProxy.PasswordValidator passwordValidator) {
RdsAuthProxy proxy = new RdsAuthProxy(
instanceId, backendHost, backendPort, engine, iamEnabled,
masterUsername, masterPassword, dbName, sigV4Validator, passwordValidator);
try {
proxy.start(proxyPort);
proxies.put(instanceId, proxy);
} catch (IOException e) {
throw new RuntimeException("Failed to start RDS proxy for instance " + instanceId
+ " on port " + proxyPort, e);
RuntimeException failure = new RuntimeException(
"Failed to start RDS proxy for instance " + instanceId
+ " on port " + proxyPort, e);
cleanupFailedStart(proxy, failure);
throw failure;
} catch (RuntimeException e) {
RuntimeException failure = new RuntimeException(
"Failed to register RDS proxy for instance " + instanceId
+ " on port " + proxyPort, e);
cleanupFailedStart(proxy, failure);
throw failure;
}
RdsAuthProxy previous;
try {
previous = proxies.put(instanceId, proxy);
} catch (RuntimeException e) {
RuntimeException failure = new RuntimeException(
"Failed to register RDS proxy for instance " + instanceId
+ " on port " + proxyPort, e);
cleanupFailedStart(proxy, failure);
throw failure;
}
if (previous != null) {
try {
previous.stop();
} catch (RuntimeException e) {
proxies.put(instanceId, previous);
RuntimeException failure = new RuntimeException(
"Failed to replace RDS proxy for instance " + instanceId, e);
cleanupFailedStart(proxy, failure);
throw failure;
}
}
}
public void stopProxy(String instanceId) {
RdsAuthProxy proxy = proxies.remove(instanceId);
public synchronized void stopProxy(String instanceId) {
RdsAuthProxy proxy = proxies.get(instanceId);
if (proxy != null) {
proxy.stop();
proxies.remove(instanceId, proxy);
LOG.infov("Stopped RDS proxy for instance {0}", instanceId);
}
}
public void stopAll() {
proxies.values().forEach(RdsAuthProxy::stop);
proxies.clear();
public synchronized void stopAll() {
proxies.forEach((instanceId, proxy) -> {
try {
proxy.stop();
proxies.remove(instanceId, proxy);
} catch (RuntimeException e) {
LOG.warnv(e, "Failed to stop RDS proxy for instance {0} during shutdown",
instanceId);
}
});
LOG.info("Stopped all RDS proxies");
}
private void cleanupFailedStart(RdsAuthProxy proxy, RuntimeException failure) {
try {
proxy.stop();
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
}
}
}
@@ -64,13 +64,15 @@ public class RdsDataController {
@POST
@Path("/CommitTransaction")
public Response commitTransaction(@Context HttpHeaders headers, String body) {
return handle(headers, body, (request, region) -> Response.ok(service.commitTransaction(request)).build());
return handle(headers, body, (request, region) ->
Response.ok(service.commitTransaction(request, region)).build());
}
@POST
@Path("/RollbackTransaction")
public Response rollbackTransaction(@Context HttpHeaders headers, String body) {
return handle(headers, body, (request, region) -> Response.ok(service.rollbackTransaction(request)).build());
return handle(headers, body, (request, region) ->
Response.ok(service.rollbackTransaction(request, region)).build());
}
private Response handle(HttpHeaders headers, String body, Handler handler) {
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.rdsdata;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
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;
@@ -19,33 +20,42 @@ class RdsDataResourceResolver {
}
DatabaseTarget resolve(String resourceArn) {
return resolve(resourceArn, null);
}
DatabaseTarget resolve(String resourceArn, String requestRegion) {
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);
try {
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
if (!"rds".equals(arn.service())) {
throw new IllegalArgumentException("not an RDS ARN");
}
}
for (DbInstance instance : rdsService.listDbInstances(null)) {
if (resourceArn.equals(instance.getDbInstanceArn())) {
return fromInstance(instance);
if (requestRegion != null && !requestRegion.isBlank()
&& !requestRegion.equals(arn.region())) {
throw new IllegalArgumentException("RDS ARN is outside the request region");
}
}
String id = identifierFromArn(resourceArn);
if (id != null) {
try {
return fromCluster(rdsService.getDbCluster(id));
} catch (AwsException ignored) {
// Try instances below.
int separator = arn.resource().indexOf(':');
if (separator <= 0 || separator == arn.resource().length() - 1) {
throw new IllegalArgumentException("invalid RDS resource");
}
try {
return fromInstance(rdsService.getDbInstance(id));
} catch (AwsException ignored) {
// Fall through to the Data API error shape.
String type = arn.resource().substring(0, separator);
String id = arn.resource().substring(separator + 1);
if ("cluster".equals(type)) {
DbCluster cluster = rdsService.getDbCluster(id, arn.region());
if (resourceArn.equals(cluster.getDbClusterArn())) {
return fromCluster(cluster);
}
} else if ("db".equals(type)) {
DbInstance instance = rdsService.getDbInstance(id, arn.region());
if (resourceArn.equals(instance.getDbInstanceArn())) {
return fromInstance(instance);
}
}
} catch (AwsException | IllegalArgumentException ignored) {
// Normalize lookup and ARN parsing failures to the RDS Data API error shape below.
}
throw new AwsException("BadRequestException",
@@ -71,18 +81,6 @@ class RdsDataResourceResolver {
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) {
}
@@ -120,13 +120,14 @@ public class RdsDataService implements Resettable {
TransactionContext tx = transaction(transactionId);
synchronized (tx) {
requireActiveTransaction(transactionId, tx);
validateTransactionIdentity(tx, request);
validateTransactionIdentity(tx, request, region);
tx.refresh(transactionTtl);
return executeOnConnection(tx.connection, tx.engine, sql, parameters, includeMetadata);
}
}
RdsDataResourceResolver.DatabaseTarget target = resourceResolver.resolve(resourceArn);
RdsDataResourceResolver.DatabaseTarget target =
resourceResolver.resolve(resourceArn, region);
Credentials credentials = credentials(request, target, region);
String database = databaseName(request, target);
try (Connection connection = connectionFactory.open(target, credentials.username(), credentials.password(), database)) {
@@ -141,7 +142,8 @@ public class RdsDataService implements Resettable {
cleanupExpiredTransactions();
String resourceArn = requiredText(request, "resourceArn");
requiredText(request, "secretArn");
RdsDataResourceResolver.DatabaseTarget target = resourceResolver.resolve(resourceArn);
RdsDataResourceResolver.DatabaseTarget target =
resourceResolver.resolve(resourceArn, region);
Credentials credentials = credentials(request, target, region);
String database = databaseName(request, target);
@@ -150,7 +152,8 @@ public class RdsDataService implements Resettable {
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.engine(), target.arn(), database, transactionTtl));
transactions.put(transactionId, new TransactionContext(
transactionId, connection, target.engine(), target.arn(), database, region, transactionTtl));
ObjectNode response = objectMapper.createObjectNode();
response.put("transactionId", transactionId);
@@ -163,14 +166,14 @@ public class RdsDataService implements Resettable {
}
}
public ObjectNode commitTransaction(JsonNode request) {
public ObjectNode commitTransaction(JsonNode request, String region) {
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);
validateTransactionResource(tx, resourceArn, region);
if (!transactions.remove(transactionId, tx)) {
throw transactionNotFound(transactionId);
}
@@ -187,14 +190,14 @@ public class RdsDataService implements Resettable {
return response;
}
public ObjectNode rollbackTransaction(JsonNode request) {
public ObjectNode rollbackTransaction(JsonNode request, String region) {
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);
validateTransactionResource(tx, resourceArn, region);
if (!transactions.remove(transactionId, tx)) {
throw transactionNotFound(transactionId);
}
@@ -371,21 +374,26 @@ public class RdsDataService implements Resettable {
}
}
private void validateTransactionIdentity(TransactionContext tx, JsonNode request) {
validateTransactionResource(tx, requiredText(request, "resourceArn"));
private void validateTransactionIdentity(
TransactionContext tx, JsonNode request, String region) {
validateTransactionResource(tx, requiredText(request, "resourceArn"), region);
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) {
private void validateTransactionResource(
TransactionContext tx, String resourceArn, String region) {
if (region == null || region.isBlank() || !region.equals(tx.region)) {
throw transactionNotFound(tx.id);
}
if (resourceArn.equals(tx.resourceArn)) {
return;
}
RdsDataResourceResolver.DatabaseTarget target;
try {
target = resourceResolver.resolve(resourceArn);
target = resourceResolver.resolve(resourceArn, region);
} catch (AwsException e) {
throw transactionNotFound(tx.id);
}
@@ -485,14 +493,18 @@ public class RdsDataService implements Resettable {
private final DatabaseEngine engine;
private final String resourceArn;
private final String database;
private final String region;
private volatile Instant expiresAt;
private TransactionContext(String id, Connection connection, DatabaseEngine engine, String resourceArn, String database, Duration ttl) {
private TransactionContext(
String id, Connection connection, DatabaseEngine engine, String resourceArn,
String database, String region, Duration ttl) {
this.id = id;
this.connection = connection;
this.engine = engine;
this.resourceArn = resourceArn;
this.database = database;
this.region = region;
refresh(ttl);
}
@@ -8,6 +8,7 @@ import com.github.dockerjava.api.command.InspectVolumeResponse;
import com.github.dockerjava.api.command.ListVolumesCmd;
import com.github.dockerjava.api.command.ListVolumesResponse;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.RemoveVolumeCmd;
import com.github.dockerjava.api.command.StartContainerCmd;
import com.github.dockerjava.api.command.StopContainerCmd;
import com.github.dockerjava.api.command.WaitContainerCmd;
@@ -158,6 +159,66 @@ class ContainerLifecycleManagerVolumeTest {
assertFalse(manager.volumeExists("some-volume"));
}
@Test
void strictContainerCleanupPropagatesRemovalFailure() {
StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
when(dockerClient.stopContainerCmd("container-id")).thenReturn(stop);
when(dockerClient.removeContainerCmd("container-id")).thenReturn(remove);
when(remove.exec()).thenThrow(new DockerException("remove failed", 500));
IllegalStateException exception = assertThrows(IllegalStateException.class, () ->
manager.stopAndRemoveStrict("container-id", null));
assertEquals("Failed to remove container container-id", exception.getMessage());
}
@Test
void strictContainerCleanupAcceptsSuccessfulForcedRemovalAfterStopFailure() {
StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
when(dockerClient.stopContainerCmd("container-id")).thenReturn(stop);
when(stop.exec()).thenThrow(new DockerException("stop failed", 500));
when(dockerClient.removeContainerCmd("container-id")).thenReturn(remove);
assertDoesNotThrow(() -> manager.stopAndRemoveStrict("container-id", null));
verify(remove).exec();
}
@Test
void strictStaleContainerCleanupPropagatesRemovalFailure() {
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
when(dockerClient.removeContainerCmd("stale-name")).thenReturn(remove);
when(remove.exec()).thenThrow(new DockerException("remove failed", 500));
IllegalStateException exception = assertThrows(IllegalStateException.class, () ->
manager.removeIfExistsStrict("stale-name"));
assertEquals("Failed to remove stale container stale-name", exception.getMessage());
}
@Test
void strictStaleContainerCleanupAcceptsMissingContainer() {
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
when(dockerClient.removeContainerCmd("stale-name")).thenReturn(remove);
when(remove.exec()).thenThrow(new NotFoundException("missing"));
assertDoesNotThrow(() -> manager.removeIfExistsStrict("stale-name"));
}
@Test
void strictVolumeCleanupPropagatesRemovalFailure() {
RemoveVolumeCmd remove = mock(RemoveVolumeCmd.class);
when(dockerClient.removeVolumeCmd("volume-id")).thenReturn(remove);
when(remove.exec()).thenThrow(new DockerException("remove failed", 500));
IllegalStateException exception = assertThrows(IllegalStateException.class, () ->
manager.removeVolumeStrict("volume-id"));
assertEquals("Failed to remove volume volume-id", exception.getMessage());
}
@Test
void tryListVolumeNamesReturnsAuthoritativeSnapshot() {
ListVolumesCmd cmd = mock(ListVolumesCmd.class);
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.core.storage;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -10,6 +11,104 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class AccountAwareStorageBackendTest {
@Test
void guardedLegacyLookupMigratesMatchingRawValue() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
raw.put("resource", "owned");
AccountAwareStorageBackend<String> storage =
new AccountAwareStorageBackend<>(raw, null, "111111111111");
assertEquals("owned", storage.getForAccountMigratingLegacy(
"111111111111", "resource", "owned"::equals).orElseThrow());
assertTrue(raw.get("resource").isEmpty());
assertEquals("owned", raw.get("111111111111/resource").orElseThrow());
}
@Test
void guardedLegacyLookupLeavesRejectedRawValueUntouched() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
raw.put("resource", "foreign");
AccountAwareStorageBackend<String> storage =
new AccountAwareStorageBackend<>(raw, null, "111111111111");
assertTrue(storage.getForAccountMigratingLegacy(
"111111111111", "resource", "owned"::equals).isEmpty());
assertEquals("foreign", raw.get("resource").orElseThrow());
assertTrue(raw.get("111111111111/resource").isEmpty());
}
@Test
void guardedLegacyLookupPrefersExistingScopedValue() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
raw.put("resource", "legacy");
raw.put("111111111111/resource", "scoped");
AccountAwareStorageBackend<String> storage =
new AccountAwareStorageBackend<>(raw, null, "111111111111");
assertEquals("scoped", storage.getForAccountMigratingLegacy(
"111111111111", "resource", value -> true).orElseThrow());
assertEquals("legacy", raw.get("resource").orElseThrow());
assertEquals("scoped", raw.get("111111111111/resource").orElseThrow());
}
@Test
void guardedLegacyLookupCanMigrateToExplicitNonDefaultAccount() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
raw.put("resource", "owned");
AccountAwareStorageBackend<String> storage =
new AccountAwareStorageBackend<>(raw, null, "111111111111");
assertEquals("owned", storage.getForAccountMigratingLegacy(
"222222222222", "resource", value -> true).orElseThrow());
assertTrue(raw.get("resource").isEmpty());
assertEquals("owned", raw.get("222222222222/resource").orElseThrow());
}
@Test
void guardedLegacyKeyLookupMigratesOlderAccountScopedKey() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
raw.put("111111111111/resource", "owned");
AccountAwareStorageBackend<String> storage =
new AccountAwareStorageBackend<>(raw, null, "111111111111");
assertEquals("owned", storage.getForAccountMigratingLegacyKeys(
"111111111111", "us-west-2::resource", List.of("resource"),
"owned"::equals).orElseThrow());
assertTrue(raw.get("111111111111/resource").isEmpty());
assertEquals("owned",
raw.get("111111111111/us-west-2::resource").orElseThrow());
}
@Test
void guardedLegacyKeyLookupDoesNotClaimWrongScope() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
raw.put("111111111111/resource", "us-east-1");
AccountAwareStorageBackend<String> storage =
new AccountAwareStorageBackend<>(raw, null, "111111111111");
assertTrue(storage.getForAccountMigratingLegacyKeys(
"111111111111", "us-west-2::resource", List.of("resource"),
"us-west-2"::equals).isEmpty());
assertEquals("us-east-1", raw.get("111111111111/resource").orElseThrow());
assertTrue(raw.get("111111111111/us-west-2::resource").isEmpty());
}
@Test
void guardedLegacyKeyLookupPreservesOwnedLegacyWhenCanonicalHasWrongOwner() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
raw.put("111111111111/us-west-2::resource", "us-east-1");
raw.put("111111111111/resource", "us-west-2");
AccountAwareStorageBackend<String> storage =
new AccountAwareStorageBackend<>(raw, null, "111111111111");
assertTrue(storage.getForAccountMigratingLegacyKeys(
"111111111111", "us-west-2::resource", List.of("resource"),
"us-west-2"::equals).isEmpty());
assertEquals("us-east-1",
raw.get("111111111111/us-west-2::resource").orElseThrow());
assertEquals("us-west-2", raw.get("111111111111/resource").orElseThrow());
}
@Test
void scanAllAccountsRawAttributesLegacyUnprefixedKeysToDefaultAccount() {
InMemoryStorage<String, String> raw = new InMemoryStorage<>();
@@ -3,11 +3,15 @@ package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.rds.model.DbCluster;
import io.github.hectorvent.floci.services.rds.model.DbEndpoint;
import io.github.hectorvent.floci.services.rds.model.DbInstance;
import io.github.hectorvent.floci.services.rds.model.DbParameterGroup;
import io.github.hectorvent.floci.services.rds.model.DbProxy;
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.SecretVersion;
@@ -16,6 +20,7 @@ import io.github.hectorvent.floci.services.ssm.model.Parameter;
import io.github.hectorvent.floci.services.ssm.model.ParameterHistory;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@@ -23,6 +28,7 @@ import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -90,6 +96,13 @@ class RdsCfnProvisionerTest {
region, "000000000000", "my-stack");
}
private StackResource provisionExisting(String logicalId, String type, String json,
String region, String physicalId,
Map<String, String> attributes) {
return provisioner.provision(logicalId, type, props(json), engine(),
region, "000000000000", "my-stack", physicalId, attributes);
}
@Test
void provisionsDbInstanceWithMappedArgsAndEndpointAttributes() {
DbInstance instance = mock(DbInstance.class);
@@ -775,7 +788,7 @@ class RdsCfnProvisionerTest {
void provisionsDbParameterGroup() {
DbParameterGroup group = mock(DbParameterGroup.class);
when(group.getDbParameterGroupName()).thenReturn("my-pg");
when(rdsService.createDbParameterGroup(any(), any(), any())).thenReturn(group);
when(rdsService.createDbParameterGroup(any(), any(), any(), any())).thenReturn(group);
StackResource r = provision("Pg", "AWS::RDS::DBParameterGroup", """
{"DBParameterGroupName":"my-pg","Family":"postgres16","Description":"params"}
@@ -783,25 +796,254 @@ class RdsCfnProvisionerTest {
assertEquals("my-pg", r.getPhysicalId());
assertEquals("my-pg", r.getAttributes().get("DBParameterGroupName"));
verify(rdsService).createDbParameterGroup("my-pg", "postgres16", "params");
verify(rdsService).createDbParameterGroup(
"my-pg", "postgres16", "params", "us-east-1");
}
@Test
void provisionsDbProxyWithDefaultAuthSchemeEndpointAndArnAttributes() {
DbProxy proxy = mock(DbProxy.class);
when(proxy.getDbProxyName()).thenReturn("app-proxy");
// RDS Proxy endpoint is a bare hostname (clients connect on the engine's default port).
when(proxy.getEndpoint()).thenReturn("host.docker.internal");
when(proxy.getDbProxyArn()).thenReturn("arn:aws:rds:us-east-1:000000000000:db-proxy:prx-abc");
when(proxy.getVpcId()).thenReturn("vpc-default");
when(rdsService.createDbProxy(any(), any(), anyBoolean(), anyBoolean(), any(), any(),
anyList(), anyList(), anyList(), anyInt(), anyBoolean(), anyMap(), any()))
.thenReturn(proxy);
StackResource r = provision("Proxy", "AWS::RDS::DBProxy", """
{"DBProxyName":"app-proxy","EngineFamily":"POSTGRESQL","RequireTLS":true,
"DebugLogging":true,"IdleClientTimeout":120,"DefaultAuthScheme":"IAM_AUTH",
"EndpointNetworkType":"IPV4","TargetConnectionNetworkType":"IPV4",
"RoleArn":"arn:aws:iam::000000000000:role/proxy",
"VpcSubnetIds":["subnet-a","subnet-b"],
"Tags":[{"Key":"owner","Value":"platform"}]}
""");
assertEquals("CREATE_COMPLETE", r.getStatus());
assertEquals("app-proxy", r.getPhysicalId());
// GetAtt "Endpoint" is the (bare-host) proxy endpoint, passed through from the model.
assertEquals("host.docker.internal", r.getAttributes().get("Endpoint"));
assertEquals("arn:aws:rds:us-east-1:000000000000:db-proxy:prx-abc", r.getAttributes().get("DBProxyArn"));
assertEquals("vpc-default", r.getAttributes().get("VpcId"));
verify(rdsService).createDbProxy(eq("app-proxy"), eq("POSTGRESQL"), eq(true), eq(true),
eq("IAM_AUTH"), eq("arn:aws:iam::000000000000:role/proxy"),
eq(List.of("subnet-a", "subnet-b")), eq(List.of()), eq(List.of()),
eq(120), eq(true), eq(Map.of("owner", "platform")), eq("us-east-1"));
}
@Test
void rejectsExplicitlyBlankDbProxyDefaultAuthSchemeBeforeMutation() {
StackResource resource = provision("Proxy", "AWS::RDS::DBProxy", """
{"DBProxyName":"app-proxy","EngineFamily":"POSTGRESQL",
"DefaultAuthScheme":" ",
"RoleArn":"arn:aws:iam::000000000000:role/proxy",
"VpcSubnetIds":["subnet-a","subnet-b"],
"Auth":[{"AuthScheme":"SECRETS",
"SecretArn":"arn:aws:secretsmanager:us-east-1:000000000000:secret:db-AbCdEf",
"IAMAuth":"DISABLED"}]}
""");
assertEquals("CREATE_FAILED", resource.getStatus());
assertTrue(resource.getStatusReason().contains(
"DefaultAuthScheme must be NONE or IAM_AUTH"));
verify(rdsService, never()).createDbProxy(
any(), any(), anyBoolean(), anyBoolean(), any(), any(),
anyList(), anyList(), anyList(), anyInt(), anyBoolean(), anyMap(), any());
}
@Test
void preservesDbProxyAuthUserNameAndDerivesSqlServerEnabledIamAuth() {
DbProxy proxy = mock(DbProxy.class);
when(proxy.getDbProxyName()).thenReturn("sqlserver-proxy");
when(rdsService.createDbProxy(
any(), any(), anyBoolean(), anyBoolean(), any(), any(),
anyList(), anyList(), anyList(), anyInt(), anyBoolean(), anyMap(), any()))
.thenReturn(proxy);
StackResource resource = provision("Proxy", "AWS::RDS::DBProxy", """
{"DBProxyName":"sqlserver-proxy","EngineFamily":"SQLSERVER",
"RoleArn":"arn:aws:iam::000000000000:role/proxy",
"VpcSubnetIds":["subnet-a","subnet-b"],
"Auth":[{"AuthScheme":"SECRETS",
"SecretArn":"arn:aws:secretsmanager:us-east-1:000000000000:secret:db-AbCdEf",
"IAMAuth":"ENABLED","UserName":"database-user",
"ClientPasswordAuthType":"SQL_SERVER_AUTHENTICATION"}]}
""");
assertEquals("CREATE_COMPLETE", resource.getStatus());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<DbProxyAuth>> authCaptor = ArgumentCaptor.forClass(List.class);
verify(rdsService).createDbProxy(
eq("sqlserver-proxy"), eq("SQLSERVER"), eq(false), eq(true), eq("NONE"),
eq("arn:aws:iam::000000000000:role/proxy"),
eq(List.of("subnet-a", "subnet-b")), eq(List.of()), authCaptor.capture(),
eq(1800), eq(false), eq(Map.of()), eq("us-east-1"));
assertEquals("database-user", authCaptor.getValue().getFirst().getUserName());
assertEquals("ENABLED", authCaptor.getValue().getFirst().getIamAuth());
}
@Test
void rejectsUnsupportedDbProxyNetworkTypesBeforeMutation() {
StackResource ipv6 = provision("Proxy", "AWS::RDS::DBProxy", """
{"DBProxyName":"app-proxy","EngineFamily":"POSTGRESQL",
"DefaultAuthScheme":"IAM_AUTH","EndpointNetworkType":"IPV6",
"RoleArn":"arn:aws:iam::000000000000:role/proxy",
"VpcSubnetIds":["subnet-a","subnet-b"]}
""");
assertEquals("CREATE_FAILED", ipv6.getStatus());
assertTrue(ipv6.getStatusReason().contains("IPv4 proxy networking only"));
verify(rdsService, never()).createDbProxy(any(), any(), anyBoolean(), anyBoolean(),
any(), any(), anyList(), anyList(), anyList(), anyInt(), anyBoolean(), anyMap(), any());
}
@Test
void mutableDbProxyUpdatePreservesPhysicalIdentity() {
String proxyArn = "arn:aws:rds:us-west-2:000000000000:db-proxy:prx-abc";
DbProxy existing = mock(DbProxy.class);
when(existing.getDbProxyName()).thenReturn("app-proxy");
when(existing.getEngineFamily()).thenReturn("POSTGRESQL");
when(existing.getVpcSubnetIds()).thenReturn(List.of("subnet-a", "subnet-b"));
when(rdsService.getDbProxy("app-proxy", "us-west-2")).thenReturn(existing);
DbProxy updated = mock(DbProxy.class);
when(updated.getDbProxyName()).thenReturn("app-proxy");
when(updated.getEndpoint()).thenReturn("updated.proxy.local");
when(updated.getDbProxyArn()).thenReturn(proxyArn);
when(rdsService.modifyDbProxy(eq("app-proxy"), eq("NONE"), anyList(), eq(true),
eq(90), eq(true), eq("arn:aws:iam::000000000000:role/proxy"),
eq(List.of("sg-updated")), eq(Map.of("owner", "platform")), eq("us-west-2")))
.thenReturn(updated);
StackResource resource = provisionExisting("Proxy", "AWS::RDS::DBProxy", """
{"DBProxyName":"app-proxy","EngineFamily":"POSTGRESQL","RequireTLS":true,
"DebugLogging":true,"IdleClientTimeout":90,"DefaultAuthScheme":"NONE",
"RoleArn":"arn:aws:iam::000000000000:role/proxy",
"VpcSubnetIds":["subnet-a","subnet-b"],
"VpcSecurityGroupIds":["sg-updated"],
"Tags":[{"Key":"owner","Value":"platform"}],
"Auth":[{"AuthScheme":"SECRETS","SecretArn":"arn:aws:secretsmanager:us-west-2:000000000000:secret:db-AbCdEf","IAMAuth":"DISABLED"}]}
""", "us-west-2", "app-proxy",
Map.of("Endpoint", "old.proxy.local", "DBProxyArn", proxyArn));
assertEquals("CREATE_COMPLETE", resource.getStatus());
assertEquals("app-proxy", resource.getPhysicalId());
assertEquals("updated.proxy.local", resource.getAttributes().get("Endpoint"));
assertEquals(proxyArn, resource.getAttributes().get("DBProxyArn"));
verify(rdsService).getDbProxy("app-proxy", "us-west-2");
verify(rdsService).modifyDbProxy(eq("app-proxy"), eq("NONE"), anyList(), eq(true),
eq(90), eq(true), eq("arn:aws:iam::000000000000:role/proxy"),
eq(List.of("sg-updated")), eq(Map.of("owner", "platform")), eq("us-west-2"));
verify(rdsService, never()).createDbProxy(any(), any(), anyBoolean(), anyBoolean(),
any(), any(), anyList(), anyList(), anyList(), anyInt(), anyBoolean(), anyMap(), any());
}
@Test
void replacementOnlyDbProxyChangeFailsBeforeMutation() {
DbProxy existing = mock(DbProxy.class);
when(existing.getDbProxyName()).thenReturn("app-proxy");
when(existing.getEngineFamily()).thenReturn("POSTGRESQL");
when(existing.getVpcSubnetIds()).thenReturn(List.of("subnet-a", "subnet-b"));
when(rdsService.getDbProxy("app-proxy", "us-east-1")).thenReturn(existing);
StackResource resource = provisionExisting("Proxy", "AWS::RDS::DBProxy", """
{"DBProxyName":"app-proxy","EngineFamily":"MYSQL","DefaultAuthScheme":"IAM_AUTH",
"RoleArn":"arn:aws:iam::000000000000:role/proxy",
"VpcSubnetIds":["subnet-a","subnet-b"]}
""", "us-east-1", "app-proxy", Map.of());
assertEquals("CREATE_FAILED", resource.getStatus());
assertTrue(resource.getStatusReason().contains("requires CloudFormation replacement"));
verify(rdsService, never()).modifyDbProxy(any(), any(), any(), any(), any(), any(),
any(), any(), any(), any());
verify(rdsService, never()).createDbProxy(any(), any(), anyBoolean(), anyBoolean(),
any(), any(), anyList(), anyList(), anyList(), anyInt(), anyBoolean(), anyMap(), any());
}
@Test
void reconcilesCompleteTargetGroupPoolConfigurationInStackRegion() {
String targetGroupArn =
"arn:aws:rds:us-west-2:000000000000:target-group:prx-tg-abc";
DbProxyTargetGroup existing = mock(DbProxyTargetGroup.class);
when(existing.getDbProxyName()).thenReturn("app-proxy");
when(existing.getTargetGroupName()).thenReturn("default");
when(rdsService.getDbProxyTargetGroupByArn(targetGroupArn, "us-west-2"))
.thenReturn(existing);
DbProxy proxy = mock(DbProxy.class);
when(proxy.getEngineFamily()).thenReturn("MYSQL");
when(rdsService.getDbProxy("app-proxy", "us-west-2")).thenReturn(proxy);
DbProxyTargetGroup reconciled = mock(DbProxyTargetGroup.class);
when(reconciled.getDbProxyName()).thenReturn("app-proxy");
when(reconciled.getTargetGroupArn()).thenReturn(targetGroupArn);
when(rdsService.reconcileDbProxyTargetGroup("app-proxy", "default",
List.of("mycluster"), List.of(), 90, 40, 17,
"SET sql_mode='STRICT_ALL_TABLES'", List.of("EXCLUDE_VARIABLE_SETS"),
"us-west-2")).thenReturn(reconciled);
StackResource resource = provisionExisting("Tg", "AWS::RDS::DBProxyTargetGroup", """
{"DBProxyName":"app-proxy","TargetGroupName":"default",
"DBClusterIdentifiers":["mycluster"],
"ConnectionPoolConfigurationInfo":{
"MaxConnectionsPercent":90,
"MaxIdleConnectionsPercent":40,
"ConnectionBorrowTimeout":17,
"InitQuery":"SET sql_mode='STRICT_ALL_TABLES'",
"SessionPinningFilters":["EXCLUDE_VARIABLE_SETS"]}}
""", "us-west-2", targetGroupArn,
Map.of("TargetGroupArn", targetGroupArn, "DBProxyName", "app-proxy"));
assertEquals("CREATE_COMPLETE", resource.getStatus());
assertEquals(targetGroupArn, resource.getPhysicalId());
assertEquals(targetGroupArn, resource.getAttributes().get("TargetGroupArn"));
assertEquals("app-proxy", resource.getAttributes().get("DBProxyName"));
verify(rdsService).getDbProxyTargetGroupByArn(targetGroupArn, "us-west-2");
verify(rdsService).reconcileDbProxyTargetGroup("app-proxy", "default",
List.of("mycluster"), List.of(), 90, 40, 17,
"SET sql_mode='STRICT_ALL_TABLES'", List.of("EXCLUDE_VARIABLE_SETS"),
"us-west-2");
}
@Test
void deleteDelegatesToRdsServiceForEachRdsType() {
// Stack deletion tears down RDS resources via the physical id set at provision time.
provisioner.delete("AWS::RDS::DBInstance", "mydb", "us-east-1");
verify(rdsService).deleteDbInstance("mydb");
verify(rdsService).deleteDbInstance("mydb", "us-east-1");
provisioner.delete("AWS::RDS::DBCluster", "mycluster", "us-east-1");
verify(rdsService).deleteDbCluster("mycluster");
verify(rdsService).deleteDbCluster("mycluster", "us-east-1");
provisioner.delete("AWS::RDS::DBSubnetGroup", "my-subnet-group", "us-east-1");
verify(rdsService).deleteDbSubnetGroup("my-subnet-group");
verify(rdsService).deleteDbSubnetGroup("my-subnet-group", "us-east-1");
provisioner.delete("AWS::RDS::DBParameterGroup", "my-pg", "us-east-1");
verify(rdsService).deleteDbParameterGroup("my-pg");
verify(rdsService).deleteDbParameterGroup("my-pg", "us-east-1");
provisioner.delete("AWS::RDS::DBClusterParameterGroup", "my-cpg", "us-east-1");
verify(rdsService).deleteDbClusterParameterGroup("my-cpg");
verify(rdsService).deleteDbClusterParameterGroup("my-cpg", "us-east-1");
provisioner.delete("AWS::RDS::DBProxy", "app-proxy", "us-east-1");
verify(rdsService).deleteDbProxy("app-proxy", "us-east-1");
provisioner.delete("AWS::RDS::DBProxyTargetGroup",
"arn:aws:rds:us-east-1:000000000000:target-group:prx-tg-abc", "us-east-1");
verify(rdsService).clearDbProxyTargetGroupByArn(
"arn:aws:rds:us-east-1:000000000000:target-group:prx-tg-abc", "us-east-1");
}
@Test
void targetGroupDeleteIsIdempotentWhenProxyDeletionAlreadyRemovedIt() {
String targetGroupArn =
"arn:aws:rds:us-east-1:000000000000:target-group:prx-tg-already-gone";
org.mockito.Mockito.doThrow(new AwsException("DBProxyTargetGroupNotFoundFault",
"target group not found", 404))
.when(rdsService).clearDbProxyTargetGroupByArn(targetGroupArn, "us-east-1");
assertDoesNotThrow(() -> provisioner.delete(
"AWS::RDS::DBProxyTargetGroup", targetGroupArn, "us-east-1"));
verify(rdsService).clearDbProxyTargetGroupByArn(targetGroupArn, "us-east-1");
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudwatch.logs;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogEvent;
import io.github.hectorvent.floci.services.cloudwatch.logs.model.LogGroup;
@@ -67,6 +68,44 @@ class CloudWatchLogsServiceTest {
service.createLogGroup("", null, null, REGION));
}
@Test
void explicitAccountLogWritesRemainIsolatedOutsideRequestContext() {
InMemoryStorage<String, LogGroup> rawGroups = new InMemoryStorage<>();
InMemoryStorage<String, LogStream> rawStreams = new InMemoryStorage<>();
InMemoryStorage<String, LogEvent> rawEvents = new InMemoryStorage<>();
CloudWatchLogsService accountService = new CloudWatchLogsService(
new AccountAwareStorageBackend<>(rawGroups, null, "000000000000"),
new AccountAwareStorageBackend<>(rawStreams, null, "000000000000"),
new AccountAwareStorageBackend<>(rawEvents, null, "000000000000"),
new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, "000000000000"),
10_000, new RegionResolver(REGION, "000000000000"));
String accountA = "111111111111";
String accountB = "222222222222";
for (String accountId : List.of(accountA, accountB)) {
accountService.createLogGroupForAccount(
accountId, "/aws/rds/instance/db1/error", null, null, REGION);
accountService.createLogStreamForAccount(
accountId, "/aws/rds/instance/db1/error", "stream", REGION);
accountService.putLogEventsForAccount(
accountId, "/aws/rds/instance/db1/error", "stream",
List.of(Map.of("timestamp", 1L, "message", accountId)), REGION);
}
String groupKey = REGION + "::/aws/rds/instance/db1/error";
String streamKey = groupKey + "::stream";
assertTrue(rawGroups.get(accountA + "/" + groupKey).isPresent());
assertTrue(rawGroups.get(accountB + "/" + groupKey).isPresent());
assertTrue(rawStreams.get(accountA + "/" + streamKey).isPresent());
assertTrue(rawStreams.get(accountB + "/" + streamKey).isPresent());
assertEquals(1, rawEvents.keys().stream()
.filter(key -> key.startsWith(accountA + "/" + streamKey + "::"))
.count());
assertEquals(1, rawEvents.keys().stream()
.filter(key -> key.startsWith(accountB + "/" + streamKey + "::"))
.count());
}
@Test
void deleteLogGroup() {
service.createLogGroup("/app/logs", null, null, REGION);
@@ -59,6 +59,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@@ -1295,10 +1296,12 @@ class ContainerLauncherTest {
launcherWithRealStreamer.launch(fn);
// The frame became a CloudWatch log event in the function's own log group.
// The frame became a CloudWatch log event in the function's own log group. Forwarding goes
// through the account-aware overload with a null account id: exec streams have no owning
// account of their own, so they land in the default account's copy of the log group.
ArgumentCaptor<List<Map<String, Object>>> events = ArgumentCaptor.forClass(List.class);
verify(cloudWatchLogs, atLeastOnce()).putLogEvents(
eq("/aws/lambda/observability-fn"), anyString(), events.capture(), anyString());
verify(cloudWatchLogs, atLeastOnce()).putLogEventsForAccount(
isNull(), eq("/aws/lambda/observability-fn"), anyString(), events.capture(), anyString());
assertTrue(events.getAllValues().stream()
.flatMap(List::stream)
.anyMatch(e -> "extension started on :8080".equals(e.get("message"))),
@@ -7,6 +7,10 @@ import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup;
import io.github.hectorvent.floci.services.rds.model.DbInstance;
import io.github.hectorvent.floci.services.rds.model.DbInstanceStatus;
import io.github.hectorvent.floci.services.rds.model.DbParameterGroup;
import io.github.hectorvent.floci.services.rds.model.DbProxy;
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
import io.github.hectorvent.floci.services.rds.model.DbProxyTarget;
import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.MultivaluedMap;
@@ -18,7 +22,7 @@ import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/**
@@ -46,7 +50,7 @@ class RdsQueryHandlerTest {
@Test
void describeDbInstances_usesDBInstanceTag() {
DbInstance instance = makeInstance("mydb");
when(service.listDbInstances(null)).thenReturn(List.of(instance));
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
Response response = handler.handle("DescribeDBInstances", params());
@@ -59,7 +63,7 @@ class RdsQueryHandlerTest {
void describeDbInstances_includesDbParameterGroupAttachment() {
DbInstance instance = makeInstance("mydb");
instance.setParameterGroupName("postgres18");
when(service.listDbInstances(null)).thenReturn(List.of(instance));
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
Response response = handler.handle("DescribeDBInstances", params());
@@ -73,7 +77,7 @@ class RdsQueryHandlerTest {
void describeDbInstances_reportsDefaultDbParameterGroupWhenUnattached() {
DbInstance instance = makeInstance("mydb");
instance.setEngineVersion("16.3");
when(service.listDbInstances(null)).thenReturn(List.of(instance));
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
Response response = handler.handle("DescribeDBInstances", params());
@@ -86,33 +90,34 @@ class RdsQueryHandlerTest {
@Test
void describeDbInstances_filterByDirectIdentifier() {
DbInstance instance = makeInstance("mydb");
when(service.listDbInstances("mydb")).thenReturn(List.of(instance));
when(service.listDbInstances("mydb", null)).thenReturn(List.of(instance));
MultivaluedMap<String, String> p = params();
p.add("DBInstanceIdentifier", "mydb");
handler.handle("DescribeDBInstances", p);
verify(service).listDbInstances("mydb");
verify(service).listDbInstances("mydb", null);
}
@Test
void describeDbInstances_filterByFiltersParam() {
DbInstance instance = makeInstance("mydb");
when(service.listDbInstances("mydb")).thenReturn(List.of(instance));
when(service.listDbInstances("mydb", null)).thenReturn(List.of(instance));
MultivaluedMap<String, String> p = params();
p.add("Filters.Filter.1.Name", "db-instance-id");
p.add("Filters.Filter.1.Values.Value.1", "mydb");
handler.handle("DescribeDBInstances", p);
verify(service).listDbInstances("mydb");
verify(service).listDbInstances("mydb", null);
}
@Test
void describeDbInstances_filterByDbiResourceId() {
DbInstance instance = makeInstance("mydb");
instance.setDbiResourceId("db-RESOURCE123");
when(service.listDbInstancesByDbiResourceIds(List.of("db-RESOURCE123", "db-RESOURCE456")))
when(service.listDbInstancesByDbiResourceIds(
List.of("db-RESOURCE123", "db-RESOURCE456"), null))
.thenReturn(List.of(instance));
MultivaluedMap<String, String> p = params();
@@ -121,14 +126,16 @@ class RdsQueryHandlerTest {
p.add("Filters.Filter.1.Values.Value.2", "db-RESOURCE456");
Response response = handler.handle("DescribeDBInstances", p);
verify(service).listDbInstancesByDbiResourceIds(List.of("db-RESOURCE123", "db-RESOURCE456"));
verify(service).listDbInstancesByDbiResourceIds(
List.of("db-RESOURCE123", "db-RESOURCE456"), null);
String body = (String) response.getEntity();
assertTrue(body.contains("<DBInstanceIdentifier>mydb</DBInstanceIdentifier>"));
}
@Test
void describeDbInstances_directIdentifierTakesPriorityOverFilters() {
when(service.listDbInstances(any())).thenReturn(List.of());
when(service.listDbInstances(any(), org.mockito.ArgumentMatchers.isNull()))
.thenReturn(List.of());
MultivaluedMap<String, String> p = params();
p.add("DBInstanceIdentifier", "direct-id");
@@ -136,15 +143,15 @@ class RdsQueryHandlerTest {
p.add("Filters.Filter.1.Values.Value.1", "filter-id");
handler.handle("DescribeDBInstances", p);
verify(service).listDbInstances("direct-id");
verify(service).listDbInstances("direct-id", null);
}
@Test
void describeDbInstances_dbSubnetGroupUsesSubnetTag() {
DbInstance instance = makeInstance("mydb");
instance.setDbSubnetGroupName("custom-group");
when(service.getDbSubnetGroup("custom-group")).thenReturn(customSubnetGroup());
when(service.listDbInstances(null)).thenReturn(List.of(instance));
when(service.getDbSubnetGroup("custom-group", null)).thenReturn(customSubnetGroup());
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
Response response = handler.handle("DescribeDBInstances", params());
@@ -160,7 +167,7 @@ class RdsQueryHandlerTest {
@Test
void describeDbClusters_usesDBClusterTag() {
DbCluster cluster = makeCluster("mycluster");
when(service.listDbClusters(null)).thenReturn(List.of(cluster));
when(service.listDbClusters(null, null)).thenReturn(List.of(cluster));
Response response = handler.handle("DescribeDBClusters", params());
@@ -171,34 +178,139 @@ class RdsQueryHandlerTest {
@Test
void describeDbClusters_filterByFiltersParam() {
when(service.listDbClusters("mycluster")).thenReturn(List.of());
when(service.listDbClusters("mycluster", null)).thenReturn(List.of());
MultivaluedMap<String, String> p = params();
p.add("Filters.Filter.1.Name", "db-cluster-id");
p.add("Filters.Filter.1.Values.Value.1", "mycluster");
handler.handle("DescribeDBClusters", p);
verify(service).listDbClusters("mycluster");
verify(service).listDbClusters("mycluster", null);
}
@Test
void describeDbInstances_unknownFilterFallsBackToUnfilteredList() {
when(service.listDbInstances(null)).thenReturn(List.of());
when(service.listDbInstances(null, null)).thenReturn(List.of());
MultivaluedMap<String, String> p = params();
p.add("Filters.Filter.1.Name", "engine");
p.add("Filters.Filter.1.Values.Value.1", "postgres");
handler.handle("DescribeDBInstances", p);
verify(service).listDbInstances(null);
verify(service).listDbInstances(null, null);
}
@Test
void instanceAndClusterActionsPropagateSignedRegion() {
DbInstance instance = makeInstance("mydb");
DbCluster cluster = makeCluster("mycluster");
when(service.listDbInstances(null, "us-west-2")).thenReturn(List.of());
when(service.getDbInstance("mydb", "us-west-2")).thenReturn(instance);
when(service.modifyDbInstance(
eq("mydb"), isNull(), isNull(), isNull(), anyList(), eq("us-west-2")))
.thenReturn(instance);
when(service.rebootDbInstance("mydb", "us-west-2")).thenReturn(instance);
when(service.listDbClusters(null, "us-west-2")).thenReturn(List.of());
when(service.getDbCluster("mycluster", "us-west-2")).thenReturn(cluster);
when(service.modifyDbCluster("mycluster", null, null, "us-west-2"))
.thenReturn(cluster);
handler.handle("DescribeDBInstances", params(), "us-west-2");
MultivaluedMap<String, String> instanceParams = params();
instanceParams.add("DBInstanceIdentifier", "mydb");
handler.handle("DeleteDBInstance", instanceParams, "us-west-2");
handler.handle("ModifyDBInstance", instanceParams, "us-west-2");
handler.handle("RebootDBInstance", instanceParams, "us-west-2");
handler.handle("DescribeDBClusters", params(), "us-west-2");
MultivaluedMap<String, String> clusterParams = params();
clusterParams.add("DBClusterIdentifier", "mycluster");
handler.handle("DeleteDBCluster", clusterParams, "us-west-2");
handler.handle("ModifyDBCluster", clusterParams, "us-west-2");
verify(service).listDbInstances(null, "us-west-2");
verify(service).getDbInstance("mydb", "us-west-2");
verify(service).deleteDbInstance("mydb", "us-west-2");
verify(service).modifyDbInstance(
eq("mydb"), isNull(), isNull(), isNull(), anyList(), eq("us-west-2"));
verify(service).rebootDbInstance("mydb", "us-west-2");
verify(service).listDbClusters(null, "us-west-2");
verify(service).getDbCluster("mycluster", "us-west-2");
verify(service).deleteDbCluster("mycluster", "us-west-2");
verify(service).modifyDbCluster("mycluster", null, null, "us-west-2");
}
@Test
void subnetAndParameterGroupActionsPropagateSignedRegion() {
DbSubnetGroup subnetGroup = customSubnetGroup();
DbParameterGroup parameterGroup = new DbParameterGroup(
"pg1", "postgres16", "parameter group");
DbClusterParameterGroup clusterParameterGroup = new DbClusterParameterGroup(
"cpg1", "aurora-postgresql16", "cluster parameter group");
when(service.modifyDbSubnetGroup(
"custom-group", List.of("subnet-a", "subnet-b"), "us-west-2"))
.thenReturn(subnetGroup);
when(service.listDbParameterGroups(null, "us-west-2"))
.thenReturn(List.of(parameterGroup));
when(service.getDbParameterGroup("pg1", "us-west-2"))
.thenReturn(parameterGroup);
when(service.modifyDbParameterGroup(
"pg1", Map.of("max_connections", "200"), "us-west-2"))
.thenReturn(parameterGroup);
when(service.listDbClusterParameterGroups(null, "us-west-2"))
.thenReturn(List.of(clusterParameterGroup));
when(service.getDbClusterParameterGroup("cpg1", "us-west-2"))
.thenReturn(clusterParameterGroup);
when(service.modifyDbClusterParameterGroup(
"cpg1", Map.of("log_statement", "all"), "us-west-2"))
.thenReturn(clusterParameterGroup);
MultivaluedMap<String, String> subnetParams = params();
subnetParams.add("DBSubnetGroupName", "custom-group");
subnetParams.add("SubnetIds.SubnetIdentifier.1", "subnet-a");
subnetParams.add("SubnetIds.SubnetIdentifier.2", "subnet-b");
handler.handle("ModifyDBSubnetGroup", subnetParams, "us-west-2");
handler.handle("DeleteDBSubnetGroup", subnetParams, "us-west-2");
handler.handle("DescribeDBParameterGroups", params(), "us-west-2");
MultivaluedMap<String, String> parameterParams = params();
parameterParams.add("DBParameterGroupName", "pg1");
parameterParams.add("Parameters.member.1.ParameterName", "max_connections");
parameterParams.add("Parameters.member.1.ParameterValue", "200");
handler.handle("ModifyDBParameterGroup", parameterParams, "us-west-2");
handler.handle("DescribeDBParameters", parameterParams, "us-west-2");
handler.handle("DeleteDBParameterGroup", parameterParams, "us-west-2");
handler.handle("DescribeDBClusterParameterGroups", params(), "us-west-2");
MultivaluedMap<String, String> clusterParameterParams = params();
clusterParameterParams.add("DBClusterParameterGroupName", "cpg1");
clusterParameterParams.add("Parameters.member.1.ParameterName", "log_statement");
clusterParameterParams.add("Parameters.member.1.ParameterValue", "all");
handler.handle("ModifyDBClusterParameterGroup", clusterParameterParams, "us-west-2");
handler.handle("DescribeDBClusterParameters", clusterParameterParams, "us-west-2");
handler.handle("DeleteDBClusterParameterGroup", clusterParameterParams, "us-west-2");
verify(service).modifyDbSubnetGroup(
"custom-group", List.of("subnet-a", "subnet-b"), "us-west-2");
verify(service).deleteDbSubnetGroup("custom-group", "us-west-2");
verify(service).listDbParameterGroups(null, "us-west-2");
verify(service).modifyDbParameterGroup(
"pg1", Map.of("max_connections", "200"), "us-west-2");
verify(service).getDbParameterGroup("pg1", "us-west-2");
verify(service).deleteDbParameterGroup("pg1", "us-west-2");
verify(service).listDbClusterParameterGroups(null, "us-west-2");
verify(service).modifyDbClusterParameterGroup(
"cpg1", Map.of("log_statement", "all"), "us-west-2");
verify(service).getDbClusterParameterGroup("cpg1", "us-west-2");
verify(service).deleteDbClusterParameterGroup("cpg1", "us-west-2");
}
@Test
void describeDbInstances_usesStoredDbSubnetGroup() {
DbInstance instance = makeInstance("mydb");
instance.setDbSubnetGroupName("sample-db-subnets");
when(service.listDbInstances(null)).thenReturn(List.of(instance));
when(service.getDbSubnetGroup("sample-db-subnets")).thenReturn(new DbSubnetGroup(
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
when(service.getDbSubnetGroup("sample-db-subnets", null)).thenReturn(new DbSubnetGroup(
"sample-db-subnets", "test subnets", "vpc-123", List.of("subnet-aaa", "subnet-bbb"),
Map.of("subnet-aaa", "us-east-1a", "subnet-bbb", "us-east-1b")));
@@ -215,7 +327,7 @@ class RdsQueryHandlerTest {
void describeDbInstances_includesTagList() {
DbInstance instance = makeInstance("mydb");
instance.setTags(java.util.Map.of("example:ClusterId", "cluster-a", "Name", "mydb"));
when(service.listDbInstances(null)).thenReturn(List.of(instance));
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
Response response = handler.handle("DescribeDBInstances", params());
@@ -301,22 +413,27 @@ class RdsQueryHandlerTest {
assertEquals(400, response.getStatus());
assertTrue(((String) response.getEntity()).contains("InvalidParameterValue"));
verify(service, never()).modifyDbInstance(any(), any(), any(), any(), any());
verify(service, never()).modifyDbInstance(
any(), any(), any(), any(), any(), any());
}
@Test
void listTagsForResource_returnsStoredTags() {
when(service.listTagsForResource("arn:aws:rds:us-east-1:000000000000:db:mydb"))
when(service.listTagsForResource(
"arn:aws:rds:us-east-1:000000000000:db:mydb", "us-west-2"))
.thenReturn(java.util.Map.of("Name", "mydb"));
MultivaluedMap<String, String> p = params();
p.add("ResourceName", "arn:aws:rds:us-east-1:000000000000:db:mydb");
Response response = handler.handle("ListTagsForResource", p);
Response response = handler.handle("ListTagsForResource", p, "us-west-2");
String body = (String) response.getEntity();
assertEquals(200, response.getStatus());
assertTrue(body.contains("<TagList>"));
assertTrue(body.contains("<Key>Name</Key>"));
assertTrue(body.contains("<Value>mydb</Value>"));
verify(service).listTagsForResource(
"arn:aws:rds:us-east-1:000000000000:db:mydb", "us-west-2");
}
@Test
@@ -325,16 +442,22 @@ class RdsQueryHandlerTest {
add.add("ResourceName", "arn:aws:rds:us-east-1:000000000000:db:mydb");
add.add("Tags.member.1.Key", "Name");
add.add("Tags.member.1.Value", "mydb");
handler.handle("AddTagsToResource", add);
Response addResponse = handler.handle("AddTagsToResource", add, "us-west-2");
verify(service).addTagsToResource("arn:aws:rds:us-east-1:000000000000:db:mydb", java.util.Map.of("Name", "mydb"));
assertEquals(200, addResponse.getStatus());
verify(service).addTagsToResource(
"arn:aws:rds:us-east-1:000000000000:db:mydb",
java.util.Map.of("Name", "mydb"), "us-west-2");
MultivaluedMap<String, String> remove = params();
remove.add("ResourceName", "arn:aws:rds:us-east-1:000000000000:db:mydb");
remove.add("TagKeys.member.1", "Name");
handler.handle("RemoveTagsFromResource", remove);
Response removeResponse = handler.handle("RemoveTagsFromResource", remove, "us-west-2");
verify(service).removeTagsFromResource("arn:aws:rds:us-east-1:000000000000:db:mydb", List.of("Name"));
assertEquals(200, removeResponse.getStatus());
verify(service).removeTagsFromResource(
"arn:aws:rds:us-east-1:000000000000:db:mydb",
List.of("Name"), "us-west-2");
}
@Test
@@ -362,7 +485,7 @@ class RdsQueryHandlerTest {
@Test
void describeDbParameterGroups_usesDBParameterGroupTag() {
DbParameterGroup group = new DbParameterGroup("pg1", "postgres15", "test group");
when(service.listDbParameterGroups(null)).thenReturn(List.of(group));
when(service.listDbParameterGroups(null, null)).thenReturn(List.of(group));
Response response = handler.handle("DescribeDBParameterGroups", params());
@@ -571,7 +694,8 @@ class RdsQueryHandlerTest {
@Test
void modifyDbParameterGroup_ignoresParametersWithoutValue() {
DbParameterGroup group = new DbParameterGroup("pg1", "postgres15", "test group");
when(service.modifyDbParameterGroup(eq("pg1"), eq(java.util.Map.of("max_connections", "200"))))
when(service.modifyDbParameterGroup(
eq("pg1"), eq(java.util.Map.of("max_connections", "200")), isNull()))
.thenReturn(group);
MultivaluedMap<String, String> p = params();
@@ -581,7 +705,8 @@ class RdsQueryHandlerTest {
p.add("Parameters.member.2.ParameterName", "ignored_without_value");
handler.handle("ModifyDBParameterGroup", p);
verify(service).modifyDbParameterGroup("pg1", java.util.Map.of("max_connections", "200"));
verify(service).modifyDbParameterGroup(
"pg1", java.util.Map.of("max_connections", "200"), null);
}
@Test
@@ -605,7 +730,7 @@ class RdsQueryHandlerTest {
@Test
void describeDbClusterParameterGroups_usesDBClusterParameterGroupTag() {
DbClusterParameterGroup group = new DbClusterParameterGroup("cpg1", "aurora-postgresql16", "test cluster group");
when(service.listDbClusterParameterGroups(null)).thenReturn(List.of(group));
when(service.listDbClusterParameterGroups(null, null)).thenReturn(List.of(group));
Response response = handler.handle("DescribeDBClusterParameterGroups", params());
@@ -634,7 +759,8 @@ class RdsQueryHandlerTest {
@Test
void createDbClusterParameterGroup_passesArgumentsToService() {
DbClusterParameterGroup group = new DbClusterParameterGroup("cpg1", "aurora-postgresql16", "desc");
when(service.createDbClusterParameterGroup("cpg1", "aurora-postgresql16", "desc")).thenReturn(group);
when(service.createDbClusterParameterGroup(
"cpg1", "aurora-postgresql16", "desc", null)).thenReturn(group);
MultivaluedMap<String, String> p = params();
p.add("DBClusterParameterGroupName", "cpg1");
@@ -642,7 +768,8 @@ class RdsQueryHandlerTest {
p.add("Description", "desc");
Response response = handler.handle("CreateDBClusterParameterGroup", p);
verify(service).createDbClusterParameterGroup("cpg1", "aurora-postgresql16", "desc");
verify(service).createDbClusterParameterGroup(
"cpg1", "aurora-postgresql16", "desc", null);
String body = (String) response.getEntity();
assertTrue(body.contains("<DBClusterParameterGroupName>cpg1</DBClusterParameterGroupName>"));
assertTrue(body.contains("<DBParameterGroupFamily>aurora-postgresql16</DBParameterGroupFamily>"));
@@ -651,7 +778,8 @@ class RdsQueryHandlerTest {
@Test
void modifyDbClusterParameterGroup_ignoresParametersWithoutValue() {
DbClusterParameterGroup group = new DbClusterParameterGroup("cpg1", "aurora-postgresql16", "test group");
when(service.modifyDbClusterParameterGroup(eq("cpg1"), eq(java.util.Map.of("log_statement", "all"))))
when(service.modifyDbClusterParameterGroup(
eq("cpg1"), eq(java.util.Map.of("log_statement", "all")), isNull()))
.thenReturn(group);
MultivaluedMap<String, String> p = params();
@@ -661,7 +789,8 @@ class RdsQueryHandlerTest {
p.add("Parameters.member.2.ParameterName", "ignored_without_value");
handler.handle("ModifyDBClusterParameterGroup", p);
verify(service).modifyDbClusterParameterGroup("cpg1", java.util.Map.of("log_statement", "all"));
verify(service).modifyDbClusterParameterGroup(
"cpg1", java.util.Map.of("log_statement", "all"), null);
}
@Test
@@ -685,7 +814,7 @@ class RdsQueryHandlerTest {
@Test
void describeDbClusters_dbSubnetGroupIsPlainString() {
DbCluster cluster = makeCluster("mycluster");
when(service.listDbClusters(null)).thenReturn(List.of(cluster));
when(service.listDbClusters(null, null)).thenReturn(List.of(cluster));
Response response = handler.handle("DescribeDBClusters", params());
@@ -775,6 +904,512 @@ class RdsQueryHandlerTest {
assertFalse(body.contains("<Marker>"));
}
// ──────────────────────────── DBProxy wire shapes ──────────────────────────
@Test
void createDbProxy_mapsParamsAndReturnsProxyEnvelope() {
DbProxy proxy = new DbProxy();
proxy.setDbProxyName("app-proxy");
proxy.setEngineFamily("POSTGRESQL");
proxy.setEndpointHost("app-proxy.host");
proxy.setDbProxyArn("arn:aws:rds:us-west-2:000000000000:db-proxy:prx-abc");
proxy.setDefaultAuthScheme("IAM_AUTH");
proxy.setIdleClientTimeout(120);
proxy.setDebugLogging(true);
proxy.setVpcId("vpc-default");
proxy.setVpcSecurityGroupIds(List.of("sg-a"));
DbProxyAuth proxyAuth = new DbProxyAuth("SECRETS", "arn:secret", "DISABLED",
"POSTGRES_SCRAM_SHA_256", "application credentials");
proxyAuth.setUserName("database-user");
proxy.setAuth(List.of(proxyAuth));
when(service.createDbProxy(eq("app-proxy"), eq("POSTGRESQL"), eq(true), eq(true),
eq("IAM_AUTH"), eq("arn:aws:iam::000000000000:role/proxy"),
anyList(), anyList(), anyList(),
eq(120), eq(true), eq(Map.of("owner", "platform")), eq("us-west-2")))
.thenReturn(proxy);
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
p.add("EngineFamily", "POSTGRESQL");
p.add("DefaultAuthScheme", "IAM_AUTH");
p.add("EndpointNetworkType", "IPV4");
p.add("TargetConnectionNetworkType", "IPV4");
p.add("RequireTLS", "true");
p.add("DebugLogging", "true");
p.add("IdleClientTimeout", "120");
p.add("RoleArn", "arn:aws:iam::000000000000:role/proxy");
p.add("VpcSubnetIds.member.1", "subnet-a");
p.add("VpcSubnetIds.member.2", "subnet-b");
p.add("VpcSecurityGroupIds.member.1", "sg-a");
p.add("Tags.Tag.1.Key", "owner");
p.add("Tags.Tag.1.Value", "platform");
p.add("Auth.member.1.AuthScheme", "SECRETS");
p.add("Auth.member.1.SecretArn", "arn:aws:secretsmanager:us-east-1:000000000000:secret:db-AbCdEf");
p.add("Auth.member.1.IAMAuth", "DISABLED");
p.add("Auth.member.1.UserName", "database-user");
Response response = handler.handle("CreateDBProxy", p, "us-west-2");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<CreateDBProxyResult>"));
assertTrue(body.contains("<DBProxy>"));
assertTrue(body.contains("<DBProxyName>app-proxy</DBProxyName>"));
assertTrue(body.contains("<Endpoint>app-proxy.host</Endpoint>"));
assertTrue(body.contains("<DBProxyArn>arn:aws:rds:us-west-2:000000000000:db-proxy:prx-abc</DBProxyArn>"));
assertTrue(body.contains("<DefaultAuthScheme>IAM_AUTH</DefaultAuthScheme>"));
assertTrue(body.contains("<EndpointNetworkType>IPV4</EndpointNetworkType>"));
assertTrue(body.contains("<TargetConnectionNetworkType>IPV4</TargetConnectionNetworkType>"));
assertTrue(body.contains("<VpcId>vpc-default</VpcId>"));
assertTrue(body.contains("<IdleClientTimeout>120</IdleClientTimeout>"));
assertTrue(body.contains("<DebugLogging>true</DebugLogging>"));
assertTrue(body.contains("<VpcSecurityGroupIds><member>sg-a</member></VpcSecurityGroupIds>"));
assertTrue(body.contains("<ClientPasswordAuthType>POSTGRES_SCRAM_SHA_256</ClientPasswordAuthType>"));
assertTrue(body.contains("<Description>application credentials</Description>"));
assertTrue(body.contains("<UserName>database-user</UserName>"));
// DefaultAuthScheme=IAM_AUTH enables IAM even when the Auth entry itself is DISABLED.
verify(service).createDbProxy(eq("app-proxy"), eq("POSTGRESQL"), eq(true), eq(true),
eq("IAM_AUTH"), eq("arn:aws:iam::000000000000:role/proxy"),
anyList(), anyList(), argThat(auth -> auth.size() == 1
&& "database-user".equals(auth.getFirst().getUserName())),
eq(120), eq(true), eq(Map.of("owner", "platform")), eq("us-west-2"));
}
@Test
void createSqlServerDbProxyEnablesIamFromAuthEntryAndPreservesUserName() {
DbProxy proxy = new DbProxy();
proxy.setDbProxyName("sqlserver-proxy");
proxy.setEngineFamily("SQLSERVER");
proxy.setEndpointHost("sqlserver-proxy.host");
proxy.setDbProxyArn(
"arn:aws:rds:us-west-2:000000000000:db-proxy:prx-sqlserver");
DbProxyAuth returnedAuth = new DbProxyAuth(
"SECRETS", "arn:aws:secretsmanager:us-west-2:000000000000:secret:sqlserver",
"ENABLED", "SQL_SERVER_AUTHENTICATION", "SQL Server credentials");
returnedAuth.setUserName("database-user");
proxy.setAuth(List.of(returnedAuth));
when(service.createDbProxy(
eq("sqlserver-proxy"), eq("SQLSERVER"), eq(true), eq(true), isNull(),
eq("arn:aws:iam::000000000000:role/proxy"), anyList(), anyList(),
argThat(auth -> auth.size() == 1
&& "ENABLED".equals(auth.getFirst().getIamAuth())
&& "database-user".equals(auth.getFirst().getUserName())),
eq(1800), eq(false), eq(Map.of()), eq("us-west-2")))
.thenReturn(proxy);
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "sqlserver-proxy");
p.add("EngineFamily", "SQLSERVER");
p.add("RequireTLS", "true");
p.add("RoleArn", "arn:aws:iam::000000000000:role/proxy");
p.add("VpcSubnetIds.member.1", "subnet-a");
p.add("VpcSubnetIds.member.2", "subnet-b");
p.add("Auth.member.1.AuthScheme", "SECRETS");
p.add("Auth.member.1.SecretArn",
"arn:aws:secretsmanager:us-west-2:000000000000:secret:sqlserver");
p.add("Auth.member.1.IAMAuth", "ENABLED");
p.add("Auth.member.1.ClientPasswordAuthType", "SQL_SERVER_AUTHENTICATION");
p.add("Auth.member.1.UserName", "database-user");
Response response = handler.handle("CreateDBProxy", p, "us-west-2");
assertEquals(200, response.getStatus());
verify(service).createDbProxy(
eq("sqlserver-proxy"), eq("SQLSERVER"), eq(true), eq(true), isNull(),
eq("arn:aws:iam::000000000000:role/proxy"), anyList(), anyList(),
argThat(auth -> auth.size() == 1
&& "ENABLED".equals(auth.getFirst().getIamAuth())
&& "database-user".equals(auth.getFirst().getUserName())),
eq(1800), eq(false), eq(Map.of()), eq("us-west-2"));
}
@Test
void createDbProxyRejectsUnsupportedOrInvalidNetworkTypesBeforeCallingService() {
MultivaluedMap<String, String> ipv6 = params();
ipv6.add("EndpointNetworkType", "IPV6");
Response ipv6Response = handler.handle("CreateDBProxy", ipv6, "us-west-2");
assertEquals(400, ipv6Response.getStatus());
assertTrue(((String) ipv6Response.getEntity()).contains("UnsupportedOperation"));
MultivaluedMap<String, String> invalidTargetType = params();
invalidTargetType.add("TargetConnectionNetworkType", "DUAL");
Response invalidResponse = handler.handle(
"CreateDBProxy", invalidTargetType, "us-west-2");
assertEquals(400, invalidResponse.getStatus());
assertTrue(((String) invalidResponse.getEntity()).contains("InvalidParameterValue"));
verifyNoInteractions(service);
}
@Test
void modifyDbProxy_mapsOptionalFieldsAndReturnsUpdatedProxy() {
DbProxy proxy = new DbProxy();
proxy.setDbProxyName("app-proxy");
proxy.setDbProxyArn("arn:aws:rds:us-west-2:000000000000:db-proxy:prx-abc");
proxy.setEngineFamily("POSTGRESQL");
proxy.setEndpointHost("app-proxy.host");
proxy.setDefaultAuthScheme("IAM_AUTH");
proxy.setRequireTls(false);
proxy.setIdleClientTimeout(900);
proxy.setDebugLogging(true);
proxy.setRoleArn("arn:aws:iam::000000000000:role/updated-proxy");
proxy.setVpcSecurityGroupIds(List.of("sg-a", "sg-b"));
proxy.setAuth(List.of(new DbProxyAuth(
"SECRETS", "arn:secret", "DISABLED", "POSTGRES_MD5", "updated")));
when(service.modifyDbProxy(
eq("app-proxy"), eq("IAM_AUTH"), anyList(), eq(false), eq(900), eq(true),
eq("arn:aws:iam::000000000000:role/updated-proxy"),
eq(List.of("sg-a", "sg-b")), isNull(), eq("us-west-2")))
.thenReturn(proxy);
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
p.add("DefaultAuthScheme", "IAM_AUTH");
p.add("RequireTLS", "false");
p.add("IdleClientTimeout", "900");
p.add("DebugLogging", "true");
p.add("RoleArn", "arn:aws:iam::000000000000:role/updated-proxy");
p.add("SecurityGroups.member.1", "sg-a");
p.add("SecurityGroups.member.2", "sg-b");
p.add("Auth.member.1.AuthScheme", "SECRETS");
p.add("Auth.member.1.SecretArn", "arn:secret");
p.add("Auth.member.1.IAMAuth", "DISABLED");
p.add("Auth.member.1.ClientPasswordAuthType", "POSTGRES_MD5");
p.add("Auth.member.1.Description", "updated");
Response response = handler.handle("ModifyDBProxy", p, "us-west-2");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<ModifyDBProxyResult>"));
assertTrue(body.contains("<DefaultAuthScheme>IAM_AUTH</DefaultAuthScheme>"));
assertTrue(body.contains("<RequireTLS>false</RequireTLS>"));
assertTrue(body.contains("<IdleClientTimeout>900</IdleClientTimeout>"));
assertTrue(body.contains("<DebugLogging>true</DebugLogging>"));
assertTrue(body.contains("<VpcSecurityGroupIds><member>sg-a</member><member>sg-b</member>"));
assertTrue(body.contains("<ClientPasswordAuthType>POSTGRES_MD5</ClientPasswordAuthType>"));
verify(service).modifyDbProxy(
eq("app-proxy"), eq("IAM_AUTH"), argThat(auth -> auth.size() == 1
&& "arn:secret".equals(auth.getFirst().getSecretArn())
&& "DISABLED".equals(auth.getFirst().getIamAuth())),
eq(false), eq(900), eq(true),
eq("arn:aws:iam::000000000000:role/updated-proxy"),
eq(List.of("sg-a", "sg-b")), isNull(), eq("us-west-2"));
}
@Test
void modifyDbProxy_rejectsMalformedOptionalValuesBeforeCallingService() {
MultivaluedMap<String, String> invalidBoolean = params();
invalidBoolean.add("DBProxyName", "app-proxy");
invalidBoolean.add("RequireTLS", "sometimes");
Response booleanResponse = handler.handle(
"ModifyDBProxy", invalidBoolean, "us-west-2");
assertEquals(400, booleanResponse.getStatus());
assertTrue(((String) booleanResponse.getEntity()).contains("InvalidParameterValue"));
assertTrue(((String) booleanResponse.getEntity()).contains("RequireTLS"));
MultivaluedMap<String, String> invalidInteger = params();
invalidInteger.add("DBProxyName", "app-proxy");
invalidInteger.add("IdleClientTimeout", "not-an-integer");
Response integerResponse = handler.handle(
"ModifyDBProxy", invalidInteger, "us-west-2");
assertEquals(400, integerResponse.getStatus());
assertTrue(((String) integerResponse.getEntity()).contains("InvalidParameterValue"));
assertTrue(((String) integerResponse.getEntity()).contains("IdleClientTimeout"));
verifyNoInteractions(service);
}
@Test
void modifyDbProxy_rejectsNewDbProxyNameBeforeCallingService() {
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
p.add("NewDBProxyName", "renamed-proxy");
Response response = handler.handle("ModifyDBProxy", p, "us-west-2");
assertEquals(400, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("UnsupportedOperation"));
assertTrue(body.contains("NewDBProxyName"));
verifyNoInteractions(service);
}
@Test
void describeDbProxies_rendersProxyMembers() {
DbProxy proxy = new DbProxy();
proxy.setDbProxyName("app-proxy");
proxy.setEndpointHost("app-proxy.host");
proxy.setDbProxyArn("arn:aws:rds:us-east-1:000000000000:db-proxy:prx-abc");
when(service.listDbProxies("app-proxy", "us-west-2")).thenReturn(List.of(proxy));
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
Response response = handler.handle("DescribeDBProxies", p, "us-west-2");
String body = (String) response.getEntity();
assertEquals(200, response.getStatus());
assertTrue(body.contains("<DescribeDBProxiesResult>"));
assertTrue(body.contains("<DBProxies><member>"));
assertTrue(body.contains("<DBProxyName>app-proxy</DBProxyName>"));
verify(service).listDbProxies("app-proxy", "us-west-2");
}
@Test
void registerDbProxyTargets_mapsClusterIdsAndRendersTargets() {
DbProxyTargetGroup tg = new DbProxyTargetGroup();
tg.setDbProxyName("app-proxy");
tg.getTargets().add(new DbProxyTarget("TRACKED_CLUSTER", "cluster1",
"arn:aws:rds:us-east-1:000000000000:cluster:cluster1", "cluster1.host", 5432));
when(service.registerDbProxyTargets(
any(), any(), anyList(), anyList(), anyInt(), anyInt(), any()))
.thenReturn(tg);
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
p.add("TargetGroupName", "default");
p.add("DBClusterIdentifiers.member.1", "cluster1");
Response response = handler.handle("RegisterDBProxyTargets", p, "us-west-2");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<RegisterDBProxyTargetsResult>"));
assertTrue(body.contains("<DBProxyTargets><member>"));
assertTrue(body.contains("<Type>TRACKED_CLUSTER</Type>"));
assertTrue(body.contains("<RdsResourceId>cluster1</RdsResourceId>"));
verify(service).registerDbProxyTargets(
"app-proxy", "default", List.of("cluster1"), List.of(), 0, 0, "us-west-2");
}
@Test
void registerDbProxyTargets_defaultsOmittedTargetGroupName() {
DbProxyTargetGroup targetGroup = new DbProxyTargetGroup();
targetGroup.setDbProxyName("app-proxy");
when(service.registerDbProxyTargets(
"app-proxy", null, List.of(), List.of("instance1"), 0, 0, "us-west-2"))
.thenReturn(targetGroup);
MultivaluedMap<String, String> params = params();
params.add("DBProxyName", "app-proxy");
params.add("DBInstanceIdentifiers.member.1", "instance1");
Response response = handler.handle(
"RegisterDBProxyTargets", params, "us-west-2");
assertEquals(200, response.getStatus());
verify(service).registerDbProxyTargets(
"app-proxy", null, List.of(), List.of("instance1"), 0, 0, "us-west-2");
}
@Test
void deregisterDbProxyTargetsMapsIdentifiersAndReturnsEmptyResult() {
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
p.add("TargetGroupName", "default");
p.add("DBInstanceIdentifiers.member.1", "instance1");
Response response = handler.handle("DeregisterDBProxyTargets", p, "us-west-2");
assertEquals(200, response.getStatus());
assertTrue(((String) response.getEntity()).contains("<DeregisterDBProxyTargetsResult>"));
verify(service).deregisterDbProxyTargets("app-proxy", "default",
List.of(), List.of("instance1"), "us-west-2");
}
@Test
void deregisterDbProxyTargets_defaultsOmittedTargetGroupName() {
MultivaluedMap<String, String> params = params();
params.add("DBProxyName", "app-proxy");
params.add("DBClusterIdentifiers.member.1", "cluster1");
Response response = handler.handle(
"DeregisterDBProxyTargets", params, "us-west-2");
assertEquals(200, response.getStatus());
verify(service).deregisterDbProxyTargets(
"app-proxy", null, List.of("cluster1"), List.of(), "us-west-2");
}
@Test
void describeDbProxyTargetGroups_rendersTargetGroupMembers() {
DbProxyTargetGroup tg = new DbProxyTargetGroup();
tg.setDbProxyName("app-proxy");
tg.setTargetGroupName("default");
tg.setTargetGroupArn("arn:aws:rds:us-east-1:000000000000:target-group:app-proxy/default");
when(service.describeDbProxyTargetGroups("app-proxy", null, "us-west-2"))
.thenReturn(List.of(tg));
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
Response response = handler.handle("DescribeDBProxyTargetGroups", p, "us-west-2");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<DescribeDBProxyTargetGroupsResult>"));
assertTrue(body.contains("<TargetGroups><member>"));
assertTrue(body.contains("<TargetGroupName>default</TargetGroupName>"));
assertTrue(body.contains("<ConnectionPoolConfig>"));
verify(service).describeDbProxyTargetGroups("app-proxy", null, "us-west-2");
}
@Test
void modifyDbProxyTargetGroup_mapsFullPoolConfigurationAndReturnsUpdatedGroup() {
DbProxyTargetGroup targetGroup = new DbProxyTargetGroup();
targetGroup.setDbProxyName("app-proxy");
targetGroup.setTargetGroupName("default");
targetGroup.setTargetGroupArn(
"arn:aws:rds:us-west-2:000000000000:target-group:prx-tg-abc");
targetGroup.setMaxConnectionsPercent(90);
targetGroup.setMaxIdleConnectionsPercent(40);
targetGroup.setConnectionBorrowTimeout(55);
targetGroup.setInitQuery("SET application_name = 'floci'");
targetGroup.setSessionPinningFilters(List.of("EXCLUDE_VARIABLE_SETS"));
when(service.configureDbProxyTargetGroup(
"app-proxy", "default", 90, 40, 55,
"SET application_name = 'floci'",
List.of("EXCLUDE_VARIABLE_SETS"),
"us-west-2"))
.thenReturn(targetGroup);
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
p.add("TargetGroupName", "default");
p.add("ConnectionPoolConfig.MaxConnectionsPercent", "90");
p.add("ConnectionPoolConfig.MaxIdleConnectionsPercent", "40");
p.add("ConnectionPoolConfig.ConnectionBorrowTimeout", "55");
p.add("ConnectionPoolConfig.InitQuery", "SET application_name = 'floci'");
p.add("ConnectionPoolConfig.SessionPinningFilters.member.1", "EXCLUDE_VARIABLE_SETS");
Response response = handler.handle(
"ModifyDBProxyTargetGroup", p, "us-west-2");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<ModifyDBProxyTargetGroupResult>"));
assertTrue(body.contains("<DBProxyTargetGroup>"));
assertTrue(body.contains("<MaxConnectionsPercent>90</MaxConnectionsPercent>"));
assertTrue(body.contains("<MaxIdleConnectionsPercent>40</MaxIdleConnectionsPercent>"));
assertTrue(body.contains("<ConnectionBorrowTimeout>55</ConnectionBorrowTimeout>"));
assertTrue(body.contains("<InitQuery>SET application_name = &apos;floci&apos;</InitQuery>"));
assertTrue(body.contains("<SessionPinningFilters><member>EXCLUDE_VARIABLE_SETS</member>"
+ "</SessionPinningFilters>"));
verify(service).configureDbProxyTargetGroup(
"app-proxy", "default", 90, 40, 55,
"SET application_name = 'floci'",
List.of("EXCLUDE_VARIABLE_SETS"),
"us-west-2");
}
@Test
void modifyDbProxyTargetGroup_rejectsNewNameBeforeCallingService() {
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
p.add("TargetGroupName", "default");
p.add("NewName", "renamed-target-group");
Response response = handler.handle(
"ModifyDBProxyTargetGroup", p, "us-west-2");
assertEquals(400, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("UnsupportedOperation"));
assertTrue(body.contains("cannot be renamed"));
verifyNoInteractions(service);
}
@Test
void modifyDbProxyTargetGroupRequiresTargetGroupName() {
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
Response response = handler.handle(
"ModifyDBProxyTargetGroup", p, "us-west-2");
assertEquals(400, response.getStatus());
assertTrue(((String) response.getEntity()).contains("TargetGroupName"));
verifyNoInteractions(service);
}
@Test
void proxyTargetActionsRejectBlankTargetGroupName() {
for (String action : List.of(
"RegisterDBProxyTargets",
"DeregisterDBProxyTargets",
"DescribeDBProxyTargets")) {
MultivaluedMap<String, String> params = params();
params.add("DBProxyName", "app-proxy");
params.add("TargetGroupName", " ");
Response response = handler.handle(action, params, "us-west-2");
assertEquals(400, response.getStatus(), action);
assertTrue(((String) response.getEntity())
.contains("TargetGroupName must be at least 1 character"), action);
}
verifyNoInteractions(service);
}
@Test
void describeDbProxyTargets_rendersTargetMembers() {
when(service.describeDbProxyTargets("app-proxy", "default", "us-west-2")).thenReturn(List.of(
new DbProxyTarget("RDS_INSTANCE", "inst1",
"arn:aws:rds:us-east-1:000000000000:db:inst1", "inst1.host", 5432)));
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
p.add("TargetGroupName", "default");
Response response = handler.handle("DescribeDBProxyTargets", p, "us-west-2");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<DescribeDBProxyTargetsResult>"));
assertTrue(body.contains("<Targets><member>"));
assertTrue(body.contains("<Type>RDS_INSTANCE</Type>"));
assertTrue(body.contains("<RdsResourceId>inst1</RdsResourceId>"));
verify(service).describeDbProxyTargets("app-proxy", "default", "us-west-2");
}
@Test
void describeDbProxyTargets_defaultsOmittedTargetGroupName() {
when(service.describeDbProxyTargets("app-proxy", null, "us-west-2"))
.thenReturn(List.of());
MultivaluedMap<String, String> params = params();
params.add("DBProxyName", "app-proxy");
Response response = handler.handle(
"DescribeDBProxyTargets", params, "us-west-2");
assertEquals(200, response.getStatus());
assertTrue(((String) response.getEntity())
.contains("<DescribeDBProxyTargetsResult>"));
verify(service).describeDbProxyTargets("app-proxy", null, "us-west-2");
}
@Test
void deleteDbProxy_delegatesToServiceAndReturnsProxy() {
DbProxy proxy = new DbProxy();
proxy.setDbProxyName("app-proxy");
proxy.setDbProxyArn("arn:aws:rds:us-east-1:000000000000:db-proxy:prx-abc");
when(service.getDbProxy("app-proxy", "us-west-2")).thenReturn(proxy);
MultivaluedMap<String, String> p = params();
p.add("DBProxyName", "app-proxy");
Response response = handler.handle("DeleteDBProxy", p, "us-west-2");
assertEquals(200, response.getStatus());
String body = (String) response.getEntity();
assertTrue(body.contains("<DeleteDBProxyResult>"));
assertTrue(body.contains("<DBProxyName>app-proxy</DBProxyName>"));
verify(service).getDbProxy("app-proxy", "us-west-2");
verify(service).deleteDbProxy("app-proxy", "us-west-2");
}
@Test
void describeDbSubnetGroupsPassesSignedRegionToService() {
DbSubnetGroup group = new DbSubnetGroup();
File diff suppressed because it is too large. Load diff
@@ -17,16 +17,26 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.github.dockerjava.api.model.Bind;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -78,7 +88,7 @@ class RdsContainerManagerTest {
ContainerDetector containerDetector = mock(ContainerDetector.class);
when(containerDetector.isRunningInContainer()).thenReturn(true);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
@@ -96,18 +106,541 @@ class RdsContainerManagerTest {
assertFalse(Files.exists(dbPath));
var spec = org.mockito.ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).createAndStart(spec.capture());
verify(lifecycleManager).create(spec.capture());
Bind bind = spec.getValue().binds().getFirst();
assertEquals(dbPath.toString(), bind.getPath());
assertEquals("/var/lib/mysql", bind.getVolume().getPath());
}
@Test
void legacyForeignAccountRuntimeReusesBareHostPath() {
Path hostRoot = tempDir.resolve("host-root");
Path dbPath = hostRoot.resolve("rds").resolve("db1");
EmulatorConfig config = config(hostRoot);
when(config.defaultAccountId()).thenReturn("000000000000");
ContainerDetector containerDetector = mock(ContainerDetector.class);
when(containerDetector.isRunningInContainer()).thenReturn(true);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager,
new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, containerDetector, config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String runtimeId = "arn:aws:rds:us-west-2:222222222222:db:db1";
manager.start(runtimeId, "db1", null,
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
var spec = org.mockito.ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).create(spec.capture());
assertEquals(dbPath.toString(), spec.getValue().binds().getFirst().getPath());
assertEquals("floci-rds-db1", spec.getValue().name());
verify(logStreamer).attachForAccount(
"222222222222", "container-id", "/aws/rds/instance/db1/error",
"log-stream", "us-west-2", "rds:" + runtimeId);
}
@Test
void sameNamedResourcesKeepIndependentActiveContainerEntries() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerDetector containerDetector = mock(ContainerDetector.class);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager,
new ContainerLifecycleManager.ContainerInfo(
"container-a", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))),
new ContainerLifecycleManager.ContainerInfo(
"container-b", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3307))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, containerDetector, config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
manager.start("arn:aws:rds:us-east-1:111111111111:db:db1", "db1",
"db-RESOURCE-A", "floci-rds-volume-a", DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db");
manager.start("arn:aws:rds:us-east-1:222222222222:db:db1", "db1",
"db-RESOURCE-B", "floci-rds-volume-b", DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db");
manager.stopAll();
verify(lifecycleManager, times(2)).stopAndRemoveStrict(
any(), org.mockito.ArgumentMatchers.isNull());
}
@Test
void sameNamedResourcesWithEqualVolumeIdsUseIndependentNamedVolumes() {
EmulatorConfig config = config(Path.of("data"));
when(config.defaultAccountId()).thenReturn("000000000000");
when(config.storage().mode()).thenReturn("memory");
ContainerDetector containerDetector = mock(ContainerDetector.class);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager,
new ContainerLifecycleManager.ContainerInfo(
"container-a", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))),
new ContainerLifecycleManager.ContainerInfo(
"container-b", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3307))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, containerDetector, config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String runtimeA = "arn:aws:rds:us-east-1:111111111111:db:db1";
String runtimeB = "arn:aws:rds:us-east-1:222222222222:db:db1";
String volumeA = "floci-rds-111111111111-us-east-1-db_db1-shared-volume";
String volumeB = "floci-rds-222222222222-us-east-1-db_db1-shared-volume";
RdsContainerHandle handleA = manager.start(
runtimeA, "db1", "db-RESOURCE-A", volumeA, DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db");
manager.start(runtimeB, "db1", "db-RESOURCE-B", volumeB, DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db");
verify(lifecycleManager).ensureVolume(volumeA);
verify(lifecycleManager).ensureVolume(volumeB);
manager.stop(handleA);
manager.removeVolume(runtimeA, "db-RESOURCE-A", volumeA);
verify(lifecycleManager).removeVolumeStrict(volumeA);
verify(lifecycleManager, never()).removeVolumeStrict(volumeB);
}
@Test
void competingLegacyHostPathClaimFailsBeforeTouchingDocker() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerDetector containerDetector = mock(ContainerDetector.class);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager,
new ContainerLifecycleManager.ContainerInfo(
"container-a", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, containerDetector, config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
manager.start("arn:aws:rds:us-east-1:111111111111:db:same", "same", null,
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
assertThrows(IllegalStateException.class, () -> manager.start(
"arn:aws:rds:us-east-1:111111111111:cluster:same", "same", null,
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
verify(lifecycleManager, times(1)).removeIfExistsStrict("floci-rds-same");
verify(lifecycleManager, times(1)).create(any());
}
@Test
void competingLegacyContainerNameClaimFailsBeforeTouchingDocker() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager,
new ContainerLifecycleManager.ContainerInfo(
"container-a", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String sharedLegacyName = "floci-rds-shared-volume";
manager.start("arn:aws:rds:us-east-1:111111111111:db:first", "first",
"first-storage", sharedLegacyName, DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db");
assertThrows(IllegalStateException.class, () -> manager.start(
"arn:aws:rds:us-east-1:111111111111:db:second", "second",
"second-storage", sharedLegacyName, DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db"));
verify(lifecycleManager, times(1)).removeIfExistsStrict(sharedLegacyName);
verify(lifecycleManager, times(1)).create(any());
}
@Test
void activeNamedVolumeIsNotRemovedUntilOwnerStops() {
EmulatorConfig config = config(Path.of("data"));
when(config.storage().mode()).thenReturn("memory");
ContainerDetector containerDetector = mock(ContainerDetector.class);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager,
new ContainerLifecycleManager.ContainerInfo(
"container-a", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, containerDetector, config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String runtime = "arn:aws:rds:us-east-1:111111111111:db:db1";
String volume = "floci-rds-legacy-volume";
RdsContainerHandle handle = manager.start(
runtime, "db1", "db1", volume, DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db");
assertThrows(IllegalStateException.class, () ->
manager.removeVolume(runtime, "db1", volume));
verify(lifecycleManager, never()).removeVolumeStrict(volume);
manager.stop(handle);
manager.removeVolume(runtime, "db1", volume);
verify(lifecycleManager).removeVolumeStrict(volume);
}
@Test
void failedStartReleasesClaimsForSameRuntimeRetry() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerDetector containerDetector = mock(ContainerDetector.class);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.create(any()))
.thenThrow(new IllegalStateException("Docker unavailable"))
.thenReturn("container-b");
when(lifecycleManager.startCreated(
org.mockito.ArgumentMatchers.eq("container-b"), any()))
.thenReturn(new ContainerLifecycleManager.ContainerInfo(
"container-b", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, containerDetector, config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:legacy";
assertThrows(IllegalStateException.class, () -> manager.start(
runtimeId, "legacy", null,
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
RdsContainerHandle retried = manager.start(
runtimeId, "legacy", null,
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
assertEquals("container-b", retried.getContainerId());
verify(lifecycleManager, times(2)).removeIfExistsStrict("floci-rds-legacy");
}
@Test
void postCreateFailureCleansContainerBeforeReleasingOwnership() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager,
new ContainerLifecycleManager.ContainerInfo(
"container-a", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))),
new ContainerLifecycleManager.ContainerInfo(
"container-b", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3307))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
when(logStreamer.attachForAccount(any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed"))
.thenReturn(null);
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String volume = "floci-rds-legacy-volume";
assertThrows(IllegalStateException.class, () -> manager.start(
"arn:aws:rds:us-east-1:111111111111:db:legacy", "legacy",
"legacy", volume, DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db"));
RdsContainerHandle retried = manager.start(
"arn:aws:rds:us-east-1:222222222222:db:legacy", "legacy",
"legacy", volume, DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db");
assertEquals("container-b", retried.getContainerId());
verify(lifecycleManager).stopAndRemoveStrict(
org.mockito.ArgumentMatchers.eq("container-a"),
org.mockito.ArgumentMatchers.isNull());
}
@Test
void failedPostCreateCleanupRetainsContainerIdentityForRuntimeRetry() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager,
new ContainerLifecycleManager.ContainerInfo(
"container-a", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
when(logStreamer.attachForAccount(any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("log attach failed"));
doThrow(new IllegalStateException("Docker cleanup failed"))
.doNothing()
.when(lifecycleManager).stopAndRemoveStrict(any(), any());
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:legacy";
assertThrows(IllegalStateException.class, () -> manager.start(
runtimeId, "legacy", "legacy", "floci-rds-legacy-volume",
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
assertEquals("container-a", manager.getActiveHandle(runtimeId).getContainerId());
manager.stopByRuntimeId(runtimeId);
assertNull(manager.getActiveHandle(runtimeId));
verify(lifecycleManager, times(2)).stopAndRemoveStrict(any(), any());
}
@Test
void failedStartCleanupRetainsCreatedContainerIdentityAndOwnership() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.create(any())).thenReturn("created-container");
when(lifecycleManager.startCreated(
org.mockito.ArgumentMatchers.eq("created-container"), any()))
.thenThrow(new IllegalStateException("Docker start failed"));
doThrow(new IllegalStateException("Docker cleanup failed"))
.doNothing()
.when(lifecycleManager).stopAndRemoveStrict(any(), any());
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:legacy";
assertThrows(IllegalStateException.class, () -> manager.start(
runtimeId, "legacy", "legacy", "floci-rds-legacy-volume",
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
assertEquals("created-container", manager.getActiveHandle(runtimeId).getContainerId());
assertThrows(IllegalStateException.class, () -> manager.start(
"arn:aws:rds:us-east-1:222222222222:db:legacy", "legacy",
"legacy", "floci-rds-legacy-volume", DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db"));
verify(lifecycleManager, times(1)).create(any());
manager.stopByRuntimeId(runtimeId);
assertNull(manager.getActiveHandle(runtimeId));
}
@Test
void failedStaleRemovalRetainsContainerNameAndOwnership() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
doThrow(new IllegalStateException("stale removal failed"))
.when(lifecycleManager).removeIfExistsStrict("floci-rds-legacy-volume");
doThrow(new IllegalStateException("cleanup retry failed"))
.doNothing()
.when(lifecycleManager).stopAndRemoveStrict(any(), any());
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:legacy";
assertThrows(IllegalStateException.class, () -> manager.start(
runtimeId, "legacy", "legacy", "floci-rds-legacy-volume",
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
assertEquals("floci-rds-legacy-volume",
manager.getActiveHandle(runtimeId).getContainerId());
verify(lifecycleManager, never()).create(any());
assertThrows(IllegalStateException.class, () -> manager.start(
"arn:aws:rds:us-east-1:222222222222:db:legacy", "legacy",
"legacy", "floci-rds-legacy-volume", DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db"));
manager.stopByRuntimeId(runtimeId);
assertNull(manager.getActiveHandle(runtimeId));
}
@Test
void inProgressRuntimeClaimRejectsConcurrentDuplicateStart() throws Exception {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
CountDownLatch createEntered = new CountDownLatch(1);
CountDownLatch allowCreate = new CountDownLatch(1);
when(lifecycleManager.create(any())).thenAnswer(invocation -> {
createEntered.countDown();
if (!allowCreate.await(5, TimeUnit.SECONDS)) {
throw new IllegalStateException("test timed out waiting to create");
}
return "container-a";
});
when(lifecycleManager.startCreated(
org.mockito.ArgumentMatchers.eq("container-a"), any()))
.thenReturn(new ContainerLifecycleManager.ContainerInfo(
"container-a", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:db1";
CompletableFuture<RdsContainerHandle> first = CompletableFuture.supplyAsync(() ->
manager.start(runtimeId, "db1", "storage-a", "floci-rds-volume-a",
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
assertTrue(createEntered.await(5, TimeUnit.SECONDS));
assertThrows(IllegalStateException.class, () -> manager.start(
runtimeId, "db1", "storage-b", "floci-rds-volume-b",
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
allowCreate.countDown();
RdsContainerHandle handle = first.get(5, TimeUnit.SECONDS);
verify(lifecycleManager, times(1)).create(any());
manager.stop(handle);
}
@Test
void stopAllContinuesAfterIndividualCleanupFailure() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager,
new ContainerLifecycleManager.ContainerInfo(
"container-a", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))),
new ContainerLifecycleManager.ContainerInfo(
"container-b", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db2", 3307))));
doAnswer(invocation -> {
if ("container-a".equals(invocation.getArgument(0))) {
throw new IllegalStateException("Docker cleanup failed");
}
return null;
}).when(lifecycleManager).stopAndRemoveStrict(any(), any());
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String runtimeA = "arn:aws:rds:us-east-1:111111111111:db:a";
String runtimeB = "arn:aws:rds:us-east-1:111111111111:db:b";
manager.start(runtimeA, "a", "storage-a", "floci-rds-volume-a",
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
manager.start(runtimeB, "b", "storage-b", "floci-rds-volume-b",
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
assertDoesNotThrow(manager::stopAll);
verify(lifecycleManager).stopAndRemoveStrict(
org.mockito.ArgumentMatchers.eq("container-a"), any());
verify(lifecycleManager).stopAndRemoveStrict(
org.mockito.ArgumentMatchers.eq("container-b"), any());
assertEquals("container-a", manager.getActiveHandle(runtimeA).getContainerId());
assertNull(manager.getActiveHandle(runtimeB));
}
@Test
void failedStopRetainsOwnershipAndActiveHandle() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
stubStarts(lifecycleManager,
new ContainerLifecycleManager.ContainerInfo(
"container-a", Map.of(3306,
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
String volume = "floci-rds-legacy-volume";
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:legacy";
RdsContainerHandle handle = manager.start(
runtimeId, "legacy",
"legacy", volume, DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db");
doThrow(new IllegalStateException("Docker stop failed"))
.doNothing()
.when(lifecycleManager).stopAndRemoveStrict(any(), any());
assertThrows(IllegalStateException.class, () -> manager.stop(handle));
assertThrows(IllegalStateException.class, () -> manager.start(
"arn:aws:rds:us-east-1:222222222222:db:legacy", "legacy",
"legacy", volume, DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db"));
verify(lifecycleManager, times(1)).create(any());
manager.stopByRuntimeId(runtimeId);
RdsContainerHandle retried = manager.start(
"arn:aws:rds:us-east-1:222222222222:db:legacy", "legacy",
"legacy", volume, DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db");
assertEquals("container-a", retried.getContainerId());
verify(lifecycleManager, times(2)).create(any());
verify(lifecycleManager, times(2)).stopAndRemoveStrict(any(), any());
}
@Test
void persistedStorageIdentityRejectsPathTraversal() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
RdsContainerManager manager = new RdsContainerManager(
new ContainerBuilder(config, mock(DockerHostResolver.class),
mock(EmbeddedDnsServer.class)),
lifecycleManager, mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
assertThrows(IllegalArgumentException.class, () -> manager.start(
"arn:aws:rds:us-east-1:111111111111:db:db1", "db1", "../escape",
"floci-rds-safe", DatabaseEngine.MYSQL, "mysql:8.0",
"root", "password", "db"));
verify(lifecycleManager, never()).removeIfExistsStrict(any());
}
@Test
void childContainerNameUsesVolumeIdWhenAvailable() {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerDetector containerDetector = mock(ContainerDetector.class);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
@@ -124,8 +657,8 @@ class RdsContainerManagerTest {
manager.start("db1", "volume-a", DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
var spec = org.mockito.ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).removeIfExists("floci-rds-volume-a");
verify(lifecycleManager).createAndStart(spec.capture());
verify(lifecycleManager).removeIfExistsStrict("floci-rds-volume-a");
verify(lifecycleManager).create(spec.capture());
assertEquals("floci-rds-volume-a", spec.getValue().name());
}
@@ -134,7 +667,7 @@ class RdsContainerManagerTest {
EmulatorConfig config = config(tempDir.resolve("host-root"));
ContainerDetector containerDetector = mock(ContainerDetector.class);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
"container-id", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
@@ -148,12 +681,19 @@ class RdsContainerManagerTest {
new RegionResolver("us-east-1", "000000000000"),
mock(ServiceConfigAccess.class));
manager.start("db1", null, DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
RdsContainerHandle handle = manager.start(
null, "db1", null, DatabaseEngine.MYSQL,
"mysql:8.0", "root", "password", "db");
var spec = org.mockito.ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).removeIfExists("floci-rds-db1");
verify(lifecycleManager).createAndStart(spec.capture());
verify(lifecycleManager).removeIfExistsStrict("floci-rds-db1");
verify(lifecycleManager).create(spec.capture());
assertEquals("floci-rds-db1", spec.getValue().name());
assertEquals("db1", handle.getRuntimeId());
manager.stop(handle);
verify(lifecycleManager).stopAndRemoveStrict(
org.mockito.ArgumentMatchers.eq("container-id"),
org.mockito.ArgumentMatchers.isNull());
}
private static EmulatorConfig config(Path hostRoot) {
@@ -174,4 +714,21 @@ class RdsContainerManagerTest {
when(storage.hostPersistentPath()).thenReturn(hostRoot.toString());
return config;
}
private static void stubStarts(
ContainerLifecycleManager lifecycleManager,
ContainerLifecycleManager.ContainerInfo... infos) {
int[] next = {0};
when(lifecycleManager.create(any())).thenAnswer(invocation ->
infos[Math.min(next[0]++, infos.length - 1)].containerId());
when(lifecycleManager.startCreated(any(), any())).thenAnswer(invocation -> {
String containerId = invocation.getArgument(0);
for (ContainerLifecycleManager.ContainerInfo info : infos) {
if (info.containerId().equals(containerId)) {
return info;
}
}
return infos[infos.length - 1];
});
}
}
@@ -0,0 +1,207 @@
package io.github.hectorvent.floci.services.rds.proxy;
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.util.concurrent.ConcurrentHashMap;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
class RdsProxyManagerTest {
@Test
void replacingProxyStopsPreviousListenerAndKeepsReplacementOwned() throws IOException {
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
int firstPort = availablePort();
try {
start(manager, "proxy", firstPort);
int replacementPort = availablePort();
start(manager, "proxy", replacementPort);
assertPortAvailable(firstPort);
assertPortUnavailable(replacementPort);
manager.stopProxy("proxy");
assertPortAvailable(replacementPort);
} finally {
manager.stopAll();
}
}
@Test
void registrationFailureAfterBindReleasesCandidateListener() throws IOException {
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
int proxyPort = availablePort();
try {
assertThrows(RuntimeException.class, () -> start(manager, null, proxyPort));
assertPortAvailable(proxyPort);
} finally {
manager.stopAll();
}
}
@Test
void failedReplacementPreservesOriginalRegistryEntry() throws IOException {
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
int originalPort = availablePort();
try {
start(manager, "proxy", originalPort);
try (ServerSocket occupied = new ServerSocket(0)) {
assertThrows(RuntimeException.class, () ->
start(manager, "proxy", occupied.getLocalPort()));
assertPortUnavailable(originalPort);
}
manager.stopProxy("proxy");
assertPortAvailable(originalPort);
} finally {
manager.stopAll();
}
}
@Test
void stopAllReleasesEveryListenerAndIsIdempotent() throws IOException {
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
int firstPort = availablePort();
start(manager, "first", firstPort);
int secondPort = availablePort();
start(manager, "second", secondPort);
manager.stopAll();
assertPortAvailable(firstPort);
assertPortAvailable(secondPort);
assertDoesNotThrow(manager::stopAll);
}
@Test
void closeFailurePropagatesAndManagerRetainsOwnership() throws Exception {
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
RdsAuthProxy proxy = authProxy("proxy");
ServerSocket serverSocket = mock(ServerSocket.class);
IOException closeFailure = new IOException("simulated close failure");
doThrow(closeFailure).when(serverSocket).close();
setServerSocket(proxy, serverSocket);
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager);
registry.put("proxy", proxy);
RuntimeException thrown = assertThrows(RuntimeException.class, () ->
manager.stopProxy("proxy"));
assertSame(closeFailure, thrown.getCause());
assertSame(proxy, registry.get("proxy"));
registry.clear();
}
@Test
void failedPreviousStopRestoresMappingAndReleasesCandidate() throws Exception {
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
RdsAuthProxy previous = mock(RdsAuthProxy.class);
doThrow(new IllegalStateException("simulated previous stop failure"))
.when(previous).stop();
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager);
registry.put("proxy", previous);
int candidatePort = availablePort();
assertThrows(RuntimeException.class, () -> start(manager, "proxy", candidatePort));
assertSame(previous, registry.get("proxy"));
assertPortAvailable(candidatePort);
registry.clear();
}
@Test
void stopAllContinuesAndRetainsOnlyFailedListenerOwnership() throws Exception {
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
int successfulPort = availablePort();
start(manager, "successful", successfulPort);
RdsAuthProxy failed = mock(RdsAuthProxy.class);
doThrow(new IllegalStateException("simulated shutdown stop failure"))
.when(failed).stop();
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager);
registry.put("failed", failed);
assertDoesNotThrow(manager::stopAll);
assertTrue(registry.containsKey("failed"));
assertFalse(registry.containsKey("successful"));
assertPortAvailable(successfulPort);
registry.clear();
}
private static void start(RdsProxyManager manager, String key, int proxyPort) {
manager.startProxy(key, DatabaseEngine.POSTGRES, false, proxyPort,
"localhost", 1, "admin", "secret", "app", (user, password) -> true);
}
private static RdsAuthProxy authProxy(String key) {
return new RdsAuthProxy(key, "localhost", 1, DatabaseEngine.POSTGRES, false,
"admin", "secret", "app", mock(RdsSigV4Validator.class),
(user, password) -> true);
}
private static void setServerSocket(RdsAuthProxy proxy, ServerSocket socket) throws Exception {
Field field = RdsAuthProxy.class.getDeclaredField("serverSocket");
field.setAccessible(true);
field.set(proxy, socket);
}
@SuppressWarnings("unchecked")
private static ConcurrentHashMap<String, RdsAuthProxy> registry(
RdsProxyManager manager) throws Exception {
Field field = RdsProxyManager.class.getDeclaredField("proxies");
field.setAccessible(true);
return (ConcurrentHashMap<String, RdsAuthProxy>) field.get(manager);
}
private static int availablePort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
}
}
private static void assertPortAvailable(int port) {
IOException lastFailure = null;
for (int attempt = 0; attempt < 50; attempt++) {
try (ServerSocket ignored = reusableSocket(port)) {
return;
} catch (IOException e) {
lastFailure = e;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
fail("Interrupted while waiting for proxy port " + port + " to be released", e);
}
}
fail("Proxy port " + port + " was not released", lastFailure);
}
private static void assertPortUnavailable(int port) {
assertThrows(IOException.class, () -> {
try (ServerSocket ignored = reusableSocket(port)) {
// The active proxy owns this listener.
}
});
}
private static ServerSocket reusableSocket(int port) throws IOException {
ServerSocket socket = new ServerSocket();
socket.setReuseAddress(true);
socket.bind(new InetSocketAddress(port));
return socket;
}
}
@@ -28,8 +28,7 @@ class RdsDataResourceResolverTest {
cluster.setDbClusterArn("arn:aws:rds:us-east-1:000000000000:cluster:cluster1");
cluster.setContainerHost("127.0.0.1");
cluster.setContainerPort(3306);
when(rdsService.listDbClusters(null)).thenReturn(List.of(cluster));
when(rdsService.listDbInstances(null)).thenReturn(List.of());
when(rdsService.getDbCluster("cluster1", "us-east-1")).thenReturn(cluster);
RdsDataResourceResolver.DatabaseTarget target = new RdsDataResourceResolver(rdsService)
.resolve("arn:aws:rds:us-east-1:000000000000:cluster:cluster1");
@@ -43,10 +42,8 @@ class RdsDataResourceResolverTest {
@Test
void missingResourceUsesModeledDataApiBadRequestCode() {
RdsService rdsService = mock(RdsService.class);
when(rdsService.listDbClusters(null)).thenReturn(List.of());
when(rdsService.listDbInstances(null)).thenReturn(List.of());
when(rdsService.getDbCluster("missing")).thenThrow(new AwsException("DBClusterNotFoundFault", "missing", 404));
when(rdsService.getDbInstance("missing")).thenThrow(new AwsException("DBInstanceNotFound", "missing", 404));
when(rdsService.getDbCluster("missing", "us-east-1"))
.thenThrow(new AwsException("DBClusterNotFoundFault", "missing", 404));
AwsException error = assertThrows(AwsException.class, () -> new RdsDataResourceResolver(rdsService)
.resolve("arn:aws:rds:us-east-1:000000000000:cluster:missing"));
@@ -54,4 +51,18 @@ class RdsDataResourceResolverTest {
assertEquals("BadRequestException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void rejectsResourceArnOutsideSignedRequestRegionBeforeLookup() {
RdsService rdsService = mock(RdsService.class);
AwsException error = assertThrows(AwsException.class, () ->
new RdsDataResourceResolver(rdsService).resolve(
"arn:aws:rds:us-west-2:000000000000:cluster:cluster1",
"us-east-1"));
assertEquals("BadRequestException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
org.mockito.Mockito.verifyNoInteractions(rdsService);
}
}
@@ -218,7 +218,8 @@ class RdsDataServiceTest {
ObjectNode insertCommitted = harness.request("insert into data_api_items(id, title, score) values ('commit', 'Commit', 1)");
insertCommitted.put("transactionId", committedTx);
harness.service.executeStatement(insertCommitted, REGION);
ObjectNode commitResponse = harness.service.commitTransaction(harness.transactionRequest(committedTx));
ObjectNode commitResponse = harness.service.commitTransaction(
harness.transactionRequest(committedTx), REGION);
assertEquals("Transaction Committed", commitResponse.get("transactionStatus").asText());
assertEquals(1L, harness.countById("commit"));
@@ -226,7 +227,8 @@ class RdsDataServiceTest {
ObjectNode insertRolledBack = harness.request("insert into data_api_items(id, title, score) values ('rollback', 'Rollback', 1)");
insertRolledBack.put("transactionId", rolledBackTx);
harness.service.executeStatement(insertRolledBack, REGION);
ObjectNode rollbackResponse = harness.service.rollbackTransaction(harness.transactionRequest(rolledBackTx));
ObjectNode rollbackResponse = harness.service.rollbackTransaction(
harness.transactionRequest(rolledBackTx), REGION);
assertEquals("Rollback Complete", rollbackResponse.get("transactionStatus").asText());
assertEquals(0L, harness.countById("rollback"));
@@ -258,7 +260,12 @@ class RdsDataServiceTest {
() -> harness.service.executeStatement(mismatchedDatabase, REGION));
assertEquals("TransactionNotFoundException", databaseMismatch.getErrorCode());
harness.service.rollbackTransaction(harness.transactionRequest(mismatchTx));
AwsException signedRegionMismatch = assertThrows(AwsException.class,
() -> harness.service.commitTransaction(
harness.transactionRequest(mismatchTx), "us-west-2"));
assertEquals("TransactionNotFoundException", signedRegionMismatch.getErrorCode());
harness.service.rollbackTransaction(harness.transactionRequest(mismatchTx), REGION);
}
@Test
@@ -273,7 +280,8 @@ class RdsDataServiceTest {
insert.put("transactionId", tx);
harness.service.executeStatement(insert, REGION);
ObjectNode commitResponse = harness.service.commitTransaction(harness.transactionRequest(FALLBACK_RESOURCE_ARN, tx));
ObjectNode commitResponse = harness.service.commitTransaction(
harness.transactionRequest(FALLBACK_RESOURCE_ARN, tx), REGION);
assertEquals("Transaction Committed", commitResponse.get("transactionStatus").asText());
assertEquals(1L, harness.countById("fallback"));
@@ -292,12 +300,13 @@ class RdsDataServiceTest {
insert.put("transactionId", tx);
harness.service.executeStatement(insert, REGION);
doThrow(new AwsException("BadRequestException", "resource is gone", 400))
.when(harness.resolver).resolve(RESOURCE_ARN);
.when(harness.resolver).resolve(RESOURCE_ARN, REGION);
ObjectNode commitResponse = harness.service.commitTransaction(harness.transactionRequest(tx));
ObjectNode commitResponse = harness.service.commitTransaction(
harness.transactionRequest(tx), REGION);
assertEquals("Transaction Committed", commitResponse.get("transactionStatus").asText());
doReturn(harness.target).when(harness.resolver).resolve(RESOURCE_ARN);
doReturn(harness.target).when(harness.resolver).resolve(RESOURCE_ARN, REGION);
assertEquals(1L, harness.countById("deleted-resource"));
}
@@ -324,17 +333,17 @@ class RdsDataServiceTest {
ObjectNode commitMissingResource = harness.transactionRequest(tx);
commitMissingResource.remove("resourceArn");
AwsException missingCommitResource = assertThrows(AwsException.class,
() -> harness.service.commitTransaction(commitMissingResource));
() -> harness.service.commitTransaction(commitMissingResource, REGION));
assertEquals("BadRequestException", missingCommitResource.getErrorCode());
assertEquals("resourceArn is required.", missingCommitResource.getMessage());
ObjectNode rollbackMismatchedResource = harness.transactionRequest(tx);
rollbackMismatchedResource.put("resourceArn", OTHER_RESOURCE_ARN);
AwsException rollbackMismatch = assertThrows(AwsException.class,
() -> harness.service.rollbackTransaction(rollbackMismatchedResource));
() -> harness.service.rollbackTransaction(rollbackMismatchedResource, REGION));
assertEquals("TransactionNotFoundException", rollbackMismatch.getErrorCode());
harness.service.rollbackTransaction(harness.transactionRequest(tx));
harness.service.rollbackTransaction(harness.transactionRequest(tx), REGION);
}
@Test
@@ -403,7 +412,7 @@ class RdsDataServiceTest {
RdsDataResourceResolver resolver = mock(RdsDataResourceResolver.class);
SecretsManagerService secrets = fallbackSecrets();
RdsDataResourceResolver.DatabaseTarget target = target();
when(resolver.resolve(RESOURCE_ARN)).thenReturn(target);
when(resolver.resolve(RESOURCE_ARN, REGION)).thenReturn(target);
AtomicBoolean closed = new AtomicBoolean(false);
RdsDataConnectionFactory failingFactory = new RdsDataConnectionFactory() {
@Override
@@ -524,10 +533,10 @@ class RdsDataServiceTest {
resolver = mock(RdsDataResourceResolver.class);
SecretsManagerService secrets = fallbackSecrets();
target = target();
when(resolver.resolve(RESOURCE_ARN)).thenReturn(target);
when(resolver.resolve(FALLBACK_RESOURCE_ARN)).thenReturn(target);
when(resolver.resolve(OTHER_RESOURCE_ARN)).thenReturn(target(OTHER_RESOURCE_ARN));
when(resolver.resolve(UNKNOWN_RESOURCE_ARN))
when(resolver.resolve(RESOURCE_ARN, REGION)).thenReturn(target);
when(resolver.resolve(FALLBACK_RESOURCE_ARN, REGION)).thenReturn(target);
when(resolver.resolve(OTHER_RESOURCE_ARN, REGION)).thenReturn(target(OTHER_RESOURCE_ARN));
when(resolver.resolve(UNKNOWN_RESOURCE_ARN, REGION))
.thenThrow(new AwsException("BadRequestException", "resource is missing", 400));
RdsDataConnectionFactory connectionFactory = new RdsDataConnectionFactory() {
@Override