From a28ebbf30827db29bd989cc7ca8d2391e1f73097 Mon Sep 17 00:00:00 2001 From: Jackson Price <59149601+jprice8@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:00:05 -0600 Subject: [PATCH] fix(cloudformation): read deleted stack resources by stack ID (#9730) Use the retained stack when a resource read names its ID. This lets SDK clients inspect the original resources after deletion or name reuse until the configured retention window expires. Signed-off-by: Jackson Price Co-authored-by: Andre Kurait --- docs/services/cloudformation.md | 6 +- .../cloudformation/CloudFormationService.java | 6 +- ...DeletedResourceHistoryIntegrationTest.java | 182 ++++++++++++++++++ .../CloudFormationIntegrationTest.java | 73 ++----- 4 files changed, 209 insertions(+), 58 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletedResourceHistoryIntegrationTest.java diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index c133863a16..1ecdc58bac 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -1301,6 +1301,10 @@ window AWS's asymmetry is reproduced: - `DescribeStacks` **by stack id** (the ARN) answers with the stack, its `DELETE_COMPLETE` status and its `DeletionTime`. `DescribeStackEvents` by stack id answers likewise. +- `ListStackResources`, `DescribeStackResources`, and `DescribeStackResource` by stack id return + the deleted stack's resource history, including `DELETE_SKIPPED` for retained resources. + The lookup uses the requesting account and region. After a stack name is reused, the name + resolves to the replacement stack, and the old stack ID still identifies the original resources. - `DescribeStacks` **by name** returns `ValidationError`, as it does on AWS. The CDK CLI depends on the pair: it monitors a delete by stack id, and a stack id that stops resolving ends the rest of a `cdk destroy --all` run. @@ -1363,8 +1367,6 @@ Deviations from AWS to be aware of: - Every resource defaults to `Delete`. AWS instead defaults `AWS::RDS::DBCluster`, and `AWS::RDS::DBInstance` without a `DBClusterIdentifier`, to `Snapshot`. - Unrecognized values are treated as `Delete`. -- After `DeleteStack` completes, a retained resource's `DELETE_SKIPPED` record is only visible - through `DescribeStackEvents` for the deleted stack, not `DescribeStackResources`. - `UpdateReplacePolicy` is honored only by the resource types that delete a displaced resource once the update commits, such as an SSM parameter or a log stream; other types keep the displaced resource, or delete it during the update, whatever the policy. The `RetainExceptOnCreate` request diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java index aa4cad068f..c4413aa646 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java @@ -2783,8 +2783,12 @@ public class CloudFormationService implements ResourceProvider { // A physical id names the stack, it does not narrow it: AWS returns "the associated // resources of the stack that the resource belongs to", which is the whole stack. Stack stack = hasStackName - ? getStackOrThrow(stackName, region) + ? resolveStackForDescribe(stackName, region) : stackContaining(physicalResourceId, region); + if (stack == null) { + throw new AwsException("ValidationError", + "Stack with id " + stackName + " does not exist", 400); + } List resources = new ArrayList<>(stack.resourcesSnapshot().values()); // Only a filter on the result. The reference documents no error for a logical id the diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletedResourceHistoryIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletedResourceHistoryIntegrationTest.java new file mode 100644 index 0000000000..ec1c4d20c6 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDeletedResourceHistoryIntegrationTest.java @@ -0,0 +1,182 @@ +package io.floci.aws.services.cloudformation; + +import io.floci.aws.testing.AwsTestClients; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.CloudFormationException; +import software.amazon.awssdk.services.cloudformation.model.StackResource; +import software.amazon.awssdk.services.cloudformation.model.StackResourceDetail; +import software.amazon.awssdk.services.cloudformation.model.StackResourceSummary; +import software.amazon.awssdk.services.ssm.SsmClient; +import software.amazon.awssdk.services.ssm.model.ParameterNotFoundException; + +import java.time.Duration; +import java.util.List; +import java.util.UUID; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@QuarkusTest +class CloudFormationDeletedResourceHistoryIntegrationTest { + + private static final String ACCOUNT = "611111111111"; + + @ParameterizedTest + @ValueSource(strings = {"us-east-1", "us-gov-west-1", "cn-north-1"}) + void deletedResourcesRemainReadableByIdAcrossAllResourceDescribeApis(String regionName) { + Region region = Region.of(regionName); + String name = "deleted-resources-" + UUID.randomUUID(); + try (CloudFormationClient cfn = client(ACCOUNT, region); + SsmClient ssm = AwsTestClients.create(SsmClient.builder(), ACCOUNT, region)) { + String id = create(cfn, name, "Original"); + StackResourceSummary original = cfn.listStackResources(b -> b.stackName(id)) + .stackResourceSummaries().getFirst(); + delete(cfn, id, name); + + assertThrows(ParameterNotFoundException.class, + () -> ssm.getParameter(b -> b.name(original.physicalResourceId()))); + assertHistory(cfn, id, "Original", original.physicalResourceId()); + assertMissing(cfn, name); + } + } + + @Test + void retainedResourceHistoryReportsSkippedDeletionWhileTheResourceStillExists() { + String name = "retained-resource-history-" + UUID.randomUUID(); + try (CloudFormationClient cfn = client(ACCOUNT, Region.US_EAST_1); + SsmClient ssm = AwsTestClients.create(SsmClient.builder(), ACCOUNT, Region.US_EAST_1)) { + String id = createWithTemplate(cfn, name, """ + {"Resources":{"Retained":{"Type":"AWS::SSM::Parameter","DeletionPolicy":"Retain", + "Properties":{"Type":"String","Value":"native"}}}} + """); + String physical = cfn.listStackResources(b -> b.stackName(id)) + .stackResourceSummaries().getFirst().physicalResourceId(); + delete(cfn, id, name); + try { + assertEquals("native", ssm.getParameter(b -> b.name(physical)).parameter().value()); + assertHistory(cfn, id, "Retained", physical, "DELETE_SKIPPED"); + assertMissing(cfn, name); + } finally { + ssm.deleteParameter(b -> b.name(physical)); + } + } + } + + @Test + void deletedResourceHistoryRemainsScopedToItsAccountAndRegion() { + String name = "scoped-deleted-resources-" + UUID.randomUUID(); + try (CloudFormationClient owner = client(ACCOUNT, Region.US_EAST_1); + CloudFormationClient otherAccount = client("622222222222", Region.US_EAST_1); + CloudFormationClient otherRegion = client(ACCOUNT, Region.EU_WEST_1)) { + String id = create(owner, name, "Original"); + String physical = owner.listStackResources(b -> b.stackName(id)) + .stackResourceSummaries().getFirst().physicalResourceId(); + delete(owner, id, name); + + assertHistory(owner, id, "Original", physical); + assertMissing(otherAccount, id); + assertMissing(otherRegion, id); + } + } + + @Test + void reusedNameKeepsOldResourceHistorySeparateFromItsReplacement() { + String name = "reused-resource-history-" + UUID.randomUUID(); + try (CloudFormationClient cfn = client(ACCOUNT, Region.US_EAST_1)) { + String oldId = create(cfn, name, "Original"); + String physical = cfn.listStackResources(b -> b.stackName(oldId)) + .stackResourceSummaries().getFirst().physicalResourceId(); + delete(cfn, oldId, name); + String replacementId = create(cfn, name, "Replacement"); + try { + assertNotEquals(oldId, replacementId); + assertHistory(cfn, oldId, "Original", physical); + List current = cfn.listStackResources(b -> b.stackName(name)) + .stackResourceSummaries(); + assertEquals(1, current.size()); + assertEquals("Replacement", current.getFirst().logicalResourceId()); + assertEquals("CREATE_COMPLETE", current.getFirst().resourceStatusAsString()); + assertNotEquals(physical, current.getFirst().physicalResourceId()); + CloudFormationException error = assertThrows(CloudFormationException.class, + () -> cfn.updateStack(b -> b.stackName(oldId).templateBody(template("Changed")))); + assertEquals("ValidationError", error.awsErrorDetails().errorCode()); + assertEquals("Stack:" + oldId + " is in DELETE_COMPLETE state and can not be updated.", + error.awsErrorDetails().errorMessage()); + assertEquals("Replacement", cfn.listStackResources(b -> b.stackName(replacementId)) + .stackResourceSummaries().getFirst().logicalResourceId()); + } finally { + delete(cfn, replacementId, name); + } + } + } + + private static void assertHistory(CloudFormationClient cfn, String id, String logical, String physical) { + assertHistory(cfn, id, logical, physical, "DELETE_COMPLETE"); + } + + private static void assertHistory(CloudFormationClient cfn, String id, String logical, String physical, + String status) { + List listed = cfn.listStackResources(b -> b.stackName(id)).stackResourceSummaries(); + assertEquals(1, listed.size()); + assertEquals(logical, listed.getFirst().logicalResourceId()); + assertEquals(physical, listed.getFirst().physicalResourceId()); + assertEquals(status, listed.getFirst().resourceStatusAsString()); + StackResource resource = cfn.describeStackResources(b -> b.stackName(id).logicalResourceId(logical)) + .stackResources().getFirst(); + assertEquals(id, resource.stackId()); + assertEquals(physical, resource.physicalResourceId()); + assertEquals(status, resource.resourceStatusAsString()); + StackResourceDetail detail = cfn.describeStackResource(b -> b.stackName(id).logicalResourceId(logical)) + .stackResourceDetail(); + assertEquals(id, detail.stackId()); + assertEquals(status, detail.resourceStatusAsString()); + } + + private static void assertMissing(CloudFormationClient cfn, String id) { + assertEquals("ValidationError", assertThrows(CloudFormationException.class, + () -> cfn.listStackResources(b -> b.stackName(id))).awsErrorDetails().errorCode()); + assertEquals("ValidationError", assertThrows(CloudFormationException.class, + () -> cfn.describeStackResources(b -> b.stackName(id))).awsErrorDetails().errorCode()); + assertEquals("ValidationError", assertThrows(CloudFormationException.class, + () -> cfn.describeStackResource(b -> b.stackName(id).logicalResourceId("Original"))) + .awsErrorDetails().errorCode()); + } + + private static String create(CloudFormationClient cfn, String name, String logical) { + return createWithTemplate(cfn, name, template(logical)); + } + + private static String createWithTemplate(CloudFormationClient cfn, String name, String body) { + String id = cfn.createStack(b -> b.stackName(name).templateBody(body)).stackId(); + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> assertEquals("CREATE_COMPLETE", + cfn.describeStacks(b -> b.stackName(id)).stacks().getFirst().stackStatusAsString())); + return id; + } + + private static void delete(CloudFormationClient cfn, String id, String name) { + cfn.deleteStack(b -> b.stackName(id)); + await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> { + assertEquals("DELETE_COMPLETE", + cfn.describeStacks(b -> b.stackName(id)).stacks().getFirst().stackStatusAsString()); + CloudFormationException missing = assertThrows(CloudFormationException.class, + () -> cfn.describeStacks(b -> b.stackName(name))); + assertEquals("ValidationError", missing.awsErrorDetails().errorCode()); + }); + } + + private static String template(String logical) { + return "{\"Resources\":{\"" + logical + "\":{\"Type\":\"AWS::SSM::Parameter\"," + + "\"Properties\":{\"Type\":\"String\",\"Value\":\"native\"}}}}"; + } + + private static CloudFormationClient client(String account, Region region) { + return AwsTestClients.create(CloudFormationClient.builder(), account, region); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIntegrationTest.java index e2acff963c..eda03cfd93 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationIntegrationTest.java @@ -2548,65 +2548,19 @@ class CloudFormationIntegrationTest { @Test void describeDeletedStack_byArn_expiresAfterRetentionWindow() throws Exception { - String template = """ - { - "Resources": { - "MyBucket": { - "Type": "AWS::S3::Bucket", - "Properties": { - "BucketName": "deleted-arn-expiry-test-bucket" - } - } - } - } - """; - - String createResponse = given() - .contentType("application/x-www-form-urlencoded") - .formParam("Action", "CreateStack") - .formParam("StackName", "deleted-arn-expiry-stack") - .formParam("TemplateBody", template) - .when() - .post("/") - .then() - .statusCode(200) - .body(containsString("")) - .extract().asString(); - CfnStackWaits.awaitStatus("deleted-arn-expiry-stack", "CREATE_COMPLETE"); - - String stackArn = createResponse.substring( - createResponse.indexOf("") + "".length(), - createResponse.indexOf("")); - - given() - .contentType("application/x-www-form-urlencoded") - .formParam("Action", "DeleteStack") - .formParam("StackName", "deleted-arn-expiry-stack") - .when() - .post("/") - .then() - .statusCode(200); - - long readyDeadline = System.currentTimeMillis() + 10_000; - while (System.currentTimeMillis() < readyDeadline) { - String deletedEventsXml = given() - .contentType("application/x-www-form-urlencoded") - .formParam("Action", "DescribeStackEvents") - .formParam("StackName", stackArn) - .when() - .post("/") - .then() - .statusCode(200) - .extract().asString(); - - if (deletedEventsXml.contains("DELETE_COMPLETE")) { - break; - } - Thread.sleep(200); + String stackArn = createAndDeleteStack("deleted-arn-expiry-stack", "deleted-arn-expiry-test-bucket"); + List resourceActions = List.of("ListStackResources", "DescribeStackResources", "DescribeStackResource"); + for (String action : resourceActions) { + readStackResources(action, stackArn).statusCode(200).body(containsString("DELETE_COMPLETE")); } clock.advance(Duration.ofSeconds(31)); + for (String action : resourceActions) { + readStackResources(action, stackArn).statusCode(400).body(containsString("ValidationError")) + .body(containsString("Stack with id " + stackArn + " does not exist")); + } + given() .contentType("application/x-www-form-urlencoded") .formParam("Action", "DescribeStackEvents") @@ -2628,6 +2582,15 @@ class CloudFormationIntegrationTest { .body(containsString("does not exist")); } + private static ValidatableResponse readStackResources(String action, String stackArn) { + RequestSpecification request = given().contentType("application/x-www-form-urlencoded") + .formParam("Action", action).formParam("StackName", stackArn); + if ("DescribeStackResource".equals(action)) { + request.formParam("LogicalResourceId", "MyBucket"); + } + return request.post("/").then(); + } + @Test void describeDeletedStack_byArn_reportsItsDeletionTime() throws Exception { String stackArn = createAndDeleteStack("deleted-deletion-time-stack",