fix(rds): check that a DB instance's security groups exist and sit in its VPC (#8258)

CreateDBInstance and ModifyDBInstance now check that every security
group a request names exists in the caller's account and Region and sits
in the instance's VPC, refusing an unknown id with InvalidParameterValue
and a group of another VPC with InvalidParameterCombination. Restores,
read replicas, Blue/Green deployments and CloudFormation go through the
same check, and DocumentDB shares it. An instance whose request names no
groups gets its VPC's default security group, as RDS documents, and
describe reports that group for an instance that keeps none.
This commit is contained in:
Suja Shaj authored and GitHub committed 2026-11-16 07:09:37 -04:00
1 parent d1acc664ed
commit 93da7a6c26
15 files changed
+648 -94

No files matched your search

@@ -11,11 +11,12 @@ import software.amazon.awssdk.services.cloudformation.model.Stack;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.DBInstance;
import software.amazon.awssdk.services.rds.model.VpcSecurityGroupMembership;
import java.util.List;
import static io.floci.aws.testing.CfnStackWaits.output;
import static io.floci.aws.testing.Ec2Requests.defaultSecurityGroupId;
import static io.floci.aws.testing.RdsRequests.vpcSecurityGroupIds;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
@@ -23,8 +24,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@code VPCSecurityGroups} and {@code StorageEncrypted} on {@code AWS::RDS::DBInstance}, read back
* through the AWS SDK: the groups follow the template in place, through a failed update and when the
* template drops them, and a change of {@code StorageEncrypted} either way replaces the instance.
* through the AWS SDK: the groups follow the template in place, through a failed update, a group of
* another VPC that RDS refuses, and a template that drops them, and a change of {@code StorageEncrypted}
* either way replaces the instance.
*/
@QuarkusTest
@TestProfile(RdsMockProfile.class)
@@ -37,19 +39,24 @@ class CloudFormationRdsDbInstanceIntegrationTest {
void securityGroupsFollowTheTemplateThroughChangeRollbackAndRemoval() {
Stack created = stack.create(template("First", false, false));
String id = output(created, "DbId");
assertEquals(List.of(output(created, "FirstId")), groups(id));
assertEquals(List.of(output(created, "FirstId")), vpcSecurityGroupIds(rds(), id));
Stack changed = stack.update(template("Second", false, false), "UPDATE_COMPLETE");
assertEquals(id, output(changed, "DbId"));
assertEquals(List.of(output(changed, "SecondId")), groups(id));
assertEquals(List.of(output(changed, "SecondId")), vpcSecurityGroupIds(rds(), id));
stack.update(template("First", false, true), "UPDATE_ROLLBACK_COMPLETE");
assertEquals(List.of(output(changed, "SecondId")), groups(id));
assertEquals(List.of(output(changed, "SecondId")), vpcSecurityGroupIds(rds(), id));
// RDS refuses a group of another VPC, so the update rolls back and the instance keeps its group.
stack.update(template("Outside", false, false), "UPDATE_ROLLBACK_COMPLETE");
assertEquals(List.of(output(changed, "SecondId")), vpcSecurityGroupIds(rds(), id));
// As AWS's handler does, a template that drops the groups puts the instance on its VPC's default group.
Stack cleared = stack.update(template(null, false, false), "UPDATE_COMPLETE");
assertEquals(id, output(cleared, "DbId"));
assertEquals(List.of(defaultGroupOf(instance(id).dbSubnetGroup().vpcId())), groups(id));
assertEquals(List.of(defaultSecurityGroupId(stack.client(Ec2Client.builder()),
instance(id).dbSubnetGroup().vpcId())), vpcSecurityGroupIds(rds(), id));
}
@Test
@@ -74,8 +81,8 @@ class CloudFormationRdsDbInstanceIntegrationTest {
}
/**
* Two security groups and a DB instance on {@code group}, First or Second, or on none when it is
* null; with {@code StorageEncrypted: true} when {@code encrypted}, and with a resource that fails
* Two security groups of the default VPC, a third, Outside, of another VPC, and a DB instance on
* {@code group}, or on none when it is null; with {@code StorageEncrypted: true} when {@code encrypted}, and with a resource that fails
* after the instance when {@code laterFails}.
*/
private static String template(String group, boolean encrypted, boolean laterFails) {
@@ -85,6 +92,9 @@ class CloudFormationRdsDbInstanceIntegrationTest {
{"Resources": {
"First": {"Type": "AWS::EC2::SecurityGroup", "Properties": {"GroupDescription": "first"}},
"Second": {"Type": "AWS::EC2::SecurityGroup", "Properties": {"GroupDescription": "second"}},
"Elsewhere": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.43.0.0/16"}},
"Outside": {"Type": "AWS::EC2::SecurityGroup", "Properties": {"GroupDescription": "outside",
"VpcId": {"Ref": "Elsewhere"}}},
"Db": {"Type": "AWS::RDS::DBInstance", "Properties": {"Engine": "postgres",
"DBInstanceClass": "db.t3.micro", "AllocatedStorage": 20, "MasterUsername": "dbadmin",
"MasterUserPassword": "password123"%s%s}}%s
@@ -105,21 +115,10 @@ class CloudFormationRdsDbInstanceIntegrationTest {
return rds().describeDBInstances(request -> request.dbInstanceIdentifier(id)).dbInstances().getFirst();
}
private List<String> groups(String id) {
return instance(id).vpcSecurityGroups().stream().map(VpcSecurityGroupMembership::vpcSecurityGroupId).toList();
}
/** The instances this stack's {@code Db} resource has, by the name CloudFormation generates for it. */
private List<String> stackInstanceIds() {
return rds().describeDBInstances().dbInstances().stream()
.map(DBInstance::dbInstanceIdentifier)
.filter(id -> id.startsWith(stack.name() + "-db-")).toList();
}
private String defaultGroupOf(String vpcId) {
return stack.client(Ec2Client.builder()).describeSecurityGroups(request -> request.filters(
filter -> filter.name("vpc-id").values(vpcId),
filter -> filter.name("group-name").values("default")))
.securityGroups().getFirst().groupId();
}
}
@@ -2072,6 +2072,8 @@ class RdsCfnProvisionerTest {
private static final String PLAIN = "{\"Engine\":\"postgres\"}";
private static final String SG_FIRST = "{\"Engine\":\"postgres\",\"VPCSecurityGroups\":[\"sg-first\"]}";
private static final String SG_SECOND = "{\"Engine\":\"postgres\",\"VPCSecurityGroups\":[\"sg-second\"]}";
private static final String MOVED_TO_SG_SECOND =
"{\"Engine\":\"postgres\",\"DBSubnetGroupName\":\"app-subnets\",\"VPCSecurityGroups\":[\"sg-second\"]}";
private static final String ENCRYPTED = "{\"Engine\":\"postgres\",\"StorageEncrypted\":true}";
private static final String MEMBER = "{\"DBClusterIdentifier\":\"cluster\"";
@@ -2130,6 +2132,17 @@ class RdsCfnProvisionerTest {
return new Created(replaced, created.id(), PLAIN, created.onFile(), created.requests());
}
/** Makes {@code groupIds} the default groups of whatever VPC an update leaves the instance in. */
private void vpcDefaultGroups(List<String> groupIds) {
when(rdsService.defaultVpcSecurityGroupIds(eq("us-east-1"), any(), any())).thenReturn(groupIds);
}
/** Asserts the update neither modified the instance nor changed its VPC security groups. */
private void assertInstanceUntouched() {
assertEquals(0, modifyCalls());
verify(rdsService, never()).setDbInstanceVpcSecurityGroups(any(), any(), any());
}
/** How many times the provisioner asked RdsService to modify an instance, whatever the arguments. */
private long modifyCalls() {
return Mockito.mockingDetails(rdsService).getInvocations().stream()
@@ -2169,6 +2182,7 @@ class RdsCfnProvisionerTest {
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
InOrder order = inOrder(rdsService);
order.verify(rdsService).requireVpcSecurityGroupsFit("us-east-1", r.getPhysicalId(), null, List.of("sg-second"));
order.verify(rdsService).modifyDbInstance(eq(r.getPhysicalId()), any(), any(), any(), any(), any(), any(),
any(), any(DbInstanceSettings.class));
order.verify(rdsService).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of("sg-second"));
@@ -2181,7 +2195,7 @@ class RdsCfnProvisionerTest {
@Test
void droppedGroupsPutTheInstanceOnItsVpcsDefaultGroupAndARollbackPutsThemBack() {
when(rdsService.defaultVpcSecurityGroupIds(eq("us-east-1"), any())).thenReturn(List.of("sg-default"));
vpcDefaultGroups(List.of("sg-default"));
StackResource r = updateFromFirstGroup(PLAIN);
@@ -2190,6 +2204,44 @@ class RdsCfnProvisionerTest {
verify(rdsService).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of("sg-first"));
}
@Test
void droppedGroupsTakeTheDefaultGroupOfTheVpcTheUpdateMovesTheInstanceTo() {
when(rdsService.defaultVpcSecurityGroupIds(eq("us-east-1"), any(), eq("app-subnets")))
.thenReturn(List.of("sg-app-default"));
StackResource r = updateFromFirstGroup("{\"Engine\":\"postgres\",\"DBSubnetGroupName\":\"app-subnets\"}");
verify(rdsService).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of("sg-app-default"));
}
@Test
void anUpdateWhoseGroupsDoNotFitTheVpcItLeavesTheInstanceInFailsBeforeAnythingChanges() {
doThrow(new AwsException("InvalidParameterCombination",
"The DB instance and EC2 security group are in different VPCs.", 400))
.when(rdsService).requireVpcSecurityGroupsFit(eq("us-east-1"), any(), eq("app-subnets"),
eq(List.of("sg-second")));
StackResource r = updateFromFirstGroup(MOVED_TO_SG_SECOND);
assertEquals("CREATE_FAILED", r.getStatus());
assertTrue(r.getStatusReason().contains("different VPCs"), r.getStatusReason());
assertInstanceUntouched();
}
@Test
void aRollbackLeavesTheGroupsOfAnInstanceTheUpdateMovedToAnotherVpc() {
// A rollback does not move the instance back, and the old VPC's groups cannot go on it there.
StackResource r = updateFromFirstGroup(MOVED_TO_SG_SECOND, created -> {
when(created.onFile().getVpcId()).thenReturn("vpc-default", "vpc-app");
when(created.onFile().getDbSubnetGroupName()).thenReturn("default", "app-subnets");
});
assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());
verify(rdsService).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of("sg-second"));
assertFalse(provisioner.rollbackUpdate(r), "the move to another VPC has no rollback here");
verify(rdsService, never()).setDbInstanceVpcSecurityGroups("us-east-1", r.getPhysicalId(), List.of("sg-first"));
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
PLAIN + " | " + PLAIN + " | sg-default",
@@ -2200,8 +2252,7 @@ class RdsCfnProvisionerTest {
String template, String updated, String defaultGroup) {
// AWS's handler gives the VPC's default group only to a standalone instance whose previous
// template declared groups, and only when there is such a group; a member's are its cluster's.
when(rdsService.defaultVpcSecurityGroupIds(eq("us-east-1"), any()))
.thenReturn(defaultGroup == null ? List.of() : List.of(defaultGroup));
vpcDefaultGroups(defaultGroup == null ? List.of() : List.of(defaultGroup));
Created created = createInstance(template, "sg-manual");
StackResource r = updateInstance(created, updated);
@@ -2222,8 +2273,7 @@ class RdsCfnProvisionerTest {
assertEquals("CREATE_FAILED", r.getStatus());
assertTrue(r.getStatusReason().contains("Modify vpc security group for the DB Cluster"), r.getStatusReason());
assertEquals(0, modifyCalls());
verify(rdsService, never()).setDbInstanceVpcSecurityGroups(any(), any(), any());
assertInstanceUntouched();
}
@Test
@@ -2299,10 +2349,9 @@ class RdsCfnProvisionerTest {
String replacement = replaced.resource().getPhysicalId();
assertEquals(new CreateRequest(replacement, List.of(), DbInstanceSettings.defaults()),
replaced.requests().get(1));
assertEquals(0, modifyCalls());
assertInstanceUntouched();
verify(rdsService, never()).deleteDbInstance(any(), any());
verify(rdsService, never()).deleteDbInstance(any());
verify(rdsService, never()).setDbInstanceVpcSecurityGroups(any(), any(), any());
assertEquals(replaced.id(), provisioner.updateCleanupPhysicalId(replaced.resource()));
assertTrue(provisioner.completeUpdate(replaced.resource()).complete());
@@ -13,7 +13,6 @@ import io.floci.aws.services.docdb.model.DocDbClusterSettings;
import io.floci.aws.services.docdb.model.DocDbInstance;
import io.floci.aws.services.docdb.model.DocDbInstanceSettings;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.SecurityGroup;
import io.floci.aws.services.kms.KmsService;
import io.floci.aws.services.kms.model.KmsKey;
import io.floci.aws.services.rds.RdsService;
@@ -27,6 +26,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import static io.floci.aws.testing.Ec2ServiceFixtures.securityGroup;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -265,9 +265,8 @@ class DocDbServiceTest {
when(rdsService.getDbSubnetGroup(eq("nope"), any())).thenThrow(new AwsException("DBSubnetGroupNotFoundFault", "x", 404));
when(rdsService.getDbClusterParameterGroup(eq("pg"), any())).thenReturn(new DbClusterParameterGroup("pg", "docdb5.0", "d"));
when(rdsService.getDbClusterParameterGroup(eq("nope"), any())).thenThrow(new AwsException("DBClusterParameterGroupNotFound", "x", 404));
SecurityGroup sg = new SecurityGroup();
sg.setGroupId("sg-1");
when(ec2Service.describeSecurityGroups(any(), eq(List.of("sg-1")), any(), any())).thenReturn(List.of(sg));
when(ec2Service.describeSecurityGroups(any(), eq(List.of("sg-1")), any(), any()))
.thenReturn(List.of(securityGroup("sg-1", "app", "vpc-1")));
when(ec2Service.describeSecurityGroups(any(), eq(List.of("sg-nope")), any(), any())).thenReturn(List.of());
KmsKey key = new KmsKey();
key.setKeyId("k1");
@@ -458,6 +458,23 @@ class RdsQueryHandlerTest {
assertTrue(body.contains("<PubliclyAccessible>true</PubliclyAccessible>"), body);
}
@Test
void describeDbInstances_showsAnInstanceThatKeepsNoGroupsOnItsVpcsDefaultGroup() {
DbInstance own = makeInstance("own");
own.setVpcSecurityGroupIds(List.of("sg-own"));
DbInstance member = makeInstance("member");
DbInstance vpcGone = makeInstance("vpc-gone");
when(service.listDbInstances(null, null)).thenReturn(List.of(own, member, vpcGone));
when(service.defaultVpcSecurityGroupIds(member)).thenReturn(List.of("sg-vpc-default"));
String body = (String) handler.handle("DescribeDBInstances", params()).getEntity();
assertTrue(body.contains("<VpcSecurityGroupId>sg-own</VpcSecurityGroupId>"), body);
assertTrue(body.contains("<VpcSecurityGroupId>sg-vpc-default</VpcSecurityGroupId>"), body);
assertTrue(body.contains("<VpcSecurityGroupId>sg-00000000</VpcSecurityGroupId>"), body);
verify(service, never()).defaultVpcSecurityGroupIds(own);
}
@Test
void describeDbInstances_reportsIncompatibleParametersWhenTheDatabaseRefusedItsGroup() {
DbInstance refused = makeInstance("refused");
@@ -103,6 +103,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.LogRecord;
import java.util.stream.Collectors;
import static io.floci.aws.testing.Ec2ServiceFixtures.securityGroup;
import static io.floci.aws.testing.ThreadStates.awaitBlockedOrDone;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
@@ -110,6 +111,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
@@ -169,6 +171,8 @@ class RdsServiceTest {
private KmsService kmsService;
private EmulatorConfig config;
private EmulatorConfig.RdsServiceConfig rdsConfig;
/** The security groups the mocked EC2 knows, by id; see {@link #securityGroupsIn}. */
private final Map<String, SecurityGroup> securityGroups = new HashMap<>();
@BeforeEach
void setUp() {
@@ -221,6 +225,11 @@ class RdsServiceTest {
.filter(Objects::nonNull)
.toList();
});
when(ec2Service.describeSecurityGroups(any(), anyList(), anyList(), anyMap()))
.thenAnswer(invocation -> invocation.<List<String>>getArgument(1).stream()
.map(securityGroups::get)
.filter(Objects::nonNull)
.toList());
}
@Test
@@ -1563,10 +1572,8 @@ class RdsServiceTest {
@Test
void vpcSecurityGroupsPersistThroughCreateModifyAndCloudFormationsExactSet() {
DbInstance instance = rdsService.createDbInstance("mydb", "postgres", "13",
"admin", "password", "dbname", "db.t3.micro",
20, false, null, null, null, null, false, false, null,
Map.of(), List.of("sg-created"));
securityGroupsIn("vpc-default", "sg-created", "sg-updated-a", "sg-updated-b");
DbInstance instance = createInstanceWithGroups(null, List.of("sg-created"));
assertEquals(List.of("sg-created"), instance.getVpcSecurityGroupIds());
@@ -1581,11 +1588,147 @@ class RdsServiceTest {
.getVpcSecurityGroupIds());
assertEquals(List.of(), rdsService.getDbInstance("mydb").getVpcSecurityGroupIds());
SecurityGroup defaultGroup = new SecurityGroup();
defaultGroup.setGroupId("sg-default");
when(ec2Service.defaultSecurityGroupOf("us-east-1", rdsService.getDbInstance("mydb").getVpcId()))
.thenReturn(Optional.of(defaultGroup));
assertEquals(List.of("sg-default"), rdsService.defaultVpcSecurityGroupIds("us-east-1", "mydb"));
vpcDefaultGroup("vpc-default", "sg-default");
assertEquals(List.of("sg-default"), rdsService.defaultVpcSecurityGroupIds("us-east-1", "mydb", null));
}
@Test
void createDbInstanceRefusesGroupsThatDoNotExistAndKeepsNothing() {
anotherVpc();
AwsException refused = assertThrows(AwsException.class,
() -> createInstanceWithGroups(null, List.of("sg-first", "sg-missing", "sg-gone")));
assertEquals("InvalidParameterValue", refused.getErrorCode());
assertEquals(400, refused.getHttpStatus());
assertEquals("Invalid security group , groupId= sg-missing, sg-gone, groupName=.", refused.getMessage());
assertThrows(AwsException.class, () -> rdsService.getDbInstance("mydb"));
verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
assertEquals(7000, createInstanceWithGroups(null, List.of("sg-first")).getEndpoint().port(),
"the refused create gave its proxy port back");
}
@Test
void createDbInstanceRefusesAGroupOutsideTheVpcOfItsSubnetGroup() {
anotherVpc();
AwsException refused = assertThrows(AwsException.class,
() -> createInstanceWithGroups("app-subnets", List.of("sg-app", "sg-first")));
assertEquals("InvalidParameterCombination", refused.getErrorCode());
assertEquals(400, refused.getHttpStatus());
assertEquals("The DB instance and EC2 security group are in different VPCs. The DB instance is in vpc-app"
+ " and the EC2 security group is in vpc-default", refused.getMessage());
assertThrows(AwsException.class, () -> rdsService.getDbInstance("mydb"));
}
@Test
void modifyDbInstanceRefusesAMissingGroupOrOneOfAnotherVpcAndKeepsTheGroups() {
instanceBesideAnotherVpc();
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> rdsService.modifyDbInstance("mydb", null, null, null, List.of("sg-missing"))).getErrorCode());
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
() -> rdsService.modifyDbInstance("mydb", null, null, null, List.of("sg-app"))).getErrorCode());
assertEquals(List.of("sg-first"), rdsService.getDbInstance("mydb").getVpcSecurityGroupIds());
}
@Test
void modifyDbInstanceChecksTheGroupsAgainstTheVpcOfANewSubnetGroup() {
instanceBesideAnotherVpc();
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
() -> rdsService.modifyDbInstance("mydb", null, null, "app-subnets", List.of("sg-first"))).getErrorCode());
assertEquals("default", rdsService.getDbInstance("mydb").getDbSubnetGroupName());
rdsService.modifyDbInstance("mydb", null, null, "app-subnets", List.of("sg-app"));
assertEquals("vpc-app", rdsService.getDbInstance("mydb").getVpcId());
// The instance is in vpc-app now, so a later change of the groups alone is checked against it.
assertEquals(List.of("sg-app-second"), rdsService.modifyDbInstance("mydb", null, null, null,
List.of("sg-app-second")).getVpcSecurityGroupIds());
}
@Test
void cloudFormationsGroupChangeIsCheckedLikeModifyDbInstance() {
instanceBesideAnotherVpc();
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
() -> rdsService.setDbInstanceVpcSecurityGroups("us-east-1", "mydb", List.of("sg-missing")))
.getErrorCode());
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
() -> rdsService.setDbInstanceVpcSecurityGroups("us-east-1", "mydb", List.of("sg-app")))
.getErrorCode());
assertEquals(List.of("sg-first"), rdsService.getDbInstance("mydb").getVpcSecurityGroupIds());
}
@Test
void cloudFormationChecksAndDefaultsTheGroupsForTheVpcItsUpdateLeavesTheInstanceIn() {
instanceBesideAnotherVpc();
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
() -> rdsService.requireVpcSecurityGroupsFit("us-east-1", "mydb", "app-subnets", List.of("sg-first")))
.getErrorCode());
assertEquals("InvalidParameterCombination", assertThrows(AwsException.class,
() -> rdsService.requireVpcSecurityGroupsFit("us-east-1", "mydb", null, List.of("sg-app")))
.getErrorCode());
rdsService.requireVpcSecurityGroupsFit("us-east-1", "mydb", "app-subnets", List.of("sg-app"));
assertEquals(List.of("sg-app-default"),
rdsService.defaultVpcSecurityGroupIds("us-east-1", "mydb", "app-subnets"));
assertEquals("default", rdsService.getDbInstance("mydb").getDbSubnetGroupName(), "neither moves the instance");
}
@Test
void aStandaloneInstanceThatNamesNoGroupsGetsItsVpcsDefaultGroupAndAClusterMemberIsOnlyShownOnIt() {
// A cluster member's groups are its cluster's, which Floci does not keep.
vpcDefaultGroup("vpc-default", "sg-default");
rdsService.createDbCluster("groups-cluster", "aurora-postgresql", "16.3",
"admin", "password", "dbname", false, null);
assertEquals(List.of("sg-default"), createInstanceWithGroups(null, List.of()).getVpcSecurityGroupIds());
DbInstance member = createMember(rdsService, "member", "db.r5.large", "groups-cluster");
assertEquals(List.of(), member.getVpcSecurityGroupIds());
assertEquals(List.of("sg-default"), rdsService.defaultVpcSecurityGroupIds(member));
}
@Test
void anInstanceStoredWithoutGroupsIsOnItsVpcsDefaultGroupWhileThatVpcIsThere() {
vpcDefaultGroup("vpc-default", "sg-default");
when(ec2Service.defaultSecurityGroupOf("us-east-1", "vpc-gone"))
.thenThrow(new AwsException("InvalidVpcID.NotFound", "The vpc ID 'vpc-gone' does not exist", 400));
DbInstance stored = persistedInstance("stored", "000000000000", "password", 5432);
assertEquals(List.of(), rdsService.defaultVpcSecurityGroupIds(stored), "no VPC recorded");
stored.setVpcId("vpc-default");
assertEquals(List.of("sg-default"), rdsService.defaultVpcSecurityGroupIds(stored));
stored.setVpcId("vpc-gone");
assertEquals(List.of(), rdsService.defaultVpcSecurityGroupIds(stored));
}
@Test
void aReplicaInAnotherVpcGetsThatVpcsDefaultGroupAndOneInTheSourcesVpcItsGroups() {
instanceBesideAnotherVpc();
String source = "arn:aws:rds:us-east-1:123456789012:db:mydb";
assertEquals(List.of("sg-app-default"), rdsService.createDbInstanceReadReplica(
replicaRequest("app-replica", source, "app-subnets"), null).getVpcSecurityGroupIds());
assertEquals(List.of("sg-first"), rdsService.createDbInstanceReadReplica(
replicaRequest("default-replica", source, "default"), null).getVpcSecurityGroupIds());
}
@Test
void aMoveToAnotherVpcWithoutGroupsPutsTheInstanceOnThatVpcsDefaultGroup() {
instanceBesideAnotherVpc();
assertEquals(List.of("sg-app-default"), rdsService.modifyDbInstance("mydb", null, null, "app-subnets", null)
.getVpcSecurityGroupIds());
// A subnet group of the VPC the instance is already in keeps its groups.
rdsService.modifyDbInstance("mydb", null, null, null, List.of("sg-app"));
assertEquals(List.of("sg-app"), rdsService.modifyDbInstance("mydb", null, null, "app-subnets", null)
.getVpcSecurityGroupIds());
}
@Test
@@ -11278,6 +11421,47 @@ class RdsServiceTest {
return subnet;
}
/** Makes {@code groupIds} security groups of {@code vpcId} that the mocked EC2 reports. */
private void securityGroupsIn(String vpcId, String... groupIds) {
for (String groupId : groupIds) {
securityGroups.put(groupId, securityGroup(groupId, groupId, vpcId));
}
}
/** Makes {@code groupId} the default security group EC2 reports for {@code vpcId} in us-east-1. */
private void vpcDefaultGroup(String vpcId, String groupId) {
when(ec2Service.defaultSecurityGroupOf("us-east-1", vpcId))
.thenReturn(Optional.of(securityGroup(groupId, "default", vpcId)));
}
/**
* Group sg-first in the default VPC, and beside it vpc-app with DB subnet group app-subnets, the
* groups sg-app and sg-app-second, and the default group sg-app-default.
*/
private void anotherVpc() {
securityGroupsIn("vpc-default", "sg-first");
securityGroupsIn("vpc-app", "sg-app", "sg-app-second");
vpcDefaultGroup("vpc-app", "sg-app-default");
List<String> subnetIds = List.of("subnet-app-a", "subnet-app-b");
when(ec2Service.describeSubnets(eq("us-east-1"), eq(subnetIds), eq(Map.of()))).thenReturn(List.of(
subnet("subnet-app-a", "vpc-app", "us-east-1a"), subnet("subnet-app-b", "vpc-app", "us-east-1b")));
rdsService.createDbSubnetGroup("app-subnets", "app", subnetIds);
}
/** {@link #anotherVpc()}, with instance mydb in the default VPC on sg-first. */
private void instanceBesideAnotherVpc() {
anotherVpc();
createInstanceWithGroups(null, List.of("sg-first"));
}
/** PostgreSQL instance mydb on DB subnet group {@code subnetGroup}, the default when null. */
private DbInstance createInstanceWithGroups(String subnetGroup, List<String> groupIds) {
return rdsService.createDbInstance("mydb", "postgres", "13",
"admin", "password", "dbname", "db.t3.micro",
20, false, null, subnetGroup, null, null, false, false, null,
Map.of(), groupIds);
}
@Test
void createDbSubnetGroupStoresTheTagsItIsGiven() {
rdsService.createDbSubnetGroup("tagged", "d", List.of("subnet-default-a", "subnet-default-b"), "us-east-1",
@@ -11718,8 +11902,13 @@ class RdsServiceTest {
}
private static ReadReplicaRequest replicaRequest(String id, String source) {
return replicaRequest(id, source, null);
}
/** A replica of {@code source} on DB subnet group {@code subnetGroup}, with nothing else named. */
private static ReadReplicaRequest replicaRequest(String id, String source, String subnetGroup) {
return new ReadReplicaRequest(id, source, null, null, null, null, null, null, null,
null, null, null, null, null, null, Map.of());
subnetGroup, null, null, null, null, null, Map.of());
}
@Test
@@ -11754,6 +11943,7 @@ class RdsServiceTest {
@Test
void createReadReplicaHonoursOverridesAndResolvesAnArnSource() {
securityGroupsIn("vpc-default", "sg-replica");
createPostgresSource("primary");
when(containerManager.createPostgresSnapshot(any(), eq("admin"))).thenReturn("DUMP");
@@ -11778,6 +11968,7 @@ class RdsServiceTest {
@Test
void sameRegionReplicaInheritsGroupsAndCrossRegionReplicaGetsDefaultsAndArnLinks() {
securityGroupsIn("vpc-default", "sg-source");
rdsService.createDbParameterGroup("primary-pg", "postgres16", "source group");
rdsService.createDbInstance("primary", "postgres", "16.3", "admin", "password", "appdb",
"db.t3.medium", 50, true, "primary-pg", null, null, null, false, false, null,
@@ -11807,9 +11998,8 @@ class RdsServiceTest {
// A subnet group goes with a source named by ARN; with a plain identifier AWS refuses it.
AwsException subnetGroup = assertThrows(AwsException.class, () ->
rdsService.createDbInstanceReadReplica(new ReadReplicaRequest("third", "primary",
null, null, null, null, null, null, null, "some-subnet-group", null, null,
null, null, null, Map.of()), null));
rdsService.createDbInstanceReadReplica(replicaRequest("third", "primary", "some-subnet-group"),
null));
assertEquals("DBSubnetGroupNotAllowedFault", subnetGroup.getErrorCode());
}
@@ -12769,12 +12959,8 @@ class RdsServiceTest {
@Test
void proxyEndpointTagsRoundTripAndItDefaultsToTheVpcsDefaultSecurityGroup() {
DbProxy proxy = proxyForEndpoints("app-proxy", "POSTGRESQL");
SecurityGroup defaultGroup = new SecurityGroup();
defaultGroup.setGroupId("sg-vpc-default");
defaultGroup.setGroupName("default");
// Picking the group out of the VPC is Ec2Service's job, covered in Ec2ServiceTest.
when(ec2Service.defaultSecurityGroupOf("us-east-1", proxy.getVpcId()))
.thenReturn(Optional.of(defaultGroup));
vpcDefaultGroup(proxy.getVpcId(), "sg-vpc-default");
DbProxyEndpoint endpoint = rdsService.createDbProxyEndpoint("us-east-1", "app-proxy", "ep",
PROXY_SUBNET_IDS, List.of(), null, null, Map.of("env", "dev"));
@@ -0,0 +1,117 @@
package io.floci.aws.services.rds;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.RdsMockProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.DbInstanceNotFoundException;
import java.util.List;
import static io.floci.aws.testing.AwsSdkErrors.assertAwsError;
import static io.floci.aws.testing.Ec2Requests.defaultSecurityGroupId;
import static io.floci.aws.testing.RdsRequests.rdsClient;
import static io.floci.aws.testing.RdsRequests.vpcSecurityGroupIds;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* The VPC security groups of a DB instance, checked through the AWS SDK against a VPC, subnets and
* groups that EC2 made: {@code CreateDBInstance} and {@code ModifyDBInstance} refuse a group that
* does not exist or sits in another VPC than the instance's DB subnet group, and keep nothing of the
* refused request. An instance that names no groups, or moves to another VPC without naming any, gets
* its VPC's default security group, and an Aurora member, which keeps none, reports it.
*/
@QuarkusTest
@TestProfile(RdsMockProfile.class)
class RdsVpcSecurityGroupsIntegrationTest {
private static final String ACCOUNT = "246813579024";
private static final String INSTANCE = "vpc-groups-db";
private static final String CLUSTER = "vpc-groups-cluster";
private static final String MEMBER = "vpc-groups-member";
@Test
void anInstancesGroupsMustExistAndSitInItsVpc() {
try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), ACCOUNT, Region.US_EAST_1);
RdsClient rds = rdsClient("us-east-1", ACCOUNT)) {
String vpcId = ec2.createVpc(request -> request.cidrBlock("10.41.0.0/16")).vpc().vpcId();
String group = group(ec2, vpcId, "app");
String otherVpcId = ec2.createVpc(request -> request.cidrBlock("10.42.0.0/16")).vpc().vpcId();
String otherVpcGroup = group(ec2, otherVpcId, "elsewhere");
subnetGroup(ec2, rds, "vpc-groups-subnets", vpcId, "10.41");
subnetGroup(ec2, rds, "vpc-groups-elsewhere", otherVpcId, "10.42");
AwsServiceException otherVpc = assertAwsError("InvalidParameterCombination", 400,
() -> create(rds, List.of(otherVpcGroup)));
assertEquals("The DB instance and EC2 security group are in different VPCs. The DB instance is in "
+ vpcId + " and the EC2 security group is in " + otherVpcId, otherVpc.awsErrorDetails().errorMessage());
assertEquals("Invalid security group , groupId= sg-0123456789abcdef0, groupName=.",
assertAwsError("InvalidParameterValue", 400, () -> create(rds, List.of("sg-0123456789abcdef0")))
.awsErrorDetails().errorMessage());
assertThrows(DbInstanceNotFoundException.class,
() -> rds.describeDBInstances(request -> request.dbInstanceIdentifier(INSTANCE)));
// An instance that names no groups gets its VPC's default group.
create(rds, List.of());
assertEquals(vpcId, rds.describeDBInstances(request -> request.dbInstanceIdentifier(INSTANCE))
.dbInstances().getFirst().dbSubnetGroup().vpcId());
List<String> defaultGroup = List.of(defaultSecurityGroupId(ec2, vpcId));
assertEquals(defaultGroup, vpcSecurityGroupIds(rds, INSTANCE));
assertAwsError("InvalidParameterCombination", 400, () -> rds.modifyDBInstance(request -> request
.dbInstanceIdentifier(INSTANCE).vpcSecurityGroupIds(otherVpcGroup)));
assertEquals(defaultGroup, vpcSecurityGroupIds(rds, INSTANCE));
rds.modifyDBInstance(request -> request.dbInstanceIdentifier(INSTANCE).vpcSecurityGroupIds(group));
assertEquals(List.of(group), vpcSecurityGroupIds(rds, INSTANCE));
// An Aurora member's groups are its cluster's, so it keeps none and reports its VPC's default group.
rds.createDBCluster(request -> request.dbClusterIdentifier(CLUSTER).engine("aurora-postgresql")
.masterUsername("dbadmin").masterUserPassword("password123")
.dbSubnetGroupName("vpc-groups-subnets"));
rds.createDBInstance(request -> request.dbInstanceIdentifier(MEMBER).dbClusterIdentifier(CLUSTER)
.engine("aurora-postgresql").dbInstanceClass("db.r5.large"));
assertEquals(defaultGroup, vpcSecurityGroupIds(rds, MEMBER));
// Its groups cannot follow it to another VPC, so a move that names none gets that VPC's default group.
rds.modifyDBInstance(request -> request.dbInstanceIdentifier(INSTANCE)
.dbSubnetGroupName("vpc-groups-elsewhere"));
assertEquals(List.of(defaultSecurityGroupId(ec2, otherVpcId)), vpcSecurityGroupIds(rds, INSTANCE));
}
}
/** DB subnet group {@code name} over two new subnets of {@code vpcId}, {@code prefix}.1.0/24 and .2.0/24. */
private static void subnetGroup(Ec2Client ec2, RdsClient rds, String name, String vpcId, String prefix) {
List<String> subnetIds = List.of(subnet(ec2, vpcId, prefix + ".1.0/24", "us-east-1a"),
subnet(ec2, vpcId, prefix + ".2.0/24", "us-east-1b"));
rds.createDBSubnetGroup(request -> request.dbSubnetGroupName(name).dbSubnetGroupDescription(name)
.subnetIds(subnetIds));
}
private static String subnet(Ec2Client ec2, String vpcId, String cidr, String zone) {
return ec2.createSubnet(request -> request.vpcId(vpcId).cidrBlock(cidr).availabilityZone(zone))
.subnet().subnetId();
}
private static String group(Ec2Client ec2, String vpcId, String name) {
return ec2.createSecurityGroup(request -> request.vpcId(vpcId).groupName(name).description(name)).groupId();
}
/** Creates the instance on DB subnet group vpc-groups-subnets, naming {@code groups} when there are any. */
private static void create(RdsClient rds, List<String> groups) {
rds.createDBInstance(request -> {
request.dbInstanceIdentifier(INSTANCE).engine("postgres").dbInstanceClass("db.t3.micro")
.allocatedStorage(20).masterUsername("dbadmin").masterUserPassword("password123")
.dbSubnetGroupName("vpc-groups-subnets");
if (!groups.isEmpty()) {
request.vpcSecurityGroupIds(groups);
}
});
}
}
@@ -1,12 +1,22 @@
package io.floci.aws.testing;
import io.restassured.specification.RequestSpecification;
import software.amazon.awssdk.services.ec2.Ec2Client;
import static io.restassured.RestAssured.given;
/** Requests to EC2 for tests: a signed Query request through RestAssured, and lookups through the SDK. */
public final class Ec2Requests {
private Ec2Requests() {}
/** The id of the {@code default} security group EC2 made with VPC {@code vpcId}. */
public static String defaultSecurityGroupId(Ec2Client client, String vpcId) {
return client.describeSecurityGroups(request -> request.filters(
filter -> filter.name("vpc-id").values(vpcId),
filter -> filter.name("group-name").values("default")))
.securityGroups().getFirst().groupId();
}
public static RequestSpecification ec2(String action, String accountId, String region) {
return given().header("Authorization",
"AWS4-HMAC-SHA256 Credential=" + accountId + "/20261016/" + region + "/ec2/aws4_request")
@@ -6,6 +6,7 @@ import io.floci.aws.services.ec2.Ec2ContainerManager;
import io.floci.aws.services.ec2.Ec2ImageCatalog;
import io.floci.aws.services.ec2.Ec2InstanceTypeCatalog;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.SecurityGroup;
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
import static org.mockito.Mockito.mock;
@@ -14,7 +15,7 @@ import static org.mockito.Mockito.when;
/**
* A mock-mode {@link Ec2Service} over in-memory storage for account 000000000000, for unit tests
* that drive the service directly: containers, port forwarding and images are mocks, so nothing
* leaves the JVM.
* leaves the JVM. {@link #securityGroup} builds a group for a test that mocks the service instead.
*/
public final class Ec2ServiceFixtures {
@@ -40,4 +41,13 @@ public final class Ec2ServiceFixtures {
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
storage);
}
/** Security group {@code groupId} named {@code groupName} in {@code vpcId}, with no rules. */
public static SecurityGroup securityGroup(String groupId, String groupName, String vpcId) {
SecurityGroup group = new SecurityGroup();
group.setGroupId(groupId);
group.setGroupName(groupName);
group.setVpcId(vpcId);
return group;
}
}
@@ -12,9 +12,11 @@ import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.RdsClientBuilder;
import software.amazon.awssdk.services.rds.model.DbInstanceNotFoundException;
import software.amazon.awssdk.services.rds.model.RdsException;
import software.amazon.awssdk.services.rds.model.VpcSecurityGroupMembership;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import static io.restassured.RestAssured.given;
import static io.restassured.http.ContentType.URLENC;
@@ -73,6 +75,12 @@ public final class RdsRequests {
}
}
/** The ids of the VPC security groups {@code DescribeDBInstances} reports for DB instance {@code id}. */
public static List<String> vpcSecurityGroupIds(RdsClient client, String id) {
return client.describeDBInstances(request -> request.dbInstanceIdentifier(id)).dbInstances().getFirst()
.vpcSecurityGroups().stream().map(VpcSecurityGroupMembership::vpcSecurityGroupId).toList();
}
private static RdsClientBuilder rdsClientBuilder(String region, String account) {
return RdsClient.builder()
.endpointOverride(URI.create("http://localhost:" + RestAssured.port))