fix(cloudformation): replace AWS::S3::Bucket when BucketName changes (#5762)

A change to BucketName is a replacement: CloudFormation creates the new
bucket first and then deletes the old one, unless UpdateReplacePolicy is
Retain. S3CfnProvisioner created the replacement but never removed the
displaced bucket, so a successful rename left both buckets, and a rename
that a later resource failed ended in UPDATE_ROLLBACK_FAILED, with
DescribeStackResources still naming the new bucket.

Record the displaced bucket with ReplacementCleanup and delegate the
replacement lifecycle to it, so the committed update deletes the old
bucket, honouring UpdateReplacePolicy: Retain, and a rollback points the
resource back at the original bucket and deletes the replacement. Route
the bucket delete through CfnDeletes.safeDelete so a bucket already gone
is tolerated while a real failure such as BucketNotEmpty still propagates
and reaches the stack as DELETE_FAILED.

Fixes #5678

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-10-18 10:52:00 -04:00
1 parent 5dcddc9dfa
commit 8298779ead
4 files changed
+515 -13

No files matched your search

@@ -69,6 +69,19 @@ public final class ReplacementCleanup {
*/
static void record(StackResource r, ProvisionContext ctx, Map<String, String> attributesBeforeProvision,
boolean replaced) {
record(r, ctx, attributesBeforeProvision, replaced, true);
}
/**
* Records a replacement the provisioner decided on, spelling out whether this update created the
* entity under the new physical id. {@code replacementCreated} is false when that entity already
* existed and the provision only took it over, the way us-east-1's idempotent {@code CreateBucket}
* answers for a bucket the account already owns. The prior entity is still displaced, so a
* committed update deletes it, but {@link #rollback} points the resource back without deleting an
* entity this update never created.
*/
static void record(StackResource r, ProvisionContext ctx, Map<String, String> attributesBeforeProvision,
boolean replaced, boolean replacementCreated) {
ObjectNode cleanup = readOrEmpty(r);
cleanup.remove("priorPhysicalId");
cleanup.remove("undeletedReplacement");
@@ -88,6 +101,11 @@ public final class ReplacementCleanup {
addDisplaced(cleanup, prior, r.getResourceType(), ctx.region(), true);
}
}
if (replaced && !replacementCreated) {
cleanup.put("replacementPreexisting", true);
} else {
cleanup.remove("replacementPreexisting");
}
write(r, cleanup);
}
@@ -104,6 +122,10 @@ public final class ReplacementCleanup {
* propagates so the stack reports it. A retry (CloudFormation {@code ContinueUpdateRollback})
* re-attempts that failed delete. Returns false when this update replaced nothing, which
* leaves the engine's handling of in-place updates unchanged.
*
* <p>A replacement this update did not create is left standing: the resource points back to the
* prior entity, and the entity under the new id, whether another resource created it or it was
* already owned, is never touched by a rollback this update did not make.
*/
static boolean rollback(StackResource r, Deleter deleter) {
ObjectNode cleanup = read(r);
@@ -137,10 +159,15 @@ public final class ReplacementCleanup {
}
cleanup.path("priorAttributes").fields()
.forEachRemaining(e -> r.getAttributes().put(e.getKey(), e.getValue().asText()));
boolean replacementPreexisting = cleanup.path("replacementPreexisting").asBoolean(false);
cleanup.remove("priorPhysicalId");
cleanup.remove("priorAttributes");
cleanup.remove("replacementPreexisting");
removeDisplaced(cleanup, prior);
write(r, cleanup);
if (replacementPreexisting) {
return true;
}
if (prior.equals(replacement) && !CfnResourceDispatcher.isStub(prior, r.getAttributes())) {
return true;
}
@@ -20,6 +20,7 @@ import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
@@ -80,6 +81,7 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
}
private void provisionBucket(StackResource r, JsonNode props, ProvisionContext ctx) {
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
String bucketName = ctx.stablePhysicalName(ctx.resolveOptional(props, "BucketName"),
r.getLogicalId(), BUCKET_NAME_MAX_LENGTH, true);
// provision is also the update path. CreateBucket on a bucket this account already owns is
@@ -88,6 +90,7 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
// and only reconcile the bucket's configuration. A replacing update derives a different
// name and still creates, hence reusesPriorEntity rather than isUpdate.
Unwind unwind = new Unwind();
boolean replacementCreated = true;
r.getAttributes().remove(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR);
try {
// Built before anything is created, so a configuration that fails validation creates nothing.
@@ -103,6 +106,7 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
boolean owned = s3Service.ownsBucket(bucketName);
s3Service.createBucket(bucketName, ctx.region());
unwind.created = !owned;
replacementCreated = !owned;
}
// Ahead of the other properties, so a destination S3 cannot validate fails the resource
// before any of them has changed the bucket. An unchanged configuration is not put again:
@@ -138,6 +142,12 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
}
r.getAttributes().put("WebsiteURL", AwsEndpoints.s3WebsiteUrl(bucketName, ctx.region()));
r.getAttributes().put("BucketName", bucketName);
// A change to BucketName is create-only, so the engine replaces the resource: this update
// created the bucket above, and the one the prior physical id named is left for the cleanup
// once the update commits, or put back when a later resource fails the update. A name the
// account already owned was not created here, so a rollback must not delete it.
ReplacementCleanup.record(r, ctx, attributesBefore,
ctx.isUpdate() && !ctx.priorPhysicalId().equals(r.getPhysicalId()), replacementCreated);
}
private void applyBucketCorsConfiguration(String bucketName, JsonNode props, ProvisionContext ctx) {
@@ -307,28 +317,27 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
@Override
public boolean rollbackUpdate(StackResource resource) {
if (!BUCKET.equals(resource.getResourceType())) {
return false;
}
String snapshot = resource.getAttributes().get(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR);
if (snapshot == null) {
return false;
if (snapshot != null) {
s3Service.restoreBucketConfiguration(resource.getPhysicalId(), snapshot);
resource.getAttributes().remove(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR);
return true;
}
s3Service.restoreBucketConfiguration(resource.getPhysicalId(), snapshot);
resource.getAttributes().remove(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR);
return true;
return ReplacementCleanup.rollback(resource, this::delete);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
return resource.getAttributes().containsKey(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR)
? new UpdateCleanupResult(true, true, null, 0, null)
: UpdateCleanupResult.notApplicable();
if (resource.getAttributes().containsKey(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR)) {
return new UpdateCleanupResult(true, true, null, 0, null);
}
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR);
ReplacementCleanup.clear(resource);
}
private static boolean sameConfiguration(NotificationConfiguration desired, NotificationConfiguration current) {
@@ -619,8 +628,10 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
public void delete(String resourceType, String physicalId, String region) {
if (BUCKET.equals(resourceType)) {
// Deleting a non-empty bucket raises BucketNotEmpty, which propagates so the stack
// reports DELETE_FAILED as AWS does.
s3Service.deleteBucket(physicalId);
// reports DELETE_FAILED as AWS does; a bucket already gone is treated as deleted, so a
// cleanup the update committed reaches an already-removed bucket without failing.
CfnDeletes.safeDelete("S3 bucket", physicalId,
() -> s3Service.deleteBucket(physicalId), "NoSuchBucket");
return;
}
if (BUCKET_POLICY.equals(resourceType)) {
@@ -628,6 +639,16 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
}
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
/**
* Clears the policy the stack put on the bucket. AWS removes it on stack delete unless the
* resource carries {@code DeletionPolicy: Retain}, and leaving it behind is how a dropped
@@ -0,0 +1,285 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Replacing updates of {@code AWS::S3::Bucket} through the whole engine. A template that changes
* {@code BucketName} replaces the bucket: the new one is created and the old is deleted once the
* update commits (unless {@code UpdateReplacePolicy: Retain}), and a later resource that fails the
* update rolls the replacement back and points the resource at the original bucket again.
*/
@QuarkusTest
class CloudFormationS3BucketReplacementIntegrationTest {
/**
* A rename the engine can commit: the old bucket is deleted after {@code UPDATE_COMPLETE} and
* its {@code DELETE_COMPLETE} event names it.
*/
@Test
void renamingTheBucketDeletesTheOldOneAfterTheUpdateCommits() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "s3-replace-" + suffix;
String oldBucket = "s3-replace-old-" + suffix;
String newBucket = "s3-replace-new-" + suffix;
createStack(stackName, template(oldBucket, "", false));
assertBucketPresent(oldBucket);
updateStack(stackName, template(newBucket, "", false));
await(stackName, "UPDATE_COMPLETE");
String describe = describeStack(stackName);
assertEquals(newBucket, output(describe, "BucketRef"));
assertBucketPresent(newBucket);
assertBucketMissing(oldBucket);
assertEvent(describeEvents(stackName), "DELETE_COMPLETE", oldBucket);
deleteStack(stackName);
}
/** {@code UpdateReplacePolicy: Retain} keeps the bucket the rename displaced. */
@Test
void updateReplacePolicyRetainKeepsTheOldBucket() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "s3-retain-" + suffix;
String oldBucket = "s3-retain-old-" + suffix;
String newBucket = "s3-retain-new-" + suffix;
createStack(stackName, template(oldBucket, "", false));
updateStack(stackName, template(newBucket, "", true));
await(stackName, "UPDATE_COMPLETE");
assertEquals(newBucket, output(describeStack(stackName), "BucketRef"));
assertBucketPresent(newBucket);
assertBucketPresent(oldBucket);
deleteStack(stackName);
}
/**
* A rename a later resource fails rolls back: the stack ends in {@code UPDATE_ROLLBACK_COMPLETE},
* the resource names the original bucket again, and the replacement the attempt created is gone.
*/
@Test
void aFailedRenameRollsBackToTheOriginalBucket() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "s3-rollback-" + suffix;
String oldBucket = "s3-rollback-old-" + suffix;
String newBucket = "s3-rollback-new-" + suffix;
createStack(stackName, template(oldBucket, "", false));
assertBucketPresent(oldBucket);
// SecretString and GenerateSecretString cannot be combined, so the resource after the
// bucket fails the update and the rename has to be undone.
String failingSecret = """
,"Failure":{"Type":"AWS::SecretsManager::Secret","DependsOn":"Bucket",
"Properties":{"Name":"s3-rollback-secret-%s","SecretString":"x",
"GenerateSecretString":{"PasswordLength":32}}}""".formatted(suffix);
updateStack(stackName, template(newBucket, failingSecret, false));
await(stackName, "UPDATE_ROLLBACK_COMPLETE");
String describe = describeStack(stackName);
assertEquals(oldBucket, output(describe, "BucketRef"));
assertBucketPresent(oldBucket);
assertBucketMissing(newBucket);
deleteStack(stackName);
}
/**
* A failed update that changed the bucket's own settings without renaming it restores them: the
* same bucket is pointed at a different {@code VersioningConfiguration}, a later resource fails,
* and the bucket ends with the versioning status the stack started with.
*/
@Test
void aFailedInPlaceUpdateRestoresTheBucketConfiguration() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "s3-inplace-" + suffix;
String bucket = "s3-inplace-" + suffix;
createStack(stackName, inPlaceTemplate(bucket, "Enabled", ""));
assertVersioning(bucket, "Enabled");
String failingSecret = """
,"Failure":{"Type":"AWS::SecretsManager::Secret","DependsOn":"Bucket",
"Properties":{"Name":"s3-inplace-secret-%s","SecretString":"x",
"GenerateSecretString":{"PasswordLength":32}}}""".formatted(suffix);
updateStack(stackName, inPlaceTemplate(bucket, "Suspended", failingSecret));
await(stackName, "UPDATE_ROLLBACK_COMPLETE");
assertVersioning(bucket, "Enabled");
deleteStack(stackName);
}
/**
* A rename onto a name the account already owns creates no bucket, so a failed update rolls the
* resource back to the original bucket without deleting the one this update never created.
*/
@Test
void aFailedRenameOntoAnAlreadyOwnedBucketLeavesThatBucketStanding() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "s3-owned-" + suffix;
String oldBucket = "s3-owned-old-" + suffix;
String ownedBucket = "s3-owned-existing-" + suffix;
createBucket(ownedBucket);
createStack(stackName, template(oldBucket, "", false));
assertBucketPresent(oldBucket);
String failingSecret = """
,"Failure":{"Type":"AWS::SecretsManager::Secret","DependsOn":"Bucket",
"Properties":{"Name":"s3-owned-secret-%s","SecretString":"x",
"GenerateSecretString":{"PasswordLength":32}}}""".formatted(suffix);
updateStack(stackName, template(ownedBucket, failingSecret, false));
await(stackName, "UPDATE_ROLLBACK_COMPLETE");
String describe = describeStack(stackName);
assertEquals(oldBucket, output(describe, "BucketRef"));
assertBucketPresent(oldBucket);
assertBucketPresent(ownedBucket);
deleteStack(stackName);
}
private static String inPlaceTemplate(String bucketName, String versioningStatus, String extraResources) {
return """
{
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {"BucketName": "%s", "VersioningConfiguration": {"Status": "%s"}}
}%s
}
}""".formatted(bucketName, versioningStatus, extraResources);
}
private static String template(String bucketName, String extraResources, boolean retain) {
String updateReplacePolicy = retain ? ", \"UpdateReplacePolicy\": \"Retain\"" : "";
return """
{
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket"%1$s,
"Properties": { "BucketName": "%2$s" }
}%3$s
},
"Outputs": { "BucketRef": { "Value": { "Ref": "Bucket" } } }
}
""".formatted(updateReplacePolicy, bucketName, extraResources);
}
private static void createStack(String stackName, String body) {
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack").formParam("Version", "2010-05-15")
.formParam("StackName", stackName).formParam("TemplateBody", body)
.when().post("/").then().statusCode(200);
await(stackName, "CREATE_COMPLETE");
}
private static void updateStack(String stackName, String body) {
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "UpdateStack").formParam("Version", "2010-05-15")
.formParam("StackName", stackName).formParam("TemplateBody", body)
.when().post("/").then().statusCode(200);
}
private static void deleteStack(String stackName) {
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack").formParam("Version", "2010-05-15")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200);
}
private static String describeStack(String stackName) {
return given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks").formParam("Version", "2010-05-15")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().asString();
}
private static String describeEvents(String stackName) {
return given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStackEvents").formParam("Version", "2010-05-15")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200).extract().asString();
}
private static void assertVersioning(String bucket, String status) {
given()
.when()
.get("/" + bucket + "?versioning")
.then()
.statusCode(200)
.body(containsString("<Status>" + status + "</Status>"));
}
private static void await(String stackName, String status) {
String xml = "";
long deadline = System.currentTimeMillis() + 10_000;
while (System.currentTimeMillis() < deadline) {
xml = describeStack(stackName);
if (xml.contains("<StackStatus>" + status + "</StackStatus>")) {
return;
}
if (xml.contains("_FAILED</StackStatus>")) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
fail("stack " + stackName + " never reached " + status + ": " + xml);
}
private static void createBucket(String bucket) {
given().when().put("/" + bucket).then().statusCode(200);
}
private static void assertBucketPresent(String bucket) {
given().when().head("/" + bucket).then().statusCode(200);
}
private static void assertBucketMissing(String bucket) {
given().when().head("/" + bucket).then().statusCode(404);
}
private static void assertEvent(String eventsXml, String status, String physicalId) {
Pattern p = Pattern.compile("<member>(.*?)</member>", Pattern.DOTALL);
Matcher m = p.matcher(eventsXml);
while (m.find()) {
String member = m.group(1);
if (member.contains("<ResourceStatus>" + status + "</ResourceStatus>")
&& member.contains("<PhysicalResourceId>" + physicalId + "</PhysicalResourceId>")) {
return;
}
}
throw new AssertionError("no " + status + " event for " + physicalId + " in " + eventsXml);
}
private static String output(String describeXml, String key) {
Matcher m = Pattern.compile("<OutputKey>" + key + "</OutputKey>\\s*<OutputValue>(.*?)</OutputValue>", Pattern.DOTALL)
.matcher(describeXml);
if (!m.find()) {
m = Pattern.compile("<OutputValue>(.*?)</OutputValue>\\s*<OutputKey>" + key + "</OutputKey>", Pattern.DOTALL)
.matcher(describeXml);
assertTrue(m.find(), "output " + key + " missing in " + describeXml);
}
return m.group(1);
}
}
@@ -20,8 +20,10 @@ import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -169,6 +171,115 @@ class S3CfnProvisionerTest {
verify(s3).createBucket("renamed", REGION);
}
/**
* A rename is a replacing update: the prior bucket is reported for the post-commit cleanup and
* deleted once the update commits, exactly as AWS replaces a bucket whose BucketName changed.
*/
@Test
void renamingTheBucketReplacesItAndReportsTheOldNameForCleanup() {
StackResource r = resource("Bucket", "AWS::S3::Bucket");
r.setPhysicalId("old-bucket");
provisioner.provision(r, props("{\"BucketName\": \"new-bucket\"}"), replacingContext("old-bucket"));
assertEquals("new-bucket", r.getPhysicalId());
verify(s3).createBucket("new-bucket", REGION);
assertTrue(provisioner.hasReplacementUpdate(r));
assertEquals("old-bucket", provisioner.updateCleanupPhysicalId(r));
UpdateCleanupResult result = provisioner.completeUpdate(r);
verify(s3).deleteBucket("old-bucket");
assertEquals(new UpdateCleanupResult(true, true, "old-bucket", 0, null), result);
provisioner.clearUpdate(r);
assertFalse(provisioner.hasReplacementUpdate(r));
assertNull(provisioner.updateCleanupPhysicalId(r));
}
/** A rename whose delete is finally done leaves nothing owed. */
@Test
void aCommittedReplacementWhoseOldBucketIsAlreadyGoneCompletesCleanup() {
doThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404))
.when(s3).deleteBucket("old-bucket");
StackResource r = resource("Bucket", "AWS::S3::Bucket");
r.setPhysicalId("old-bucket");
provisioner.provision(r, props("{\"BucketName\": \"new-bucket\"}"), replacingContext("old-bucket"));
assertDoesNotThrow(() -> provisioner.completeUpdate(r));
assertFalse(provisioner.hasReplacementUpdate(r));
}
/**
* A later resource failing the update rolls the rename back: the resource names the old bucket
* again, with the attributes it had, and the replacement the attempt created is deleted.
*/
@Test
void rollingBackAReplacingUpdateRestoresTheOldBucketAndDeletesTheReplacement() {
StackResource r = resource("Bucket", "AWS::S3::Bucket");
r.setPhysicalId("old-bucket");
r.getAttributes().put("BucketName", "old-bucket");
r.getAttributes().put("Arn", "arn:aws:s3:::old-bucket");
provisioner.provision(r, props("{\"BucketName\": \"new-bucket\"}"), replacingContext("old-bucket"));
assertEquals("new-bucket", r.getPhysicalId());
assertTrue(provisioner.rollbackUpdate(r));
assertEquals("old-bucket", r.getPhysicalId());
assertEquals("arn:aws:s3:::old-bucket", r.getAttributes().get("Arn"));
verify(s3).deleteBucket("new-bucket");
}
/** A bucket already gone when its replacement is undone is not a rollback failure. */
@Test
void aReplacementAlreadyGoneWhenRolledBackDoesNotFailTheRollback() {
doThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404))
.when(s3).deleteBucket("new-bucket");
StackResource r = resource("Bucket", "AWS::S3::Bucket");
r.setPhysicalId("old-bucket");
provisioner.provision(r, props("{\"BucketName\": \"new-bucket\"}"), replacingContext("old-bucket"));
assertTrue(provisioner.rollbackUpdate(r));
assertEquals("old-bucket", r.getPhysicalId());
}
/**
* A rename onto a name the account already owns does not create a bucket, so a rollback points
* the resource back without deleting a bucket this update never created. The prior bucket stays
* displaced and is still the one a committed cleanup deletes.
*/
@Test
void rollingBackARenameOntoAnOwnedBucketLeavesThatBucketStanding() {
when(s3.ownsBucket("new-bucket")).thenReturn(true);
StackResource r = resource("Bucket", "AWS::S3::Bucket");
r.setPhysicalId("old-bucket");
r.getAttributes().put("BucketName", "old-bucket");
r.getAttributes().put("Arn", "arn:aws:s3:::old-bucket");
provisioner.provision(r, props("{\"BucketName\": \"new-bucket\"}"), replacingContext("old-bucket"));
assertEquals("new-bucket", r.getPhysicalId());
assertTrue(provisioner.rollbackUpdate(r));
assertEquals("old-bucket", r.getPhysicalId());
assertEquals("arn:aws:s3:::old-bucket", r.getAttributes().get("Arn"));
verify(s3, never()).deleteBucket(anyString());
}
/** A committed rename onto an owned bucket deletes only the bucket the stack owned. */
@Test
void committingARenameOntoAnOwnedBucketDeletesOnlyThePriorBucket() {
when(s3.ownsBucket("new-bucket")).thenReturn(true);
StackResource r = resource("Bucket", "AWS::S3::Bucket");
r.setPhysicalId("old-bucket");
provisioner.provision(r, props("{\"BucketName\": \"new-bucket\"}"), replacingContext("old-bucket"));
assertEquals(new UpdateCleanupResult(true, true, "old-bucket", 0, null), provisioner.completeUpdate(r));
verify(s3).deleteBucket("old-bucket");
verify(s3, never()).deleteBucket("new-bucket");
}
private ProvisionContext replacingContext(String priorPhysicalId) {
return new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", priorPhysicalId);
}
/** ISO-E publishes no S3 dual-stack endpoint, so the attribute is absent rather than invented. */
@Test
void aBucketInARegionWithoutS3DualStackHasNoDualStackDomainName() {
@@ -582,6 +693,38 @@ class S3CfnProvisionerTest {
assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
/** A committed in-place update reports the snapshot cleanup done, so the engine drops the snapshot. */
@Test
void completingAnInPlaceUpdateClearsTheSnapshot() {
StackResource r = resource("Bucket", "AWS::S3::Bucket");
r.setPhysicalId("b");
provisioner.provision(r, props("{\"BucketName\": \"b\", \"VersioningConfiguration\": {\"Status\": \"Enabled\"}}"),
new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", "b", event -> { },
props("{\"BucketName\": \"b\"}")));
assertTrue(r.getAttributes().containsKey(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR));
assertEquals(new UpdateCleanupResult(true, true, null, 0, null), provisioner.completeUpdate(r));
provisioner.clearUpdate(r);
assertFalse(r.getAttributes().containsKey(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR));
}
/**
* A later resource failing an update that changed the bucket in place restores the settings from
* the snapshot, the engine calling the same hook a replacement rollback uses.
*/
@Test
void rollingBackAnInPlaceUpdateRestoresTheBucketSnapshot() {
StackResource r = resource("Bucket", "AWS::S3::Bucket");
r.setPhysicalId("b");
provisioner.provision(r, props("{\"BucketName\": \"b\", \"VersioningConfiguration\": {\"Status\": \"Enabled\"}}"),
new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", "b", event -> { },
props("{\"BucketName\": \"b\"}")));
assertTrue(provisioner.rollbackUpdate(r));
verify(s3).restoreBucketConfiguration("b", "snapshot");
assertFalse(r.getAttributes().containsKey(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR));
}
@Test
void aLaterFailureOnCreateDeletesTheBucketItCreated() {
doThrow(new AwsException("MalformedXML", "bad", 400)).when(s3).putBucketVersioning("b", "Bogus");
@@ -692,6 +835,32 @@ class S3CfnProvisionerTest {
verify(s3, never()).deleteBucketPolicy(anyString());
}
/** A bucket already gone is treated as deleted, not as a failure. */
@Test
void deletingAnAlreadyGoneBucketIsTolerated() {
doThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404))
.when(s3).deleteBucket("gone");
assertDoesNotThrow(() -> provisioner.delete("AWS::S3::Bucket", "gone", REGION));
verify(s3).deleteBucket("gone");
}
/**
* A non-empty bucket cannot be deleted, and that failure has to reach the stack so it reports
* DELETE_FAILED rather than a clean deletion over a bucket that is still there.
*/
@Test
void deletingANonEmptyBucketPropagatesBucketNotEmpty() {
doThrow(new AwsException("BucketNotEmpty", "The bucket you tried to delete is not empty.", 409))
.when(s3).deleteBucket("b");
AwsException e = assertThrows(AwsException.class,
() -> provisioner.delete("AWS::S3::Bucket", "b", REGION));
assertEquals("BucketNotEmpty", e.getErrorCode());
}
@Test
void deletingABucketPolicyClearsItFromTheBucketAndLeavesTheBucket() {
provisioner.delete("AWS::S3::BucketPolicy", "b", REGION);