diff --git a/docs/services/rds.md b/docs/services/rds.md index 154810de58..e5a88524ed 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -200,6 +200,19 @@ A CloudFormation update that drops `VpcSecurityGroupIds` the previous template d cluster back on its VPC's default security group, as AWS does; groups the stack never declared are left alone, and `DeletionProtection` and the two windows keep their stored values. +`CreateDBCluster` and `ModifyDBCluster` check each id in `VpcSecurityGroupIds` against EC2 the way +they are checked for a DB instance (see [VPC security groups](#vpc-security-groups)): a group that does +not exist is `InvalidParameterValue`, one outside the cluster's VPC is `InvalidParameterCombination`. +They also store `MonitoringInterval`, `MonitoringRoleArn`, `EnablePerformanceInsights`, +`PerformanceInsightsRetentionPeriod` and `DatabaseInsightsMode`, and `DescribeDBClusters` returns +them. A cluster that names none of them has no monitoring and Database Insights `standard`. The +interval is one of 0, 1, 5, 10, 15, 30 or 60 and needs a `MonitoringRoleArn` when it is not 0, the +retention period is 7, 731 or a multiple of 31 up to 713 (7 when Performance Insights is turned on +without one), and `advanced` Database Insights needs Performance Insights with a retention period of +at least 465 days. A refused create leaves no cluster behind, and a refused modify stores none of its +changes. Floci collects no Enhanced Monitoring or Performance Insights data. +`DescribeDBClusterAutomatedBackups` reports the backup window of the cluster a backup was taken from. + !!! note "Stopping and starting" `StopDBInstance` and `StopDBCluster` follow the user guide: the response reports `stopping` @@ -538,9 +551,9 @@ RDS documents for `CreateDBInstance` and `CreateDBInstanceReadReplica`. A same-R 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 +its cluster's, so it keeps none and `DescribeDBInstances` reports its cluster's groups. It reports the +VPC's default group for an instance that keeps none otherwise, such as a member of a cluster that has +no groups 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. 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 5c06d4b27c..a7a6a476ec 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java @@ -21,6 +21,7 @@ import io.floci.aws.services.rds.model.DatabaseEngine; import io.floci.aws.services.rds.model.DbCluster; import io.floci.aws.services.rds.model.DbClusterAutomatedBackup; import io.floci.aws.services.rds.model.DbClusterEndpoint; +import io.floci.aws.services.rds.model.DbClusterMonitoringSettings; import io.floci.aws.services.rds.model.DbClusterParameterGroup; import io.floci.aws.services.rds.model.DbClusterSnapshot; import io.floci.aws.services.rds.model.DbEndpoint; @@ -1469,6 +1470,8 @@ public class RdsQueryHandler { // parsed before any mutating call so a malformed value leaves no cluster behind List securityGroupIds = hasMemberKeys(params, "VpcSecurityGroupIds") ? vpcSecurityGroupIds(params) : null; + DbClusterMonitoringSettings monitoring = clusterMonitoringSettings(params); + monitoring.validate(); DbCluster cluster; if (globalClusterIdentifier != null && !globalClusterIdentifier.isBlank()) { cluster = service.createDbClusterInGlobalCluster(globalClusterIdentifier, id, engine, @@ -1495,16 +1498,20 @@ public class RdsQueryHandler { } else if (!tags.isEmpty()) { cluster = service.getDbCluster(id, region); } - if (!associatedRoles.isEmpty()) { - try { + // Checks that need the stored cluster; a refusal deletes the cluster this request created. + try { + // the groups are checked against the VPC the new cluster was placed in + service.requireClusterSecurityGroups(region, id, securityGroupIds); + service.setClusterMonitoringSettings(region, id, monitoring, true); + if (!associatedRoles.isEmpty()) { cluster = service.addRolesToNewDbCluster(region, id, associatedRoles); - } catch (AwsException e) { - if (protectedCluster) { - service.setDeletionProtection(region, id, false); - } - service.deleteDbCluster(id, region); - throw e; } + } catch (AwsException e) { + if (protectedCluster) { + service.setDeletionProtection(region, id, false); + } + service.deleteDbCluster(id, region); + throw e; } if (enableHttpEndpoint) { cluster = service.setHttpEndpoint(region, id, true); @@ -1523,6 +1530,16 @@ public class RdsQueryHandler { } } + /** The Enhanced Monitoring, Performance Insights and Database Insights members of a Create/ModifyDBCluster. */ + private static DbClusterMonitoringSettings clusterMonitoringSettings(MultivaluedMap params) { + return new DbClusterMonitoringSettings( + parseIntegerParam(params, "MonitoringInterval"), + params.getFirst("MonitoringRoleArn"), + parseOptionalBoolean(params, "EnablePerformanceInsights"), + parseIntegerParam(params, "PerformanceInsightsRetentionPeriod"), + params.getFirst("DatabaseInsightsMode")); + } + private static Double parseDoubleParam(MultivaluedMap params, String name) { String value = params.getFirst(name); if (value == null || value.isBlank()) { @@ -1652,6 +1669,11 @@ public class RdsQueryHandler { // parsed before any mutating call so a malformed value changes nothing List securityGroupIds = hasMemberKeys(params, "VpcSecurityGroupIds") ? vpcSecurityGroupIds(params) : null; + service.requireClusterSecurityGroups(region, id, securityGroupIds); + DbClusterMonitoringSettings monitoring = clusterMonitoringSettings(params); + if (!monitoring.isEmpty()) { + service.validateClusterMonitoringSettings(region, id, monitoring); + } DbCluster cluster = service.modifyDbCluster(id, newPassword, iamEnabled, serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause, manageMasterUserPassword, masterUserSecretKmsKeyId, @@ -1669,6 +1691,9 @@ public class RdsQueryHandler { } cluster = service.setDbClusterRequestSettings(id, region, securityGroupIds, params.getFirst("PreferredBackupWindow"), params.getFirst("PreferredMaintenanceWindow")); + if (!monitoring.isEmpty()) { + cluster = service.setClusterMonitoringSettings(region, id, monitoring, false); + } if (deletionProtection != null) { cluster = service.setDeletionProtection(region, id, deletionProtection); } @@ -3314,7 +3339,8 @@ public class RdsQueryHandler { .elem("EngineVersion", c.getEngineVersion()) .elem("DBClusterArn", c.getDbClusterArn()) .elem("BackupRetentionPeriod", backup.getBackupRetentionPeriod()) - .elem("PreferredBackupWindow", "04:00-06:00") + .elem("PreferredBackupWindow", c.getPreferredBackupWindow() != null + ? c.getPreferredBackupWindow() : BackupWindows.DEFAULT_BACKUP_WINDOW) .elem("EngineMode", c.getEngineMode() != null ? c.getEngineMode() : "provisioned"); if (c.getEndpoint() != null) { xml.elem("Port", c.getEndpoint().port()); @@ -3752,7 +3778,18 @@ public class RdsQueryHandler { .elem("PreferredBackupWindow", c.getPreferredBackupWindow() != null ? c.getPreferredBackupWindow() : BackupWindows.DEFAULT_BACKUP_WINDOW) .raw(vpcSecurityGroupsXml(c.getVpcSecurityGroupIds())) - .elem("DBSubnetGroup", c.getDbSubnetGroupName() != null ? c.getDbSubnetGroupName() : "default"); + .elem("MonitoringInterval", c.getMonitoringInterval()); + if (c.getMonitoringRoleArn() != null && !c.getMonitoringRoleArn().isBlank()) { + xml.elem("MonitoringRoleArn", c.getMonitoringRoleArn()); + } + xml.elem("PerformanceInsightsEnabled", c.isPerformanceInsightsEnabled()); + if (c.isPerformanceInsightsEnabled() && c.getPerformanceInsightsRetentionPeriod() != null) { + xml.elem("PerformanceInsightsRetentionPeriod", c.getPerformanceInsightsRetentionPeriod()); + } + if (c.getDatabaseInsightsMode() != null) { + xml.elem("DatabaseInsightsMode", c.getDatabaseInsightsMode()); + } + xml.elem("DBSubnetGroup", c.getDbSubnetGroupName() != null ? c.getDbSubnetGroupName() : "default"); String clusterParameterGroup = dbClusterParameterGroupName(c, engineStr); if (clusterParameterGroup != null) { xml.elem("DBClusterParameterGroup", clusterParameterGroup); 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 677180d522..d269053b12 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsService.java +++ b/src/main/java/io/floci/aws/services/rds/RdsService.java @@ -40,6 +40,7 @@ import io.floci.aws.services.rds.model.DatabaseEngine; import io.floci.aws.services.rds.model.DbCluster; import io.floci.aws.services.rds.model.DbClusterAutomatedBackup; import io.floci.aws.services.rds.model.DbClusterEndpoint; +import io.floci.aws.services.rds.model.DbClusterMonitoringSettings; import io.floci.aws.services.rds.model.DbClusterParameterGroup; import io.floci.aws.services.rds.model.DbClusterSnapshot; import io.floci.aws.services.rds.model.DbEndpoint; @@ -4342,11 +4343,18 @@ public class RdsService implements Resettable, ResourceProvider { } /** - * 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. + * The groups describe reports for an instance that keeps none: an Aurora member reports its + * cluster's groups, and otherwise, or for one stored before RDS gave one, the default security + * group of its VPC. No group when its VPC is unknown or gone. */ public List defaultVpcSecurityGroupIds(DbInstance instance) { + if (!isBlank(instance.getDbClusterIdentifier())) { + DbCluster cluster = findClusterForScope(accountIdFromArn(instance.getDbInstanceArn()), + regionResolver.regionOf(instance.getDbInstanceArn()), instance.getDbClusterIdentifier()); + if (cluster != null && !cluster.getVpcSecurityGroupIds().isEmpty()) { + return List.copyOf(cluster.getVpcSecurityGroupIds()); + } + } try { return RdsSecurityGroups.vpcDefault(ec2Service, regionResolver.regionOf(instance.getDbInstanceArn()), instance.getVpcId()); @@ -12055,6 +12063,85 @@ public class RdsService implements Resettable, ResourceProvider { return member == null ? 1 : member.getPromotionTier(); } + /** + * Refuses {@code vpcSecurityGroupIds} unless each names a security group of the cluster's Region in + * the cluster's VPC, as CreateDBCluster and ModifyDBCluster do. A null or empty list passes. + */ + public void requireClusterSecurityGroups(String region, String clusterId, List vpcSecurityGroupIds) { + if (vpcSecurityGroupIds == null || vpcSecurityGroupIds.isEmpty()) { + return; + } + String effectiveRegion = effectiveRegion(region); + RdsSecurityGroups.requireInVpc(ec2Service, effectiveRegion, vpcSecurityGroupIds, + getDbCluster(clusterId, effectiveRegion).getVpcId()); + } + + /** + * Applies the Enhanced Monitoring, Performance Insights and Database Insights members of a + * CreateDBCluster ({@code create} true) or ModifyDBCluster request. On create a member left out + * takes the AWS default (no monitoring, Database Insights {@code standard}); on modify it keeps + * the cluster's value. The monitoring pair and the Database Insights mode are judged on the + * values in effect after the request. + */ + public synchronized DbCluster setClusterMonitoringSettings(String region, String clusterId, + DbClusterMonitoringSettings settings, boolean create) { + String effectiveRegion = effectiveRegion(region); + DbCluster cluster = getDbCluster(clusterId, effectiveRegion); + applyClusterMonitoringSettings(cluster, settings, create); + putClusterForScope(currentAccountId(), effectiveRegion, cluster.getDbClusterIdentifier(), cluster); + return RESPONSE_COPIER.convertValue(cluster, DbCluster.class); + } + + /** + * Runs the checks of {@link #setClusterMonitoringSettings} against the cluster as it stands, storing + * nothing, so a ModifyDBCluster can refuse the request before any of its other changes is stored. + */ + public synchronized void validateClusterMonitoringSettings(String region, String clusterId, + DbClusterMonitoringSettings settings) { + DbCluster copy = RESPONSE_COPIER.convertValue(getDbCluster(clusterId, effectiveRegion(region)), + DbCluster.class); + applyClusterMonitoringSettings(copy, settings, false); + } + + private static void applyClusterMonitoringSettings(DbCluster cluster, DbClusterMonitoringSettings settings, + boolean create) { + settings.validate(); + int interval = settings.monitoringInterval() != null + ? settings.monitoringInterval() : cluster.getMonitoringInterval(); + String role = settings.monitoringRoleArn() != null + ? settings.monitoringRoleArn() : cluster.getMonitoringRoleArn(); + if (create) { + DbInstanceSettings.validateMonitoringPairOnCreate(interval, role); + } else if (interval != 0 && (role == null || role.isBlank())) { + throw new AwsException("InvalidParameterCombination", + "A MonitoringRoleArn value is required if you specify a MonitoringInterval value " + + "other than 0.", 400); + } + boolean insightsEnabled = settings.performanceInsightsEnabled() != null + ? settings.performanceInsightsEnabled() : cluster.isPerformanceInsightsEnabled(); + Integer retention = settings.performanceInsightsRetentionPeriod() != null + ? settings.performanceInsightsRetentionPeriod() : cluster.getPerformanceInsightsRetentionPeriod(); + if (insightsEnabled && retention == null) { + retention = 7; + } + String mode = settings.databaseInsightsMode() != null + ? settings.databaseInsightsMode() : cluster.getDatabaseInsightsMode(); + if (create && mode == null) { + mode = DbClusterMonitoringSettings.DATABASE_INSIGHTS_STANDARD; + } + if (DbClusterMonitoringSettings.DATABASE_INSIGHTS_ADVANCED.equals(mode) + && (!insightsEnabled || retention < 465)) { + throw new AwsException("InvalidParameterCombination", + "Database Insights advanced mode requires Performance Insights to be enabled " + + "with a retention period of at least 465 days.", 400); + } + cluster.setMonitoringInterval(interval); + cluster.setMonitoringRoleArn(role); + cluster.setPerformanceInsightsEnabled(insightsEnabled); + cluster.setPerformanceInsightsRetentionPeriod(insightsEnabled ? retention : null); + cluster.setDatabaseInsightsMode(mode); + } + /** Stores what a Create/ModifyDBCluster request carries; a null argument leaves that field as it is. */ public synchronized DbCluster setDbClusterRequestSettings(String id, String region, List vpcSecurityGroupIds, String backupWindow, String maintenanceWindow) { diff --git a/src/main/java/io/floci/aws/services/rds/model/DbCluster.java b/src/main/java/io/floci/aws/services/rds/model/DbCluster.java index 2ef52047d1..1767b51249 100644 --- a/src/main/java/io/floci/aws/services/rds/model/DbCluster.java +++ b/src/main/java/io/floci/aws/services/rds/model/DbCluster.java @@ -36,6 +36,13 @@ public class DbCluster { // Null until a request names them; the emitted XML then falls back to the defaults. private String preferredBackupWindow; private String preferredMaintenanceWindow; + /** MonitoringInterval documents 0 as its default. */ + private int monitoringInterval; + private String monitoringRoleArn; + private boolean performanceInsightsEnabled; + private Integer performanceInsightsRetentionPeriod; + // Null on a cluster stored before it was kept; the response then leaves it out. + private String databaseInsightsMode; private String availabilityZone; private boolean multiAz; private Map subnetAvailabilityZones = new LinkedHashMap<>(); @@ -283,4 +290,22 @@ public class DbCluster { enabledCloudwatchLogsExports = value == null ? new ArrayList<>() : new ArrayList<>(value); } + public int getMonitoringInterval() { return monitoringInterval; } + public void setMonitoringInterval(int monitoringInterval) { this.monitoringInterval = monitoringInterval; } + + public String getMonitoringRoleArn() { return monitoringRoleArn; } + public void setMonitoringRoleArn(String monitoringRoleArn) { this.monitoringRoleArn = monitoringRoleArn; } + + public boolean isPerformanceInsightsEnabled() { return performanceInsightsEnabled; } + public void setPerformanceInsightsEnabled(boolean performanceInsightsEnabled) { + this.performanceInsightsEnabled = performanceInsightsEnabled; + } + + public Integer getPerformanceInsightsRetentionPeriod() { return performanceInsightsRetentionPeriod; } + public void setPerformanceInsightsRetentionPeriod(Integer performanceInsightsRetentionPeriod) { + this.performanceInsightsRetentionPeriod = performanceInsightsRetentionPeriod; + } + + public String getDatabaseInsightsMode() { return databaseInsightsMode; } + public void setDatabaseInsightsMode(String databaseInsightsMode) { this.databaseInsightsMode = databaseInsightsMode; } } diff --git a/src/main/java/io/floci/aws/services/rds/model/DbClusterMonitoringSettings.java b/src/main/java/io/floci/aws/services/rds/model/DbClusterMonitoringSettings.java new file mode 100644 index 0000000000..942b4a55f8 --- /dev/null +++ b/src/main/java/io/floci/aws/services/rds/model/DbClusterMonitoringSettings.java @@ -0,0 +1,42 @@ +package io.floci.aws.services.rds.model; + +import io.floci.aws.core.common.AwsException; +import io.quarkus.runtime.annotations.RegisterForReflection; + +/** + * The Enhanced Monitoring, Performance Insights and Database Insights members of a CreateDBCluster + * or ModifyDBCluster request. A null member is one the request left out: on create that means the + * AWS default, on modify it means unchanged. + */ +@RegisterForReflection +public record DbClusterMonitoringSettings(Integer monitoringInterval, + String monitoringRoleArn, + Boolean performanceInsightsEnabled, + Integer performanceInsightsRetentionPeriod, + String databaseInsightsMode) { + + public static final String DATABASE_INSIGHTS_STANDARD = "standard"; + public static final String DATABASE_INSIGHTS_ADVANCED = "advanced"; + + public boolean isEmpty() { + return monitoringInterval == null && monitoringRoleArn == null && performanceInsightsEnabled == null + && performanceInsightsRetentionPeriod == null && databaseInsightsMode == null; + } + + /** + * The checks the members get on their own, before any is applied: the monitoring interval and + * the Performance Insights retention period as on a DB instance, and the Database Insights mode. + */ + public void validate() { + new DbInstanceSettings(null, null, null, null, null, null, monitoringInterval, monitoringRoleArn, + performanceInsightsEnabled, performanceInsightsRetentionPeriod, null, null, null, null).validate(); + if (databaseInsightsMode != null + && !DATABASE_INSIGHTS_STANDARD.equals(databaseInsightsMode) + && !DATABASE_INSIGHTS_ADVANCED.equals(databaseInsightsMode)) { + throw new AwsException("InvalidParameterValue", + "Invalid database insights mode: " + databaseInsightsMode + + ". Valid values are " + DATABASE_INSIGHTS_STANDARD + ", " + + DATABASE_INSIGHTS_ADVANCED + ".", 400); + } + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsAssociatedRolesIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsAssociatedRolesIntegrationTest.java index 2a6a2ed874..47d0492530 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsAssociatedRolesIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsAssociatedRolesIntegrationTest.java @@ -12,6 +12,8 @@ import org.junit.jupiter.params.provider.ValueSource; import java.util.List; +import static io.floci.aws.testing.Ec2Requests.createDefaultVpcSecurityGroup; +import static io.floci.aws.testing.Ec2Requests.ec2; import static io.floci.aws.testing.RdsRequests.auroraClusterWithMember; import static io.restassured.RestAssured.given; import static org.hamcrest.MatcherAssert.assertThat; @@ -304,6 +306,8 @@ class CloudFormationRdsAssociatedRolesIntegrationTest { String suffix = Long.toString(System.nanoTime(), 36); String stackName = "cfn-rds-sg-out-" + suffix; String clusterId = "cfn-sg-out-" + suffix; + // ModifyDBCluster refuses a group EC2 does not know; the cluster is in the default VPC + String outside = createDefaultVpcSecurityGroup("test", "us-east-1", "cfn-sg-outside-" + suffix); String cluster = """ {"Resources": {"Cluster": {"Type": "AWS::RDS::DBCluster", "Properties": { "DBClusterIdentifier": "%s", "Engine": "aurora-postgresql", @@ -315,12 +319,12 @@ class CloudFormationRdsAssociatedRolesIntegrationTest { + " \"PreferredMaintenanceWindow\": \"mon:05:00-mon:06:00\"")); assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); rds("ModifyDBCluster").formParam("DBClusterIdentifier", clusterId) - .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.1", "sg-outside") + .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.1", outside) .when().post("/").then().statusCode(200); stack("UpdateStack", stackName, cluster.formatted(clusterId, "password456", "")); assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); - assertEquals(List.of("sg-outside"), clusterGroups(clusterId)); + assertEquals(List.of(outside), clusterGroups(clusterId)); XmlPath xml = rds("DescribeDBClusters").formParam("DBClusterIdentifier", clusterId) .when().post("/").then().statusCode(200).extract().xmlPath(); assertEquals("true", xml.getString("**.find { it.name() == 'DeletionProtection' }")); @@ -332,6 +336,7 @@ class CloudFormationRdsAssociatedRolesIntegrationTest { .formParam("DeletionProtection", "false").when().post("/"); stack("DeleteStack", stackName, null); CfnStackWaits.awaitStackDeleted(stackName); + ec2("DeleteSecurityGroup", "test", "us-east-1").formParam("GroupId", outside).when().post("/"); } } diff --git a/src/test/java/io/floci/aws/services/rds/RdsClusterSettingsIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsClusterSettingsIntegrationTest.java new file mode 100644 index 0000000000..e817f1ebb4 --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/RdsClusterSettingsIntegrationTest.java @@ -0,0 +1,192 @@ +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.AfterEach; +import org.junit.jupiter.api.Test; +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.DBCluster; +import software.amazon.awssdk.services.rds.model.DbClusterNotFoundException; +import software.amazon.awssdk.services.rds.model.DbInstanceNotFoundException; +import software.amazon.awssdk.services.rds.model.VpcSecurityGroupMembership; + +import java.util.List; + +import static io.floci.aws.testing.AwsSdkErrors.assertAwsError; +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.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The Enhanced Monitoring, Performance Insights and Database Insights settings of a DB cluster + * round-trip from CreateDBCluster and ModifyDBCluster to DescribeDBClusters; the cluster's VPC + * security groups must exist in its VPC; an Aurora member reports its cluster's groups; and a + * retained automated backup reports its cluster's backup window. Before, the monitoring members were + * dropped, so the Terraform AWS provider planned the same change on every run. + */ +@QuarkusTest +@TestProfile(RdsMockProfile.class) +class RdsClusterSettingsIntegrationTest { + + private static final String ACCOUNT = "135792468024"; + private static final String CLUSTER = "settings-cluster"; + private static final String DEFAULTS = "settings-defaults"; + private static final String REFUSED = "settings-refused"; + private static final String MEMBER = "settings-member"; + private static final String ROLE = "arn:aws:iam::" + ACCOUNT + ":role/rds-monitoring"; + + /** Frees the proxy ports the clusters hold, which later tests in the same run count on. */ + @AfterEach + void cleanUp() { + try (RdsClient rds = rdsClient("us-east-1", ACCOUNT)) { + try { + rds.deleteDBInstance(request -> request.dbInstanceIdentifier(MEMBER).skipFinalSnapshot(true)); + } catch (DbInstanceNotFoundException ignored) { + // the test failed before it created the member, or already deleted it + } + for (String id : List.of(CLUSTER, DEFAULTS, REFUSED)) { + try { + rds.deleteDBCluster(request -> request.dbClusterIdentifier(id).skipFinalSnapshot(true)); + } catch (DbClusterNotFoundException ignored) { + // never created, refused, or already deleted by the test + } + } + } + } + + @Test + void clusterSettingsRoundTripThroughCreateAndModify() { + 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.51.0.0/16")).vpc().vpcId(); + String app = group(ec2, vpcId, "app"); + String other = group(ec2, vpcId, "other"); + String elsewhereVpc = ec2.createVpc(request -> request.cidrBlock("10.52.0.0/16")).vpc().vpcId(); + String elsewhere = group(ec2, elsewhereVpc, "elsewhere"); + subnetGroup(ec2, rds, "settings-subnets", vpcId, "10.51"); + + // A cluster that names none of them takes the AWS defaults. + rds.createDBCluster(request -> request.dbClusterIdentifier(DEFAULTS).engine("aurora-postgresql") + .masterUsername("dbadmin").masterUserPassword("password123") + .dbSubnetGroupName("settings-subnets")); + DBCluster defaults = describe(rds, DEFAULTS); + assertEquals(0, defaults.monitoringInterval()); + assertNull(defaults.monitoringRoleArn()); + assertFalse(defaults.performanceInsightsEnabled()); + assertNull(defaults.performanceInsightsRetentionPeriod()); + assertEquals("standard", defaults.databaseInsightsModeAsString()); + + rds.createDBCluster(request -> request.dbClusterIdentifier(CLUSTER).engine("aurora-postgresql") + .masterUsername("dbadmin").masterUserPassword("password123") + .dbSubnetGroupName("settings-subnets").vpcSecurityGroupIds(app) + .preferredBackupWindow("03:00-06:00").preferredMaintenanceWindow("Sun:23:00-Mon:02:00") + .monitoringInterval(60).monitoringRoleArn(ROLE) + .enablePerformanceInsights(true).performanceInsightsRetentionPeriod(558) + .databaseInsightsMode("advanced")); + DBCluster created = describe(rds, CLUSTER); + assertEquals(60, created.monitoringInterval()); + assertEquals(ROLE, created.monitoringRoleArn()); + assertTrue(created.performanceInsightsEnabled()); + assertEquals(558, created.performanceInsightsRetentionPeriod()); + assertEquals("advanced", created.databaseInsightsModeAsString()); + + // A modify changes what it names and keeps the rest. + rds.modifyDBCluster(request -> request.dbClusterIdentifier(CLUSTER).applyImmediately(true) + .vpcSecurityGroupIds(other).preferredBackupWindow("06:30-07:30")); + DBCluster modified = describe(rds, CLUSTER); + assertEquals(List.of(other), groups(modified)); + assertEquals(60, modified.monitoringInterval()); + assertEquals(558, modified.performanceInsightsRetentionPeriod()); + assertEquals("advanced", modified.databaseInsightsModeAsString()); + + rds.modifyDBCluster(request -> request.dbClusterIdentifier(CLUSTER).applyImmediately(true) + .databaseInsightsMode("standard").enablePerformanceInsights(false).monitoringInterval(0)); + DBCluster disabled = describe(rds, CLUSTER); + assertEquals("standard", disabled.databaseInsightsModeAsString()); + assertFalse(disabled.performanceInsightsEnabled()); + assertNull(disabled.performanceInsightsRetentionPeriod()); + assertEquals(0, disabled.monitoringInterval()); + + // Refused requests change nothing: a group of another VPC, one EC2 does not know, a bad + // interval, advanced Database Insights without Performance Insights. + assertAwsError("InvalidParameterCombination", 400, () -> rds.modifyDBCluster(request -> request + .dbClusterIdentifier(CLUSTER).vpcSecurityGroupIds(elsewhere))); + assertAwsError("InvalidParameterValue", 400, () -> rds.modifyDBCluster(request -> request + .dbClusterIdentifier(CLUSTER).vpcSecurityGroupIds("sg-0123456789abcdef0"))); + assertAwsError("InvalidParameterValue", 400, () -> rds.modifyDBCluster(request -> request + .dbClusterIdentifier(CLUSTER).monitoringInterval(7))); + assertAwsError("InvalidParameterCombination", 400, () -> rds.modifyDBCluster(request -> request + .dbClusterIdentifier(CLUSTER).databaseInsightsMode("advanced"))); + assertEquals(List.of(other), groups(describe(rds, CLUSTER))); + assertEquals("standard", describe(rds, CLUSTER).databaseInsightsModeAsString()); + + // A refused setting refuses the whole modify, so the other changes it names are not stored. + assertAwsError("InvalidParameterCombination", 400, () -> rds.modifyDBCluster(request -> request + .dbClusterIdentifier(CLUSTER).backupRetentionPeriod(14).deletionProtection(true) + .vpcSecurityGroupIds(elsewhere))); + assertAwsError("InvalidParameterCombination", 400, () -> rds.modifyDBCluster(request -> request + .dbClusterIdentifier(CLUSTER).backupRetentionPeriod(14).monitoringInterval(30) + .databaseInsightsMode("advanced"))); + DBCluster unchanged = describe(rds, CLUSTER); + assertEquals(1, unchanged.backupRetentionPeriod()); + assertFalse(unchanged.deletionProtection()); + assertEquals(0, unchanged.monitoringInterval()); + + assertAwsError("InvalidParameterCombination", 400, () -> rds.createDBCluster(request -> request + .dbClusterIdentifier(REFUSED).engine("aurora-postgresql") + .masterUsername("dbadmin").masterUserPassword("password123") + .dbSubnetGroupName("settings-subnets").vpcSecurityGroupIds(elsewhere))); + assertAwsError("InvalidParameterCombination", 400, () -> rds.createDBCluster(request -> request + .dbClusterIdentifier(REFUSED).engine("aurora-postgresql") + .masterUsername("dbadmin").masterUserPassword("password123") + .monitoringInterval(60))); + assertThrows(DbClusterNotFoundException.class, () -> describe(rds, REFUSED)); + + // An Aurora member keeps no groups of its own and reports its cluster's. + rds.createDBInstance(request -> request.dbInstanceIdentifier(MEMBER).dbClusterIdentifier(CLUSTER) + .engine("aurora-postgresql").dbInstanceClass("db.r5.large")); + assertEquals(List.of(other), vpcSecurityGroupIds(rds, MEMBER)); + rds.modifyDBCluster(request -> request.dbClusterIdentifier(CLUSTER).vpcSecurityGroupIds(app)); + assertEquals(List.of(app), vpcSecurityGroupIds(rds, MEMBER)); + + // A retained automated backup reports the window of the cluster it was taken from. + rds.deleteDBInstance(request -> request.dbInstanceIdentifier(MEMBER).skipFinalSnapshot(true)); + rds.deleteDBCluster(request -> request.dbClusterIdentifier(CLUSTER).skipFinalSnapshot(true) + .deleteAutomatedBackups(false)); + assertEquals("06:30-07:30", rds.describeDBClusterAutomatedBackups(request -> request + .dbClusterIdentifier(CLUSTER)).dbClusterAutomatedBackups().getFirst().preferredBackupWindow()); + } + } + + private static DBCluster describe(RdsClient rds, String id) { + return rds.describeDBClusters(request -> request.dbClusterIdentifier(id)).dbClusters().getFirst(); + } + + private static List groups(DBCluster cluster) { + return cluster.vpcSecurityGroups().stream().map(VpcSecurityGroupMembership::vpcSecurityGroupId).toList(); + } + + 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(); + } +} diff --git a/src/test/java/io/floci/aws/services/rds/RdsClusterVpcSecurityGroupsIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsClusterVpcSecurityGroupsIntegrationTest.java index 1ae237bf8f..24375bcf6c 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsClusterVpcSecurityGroupsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsClusterVpcSecurityGroupsIntegrationTest.java @@ -18,6 +18,8 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; +import static io.floci.aws.testing.Ec2Requests.createDefaultVpcSecurityGroup; +import static io.floci.aws.testing.Ec2Requests.ec2; import static io.floci.aws.testing.RdsRequests.createAuroraPostgresCluster; import static io.floci.aws.testing.RdsRequests.rds; import static org.hamcrest.Matchers.containsString; @@ -57,10 +59,25 @@ class RdsClusterVpcSecurityGroupsIntegrationTest { .when().post("/").then().statusCode(200).extract().asString()); } + private final List createdGroups = new ArrayList<>(); + + /** + * A new security group of the default VPC, which a cluster created without a DB subnet group is + * placed in: CreateDBCluster and ModifyDBCluster refuse a group EC2 does not know. + */ + private String securityGroup(String name) { + String groupId = createDefaultVpcSecurityGroup("test", "us-east-1", name + "-" + System.nanoTime()); + createdGroups.add(groupId); + return groupId; + } + @AfterEach void cleanUp() { rds("DeleteDBCluster").formParam("DBClusterIdentifier", ID) .formParam("SkipFinalSnapshot", "true").when().post("/"); + for (String groupId : createdGroups) { + ec2("DeleteSecurityGroup", "test", "us-east-1").formParam("GroupId", groupId).when().post("/"); + } // after the cluster, which may reference it; absent in most tests rds("DeleteDBClusterParameterGroup").formParam("DBClusterParameterGroupName", "pg-rejected") .when().post("/"); @@ -68,25 +85,28 @@ class RdsClusterVpcSecurityGroupsIntegrationTest { @Test void createStoresRequestedGroupsAndModifyReplacesThem() { + String first = securityGroup("first"); + String second = securityGroup("second"); + String third = securityGroup("third"); String created = createAuroraPostgresCluster(ID) - .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.1", "sg-abcdef01") + .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.1", first) .when().post("/").then().statusCode(200).extract().asString(); - assertEquals(List.of("sg-abcdef01"), groupIds(created)); - assertEquals(List.of("sg-abcdef01"), describedGroupIds()); + assertEquals(List.of(first), groupIds(created)); + assertEquals(List.of(first), describedGroupIds()); rds("ModifyDBCluster") .formParam("DBClusterIdentifier", ID) - .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.1", "sg-11111111") - .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.2", "sg-22222222") + .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.1", second) + .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.2", third) .when().post("/").then().statusCode(200); - assertEquals(List.of("sg-11111111", "sg-22222222"), describedGroupIds()); + assertEquals(List.of(second, third), describedGroupIds()); // A modify that does not name VpcSecurityGroupIds leaves them alone. rds("ModifyDBCluster") .formParam("DBClusterIdentifier", ID) .formParam("EnableIAMDatabaseAuthentication", "true") .when().post("/").then().statusCode(200); - assertEquals(List.of("sg-11111111", "sg-22222222"), describedGroupIds()); + assertEquals(List.of(second, third), describedGroupIds()); } @Test @@ -271,21 +291,22 @@ class RdsClusterVpcSecurityGroupsIntegrationTest { rds("CreateDBClusterParameterGroup").formParam("DBClusterParameterGroupName", "pg-rejected") .formParam("DBParameterGroupFamily", "aurora-postgresql15").formParam("Description", "d") .when().post("/").then().statusCode(200); + String old = securityGroup("old"); createAuroraPostgresCluster(ID).formParam("MasterUserPassword", "original-password1") - .formParam("VpcSecurityGroupIds.member.1", "sg-old").when().post("/").then().statusCode(200); + .formParam("VpcSecurityGroupIds.member.1", old).when().post("/").then().statusCode(200); String groupBefore = described("DBClusterParameterGroup"); rds("ModifyDBCluster").formParam("DBClusterIdentifier", ID) .formParam("DeletionProtection", "garbage").formParam("BackupRetentionPeriod", "9") .formParam("EnableIAMDatabaseAuthentication", "true") .formParam("MasterUserPassword", "changed-password2") - .formParam("VpcSecurityGroupIds.member.1", "sg-new") + .formParam("VpcSecurityGroupIds.member.1", securityGroup("new")) .formParam("DBClusterParameterGroupName", "pg-rejected") .when().post("/").then().statusCode(400) .body(containsString("InvalidParameterValue")); assertEquals("1", described("BackupRetentionPeriod")); assertEquals("false", described("IAMDatabaseAuthenticationEnabled")); assertEquals("false", described("DeletionProtection")); - assertEquals(List.of("sg-old"), describedGroupIds()); + assertEquals(List.of(old), describedGroupIds()); assertEquals(groupBefore, described("DBClusterParameterGroup")); } @@ -298,12 +319,13 @@ class RdsClusterVpcSecurityGroupsIntegrationTest { @Test void modifyWithEmptySecurityGroupMemberChangesNothing() { - createAuroraPostgresCluster(ID).formParam("VpcSecurityGroupIds.member.1", "sg-old").when().post("/").then().statusCode(200); + String old = securityGroup("old"); + createAuroraPostgresCluster(ID).formParam("VpcSecurityGroupIds.member.1", old).when().post("/").then().statusCode(200); rds("ModifyDBCluster").formParam("DBClusterIdentifier", ID) .formParam("VpcSecurityGroupIds.member.1", "").formParam("BackupRetentionPeriod", "9") .when().post("/").then().statusCode(400) .body(containsString("InvalidParameterValue")); assertEquals("1", described("BackupRetentionPeriod")); - assertEquals(List.of("sg-old"), describedGroupIds()); + assertEquals(List.of(old), describedGroupIds()); } } diff --git a/src/test/java/io/floci/aws/testing/Ec2Requests.java b/src/test/java/io/floci/aws/testing/Ec2Requests.java index 64562e13d4..6dccf2a8bc 100644 --- a/src/test/java/io/floci/aws/testing/Ec2Requests.java +++ b/src/test/java/io/floci/aws/testing/Ec2Requests.java @@ -17,6 +17,18 @@ public final class Ec2Requests { .securityGroups().getFirst().groupId(); } + /** Creates security group {@code name} in the default VPC of {@code accountId} in {@code region}; returns its id. */ + public static String createDefaultVpcSecurityGroup(String accountId, String region, String name) { + String vpcId = ec2("DescribeVpcs", accountId, region) + .formParam("Filter.1.Name", "isDefault").formParam("Filter.1.Value.1", "true") + .when().post("/").then().statusCode(200).extract().xmlPath() + .getString("DescribeVpcsResponse.vpcSet.item[0].vpcId"); + return ec2("CreateSecurityGroup", accountId, region) + .formParam("GroupName", name).formParam("GroupDescription", name).formParam("VpcId", vpcId) + .when().post("/").then().statusCode(200).extract().xmlPath() + .getString("CreateSecurityGroupResponse.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")