fix(redshift): refuse deleting the default parameter group, and a parameter or subnet group a cluster uses (#9233)

This commit is contained in:
mrfelek authored and GitHub committed 2026-11-23 06:40:42 -04:00
1 parent 29e262e783
commit 272f3f8435
5 files changed
+262 -10

No files matched your search

@@ -115,6 +115,12 @@ public class RedshiftQueryHandler {
String region = regionResolver.resolveRegionFromAuth(authorizationHeader);
String defaultIamRoleArn = params.getFirst("DefaultIamRoleArn");
Integer automatedRetention = parseOptionalInteger(params, "AutomatedSnapshotRetentionPeriod");
String parameterGroupName = params.getFirst("ClusterParameterGroupName");
boolean hasParameterGroup = parameterGroupName != null && !parameterGroupName.isBlank();
if (hasParameterGroup) {
// Refused before the cluster is created, as Redshift refuses a CreateCluster naming no group.
service.describeClusterParameterGroups(parameterGroupName);
}
Cluster cluster;
if (manageMasterPassword) {
cluster = automatedRetention == null
@@ -131,12 +137,20 @@ public class RedshiftQueryHandler {
: service.createCluster(identifier, nodeType, masterUsername, masterUserPassword,
clusterSubnetGroupName, vpcSecurityGroupIds, iamRoleArns, defaultIamRoleArn, automatedRetention);
}
String parameterGroupName = params.getFirst("ClusterParameterGroupName");
String multiAz = params.getFirst("MultiAZ");
boolean hasParameterGroup = parameterGroupName != null && !parameterGroupName.isBlank();
if (hasParameterGroup || multiAz != null) {
cluster = service.modifyCluster(identifier, null, null, null, parameterGroupName, null,
multiAz == null ? null : Boolean.parseBoolean(multiAz));
try {
cluster = service.modifyCluster(identifier, null, null, null, parameterGroupName, null,
multiAz == null ? null : Boolean.parseBoolean(multiAz));
} catch (AwsException refused) {
// The group was deleted after the check above: the create fails as a whole, leaving no cluster.
try {
service.deleteCluster(identifier);
} catch (RuntimeException cleanupFailure) {
refused.addSuppressed(cleanupFailure);
}
throw refused;
}
}
String xml = new XmlBuilder()
.start("CreateClusterResponse")
@@ -1388,9 +1388,12 @@ public class RedshiftService implements ManagedSecretRotator {
rejectPausedCluster(cluster);
validateAutomatedRetention(nodeType == null ? cluster.getNodeType() : nodeType,
automatedRetention == null ? cluster.getAutomatedSnapshotRetentionPeriod() : automatedRetention);
boolean parameterGroupChanged = clusterParameterGroupName != null && !clusterParameterGroupName.isBlank();
if (parameterGroupChanged) {
requireParameterGroup(clusterParameterGroupName);
}
boolean passwordChanged = masterUserPassword != null && !masterUserPassword.isBlank();
boolean parameterGroupChanged = clusterParameterGroupName != null && !clusterParameterGroupName.isBlank();
boolean securityGroupsChanged = vpcSecurityGroupIds != null && !vpcSecurityGroupIds.isEmpty();
// alterUserPassword runs before any mutation of the cluster object (a live reference
// from HybridStorage, not a copy); if it throws, no metadata has been changed yet.
@@ -1410,7 +1413,7 @@ public class RedshiftService implements ManagedSecretRotator {
if (nodeType != null && !nodeType.isBlank()) {
cluster.setNodeType(nodeType);
}
if (clusterParameterGroupName != null && !clusterParameterGroupName.isBlank()) {
if (parameterGroupChanged) {
cluster.setClusterParameterGroupName(clusterParameterGroupName);
cluster.setUserActivityLoggingEnabled(userActivityLoggingEnabled(clusterParameterGroupName));
}
@@ -2740,7 +2743,16 @@ public class RedshiftService implements ManagedSecretRotator {
Cluster cluster = restoreSnapshot(clusterIdentifier, snapshotIdentifier, null, nodeType,
clusters.accountId());
try {
cluster.setClusterSubnetGroupName(clusterSubnetGroupName);
// Under the lock the subnet group's delete takes, so the group is either refused here or
// seen by the delete's in-use check once the cluster is stored with it.
mutate(() -> {
if (clusterSubnetGroupName != null && !clusterSubnetGroupName.isBlank()) {
requireSubnetGroup(clusterSubnetGroupName);
}
cluster.setClusterSubnetGroupName(clusterSubnetGroupName);
storeCluster(cluster);
return cluster;
});
if (manageMasterPassword) {
String password = RandomPasswordGenerator.generate(objectMapper.createObjectNode());
modifyCluster(clusterIdentifier, null, null, password, null, List.of());
@@ -3072,6 +3084,24 @@ public class RedshiftService implements ManagedSecretRotator {
}
}
/**
* Refuses a parameter group name this Region holds no group of, as Redshift refuses a cluster naming one; the
* default group, which Describe lists, is always there. Callers check under {@link #mutate}, the lock the
* group's delete takes, so a group deleted meanwhile is either refused here or kept by the delete's in-use check.
*/
private void requireParameterGroup(String name) {
if (!DEFAULT_PARAMETER_GROUP_NAME.equals(name) && parameterGroups.get(regionalKey(name)).isEmpty()) {
throw new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group " + name + " not found", 404);
}
}
/** As {@link #requireParameterGroup}, for a subnet group. */
private void requireSubnetGroup(String name) {
if (subnetGroups.get(regionalKey(name)).isEmpty()) {
throw new AwsException("ClusterSubnetGroupNotFoundFault", "Cluster subnet group " + name + " not found", 400);
}
}
private void requireMutableParameterGroup(String name) {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidParameterValue", "ParameterGroupName is required", 400);
@@ -3101,9 +3131,21 @@ public class RedshiftService implements ManagedSecretRotator {
// resetClusterParameterGroup hold from their read to their write, so a delete can't land in between and be
// undone by their write; the event is emitted after it.
ClusterParameterGroup group = mutate(() -> {
ClusterParameterGroup found = parameterGroups.get(regionalKey(parameterGroupName))
.orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound",
"Cluster parameter group " + parameterGroupName + " not found", 404));
// As Redshift answers (measured on AWS): the default group, which is answered for without being stored,
// can't be deleted (a custom group an older Floci stored under its name stays deletable, as it stays
// modifiable), and a group a cluster of the Region still uses is refused, checked under the lock cluster
// changes hold too.
Optional<ClusterParameterGroup> stored = parameterGroups.get(regionalKey(parameterGroupName));
if (stored.isEmpty() && DEFAULT_PARAMETER_GROUP_NAME.equals(parameterGroupName)) {
throw new AwsException("InvalidParameterValue",
"The Cluster Parameter Group cannot be deleted: " + parameterGroupName, 400);
}
ClusterParameterGroup found = stored.orElseThrow(() -> new AwsException("ClusterParameterGroupNotFound",
"Cluster parameter group " + parameterGroupName + " not found", 404));
if (regionalClusters().stream().anyMatch(c -> parameterGroupName.equals(c.getClusterParameterGroupName()))) {
throw new AwsException("InvalidClusterParameterGroupState", "One or more Clusters are still members of "
+ "this parameter group " + parameterGroupName + ", so the group cannot be deleted", 400);
}
parameterGroups.delete(regionalKey(parameterGroupName));
parameterGroups.flush();
return found;
@@ -3272,6 +3314,13 @@ public class RedshiftService implements ManagedSecretRotator {
ClusterSubnetGroup group = subnetGroups.get(regionalKey(name))
.orElseThrow(() -> new AwsException("ClusterSubnetGroupNotFoundFault",
"Cluster subnet group " + name + " not found", 400));
// A group a cluster of the Region still uses is refused, naming one such cluster, as Redshift answers
// (measured on AWS).
regionalClusters().stream().filter(c -> name.equals(c.getClusterSubnetGroupName()))
.map(Cluster::getClusterIdentifier).sorted().findFirst().ifPresent(cluster -> {
throw new AwsException("InvalidClusterSubnetGroupStateFault", "Cannot delete the subnet group '"
+ name + "' because at least one Cluster: " + cluster + " is still using it.", 400);
});
subnetGroups.delete(regionalKey(name));
subnetGroups.flush();
return group;
@@ -1155,6 +1155,18 @@ public class RedshiftOperationsTest {
return redshiftIn("us-east-1", action, keyValues);
}
/** DeleteClusterParameterGroup refuses the default group with Redshift's fault and message (measured on AWS). */
@Test
void theDefaultParameterGroupCannotBeDeleted() {
Response response = redshift("DeleteClusterParameterGroup", "ParameterGroupName", "default.redshift-1.0");
assertFault(response, 400, "InvalidParameterValue");
assertEquals("The Cluster Parameter Group cannot be deleted: default.redshift-1.0",
XmlPath.from(response.asString()).getString("ErrorResponse.Error.Message"));
assertEquals(200, redshift("DescribeClusterParameterGroups", "ParameterGroupName", "default.redshift-1.0")
.statusCode());
}
private static void assertFault(Response response, int status, String code) {
assertEquals(status, response.statusCode(), response.asString());
assertEquals(code, XmlPath.from(response.asString()).getString("ErrorResponse.Error.Code"));
@@ -400,6 +400,41 @@ class RedshiftQueryHandlerTest {
assertTrue(xml.contains("<RequestId>test-req-id</RequestId>"));
}
@Test
void createClusterNamingAParameterGroupThatDoesNotExistIsRefusedBeforeAClusterIsCreated() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
params.putSingle("NodeType", "dc2.large");
params.putSingle("MasterUsername", "admin");
params.putSingle("MasterUserPassword", "pw");
params.putSingle("ClusterParameterGroupName", "missing-pg");
when(service.describeClusterParameterGroups("missing-pg")).thenThrow(
new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group missing-pg not found", 404));
AwsException refused = assertThrows(AwsException.class, () -> handler.handle("CreateCluster", params));
assertEquals("ClusterParameterGroupNotFound", refused.getErrorCode());
verify(service, never()).createCluster(any(), any(), any(), any(), any(), any(), any(), any());
}
@Test
void createClusterWhoseParameterGroupIsDeletedBeforeItIsAppliedLeavesNoCluster() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.putSingle("ClusterIdentifier", "c1");
params.putSingle("NodeType", "dc2.large");
params.putSingle("MasterUsername", "admin");
params.putSingle("MasterUserPassword", "pw");
params.putSingle("ClusterParameterGroupName", "custom-pg");
when(service.createCluster(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(new Cluster());
when(service.modifyCluster("c1", null, null, null, "custom-pg", null, null)).thenThrow(
new AwsException("ClusterParameterGroupNotFound", "Cluster parameter group custom-pg not found", 404));
AwsException refused = assertThrows(AwsException.class, () -> handler.handle("CreateCluster", params));
assertEquals("ClusterParameterGroupNotFound", refused.getErrorCode());
verify(service).deleteCluster("c1");
}
@Test
void createClusterWithManagedMasterPasswordUsesSecretsManagerSecret() {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
@@ -590,6 +590,70 @@ class RedshiftServiceTest {
verify(snapshotScheduleBackend, never()).delete(RedshiftService.regionalKey("eu-west-1", "nightly"));
}
/** The default parameter group, which is answered for without being stored, can't be deleted, as on Redshift. */
@Test
void theDefaultParameterGroupIsNotDeleted() {
AwsException refused = assertThrows(AwsException.class,
() -> service.deleteClusterParameterGroup("default.redshift-1.0"));
assertEquals("InvalidParameterValue", refused.getErrorCode());
assertEquals("The Cluster Parameter Group cannot be deleted: default.redshift-1.0", refused.getMessage());
assertEquals(400, refused.getHttpStatus());
verify(parameterGroupBackend, never()).delete(any());
}
/**
* A parameter group a cluster of its Region uses is not deleted, with Redshift's fault; a cluster of another
* Region, which uses that Region's group of the same name, doesn't keep it.
*/
@Test
void aParameterGroupAClusterOfItsRegionUsesIsNotDeleted() {
Cluster west = storedCluster("west", "eu-west-1");
west.setClusterParameterGroupName("etl");
when(clusterBackend.scan(any())).thenReturn(List.of(west));
ClusterParameterGroup group = new ClusterParameterGroup("etl", "redshift-1.0", "etl");
when(parameterGroupBackend.get(regionalKey("etl"))).thenReturn(Optional.of(group));
when(parameterGroupBackend.get(RedshiftService.regionalKey("eu-west-1", "etl"))).thenReturn(Optional.of(group));
RedshiftService westService = serviceIn("eu-west-1");
AwsException refused = assertThrows(AwsException.class, () -> westService.deleteClusterParameterGroup("etl"));
assertEquals("InvalidClusterParameterGroupState", refused.getErrorCode());
assertEquals("One or more Clusters are still members of this parameter group etl, so the group cannot be deleted",
refused.getMessage());
assertEquals(400, refused.getHttpStatus());
verify(parameterGroupBackend, never()).delete(RedshiftService.regionalKey("eu-west-1", "etl"));
service.deleteClusterParameterGroup("etl");
verify(parameterGroupBackend).delete(regionalKey("etl"));
}
/**
* A subnet group a cluster of its Region uses is not deleted, with Redshift's fault naming one such cluster; a
* cluster of another Region doesn't keep it.
*/
@Test
void aSubnetGroupAClusterOfItsRegionUsesIsNotDeleted() {
Cluster second = storedCluster("west-b", "eu-west-1");
second.setClusterSubnetGroupName("private");
Cluster first = storedCluster("west-a", "eu-west-1");
first.setClusterSubnetGroupName("private");
when(clusterBackend.scan(any())).thenReturn(List.of(second, first));
ClusterSubnetGroup group = new ClusterSubnetGroup("private", "d", "vpc-1", List.of("subnet-1"));
when(subnetGroupBackend.get(regionalKey("private"))).thenReturn(Optional.of(group));
when(subnetGroupBackend.get(RedshiftService.regionalKey("eu-west-1", "private"))).thenReturn(Optional.of(group));
RedshiftService westService = serviceIn("eu-west-1");
AwsException refused = assertThrows(AwsException.class, () -> westService.deleteClusterSubnetGroup("private"));
assertEquals("InvalidClusterSubnetGroupStateFault", refused.getErrorCode());
assertEquals("Cannot delete the subnet group 'private' because at least one Cluster: west-a is still using it.",
refused.getMessage());
assertEquals(400, refused.getHttpStatus());
verify(subnetGroupBackend, never()).delete(RedshiftService.regionalKey("eu-west-1", "private"));
service.deleteClusterSubnetGroup("private");
verify(subnetGroupBackend).delete(regionalKey("private"));
}
@Test
void recoveryProxyFailureDoesNotDestructivelyStopAnAdoptedContainer() {
Cluster cluster = new Cluster();
@@ -1654,6 +1718,8 @@ class RedshiftServiceTest {
Cluster cluster = service.createCluster("event-cluster", "dc2.large", "admin", "password123");
when(clusterBackend.get("event-cluster")).thenReturn(Optional.of(cluster));
when(parameterGroupBackend.get(regionalKey("custom-pg")))
.thenReturn(Optional.of(new ClusterParameterGroup("custom-pg", "redshift-1.0", "custom pg")));
service.modifyCluster("event-cluster", null, null, "changedPassword123", "custom-pg", List.of("sg-new"));
service.rebootCluster("event-cluster");
service.deleteCluster("event-cluster");
@@ -2953,6 +3019,8 @@ class RedshiftServiceTest {
cluster.setClusterIdentifier("my-cluster");
cluster.setMasterUsername("admin");
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
when(parameterGroupBackend.get(regionalKey("custom-pg")))
.thenReturn(Optional.of(new ClusterParameterGroup("custom-pg", "redshift-1.0", "custom pg")));
Cluster updated = service.modifyCluster("my-cluster", null, null, null, "custom-pg", List.of("sg-9"));
@@ -2961,6 +3029,59 @@ class RedshiftServiceTest {
verify(cm, never()).alterUserPassword(any(), any(), any(), any());
}
@Test
void modifyClusterRefusesAParameterGroupThatDoesNotExist() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
cluster.setMasterUsername("admin");
cluster.setClusterParameterGroupName("default.redshift-1.0");
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
when(parameterGroupBackend.get(regionalKey("deleted-pg"))).thenReturn(Optional.empty());
AwsException refused = assertThrows(AwsException.class,
() -> service.modifyCluster("my-cluster", null, null, null, "deleted-pg", null));
assertEquals("ClusterParameterGroupNotFound", refused.getErrorCode());
assertEquals("Cluster parameter group deleted-pg not found", refused.getMessage());
assertEquals("default.redshift-1.0", cluster.getClusterParameterGroupName());
verify(clusterBackend, never()).put(eq("my-cluster"), any(Cluster.class));
}
@Test
void modifyClusterRefusingAParameterGroupLeavesThePasswordAndNodeTypeUntouched() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
cluster.setNodeType("dc2.large");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("old-pw");
cluster.setClusterParameterGroupName("default.redshift-1.0");
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
when(parameterGroupBackend.get(regionalKey("deleted-pg"))).thenReturn(Optional.empty());
AwsException refused = assertThrows(AwsException.class,
() -> service.modifyCluster("my-cluster", "ra3.xlplus", null, "new-pw", "deleted-pg", null));
assertEquals("ClusterParameterGroupNotFound", refused.getErrorCode());
assertEquals("old-pw", cluster.getMasterPassword());
assertEquals("dc2.large", cluster.getNodeType());
verify(cm, never()).alterUserPassword(any(), any(), any(), any());
verify(proxyManager, never()).updateMasterPassword(any(), any());
verify(clusterBackend, never()).put(eq("my-cluster"), any(Cluster.class));
}
@Test
void modifyClusterTakesTheDefaultParameterGroup() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("my-cluster");
cluster.setMasterUsername("admin");
cluster.setClusterParameterGroupName("custom-pg");
when(clusterBackend.get("my-cluster")).thenReturn(Optional.of(cluster));
Cluster updated = service.modifyCluster("my-cluster", null, null, null, "default.redshift-1.0", null);
assertEquals("default.redshift-1.0", updated.getClusterParameterGroupName());
}
@Test
void modifyClusterNotFound() {
when(clusterBackend.get("missing")).thenReturn(Optional.empty());
@@ -3524,6 +3645,9 @@ class RedshiftServiceTest {
when(secretsManagerService.createSecret(eq("redshift/restored-managed"), anyString(), isNull(),
anyString(), eq("alias/restore-key"), anyList(), eq("redshift"), eq("us-east-1"))).thenReturn(secret);
when(subnetGroupBackend.get(regionalKey("restore-subnets"))).thenReturn(Optional.of(
new ClusterSubnetGroup("restore-subnets", "d", "vpc-1", List.of("subnet-1"))));
Cluster cluster = service.restoreFromClusterSnapshot("restored-managed", "managed-backup", "ra3.large",
"restore-subnets", true, "alias/restore-key", "us-east-1");
@@ -3537,6 +3661,24 @@ class RedshiftServiceTest {
verify(cm).alterUserPassword("111111111111", "restored-managed", "admin", cluster.getMasterPassword());
}
@Test
void snapshotRestoreRefusesASubnetGroupThatDoesNotExistAndLeavesNoCluster() {
useStatefulClusterStorage();
Snapshot snapshot = new Snapshot("backup", "deleted-source", "available", 5439, "admin");
snapshot.setMasterPassword("Original123");
when(snapshotBackend.get("backup")).thenReturn(Optional.of(snapshot));
when(cm.start("111111111111", "restored", "admin", "Original123"))
.thenReturn(new RedshiftContainerHandle("restored", "restored", "localhost", 5432));
when(subnetGroupBackend.get(regionalKey("deleted-subnets"))).thenReturn(Optional.empty());
AwsException refused = assertThrows(AwsException.class, () -> service.restoreFromClusterSnapshot("restored",
"backup", "ra3.large", "deleted-subnets", false, null, "us-east-1"));
assertEquals("ClusterSubnetGroupNotFoundFault", refused.getErrorCode());
assertTrue(service.describeClusters(null).isEmpty());
assertTrue(service.getSnapshot("backup").isPresent());
}
@Test
void managedSnapshotRestoreCleansUpWhenSecretCreationFails() {
useStatefulClusterStorage();