diff --git a/docs/services/rds.md b/docs/services/rds.md index dbdc92d1b2..315cfd8540 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -457,6 +457,32 @@ Not emulated: Data API requests to a paused cluster wait for the resume, as the describes, and never fail with `DatabaseResumingException`; logical or binlog replication does not keep a cluster awake; and parameter group changes do not resume one. +## VPC security groups + +`CreateDBInstance` and `ModifyDBInstance` check each id in `VpcSecurityGroupIds` against EC2 before +anything is stored or a container starts, and refuse the request the way RDS does: + +- An id that names no security group of the account and Region fails with `InvalidParameterValue` + (`Invalid security group , groupId= sg-..., groupName=.`). +- A group outside the VPC of the instance's DB subnet group fails with `InvalidParameterCombination` + (`The DB instance and EC2 security group are in different VPCs. ...`). + +A modify that also names a new `DBSubnetGroupName` checks the groups against that subnet group's VPC. +Snapshot and point-in-time restores, read replicas, the green instance of a Blue/Green deployment and +a CloudFormation update of `VPCSecurityGroups` are checked the same way. A request that names no groups +is not checked. + +A standalone instance whose request names no groups gets the default security group of its VPC, as +RDS documents for `CreateDBInstance` and `CreateDBInstanceReadReplica`. A same-Region read replica +otherwise takes its source's groups, but only in the source's VPC: in another VPC it gets that VPC's +default group. A modify that moves an instance to another VPC without naming groups puts it on the +new VPC's default group, since the old VPC's groups cannot go with it. A cluster member's groups are +its cluster's, which Floci does not keep, so it keeps none. `DescribeDBInstances` reports the VPC's +default group for an instance that keeps none, such as a cluster member or an instance stored before +these defaults, and `sg-00000000` only when its VPC is unknown. A CloudFormation update checks its groups against the VPC it leaves the instance in +before it changes anything, and a rollback leaves the groups of an instance the update moved to +another VPC, which it does not move back. + ## Modifying a DB instance `ModifyDBInstance` applies `DBInstanceClass` and `AllocatedStorage`, and diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/RdsCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/RdsCfnProvisioner.java index 51a03867df..f200341704 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/RdsCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/RdsCfnProvisioner.java @@ -438,17 +438,22 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { boolean created = instance == null; String caCertificate = resolveOptional(props, "CACertificateIdentifier", engine); DbInstanceInPlaceState stateBefore = created ? null : DbInstanceInPlaceState.of(instance); - // Worked out before anything changes, so that nothing can fail between the changes a - // rollback cannot undo and the groups, which it can. + String subnetGroupName = resolveOptional(props, "DBSubnetGroupName", engine); + // Worked out and checked against the VPC the update leaves the instance in before anything + // changes, so that nothing can fail between the changes a rollback cannot undo and the groups, + // which it can. List desiredGroups = created ? null - : desiredVpcSecurityGroups(vpcSecurityGroups, clusterMember, id, ctx); + : desiredVpcSecurityGroups(vpcSecurityGroups, clusterMember, id, subnetGroupName, ctx); + if (desiredGroups != null) { + rdsService.requireVpcSecurityGroupsFit(ctx.region(), id, subnetGroupName, desiredGroups); + } if (instance != null) { // A null region keeps the default-region lookup sameNameExistingResource made. instance = rdsService.modifyDbInstance( id, resolveDynamicReferences(resolveOptionalWithoutDynamicReferences(props, "MasterUserPassword", engine), region, true), parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine), - resolveOptional(props, "DBSubnetGroupName", engine), null, null, null, null, + subnetGroupName, null, null, null, null, DbInstanceSettings.unchanged().withCaCertificateIdentifier(caCertificate)); } else { instance = rdsService.createDbInstance( @@ -462,7 +467,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { parseIntProp(props, "AllocatedStorage", engine, 20), parseBoolProp(props, "EnableIAMDatabaseAuthentication", engine), resolveOptional(props, "DBParameterGroupName", engine), - resolveOptional(props, "DBSubnetGroupName", engine), + subnetGroupName, resolveOptional(props, "DBClusterIdentifier", engine), null, false, false, null, Map.of(), vpcSecurityGroups, null, region, true, new DbInstanceSettings(storageEncrypted, null, null, null, null, null) @@ -510,13 +515,14 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { * changes a member's list fails the update, as on AWS, where the handler sends the change to * ModifyDBInstance and RDS refuses it for a member. The change is read from the template, as * there, so a member a stack created before Floci applied the list still takes it. A list the - * previous template declared and this one drops puts a standalone instance on its VPC's default - * security group, as AWS's handler does, and leaves them when there is no such group, as there; a + * previous template declared and this one drops puts a standalone instance on the default security + * group of the VPC {@code subnetGroupName} leaves it in, as AWS's handler does, and leaves them + * when there is no such group, as there; a * cluster member keeps its groups, as there too. A list the stack never declared leaves groups set * outside it alone. */ private List desiredVpcSecurityGroups(List declared, String clusterMember, String id, - ProvisionContext ctx) { + String subnetGroupName, ProvisionContext ctx) { boolean member = clusterMember != null && !clusterMember.isBlank(); if (!declared.isEmpty()) { if (member && ctx.priorProperties() != null && !Set.copyOf(declared).equals( @@ -529,7 +535,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { if (!ctx.previouslyDeclared("VPCSecurityGroups") || member) { return null; } - List defaultGroup = rdsService.defaultVpcSecurityGroupIds(ctx.region(), id); + List defaultGroup = rdsService.defaultVpcSecurityGroupIds(ctx.region(), id, subnetGroupName); return defaultGroup.isEmpty() ? null : defaultGroup; } @@ -538,7 +544,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { * when an earlier step fails, the engine restores the resource without calling * {@link #rollbackUpdate}, so only a change made after every other one can be put back there. * What the instance had is saved first, with whether the update changed anything else, for - * {@link #rollbackUpdate}. + * {@link #rollbackUpdate}, except the groups of an instance the update moved to another VPC: a + * rollback does not move it back, and the old VPC's groups cannot go on it in the new one. */ private void reconcileInstanceSecurityGroups(StackResource r, DbInstance instance, List desired, DbInstanceInPlaceState stateBefore, ProvisionContext ctx) { @@ -546,7 +553,7 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { List groupsBefore = stateBefore.vpcSecurityGroups(); boolean groupsChange = desired != null && !Set.copyOf(desired).equals(Set.copyOf(groupsBefore)); ObjectNode saved = MAPPER.createObjectNode().put("region", ctx.region()); - if (groupsChange) { + if (groupsChange && Objects.equals(stateBefore.vpcId(), instance.getVpcId())) { ArrayNode priorGroups = saved.putArray("vpcSecurityGroups"); groupsBefore.forEach(priorGroups::add); } @@ -563,7 +570,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { * changes do not reach them. Only the groups have a rollback here. */ private record DbInstanceInPlaceState(String masterPassword, boolean iamAuthentication, String subnetGroup, - String caCertificate, Set roles, List vpcSecurityGroups) { + String vpcId, String caCertificate, Set roles, + List vpcSecurityGroups) { static DbInstanceInPlaceState of(DbInstance instance) { Set roles = new HashSet<>(); @@ -572,7 +580,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { } return new DbInstanceInPlaceState(instance.getMasterPassword(), instance.isIamDatabaseAuthenticationEnabled(), instance.getDbSubnetGroupName(), - instance.getCaCertificateIdentifier(), roles, List.copyOf(instance.getVpcSecurityGroupIds())); + instance.getVpcId(), instance.getCaCertificateIdentifier(), roles, + List.copyOf(instance.getVpcSecurityGroupIds())); } /** Whether {@code other} has the same settings and roles, whatever its groups. */ diff --git a/src/main/java/io/floci/aws/services/docdb/DocDbService.java b/src/main/java/io/floci/aws/services/docdb/DocDbService.java index a2b5565478..9280909292 100644 --- a/src/main/java/io/floci/aws/services/docdb/DocDbService.java +++ b/src/main/java/io/floci/aws/services/docdb/DocDbService.java @@ -18,6 +18,7 @@ import io.floci.aws.services.docdb.model.DocDbInstanceSettings; import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.kms.KmsService; import io.floci.aws.services.kms.model.KmsKey; +import io.floci.aws.services.rds.RdsSecurityGroups; import io.floci.aws.services.rds.RdsService; import io.floci.aws.services.rds.model.DbClusterParameterGroup; import jakarta.enterprise.context.ApplicationScoped; @@ -334,14 +335,7 @@ public class DocDbService { if (ec2Service == null) { throw new IllegalStateException("DocDbService was built without an Ec2Service"); } - for (String groupId : securityGroups) { - boolean known = ec2Service.describeSecurityGroups(region, List.of(groupId), List.of(), Map.of()) - .stream().anyMatch(sg -> groupId.equals(sg.getGroupId())); - if (!known) { - throw new AwsException("InvalidParameterValue", - "Invalid security group , groupId= " + groupId + ", groupName=.", 400); - } - } + RdsSecurityGroups.requireInVpc(ec2Service, region, securityGroups, null); } else if (create) { securityGroups = List.of(Ec2Service.defaultSecurityGroupId(region)); } diff --git a/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java b/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java index 27f5b9ded2..7436cb911a 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java @@ -3473,9 +3473,13 @@ public class RdsQueryHandler { } private String vpcSecurityGroupsXml(DbInstance i) { - List groupIds = i.getVpcSecurityGroupIds().isEmpty() - ? List.of("sg-00000000") - : i.getVpcSecurityGroupIds(); + List groupIds = i.getVpcSecurityGroupIds(); + if (groupIds.isEmpty()) { + groupIds = service.defaultVpcSecurityGroupIds(i); + } + if (groupIds.isEmpty()) { + groupIds = List.of("sg-00000000"); + } XmlBuilder xml = new XmlBuilder().start("VpcSecurityGroups"); for (String groupId : groupIds) { xml.start("VpcSecurityGroupMembership") diff --git a/src/main/java/io/floci/aws/services/rds/RdsSecurityGroups.java b/src/main/java/io/floci/aws/services/rds/RdsSecurityGroups.java new file mode 100644 index 0000000000..b18335cb5c --- /dev/null +++ b/src/main/java/io/floci/aws/services/rds/RdsSecurityGroups.java @@ -0,0 +1,70 @@ +package io.floci.aws.services.rds; + +import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.ec2.Ec2Service; +import io.floci.aws.services.ec2.model.SecurityGroup; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The checks the RDS API makes on the VPC security group ids a request names, shared with DocumentDB, + * which serves the same API: each id names a security group of the caller's account and Region, and + * every group sits in the resource's VPC. When a request names none, RDS puts a DB instance on its + * VPC's default security group. + */ +public final class RdsSecurityGroups { + + private RdsSecurityGroups() { + } + + /** + * Refuses {@code groupIds} unless each names a security group of {@code region} and, when + * {@code vpcId} is given, every one of them is in that VPC. A null or empty list names no groups + * and passes. + */ + public static void requireInVpc(Ec2Service ec2Service, String region, List groupIds, String vpcId) { + if (groupIds == null || groupIds.isEmpty()) { + return; + } + Map found = new LinkedHashMap<>(); + for (SecurityGroup group : ec2Service.describeSecurityGroups(region, groupIds, List.of(), Map.of())) { + found.put(group.getGroupId(), group); + } + List unknown = groupIds.stream().filter(id -> !found.containsKey(id)).distinct().toList(); + if (!unknown.isEmpty()) { + throw new AwsException("InvalidParameterValue", + "Invalid security group , groupId= " + String.join(", ", unknown) + ", groupName=.", 400); + } + if (vpcId == null) { + return; + } + for (String groupId : groupIds) { + String groupVpcId = found.get(groupId).getVpcId(); + if (!vpcId.equals(groupVpcId)) { + throw new AwsException("InvalidParameterCombination", + "The DB instance and EC2 security group are in different VPCs. The DB instance is in " + + vpcId + " and the EC2 security group is in " + groupVpcId, 400); + } + } + } + + /** {@code groupIds}, or when they name no group, the default security group of {@code vpcId}. */ + public static List orVpcDefault(Ec2Service ec2Service, String region, List groupIds, + String vpcId) { + return groupIds == null || groupIds.isEmpty() ? vpcDefault(ec2Service, region, vpcId) : groupIds; + } + + /** + * The default security group of {@code vpcId}, or no group when there is no VPC or EC2 has no + * default group for it. + */ + public static List vpcDefault(Ec2Service ec2Service, String region, String vpcId) { + if (vpcId == null || vpcId.isBlank()) { + return List.of(); + } + return ec2Service.defaultSecurityGroupOf(region, vpcId).map(group -> List.of(group.getGroupId())) + .orElse(List.of()); + } +} diff --git a/src/main/java/io/floci/aws/services/rds/RdsService.java b/src/main/java/io/floci/aws/services/rds/RdsService.java index 90f6aff595..cf05914a21 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsService.java +++ b/src/main/java/io/floci/aws/services/rds/RdsService.java @@ -856,6 +856,18 @@ public class RdsService implements Resettable, ResourceProvider { } } } + List instanceSecurityGroupIds; + try { + RdsSecurityGroups.requireInVpc(ec2Service, effectiveRegion, vpcSecurityGroupIds, placement.vpcId()); + // A cluster member's groups are its cluster's. + instanceSecurityGroupIds = isBlank(dbClusterIdentifier) + ? RdsSecurityGroups.orVpcDefault(ec2Service, effectiveRegion, vpcSecurityGroupIds, + placement.vpcId()) + : vpcSecurityGroupIds; + } catch (RuntimeException | Error failure) { + releaseProxyPort(proxyPort); + throw failure; + } DbEndpoint endpoint; DbInstance instance; @@ -873,7 +885,7 @@ public class RdsService implements Resettable, ResourceProvider { instance.setDockerVolumeName(instanceDockerVolumeName); instance.setContainerStorageResourceId(instanceStorageResourceId); instance.setTags(tags); - instance.setVpcSecurityGroupIds(vpcSecurityGroupIds); + instance.setVpcSecurityGroupIds(instanceSecurityGroupIds); instance.setDbSubnetGroupName(placement.dbSubnetGroupName()); instance.setVpcId(placement.vpcId()); instance.setAvailabilityZone(placement.availabilityZone()); @@ -2210,9 +2222,13 @@ public class RdsService implements Resettable, ResourceProvider { request.optionGroupName(), sameRegion ? source.getOptionGroupName() : null); String dbSubnetGroupName = firstNonBlank( request.dbSubnetGroupName(), sameRegion ? source.getDbSubnetGroupName() : null); + // The source's groups belong to its VPC, so a replica placed in another one gets that VPC's + // default group instead. + boolean inSourceVpc = sameRegion && (isBlank(request.dbSubnetGroupName()) || Objects.equals( + getDbSubnetGroup(request.dbSubnetGroupName(), effectiveRegion).getVpcId(), source.getVpcId())); List vpcSecurityGroupIds = request.vpcSecurityGroupIds() != null ? request.vpcSecurityGroupIds() - : sameRegion ? source.getVpcSecurityGroupIds() : List.of(); + : inSourceVpc ? source.getVpcSecurityGroupIds() : List.of(); boolean autoMinorVersionUpgrade = request.autoMinorVersionUpgrade() != null ? request.autoMinorVersionUpgrade() : source.isAutoMinorVersionUpgrade(); // Backups stay off on a replica; the source's windows carry over, and encryption follows @@ -3912,6 +3928,16 @@ public class RdsService implements Resettable, ResourceProvider { validateInstanceParameterGroup(dbParameterGroupName, engineName(instance), instance.getEngineVersion(), effectiveRegion); } + // A new subnet group can move the instance to another VPC, so the groups are checked against that VPC. + DbSubnetGroup newSubnetGroup = isBlank(dbSubnetGroupName) + ? null : getDbSubnetGroup(dbSubnetGroupName, effectiveRegion); + String vpcIdAfter = newSubnetGroup != null ? newSubnetGroup.getVpcId() : instance.getVpcId(); + RdsSecurityGroups.requireInVpc(ec2Service, effectiveRegion, vpcSecurityGroupIds, vpcIdAfter); + // The old VPC's groups cannot follow the instance to another one, so it gets the groups the request + // names or that VPC's default group. Null keeps the groups it has. + List securityGroupIdsAfter = !Objects.equals(vpcIdAfter, instance.getVpcId()) + ? RdsSecurityGroups.orVpcDefault(ec2Service, effectiveRegion, vpcSecurityGroupIds, vpcIdAfter) + : vpcSecurityGroupIds == null || vpcSecurityGroupIds.isEmpty() ? null : vpcSecurityGroupIds; instance.setStatus(DbInstanceStatus.AVAILABLE); if (changesParameterGroup) { instance.setParameterGroupName(dbParameterGroupName); @@ -3947,12 +3973,12 @@ public class RdsService implements Resettable, ResourceProvider { if (iamEnabled != null) { instance.setIamDatabaseAuthenticationEnabled(iamEnabled); } - if (dbSubnetGroupName != null && !dbSubnetGroupName.isBlank()) { - getDbSubnetGroup(dbSubnetGroupName, effectiveRegion); + if (newSubnetGroup != null) { instance.setDbSubnetGroupName(dbSubnetGroupName); + instance.setVpcId(newSubnetGroup.getVpcId()); } - if (vpcSecurityGroupIds != null && !vpcSecurityGroupIds.isEmpty()) { - instance.setVpcSecurityGroupIds(vpcSecurityGroupIds); + if (securityGroupIdsAfter != null) { + instance.setVpcSecurityGroupIds(securityGroupIdsAfter); } if (autoMinorVersionUpgrade != null) { instance.setAutoMinorVersionUpgrade(autoMinorVersionUpgrade); @@ -4068,6 +4094,7 @@ public class RdsService implements Resettable, ResourceProvider { String effectiveRegion = effectiveRegion(region); DbInstance instance = getDbInstance(instanceId, effectiveRegion); requireAvailableInstance(instance, instanceId); + RdsSecurityGroups.requireInVpc(ec2Service, effectiveRegion, groupIds, instance.getVpcId()); instance.setVpcSecurityGroupIds(groupIds); putInstanceForScope(currentAccountId(), effectiveRegion, instanceId, instance); LOG.infov("DB instance {0} security groups set to {1}", instanceId, groupIds); @@ -4075,19 +4102,50 @@ public class RdsService implements Resettable, ResourceProvider { } /** - * The groups AWS's CloudFormation handler gives a standalone DB instance whose template stops - * declaring {@code VPCSecurityGroups}: the default security group of its VPC, or none when EC2 - * has no default group for it. + * The default security group of {@code instance}'s VPC, which describe reports for an instance that + * keeps no groups: an Aurora member, whose groups are its cluster's, or one stored before RDS gave + * one. No group when its VPC is unknown or gone. */ - public List defaultVpcSecurityGroupIds(String region, String instanceId) { - String effectiveRegion = effectiveRegion(region); - String vpcId = getDbInstance(instanceId, effectiveRegion).getVpcId(); - if (isBlank(vpcId)) { + public List defaultVpcSecurityGroupIds(DbInstance instance) { + try { + return RdsSecurityGroups.vpcDefault(ec2Service, regionFromArn(instance.getDbInstanceArn()), + instance.getVpcId()); + } catch (AwsException e) { + LOG.debugv("No default security group to report for DB instance {0} in {1}: {2}", + instance.getDbInstanceIdentifier(), instance.getVpcId(), e.getMessage()); return List.of(); } - return ec2Service.defaultSecurityGroupOf(effectiveRegion, vpcId) - .map(group -> List.of(group.getGroupId())) - .orElse(List.of()); + } + + /** + * The groups AWS's CloudFormation handler gives a standalone DB instance whose template stops + * declaring {@code VPCSecurityGroups}: the default security group of the VPC it is in once + * {@code dbSubnetGroupName}, when given, is its subnet group, or none when EC2 has no default group + * for it. + */ + public List defaultVpcSecurityGroupIds(String region, String instanceId, String dbSubnetGroupName) { + String effectiveRegion = effectiveRegion(region); + return RdsSecurityGroups.vpcDefault(ec2Service, effectiveRegion, + vpcIdAfter(instanceId, dbSubnetGroupName, effectiveRegion)); + } + + /** + * Refuses {@code groupIds} as {@code ModifyDBInstance} would for instance {@code instanceId} given + * {@code dbSubnetGroupName}, for CloudFormation, which changes the subnet group and the groups in + * separate steps and so checks the groups before the first one. + */ + public void requireVpcSecurityGroupsFit(String region, String instanceId, String dbSubnetGroupName, + List groupIds) { + String effectiveRegion = effectiveRegion(region); + RdsSecurityGroups.requireInVpc(ec2Service, effectiveRegion, groupIds, + vpcIdAfter(instanceId, dbSubnetGroupName, effectiveRegion)); + } + + /** The VPC instance {@code instanceId} is in once {@code dbSubnetGroupName}, when given, is its subnet group. */ + private String vpcIdAfter(String instanceId, String dbSubnetGroupName, String effectiveRegion) { + return isBlank(dbSubnetGroupName) + ? getDbInstance(instanceId, effectiveRegion).getVpcId() + : getDbSubnetGroup(dbSubnetGroupName, effectiveRegion).getVpcId(); } private static void validateInstanceSettings(DbInstanceSettings settings) { @@ -7744,10 +7802,8 @@ public class RdsService implements Resettable, ResourceProvider { endpoint.setStatus("available"); endpoint.setVpcId(vpcId); endpoint.setVpcSubnetIds(vpcSubnetIds); - endpoint.setVpcSecurityGroupIds(vpcSecurityGroupIds == null || vpcSecurityGroupIds.isEmpty() - ? ec2Service.defaultSecurityGroupOf(effectiveRegion, vpcId).map(sg -> List.of(sg.getGroupId())) - .orElse(List.of()) - : vpcSecurityGroupIds); + endpoint.setVpcSecurityGroupIds( + RdsSecurityGroups.orVpcDefault(ec2Service, effectiveRegion, vpcSecurityGroupIds, vpcId)); endpoint.setCreatedDate(Instant.now()); endpoint.setTargetRole(role); endpoint.setEndpointNetworkType(networkType); diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsDbInstanceIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsDbInstanceIntegrationTest.java index c08eaf100f..a2cefd326c 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsDbInstanceIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsDbInstanceIntegrationTest.java @@ -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 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 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(); - } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/RdsCfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/RdsCfnProvisionerTest.java index 408834cb4e..1f3a630f51 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/RdsCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/RdsCfnProvisionerTest.java @@ -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 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()); diff --git a/src/test/java/io/floci/aws/services/docdb/DocDbServiceTest.java b/src/test/java/io/floci/aws/services/docdb/DocDbServiceTest.java index 4a66741e3c..b8ed55d2f9 100644 --- a/src/test/java/io/floci/aws/services/docdb/DocDbServiceTest.java +++ b/src/test/java/io/floci/aws/services/docdb/DocDbServiceTest.java @@ -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"); diff --git a/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java b/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java index cc0b519268..191f6c7173 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java @@ -458,6 +458,23 @@ class RdsQueryHandlerTest { assertTrue(body.contains("true"), 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("sg-own"), body); + assertTrue(body.contains("sg-vpc-default"), body); + assertTrue(body.contains("sg-00000000"), body); + verify(service, never()).defaultVpcSecurityGroupIds(own); + } + @Test void describeDbInstances_reportsIncompatibleParametersWhenTheDatabaseRefusedItsGroup() { DbInstance refused = makeInstance("refused"); diff --git a/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java b/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java index 9e0e8f6409..49c8380699 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java @@ -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 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.>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 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 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")); diff --git a/src/test/java/io/floci/aws/services/rds/RdsVpcSecurityGroupsIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsVpcSecurityGroupsIntegrationTest.java new file mode 100644 index 0000000000..6c3a7ac133 --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/RdsVpcSecurityGroupsIntegrationTest.java @@ -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 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 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 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); + } + }); + } +} diff --git a/src/test/java/io/floci/aws/testing/Ec2Requests.java b/src/test/java/io/floci/aws/testing/Ec2Requests.java index a158936ac6..64562e13d4 100644 --- a/src/test/java/io/floci/aws/testing/Ec2Requests.java +++ b/src/test/java/io/floci/aws/testing/Ec2Requests.java @@ -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") diff --git a/src/test/java/io/floci/aws/testing/Ec2ServiceFixtures.java b/src/test/java/io/floci/aws/testing/Ec2ServiceFixtures.java index 5108cbd0e2..18d6f2af09 100644 --- a/src/test/java/io/floci/aws/testing/Ec2ServiceFixtures.java +++ b/src/test/java/io/floci/aws/testing/Ec2ServiceFixtures.java @@ -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; + } } diff --git a/src/test/java/io/floci/aws/testing/RdsRequests.java b/src/test/java/io/floci/aws/testing/RdsRequests.java index d6c1fe582a..a36fd452a1 100644 --- a/src/test/java/io/floci/aws/testing/RdsRequests.java +++ b/src/test/java/io/floci/aws/testing/RdsRequests.java @@ -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 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))