diff --git a/docs/services/rds.md b/docs/services/rds.md index fe53c07050..f74991dbac 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -187,6 +187,19 @@ usual default, a 30-minute window starting where the given one ends); a window g checked against the instance's other window. Modifications apply immediately — `PendingModifiedValues` is not modeled. +`CreateDBCluster` and `ModifyDBCluster` store `VpcSecurityGroupIds` (a cluster given none gets its +VPC's default security group), `PreferredBackupWindow` and `PreferredMaintenanceWindow`. Windows are +checked like an instance's and the maintenance window is returned with lowercase day names. +`RestoreDBClusterFromSnapshot` and `RestoreDBClusterToPointInTime` take `VpcSecurityGroupIds` and +`PreferredBackupWindow` the same way, and a restored cluster given no group is put in its VPC's +default security group. +`AWS::RDS::DBCluster` applies `VpcSecurityGroupIds`, `PreferredBackupWindow` and +`PreferredMaintenanceWindow` the same way, and a cluster whose template names no groups gets its VPC's +default security group. `ModifyDBCluster` leaves the groups alone unless it names them. +A CloudFormation update that drops `VpcSecurityGroupIds` the previous template declared puts the +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. + !!! note "Stopping and starting" `StopDBInstance` and `StopDBCluster` follow the user guide: the response reports `stopping` diff --git a/src/main/java/io/floci/aws/core/common/BackupWindows.java b/src/main/java/io/floci/aws/core/common/BackupWindows.java index 5419f2d467..8ef81625f4 100644 --- a/src/main/java/io/floci/aws/core/common/BackupWindows.java +++ b/src/main/java/io/floci/aws/core/common/BackupWindows.java @@ -87,6 +87,59 @@ public final class BackupWindows { "The backup window and maintenance window must not overlap.", 400); } + /** + * The {backup, maintenance} windows in effect after a request, checked against each other. On + * create a window given alone is paired with the default, or with one starting where the given + * one ends when the default would overlap it, as AWS picks a clear window itself. On modify the + * counterpart is the resource's current window ({@code currentBackup}, {@code currentMaintenance}, + * either may be null for the default). + */ + public static String[] effectiveWindows(boolean create, String backup, String maintenance, + String currentBackup, String currentMaintenance) { + boolean backupGiven = backup != null; + boolean maintenanceGiven = maintenance != null; + if (backupGiven) { + parseBackupWindow(backup); + } + if (maintenanceGiven) { + parseMaintenanceWindow(maintenance); + } + if (create) { + if (!backupGiven) { + backup = maintenanceGiven && overlap(DEFAULT_BACKUP_WINDOW, maintenance) + ? backupWindowAfter(maintenance) : DEFAULT_BACKUP_WINDOW; + } + if (!maintenanceGiven) { + maintenance = backupGiven && overlap(backup, DEFAULT_MAINTENANCE_WINDOW) + ? maintenanceWindowAfter(backup) : DEFAULT_MAINTENANCE_WINDOW; + } + // a derived window is clear unless the given one leaves no 30-minute gap at all + if (overlap(backup, maintenance)) { + if (!maintenanceGiven) { + throw new AwsException("InvalidParameterValue", "The specified backup window overlaps all " + + "available default maintenance windows. Shrink the backup window or specify a " + + "non-overlapping maintenance window.", 400); + } + if (!backupGiven) { + throw new AwsException("InvalidParameterValue", "The specified maintenance window overlaps " + + "all available default backup windows. Shrink the maintenance window or specify " + + "a non-overlapping backup window.", 400); + } + } + } else { + if (!backupGiven) { + backup = currentBackup != null ? currentBackup : DEFAULT_BACKUP_WINDOW; + } + if (!maintenanceGiven) { + maintenance = currentMaintenance != null ? currentMaintenance : DEFAULT_MAINTENANCE_WINDOW; + } + } + if (overlap(backup, maintenance)) { + throw overlapping(); + } + return new String[] {backup, maintenance}; + } + /** A 30-minute maintenance window starting the minute the given daily window ends. */ public static String maintenanceWindowAfter(String backupWindow) { int end = parseBackupWindow(backupWindow)[1] % MINUTES_PER_DAY; 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 ca183a11cb..fb7ce9b480 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 @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.BackupWindows; import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine; import io.floci.aws.services.cloudformation.model.StackResource; import io.floci.aws.services.rds.RdsService; @@ -114,8 +115,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { private static final CreateOnlyInputs DB_INSTANCE_STORAGE_ENCRYPTED = new CreateOnlyInputs( "__FlociDbInstanceStorageEncrypted", "__FlociDbInstanceStorageEncryptedPrior"); /** - * What an update that kept a DB instance needs for {@link #rollbackUpdate}: the region, the VPC - * security groups the instance had when the update changed them, and whether it changed anything + * What an update that kept a DB instance or cluster needs for {@link #rollbackUpdate}: the region, + * the VPC security groups it had when the update changed them, and whether it changed anything * else, which has no rollback here. */ static final String DB_INSTANCE_PRIOR_IN_PLACE_ATTR = "__FlociDbInstancePriorInPlaceUpdate"; @@ -245,7 +246,8 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { /** * Puts back the VPC security groups an update that kept the instance changed, and answers whether * that undid the whole update. The saved record is dropped only once the groups are back, so an - * instance gone since the update fails the rollback, and a retried one tries again. + * instance gone since the update fails the rollback, and a retried one tries again. A record + * carrying the {@code cluster} flag puts back a DB cluster's groups the same way. */ private boolean restoreDbInstanceInPlaceUpdate(StackResource resource) { String saved = resource.getAttributes().get(DB_INSTANCE_PRIOR_IN_PLACE_ATTR); @@ -263,8 +265,13 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { if (groups.isArray()) { List groupIds = new ArrayList<>(); groups.forEach(group -> groupIds.add(group.asText())); - rdsService.setDbInstanceVpcSecurityGroups(prior.path("region").asText(), resource.getPhysicalId(), - groupIds); + if (prior.path("cluster").asBoolean(false)) { + rdsService.setDbClusterRequestSettings(resource.getPhysicalId(), prior.path("region").asText(), + groupIds, null, null); + } else { + rdsService.setDbInstanceVpcSecurityGroups(prior.path("region").asText(), + resource.getPhysicalId(), groupIds); + } } resource.getAttributes().remove(DB_INSTANCE_PRIOR_IN_PLACE_ATTR); return !prior.path("otherChanges").asBoolean(true); @@ -655,8 +662,23 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { // Refused before a new cluster exists, rather than leaving one behind. RdsService.requireDataApiEngine(resolveOptional(props, "Engine", engine)); } - boolean deletionProtection = parseStrictBoolProp(props, "DeletionProtection", engine); + // null when the template drops it: an update then keeps the stored value, as AWS's null does + Boolean requestedDeletionProtection = parseOptionalStrictBoolProp(props, "DeletionProtection", engine); + boolean deletionProtection = Boolean.TRUE.equals(requestedDeletionProtection); boolean created = cluster == null; + String backupWindow = resolveOptional(props, "PreferredBackupWindow", engine); + String maintenanceWindow = resolveOptional(props, "PreferredMaintenanceWindow", engine); + if (created) { + // validated before the cluster exists, so a bad window leaves none behind + String[] windows = BackupWindows.effectiveWindows(true, backupWindow, maintenanceWindow, null, null); + backupWindow = windows[0]; + maintenanceWindow = windows[1]; + } else { + // validated against the stored windows before the modify, so a bad window changes nothing + BackupWindows.effectiveWindows(false, backupWindow, maintenanceWindow, + cluster.getPreferredBackupWindow(), cluster.getPreferredMaintenanceWindow()); + } + List securityGroupIds = resolveStringList(props, "VpcSecurityGroupIds", engine); if (cluster != null) { cluster = rdsService.modifyDbCluster( id, @@ -683,13 +705,34 @@ public class RdsCfnProvisioner implements CfnResourceProvisioner { serverlessV2MinCapacity, serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause, false, null, engineMode, storageEncrypted, null, deletionProtection); } + if (securityGroupIds.isEmpty()) { + // A list the previous template declared and this one drops puts the cluster on its VPC's + // default group, as AWS's handler does, and leaves them when there is none. Groups the + // stack never declared, and the other settings, keep what is stored. + List defaultGroup = !created && ctx.previouslyDeclared("VpcSecurityGroupIds") + ? rdsService.defaultClusterVpcSecurityGroupIds(region, cluster.getDbClusterIdentifier()) + : List.of(); + securityGroupIds = defaultGroup.isEmpty() ? null : defaultGroup; + } + // The groups an in-place update changes are saved, for rollbackUpdate, as an instance's are. + r.getAttributes().remove(DB_INSTANCE_PRIOR_IN_PLACE_ATTR); + if (!created && securityGroupIds != null + && !Set.copyOf(securityGroupIds).equals(Set.copyOf(cluster.getVpcSecurityGroupIds()))) { + ObjectNode saved = MAPPER.createObjectNode().put("region", region).put("cluster", true) + .put("otherChanges", true); + ArrayNode priorGroups = saved.putArray("vpcSecurityGroups"); + cluster.getVpcSecurityGroupIds().forEach(priorGroups::add); + r.getAttributes().put(DB_INSTANCE_PRIOR_IN_PLACE_ATTR, saved.toString()); + } + rdsService.setDbClusterRequestSettings(cluster.getDbClusterIdentifier(), region, + securityGroupIds, backupWindow, maintenanceWindow); cluster = reconcileClusterRoles(r, cluster, roles, created, region); ASSOCIATED_ROLES.record(r, ctx, attributesBefore, associatedRolesRecord(roles)); // EnableHttpEndpoint updates with no interruption; a template that leaves it out wants it off. if (httpEndpoint != cluster.isHttpEndpointEnabled()) { cluster = rdsService.setHttpEndpoint(region, cluster.getDbClusterIdentifier(), httpEndpoint); } - if (deletionProtection != cluster.isDeletionProtection()) { + if (requestedDeletionProtection != null && deletionProtection != cluster.isDeletionProtection()) { cluster = rdsService.setDeletionProtection(region, cluster.getDbClusterIdentifier(), deletionProtection); } r.setPhysicalId(cluster.getDbClusterIdentifier()); 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 0547b4d39d..f54c135ab3 100644 --- a/src/main/java/io/floci/aws/services/docdb/DocDbService.java +++ b/src/main/java/io/floci/aws/services/docdb/DocDbService.java @@ -342,46 +342,13 @@ public class DocDbService { securityGroups = List.of(resolveDefaultSecurityGroupId(ec2Service, region)); } String kmsKeyArn = resolveKmsKeyArn(settings.kmsKeyId(), region); - String backup = settings.preferredBackupWindow(); - String maintenance = settings.preferredMaintenanceWindow(); - boolean backupGiven = backup != null; - boolean maintenanceGiven = maintenance != null; - if (create) { - if (!backupGiven) { - backup = maintenanceGiven && BackupWindows.overlap(BackupWindows.DEFAULT_BACKUP_WINDOW, maintenance) - ? BackupWindows.backupWindowAfter(maintenance) : BackupWindows.DEFAULT_BACKUP_WINDOW; - if (maintenanceGiven && BackupWindows.overlap(backup, maintenance)) { - // the given window leaves no daily half hour free - throw new AwsException("InvalidParameterValue", "The specified maintenance window overlaps " - + "all available default backup windows. Shrink the maintenance window or specify " - + "a non-overlapping backup window.", 400); - } - } - if (!maintenanceGiven) { - maintenance = backupGiven && BackupWindows.overlap(backup, BackupWindows.DEFAULT_MAINTENANCE_WINDOW) - ? BackupWindows.maintenanceWindowAfter(backup) : BackupWindows.DEFAULT_MAINTENANCE_WINDOW; - if (BackupWindows.overlap(backup, maintenance)) { - throw new AwsException("InvalidParameterValue", "The specified backup window overlaps " - + "all available default maintenance windows. Shrink the backup window or specify " - + "a non-overlapping maintenance window.", 400); - } - } - } else { - if (!backupGiven) { - backup = current.getPreferredBackupWindow() != null - ? current.getPreferredBackupWindow() : BackupWindows.DEFAULT_BACKUP_WINDOW; - } - if (!maintenanceGiven) { - maintenance = current.getPreferredMaintenanceWindow() != null - ? current.getPreferredMaintenanceWindow() : BackupWindows.DEFAULT_MAINTENANCE_WINDOW; - } - } - if (BackupWindows.overlap(backup, maintenance)) { - throw BackupWindows.overlapping(); - } + String[] windows = BackupWindows.effectiveWindows(create, settings.preferredBackupWindow(), + settings.preferredMaintenanceWindow(), + create ? null : current.getPreferredBackupWindow(), + create ? null : current.getPreferredMaintenanceWindow()); return new DocDbClusterSettings(subnetGroup, parameterGroup, securityGroups, settings.storageEncrypted(), kmsKeyArn, settings.backupRetentionPeriod(), - backup, maintenance, settings.deletionProtection()); + windows[0], windows[1], settings.deletionProtection()); } /** The security group a cluster's VPC security group ids fall back to: the service's 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 7c80e1de3e..5c06d4b27c 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/rds/RdsQueryHandler.java @@ -8,6 +8,7 @@ import io.floci.aws.core.common.AwsNamespaces; import io.floci.aws.core.common.AwsQueryLists; import io.floci.aws.core.common.AwsQueryResponse; import io.floci.aws.core.common.AwsRegionFacts; +import io.floci.aws.core.common.BackupWindows; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.XmlBuilder; @@ -1463,6 +1464,11 @@ public class RdsQueryHandler { Integer requestedPort = parseIntegerParam(params, "Port"); String globalClusterIdentifier = params.getFirst("GlobalClusterIdentifier"); boolean protectedCluster = Boolean.TRUE.equals(deletionProtection); + String[] windows = BackupWindows.effectiveWindows(true, + params.getFirst("PreferredBackupWindow"), params.getFirst("PreferredMaintenanceWindow"), null, null); + // parsed before any mutating call so a malformed value leaves no cluster behind + List securityGroupIds = hasMemberKeys(params, "VpcSecurityGroupIds") + ? vpcSecurityGroupIds(params) : null; DbCluster cluster; if (globalClusterIdentifier != null && !globalClusterIdentifier.isBlank()) { cluster = service.createDbClusterInGlobalCluster(globalClusterIdentifier, id, engine, @@ -1509,6 +1515,7 @@ public class RdsQueryHandler { if (copyTagsToSnapshot != null || exports != null) { cluster = service.setClusterSnapshotAndLogSettings(region, id, copyTagsToSnapshot, exports, null); } + cluster = service.setDbClusterRequestSettings(id, region, securityGroupIds, windows[0], windows[1]); String result = dbClusterXml(cluster); return Response.ok(AwsQueryResponse.envelope("CreateDBCluster", AwsNamespaces.RDS, result)).build(); } catch (AwsException e) { @@ -1626,9 +1633,25 @@ public class RdsQueryHandler { RdsService.validateBackupRetentionPeriod(modifyBackupRetentionPeriod); } Boolean deletionProtection = parseOptionalBoolean(params, "DeletionProtection"); - if (Boolean.TRUE.equals(enableHttpEndpoint)) { - RdsService.requireDataApiEngine(service.getDbCluster(id, region).getEngineIdentifier()); + DbCluster current; + try { + current = service.getDbCluster(id, region); + } catch (AwsException notFound) { + if (!"DBClusterNotFoundFault".equals(notFound.getErrorCode())) { + throw notFound; + } + // AWS words a modify of a missing cluster this way, unlike the describe and delete paths + throw new AwsException("DBClusterNotFoundFault", "DBCluster not found", 404); } + if (Boolean.TRUE.equals(enableHttpEndpoint)) { + RdsService.requireDataApiEngine(current.getEngineIdentifier()); + } + BackupWindows.effectiveWindows(false, params.getFirst("PreferredBackupWindow"), + params.getFirst("PreferredMaintenanceWindow"), current.getPreferredBackupWindow(), + current.getPreferredMaintenanceWindow()); + // parsed before any mutating call so a malformed value changes nothing + List securityGroupIds = hasMemberKeys(params, "VpcSecurityGroupIds") + ? vpcSecurityGroupIds(params) : null; DbCluster cluster = service.modifyDbCluster(id, newPassword, iamEnabled, serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause, manageMasterUserPassword, masterUserSecretKmsKeyId, @@ -1644,6 +1667,8 @@ public class RdsQueryHandler { if (copyTagsToSnapshot != null || exportChanges != null) { cluster = service.setClusterSnapshotAndLogSettings(region, id, copyTagsToSnapshot, null, exportChanges); } + cluster = service.setDbClusterRequestSettings(id, region, securityGroupIds, + params.getFirst("PreferredBackupWindow"), params.getFirst("PreferredMaintenanceWindow")); if (deletionProtection != null) { cluster = service.setDeletionProtection(region, id, deletionProtection); } @@ -3051,6 +3076,7 @@ public class RdsQueryHandler { return missing; } try { + RestoreSettings settings = RestoreSettings.parse(params); DbCluster cluster = service.restoreDbClusterToPointInTime(clusterId, params.getFirst("SourceDBClusterIdentifier"), params.getFirst("SourceDbClusterResourceId"), params.getFirst("RestoreType"), @@ -3062,6 +3088,7 @@ public class RdsQueryHandler { params.getFirst("EngineMode"), Boolean.TRUE.equals(parseOptionalBoolean(params, "DeletionProtection")), parseTags(params), region); + cluster = settings.applyTo(service, clusterId, region); return Response.ok(AwsQueryResponse.envelope("RestoreDBClusterToPointInTime", AwsNamespaces.RDS, dbClusterXml(cluster))).build(); } catch (AwsException e) { @@ -3080,17 +3107,37 @@ public class RdsQueryHandler { if (missing != null) { return missing; } - DbCluster cluster = service.restoreDbClusterFromSnapshot(clusterId, snapshotId, engine, - params.getFirst("EngineVersion"), optionalInt(params.getFirst("Port")), - params.getFirst("DatabaseName"), params.getFirst("DBSubnetGroupName"), - params.getFirst("DBClusterParameterGroupName"), - params.getFirst("AvailabilityZones.member.1"), - parseOptionalBoolean(params, "EnableIAMDatabaseAuthentication"), - params.getFirst("EngineMode"), - Boolean.TRUE.equals(parseOptionalBoolean(params, "DeletionProtection")), - parseTags(params), region); - return Response.ok(AwsQueryResponse.envelope("RestoreDBClusterFromSnapshot", AwsNamespaces.RDS, - dbClusterXml(cluster))).build(); + try { + RestoreSettings settings = RestoreSettings.parse(params); + service.restoreDbClusterFromSnapshot(clusterId, snapshotId, engine, + params.getFirst("EngineVersion"), optionalInt(params.getFirst("Port")), + params.getFirst("DatabaseName"), params.getFirst("DBSubnetGroupName"), + params.getFirst("DBClusterParameterGroupName"), + params.getFirst("AvailabilityZones.member.1"), + parseOptionalBoolean(params, "EnableIAMDatabaseAuthentication"), + params.getFirst("EngineMode"), + Boolean.TRUE.equals(parseOptionalBoolean(params, "DeletionProtection")), + parseTags(params), region); + DbCluster cluster = settings.applyTo(service, clusterId, region); + return Response.ok(AwsQueryResponse.envelope("RestoreDBClusterFromSnapshot", AwsNamespaces.RDS, + dbClusterXml(cluster))).build(); + } catch (AwsException e) { + return AwsQueryResponse.error(e.getErrorCode(), e.getMessage(), AwsNamespaces.RDS, e.getHttpStatus()); + } + } + + /** What a cluster restore request says about security groups, and backup window. */ + private record RestoreSettings(List securityGroupIds, String[] windows) { + // parsed before the restore so a malformed value leaves no cluster behind + static RestoreSettings parse(MultivaluedMap params) { + return new RestoreSettings( + hasMemberKeys(params, "VpcSecurityGroupIds") ? vpcSecurityGroupIds(params) : null, + BackupWindows.effectiveWindows(true, params.getFirst("PreferredBackupWindow"), null, null, null)); + } + + DbCluster applyTo(RdsService service, String id, String region) { + return service.setDbClusterRequestSettings(id, region, securityGroupIds, windows[0], windows[1]); + } } private Response handleDescribeDbClusterSnapshotAttributes(MultivaluedMap params, String region) { @@ -3549,8 +3596,12 @@ public class RdsQueryHandler { if (groupIds.isEmpty()) { groupIds = List.of("sg-00000000"); } + return vpcSecurityGroupsXml(groupIds); + } + + private String vpcSecurityGroupsXml(List vpcSecurityGroupIds) { XmlBuilder xml = new XmlBuilder().start("VpcSecurityGroups"); - for (String groupId : groupIds) { + for (String groupId : vpcSecurityGroupIds) { xml.start("VpcSecurityGroupMembership") .elem("VpcSecurityGroupId", groupId) .elem("Status", "active") @@ -3696,14 +3747,11 @@ public class RdsQueryHandler { .elem("CopyTagsToSnapshot", c.isCopyTagsToSnapshot()) .elem("KmsKeyId", c.getKmsKeyId()) .elem("AvailabilityZone", c.getAvailabilityZone() != null ? c.getAvailabilityZone() : config.defaultAvailabilityZone()) - .elem("PreferredMaintenanceWindow", "mon:00:00-mon:03:00") - .elem("PreferredBackupWindow", "04:00-06:00") - .start("VpcSecurityGroups") - .start("VpcSecurityGroupMembership") - .elem("VpcSecurityGroupId", "sg-00000000") - .elem("Status", "active") - .end("VpcSecurityGroupMembership") - .end("VpcSecurityGroups") + .elem("PreferredMaintenanceWindow", c.getPreferredMaintenanceWindow() != null + ? c.getPreferredMaintenanceWindow() : BackupWindows.DEFAULT_MAINTENANCE_WINDOW) + .elem("PreferredBackupWindow", c.getPreferredBackupWindow() != null + ? c.getPreferredBackupWindow() : BackupWindows.DEFAULT_BACKUP_WINDOW) + .raw(vpcSecurityGroupsXml(c.getVpcSecurityGroupIds())) .elem("DBSubnetGroup", c.getDbSubnetGroupName() != null ? c.getDbSubnetGroupName() : "default"); String clusterParameterGroup = dbClusterParameterGroupName(c, engineStr); if (clusterParameterGroup != null) { 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 c21cc2100d..677180d522 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsService.java +++ b/src/main/java/io/floci/aws/services/rds/RdsService.java @@ -4388,6 +4388,13 @@ public class RdsService implements Resettable, ResourceProvider { : getDbSubnetGroup(dbSubnetGroupName, effectiveRegion).getVpcId(); } + /** As {@link #defaultVpcSecurityGroupIds(String, String, String)} for a DB cluster. */ + public List defaultClusterVpcSecurityGroupIds(String region, String clusterId) { + String effectiveRegion = effectiveRegion(region); + return RdsSecurityGroups.vpcDefault(ec2Service, effectiveRegion, + getDbCluster(clusterId, effectiveRegion).getVpcId()); + } + private static void validateInstanceSettings(DbInstanceSettings settings) { settings.validate(); } @@ -4430,46 +4437,11 @@ public class RdsService implements Resettable, ResourceProvider { * the instance's. */ private static DbInstanceSettings withEffectiveWindows(DbInstanceSettings settings, DbInstance current) { - String backup = settings.preferredBackupWindow(); - String maintenance = settings.preferredMaintenanceWindow(); - boolean backupGiven = backup != null; - boolean maintenanceGiven = maintenance != null; - if (current == null) { - if (!backupGiven) { - backup = maintenanceGiven && DbInstanceSettings.windowsOverlap( - DbInstanceSettings.DEFAULT_BACKUP_WINDOW, maintenance) - ? DbInstanceSettings.backupWindowAfter(maintenance) - : DbInstanceSettings.DEFAULT_BACKUP_WINDOW; - } - if (!maintenanceGiven) { - maintenance = backupGiven && DbInstanceSettings.windowsOverlap( - backup, DbInstanceSettings.DEFAULT_MAINTENANCE_WINDOW) - ? DbInstanceSettings.maintenanceWindowAfter(backup) - : DbInstanceSettings.DEFAULT_MAINTENANCE_WINDOW; - } - // a derived window is clear unless the given one leaves no 30-minute gap at all - if (DbInstanceSettings.windowsOverlap(backup, maintenance)) { - if (!maintenanceGiven) { - throw DbInstanceSettings.noRoomForMaintenanceWindow(); - } - if (!backupGiven) { - throw DbInstanceSettings.noRoomForBackupWindow(); - } - } - } else { - if (!backupGiven) { - backup = current.getPreferredBackupWindow() != null - ? current.getPreferredBackupWindow() : DbInstanceSettings.DEFAULT_BACKUP_WINDOW; - } - if (!maintenanceGiven) { - maintenance = current.getPreferredMaintenanceWindow() != null - ? current.getPreferredMaintenanceWindow() : DbInstanceSettings.DEFAULT_MAINTENANCE_WINDOW; - } - } - if (DbInstanceSettings.windowsOverlap(backup, maintenance)) { - throw DbInstanceSettings.overlappingWindows(); - } - return settings.withWindows(backup, maintenance); + String[] windows = BackupWindows.effectiveWindows(current == null, settings.preferredBackupWindow(), + settings.preferredMaintenanceWindow(), + current == null ? null : current.getPreferredBackupWindow(), + current == null ? null : current.getPreferredMaintenanceWindow()); + return settings.withWindows(windows[0], windows[1]); } /** @@ -5909,6 +5881,8 @@ public class RdsService implements Resettable, ResourceProvider { } cluster.setDbSubnetGroupName(placement.dbSubnetGroupName()); cluster.setVpcId(placement.vpcId()); + // none named yet: AWS puts the cluster in its VPC's default group; EC2 without one leaves none + cluster.setVpcSecurityGroupIds(RdsSecurityGroups.vpcDefault(ec2Service, effectiveRegion, placement.vpcId())); cluster.setAvailabilityZone(placement.availabilityZone()); cluster.setMultiAz(placement.multiAz()); cluster.setSubnetAvailabilityZones(placement.subnetAvailabilityZones()); @@ -12081,6 +12055,26 @@ public class RdsService implements Resettable, ResourceProvider { return member == null ? 1 : member.getPromotionTier(); } + /** 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) { + String effectiveRegion = effectiveRegion(region); + DbCluster cluster = getDbCluster(id, effectiveRegion); + BackupWindows.effectiveWindows(false, backupWindow, maintenanceWindow, + cluster.getPreferredBackupWindow(), cluster.getPreferredMaintenanceWindow()); + if (vpcSecurityGroupIds != null) { + cluster.setVpcSecurityGroupIds(vpcSecurityGroupIds); + } + if (backupWindow != null) { + cluster.setPreferredBackupWindow(backupWindow); + } + if (maintenanceWindow != null) { + cluster.setPreferredMaintenanceWindow(BackupWindows.lowerCase(maintenanceWindow)); + } + putClusterForScope(currentAccountId(), effectiveRegion, id, cluster); + return RESPONSE_COPIER.convertValue(cluster, DbCluster.class); + } + private static final Set DATA_API_ENGINES = Set.of("aurora-postgresql", "aurora-mysql"); /** 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 392deb68f8..2ef52047d1 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 @@ -32,6 +32,10 @@ public class DbCluster { private String parameterGroupName; private String dbSubnetGroupName; private String vpcId; + private List vpcSecurityGroupIds = new ArrayList<>(); + // Null until a request names them; the emitted XML then falls back to the defaults. + private String preferredBackupWindow; + private String preferredMaintenanceWindow; private String availabilityZone; private boolean multiAz; private Map subnetAvailabilityZones = new LinkedHashMap<>(); @@ -163,6 +167,19 @@ public class DbCluster { public boolean isMultiAz() { return multiAz; } public void setMultiAz(boolean multiAz) { this.multiAz = multiAz; } + public List getVpcSecurityGroupIds() { return vpcSecurityGroupIds; } + public void setVpcSecurityGroupIds(List vpcSecurityGroupIds) { + this.vpcSecurityGroupIds = vpcSecurityGroupIds != null ? new ArrayList<>(vpcSecurityGroupIds) : new ArrayList<>(); + } + + public String getPreferredBackupWindow() { return preferredBackupWindow; } + public void setPreferredBackupWindow(String preferredBackupWindow) { this.preferredBackupWindow = preferredBackupWindow; } + + public String getPreferredMaintenanceWindow() { return preferredMaintenanceWindow; } + public void setPreferredMaintenanceWindow(String preferredMaintenanceWindow) { + this.preferredMaintenanceWindow = preferredMaintenanceWindow; + } + public Map getSubnetAvailabilityZones() { return subnetAvailabilityZones; } public void setSubnetAvailabilityZones(Map subnetAvailabilityZones) { this.subnetAvailabilityZones = subnetAvailabilityZones != null diff --git a/src/main/java/io/floci/aws/services/rds/model/DbInstanceSettings.java b/src/main/java/io/floci/aws/services/rds/model/DbInstanceSettings.java index 460645fb93..028602cfac 100644 --- a/src/main/java/io/floci/aws/services/rds/model/DbInstanceSettings.java +++ b/src/main/java/io/floci/aws/services/rds/model/DbInstanceSettings.java @@ -195,19 +195,6 @@ public record DbInstanceSettings(Boolean storageEncrypted, return BackupWindows.backupWindowAfter(maintenanceWindow); } - /** A window given alone that leaves no room for the other kind, in AWS's words. */ - public static AwsException noRoomForMaintenanceWindow() { - return new AwsException("InvalidParameterValue", "The specified backup window overlaps all " - + "available default maintenance windows. Shrink the backup window or specify a " - + "non-overlapping maintenance window.", 400); - } - - public static AwsException noRoomForBackupWindow() { - return new AwsException("InvalidParameterValue", "The specified maintenance window overlaps " - + "all available default backup windows. Shrink the maintenance window or specify a " - + "non-overlapping backup window.", 400); - } - public static AwsException overlappingWindows() { return BackupWindows.overlapping(); } 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 baeeb8a3ba..2a6a2ed874 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsAssociatedRolesIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRdsAssociatedRolesIntegrationTest.java @@ -7,6 +7,8 @@ import io.quarkus.test.junit.TestProfile; import io.restassured.path.xml.XmlPath; import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.util.List; @@ -266,6 +268,155 @@ class CloudFormationRdsAssociatedRolesIntegrationTest { } } + @Test + void aClusterWithNoTemplateGroupsGetsTheVpcDefaultAndADroppedListGoesBackToIt() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-rds-sg-" + suffix; + String clusterId = "cfn-sg-cluster-" + suffix; + String cluster = """ + {"Resources": {"Cluster": {"Type": "AWS::RDS::DBCluster", "Properties": { + "DBClusterIdentifier": "%s", "Engine": "aurora-postgresql", + "MasterUsername": "dbadmin", "MasterUserPassword": "%s"%s}}}} + """; + try { + stack("CreateStack", stackName, cluster.formatted(clusterId, "password123", "")); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + List defaultGroup = clusterGroups(clusterId); + assertEquals(1, defaultGroup.size(), defaultGroup.toString()); + + stack("UpdateStack", stackName, cluster.formatted(clusterId, "password123", + ", \"VpcSecurityGroupIds\": [\"sg-named\"]")); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals(List.of("sg-named"), clusterGroups(clusterId)); + + // A list the previous template declared and this one drops goes back to the VPC default. + stack("UpdateStack", stackName, cluster.formatted(clusterId, "password456", "")); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals(defaultGroup, clusterGroups(clusterId)); + } finally { + stack("DeleteStack", stackName, null); + CfnStackWaits.awaitStackDeleted(stackName); + } + } + + @Test + void anUpdateLeavesGroupsSetOutsideTheStackAndDroppedSettingsKeepTheirValues() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-rds-sg-out-" + suffix; + String clusterId = "cfn-sg-out-" + suffix; + String cluster = """ + {"Resources": {"Cluster": {"Type": "AWS::RDS::DBCluster", "Properties": { + "DBClusterIdentifier": "%s", "Engine": "aurora-postgresql", + "MasterUsername": "dbadmin", "MasterUserPassword": "%s"%s}}}} + """; + try { + stack("CreateStack", stackName, cluster.formatted(clusterId, "password123", + ", \"DeletionProtection\": true, \"PreferredBackupWindow\": \"03:00-04:00\"," + + " \"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") + .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)); + XmlPath xml = rds("DescribeDBClusters").formParam("DBClusterIdentifier", clusterId) + .when().post("/").then().statusCode(200).extract().xmlPath(); + assertEquals("true", xml.getString("**.find { it.name() == 'DeletionProtection' }")); + assertEquals("03:00-04:00", xml.getString("**.find { it.name() == 'PreferredBackupWindow' }")); + assertEquals("mon:05:00-mon:06:00", + xml.getString("**.find { it.name() == 'PreferredMaintenanceWindow' }")); + } finally { + rds("ModifyDBCluster").formParam("DBClusterIdentifier", clusterId) + .formParam("DeletionProtection", "false").when().post("/"); + stack("DeleteStack", stackName, null); + CfnStackWaits.awaitStackDeleted(stackName); + } + } + + @Test + void anExplicitEmptyGroupListKeepsTheDefaultOnCreateAndRestoresItOnUpdate() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-rds-sg-empty-" + suffix; + String clusterId = "cfn-sg-empty-" + suffix; + String cluster = """ + {"Resources": {"Cluster": {"Type": "AWS::RDS::DBCluster", "Properties": { + "DBClusterIdentifier": "%s", "Engine": "aurora-postgresql", + "MasterUsername": "dbadmin", "MasterUserPassword": "password123", + "VpcSecurityGroupIds": %s}}}} + """; + try { + List vpcDefault = vpcDefaultGroup(suffix); + stack("CreateStack", stackName, cluster.formatted(clusterId, "[]")); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals(vpcDefault, clusterGroups(clusterId)); + + stack("UpdateStack", stackName, cluster.formatted(clusterId, "[\"sg-named\"]")); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals(List.of("sg-named"), clusterGroups(clusterId)); + + stack("UpdateStack", stackName, cluster.formatted(clusterId, "[]")); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals(vpcDefault, clusterGroups(clusterId)); + } finally { + stack("DeleteStack", stackName, null); + CfnStackWaits.awaitStackDeleted(stackName); + } + } + + @ParameterizedTest + @ValueSource(strings = {", \"VpcSecurityGroupIds\": [\"sg-second\"]", ""}) + void aGroupChangeIsUndoneWhenALaterResourceFailsTheUpdate(String updatedGroups) { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "cfn-rds-sg-undo-" + suffix; + String clusterId = "cfn-sg-undo-" + suffix; + String cluster = """ + "Cluster": {"Type": "AWS::RDS::DBCluster", "Properties": { + "DBClusterIdentifier": "%s", "Engine": "aurora-postgresql", + "MasterUsername": "dbadmin", "MasterUserPassword": "password123"%s}}"""; + // A member carrying its own roles is refused, after the cluster has been updated. + String failingMember = """ + , "Member": {"Type": "AWS::RDS::DBInstance", "Properties": { + "DBClusterIdentifier": {"Ref": "Cluster"}, "Engine": "aurora-postgresql", + "DBInstanceClass": "db.r6g.large", + "AssociatedRoles": [{"RoleArn": "%s", "FeatureName": "s3Import"}]}}""".formatted(EXPORT_ROLE); + try { + stack("CreateStack", stackName, "{\"Resources\": {" + + cluster.formatted(clusterId, ", \"VpcSecurityGroupIds\": [\"sg-first\"]") + "}}"); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + + stack("UpdateStack", stackName, "{\"Resources\": {" + + cluster.formatted(clusterId, updatedGroups) + failingMember + "}}"); + // The cluster's other settings have no rollback, so the stack reports the rollback failed. + assertEquals("UPDATE_ROLLBACK_FAILED", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals(List.of("sg-first"), clusterGroups(clusterId)); + } finally { + stack("DeleteStack", stackName, null); + CfnStackWaits.awaitStackDeleted(stackName); + } + } + + /** The group a cluster created with none lands on, read from a throwaway cluster. */ + private static List vpcDefaultGroup(String suffix) { + String id = "cfn-sg-ref-" + suffix; + rds("CreateDBCluster").formParam("DBClusterIdentifier", id).formParam("Engine", "aurora-postgresql") + .formParam("MasterUsername", "dbadmin").formParam("MasterUserPassword", "password123") + .when().post("/").then().statusCode(200); + try { + return clusterGroups(id); + } finally { + rds("DeleteDBCluster").formParam("DBClusterIdentifier", id).formParam("SkipFinalSnapshot", "true") + .when().post("/").then().statusCode(200); + } + } + + private static List clusterGroups(String clusterId) { + XmlPath xml = rds("DescribeDBClusters").formParam("DBClusterIdentifier", clusterId) + .when().post("/").then().statusCode(200).extract().xmlPath(); + return xml.getList("**.findAll { it.name() == 'VpcSecurityGroupId' }", String.class); + } + private static String template(String clusterId, String instanceId, String clusterRoles) { return """ {"Resources": { 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 37ba87f64c..1ef83d701a 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/RdsCfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/RdsCfnProvisionerTest.java @@ -292,6 +292,40 @@ class RdsCfnProvisionerTest { null, null, null, false, null, null, false, null, false); } + @Test + void dbClusterPassesTemplateGroupsProtectionAndWindowsToTheRequestSettings() { + DbCluster cluster = mock(DbCluster.class); + when(cluster.getDbClusterIdentifier()).thenReturn("mycluster"); + when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(), + any(), any(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), any(), any(), + anyBoolean(), any(), anyBoolean())) + .thenReturn(cluster); + + provision("Cluster", "AWS::RDS::DBCluster", """ + {"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql", + "VpcSecurityGroupIds":["sg-a","sg-b"],"DeletionProtection":true, + "PreferredBackupWindow":"03:00-04:00","PreferredMaintenanceWindow":"Mon:05:00-Mon:06:00"} + """); + verify(rdsService).setDbClusterRequestSettings("mycluster", "us-east-1", List.of("sg-a", "sg-b"), + "03:00-04:00", "Mon:05:00-Mon:06:00"); + } + + @Test + void dbClusterWithoutTemplateGroupsLeavesGroupsToTheServiceDefault() { + DbCluster cluster = mock(DbCluster.class); + when(cluster.getDbClusterIdentifier()).thenReturn("mycluster"); + when(rdsService.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(), + any(), any(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), any(), any(), + anyBoolean(), any(), anyBoolean())) + .thenReturn(cluster); + + provision("Cluster", "AWS::RDS::DBCluster", """ + {"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql"} + """); + verify(rdsService).setDbClusterRequestSettings(eq("mycluster"), eq("us-east-1"), isNull(), + nullable(String.class), nullable(String.class)); + } + @Test void dbClusterEnableHttpEndpointIsAppliedOnCreateAndUpdate() { createDbClusterEchoesRequestedId(); @@ -336,6 +370,25 @@ class RdsCfnProvisionerTest { verify(rdsService, never()).modifyDbCluster(any(), any(), any(), any(), any(), any(), any()); } + @Test + void anUpdateWindowOverlappingTheStoredOneFailsBeforeTheClusterIsModified() { + DbCluster existing = mock(DbCluster.class); + when(existing.getDbClusterIdentifier()).thenReturn("mycluster"); + when(existing.getPreferredMaintenanceWindow()).thenReturn("mon:05:00-mon:06:00"); + when(rdsService.getDbCluster("mycluster")).thenReturn(existing); + when(rdsService.modifyDbCluster(eq("mycluster"), any(), any(), any(), any(), any(), any())).thenReturn(existing); + + StackResource r = provisionExisting("Cluster", "AWS::RDS::DBCluster", """ + {"DBClusterIdentifier":"mycluster","Engine":"aurora-postgresql","MasterUserPassword":"changed", + "PreferredBackupWindow":"05:00-06:00"} + """, "us-east-1", "mycluster", Map.of("DBClusterIdentifier", "mycluster")); + + assertEquals("CREATE_FAILED", r.getStatus()); + assertTrue(r.getStatusReason().contains("must not overlap"), r.getStatusReason()); + verify(rdsService, never()).modifyDbCluster(any(), any(), any(), any(), any(), any(), any()); + verify(rdsService, never()).setDbClusterRequestSettings(any(), any(), any(), any(), any()); + } + @Test void dbClusterEnableHttpEndpointOnANonAuroraEngineFailsBeforeCreating() { StackResource r = provision("Cluster", "AWS::RDS::DBCluster", """ diff --git a/src/test/java/io/floci/aws/services/rds/RdsClusterVpcSecurityGroupsIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsClusterVpcSecurityGroupsIntegrationTest.java new file mode 100644 index 0000000000..1ae237bf8f --- /dev/null +++ b/src/test/java/io/floci/aws/services/rds/RdsClusterVpcSecurityGroupsIntegrationTest.java @@ -0,0 +1,309 @@ +package io.floci.aws.services.rds; + +import io.floci.aws.core.common.BackupWindows; +import io.floci.aws.testing.RdsMockProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.w3c.dom.NodeList; + +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; + +import static io.floci.aws.testing.RdsRequests.createAuroraPostgresCluster; +import static io.floci.aws.testing.RdsRequests.rds; +import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * VpcSecurityGroupIds, PreferredBackupWindow and PreferredMaintenanceWindow given to CreateDBCluster + * and ModifyDBCluster are stored on the cluster and read back through DescribeDBClusters, instead of a + * fixed sg-00000000 membership and fixed windows, and a request refused for a malformed value changes + * nothing. + */ +@QuarkusTest +@TestProfile(RdsMockProfile.class) +class RdsClusterVpcSecurityGroupsIntegrationTest { + + private static final String ID = "vpc-sg-cluster-" + System.nanoTime(); + + private static List groupIds(String xml) { + try { + NodeList nodes = DocumentBuilderFactory.newInstance().newDocumentBuilder() + .parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))) + .getElementsByTagName("VpcSecurityGroupId"); + List ids = new ArrayList<>(); + for (int i = 0; i < nodes.getLength(); i++) { + ids.add(nodes.item(i).getTextContent()); + } + return ids; + } catch (Exception e) { + throw new IllegalStateException("unparseable RDS response: " + xml, e); + } + } + + private static List describedGroupIds() { + return groupIds(rds("DescribeDBClusters").formParam("DBClusterIdentifier", ID) + .when().post("/").then().statusCode(200).extract().asString()); + } + + @AfterEach + void cleanUp() { + rds("DeleteDBCluster").formParam("DBClusterIdentifier", ID) + .formParam("SkipFinalSnapshot", "true").when().post("/"); + // after the cluster, which may reference it; absent in most tests + rds("DeleteDBClusterParameterGroup").formParam("DBClusterParameterGroupName", "pg-rejected") + .when().post("/"); + } + + @Test + void createStoresRequestedGroupsAndModifyReplacesThem() { + String created = createAuroraPostgresCluster(ID) + .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.1", "sg-abcdef01") + .when().post("/").then().statusCode(200).extract().asString(); + assertEquals(List.of("sg-abcdef01"), groupIds(created)); + assertEquals(List.of("sg-abcdef01"), describedGroupIds()); + + rds("ModifyDBCluster") + .formParam("DBClusterIdentifier", ID) + .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.1", "sg-11111111") + .formParam("VpcSecurityGroupIds.VpcSecurityGroupId.2", "sg-22222222") + .when().post("/").then().statusCode(200); + assertEquals(List.of("sg-11111111", "sg-22222222"), 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()); + } + + @Test + void omittedGroupsDefaultToTheVpcsDefaultSecurityGroup() { + String created = createAuroraPostgresCluster(ID).when().post("/").then().statusCode(200).extract().asString(); + List groups = describedGroupIds(); + assertEquals(1, groups.size()); + assertNotEquals("sg-00000000", groups.get(0)); + assertTrue(groups.get(0).startsWith("sg-")); + assertEquals(groups, groupIds(created)); + } + + @ParameterizedTest + @ValueSource(strings = {"snapshot", "pitr"}) + void restoredClusterHoldsRequestedOrDefaultGroupsAndModifyLeavesThem(String path) { + String restored = ID + "-restored"; + String snapshot = ID + "-snap"; + try { + createAuroraPostgresCluster(ID).when().post("/").then().statusCode(200); + rds("CreateDBClusterSnapshot").formParam("DBClusterIdentifier", ID) + .formParam("DBClusterSnapshotIdentifier", snapshot).post("/").then().statusCode(200); + for (String group : new String[] {null, "sg-abcdef01"}) { + RequestSpecification restore = "snapshot".equals(path) + ? rds("RestoreDBClusterFromSnapshot").formParam("SnapshotIdentifier", snapshot) + .formParam("Engine", "aurora-postgresql") + : rds("RestoreDBClusterToPointInTime").formParam("SourceDBClusterIdentifier", ID) + .formParam("UseLatestRestorableTime", "true"); + restore.formParam("DBClusterIdentifier", restored); + if (group != null) { + restore.formParam("VpcSecurityGroupIds.VpcSecurityGroupId.1", group); + } + List reported = groupIds(restore.post("/").then().statusCode(200).extract().asString()); + if (group != null) { + assertEquals(List.of(group), reported); + } else { + assertEquals(1, reported.size()); + assertNotEquals("sg-00000000", reported.get(0)); + } + rds("ModifyDBCluster").formParam("DBClusterIdentifier", restored) + .formParam("EnableIAMDatabaseAuthentication", "true").post("/").then().statusCode(200); + assertEquals(reported, groupIds(rds("DescribeDBClusters") + .formParam("DBClusterIdentifier", restored).post("/").then().statusCode(200) + .extract().asString())); + rds("DeleteDBCluster").formParam("DBClusterIdentifier", restored) + .formParam("SkipFinalSnapshot", "true").post("/"); + } + } finally { + rds("DeleteDBCluster").formParam("DBClusterIdentifier", restored) + .formParam("SkipFinalSnapshot", "true").post("/"); + rds("DeleteDBClusterSnapshot").formParam("DBClusterSnapshotIdentifier", snapshot).post("/"); + } + } + + @Test + void maintenanceWindowDayNamesReadBackLowerCase() { + String created = createAuroraPostgresCluster(ID) + .formParam("PreferredMaintenanceWindow", "Mon:00:00-Mon:03:00") + .when().post("/").then().statusCode(200).extract().asString(); + assertEquals(true, created.contains("mon:00:00-mon:03:00<")); + assertEquals("mon:00:00-mon:03:00", described("PreferredMaintenanceWindow")); + + rds("ModifyDBCluster").formParam("DBClusterIdentifier", ID) + .formParam("PreferredMaintenanceWindow", "TUE:07:00-Tue:08:00") + .when().post("/").then().statusCode(200); + assertEquals("tue:07:00-tue:08:00", described("PreferredMaintenanceWindow")); + } + + @Test + void modifyOfAMissingClusterIsDbClusterNotFound() { + rds("ModifyDBCluster").formParam("DBClusterIdentifier", "no-such-cluster") + .when().post("/").then().statusCode(404) + .body(containsString("DBClusterNotFoundFault")) + .body(containsString("DBCluster not found")); + } + + private static String described(String tag) { + String xml = rds("DescribeDBClusters").formParam("DBClusterIdentifier", ID) + .when().post("/").then().statusCode(200).extract().asString(); + try { + return DocumentBuilderFactory.newInstance().newDocumentBuilder() + .parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))) + .getElementsByTagName(tag).item(0).getTextContent(); + } catch (Exception e) { + throw new IllegalStateException("no " + tag + " in RDS response: " + xml, e); + } + } + + @Test + void windowsAreStoredAndDefaulted() { + createAuroraPostgresCluster(ID).when().post("/").then().statusCode(200); + assertEquals("mon:00:00-mon:03:00", described("PreferredMaintenanceWindow")); + assertEquals("04:00-06:00", described("PreferredBackupWindow")); + rds("DeleteDBCluster").formParam("DBClusterIdentifier", ID) + .formParam("SkipFinalSnapshot", "true").when().post("/"); + + String created = createAuroraPostgresCluster(ID) + .formParam("PreferredBackupWindow", "05:00-06:00") + .formParam("PreferredMaintenanceWindow", "tue:07:00-tue:08:00") + .when().post("/").then().statusCode(200).extract().asString(); + assertEquals(true, created.contains("05:00-06:00")); + assertEquals("05:00-06:00", described("PreferredBackupWindow")); + assertEquals("tue:07:00-tue:08:00", described("PreferredMaintenanceWindow")); + + rds("ModifyDBCluster").formParam("DBClusterIdentifier", ID) + .formParam("PreferredBackupWindow", "03:00-04:00") + .when().post("/").then().statusCode(200); + assertEquals("03:00-04:00", described("PreferredBackupWindow")); + assertEquals("tue:07:00-tue:08:00", described("PreferredMaintenanceWindow")); + } + + private static int clusterCount() { + return rds("DescribeDBClusters").when().post("/").then().statusCode(200).extract().asString() + .split("" + ID + "", -1).length - 1; + } + + @Test + void invalidWindowsAreRefusedAndLeaveNoClusterBehind() { + createAuroraPostgresCluster(ID).formParam("PreferredBackupWindow", "garbage").when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")); + assertEquals(0, clusterCount()); + createAuroraPostgresCluster(ID).formParam("PreferredBackupWindow", "05:00-06:00") + .formParam("PreferredMaintenanceWindow", "mon:05:30-mon:06:30") + .when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")); + assertEquals(0, clusterCount()); + + createAuroraPostgresCluster(ID).formParam("PreferredBackupWindow", "05:00-06:00").when().post("/").then().statusCode(200); + rds("ModifyDBCluster").formParam("DBClusterIdentifier", ID) + .formParam("PreferredBackupWindow", "garbage").when().post("/").then().statusCode(400); + assertEquals("05:00-06:00", described("PreferredBackupWindow")); + } + + private static void assertOverlapRefused(ValidatableResponse r) { + r.statusCode(400).body(containsString("InvalidParameterValue")); + } + + @Test + void windowGivenAloneIsPairedWithAClearOneOnCreateAndRefusedOnModify() { + // default maintenance mon:00:00-mon:03:00 overlaps 01:00-02:00, so a clear one is derived + createAuroraPostgresCluster(ID).formParam("PreferredBackupWindow", "01:00-02:00").when().post("/").then().statusCode(200); + assertEquals("01:00-02:00", described("PreferredBackupWindow")); + String maint = described("PreferredMaintenanceWindow"); + assertEquals(false, BackupWindows.overlap("01:00-02:00", maint), maint); + rds("DeleteDBCluster").formParam("DBClusterIdentifier", ID) + .formParam("SkipFinalSnapshot", "true").when().post("/"); + + // default backup 04:00-06:00 overlaps mon:04:30-mon:05:30 + createAuroraPostgresCluster(ID).formParam("PreferredMaintenanceWindow", "mon:04:30-mon:05:30") + .when().post("/").then().statusCode(200); + String backup = described("PreferredBackupWindow"); + assertEquals(false, BackupWindows.overlap(backup, "mon:04:30-mon:05:30"), backup); + rds("DeleteDBCluster").formParam("DBClusterIdentifier", ID) + .formParam("SkipFinalSnapshot", "true").when().post("/"); + + // never-set windows count as the defaults on modify + createAuroraPostgresCluster(ID).when().post("/").then().statusCode(200); + assertOverlapRefused(rds("ModifyDBCluster").formParam("DBClusterIdentifier", ID) + .formParam("PreferredBackupWindow", "01:00-02:00").when().post("/").then()); + assertOverlapRefused(rds("ModifyDBCluster").formParam("DBClusterIdentifier", ID) + .formParam("PreferredMaintenanceWindow", "mon:04:30-mon:05:30").when().post("/").then()); + assertEquals("04:00-06:00", described("PreferredBackupWindow")); + } + + @Test + void modifyWithABadWindowChangesNothing() { + createAuroraPostgresCluster(ID).when().post("/").then().statusCode(200); + rds("ModifyDBCluster").formParam("DBClusterIdentifier", ID) + .formParam("BackupRetentionPeriod", "9").formParam("PreferredBackupWindow", "garbage") + .when().post("/").then().statusCode(400); + assertEquals("1", described("BackupRetentionPeriod")); + } + + @Test + void createWithMalformedDeletionProtectionLeavesNoClusterBehind() { + createAuroraPostgresCluster(ID).formParam("DeletionProtection", "garbage").when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")); + assertEquals(0, clusterCount()); + } + + @Test + void modifyWithMalformedDeletionProtectionChangesNothing() { + rds("CreateDBClusterParameterGroup").formParam("DBClusterParameterGroupName", "pg-rejected") + .formParam("DBParameterGroupFamily", "aurora-postgresql15").formParam("Description", "d") + .when().post("/").then().statusCode(200); + createAuroraPostgresCluster(ID).formParam("MasterUserPassword", "original-password1") + .formParam("VpcSecurityGroupIds.member.1", "sg-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("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(groupBefore, described("DBClusterParameterGroup")); + } + + @Test + void createWithEmptySecurityGroupMemberLeavesNoClusterBehind() { + createAuroraPostgresCluster(ID).formParam("VpcSecurityGroupIds.member.1", "").when().post("/").then().statusCode(400) + .body(containsString("InvalidParameterValue")); + assertEquals(0, clusterCount()); + } + + @Test + void modifyWithEmptySecurityGroupMemberChangesNothing() { + createAuroraPostgresCluster(ID).formParam("VpcSecurityGroupIds.member.1", "sg-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()); + } +} 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 21ea706802..37e0865c31 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsQueryHandlerTest.java @@ -68,6 +68,9 @@ class RdsQueryHandlerTest { @BeforeEach void setUp() { service = mock(RdsService.class); + when(service.getDbCluster(any(), any())).thenAnswer(inv -> makeCluster(inv.getArgument(0))); + when(service.setDbClusterRequestSettings(any(), any(), any(), any(), any())) + .thenAnswer(inv -> makeCluster(inv.getArgument(0))); when(service.instanceCertificate(any())).thenReturn( new RdsService.InstanceCertificate("rds-ca-rsa2048-g1", Instant.parse("2061-05-25T23:34:57Z"))); EmulatorConfig config = mock(EmulatorConfig.class); @@ -912,7 +915,7 @@ class RdsQueryHandlerTest { any(DbInstanceSettings.class), isNull(), any(DbInstanceScalingChanges.class), isNull(), isNull()); verify(service).rebootDbInstance("mydb", "us-west-2"); verify(service).listDbClusters(null, "us-west-2"); - verify(service).getDbCluster("mycluster", "us-west-2"); + verify(service, times(2)).getDbCluster("mycluster", "us-west-2"); verify(service).deleteDbCluster("mycluster", "us-west-2", true); verify(service).modifyDbCluster("mycluster", null, null, null, null, null, null, null, null, false, false, "us-west-2"); @@ -924,6 +927,7 @@ class RdsQueryHandlerTest { cluster.setMasterUserSecretArn("arn:aws:secretsmanager:us-east-1:000000000000:secret:rds!cluster-ABC"); cluster.setMasterUserSecretStatus("active"); cluster.setMasterUserSecretKmsKeyId("kms-key-1"); + when(service.setDbClusterRequestSettings(any(), any(), any(), any(), any())).thenReturn(cluster); when(service.createDbCluster(eq("mycluster"), eq("aurora-postgresql"), any(), eq("omni_admin"), isNull(), eq("omni"), eq(false), isNull(), isNull(), isNull(), eq(false), any(), @@ -1032,6 +1036,7 @@ class RdsQueryHandlerTest { @CsvSource({"true,true", "true,false", "false,true", "false,false"}) void modifyDbClusterForwardsRotationAndApplyImmediately(boolean rotatePassword, boolean applyImmediately) { DbCluster cluster = makeCluster("mycluster"); + when(service.setDbClusterRequestSettings(any(), any(), any(), any(), any())).thenReturn(cluster); when(service.modifyDbCluster("mycluster", null, null, null, null, null, null, null, null, rotatePassword, applyImmediately, "us-west-2")).thenReturn(cluster); MultivaluedMap p = params(); 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 4818649651..c1f3d5421a 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsServiceTest.java @@ -1791,6 +1791,43 @@ class RdsServiceTest { .getVpcSecurityGroupIds()); } + @Test + void clusterCreatedWithNoGroupsGetsTheVpcDefaultAndModifyOnlyStoresWhatItNames() { + SecurityGroup defaultGroup = new SecurityGroup(); + defaultGroup.setGroupId("sg-default"); + when(ec2Service.defaultSecurityGroupOf(eq("us-east-1"), any())).thenReturn(Optional.of(defaultGroup)); + DbCluster created = rdsService.createDbCluster("sg-cluster", "aurora-postgresql", null, + "admin", "password", "dbname", false, null); + assertEquals(List.of("sg-default"), created.getVpcSecurityGroupIds()); + + // an unrelated Modify leaves a null-groups request alone + assertEquals(List.of("sg-default"), rdsService.setDbClusterRequestSettings( + "sg-cluster", "us-east-1", null, null, null).getVpcSecurityGroupIds()); + rdsService.setDbClusterRequestSettings("sg-cluster", "us-east-1", List.of(), null, null); + assertEquals(List.of(), rdsService.getDbCluster("sg-cluster").getVpcSecurityGroupIds()); + // ... and does not re-assign the default to a cluster stored with no groups + rdsService.setDbClusterRequestSettings("sg-cluster", "us-east-1", null, null, null); + assertEquals(List.of(), rdsService.getDbCluster("sg-cluster").getVpcSecurityGroupIds()); + } + + @Test + void restoredAndGlobalMemberClustersGetTheVpcDefaultGroup() { + SecurityGroup defaultGroup = new SecurityGroup(); + defaultGroup.setGroupId("sg-default"); + when(ec2Service.defaultSecurityGroupOf(eq("us-east-1"), any())).thenReturn(Optional.of(defaultGroup)); + + clusterSnapshotOfNewCluster("csnap"); + assertEquals(List.of("sg-default"), rdsService.restoreDbClusterFromSnapshot("restored-sg", "csnap", + "aurora-postgresql", null, null, null, null, null, null, null, null, false, null, "us-east-1") + .getVpcSecurityGroupIds()); + + rdsService.createGlobalCluster("sg-global", null, "aurora-postgresql", "16.3", + "dbname", false, false, Map.of(), "us-east-1"); + assertEquals(List.of("sg-default"), rdsService.createDbClusterInGlobalCluster("sg-global", "global-member", + "aurora-postgresql", null, "admin", "password", "dbname", false, null, null, null, false, + "us-east-1", null, null, null, false, null, null, false).getVpcSecurityGroupIds()); + } + @Test void createAndModifyDbInstancePersistPubliclyAccessible() { DbInstance instance = rdsService.createDbInstance("pubdb", "postgres", "13", diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index 4e6ab2326e..b65dc1bffe 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -463,13 +463,10 @@ AWS::RDS::DBCluster PerformanceInsightsEnabled accepted and ignored AWS::RDS::DBCluster PerformanceInsightsKmsKeyId accepted and ignored AWS::RDS::DBCluster PerformanceInsightsRetentionPeriod accepted and ignored AWS::RDS::DBCluster Port accepted and ignored -AWS::RDS::DBCluster PreferredBackupWindow accepted and ignored -AWS::RDS::DBCluster PreferredMaintenanceWindow accepted and ignored AWS::RDS::DBCluster ReplicationSourceIdentifier accepted and ignored AWS::RDS::DBCluster ScalingConfiguration accepted and ignored AWS::RDS::DBCluster StorageType accepted and ignored AWS::RDS::DBCluster Tags accepted and ignored -AWS::RDS::DBCluster VpcSecurityGroupIds accepted and ignored AWS::RDS::DBCluster WithExpressConfiguration accepted and ignored AWS::RDS::DBClusterParameterGroup Parameters accepted and ignored AWS::RDS::DBClusterParameterGroup Tags accepted and ignored