fix(rds): persist DB cluster DeletionProtection and refuse to delete a protected cluster (#8985)

This commit is contained in:
rajp33 authored and GitHub committed 2026-11-19 19:53:59 -04:00
1 parent fca7dfdd22
commit 30503c4c2e
14 files changed
+346 -77

No files matched your search

@@ -0,0 +1,14 @@
variable "deletion_protection" {
type = bool
default = true
}
resource "aws_rds_cluster" "protected" {
cluster_identifier = "floci-rds-cluster-deletion-protection"
engine = "aurora-postgresql"
engine_version = "16.3"
master_username = "app"
master_password = "changeme123!"
skip_final_snapshot = true
deletion_protection = var.deletion_protection
}
@@ -0,0 +1,27 @@
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.0"
}
}
}
variable "endpoint" {
type = string
default = "http://localhost:4566"
}
provider "aws" {
region = "us-east-1"
access_key = "test"
secret_key = "test"
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
endpoints {
rds = var.endpoint
}
}
@@ -0,0 +1,78 @@
#!/usr/bin/env bats
setup_file() {
load 'test_helper/common-setup'
DP_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/rds-cluster-deletion-protection-tf" && pwd)"
cd "$DP_TF_DIR"
echo "# === RDS Cluster Deletion Protection Test ===" >&3
echo "# Endpoint: $FLOCI_ENDPOINT" >&3
echo "# Config: $DP_TF_DIR" >&3
rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true
echo "# --- terraform init ---" >&3
run terraform init -input=false -no-color
if [ "$status" -ne 0 ]; then
echo "# terraform init failed: $output" >&3
return 1
fi
echo "# --- terraform apply ---" >&3
run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color
if [ "$status" -ne 0 ]; then
echo "# terraform apply failed: $output" >&3
return 1
fi
}
teardown_file() {
load 'test_helper/common-setup'
DP_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/rds-cluster-deletion-protection-tf" && pwd)"
cd "$DP_TF_DIR"
terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -var="deletion_protection=false" \
-input=false -auto-approve -no-color || true
terraform destroy -var="endpoint=${FLOCI_ENDPOINT}" -var="deletion_protection=false" \
-input=false -auto-approve -no-color || true
rm -rf .terraform .terraform.lock.hcl terraform.tfstate* 2>/dev/null || true
}
setup() {
load 'test_helper/common-setup'
DP_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/rds-cluster-deletion-protection-tf" && pwd)"
}
@test "RDS cluster deletion protection: DescribeDBClusters returns DeletionProtection" {
run aws_cmd rds describe-db-clusters --db-cluster-identifier floci-rds-cluster-deletion-protection \
--query 'DBClusters[0].DeletionProtection' --output text
assert_success
assert_output "True"
}
@test "RDS cluster deletion protection: plan after apply reports no changes" {
cd "$DP_TF_DIR"
run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode
assert_success
assert_output --partial "No changes"
}
@test "RDS cluster deletion protection: turning it off applies and re-plans clean" {
cd "$DP_TF_DIR"
run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -var="deletion_protection=false" \
-input=false -auto-approve -no-color
assert_success
assert_output --partial "1 changed"
run aws_cmd rds describe-db-clusters --db-cluster-identifier floci-rds-cluster-deletion-protection \
--query 'DBClusters[0].DeletionProtection' --output text
assert_success
assert_output "False"
run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -var="deletion_protection=false" \
-input=false -no-color -detailed-exitcode
assert_success
assert_output --partial "No changes"
}
+5 -5
View File
@@ -97,8 +97,8 @@ RDS endpoints return the us-east-1 hosted zone ID `Z2R2ITUGPM61AM` in all region
| `DeleteDBSubnetGroup` | Delete a DB subnet group |
| `CreateDBCluster` | Create an Aurora-compatible cluster |
| `DescribeDBClusters` | List clusters — the list form covers the RDS family, DocumentDB and Neptune clusters included, and takes an `engine` filter |
| `DeleteDBCluster` | Delete a cluster |
| `ModifyDBCluster` | Update cluster settings |
| `DeleteDBCluster` | Delete a cluster; refused with `InvalidParameterCombination` while deletion protection is on |
| `ModifyDBCluster` | Update cluster settings, including deletion protection |
| `CreateDBParameterGroup` | Create a parameter group |
| `DescribeDBParameterGroups` | List parameter groups |
| `DeleteDBParameterGroup` | Delete a parameter group |
@@ -234,9 +234,9 @@ checked against the instance's other window. Modifications apply immediately —
## Cluster settings read-back
`CreateDBCluster` and `ModifyDBCluster` retain `CopyTagsToSnapshot` and the enabled
CloudWatch log export types. Modify uses `CloudwatchLogsExportConfiguration` enable
and disable deltas; omitted fields preserve their values, including an explicit
`CreateDBCluster` and `ModifyDBCluster` retain `CopyTagsToSnapshot`, `DeletionProtection`
and the enabled CloudWatch log export types. Modify uses `CloudwatchLogsExportConfiguration`
enable and disable deltas; omitted fields preserve their values, including an explicit
false snapshot-copy flag. Create, modify and describe return the stored settings.
Aurora member instances retain `PromotionTier` from create and modify, defaulting
@@ -1450,6 +1450,7 @@ public class RdsQueryHandler {
List<DbRoleAssociation> associatedRoles = parseAssociatedRoles(params);
service.validateClusterRoleAssociations(id, engine, associatedRoles);
boolean enableHttpEndpoint = Boolean.TRUE.equals(parseOptionalBoolean(params, "EnableHttpEndpoint"));
Boolean deletionProtection = parseOptionalBoolean(params, "DeletionProtection");
String globalCluster = params.getFirst("GlobalClusterIdentifier");
if (enableHttpEndpoint && (globalCluster == null || globalCluster.isBlank())) {
// A global cluster's members take its Aurora engine; any other create names its own.
@@ -1461,33 +1462,22 @@ public class RdsQueryHandler {
params, "ServerlessV2ScalingConfiguration.SecondsUntilAutoPause");
Integer requestedPort = parseIntegerParam(params, "Port");
String globalClusterIdentifier = params.getFirst("GlobalClusterIdentifier");
boolean protectedCluster = Boolean.TRUE.equals(deletionProtection);
DbCluster cluster;
if (globalClusterIdentifier != null && !globalClusterIdentifier.isBlank()) {
cluster = requestedPort == null
? service.createDbClusterInGlobalCluster(globalClusterIdentifier, id, engine,
params.getFirst("EngineVersion"), masterUsername, masterPassword, databaseName,
iamEnabled, paramGroupName, dbSubnetGroupName, availabilityZone, multiAz, region,
serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause,
manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode, storageEncrypted)
: service.createDbClusterInGlobalCluster(globalClusterIdentifier, id, engine,
params.getFirst("EngineVersion"), masterUsername, masterPassword, databaseName,
iamEnabled, paramGroupName, dbSubnetGroupName, availabilityZone, multiAz, region,
serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause,
manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode, storageEncrypted,
requestedPort);
cluster = service.createDbClusterInGlobalCluster(globalClusterIdentifier, id, engine,
params.getFirst("EngineVersion"), masterUsername, masterPassword, databaseName,
iamEnabled, paramGroupName, dbSubnetGroupName, availabilityZone, multiAz, region,
serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause,
manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode, storageEncrypted,
requestedPort, protectedCluster);
} else {
cluster = requestedPort == null
? service.createDbCluster(id, engine, engineVersion, masterUsername,
masterPassword, databaseName, iamEnabled, paramGroupName,
dbSubnetGroupName, availabilityZone, multiAz, region,
serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause,
manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode, storageEncrypted)
: service.createDbCluster(id, engine, engineVersion, masterUsername,
masterPassword, databaseName, iamEnabled, paramGroupName,
dbSubnetGroupName, availabilityZone, multiAz, region,
serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause,
manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode, storageEncrypted,
requestedPort);
cluster = service.createDbCluster(id, engine, engineVersion, masterUsername,
masterPassword, databaseName, iamEnabled, paramGroupName,
dbSubnetGroupName, availabilityZone, multiAz, region,
serverlessV2Min, serverlessV2Max, serverlessV2SecondsUntilAutoPause,
manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode, storageEncrypted,
requestedPort, protectedCluster);
}
Map<String, String> tags = parseTags(params);
String kmsKeyId = params.getFirst("KmsKeyId");
@@ -1503,6 +1493,9 @@ public class RdsQueryHandler {
try {
cluster = service.addRolesToNewDbCluster(region, id, associatedRoles);
} catch (AwsException e) {
if (protectedCluster) {
service.setDeletionProtection(region, id, false);
}
service.deleteDbCluster(id, region);
throw e;
}
@@ -1632,6 +1625,7 @@ public class RdsQueryHandler {
if (modifyBackupRetentionPeriod != null) {
RdsService.validateBackupRetentionPeriod(modifyBackupRetentionPeriod);
}
Boolean deletionProtection = parseOptionalBoolean(params, "DeletionProtection");
if (Boolean.TRUE.equals(enableHttpEndpoint)) {
RdsService.requireDataApiEngine(service.getDbCluster(id, region).getEngineIdentifier());
}
@@ -1650,6 +1644,9 @@ public class RdsQueryHandler {
if (copyTagsToSnapshot != null || exportChanges != null) {
cluster = service.setClusterSnapshotAndLogSettings(region, id, copyTagsToSnapshot, null, exportChanges);
}
if (deletionProtection != null) {
cluster = service.setDeletionProtection(region, id, deletionProtection);
}
String result = dbClusterXml(cluster);
return Response.ok(AwsQueryResponse.envelope("ModifyDBCluster", AwsNamespaces.RDS, result)).build();
} catch (AwsException e) {
@@ -3691,6 +3688,7 @@ public class RdsQueryHandler {
.elem("MultiAZ", c.isMultiAz())
.elem("StorageEncrypted", c.isStorageEncrypted())
.elem("BackupRetentionPeriod", c.getBackupRetentionPeriod())
.elem("DeletionProtection", c.isDeletionProtection())
.elem("CopyTagsToSnapshot", c.isCopyTagsToSnapshot())
.elem("KmsKeyId", c.getKmsKeyId())
.elem("AvailabilityZone", c.getAvailabilityZone() != null ? c.getAvailabilityZone() : config.defaultAvailabilityZone())
@@ -2798,7 +2798,7 @@ public class RdsService implements Resettable, ResourceProvider {
parameterGroupName, dbSubnetGroupName, availabilityZone, false, effectiveRegion,
null, null, null, false, null,
engineMode != null && !engineMode.isBlank() ? engineMode : snapshot.getEngineMode(),
snapshot.isStorageEncrypted(), port);
snapshot.isStorageEncrypted(), port, false);
if (tags != null && !tags.isEmpty()) {
cluster.getTags().putAll(tags);
putClusterForScope(accountId, effectiveRegion, clusterId, cluster);
@@ -2897,7 +2897,7 @@ public class RdsService implements Resettable, ResourceProvider {
parameterGroupName, dbSubnetGroupName, null, false, effectiveRegion,
null, null, null, false, null,
!isBlank(engineMode) ? engineMode : source.getEngineMode(),
source.isStorageEncrypted(), port);
source.isStorageEncrypted(), port, false);
if (tags != null && !tags.isEmpty()) {
cluster.getTags().putAll(tags);
putClusterForScope(accountId, effectiveRegion, clusterId, cluster);
@@ -5769,11 +5769,28 @@ public class RdsService implements Resettable, ResourceProvider {
Integer serverlessV2SecondsUntilAutoPause,
boolean manageMasterUserPassword, String masterUserSecretKmsKeyId,
String engineMode, boolean storageEncrypted, Integer requestedPort) {
return createDbCluster(id, engineParam, engineVersion, masterUsername, masterPassword,
databaseName, iamEnabled, paramGroupName, dbSubnetGroupName, availabilityZone,
multiAz, region, serverlessV2MinCapacity, serverlessV2MaxCapacity,
serverlessV2SecondsUntilAutoPause, manageMasterUserPassword, masterUserSecretKmsKeyId,
engineMode, storageEncrypted, requestedPort, false);
}
public DbCluster createDbCluster(String id, String engineParam, String engineVersion,
String masterUsername, String masterPassword,
String databaseName, boolean iamEnabled,
String paramGroupName, String dbSubnetGroupName,
String availabilityZone, boolean multiAz, String region,
Double serverlessV2MinCapacity, Double serverlessV2MaxCapacity,
Integer serverlessV2SecondsUntilAutoPause,
boolean manageMasterUserPassword, String masterUserSecretKmsKeyId,
String engineMode, boolean storageEncrypted, Integer requestedPort,
boolean deletionProtection) {
return createDbClusterWithPort(id, engineParam, engineVersion, masterUsername, masterPassword,
databaseName, iamEnabled, paramGroupName, dbSubnetGroupName, availabilityZone,
multiAz, region, serverlessV2MinCapacity, serverlessV2MaxCapacity,
serverlessV2SecondsUntilAutoPause, manageMasterUserPassword, masterUserSecretKmsKeyId,
engineMode, storageEncrypted, requestedPort);
engineMode, storageEncrypted, requestedPort, deletionProtection);
}
private DbCluster createDbClusterWithPort(String id, String engineParam, String engineVersion,
@@ -5784,7 +5801,8 @@ public class RdsService implements Resettable, ResourceProvider {
Double serverlessV2MinCapacity, Double serverlessV2MaxCapacity,
Integer serverlessV2SecondsUntilAutoPause,
boolean manageMasterUserPassword, String masterUserSecretKmsKeyId,
String engineMode, boolean storageEncrypted, Integer requestedPort) {
String engineMode, boolean storageEncrypted, Integer requestedPort,
boolean deletionProtection) {
String provisioningKey = "cluster:" + currentAccountId() + ":"
+ dbResourceKey(effectiveRegion(region), id);
if (!provisioningIds.add(provisioningKey)) {
@@ -5796,7 +5814,7 @@ public class RdsService implements Resettable, ResourceProvider {
databaseName, iamEnabled, paramGroupName, dbSubnetGroupName, availabilityZone,
multiAz, region, serverlessV2MinCapacity, serverlessV2MaxCapacity,
serverlessV2SecondsUntilAutoPause, manageMasterUserPassword, masterUserSecretKmsKeyId,
engineMode, storageEncrypted, requestedPort);
engineMode, storageEncrypted, requestedPort, deletionProtection);
} finally {
provisioningIds.remove(provisioningKey);
}
@@ -5810,7 +5828,8 @@ public class RdsService implements Resettable, ResourceProvider {
Double serverlessV2MinCapacity, Double serverlessV2MaxCapacity,
Integer serverlessV2SecondsUntilAutoPause,
boolean manageMasterUserPassword, String masterUserSecretKmsKeyId,
String engineMode, boolean storageEncrypted, Integer requestedPort) {
String engineMode, boolean storageEncrypted, Integer requestedPort,
boolean deletionProtection) {
String effectiveRegion = effectiveRegion(region);
String clusterResourceId = "cluster-" + UUID.randomUUID().toString()
.replace("-", "").substring(0, 24).toUpperCase();
@@ -5848,6 +5867,7 @@ public class RdsService implements Resettable, ResourceProvider {
cluster.setEngineIdentifier(effectiveEngineName(engineParam).toLowerCase(Locale.ROOT));
cluster.setEngineMode(engineMode != null && !engineMode.isBlank() ? engineMode : "provisioned");
cluster.setStorageEncrypted(storageEncrypted);
cluster.setDeletionProtection(deletionProtection);
cluster.setContainerStorageResourceId(clusterResourceId);
if (!mock) {
String clusterVolumeId;
@@ -6541,6 +6561,10 @@ public class RdsService implements Resettable, ResourceProvider {
new AwsException("DBClusterNotFoundFault",
"DB cluster " + id + " not found.", 404));
if (cluster.isDeletionProtection()) {
throw new AwsException("InvalidParameterCombination",
"Cannot delete protected Cluster, please disable deletion protection and try again.", 400);
}
if (!cluster.getDbClusterMembers().isEmpty()) {
throw new AwsException("InvalidDBClusterStateFault",
"DB cluster " + id + " still has DB instances.", 400);
@@ -6704,7 +6728,7 @@ public class RdsService implements Resettable, ResourceProvider {
masterUsername, masterPassword, databaseName, iamEnabled, paramGroupName,
dbSubnetGroupName, availabilityZone, multiAz, region, serverlessV2MinCapacity,
serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause, manageMasterUserPassword,
masterUserSecretKmsKeyId, engineMode, storageEncrypted, null);
masterUserSecretKmsKeyId, engineMode, storageEncrypted, null, false);
}
public DbCluster createDbClusterInGlobalCluster(String globalClusterIdentifier, String id,
@@ -6716,7 +6740,8 @@ public class RdsService implements Resettable, ResourceProvider {
Double serverlessV2MinCapacity, Double serverlessV2MaxCapacity,
Integer serverlessV2SecondsUntilAutoPause,
boolean manageMasterUserPassword, String masterUserSecretKmsKeyId,
String engineMode, boolean storageEncrypted, Integer requestedPort) {
String engineMode, boolean storageEncrypted, Integer requestedPort,
boolean deletionProtection) {
String effectiveRegion = effectiveRegion(region);
String accountId = currentAccountId();
GlobalCluster global = requireGlobalCluster(accountId, globalClusterIdentifier);
@@ -6737,7 +6762,7 @@ public class RdsService implements Resettable, ResourceProvider {
paramGroupName, dbSubnetGroupName, availabilityZone, multiAz, effectiveRegion,
serverlessV2MinCapacity, serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause,
manageMasterUserPassword, masterUserSecretKmsKeyId, engineMode,
storageEncrypted || global.isStorageEncrypted(), requestedPort);
storageEncrypted || global.isStorageEncrypted(), requestedPort, deletionProtection);
} else {
if (hasText(masterUsername) || hasText(masterPassword) || manageMasterUserPassword) {
throw new AwsException("InvalidParameterCombination",
@@ -6772,7 +6797,7 @@ public class RdsService implements Resettable, ResourceProvider {
primary.getDatabaseName(), iamEnabled, paramGroupName, dbSubnetGroupName,
availabilityZone, multiAz, effectiveRegion, serverlessV2MinCapacity,
serverlessV2MaxCapacity, serverlessV2SecondsUntilAutoPause, false, null,
engineMode, primary.isStorageEncrypted(), requestedPort);
engineMode, primary.isStorageEncrypted(), requestedPort, deletionProtection);
}
try {
attachToGlobalCluster(accountId, global.getGlobalClusterIdentifier(), cluster, primary == null);
@@ -6785,6 +6810,9 @@ public class RdsService implements Resettable, ResourceProvider {
}
} catch (Exception e) {
try {
if (deletionProtection) {
setDeletionProtection(effectiveRegion, id, false);
}
deleteDbCluster(id, effectiveRegion);
} catch (RuntimeException cleanupError) {
e.addSuppressed(cleanupError);
@@ -11999,6 +12027,14 @@ public class RdsService implements Resettable, ResourceProvider {
return RESPONSE_COPIER.convertValue(cluster, DbCluster.class);
}
public synchronized DbCluster setDeletionProtection(String region, String clusterId, boolean deletionProtection) {
String effectiveRegion = effectiveRegion(region);
DbCluster cluster = getDbCluster(clusterId, effectiveRegion);
cluster.setDeletionProtection(deletionProtection);
putClusterForScope(currentAccountId(), effectiveRegion, cluster.getDbClusterIdentifier(), cluster);
return RESPONSE_COPIER.convertValue(cluster, DbCluster.class);
}
public synchronized DbCluster setClusterSnapshotAndLogSettings(String region, String clusterId,
Boolean copyTagsToSnapshot, List<String> exports, LogExportChanges changes) {
String effectiveRegion = effectiveRegion(region);
@@ -48,6 +48,7 @@ public class DbCluster {
private String engineMode;
private boolean storageEncrypted;
private int backupRetentionPeriod = 1;
private boolean deletionProtection;
private boolean copyTagsToSnapshot;
private List<String> enabledCloudwatchLogsExports = new ArrayList<>();
private String kmsKeyId;
@@ -212,6 +213,9 @@ public class DbCluster {
public int getBackupRetentionPeriod() { return backupRetentionPeriod; }
public void setBackupRetentionPeriod(int backupRetentionPeriod) { this.backupRetentionPeriod = backupRetentionPeriod; }
public boolean isDeletionProtection() { return deletionProtection; }
public void setDeletionProtection(boolean deletionProtection) { this.deletionProtection = deletionProtection; }
public String getKmsKeyId() { return kmsKeyId; }
public void setKmsKeyId(String kmsKeyId) { this.kmsKeyId = kmsKeyId; }
@@ -8,6 +8,7 @@ import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static io.floci.aws.testing.RdsRequests.createAuroraPostgresCluster;
import static io.floci.aws.testing.RdsRequests.rds;
import static org.hamcrest.Matchers.containsString;
@@ -32,12 +33,7 @@ class RdsClusterBackupRetentionPeriodIntegrationTest {
}
private static Response createCluster(String id, String period) {
RequestSpecification req = rds("CreateDBCluster")
.formParam("DBClusterIdentifier", id)
.formParam("Engine", "aurora-postgresql")
.formParam("EngineVersion", "16.3")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "secret99password");
RequestSpecification req = createAuroraPostgresCluster(id);
if (period != null) {
req = req.formParam("BackupRetentionPeriod", period);
}
@@ -3,10 +3,10 @@ package io.floci.aws.services.rds;
import io.floci.aws.testing.RdsMockProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
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.hamcrest.Matchers.not;
@@ -31,7 +31,7 @@ class RdsClusterCreateTagsAndKmsKeyIntegrationTest {
@Test
void tagsGivenAtCreateAreReadableThroughListTagsForResource() {
String arn = createCluster()
String arn = createAuroraPostgresCluster(ID)
.formParam("Tags.Tag.1.Key", "Accounting").formParam("Tags.Tag.1.Value", "gna")
.formParam("Tags.Tag.2.Key", "BusinessSolution").formParam("Tags.Tag.2.Value", "gue")
.when().post("/").then().statusCode(200)
@@ -48,7 +48,7 @@ class RdsClusterCreateTagsAndKmsKeyIntegrationTest {
@Test
void tagsAreAlsoReturnedAsTheTagListOfDescribeDbClusters() {
// The Terraform AWS provider reads a cluster's tags from here, not from ListTagsForResource.
createCluster()
createAuroraPostgresCluster(ID)
.formParam("Tags.Tag.1.Key", "Accounting").formParam("Tags.Tag.1.Value", "gna")
.when().post("/").then().statusCode(200)
.body(containsString("<TagList><Tag><Key>Accounting</Key><Value>gna</Value></Tag></TagList>"));
@@ -60,7 +60,7 @@ class RdsClusterCreateTagsAndKmsKeyIntegrationTest {
@Test
void tagsAreAlsoReadInTheMemberForm() {
String arn = createCluster()
String arn = createAuroraPostgresCluster(ID)
.formParam("Tags.member.1.Key", "team").formParam("Tags.member.1.Value", "platform")
.when().post("/").then().statusCode(200)
.extract().path("CreateDBClusterResponse.CreateDBClusterResult.DBCluster.DBClusterArn");
@@ -73,7 +73,7 @@ class RdsClusterCreateTagsAndKmsKeyIntegrationTest {
@Test
void kmsKeyIdRoundTripsFromCreateToDescribe() {
createCluster()
createAuroraPostgresCluster(ID)
.formParam("StorageEncrypted", "true").formParam("KmsKeyId", KEY_ARN)
.when().post("/").then().statusCode(200)
.body(containsString("<KmsKeyId>" + KEY_ARN + "</KmsKeyId>"));
@@ -86,7 +86,7 @@ class RdsClusterCreateTagsAndKmsKeyIntegrationTest {
@Test
void aClusterCreatedWithoutThemHasNoTagsAndNoKmsKeyId() {
String arn = createCluster().when().post("/").then().statusCode(200)
String arn = createAuroraPostgresCluster(ID).when().post("/").then().statusCode(200)
.body(not(containsString("<KmsKeyId>")))
.extract().path("CreateDBClusterResponse.CreateDBClusterResult.DBCluster.DBClusterArn");
@@ -97,13 +97,4 @@ class RdsClusterCreateTagsAndKmsKeyIntegrationTest {
.when().post("/").then().statusCode(200)
.body(not(containsString("<KmsKeyId>")));
}
private static RequestSpecification createCluster() {
return rds("CreateDBCluster")
.formParam("DBClusterIdentifier", ID)
.formParam("Engine", "aurora-postgresql")
.formParam("EngineVersion", "16.3")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "secret99password");
}
}
@@ -0,0 +1,106 @@
package io.floci.aws.services.rds;
import io.floci.aws.testing.RdsMockProfile;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static io.floci.aws.testing.RdsRequests.createAuroraPostgresCluster;
import static io.floci.aws.testing.RdsRequests.rds;
import static org.hamcrest.Matchers.containsString;
@QuarkusTest
@TestProfile(RdsMockProfile.class)
class RdsClusterDeletionProtectionIntegrationTest {
private static final String ID = "dp-cluster";
@AfterEach
void cleanUp() {
rds("ModifyDBCluster").formParam("DBClusterIdentifier", ID)
.formParam("DeletionProtection", "false").when().post("/");
rds("DeleteDBCluster").formParam("DBClusterIdentifier", ID)
.formParam("SkipFinalSnapshot", "true").when().post("/");
}
private static Response createCluster(String deletionProtection) {
RequestSpecification req = createAuroraPostgresCluster(ID);
if (deletionProtection != null) {
req = req.formParam("DeletionProtection", deletionProtection);
}
return req.when().post("/");
}
private static void describeReports(String expected) {
rds("DescribeDBClusters").formParam("DBClusterIdentifier", ID)
.when().post("/").then().statusCode(200)
.body(containsString("<DeletionProtection>" + expected + "</DeletionProtection>"));
}
@Test
void deletionProtectionDefaultsToFalse() {
createCluster(null).then().statusCode(200)
.body(containsString("<DeletionProtection>false</DeletionProtection>"));
describeReports("false");
}
@Test
void deletionProtectionSetOnCreateIsReadBack() {
createCluster("true").then().statusCode(200)
.body(containsString("<DeletionProtection>true</DeletionProtection>"));
describeReports("true");
}
@Test
void modifyChangesDeletionProtection() {
createCluster(null).then().statusCode(200);
rds("ModifyDBCluster")
.formParam("DBClusterIdentifier", ID)
.formParam("DeletionProtection", "true")
.when().post("/").then().statusCode(200)
.body(containsString("<DeletionProtection>true</DeletionProtection>"));
describeReports("true");
rds("ModifyDBCluster")
.formParam("DBClusterIdentifier", ID)
.formParam("DeletionProtection", "false")
.when().post("/").then().statusCode(200);
describeReports("false");
}
@Test
void protectedClusterIsNotDeletedUntilProtectionIsDisabled() {
createCluster("true").then().statusCode(200);
rds("DeleteDBCluster").formParam("DBClusterIdentifier", ID)
.formParam("SkipFinalSnapshot", "true")
.when().post("/").then().statusCode(400)
.body(containsString("<Code>InvalidParameterCombination</Code>"));
describeReports("true");
rds("ModifyDBCluster").formParam("DBClusterIdentifier", ID)
.formParam("DeletionProtection", "false")
.when().post("/").then().statusCode(200);
rds("DeleteDBCluster").formParam("DBClusterIdentifier", ID)
.formParam("SkipFinalSnapshot", "true")
.when().post("/").then().statusCode(200);
}
@Test
void modifyWithoutDeletionProtectionKeepsIt() {
createCluster("true").then().statusCode(200);
rds("ModifyDBCluster")
.formParam("DBClusterIdentifier", ID)
.formParam("ApplyImmediately", "true")
.when().post("/").then().statusCode(200)
.body(containsString("<DeletionProtection>true</DeletionProtection>"));
describeReports("true");
}
}
@@ -6,6 +6,7 @@ import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static io.floci.aws.testing.RdsRequests.createAuroraPostgresCluster;
import static io.floci.aws.testing.RdsRequests.rds;
import static org.hamcrest.Matchers.containsString;
@@ -33,12 +34,7 @@ class RdsClusterEngineModeStorageEncryptedIntegrationTest {
@Test
void engineModeAndStorageEncryptedRoundTripThroughDescribe() {
rds("CreateDBCluster")
.formParam("DBClusterIdentifier", ID)
.formParam("Engine", "aurora-postgresql")
.formParam("EngineVersion", "16.3")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "secret99password")
createAuroraPostgresCluster(ID)
.formParam("EngineMode", "serverless")
.formParam("StorageEncrypted", "true")
.when().post("/").then().statusCode(200)
@@ -53,12 +49,7 @@ class RdsClusterEngineModeStorageEncryptedIntegrationTest {
@Test
void engineModeDefaultsToProvisionedAndStorageEncryptedDefaultsToFalseWhenOmitted() {
rds("CreateDBCluster")
.formParam("DBClusterIdentifier", ID)
.formParam("Engine", "aurora-postgresql")
.formParam("EngineVersion", "16.3")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "secret99password")
createAuroraPostgresCluster(ID)
.when().post("/").then().statusCode(200)
.body(containsString("<EngineMode>provisioned</EngineMode>"))
.body(containsString("<StorageEncrypted>false</StorageEncrypted>"));
@@ -927,7 +927,7 @@ class RdsQueryHandlerTest {
when(service.createDbCluster(eq("mycluster"), eq("aurora-postgresql"), any(),
eq("omni_admin"), isNull(), eq("omni"), eq(false), isNull(),
isNull(), isNull(), eq(false), any(),
isNull(), isNull(), isNull(), eq(true), eq("kms-key-1"), isNull(), eq(false)))
isNull(), isNull(), isNull(), eq(true), eq("kms-key-1"), isNull(), eq(false), isNull(), eq(false)))
.thenReturn(cluster);
MultivaluedMap<String, String> p = params();
@@ -947,7 +947,7 @@ class RdsQueryHandlerTest {
verify(service).createDbCluster(eq("mycluster"), eq("aurora-postgresql"), any(),
eq("omni_admin"), isNull(), eq("omni"), eq(false), isNull(),
isNull(), isNull(), eq(false), any(),
isNull(), isNull(), isNull(), eq(true), eq("kms-key-1"), isNull(), eq(false));
isNull(), isNull(), isNull(), eq(true), eq("kms-key-1"), isNull(), eq(false), isNull(), eq(false));
}
@Test
@@ -955,7 +955,7 @@ class RdsQueryHandlerTest {
DbCluster cluster = makeCluster("mycluster");
when(service.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
any(), any(), anyBoolean(), any(), any(), any(), any(), eq(false), isNull(),
any(), anyBoolean()))
any(), anyBoolean(), any(), anyBoolean()))
.thenReturn(cluster);
MultivaluedMap<String, String> p = params();
@@ -972,7 +972,7 @@ class RdsQueryHandlerTest {
void createDbClusterAnswersADockerRejectionWithANonRetryableCapacityError() {
when(service.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
any(), any(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), any(),
any(), anyBoolean()))
any(), anyBoolean(), any(), anyBoolean()))
.thenThrow(new ContainerRejectedException(
new DockerException("authorization denied by plugin: --mounts is not allowed", 403)));
@@ -993,7 +993,7 @@ class RdsQueryHandlerTest {
DbCluster cluster = makeCluster("mycluster");
when(service.createDbCluster(any(), any(), any(), any(), any(), any(), anyBoolean(), any(),
any(), any(), anyBoolean(), any(), any(), any(), any(), anyBoolean(), any(),
any(), anyBoolean()))
any(), anyBoolean(), any(), anyBoolean()))
.thenReturn(cluster);
// Another request associated the role between the create and the roles being added.
when(service.addRolesToNewDbCluster(any(), eq("mycluster"), anyList()))
@@ -59,6 +59,7 @@ class DbClusterPersistenceTest {
DbCluster restored = clusterReader.get("legacy").orElseThrow();
assertFalse(restored.isCopyTagsToSnapshot());
assertTrue(restored.getEnabledCloudwatchLogsExports().isEmpty());
assertFalse(restored.isDeletionProtection());
PersistentStorage<String, DbInstance> instanceReader = new PersistentStorage<>(
instances, new TypeReference<Map<String, DbInstance>>() {});
instanceReader.load();
@@ -156,4 +157,22 @@ class DbClusterPersistenceTest {
assertTrue(reader.get("data-api-cluster").orElseThrow().isHttpEndpointEnabled());
}
@Test
void deletionProtectionPersistsAcrossInstances(@TempDir Path directory) {
Path file = directory.resolve("rds-clusters.json");
DbCluster cluster = new DbCluster();
cluster.setDbClusterIdentifier("protected-cluster");
cluster.setDeletionProtection(true);
PersistentStorage<String, DbCluster> writer = new PersistentStorage<>(
file, new TypeReference<Map<String, DbCluster>>() {});
writer.put(cluster.getDbClusterIdentifier(), cluster);
PersistentStorage<String, DbCluster> reader = new PersistentStorage<>(
file, new TypeReference<Map<String, DbCluster>>() {});
reader.load();
assertTrue(reader.get("protected-cluster").orElseThrow().isDeletionProtection());
}
}
@@ -128,6 +128,15 @@ public final class RdsRequests {
.getInt("CreateDBInstanceResponse.CreateDBInstanceResult.DBInstance.Endpoint.Port");
}
public static RequestSpecification createAuroraPostgresCluster(String id) {
return rds("CreateDBCluster")
.formParam("DBClusterIdentifier", id)
.formParam("Engine", "aurora-postgresql")
.formParam("EngineVersion", "16.3")
.formParam("MasterUsername", "admin")
.formParam("MasterUserPassword", "secret99password");
}
public static void deleteInstance(String id) {
rds("DeleteDBInstance")
.formParam("DBInstanceIdentifier", id)