mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(rds): model DB proxies and their target groups (#1813)
* feat(rds): model DB proxies and their target groups Add DB proxies as first-class RDS resources for both the RDS Query API and CloudFormation: - RdsService: two persisted stores plus the proxy lifecycle (create/register-targets/describe/delete). A proxy exposes a bare-host endpoint on the engine family's default port; in non-mock mode registering a target starts an auth relay (via RdsProxyManager) that forwards 1:1 to the target cluster/instance, re-armed on restart. - RdsQueryHandler: CreateDBProxy, DeleteDBProxy, RegisterDBProxyTargets, DescribeDBProxyTargetGroups, DescribeDBProxyTargets, and a real DescribeDBProxies listing (2014-10-31 XML shapes). - AwsQueryController: route the six DBProxy actions to RDS. - CloudFormation: provision/delete AWS::RDS::DBProxy and AWS::RDS::DBProxyTargetGroup. This models DB proxies for provisioning and discovery; it does not add real connection pooling (the relay forwards 1:1), so it does not close #1679. * fix(rds): reserve DB proxy port so same-engine proxies get distinct ports createDbProxy used the engine family's default port (5432/3306/1433) directly without reserving it, so two proxies for the same engine got the identical port and the second relay failed to bind in non-mock mode. Reserve the default port via reserveOrAllocateProxyPort, falling back to an allocated pool port when it is already taken — the first proxy keeps the clean bare-host default port, later ones get a distinct port, and the persisted port stays canonical across restarts. * fix(rds): harden DB proxy lifecycle compatibility * fix(rds): complete DB proxy compatibility hardening * fix(rds): make DB proxy lifecycle rollback-safe * fix(rds): default omitted proxy target group * test(dynamodb): retain Quarkus port for cleanup --------- Co-authored-by: Alexander Banna <abanna@users.noreply.github.com>
This commit is contained in:
1 parent
42a79a7fd7
commit
e4010ec12f
38 files changed
+9734
-546
No files matched your search
+61
@@ -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);
|
||||
|
||||
+99
@@ -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<>();
|
||||
|
||||
+249
-7
@@ -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");
|
||||
}
|
||||
}
|
||||
+39
@@ -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);
|
||||
|
||||
+6
-3
@@ -59,6 +59,7 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@@ -1295,10 +1296,12 @@ class ContainerLauncherTest {
|
||||
|
||||
launcherWithRealStreamer.launch(fn);
|
||||
|
||||
// The frame became a CloudWatch log event in the function's own log group.
|
||||
// The frame became a CloudWatch log event in the function's own log group. Forwarding goes
|
||||
// through the account-aware overload with a null account id: exec streams have no owning
|
||||
// account of their own, so they land in the default account's copy of the log group.
|
||||
ArgumentCaptor<List<Map<String, Object>>> events = ArgumentCaptor.forClass(List.class);
|
||||
verify(cloudWatchLogs, atLeastOnce()).putLogEvents(
|
||||
eq("/aws/lambda/observability-fn"), anyString(), events.capture(), anyString());
|
||||
verify(cloudWatchLogs, atLeastOnce()).putLogEventsForAccount(
|
||||
isNull(), eq("/aws/lambda/observability-fn"), anyString(), events.capture(), anyString());
|
||||
assertTrue(events.getAllValues().stream()
|
||||
.flatMap(List::stream)
|
||||
.anyMatch(e -> "extension started on :8080".equals(e.get("message"))),
|
||||
|
||||
@@ -7,6 +7,10 @@ import io.github.hectorvent.floci.services.rds.model.DbClusterParameterGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbInstance;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbInstanceStatus;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbParameterGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxy;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxyAuth;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxyTarget;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbProxyTargetGroup;
|
||||
import io.github.hectorvent.floci.services.rds.model.DbSubnetGroup;
|
||||
import jakarta.ws.rs.core.MultivaluedHashMap;
|
||||
import jakarta.ws.rs.core.MultivaluedMap;
|
||||
@@ -18,7 +22,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
@@ -46,7 +50,7 @@ class RdsQueryHandlerTest {
|
||||
@Test
|
||||
void describeDbInstances_usesDBInstanceTag() {
|
||||
DbInstance instance = makeInstance("mydb");
|
||||
when(service.listDbInstances(null)).thenReturn(List.of(instance));
|
||||
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
|
||||
|
||||
Response response = handler.handle("DescribeDBInstances", params());
|
||||
|
||||
@@ -59,7 +63,7 @@ class RdsQueryHandlerTest {
|
||||
void describeDbInstances_includesDbParameterGroupAttachment() {
|
||||
DbInstance instance = makeInstance("mydb");
|
||||
instance.setParameterGroupName("postgres18");
|
||||
when(service.listDbInstances(null)).thenReturn(List.of(instance));
|
||||
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
|
||||
|
||||
Response response = handler.handle("DescribeDBInstances", params());
|
||||
|
||||
@@ -73,7 +77,7 @@ class RdsQueryHandlerTest {
|
||||
void describeDbInstances_reportsDefaultDbParameterGroupWhenUnattached() {
|
||||
DbInstance instance = makeInstance("mydb");
|
||||
instance.setEngineVersion("16.3");
|
||||
when(service.listDbInstances(null)).thenReturn(List.of(instance));
|
||||
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
|
||||
|
||||
Response response = handler.handle("DescribeDBInstances", params());
|
||||
|
||||
@@ -86,33 +90,34 @@ class RdsQueryHandlerTest {
|
||||
@Test
|
||||
void describeDbInstances_filterByDirectIdentifier() {
|
||||
DbInstance instance = makeInstance("mydb");
|
||||
when(service.listDbInstances("mydb")).thenReturn(List.of(instance));
|
||||
when(service.listDbInstances("mydb", null)).thenReturn(List.of(instance));
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBInstanceIdentifier", "mydb");
|
||||
handler.handle("DescribeDBInstances", p);
|
||||
|
||||
verify(service).listDbInstances("mydb");
|
||||
verify(service).listDbInstances("mydb", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbInstances_filterByFiltersParam() {
|
||||
DbInstance instance = makeInstance("mydb");
|
||||
when(service.listDbInstances("mydb")).thenReturn(List.of(instance));
|
||||
when(service.listDbInstances("mydb", null)).thenReturn(List.of(instance));
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("Filters.Filter.1.Name", "db-instance-id");
|
||||
p.add("Filters.Filter.1.Values.Value.1", "mydb");
|
||||
handler.handle("DescribeDBInstances", p);
|
||||
|
||||
verify(service).listDbInstances("mydb");
|
||||
verify(service).listDbInstances("mydb", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbInstances_filterByDbiResourceId() {
|
||||
DbInstance instance = makeInstance("mydb");
|
||||
instance.setDbiResourceId("db-RESOURCE123");
|
||||
when(service.listDbInstancesByDbiResourceIds(List.of("db-RESOURCE123", "db-RESOURCE456")))
|
||||
when(service.listDbInstancesByDbiResourceIds(
|
||||
List.of("db-RESOURCE123", "db-RESOURCE456"), null))
|
||||
.thenReturn(List.of(instance));
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
@@ -121,14 +126,16 @@ class RdsQueryHandlerTest {
|
||||
p.add("Filters.Filter.1.Values.Value.2", "db-RESOURCE456");
|
||||
Response response = handler.handle("DescribeDBInstances", p);
|
||||
|
||||
verify(service).listDbInstancesByDbiResourceIds(List.of("db-RESOURCE123", "db-RESOURCE456"));
|
||||
verify(service).listDbInstancesByDbiResourceIds(
|
||||
List.of("db-RESOURCE123", "db-RESOURCE456"), null);
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<DBInstanceIdentifier>mydb</DBInstanceIdentifier>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbInstances_directIdentifierTakesPriorityOverFilters() {
|
||||
when(service.listDbInstances(any())).thenReturn(List.of());
|
||||
when(service.listDbInstances(any(), org.mockito.ArgumentMatchers.isNull()))
|
||||
.thenReturn(List.of());
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBInstanceIdentifier", "direct-id");
|
||||
@@ -136,15 +143,15 @@ class RdsQueryHandlerTest {
|
||||
p.add("Filters.Filter.1.Values.Value.1", "filter-id");
|
||||
handler.handle("DescribeDBInstances", p);
|
||||
|
||||
verify(service).listDbInstances("direct-id");
|
||||
verify(service).listDbInstances("direct-id", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbInstances_dbSubnetGroupUsesSubnetTag() {
|
||||
DbInstance instance = makeInstance("mydb");
|
||||
instance.setDbSubnetGroupName("custom-group");
|
||||
when(service.getDbSubnetGroup("custom-group")).thenReturn(customSubnetGroup());
|
||||
when(service.listDbInstances(null)).thenReturn(List.of(instance));
|
||||
when(service.getDbSubnetGroup("custom-group", null)).thenReturn(customSubnetGroup());
|
||||
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
|
||||
|
||||
Response response = handler.handle("DescribeDBInstances", params());
|
||||
|
||||
@@ -160,7 +167,7 @@ class RdsQueryHandlerTest {
|
||||
@Test
|
||||
void describeDbClusters_usesDBClusterTag() {
|
||||
DbCluster cluster = makeCluster("mycluster");
|
||||
when(service.listDbClusters(null)).thenReturn(List.of(cluster));
|
||||
when(service.listDbClusters(null, null)).thenReturn(List.of(cluster));
|
||||
|
||||
Response response = handler.handle("DescribeDBClusters", params());
|
||||
|
||||
@@ -171,34 +178,139 @@ class RdsQueryHandlerTest {
|
||||
|
||||
@Test
|
||||
void describeDbClusters_filterByFiltersParam() {
|
||||
when(service.listDbClusters("mycluster")).thenReturn(List.of());
|
||||
when(service.listDbClusters("mycluster", null)).thenReturn(List.of());
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("Filters.Filter.1.Name", "db-cluster-id");
|
||||
p.add("Filters.Filter.1.Values.Value.1", "mycluster");
|
||||
handler.handle("DescribeDBClusters", p);
|
||||
|
||||
verify(service).listDbClusters("mycluster");
|
||||
verify(service).listDbClusters("mycluster", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbInstances_unknownFilterFallsBackToUnfilteredList() {
|
||||
when(service.listDbInstances(null)).thenReturn(List.of());
|
||||
when(service.listDbInstances(null, null)).thenReturn(List.of());
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("Filters.Filter.1.Name", "engine");
|
||||
p.add("Filters.Filter.1.Values.Value.1", "postgres");
|
||||
handler.handle("DescribeDBInstances", p);
|
||||
|
||||
verify(service).listDbInstances(null);
|
||||
verify(service).listDbInstances(null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceAndClusterActionsPropagateSignedRegion() {
|
||||
DbInstance instance = makeInstance("mydb");
|
||||
DbCluster cluster = makeCluster("mycluster");
|
||||
when(service.listDbInstances(null, "us-west-2")).thenReturn(List.of());
|
||||
when(service.getDbInstance("mydb", "us-west-2")).thenReturn(instance);
|
||||
when(service.modifyDbInstance(
|
||||
eq("mydb"), isNull(), isNull(), isNull(), anyList(), eq("us-west-2")))
|
||||
.thenReturn(instance);
|
||||
when(service.rebootDbInstance("mydb", "us-west-2")).thenReturn(instance);
|
||||
when(service.listDbClusters(null, "us-west-2")).thenReturn(List.of());
|
||||
when(service.getDbCluster("mycluster", "us-west-2")).thenReturn(cluster);
|
||||
when(service.modifyDbCluster("mycluster", null, null, "us-west-2"))
|
||||
.thenReturn(cluster);
|
||||
|
||||
handler.handle("DescribeDBInstances", params(), "us-west-2");
|
||||
MultivaluedMap<String, String> instanceParams = params();
|
||||
instanceParams.add("DBInstanceIdentifier", "mydb");
|
||||
handler.handle("DeleteDBInstance", instanceParams, "us-west-2");
|
||||
handler.handle("ModifyDBInstance", instanceParams, "us-west-2");
|
||||
handler.handle("RebootDBInstance", instanceParams, "us-west-2");
|
||||
|
||||
handler.handle("DescribeDBClusters", params(), "us-west-2");
|
||||
MultivaluedMap<String, String> clusterParams = params();
|
||||
clusterParams.add("DBClusterIdentifier", "mycluster");
|
||||
handler.handle("DeleteDBCluster", clusterParams, "us-west-2");
|
||||
handler.handle("ModifyDBCluster", clusterParams, "us-west-2");
|
||||
|
||||
verify(service).listDbInstances(null, "us-west-2");
|
||||
verify(service).getDbInstance("mydb", "us-west-2");
|
||||
verify(service).deleteDbInstance("mydb", "us-west-2");
|
||||
verify(service).modifyDbInstance(
|
||||
eq("mydb"), isNull(), isNull(), isNull(), anyList(), eq("us-west-2"));
|
||||
verify(service).rebootDbInstance("mydb", "us-west-2");
|
||||
verify(service).listDbClusters(null, "us-west-2");
|
||||
verify(service).getDbCluster("mycluster", "us-west-2");
|
||||
verify(service).deleteDbCluster("mycluster", "us-west-2");
|
||||
verify(service).modifyDbCluster("mycluster", null, null, "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void subnetAndParameterGroupActionsPropagateSignedRegion() {
|
||||
DbSubnetGroup subnetGroup = customSubnetGroup();
|
||||
DbParameterGroup parameterGroup = new DbParameterGroup(
|
||||
"pg1", "postgres16", "parameter group");
|
||||
DbClusterParameterGroup clusterParameterGroup = new DbClusterParameterGroup(
|
||||
"cpg1", "aurora-postgresql16", "cluster parameter group");
|
||||
when(service.modifyDbSubnetGroup(
|
||||
"custom-group", List.of("subnet-a", "subnet-b"), "us-west-2"))
|
||||
.thenReturn(subnetGroup);
|
||||
when(service.listDbParameterGroups(null, "us-west-2"))
|
||||
.thenReturn(List.of(parameterGroup));
|
||||
when(service.getDbParameterGroup("pg1", "us-west-2"))
|
||||
.thenReturn(parameterGroup);
|
||||
when(service.modifyDbParameterGroup(
|
||||
"pg1", Map.of("max_connections", "200"), "us-west-2"))
|
||||
.thenReturn(parameterGroup);
|
||||
when(service.listDbClusterParameterGroups(null, "us-west-2"))
|
||||
.thenReturn(List.of(clusterParameterGroup));
|
||||
when(service.getDbClusterParameterGroup("cpg1", "us-west-2"))
|
||||
.thenReturn(clusterParameterGroup);
|
||||
when(service.modifyDbClusterParameterGroup(
|
||||
"cpg1", Map.of("log_statement", "all"), "us-west-2"))
|
||||
.thenReturn(clusterParameterGroup);
|
||||
|
||||
MultivaluedMap<String, String> subnetParams = params();
|
||||
subnetParams.add("DBSubnetGroupName", "custom-group");
|
||||
subnetParams.add("SubnetIds.SubnetIdentifier.1", "subnet-a");
|
||||
subnetParams.add("SubnetIds.SubnetIdentifier.2", "subnet-b");
|
||||
handler.handle("ModifyDBSubnetGroup", subnetParams, "us-west-2");
|
||||
handler.handle("DeleteDBSubnetGroup", subnetParams, "us-west-2");
|
||||
|
||||
handler.handle("DescribeDBParameterGroups", params(), "us-west-2");
|
||||
MultivaluedMap<String, String> parameterParams = params();
|
||||
parameterParams.add("DBParameterGroupName", "pg1");
|
||||
parameterParams.add("Parameters.member.1.ParameterName", "max_connections");
|
||||
parameterParams.add("Parameters.member.1.ParameterValue", "200");
|
||||
handler.handle("ModifyDBParameterGroup", parameterParams, "us-west-2");
|
||||
handler.handle("DescribeDBParameters", parameterParams, "us-west-2");
|
||||
handler.handle("DeleteDBParameterGroup", parameterParams, "us-west-2");
|
||||
|
||||
handler.handle("DescribeDBClusterParameterGroups", params(), "us-west-2");
|
||||
MultivaluedMap<String, String> clusterParameterParams = params();
|
||||
clusterParameterParams.add("DBClusterParameterGroupName", "cpg1");
|
||||
clusterParameterParams.add("Parameters.member.1.ParameterName", "log_statement");
|
||||
clusterParameterParams.add("Parameters.member.1.ParameterValue", "all");
|
||||
handler.handle("ModifyDBClusterParameterGroup", clusterParameterParams, "us-west-2");
|
||||
handler.handle("DescribeDBClusterParameters", clusterParameterParams, "us-west-2");
|
||||
handler.handle("DeleteDBClusterParameterGroup", clusterParameterParams, "us-west-2");
|
||||
|
||||
verify(service).modifyDbSubnetGroup(
|
||||
"custom-group", List.of("subnet-a", "subnet-b"), "us-west-2");
|
||||
verify(service).deleteDbSubnetGroup("custom-group", "us-west-2");
|
||||
verify(service).listDbParameterGroups(null, "us-west-2");
|
||||
verify(service).modifyDbParameterGroup(
|
||||
"pg1", Map.of("max_connections", "200"), "us-west-2");
|
||||
verify(service).getDbParameterGroup("pg1", "us-west-2");
|
||||
verify(service).deleteDbParameterGroup("pg1", "us-west-2");
|
||||
verify(service).listDbClusterParameterGroups(null, "us-west-2");
|
||||
verify(service).modifyDbClusterParameterGroup(
|
||||
"cpg1", Map.of("log_statement", "all"), "us-west-2");
|
||||
verify(service).getDbClusterParameterGroup("cpg1", "us-west-2");
|
||||
verify(service).deleteDbClusterParameterGroup("cpg1", "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbInstances_usesStoredDbSubnetGroup() {
|
||||
DbInstance instance = makeInstance("mydb");
|
||||
instance.setDbSubnetGroupName("sample-db-subnets");
|
||||
when(service.listDbInstances(null)).thenReturn(List.of(instance));
|
||||
when(service.getDbSubnetGroup("sample-db-subnets")).thenReturn(new DbSubnetGroup(
|
||||
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
|
||||
when(service.getDbSubnetGroup("sample-db-subnets", null)).thenReturn(new DbSubnetGroup(
|
||||
"sample-db-subnets", "test subnets", "vpc-123", List.of("subnet-aaa", "subnet-bbb"),
|
||||
Map.of("subnet-aaa", "us-east-1a", "subnet-bbb", "us-east-1b")));
|
||||
|
||||
@@ -215,7 +327,7 @@ class RdsQueryHandlerTest {
|
||||
void describeDbInstances_includesTagList() {
|
||||
DbInstance instance = makeInstance("mydb");
|
||||
instance.setTags(java.util.Map.of("example:ClusterId", "cluster-a", "Name", "mydb"));
|
||||
when(service.listDbInstances(null)).thenReturn(List.of(instance));
|
||||
when(service.listDbInstances(null, null)).thenReturn(List.of(instance));
|
||||
|
||||
Response response = handler.handle("DescribeDBInstances", params());
|
||||
|
||||
@@ -301,22 +413,27 @@ class RdsQueryHandlerTest {
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertTrue(((String) response.getEntity()).contains("InvalidParameterValue"));
|
||||
verify(service, never()).modifyDbInstance(any(), any(), any(), any(), any());
|
||||
verify(service, never()).modifyDbInstance(
|
||||
any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listTagsForResource_returnsStoredTags() {
|
||||
when(service.listTagsForResource("arn:aws:rds:us-east-1:000000000000:db:mydb"))
|
||||
when(service.listTagsForResource(
|
||||
"arn:aws:rds:us-east-1:000000000000:db:mydb", "us-west-2"))
|
||||
.thenReturn(java.util.Map.of("Name", "mydb"));
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("ResourceName", "arn:aws:rds:us-east-1:000000000000:db:mydb");
|
||||
Response response = handler.handle("ListTagsForResource", p);
|
||||
Response response = handler.handle("ListTagsForResource", p, "us-west-2");
|
||||
|
||||
String body = (String) response.getEntity();
|
||||
assertEquals(200, response.getStatus());
|
||||
assertTrue(body.contains("<TagList>"));
|
||||
assertTrue(body.contains("<Key>Name</Key>"));
|
||||
assertTrue(body.contains("<Value>mydb</Value>"));
|
||||
verify(service).listTagsForResource(
|
||||
"arn:aws:rds:us-east-1:000000000000:db:mydb", "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -325,16 +442,22 @@ class RdsQueryHandlerTest {
|
||||
add.add("ResourceName", "arn:aws:rds:us-east-1:000000000000:db:mydb");
|
||||
add.add("Tags.member.1.Key", "Name");
|
||||
add.add("Tags.member.1.Value", "mydb");
|
||||
handler.handle("AddTagsToResource", add);
|
||||
Response addResponse = handler.handle("AddTagsToResource", add, "us-west-2");
|
||||
|
||||
verify(service).addTagsToResource("arn:aws:rds:us-east-1:000000000000:db:mydb", java.util.Map.of("Name", "mydb"));
|
||||
assertEquals(200, addResponse.getStatus());
|
||||
verify(service).addTagsToResource(
|
||||
"arn:aws:rds:us-east-1:000000000000:db:mydb",
|
||||
java.util.Map.of("Name", "mydb"), "us-west-2");
|
||||
|
||||
MultivaluedMap<String, String> remove = params();
|
||||
remove.add("ResourceName", "arn:aws:rds:us-east-1:000000000000:db:mydb");
|
||||
remove.add("TagKeys.member.1", "Name");
|
||||
handler.handle("RemoveTagsFromResource", remove);
|
||||
Response removeResponse = handler.handle("RemoveTagsFromResource", remove, "us-west-2");
|
||||
|
||||
verify(service).removeTagsFromResource("arn:aws:rds:us-east-1:000000000000:db:mydb", List.of("Name"));
|
||||
assertEquals(200, removeResponse.getStatus());
|
||||
verify(service).removeTagsFromResource(
|
||||
"arn:aws:rds:us-east-1:000000000000:db:mydb",
|
||||
List.of("Name"), "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -362,7 +485,7 @@ class RdsQueryHandlerTest {
|
||||
@Test
|
||||
void describeDbParameterGroups_usesDBParameterGroupTag() {
|
||||
DbParameterGroup group = new DbParameterGroup("pg1", "postgres15", "test group");
|
||||
when(service.listDbParameterGroups(null)).thenReturn(List.of(group));
|
||||
when(service.listDbParameterGroups(null, null)).thenReturn(List.of(group));
|
||||
|
||||
Response response = handler.handle("DescribeDBParameterGroups", params());
|
||||
|
||||
@@ -571,7 +694,8 @@ class RdsQueryHandlerTest {
|
||||
@Test
|
||||
void modifyDbParameterGroup_ignoresParametersWithoutValue() {
|
||||
DbParameterGroup group = new DbParameterGroup("pg1", "postgres15", "test group");
|
||||
when(service.modifyDbParameterGroup(eq("pg1"), eq(java.util.Map.of("max_connections", "200"))))
|
||||
when(service.modifyDbParameterGroup(
|
||||
eq("pg1"), eq(java.util.Map.of("max_connections", "200")), isNull()))
|
||||
.thenReturn(group);
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
@@ -581,7 +705,8 @@ class RdsQueryHandlerTest {
|
||||
p.add("Parameters.member.2.ParameterName", "ignored_without_value");
|
||||
handler.handle("ModifyDBParameterGroup", p);
|
||||
|
||||
verify(service).modifyDbParameterGroup("pg1", java.util.Map.of("max_connections", "200"));
|
||||
verify(service).modifyDbParameterGroup(
|
||||
"pg1", java.util.Map.of("max_connections", "200"), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -605,7 +730,7 @@ class RdsQueryHandlerTest {
|
||||
@Test
|
||||
void describeDbClusterParameterGroups_usesDBClusterParameterGroupTag() {
|
||||
DbClusterParameterGroup group = new DbClusterParameterGroup("cpg1", "aurora-postgresql16", "test cluster group");
|
||||
when(service.listDbClusterParameterGroups(null)).thenReturn(List.of(group));
|
||||
when(service.listDbClusterParameterGroups(null, null)).thenReturn(List.of(group));
|
||||
|
||||
Response response = handler.handle("DescribeDBClusterParameterGroups", params());
|
||||
|
||||
@@ -634,7 +759,8 @@ class RdsQueryHandlerTest {
|
||||
@Test
|
||||
void createDbClusterParameterGroup_passesArgumentsToService() {
|
||||
DbClusterParameterGroup group = new DbClusterParameterGroup("cpg1", "aurora-postgresql16", "desc");
|
||||
when(service.createDbClusterParameterGroup("cpg1", "aurora-postgresql16", "desc")).thenReturn(group);
|
||||
when(service.createDbClusterParameterGroup(
|
||||
"cpg1", "aurora-postgresql16", "desc", null)).thenReturn(group);
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBClusterParameterGroupName", "cpg1");
|
||||
@@ -642,7 +768,8 @@ class RdsQueryHandlerTest {
|
||||
p.add("Description", "desc");
|
||||
Response response = handler.handle("CreateDBClusterParameterGroup", p);
|
||||
|
||||
verify(service).createDbClusterParameterGroup("cpg1", "aurora-postgresql16", "desc");
|
||||
verify(service).createDbClusterParameterGroup(
|
||||
"cpg1", "aurora-postgresql16", "desc", null);
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<DBClusterParameterGroupName>cpg1</DBClusterParameterGroupName>"));
|
||||
assertTrue(body.contains("<DBParameterGroupFamily>aurora-postgresql16</DBParameterGroupFamily>"));
|
||||
@@ -651,7 +778,8 @@ class RdsQueryHandlerTest {
|
||||
@Test
|
||||
void modifyDbClusterParameterGroup_ignoresParametersWithoutValue() {
|
||||
DbClusterParameterGroup group = new DbClusterParameterGroup("cpg1", "aurora-postgresql16", "test group");
|
||||
when(service.modifyDbClusterParameterGroup(eq("cpg1"), eq(java.util.Map.of("log_statement", "all"))))
|
||||
when(service.modifyDbClusterParameterGroup(
|
||||
eq("cpg1"), eq(java.util.Map.of("log_statement", "all")), isNull()))
|
||||
.thenReturn(group);
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
@@ -661,7 +789,8 @@ class RdsQueryHandlerTest {
|
||||
p.add("Parameters.member.2.ParameterName", "ignored_without_value");
|
||||
handler.handle("ModifyDBClusterParameterGroup", p);
|
||||
|
||||
verify(service).modifyDbClusterParameterGroup("cpg1", java.util.Map.of("log_statement", "all"));
|
||||
verify(service).modifyDbClusterParameterGroup(
|
||||
"cpg1", java.util.Map.of("log_statement", "all"), null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -685,7 +814,7 @@ class RdsQueryHandlerTest {
|
||||
@Test
|
||||
void describeDbClusters_dbSubnetGroupIsPlainString() {
|
||||
DbCluster cluster = makeCluster("mycluster");
|
||||
when(service.listDbClusters(null)).thenReturn(List.of(cluster));
|
||||
when(service.listDbClusters(null, null)).thenReturn(List.of(cluster));
|
||||
|
||||
Response response = handler.handle("DescribeDBClusters", params());
|
||||
|
||||
@@ -775,6 +904,512 @@ class RdsQueryHandlerTest {
|
||||
assertFalse(body.contains("<Marker>"));
|
||||
}
|
||||
|
||||
// ──────────────────────────── DBProxy wire shapes ──────────────────────────
|
||||
|
||||
@Test
|
||||
void createDbProxy_mapsParamsAndReturnsProxyEnvelope() {
|
||||
DbProxy proxy = new DbProxy();
|
||||
proxy.setDbProxyName("app-proxy");
|
||||
proxy.setEngineFamily("POSTGRESQL");
|
||||
proxy.setEndpointHost("app-proxy.host");
|
||||
proxy.setDbProxyArn("arn:aws:rds:us-west-2:000000000000:db-proxy:prx-abc");
|
||||
proxy.setDefaultAuthScheme("IAM_AUTH");
|
||||
proxy.setIdleClientTimeout(120);
|
||||
proxy.setDebugLogging(true);
|
||||
proxy.setVpcId("vpc-default");
|
||||
proxy.setVpcSecurityGroupIds(List.of("sg-a"));
|
||||
DbProxyAuth proxyAuth = new DbProxyAuth("SECRETS", "arn:secret", "DISABLED",
|
||||
"POSTGRES_SCRAM_SHA_256", "application credentials");
|
||||
proxyAuth.setUserName("database-user");
|
||||
proxy.setAuth(List.of(proxyAuth));
|
||||
when(service.createDbProxy(eq("app-proxy"), eq("POSTGRESQL"), eq(true), eq(true),
|
||||
eq("IAM_AUTH"), eq("arn:aws:iam::000000000000:role/proxy"),
|
||||
anyList(), anyList(), anyList(),
|
||||
eq(120), eq(true), eq(Map.of("owner", "platform")), eq("us-west-2")))
|
||||
.thenReturn(proxy);
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
p.add("EngineFamily", "POSTGRESQL");
|
||||
p.add("DefaultAuthScheme", "IAM_AUTH");
|
||||
p.add("EndpointNetworkType", "IPV4");
|
||||
p.add("TargetConnectionNetworkType", "IPV4");
|
||||
p.add("RequireTLS", "true");
|
||||
p.add("DebugLogging", "true");
|
||||
p.add("IdleClientTimeout", "120");
|
||||
p.add("RoleArn", "arn:aws:iam::000000000000:role/proxy");
|
||||
p.add("VpcSubnetIds.member.1", "subnet-a");
|
||||
p.add("VpcSubnetIds.member.2", "subnet-b");
|
||||
p.add("VpcSecurityGroupIds.member.1", "sg-a");
|
||||
p.add("Tags.Tag.1.Key", "owner");
|
||||
p.add("Tags.Tag.1.Value", "platform");
|
||||
p.add("Auth.member.1.AuthScheme", "SECRETS");
|
||||
p.add("Auth.member.1.SecretArn", "arn:aws:secretsmanager:us-east-1:000000000000:secret:db-AbCdEf");
|
||||
p.add("Auth.member.1.IAMAuth", "DISABLED");
|
||||
p.add("Auth.member.1.UserName", "database-user");
|
||||
Response response = handler.handle("CreateDBProxy", p, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<CreateDBProxyResult>"));
|
||||
assertTrue(body.contains("<DBProxy>"));
|
||||
assertTrue(body.contains("<DBProxyName>app-proxy</DBProxyName>"));
|
||||
assertTrue(body.contains("<Endpoint>app-proxy.host</Endpoint>"));
|
||||
assertTrue(body.contains("<DBProxyArn>arn:aws:rds:us-west-2:000000000000:db-proxy:prx-abc</DBProxyArn>"));
|
||||
assertTrue(body.contains("<DefaultAuthScheme>IAM_AUTH</DefaultAuthScheme>"));
|
||||
assertTrue(body.contains("<EndpointNetworkType>IPV4</EndpointNetworkType>"));
|
||||
assertTrue(body.contains("<TargetConnectionNetworkType>IPV4</TargetConnectionNetworkType>"));
|
||||
assertTrue(body.contains("<VpcId>vpc-default</VpcId>"));
|
||||
assertTrue(body.contains("<IdleClientTimeout>120</IdleClientTimeout>"));
|
||||
assertTrue(body.contains("<DebugLogging>true</DebugLogging>"));
|
||||
assertTrue(body.contains("<VpcSecurityGroupIds><member>sg-a</member></VpcSecurityGroupIds>"));
|
||||
assertTrue(body.contains("<ClientPasswordAuthType>POSTGRES_SCRAM_SHA_256</ClientPasswordAuthType>"));
|
||||
assertTrue(body.contains("<Description>application credentials</Description>"));
|
||||
assertTrue(body.contains("<UserName>database-user</UserName>"));
|
||||
// DefaultAuthScheme=IAM_AUTH enables IAM even when the Auth entry itself is DISABLED.
|
||||
verify(service).createDbProxy(eq("app-proxy"), eq("POSTGRESQL"), eq(true), eq(true),
|
||||
eq("IAM_AUTH"), eq("arn:aws:iam::000000000000:role/proxy"),
|
||||
anyList(), anyList(), argThat(auth -> auth.size() == 1
|
||||
&& "database-user".equals(auth.getFirst().getUserName())),
|
||||
eq(120), eq(true), eq(Map.of("owner", "platform")), eq("us-west-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSqlServerDbProxyEnablesIamFromAuthEntryAndPreservesUserName() {
|
||||
DbProxy proxy = new DbProxy();
|
||||
proxy.setDbProxyName("sqlserver-proxy");
|
||||
proxy.setEngineFamily("SQLSERVER");
|
||||
proxy.setEndpointHost("sqlserver-proxy.host");
|
||||
proxy.setDbProxyArn(
|
||||
"arn:aws:rds:us-west-2:000000000000:db-proxy:prx-sqlserver");
|
||||
DbProxyAuth returnedAuth = new DbProxyAuth(
|
||||
"SECRETS", "arn:aws:secretsmanager:us-west-2:000000000000:secret:sqlserver",
|
||||
"ENABLED", "SQL_SERVER_AUTHENTICATION", "SQL Server credentials");
|
||||
returnedAuth.setUserName("database-user");
|
||||
proxy.setAuth(List.of(returnedAuth));
|
||||
when(service.createDbProxy(
|
||||
eq("sqlserver-proxy"), eq("SQLSERVER"), eq(true), eq(true), isNull(),
|
||||
eq("arn:aws:iam::000000000000:role/proxy"), anyList(), anyList(),
|
||||
argThat(auth -> auth.size() == 1
|
||||
&& "ENABLED".equals(auth.getFirst().getIamAuth())
|
||||
&& "database-user".equals(auth.getFirst().getUserName())),
|
||||
eq(1800), eq(false), eq(Map.of()), eq("us-west-2")))
|
||||
.thenReturn(proxy);
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "sqlserver-proxy");
|
||||
p.add("EngineFamily", "SQLSERVER");
|
||||
p.add("RequireTLS", "true");
|
||||
p.add("RoleArn", "arn:aws:iam::000000000000:role/proxy");
|
||||
p.add("VpcSubnetIds.member.1", "subnet-a");
|
||||
p.add("VpcSubnetIds.member.2", "subnet-b");
|
||||
p.add("Auth.member.1.AuthScheme", "SECRETS");
|
||||
p.add("Auth.member.1.SecretArn",
|
||||
"arn:aws:secretsmanager:us-west-2:000000000000:secret:sqlserver");
|
||||
p.add("Auth.member.1.IAMAuth", "ENABLED");
|
||||
p.add("Auth.member.1.ClientPasswordAuthType", "SQL_SERVER_AUTHENTICATION");
|
||||
p.add("Auth.member.1.UserName", "database-user");
|
||||
|
||||
Response response = handler.handle("CreateDBProxy", p, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
verify(service).createDbProxy(
|
||||
eq("sqlserver-proxy"), eq("SQLSERVER"), eq(true), eq(true), isNull(),
|
||||
eq("arn:aws:iam::000000000000:role/proxy"), anyList(), anyList(),
|
||||
argThat(auth -> auth.size() == 1
|
||||
&& "ENABLED".equals(auth.getFirst().getIamAuth())
|
||||
&& "database-user".equals(auth.getFirst().getUserName())),
|
||||
eq(1800), eq(false), eq(Map.of()), eq("us-west-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDbProxyRejectsUnsupportedOrInvalidNetworkTypesBeforeCallingService() {
|
||||
MultivaluedMap<String, String> ipv6 = params();
|
||||
ipv6.add("EndpointNetworkType", "IPV6");
|
||||
|
||||
Response ipv6Response = handler.handle("CreateDBProxy", ipv6, "us-west-2");
|
||||
|
||||
assertEquals(400, ipv6Response.getStatus());
|
||||
assertTrue(((String) ipv6Response.getEntity()).contains("UnsupportedOperation"));
|
||||
|
||||
MultivaluedMap<String, String> invalidTargetType = params();
|
||||
invalidTargetType.add("TargetConnectionNetworkType", "DUAL");
|
||||
|
||||
Response invalidResponse = handler.handle(
|
||||
"CreateDBProxy", invalidTargetType, "us-west-2");
|
||||
|
||||
assertEquals(400, invalidResponse.getStatus());
|
||||
assertTrue(((String) invalidResponse.getEntity()).contains("InvalidParameterValue"));
|
||||
verifyNoInteractions(service);
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyDbProxy_mapsOptionalFieldsAndReturnsUpdatedProxy() {
|
||||
DbProxy proxy = new DbProxy();
|
||||
proxy.setDbProxyName("app-proxy");
|
||||
proxy.setDbProxyArn("arn:aws:rds:us-west-2:000000000000:db-proxy:prx-abc");
|
||||
proxy.setEngineFamily("POSTGRESQL");
|
||||
proxy.setEndpointHost("app-proxy.host");
|
||||
proxy.setDefaultAuthScheme("IAM_AUTH");
|
||||
proxy.setRequireTls(false);
|
||||
proxy.setIdleClientTimeout(900);
|
||||
proxy.setDebugLogging(true);
|
||||
proxy.setRoleArn("arn:aws:iam::000000000000:role/updated-proxy");
|
||||
proxy.setVpcSecurityGroupIds(List.of("sg-a", "sg-b"));
|
||||
proxy.setAuth(List.of(new DbProxyAuth(
|
||||
"SECRETS", "arn:secret", "DISABLED", "POSTGRES_MD5", "updated")));
|
||||
when(service.modifyDbProxy(
|
||||
eq("app-proxy"), eq("IAM_AUTH"), anyList(), eq(false), eq(900), eq(true),
|
||||
eq("arn:aws:iam::000000000000:role/updated-proxy"),
|
||||
eq(List.of("sg-a", "sg-b")), isNull(), eq("us-west-2")))
|
||||
.thenReturn(proxy);
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
p.add("DefaultAuthScheme", "IAM_AUTH");
|
||||
p.add("RequireTLS", "false");
|
||||
p.add("IdleClientTimeout", "900");
|
||||
p.add("DebugLogging", "true");
|
||||
p.add("RoleArn", "arn:aws:iam::000000000000:role/updated-proxy");
|
||||
p.add("SecurityGroups.member.1", "sg-a");
|
||||
p.add("SecurityGroups.member.2", "sg-b");
|
||||
p.add("Auth.member.1.AuthScheme", "SECRETS");
|
||||
p.add("Auth.member.1.SecretArn", "arn:secret");
|
||||
p.add("Auth.member.1.IAMAuth", "DISABLED");
|
||||
p.add("Auth.member.1.ClientPasswordAuthType", "POSTGRES_MD5");
|
||||
p.add("Auth.member.1.Description", "updated");
|
||||
|
||||
Response response = handler.handle("ModifyDBProxy", p, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<ModifyDBProxyResult>"));
|
||||
assertTrue(body.contains("<DefaultAuthScheme>IAM_AUTH</DefaultAuthScheme>"));
|
||||
assertTrue(body.contains("<RequireTLS>false</RequireTLS>"));
|
||||
assertTrue(body.contains("<IdleClientTimeout>900</IdleClientTimeout>"));
|
||||
assertTrue(body.contains("<DebugLogging>true</DebugLogging>"));
|
||||
assertTrue(body.contains("<VpcSecurityGroupIds><member>sg-a</member><member>sg-b</member>"));
|
||||
assertTrue(body.contains("<ClientPasswordAuthType>POSTGRES_MD5</ClientPasswordAuthType>"));
|
||||
verify(service).modifyDbProxy(
|
||||
eq("app-proxy"), eq("IAM_AUTH"), argThat(auth -> auth.size() == 1
|
||||
&& "arn:secret".equals(auth.getFirst().getSecretArn())
|
||||
&& "DISABLED".equals(auth.getFirst().getIamAuth())),
|
||||
eq(false), eq(900), eq(true),
|
||||
eq("arn:aws:iam::000000000000:role/updated-proxy"),
|
||||
eq(List.of("sg-a", "sg-b")), isNull(), eq("us-west-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyDbProxy_rejectsMalformedOptionalValuesBeforeCallingService() {
|
||||
MultivaluedMap<String, String> invalidBoolean = params();
|
||||
invalidBoolean.add("DBProxyName", "app-proxy");
|
||||
invalidBoolean.add("RequireTLS", "sometimes");
|
||||
|
||||
Response booleanResponse = handler.handle(
|
||||
"ModifyDBProxy", invalidBoolean, "us-west-2");
|
||||
|
||||
assertEquals(400, booleanResponse.getStatus());
|
||||
assertTrue(((String) booleanResponse.getEntity()).contains("InvalidParameterValue"));
|
||||
assertTrue(((String) booleanResponse.getEntity()).contains("RequireTLS"));
|
||||
|
||||
MultivaluedMap<String, String> invalidInteger = params();
|
||||
invalidInteger.add("DBProxyName", "app-proxy");
|
||||
invalidInteger.add("IdleClientTimeout", "not-an-integer");
|
||||
|
||||
Response integerResponse = handler.handle(
|
||||
"ModifyDBProxy", invalidInteger, "us-west-2");
|
||||
|
||||
assertEquals(400, integerResponse.getStatus());
|
||||
assertTrue(((String) integerResponse.getEntity()).contains("InvalidParameterValue"));
|
||||
assertTrue(((String) integerResponse.getEntity()).contains("IdleClientTimeout"));
|
||||
verifyNoInteractions(service);
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyDbProxy_rejectsNewDbProxyNameBeforeCallingService() {
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
p.add("NewDBProxyName", "renamed-proxy");
|
||||
|
||||
Response response = handler.handle("ModifyDBProxy", p, "us-west-2");
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("UnsupportedOperation"));
|
||||
assertTrue(body.contains("NewDBProxyName"));
|
||||
verifyNoInteractions(service);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbProxies_rendersProxyMembers() {
|
||||
DbProxy proxy = new DbProxy();
|
||||
proxy.setDbProxyName("app-proxy");
|
||||
proxy.setEndpointHost("app-proxy.host");
|
||||
proxy.setDbProxyArn("arn:aws:rds:us-east-1:000000000000:db-proxy:prx-abc");
|
||||
when(service.listDbProxies("app-proxy", "us-west-2")).thenReturn(List.of(proxy));
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
Response response = handler.handle("DescribeDBProxies", p, "us-west-2");
|
||||
|
||||
String body = (String) response.getEntity();
|
||||
assertEquals(200, response.getStatus());
|
||||
assertTrue(body.contains("<DescribeDBProxiesResult>"));
|
||||
assertTrue(body.contains("<DBProxies><member>"));
|
||||
assertTrue(body.contains("<DBProxyName>app-proxy</DBProxyName>"));
|
||||
verify(service).listDbProxies("app-proxy", "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerDbProxyTargets_mapsClusterIdsAndRendersTargets() {
|
||||
DbProxyTargetGroup tg = new DbProxyTargetGroup();
|
||||
tg.setDbProxyName("app-proxy");
|
||||
tg.getTargets().add(new DbProxyTarget("TRACKED_CLUSTER", "cluster1",
|
||||
"arn:aws:rds:us-east-1:000000000000:cluster:cluster1", "cluster1.host", 5432));
|
||||
when(service.registerDbProxyTargets(
|
||||
any(), any(), anyList(), anyList(), anyInt(), anyInt(), any()))
|
||||
.thenReturn(tg);
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
p.add("TargetGroupName", "default");
|
||||
p.add("DBClusterIdentifiers.member.1", "cluster1");
|
||||
Response response = handler.handle("RegisterDBProxyTargets", p, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<RegisterDBProxyTargetsResult>"));
|
||||
assertTrue(body.contains("<DBProxyTargets><member>"));
|
||||
assertTrue(body.contains("<Type>TRACKED_CLUSTER</Type>"));
|
||||
assertTrue(body.contains("<RdsResourceId>cluster1</RdsResourceId>"));
|
||||
verify(service).registerDbProxyTargets(
|
||||
"app-proxy", "default", List.of("cluster1"), List.of(), 0, 0, "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void registerDbProxyTargets_defaultsOmittedTargetGroupName() {
|
||||
DbProxyTargetGroup targetGroup = new DbProxyTargetGroup();
|
||||
targetGroup.setDbProxyName("app-proxy");
|
||||
when(service.registerDbProxyTargets(
|
||||
"app-proxy", null, List.of(), List.of("instance1"), 0, 0, "us-west-2"))
|
||||
.thenReturn(targetGroup);
|
||||
|
||||
MultivaluedMap<String, String> params = params();
|
||||
params.add("DBProxyName", "app-proxy");
|
||||
params.add("DBInstanceIdentifiers.member.1", "instance1");
|
||||
|
||||
Response response = handler.handle(
|
||||
"RegisterDBProxyTargets", params, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
verify(service).registerDbProxyTargets(
|
||||
"app-proxy", null, List.of(), List.of("instance1"), 0, 0, "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deregisterDbProxyTargetsMapsIdentifiersAndReturnsEmptyResult() {
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
p.add("TargetGroupName", "default");
|
||||
p.add("DBInstanceIdentifiers.member.1", "instance1");
|
||||
|
||||
Response response = handler.handle("DeregisterDBProxyTargets", p, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertTrue(((String) response.getEntity()).contains("<DeregisterDBProxyTargetsResult>"));
|
||||
verify(service).deregisterDbProxyTargets("app-proxy", "default",
|
||||
List.of(), List.of("instance1"), "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deregisterDbProxyTargets_defaultsOmittedTargetGroupName() {
|
||||
MultivaluedMap<String, String> params = params();
|
||||
params.add("DBProxyName", "app-proxy");
|
||||
params.add("DBClusterIdentifiers.member.1", "cluster1");
|
||||
|
||||
Response response = handler.handle(
|
||||
"DeregisterDBProxyTargets", params, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
verify(service).deregisterDbProxyTargets(
|
||||
"app-proxy", null, List.of("cluster1"), List.of(), "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbProxyTargetGroups_rendersTargetGroupMembers() {
|
||||
DbProxyTargetGroup tg = new DbProxyTargetGroup();
|
||||
tg.setDbProxyName("app-proxy");
|
||||
tg.setTargetGroupName("default");
|
||||
tg.setTargetGroupArn("arn:aws:rds:us-east-1:000000000000:target-group:app-proxy/default");
|
||||
when(service.describeDbProxyTargetGroups("app-proxy", null, "us-west-2"))
|
||||
.thenReturn(List.of(tg));
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
Response response = handler.handle("DescribeDBProxyTargetGroups", p, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<DescribeDBProxyTargetGroupsResult>"));
|
||||
assertTrue(body.contains("<TargetGroups><member>"));
|
||||
assertTrue(body.contains("<TargetGroupName>default</TargetGroupName>"));
|
||||
assertTrue(body.contains("<ConnectionPoolConfig>"));
|
||||
verify(service).describeDbProxyTargetGroups("app-proxy", null, "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyDbProxyTargetGroup_mapsFullPoolConfigurationAndReturnsUpdatedGroup() {
|
||||
DbProxyTargetGroup targetGroup = new DbProxyTargetGroup();
|
||||
targetGroup.setDbProxyName("app-proxy");
|
||||
targetGroup.setTargetGroupName("default");
|
||||
targetGroup.setTargetGroupArn(
|
||||
"arn:aws:rds:us-west-2:000000000000:target-group:prx-tg-abc");
|
||||
targetGroup.setMaxConnectionsPercent(90);
|
||||
targetGroup.setMaxIdleConnectionsPercent(40);
|
||||
targetGroup.setConnectionBorrowTimeout(55);
|
||||
targetGroup.setInitQuery("SET application_name = 'floci'");
|
||||
targetGroup.setSessionPinningFilters(List.of("EXCLUDE_VARIABLE_SETS"));
|
||||
when(service.configureDbProxyTargetGroup(
|
||||
"app-proxy", "default", 90, 40, 55,
|
||||
"SET application_name = 'floci'",
|
||||
List.of("EXCLUDE_VARIABLE_SETS"),
|
||||
"us-west-2"))
|
||||
.thenReturn(targetGroup);
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
p.add("TargetGroupName", "default");
|
||||
p.add("ConnectionPoolConfig.MaxConnectionsPercent", "90");
|
||||
p.add("ConnectionPoolConfig.MaxIdleConnectionsPercent", "40");
|
||||
p.add("ConnectionPoolConfig.ConnectionBorrowTimeout", "55");
|
||||
p.add("ConnectionPoolConfig.InitQuery", "SET application_name = 'floci'");
|
||||
p.add("ConnectionPoolConfig.SessionPinningFilters.member.1", "EXCLUDE_VARIABLE_SETS");
|
||||
|
||||
Response response = handler.handle(
|
||||
"ModifyDBProxyTargetGroup", p, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<ModifyDBProxyTargetGroupResult>"));
|
||||
assertTrue(body.contains("<DBProxyTargetGroup>"));
|
||||
assertTrue(body.contains("<MaxConnectionsPercent>90</MaxConnectionsPercent>"));
|
||||
assertTrue(body.contains("<MaxIdleConnectionsPercent>40</MaxIdleConnectionsPercent>"));
|
||||
assertTrue(body.contains("<ConnectionBorrowTimeout>55</ConnectionBorrowTimeout>"));
|
||||
assertTrue(body.contains("<InitQuery>SET application_name = 'floci'</InitQuery>"));
|
||||
assertTrue(body.contains("<SessionPinningFilters><member>EXCLUDE_VARIABLE_SETS</member>"
|
||||
+ "</SessionPinningFilters>"));
|
||||
verify(service).configureDbProxyTargetGroup(
|
||||
"app-proxy", "default", 90, 40, 55,
|
||||
"SET application_name = 'floci'",
|
||||
List.of("EXCLUDE_VARIABLE_SETS"),
|
||||
"us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyDbProxyTargetGroup_rejectsNewNameBeforeCallingService() {
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
p.add("TargetGroupName", "default");
|
||||
p.add("NewName", "renamed-target-group");
|
||||
|
||||
Response response = handler.handle(
|
||||
"ModifyDBProxyTargetGroup", p, "us-west-2");
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("UnsupportedOperation"));
|
||||
assertTrue(body.contains("cannot be renamed"));
|
||||
verifyNoInteractions(service);
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyDbProxyTargetGroupRequiresTargetGroupName() {
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
|
||||
Response response = handler.handle(
|
||||
"ModifyDBProxyTargetGroup", p, "us-west-2");
|
||||
|
||||
assertEquals(400, response.getStatus());
|
||||
assertTrue(((String) response.getEntity()).contains("TargetGroupName"));
|
||||
verifyNoInteractions(service);
|
||||
}
|
||||
|
||||
@Test
|
||||
void proxyTargetActionsRejectBlankTargetGroupName() {
|
||||
for (String action : List.of(
|
||||
"RegisterDBProxyTargets",
|
||||
"DeregisterDBProxyTargets",
|
||||
"DescribeDBProxyTargets")) {
|
||||
MultivaluedMap<String, String> params = params();
|
||||
params.add("DBProxyName", "app-proxy");
|
||||
params.add("TargetGroupName", " ");
|
||||
|
||||
Response response = handler.handle(action, params, "us-west-2");
|
||||
|
||||
assertEquals(400, response.getStatus(), action);
|
||||
assertTrue(((String) response.getEntity())
|
||||
.contains("TargetGroupName must be at least 1 character"), action);
|
||||
}
|
||||
verifyNoInteractions(service);
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbProxyTargets_rendersTargetMembers() {
|
||||
when(service.describeDbProxyTargets("app-proxy", "default", "us-west-2")).thenReturn(List.of(
|
||||
new DbProxyTarget("RDS_INSTANCE", "inst1",
|
||||
"arn:aws:rds:us-east-1:000000000000:db:inst1", "inst1.host", 5432)));
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
p.add("TargetGroupName", "default");
|
||||
Response response = handler.handle("DescribeDBProxyTargets", p, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<DescribeDBProxyTargetsResult>"));
|
||||
assertTrue(body.contains("<Targets><member>"));
|
||||
assertTrue(body.contains("<Type>RDS_INSTANCE</Type>"));
|
||||
assertTrue(body.contains("<RdsResourceId>inst1</RdsResourceId>"));
|
||||
verify(service).describeDbProxyTargets("app-proxy", "default", "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbProxyTargets_defaultsOmittedTargetGroupName() {
|
||||
when(service.describeDbProxyTargets("app-proxy", null, "us-west-2"))
|
||||
.thenReturn(List.of());
|
||||
|
||||
MultivaluedMap<String, String> params = params();
|
||||
params.add("DBProxyName", "app-proxy");
|
||||
|
||||
Response response = handler.handle(
|
||||
"DescribeDBProxyTargets", params, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertTrue(((String) response.getEntity())
|
||||
.contains("<DescribeDBProxyTargetsResult>"));
|
||||
verify(service).describeDbProxyTargets("app-proxy", null, "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDbProxy_delegatesToServiceAndReturnsProxy() {
|
||||
DbProxy proxy = new DbProxy();
|
||||
proxy.setDbProxyName("app-proxy");
|
||||
proxy.setDbProxyArn("arn:aws:rds:us-east-1:000000000000:db-proxy:prx-abc");
|
||||
when(service.getDbProxy("app-proxy", "us-west-2")).thenReturn(proxy);
|
||||
|
||||
MultivaluedMap<String, String> p = params();
|
||||
p.add("DBProxyName", "app-proxy");
|
||||
Response response = handler.handle("DeleteDBProxy", p, "us-west-2");
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
String body = (String) response.getEntity();
|
||||
assertTrue(body.contains("<DeleteDBProxyResult>"));
|
||||
assertTrue(body.contains("<DBProxyName>app-proxy</DBProxyName>"));
|
||||
verify(service).getDbProxy("app-proxy", "us-west-2");
|
||||
verify(service).deleteDbProxy("app-proxy", "us-west-2");
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeDbSubnetGroupsPassesSignedRegionToService() {
|
||||
DbSubnetGroup group = new DbSubnetGroup();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+566
-9
@@ -17,16 +17,26 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.github.dockerjava.api.model.Bind;
|
||||
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -78,7 +88,7 @@ class RdsContainerManagerTest {
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-id", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
@@ -96,18 +106,541 @@ class RdsContainerManagerTest {
|
||||
|
||||
assertFalse(Files.exists(dbPath));
|
||||
var spec = org.mockito.ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
verify(lifecycleManager).createAndStart(spec.capture());
|
||||
verify(lifecycleManager).create(spec.capture());
|
||||
Bind bind = spec.getValue().binds().getFirst();
|
||||
assertEquals(dbPath.toString(), bind.getPath());
|
||||
assertEquals("/var/lib/mysql", bind.getVolume().getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyForeignAccountRuntimeReusesBareHostPath() {
|
||||
Path hostRoot = tempDir.resolve("host-root");
|
||||
Path dbPath = hostRoot.resolve("rds").resolve("db1");
|
||||
EmulatorConfig config = config(hostRoot);
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager,
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-id", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, containerDetector, config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
|
||||
String runtimeId = "arn:aws:rds:us-west-2:222222222222:db:db1";
|
||||
manager.start(runtimeId, "db1", null,
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
|
||||
|
||||
var spec = org.mockito.ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
verify(lifecycleManager).create(spec.capture());
|
||||
assertEquals(dbPath.toString(), spec.getValue().binds().getFirst().getPath());
|
||||
assertEquals("floci-rds-db1", spec.getValue().name());
|
||||
verify(logStreamer).attachForAccount(
|
||||
"222222222222", "container-id", "/aws/rds/instance/db1/error",
|
||||
"log-stream", "us-west-2", "rds:" + runtimeId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameNamedResourcesKeepIndependentActiveContainerEntries() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager,
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-a", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))),
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-b", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3307))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, containerDetector, config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
|
||||
manager.start("arn:aws:rds:us-east-1:111111111111:db:db1", "db1",
|
||||
"db-RESOURCE-A", "floci-rds-volume-a", DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db");
|
||||
manager.start("arn:aws:rds:us-east-1:222222222222:db:db1", "db1",
|
||||
"db-RESOURCE-B", "floci-rds-volume-b", DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db");
|
||||
|
||||
manager.stopAll();
|
||||
|
||||
verify(lifecycleManager, times(2)).stopAndRemoveStrict(
|
||||
any(), org.mockito.ArgumentMatchers.isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameNamedResourcesWithEqualVolumeIdsUseIndependentNamedVolumes() {
|
||||
EmulatorConfig config = config(Path.of("data"));
|
||||
when(config.defaultAccountId()).thenReturn("000000000000");
|
||||
when(config.storage().mode()).thenReturn("memory");
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager,
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-a", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))),
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-b", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3307))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, containerDetector, config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
String runtimeA = "arn:aws:rds:us-east-1:111111111111:db:db1";
|
||||
String runtimeB = "arn:aws:rds:us-east-1:222222222222:db:db1";
|
||||
String volumeA = "floci-rds-111111111111-us-east-1-db_db1-shared-volume";
|
||||
String volumeB = "floci-rds-222222222222-us-east-1-db_db1-shared-volume";
|
||||
|
||||
RdsContainerHandle handleA = manager.start(
|
||||
runtimeA, "db1", "db-RESOURCE-A", volumeA, DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db");
|
||||
manager.start(runtimeB, "db1", "db-RESOURCE-B", volumeB, DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db");
|
||||
|
||||
verify(lifecycleManager).ensureVolume(volumeA);
|
||||
verify(lifecycleManager).ensureVolume(volumeB);
|
||||
manager.stop(handleA);
|
||||
manager.removeVolume(runtimeA, "db-RESOURCE-A", volumeA);
|
||||
verify(lifecycleManager).removeVolumeStrict(volumeA);
|
||||
verify(lifecycleManager, never()).removeVolumeStrict(volumeB);
|
||||
}
|
||||
|
||||
@Test
|
||||
void competingLegacyHostPathClaimFailsBeforeTouchingDocker() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager,
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-a", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, containerDetector, config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
|
||||
manager.start("arn:aws:rds:us-east-1:111111111111:db:same", "same", null,
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
"arn:aws:rds:us-east-1:111111111111:cluster:same", "same", null,
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
|
||||
verify(lifecycleManager, times(1)).removeIfExistsStrict("floci-rds-same");
|
||||
verify(lifecycleManager, times(1)).create(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void competingLegacyContainerNameClaimFailsBeforeTouchingDocker() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager,
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-a", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
String sharedLegacyName = "floci-rds-shared-volume";
|
||||
|
||||
manager.start("arn:aws:rds:us-east-1:111111111111:db:first", "first",
|
||||
"first-storage", sharedLegacyName, DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db");
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
"arn:aws:rds:us-east-1:111111111111:db:second", "second",
|
||||
"second-storage", sharedLegacyName, DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db"));
|
||||
verify(lifecycleManager, times(1)).removeIfExistsStrict(sharedLegacyName);
|
||||
verify(lifecycleManager, times(1)).create(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void activeNamedVolumeIsNotRemovedUntilOwnerStops() {
|
||||
EmulatorConfig config = config(Path.of("data"));
|
||||
when(config.storage().mode()).thenReturn("memory");
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager,
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-a", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, containerDetector, config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
String runtime = "arn:aws:rds:us-east-1:111111111111:db:db1";
|
||||
String volume = "floci-rds-legacy-volume";
|
||||
|
||||
RdsContainerHandle handle = manager.start(
|
||||
runtime, "db1", "db1", volume, DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db");
|
||||
assertThrows(IllegalStateException.class, () ->
|
||||
manager.removeVolume(runtime, "db1", volume));
|
||||
verify(lifecycleManager, never()).removeVolumeStrict(volume);
|
||||
|
||||
manager.stop(handle);
|
||||
manager.removeVolume(runtime, "db1", volume);
|
||||
verify(lifecycleManager).removeVolumeStrict(volume);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedStartReleasesClaimsForSameRuntimeRetry() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.create(any()))
|
||||
.thenThrow(new IllegalStateException("Docker unavailable"))
|
||||
.thenReturn("container-b");
|
||||
when(lifecycleManager.startCreated(
|
||||
org.mockito.ArgumentMatchers.eq("container-b"), any()))
|
||||
.thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-b", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, containerDetector, config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
|
||||
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:legacy";
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
runtimeId, "legacy", null,
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
|
||||
RdsContainerHandle retried = manager.start(
|
||||
runtimeId, "legacy", null,
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
|
||||
|
||||
assertEquals("container-b", retried.getContainerId());
|
||||
verify(lifecycleManager, times(2)).removeIfExistsStrict("floci-rds-legacy");
|
||||
}
|
||||
|
||||
@Test
|
||||
void postCreateFailureCleansContainerBeforeReleasingOwnership() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager,
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-a", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))),
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-b", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3307))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
when(logStreamer.attachForAccount(any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new IllegalStateException("log attach failed"))
|
||||
.thenReturn(null);
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
String volume = "floci-rds-legacy-volume";
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
"arn:aws:rds:us-east-1:111111111111:db:legacy", "legacy",
|
||||
"legacy", volume, DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db"));
|
||||
RdsContainerHandle retried = manager.start(
|
||||
"arn:aws:rds:us-east-1:222222222222:db:legacy", "legacy",
|
||||
"legacy", volume, DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db");
|
||||
|
||||
assertEquals("container-b", retried.getContainerId());
|
||||
verify(lifecycleManager).stopAndRemoveStrict(
|
||||
org.mockito.ArgumentMatchers.eq("container-a"),
|
||||
org.mockito.ArgumentMatchers.isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedPostCreateCleanupRetainsContainerIdentityForRuntimeRetry() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager,
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-a", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
when(logStreamer.attachForAccount(any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(new IllegalStateException("log attach failed"));
|
||||
doThrow(new IllegalStateException("Docker cleanup failed"))
|
||||
.doNothing()
|
||||
.when(lifecycleManager).stopAndRemoveStrict(any(), any());
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:legacy";
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
runtimeId, "legacy", "legacy", "floci-rds-legacy-volume",
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
|
||||
|
||||
assertEquals("container-a", manager.getActiveHandle(runtimeId).getContainerId());
|
||||
manager.stopByRuntimeId(runtimeId);
|
||||
assertNull(manager.getActiveHandle(runtimeId));
|
||||
verify(lifecycleManager, times(2)).stopAndRemoveStrict(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedStartCleanupRetainsCreatedContainerIdentityAndOwnership() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.create(any())).thenReturn("created-container");
|
||||
when(lifecycleManager.startCreated(
|
||||
org.mockito.ArgumentMatchers.eq("created-container"), any()))
|
||||
.thenThrow(new IllegalStateException("Docker start failed"));
|
||||
doThrow(new IllegalStateException("Docker cleanup failed"))
|
||||
.doNothing()
|
||||
.when(lifecycleManager).stopAndRemoveStrict(any(), any());
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, mock(ContainerLogStreamer.class),
|
||||
mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:legacy";
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
runtimeId, "legacy", "legacy", "floci-rds-legacy-volume",
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
|
||||
|
||||
assertEquals("created-container", manager.getActiveHandle(runtimeId).getContainerId());
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
"arn:aws:rds:us-east-1:222222222222:db:legacy", "legacy",
|
||||
"legacy", "floci-rds-legacy-volume", DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db"));
|
||||
verify(lifecycleManager, times(1)).create(any());
|
||||
|
||||
manager.stopByRuntimeId(runtimeId);
|
||||
assertNull(manager.getActiveHandle(runtimeId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedStaleRemovalRetainsContainerNameAndOwnership() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
doThrow(new IllegalStateException("stale removal failed"))
|
||||
.when(lifecycleManager).removeIfExistsStrict("floci-rds-legacy-volume");
|
||||
doThrow(new IllegalStateException("cleanup retry failed"))
|
||||
.doNothing()
|
||||
.when(lifecycleManager).stopAndRemoveStrict(any(), any());
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, mock(ContainerLogStreamer.class),
|
||||
mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:legacy";
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
runtimeId, "legacy", "legacy", "floci-rds-legacy-volume",
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
|
||||
|
||||
assertEquals("floci-rds-legacy-volume",
|
||||
manager.getActiveHandle(runtimeId).getContainerId());
|
||||
verify(lifecycleManager, never()).create(any());
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
"arn:aws:rds:us-east-1:222222222222:db:legacy", "legacy",
|
||||
"legacy", "floci-rds-legacy-volume", DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db"));
|
||||
|
||||
manager.stopByRuntimeId(runtimeId);
|
||||
assertNull(manager.getActiveHandle(runtimeId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inProgressRuntimeClaimRejectsConcurrentDuplicateStart() throws Exception {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
CountDownLatch createEntered = new CountDownLatch(1);
|
||||
CountDownLatch allowCreate = new CountDownLatch(1);
|
||||
when(lifecycleManager.create(any())).thenAnswer(invocation -> {
|
||||
createEntered.countDown();
|
||||
if (!allowCreate.await(5, TimeUnit.SECONDS)) {
|
||||
throw new IllegalStateException("test timed out waiting to create");
|
||||
}
|
||||
return "container-a";
|
||||
});
|
||||
when(lifecycleManager.startCreated(
|
||||
org.mockito.ArgumentMatchers.eq("container-a"), any()))
|
||||
.thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-a", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:db1";
|
||||
|
||||
CompletableFuture<RdsContainerHandle> first = CompletableFuture.supplyAsync(() ->
|
||||
manager.start(runtimeId, "db1", "storage-a", "floci-rds-volume-a",
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
|
||||
assertTrue(createEntered.await(5, TimeUnit.SECONDS));
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
runtimeId, "db1", "storage-b", "floci-rds-volume-b",
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db"));
|
||||
allowCreate.countDown();
|
||||
|
||||
RdsContainerHandle handle = first.get(5, TimeUnit.SECONDS);
|
||||
verify(lifecycleManager, times(1)).create(any());
|
||||
manager.stop(handle);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopAllContinuesAfterIndividualCleanupFailure() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager,
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-a", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))),
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-b", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db2", 3307))));
|
||||
doAnswer(invocation -> {
|
||||
if ("container-a".equals(invocation.getArgument(0))) {
|
||||
throw new IllegalStateException("Docker cleanup failed");
|
||||
}
|
||||
return null;
|
||||
}).when(lifecycleManager).stopAndRemoveStrict(any(), any());
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
String runtimeA = "arn:aws:rds:us-east-1:111111111111:db:a";
|
||||
String runtimeB = "arn:aws:rds:us-east-1:111111111111:db:b";
|
||||
manager.start(runtimeA, "a", "storage-a", "floci-rds-volume-a",
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
|
||||
manager.start(runtimeB, "b", "storage-b", "floci-rds-volume-b",
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
|
||||
|
||||
assertDoesNotThrow(manager::stopAll);
|
||||
|
||||
verify(lifecycleManager).stopAndRemoveStrict(
|
||||
org.mockito.ArgumentMatchers.eq("container-a"), any());
|
||||
verify(lifecycleManager).stopAndRemoveStrict(
|
||||
org.mockito.ArgumentMatchers.eq("container-b"), any());
|
||||
assertEquals("container-a", manager.getActiveHandle(runtimeA).getContainerId());
|
||||
assertNull(manager.getActiveHandle(runtimeB));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedStopRetainsOwnershipAndActiveHandle() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
stubStarts(lifecycleManager,
|
||||
new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-a", Map.of(3306,
|
||||
new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, logStreamer, mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
String volume = "floci-rds-legacy-volume";
|
||||
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:legacy";
|
||||
RdsContainerHandle handle = manager.start(
|
||||
runtimeId, "legacy",
|
||||
"legacy", volume, DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db");
|
||||
doThrow(new IllegalStateException("Docker stop failed"))
|
||||
.doNothing()
|
||||
.when(lifecycleManager).stopAndRemoveStrict(any(), any());
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.stop(handle));
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
"arn:aws:rds:us-east-1:222222222222:db:legacy", "legacy",
|
||||
"legacy", volume, DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db"));
|
||||
verify(lifecycleManager, times(1)).create(any());
|
||||
|
||||
manager.stopByRuntimeId(runtimeId);
|
||||
RdsContainerHandle retried = manager.start(
|
||||
"arn:aws:rds:us-east-1:222222222222:db:legacy", "legacy",
|
||||
"legacy", volume, DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db");
|
||||
|
||||
assertEquals("container-a", retried.getContainerId());
|
||||
verify(lifecycleManager, times(2)).create(any());
|
||||
verify(lifecycleManager, times(2)).stopAndRemoveStrict(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void persistedStorageIdentityRejectsPathTraversal() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, mock(ContainerLogStreamer.class),
|
||||
mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> manager.start(
|
||||
"arn:aws:rds:us-east-1:111111111111:db:db1", "db1", "../escape",
|
||||
"floci-rds-safe", DatabaseEngine.MYSQL, "mysql:8.0",
|
||||
"root", "password", "db"));
|
||||
verify(lifecycleManager, never()).removeIfExistsStrict(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void childContainerNameUsesVolumeIdWhenAvailable() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-id", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
@@ -124,8 +657,8 @@ class RdsContainerManagerTest {
|
||||
manager.start("db1", "volume-a", DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
|
||||
|
||||
var spec = org.mockito.ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
verify(lifecycleManager).removeIfExists("floci-rds-volume-a");
|
||||
verify(lifecycleManager).createAndStart(spec.capture());
|
||||
verify(lifecycleManager).removeIfExistsStrict("floci-rds-volume-a");
|
||||
verify(lifecycleManager).create(spec.capture());
|
||||
assertEquals("floci-rds-volume-a", spec.getValue().name());
|
||||
}
|
||||
|
||||
@@ -134,7 +667,7 @@ class RdsContainerManagerTest {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerLifecycleManager.ContainerInfo(
|
||||
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
|
||||
"container-id", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
lenient().when(logStreamer.generateLogStreamName(any())).thenReturn("log-stream");
|
||||
@@ -148,12 +681,19 @@ class RdsContainerManagerTest {
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
|
||||
manager.start("db1", null, DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db");
|
||||
RdsContainerHandle handle = manager.start(
|
||||
null, "db1", null, DatabaseEngine.MYSQL,
|
||||
"mysql:8.0", "root", "password", "db");
|
||||
|
||||
var spec = org.mockito.ArgumentCaptor.forClass(ContainerSpec.class);
|
||||
verify(lifecycleManager).removeIfExists("floci-rds-db1");
|
||||
verify(lifecycleManager).createAndStart(spec.capture());
|
||||
verify(lifecycleManager).removeIfExistsStrict("floci-rds-db1");
|
||||
verify(lifecycleManager).create(spec.capture());
|
||||
assertEquals("floci-rds-db1", spec.getValue().name());
|
||||
assertEquals("db1", handle.getRuntimeId());
|
||||
manager.stop(handle);
|
||||
verify(lifecycleManager).stopAndRemoveStrict(
|
||||
org.mockito.ArgumentMatchers.eq("container-id"),
|
||||
org.mockito.ArgumentMatchers.isNull());
|
||||
}
|
||||
|
||||
private static EmulatorConfig config(Path hostRoot) {
|
||||
@@ -174,4 +714,21 @@ class RdsContainerManagerTest {
|
||||
when(storage.hostPersistentPath()).thenReturn(hostRoot.toString());
|
||||
return config;
|
||||
}
|
||||
|
||||
private static void stubStarts(
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
ContainerLifecycleManager.ContainerInfo... infos) {
|
||||
int[] next = {0};
|
||||
when(lifecycleManager.create(any())).thenAnswer(invocation ->
|
||||
infos[Math.min(next[0]++, infos.length - 1)].containerId());
|
||||
when(lifecycleManager.startCreated(any(), any())).thenAnswer(invocation -> {
|
||||
String containerId = invocation.getArgument(0);
|
||||
for (ContainerLifecycleManager.ContainerInfo info : infos) {
|
||||
if (info.containerId().equals(containerId)) {
|
||||
return info;
|
||||
}
|
||||
}
|
||||
return infos[infos.length - 1];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package io.github.hectorvent.floci.services.rds.proxy;
|
||||
|
||||
import io.github.hectorvent.floci.services.rds.model.DatabaseEngine;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
class RdsProxyManagerTest {
|
||||
|
||||
@Test
|
||||
void replacingProxyStopsPreviousListenerAndKeepsReplacementOwned() throws IOException {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
int firstPort = availablePort();
|
||||
try {
|
||||
start(manager, "proxy", firstPort);
|
||||
int replacementPort = availablePort();
|
||||
|
||||
start(manager, "proxy", replacementPort);
|
||||
|
||||
assertPortAvailable(firstPort);
|
||||
assertPortUnavailable(replacementPort);
|
||||
manager.stopProxy("proxy");
|
||||
assertPortAvailable(replacementPort);
|
||||
} finally {
|
||||
manager.stopAll();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void registrationFailureAfterBindReleasesCandidateListener() throws IOException {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
int proxyPort = availablePort();
|
||||
try {
|
||||
assertThrows(RuntimeException.class, () -> start(manager, null, proxyPort));
|
||||
|
||||
assertPortAvailable(proxyPort);
|
||||
} finally {
|
||||
manager.stopAll();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedReplacementPreservesOriginalRegistryEntry() throws IOException {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
int originalPort = availablePort();
|
||||
try {
|
||||
start(manager, "proxy", originalPort);
|
||||
try (ServerSocket occupied = new ServerSocket(0)) {
|
||||
assertThrows(RuntimeException.class, () ->
|
||||
start(manager, "proxy", occupied.getLocalPort()));
|
||||
assertPortUnavailable(originalPort);
|
||||
}
|
||||
|
||||
manager.stopProxy("proxy");
|
||||
assertPortAvailable(originalPort);
|
||||
} finally {
|
||||
manager.stopAll();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopAllReleasesEveryListenerAndIsIdempotent() throws IOException {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
int firstPort = availablePort();
|
||||
start(manager, "first", firstPort);
|
||||
int secondPort = availablePort();
|
||||
start(manager, "second", secondPort);
|
||||
|
||||
manager.stopAll();
|
||||
|
||||
assertPortAvailable(firstPort);
|
||||
assertPortAvailable(secondPort);
|
||||
assertDoesNotThrow(manager::stopAll);
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeFailurePropagatesAndManagerRetainsOwnership() throws Exception {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
RdsAuthProxy proxy = authProxy("proxy");
|
||||
ServerSocket serverSocket = mock(ServerSocket.class);
|
||||
IOException closeFailure = new IOException("simulated close failure");
|
||||
doThrow(closeFailure).when(serverSocket).close();
|
||||
setServerSocket(proxy, serverSocket);
|
||||
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager);
|
||||
registry.put("proxy", proxy);
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class, () ->
|
||||
manager.stopProxy("proxy"));
|
||||
|
||||
assertSame(closeFailure, thrown.getCause());
|
||||
assertSame(proxy, registry.get("proxy"));
|
||||
registry.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedPreviousStopRestoresMappingAndReleasesCandidate() throws Exception {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
RdsAuthProxy previous = mock(RdsAuthProxy.class);
|
||||
doThrow(new IllegalStateException("simulated previous stop failure"))
|
||||
.when(previous).stop();
|
||||
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager);
|
||||
registry.put("proxy", previous);
|
||||
int candidatePort = availablePort();
|
||||
|
||||
assertThrows(RuntimeException.class, () -> start(manager, "proxy", candidatePort));
|
||||
|
||||
assertSame(previous, registry.get("proxy"));
|
||||
assertPortAvailable(candidatePort);
|
||||
registry.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopAllContinuesAndRetainsOnlyFailedListenerOwnership() throws Exception {
|
||||
RdsProxyManager manager = new RdsProxyManager(mock(RdsSigV4Validator.class));
|
||||
int successfulPort = availablePort();
|
||||
start(manager, "successful", successfulPort);
|
||||
RdsAuthProxy failed = mock(RdsAuthProxy.class);
|
||||
doThrow(new IllegalStateException("simulated shutdown stop failure"))
|
||||
.when(failed).stop();
|
||||
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager);
|
||||
registry.put("failed", failed);
|
||||
|
||||
assertDoesNotThrow(manager::stopAll);
|
||||
|
||||
assertTrue(registry.containsKey("failed"));
|
||||
assertFalse(registry.containsKey("successful"));
|
||||
assertPortAvailable(successfulPort);
|
||||
registry.clear();
|
||||
}
|
||||
|
||||
private static void start(RdsProxyManager manager, String key, int proxyPort) {
|
||||
manager.startProxy(key, DatabaseEngine.POSTGRES, false, proxyPort,
|
||||
"localhost", 1, "admin", "secret", "app", (user, password) -> true);
|
||||
}
|
||||
|
||||
private static RdsAuthProxy authProxy(String key) {
|
||||
return new RdsAuthProxy(key, "localhost", 1, DatabaseEngine.POSTGRES, false,
|
||||
"admin", "secret", "app", mock(RdsSigV4Validator.class),
|
||||
(user, password) -> true);
|
||||
}
|
||||
|
||||
private static void setServerSocket(RdsAuthProxy proxy, ServerSocket socket) throws Exception {
|
||||
Field field = RdsAuthProxy.class.getDeclaredField("serverSocket");
|
||||
field.setAccessible(true);
|
||||
field.set(proxy, socket);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static ConcurrentHashMap<String, RdsAuthProxy> registry(
|
||||
RdsProxyManager manager) throws Exception {
|
||||
Field field = RdsProxyManager.class.getDeclaredField("proxies");
|
||||
field.setAccessible(true);
|
||||
return (ConcurrentHashMap<String, RdsAuthProxy>) field.get(manager);
|
||||
}
|
||||
|
||||
private static int availablePort() throws IOException {
|
||||
try (ServerSocket socket = new ServerSocket(0)) {
|
||||
return socket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
private static void assertPortAvailable(int port) {
|
||||
IOException lastFailure = null;
|
||||
for (int attempt = 0; attempt < 50; attempt++) {
|
||||
try (ServerSocket ignored = reusableSocket(port)) {
|
||||
return;
|
||||
} catch (IOException e) {
|
||||
lastFailure = e;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(10);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
fail("Interrupted while waiting for proxy port " + port + " to be released", e);
|
||||
}
|
||||
}
|
||||
fail("Proxy port " + port + " was not released", lastFailure);
|
||||
}
|
||||
|
||||
private static void assertPortUnavailable(int port) {
|
||||
assertThrows(IOException.class, () -> {
|
||||
try (ServerSocket ignored = reusableSocket(port)) {
|
||||
// The active proxy owns this listener.
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static ServerSocket reusableSocket(int port) throws IOException {
|
||||
ServerSocket socket = new ServerSocket();
|
||||
socket.setReuseAddress(true);
|
||||
socket.bind(new InetSocketAddress(port));
|
||||
return socket;
|
||||
}
|
||||
}
|
||||
+17
-6
@@ -28,8 +28,7 @@ class RdsDataResourceResolverTest {
|
||||
cluster.setDbClusterArn("arn:aws:rds:us-east-1:000000000000:cluster:cluster1");
|
||||
cluster.setContainerHost("127.0.0.1");
|
||||
cluster.setContainerPort(3306);
|
||||
when(rdsService.listDbClusters(null)).thenReturn(List.of(cluster));
|
||||
when(rdsService.listDbInstances(null)).thenReturn(List.of());
|
||||
when(rdsService.getDbCluster("cluster1", "us-east-1")).thenReturn(cluster);
|
||||
|
||||
RdsDataResourceResolver.DatabaseTarget target = new RdsDataResourceResolver(rdsService)
|
||||
.resolve("arn:aws:rds:us-east-1:000000000000:cluster:cluster1");
|
||||
@@ -43,10 +42,8 @@ class RdsDataResourceResolverTest {
|
||||
@Test
|
||||
void missingResourceUsesModeledDataApiBadRequestCode() {
|
||||
RdsService rdsService = mock(RdsService.class);
|
||||
when(rdsService.listDbClusters(null)).thenReturn(List.of());
|
||||
when(rdsService.listDbInstances(null)).thenReturn(List.of());
|
||||
when(rdsService.getDbCluster("missing")).thenThrow(new AwsException("DBClusterNotFoundFault", "missing", 404));
|
||||
when(rdsService.getDbInstance("missing")).thenThrow(new AwsException("DBInstanceNotFound", "missing", 404));
|
||||
when(rdsService.getDbCluster("missing", "us-east-1"))
|
||||
.thenThrow(new AwsException("DBClusterNotFoundFault", "missing", 404));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> new RdsDataResourceResolver(rdsService)
|
||||
.resolve("arn:aws:rds:us-east-1:000000000000:cluster:missing"));
|
||||
@@ -54,4 +51,18 @@ class RdsDataResourceResolverTest {
|
||||
assertEquals("BadRequestException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsResourceArnOutsideSignedRequestRegionBeforeLookup() {
|
||||
RdsService rdsService = mock(RdsService.class);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () ->
|
||||
new RdsDataResourceResolver(rdsService).resolve(
|
||||
"arn:aws:rds:us-west-2:000000000000:cluster:cluster1",
|
||||
"us-east-1"));
|
||||
|
||||
assertEquals("BadRequestException", error.getErrorCode());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
org.mockito.Mockito.verifyNoInteractions(rdsService);
|
||||
}
|
||||
}
|
||||
@@ -218,7 +218,8 @@ class RdsDataServiceTest {
|
||||
ObjectNode insertCommitted = harness.request("insert into data_api_items(id, title, score) values ('commit', 'Commit', 1)");
|
||||
insertCommitted.put("transactionId", committedTx);
|
||||
harness.service.executeStatement(insertCommitted, REGION);
|
||||
ObjectNode commitResponse = harness.service.commitTransaction(harness.transactionRequest(committedTx));
|
||||
ObjectNode commitResponse = harness.service.commitTransaction(
|
||||
harness.transactionRequest(committedTx), REGION);
|
||||
assertEquals("Transaction Committed", commitResponse.get("transactionStatus").asText());
|
||||
assertEquals(1L, harness.countById("commit"));
|
||||
|
||||
@@ -226,7 +227,8 @@ class RdsDataServiceTest {
|
||||
ObjectNode insertRolledBack = harness.request("insert into data_api_items(id, title, score) values ('rollback', 'Rollback', 1)");
|
||||
insertRolledBack.put("transactionId", rolledBackTx);
|
||||
harness.service.executeStatement(insertRolledBack, REGION);
|
||||
ObjectNode rollbackResponse = harness.service.rollbackTransaction(harness.transactionRequest(rolledBackTx));
|
||||
ObjectNode rollbackResponse = harness.service.rollbackTransaction(
|
||||
harness.transactionRequest(rolledBackTx), REGION);
|
||||
assertEquals("Rollback Complete", rollbackResponse.get("transactionStatus").asText());
|
||||
assertEquals(0L, harness.countById("rollback"));
|
||||
|
||||
@@ -258,7 +260,12 @@ class RdsDataServiceTest {
|
||||
() -> harness.service.executeStatement(mismatchedDatabase, REGION));
|
||||
assertEquals("TransactionNotFoundException", databaseMismatch.getErrorCode());
|
||||
|
||||
harness.service.rollbackTransaction(harness.transactionRequest(mismatchTx));
|
||||
AwsException signedRegionMismatch = assertThrows(AwsException.class,
|
||||
() -> harness.service.commitTransaction(
|
||||
harness.transactionRequest(mismatchTx), "us-west-2"));
|
||||
assertEquals("TransactionNotFoundException", signedRegionMismatch.getErrorCode());
|
||||
|
||||
harness.service.rollbackTransaction(harness.transactionRequest(mismatchTx), REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -273,7 +280,8 @@ class RdsDataServiceTest {
|
||||
insert.put("transactionId", tx);
|
||||
harness.service.executeStatement(insert, REGION);
|
||||
|
||||
ObjectNode commitResponse = harness.service.commitTransaction(harness.transactionRequest(FALLBACK_RESOURCE_ARN, tx));
|
||||
ObjectNode commitResponse = harness.service.commitTransaction(
|
||||
harness.transactionRequest(FALLBACK_RESOURCE_ARN, tx), REGION);
|
||||
|
||||
assertEquals("Transaction Committed", commitResponse.get("transactionStatus").asText());
|
||||
assertEquals(1L, harness.countById("fallback"));
|
||||
@@ -292,12 +300,13 @@ class RdsDataServiceTest {
|
||||
insert.put("transactionId", tx);
|
||||
harness.service.executeStatement(insert, REGION);
|
||||
doThrow(new AwsException("BadRequestException", "resource is gone", 400))
|
||||
.when(harness.resolver).resolve(RESOURCE_ARN);
|
||||
.when(harness.resolver).resolve(RESOURCE_ARN, REGION);
|
||||
|
||||
ObjectNode commitResponse = harness.service.commitTransaction(harness.transactionRequest(tx));
|
||||
ObjectNode commitResponse = harness.service.commitTransaction(
|
||||
harness.transactionRequest(tx), REGION);
|
||||
|
||||
assertEquals("Transaction Committed", commitResponse.get("transactionStatus").asText());
|
||||
doReturn(harness.target).when(harness.resolver).resolve(RESOURCE_ARN);
|
||||
doReturn(harness.target).when(harness.resolver).resolve(RESOURCE_ARN, REGION);
|
||||
assertEquals(1L, harness.countById("deleted-resource"));
|
||||
}
|
||||
|
||||
@@ -324,17 +333,17 @@ class RdsDataServiceTest {
|
||||
ObjectNode commitMissingResource = harness.transactionRequest(tx);
|
||||
commitMissingResource.remove("resourceArn");
|
||||
AwsException missingCommitResource = assertThrows(AwsException.class,
|
||||
() -> harness.service.commitTransaction(commitMissingResource));
|
||||
() -> harness.service.commitTransaction(commitMissingResource, REGION));
|
||||
assertEquals("BadRequestException", missingCommitResource.getErrorCode());
|
||||
assertEquals("resourceArn is required.", missingCommitResource.getMessage());
|
||||
|
||||
ObjectNode rollbackMismatchedResource = harness.transactionRequest(tx);
|
||||
rollbackMismatchedResource.put("resourceArn", OTHER_RESOURCE_ARN);
|
||||
AwsException rollbackMismatch = assertThrows(AwsException.class,
|
||||
() -> harness.service.rollbackTransaction(rollbackMismatchedResource));
|
||||
() -> harness.service.rollbackTransaction(rollbackMismatchedResource, REGION));
|
||||
assertEquals("TransactionNotFoundException", rollbackMismatch.getErrorCode());
|
||||
|
||||
harness.service.rollbackTransaction(harness.transactionRequest(tx));
|
||||
harness.service.rollbackTransaction(harness.transactionRequest(tx), REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -403,7 +412,7 @@ class RdsDataServiceTest {
|
||||
RdsDataResourceResolver resolver = mock(RdsDataResourceResolver.class);
|
||||
SecretsManagerService secrets = fallbackSecrets();
|
||||
RdsDataResourceResolver.DatabaseTarget target = target();
|
||||
when(resolver.resolve(RESOURCE_ARN)).thenReturn(target);
|
||||
when(resolver.resolve(RESOURCE_ARN, REGION)).thenReturn(target);
|
||||
AtomicBoolean closed = new AtomicBoolean(false);
|
||||
RdsDataConnectionFactory failingFactory = new RdsDataConnectionFactory() {
|
||||
@Override
|
||||
@@ -524,10 +533,10 @@ class RdsDataServiceTest {
|
||||
resolver = mock(RdsDataResourceResolver.class);
|
||||
SecretsManagerService secrets = fallbackSecrets();
|
||||
target = target();
|
||||
when(resolver.resolve(RESOURCE_ARN)).thenReturn(target);
|
||||
when(resolver.resolve(FALLBACK_RESOURCE_ARN)).thenReturn(target);
|
||||
when(resolver.resolve(OTHER_RESOURCE_ARN)).thenReturn(target(OTHER_RESOURCE_ARN));
|
||||
when(resolver.resolve(UNKNOWN_RESOURCE_ARN))
|
||||
when(resolver.resolve(RESOURCE_ARN, REGION)).thenReturn(target);
|
||||
when(resolver.resolve(FALLBACK_RESOURCE_ARN, REGION)).thenReturn(target);
|
||||
when(resolver.resolve(OTHER_RESOURCE_ARN, REGION)).thenReturn(target(OTHER_RESOURCE_ARN));
|
||||
when(resolver.resolve(UNKNOWN_RESOURCE_ARN, REGION))
|
||||
.thenThrow(new AwsException("BadRequestException", "resource is missing", 400));
|
||||
RdsDataConnectionFactory connectionFactory = new RdsDataConnectionFactory() {
|
||||
@Override
|
||||
|
||||
Reference in new issue
Block a user