Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

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

Alex Bannae4010ec12f21
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java
index afb04cd108..3a4a87e2a4 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/RdsControlPlaneTest.java
@@ -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");
+ }
}
diff --git a/docs/services/rds.md b/docs/services/rds.md
index aeebaf1bc1..99b23b7e56 100644
--- a/docs/services/rds.md
+++ b/docs/services/rds.md
@@ -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
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
index 73890d8613..92170cfd25 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java
@@ -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(
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
index 9ceeb79a0d..6199fbbda8 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
@@ -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
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLogStreamer.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLogStreamer.java
index 0fca8b72a6..a406bc7ab2 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLogStreamer.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLogStreamer.java
@@ -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());
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelper.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelper.java
index 8bba7d80cc..1fca2eb492 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelper.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerStorageHelper.java
@@ -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.
diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java
index 7aa1f4a33c..7ce91deb54 100644
--- a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java
+++ b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java
@@ -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()
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index bb0337ecbe..b308d54c7d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -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));
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
index 90a527a0c9..4f99898149 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsService.java
@@ -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,
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java
index a693c6071e..16e1d9a494 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsQueryHandler.java
@@ -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);
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java
index 7043883cd7..b329aa1c5e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
+import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
@@ -24,6 +25,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 io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
@@ -83,6 +88,8 @@ public class RdsService implements Resettable {
private final StorageBackend<String, DbParameterGroup> parameterGroups;
private final StorageBackend<String, DbClusterParameterGroup> clusterParameterGroups;
private final StorageBackend<String, DbSubnetGroup> subnetGroups;
+ private final StorageBackend<String, DbProxy> proxies;
+ private final StorageBackend<String, DbProxyTargetGroup> proxyTargetGroups;
private final RdsContainerManager containerManager;
private final RdsProxyManager proxyManager;
private final Ec2Service ec2Service;
@@ -94,6 +101,14 @@ public class RdsService implements Resettable {
private final Set<Integer> usedPorts = ConcurrentHashMap.newKeySet();
private static final Pattern IMAGE_TAG_VERSION_PATTERN = Pattern.compile("^(\\d+(?:\\.\\d+)*)(.*)$");
private static final Pattern SAFE_IMAGE_TAG_PATTERN = Pattern.compile("[A-Za-z0-9._-]+");
+ private static final Pattern DB_PROXY_NAME_PATTERN =
+ Pattern.compile("[a-zA-Z](?:-?[a-zA-Z0-9]+)*");
+ private static final Set<String> DB_PROXY_AUTH_SCHEMES = Set.of("SECRETS");
+ private static final Set<String> DB_PROXY_IAM_AUTH_MODES =
+ Set.of("DISABLED", "REQUIRED", "ENABLED");
+ private static final Set<String> DB_PROXY_CLIENT_PASSWORD_AUTH_TYPES = Set.of(
+ "MYSQL_NATIVE_PASSWORD", "MYSQL_CACHING_SHA2_PASSWORD",
+ "POSTGRES_SCRAM_SHA_256", "POSTGRES_MD5", "SQL_SERVER_AUTHENTICATION");
@Inject
public RdsService(RdsContainerManager containerManager,
@@ -123,6 +138,10 @@ public class RdsService implements Resettable {
new TypeReference<Map<String, DbClusterParameterGroup>>() {});
this.subnetGroups = storageFactory.create("rds", "rds-subnet-groups.json",
new TypeReference<Map<String, DbSubnetGroup>>() {});
+ this.proxies = storageFactory.create("rds", "rds-proxies.json",
+ new TypeReference<Map<String, DbProxy>>() {});
+ this.proxyTargetGroups = storageFactory.create("rds", "rds-proxy-target-groups.json",
+ new TypeReference<Map<String, DbProxyTargetGroup>>() {});
}
RdsService(RdsContainerManager containerManager,
@@ -140,6 +159,24 @@ public class RdsService implements Resettable {
null, null, null);
}
+ RdsService(RdsContainerManager containerManager,
+ RdsProxyManager proxyManager,
+ Ec2Service ec2Service,
+ RegionResolver regionResolver,
+ EmulatorConfig config,
+ StorageBackend<String, DbInstance> instances,
+ StorageBackend<String, DbCluster> clusters,
+ StorageBackend<String, DbParameterGroup> parameterGroups,
+ StorageBackend<String, DbClusterParameterGroup> clusterParameterGroups,
+ StorageBackend<String, DbSubnetGroup> subnetGroups,
+ SecretsManagerService secretsManagerService,
+ DockerHostResolver dockerHostResolver) {
+ this(containerManager, proxyManager, ec2Service, regionResolver, config,
+ instances, clusters, parameterGroups, clusterParameterGroups, subnetGroups,
+ secretsManagerService, dockerHostResolver, null,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+ }
+
RdsService(RdsContainerManager containerManager,
RdsProxyManager proxyManager,
Ec2Service ec2Service,
@@ -153,6 +190,47 @@ public class RdsService implements Resettable {
SecretsManagerService secretsManagerService,
DockerHostResolver dockerHostResolver,
CurrentContainerNetworkResolver currentContainerNetworkResolver) {
+ this(containerManager, proxyManager, ec2Service, regionResolver, config,
+ instances, clusters, parameterGroups, clusterParameterGroups, subnetGroups,
+ secretsManagerService, dockerHostResolver, currentContainerNetworkResolver,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+ }
+
+ // Test overload that also injects the DB-proxy stores (for restore-across-restart tests).
+ RdsService(RdsContainerManager containerManager,
+ RdsProxyManager proxyManager,
+ Ec2Service ec2Service,
+ RegionResolver regionResolver,
+ EmulatorConfig config,
+ StorageBackend<String, DbInstance> instances,
+ StorageBackend<String, DbCluster> clusters,
+ StorageBackend<String, DbParameterGroup> parameterGroups,
+ StorageBackend<String, DbClusterParameterGroup> clusterParameterGroups,
+ StorageBackend<String, DbSubnetGroup> subnetGroups,
+ SecretsManagerService secretsManagerService,
+ DockerHostResolver dockerHostResolver,
+ StorageBackend<String, DbProxy> proxies,
+ StorageBackend<String, DbProxyTargetGroup> proxyTargetGroups) {
+ this(containerManager, proxyManager, ec2Service, regionResolver, config,
+ instances, clusters, parameterGroups, clusterParameterGroups, subnetGroups,
+ secretsManagerService, dockerHostResolver, null, proxies, proxyTargetGroups);
+ }
+
+ RdsService(RdsContainerManager containerManager,
+ RdsProxyManager proxyManager,
+ Ec2Service ec2Service,
+ RegionResolver regionResolver,
+ EmulatorConfig config,
+ StorageBackend<String, DbInstance> instances,
+ StorageBackend<String, DbCluster> clusters,
+ StorageBackend<String, DbParameterGroup> parameterGroups,
+ StorageBackend<String, DbClusterParameterGroup> clusterParameterGroups,
+ StorageBackend<String, DbSubnetGroup> subnetGroups,
+ SecretsManagerService secretsManagerService,
+ DockerHostResolver dockerHostResolver,
+ CurrentContainerNetworkResolver currentContainerNetworkResolver,
+ StorageBackend<String, DbProxy> proxies,
+ StorageBackend<String, DbProxyTargetGroup> proxyTargetGroups) {
this.containerManager = containerManager;
this.proxyManager = proxyManager;
this.ec2Service = ec2Service;
@@ -166,11 +244,14 @@ public class RdsService implements Resettable {
this.parameterGroups = parameterGroups;
this.clusterParameterGroups = clusterParameterGroups;
this.subnetGroups = subnetGroups;
+ this.proxies = proxies;
+ this.proxyTargetGroups = proxyTargetGroups;
}
public void restorePersistedRuntime() {
restoreClusters();
restoreInstances();
+ restoreProxies();
}
public void clear() {
@@ -291,16 +372,21 @@ public class RdsService implements Resettable {
List<String> vpcSecurityGroupIds,
String region) {
String effectiveRegion = effectiveRegion(region);
- if (instances.get(id).isPresent()) {
+ String dbiResourceId = "db-" + java.util.UUID.randomUUID().toString()
+ .replace("-", "").substring(0, 24).toUpperCase();
+ String dbInstanceArn = regionResolver.buildArn("rds", effectiveRegion, "db:" + id);
+ if (findInstanceForScope(currentAccountId(), effectiveRegion, id) != null
+ || scopedKeyExists(instances, currentAccountId(), dbResourceKey(effectiveRegion, id))) {
throw new AwsException("DBInstanceAlreadyExists",
"DB instance " + id + " already exists.", 400);
}
DatabaseEngine engine = resolveEngine(engineParam);
if (dbSubnetGroupName != null && !dbSubnetGroupName.isBlank() && !"default".equalsIgnoreCase(dbSubnetGroupName)) {
- getDbSubnetGroup(dbSubnetGroupName);
+ getDbSubnetGroup(dbSubnetGroupName, effectiveRegion);
}
- validateInstanceParameterGroup(paramGroupName, engineParam, engineVersion);
+ validateInstanceParameterGroup(
+ paramGroupName, engineParam, engineVersion, effectiveRegion);
boolean mock = config.services().rds().mock();
// Always reserve a unique port (even in mock) so endpoints stay distinct and usedPorts
// is consistent; mock mode only skips starting the container and auth proxy.
@@ -319,11 +405,15 @@ public class RdsService implements Resettable {
int containerPort = 0;
String instanceVolumeId = null;
String instanceDockerVolumeName = null;
+ String instanceStorageResourceId = dbiResourceId;
PlacementResolution placement;
if (dbClusterIdentifier != null && !dbClusterIdentifier.isBlank()) {
// Cluster member — share the cluster's container (none exists in mock mode)
- DbCluster cluster = clusters.get(dbClusterIdentifier).orElseThrow(() ->
+ DbCluster cluster = Optional.ofNullable(
+ findClusterForScope(currentAccountId(), effectiveRegion,
+ dbClusterIdentifier))
+ .orElseThrow(() ->
new AwsException("DBClusterNotFoundFault",
"DB cluster " + dbClusterIdentifier + " not found.", 404));
backendHost = cluster.getContainerHost();
@@ -336,8 +426,10 @@ public class RdsService implements Resettable {
// bogus volume name that a later non-mock restore could try to reference.
instanceDockerVolumeName = cluster.getDockerVolumeName() != null
? cluster.getDockerVolumeName()
- : volumeName(cluster.getVolumeId(), cluster.getDbClusterIdentifier());
+ : volumeName(cluster.getVolumeId(),
+ resolvedClusterStorageResourceId(cluster));
}
+ instanceStorageResourceId = resolvedClusterStorageResourceId(cluster);
placement = PlacementResolution.fromCluster(cluster);
} else {
placement = resolvePlacement(dbSubnetGroupName, availabilityZone, multiAz, effectiveRegion);
@@ -345,13 +437,17 @@ public class RdsService implements Resettable {
// Standalone instance — start its own container
String image = imageForEngine(engine, engineVersion);
instanceVolumeId = String.format("%06x", new SecureRandom().nextInt(0xFFFFFF));
- RdsContainerHandle handle = containerManager.start(id, instanceVolumeId, engine, image, masterUsername, masterPassword, dbName);
+ instanceDockerVolumeName = newVolumeName(
+ instanceVolumeId, instanceStorageResourceId);
+ RdsContainerHandle handle = containerManager.start(
+ dbInstanceArn, id, instanceStorageResourceId,
+ instanceDockerVolumeName, engine, image,
+ masterUsername, masterPassword, dbName);
backendHost = handle.getHost();
backendPort = handle.getPort();
containerId = handle.getContainerId();
containerHost = handle.getHost();
containerPort = handle.getPort();
- instanceDockerVolumeName = volumeName(instanceVolumeId, id);
}
}
@@ -365,6 +461,7 @@ public class RdsService implements Resettable {
instance.setContainerPort(containerPort);
instance.setVolumeId(instanceVolumeId);
instance.setDockerVolumeName(instanceDockerVolumeName);
+ instance.setContainerStorageResourceId(instanceStorageResourceId);
instance.setTags(tags);
instance.setVpcSecurityGroupIds(vpcSecurityGroupIds);
instance.setDbSubnetGroupName(placement.dbSubnetGroupName());
@@ -373,45 +470,65 @@ public class RdsService implements Resettable {
instance.setMultiAz(placement.multiAz());
instance.setSubnetAvailabilityZones(placement.subnetAvailabilityZones());
- instance.setDbiResourceId("db-" + java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 24).toUpperCase());
- instance.setDbInstanceArn(regionResolver.buildArn("rds", effectiveRegion, "db:" + id));
+ instance.setDbiResourceId(dbiResourceId);
+ instance.setDbInstanceArn(dbInstanceArn);
if (manageMasterUserPassword) {
attachManagedMasterUserSecret(instance, effectiveRegion, masterUserSecretKmsKeyId);
}
if (!mock) {
- proxyManager.startProxy(id, engine, iamEnabled, proxyPort, backendHost, backendPort,
+ final String accountId = accountIdFromArn(instance.getDbInstanceArn());
+ final String instanceRegion = regionFromArn(instance.getDbInstanceArn());
+ proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id),
+ engine, iamEnabled, proxyPort, backendHost, backendPort,
masterUsername, masterPassword, dbName,
- (user, pw) -> validateDbPassword(id, user, pw));
+ (user, pw) -> validateDbPasswordForScope(
+ accountId, instanceRegion, id, user, pw));
}
if (dbClusterIdentifier != null && !dbClusterIdentifier.isBlank()) {
- DbCluster cluster = clusters.get(dbClusterIdentifier).orElse(null);
+ DbCluster cluster = findClusterForScope(
+ currentAccountId(), effectiveRegion, dbClusterIdentifier);
if (cluster != null) {
cluster.getDbClusterMembers().add(id);
- clusters.put(dbClusterIdentifier, cluster);
+ putClusterForScope(currentAccountId(), effectiveRegion,
+ dbClusterIdentifier, cluster);
}
}
- instances.put(id, instance);
+ putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
LOG.infov("DB instance {0} created, engine={1}, endpoint={2}:{3}",
id, engine, endpoint.address(), String.valueOf(endpoint.port()));
return instance;
}
public Map<String, String> listTagsForResource(String resourceName) {
- return Map.copyOf(resolveTagHandle(resourceName).tags());
+ return listTagsForResource(resourceName, resourceRegionOrDefault(resourceName));
+ }
+
+ public Map<String, String> listTagsForResource(String resourceName, String region) {
+ return Map.copyOf(resolveTagHandle(resourceName, region).tags());
}
public void addTagsToResource(String resourceName, Map<String, String> tags) {
- TagHandle handle = resolveTagHandle(resourceName);
+ addTagsToResource(resourceName, tags, resourceRegionOrDefault(resourceName));
+ }
+
+ public synchronized void addTagsToResource(
+ String resourceName, Map<String, String> tags, String region) {
+ TagHandle handle = resolveTagHandle(resourceName, region);
Map<String, String> updated = new java.util.LinkedHashMap<>(handle.tags());
updated.putAll(tags);
handle.save().accept(updated);
}
public void removeTagsFromResource(String resourceName, Collection<String> tagKeys) {
- TagHandle handle = resolveTagHandle(resourceName);
+ removeTagsFromResource(resourceName, tagKeys, resourceRegionOrDefault(resourceName));
+ }
+
+ public synchronized void removeTagsFromResource(
+ String resourceName, Collection<String> tagKeys, String region) {
+ TagHandle handle = resolveTagHandle(resourceName, region);
Map<String, String> updated = new java.util.LinkedHashMap<>(handle.tags());
tagKeys.forEach(updated::remove);
handle.save().accept(updated);
@@ -427,11 +544,12 @@ public class RdsService implements Resettable {
* each identified by an ARN of the form {@code arn:aws:rds:<region>:<account>:<type>:<id>}.
* A bare resource name (no ARN) is treated as a DB instance identifier for backwards compatibility.
*/
- private TagHandle resolveTagHandle(String resourceName) {
+ private TagHandle resolveTagHandle(String resourceName, String region) {
if (resourceName == null || resourceName.isBlank()) {
throw new AwsException("InvalidParameterValue", "ResourceName is required.", 400);
}
+ String effectiveRegion = effectiveRegion(region);
String type = "db";
String id = resourceName;
if (resourceName.startsWith("arn:")) {
@@ -444,6 +562,14 @@ public class RdsService implements Resettable {
if (!"rds".equals(arn.service())) {
throw new AwsException("InvalidParameterValue", "Invalid resource name: " + resourceName, 400);
}
+ if (!effectiveRegion.equals(arn.region())) {
+ throw new AwsException("InvalidParameterValue",
+ "ResourceName is not in region " + effectiveRegion + ": " + resourceName, 400);
+ }
+ if (!Objects.equals(regionResolver.getAccountId(), arn.accountId())) {
+ throw new AwsException("InvalidParameterValue",
+ "ResourceName is not in the current account: " + resourceName, 400);
+ }
String resource = arn.resource();
int sep = resource.indexOf(':');
if (sep < 0) {
@@ -458,24 +584,45 @@ public class RdsService implements Resettable {
String resourceId = id;
return switch (type) {
case "db" -> {
- DbInstance instance = getDbInstance(resourceId);
+ DbInstance instance = getDbInstance(resourceId, effectiveRegion);
yield new TagHandle(instance.getTags(), updated -> {
instance.setTags(updated);
- instances.put(resourceId, instance);
+ putInstanceForScope(currentAccountId(), effectiveRegion,
+ resourceId, instance);
});
}
case "cluster" -> {
- DbCluster cluster = getDbCluster(resourceId);
+ DbCluster cluster = getDbCluster(resourceId, effectiveRegion);
yield new TagHandle(cluster.getTags(), updated -> {
cluster.setTags(updated);
- clusters.put(resourceId, cluster);
+ putClusterForScope(currentAccountId(), effectiveRegion,
+ resourceId, cluster);
});
}
case "subgrp" -> {
- DbSubnetGroup group = getDbSubnetGroup(resourceId);
+ DbSubnetGroup group = getDbSubnetGroup(resourceId, effectiveRegion);
yield new TagHandle(group.getTags(), updated -> {
group.setTags(updated);
- subnetGroups.put(resourceId, group);
+ putSubnetGroupForScope(
+ currentAccountId(), effectiveRegion, resourceId, group);
+ });
+ }
+ case "db-proxy" -> {
+ DbProxy proxy = proxies.scan(k -> true).stream()
+ .filter(candidate -> effectiveRegion.equals(regionFromArn(candidate.getDbProxyArn())))
+ .filter(candidate -> resourceName.equals(candidate.getDbProxyArn()))
+ .findFirst()
+ .orElseThrow(() -> new AwsException("DBProxyNotFoundFault",
+ "DB proxy " + resourceId + " not found.", 404));
+ proxy = findDbProxy(proxy.getDbProxyName(), effectiveRegion)
+ .filter(candidate -> resourceName.equals(candidate.getDbProxyArn()))
+ .orElseThrow(() -> new AwsException("DBProxyNotFoundFault",
+ "DB proxy " + resourceId + " not found.", 404));
+ DbProxy resolvedProxy = proxy;
+ yield new TagHandle(proxy.getTags(), updated -> {
+ DbProxy updatedProxy = copyDbProxy(resolvedProxy);
+ updatedProxy.setTags(updated);
+ proxies.put(dbProxyKey(effectiveRegion, resolvedProxy.getDbProxyName()), updatedProxy);
});
}
// Valid RDS resource types Floci does not model yet (og, pg, snapshot, ...) — taggable
@@ -485,6 +632,11 @@ public class RdsService implements Resettable {
};
}
+ private String resourceRegionOrDefault(String resourceName) {
+ return resourceName != null && resourceName.startsWith("arn:")
+ ? regionFromArn(resourceName) : regionResolver.getDefaultRegion();
+ }
+
private void attachManagedMasterUserSecret(DbInstance instance, String region, String kmsKeyId) {
if (secretsManagerService == null) {
throw new AwsException("InvalidParameterCombination",
@@ -524,32 +676,54 @@ public class RdsService implements Resettable {
}
public DbInstance getDbInstance(String id) {
- return instances.get(id).orElseThrow(() ->
+ return getDbInstance(id, regionResolver.getDefaultRegion());
+ }
+
+ public DbInstance getDbInstance(String id, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ return Optional.ofNullable(findInstanceForScope(
+ currentAccountId(), effectiveRegion, id)).orElseThrow(() ->
new AwsException("DBInstanceNotFound",
"DB instance " + id + " not found.", 404));
}
public Collection<DbInstance> listDbInstances(String filterId) {
- if (filterId != null && !filterId.isBlank()) {
- // DBInstanceIdentifier also accepts an ARN per the AWS model. Match the
- // full ARN against each instance's stored ARN rather than reducing it to
- // the bare identifier, so a cross-account or cross-region ARN does not
- // resolve a same-named local instance.
- if (filterId.startsWith("arn:")) {
- return instances.scan(k -> true).stream()
- .filter(i -> filterId.equalsIgnoreCase(i.getDbInstanceArn()))
- .toList();
+ return listDbInstances(filterId, regionResolver.getDefaultRegion());
+ }
+
+ public Collection<DbInstance> listDbInstances(String filterId, String region) {
+ String accountId = currentAccountId();
+ String effectiveRegion = effectiveRegion(region);
+ Map<String, DbInstance> unique = new LinkedHashMap<>();
+ for (DbInstance instance : instances.scan(k -> true)) {
+ boolean matchesFilter = filterId == null || filterId.isBlank()
+ || (filterId.startsWith("arn:")
+ ? filterId.equalsIgnoreCase(instance.getDbInstanceArn())
+ : instance.getDbInstanceIdentifier().equalsIgnoreCase(filterId));
+ if (matchesFilter
+ && hasRdsResourceIdentity(
+ instance.getDbInstanceArn(), accountId, effectiveRegion, "db",
+ instance.getDbInstanceIdentifier())) {
+ DbInstance canonical = findInstanceForScope(
+ accountId, effectiveRegion, instance.getDbInstanceIdentifier());
+ if (canonical != null) {
+ unique.put(canonical.getDbInstanceArn(), canonical);
+ }
}
- return instances.scan(k -> k.equalsIgnoreCase(filterId));
}
- return instances.scan(k -> true);
+ return unique.values();
}
public Collection<DbInstance> listDbInstancesByDbiResourceIds(Collection<String> resourceIds) {
+ return listDbInstancesByDbiResourceIds(resourceIds, regionResolver.getDefaultRegion());
+ }
+
+ public Collection<DbInstance> listDbInstancesByDbiResourceIds(
+ Collection<String> resourceIds, String region) {
if (resourceIds == null || resourceIds.isEmpty()) {
- return instances.scan(k -> true);
+ return listDbInstances(null, region);
}
- return instances.scan(k -> true).stream()
+ return listDbInstances(null, region).stream()
.filter(instance -> resourceIds.contains(instance.getDbiResourceId()))
.toList();
}
@@ -561,7 +735,15 @@ public class RdsService implements Resettable {
public DbInstance modifyDbInstance(String id, String newPassword, Boolean iamEnabled,
String dbSubnetGroupName, List<String> vpcSecurityGroupIds) {
- DbInstance instance = getDbInstance(id);
+ return modifyDbInstance(id, newPassword, iamEnabled, dbSubnetGroupName,
+ vpcSecurityGroupIds, regionResolver.getDefaultRegion());
+ }
+
+ public DbInstance modifyDbInstance(
+ String id, String newPassword, Boolean iamEnabled,
+ String dbSubnetGroupName, List<String> vpcSecurityGroupIds, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbInstance instance = getDbInstance(id, effectiveRegion);
instance.setStatus(DbInstanceStatus.AVAILABLE);
if (newPassword != null && !newPassword.isBlank()) {
instance.setMasterPassword(newPassword);
@@ -570,13 +752,13 @@ public class RdsService implements Resettable {
instance.setIamDatabaseAuthenticationEnabled(iamEnabled);
}
if (dbSubnetGroupName != null && !dbSubnetGroupName.isBlank()) {
- getDbSubnetGroup(dbSubnetGroupName);
+ getDbSubnetGroup(dbSubnetGroupName, effectiveRegion);
instance.setDbSubnetGroupName(dbSubnetGroupName);
}
if (vpcSecurityGroupIds != null && !vpcSecurityGroupIds.isEmpty()) {
instance.setVpcSecurityGroupIds(vpcSecurityGroupIds);
}
- instances.put(id, instance);
+ putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
LOG.infov("DB instance {0} modified", id);
return instance;
}
@@ -607,26 +789,43 @@ public class RdsService implements Resettable {
}
public DbInstance rebootDbInstance(String id) {
- DbInstance instance = getDbInstance(id);
+ return rebootDbInstance(id, regionResolver.getDefaultRegion());
+ }
+
+ public DbInstance rebootDbInstance(String id, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbInstance instance = getDbInstance(id, effectiveRegion);
instance.setStatus(DbInstanceStatus.REBOOTING);
- instances.put(id, instance);
+ putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
boolean mock = config.services().rds().mock();
if (!mock) {
// Stop proxy during reboot
- proxyManager.stopProxy(id);
+ proxyManager.stopProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id));
// Restart container if it's a standalone instance
if (instance.getDbClusterIdentifier() == null && instance.getContainerId() != null) {
try {
containerManager.stop(buildHandle(instance));
- } catch (Exception e) {
- LOG.warnv("Error stopping container during reboot of {0}: {1}", id, e.getMessage());
+ } catch (RuntimeException | Error e) {
+ instance.setStatus(DbInstanceStatus.FAILED);
+ try {
+ putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
+ } catch (RuntimeException persistFailure) {
+ e.addSuppressed(persistFailure);
+ }
+ throw e;
}
String image = imageForEngine(instance.getEngine(), instance.getEngineVersion());
- RdsContainerHandle handle = containerManager.start(id, instance.getVolumeId(), instance.getEngine(), image,
- instance.getMasterUsername(), instance.getMasterPassword(), instance.getDbName());
+ String storageResourceId = resolvedInstanceStorageResourceId(instance);
+ String dockerVolumeName = resolvedInstanceDockerVolumeName(instance);
+ RdsContainerHandle handle = containerManager.start(
+ instance.getDbInstanceArn(), id, storageResourceId,
+ dockerVolumeName, instance.getEngine(), image, instance.getMasterUsername(),
+ instance.getMasterPassword(), instance.getDbName());
+ instance.setContainerStorageResourceId(storageResourceId);
+ instance.setDockerVolumeName(dockerVolumeName);
instance.setContainerId(handle.getContainerId());
instance.setContainerHost(handle.getHost());
instance.setContainerPort(handle.getPort());
@@ -634,37 +833,49 @@ public class RdsService implements Resettable {
}
instance.setStatus(DbInstanceStatus.AVAILABLE);
- instances.put(id, instance);
+ putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
if (!mock) {
String effectiveMasterUser = instance.getMasterUsername() != null
? instance.getMasterUsername() : "root";
- proxyManager.startProxy(id, instance.getEngine(),
+ final String accountId = accountIdFromArn(instance.getDbInstanceArn());
+ final String instanceRegion = regionFromArn(instance.getDbInstanceArn());
+ proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id),
+ instance.getEngine(),
instance.isIamDatabaseAuthenticationEnabled(),
instance.getProxyPort(), instance.getContainerHost(), instance.getContainerPort(),
effectiveMasterUser, instance.getMasterPassword(), instance.getDbName(),
- (user, pw) -> validateDbPassword(id, user, pw));
+ (user, pw) -> validateDbPasswordForScope(
+ accountId, instanceRegion, id, user, pw));
}
LOG.infov("DB instance {0} rebooted", id);
return instance;
}
- public void deleteDbInstance(String id) {
- DbInstance instance = instances.get(id).orElseThrow(() ->
+ public synchronized void deleteDbInstance(String id) {
+ deleteDbInstance(id, regionResolver.getDefaultRegion());
+ }
+
+ public synchronized void deleteDbInstance(String id, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbInstance instance = Optional.ofNullable(
+ findInstanceForScope(currentAccountId(), effectiveRegion, id))
+ .orElseThrow(() ->
new AwsException("DBInstanceNotFound", "DB instance " + id + " not found.", 404));
- if (instance.getStatus() == DbInstanceStatus.DELETING) {
+ if (isRegisteredProxyTarget(
+ "RDS_INSTANCE", id, regionFromArn(instance.getDbInstanceArn()))) {
throw new AwsException("InvalidDBInstanceState",
- "DB instance " + id + " is already being deleted.", 400);
+ "DB instance " + id + " is registered with a DB proxy target group.", 400);
}
instance.setStatus(DbInstanceStatus.DELETING);
- instances.put(id, instance);
+ putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
boolean mock = config.services().rds().mock();
if (!mock) {
- proxyManager.stopProxy(id);
+ proxyManager.stopProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id));
}
String clusterId = instance.getDbClusterIdentifier();
@@ -673,20 +884,26 @@ public class RdsService implements Resettable {
if (!mock) {
if (instance.getContainerId() != null) {
containerManager.stop(buildHandle(instance));
+ } else {
+ containerManager.stopByRuntimeId(instance.getDbInstanceArn());
}
- containerManager.removeVolume(instance.getDbInstanceIdentifier(), instance.getVolumeId());
+ containerManager.removeVolume(
+ instance.getDbInstanceArn(),
+ resolvedInstanceStorageResourceId(instance),
+ resolvedInstanceDockerVolumeName(instance));
}
} else {
// Cluster member — remove from cluster's member list
- DbCluster cluster = clusters.get(clusterId).orElse(null);
+ DbCluster cluster = findClusterForScope(
+ currentAccountId(), effectiveRegion, clusterId);
if (cluster != null) {
cluster.getDbClusterMembers().remove(id);
- clusters.put(clusterId, cluster);
+ putClusterForScope(currentAccountId(), effectiveRegion, clusterId, cluster);
}
}
releaseProxyPort(instance.getProxyPort());
- instances.delete(id);
+ deleteInstanceForScope(currentAccountId(), effectiveRegion, id);
LOG.infov("DB instance {0} deleted", id);
}
@@ -716,13 +933,18 @@ public class RdsService implements Resettable {
String paramGroupName, String dbSubnetGroupName,
String availabilityZone, boolean multiAz, String region) {
String effectiveRegion = effectiveRegion(region);
- if (clusters.get(id).isPresent()) {
+ String clusterResourceId = "cluster-" + java.util.UUID.randomUUID().toString()
+ .replace("-", "").substring(0, 24).toUpperCase();
+ String clusterArn = regionResolver.buildArn("rds", effectiveRegion, "cluster:" + id);
+ if (findClusterForScope(currentAccountId(), effectiveRegion, id) != null
+ || scopedKeyExists(clusters, currentAccountId(), dbResourceKey(effectiveRegion, id))) {
throw new AwsException("DBClusterAlreadyExistsFault",
"DB cluster " + id + " already exists.", 400);
}
DatabaseEngine engine = resolveEngine(engineParam);
- validateClusterParameterGroup(paramGroupName, engineParam, engineVersion);
+ validateClusterParameterGroup(
+ paramGroupName, engineParam, engineVersion, effectiveRegion);
PlacementResolution placement = resolvePlacement(dbSubnetGroupName, availabilityZone, multiAz, effectiveRegion);
boolean mock = config.services().rds().mock();
@@ -733,15 +955,21 @@ public class RdsService implements Resettable {
DbCluster cluster = new DbCluster(id, engine, engineVersion, masterUsername, masterPassword,
databaseName, DbInstanceStatus.AVAILABLE, endpoint, endpoint,
iamEnabled, new ArrayList<>(), paramGroupName, Instant.now(), proxyPort);
+ cluster.setContainerStorageResourceId(clusterResourceId);
if (!mock) {
String image = imageForEngine(engine, engineVersion);
String clusterVolumeId = String.format("%06x", new SecureRandom().nextInt(0xFFFFFF));
- RdsContainerHandle handle = containerManager.start(id, clusterVolumeId, engine, image, masterUsername, masterPassword, databaseName);
+ String clusterDockerVolumeName = newVolumeName(
+ clusterVolumeId, clusterResourceId);
+ RdsContainerHandle handle = containerManager.start(
+ clusterArn, id, clusterResourceId, clusterDockerVolumeName,
+ engine, image,
+ masterUsername, masterPassword, databaseName);
cluster.setContainerId(handle.getContainerId());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
cluster.setVolumeId(clusterVolumeId);
- cluster.setDockerVolumeName(volumeName(clusterVolumeId, id));
+ cluster.setDockerVolumeName(clusterDockerVolumeName);
}
cluster.setDbSubnetGroupName(placement.dbSubnetGroupName());
cluster.setVpcId(placement.vpcId());
@@ -749,59 +977,95 @@ public class RdsService implements Resettable {
cluster.setMultiAz(placement.multiAz());
cluster.setSubnetAvailabilityZones(placement.subnetAvailabilityZones());
- cluster.setDbClusterResourceId("cluster-" + java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 24).toUpperCase());
- cluster.setDbClusterArn(regionResolver.buildArn("rds", effectiveRegion, "cluster:" + id));
+ cluster.setDbClusterResourceId(clusterResourceId);
+ cluster.setDbClusterArn(clusterArn);
if (!mock) {
String effectiveMasterUser = masterUsername != null ? masterUsername : "root";
- proxyManager.startProxy(id, engine, iamEnabled, proxyPort, cluster.getContainerHost(), cluster.getContainerPort(),
+ final String accountId = accountIdFromArn(cluster.getDbClusterArn());
+ final String clusterRegion = regionFromArn(cluster.getDbClusterArn());
+ proxyManager.startProxy(rdsResourceRelayKey(cluster.getDbClusterArn(), id),
+ engine, iamEnabled, proxyPort,
+ cluster.getContainerHost(), cluster.getContainerPort(),
effectiveMasterUser, masterPassword, databaseName,
- (user, pw) -> validateDbClusterPassword(id, user, pw));
+ (user, pw) -> validateDbClusterPasswordForScope(
+ accountId, clusterRegion, id, user, pw));
}
- clusters.put(id, cluster);
+ putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
LOG.infov("DB cluster {0} created (mock={1}), engine={2}, endpoint={3}:{4}",
id, String.valueOf(mock), engine, endpoint.address(), String.valueOf(endpoint.port()));
return cluster;
}
public DbCluster getDbCluster(String id) {
- return clusters.get(id).orElseThrow(() ->
+ return getDbCluster(id, regionResolver.getDefaultRegion());
+ }
+
+ public DbCluster getDbCluster(String id, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ return Optional.ofNullable(findClusterForScope(
+ currentAccountId(), effectiveRegion, id)).orElseThrow(() ->
new AwsException("DBClusterNotFoundFault",
"DB cluster " + id + " not found.", 404));
}
public Collection<DbCluster> listDbClusters(String filterId) {
- if (filterId != null && !filterId.isBlank()) {
- // DBClusterIdentifier also accepts an ARN per the AWS model. Match the
- // full ARN against each cluster's stored ARN rather than reducing it to
- // the bare identifier, so a cross-account or cross-region ARN does not
- // resolve a same-named local cluster.
- if (filterId.startsWith("arn:")) {
- return clusters.scan(k -> true).stream()
- .filter(c -> filterId.equalsIgnoreCase(c.getDbClusterArn()))
- .toList();
+ return listDbClusters(filterId, regionResolver.getDefaultRegion());
+ }
+
+ public Collection<DbCluster> listDbClusters(String filterId, String region) {
+ String accountId = currentAccountId();
+ String effectiveRegion = effectiveRegion(region);
+ Map<String, DbCluster> unique = new LinkedHashMap<>();
+ for (DbCluster cluster : clusters.scan(k -> true)) {
+ boolean matchesFilter = filterId == null || filterId.isBlank()
+ || (filterId.startsWith("arn:")
+ ? filterId.equalsIgnoreCase(cluster.getDbClusterArn())
+ : cluster.getDbClusterIdentifier().equalsIgnoreCase(filterId));
+ if (matchesFilter
+ && hasRdsResourceIdentity(
+ cluster.getDbClusterArn(), accountId, effectiveRegion, "cluster",
+ cluster.getDbClusterIdentifier())) {
+ DbCluster canonical = findClusterForScope(
+ accountId, effectiveRegion, cluster.getDbClusterIdentifier());
+ if (canonical != null) {
+ unique.put(canonical.getDbClusterArn(), canonical);
+ }
}
- return clusters.scan(k -> k.equalsIgnoreCase(filterId));
}
- return clusters.scan(k -> true);
+ return unique.values();
}
public DbCluster modifyDbCluster(String id, String newPassword, Boolean iamEnabled) {
- DbCluster cluster = getDbCluster(id);
+ return modifyDbCluster(id, newPassword, iamEnabled,
+ regionResolver.getDefaultRegion());
+ }
+
+ public DbCluster modifyDbCluster(
+ String id, String newPassword, Boolean iamEnabled, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbCluster cluster = getDbCluster(id, effectiveRegion);
if (newPassword != null && !newPassword.isBlank()) {
cluster.setMasterPassword(newPassword);
}
if (iamEnabled != null) {
cluster.setIamDatabaseAuthenticationEnabled(iamEnabled);
}
- clusters.put(id, cluster);
+ putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
LOG.infov("DB cluster {0} modified", id);
return cluster;
}
- public void deleteDbCluster(String id) {
- DbCluster cluster = clusters.get(id).orElseThrow(() ->
+ public synchronized void deleteDbCluster(String id) {
+ deleteDbCluster(id, regionResolver.getDefaultRegion());
+ }
+
+ public synchronized void deleteDbCluster(String id, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbCluster cluster = Optional.ofNullable(
+ findClusterForScope(currentAccountId(), effectiveRegion, id))
+ .orElseThrow(() ->
new AwsException("DBClusterNotFoundFault",
"DB cluster " + id + " not found.", 404));
@@ -809,192 +1073,1053 @@ public class RdsService implements Resettable {
throw new AwsException("InvalidDBClusterStateFault",
"DB cluster " + id + " still has DB instances.", 400);
}
+ if (isRegisteredProxyTarget(
+ "TRACKED_CLUSTER", id, regionFromArn(cluster.getDbClusterArn()))) {
+ throw new AwsException("InvalidDBClusterStateFault",
+ "DB cluster " + id + " is registered with a DB proxy target group.", 400);
+ }
cluster.setStatus(DbInstanceStatus.DELETING);
- clusters.put(id, cluster);
+ putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
if (!config.services().rds().mock()) {
- proxyManager.stopProxy(id);
+ proxyManager.stopProxy(rdsResourceRelayKey(cluster.getDbClusterArn(), id));
if (cluster.getContainerId() != null) {
containerManager.stop(buildClusterHandle(cluster));
+ } else {
+ containerManager.stopByRuntimeId(cluster.getDbClusterArn());
}
- containerManager.removeVolume(id, cluster.getVolumeId());
+ containerManager.removeVolume(
+ cluster.getDbClusterArn(),
+ resolvedClusterStorageResourceId(cluster),
+ resolvedClusterDockerVolumeName(cluster));
}
releaseProxyPort(cluster.getProxyPort());
- clusters.delete(id);
+ deleteClusterForScope(currentAccountId(), effectiveRegion, id);
LOG.infov("DB cluster {0} deleted", id);
}
- // ── DB Subnet Groups ──────────────────────────────────────────────────────
+ // ── DB Proxies (AWS::RDS::DBProxy) ──────────────────────────────────────────
- public DbSubnetGroup createDbSubnetGroup(String name, String description, List<String> subnetIds) {
- return createDbSubnetGroup(name, description, subnetIds, regionResolver.getDefaultRegion());
+ /**
+ * Creates a DB Proxy. No relay is started here — the backend target is unknown until a target
+ * group registers a cluster/instance (see {@link #registerDbProxyTargets}). The relay listens on
+ * the engine family's default port so the endpoint is a bare host clients reach at 5432/3306.
+ */
+ public DbProxy createDbProxy(String dbProxyName, String engineFamily, boolean requireTls,
+ boolean iamAuth, String roleArn, List<String> vpcSubnetIds,
+ List<String> vpcSecurityGroupIds, List<DbProxyAuth> auth,
+ Map<String, String> tags) {
+ return createDbProxy(dbProxyName, engineFamily, requireTls, iamAuth, roleArn,
+ vpcSubnetIds, vpcSecurityGroupIds, auth, 1800, false, tags,
+ regionResolver.getDefaultRegion());
}
- public DbSubnetGroup createDbSubnetGroup(String name, String description, List<String> subnetIds, String region) {
- if (name == null || name.isBlank()) {
- throw new AwsException("MissingParameter", "The request must contain the parameter DBSubnetGroupName.", 400);
- }
- if (subnetGroups.get(name).isPresent() || "default".equalsIgnoreCase(name)) {
- throw new AwsException("DBSubnetGroupAlreadyExists",
- "DB subnet group " + name + " already exists.", 400);
+ public DbProxy createDbProxy(String dbProxyName, String engineFamily, boolean requireTls,
+ boolean iamAuth, String roleArn, List<String> vpcSubnetIds,
+ List<String> vpcSecurityGroupIds, List<DbProxyAuth> auth,
+ int idleClientTimeout, boolean debugLogging,
+ Map<String, String> tags, String region) {
+ return createDbProxy(dbProxyName, engineFamily, requireTls, iamAuth, "NONE", roleArn,
+ vpcSubnetIds, vpcSecurityGroupIds, auth, idleClientTimeout, debugLogging, tags, region);
+ }
+
+ public synchronized DbProxy createDbProxy(String dbProxyName, String engineFamily, boolean requireTls,
+ boolean iamAuth, String defaultAuthScheme, String roleArn,
+ List<String> vpcSubnetIds,
+ List<String> vpcSecurityGroupIds, List<DbProxyAuth> auth,
+ int idleClientTimeout, boolean debugLogging,
+ Map<String, String> tags, String region) {
+ String effectiveDefaultAuthScheme = normalizeDefaultAuthScheme(defaultAuthScheme);
+ validateDbProxyCreate(dbProxyName, engineFamily, roleArn, vpcSubnetIds, auth,
+ effectiveDefaultAuthScheme, idleClientTimeout);
+ String effectiveRegion = effectiveRegion(region);
+ String vpcId = resolveDbProxyVpc(vpcSubnetIds, effectiveRegion);
+ String proxyKey = dbProxyKey(effectiveRegion, dbProxyName);
+ String accountId = currentAccountId();
+ if (findDbProxy(dbProxyName, effectiveRegion).isPresent()
+ || scopedKeyExists(proxies, accountId, proxyKey)) {
+ throw new AwsException("DBProxyAlreadyExistsFault",
+ "DB proxy " + dbProxyName + " already exists.", 400);
}
- if (subnetIds == null || subnetIds.isEmpty()) {
- throw new AwsException("MissingParameter", "The request must contain the parameter SubnetIds.", 400);
+
+ boolean mock = config.services().rds().mock();
+ // RDS Proxy exposes a bare hostname on the engine's default port. Floci currently models
+ // that contract directly; a separate endpoint-routing design is required before multiple
+ // same-engine proxies can be made externally reachable through one Docker host.
+ int proxyPort = reserveOrAllocateProxyPort(defaultPortForEngineFamily(engineFamily));
+ DbProxy proxy = new DbProxy();
+ proxy.setDbProxyName(dbProxyName);
+ proxy.setEngineFamily(engineFamily.toUpperCase());
+ proxy.setRequireTls(requireTls);
+ proxy.setIamAuth(iamAuth || "IAM_AUTH".equals(effectiveDefaultAuthScheme)
+ || (auth != null && auth.stream()
+ .anyMatch(entry -> isIamEnabledAuthMode(entry.getIamAuth()))));
+ proxy.setDefaultAuthScheme(effectiveDefaultAuthScheme);
+ proxy.setRoleArn(roleArn);
+ proxy.setVpcSubnetIds(vpcSubnetIds);
+ proxy.setVpcSecurityGroupIds(vpcSecurityGroupIds);
+ proxy.setAuth(auth);
+ proxy.setIdleClientTimeout(idleClientTimeout);
+ proxy.setDebugLogging(debugLogging);
+ proxy.setTags(tags);
+ proxy.setProxyPort(proxyPort);
+ proxy.setEndpointHost(mock ? "localhost" : proxyEndpointHost());
+ proxy.setStatus("available");
+ Instant now = Instant.now();
+ proxy.setCreatedAt(now);
+ proxy.setUpdatedAt(now);
+ proxy.setVpcId(vpcId);
+ String resourceId = "prx-" + randomResourceSuffix();
+ proxy.setDbProxyResourceId(resourceId);
+ proxy.setDbProxyArn(regionResolver.buildArn("rds", effectiveRegion, "db-proxy:" + resourceId));
+
+ DbProxyTargetGroup targetGroup = new DbProxyTargetGroup();
+ targetGroup.setDbProxyName(dbProxyName);
+ targetGroup.setTargetGroupName("default");
+ targetGroup.setTargetGroupArn(regionResolver.buildArn("rds", effectiveRegion,
+ "target-group:prx-tg-" + randomResourceSuffix()));
+ targetGroup.setDefaultTargetGroup(true);
+ if ("SQLSERVER".equalsIgnoreCase(engineFamily)) {
+ targetGroup.setMaxConnectionsPercent(10);
+ targetGroup.setMaxIdleConnectionsPercent(5);
}
+ targetGroup.setCreatedAt(now);
+ targetGroup.setUpdatedAt(now);
- DbSubnetGroup group = buildSubnetGroup(name, description, subnetIds, effectiveRegion(region));
- subnetGroups.put(name, group);
- return group;
+ try {
+ putProxyForAccount(accountId, proxyKey, proxy);
+ putTargetGroupForAccount(accountId, proxyKey, targetGroup);
+ } catch (RuntimeException createFailure) {
+ attemptRollback(createFailure,
+ () -> deleteTargetGroupKey(accountId, proxyKey));
+ attemptRollback(createFailure,
+ () -> deleteProxyKey(accountId, proxyKey));
+ boolean stateRemoved = false;
+ try {
+ stateRemoved = getProxyForAccount(accountId, proxyKey).isEmpty()
+ && getTargetGroupForAccount(accountId, proxyKey).isEmpty();
+ } catch (RuntimeException verificationFailure) {
+ createFailure.addSuppressed(verificationFailure);
+ }
+ if (stateRemoved) {
+ releaseProxyPort(proxyPort);
+ throw createFailure;
+ }
+ attemptRollback(createFailure,
+ () -> putProxyForAccount(accountId, proxyKey, proxy));
+ attemptRollback(createFailure,
+ () -> putTargetGroupForAccount(accountId, proxyKey, targetGroup));
+ throw createFailure;
+ }
+ LOG.infov("DB proxy {0} created (mock={1}), endpoint={2}",
+ dbProxyName, String.valueOf(mock), proxy.getEndpoint());
+ return proxy;
}
- public Collection<DbSubnetGroup> listDbSubnetGroups(String filterName) {
- return listDbSubnetGroups(filterName, regionResolver.getDefaultRegion());
- }
+ public synchronized DbProxy modifyDbProxy(
+ String dbProxyName, String defaultAuthScheme, List<DbProxyAuth> auth,
+ Boolean requireTls, Integer idleClientTimeout, Boolean debugLogging,
+ String roleArn, List<String> vpcSecurityGroupIds, Map<String, String> tags,
+ String region) {
+ String effectiveRegion = effectiveRegion(region);
+ String proxyKey = dbProxyKey(effectiveRegion, dbProxyName);
+ DbProxy existing = getDbProxy(dbProxyName, effectiveRegion);
+ DbProxy updated = copyDbProxy(existing);
+
+ if (defaultAuthScheme != null) {
+ updated.setDefaultAuthScheme(normalizeDefaultAuthScheme(defaultAuthScheme));
+ } else if (updated.getDefaultAuthScheme() == null) {
+ updated.setDefaultAuthScheme("NONE");
+ }
+ if (auth != null) {
+ updated.setAuth(auth);
+ }
+ if (requireTls != null) {
+ updated.setRequireTls(requireTls);
+ }
+ if (idleClientTimeout != null) {
+ updated.setIdleClientTimeout(idleClientTimeout);
+ }
+ if (debugLogging != null) {
+ updated.setDebugLogging(debugLogging);
+ }
+ if (roleArn != null) {
+ updated.setRoleArn(roleArn);
+ }
+ if (vpcSecurityGroupIds != null) {
+ updated.setVpcSecurityGroupIds(vpcSecurityGroupIds);
+ }
+ if (tags != null) {
+ updated.setTags(tags);
+ }
+ boolean effectiveIamAuth = "IAM_AUTH".equals(updated.getDefaultAuthScheme())
+ || updated.getAuth().stream()
+ .anyMatch(entry -> isIamEnabledAuthMode(entry.getIamAuth()));
+ updated.setIamAuth(effectiveIamAuth);
+
+ validateDbProxyCreate(updated.getDbProxyName(), updated.getEngineFamily(),
+ updated.getRoleArn(), updated.getVpcSubnetIds(), updated.getAuth(),
+ normalizeDefaultAuthScheme(updated.getDefaultAuthScheme()),
+ updated.getIdleClientTimeout());
+ if (sameDbProxyState(existing, updated)) {
+ return existing;
+ }
- public Collection<DbSubnetGroup> listDbSubnetGroups(String filterName, String region) {
- List<DbSubnetGroup> groups = new ArrayList<>();
- if (filterName == null || filterName.isBlank() || "default".equalsIgnoreCase(filterName)) {
- groups.add(buildDefaultSubnetGroup(effectiveRegion(region)));
+ DbProxyTargetGroup targetGroup = getDefaultProxyTargetGroup(
+ dbProxyName, "default", effectiveRegion);
+ DbProxyTarget registeredTarget = targetGroup.getTargets().isEmpty()
+ ? null : targetGroup.getTargets().get(0);
+ if (registeredTarget != null && !config.services().rds().mock()
+ && "IAM_AUTH".equals(updated.getDefaultAuthScheme())) {
+ throw new AwsException("InvalidDBProxyStateFault",
+ "DefaultAuthScheme IAM_AUTH is available for control-plane emulation only; "
+ + "the real-mode relay does not support end-to-end IAM authentication.",
+ 400);
}
- if (filterName != null && !filterName.isBlank()) {
- if (!"default".equalsIgnoreCase(filterName)) {
- // Specific name: AWS DescribeDBSubnetGroups faults when absent (not empty 200).
- groups.add(resolveDbSubnetGroupView(filterName, region));
+
+ updated.setUpdatedAt(Instant.now());
+ String accountId = accountIdFromArn(existing.getDbProxyArn());
+ if (registeredTarget == null || config.services().rds().mock()
+ || existing.isIamAuth() == updated.isIamAuth()) {
+ try {
+ putProxyForAccount(accountId, proxyKey, updated);
+ return updated;
+ } catch (RuntimeException updateFailure) {
+ attemptRollback(updateFailure,
+ () -> putProxyForAccount(accountId, proxyKey, existing));
+ throw updateFailure;
}
- return groups;
}
- groups.addAll(subnetGroups.scan(k -> true));
- return groups;
+
+ try {
+ proxyManager.stopProxy(dbProxyRelayKey(existing));
+ } catch (RuntimeException stopFailure) {
+ attemptRollback(stopFailure,
+ () -> startDbProxyRelay(existing, registeredTarget));
+ throw stopFailure;
+ }
+ try {
+ startDbProxyRelay(updated, registeredTarget);
+ putProxyForAccount(accountId, proxyKey, updated);
+ return updated;
+ } catch (RuntimeException updateFailure) {
+ attemptRollback(updateFailure,
+ () -> proxyManager.stopProxy(dbProxyRelayKey(updated)));
+ attemptRollback(updateFailure,
+ () -> putProxyForAccount(accountId, proxyKey, existing));
+ attemptRollback(updateFailure,
+ () -> startDbProxyRelay(existing, registeredTarget));
+ throw updateFailure;
+ }
}
- public DbSubnetGroup resolveDbSubnetGroupView(String name) {
- return resolveDbSubnetGroupView(name, regionResolver.getDefaultRegion());
+ /**
+ * Registers the target cluster/instance for a proxy's (single, "default") target group and — in
+ * real mode — starts the auth relay forwarding the proxy endpoint to the target's backend
+ * container. This is the point where the backend host/port become known.
+ */
+ public DbProxyTargetGroup registerDbProxyTargets(String dbProxyName, String targetGroupName,
+ List<String> dbClusterIdentifiers,
+ List<String> dbInstanceIdentifiers,
+ int maxConnectionsPercent,
+ int maxIdleConnectionsPercent) {
+ return registerDbProxyTargets(dbProxyName, targetGroupName, dbClusterIdentifiers,
+ dbInstanceIdentifiers, maxConnectionsPercent, maxIdleConnectionsPercent,
+ regionResolver.getDefaultRegion());
}
- public DbSubnetGroup resolveDbSubnetGroupView(String name, String region) {
- String effectiveName = (name == null || name.isBlank()) ? "default" : name;
- if ("default".equalsIgnoreCase(effectiveName)) {
- return buildDefaultSubnetGroup(effectiveRegion(region));
+ public synchronized DbProxyTargetGroup registerDbProxyTargets(
+ String dbProxyName, String targetGroupName,
+ List<String> dbClusterIdentifiers, List<String> dbInstanceIdentifiers,
+ int maxConnectionsPercent, int maxIdleConnectionsPercent, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ String proxyKey = dbProxyKey(effectiveRegion, dbProxyName);
+ DbProxy proxy = getDbProxy(dbProxyName, effectiveRegion);
+ DbProxyTargetGroup targetGroup = getDefaultProxyTargetGroup(
+ dbProxyName, targetGroupName, effectiveRegion);
+ if (!config.services().rds().mock()
+ && "IAM_AUTH".equals(proxy.getDefaultAuthScheme())) {
+ throw new AwsException("InvalidDBProxyStateFault",
+ "DefaultAuthScheme IAM_AUTH is available for control-plane emulation only; "
+ + "the real-mode relay does not support end-to-end IAM authentication.",
+ 400);
}
- return subnetGroups.get(effectiveName).orElseThrow(() ->
- new AwsException("DBSubnetGroupNotFoundFault",
- "DB subnet group " + effectiveName + " not found.", 404));
- }
- // ── Parameter Groups ──────────────────────────────────────────────────────
+ int clusterCount = dbClusterIdentifiers == null ? 0 : dbClusterIdentifiers.size();
+ int instanceCount = dbInstanceIdentifiers == null ? 0 : dbInstanceIdentifiers.size();
+ if (clusterCount + instanceCount == 0) {
+ throw new AwsException("InvalidParameterValue",
+ "RegisterDBProxyTargets requires a DBClusterIdentifier or DBInstanceIdentifier.", 400);
+ }
+ if (clusterCount + instanceCount != 1) {
+ throw new AwsException("InvalidParameterCombination",
+ "Floci currently supports exactly one DB cluster or DB instance per proxy target group.", 400);
+ }
+ Integer configuredMaxConnections = maxConnectionsPercent > 0 ? maxConnectionsPercent : null;
+ Integer configuredMaxIdle = maxIdleConnectionsPercent > 0 ? maxIdleConnectionsPercent : null;
+ validatePoolConfiguration(configuredMaxConnections, configuredMaxIdle);
+
+ String backendHost;
+ int backendPort;
+ DatabaseEngine engine;
+ String masterUser;
+ String masterPassword;
+ String dbName;
+ DbProxyTarget target;
+ String proxyAccountId = accountIdFromArn(proxy.getDbProxyArn());
+
+ if (clusterCount == 1) {
+ String clusterId = dbClusterIdentifiers.get(0);
+ DbCluster cluster = Optional.ofNullable(findClusterForScope(
+ proxyAccountId, effectiveRegion, clusterId))
+ .orElseThrow(() ->
+ new AwsException("DBClusterNotFoundFault", "DB cluster " + clusterId + " not found.", 404));
+ if (cluster.getStatus() != DbInstanceStatus.AVAILABLE) {
+ throw new AwsException("InvalidDBClusterStateFault",
+ "DB cluster " + clusterId + " is not available.", 400);
+ }
+ validateProxyTargetScope(cluster.getDbClusterArn(), proxyAccountId,
+ effectiveRegion, "DB cluster", clusterId);
+ backendHost = cluster.getContainerHost();
+ backendPort = cluster.getContainerPort();
+ engine = cluster.getEngine();
+ masterUser = cluster.getMasterUsername();
+ masterPassword = cluster.getMasterPassword();
+ dbName = cluster.getDatabaseName();
+ target = new DbProxyTarget("TRACKED_CLUSTER", clusterId, cluster.getDbClusterArn(),
+ cluster.getContainerHost(), cluster.getContainerPort());
+ } else {
+ String instanceId = dbInstanceIdentifiers.get(0);
+ DbInstance instance = Optional.ofNullable(findInstanceForScope(
+ proxyAccountId, effectiveRegion, instanceId))
+ .orElseThrow(() ->
+ new AwsException("DBInstanceNotFound", "DB instance " + instanceId + " not found.", 404));
+ if (instance.getStatus() != DbInstanceStatus.AVAILABLE) {
+ throw new AwsException("InvalidDBInstanceState",
+ "DB instance " + instanceId + " is not available.", 400);
+ }
+ validateProxyTargetScope(instance.getDbInstanceArn(), proxyAccountId,
+ effectiveRegion, "DB instance", instanceId);
+ backendHost = instance.getContainerHost();
+ backendPort = instance.getContainerPort();
+ engine = instance.getEngine();
+ masterUser = instance.getMasterUsername();
+ masterPassword = instance.getMasterPassword();
+ dbName = instance.getDbName();
+ target = new DbProxyTarget("RDS_INSTANCE", instanceId, instance.getDbInstanceArn(),
+ instance.getContainerHost(), instance.getContainerPort());
+ }
- public DbParameterGroup createDbParameterGroup(String name, String family, String description) {
- if (parameterGroups.get(name).isPresent()) {
- throw new AwsException("DBParameterGroupAlreadyExists",
- "DB parameter group " + name + " already exists.", 400);
+ validateTargetEngineFamily(proxy, engine);
+ if (targetGroup.getTargets().stream().anyMatch(existing ->
+ existing.getType().equals(target.getType())
+ && existing.getRdsResourceId().equals(target.getRdsResourceId()))) {
+ throw new AwsException("DBProxyTargetAlreadyRegisteredFault",
+ "The target is already registered with proxy " + dbProxyName + ".", 400);
}
- DbParameterGroup group = new DbParameterGroup(name, family, description);
- parameterGroups.put(name, group);
- return group;
+ if (!targetGroup.getTargets().isEmpty()) {
+ throw new AwsException("InvalidDBProxyStateFault",
+ "The default target group already has a registered target.", 400);
+ }
+
+ boolean realMode = !config.services().rds().mock();
+ if (realMode) {
+ if (backendHost == null || backendPort <= 0) {
+ throw new AwsException("InvalidDBProxyStateFault",
+ "Target backend for proxy " + dbProxyName + " is not available.", 400);
+ }
+ }
+
+ DbProxyTargetGroup updatedTargetGroup = copyProxyTargetGroup(targetGroup);
+ if (configuredMaxConnections != null) {
+ updatedTargetGroup.setMaxConnectionsPercent(configuredMaxConnections);
+ }
+ if (configuredMaxIdle != null) {
+ updatedTargetGroup.setMaxIdleConnectionsPercent(configuredMaxIdle);
+ } else if (configuredMaxConnections != null) {
+ updatedTargetGroup.setMaxIdleConnectionsPercent(configuredMaxConnections / 2);
+ }
+ updatedTargetGroup.getTargets().add(target);
+ updatedTargetGroup.setUpdatedAt(Instant.now());
+ DbProxy updatedProxy = null;
+ if (!"available".equals(proxy.getStatus())) {
+ updatedProxy = copyDbProxy(proxy);
+ updatedProxy.setStatus("available");
+ updatedProxy.setUpdatedAt(Instant.now());
+ }
+ try {
+ if (realMode) {
+ String effectiveMasterUser = masterUser != null ? masterUser : "root";
+ final String targetId = target.getRdsResourceId();
+ final boolean isCluster = "TRACKED_CLUSTER".equals(target.getType());
+ final String targetRegion = regionFromArn(proxy.getDbProxyArn());
+ proxyManager.startProxy(dbProxyRelayKey(proxy), engine, proxy.isIamAuth(),
+ proxy.getProxyPort(), backendHost, backendPort, effectiveMasterUser,
+ masterPassword, dbName,
+ (user, pw) -> isCluster
+ ? validateDbClusterPasswordForScope(
+ proxyAccountId, targetRegion, targetId, user, pw)
+ : validateDbPasswordForScope(
+ proxyAccountId, targetRegion, targetId, user, pw));
+ }
+ putTargetGroupForAccount(proxyAccountId, proxyKey, updatedTargetGroup);
+ if (updatedProxy != null) {
+ putProxyForAccount(proxyAccountId, proxyKey, updatedProxy);
+ }
+ } catch (RuntimeException e) {
+ if (realMode) {
+ attemptRollback(e,
+ () -> proxyManager.stopProxy(dbProxyRelayKey(proxy)));
+ }
+ attemptRollback(e,
+ () -> putTargetGroupForAccount(proxyAccountId, proxyKey, targetGroup));
+ if (updatedProxy != null) {
+ attemptRollback(e,
+ () -> putProxyForAccount(proxyAccountId, proxyKey, proxy));
+ }
+ throw e;
+ }
+ LOG.infov("DB proxy {0} target group default registered target {1}",
+ dbProxyName, target.getRdsResourceId());
+ return updatedTargetGroup;
}
- public DbParameterGroup getDbParameterGroup(String name) {
- return parameterGroups.get(name).orElseThrow(() ->
- new AwsException("DBParameterGroupNotFound",
- "DBParameterGroupName doesn't refer to an existing DB parameter group.", 404));
+ public DbProxyTargetGroup configureDbProxyTargetGroup(String dbProxyName,
+ String targetGroupName,
+ Integer maxConnectionsPercent,
+ Integer maxIdleConnectionsPercent) {
+ return configureDbProxyTargetGroup(dbProxyName, targetGroupName, maxConnectionsPercent,
+ maxIdleConnectionsPercent, null, null, null, regionResolver.getDefaultRegion());
}
- public Collection<DbParameterGroup> listDbParameterGroups(String filterName) {
- if (filterName != null && !filterName.isBlank()) {
- return parameterGroups.get(filterName).map(List::of).orElse(List.of());
- }
- return parameterGroups.scan(k -> true);
+ public DbProxyTargetGroup configureDbProxyTargetGroup(
+ String dbProxyName, String targetGroupName,
+ Integer maxConnectionsPercent, Integer maxIdleConnectionsPercent, String region) {
+ return configureDbProxyTargetGroup(dbProxyName, targetGroupName, maxConnectionsPercent,
+ maxIdleConnectionsPercent, null, null, null, region);
}
- public void deleteDbParameterGroup(String name) {
- if (parameterGroups.get(name).isEmpty()) {
- throw new AwsException("DBParameterGroupNotFound",
- "DBParameterGroupName doesn't refer to an existing DB parameter group.", 404);
+ public synchronized DbProxyTargetGroup configureDbProxyTargetGroup(
+ String dbProxyName, String targetGroupName,
+ Integer maxConnectionsPercent, Integer maxIdleConnectionsPercent,
+ Integer connectionBorrowTimeout, String initQuery,
+ List<String> sessionPinningFilters, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbProxy proxy = getDbProxy(dbProxyName, effectiveRegion);
+ DbProxyTargetGroup targetGroup = getDefaultProxyTargetGroup(
+ dbProxyName, targetGroupName, effectiveRegion);
+ validatePoolConfiguration(proxy, maxConnectionsPercent, maxIdleConnectionsPercent,
+ connectionBorrowTimeout, sessionPinningFilters);
+ DbProxyTargetGroup updatedTargetGroup = copyProxyTargetGroup(targetGroup);
+ if (maxConnectionsPercent != null) {
+ updatedTargetGroup.setMaxConnectionsPercent(maxConnectionsPercent);
+ }
+ if (maxIdleConnectionsPercent != null) {
+ updatedTargetGroup.setMaxIdleConnectionsPercent(maxIdleConnectionsPercent);
+ } else if (maxConnectionsPercent != null) {
+ updatedTargetGroup.setMaxIdleConnectionsPercent(maxConnectionsPercent / 2);
+ }
+ if (connectionBorrowTimeout != null) {
+ updatedTargetGroup.setConnectionBorrowTimeout(connectionBorrowTimeout);
+ }
+ if (initQuery != null) {
+ updatedTargetGroup.setInitQuery(initQuery.isBlank() ? null : initQuery);
+ }
+ if (sessionPinningFilters != null) {
+ updatedTargetGroup.setSessionPinningFilters(sessionPinningFilters);
+ }
+ if (sameProxyTargetGroupConfiguration(targetGroup, updatedTargetGroup)) {
+ return targetGroup;
+ }
+ updatedTargetGroup.setUpdatedAt(Instant.now());
+ String proxyKey = dbProxyKey(effectiveRegion, dbProxyName);
+ String accountId = accountIdFromArn(proxy.getDbProxyArn());
+ try {
+ putTargetGroupForAccount(accountId, proxyKey, updatedTargetGroup);
+ return updatedTargetGroup;
+ } catch (RuntimeException updateFailure) {
+ attemptRollback(updateFailure,
+ () -> putTargetGroupForAccount(accountId, proxyKey, targetGroup));
+ throw updateFailure;
}
- parameterGroups.delete(name);
}
- public DbParameterGroup modifyDbParameterGroup(String name,
- java.util.Map<String, String> parameters) {
- DbParameterGroup group = getDbParameterGroup(name);
- if (parameters != null) {
- group.getParameters().putAll(parameters);
+ public synchronized DbProxyTargetGroup reconcileDbProxyTargetGroup(
+ String dbProxyName, String targetGroupName,
+ List<String> dbClusterIdentifiers, List<String> dbInstanceIdentifiers,
+ int maxConnectionsPercent, int maxIdleConnectionsPercent,
+ int connectionBorrowTimeout, String initQuery,
+ List<String> sessionPinningFilters, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbProxy proxy = getDbProxy(dbProxyName, effectiveRegion);
+ DbProxyTargetGroup original = getDefaultProxyTargetGroup(
+ dbProxyName, targetGroupName, effectiveRegion);
+ List<String> clusterIds = dbClusterIdentifiers != null
+ ? dbClusterIdentifiers : List.of();
+ List<String> instanceIds = dbInstanceIdentifiers != null
+ ? dbInstanceIdentifiers : List.of();
+ validateProxyTargetSelection(proxy, clusterIds, instanceIds, effectiveRegion);
+ validatePoolConfiguration(proxy, maxConnectionsPercent, maxIdleConnectionsPercent,
+ connectionBorrowTimeout, sessionPinningFilters);
+
+ DbProxyTarget currentTarget = original.getTargets().isEmpty()
+ ? null : original.getTargets().get(0);
+ String desiredType = !clusterIds.isEmpty() ? "TRACKED_CLUSTER"
+ : (!instanceIds.isEmpty() ? "RDS_INSTANCE" : null);
+ String desiredId = !clusterIds.isEmpty() ? clusterIds.get(0)
+ : (!instanceIds.isEmpty() ? instanceIds.get(0) : null);
+ boolean targetUnchanged = currentTarget == null
+ ? desiredType == null
+ : Objects.equals(currentTarget.getType(), desiredType)
+ && Objects.equals(currentTarget.getRdsResourceId(), desiredId);
+
+ if (targetUnchanged) {
+ return applyExactProxyTargetGroupConfiguration(proxy, original,
+ maxConnectionsPercent, maxIdleConnectionsPercent,
+ connectionBorrowTimeout, initQuery, sessionPinningFilters, effectiveRegion);
}
- parameterGroups.put(name, group);
- return group;
- }
- public DbSubnetGroup getDbSubnetGroup(String name) {
- return getDbSubnetGroup(name, regionResolver.getDefaultRegion());
+ try {
+ if (currentTarget != null) {
+ deregisterDbProxyTargets(dbProxyName, targetGroupName,
+ "TRACKED_CLUSTER".equals(currentTarget.getType())
+ ? List.of(currentTarget.getRdsResourceId()) : List.of(),
+ "RDS_INSTANCE".equals(currentTarget.getType())
+ ? List.of(currentTarget.getRdsResourceId()) : List.of(),
+ effectiveRegion);
+ }
+ DbProxyTargetGroup reconciled = desiredType == null
+ ? getDefaultProxyTargetGroup(dbProxyName, targetGroupName, effectiveRegion)
+ : registerDbProxyTargets(dbProxyName, targetGroupName,
+ clusterIds, instanceIds, 0, 0, effectiveRegion);
+ return applyExactProxyTargetGroupConfiguration(proxy, reconciled,
+ maxConnectionsPercent, maxIdleConnectionsPercent,
+ connectionBorrowTimeout, initQuery, sessionPinningFilters, effectiveRegion);
+ } catch (RuntimeException reconciliationFailure) {
+ if (!config.services().rds().mock()) {
+ attemptRollback(reconciliationFailure,
+ () -> proxyManager.stopProxy(dbProxyRelayKey(proxy)));
+ }
+ String proxyKey = dbProxyKey(effectiveRegion, dbProxyName);
+ String accountId = accountIdFromArn(proxy.getDbProxyArn());
+ attemptRollback(reconciliationFailure,
+ () -> putTargetGroupForAccount(accountId, proxyKey, original));
+ restartDbProxyRelayAfterFailure(proxy, original, reconciliationFailure);
+ throw reconciliationFailure;
+ }
}
- public DbSubnetGroup getDbSubnetGroup(String name, String region) {
- if ("default".equalsIgnoreCase(name)) {
- return buildDefaultSubnetGroup(effectiveRegion(region));
+ private DbProxyTargetGroup applyExactProxyTargetGroupConfiguration(
+ DbProxy proxy, DbProxyTargetGroup targetGroup,
+ int maxConnectionsPercent, int maxIdleConnectionsPercent,
+ int connectionBorrowTimeout, String initQuery,
+ List<String> sessionPinningFilters, String region) {
+ DbProxyTargetGroup updated = copyProxyTargetGroup(targetGroup);
+ updated.setMaxConnectionsPercent(maxConnectionsPercent);
+ updated.setMaxIdleConnectionsPercent(maxIdleConnectionsPercent);
+ updated.setConnectionBorrowTimeout(connectionBorrowTimeout);
+ updated.setInitQuery(initQuery == null || initQuery.isBlank() ? null : initQuery);
+ updated.setSessionPinningFilters(sessionPinningFilters);
+ if (sameProxyTargetGroupConfiguration(targetGroup, updated)) {
+ return targetGroup;
+ }
+ updated.setUpdatedAt(Instant.now());
+ String proxyKey = dbProxyKey(region, proxy.getDbProxyName());
+ String accountId = accountIdFromArn(proxy.getDbProxyArn());
+ try {
+ putTargetGroupForAccount(accountId, proxyKey, updated);
+ return updated;
+ } catch (RuntimeException updateFailure) {
+ attemptRollback(updateFailure,
+ () -> putTargetGroupForAccount(accountId, proxyKey, targetGroup));
+ throw updateFailure;
}
- return subnetGroups.get(name).orElseThrow(() ->
- new AwsException("DBSubnetGroupNotFoundFault",
- "DB subnet group " + name + " not found.", 404));
}
- public DbSubnetGroup modifyDbSubnetGroup(String name, List<String> subnetIds) {
- return modifyDbSubnetGroup(name, subnetIds, regionResolver.getDefaultRegion());
+ public void deregisterDbProxyTargets(String dbProxyName, String targetGroupName,
+ List<String> dbClusterIdentifiers,
+ List<String> dbInstanceIdentifiers) {
+ deregisterDbProxyTargets(dbProxyName, targetGroupName, dbClusterIdentifiers,
+ dbInstanceIdentifiers, regionResolver.getDefaultRegion());
}
- public DbSubnetGroup modifyDbSubnetGroup(String name, List<String> subnetIds, String region) {
- DbSubnetGroup existing = getDbSubnetGroup(name);
- if (subnetIds == null || subnetIds.isEmpty()) {
+ public synchronized void deregisterDbProxyTargets(
+ String dbProxyName, String targetGroupName,
+ List<String> dbClusterIdentifiers, List<String> dbInstanceIdentifiers, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbProxy proxy = getDbProxy(dbProxyName, effectiveRegion);
+ DbProxyTargetGroup targetGroup = getDefaultProxyTargetGroup(
+ dbProxyName, targetGroupName, effectiveRegion);
+ List<String> clusterIds = dbClusterIdentifiers == null ? List.of() : dbClusterIdentifiers;
+ List<String> instanceIds = dbInstanceIdentifiers == null ? List.of() : dbInstanceIdentifiers;
+ if (clusterIds.isEmpty() && instanceIds.isEmpty()) {
throw new AwsException("InvalidParameterValue",
- "SubnetIds must contain at least one subnet.", 400);
+ "DeregisterDBProxyTargets requires a DBClusterIdentifier or DBInstanceIdentifier.", 400);
}
- DbSubnetGroup group = buildSubnetGroup(name, existing.getDescription(), subnetIds, effectiveRegion(region));
- group.setTags(existing.getTags());
- subnetGroups.put(name, group);
- return group;
- }
- public void deleteDbSubnetGroup(String name) {
- if (subnetGroups.get(name).isEmpty()) {
- throw new AwsException("DBSubnetGroupNotFoundFault",
- "DB subnet group " + name + " not found.", 404);
+ DbProxyTargetGroup updatedTargetGroup = copyProxyTargetGroup(targetGroup);
+ int before = updatedTargetGroup.getTargets().size();
+ updatedTargetGroup.getTargets().removeIf(target ->
+ ("TRACKED_CLUSTER".equals(target.getType()) && clusterIds.contains(target.getRdsResourceId()))
+ || ("RDS_INSTANCE".equals(target.getType())
+ && instanceIds.contains(target.getRdsResourceId())));
+ if (updatedTargetGroup.getTargets().size() == before) {
+ throw new AwsException("DBProxyTargetNotFoundFault",
+ "The specified target is not registered with proxy " + dbProxyName + ".", 404);
}
- subnetGroups.delete(name);
+ updatedTargetGroup.setUpdatedAt(Instant.now());
+ persistTargetGroupAfterRelayStop(proxy, targetGroup, updatedTargetGroup, effectiveRegion);
}
- // ── Cluster Parameter Groups ──────────────────────────────────────────────
+ public DbProxy getDbProxy(String name) {
+ return getDbProxy(name, regionResolver.getDefaultRegion());
+ }
- public DbClusterParameterGroup createDbClusterParameterGroup(String name, String family, String description) {
- if (managedClusterParameterGroup(name) != null || clusterParameterGroups.get(name).isPresent()) {
- throw new AwsException("DBParameterGroupAlreadyExists",
- "DB cluster parameter group " + name + " already exists.", 400);
+ public DbProxy getDbProxy(String name, String region) {
+ if (name == null || name.isBlank()) {
+ throw new AwsException("InvalidParameterValue", "DBProxyName is required.", 400);
}
- DbClusterParameterGroup group = new DbClusterParameterGroup(name, family, description);
- clusterParameterGroups.put(name, group);
- return group;
+ String effectiveRegion = effectiveRegion(region);
+ return findDbProxy(name, effectiveRegion).orElseThrow(() ->
+ new AwsException("DBProxyNotFoundFault", "DB proxy " + name + " not found.", 404));
}
- public DbClusterParameterGroup getDbClusterParameterGroup(String name) {
- if (name != null) {
- DbClusterParameterGroup persisted = clusterParameterGroups.get(name).orElse(null);
- if (persisted != null) {
- return persisted;
- }
- ManagedClusterParameterGroup managed = managedClusterParameterGroup(name);
- if (managed != null) {
- return managed.toModel();
- }
- }
- throw new AwsException("DBClusterParameterGroupNotFound",
- "DBClusterParameterGroupName doesn't refer to an existing DB cluster parameter group.", 404);
+ public Collection<DbProxy> listDbProxies(String filterName) {
+ return listDbProxies(filterName, regionResolver.getDefaultRegion());
}
- public Collection<DbClusterParameterGroup> listDbClusterParameterGroups(String filterName) {
+ public Collection<DbProxy> listDbProxies(String filterName, String region) {
+ String effectiveRegion = effectiveRegion(region);
if (filterName != null && !filterName.isBlank()) {
- try {
- return List.of(getDbClusterParameterGroup(filterName));
- } catch (AwsException e) {
+ return List.of(getDbProxy(filterName, effectiveRegion));
+ }
+ String accountId = currentAccountId();
+ Map<String, DbProxy> unique = new LinkedHashMap<>();
+ proxies.scan(k -> true).stream()
+ .filter(proxy -> proxyBelongsTo(proxy, accountId, effectiveRegion))
+ .forEach(proxy -> findDbProxy(proxy.getDbProxyName(), effectiveRegion)
+ .ifPresent(canonical -> unique.put(
+ canonical.getDbProxyArn(), canonical)));
+ return List.copyOf(unique.values());
+ }
+
+ public Collection<DbProxyTargetGroup> describeDbProxyTargetGroups(String dbProxyName) {
+ return describeDbProxyTargetGroups(dbProxyName, null);
+ }
+
+ public Collection<DbProxyTargetGroup> describeDbProxyTargetGroups(String dbProxyName,
+ String targetGroupName) {
+ return describeDbProxyTargetGroups(dbProxyName, targetGroupName,
+ regionResolver.getDefaultRegion());
+ }
+
+ public Collection<DbProxyTargetGroup> describeDbProxyTargetGroups(
+ String dbProxyName, String targetGroupName, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ getDbProxy(dbProxyName, effectiveRegion);
+ return List.of(getDefaultProxyTargetGroup(dbProxyName, targetGroupName, effectiveRegion));
+ }
+
+ public Collection<DbProxyTarget> describeDbProxyTargets(String dbProxyName, String targetGroupName) {
+ return describeDbProxyTargets(dbProxyName, targetGroupName,
+ regionResolver.getDefaultRegion());
+ }
+
+ public Collection<DbProxyTarget> describeDbProxyTargets(
+ String dbProxyName, String targetGroupName, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ getDbProxy(dbProxyName, effectiveRegion);
+ return new ArrayList<>(getDefaultProxyTargetGroup(
+ dbProxyName, targetGroupName, effectiveRegion).getTargets());
+ }
+
+ public synchronized void clearDbProxyTargetGroupByArn(String targetGroupArn) {
+ clearDbProxyTargetGroupByArn(targetGroupArn, regionFromArn(targetGroupArn));
+ }
+
+ public synchronized void clearDbProxyTargetGroupByArn(String targetGroupArn, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbProxyTargetGroup targetGroup = getDbProxyTargetGroupByArn(targetGroupArn, effectiveRegion);
+ DbProxyTargetGroup clearedTargetGroup = copyProxyTargetGroup(targetGroup);
+ clearedTargetGroup.getTargets().clear();
+ DbProxy proxy = getDbProxy(targetGroup.getDbProxyName(), effectiveRegion);
+ boolean sqlServer = "SQLSERVER".equals(proxy.getEngineFamily());
+ clearedTargetGroup.setMaxConnectionsPercent(sqlServer ? 10 : 100);
+ clearedTargetGroup.setMaxIdleConnectionsPercent(sqlServer ? 5 : 50);
+ clearedTargetGroup.setConnectionBorrowTimeout(120);
+ clearedTargetGroup.setInitQuery(null);
+ clearedTargetGroup.setSessionPinningFilters(List.of());
+ clearedTargetGroup.setUpdatedAt(Instant.now());
+ persistTargetGroupAfterRelayStop(proxy, targetGroup, clearedTargetGroup, effectiveRegion);
+ }
+
+ public synchronized DbProxyTargetGroup getDbProxyTargetGroupByArn(
+ String targetGroupArn, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ validateResourceRegion(targetGroupArn, effectiveRegion, "DB proxy target group");
+ DbProxyTargetGroup targetGroup = proxyTargetGroups.scan(k -> true).stream()
+ .filter(candidate -> effectiveRegion.equals(regionFromArn(candidate.getTargetGroupArn())))
+ .filter(candidate -> Objects.equals(targetGroupArn, candidate.getTargetGroupArn()))
+ .findFirst()
+ .orElseThrow(() -> new AwsException("DBProxyTargetGroupNotFoundFault",
+ "DB proxy target group " + targetGroupArn + " not found.", 404));
+ return findProxyTargetGroup(targetGroup.getDbProxyName(), effectiveRegion)
+ .filter(candidate -> Objects.equals(targetGroupArn, candidate.getTargetGroupArn()))
+ .orElseThrow(() -> new AwsException("DBProxyTargetGroupNotFoundFault",
+ "DB proxy target group " + targetGroupArn + " not found.", 404));
+ }
+
+ public synchronized void deleteDbProxy(String name) {
+ deleteDbProxy(name, regionResolver.getDefaultRegion());
+ }
+
+ public synchronized void deleteDbProxy(String name, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ String proxyKey = dbProxyKey(effectiveRegion, name);
+ DbProxy proxy = getDbProxy(name, effectiveRegion);
+ String accountId = accountIdFromArn(proxy.getDbProxyArn());
+ Optional<DbProxyTargetGroup> canonicalTargetGroup =
+ getTargetGroupForAccount(accountId, proxyKey);
+ Optional<DbProxyTargetGroup> legacyTargetGroup =
+ getTargetGroupForAccount(accountId, name)
+ .filter(candidate -> targetGroupBelongsTo(
+ candidate, accountId, effectiveRegion)
+ && Objects.equals(name, candidate.getDbProxyName()));
+ Optional<DbProxy> legacyProxy = getProxyForAccount(accountId, name)
+ .filter(candidate -> proxyBelongsTo(candidate, accountId, effectiveRegion)
+ && Objects.equals(name, candidate.getDbProxyName()));
+ DbProxyTargetGroup relayTargetGroup = canonicalTargetGroup
+ .filter(candidate -> targetGroupMatchesProxy(candidate, proxy))
+ .or(() -> legacyTargetGroup
+ .filter(candidate -> targetGroupMatchesProxy(candidate, proxy)))
+ .orElse(null);
+ boolean realMode = !config.services().rds().mock();
+ if (realMode) {
+ try {
+ proxyManager.stopProxy(dbProxyRelayKey(proxy));
+ } catch (RuntimeException stopFailure) {
+ restartDbProxyRelayAfterFailure(proxy, relayTargetGroup, stopFailure);
+ throw stopFailure;
+ }
+ }
+ try {
+ deleteTargetGroupKey(accountId, proxyKey);
+ if (legacyTargetGroup.isPresent()) {
+ deleteTargetGroupKey(accountId, name);
+ }
+ if (legacyProxy.isPresent()) {
+ deleteProxyKey(accountId, name);
+ }
+ deleteProxyKey(accountId, proxyKey);
+ } catch (RuntimeException deleteFailure) {
+ attemptRollback(deleteFailure,
+ () -> putProxyForAccount(accountId, proxyKey, proxy));
+ canonicalTargetGroup.ifPresent(targetGroup -> attemptRollback(deleteFailure,
+ () -> putTargetGroupForAccount(accountId, proxyKey, targetGroup)));
+ legacyProxy.ifPresent(candidate -> attemptRollback(deleteFailure,
+ () -> putProxyForAccount(accountId, name, candidate)));
+ legacyTargetGroup.ifPresent(targetGroup -> attemptRollback(deleteFailure,
+ () -> putTargetGroupForAccount(accountId, name, targetGroup)));
+ restartDbProxyRelayAfterFailure(proxy, relayTargetGroup, deleteFailure);
+ throw deleteFailure;
+ }
+ releaseProxyPort(proxy.getProxyPort());
+ LOG.infov("DB proxy {0} deleted", name);
+ }
+
+ // ── DB Subnet Groups ──────────────────────────────────────────────────────
+
+ public DbSubnetGroup createDbSubnetGroup(String name, String description, List<String> subnetIds) {
+ return createDbSubnetGroup(name, description, subnetIds, regionResolver.getDefaultRegion());
+ }
+
+ public DbSubnetGroup createDbSubnetGroup(String name, String description, List<String> subnetIds, String region) {
+ if (name == null || name.isBlank()) {
+ throw new AwsException("MissingParameter", "The request must contain the parameter DBSubnetGroupName.", 400);
+ }
+ String effectiveRegion = effectiveRegion(region);
+ if (findSubnetGroupForScope(currentAccountId(), effectiveRegion, name) != null
+ || scopedKeyExists(subnetGroups, currentAccountId(),
+ dbResourceKey(effectiveRegion, name))
+ || "default".equalsIgnoreCase(name)) {
+ throw new AwsException("DBSubnetGroupAlreadyExists",
+ "DB subnet group " + name + " already exists.", 400);
+ }
+ if (subnetIds == null || subnetIds.isEmpty()) {
+ throw new AwsException("MissingParameter", "The request must contain the parameter SubnetIds.", 400);
+ }
+
+ DbSubnetGroup group = buildSubnetGroup(name, description, subnetIds, effectiveRegion);
+ putSubnetGroupForScope(currentAccountId(), effectiveRegion, name, group);
+ return group;
+ }
+
+ public Collection<DbSubnetGroup> listDbSubnetGroups(String filterName) {
+ return listDbSubnetGroups(filterName, regionResolver.getDefaultRegion());
+ }
+
+ public Collection<DbSubnetGroup> listDbSubnetGroups(String filterName, String region) {
+ String accountId = currentAccountId();
+ String effectiveRegion = effectiveRegion(region);
+ List<DbSubnetGroup> groups = new ArrayList<>();
+ if (filterName == null || filterName.isBlank() || "default".equalsIgnoreCase(filterName)) {
+ groups.add(buildDefaultSubnetGroup(effectiveRegion));
+ }
+ if (filterName != null && !filterName.isBlank()) {
+ if (!"default".equalsIgnoreCase(filterName)) {
+ // Specific name: AWS DescribeDBSubnetGroups faults when absent (not empty 200).
+ groups.add(resolveDbSubnetGroupView(filterName, effectiveRegion));
+ }
+ return groups;
+ }
+ Map<String, DbSubnetGroup> unique = new LinkedHashMap<>();
+ List<DbSubnetGroup> storedGroups;
+ if (subnetGroups instanceof AccountAwareStorageBackend<DbSubnetGroup> aware) {
+ storedGroups = new ArrayList<>(aware.scanForAccount(accountId, k -> true));
+ storedGroups.addAll(aware.scanUnscopedLegacy(group ->
+ group != null
+ && hasRdsResourceIdentity(
+ group.getDbSubnetGroupArn(), accountId, effectiveRegion,
+ "subgrp", group.getDbSubnetGroupName())));
+ } else {
+ storedGroups = subnetGroups.scan(k -> true);
+ }
+ for (DbSubnetGroup group : storedGroups) {
+ if (hasRdsResourceIdentity(
+ group.getDbSubnetGroupArn(), accountId, effectiveRegion,
+ "subgrp", group.getDbSubnetGroupName())) {
+ DbSubnetGroup canonical = findSubnetGroupForScope(
+ accountId, effectiveRegion, group.getDbSubnetGroupName());
+ if (canonical != null) {
+ unique.put(canonical.getDbSubnetGroupArn(), canonical);
+ }
+ }
+ }
+ groups.addAll(unique.values());
+ return groups;
+ }
+
+ public DbSubnetGroup resolveDbSubnetGroupView(String name) {
+ return resolveDbSubnetGroupView(name, regionResolver.getDefaultRegion());
+ }
+
+ public DbSubnetGroup resolveDbSubnetGroupView(String name, String region) {
+ String effectiveName = (name == null || name.isBlank()) ? "default" : name;
+ if ("default".equalsIgnoreCase(effectiveName)) {
+ return buildDefaultSubnetGroup(effectiveRegion(region));
+ }
+ DbSubnetGroup group = findSubnetGroupForScope(
+ currentAccountId(), effectiveRegion(region), effectiveName);
+ if (group == null) {
+ throw new AwsException("DBSubnetGroupNotFoundFault",
+ "DB subnet group " + effectiveName + " not found.", 404);
+ }
+ return group;
+ }
+
+ // ── Parameter Groups ──────────────────────────────────────────────────────
+
+ public DbParameterGroup createDbParameterGroup(String name, String family, String description) {
+ return createDbParameterGroup(
+ name, family, description, regionResolver.getDefaultRegion());
+ }
+
+ public DbParameterGroup createDbParameterGroup(
+ String name, String family, String description, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ if (findParameterGroupForRegion(name, effectiveRegion) != null
+ || scopedKeyExists(parameterGroups, currentAccountId(),
+ dbResourceKey(effectiveRegion, name))) {
+ throw new AwsException("DBParameterGroupAlreadyExists",
+ "DB parameter group " + name + " already exists.", 400);
+ }
+ DbParameterGroup group = new DbParameterGroup(name, family, description);
+ group.setRegion(effectiveRegion);
+ putParameterGroupForRegion(name, effectiveRegion, group);
+ return group;
+ }
+
+ public DbParameterGroup getDbParameterGroup(String name) {
+ return getDbParameterGroup(name, regionResolver.getDefaultRegion());
+ }
+
+ public DbParameterGroup getDbParameterGroup(String name, String region) {
+ DbParameterGroup group = findParameterGroupForRegion(name, effectiveRegion(region));
+ if (group == null) {
+ throw new AwsException("DBParameterGroupNotFound",
+ "DBParameterGroupName doesn't refer to an existing DB parameter group.", 404);
+ }
+ return group;
+ }
+
+ public Collection<DbParameterGroup> listDbParameterGroups(String filterName) {
+ return listDbParameterGroups(filterName, regionResolver.getDefaultRegion());
+ }
+
+ public Collection<DbParameterGroup> listDbParameterGroups(
+ String filterName, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ if (filterName != null && !filterName.isBlank()) {
+ DbParameterGroup group = findParameterGroupForRegion(filterName, effectiveRegion);
+ return group != null ? List.of(group) : List.of();
+ }
+ Map<String, DbParameterGroup> unique = new LinkedHashMap<>();
+ List<DbParameterGroup> storedGroups;
+ if (parameterGroups instanceof AccountAwareStorageBackend<DbParameterGroup> aware) {
+ storedGroups = new ArrayList<>(aware.scanForAccount(currentAccountId(), k -> true));
+ if (Objects.equals(currentAccountId(), defaultAccountId())) {
+ storedGroups.addAll(aware.scanUnscopedLegacy(group ->
+ parameterGroupBelongsToRegion(group, effectiveRegion)));
+ }
+ } else {
+ storedGroups = parameterGroups.scan(k -> true);
+ }
+ for (DbParameterGroup group : storedGroups) {
+ if (parameterGroupBelongsToRegion(group, effectiveRegion)) {
+ DbParameterGroup canonical = findParameterGroupForRegion(
+ group.getDbParameterGroupName(), effectiveRegion);
+ if (canonical != null) {
+ unique.put(canonical.getDbParameterGroupName(), canonical);
+ }
+ }
+ }
+ return unique.values();
+ }
+
+ public void deleteDbParameterGroup(String name) {
+ deleteDbParameterGroup(name, regionResolver.getDefaultRegion());
+ }
+
+ public void deleteDbParameterGroup(String name, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ if (findParameterGroupForRegion(name, effectiveRegion) == null) {
+ throw new AwsException("DBParameterGroupNotFound",
+ "DBParameterGroupName doesn't refer to an existing DB parameter group.", 404);
+ }
+ deleteParameterGroupForRegion(name, effectiveRegion);
+ }
+
+ public DbParameterGroup modifyDbParameterGroup(String name,
+ java.util.Map<String, String> parameters) {
+ return modifyDbParameterGroup(
+ name, parameters, regionResolver.getDefaultRegion());
+ }
+
+ public DbParameterGroup modifyDbParameterGroup(
+ String name, java.util.Map<String, String> parameters, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ DbParameterGroup group = getDbParameterGroup(name, effectiveRegion);
+ if (parameters != null) {
+ group.getParameters().putAll(parameters);
+ }
+ putParameterGroupForRegion(name, effectiveRegion, group);
+ return group;
+ }
+
+ public DbSubnetGroup getDbSubnetGroup(String name) {
+ return getDbSubnetGroup(name, regionResolver.getDefaultRegion());
+ }
+
+ public DbSubnetGroup getDbSubnetGroup(String name, String region) {
+ if ("default".equalsIgnoreCase(name)) {
+ return buildDefaultSubnetGroup(effectiveRegion(region));
+ }
+ DbSubnetGroup group = findSubnetGroupForScope(
+ currentAccountId(), effectiveRegion(region), name);
+ if (group == null) {
+ throw new AwsException("DBSubnetGroupNotFoundFault",
+ "DB subnet group " + name + " not found.", 404);
+ }
+ return group;
+ }
+
+ public DbSubnetGroup modifyDbSubnetGroup(String name, List<String> subnetIds) {
+ return modifyDbSubnetGroup(name, subnetIds, regionResolver.getDefaultRegion());
+ }
+
+ public DbSubnetGroup modifyDbSubnetGroup(String name, List<String> subnetIds, String region) {
+ DbSubnetGroup existing = getDbSubnetGroup(name, region);
+ if (subnetIds == null || subnetIds.isEmpty()) {
+ throw new AwsException("InvalidParameterValue",
+ "SubnetIds must contain at least one subnet.", 400);
+ }
+ DbSubnetGroup group = buildSubnetGroup(name, existing.getDescription(), subnetIds, effectiveRegion(region));
+ group.setTags(existing.getTags());
+ putSubnetGroupForScope(
+ currentAccountId(), effectiveRegion(region), name, group);
+ return group;
+ }
+
+ public void deleteDbSubnetGroup(String name) {
+ deleteDbSubnetGroup(name, regionResolver.getDefaultRegion());
+ }
+
+ public void deleteDbSubnetGroup(String name, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ String accountId = currentAccountId();
+ if (findSubnetGroupForScope(accountId, effectiveRegion, name) == null) {
+ throw new AwsException("DBSubnetGroupNotFoundFault",
+ "DB subnet group " + name + " not found.", 404);
+ }
+ deleteSubnetGroupForScope(accountId, effectiveRegion, name);
+ }
+
+ // ── Cluster Parameter Groups ──────────────────────────────────────────────
+
+ public DbClusterParameterGroup createDbClusterParameterGroup(String name, String family, String description) {
+ return createDbClusterParameterGroup(
+ name, family, description, regionResolver.getDefaultRegion());
+ }
+
+ public DbClusterParameterGroup createDbClusterParameterGroup(
+ String name, String family, String description, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ if (managedClusterParameterGroup(name) != null
+ || findClusterParameterGroupForRegion(name, effectiveRegion) != null
+ || scopedKeyExists(clusterParameterGroups, currentAccountId(),
+ dbResourceKey(effectiveRegion, name))) {
+ throw new AwsException("DBParameterGroupAlreadyExists",
+ "DB cluster parameter group " + name + " already exists.", 400);
+ }
+ DbClusterParameterGroup group = new DbClusterParameterGroup(name, family, description);
+ group.setRegion(effectiveRegion);
+ putClusterParameterGroupForRegion(name, effectiveRegion, group);
+ return group;
+ }
+
+ public DbClusterParameterGroup getDbClusterParameterGroup(String name) {
+ return getDbClusterParameterGroup(name, regionResolver.getDefaultRegion());
+ }
+
+ public DbClusterParameterGroup getDbClusterParameterGroup(String name, String region) {
+ DbClusterParameterGroup group = findClusterParameterGroupForRegion(
+ name, effectiveRegion(region));
+ if (group == null) {
+ ManagedClusterParameterGroup managed = managedClusterParameterGroup(name);
+ if (managed != null) {
+ group = managed.toModel(effectiveRegion(region));
+ }
+ }
+ if (group == null) {
+ throw new AwsException("DBClusterParameterGroupNotFound",
+ "DBClusterParameterGroupName doesn't refer to an existing DB cluster parameter group.", 404);
+ }
+ return group;
+ }
+
+ public Collection<DbClusterParameterGroup> listDbClusterParameterGroups(String filterName) {
+ return listDbClusterParameterGroups(filterName, regionResolver.getDefaultRegion());
+ }
+
+ public Collection<DbClusterParameterGroup> listDbClusterParameterGroups(
+ String filterName, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ if (filterName != null && !filterName.isBlank()) {
+ try {
+ return List.of(getDbClusterParameterGroup(filterName, effectiveRegion));
+ } catch (AwsException e) {
if ("DBClusterParameterGroupNotFound".equals(e.getErrorCode())) {
throw new AwsException("DBParameterGroupNotFound",
"DBParameterGroupName doesn't refer to an existing DB parameter group.", 404);
@@ -1002,16 +2127,32 @@ public class RdsService implements Resettable {
throw e;
}
}
- Map<String, DbClusterParameterGroup> groups = new LinkedHashMap<>();
+ Map<String, DbClusterParameterGroup> unique = new LinkedHashMap<>();
for (ManagedClusterParameterGroup managed : MANAGED_CLUSTER_PARAMETER_GROUPS) {
- groups.put(managed.name(), managed.toModel());
+ DbClusterParameterGroup group = managed.toModel(effectiveRegion);
+ unique.put(group.getDbClusterParameterGroupName(), group);
+ }
+ List<DbClusterParameterGroup> storedGroups;
+ if (clusterParameterGroups
+ instanceof AccountAwareStorageBackend<DbClusterParameterGroup> aware) {
+ storedGroups = new ArrayList<>(aware.scanForAccount(currentAccountId(), k -> true));
+ if (Objects.equals(currentAccountId(), defaultAccountId())) {
+ storedGroups.addAll(aware.scanUnscopedLegacy(group ->
+ clusterParameterGroupBelongsToRegion(group, effectiveRegion)));
+ }
+ } else {
+ storedGroups = clusterParameterGroups.scan(k -> true);
}
- clusterParameterGroups.scan(k -> true).stream()
+ storedGroups.stream()
.sorted(Comparator.comparing(
DbClusterParameterGroup::getDbClusterParameterGroupName,
Comparator.nullsLast(Comparator.naturalOrder())))
- .forEach(group -> groups.put(group.getDbClusterParameterGroupName(), group));
- return List.copyOf(groups.values());
+ .filter(group -> clusterParameterGroupBelongsToRegion(group, effectiveRegion))
+ .map(group -> findClusterParameterGroupForRegion(
+ group.getDbClusterParameterGroupName(), effectiveRegion))
+ .filter(Objects::nonNull)
+ .forEach(group -> unique.put(group.getDbClusterParameterGroupName(), group));
+ return unique.values();
}
private static ManagedClusterParameterGroup managedClusterParameterGroup(String name) {
@@ -1031,41 +2172,62 @@ public class RdsService implements Resettable {
}
private record ManagedClusterParameterGroup(String name, String family, String description) {
- private DbClusterParameterGroup toModel() {
- return new DbClusterParameterGroup(name, family, description);
+ private DbClusterParameterGroup toModel(String region) {
+ DbClusterParameterGroup group = new DbClusterParameterGroup(name, family, description);
+ group.setRegion(region);
+ return group;
}
}
public void deleteDbClusterParameterGroup(String name) {
+ deleteDbClusterParameterGroup(name, regionResolver.getDefaultRegion());
+ }
+
+ public void deleteDbClusterParameterGroup(String name, String region) {
+ String effectiveRegion = effectiveRegion(region);
if (managedClusterParameterGroup(name) != null) {
throw new AwsException("InvalidDBParameterGroupState",
"The default DB cluster parameter group cannot be deleted.", 400);
}
- if (clusterParameterGroups.get(name).isEmpty()) {
+ if (findClusterParameterGroupForRegion(name, effectiveRegion) == null) {
throw new AwsException("DBClusterParameterGroupNotFound",
"DBClusterParameterGroupName doesn't refer to an existing DB cluster parameter group.", 404);
}
- clusterParameterGroups.delete(name);
+ deleteClusterParameterGroupForRegion(name, effectiveRegion);
}
public DbClusterParameterGroup modifyDbClusterParameterGroup(String name,
java.util.Map<String, String> parameters) {
+ return modifyDbClusterParameterGroup(
+ name, parameters, regionResolver.getDefaultRegion());
+ }
+
+ public DbClusterParameterGroup modifyDbClusterParameterGroup(
+ String name, java.util.Map<String, String> parameters, String region) {
+ String effectiveRegion = effectiveRegion(region);
if (managedClusterParameterGroup(name) != null) {
throw new AwsException("InvalidDBParameterGroupState",
"The default DB cluster parameter group cannot be modified.", 400);
}
- DbClusterParameterGroup group = getDbClusterParameterGroup(name);
+ DbClusterParameterGroup group = getDbClusterParameterGroup(name, effectiveRegion);
if (parameters != null) {
group.getParameters().putAll(parameters);
}
- clusterParameterGroups.put(name, group);
+ putClusterParameterGroupForRegion(name, effectiveRegion, group);
return group;
}
// ── Password validation callbacks ─────────────────────────────────────────
public boolean validateDbPassword(String instanceId, String clientUser, String password) {
- DbInstance instance = instances.get(instanceId).orElse(null);
+ return validateDbPasswordForScope(
+ null, regionResolver.getDefaultRegion(), instanceId, clientUser, password);
+ }
+
+ private boolean validateDbPasswordForScope(
+ String accountId, String region, String instanceId,
+ String clientUser, String password) {
+ DbInstance instance = findInstanceForScope(accountId, effectiveRegion(region), instanceId);
if (instance == null) {
return false;
}
@@ -1076,7 +2238,14 @@ public class RdsService implements Resettable {
}
public boolean validateDbClusterPassword(String clusterId, String clientUser, String password) {
- DbCluster cluster = clusters.get(clusterId).orElse(null);
+ return validateDbClusterPasswordForScope(
+ null, regionResolver.getDefaultRegion(), clusterId, clientUser, password);
+ }
+
+ private boolean validateDbClusterPasswordForScope(
+ String accountId, String region, String clusterId,
+ String clientUser, String password) {
+ DbCluster cluster = findClusterForScope(accountId, effectiveRegion(region), clusterId);
if (cluster == null) {
return false;
}
@@ -1114,19 +2283,21 @@ public class RdsService implements Resettable {
};
}
- private void validateInstanceParameterGroup(String paramGroupName, String engineParam, String engineVersion) {
+ private void validateInstanceParameterGroup(
+ String paramGroupName, String engineParam, String engineVersion, String region) {
if (paramGroupName == null || paramGroupName.isBlank()) {
return;
}
- DbParameterGroup group = getDbParameterGroup(paramGroupName);
+ DbParameterGroup group = getDbParameterGroup(paramGroupName, region);
validateParameterGroupFamily(paramGroupName, group.getDbParameterGroupFamily(), engineParam, engineVersion);
}
- private void validateClusterParameterGroup(String paramGroupName, String engineParam, String engineVersion) {
+ private void validateClusterParameterGroup(
+ String paramGroupName, String engineParam, String engineVersion, String region) {
if (paramGroupName == null || paramGroupName.isBlank()) {
return;
}
- DbClusterParameterGroup group = getDbClusterParameterGroup(paramGroupName);
+ DbClusterParameterGroup group = getDbClusterParameterGroup(paramGroupName, region);
String family = group.getDbParameterGroupFamily();
String expectedFamily = expectedClusterParameterGroupFamily(engineParam, engineVersion);
if (family == null || !family.equalsIgnoreCase(expectedFamily)) {
@@ -1260,47 +2431,745 @@ public class RdsService implements Resettable {
return dockerHostResolver != null ? dockerHostResolver.resolve() : "localhost";
}
- private void restoreClusters() {
- for (DbCluster cluster : allClusters()) {
- if (cluster.getStatus() == DbInstanceStatus.DELETING) {
- continue;
- }
- if (config.services().rds().mock()) {
- int mockPort = reserveOrAllocateProxyPort(cluster.getProxyPort());
- cluster.setProxyPort(mockPort);
- cluster.setEndpoint(new DbEndpoint("localhost", mockPort));
- cluster.setReaderEndpoint(new DbEndpoint("localhost", mockPort));
- cluster.setStatus(DbInstanceStatus.AVAILABLE);
- continue;
- }
- int proxyPort = reserveOrAllocateProxyPort(cluster.getProxyPort());
- cluster.setProxyPort(proxyPort);
- DbEndpoint endpoint = proxyEndpoint(proxyPort);
- cluster.setEndpoint(endpoint);
- cluster.setReaderEndpoint(endpoint);
- if (cluster.getDockerVolumeName() == null) {
- cluster.setDockerVolumeName(volumeName(cluster.getVolumeId(), cluster.getDbClusterIdentifier()));
- }
- try {
- String image = imageForEngine(cluster.getEngine(), cluster.getEngineVersion());
- RdsContainerHandle handle = containerManager.start(cluster.getDbClusterIdentifier(),
- cluster.getVolumeId(), cluster.getEngine(), image,
- cluster.getMasterUsername(), cluster.getMasterPassword(), cluster.getDatabaseName());
- cluster.setContainerId(handle.getContainerId());
- cluster.setContainerHost(handle.getHost());
- cluster.setContainerPort(handle.getPort());
-
- String effectiveMasterUser = cluster.getMasterUsername() != null
- ? cluster.getMasterUsername() : "root";
- proxyManager.startProxy(cluster.getDbClusterIdentifier(), cluster.getEngine(),
- cluster.isIamDatabaseAuthenticationEnabled(), proxyPort,
- handle.getHost(), handle.getPort(), effectiveMasterUser,
- cluster.getMasterPassword(), cluster.getDatabaseName(),
- (user, pw) -> validateDbClusterPassword(cluster.getDbClusterIdentifier(), user, pw));
- cluster.setStatus(DbInstanceStatus.AVAILABLE);
- } catch (Exception e) {
- releaseProxyPort(proxyPort);
- LOG.warnv(e, "Failed to restore RDS cluster {0}", cluster.getDbClusterIdentifier());
+ private void validateDbProxyCreate(String name, String engineFamily, String roleArn,
+ List<String> subnetIds, List<DbProxyAuth> auth,
+ String defaultAuthScheme, int idleClientTimeout) {
+ if (name == null || name.isBlank() || name.length() > 63
+ || !DB_PROXY_NAME_PATTERN.matcher(name).matches()) {
+ throw new AwsException("InvalidParameterValue",
+ "DBProxyName must be 1-63 characters, begin with a letter, and contain only letters, digits, and single hyphens.",
+ 400);
+ }
+ if (engineFamily == null || !("MYSQL".equalsIgnoreCase(engineFamily)
+ || "POSTGRESQL".equalsIgnoreCase(engineFamily)
+ || "SQLSERVER".equalsIgnoreCase(engineFamily))) {
+ throw new AwsException("InvalidParameterValue",
+ "EngineFamily must be MYSQL, POSTGRESQL, or SQLSERVER.", 400);
+ }
+ if (roleArn == null || roleArn.length() < 20 || roleArn.length() > 2048) {
+ throw new AwsException("InvalidParameterValue", "RoleArn is required.", 400);
+ }
+ if (subnetIds == null || subnetIds.stream()
+ .filter(subnetId -> subnetId != null && !subnetId.isBlank())
+ .distinct()
+ .count() < 2) {
+ throw new AwsException("InvalidParameterValue",
+ "VpcSubnetIds must contain at least two distinct subnet IDs.", 400);
+ }
+ if ("NONE".equals(defaultAuthScheme) && (auth == null || auth.isEmpty())) {
+ throw new AwsException("InvalidParameterValue",
+ "Auth is required when DefaultAuthScheme is NONE.", 400);
+ }
+ if ("SQLSERVER".equalsIgnoreCase(engineFamily)
+ && "IAM_AUTH".equals(defaultAuthScheme)) {
+ throw new AwsException("InvalidParameterValue",
+ "DefaultAuthScheme IAM_AUTH is not supported for SQLSERVER DB proxies.", 400);
+ }
+ validateDbProxyAuth(engineFamily, auth);
+ if (idleClientTimeout < 1 || idleClientTimeout > 28_800) {
+ throw new AwsException("InvalidParameterValue",
+ "IdleClientTimeout must be between 1 and 28800 seconds.", 400);
+ }
+ }
+
+ private String normalizeDefaultAuthScheme(String defaultAuthScheme) {
+ if (defaultAuthScheme == null || "NONE".equalsIgnoreCase(defaultAuthScheme)) {
+ return "NONE";
+ }
+ if ("IAM_AUTH".equalsIgnoreCase(defaultAuthScheme)) {
+ return "IAM_AUTH";
+ }
+ throw new AwsException("InvalidParameterValue",
+ "DefaultAuthScheme must be NONE or IAM_AUTH.", 400);
+ }
+
+ private static boolean isIamEnabledAuthMode(String iamAuth) {
+ return "REQUIRED".equalsIgnoreCase(iamAuth)
+ || "ENABLED".equalsIgnoreCase(iamAuth);
+ }
+
+ private void validateDbProxyAuth(String engineFamily, List<DbProxyAuth> auth) {
+ if (auth == null) {
+ return;
+ }
+ if (auth.size() > 200) {
+ throw new AwsException("InvalidParameterValue",
+ "Auth cannot contain more than 200 entries.", 400);
+ }
+ for (DbProxyAuth entry : auth) {
+ if (entry == null) {
+ throw new AwsException("InvalidParameterValue",
+ "Auth entries must not be null.", 400);
+ }
+ validateOptionalEnum("AuthScheme", entry.getAuthScheme(), DB_PROXY_AUTH_SCHEMES);
+ validateOptionalEnum("IAMAuth", entry.getIamAuth(), DB_PROXY_IAM_AUTH_MODES);
+ validateOptionalEnum("ClientPasswordAuthType", entry.getClientPasswordAuthType(),
+ DB_PROXY_CLIENT_PASSWORD_AUTH_TYPES);
+ if ("ENABLED".equals(entry.getIamAuth())
+ && !"SQLSERVER".equalsIgnoreCase(engineFamily)) {
+ throw new AwsException("InvalidParameterValue",
+ "IAMAuth ENABLED is supported only for SQLSERVER DB proxies.", 400);
+ }
+ validateOptionalLength("Description", entry.getDescription(), 1, 1_000);
+ validateOptionalLength("SecretArn", entry.getSecretArn(), 20, 2_048);
+ validateOptionalLength("UserName", entry.getUserName(), 1, 128);
+ }
+ }
+
+ private void validateOptionalEnum(String name, String value, Set<String> validValues) {
+ if (value != null && !validValues.contains(value)) {
+ throw new AwsException("InvalidParameterValue",
+ name + " must be one of " + String.join(", ", validValues) + ".", 400);
+ }
+ }
+
+ private void validateOptionalLength(String name, String value, int minimum, int maximum) {
+ if (value != null && (value.length() < minimum || value.length() > maximum)) {
+ throw new AwsException("InvalidParameterValue",
+ name + " must be between " + minimum + " and " + maximum + " characters.",
+ 400);
+ }
+ }
+
+ private DbProxyTargetGroup getDefaultProxyTargetGroup(String dbProxyName, String targetGroupName) {
+ return getDefaultProxyTargetGroup(
+ dbProxyName, targetGroupName, regionResolver.getDefaultRegion());
+ }
+
+ private DbProxyTargetGroup getDefaultProxyTargetGroup(
+ String dbProxyName, String targetGroupName, String region) {
+ String effectiveName = targetGroupName == null || targetGroupName.isBlank()
+ ? "default" : targetGroupName;
+ if (!"default".equals(effectiveName)) {
+ throw new AwsException("DBProxyTargetGroupNotFoundFault",
+ "DB proxy target group " + effectiveName + " not found for proxy " + dbProxyName + ".", 404);
+ }
+ return findProxyTargetGroup(dbProxyName, effectiveRegion(region)).orElseThrow(() ->
+ new AwsException("DBProxyTargetGroupNotFoundFault",
+ "DB proxy target group default not found for proxy " + dbProxyName + ".", 404));
+ }
+
+ private synchronized Optional<DbProxy> findDbProxy(String dbProxyName, String region) {
+ String key = dbProxyKey(region, dbProxyName);
+ String accountId = currentAccountId();
+ Optional<DbProxy> proxy;
+ Optional<DbProxy> legacy;
+ if (proxies instanceof AccountAwareStorageBackend<DbProxy> aware) {
+ proxy = aware.getForAccount(accountId, key);
+ legacy = aware.getForAccount(accountId, dbProxyName);
+ } else {
+ proxy = proxies.get(key);
+ legacy = proxies.get(dbProxyName);
+ }
+ if (proxy.isPresent()) {
+ if (!proxyBelongsTo(proxy.get(), accountId, region)
+ || !Objects.equals(dbProxyName, proxy.get().getDbProxyName())) {
+ return Optional.empty();
+ }
+ if (legacy.filter(candidate -> sameProxyScope(candidate, proxy.get())).isPresent()) {
+ deleteProxyKey(accountId, dbProxyName);
+ }
+ return proxy;
+ }
+ if (legacy.filter(candidate -> proxyBelongsTo(candidate, accountId, region)
+ && Objects.equals(dbProxyName, candidate.getDbProxyName())).isPresent()) {
+ putProxyForAccount(accountId, key, legacy.get());
+ deleteProxyKey(accountId, dbProxyName);
+ return legacy;
+ }
+ return Optional.empty();
+ }
+
+ private synchronized Optional<DbProxyTargetGroup> findProxyTargetGroup(
+ String dbProxyName, String region) {
+ String key = dbProxyKey(region, dbProxyName);
+ String accountId = currentAccountId();
+ Optional<DbProxy> ownerProxy = findDbProxy(dbProxyName, region);
+ java.util.function.Predicate<DbProxyTargetGroup> owner = candidate ->
+ ownerProxy.isPresent()
+ && targetGroupBelongsTo(candidate, accountId, region)
+ && targetGroupMatchesProxy(candidate, ownerProxy.get());
+ Optional<DbProxyTargetGroup> targetGroup;
+ Optional<DbProxyTargetGroup> legacy;
+ if (proxyTargetGroups instanceof AccountAwareStorageBackend<DbProxyTargetGroup> aware) {
+ targetGroup = aware.getForAccount(accountId, key);
+ legacy = aware.getForAccount(accountId, dbProxyName);
+ } else {
+ targetGroup = proxyTargetGroups.get(key);
+ legacy = proxyTargetGroups.get(dbProxyName);
+ }
+ if (targetGroup.isPresent()) {
+ if (!owner.test(targetGroup.get())) {
+ return Optional.empty();
+ }
+ if (legacy.filter(candidate -> sameTargetGroupScope(
+ candidate, targetGroup.get())).isPresent()) {
+ deleteTargetGroupKey(accountId, dbProxyName);
+ }
+ return targetGroup;
+ }
+ if (legacy.filter(owner).isPresent()) {
+ putTargetGroupForAccount(accountId, key, legacy.get());
+ deleteTargetGroupKey(accountId, dbProxyName);
+ return legacy;
+ }
+ return Optional.empty();
+ }
+
+ private String currentAccountId() {
+ String accountId = regionResolver.getAccountId();
+ return accountId == null || accountId.isBlank() ? defaultAccountId() : accountId;
+ }
+
+ private boolean proxyBelongsTo(DbProxy proxy, String accountId, String region) {
+ if (proxy == null || proxy.getDbProxyResourceId() == null
+ || proxy.getDbProxyResourceId().isBlank()) {
+ return false;
+ }
+ return hasRdsResourceIdentity(
+ proxy.getDbProxyArn(), accountId, region, "db-proxy",
+ proxy.getDbProxyResourceId());
+ }
+
+ private boolean targetGroupBelongsTo(
+ DbProxyTargetGroup targetGroup, String accountId, String region) {
+ if (targetGroup == null || targetGroup.getTargetGroupArn() == null) {
+ return false;
+ }
+ try {
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(targetGroup.getTargetGroupArn());
+ return "aws".equals(arn.partition())
+ && "rds".equals(arn.service())
+ && Objects.equals(accountId, arn.accountId())
+ && Objects.equals(region, arn.region())
+ && arn.resource().matches("target-group:prx-tg-[A-Za-z0-9-]+");
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ }
+
+ private void putProxyForAccount(String accountId, String key, DbProxy proxy) {
+ if (proxies instanceof AccountAwareStorageBackend<DbProxy> aware) {
+ aware.putForAccount(accountId, key, proxy);
+ } else {
+ proxies.put(key, proxy);
+ }
+ }
+
+ private Optional<DbProxy> getProxyForAccount(String accountId, String key) {
+ if (proxies instanceof AccountAwareStorageBackend<DbProxy> aware) {
+ return aware.getForAccount(accountId, key);
+ }
+ return proxies.get(key);
+ }
+
+ private void deleteProxyKey(String accountId, String key) {
+ if (proxies instanceof AccountAwareStorageBackend<DbProxy> aware) {
+ aware.deleteForAccount(accountId, key);
+ } else {
+ proxies.delete(key);
+ }
+ }
+
+ private void putTargetGroupForAccount(
+ String accountId, String key, DbProxyTargetGroup targetGroup) {
+ if (proxyTargetGroups instanceof AccountAwareStorageBackend<DbProxyTargetGroup> aware) {
+ aware.putForAccount(accountId, key, targetGroup);
+ } else {
+ proxyTargetGroups.put(key, targetGroup);
+ }
+ }
+
+ private Optional<DbProxyTargetGroup> getTargetGroupForAccount(
+ String accountId, String key) {
+ if (proxyTargetGroups instanceof AccountAwareStorageBackend<DbProxyTargetGroup> aware) {
+ return aware.getForAccount(accountId, key);
+ }
+ return proxyTargetGroups.get(key);
+ }
+
+ private void deleteTargetGroupKey(String accountId, String key) {
+ if (proxyTargetGroups instanceof AccountAwareStorageBackend<DbProxyTargetGroup> aware) {
+ aware.deleteForAccount(accountId, key);
+ } else {
+ proxyTargetGroups.delete(key);
+ }
+ }
+
+ private void attemptRollback(RuntimeException failure, Runnable rollback) {
+ try {
+ rollback.run();
+ } catch (RuntimeException rollbackFailure) {
+ if (rollbackFailure != failure) {
+ failure.addSuppressed(rollbackFailure);
+ }
+ }
+ }
+
+ private void restartDbProxyRelayAfterFailure(
+ DbProxy proxy, DbProxyTargetGroup targetGroup, RuntimeException failure) {
+ if (config.services().rds().mock()
+ || targetGroup == null || targetGroup.getTargets().isEmpty()
+ || !targetGroupMatchesProxy(targetGroup, proxy)
+ || !"available".equals(proxy.getStatus())
+ || "IAM_AUTH".equals(proxy.getDefaultAuthScheme())) {
+ return;
+ }
+ attemptRollback(failure,
+ () -> startDbProxyRelay(proxy, targetGroup.getTargets().getFirst()));
+ }
+
+ private void persistTargetGroupAfterRelayStop(
+ DbProxy proxy, DbProxyTargetGroup original,
+ DbProxyTargetGroup updated, String region) {
+ String accountId = accountIdFromArn(proxy.getDbProxyArn());
+ String proxyKey = dbProxyKey(region, proxy.getDbProxyName());
+ boolean realMode = !config.services().rds().mock();
+ DbProxyTarget desiredTarget = updated.getTargets().isEmpty()
+ ? null : updated.getTargets().getFirst();
+ boolean relayTransition = realMode
+ && (!original.getTargets().isEmpty() || desiredTarget != null);
+ try {
+ if (relayTransition && !original.getTargets().isEmpty()) {
+ proxyManager.stopProxy(dbProxyRelayKey(proxy));
+ }
+ putTargetGroupForAccount(accountId, proxyKey, updated);
+ if (relayTransition && desiredTarget != null) {
+ startDbProxyRelay(proxy, desiredTarget);
+ }
+ } catch (RuntimeException transitionFailure) {
+ if (relayTransition) {
+ attemptRollback(transitionFailure,
+ () -> proxyManager.stopProxy(dbProxyRelayKey(proxy)));
+ }
+ attemptRollback(transitionFailure,
+ () -> putTargetGroupForAccount(accountId, proxyKey, original));
+ restartDbProxyRelayAfterFailure(proxy, original, transitionFailure);
+ throw transitionFailure;
+ }
+ }
+
+ private String dbProxyKey(String region, String dbProxyName) {
+ return effectiveRegion(region) + "::" + dbProxyName;
+ }
+
+ private String regionFromArn(String arn) {
+ return AwsArnUtils.regionOrDefault(arn, regionResolver.getDefaultRegion());
+ }
+
+ private void validateProxyTargetScope(
+ String targetArn, String proxyAccountId, String proxyRegion,
+ String resourceType, String resourceId) {
+ AwsArnUtils.Arn parsed;
+ try {
+ parsed = AwsArnUtils.parse(targetArn);
+ } catch (IllegalArgumentException e) {
+ throw new AwsException("InvalidParameterValue",
+ resourceType + " " + resourceId + " has an invalid ARN.", 400);
+ }
+ if (!"rds".equals(parsed.service())
+ || !Objects.equals(proxyAccountId, parsed.accountId())
+ || !Objects.equals(proxyRegion, parsed.region())) {
+ throw new AwsException("InvalidParameterValue",
+ resourceType + " " + resourceId
+ + " is not in the proxy account and region.", 400);
+ }
+ }
+
+ private void validateResourceRegion(String arn, String expectedRegion, String resourceType) {
+ try {
+ AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
+ if (!"rds".equals(parsed.service())
+ || !expectedRegion.equals(parsed.region())
+ || !Objects.equals(currentAccountId(), parsed.accountId())) {
+ throw new AwsException("InvalidParameterValue",
+ resourceType + " is not in the current account and region "
+ + expectedRegion + ".", 400);
+ }
+ } catch (IllegalArgumentException e) {
+ throw new AwsException("InvalidParameterValue",
+ "Invalid " + resourceType + " ARN: " + arn, 400);
+ }
+ }
+
+ private void validateTargetEngineFamily(DbProxy proxy, DatabaseEngine targetEngine) {
+ boolean compatible = switch (proxy.getEngineFamily()) {
+ case "POSTGRESQL" -> targetEngine == DatabaseEngine.POSTGRES;
+ case "MYSQL" -> targetEngine == DatabaseEngine.MYSQL || targetEngine == DatabaseEngine.MARIADB;
+ default -> false;
+ };
+ if (!compatible) {
+ throw new AwsException("InvalidParameterValue",
+ "Target engine " + targetEngine + " is incompatible with proxy engine family "
+ + proxy.getEngineFamily() + ".", 400);
+ }
+ }
+
+ private void validateProxyTargetSelection(
+ DbProxy proxy, List<String> clusterIds, List<String> instanceIds, String region) {
+ if (clusterIds.size() + instanceIds.size() > 1) {
+ throw new AwsException("InvalidParameterCombination",
+ "Floci currently supports at most one DB cluster or DB instance per proxy target group.",
+ 400);
+ }
+ if (!clusterIds.isEmpty()) {
+ String clusterId = clusterIds.get(0);
+ String proxyAccountId = accountIdFromArn(proxy.getDbProxyArn());
+ DbCluster cluster = Optional.ofNullable(findClusterForScope(
+ proxyAccountId, region, clusterId))
+ .orElseThrow(() ->
+ new AwsException("DBClusterNotFoundFault",
+ "DB cluster " + clusterId + " not found.", 404));
+ if (cluster.getStatus() != DbInstanceStatus.AVAILABLE) {
+ throw new AwsException("InvalidDBClusterStateFault",
+ "DB cluster " + clusterId + " is not available.", 400);
+ }
+ validateProxyTargetScope(cluster.getDbClusterArn(), proxyAccountId, region,
+ "DB cluster", clusterId);
+ validateTargetEngineFamily(proxy, cluster.getEngine());
+ } else if (!instanceIds.isEmpty()) {
+ String instanceId = instanceIds.get(0);
+ String proxyAccountId = accountIdFromArn(proxy.getDbProxyArn());
+ DbInstance instance = Optional.ofNullable(findInstanceForScope(
+ proxyAccountId, region, instanceId))
+ .orElseThrow(() ->
+ new AwsException("DBInstanceNotFoundFault",
+ "DB instance " + instanceId + " not found.", 404));
+ if (instance.getStatus() != DbInstanceStatus.AVAILABLE) {
+ throw new AwsException("InvalidDBInstanceState",
+ "DB instance " + instanceId + " is not available.", 400);
+ }
+ validateProxyTargetScope(instance.getDbInstanceArn(), proxyAccountId, region,
+ "DB instance", instanceId);
+ validateTargetEngineFamily(proxy, instance.getEngine());
+ }
+ }
+
+ private void validatePercent(String name, int value, int minimum, int maximum) {
+ if (value < minimum || value > maximum) {
+ throw new AwsException("InvalidParameterValue",
+ name + " must be between " + minimum + " and " + maximum + ".", 400);
+ }
+ }
+
+ private void validatePoolConfiguration(Integer maxConnectionsPercent,
+ Integer maxIdleConnectionsPercent) {
+ validatePoolConfiguration(null, maxConnectionsPercent, maxIdleConnectionsPercent,
+ null, null);
+ }
+
+ private void validatePoolConfiguration(
+ DbProxy proxy, Integer maxConnectionsPercent, Integer maxIdleConnectionsPercent,
+ Integer connectionBorrowTimeout, List<String> sessionPinningFilters) {
+ if (maxConnectionsPercent != null) {
+ validatePercent("MaxConnectionsPercent", maxConnectionsPercent, 1, 100);
+ }
+ if (maxIdleConnectionsPercent != null) {
+ if (maxConnectionsPercent == null) {
+ throw new AwsException("InvalidParameterValue",
+ "MaxConnectionsPercent is required when MaxIdleConnectionsPercent is specified.", 400);
+ }
+ validatePercent("MaxIdleConnectionsPercent", maxIdleConnectionsPercent,
+ 0, maxConnectionsPercent);
+ }
+ if (connectionBorrowTimeout != null) {
+ validatePercent("ConnectionBorrowTimeout", connectionBorrowTimeout, 0, 300);
+ }
+ if (sessionPinningFilters != null && !sessionPinningFilters.isEmpty()) {
+ if (proxy == null || !"MYSQL".equals(proxy.getEngineFamily())) {
+ throw new AwsException("InvalidParameterValue",
+ "SessionPinningFilters are supported only for MYSQL DB proxies.", 400);
+ }
+ if (sessionPinningFilters.stream()
+ .anyMatch(filter -> !"EXCLUDE_VARIABLE_SETS".equals(filter))) {
+ throw new AwsException("InvalidParameterValue",
+ "SessionPinningFilters supports only EXCLUDE_VARIABLE_SETS.", 400);
+ }
+ }
+ }
+
+ private boolean sameProxyTargetGroupConfiguration(
+ DbProxyTargetGroup left, DbProxyTargetGroup right) {
+ return left.getMaxConnectionsPercent() == right.getMaxConnectionsPercent()
+ && left.getMaxIdleConnectionsPercent() == right.getMaxIdleConnectionsPercent()
+ && left.getConnectionBorrowTimeout() == right.getConnectionBorrowTimeout()
+ && Objects.equals(left.getInitQuery(), right.getInitQuery())
+ && Objects.equals(left.getSessionPinningFilters(), right.getSessionPinningFilters());
+ }
+
+ private boolean isRegisteredProxyTarget(String type, String resourceId, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ return proxyTargetGroups.scan(k -> true).stream()
+ .filter(targetGroup -> targetGroupBelongsTo(
+ targetGroup, currentAccountId(), effectiveRegion))
+ .filter(targetGroup -> findDbProxy(
+ targetGroup.getDbProxyName(), effectiveRegion)
+ .filter(proxy -> targetGroupMatchesProxy(targetGroup, proxy))
+ .isPresent())
+ .flatMap(targetGroup -> targetGroup.getTargets().stream())
+ .anyMatch(target -> type.equals(target.getType())
+ && resourceId.equals(target.getRdsResourceId()));
+ }
+
+ private DbProxy copyDbProxy(DbProxy source) {
+ DbProxy copy = new DbProxy();
+ copy.setDbProxyName(source.getDbProxyName());
+ copy.setDbProxyArn(source.getDbProxyArn());
+ copy.setDbProxyResourceId(source.getDbProxyResourceId());
+ copy.setEndpointHost(source.getEndpointHost());
+ copy.setProxyPort(source.getProxyPort());
+ copy.setEngineFamily(source.getEngineFamily());
+ copy.setRequireTls(source.isRequireTls());
+ copy.setIamAuth(source.isIamAuth());
+ copy.setDefaultAuthScheme(source.getDefaultAuthScheme() != null
+ ? source.getDefaultAuthScheme() : "NONE");
+ copy.setRoleArn(source.getRoleArn());
+ copy.setIdleClientTimeout(source.getIdleClientTimeout());
+ copy.setDebugLogging(source.isDebugLogging());
+ copy.setStatus(source.getStatus());
+ copy.setCreatedAt(source.getCreatedAt());
+ copy.setUpdatedAt(source.getUpdatedAt());
+ copy.setVpcId(source.getVpcId());
+ copy.setEndpointNetworkType(source.getEndpointNetworkType() != null
+ ? source.getEndpointNetworkType() : "IPV4");
+ copy.setTargetConnectionNetworkType(source.getTargetConnectionNetworkType() != null
+ ? source.getTargetConnectionNetworkType() : "IPV4");
+ copy.setVpcSubnetIds(source.getVpcSubnetIds());
+ copy.setVpcSecurityGroupIds(source.getVpcSecurityGroupIds());
+ copy.setAuth(source.getAuth().stream().map(this::copyDbProxyAuth).toList());
+ copy.setTags(source.getTags());
+ return copy;
+ }
+
+ private DbProxyAuth copyDbProxyAuth(DbProxyAuth source) {
+ DbProxyAuth copy = new DbProxyAuth(
+ source.getAuthScheme(), source.getSecretArn(), source.getIamAuth(),
+ source.getClientPasswordAuthType(), source.getDescription());
+ copy.setUserName(source.getUserName());
+ return copy;
+ }
+
+ private boolean sameDbProxyState(DbProxy left, DbProxy right) {
+ return left.isRequireTls() == right.isRequireTls()
+ && left.isIamAuth() == right.isIamAuth()
+ && left.getIdleClientTimeout() == right.getIdleClientTimeout()
+ && left.isDebugLogging() == right.isDebugLogging()
+ && Objects.equals(normalizeDefaultAuthScheme(left.getDefaultAuthScheme()),
+ normalizeDefaultAuthScheme(right.getDefaultAuthScheme()))
+ && Objects.equals(left.getRoleArn(), right.getRoleArn())
+ && Objects.equals(left.getVpcSecurityGroupIds(), right.getVpcSecurityGroupIds())
+ && sameDbProxyAuth(left.getAuth(), right.getAuth())
+ && Objects.equals(left.getTags(), right.getTags());
+ }
+
+ private boolean sameDbProxyAuth(List<DbProxyAuth> left, List<DbProxyAuth> right) {
+ if (left.size() != right.size()) {
+ return false;
+ }
+ for (int index = 0; index < left.size(); index++) {
+ DbProxyAuth a = left.get(index);
+ DbProxyAuth b = right.get(index);
+ if (!Objects.equals(a.getAuthScheme(), b.getAuthScheme())
+ || !Objects.equals(a.getSecretArn(), b.getSecretArn())
+ || !Objects.equals(a.getIamAuth(), b.getIamAuth())
+ || !Objects.equals(a.getClientPasswordAuthType(), b.getClientPasswordAuthType())
+ || !Objects.equals(a.getDescription(), b.getDescription())
+ || !Objects.equals(a.getUserName(), b.getUserName())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private void startDbProxyRelay(DbProxy proxy, DbProxyTarget target) {
+ if ("IAM_AUTH".equals(proxy.getDefaultAuthScheme())) {
+ throw new AwsException("InvalidDBProxyStateFault",
+ "DefaultAuthScheme IAM_AUTH is available for control-plane emulation only; "
+ + "the real-mode relay does not support end-to-end IAM authentication.",
+ 400);
+ }
+ String accountId = accountIdFromArn(proxy.getDbProxyArn());
+ String proxyRegion = regionFromArn(proxy.getDbProxyArn());
+ if (!"TRACKED_CLUSTER".equals(target.getType())
+ && !"RDS_INSTANCE".equals(target.getType())) {
+ throw new AwsException("InvalidDBProxyStateFault",
+ "Unsupported persisted DB proxy target type " + target.getType() + ".", 400);
+ }
+ boolean clusterTarget = "TRACKED_CLUSTER".equals(target.getType());
+ DatabaseEngine engine;
+ String backendHost;
+ int backendPort;
+ String masterUser;
+ String masterPassword;
+ String dbName;
+ if (clusterTarget) {
+ DbCluster cluster = findClusterForScope(
+ accountId, proxyRegion, target.getRdsResourceId());
+ if (cluster == null) {
+ throw new AwsException("DBClusterNotFoundFault",
+ "DB cluster " + target.getRdsResourceId() + " not found.", 404);
+ }
+ validateProxyTargetScope(cluster.getDbClusterArn(), accountId, proxyRegion,
+ "DB cluster", target.getRdsResourceId());
+ engine = cluster.getEngine();
+ backendHost = cluster.getContainerHost();
+ backendPort = cluster.getContainerPort();
+ masterUser = cluster.getMasterUsername();
+ masterPassword = cluster.getMasterPassword();
+ dbName = cluster.getDatabaseName();
+ } else {
+ DbInstance instance = findInstanceForScope(
+ accountId, proxyRegion, target.getRdsResourceId());
+ if (instance == null) {
+ throw new AwsException("DBInstanceNotFoundFault",
+ "DB instance " + target.getRdsResourceId() + " not found.", 404);
+ }
+ validateProxyTargetScope(instance.getDbInstanceArn(), accountId, proxyRegion,
+ "DB instance", target.getRdsResourceId());
+ engine = instance.getEngine();
+ backendHost = instance.getContainerHost();
+ backendPort = instance.getContainerPort();
+ masterUser = instance.getMasterUsername();
+ masterPassword = instance.getMasterPassword();
+ dbName = instance.getDbName();
+ }
+ if (backendHost == null || backendPort <= 0) {
+ throw new AwsException("InvalidDBProxyStateFault",
+ "Target backend for proxy " + proxy.getDbProxyName() + " is not available.", 400);
+ }
+ validateTargetEngineFamily(proxy, engine);
+ String effectiveMasterUser = masterUser != null ? masterUser : "root";
+ String targetId = target.getRdsResourceId();
+ proxyManager.startProxy(dbProxyRelayKey(proxy), engine, proxy.isIamAuth(), proxy.getProxyPort(),
+ backendHost, backendPort, effectiveMasterUser, masterPassword, dbName,
+ (user, password) -> clusterTarget
+ ? validateDbClusterPasswordForScope(
+ accountId, proxyRegion, targetId, user, password)
+ : validateDbPasswordForScope(
+ accountId, proxyRegion, targetId, user, password));
+ }
+
+ private DbProxyTargetGroup copyProxyTargetGroup(DbProxyTargetGroup source) {
+ DbProxyTargetGroup copy = new DbProxyTargetGroup();
+ copy.setDbProxyName(source.getDbProxyName());
+ copy.setTargetGroupName(source.getTargetGroupName());
+ copy.setTargetGroupArn(source.getTargetGroupArn());
+ copy.setStatus(source.getStatus());
+ copy.setDefaultTargetGroup(source.isDefaultTargetGroup());
+ copy.setCreatedAt(source.getCreatedAt());
+ copy.setUpdatedAt(source.getUpdatedAt());
+ copy.setMaxConnectionsPercent(source.getMaxConnectionsPercent());
+ copy.setMaxIdleConnectionsPercent(source.getMaxIdleConnectionsPercent());
+ copy.setConnectionBorrowTimeout(source.getConnectionBorrowTimeout());
+ copy.setInitQuery(source.getInitQuery());
+ copy.setSessionPinningFilters(source.getSessionPinningFilters());
+ copy.setTargets(source.getTargets());
+ return copy;
+ }
+
+ private String randomResourceSuffix() {
+ return java.util.UUID.randomUUID().toString().replace("-", "").substring(0, 17);
+ }
+
+ /** The engine's default listener port — an RDS Proxy endpoint is a bare host reached on this port. */
+ private int defaultPortForEngineFamily(String engineFamily) {
+ if (engineFamily == null) {
+ return 5432;
+ }
+ return switch (engineFamily.toUpperCase()) {
+ case "MYSQL" -> 3306;
+ case "SQLSERVER" -> 1433;
+ default -> 5432; // POSTGRESQL
+ };
+ }
+
+ private void restoreClusters() {
+ for (DbCluster cluster : allClusters()) {
+ if (cluster.getStatus() == DbInstanceStatus.DELETING) {
+ continue;
+ }
+ String accountId = accountIdFromArn(cluster.getDbClusterArn());
+ String clusterRegion = regionFromArn(cluster.getDbClusterArn());
+ String storageResourceId = resolvedClusterStorageResourceId(cluster);
+ String dockerVolumeName = resolvedClusterDockerVolumeName(cluster);
+ cluster.setContainerStorageResourceId(storageResourceId);
+ cluster.setDockerVolumeName(dockerVolumeName);
+ String persistedContainerId = cluster.getContainerId();
+ RdsContainerHandle restoredHandle = null;
+ int proxyPort = 0;
+ boolean portReserved = false;
+ try {
+ proxyPort = reserveOrAllocateProxyPort(cluster.getProxyPort());
+ portReserved = true;
+ cluster.setProxyPort(proxyPort);
+ if (config.services().rds().mock()) {
+ cluster.setEndpoint(new DbEndpoint("localhost", proxyPort));
+ cluster.setReaderEndpoint(new DbEndpoint("localhost", proxyPort));
+ cluster.setStatus(DbInstanceStatus.AVAILABLE);
+ putClusterForScope(accountId, clusterRegion,
+ cluster.getDbClusterIdentifier(), cluster);
+ continue;
+ }
+ DbEndpoint endpoint = proxyEndpoint(proxyPort);
+ cluster.setEndpoint(endpoint);
+ cluster.setReaderEndpoint(endpoint);
+ String image = imageForEngine(cluster.getEngine(), cluster.getEngineVersion());
+ restoredHandle = containerManager.start(
+ cluster.getDbClusterArn(), cluster.getDbClusterIdentifier(),
+ storageResourceId, dockerVolumeName, cluster.getEngine(), image,
+ cluster.getMasterUsername(), cluster.getMasterPassword(), cluster.getDatabaseName());
+ cluster.setContainerId(restoredHandle.getContainerId());
+ cluster.setContainerHost(restoredHandle.getHost());
+ cluster.setContainerPort(restoredHandle.getPort());
+
+ String effectiveMasterUser = cluster.getMasterUsername() != null
+ ? cluster.getMasterUsername() : "root";
+ proxyManager.startProxy(rdsResourceRelayKey(
+ cluster.getDbClusterArn(), cluster.getDbClusterIdentifier()),
+ cluster.getEngine(),
+ cluster.isIamDatabaseAuthenticationEnabled(), proxyPort,
+ restoredHandle.getHost(), restoredHandle.getPort(), effectiveMasterUser,
+ cluster.getMasterPassword(), cluster.getDatabaseName(),
+ (user, pw) -> validateDbClusterPasswordForScope(
+ accountId, clusterRegion,
+ cluster.getDbClusterIdentifier(), user, pw));
+ cluster.setStatus(DbInstanceStatus.AVAILABLE);
+ putClusterForScope(accountId, clusterRegion,
+ cluster.getDbClusterIdentifier(), cluster);
+ } catch (Exception e) {
+ if (!config.services().rds().mock()) {
+ try {
+ proxyManager.stopProxy(rdsResourceRelayKey(
+ cluster.getDbClusterArn(), cluster.getDbClusterIdentifier()));
+ } catch (RuntimeException stopFailure) {
+ e.addSuppressed(stopFailure);
+ }
+ }
+ RdsContainerHandle cleanupHandle = restoredHandle != null
+ ? restoredHandle
+ : containerManager.getActiveHandle(cluster.getDbClusterArn());
+ boolean containerCleaned = stopRestoredContainer(cleanupHandle, e, "cluster",
+ cluster.getDbClusterIdentifier());
+ if (portReserved) {
+ releaseProxyPort(proxyPort);
+ }
+ cluster.setProxyPort(0);
+ cluster.setStatus(DbInstanceStatus.FAILED);
+ cluster.setEndpoint(null);
+ cluster.setReaderEndpoint(null);
+ String retainedContainerId = !containerCleaned && cleanupHandle != null
+ ? cleanupHandle.getContainerId()
+ : restoredHandle == null ? persistedContainerId : null;
+ cluster.setContainerId(retainedContainerId);
+ cluster.setContainerHost(null);
+ cluster.setContainerPort(0);
+ try {
+ putClusterForScope(accountId, clusterRegion,
+ cluster.getDbClusterIdentifier(), cluster);
+ } catch (RuntimeException persistFailure) {
+ e.addSuppressed(persistFailure);
+ }
+ LOG.warnv(e, "Failed to restore RDS cluster {0}", cluster.getDbClusterIdentifier());
}
}
}
@@ -1310,24 +3179,47 @@ public class RdsService implements Resettable {
if (instance.getStatus() == DbInstanceStatus.DELETING) {
continue;
}
- if (config.services().rds().mock()) {
- int mockPort = reserveOrAllocateProxyPort(instance.getProxyPort());
- instance.setProxyPort(mockPort);
- instance.setEndpoint(new DbEndpoint("localhost", mockPort));
- instance.setStatus(DbInstanceStatus.AVAILABLE);
- continue;
+ String accountId = accountIdFromArn(instance.getDbInstanceArn());
+ String instanceRegion = regionFromArn(instance.getDbInstanceArn());
+ String clusterId = instance.getDbClusterIdentifier();
+ if (clusterId != null && !clusterId.isBlank()) {
+ DbCluster owningCluster = findClusterForScope(accountId, instanceRegion, clusterId);
+ if (owningCluster != null) {
+ instance.setContainerStorageResourceId(
+ resolvedClusterStorageResourceId(owningCluster));
+ instance.setDockerVolumeName(resolvedClusterDockerVolumeName(owningCluster));
+ }
+ } else {
+ instance.setContainerStorageResourceId(
+ resolvedInstanceStorageResourceId(instance));
+ instance.setDockerVolumeName(resolvedInstanceDockerVolumeName(instance));
}
- int proxyPort = reserveOrAllocateProxyPort(instance.getProxyPort());
- instance.setProxyPort(proxyPort);
- instance.setEndpoint(proxyEndpoint(proxyPort));
+ String persistedContainerId = instance.getContainerId();
+ RdsContainerHandle restoredHandle = null;
+ int proxyPort = 0;
+ boolean portReserved = false;
try {
+ proxyPort = reserveOrAllocateProxyPort(instance.getProxyPort());
+ portReserved = true;
+ instance.setProxyPort(proxyPort);
+ if (config.services().rds().mock()) {
+ instance.setEndpoint(new DbEndpoint("localhost", proxyPort));
+ instance.setStatus(DbInstanceStatus.AVAILABLE);
+ putInstanceForScope(accountId, instanceRegion,
+ instance.getDbInstanceIdentifier(), instance);
+ continue;
+ }
+ instance.setEndpoint(proxyEndpoint(proxyPort));
String backendHost;
int backendPort;
- String clusterId = instance.getDbClusterIdentifier();
if (clusterId != null && !clusterId.isBlank()) {
- DbCluster cluster = clusters.get(clusterId).orElseThrow(() ->
- new AwsException("DBClusterNotFoundFault",
- "DB cluster " + clusterId + " not found.", 404));
+ DbCluster cluster = findClusterForScope(
+ accountId,
+ instanceRegion, clusterId);
+ if (cluster == null) {
+ throw new AwsException("DBClusterNotFoundFault",
+ "DB cluster " + clusterId + " not found.", 404);
+ }
backendHost = cluster.getContainerHost();
backendPort = cluster.getContainerPort();
if (backendHost == null || backendPort <= 0) {
@@ -1337,53 +3229,883 @@ public class RdsService implements Resettable {
instance.setContainerId(cluster.getContainerId());
instance.setContainerHost(cluster.getContainerHost());
instance.setContainerPort(cluster.getContainerPort());
- if (instance.getDockerVolumeName() == null) {
- instance.setDockerVolumeName(cluster.getDockerVolumeName() != null
- ? cluster.getDockerVolumeName()
- : volumeName(cluster.getVolumeId(), cluster.getDbClusterIdentifier()));
- }
} else {
- if (instance.getDockerVolumeName() == null) {
- instance.setDockerVolumeName(volumeName(instance.getVolumeId(), instance.getDbInstanceIdentifier()));
- }
String image = imageForEngine(instance.getEngine(), instance.getEngineVersion());
- RdsContainerHandle handle = containerManager.start(instance.getDbInstanceIdentifier(),
- instance.getVolumeId(), instance.getEngine(), image,
+ restoredHandle = containerManager.start(
+ instance.getDbInstanceArn(), instance.getDbInstanceIdentifier(),
+ instance.getContainerStorageResourceId(),
+ instance.getDockerVolumeName(), instance.getEngine(), image,
instance.getMasterUsername(), instance.getMasterPassword(), instance.getDbName());
- backendHost = handle.getHost();
- backendPort = handle.getPort();
- instance.setContainerId(handle.getContainerId());
- instance.setContainerHost(handle.getHost());
- instance.setContainerPort(handle.getPort());
+ backendHost = restoredHandle.getHost();
+ backendPort = restoredHandle.getPort();
+ instance.setContainerId(restoredHandle.getContainerId());
+ instance.setContainerHost(restoredHandle.getHost());
+ instance.setContainerPort(restoredHandle.getPort());
}
String effectiveMasterUser = instance.getMasterUsername() != null
? instance.getMasterUsername() : "root";
- proxyManager.startProxy(instance.getDbInstanceIdentifier(), instance.getEngine(),
+ proxyManager.startProxy(rdsResourceRelayKey(
+ instance.getDbInstanceArn(), instance.getDbInstanceIdentifier()),
+ instance.getEngine(),
instance.isIamDatabaseAuthenticationEnabled(), proxyPort,
backendHost, backendPort, effectiveMasterUser,
instance.getMasterPassword(), instance.getDbName(),
- (user, pw) -> validateDbPassword(instance.getDbInstanceIdentifier(), user, pw));
+ (user, pw) -> validateDbPasswordForScope(
+ accountId, instanceRegion,
+ instance.getDbInstanceIdentifier(), user, pw));
instance.setStatus(DbInstanceStatus.AVAILABLE);
+ putInstanceForScope(accountId, instanceRegion,
+ instance.getDbInstanceIdentifier(), instance);
} catch (Exception e) {
- releaseProxyPort(proxyPort);
+ if (!config.services().rds().mock()) {
+ try {
+ proxyManager.stopProxy(rdsResourceRelayKey(
+ instance.getDbInstanceArn(), instance.getDbInstanceIdentifier()));
+ } catch (RuntimeException stopFailure) {
+ e.addSuppressed(stopFailure);
+ }
+ }
+ RdsContainerHandle cleanupHandle = restoredHandle != null
+ ? restoredHandle
+ : containerManager.getActiveHandle(instance.getDbInstanceArn());
+ boolean containerCleaned = stopRestoredContainer(cleanupHandle, e, "instance",
+ instance.getDbInstanceIdentifier());
+ if (portReserved) {
+ releaseProxyPort(proxyPort);
+ }
+ instance.setProxyPort(0);
+ instance.setStatus(DbInstanceStatus.FAILED);
+ instance.setEndpoint(null);
+ String retainedContainerId = !containerCleaned && cleanupHandle != null
+ ? cleanupHandle.getContainerId()
+ : restoredHandle == null ? persistedContainerId : null;
+ instance.setContainerId(retainedContainerId);
+ instance.setContainerHost(null);
+ instance.setContainerPort(0);
+ try {
+ putInstanceForScope(accountId, instanceRegion,
+ instance.getDbInstanceIdentifier(), instance);
+ } catch (RuntimeException persistFailure) {
+ e.addSuppressed(persistFailure);
+ }
LOG.warnv(e, "Failed to restore RDS instance {0}", instance.getDbInstanceIdentifier());
}
}
}
- private Collection<DbCluster> allClusters() {
+ private boolean stopRestoredContainer(
+ RdsContainerHandle handle, Exception restoreFailure,
+ String resourceType, String resourceId) {
+ if (handle == null) {
+ return true;
+ }
+ try {
+ containerManager.stop(handle);
+ return true;
+ } catch (RuntimeException | Error cleanupFailure) {
+ restoreFailure.addSuppressed(cleanupFailure);
+ LOG.errorv(cleanupFailure,
+ "Failed to clean up container after restoring RDS {0} {1}",
+ resourceType, resourceId);
+ return false;
+ }
+ }
+
+ /** Re-arms each persisted DB proxy's relay after a restart (clusters/instances restored first). */
+ private void restoreProxies() {
+ for (DbProxy proxy : allProxies()) {
+ if (proxy.getDefaultAuthScheme() == null || proxy.getDefaultAuthScheme().isBlank()) {
+ proxy.setDefaultAuthScheme("NONE");
+ }
+ if (proxy.getEndpointNetworkType() == null
+ || proxy.getEndpointNetworkType().isBlank()) {
+ proxy.setEndpointNetworkType("IPV4");
+ }
+ if (proxy.getTargetConnectionNetworkType() == null
+ || proxy.getTargetConnectionNetworkType().isBlank()) {
+ proxy.setTargetConnectionNetworkType("IPV4");
+ }
+ if (proxy.getCreatedAt() == null && proxy.getUpdatedAt() != null) {
+ proxy.setCreatedAt(proxy.getUpdatedAt());
+ }
+ if (proxy.getUpdatedAt() == null && proxy.getCreatedAt() != null) {
+ proxy.setUpdatedAt(proxy.getCreatedAt());
+ }
+ String proxyAccountId = accountIdFromArn(proxy.getDbProxyArn());
+ if (proxy.getVpcId() == null && proxy.getVpcSubnetIds().size() >= 2
+ && Objects.equals(proxyAccountId, defaultAccountId())) {
+ try {
+ proxy.setVpcId(resolveDbProxyVpc(
+ proxy.getVpcSubnetIds(), regionFromArn(proxy.getDbProxyArn())));
+ } catch (AwsException migrationFailure) {
+ LOG.warnv(migrationFailure,
+ "Could not derive VPC for persisted RDS proxy {0}; preserving existing state",
+ proxy.getDbProxyName());
+ }
+ }
+ boolean portReserved = false;
+ try {
+ int proxyPort = reserveOrAllocateProxyPort(proxy.getProxyPort());
+ portReserved = true;
+ proxy.setProxyPort(proxyPort);
+ if (config.services().rds().mock()) {
+ proxy.setEndpointHost("localhost");
+ proxy.setStatus("available");
+ persistRestoredProxy(proxy);
+ ensureRestoredDefaultTargetGroup(proxy);
+ continue;
+ }
+ proxy.setEndpointHost(proxyEndpointHost());
+ persistRestoredProxy(proxy);
+ DbProxyTargetGroup targetGroup = ensureRestoredDefaultTargetGroup(proxy);
+ if (targetGroup.getTargets().isEmpty()) {
+ proxy.setStatus("available");
+ persistRestoredProxy(proxy);
+ continue; // no target registered yet; nothing to relay to
+ }
+ if ("IAM_AUTH".equals(proxy.getDefaultAuthScheme())) {
+ throw new AwsException("InvalidDBProxyStateFault",
+ "DefaultAuthScheme IAM_AUTH is available for control-plane emulation only; "
+ + "the real-mode relay does not support end-to-end IAM authentication.",
+ 400);
+ }
+ startDbProxyRelay(proxy, targetGroup.getTargets().get(0));
+ proxy.setStatus("available");
+ persistRestoredProxy(proxy);
+ } catch (Exception e) {
+ if (!config.services().rds().mock()) {
+ try {
+ proxyManager.stopProxy(dbProxyRelayKey(proxy));
+ } catch (RuntimeException stopFailure) {
+ e.addSuppressed(stopFailure);
+ }
+ }
+ if (!portReserved) {
+ proxy.setProxyPort(0);
+ proxy.setEndpointHost(null);
+ }
+ proxy.setStatus("insufficient-resource-limits");
+ try {
+ persistRestoredProxy(proxy);
+ } catch (RuntimeException persistFailure) {
+ e.addSuppressed(persistFailure);
+ }
+ LOG.warnv(e, "Failed to restore RDS proxy {0}", proxy.getDbProxyName());
+ }
+ }
+ }
+
+ private void persistRestoredProxy(DbProxy proxy) {
+ String accountId = AwsArnUtils.accountOrDefault(proxy.getDbProxyArn(), defaultAccountId());
+ String proxyKey = dbProxyKey(regionFromArn(proxy.getDbProxyArn()), proxy.getDbProxyName());
+ if (proxies instanceof AccountAwareStorageBackend<DbProxy> aware) {
+ Optional<DbProxy> canonical = aware.getForAccount(accountId, proxyKey);
+ if (canonical.isPresent() && !sameProxyScope(canonical.get(), proxy)) {
+ throw new IllegalStateException(
+ "Refusing to overwrite corrupt canonical RDS proxy "
+ + proxy.getDbProxyName());
+ }
+ aware.getForAccountMigratingLegacyKeys(
+ accountId, proxyKey, List.of(proxy.getDbProxyName()),
+ candidate -> sameProxyScope(candidate, proxy));
+ aware.putForAccount(accountId, proxyKey, proxy);
+ } else {
+ Optional<DbProxy> canonical = proxies.get(proxyKey);
+ if (canonical.isPresent() && !sameProxyScope(canonical.get(), proxy)) {
+ throw new IllegalStateException(
+ "Refusing to overwrite corrupt canonical RDS proxy "
+ + proxy.getDbProxyName());
+ }
+ Optional<DbProxy> legacy = proxies.get(proxy.getDbProxyName());
+ proxies.put(proxyKey, proxy);
+ if (legacy.filter(candidate -> sameProxyScope(candidate, proxy)).isPresent()) {
+ proxies.delete(proxy.getDbProxyName());
+ }
+ }
+ }
+
+ private boolean sameProxyScope(DbProxy left, DbProxy right) {
+ if (left == null || right == null
+ || !Objects.equals(left.getDbProxyName(), right.getDbProxyName())
+ || !Objects.equals(left.getDbProxyArn(), right.getDbProxyArn())) {
+ return false;
+ }
+ try {
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(left.getDbProxyArn());
+ return proxyBelongsTo(left, arn.accountId(), arn.region())
+ && proxyBelongsTo(right, arn.accountId(), arn.region());
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ }
+
+ private DbProxyTargetGroup ensureRestoredDefaultTargetGroup(DbProxy proxy) {
+ String defaultAccountId = defaultAccountId();
+ String accountId = AwsArnUtils.accountOrDefault(proxy.getDbProxyArn(), defaultAccountId);
+ String region = regionFromArn(proxy.getDbProxyArn());
+ String proxyKey = dbProxyKey(region, proxy.getDbProxyName());
+ java.util.function.Predicate<DbProxyTargetGroup> legacyOwner = candidate ->
+ targetGroupCanMigrateToProxy(candidate, proxy);
+ DbProxyTargetGroup targetGroup;
+ if (proxyTargetGroups instanceof AccountAwareStorageBackend<DbProxyTargetGroup> aware) {
+ Optional<DbProxyTargetGroup> canonical = aware.getForAccount(accountId, proxyKey);
+ if (canonical.isPresent() && canonical.filter(legacyOwner).isEmpty()) {
+ throw new IllegalStateException(
+ "Refusing to overwrite corrupt canonical target group for RDS proxy "
+ + proxy.getDbProxyName());
+ }
+ targetGroup = canonical.orElse(null);
+ if (canonical.isEmpty()) {
+ targetGroup = aware.getForAccountMigratingLegacyKeys(
+ accountId, proxyKey, List.of(proxy.getDbProxyName()), legacyOwner)
+ .filter(legacyOwner)
+ .orElse(null);
+ }
+ } else {
+ Optional<DbProxyTargetGroup> canonical = proxyTargetGroups.get(proxyKey);
+ if (canonical.isPresent() && canonical.filter(legacyOwner).isEmpty()) {
+ throw new IllegalStateException(
+ "Refusing to overwrite corrupt canonical target group for RDS proxy "
+ + proxy.getDbProxyName());
+ }
+ targetGroup = canonical.orElseGet(() -> proxyTargetGroups
+ .get(proxy.getDbProxyName()).filter(legacyOwner).orElse(null));
+ }
+ if (targetGroup != null) {
+ Instant generation = proxy.getCreatedAt() != null
+ ? proxy.getCreatedAt()
+ : targetGroup.getCreatedAt() != null
+ ? targetGroup.getCreatedAt()
+ : Instant.now();
+ proxy.setCreatedAt(generation);
+ if (proxy.getUpdatedAt() == null) {
+ proxy.setUpdatedAt(generation);
+ }
+ targetGroup.setDbProxyName(proxy.getDbProxyName());
+ targetGroup.setTargetGroupName("default");
+ targetGroup.setDefaultTargetGroup(true);
+ targetGroup.setCreatedAt(generation);
+ if (targetGroup.getUpdatedAt() == null) {
+ targetGroup.setUpdatedAt(generation);
+ }
+ persistRestoredProxy(proxy);
+ persistRestoredTargetGroup(accountId, proxyKey, proxy.getDbProxyName(), targetGroup);
+ return targetGroup;
+ }
+
+ Instant now = proxy.getCreatedAt() != null ? proxy.getCreatedAt() : Instant.now();
+ proxy.setCreatedAt(now);
+ if (proxy.getUpdatedAt() == null) {
+ proxy.setUpdatedAt(now);
+ }
+ persistRestoredProxy(proxy);
+ targetGroup = new DbProxyTargetGroup();
+ targetGroup.setDbProxyName(proxy.getDbProxyName());
+ targetGroup.setTargetGroupName("default");
+ targetGroup.setTargetGroupArn(AwsArnUtils.Arn.of("rds",
+ region,
+ accountId, "target-group:prx-tg-" + randomResourceSuffix()).toString());
+ targetGroup.setDefaultTargetGroup(true);
+ targetGroup.setCreatedAt(now);
+ targetGroup.setUpdatedAt(now);
+ persistRestoredTargetGroup(accountId, proxyKey, proxy.getDbProxyName(), targetGroup);
+ return targetGroup;
+ }
+
+ private boolean targetGroupCanMigrateToProxy(
+ DbProxyTargetGroup targetGroup, DbProxy proxy) {
+ if (targetGroup == null || proxy == null
+ || !Objects.equals(proxy.getDbProxyName(), targetGroup.getDbProxyName())
+ || (targetGroup.getTargetGroupName() != null
+ && !targetGroup.getTargetGroupName().isBlank()
+ && !"default".equals(targetGroup.getTargetGroupName()))) {
+ return false;
+ }
+ try {
+ AwsArnUtils.Arn proxyArn = AwsArnUtils.parse(proxy.getDbProxyArn());
+ if (!proxyBelongsTo(proxy, proxyArn.accountId(), proxyArn.region())
+ || !targetGroupBelongsTo(
+ targetGroup, proxyArn.accountId(), proxyArn.region())) {
+ return false;
+ }
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ if (proxy.getCreatedAt() != null && targetGroup.getCreatedAt() == null) {
+ return false;
+ }
+ return proxy.getCreatedAt() == null
+ || Objects.equals(proxy.getCreatedAt(), targetGroup.getCreatedAt());
+ }
+
+ private void persistRestoredTargetGroup(
+ String accountId, String proxyKey, String legacyKey, DbProxyTargetGroup targetGroup) {
+ if (proxyTargetGroups instanceof AccountAwareStorageBackend<DbProxyTargetGroup> aware) {
+ Optional<DbProxyTargetGroup> canonical = aware.getForAccount(accountId, proxyKey);
+ if (canonical.isPresent()
+ && !sameTargetGroupScope(canonical.get(), targetGroup)) {
+ throw new IllegalStateException(
+ "Refusing to overwrite corrupt canonical RDS proxy target group "
+ + targetGroup.getDbProxyName());
+ }
+ aware.getForAccountMigratingLegacyKeys(
+ accountId, proxyKey, List.of(legacyKey),
+ candidate -> sameTargetGroupScope(candidate, targetGroup));
+ aware.putForAccount(accountId, proxyKey, targetGroup);
+ } else {
+ Optional<DbProxyTargetGroup> canonical = proxyTargetGroups.get(proxyKey);
+ if (canonical.isPresent()
+ && !sameTargetGroupScope(canonical.get(), targetGroup)) {
+ throw new IllegalStateException(
+ "Refusing to overwrite corrupt canonical RDS proxy target group "
+ + targetGroup.getDbProxyName());
+ }
+ Optional<DbProxyTargetGroup> legacy = proxyTargetGroups.get(legacyKey);
+ proxyTargetGroups.put(proxyKey, targetGroup);
+ if (legacy.filter(candidate -> sameTargetGroupScope(candidate, targetGroup)).isPresent()) {
+ proxyTargetGroups.delete(legacyKey);
+ }
+ }
+ }
+
+ private boolean targetGroupMatchesProxy(DbProxyTargetGroup targetGroup, DbProxy proxy) {
+ if (proxy == null || targetGroup == null
+ || !Objects.equals(proxy.getDbProxyName(), targetGroup.getDbProxyName())
+ || !"default".equals(targetGroup.getTargetGroupName())
+ || !targetGroup.isDefaultTargetGroup()
+ || proxy.getCreatedAt() == null
+ || !Objects.equals(proxy.getCreatedAt(), targetGroup.getCreatedAt())) {
+ return false;
+ }
+ try {
+ AwsArnUtils.Arn proxyArn = AwsArnUtils.parse(proxy.getDbProxyArn());
+ return proxyBelongsTo(proxy, proxyArn.accountId(), proxyArn.region())
+ && targetGroupBelongsTo(
+ targetGroup, proxyArn.accountId(), proxyArn.region());
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ }
+
+ private boolean sameTargetGroupScope(
+ DbProxyTargetGroup left, DbProxyTargetGroup right) {
+ if (left == null || right == null
+ || !Objects.equals(left.getDbProxyName(), right.getDbProxyName())
+ || !Objects.equals(left.getTargetGroupArn(), right.getTargetGroupArn())) {
+ return false;
+ }
+ try {
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(left.getTargetGroupArn());
+ return targetGroupBelongsTo(left, arn.accountId(), arn.region())
+ && targetGroupBelongsTo(right, arn.accountId(), arn.region());
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ }
+
+ private DbCluster getClusterForRestore(DbProxy proxy, String clusterId) {
+ DbCluster cluster = findClusterForScope(
+ accountIdFromArn(proxy.getDbProxyArn()),
+ regionFromArn(proxy.getDbProxyArn()), clusterId);
+ if (cluster == null) {
+ throw new AwsException("DBClusterNotFoundFault",
+ "DB cluster " + clusterId + " not found.", 404);
+ }
+ return cluster;
+ }
+
+ private DbInstance getInstanceForRestore(DbProxy proxy, String instanceId) {
+ DbInstance instance = findInstanceForScope(
+ accountIdFromArn(proxy.getDbProxyArn()),
+ regionFromArn(proxy.getDbProxyArn()), instanceId);
+ if (instance == null) {
+ throw new AwsException("DBInstanceNotFoundFault",
+ "DB instance " + instanceId + " not found.", 404);
+ }
+ return instance;
+ }
+
+ private synchronized DbCluster findClusterForScope(
+ String accountId, String region, String clusterId) {
+ String effectiveAccountId = accountId != null ? accountId : currentAccountId();
+ String effectiveRegion = effectiveRegion(region);
+ String key = dbResourceKey(effectiveRegion, clusterId);
+ java.util.function.Predicate<DbCluster> owner = cluster -> hasRdsResourceIdentity(
+ cluster.getDbClusterArn(), effectiveAccountId, effectiveRegion,
+ "cluster", clusterId);
if (clusters instanceof AccountAwareStorageBackend<DbCluster> aware) {
- return aware.scanAllAccounts();
+ return aware.getForAccountMigratingLegacyKeys(
+ effectiveAccountId, key, List.of(clusterId), owner)
+ .filter(owner)
+ .orElse(null);
+ }
+
+ Optional<DbCluster> canonical = clusters.get(key).filter(owner);
+ if (canonical.isPresent()) {
+ clusters.get(clusterId).filter(owner).ifPresent(ignored -> clusters.delete(clusterId));
+ return canonical.get();
}
- return clusters.scan(k -> true);
+ Optional<DbCluster> legacy = clusters.get(clusterId).filter(owner);
+ if (legacy.isPresent()) {
+ clusters.put(key, legacy.get());
+ clusters.delete(clusterId);
+ }
+ return legacy.orElse(null);
}
- private Collection<DbInstance> allInstances() {
+ private synchronized DbInstance findInstanceForScope(
+ String accountId, String region, String instanceId) {
+ String effectiveAccountId = accountId != null ? accountId : currentAccountId();
+ String effectiveRegion = effectiveRegion(region);
+ String key = dbResourceKey(effectiveRegion, instanceId);
+ java.util.function.Predicate<DbInstance> owner = instance -> hasRdsResourceIdentity(
+ instance.getDbInstanceArn(), effectiveAccountId, effectiveRegion,
+ "db", instanceId);
+ if (instances instanceof AccountAwareStorageBackend<DbInstance> aware) {
+ return aware.getForAccountMigratingLegacyKeys(
+ effectiveAccountId, key, List.of(instanceId), owner)
+ .filter(owner)
+ .orElse(null);
+ }
+
+ Optional<DbInstance> canonical = instances.get(key).filter(owner);
+ if (canonical.isPresent()) {
+ instances.get(instanceId).filter(owner).ifPresent(ignored -> instances.delete(instanceId));
+ return canonical.get();
+ }
+ Optional<DbInstance> legacy = instances.get(instanceId).filter(owner);
+ if (legacy.isPresent()) {
+ instances.put(key, legacy.get());
+ instances.delete(instanceId);
+ }
+ return legacy.orElse(null);
+ }
+
+ private void putClusterForScope(
+ String accountId, String region, String clusterId, DbCluster cluster) {
+ String key = dbResourceKey(region, clusterId);
+ if (clusters instanceof AccountAwareStorageBackend<DbCluster> aware) {
+ aware.putForAccount(accountId, key, cluster);
+ } else {
+ clusters.put(key, cluster);
+ }
+ }
+
+ private void deleteClusterForScope(String accountId, String region, String clusterId) {
+ String key = dbResourceKey(region, clusterId);
+ if (clusters instanceof AccountAwareStorageBackend<DbCluster> aware) {
+ aware.deleteForAccount(accountId, key);
+ } else {
+ clusters.delete(key);
+ }
+ }
+
+ private void putInstanceForScope(
+ String accountId, String region, String instanceId, DbInstance instance) {
+ String key = dbResourceKey(region, instanceId);
+ if (instances instanceof AccountAwareStorageBackend<DbInstance> aware) {
+ aware.putForAccount(accountId, key, instance);
+ } else {
+ instances.put(key, instance);
+ }
+ }
+
+ private void deleteInstanceForScope(String accountId, String region, String instanceId) {
+ String key = dbResourceKey(region, instanceId);
if (instances instanceof AccountAwareStorageBackend<DbInstance> aware) {
- return aware.scanAllAccounts();
+ aware.deleteForAccount(accountId, key);
+ } else {
+ instances.delete(key);
+ }
+ }
+
+ private synchronized DbSubnetGroup findSubnetGroupForScope(
+ String accountId, String region, String groupName) {
+ String effectiveRegion = effectiveRegion(region);
+ String key = dbResourceKey(effectiveRegion, groupName);
+ java.util.function.Predicate<DbSubnetGroup> owner = group ->
+ Objects.equals(groupName, group.getDbSubnetGroupName())
+ && hasRdsResourceIdentity(
+ group.getDbSubnetGroupArn(), accountId, effectiveRegion,
+ "subgrp", groupName);
+ if (subnetGroups instanceof AccountAwareStorageBackend<DbSubnetGroup> aware) {
+ return aware.getForAccountMigratingLegacyKeys(
+ accountId, key, List.of(groupName), owner)
+ .filter(owner)
+ .orElse(null);
+ }
+
+ Optional<DbSubnetGroup> canonicalValue = subnetGroups.get(key);
+ Optional<DbSubnetGroup> canonical = canonicalValue.filter(owner);
+ if (canonical.isPresent()) {
+ subnetGroups.get(groupName).filter(owner)
+ .ifPresent(ignored -> subnetGroups.delete(groupName));
+ return canonical.get();
+ }
+ if (canonicalValue.isPresent()) {
+ return null;
+ }
+ Optional<DbSubnetGroup> legacy = subnetGroups.get(groupName).filter(owner);
+ if (legacy.isPresent()) {
+ subnetGroups.put(key, legacy.get());
+ subnetGroups.delete(groupName);
+ }
+ return legacy.orElse(null);
+ }
+
+ private synchronized DbParameterGroup findParameterGroupForRegion(
+ String groupName, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ String accountId = currentAccountId();
+ String key = dbResourceKey(effectiveRegion, groupName);
+ java.util.function.Predicate<DbParameterGroup> owner = group ->
+ Objects.equals(groupName, group.getDbParameterGroupName())
+ && parameterGroupBelongsToRegion(group, effectiveRegion);
+ Optional<DbParameterGroup> resolved;
+ if (parameterGroups instanceof AccountAwareStorageBackend<DbParameterGroup> aware) {
+ resolved = aware.getForAccountMigratingLegacyKeys(
+ accountId, key, List.of(groupName), owner,
+ Objects.equals(accountId, defaultAccountId()));
+ } else {
+ Optional<DbParameterGroup> canonicalValue = parameterGroups.get(key);
+ Optional<DbParameterGroup> canonical = canonicalValue.filter(owner);
+ if (canonical.isPresent()) {
+ parameterGroups.get(groupName).filter(owner)
+ .ifPresent(ignored -> parameterGroups.delete(groupName));
+ resolved = canonical;
+ } else if (canonicalValue.isPresent()) {
+ resolved = Optional.empty();
+ } else {
+ Optional<DbParameterGroup> legacy = parameterGroups.get(groupName).filter(owner);
+ if (legacy.isPresent()) {
+ parameterGroups.put(key, legacy.get());
+ parameterGroups.delete(groupName);
+ }
+ resolved = legacy;
+ }
+ }
+ resolved.ifPresent(group -> {
+ if (group.getRegion() == null || group.getRegion().isBlank()) {
+ group.setRegion(effectiveRegion);
+ putParameterGroupForRegion(groupName, effectiveRegion, group);
+ }
+ });
+ return resolved.orElse(null);
+ }
+
+ private boolean parameterGroupBelongsToRegion(
+ DbParameterGroup group, String region) {
+ if (group == null) {
+ return false;
}
- return instances.scan(k -> true);
+ String storedRegion = group.getRegion();
+ return storedRegion == null || storedRegion.isBlank()
+ ? Objects.equals(regionResolver.getDefaultRegion(), region)
+ : Objects.equals(storedRegion, region);
+ }
+
+ private void putParameterGroupForRegion(
+ String groupName, String region, DbParameterGroup group) {
+ String key = dbResourceKey(region, groupName);
+ if (parameterGroups instanceof AccountAwareStorageBackend<DbParameterGroup> aware) {
+ aware.putForAccount(currentAccountId(), key, group);
+ } else {
+ parameterGroups.put(key, group);
+ }
+ }
+
+ private void deleteParameterGroupForRegion(String groupName, String region) {
+ String key = dbResourceKey(region, groupName);
+ if (parameterGroups instanceof AccountAwareStorageBackend<DbParameterGroup> aware) {
+ aware.deleteForAccount(currentAccountId(), key);
+ } else {
+ parameterGroups.delete(key);
+ }
+ }
+
+ private synchronized DbClusterParameterGroup findClusterParameterGroupForRegion(
+ String groupName, String region) {
+ String effectiveRegion = effectiveRegion(region);
+ String accountId = currentAccountId();
+ String key = dbResourceKey(effectiveRegion, groupName);
+ java.util.function.Predicate<DbClusterParameterGroup> owner = group ->
+ Objects.equals(groupName, group.getDbClusterParameterGroupName())
+ && clusterParameterGroupBelongsToRegion(group, effectiveRegion);
+ Optional<DbClusterParameterGroup> resolved;
+ if (clusterParameterGroups
+ instanceof AccountAwareStorageBackend<DbClusterParameterGroup> aware) {
+ resolved = aware.getForAccountMigratingLegacyKeys(
+ accountId, key, List.of(groupName), owner,
+ Objects.equals(accountId, defaultAccountId()));
+ } else {
+ Optional<DbClusterParameterGroup> canonicalValue =
+ clusterParameterGroups.get(key);
+ Optional<DbClusterParameterGroup> canonical = canonicalValue.filter(owner);
+ if (canonical.isPresent()) {
+ clusterParameterGroups.get(groupName).filter(owner)
+ .ifPresent(ignored -> clusterParameterGroups.delete(groupName));
+ resolved = canonical;
+ } else if (canonicalValue.isPresent()) {
+ resolved = Optional.empty();
+ } else {
+ Optional<DbClusterParameterGroup> legacy =
+ clusterParameterGroups.get(groupName).filter(owner);
+ if (legacy.isPresent()) {
+ clusterParameterGroups.put(key, legacy.get());
+ clusterParameterGroups.delete(groupName);
+ }
+ resolved = legacy;
+ }
+ }
+ resolved.ifPresent(group -> {
+ if (group.getRegion() == null || group.getRegion().isBlank()) {
+ group.setRegion(effectiveRegion);
+ putClusterParameterGroupForRegion(groupName, effectiveRegion, group);
+ }
+ });
+ return resolved.orElse(null);
+ }
+
+ private boolean clusterParameterGroupBelongsToRegion(
+ DbClusterParameterGroup group, String region) {
+ if (group == null) {
+ return false;
+ }
+ String storedRegion = group.getRegion();
+ return storedRegion == null || storedRegion.isBlank()
+ ? Objects.equals(regionResolver.getDefaultRegion(), region)
+ : Objects.equals(storedRegion, region);
+ }
+
+ private void putClusterParameterGroupForRegion(
+ String groupName, String region, DbClusterParameterGroup group) {
+ String key = dbResourceKey(region, groupName);
+ if (clusterParameterGroups
+ instanceof AccountAwareStorageBackend<DbClusterParameterGroup> aware) {
+ aware.putForAccount(currentAccountId(), key, group);
+ } else {
+ clusterParameterGroups.put(key, group);
+ }
+ }
+
+ private void deleteClusterParameterGroupForRegion(String groupName, String region) {
+ String key = dbResourceKey(region, groupName);
+ if (clusterParameterGroups
+ instanceof AccountAwareStorageBackend<DbClusterParameterGroup> aware) {
+ aware.deleteForAccount(currentAccountId(), key);
+ } else {
+ clusterParameterGroups.delete(key);
+ }
+ }
+
+ private void putSubnetGroupForScope(
+ String accountId, String region, String groupName, DbSubnetGroup group) {
+ String key = dbResourceKey(region, groupName);
+ if (subnetGroups instanceof AccountAwareStorageBackend<DbSubnetGroup> aware) {
+ aware.putForAccount(accountId, key, group);
+ } else {
+ subnetGroups.put(key, group);
+ }
+ }
+
+ private void deleteSubnetGroupForScope(
+ String accountId, String region, String groupName) {
+ String key = dbResourceKey(region, groupName);
+ if (subnetGroups instanceof AccountAwareStorageBackend<DbSubnetGroup> aware) {
+ aware.deleteForAccount(accountId, key);
+ } else {
+ subnetGroups.delete(key);
+ }
+ }
+
+ private String dbResourceKey(String region, String resourceId) {
+ return effectiveRegion(region) + "::" + resourceId;
+ }
+
+ private <T> boolean scopedKeyExists(
+ StorageBackend<String, T> storage, String accountId, String key) {
+ if (storage instanceof AccountAwareStorageBackend<T> aware) {
+ return aware.getForAccount(accountId, key).isPresent();
+ }
+ return storage.get(key).isPresent();
+ }
+
+ private boolean hasRdsResourceIdentity(
+ String arn, String accountId, String region,
+ String resourceType, String resourceId) {
+ try {
+ AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
+ return "aws".equals(parsed.partition())
+ && "rds".equals(parsed.service())
+ && Objects.equals(accountId, parsed.accountId())
+ && Objects.equals(region, parsed.region())
+ && Objects.equals(resourceType + ":" + resourceId, parsed.resource());
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ }
+
+ private String accountIdFromArn(String arn) {
+ return AwsArnUtils.accountOrDefault(arn, defaultAccountId());
+ }
+
+ private String defaultAccountId() {
+ String configured = config.defaultAccountId();
+ return configured == null || configured.isBlank() ? regionResolver.getAccountId() : configured;
+ }
+
+ private String dbProxyRelayKey(DbProxy proxy) {
+ String identity = proxy.getDbProxyArn();
+ if (identity == null || identity.isBlank()) {
+ identity = proxy.getDbProxyName();
+ }
+ return "db-proxy:" + identity;
+ }
+
+ private String rdsResourceRelayKey(String resourceArn, String resourceId) {
+ String identity = resourceArn;
+ if (identity == null || identity.isBlank()) {
+ identity = currentAccountId() + ":" + resourceId;
+ }
+ return "rds-resource:" + identity;
+ }
+
+ private Collection<DbCluster> allClusters() {
+ Collection<DbCluster> stored = clusters instanceof AccountAwareStorageBackend<DbCluster> aware
+ ? aware.scanAllAccounts() : clusters.scan(k -> true);
+ Map<String, DbCluster> unique = new LinkedHashMap<>();
+ for (DbCluster cluster : stored) {
+ try {
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(cluster.getDbClusterArn());
+ if (!"rds".equals(arn.service())
+ || !Objects.equals("cluster:" + cluster.getDbClusterIdentifier(), arn.resource())) {
+ continue;
+ }
+ DbCluster canonical = findClusterForScope(
+ arn.accountId(), arn.region(), cluster.getDbClusterIdentifier());
+ if (canonical != null) {
+ unique.put(canonical.getDbClusterArn(), canonical);
+ }
+ } catch (IllegalArgumentException e) {
+ LOG.warnv("Skipping persisted RDS cluster with invalid ARN: {0}",
+ cluster.getDbClusterIdentifier());
+ }
+ }
+ return unique.values();
+ }
+
+ private Collection<DbInstance> allInstances() {
+ Collection<DbInstance> stored = instances instanceof AccountAwareStorageBackend<DbInstance> aware
+ ? aware.scanAllAccounts() : instances.scan(k -> true);
+ Map<String, DbInstance> unique = new LinkedHashMap<>();
+ for (DbInstance instance : stored) {
+ try {
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(instance.getDbInstanceArn());
+ if (!"rds".equals(arn.service())
+ || !Objects.equals("db:" + instance.getDbInstanceIdentifier(), arn.resource())) {
+ continue;
+ }
+ DbInstance canonical = findInstanceForScope(
+ arn.accountId(), arn.region(), instance.getDbInstanceIdentifier());
+ if (canonical != null) {
+ unique.put(canonical.getDbInstanceArn(), canonical);
+ }
+ } catch (IllegalArgumentException e) {
+ LOG.warnv("Skipping persisted RDS instance with invalid ARN: {0}",
+ instance.getDbInstanceIdentifier());
+ }
+ }
+ return unique.values();
+ }
+
+ private Collection<DbProxy> allProxies() {
+ boolean accountAware = proxies instanceof AccountAwareStorageBackend<DbProxy>;
+ Map<String, DbProxy> stored = new LinkedHashMap<>();
+ if (proxies instanceof AccountAwareStorageBackend<DbProxy> aware) {
+ stored.putAll(aware.scanAllAccountsWithRawKeys());
+ } else {
+ for (String rawKey : proxies.keys()) {
+ proxies.get(rawKey).ifPresent(proxy -> stored.put(rawKey, proxy));
+ }
+ }
+ List<Map.Entry<String, DbProxy>> candidates = new ArrayList<>(stored.entrySet());
+ candidates.sort(Comparator.comparingInt(entry -> {
+ try {
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(entry.getValue().getDbProxyArn());
+ return proxyStorageKeyPriority(
+ entry.getKey(), entry.getValue(), arn, accountAware);
+ } catch (IllegalArgumentException e) {
+ return Integer.MAX_VALUE;
+ }
+ }));
+ Map<String, DbProxy> unique = new LinkedHashMap<>();
+ for (Map.Entry<String, DbProxy> entry : candidates) {
+ String rawKey = entry.getKey();
+ DbProxy proxy = entry.getValue();
+ try {
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(proxy.getDbProxyArn());
+ if (!validPersistedProxyIdentity(proxy, arn)
+ || !proxyBelongsTo(proxy, arn.accountId(), arn.region())
+ || proxyStorageKeyPriority(rawKey, proxy, arn, accountAware)
+ == Integer.MAX_VALUE) {
+ LOG.warnv("Skipping persisted RDS proxy with invalid ARN identity: {0}",
+ proxy.getDbProxyName());
+ continue;
+ }
+ String key = dbProxyKey(arn.region(), proxy.getDbProxyName());
+ DbProxy canonical = proxies instanceof AccountAwareStorageBackend<DbProxy> aware
+ ? aware.getForAccount(arn.accountId(), key).orElse(proxy)
+ : proxies.get(key).orElse(proxy);
+ if (!proxyBelongsTo(canonical, arn.accountId(), arn.region())
+ || !sameProxyScope(canonical, proxy)) {
+ LOG.warnv("Skipping persisted RDS proxy with corrupt canonical state: {0}",
+ proxy.getDbProxyName());
+ continue;
+ }
+ String identity = arn.accountId() + "/" + arn.region()
+ + "/" + proxy.getDbProxyName();
+ unique.putIfAbsent(identity, canonical);
+ } catch (IllegalArgumentException e) {
+ LOG.warnv("Skipping persisted RDS proxy with malformed ARN: {0}",
+ proxy.getDbProxyName());
+ }
+ }
+ return unique.values();
+ }
+
+ private boolean validPersistedProxyIdentity(DbProxy proxy, AwsArnUtils.Arn arn) {
+ String name = proxy.getDbProxyName();
+ return !arn.accountId().isBlank()
+ && !arn.region().isBlank()
+ && name != null
+ && !name.isBlank()
+ && name.length() <= 63
+ && DB_PROXY_NAME_PATTERN.matcher(name).matches();
+ }
+
+ private int proxyStorageKeyPriority(
+ String rawKey, DbProxy proxy, AwsArnUtils.Arn arn, boolean accountAware) {
+ if (rawKey == null || proxy.getDbProxyName() == null) {
+ return Integer.MAX_VALUE;
+ }
+ String canonicalKey = dbProxyKey(arn.region(), proxy.getDbProxyName());
+ if (!accountAware) {
+ if (rawKey.equals(canonicalKey)) {
+ return 0;
+ }
+ return rawKey.equals(proxy.getDbProxyName()) ? 1 : Integer.MAX_VALUE;
+ }
+ if (rawKey.equals(arn.accountId() + "/" + canonicalKey)) {
+ return 0;
+ }
+ if (rawKey.equals(canonicalKey)) {
+ return 1;
+ }
+ if (rawKey.equals(arn.accountId() + "/" + proxy.getDbProxyName())) {
+ return 2;
+ }
+ return rawKey.equals(proxy.getDbProxyName()) ? 3 : Integer.MAX_VALUE;
}
private int reserveOrAllocateProxyPort(int persistedPort) {
@@ -1404,9 +4126,7 @@ public class RdsService implements Resettable {
: dbSubnetGroupName;
DbSubnetGroup group = "default".equals(effectiveSubnetGroupName)
? buildDefaultSubnetGroup(region)
- : subnetGroups.get(effectiveSubnetGroupName).orElseThrow(() ->
- new AwsException("DBSubnetGroupNotFoundFault",
- "DB subnet group " + effectiveSubnetGroupName + " not found.", 404));
+ : getDbSubnetGroup(effectiveSubnetGroupName, region);
Map<String, String> subnetAvailabilityZones = group.getSubnetAvailabilityZones();
String vpcId = group.getVpcId();
@@ -1457,6 +4177,39 @@ public class RdsService implements Resettable {
return buildSubnetGroup("default", "default subnet group", extractSubnetIds(subnets), region);
}
+ private String resolveDbProxyVpc(List<String> subnetIds, String region) {
+ List<Subnet> resolvedSubnets = ec2Service.describeSubnets(region, subnetIds, Map.of());
+ Set<String> requestedIds = Set.copyOf(subnetIds);
+ Set<String> resolvedIds = resolvedSubnets.stream()
+ .map(Subnet::getSubnetId)
+ .filter(Objects::nonNull)
+ .collect(java.util.stream.Collectors.toSet());
+ if (!resolvedIds.equals(requestedIds)) {
+ throw new AwsException("InvalidSubnet",
+ "One or more VpcSubnetIds do not exist in region " + region + ".", 400);
+ }
+
+ Set<String> vpcIds = resolvedSubnets.stream()
+ .map(Subnet::getVpcId)
+ .filter(id -> id != null && !id.isBlank())
+ .collect(java.util.stream.Collectors.toSet());
+ if (vpcIds.size() != 1) {
+ throw new AwsException("InvalidSubnet",
+ "VpcSubnetIds must belong to one VPC.", 400);
+ }
+
+ long availabilityZones = resolvedSubnets.stream()
+ .map(Subnet::getAvailabilityZone)
+ .filter(zone -> zone != null && !zone.isBlank())
+ .distinct()
+ .count();
+ if (availabilityZones < 2) {
+ throw new AwsException("InvalidSubnet",
+ "VpcSubnetIds must span at least two Availability Zones.", 400);
+ }
+ return vpcIds.iterator().next();
+ }
+
private DbSubnetGroup buildSubnetGroup(String name, String description, List<String> subnetIds, String region) {
List<Subnet> resolvedSubnets = ec2Service.describeSubnets(region, subnetIds, Map.of());
if (resolvedSubnets.size() != subnetIds.size()) {
@@ -1497,13 +4250,65 @@ public class RdsService implements Resettable {
return ContainerStorageHelper.resourceName(config, "rds", volumeId, fallbackId);
}
+ private String newVolumeName(String volumeId, String storageResourceId) {
+ String qualifiedVolumeId = volumeId == null || volumeId.isBlank()
+ ? null : storageResourceId + "-" + volumeId;
+ return volumeName(qualifiedVolumeId, storageResourceId);
+ }
+
+ private String resolvedInstanceStorageResourceId(DbInstance instance) {
+ return firstNonBlank(
+ instance.getContainerStorageResourceId(),
+ instance.getDbInstanceIdentifier());
+ }
+
+ private String resolvedInstanceDockerVolumeName(DbInstance instance) {
+ if (instance.getDockerVolumeName() != null
+ && !instance.getDockerVolumeName().isBlank()) {
+ return instance.getDockerVolumeName();
+ }
+ if (instance.getContainerStorageResourceId() != null
+ && !instance.getContainerStorageResourceId().isBlank()) {
+ return newVolumeName(
+ instance.getVolumeId(), instance.getContainerStorageResourceId());
+ }
+ return volumeName(instance.getVolumeId(), instance.getDbInstanceIdentifier());
+ }
+
+ private String resolvedClusterStorageResourceId(DbCluster cluster) {
+ return firstNonBlank(
+ cluster.getContainerStorageResourceId(),
+ cluster.getDbClusterIdentifier());
+ }
+
+ private String resolvedClusterDockerVolumeName(DbCluster cluster) {
+ if (cluster.getDockerVolumeName() != null
+ && !cluster.getDockerVolumeName().isBlank()) {
+ return cluster.getDockerVolumeName();
+ }
+ if (cluster.getContainerStorageResourceId() != null
+ && !cluster.getContainerStorageResourceId().isBlank()) {
+ return newVolumeName(
+ cluster.getVolumeId(), cluster.getContainerStorageResourceId());
+ }
+ return volumeName(cluster.getVolumeId(), cluster.getDbClusterIdentifier());
+ }
+
+ private static String firstNonBlank(String value, String fallback) {
+ return value == null || value.isBlank() ? fallback : value;
+ }
+
private RdsContainerHandle buildHandle(DbInstance instance) {
- return new RdsContainerHandle(instance.getContainerId(), instance.getDbInstanceIdentifier(),
+ return new RdsContainerHandle(
+ instance.getContainerId(), instance.getDbInstanceArn(),
+ instance.getDbInstanceIdentifier(),
instance.getContainerHost(), instance.getContainerPort());
}
private RdsContainerHandle buildClusterHandle(DbCluster cluster) {
- return new RdsContainerHandle(cluster.getContainerId(), cluster.getDbClusterIdentifier(),
+ return new RdsContainerHandle(
+ cluster.getContainerId(), cluster.getDbClusterArn(),
+ cluster.getDbClusterIdentifier(),
cluster.getContainerHost(), cluster.getContainerPort());
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerHandle.java b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerHandle.java
index 4fe51207b2..0e499836ca 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerHandle.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerHandle.java
@@ -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; }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java
index 9100592030..0dd32c98e3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManager.java
@@ -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();
-
- if (!containerDetector.isRunningInContainer()) {
- specBuilder.withDynamicPort(enginePort);
- } else {
- specBuilder.withExposedPort(enginePort);
- }
+ 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);
+ }
// 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();
-
- Closeable logHandle = logStreamer.attach(
- info.containerId(), logGroup, logStream, region, "rds:" + instanceId);
- handle.setLogStream(logHandle);
-
- return handle;
+ 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 = 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;
+ } 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";
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java
index 3453af6054..90c4463e8e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbCluster.java
@@ -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; }
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbClusterParameterGroup.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbClusterParameterGroup.java
index f4b2847f94..7ae0eb4969 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbClusterParameterGroup.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbClusterParameterGroup.java
@@ -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; }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java
index 6b6b846805..ded4e59a43 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstance.java
@@ -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; }
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceStatus.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceStatus.java
index 597804b462..43407dcb65 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceStatus.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbInstanceStatus.java
@@ -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
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbParameterGroup.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbParameterGroup.java
index 2da9816e50..57dbda826f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbParameterGroup.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbParameterGroup.java
@@ -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; }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxy.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxy.java
new file mode 100644
index 0000000000..cd3735ebbc
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxy.java
@@ -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<>(); }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxyAuth.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxyAuth.java
new file mode 100644
index 0000000000..50dc07e026
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxyAuth.java
@@ -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; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxyTarget.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxyTarget.java
new file mode 100644
index 0000000000..f34a2180dd
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxyTarget.java
@@ -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; }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxyTargetGroup.java b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxyTargetGroup.java
new file mode 100644
index 0000000000..b7605578d8
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/model/DbProxyTargetGroup.java
@@ -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<>();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java
index 9ae2b1e46d..b84d1042d3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsAuthProxy.java
@@ -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");
+ }
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java
index e68c4599a2..f9e47a6428 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManager.java
@@ -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);
+ }
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataController.java b/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataController.java
index 1cd8691347..e064c0b1fb 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataController.java
@@ -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) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataResourceResolver.java b/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataResourceResolver.java
index b005574e0f..0dd0b505b7 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataResourceResolver.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataResourceResolver.java
@@ -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) {
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataService.java b/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataService.java
index 1e8bd3344e..c0a4dd39a1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/rdsdata/RdsDataService.java
@@ -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);
}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java
index c4811d1452..62dfd3e0c2 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java
@@ -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);
diff --git a/src/test/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackendTest.java b/src/test/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackendTest.java
index f23e166de2..92a1f92a79 100644
--- a/src/test/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackendTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackendTest.java
@@ -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<>();
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java
index cb3a3b19b8..7b82d96fbb 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/RdsCfnProvisionerTest.java
@@ -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");
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
index 581401dee9..7ce41e1bfa 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudwatch/logs/CloudWatchLogsServiceTest.java
@@ -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);
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
index 74852b90bd..4d27c86f61 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java
@@ -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"))),
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java
index 5c24e9f912..cc8d8b7f1c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsQueryHandlerTest.java
@@ -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();
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java
index 4208c048e9..ccb5741fe5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
+import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
@@ -14,10 +15,16 @@ import io.github.hectorvent.floci.services.rds.model.DbCluster;
import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup;
import io.github.hectorvent.floci.services.rds.container.RdsContainerHandle;
import io.github.hectorvent.floci.services.rds.container.RdsContainerManager;
+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 io.github.hectorvent.floci.services.rds.proxy.RdsAuthProxy;
import io.github.hectorvent.floci.services.rds.proxy.RdsProxyManager;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.secretsmanager.model.Secret;
@@ -27,10 +34,12 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.ArgumentCaptor;
+import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.OptionalInt;
import java.util.stream.Collectors;
@@ -42,11 +51,22 @@ import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.doCallRealMethod;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class RdsServiceTest {
+ private static final String PROXY_ROLE_ARN = "arn:aws:iam::123456789012:role/proxy";
+ private static final List<String> PROXY_SUBNET_IDS =
+ List.of("subnet-default-a", "subnet-default-b");
+ private static final List<DbProxyAuth> PROXY_AUTH = List.of(new DbProxyAuth(
+ "SECRETS", "arn:aws:secretsmanager:us-east-1:123456789012:secret:db-AbCdEf",
+ "DISABLED", null, null));
private static final List<String> CURRENT_MANAGED_CLUSTER_PARAMETER_GROUP_FAMILIES = List.of(
"aurora-mysql5.7",
"aurora-mysql8.0",
@@ -87,6 +107,7 @@ class RdsServiceTest {
rdsConfig = mock(EmulatorConfig.RdsServiceConfig.class);
when(config.services()).thenReturn(servicesConfig);
+ when(config.defaultAccountId()).thenReturn("123456789012");
when(servicesConfig.rds()).thenReturn(rdsConfig);
when(rdsConfig.proxyBasePort()).thenReturn(7000);
when(rdsConfig.proxyMaxPort()).thenReturn(7099);
@@ -98,9 +119,9 @@ class RdsServiceTest {
new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
- when(containerManager.start(any(), any(), any(), any(), any(), any(), any()))
+ when(containerManager.start(any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new RdsContainerHandle("cont-id", "id", "localhost", 5432));
- when(ec2Service.describeSubnets(eq("us-east-1"), anyList(), any()))
+ when(ec2Service.describeSubnets(any(), anyList(), any()))
.thenAnswer(invocation -> {
@SuppressWarnings("unchecked")
List<String> subnetIds = invocation.getArgument(1, List.class);
@@ -162,7 +183,9 @@ class RdsServiceTest {
"admin", "password", "dbname", "db.t3.micro",
20, false, null, null, null);
- verify(containerManager).start(eq("mydb"), any(), eq(DatabaseEngine.POSTGRES),
+ verify(containerManager).start(
+ eq("arn:aws:rds:us-east-1:123456789012:db:mydb"), eq("mydb"),
+ any(), any(), eq(DatabaseEngine.POSTGRES),
eq("postgres:18.1-alpine"), eq("admin"), eq("password"), eq("dbname"));
}
@@ -173,7 +196,9 @@ class RdsServiceTest {
rdsService.createDbCluster("cluster1", "postgres", "16.3",
"admin", "password", "dbname", false, null);
- verify(containerManager).start(eq("cluster1"), any(), eq(DatabaseEngine.POSTGRES),
+ verify(containerManager).start(
+ eq("arn:aws:rds:us-east-1:123456789012:cluster:cluster1"), eq("cluster1"),
+ any(), any(), eq(DatabaseEngine.POSTGRES),
eq("postgres:16.14-alpine3.23"), eq("admin"), eq("password"), eq("dbname"));
}
@@ -185,7 +210,9 @@ class RdsServiceTest {
rdsService.createDbCluster("cluster1", "postgres", "18.1",
"admin", "password", "dbname", false, null);
- verify(containerManager).start(eq("cluster1"), any(), eq(DatabaseEngine.POSTGRES),
+ verify(containerManager).start(
+ eq("arn:aws:rds:us-east-1:123456789012:cluster:cluster1"), eq("cluster1"),
+ any(), any(), eq(DatabaseEngine.POSTGRES),
eq(EmulatorConfig.RdsServiceConfig.DEFAULT_POSTGRES_IMAGE),
eq("admin"), eq("password"), eq("dbname"));
}
@@ -473,6 +500,42 @@ class RdsServiceTest {
rdsService.listTagsForResource(arn));
}
+ @Test
+ void sameNamedSubnetGroupsAreRegionScopedIncludingTagsAndDeletion() {
+ List<String> westSubnetIds = List.of("subnet-west-a", "subnet-west-b");
+ when(ec2Service.describeSubnets(eq("us-west-2"), eq(westSubnetIds), eq(Map.of())))
+ .thenReturn(List.of(
+ subnet("subnet-west-a", "vpc-west", "us-west-2a"),
+ subnet("subnet-west-b", "vpc-west", "us-west-2b")));
+
+ DbSubnetGroup east = rdsService.createDbSubnetGroup(
+ "regional-subnets", "east", PROXY_SUBNET_IDS, "us-east-1");
+ DbSubnetGroup west = rdsService.createDbSubnetGroup(
+ "regional-subnets", "west", westSubnetIds, "us-west-2");
+
+ rdsService.addTagsToResource(
+ east.getDbSubnetGroupArn(), Map.of("region", "east"), "us-east-1");
+ rdsService.addTagsToResource(
+ west.getDbSubnetGroupArn(), Map.of("region", "west"), "us-west-2");
+
+ assertEquals("vpc-default", rdsService.getDbSubnetGroup(
+ "regional-subnets", "us-east-1").getVpcId());
+ assertEquals("vpc-west", rdsService.getDbSubnetGroup(
+ "regional-subnets", "us-west-2").getVpcId());
+ assertEquals(Map.of("region", "east"), rdsService.listTagsForResource(
+ east.getDbSubnetGroupArn(), "us-east-1"));
+ assertEquals(Map.of("region", "west"), rdsService.listTagsForResource(
+ west.getDbSubnetGroupArn(), "us-west-2"));
+
+ rdsService.deleteDbSubnetGroup("regional-subnets", "us-west-2");
+
+ assertEquals(east.getDbSubnetGroupArn(), rdsService.getDbSubnetGroup(
+ "regional-subnets", "us-east-1").getDbSubnetGroupArn());
+ AwsException missingWest = assertThrows(AwsException.class, () ->
+ rdsService.getDbSubnetGroup("regional-subnets", "us-west-2"));
+ assertEquals("DBSubnetGroupNotFoundFault", missingWest.getErrorCode());
+ }
+
@Test
void listTagsForMissingSubnetGroupReturnsSubnetGroupNotFound() {
AwsException exception = assertThrows(AwsException.class, () ->
@@ -537,7 +600,7 @@ class RdsServiceTest {
20, false, null, "missing-subnet-group", null));
assertEquals("DBSubnetGroupNotFoundFault", exception.getErrorCode());
- verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any());
+ verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(),
any(), anyInt(), any(), any(), any(), any());
}
@@ -602,7 +665,7 @@ class RdsServiceTest {
assertEquals("localhost", cluster.getEndpoint().address());
assertTrue(cluster.getEndpoint().port() > 0);
assertNull(cluster.getContainerId());
- verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any());
+ verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
any(), any(), any(), any());
}
@@ -622,7 +685,7 @@ class RdsServiceTest {
// No Docker volume name may be persisted: the mock cluster has a null volume id, so the
// fallback would fabricate a name that a later non-mock restore could try to reference.
assertNull(instance.getDockerVolumeName());
- verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any());
+ verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
any(), any(), any(), any());
}
@@ -637,7 +700,7 @@ class RdsServiceTest {
assertEquals(DbInstanceStatus.AVAILABLE, instance.getStatus());
assertNull(instance.getContainerId());
- verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any());
+ verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
@@ -649,7 +712,7 @@ class RdsServiceTest {
rdsService.deleteDbCluster("cluster1");
verify(containerManager, never()).stop(any());
- verify(containerManager, never()).removeVolume(any(), any());
+ verify(containerManager, never()).removeVolume(any(), any(), any());
}
@Test
@@ -662,7 +725,7 @@ class RdsServiceTest {
rdsService.deleteDbInstance("standalone");
verify(containerManager, never()).stop(any());
- verify(containerManager, never()).removeVolume(any(), any());
+ verify(containerManager, never()).removeVolume(any(), any(), any());
}
@Test
@@ -687,12 +750,31 @@ class RdsServiceTest {
DbInstance rebooted = rdsService.rebootDbInstance("standalone");
assertEquals(DbInstanceStatus.AVAILABLE, rebooted.getStatus());
- verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any());
+ verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(containerManager, never()).stop(any());
verify(proxyManager, never()).startProxy(any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
any(), any(), any(), any());
}
+ @Test
+ void rebootStopsBeforeRestartAndPersistsFailedStatusWhenCleanupFails() {
+ DbInstance instance = rdsService.createDbInstance(
+ "standalone", "postgres", "16", "admin", "password", "dbname",
+ "db.t3.micro", 20, false, null, null, null);
+ doThrow(new IllegalStateException("Docker cleanup failed"))
+ .when(containerManager).stop(any());
+
+ assertThrows(IllegalStateException.class, () ->
+ rdsService.rebootDbInstance("standalone"));
+
+ DbInstance failed = rdsService.getDbInstance("standalone");
+ assertEquals(DbInstanceStatus.FAILED, failed.getStatus());
+ assertEquals(instance.getContainerId(), failed.getContainerId());
+ verify(containerManager, times(1)).start(
+ any(), any(), any(), any(), any(), any(), any(), any(), any());
+ verify(proxyManager).stopProxy("rds-resource:" + instance.getDbInstanceArn());
+ }
+
@Test
void createDbClusterRejectsUnknownClusterParameterGroup() {
AwsException exception = assertThrows(AwsException.class, () -> rdsService.createDbCluster("cluster1", "aurora-postgresql", "16.3",
@@ -877,6 +959,187 @@ class RdsServiceTest {
assertEquals("persisted default", matching.getFirst().getDescription());
}
+ @Test
+ void parameterGroupsAreRegionScopedAndRegionalResourcesCannotClaimForeignGroups() {
+ when(config.services().rds().mock()).thenReturn(true);
+ rdsService.createDbParameterGroup("regional-pg", "postgres16", "east", "us-east-1");
+ rdsService.createDbParameterGroup("regional-pg", "postgres16", "west", "us-west-2");
+ rdsService.modifyDbParameterGroup(
+ "regional-pg", Map.of("application_name", "east"), "us-east-1");
+ rdsService.modifyDbParameterGroup(
+ "regional-pg", Map.of("application_name", "west"), "us-west-2");
+
+ assertEquals("east", rdsService.getDbParameterGroup(
+ "regional-pg", "us-east-1").getParameters().get("application_name"));
+ assertEquals("west", rdsService.getDbParameterGroup(
+ "regional-pg", "us-west-2").getParameters().get("application_name"));
+
+ rdsService.createDbClusterParameterGroup(
+ "regional-cpg", "aurora-postgresql16", "east", "us-east-1");
+ rdsService.createDbClusterParameterGroup(
+ "regional-cpg", "aurora-postgresql16", "west", "us-west-2");
+ rdsService.modifyDbClusterParameterGroup(
+ "regional-cpg", Map.of("log_statement", "none"), "us-east-1");
+ rdsService.modifyDbClusterParameterGroup(
+ "regional-cpg", Map.of("log_statement", "all"), "us-west-2");
+
+ assertEquals("none", rdsService.getDbClusterParameterGroup(
+ "regional-cpg", "us-east-1").getParameters().get("log_statement"));
+ assertEquals("all", rdsService.getDbClusterParameterGroup(
+ "regional-cpg", "us-west-2").getParameters().get("log_statement"));
+
+ rdsService.createDbParameterGroup(
+ "east-only-pg", "postgres16", "east", "us-east-1");
+ AwsException instanceGroupMissing = assertThrows(AwsException.class, () ->
+ rdsService.createDbInstance(
+ "west-db", "postgres", "16.3", "admin", "secret", "app",
+ "db.t3.micro", 20, false, "east-only-pg", null, null,
+ null, false, false, null, Map.of(), List.of(), "us-west-2"));
+ assertEquals("DBParameterGroupNotFound", instanceGroupMissing.getErrorCode());
+
+ rdsService.createDbClusterParameterGroup(
+ "east-only-cpg", "aurora-postgresql16", "east", "us-east-1");
+ AwsException clusterGroupMissing = assertThrows(AwsException.class, () ->
+ rdsService.createDbCluster(
+ "west-cluster", "aurora-postgresql", "16.3", "admin", "secret",
+ "app", false, "east-only-cpg", null, null, false, "us-west-2"));
+ assertEquals("DBClusterParameterGroupNotFound", clusterGroupMissing.getErrorCode());
+
+ rdsService.deleteDbParameterGroup("regional-pg", "us-east-1");
+ rdsService.deleteDbClusterParameterGroup("regional-cpg", "us-east-1");
+ assertEquals("west", rdsService.getDbParameterGroup(
+ "regional-pg", "us-west-2").getDescription());
+ assertEquals("west", rdsService.getDbClusterParameterGroup(
+ "regional-cpg", "us-west-2").getDescription());
+ }
+
+ @Test
+ void rawLegacyParameterGroupsCannotBeClaimedByANonDefaultAccount() {
+ String defaultAccount = "123456789012";
+ String otherAccount = "222222222222";
+ RegionResolver otherResolver = new RegionResolver("us-east-1", otherAccount);
+ InMemoryStorage<String, DbParameterGroup> rawParameterGroups = new InMemoryStorage<>();
+ InMemoryStorage<String, DbClusterParameterGroup> rawClusterParameterGroups =
+ new InMemoryStorage<>();
+ rawParameterGroups.put("legacy-pg", new DbParameterGroup(
+ "legacy-pg", "postgres16", "legacy"));
+ rawClusterParameterGroups.put("legacy-cpg", new DbClusterParameterGroup(
+ "legacy-cpg", "aurora-postgresql16", "legacy"));
+ RdsService service = new RdsService(
+ containerManager, proxyManager, ec2Service, otherResolver, config,
+ new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new AccountAwareStorageBackend<>(rawParameterGroups, null, defaultAccount),
+ new AccountAwareStorageBackend<>(rawClusterParameterGroups, null, defaultAccount),
+ new InMemoryStorage<>());
+
+ assertEquals("DBParameterGroupNotFound", assertThrows(AwsException.class, () ->
+ service.getDbParameterGroup("legacy-pg", "us-east-1")).getErrorCode());
+ assertEquals("DBClusterParameterGroupNotFound", assertThrows(AwsException.class, () ->
+ service.getDbClusterParameterGroup("legacy-cpg", "us-east-1")).getErrorCode());
+ assertTrue(rawParameterGroups.get("legacy-pg").isPresent());
+ assertTrue(rawClusterParameterGroups.get("legacy-cpg").isPresent());
+ assertTrue(rawParameterGroups.get(otherAccount + "/us-east-1::legacy-pg").isEmpty());
+ assertTrue(rawClusterParameterGroups.get(
+ otherAccount + "/us-east-1::legacy-cpg").isEmpty());
+ }
+
+ @Test
+ void unfilteredGroupListsMigrateSafeRawLegacyStateForTheDefaultAccount() {
+ String accountId = "123456789012";
+ InMemoryStorage<String, DbSubnetGroup> rawSubnetGroups = new InMemoryStorage<>();
+ InMemoryStorage<String, DbParameterGroup> rawParameterGroups = new InMemoryStorage<>();
+ InMemoryStorage<String, DbClusterParameterGroup> rawClusterParameterGroups =
+ new InMemoryStorage<>();
+ DbSubnetGroup subnetGroup = new DbSubnetGroup(
+ "legacy-subnets", "legacy", "vpc-default", PROXY_SUBNET_IDS,
+ Map.of("subnet-default-a", "us-east-1a", "subnet-default-b", "us-east-1b"));
+ subnetGroup.setDbSubnetGroupArn(
+ "arn:aws:rds:us-east-1:" + accountId + ":subgrp:legacy-subnets");
+ rawSubnetGroups.put("legacy-subnets", subnetGroup);
+ rawParameterGroups.put("legacy-pg", new DbParameterGroup(
+ "legacy-pg", "postgres16", "legacy"));
+ rawClusterParameterGroups.put("legacy-cpg", new DbClusterParameterGroup(
+ "legacy-cpg", "aurora-postgresql16", "legacy"));
+ RdsService service = new RdsService(
+ containerManager, proxyManager, ec2Service, regionResolver, config,
+ new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new AccountAwareStorageBackend<>(rawParameterGroups, null, accountId),
+ new AccountAwareStorageBackend<>(rawClusterParameterGroups, null, accountId),
+ new AccountAwareStorageBackend<>(rawSubnetGroups, null, accountId));
+
+ assertTrue(service.listDbSubnetGroups(null, "us-east-1").stream()
+ .anyMatch(group -> "legacy-subnets".equals(group.getDbSubnetGroupName())));
+ assertTrue(service.listDbParameterGroups(null, "us-east-1").stream()
+ .anyMatch(group -> "legacy-pg".equals(group.getDbParameterGroupName())));
+ assertTrue(service.listDbClusterParameterGroups(null, "us-east-1").stream()
+ .anyMatch(group -> "legacy-cpg".equals(group.getDbClusterParameterGroupName())));
+ assertTrue(rawSubnetGroups.get("legacy-subnets").isEmpty());
+ assertTrue(rawParameterGroups.get("legacy-pg").isEmpty());
+ assertTrue(rawClusterParameterGroups.get("legacy-cpg").isEmpty());
+ assertTrue(rawSubnetGroups.get(accountId + "/us-east-1::legacy-subnets").isPresent());
+ assertTrue(rawParameterGroups.get(accountId + "/us-east-1::legacy-pg").isPresent());
+ assertTrue(rawClusterParameterGroups.get(accountId + "/us-east-1::legacy-cpg").isPresent());
+ }
+
+ @Test
+ void corruptCanonicalGroupStateFailsClosedAndCreateDoesNotOverwriteIt() {
+ String accountId = "123456789012";
+ InMemoryStorage<String, DbSubnetGroup> rawSubnetGroups = new InMemoryStorage<>();
+ InMemoryStorage<String, DbParameterGroup> rawParameterGroups = new InMemoryStorage<>();
+ InMemoryStorage<String, DbClusterParameterGroup> rawClusterParameterGroups =
+ new InMemoryStorage<>();
+ DbSubnetGroup wrongSubnetName = new DbSubnetGroup(
+ "other-subnets", "corrupt", "vpc-default", PROXY_SUBNET_IDS, Map.of());
+ wrongSubnetName.setDbSubnetGroupArn(
+ "arn:aws:rds:us-east-1:" + accountId + ":subgrp:expected-subnets");
+ DbParameterGroup wrongParameterName = new DbParameterGroup(
+ "other-pg", "postgres16", "corrupt");
+ wrongParameterName.setRegion("us-east-1");
+ DbParameterGroup legacyParameter = new DbParameterGroup(
+ "expected-pg", "postgres16", "legacy");
+ DbClusterParameterGroup wrongClusterParameterName = new DbClusterParameterGroup(
+ "other-cpg", "aurora-postgresql16", "corrupt");
+ wrongClusterParameterName.setRegion("us-east-1");
+ rawSubnetGroups.put(accountId + "/us-east-1::expected-subnets", wrongSubnetName);
+ rawParameterGroups.put(accountId + "/us-east-1::expected-pg", wrongParameterName);
+ rawParameterGroups.put(accountId + "/expected-pg", legacyParameter);
+ rawClusterParameterGroups.put(
+ accountId + "/us-east-1::expected-cpg", wrongClusterParameterName);
+ RdsService service = new RdsService(
+ containerManager, proxyManager, ec2Service, regionResolver, config,
+ new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new AccountAwareStorageBackend<>(rawParameterGroups, null, accountId),
+ new AccountAwareStorageBackend<>(rawClusterParameterGroups, null, accountId),
+ new AccountAwareStorageBackend<>(rawSubnetGroups, null, accountId));
+
+ assertThrows(AwsException.class, () ->
+ service.getDbSubnetGroup("expected-subnets", "us-east-1"));
+ assertThrows(AwsException.class, () ->
+ service.getDbParameterGroup("expected-pg", "us-east-1"));
+ assertThrows(AwsException.class, () ->
+ service.getDbClusterParameterGroup("expected-cpg", "us-east-1"));
+ assertEquals("DBSubnetGroupAlreadyExists", assertThrows(AwsException.class, () ->
+ service.createDbSubnetGroup(
+ "expected-subnets", "new", PROXY_SUBNET_IDS, "us-east-1"))
+ .getErrorCode());
+ assertEquals("DBParameterGroupAlreadyExists", assertThrows(AwsException.class, () ->
+ service.createDbParameterGroup(
+ "expected-pg", "postgres16", "new", "us-east-1"))
+ .getErrorCode());
+ assertEquals("DBParameterGroupAlreadyExists", assertThrows(AwsException.class, () ->
+ service.createDbClusterParameterGroup(
+ "expected-cpg", "aurora-postgresql16", "new", "us-east-1"))
+ .getErrorCode());
+ assertSame(wrongSubnetName, rawSubnetGroups.get(
+ accountId + "/us-east-1::expected-subnets").orElseThrow());
+ assertSame(wrongParameterName, rawParameterGroups.get(
+ accountId + "/us-east-1::expected-pg").orElseThrow());
+ assertSame(legacyParameter, rawParameterGroups.get(
+ accountId + "/expected-pg").orElseThrow());
+ assertSame(wrongClusterParameterName, rawClusterParameterGroups.get(
+ accountId + "/us-east-1::expected-cpg").orElseThrow());
+ }
+
@Test
void createDbClusterParameterGroupRejectsDuplicate() {
rdsService.createDbClusterParameterGroup("cpg1", "aurora-postgresql16", "desc");
@@ -931,12 +1194,15 @@ class RdsServiceTest {
@Test
void createDbInstanceMultiAzRequiresSubnetGroupCoverageAcrossAvailabilityZones() {
StorageBackend<String, DbSubnetGroup> subnetGroups = new InMemoryStorage<>();
- subnetGroups.put("single-az-group", new DbSubnetGroup(
+ DbSubnetGroup singleAzGroup = new DbSubnetGroup(
"single-az-group",
"desc",
"vpc-default",
List.of("subnet-a", "subnet-b"),
- Map.of("subnet-a", "us-east-1a", "subnet-b", "us-east-1a")));
+ Map.of("subnet-a", "us-east-1a", "subnet-b", "us-east-1a"));
+ singleAzGroup.setDbSubnetGroupArn(
+ "arn:aws:rds:us-east-1:123456789012:subgrp:single-az-group");
+ subnetGroups.put("single-az-group", singleAzGroup);
RdsService service = newService(containerManager, proxyManager,
new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>(), subnetGroups);
@@ -947,7 +1213,7 @@ class RdsServiceTest {
20, false, null, "single-az-group", null, null, true));
assertEquals("DBSubnetGroupDoesNotCoverEnoughAZs", exception.getErrorCode());
- verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any());
+ verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
@@ -958,7 +1224,7 @@ class RdsServiceTest {
null, null, "us-east-1a", true));
assertEquals("InvalidParameterCombination", exception.getErrorCode());
- verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any());
+ verify(containerManager, never()).start(any(), any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
@@ -1064,13 +1330,13 @@ class RdsServiceTest {
}
@Test
- void restorePersistedRuntimeRestartsStandaloneInstanceWithSameVolumeAndProxyPort() {
+ void restorePersistedRuntimeReusesLegacyStandaloneStorageAndProxyPort() {
StorageBackend<String, DbInstance> instances = new InMemoryStorage<>();
StorageBackend<String, DbCluster> clusters = new InMemoryStorage<>();
StorageBackend<String, DbParameterGroup> parameterGroups = new InMemoryStorage<>();
StorageBackend<String, DbClusterParameterGroup> clusterParameterGroups = new InMemoryStorage<>();
- when(containerManager.start(any(), any(), any(), any(), any(), any(), any()))
+ when(containerManager.start(any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new RdsContainerHandle("initial-container", "mydb", "localhost", 5432));
RdsService initialService = newService(containerManager, proxyManager,
@@ -1081,10 +1347,12 @@ class RdsServiceTest {
String persistedVolumeId = created.getVolumeId();
int persistedProxyPort = created.getProxyPort();
+ created.setContainerStorageResourceId(null);
+ created.setDockerVolumeName("floci-rds-" + persistedVolumeId);
RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class);
RdsProxyManager restoredProxyManager = mock(RdsProxyManager.class);
- when(restoredContainerManager.start(any(), any(), any(), any(), any(), any(), any()))
+ when(restoredContainerManager.start(any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new RdsContainerHandle("restored-container", "mydb", "127.0.0.1", 15432));
RdsService restoredService = newService(restoredContainerManager, restoredProxyManager,
@@ -1093,6 +1361,7 @@ class RdsServiceTest {
DbInstance restored = restoredService.getDbInstance("mydb");
assertEquals(persistedVolumeId, restored.getVolumeId());
+ assertEquals("mydb", restored.getContainerStorageResourceId());
assertEquals("floci-rds-" + persistedVolumeId, restored.getDockerVolumeName());
assertEquals(persistedProxyPort, restored.getProxyPort());
assertEquals(persistedProxyPort, restored.getEndpoint().port());
@@ -1100,11 +1369,19 @@ class RdsServiceTest {
assertEquals("127.0.0.1", restored.getContainerHost());
assertEquals(15432, restored.getContainerPort());
- verify(restoredContainerManager).start(eq("mydb"), eq(persistedVolumeId),
- eq(DatabaseEngine.POSTGRES), eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app"));
- verify(restoredProxyManager).startProxy(eq("mydb"), eq(DatabaseEngine.POSTGRES),
+ verify(restoredContainerManager).start(
+ eq(restored.getDbInstanceArn()), eq("mydb"),
+ eq(restored.getContainerStorageResourceId()),
+ eq(restored.getDockerVolumeName()), eq(DatabaseEngine.POSTGRES),
+ eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app"));
+ verify(restoredProxyManager).startProxy(
+ eq("rds-resource:" + restored.getDbInstanceArn()), eq(DatabaseEngine.POSTGRES),
eq(false), eq(persistedProxyPort), eq("127.0.0.1"), eq(15432),
eq("admin"), eq("secret"), eq("app"), any());
+
+ restoredService.deleteDbInstance("mydb");
+ verify(restoredContainerManager).removeVolume(
+ restored.getDbInstanceArn(), "mydb", "floci-rds-" + persistedVolumeId);
}
@Test
@@ -1114,7 +1391,7 @@ class RdsServiceTest {
StorageBackend<String, DbParameterGroup> parameterGroups = new InMemoryStorage<>();
StorageBackend<String, DbClusterParameterGroup> clusterParameterGroups = new InMemoryStorage<>();
- when(containerManager.start(any(), any(), any(), any(), any(), any(), any()))
+ when(containerManager.start(any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new RdsContainerHandle("initial-cluster-container", "cluster1", "localhost", 5432));
RdsService initialService = newService(containerManager, proxyManager,
@@ -1127,7 +1404,7 @@ class RdsServiceTest {
RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class);
RdsProxyManager restoredProxyManager = mock(RdsProxyManager.class);
- when(restoredContainerManager.start(any(), any(), any(), any(), any(), any(), any()))
+ when(restoredContainerManager.start(any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new RdsContainerHandle("restored-cluster-container", "cluster1", "127.0.0.1", 15432));
RdsService restoredService = newService(restoredContainerManager, restoredProxyManager,
@@ -1145,16 +1422,2310 @@ class RdsServiceTest {
assertEquals("127.0.0.1", restoredMember.getContainerHost());
assertEquals(15432, restoredMember.getContainerPort());
- verify(restoredContainerManager).start(eq("cluster1"), eq(cluster.getVolumeId()),
- eq(DatabaseEngine.POSTGRES), eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app"));
- verify(restoredProxyManager).startProxy(eq("cluster1"), eq(DatabaseEngine.POSTGRES),
+ verify(restoredContainerManager).start(
+ eq(restoredCluster.getDbClusterArn()), eq("cluster1"),
+ eq(restoredCluster.getContainerStorageResourceId()),
+ eq(restoredCluster.getDockerVolumeName()), eq(DatabaseEngine.POSTGRES),
+ eq("postgres:16.3-alpine"), eq("admin"), eq("secret"), eq("app"));
+ verify(restoredProxyManager).startProxy(
+ eq("rds-resource:" + restoredCluster.getDbClusterArn()), eq(DatabaseEngine.POSTGRES),
eq(false), eq(cluster.getProxyPort()), eq("127.0.0.1"), eq(15432),
eq("admin"), eq("secret"), eq("app"), any());
- verify(restoredProxyManager).startProxy(eq("member1"), eq(DatabaseEngine.POSTGRES),
+ verify(restoredProxyManager).startProxy(
+ eq("rds-resource:" + restoredMember.getDbInstanceArn()), eq(DatabaseEngine.POSTGRES),
eq(false), eq(member.getProxyPort()), eq("127.0.0.1"), eq(15432),
eq("admin"), eq("secret"), eq("app"), any());
}
+ @Test
+ void failedInstanceRestoreClearsRuntimeStateAndReleasesItsEndpointPort() {
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ instances.put("broken", persistedInstance("broken", "123456789012", "secret", 7000));
+ RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class);
+ RdsProxyManager restoredProxyManager = mock(RdsProxyManager.class);
+ String runtimeId = "arn:aws:rds:us-east-1:123456789012:db:broken";
+ RdsContainerHandle restoredHandle = new RdsContainerHandle(
+ "restored-container", runtimeId, "broken", "127.0.0.1", 15432);
+ RdsContainerHandle replacementHandle = new RdsContainerHandle(
+ "replacement-container", "arn:aws:rds:us-east-1:123456789012:db:replacement",
+ "replacement", "127.0.0.1", 15433);
+ when(restoredContainerManager.start(
+ any(), any(), any(), any(), any(), any(), any(), any(), any()))
+ .thenReturn(restoredHandle, replacementHandle);
+ org.mockito.Mockito.doThrow(new IllegalStateException("relay failed"))
+ .doNothing()
+ .doNothing()
+ .when(restoredProxyManager).startProxy(
+ any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
+ any(), any(), any(), any());
+ org.mockito.Mockito.doThrow(new IllegalStateException("cleanup failed"))
+ .doNothing()
+ .doNothing()
+ .when(restoredProxyManager).stopProxy(any());
+ org.mockito.Mockito.doThrow(new IllegalStateException("restore container cleanup failed"))
+ .doThrow(new IllegalStateException("delete container cleanup failed"))
+ .doNothing()
+ .when(restoredContainerManager).stop(org.mockito.ArgumentMatchers.argThat(
+ handle -> runtimeId.equals(handle.getRuntimeId())));
+ RdsService restoredService = newService(
+ restoredContainerManager, restoredProxyManager, instances,
+ new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ restoredService.restorePersistedRuntime();
+
+ DbInstance failed = restoredService.getDbInstance("broken");
+ assertEquals(DbInstanceStatus.FAILED, failed.getStatus());
+ assertNull(failed.getEndpoint());
+ assertEquals("restored-container", failed.getContainerId());
+ assertNull(failed.getContainerHost());
+ assertEquals(0, failed.getContainerPort());
+ assertEquals(0, failed.getProxyPort());
+
+ assertThrows(IllegalStateException.class, () ->
+ restoredService.deleteDbInstance("broken"));
+ assertEquals(DbInstanceStatus.DELETING,
+ restoredService.getDbInstance("broken").getStatus());
+ verify(restoredContainerManager, never()).removeVolume(any(), any(), any());
+
+ assertDoesNotThrow(() -> restoredService.deleteDbInstance("broken"));
+ assertThrows(AwsException.class, () -> restoredService.getDbInstance("broken"));
+ verify(restoredContainerManager, times(3)).stop(
+ org.mockito.ArgumentMatchers.argThat(
+ handle -> runtimeId.equals(handle.getRuntimeId())));
+ verify(restoredContainerManager).removeVolume(any(), any(), any());
+
+ DbInstance replacement = restoredService.createDbInstance(
+ "replacement", "postgres", "16.3", "admin", "secret", "app",
+ "db.t3.micro", 20, false, null, null, null);
+ assertEquals(7000, replacement.getEndpoint().port());
+ }
+
+ @Test
+ void failedInstanceStartPreservesPersistedContainerIdentityForDeletion() {
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ DbInstance persisted = persistedInstance(
+ "broken", "123456789012", "secret", 7000);
+ persisted.setContainerId("persisted-container");
+ instances.put("broken", persisted);
+ RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class);
+ when(restoredContainerManager.start(
+ any(), any(), any(), any(), any(), any(), any(), any(), any()))
+ .thenThrow(new IllegalStateException("Docker start failed"));
+ RdsService restoredService = newService(
+ restoredContainerManager, mock(RdsProxyManager.class), instances,
+ new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ restoredService.restorePersistedRuntime();
+
+ DbInstance failed = restoredService.getDbInstance("broken");
+ assertEquals(DbInstanceStatus.FAILED, failed.getStatus());
+ assertNull(failed.getEndpoint());
+ assertEquals("persisted-container", failed.getContainerId());
+ assertNull(failed.getContainerHost());
+ assertEquals(0, failed.getContainerPort());
+
+ assertDoesNotThrow(() -> restoredService.deleteDbInstance("broken"));
+ verify(restoredContainerManager).stop(
+ org.mockito.ArgumentMatchers.argThat(handle ->
+ "persisted-container".equals(handle.getContainerId())
+ && persisted.getDbInstanceArn().equals(handle.getRuntimeId())));
+ assertThrows(AwsException.class, () -> restoredService.getDbInstance("broken"));
+ }
+
+ @Test
+ void restorePortExhaustionMarksEachUnrestorableInstanceAndContinues() {
+ when(config.services().rds().mock()).thenReturn(true);
+ when(config.services().rds().proxyBasePort()).thenReturn(7000);
+ when(config.services().rds().proxyMaxPort()).thenReturn(7000);
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ instances.put("first", persistedInstance(
+ "first", "123456789012", "secret", 7000));
+ instances.put("second", persistedInstance(
+ "second", "123456789012", "secret", 7000));
+ RdsService restoredService = newService(
+ containerManager, proxyManager, instances, new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ assertDoesNotThrow(restoredService::restorePersistedRuntime);
+
+ Collection<DbInstance> restored = restoredService.listDbInstances(null);
+ assertEquals(2, restored.size());
+ assertEquals(1, restored.stream()
+ .filter(instance -> instance.getStatus() == DbInstanceStatus.AVAILABLE)
+ .count());
+ DbInstance failed = restored.stream()
+ .filter(instance -> instance.getStatus() == DbInstanceStatus.FAILED)
+ .findFirst()
+ .orElseThrow();
+ assertNull(failed.getEndpoint());
+ assertEquals(0, failed.getProxyPort());
+ }
+
+ @Test
+ void failedClusterRestoreClearsRuntimeStateAndReleasesItsEndpointPort() {
+ InMemoryStorage<String, DbCluster> clusters = new InMemoryStorage<>();
+ clusters.put("cluster1", persistedCluster("123456789012", "secret", 7000));
+ RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class);
+ RdsProxyManager restoredProxyManager = mock(RdsProxyManager.class);
+ String runtimeId = "arn:aws:rds:us-east-1:123456789012:cluster:cluster1";
+ RdsContainerHandle restoredHandle = new RdsContainerHandle(
+ "restored-container", runtimeId, "cluster1", "127.0.0.1", 15432);
+ RdsContainerHandle replacementHandle = new RdsContainerHandle(
+ "replacement-container", "arn:aws:rds:us-east-1:123456789012:cluster:replacement",
+ "replacement", "127.0.0.1", 15433);
+ when(restoredContainerManager.start(
+ any(), any(), any(), any(), any(), any(), any(), any(), any()))
+ .thenReturn(restoredHandle, replacementHandle);
+ org.mockito.Mockito.doThrow(new IllegalStateException("relay failed"))
+ .doNothing()
+ .when(restoredProxyManager).startProxy(
+ any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
+ any(), any(), any(), any());
+ org.mockito.Mockito.doThrow(new IllegalStateException("restore container cleanup failed"))
+ .doThrow(new IllegalStateException("delete container cleanup failed"))
+ .doNothing()
+ .when(restoredContainerManager).stop(org.mockito.ArgumentMatchers.argThat(
+ handle -> runtimeId.equals(handle.getRuntimeId())));
+ RdsService restoredService = newService(
+ restoredContainerManager, restoredProxyManager, new InMemoryStorage<>(),
+ clusters, new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>());
+
+ restoredService.restorePersistedRuntime();
+
+ DbCluster failed = restoredService.getDbCluster("cluster1");
+ assertEquals(DbInstanceStatus.FAILED, failed.getStatus());
+ assertNull(failed.getEndpoint());
+ assertNull(failed.getReaderEndpoint());
+ assertEquals("restored-container", failed.getContainerId());
+ assertNull(failed.getContainerHost());
+ assertEquals(0, failed.getContainerPort());
+ assertEquals(0, failed.getProxyPort());
+
+ assertThrows(IllegalStateException.class, () ->
+ restoredService.deleteDbCluster("cluster1"));
+ assertEquals(DbInstanceStatus.DELETING,
+ restoredService.getDbCluster("cluster1").getStatus());
+ verify(restoredContainerManager, never()).removeVolume(any(), any(), any());
+
+ assertDoesNotThrow(() -> restoredService.deleteDbCluster("cluster1"));
+ assertThrows(AwsException.class, () -> restoredService.getDbCluster("cluster1"));
+ verify(restoredContainerManager, times(3)).stop(
+ org.mockito.ArgumentMatchers.argThat(
+ handle -> runtimeId.equals(handle.getRuntimeId())));
+ verify(restoredContainerManager).removeVolume(any(), any(), any());
+
+ DbCluster replacement = restoredService.createDbCluster(
+ "replacement", "aurora-postgresql", "16.3", "admin", "secret",
+ "app", false, null);
+ assertEquals(7000, replacement.getEndpoint().port());
+ }
+
+ @Test
+ void createDbProxyPopulatesEndpointArnAndDefaultPort() {
+ DbProxy proxy = rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of("sg-a"), PROXY_AUTH, Map.of());
+
+ assertEquals("app-proxy", proxy.getDbProxyName());
+ assertEquals("available", proxy.getStatus());
+ assertEquals(5432, proxy.getProxyPort()); // POSTGRESQL default listener port
+ assertNotNull(proxy.getDbProxyResourceId());
+ assertTrue(proxy.getDbProxyResourceId().startsWith("prx-"));
+ assertEquals("arn:aws:rds:us-east-1:123456789012:db-proxy:" + proxy.getDbProxyResourceId(),
+ proxy.getDbProxyArn());
+ assertEquals("vpc-default", proxy.getVpcId());
+ assertEquals(1, rdsService.listDbProxies("app-proxy").size());
+ DbProxyTargetGroup targetGroup = rdsService.describeDbProxyTargetGroups("app-proxy").iterator().next();
+ assertEquals("default", targetGroup.getTargetGroupName());
+ assertTrue(targetGroup.getTargets().isEmpty());
+ assertTrue(targetGroup.getTargetGroupArn().contains(":target-group:prx-tg-"));
+ }
+
+ @Test
+ void createDbProxyRejectsDuplicate() {
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of()));
+
+ assertEquals("DBProxyAlreadyExistsFault", exception.getErrorCode());
+ }
+
+ @Test
+ void createDbProxyReservesDistinctInternalListenerPorts() {
+ // Listener ports must never collide even though externally routing multiple same-engine
+ // proxy hostnames remains a separate concern.
+ DbProxy first = rdsService.createDbProxy("proxy-a", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ DbProxy second = rdsService.createDbProxy("proxy-b", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+
+ assertEquals(5432, first.getProxyPort()); // first proxy keeps the clean engine default
+ assertNotEquals(first.getProxyPort(), second.getProxyPort());
+ }
+
+ @Test
+ void registerDbProxyTargetsCreatesDefaultTargetGroupForCluster() {
+ when(config.services().rds().mock()).thenReturn(true);
+ rdsService.createDbCluster("cluster1", "aurora-postgresql", "16.3",
+ "admin", "secret", "app", false, null);
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+
+ DbProxyTargetGroup tg = rdsService.registerDbProxyTargets("app-proxy", null,
+ List.of("cluster1"), List.of(), 90, 40);
+
+ assertEquals("app-proxy", tg.getDbProxyName());
+ assertEquals("default", tg.getTargetGroupName()); // blank TargetGroupName defaults to "default"
+ assertEquals(90, tg.getMaxConnectionsPercent());
+ assertEquals(40, tg.getMaxIdleConnectionsPercent());
+ assertEquals(1, tg.getTargets().size());
+ DbProxyTarget target = tg.getTargets().get(0);
+ assertEquals("TRACKED_CLUSTER", target.getType());
+ assertEquals("cluster1", target.getRdsResourceId());
+ // The registered target group and target are read back through the describe APIs.
+ assertEquals(1, rdsService.describeDbProxyTargetGroups("app-proxy").size());
+ assertEquals(1, rdsService.describeDbProxyTargets("app-proxy", "default").size());
+ }
+
+ @Test
+ void createDbProxyValidatesRequiredInputsAndTimeout() {
+ AwsException missingName = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy(null, "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of()));
+ assertEquals("InvalidParameterValue", missingName.getErrorCode());
+
+ AwsException invalidEngine = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy("app-proxy", "ORACLE", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of()));
+ assertEquals("InvalidParameterValue", invalidEngine.getErrorCode());
+
+ AwsException missingRole = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, null,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of()));
+ assertEquals("InvalidParameterValue", missingRole.getErrorCode());
+
+ AwsException missingSubnets = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ List.of(), List.of(), PROXY_AUTH, Map.of()));
+ assertEquals("InvalidParameterValue", missingSubnets.getErrorCode());
+
+ AwsException oneSubnet = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ List.of("subnet-a"), List.of(), PROXY_AUTH, Map.of()));
+ assertEquals("InvalidParameterValue", oneSubnet.getErrorCode());
+ assertEquals(400, oneSubnet.getHttpStatus());
+ assertTrue(oneSubnet.getMessage().contains("at least two distinct subnet IDs"));
+ assertTrue(rdsService.listDbProxies(null).isEmpty());
+
+ AwsException duplicateSubnets = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ List.of("subnet-a", "subnet-a"), List.of(), PROXY_AUTH, Map.of()));
+ assertEquals("InvalidParameterValue", duplicateSubnets.getErrorCode());
+
+ AwsException invalidTimeout = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, 0, false, Map.of(), "us-east-1"));
+ assertEquals("InvalidParameterValue", invalidTimeout.getErrorCode());
+
+ AwsException missingSubnet = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ List.of("subnet-missing-a", "subnet-missing-b"),
+ List.of(), PROXY_AUTH, Map.of()));
+ assertEquals("InvalidSubnet", missingSubnet.getErrorCode());
+
+ when(ec2Service.describeSubnets(eq("us-east-1"),
+ eq(List.of("subnet-same-az-a", "subnet-same-az-b")), any()))
+ .thenReturn(List.of(
+ subnet("subnet-same-az-a", "vpc-a", "us-east-1a"),
+ subnet("subnet-same-az-b", "vpc-a", "us-east-1a")));
+ AwsException sameAvailabilityZone = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ List.of("subnet-same-az-a", "subnet-same-az-b"),
+ List.of(), PROXY_AUTH, Map.of()));
+ assertEquals("InvalidSubnet", sameAvailabilityZone.getErrorCode());
+
+ when(ec2Service.describeSubnets(eq("us-east-1"),
+ eq(List.of("subnet-vpc-a", "subnet-vpc-b")), any()))
+ .thenReturn(List.of(
+ subnet("subnet-vpc-a", "vpc-a", "us-east-1a"),
+ subnet("subnet-vpc-b", "vpc-b", "us-east-1b")));
+ AwsException mixedVpc = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ List.of("subnet-vpc-a", "subnet-vpc-b"),
+ List.of(), PROXY_AUTH, Map.of()));
+ assertEquals("InvalidSubnet", mixedVpc.getErrorCode());
+ }
+
+ @Test
+ void createDbProxyValidatesAndPersistsDefaultAuthScheme() {
+ DbProxy iamProxy = rdsService.createDbProxy(
+ "iam-proxy", "POSTGRESQL", true, true, "IAM_AUTH", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), List.of(), 1800, false, Map.of(), "us-east-1");
+
+ assertEquals("IAM_AUTH", iamProxy.getDefaultAuthScheme());
+ assertTrue(iamProxy.isIamAuth());
+ assertTrue(iamProxy.getAuth().isEmpty());
+ assertNotNull(iamProxy.getUpdatedAt());
+
+ AwsException missingAuth = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy(
+ "none-proxy", "POSTGRESQL", true, false, "NONE", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), List.of(), 1800, false, Map.of(), "us-east-1"));
+ assertEquals("InvalidParameterValue", missingAuth.getErrorCode());
+
+ AwsException invalidScheme = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy(
+ "bad-proxy", "POSTGRESQL", true, false, "PASSWORD", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, 1800, false, Map.of(), "us-east-1"));
+ assertEquals("InvalidParameterValue", invalidScheme.getErrorCode());
+
+ AwsException sqlServerIamAuth = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy(
+ "sqlserver-proxy", "SQLSERVER", true, true, "IAM_AUTH", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), List.of(), 1800, false, Map.of(), "us-east-1"));
+ assertEquals("InvalidParameterValue", sqlServerIamAuth.getErrorCode());
+
+ AwsException blankScheme = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy(
+ "blank-proxy", "POSTGRESQL", true, false, "", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, 1800, false,
+ Map.of(), "us-east-1"));
+ assertEquals("InvalidParameterValue", blankScheme.getErrorCode());
+ }
+
+ @Test
+ void createAndModifyDbProxyValidateUserAuthConfig() {
+ List<DbProxyAuth> invalidEntries = List.of(
+ new DbProxyAuth("PASSWORD", PROXY_AUTH.getFirst().getSecretArn(),
+ "DISABLED", null, null),
+ new DbProxyAuth("SECRETS", PROXY_AUTH.getFirst().getSecretArn(),
+ "OPTIONAL", null, null),
+ new DbProxyAuth("SECRETS", PROXY_AUTH.getFirst().getSecretArn(),
+ "ENABLED", null, null),
+ new DbProxyAuth("SECRETS", PROXY_AUTH.getFirst().getSecretArn(),
+ "DISABLED", "KERBEROS", null),
+ new DbProxyAuth("SECRETS", PROXY_AUTH.getFirst().getSecretArn(),
+ "DISABLED", null, ""),
+ new DbProxyAuth("SECRETS", "too-short", "DISABLED", null, null),
+ proxyAuthWithUserName(""),
+ proxyAuthWithUserName("u".repeat(129)));
+
+ for (DbProxyAuth invalidEntry : invalidEntries) {
+ AwsException exception = assertThrows(AwsException.class, () ->
+ rdsService.createDbProxy(
+ "invalid-auth-proxy", "POSTGRESQL", true, false, "NONE",
+ PROXY_ROLE_ARN, PROXY_SUBNET_IDS, List.of(), List.of(invalidEntry),
+ 1800, false, Map.of(), "us-east-1"));
+ assertEquals("InvalidParameterValue", exception.getErrorCode());
+ }
+
+ DbProxyAuth longDescription = new DbProxyAuth(
+ "SECRETS", PROXY_AUTH.getFirst().getSecretArn(), "DISABLED", null,
+ "d".repeat(1_001));
+ assertThrows(AwsException.class, () -> rdsService.createDbProxy(
+ "long-description-proxy", "POSTGRESQL", true, false, "NONE",
+ PROXY_ROLE_ARN, PROXY_SUBNET_IDS, List.of(), List.of(longDescription),
+ 1800, false, Map.of(), "us-east-1"));
+
+ List<DbProxyAuth> tooManyEntries = java.util.Collections.nCopies(201, PROXY_AUTH.getFirst());
+ assertThrows(AwsException.class, () -> rdsService.createDbProxy(
+ "too-many-auth-proxy", "POSTGRESQL", true, false, "NONE",
+ PROXY_ROLE_ARN, PROXY_SUBNET_IDS, List.of(), tooManyEntries,
+ 1800, false, Map.of(), "us-east-1"));
+
+ DbProxyAuth sqlServerAuth = new DbProxyAuth(
+ "SECRETS", PROXY_AUTH.getFirst().getSecretArn(), "ENABLED",
+ "SQL_SERVER_AUTHENTICATION", "SQL Server credentials");
+ DbProxy sqlServerProxy = rdsService.createDbProxy(
+ "sqlserver-proxy", "SQLSERVER", true, false, "NONE", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), List.of(sqlServerAuth),
+ 1800, false, Map.of(), "us-east-1");
+ assertEquals("ENABLED", sqlServerProxy.getAuth().getFirst().getIamAuth());
+ assertTrue(sqlServerProxy.isIamAuth());
+
+ DbProxyAuth sqlServerAuthDisabled = new DbProxyAuth(
+ "SECRETS", PROXY_AUTH.getFirst().getSecretArn(), "DISABLED",
+ "SQL_SERVER_AUTHENTICATION", "SQL Server credentials");
+ DbProxy sqlServerToModify = rdsService.createDbProxy(
+ "sqlserver-modify-proxy", "SQLSERVER", true, false, "NONE", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), List.of(sqlServerAuthDisabled),
+ 1800, false, Map.of(), "us-east-1");
+ assertFalse(sqlServerToModify.isIamAuth());
+ DbProxy sqlServerModified = rdsService.modifyDbProxy(
+ "sqlserver-modify-proxy", null, List.of(sqlServerAuth),
+ null, null, null, null, null, null, "us-east-1");
+ assertTrue(sqlServerModified.isIamAuth());
+
+ DbProxy created = rdsService.createDbProxy(
+ "modify-auth-proxy", "POSTGRESQL", true, false, "NONE", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH,
+ 1800, false, Map.of(), "us-east-1");
+ AwsException invalidModify = assertThrows(AwsException.class, () ->
+ rdsService.modifyDbProxy(
+ created.getDbProxyName(), null, List.of(invalidEntries.getFirst()),
+ null, null, null, null, null, null, "us-east-1"));
+ assertEquals("InvalidParameterValue", invalidModify.getErrorCode());
+ assertEquals("SECRETS", rdsService.getDbProxy(
+ created.getDbProxyName(), "us-east-1").getAuth().getFirst().getAuthScheme());
+ }
+
+ @Test
+ void modifyDbProxyIsCopyOnWriteAndPreservesIdentity() {
+ DbProxy created = rdsService.createDbProxy(
+ "app-proxy", "POSTGRESQL", true, false, "NONE", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of("sg-old"), PROXY_AUTH,
+ 1800, false, Map.of("owner", "old"), "us-east-1");
+ Instant originalUpdatedAt = created.getUpdatedAt();
+
+ DbProxy modified = rdsService.modifyDbProxy(
+ "app-proxy", "NONE", PROXY_AUTH, false, 900, true,
+ PROXY_ROLE_ARN, List.of("sg-new"), Map.of("owner", "new"), "us-east-1");
+
+ assertEquals(created.getDbProxyArn(), modified.getDbProxyArn());
+ assertEquals(created.getDbProxyResourceId(), modified.getDbProxyResourceId());
+ assertEquals(created.getEndpoint(), modified.getEndpoint());
+ assertEquals(created.getProxyPort(), modified.getProxyPort());
+ assertEquals(created.getCreatedAt(), modified.getCreatedAt());
+ assertFalse(modified.isRequireTls());
+ assertEquals(900, modified.getIdleClientTimeout());
+ assertTrue(modified.isDebugLogging());
+ assertEquals(List.of("sg-new"), modified.getVpcSecurityGroupIds());
+ assertEquals(Map.of("owner", "new"), modified.getTags());
+ assertFalse(modified.getUpdatedAt().isBefore(originalUpdatedAt));
+
+ Instant modifiedAt = modified.getUpdatedAt();
+ DbProxy unchanged = rdsService.modifyDbProxy(
+ "app-proxy", "NONE", PROXY_AUTH, false, 900, true,
+ PROXY_ROLE_ARN, List.of("sg-new"), Map.of("owner", "new"), "us-east-1");
+ assertSame(modified, unchanged);
+ assertEquals(modifiedAt, unchanged.getUpdatedAt());
+ }
+
+ @Test
+ void createDbProxyPreservesOriginalFailureWhenProxyCleanupFails() {
+ InMemoryStorage<String, DbProxy> proxies = spy(new InMemoryStorage<>());
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = spy(new InMemoryStorage<>());
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+ String proxyKey = "us-east-1::first-proxy";
+ IllegalStateException persistenceFailure =
+ new IllegalStateException("simulated target-group persistence failure");
+ IllegalStateException cleanupFailure =
+ new IllegalStateException("simulated proxy cleanup failure");
+ doThrow(persistenceFailure).when(targetGroups).put(eq(proxyKey), any());
+ doThrow(cleanupFailure).doCallRealMethod().when(proxies).delete(proxyKey);
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
+ service.createDbProxy(
+ "first-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of()));
+
+ assertSame(persistenceFailure, thrown);
+ assertTrue(List.of(thrown.getSuppressed()).contains(cleanupFailure));
+ verify(targetGroups).delete(proxyKey);
+ DbProxy first = proxies.get(proxyKey).orElseThrow();
+ DbProxy second = service.createDbProxy(
+ "second-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ assertNotEquals(first.getProxyPort(), second.getProxyPort());
+
+ service.deleteDbProxy("first-proxy", "us-east-1");
+ DbProxy third = service.createDbProxy(
+ "third-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ assertEquals(first.getProxyPort(), third.getProxyPort());
+ }
+
+ @Test
+ void createDbProxyContinuesCleanupWhenTargetGroupCleanupFails() {
+ InMemoryStorage<String, DbProxy> proxies = spy(new InMemoryStorage<>());
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = spy(new InMemoryStorage<>());
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+ String proxyKey = "us-east-1::first-proxy";
+ IllegalStateException persistenceFailure =
+ new IllegalStateException("simulated post-mutation persistence failure");
+ IllegalStateException cleanupFailure =
+ new IllegalStateException("simulated post-mutation cleanup failure");
+ doAnswer(invocation -> {
+ invocation.callRealMethod();
+ throw persistenceFailure;
+ }).doCallRealMethod().when(targetGroups).put(eq(proxyKey), any());
+ doAnswer(invocation -> {
+ invocation.callRealMethod();
+ throw cleanupFailure;
+ }).doCallRealMethod().when(targetGroups).delete(proxyKey);
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
+ service.createDbProxy(
+ "first-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of()));
+
+ assertSame(persistenceFailure, thrown);
+ assertTrue(List.of(thrown.getSuppressed()).contains(cleanupFailure));
+ assertTrue(proxies.get(proxyKey).isEmpty());
+ assertTrue(targetGroups.get(proxyKey).isEmpty());
+ DbProxy replacement = service.createDbProxy(
+ "replacement-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ assertEquals(5432, replacement.getProxyPort());
+ }
+
+ @Test
+ void createDbProxyRestoresRetryOwnerWhenTargetGroupCleanupFailsBeforeMutation() {
+ InMemoryStorage<String, DbProxy> proxies = spy(new InMemoryStorage<>());
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = spy(new InMemoryStorage<>());
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+ String proxyKey = "us-east-1::first-proxy";
+ IllegalStateException persistenceFailure =
+ new IllegalStateException("simulated post-mutation persistence failure");
+ IllegalStateException cleanupFailure =
+ new IllegalStateException("simulated pre-mutation cleanup failure");
+ doAnswer(invocation -> {
+ invocation.callRealMethod();
+ throw persistenceFailure;
+ }).doCallRealMethod().when(targetGroups).put(eq(proxyKey), any());
+ doThrow(cleanupFailure).doCallRealMethod().when(targetGroups).delete(proxyKey);
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
+ service.createDbProxy(
+ "first-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of()));
+
+ assertSame(persistenceFailure, thrown);
+ assertTrue(List.of(thrown.getSuppressed()).contains(cleanupFailure));
+ DbProxy first = proxies.get(proxyKey).orElseThrow();
+ assertTrue(targetGroups.get(proxyKey).isPresent());
+ DbProxy second = service.createDbProxy(
+ "second-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ assertNotEquals(first.getProxyPort(), second.getProxyPort());
+
+ service.deleteDbProxy("first-proxy", "us-east-1");
+ DbProxy third = service.createDbProxy(
+ "third-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ assertEquals(first.getProxyPort(), third.getProxyPort());
+ }
+
+ @Test
+ void modifyDbProxyPersistenceFailureLeavesStoredStateUntouched() {
+ InMemoryStorage<String, DbProxy> proxies = spy(new InMemoryStorage<>());
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "abc", 5432);
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "abc");
+ proxies.put("us-east-1::app-proxy", proxy);
+ targetGroups.put("us-east-1::app-proxy", targetGroup);
+ IllegalStateException persistenceFailure =
+ new IllegalStateException("simulated post-mutation persistence failure");
+ doAnswer(invocation -> {
+ invocation.callRealMethod();
+ throw persistenceFailure;
+ }).doCallRealMethod().when(proxies).put(eq("us-east-1::app-proxy"), any());
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
+ service.modifyDbProxy(
+ "app-proxy", null, null, null, null, true,
+ null, null, null, "us-east-1"));
+
+ assertSame(persistenceFailure, thrown);
+ assertFalse(proxy.isDebugLogging());
+ assertSame(proxy, service.getDbProxy("app-proxy", "us-east-1"));
+ }
+
+ @Test
+ void modifyDbProxyRestartsOriginalRelayWhenInitialStopPartiallySucceeds() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "relay", 5432);
+ proxy.setDefaultAuthScheme("NONE");
+ proxy.setIamAuth(false);
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "relay");
+ targetGroup.setTargets(List.of(new DbProxyTarget(
+ "RDS_INSTANCE", "db1",
+ "arn:aws:rds:us-east-1:123456789012:db:db1", "localhost", 15432)));
+ DbInstance instance = persistedInstance("db1", "123456789012", "secret", 15432);
+ instance.setContainerHost("localhost");
+ instance.setContainerPort(15432);
+ proxies.put("us-east-1::app-proxy", proxy);
+ targetGroups.put("us-east-1::app-proxy", targetGroup);
+ instances.put("db1", instance);
+ AtomicBoolean relayRunning = new AtomicBoolean(true);
+ IllegalStateException stopFailure =
+ new IllegalStateException("simulated post-stop failure");
+ doAnswer(invocation -> {
+ relayRunning.set(false);
+ throw stopFailure;
+ }).when(proxyManager).stopProxy("db-proxy:" + proxy.getDbProxyArn());
+ java.util.ArrayList<Boolean> startedModes = new java.util.ArrayList<>();
+ doAnswer(invocation -> {
+ startedModes.add(invocation.getArgument(2));
+ relayRunning.set(true);
+ return null;
+ }).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
+ anyInt(), any(), any(), any(), any());
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
+ DbProxyAuth requiredAuth = new DbProxyAuth(
+ "SECRETS", PROXY_AUTH.getFirst().getSecretArn(), "REQUIRED", null, null);
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
+ service.modifyDbProxy("app-proxy", null, List.of(requiredAuth),
+ null, null, null, null, null, null, "us-east-1"));
+
+ assertSame(stopFailure, thrown);
+ assertTrue(relayRunning.get());
+ assertEquals(List.of(false), startedModes);
+ assertSame(proxy, proxies.get("us-east-1::app-proxy").orElseThrow());
+ assertFalse(proxy.isIamAuth());
+ }
+
+ @Test
+ void modifyDbProxyRestoresDurableStateAndRelayAfterPostMutationFailure() {
+ InMemoryStorage<String, DbProxy> proxies = spy(new InMemoryStorage<>());
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "relay", 5432);
+ proxy.setDefaultAuthScheme("NONE");
+ proxy.setIamAuth(false);
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "relay");
+ targetGroup.setTargets(List.of(new DbProxyTarget(
+ "RDS_INSTANCE", "db1",
+ "arn:aws:rds:us-east-1:123456789012:db:db1", "localhost", 15432)));
+ DbInstance instance = persistedInstance("db1", "123456789012", "secret", 15432);
+ instance.setContainerHost("localhost");
+ instance.setContainerPort(15432);
+ proxies.put("us-east-1::app-proxy", proxy);
+ targetGroups.put("us-east-1::app-proxy", targetGroup);
+ instances.put("db1", instance);
+ IllegalStateException persistenceFailure =
+ new IllegalStateException("simulated post-mutation persistence failure");
+ doAnswer(invocation -> {
+ invocation.callRealMethod();
+ throw persistenceFailure;
+ }).doCallRealMethod().when(proxies).put(eq("us-east-1::app-proxy"), any());
+ AtomicBoolean relayRunning = new AtomicBoolean(true);
+ doAnswer(invocation -> {
+ relayRunning.set(false);
+ return null;
+ }).when(proxyManager).stopProxy("db-proxy:" + proxy.getDbProxyArn());
+ java.util.ArrayList<Boolean> startedModes = new java.util.ArrayList<>();
+ doAnswer(invocation -> {
+ startedModes.add(invocation.getArgument(2));
+ relayRunning.set(true);
+ return null;
+ }).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
+ anyInt(), any(), any(), any(), any());
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
+ DbProxyAuth requiredAuth = new DbProxyAuth(
+ "SECRETS", PROXY_AUTH.getFirst().getSecretArn(), "REQUIRED", null, null);
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
+ service.modifyDbProxy("app-proxy", null, List.of(requiredAuth),
+ null, null, null, null, null, null, "us-east-1"));
+
+ assertSame(persistenceFailure, thrown);
+ assertTrue(relayRunning.get());
+ assertEquals(List.of(true, false), startedModes);
+ DbProxy restored = proxies.get("us-east-1::app-proxy").orElseThrow();
+ assertSame(proxy, restored);
+ assertFalse(restored.isIamAuth());
+ assertEquals("DISABLED", restored.getAuth().getFirst().getIamAuth());
+ }
+
+ @Test
+ void dbProxyIdentityAndTagsAreRegionScoped() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ RdsService service = new RdsService(containerManager, proxyManager, ec2Service,
+ regionResolver, config, new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
+ null, null, proxies, targetGroups);
+
+ DbProxy east = service.createDbProxy(
+ "shared-proxy", "POSTGRESQL", true, false, "NONE", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, 1800, false,
+ Map.of("region", "east"), "us-east-1");
+ DbProxy west = service.createDbProxy(
+ "shared-proxy", "POSTGRESQL", true, false, "NONE", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, 1800, false,
+ Map.of("region", "west"), "us-west-2");
+
+ assertTrue(proxies.get("us-east-1::shared-proxy").isPresent());
+ assertTrue(proxies.get("us-west-2::shared-proxy").isPresent());
+ assertTrue(targetGroups.get("us-east-1::shared-proxy").isPresent());
+ assertTrue(targetGroups.get("us-west-2::shared-proxy").isPresent());
+ assertEquals(east.getDbProxyArn(), service.getDbProxy("shared-proxy", "us-east-1").getDbProxyArn());
+ assertEquals(west.getDbProxyArn(), service.getDbProxy("shared-proxy", "us-west-2").getDbProxyArn());
+ assertEquals(Map.of("region", "east"), service.listTagsForResource(east.getDbProxyArn(), "us-east-1"));
+ assertEquals(Map.of("region", "west"), service.listTagsForResource(west.getDbProxyArn(), "us-west-2"));
+
+ AwsException wrongRegion = assertThrows(AwsException.class, () ->
+ service.addTagsToResource(west.getDbProxyArn(), Map.of("bad", "tag"), "us-east-1"));
+ assertEquals("InvalidParameterValue", wrongRegion.getErrorCode());
+ String wrongAccountArn = east.getDbProxyArn().replace("123456789012", "999999999999");
+ AwsException wrongAccount = assertThrows(AwsException.class, () ->
+ service.addTagsToResource(wrongAccountArn, Map.of("bad", "tag"), "us-east-1"));
+ assertEquals("InvalidParameterValue", wrongAccount.getErrorCode());
+
+ service.deleteDbProxy("shared-proxy", "us-west-2");
+ assertEquals(east.getDbProxyArn(), service.getDbProxy("shared-proxy", "us-east-1").getDbProxyArn());
+ assertThrows(AwsException.class, () -> service.getDbProxy("shared-proxy", "us-west-2"));
+ }
+
+ @Test
+ void dbProxyTagsRoundTripByArn() {
+ DbProxy proxy = rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false,
+ PROXY_ROLE_ARN, PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of("owner", "platform"));
+
+ assertEquals(Map.of("owner", "platform"), rdsService.listTagsForResource(proxy.getDbProxyArn()));
+ rdsService.addTagsToResource(proxy.getDbProxyArn(), Map.of("env", "test"));
+ assertEquals(Map.of("owner", "platform", "env", "test"),
+ rdsService.listTagsForResource(proxy.getDbProxyArn()));
+ rdsService.removeTagsFromResource(proxy.getDbProxyArn(), List.of("owner"));
+ assertEquals(Map.of("env", "test"), rdsService.listTagsForResource(proxy.getDbProxyArn()));
+ }
+
+ @Test
+ void targetGroupConfigurationValidatesBeforeMutatingStoredState() {
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false,
+ PROXY_ROLE_ARN, PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+
+ AwsException invalid = assertThrows(AwsException.class, () ->
+ rdsService.configureDbProxyTargetGroup("app-proxy", "default", 80, 101));
+
+ assertEquals("InvalidParameterValue", invalid.getErrorCode());
+ DbProxyTargetGroup targetGroup =
+ rdsService.describeDbProxyTargetGroups("app-proxy").iterator().next();
+ assertEquals(100, targetGroup.getMaxConnectionsPercent());
+ assertEquals(50, targetGroup.getMaxIdleConnectionsPercent());
+
+ AwsException missingMaxConnections = assertThrows(AwsException.class, () ->
+ rdsService.configureDbProxyTargetGroup("app-proxy", "default", null, 0));
+ assertEquals("InvalidParameterValue", missingMaxConnections.getErrorCode());
+
+ DbProxyTargetGroup configured =
+ rdsService.configureDbProxyTargetGroup("app-proxy", "default", 80, null);
+ assertEquals(80, configured.getMaxConnectionsPercent());
+ assertEquals(40, configured.getMaxIdleConnectionsPercent());
+ }
+
+ @Test
+ void targetGroupConfigurationRestoresStateAfterPostMutationPersistenceFailure() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = spy(new InMemoryStorage<>());
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+ service.createDbProxy(
+ "app-proxy", "MYSQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ DbProxyTargetGroup original = targetGroups.get(
+ "us-east-1::app-proxy").orElseThrow();
+ IllegalStateException persistenceFailure =
+ new IllegalStateException("simulated post-mutation persistence failure");
+ doAnswer(invocation -> {
+ invocation.callRealMethod();
+ throw persistenceFailure;
+ }).doCallRealMethod().when(targetGroups).put(eq("us-east-1::app-proxy"), any());
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
+ service.configureDbProxyTargetGroup(
+ "app-proxy", "default", 80, 20, 45,
+ "SET application_name = 'floci'",
+ List.of("EXCLUDE_VARIABLE_SETS"), "us-east-1"));
+
+ assertSame(persistenceFailure, thrown);
+ assertProxyTargetGroupState(original,
+ targetGroups.get("us-east-1::app-proxy").orElseThrow());
+ }
+
+ @Test
+ void targetGroupReconciliationIsCompleteAndIdempotent() {
+ when(config.services().rds().mock()).thenReturn(true);
+ rdsService.createDbCluster("cluster1", "aurora-mysql", "8.0.36",
+ "admin", "secret", "app", false, null);
+ rdsService.createDbProxy("mysql-proxy", "MYSQL", true, false,
+ PROXY_ROLE_ARN, PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+
+ DbProxyTargetGroup reconciled = rdsService.reconcileDbProxyTargetGroup(
+ "mysql-proxy", "default", List.of("cluster1"), List.of(),
+ 85, 35, 45, "SET sql_mode='ANSI'", List.of("EXCLUDE_VARIABLE_SETS"),
+ "us-east-1");
+ String targetGroupArn = reconciled.getTargetGroupArn();
+ Instant createdAt = reconciled.getCreatedAt();
+ Instant updatedAt = reconciled.getUpdatedAt();
+
+ assertEquals(1, reconciled.getTargets().size());
+ assertEquals(85, reconciled.getMaxConnectionsPercent());
+ assertEquals(35, reconciled.getMaxIdleConnectionsPercent());
+ assertEquals(45, reconciled.getConnectionBorrowTimeout());
+ assertEquals("SET sql_mode='ANSI'", reconciled.getInitQuery());
+ assertEquals(List.of("EXCLUDE_VARIABLE_SETS"), reconciled.getSessionPinningFilters());
+
+ DbProxyTargetGroup retry = rdsService.reconcileDbProxyTargetGroup(
+ "mysql-proxy", "default", List.of("cluster1"), List.of(),
+ 85, 35, 45, "SET sql_mode='ANSI'", List.of("EXCLUDE_VARIABLE_SETS"),
+ "us-east-1");
+
+ assertEquals(targetGroupArn, retry.getTargetGroupArn());
+ assertEquals(createdAt, retry.getCreatedAt());
+ assertEquals(updatedAt, retry.getUpdatedAt());
+ assertEquals(1, retry.getTargets().size());
+ }
+
+ @Test
+ void targetGroupReconciliationValidatesBeforeMutation() {
+ when(config.services().rds().mock()).thenReturn(true);
+ rdsService.createDbCluster("cluster1", "aurora-postgresql", "16.3",
+ "admin", "secret", "app", false, null);
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false,
+ PROXY_ROLE_ARN, PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ DbProxyTargetGroup before = rdsService.describeDbProxyTargetGroups("app-proxy")
+ .iterator().next();
+
+ AwsException invalid = assertThrows(AwsException.class, () ->
+ rdsService.reconcileDbProxyTargetGroup(
+ "app-proxy", "default", List.of("cluster1"), List.of(),
+ 80, 40, 120, null, List.of("EXCLUDE_VARIABLE_SETS"), "us-east-1"));
+
+ assertEquals("InvalidParameterValue", invalid.getErrorCode());
+ DbProxyTargetGroup after = rdsService.describeDbProxyTargetGroups("app-proxy")
+ .iterator().next();
+ assertEquals(before.getTargetGroupArn(), after.getTargetGroupArn());
+ assertEquals(before.getUpdatedAt(), after.getUpdatedAt());
+ assertTrue(after.getTargets().isEmpty());
+ }
+
+ @Test
+ void proxyTargetRegistrationRejectsCrossRegionDatabase() {
+ when(config.services().rds().mock()).thenReturn(true);
+ rdsService.createDbCluster("cluster1", "aurora-postgresql", "16.3",
+ "admin", "secret", "app", false, null,
+ null, null, false, "us-east-1");
+ rdsService.createDbProxy(
+ "west-proxy", "POSTGRESQL", true, false, "NONE", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, 1800, false, Map.of(), "us-west-2");
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ rdsService.registerDbProxyTargets(
+ "west-proxy", "default", List.of("cluster1"), List.of(),
+ 0, 0, "us-west-2"));
+
+ assertEquals("DBClusterNotFoundFault", exception.getErrorCode());
+ assertTrue(rdsService.describeDbProxyTargets(
+ "west-proxy", "default", "us-west-2").isEmpty());
+ }
+
+ @Test
+ void clearingTargetGroupPreservesIdentityResetsDefaultsAndAllowsReregistration() {
+ when(config.services().rds().mock()).thenReturn(true);
+ rdsService.createDbCluster("cluster1", "aurora-postgresql", "16.3",
+ "admin", "secret", "app", false, null);
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false,
+ PROXY_ROLE_ARN, PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ DbProxyTargetGroup registered = rdsService.registerDbProxyTargets("app-proxy", "default",
+ List.of("cluster1"), List.of(), 80, 20);
+
+ rdsService.clearDbProxyTargetGroupByArn(registered.getTargetGroupArn());
+
+ DbProxyTargetGroup cleared = rdsService.describeDbProxyTargetGroups("app-proxy")
+ .iterator().next();
+ assertEquals(registered.getTargetGroupArn(), cleared.getTargetGroupArn());
+ assertTrue(cleared.isDefaultTargetGroup());
+ assertTrue(cleared.getTargets().isEmpty());
+ assertEquals(100, cleared.getMaxConnectionsPercent());
+ assertEquals(50, cleared.getMaxIdleConnectionsPercent());
+
+ DbProxyTargetGroup reregistered = rdsService.registerDbProxyTargets("app-proxy", "default",
+ List.of("cluster1"), List.of(), 0, 0);
+ assertEquals(1, reregistered.getTargets().size());
+ }
+
+ @Test
+ void clearingTargetGroupRestoresConfigurationAndRelayAfterPersistenceFailure() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = spy(new InMemoryStorage<>());
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "clear", 5432);
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "clear");
+ targetGroup.setMaxConnectionsPercent(73);
+ targetGroup.setMaxIdleConnectionsPercent(29);
+ targetGroup.setConnectionBorrowTimeout(45);
+ targetGroup.setInitQuery("SET application_name = 'floci'");
+ targetGroup.setSessionPinningFilters(List.of("EXCLUDE_VARIABLE_SETS"));
+ targetGroup.setTargets(List.of(new DbProxyTarget(
+ "RDS_INSTANCE", "db1",
+ "arn:aws:rds:us-east-1:123456789012:db:db1", "localhost", 15432)));
+ DbInstance instance = persistedInstance("db1", "123456789012", "secret", 15432);
+ instance.setContainerHost("localhost");
+ instance.setContainerPort(15432);
+ proxies.put("us-east-1::app-proxy", proxy);
+ targetGroups.put("us-east-1::app-proxy", targetGroup);
+ instances.put("db1", instance);
+ IllegalStateException persistenceFailure =
+ new IllegalStateException("simulated post-mutation persistence failure");
+ doAnswer(invocation -> {
+ invocation.callRealMethod();
+ throw persistenceFailure;
+ }).doCallRealMethod().when(targetGroups).put(eq("us-east-1::app-proxy"), any());
+ AtomicBoolean relayRunning = new AtomicBoolean(true);
+ doAnswer(invocation -> {
+ relayRunning.set(false);
+ return null;
+ }).when(proxyManager).stopProxy("db-proxy:" + proxy.getDbProxyArn());
+ doAnswer(invocation -> {
+ relayRunning.set(true);
+ return null;
+ }).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
+ anyInt(), any(), any(), any(), any());
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
+ service.clearDbProxyTargetGroupByArn(
+ targetGroup.getTargetGroupArn(), "us-east-1"));
+
+ assertSame(persistenceFailure, thrown);
+ assertTrue(relayRunning.get());
+ assertProxyTargetGroupState(targetGroup,
+ targetGroups.get("us-east-1::app-proxy").orElseThrow());
+
+ service.clearDbProxyTargetGroupByArn(
+ targetGroup.getTargetGroupArn(), "us-east-1");
+ DbProxyTargetGroup cleared = targetGroups.get(
+ "us-east-1::app-proxy").orElseThrow();
+ assertFalse(relayRunning.get());
+ assertTrue(cleared.getTargets().isEmpty());
+ assertEquals(100, cleared.getMaxConnectionsPercent());
+ assertEquals(50, cleared.getMaxIdleConnectionsPercent());
+ assertEquals(120, cleared.getConnectionBorrowTimeout());
+ assertNull(cleared.getInitQuery());
+ assertTrue(cleared.getSessionPinningFilters().isEmpty());
+ }
+
+ @Test
+ void sqlServerTargetGroupUsesEngineSpecificPoolDefaults() {
+ rdsService.createDbProxy("sqlserver-proxy", "SQLSERVER", true, false,
+ PROXY_ROLE_ARN, PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ DbProxyTargetGroup targetGroup = rdsService.describeDbProxyTargetGroups("sqlserver-proxy")
+ .iterator().next();
+
+ assertEquals(10, targetGroup.getMaxConnectionsPercent());
+ assertEquals(5, targetGroup.getMaxIdleConnectionsPercent());
+
+ rdsService.configureDbProxyTargetGroup("sqlserver-proxy", "default", 80, 20);
+ rdsService.clearDbProxyTargetGroupByArn(targetGroup.getTargetGroupArn());
+
+ DbProxyTargetGroup cleared = rdsService.describeDbProxyTargetGroups("sqlserver-proxy")
+ .iterator().next();
+ assertEquals(10, cleared.getMaxConnectionsPercent());
+ assertEquals(5, cleared.getMaxIdleConnectionsPercent());
+ }
+
+ @Test
+ void registerDbProxyTargetRejectsDuplicateAndSupportsDeregistration() {
+ when(config.services().rds().mock()).thenReturn(true);
+ rdsService.createDbCluster("cluster1", "aurora-postgresql", "16.3",
+ "admin", "secret", "app", false, null);
+ rdsService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ rdsService.registerDbProxyTargets("app-proxy", "default",
+ List.of("cluster1"), List.of(), 0, 0);
+
+ AwsException duplicate = assertThrows(AwsException.class, () ->
+ rdsService.registerDbProxyTargets("app-proxy", "default",
+ List.of("cluster1"), List.of(), 0, 0));
+ assertEquals("DBProxyTargetAlreadyRegisteredFault", duplicate.getErrorCode());
+
+ AwsException referenced = assertThrows(AwsException.class, () ->
+ rdsService.deleteDbCluster("cluster1"));
+ assertEquals("InvalidDBClusterStateFault", referenced.getErrorCode());
+
+ rdsService.deregisterDbProxyTargets("app-proxy", "default", List.of("cluster1"), List.of());
+ assertTrue(rdsService.describeDbProxyTargets("app-proxy", "default").isEmpty());
+ rdsService.deleteDbCluster("cluster1");
+
+ AwsException missing = assertThrows(AwsException.class, () ->
+ rdsService.deregisterDbProxyTargets("app-proxy", "default",
+ List.of("cluster1"), List.of()));
+ assertEquals("DBProxyTargetNotFoundFault", missing.getErrorCode());
+ }
+
+ @Test
+ void deregistrationRestoresTargetAndRelayAfterStopAndPersistenceFailures() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = spy(new InMemoryStorage<>());
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "abc", 5432);
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "abc");
+ targetGroup.setMaxConnectionsPercent(77);
+ targetGroup.setMaxIdleConnectionsPercent(31);
+ targetGroup.setConnectionBorrowTimeout(45);
+ targetGroup.setInitQuery("SET application_name = 'floci'");
+ targetGroup.setSessionPinningFilters(List.of("EXCLUDE_VARIABLE_SETS"));
+ targetGroup.setTargets(List.of(new DbProxyTarget(
+ "RDS_INSTANCE", "db1",
+ "arn:aws:rds:us-east-1:123456789012:db:db1", "localhost", 15432)));
+ DbInstance instance = persistedInstance("db1", "123456789012", "secret", 15432);
+ instance.setContainerHost("localhost");
+ instance.setContainerPort(15432);
+ proxies.put("us-east-1::app-proxy", proxy);
+ targetGroups.put("us-east-1::app-proxy", targetGroup);
+ instances.put("db1", instance);
+ IllegalStateException persistenceFailure =
+ new IllegalStateException("simulated post-mutation persistence failure");
+ doCallRealMethod().doAnswer(invocation -> {
+ invocation.callRealMethod();
+ throw persistenceFailure;
+ }).doCallRealMethod().when(targetGroups).put(eq("us-east-1::app-proxy"), any());
+ AtomicBoolean relayRunning = new AtomicBoolean(true);
+ IllegalStateException stopFailure =
+ new IllegalStateException("simulated post-stop failure");
+ doAnswer(invocation -> {
+ relayRunning.set(false);
+ throw stopFailure;
+ }).doAnswer(invocation -> {
+ relayRunning.set(false);
+ return null;
+ }).when(proxyManager).stopProxy("db-proxy:" + proxy.getDbProxyArn());
+ doAnswer(invocation -> {
+ relayRunning.set(true);
+ return null;
+ }).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
+ anyInt(), any(), any(), any(), any());
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
+
+ IllegalStateException stopThrown = assertThrows(IllegalStateException.class, () ->
+ service.deregisterDbProxyTargets(
+ "app-proxy", "default", List.of(), List.of("db1")));
+
+ assertSame(stopFailure, stopThrown);
+ assertTrue(relayRunning.get());
+ assertProxyTargetGroupState(targetGroup,
+ targetGroups.get("us-east-1::app-proxy").orElseThrow());
+
+ IllegalStateException persistenceThrown = assertThrows(IllegalStateException.class, () ->
+ service.deregisterDbProxyTargets(
+ "app-proxy", "default", List.of(), List.of("db1")));
+
+ assertSame(persistenceFailure, persistenceThrown);
+ assertTrue(relayRunning.get());
+ assertProxyTargetGroupState(targetGroup,
+ targetGroups.get("us-east-1::app-proxy").orElseThrow());
+
+ service.deregisterDbProxyTargets(
+ "app-proxy", "default", List.of(), List.of("db1"));
+ assertFalse(relayRunning.get());
+ assertTrue(targetGroups.get("us-east-1::app-proxy").orElseThrow()
+ .getTargets().isEmpty());
+ }
+
+ @Test
+ void registrationRollsBackMutateThenThrowProxyStatusPersistence() {
+ InMemoryStorage<String, DbProxy> proxies =
+ spy(new InMemoryStorage<String, DbProxy>());
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "mysql-proxy", "us-east-1", "123456789012", "current", 3306);
+ proxy.setEngineFamily("MYSQL");
+ proxy.setStatus("insufficient-resource-limits");
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "mysql-proxy", "us-east-1", "123456789012", "current");
+ targetGroup.setCreatedAt(proxy.getCreatedAt());
+ targetGroup.setUpdatedAt(proxy.getCreatedAt());
+ DbInstance instance = persistedInstance(
+ "mysql-db", "123456789012", "secret", 7000);
+ instance.setEngine(DatabaseEngine.MYSQL);
+ instance.setContainerHost("localhost");
+ instance.setContainerPort(3306);
+ proxies.put("us-east-1::mysql-proxy", proxy);
+ targetGroups.put("us-east-1::mysql-proxy", targetGroup);
+ instances.put("mysql-db", instance);
+ doAnswer(invocation -> {
+ invocation.callRealMethod();
+ throw new IllegalStateException("simulated post-mutation persistence failure");
+ }).doCallRealMethod().when(proxies).put(
+ eq("us-east-1::mysql-proxy"), any());
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ instances, new InMemoryStorage<>());
+
+ assertThrows(IllegalStateException.class, () -> service.registerDbProxyTargets(
+ "mysql-proxy", "default", List.of(), List.of("mysql-db"), 0, 0));
+
+ assertEquals("insufficient-resource-limits", proxies.get(
+ "us-east-1::mysql-proxy").orElseThrow().getStatus());
+ assertTrue(targetGroups.get("us-east-1::mysql-proxy").orElseThrow()
+ .getTargets().isEmpty());
+ verify(proxyManager).startProxy(
+ eq("db-proxy:" + proxy.getDbProxyArn()), eq(DatabaseEngine.MYSQL),
+ anyBoolean(), eq(3306), eq("localhost"), eq(3306),
+ eq("admin"), eq("secret"), eq("app"), any());
+ verify(proxyManager).stopProxy("db-proxy:" + proxy.getDbProxyArn());
+ }
+
+ @Test
+ void registrationStopsRelayWhenStartupPartiallySucceeds() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "mysql-proxy", "us-east-1", "123456789012", "current", 3306);
+ proxy.setEngineFamily("MYSQL");
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "mysql-proxy", "us-east-1", "123456789012", "current");
+ DbInstance instance = persistedInstance(
+ "mysql-db", "123456789012", "secret", 3306);
+ instance.setEngine(DatabaseEngine.MYSQL);
+ instance.setContainerHost("localhost");
+ instance.setContainerPort(3306);
+ proxies.put("us-east-1::mysql-proxy", proxy);
+ targetGroups.put("us-east-1::mysql-proxy", targetGroup);
+ instances.put("mysql-db", instance);
+ AtomicBoolean relayRunning = new AtomicBoolean(false);
+ IllegalStateException startupFailure =
+ new IllegalStateException("simulated post-start failure");
+ doAnswer(invocation -> {
+ relayRunning.set(true);
+ throw startupFailure;
+ }).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
+ anyInt(), any(), any(), any(), any());
+ doAnswer(invocation -> {
+ relayRunning.set(false);
+ return null;
+ }).when(proxyManager).stopProxy("db-proxy:" + proxy.getDbProxyArn());
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups, instances, new InMemoryStorage<>());
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
+ service.registerDbProxyTargets(
+ "mysql-proxy", "default", List.of(), List.of("mysql-db"), 0, 0));
+
+ assertSame(startupFailure, thrown);
+ assertFalse(relayRunning.get());
+ assertSame(proxy, proxies.get("us-east-1::mysql-proxy").orElseThrow());
+ assertTrue(targetGroups.get("us-east-1::mysql-proxy").orElseThrow()
+ .getTargets().isEmpty());
+ }
+
+ @Test
+ void deletingLegacyDbProxyAlsoRemovesLegacyTargetGroup() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy("app-proxy", "us-east-1", "123456789012", "old", 5432);
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "old");
+ proxies.put("app-proxy", proxy);
+ targetGroups.put("app-proxy", targetGroup);
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.deleteDbProxy("app-proxy", "us-east-1");
+
+ assertTrue(proxies.get("app-proxy").isEmpty());
+ assertTrue(proxies.get("us-east-1::app-proxy").isEmpty());
+ assertTrue(targetGroups.get("app-proxy").isEmpty());
+ assertTrue(targetGroups.get("us-east-1::app-proxy").isEmpty());
+ }
+
+ @Test
+ void staleProxyAndTargetGroupArnsCannotOverwriteRecreatedResources() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ DbProxy current = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "new", 5432);
+ current.setTags(Map.of("generation", "new"));
+ DbProxy stale = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "old", 5432);
+ DbProxyTargetGroup currentTargetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "new");
+ DbProxyTargetGroup staleTargetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "old");
+ proxies.put("us-east-1::app-proxy", current);
+ proxies.put("app-proxy", stale);
+ targetGroups.put("us-east-1::app-proxy", currentTargetGroup);
+ targetGroups.put("app-proxy", staleTargetGroup);
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ AwsException staleProxyArn = assertThrows(AwsException.class, () ->
+ service.addTagsToResource(stale.getDbProxyArn(), Map.of("bad", "tag"), "us-east-1"));
+ AwsException staleTargetGroupArn = assertThrows(AwsException.class, () ->
+ service.clearDbProxyTargetGroupByArn(
+ staleTargetGroup.getTargetGroupArn(), "us-east-1"));
+
+ assertEquals("DBProxyNotFoundFault", staleProxyArn.getErrorCode());
+ assertEquals("DBProxyTargetGroupNotFoundFault", staleTargetGroupArn.getErrorCode());
+ assertEquals(current.getDbProxyArn(),
+ proxies.get("us-east-1::app-proxy").orElseThrow().getDbProxyArn());
+ assertEquals(Map.of("generation", "new"),
+ proxies.get("us-east-1::app-proxy").orElseThrow().getTags());
+ assertEquals(currentTargetGroup.getTargetGroupArn(),
+ targetGroups.get("us-east-1::app-proxy").orElseThrow().getTargetGroupArn());
+ }
+
+ @Test
+ void rawLegacyProxyCannotBeClaimedByAnotherAccount() {
+ String foreignAccount = "222222222222";
+ String currentAccount = "333333333333";
+ RegionResolver otherRegionResolver = new RegionResolver("us-east-1", currentAccount);
+ EmulatorConfig otherConfig = mock(EmulatorConfig.class);
+ when(otherConfig.defaultAccountId()).thenReturn(currentAccount);
+ InMemoryStorage<String, DbProxy> rawProxies = new InMemoryStorage<>();
+ rawProxies.put("app-proxy", persistedProxy(
+ "app-proxy", "us-east-1", foreignAccount, "foreign", 5432));
+ rawProxies.put(currentAccount + "/us-east-1::corrupt-proxy", persistedProxy(
+ "corrupt-proxy", "us-east-1", foreignAccount, "corrupt", 5433));
+ AccountAwareStorageBackend<DbProxy> proxies =
+ new AccountAwareStorageBackend<>(rawProxies, null, currentAccount);
+ AccountAwareStorageBackend<DbProxyTargetGroup> targetGroups =
+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, currentAccount);
+ RdsService service = proxyStoreService(
+ otherRegionResolver, otherConfig, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ service.getDbProxy("app-proxy", "us-east-1"));
+
+ assertEquals("DBProxyNotFoundFault", exception.getErrorCode());
+ assertTrue(service.listDbProxies(null, "us-east-1").isEmpty());
+ assertTrue(rawProxies.get("app-proxy").isPresent());
+ assertTrue(rawProxies.get(currentAccount + "/app-proxy").isEmpty());
+ }
+
+ @Test
+ void malformedPersistedProxyArnIsSkippedWithoutMigration() {
+ when(config.services().rds().mock()).thenReturn(true);
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ DbProxy malformed = persistedProxy(
+ "malformed-proxy", "us-east-1", "123456789012", "bad", 5432);
+ malformed.setDbProxyArn("not-an-arn");
+ proxies.put("malformed-proxy", malformed);
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, new InMemoryStorage<>(),
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.restorePersistedRuntime();
+
+ assertTrue(service.listDbProxies(null, "us-east-1").isEmpty());
+ AwsException missing = assertThrows(AwsException.class, () ->
+ service.getDbProxy("malformed-proxy", "us-east-1"));
+ assertEquals("DBProxyNotFoundFault", missing.getErrorCode());
+ assertTrue(proxies.get("malformed-proxy").isPresent());
+ assertTrue(proxies.get("us-east-1::malformed-proxy").isEmpty());
+ }
+
+ @Test
+ void corruptCanonicalProxyAndTargetGroupFailClosedWithoutBeingOverwritten() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ DbProxy wrongName = persistedProxy(
+ "other-proxy", "us-east-1", "123456789012", "other", 5432);
+ proxies.put("us-east-1::expected-proxy", wrongName);
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ AwsException missing = assertThrows(AwsException.class, () ->
+ service.getDbProxy("expected-proxy", "us-east-1"));
+ assertEquals("DBProxyNotFoundFault", missing.getErrorCode());
+ AwsException occupied = assertThrows(AwsException.class, () ->
+ service.createDbProxy(
+ "expected-proxy", "POSTGRESQL", true, false, "NONE", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH,
+ 1800, false, Map.of(), "us-east-1"));
+ assertEquals("DBProxyAlreadyExistsFault", occupied.getErrorCode());
+ assertSame(wrongName, proxies.get("us-east-1::expected-proxy").orElseThrow());
+
+ DbProxy current = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "current", 5433);
+ DbProxyTargetGroup stale = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "stale");
+ proxies.put("us-east-1::app-proxy", current);
+ targetGroups.put("us-east-1::app-proxy", stale);
+
+ AwsException staleGroup = assertThrows(AwsException.class, () ->
+ service.describeDbProxyTargets("app-proxy", "default", "us-east-1"));
+ assertEquals("DBProxyTargetGroupNotFoundFault", staleGroup.getErrorCode());
+ assertSame(stale, targetGroups.get("us-east-1::app-proxy").orElseThrow());
+ }
+
+ @Test
+ void proxyRestoreDoesNotReplaceCorruptCanonicalTargetGroupWithLegacyState() {
+ when(config.services().rds().mock()).thenReturn(true);
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "current", 5432);
+ DbProxyTargetGroup staleCanonical = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "stale");
+ DbProxyTargetGroup recoverableLegacy = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "current");
+ recoverableLegacy.setCreatedAt(proxy.getCreatedAt());
+ recoverableLegacy.setUpdatedAt(proxy.getCreatedAt());
+ proxies.put("us-east-1::app-proxy", proxy);
+ targetGroups.put("us-east-1::app-proxy", staleCanonical);
+ targetGroups.put("app-proxy", recoverableLegacy);
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.restorePersistedRuntime();
+
+ assertSame(staleCanonical,
+ targetGroups.get("us-east-1::app-proxy").orElseThrow());
+ assertSame(recoverableLegacy, targetGroups.get("app-proxy").orElseThrow());
+ assertEquals("insufficient-resource-limits",
+ service.getDbProxy("app-proxy", "us-east-1").getStatus());
+ }
+
+ @Test
+ void proxyRestoreRejectsAccountScopedKeyWhoseModelHasAnotherName() {
+ when(config.services().rds().mock()).thenReturn(true);
+ String accountId = "123456789012";
+ InMemoryStorage<String, DbProxy> rawProxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> rawTargetGroups = new InMemoryStorage<>();
+ DbProxy wrongName = persistedProxy(
+ "other-proxy", "us-east-1", accountId, "other", 5432);
+ String corruptKey = accountId + "/us-east-1::expected-proxy";
+ rawProxies.put(corruptKey, wrongName);
+ RdsService service = proxyStoreService(
+ regionResolver, config,
+ new AccountAwareStorageBackend<>(rawProxies, null, accountId),
+ new AccountAwareStorageBackend<>(rawTargetGroups, null, accountId),
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.restorePersistedRuntime();
+
+ assertSame(wrongName, rawProxies.get(corruptKey).orElseThrow());
+ assertTrue(rawProxies.get(accountId + "/us-east-1::other-proxy").isEmpty());
+ assertTrue(rawTargetGroups.get(accountId + "/us-east-1::other-proxy").isEmpty());
+ assertTrue(service.listDbProxies(null, "us-east-1").isEmpty());
+ }
+
+ @Test
+ void proxyRestorePrefersRawRegionalCanonicalOverAccountNameLegacy() {
+ when(config.services().rds().mock()).thenReturn(true);
+ String accountId = "123456789012";
+ InMemoryStorage<String, DbProxy> rawProxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> rawTargetGroups = new InMemoryStorage<>();
+ DbProxy regional = persistedProxy(
+ "app-proxy", "us-east-1", accountId, "shared", 5432);
+ regional.setTags(Map.of("source", "regional"));
+ DbProxy accountName = persistedProxy(
+ "app-proxy", "us-east-1", accountId, "shared", 5432);
+ accountName.setTags(Map.of("source", "account-name"));
+ rawProxies.put("us-east-1::app-proxy", regional);
+ rawProxies.put(accountId + "/app-proxy", accountName);
+ RdsService service = proxyStoreService(
+ regionResolver, config,
+ new AccountAwareStorageBackend<>(rawProxies, null, accountId),
+ new AccountAwareStorageBackend<>(rawTargetGroups, null, accountId),
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.restorePersistedRuntime();
+
+ DbProxy canonical = rawProxies.get(
+ accountId + "/us-east-1::app-proxy").orElseThrow();
+ assertSame(regional, canonical);
+ assertEquals(Map.of("source", "regional"), canonical.getTags());
+ assertTrue(rawProxies.get("us-east-1::app-proxy").isEmpty());
+ assertTrue(rawProxies.get(accountId + "/app-proxy").isEmpty());
+ }
+
+ @Test
+ void proxyRestoreUsesRegionalLegacyGenerationDeterministically() {
+ when(config.services().rds().mock()).thenReturn(true);
+ String accountId = "123456789012";
+ InMemoryStorage<String, DbProxy> rawProxies = new InMemoryStorage<>();
+ DbProxy regional = persistedProxy(
+ "app-proxy", "us-east-1", accountId, "regional", 5432);
+ DbProxy accountName = persistedProxy(
+ "app-proxy", "us-east-1", accountId, "account", 5433);
+ rawProxies.put("us-east-1::app-proxy", regional);
+ rawProxies.put(accountId + "/app-proxy", accountName);
+ RdsService service = proxyStoreService(
+ regionResolver, config,
+ new AccountAwareStorageBackend<>(rawProxies, null, accountId),
+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, accountId),
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.restorePersistedRuntime();
+
+ assertEquals("prx-regional", rawProxies.get(
+ accountId + "/us-east-1::app-proxy").orElseThrow()
+ .getDbProxyResourceId());
+ assertTrue(rawProxies.get("us-east-1::app-proxy").isEmpty());
+ assertSame(accountName, rawProxies.get(accountId + "/app-proxy").orElseThrow());
+ }
+
+ @Test
+ void proxyRestoreRejectsInvalidPersistedIdentity() {
+ when(config.services().rds().mock()).thenReturn(true);
+ String accountId = "123456789012";
+ InMemoryStorage<String, DbProxy> rawProxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> rawTargetGroups = new InMemoryStorage<>();
+ DbProxy invalidName = persistedProxy(
+ "bad/name", "us-east-1", accountId, "bad-name", 5432);
+ DbProxy blankRegion = persistedProxy(
+ "blank-region", "", accountId, "blank-region", 5433);
+ invalidName.setDefaultAuthScheme(null);
+ blankRegion.setDefaultAuthScheme(null);
+ rawProxies.put(accountId + "/us-east-1::bad/name", invalidName);
+ rawProxies.put(accountId + "/us-east-1::blank-region", blankRegion);
+ RdsService service = proxyStoreService(
+ regionResolver, config,
+ new AccountAwareStorageBackend<>(rawProxies, null, accountId),
+ new AccountAwareStorageBackend<>(rawTargetGroups, null, accountId),
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.restorePersistedRuntime();
+
+ assertSame(invalidName, rawProxies.get(
+ accountId + "/us-east-1::bad/name").orElseThrow());
+ assertSame(blankRegion, rawProxies.get(
+ accountId + "/us-east-1::blank-region").orElseThrow());
+ assertNull(invalidName.getDefaultAuthScheme());
+ assertNull(blankRegion.getDefaultAuthScheme());
+ assertTrue(rawTargetGroups.keys().isEmpty());
+ }
+
+ @Test
+ void proxyRestoreDoesNotClaimWrongKeyTargetGroup() {
+ when(config.services().rds().mock()).thenReturn(true);
+ String accountId = "123456789012";
+ String otherAccount = "999999999999";
+ InMemoryStorage<String, DbProxy> rawProxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> rawTargetGroups = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", accountId, "current", 5432);
+ DbProxyTargetGroup wrongKey = persistedTargetGroup(
+ "app-proxy", "us-east-1", accountId, "current");
+ wrongKey.setCreatedAt(proxy.getCreatedAt());
+ wrongKey.setUpdatedAt(proxy.getCreatedAt());
+ wrongKey.setMaxConnectionsPercent(37);
+ wrongKey.setTargets(List.of(new DbProxyTarget(
+ "RDS_INSTANCE", "marker",
+ "arn:aws:rds:us-east-1:" + accountId + ":db:marker",
+ "localhost", 5432)));
+ rawProxies.put(accountId + "/us-east-1::app-proxy", proxy);
+ String wrongRawKey = otherAccount + "/us-east-1::wrong";
+ rawTargetGroups.put(wrongRawKey, wrongKey);
+ RdsService service = proxyStoreService(
+ regionResolver, config,
+ new AccountAwareStorageBackend<>(rawProxies, null, accountId),
+ new AccountAwareStorageBackend<>(rawTargetGroups, null, accountId),
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.restorePersistedRuntime();
+
+ DbProxyTargetGroup canonical = rawTargetGroups.get(
+ accountId + "/us-east-1::app-proxy").orElseThrow();
+ assertSame(wrongKey, rawTargetGroups.get(wrongRawKey).orElseThrow());
+ assertNotSame(wrongKey, canonical);
+ assertNotEquals(wrongKey.getTargetGroupArn(), canonical.getTargetGroupArn());
+ assertTrue(canonical.getTargets().isEmpty());
+ assertEquals(100, canonical.getMaxConnectionsPercent());
+ assertEquals(37, wrongKey.getMaxConnectionsPercent());
+ }
+
+ @Test
+ void restoreNormalizesLegacyTargetGroupWithoutLosingTargetsOrPoolConfiguration() {
+ when(config.services().rds().mock()).thenReturn(true);
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "legacy", 3306);
+ proxy.setEngineFamily("MYSQL");
+ proxy.setCreatedAt(null);
+ proxy.setUpdatedAt(null);
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "legacy");
+ targetGroup.setTargetGroupName(null);
+ targetGroup.setDefaultTargetGroup(false);
+ targetGroup.setCreatedAt(null);
+ targetGroup.setUpdatedAt(null);
+ targetGroup.setMaxConnectionsPercent(71);
+ targetGroup.setMaxIdleConnectionsPercent(29);
+ targetGroup.setConnectionBorrowTimeout(45);
+ targetGroup.setInitQuery("SET application_name = 'floci'");
+ targetGroup.setSessionPinningFilters(List.of("EXCLUDE_VARIABLE_SETS"));
+ DbProxyTarget target = new DbProxyTarget(
+ "RDS_INSTANCE", "db1",
+ "arn:aws:rds:us-east-1:123456789012:db:db1", "localhost", 5432);
+ targetGroup.setTargets(List.of(target));
+ proxies.put("app-proxy", proxy);
+ targetGroups.put("app-proxy", targetGroup);
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.restorePersistedRuntime();
+
+ DbProxy restoredProxy = service.getDbProxy("app-proxy", "us-east-1");
+ DbProxyTargetGroup restoredGroup = service.describeDbProxyTargetGroups(
+ "app-proxy", "default", "us-east-1").iterator().next();
+ assertNotNull(restoredProxy.getCreatedAt());
+ assertEquals(restoredProxy.getCreatedAt(), restoredGroup.getCreatedAt());
+ assertEquals("default", restoredGroup.getTargetGroupName());
+ assertTrue(restoredGroup.isDefaultTargetGroup());
+ assertEquals(List.of(target), restoredGroup.getTargets());
+ assertEquals(71, restoredGroup.getMaxConnectionsPercent());
+ assertEquals(29, restoredGroup.getMaxIdleConnectionsPercent());
+ assertEquals(45, restoredGroup.getConnectionBorrowTimeout());
+ assertEquals("SET application_name = 'floci'", restoredGroup.getInitQuery());
+ assertEquals(List.of("EXCLUDE_VARIABLE_SETS"),
+ restoredGroup.getSessionPinningFilters());
+ assertTrue(proxies.get("app-proxy").isEmpty());
+ assertTrue(targetGroups.get("app-proxy").isEmpty());
+ }
+
+ @Test
+ void deleteDbProxySucceedsWhenItsCanonicalTargetGroupIsStale() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "current", 5432);
+ DbProxyTargetGroup staleTargetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "stale");
+ proxies.put("us-east-1::app-proxy", proxy);
+ targetGroups.put("us-east-1::app-proxy", staleTargetGroup);
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ assertDoesNotThrow(() -> service.deleteDbProxy("app-proxy", "us-east-1"));
+
+ assertTrue(proxies.get("us-east-1::app-proxy").isEmpty());
+ assertTrue(targetGroups.get("us-east-1::app-proxy").isEmpty());
+ verify(proxyManager).stopProxy("db-proxy:" + proxy.getDbProxyArn());
+ }
+
+ @Test
+ void deleteDbProxySucceedsWhenTargetGroupIsMissing() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "current", 5432);
+ proxies.put("us-east-1::app-proxy", proxy);
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ assertDoesNotThrow(() -> service.deleteDbProxy("app-proxy", "us-east-1"));
+
+ assertTrue(proxies.get("us-east-1::app-proxy").isEmpty());
+ assertTrue(targetGroups.get("us-east-1::app-proxy").isEmpty());
+ verify(proxyManager).stopProxy("db-proxy:" + proxy.getDbProxyArn());
+ }
+
+ @Test
+ void failedDbProxyDeleteKeepsPortReservedUntilRetrySucceeds() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups =
+ spy(new InMemoryStorage<>());
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ instances, new InMemoryStorage<>());
+ DbProxy first = service.createDbProxy(
+ "first-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ DbProxyTargetGroup originalTargetGroup = targetGroups.get(
+ "us-east-1::first-proxy").orElseThrow();
+ originalTargetGroup.setMaxConnectionsPercent(79);
+ originalTargetGroup.setMaxIdleConnectionsPercent(33);
+ originalTargetGroup.setConnectionBorrowTimeout(45);
+ originalTargetGroup.setInitQuery("SET application_name = 'floci'");
+ originalTargetGroup.setSessionPinningFilters(List.of("EXCLUDE_VARIABLE_SETS"));
+ originalTargetGroup.setTargets(List.of(new DbProxyTarget(
+ "RDS_INSTANCE", "db1",
+ "arn:aws:rds:us-east-1:123456789012:db:db1", "localhost", 15432)));
+ DbInstance instance = persistedInstance("db1", "123456789012", "secret", 15432);
+ instance.setContainerHost("localhost");
+ instance.setContainerPort(15432);
+ instances.put("db1", instance);
+ AtomicBoolean relayRunning = new AtomicBoolean(true);
+ doAnswer(invocation -> {
+ relayRunning.set(false);
+ return null;
+ }).when(proxyManager).stopProxy("db-proxy:" + first.getDbProxyArn());
+ doAnswer(invocation -> {
+ relayRunning.set(true);
+ return null;
+ }).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
+ anyInt(), any(), any(), any(), any());
+ IllegalStateException deleteFailure =
+ new IllegalStateException("simulated post-mutation target-group delete failure");
+ doAnswer(invocation -> {
+ invocation.callRealMethod();
+ throw deleteFailure;
+ }).doCallRealMethod().when(targetGroups).delete("us-east-1::first-proxy");
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
+ service.deleteDbProxy("first-proxy", "us-east-1"));
+ assertSame(deleteFailure, thrown);
+ assertEquals(first.getDbProxyArn(),
+ service.getDbProxy("first-proxy", "us-east-1").getDbProxyArn());
+ assertProxyTargetGroupState(originalTargetGroup,
+ targetGroups.get("us-east-1::first-proxy").orElseThrow());
+ assertTrue(relayRunning.get());
+
+ DbProxy second = service.createDbProxy(
+ "second-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ assertNotEquals(first.getProxyPort(), second.getProxyPort());
+
+ assertDoesNotThrow(() -> service.deleteDbProxy("first-proxy", "us-east-1"));
+ assertFalse(relayRunning.get());
+ DbProxy third = service.createDbProxy(
+ "third-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ assertEquals(first.getProxyPort(), third.getProxyPort());
+ }
+
+ @Test
+ void mutateThenThrowDbProxyDeleteRestoresRetryOwnerAndKeepsPortReserved() {
+ InMemoryStorage<String, DbProxy> proxies =
+ spy(new InMemoryStorage<String, DbProxy>());
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ instances, new InMemoryStorage<>());
+ DbProxy first = service.createDbProxy(
+ "first-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ DbProxyTargetGroup originalTargetGroup = targetGroups.get(
+ "us-east-1::first-proxy").orElseThrow();
+ originalTargetGroup.setMaxConnectionsPercent(79);
+ originalTargetGroup.setMaxIdleConnectionsPercent(33);
+ originalTargetGroup.setConnectionBorrowTimeout(45);
+ originalTargetGroup.setInitQuery("SET application_name = 'floci'");
+ originalTargetGroup.setSessionPinningFilters(List.of("EXCLUDE_VARIABLE_SETS"));
+ originalTargetGroup.setTargets(List.of(new DbProxyTarget(
+ "RDS_INSTANCE", "db1",
+ "arn:aws:rds:us-east-1:123456789012:db:db1", "localhost", 15432)));
+ DbInstance instance = persistedInstance("db1", "123456789012", "secret", 15432);
+ instance.setContainerHost("localhost");
+ instance.setContainerPort(15432);
+ instances.put("db1", instance);
+ AtomicBoolean relayRunning = new AtomicBoolean(true);
+ doAnswer(invocation -> {
+ relayRunning.set(false);
+ return null;
+ }).when(proxyManager).stopProxy("db-proxy:" + first.getDbProxyArn());
+ doAnswer(invocation -> {
+ relayRunning.set(true);
+ return null;
+ }).when(proxyManager).startProxy(any(), any(), anyBoolean(), anyInt(), any(),
+ anyInt(), any(), any(), any(), any());
+ IllegalStateException deleteFailure =
+ new IllegalStateException("simulated post-mutation proxy delete failure");
+ doAnswer(invocation -> {
+ invocation.callRealMethod();
+ throw deleteFailure;
+ }).doCallRealMethod().when(proxies).delete("us-east-1::first-proxy");
+
+ IllegalStateException thrown = assertThrows(IllegalStateException.class, () ->
+ service.deleteDbProxy("first-proxy", "us-east-1"));
+ assertSame(deleteFailure, thrown);
+ assertEquals(first.getDbProxyArn(), proxies.get(
+ "us-east-1::first-proxy").orElseThrow().getDbProxyArn());
+ assertProxyTargetGroupState(originalTargetGroup,
+ targetGroups.get("us-east-1::first-proxy").orElseThrow());
+ assertTrue(relayRunning.get());
+
+ DbProxy second = service.createDbProxy(
+ "second-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ assertNotEquals(first.getProxyPort(), second.getProxyPort());
+
+ assertDoesNotThrow(() -> service.deleteDbProxy("first-proxy", "us-east-1"));
+ assertFalse(relayRunning.get());
+ DbProxy third = service.createDbProxy(
+ "third-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ assertEquals(first.getProxyPort(), third.getProxyPort());
+ }
+
+ @Test
+ void staleGenerationTargetGroupDoesNotBlockDbInstanceDeletion() {
+ when(config.services().rds().mock()).thenReturn(true);
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ InMemoryStorage<String, DbInstance> instances = new InMemoryStorage<>();
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ instances, new InMemoryStorage<>());
+ DbInstance instance = service.createDbInstance(
+ "db1", "postgres", "16.3", "admin", "secret", "app",
+ "db.t3.micro", 20, false, null, null, null);
+ DbProxy currentProxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "current", 5432);
+ DbProxyTargetGroup staleTargetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "stale");
+ staleTargetGroup.setTargets(List.of(new DbProxyTarget(
+ "RDS_INSTANCE", "db1", instance.getDbInstanceArn(), "localhost", 5432)));
+ proxies.put("us-east-1::app-proxy", currentProxy);
+ targetGroups.put("us-east-1::app-proxy", staleTargetGroup);
+
+ assertDoesNotThrow(() -> service.deleteDbInstance("db1", "us-east-1"));
+
+ assertThrows(AwsException.class, () -> service.getDbInstance("db1", "us-east-1"));
+ assertSame(staleTargetGroup,
+ targetGroups.get("us-east-1::app-proxy").orElseThrow());
+ }
+
+ @Test
+ void unsupportedPartitionAndMalformedTargetGroupResourceAreRejected() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "valid", 5432);
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "valid");
+ targetGroup.setCreatedAt(proxy.getCreatedAt());
+ targetGroup.setUpdatedAt(proxy.getCreatedAt());
+ targetGroup.setTargetGroupArn(
+ "arn:bogus:rds:us-east-1:123456789012:target-group:prx-tg-valid:garbage");
+ proxies.put("us-east-1::app-proxy", proxy);
+ targetGroups.put("us-east-1::app-proxy", targetGroup);
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ AwsException missing = assertThrows(AwsException.class, () ->
+ service.describeDbProxyTargets("app-proxy", "default", "us-east-1"));
+
+ assertEquals("DBProxyTargetGroupNotFoundFault", missing.getErrorCode());
+ assertSame(targetGroup, targetGroups.get("us-east-1::app-proxy").orElseThrow());
+ }
+
+ @Test
+ void guardedLegacyRdsLookupsEnforceAccountOwnership() {
+ String foreignAccount = "222222222222";
+ String currentAccount = "333333333333";
+ RegionResolver currentResolver = new RegionResolver("us-east-1", currentAccount);
+ EmulatorConfig currentConfig = mock(EmulatorConfig.class);
+ when(currentConfig.defaultAccountId()).thenReturn(currentAccount);
+
+ InMemoryStorage<String, DbCluster> rawForeignClusters = new InMemoryStorage<>();
+ InMemoryStorage<String, DbInstance> rawForeignInstances = new InMemoryStorage<>();
+ rawForeignClusters.put("cluster1", persistedCluster(foreignAccount, "secret", 7000));
+ rawForeignInstances.put("instance1", persistedInstance(
+ "instance1", foreignAccount, "secret", 7001));
+ rawForeignClusters.put(currentAccount + "/scoped-cluster",
+ persistedCluster(foreignAccount, "secret", 7002));
+ rawForeignInstances.put(currentAccount + "/scoped-instance",
+ persistedInstance("scoped-instance", foreignAccount, "secret", 7003));
+ RdsService foreignService = proxyStoreService(
+ currentResolver, currentConfig, new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new AccountAwareStorageBackend<>(rawForeignInstances, null, currentAccount),
+ new AccountAwareStorageBackend<>(rawForeignClusters, null, currentAccount));
+
+ assertThrows(AwsException.class, () -> foreignService.getDbCluster("cluster1"));
+ assertThrows(AwsException.class, () -> foreignService.getDbInstance("instance1"));
+ assertTrue(foreignService.listDbClusters(null).isEmpty());
+ assertTrue(foreignService.listDbInstances(null).isEmpty());
+ assertTrue(rawForeignClusters.get("cluster1").isPresent());
+ assertTrue(rawForeignInstances.get("instance1").isPresent());
+ assertTrue(rawForeignClusters.get(currentAccount + "/cluster1").isEmpty());
+ assertTrue(rawForeignInstances.get(currentAccount + "/instance1").isEmpty());
+
+ InMemoryStorage<String, DbCluster> rawOwnedClusters = new InMemoryStorage<>();
+ InMemoryStorage<String, DbInstance> rawOwnedInstances = new InMemoryStorage<>();
+ rawOwnedClusters.put("cluster1", persistedCluster(currentAccount, "secret", 7000));
+ rawOwnedInstances.put("instance1", persistedInstance(
+ "instance1", currentAccount, "secret", 7001));
+ RdsService ownedService = proxyStoreService(
+ currentResolver, currentConfig, new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new AccountAwareStorageBackend<>(rawOwnedInstances, null, currentAccount),
+ new AccountAwareStorageBackend<>(rawOwnedClusters, null, currentAccount));
+
+ assertEquals("cluster1", ownedService.getDbCluster("cluster1").getDbClusterIdentifier());
+ assertEquals("instance1", ownedService.getDbInstance("instance1").getDbInstanceIdentifier());
+ assertTrue(rawOwnedClusters.get("cluster1").isEmpty());
+ assertTrue(rawOwnedInstances.get("instance1").isEmpty());
+ assertTrue(rawOwnedClusters.get(
+ currentAccount + "/us-east-1::cluster1").isPresent());
+ assertTrue(rawOwnedInstances.get(
+ currentAccount + "/us-east-1::instance1").isPresent());
+ }
+
+ @Test
+ void sameNamedInstancesInDifferentAccountsUseIndependentRelayKeys() {
+ String accountA = "111111111111";
+ String accountB = "222222222222";
+ InMemoryStorage<String, DbInstance> rawInstances = new InMemoryStorage<>();
+ InMemoryStorage<String, DbCluster> rawClusters = new InMemoryStorage<>();
+ RdsService serviceA = new RdsService(
+ containerManager, proxyManager, ec2Service,
+ new RegionResolver("us-east-1", accountA), config,
+ new AccountAwareStorageBackend<>(rawInstances, null, accountA),
+ new AccountAwareStorageBackend<>(rawClusters, null, accountA),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
+ RdsService serviceB = new RdsService(
+ containerManager, proxyManager, ec2Service,
+ new RegionResolver("us-east-1", accountB), config,
+ new AccountAwareStorageBackend<>(rawInstances, null, accountB),
+ new AccountAwareStorageBackend<>(rawClusters, null, accountB),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ DbInstance instanceA = serviceA.createDbInstance(
+ "shared-db", "postgres", "16.3", "admin", "secret", "app",
+ "db.t3.micro", 20, false, null, null, null);
+ DbInstance instanceB = serviceB.createDbInstance(
+ "shared-db", "postgres", "16.3", "admin", "secret", "app",
+ "db.t3.micro", 20, false, null, null, null);
+ String relayKeyA = "rds-resource:" + instanceA.getDbInstanceArn();
+ String relayKeyB = "rds-resource:" + instanceB.getDbInstanceArn();
+
+ verify(proxyManager).startProxy(eq(relayKeyA), any(), anyBoolean(), anyInt(),
+ any(), anyInt(), any(), any(), any(), any());
+ verify(proxyManager).startProxy(eq(relayKeyB), any(), anyBoolean(), anyInt(),
+ any(), anyInt(), any(), any(), any(), any());
+
+ org.mockito.Mockito.clearInvocations(proxyManager);
+ serviceA.deleteDbInstance("shared-db");
+
+ verify(proxyManager).stopProxy(relayKeyA);
+ verify(proxyManager, never()).stopProxy(relayKeyB);
+ assertTrue(rawInstances.get(accountA + "/us-east-1::shared-db").isEmpty());
+ assertTrue(rawInstances.get(accountB + "/us-east-1::shared-db").isPresent());
+ }
+
+ @Test
+ void sameNamedInstancesAndClustersAreIsolatedByRegion() {
+ when(config.services().rds().mock()).thenReturn(true);
+ String accountId = "123456789012";
+ InMemoryStorage<String, DbInstance> rawInstances = new InMemoryStorage<>();
+ InMemoryStorage<String, DbCluster> rawClusters = new InMemoryStorage<>();
+ RdsService service = new RdsService(
+ containerManager, proxyManager, ec2Service, regionResolver, config,
+ new AccountAwareStorageBackend<>(rawInstances, null, accountId),
+ new AccountAwareStorageBackend<>(rawClusters, null, accountId),
+ new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ DbInstance eastInstance = service.createDbInstance(
+ "shared", "postgres", "16.3", "admin", "east-secret", "app",
+ "db.t3.micro", 20, false, null, null, null, null, false,
+ false, null, Map.of(), List.of(), "us-east-1");
+ DbInstance westInstance = service.createDbInstance(
+ "shared", "postgres", "16.3", "admin", "west-secret", "app",
+ "db.t3.micro", 20, false, null, null, null, null, false,
+ false, null, Map.of(), List.of(), "us-west-2");
+ DbCluster eastCluster = service.createDbCluster(
+ "shared", "aurora-postgresql", "16.3", "admin", "east-cluster",
+ "app", false, null, null, null, false, "us-east-1");
+ DbCluster westCluster = service.createDbCluster(
+ "shared", "aurora-postgresql", "16.3", "admin", "west-cluster",
+ "app", false, null, null, null, false, "us-west-2");
+
+ assertEquals(eastInstance.getDbInstanceArn(),
+ service.getDbInstance("shared", "us-east-1").getDbInstanceArn());
+ assertEquals(westInstance.getDbInstanceArn(),
+ service.getDbInstance("shared", "us-west-2").getDbInstanceArn());
+ assertEquals(eastCluster.getDbClusterArn(),
+ service.getDbCluster("shared", "us-east-1").getDbClusterArn());
+ assertEquals(westCluster.getDbClusterArn(),
+ service.getDbCluster("shared", "us-west-2").getDbClusterArn());
+ assertNotEquals(eastInstance.getContainerStorageResourceId(),
+ westInstance.getContainerStorageResourceId());
+ assertNotEquals(eastInstance.getContainerStorageResourceId(),
+ eastCluster.getContainerStorageResourceId());
+ assertTrue(rawInstances.get(accountId + "/us-east-1::shared").isPresent());
+ assertTrue(rawInstances.get(accountId + "/us-west-2::shared").isPresent());
+ assertTrue(rawClusters.get(accountId + "/us-east-1::shared").isPresent());
+ assertTrue(rawClusters.get(accountId + "/us-west-2::shared").isPresent());
+
+ service.modifyDbInstance(
+ "shared", "east-updated", null, null, List.of(), "us-east-1");
+ service.modifyDbCluster(
+ "shared", "east-cluster-updated", null, "us-east-1");
+ service.addTagsToResource(
+ eastInstance.getDbInstanceArn(), Map.of("region", "east"), "us-east-1");
+ assertEquals("east-updated",
+ service.getDbInstance("shared", "us-east-1").getMasterPassword());
+ assertEquals("west-secret",
+ service.getDbInstance("shared", "us-west-2").getMasterPassword());
+ assertEquals("east-cluster-updated",
+ service.getDbCluster("shared", "us-east-1").getMasterPassword());
+ assertEquals("west-cluster",
+ service.getDbCluster("shared", "us-west-2").getMasterPassword());
+ assertEquals(Map.of("region", "east"),
+ service.listTagsForResource(eastInstance.getDbInstanceArn(), "us-east-1"));
+ assertEquals(Map.of(),
+ service.listTagsForResource(westInstance.getDbInstanceArn(), "us-west-2"));
+
+ service.deleteDbInstance("shared", "us-east-1");
+ service.deleteDbCluster("shared", "us-east-1");
+ assertThrows(AwsException.class,
+ () -> service.getDbInstance("shared", "us-east-1"));
+ assertThrows(AwsException.class,
+ () -> service.getDbCluster("shared", "us-east-1"));
+ assertEquals(westInstance.getDbInstanceArn(),
+ service.getDbInstance("shared", "us-west-2").getDbInstanceArn());
+ assertEquals(westCluster.getDbClusterArn(),
+ service.getDbCluster("shared", "us-west-2").getDbClusterArn());
+ }
+
+ @Test
+ void proxyRegistrationCannotClaimForeignLegacyTarget() {
+ when(config.services().rds().mock()).thenReturn(true);
+ String currentAccount = "123456789012";
+ String foreignAccount = "222222222222";
+ InMemoryStorage<String, DbCluster> rawClusters = new InMemoryStorage<>();
+ rawClusters.put("cluster1", persistedCluster(foreignAccount, "secret", 7000));
+ AccountAwareStorageBackend<DbCluster> clusters =
+ new AccountAwareStorageBackend<>(rawClusters, null, currentAccount);
+ RdsService service = proxyStoreService(
+ regionResolver, config,
+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, currentAccount),
+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, currentAccount),
+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, currentAccount),
+ clusters);
+ service.createDbProxy(
+ "app-proxy", "POSTGRESQL", true, false, "NONE", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH,
+ 1800, false, Map.of(), "us-east-1");
+
+ AwsException exception = assertThrows(AwsException.class, () ->
+ service.registerDbProxyTargets(
+ "app-proxy", "default", List.of("cluster1"), List.of(),
+ 0, 0, "us-east-1"));
+
+ assertEquals("DBClusterNotFoundFault", exception.getErrorCode());
+ assertTrue(rawClusters.get("cluster1").isPresent());
+ assertTrue(rawClusters.get(currentAccount + "/cluster1").isEmpty());
+ verify(proxyManager, never()).startProxy(
+ any(), any(), anyBoolean(), anyInt(), any(), anyInt(), any(), any(), any(), any());
+ }
+
+ @Test
+ void foreignAccountProxyRestoreDoesNotDeriveVpcFromDefaultAccount() {
+ when(config.services().rds().mock()).thenReturn(true);
+ String defaultAccount = "123456789012";
+ String foreignAccount = "999999999999";
+ InMemoryStorage<String, DbProxy> rawProxies = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "foreign-proxy", "us-east-1", foreignAccount, "foreign", 5432);
+ proxy.setVpcId(null);
+ rawProxies.put(foreignAccount + "/foreign-proxy", proxy);
+ RdsService service = proxyStoreService(
+ regionResolver, config,
+ new AccountAwareStorageBackend<>(rawProxies, null, defaultAccount),
+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, defaultAccount),
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.restorePersistedRuntime();
+
+ DbProxy restored = rawProxies.get(
+ foreignAccount + "/us-east-1::foreign-proxy").orElseThrow();
+ assertNull(restored.getVpcId());
+ }
+
+ @Test
+ void restorePreservesSameNameLegacyAndCanonicalProxiesAcrossRegions() {
+ when(config.services().rds().mock()).thenReturn(true);
+ String accountId = "123456789012";
+ InMemoryStorage<String, DbProxy> rawProxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> rawTargetGroups = new InMemoryStorage<>();
+ DbProxy east = persistedProxy(
+ "shared-proxy", "us-east-1", accountId, "east", 5432);
+ DbProxy west = persistedProxy(
+ "shared-proxy", "us-west-2", accountId, "west", 7002);
+ DbProxyTargetGroup eastTargetGroup = persistedTargetGroup(
+ "shared-proxy", "us-east-1", accountId, "east");
+ eastTargetGroup.setCreatedAt(east.getCreatedAt());
+ eastTargetGroup.setUpdatedAt(east.getCreatedAt());
+ eastTargetGroup.setTargets(List.of(new DbProxyTarget(
+ "TRACKED_CLUSTER", "east-cluster",
+ "arn:aws:rds:us-east-1:" + accountId + ":cluster:east-cluster",
+ "localhost", 5432)));
+ DbProxyTargetGroup westTargetGroup = persistedTargetGroup(
+ "shared-proxy", "us-west-2", accountId, "west");
+ westTargetGroup.setCreatedAt(west.getCreatedAt());
+ westTargetGroup.setUpdatedAt(west.getCreatedAt());
+ westTargetGroup.setTargets(List.of(new DbProxyTarget(
+ "TRACKED_CLUSTER", "west-cluster",
+ "arn:aws:rds:us-west-2:" + accountId + ":cluster:west-cluster",
+ "localhost", 5432)));
+ rawProxies.put(accountId + "/shared-proxy", east);
+ rawProxies.put(accountId + "/us-west-2::shared-proxy", west);
+ rawTargetGroups.put(accountId + "/shared-proxy", eastTargetGroup);
+ rawTargetGroups.put(accountId + "/us-west-2::shared-proxy", westTargetGroup);
+ RdsService service = proxyStoreService(
+ regionResolver, config,
+ new AccountAwareStorageBackend<>(rawProxies, null, accountId),
+ new AccountAwareStorageBackend<>(rawTargetGroups, null, accountId),
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.restorePersistedRuntime();
+
+ assertEquals("prx-east", rawProxies.get(
+ accountId + "/us-east-1::shared-proxy").orElseThrow().getDbProxyResourceId());
+ assertEquals("prx-west", rawProxies.get(
+ accountId + "/us-west-2::shared-proxy").orElseThrow().getDbProxyResourceId());
+ assertEquals("east-cluster", rawTargetGroups.get(
+ accountId + "/us-east-1::shared-proxy").orElseThrow()
+ .getTargets().getFirst().getRdsResourceId());
+ assertEquals("west-cluster", rawTargetGroups.get(
+ accountId + "/us-west-2::shared-proxy").orElseThrow()
+ .getTargets().getFirst().getRdsResourceId());
+ assertTrue(rawProxies.get(accountId + "/shared-proxy").isEmpty());
+ assertTrue(rawTargetGroups.get(accountId + "/shared-proxy").isEmpty());
+ }
+
+ @Test
+ void failedCrossEngineRestoreKeepsProxyPortReserved() {
+ InMemoryStorage<String, DbCluster> clusters = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ DbCluster cluster = persistedCluster("123456789012", "secret", 7000);
+ clusters.put("cluster1", cluster);
+ DbProxy proxy = persistedProxy(
+ "mysql-proxy", "us-east-1", "123456789012", "mysql", 3306);
+ proxy.setEngineFamily("MYSQL");
+ proxies.put("us-east-1::mysql-proxy", proxy);
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "mysql-proxy", "us-east-1", "123456789012", "mysql");
+ targetGroup.setCreatedAt(proxy.getCreatedAt());
+ targetGroup.setUpdatedAt(proxy.getCreatedAt());
+ targetGroup.setTargets(List.of(new DbProxyTarget(
+ "TRACKED_CLUSTER", "cluster1", cluster.getDbClusterArn(), "localhost", 5432)));
+ targetGroups.put("us-east-1::mysql-proxy", targetGroup);
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), clusters);
+
+ service.restorePersistedRuntime();
+
+ DbProxy failed = service.getDbProxy("mysql-proxy", "us-east-1");
+ assertEquals("insufficient-resource-limits", failed.getStatus());
+ verify(proxyManager, never()).startProxy(
+ eq("db-proxy:" + proxy.getDbProxyArn()), any(), anyBoolean(), anyInt(),
+ any(), anyInt(), any(), any(), any(), any());
+
+ DbProxy another = service.createDbProxy(
+ "another-proxy", "MYSQL", true, false, "NONE", PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, 1800, false, Map.of(), "us-east-1");
+ assertNotEquals(failed.getProxyPort(), another.getProxyPort());
+
+ service.deregisterDbProxyTargets(
+ "mysql-proxy", "default", List.of("cluster1"), List.of());
+ service.createDbInstance(
+ "mysql-db", "mysql", "8.0", "admin", "secret", "app",
+ "db.t3.micro", 20, false, null, null, null);
+ service.registerDbProxyTargets(
+ "mysql-proxy", "default", List.of(), List.of("mysql-db"), 0, 0);
+
+ assertEquals("available",
+ service.getDbProxy("mysql-proxy", "us-east-1").getStatus());
+ verify(proxyManager).startProxy(
+ eq("db-proxy:" + proxy.getDbProxyArn()), eq(DatabaseEngine.MYSQL),
+ anyBoolean(), eq(failed.getProxyPort()), any(), anyInt(),
+ any(), any(), any(), any());
+ }
+
+ @Test
+ void restoreProxyWithoutTargetsRecoversAvailableStatus() {
+ InMemoryStorage<String, DbProxy> proxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> targetGroups = new InMemoryStorage<>();
+ DbProxy proxy = persistedProxy(
+ "app-proxy", "us-east-1", "123456789012", "current", 5432);
+ proxy.setStatus("insufficient-resource-limits");
+ DbProxyTargetGroup targetGroup = persistedTargetGroup(
+ "app-proxy", "us-east-1", "123456789012", "current");
+ targetGroup.setCreatedAt(proxy.getCreatedAt());
+ targetGroup.setUpdatedAt(proxy.getCreatedAt());
+ proxies.put("us-east-1::app-proxy", proxy);
+ targetGroups.put("us-east-1::app-proxy", targetGroup);
+ RdsService service = proxyStoreService(
+ regionResolver, config, proxies, targetGroups,
+ new InMemoryStorage<>(), new InMemoryStorage<>());
+
+ service.restorePersistedRuntime();
+
+ assertEquals("available",
+ service.getDbProxy("app-proxy", "us-east-1").getStatus());
+ verify(proxyManager, never()).startProxy(
+ eq("db-proxy:" + proxy.getDbProxyArn()), any(), anyBoolean(), anyInt(),
+ any(), anyInt(), any(), any(), any(), any());
+ }
+
+ @Test
+ void proxyTargetGroupRejectsUnsupportedNameCardinalityAndEngine() {
+ when(config.services().rds().mock()).thenReturn(true);
+ rdsService.createDbCluster("cluster1", "aurora-postgresql", "16.3",
+ "admin", "secret", "app", false, null);
+ rdsService.createDbProxy("mysql-proxy", "MYSQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+
+ AwsException missingGroup = assertThrows(AwsException.class, () ->
+ rdsService.describeDbProxyTargets("mysql-proxy", "other"));
+ assertEquals("DBProxyTargetGroupNotFoundFault", missingGroup.getErrorCode());
+
+ AwsException multiple = assertThrows(AwsException.class, () ->
+ rdsService.registerDbProxyTargets("mysql-proxy", "default",
+ List.of("cluster1", "cluster2"), List.of(), 0, 0));
+ assertEquals("InvalidParameterCombination", multiple.getErrorCode());
+
+ AwsException mismatch = assertThrows(AwsException.class, () ->
+ rdsService.registerDbProxyTargets("mysql-proxy", "default",
+ List.of("cluster1"), List.of(), 0, 0));
+ assertEquals("InvalidParameterValue", mismatch.getErrorCode());
+ }
+
+ @Test
+ void restorePersistedRuntimeReArmsDbProxyRelayAcrossRestart() {
+ StorageBackend<String, DbInstance> instances = new InMemoryStorage<>();
+ StorageBackend<String, DbCluster> clusters = new InMemoryStorage<>();
+ StorageBackend<String, DbParameterGroup> parameterGroups = new InMemoryStorage<>();
+ StorageBackend<String, DbClusterParameterGroup> clusterParameterGroups = new InMemoryStorage<>();
+ StorageBackend<String, DbSubnetGroup> subnetGroups = new InMemoryStorage<>();
+ // Shared across the two RdsService instances: this is what persists a proxy over a "restart".
+ StorageBackend<String, DbProxy> proxies = new InMemoryStorage<>();
+ StorageBackend<String, DbProxyTargetGroup> proxyTargetGroups = new InMemoryStorage<>();
+
+ when(containerManager.start(any(), any(), any(), any(), any(), any(), any(), any(), any()))
+ .thenReturn(new RdsContainerHandle("initial-container", "cluster1", "localhost", 5432));
+
+ RdsService initialService = new RdsService(containerManager, proxyManager, ec2Service,
+ regionResolver, config, instances, clusters, parameterGroups, clusterParameterGroups,
+ subnetGroups, null, null, proxies, proxyTargetGroups);
+ initialService.createDbCluster("cluster1", "aurora-postgresql", "16.3",
+ "admin", "secret", "app", false, null);
+ initialService.createDbProxy("app-proxy", "POSTGRESQL", true, false, PROXY_ROLE_ARN,
+ PROXY_SUBNET_IDS, List.of(), PROXY_AUTH, Map.of());
+ initialService.registerDbProxyTargets("app-proxy", null, List.of("cluster1"), List.of(), 0, 0);
+
+ RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class);
+ RdsProxyManager restoredProxyManager = mock(RdsProxyManager.class);
+ when(restoredContainerManager.start(any(), any(), any(), any(), any(), any(), any(), any(), any()))
+ .thenReturn(new RdsContainerHandle("restored-container", "cluster1", "127.0.0.1", 15432));
+
+ RdsService restoredService = new RdsService(restoredContainerManager, restoredProxyManager, ec2Service,
+ regionResolver, config, instances, clusters, parameterGroups, clusterParameterGroups,
+ subnetGroups, null, null, proxies, proxyTargetGroups);
+ restoredService.restorePersistedRuntime();
+
+ // The proxy survives the restart and its relay is re-armed against the restored backend.
+ DbProxy restored = restoredService.getDbProxy("app-proxy");
+ assertEquals("app-proxy", restored.getDbProxyName());
+ verify(restoredProxyManager).startProxy(eq("db-proxy:" + restored.getDbProxyArn()),
+ eq(DatabaseEngine.POSTGRES),
+ eq(false), anyInt(), eq("127.0.0.1"), eq(15432),
+ eq("admin"), eq("secret"), eq("app"), any());
+ }
+
+ @Test
+ void restoreDbProxyAuthCallbackKeepsTheTargetAccount() {
+ String defaultAccount = "123456789012";
+ String targetAccount = "999999999999";
+ InMemoryStorage<String, DbInstance> rawInstances = new InMemoryStorage<>();
+ InMemoryStorage<String, DbCluster> rawClusters = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxy> rawProxies = new InMemoryStorage<>();
+ InMemoryStorage<String, DbProxyTargetGroup> rawTargetGroups = new InMemoryStorage<>();
+
+ // A same-named default-account cluster makes an account-blind callback observably wrong.
+ DbCluster defaultCluster = persistedCluster(
+ defaultAccount, "default-secret", 7000);
+ defaultCluster.setContainerStorageResourceId("cluster-DEFAULT");
+ defaultCluster.setDockerVolumeName("floci-rds-default-cluster");
+ DbCluster targetCluster = persistedCluster(
+ targetAccount, "target-secret", 7001);
+ targetCluster.setContainerStorageResourceId("cluster-TARGET");
+ targetCluster.setDockerVolumeName("floci-rds-target-cluster");
+ rawClusters.put(defaultAccount + "/cluster1", defaultCluster);
+ rawClusters.put(targetAccount + "/cluster1", targetCluster);
+
+ DbProxy proxy = new DbProxy();
+ proxy.setDbProxyName("app-proxy");
+ proxy.setDbProxyArn("arn:aws:rds:us-east-1:" + targetAccount + ":db-proxy:prx-abc");
+ proxy.setDbProxyResourceId("prx-abc");
+ proxy.setEngineFamily("POSTGRESQL");
+ proxy.setProxyPort(5432);
+ proxy.setEndpointHost("stale-host");
+ proxy.setStatus("available");
+ Instant proxyCreatedAt = Instant.now();
+ proxy.setCreatedAt(proxyCreatedAt);
+ rawProxies.put(targetAccount + "/app-proxy", proxy);
+
+ DbProxyTargetGroup targetGroup = new DbProxyTargetGroup();
+ targetGroup.setDbProxyName("app-proxy");
+ targetGroup.setTargetGroupName("default");
+ targetGroup.setTargetGroupArn("arn:aws:rds:us-east-1:" + targetAccount
+ + ":target-group:prx-tg-abc");
+ targetGroup.setCreatedAt(proxyCreatedAt);
+ targetGroup.setUpdatedAt(proxyCreatedAt);
+ targetGroup.setTargets(List.of(new DbProxyTarget("TRACKED_CLUSTER", "cluster1",
+ "arn:aws:rds:us-east-1:" + targetAccount + ":cluster:cluster1",
+ "stale-host", 5432)));
+ rawTargetGroups.put(targetAccount + "/app-proxy", targetGroup);
+
+ RdsContainerManager restoredContainerManager = mock(RdsContainerManager.class);
+ RdsProxyManager restoredProxyManager = mock(RdsProxyManager.class);
+ when(restoredContainerManager.start(any(), any(), any(), any(), any(), any(), any(), any(), any()))
+ .thenReturn(new RdsContainerHandle("restored-container", "cluster1",
+ "127.0.0.1", 15432));
+
+ RdsService restoredService = new RdsService(restoredContainerManager, restoredProxyManager,
+ ec2Service, regionResolver, config,
+ new AccountAwareStorageBackend<>(rawInstances, null, defaultAccount),
+ new AccountAwareStorageBackend<>(rawClusters, null, defaultAccount),
+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, defaultAccount),
+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, defaultAccount),
+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), null, defaultAccount),
+ null, null,
+ new AccountAwareStorageBackend<>(rawProxies, null, defaultAccount),
+ new AccountAwareStorageBackend<>(rawTargetGroups, null, defaultAccount));
+
+ restoredService.restorePersistedRuntime();
+
+ ArgumentCaptor<RdsAuthProxy.PasswordValidator> validator =
+ ArgumentCaptor.forClass(RdsAuthProxy.PasswordValidator.class);
+ verify(restoredProxyManager).startProxy(eq("db-proxy:" + proxy.getDbProxyArn()),
+ eq(DatabaseEngine.POSTGRES),
+ eq(false), eq(5432), eq("127.0.0.1"), eq(15432), eq("admin"),
+ eq("target-secret"), eq("app"), validator.capture());
+ assertTrue(validator.getValue().validate("admin", "target-secret"));
+ assertFalse(validator.getValue().validate("admin", "default-secret"));
+ assertTrue(rawProxies.get(targetAccount + "/us-east-1::app-proxy").isPresent());
+ assertTrue(rawTargetGroups.get(targetAccount + "/us-east-1::app-proxy").isPresent());
+ assertTrue(rawProxies.get(targetAccount + "/app-proxy").isEmpty());
+ assertTrue(rawTargetGroups.get(targetAccount + "/app-proxy").isEmpty());
+ }
+
private RdsService newService(RdsContainerManager containerManager,
RdsProxyManager proxyManager,
StorageBackend<String, DbInstance> instances,
@@ -1178,12 +3749,116 @@ class RdsServiceTest {
secretsManager, null, null);
}
+ private RdsService proxyStoreService(
+ RegionResolver resolver, EmulatorConfig serviceConfig,
+ StorageBackend<String, DbProxy> proxies,
+ StorageBackend<String, DbProxyTargetGroup> targetGroups,
+ StorageBackend<String, DbInstance> instances,
+ StorageBackend<String, DbCluster> clusters) {
+ return new RdsService(containerManager, proxyManager, ec2Service, resolver, serviceConfig,
+ instances, clusters, new InMemoryStorage<>(), new InMemoryStorage<>(),
+ new InMemoryStorage<>(), null, null, proxies, targetGroups);
+ }
+
+ private static DbProxy persistedProxy(
+ String name, String region, String accountId, String suffix, int proxyPort) {
+ DbProxy proxy = new DbProxy();
+ proxy.setDbProxyName(name);
+ proxy.setDbProxyArn("arn:aws:rds:" + region + ":" + accountId
+ + ":db-proxy:prx-" + suffix);
+ proxy.setDbProxyResourceId("prx-" + suffix);
+ proxy.setEngineFamily("POSTGRESQL");
+ proxy.setRoleArn("arn:aws:iam::" + accountId + ":role/proxy");
+ proxy.setVpcId("vpc-default");
+ proxy.setVpcSubnetIds(PROXY_SUBNET_IDS);
+ proxy.setAuth(PROXY_AUTH);
+ proxy.setProxyPort(proxyPort);
+ proxy.setEndpointHost("localhost");
+ proxy.setStatus("available");
+ proxy.setCreatedAt(persistedGenerationTime(suffix));
+ proxy.setUpdatedAt(proxy.getCreatedAt());
+ return proxy;
+ }
+
+ private static DbProxyTargetGroup persistedTargetGroup(
+ String proxyName, String region, String accountId, String suffix) {
+ DbProxyTargetGroup targetGroup = new DbProxyTargetGroup();
+ targetGroup.setDbProxyName(proxyName);
+ targetGroup.setTargetGroupName("default");
+ targetGroup.setTargetGroupArn("arn:aws:rds:" + region + ":" + accountId
+ + ":target-group:prx-tg-" + suffix);
+ targetGroup.setDefaultTargetGroup(true);
+ targetGroup.setCreatedAt(persistedGenerationTime(suffix));
+ targetGroup.setUpdatedAt(targetGroup.getCreatedAt());
+ return targetGroup;
+ }
+
+ private static void assertProxyTargetGroupState(
+ DbProxyTargetGroup expected, DbProxyTargetGroup actual) {
+ assertEquals(expected.getDbProxyName(), actual.getDbProxyName());
+ assertEquals(expected.getTargetGroupName(), actual.getTargetGroupName());
+ assertEquals(expected.getTargetGroupArn(), actual.getTargetGroupArn());
+ assertEquals(expected.getStatus(), actual.getStatus());
+ assertEquals(expected.isDefaultTargetGroup(), actual.isDefaultTargetGroup());
+ assertEquals(expected.getCreatedAt(), actual.getCreatedAt());
+ assertEquals(expected.getUpdatedAt(), actual.getUpdatedAt());
+ assertEquals(expected.getMaxConnectionsPercent(), actual.getMaxConnectionsPercent());
+ assertEquals(expected.getMaxIdleConnectionsPercent(), actual.getMaxIdleConnectionsPercent());
+ assertEquals(expected.getConnectionBorrowTimeout(), actual.getConnectionBorrowTimeout());
+ assertEquals(expected.getInitQuery(), actual.getInitQuery());
+ assertEquals(expected.getSessionPinningFilters(), actual.getSessionPinningFilters());
+ assertEquals(expected.getTargets().size(), actual.getTargets().size());
+ for (int index = 0; index < expected.getTargets().size(); index++) {
+ DbProxyTarget expectedTarget = expected.getTargets().get(index);
+ DbProxyTarget actualTarget = actual.getTargets().get(index);
+ assertEquals(expectedTarget.getType(), actualTarget.getType());
+ assertEquals(expectedTarget.getRdsResourceId(), actualTarget.getRdsResourceId());
+ assertEquals(expectedTarget.getTargetArn(), actualTarget.getTargetArn());
+ assertEquals(expectedTarget.getEndpoint(), actualTarget.getEndpoint());
+ assertEquals(expectedTarget.getPort(), actualTarget.getPort());
+ assertEquals(expectedTarget.getTargetHealth(), actualTarget.getTargetHealth());
+ }
+ }
+
+ private static Instant persistedGenerationTime(String suffix) {
+ return Instant.ofEpochSecond(Integer.toUnsignedLong(suffix.hashCode()));
+ }
+
+ private static DbProxyAuth proxyAuthWithUserName(String userName) {
+ DbProxyAuth auth = new DbProxyAuth(
+ "SECRETS", PROXY_AUTH.getFirst().getSecretArn(), "DISABLED", null, null);
+ auth.setUserName(userName);
+ return auth;
+ }
+
private static List<Subnet> defaultSubnets() {
return List.of(
subnet("subnet-default-a", "vpc-default", "us-east-1a"),
subnet("subnet-default-b", "vpc-default", "us-east-1b"));
}
+ private static DbInstance persistedInstance(
+ String instanceId, String accountId, String password, int proxyPort) {
+ DbInstance instance = new DbInstance(
+ instanceId, DatabaseEngine.POSTGRES, "16.3", "admin", password,
+ "app", "db.t3.micro", 20, DbInstanceStatus.AVAILABLE,
+ new DbEndpoint("stale-host", proxyPort), false, null, null,
+ Instant.now(), proxyPort);
+ instance.setDbInstanceArn(
+ "arn:aws:rds:us-east-1:" + accountId + ":db:" + instanceId);
+ return instance;
+ }
+
+ private static DbCluster persistedCluster(String accountId, String password, int proxyPort) {
+ DbCluster cluster = new DbCluster("cluster1", DatabaseEngine.POSTGRES, "16.3",
+ "admin", password, "app", DbInstanceStatus.AVAILABLE,
+ new DbEndpoint("stale-host", proxyPort), new DbEndpoint("stale-host", proxyPort),
+ false, List.of(), null, Instant.now(), proxyPort);
+ cluster.setDbClusterArn("arn:aws:rds:us-east-1:" + accountId + ":cluster:cluster1");
+ cluster.setVolumeId("volume-" + accountId);
+ return cluster;
+ }
+
private static Subnet subnet(String subnetId, String vpcId, String availabilityZone) {
Subnet subnet = new Subnet();
subnet.setSubnetId(subnetId);
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java
index 09899ad2f3..0b0d65d61d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/container/RdsContainerManagerTest.java
@@ -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];
+ });
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java
new file mode 100644
index 0000000000..bf2878318f
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/rds/proxy/RdsProxyManagerTest.java
@@ -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;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/rdsdata/RdsDataResourceResolverTest.java b/src/test/java/io/github/hectorvent/floci/services/rdsdata/RdsDataResourceResolverTest.java
index b32b4b04af..891c7e6b55 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rdsdata/RdsDataResourceResolverTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rdsdata/RdsDataResourceResolverTest.java
@@ -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);
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/rdsdata/RdsDataServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rdsdata/RdsDataServiceTest.java
index ff5cfb30a3..e41ab3ae73 100644
--- a/src/test/java/io/github/hectorvent/floci/services/rdsdata/RdsDataServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/rdsdata/RdsDataServiceTest.java
@@ -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