Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(cloudformation): honour the DescribeStackResources filters (#5455)

Anders Wasenc5feab635a2c
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java
index e424678c35..eac7e9e14c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationQueryHandler.java
@@ -396,8 +396,11 @@ public class CloudFormationQueryHandler {
private Response describeStackResources(MultivaluedMap<String, String> params, String region) {
String stackName = params.getFirst("StackName");
try {
- List<StackResource> resources = cfnService.describeStackResources(stackName, region);
- return stackResourcesXml(resources, stackName, region);
+ CloudFormationService.StackResourcesView view = cfnService.describeStackResourcesView(stackName,
+ params.getFirst("LogicalResourceId"), params.getFirst("PhysicalResourceId"), region);
+ // The stack's own name, not what the caller passed: it may be an ARN, or absent
+ // entirely when the call named only a PhysicalResourceId.
+ return stackResourcesXml(view.resources(), view.stackName(), region);
} catch (AwsException e) {
return xmlError(e.getErrorCode(), e.getMessage(), e.getHttpStatus());
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
index fb4931e515..9c405d5464 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java
@@ -1282,8 +1282,83 @@ public class CloudFormationService implements ResourceProvider {
// ── DescribeStackResources ────────────────────────────────────────────────
public List<StackResource> describeStackResources(String stackName, String region) {
- Stack stack = getStackOrThrow(stackName, region);
- return new ArrayList<>(stack.resourcesSnapshot().values());
+ return describeStackResources(stackName, null, null, region);
+ }
+
+ /**
+ * The stack's resources, narrowed by the two filters {@code DescribeStackResources} accepts.
+ *
+ * <p>AWS takes either {@code StackName} or {@code PhysicalResourceId}, never both: given a
+ * physical id it answers with the whole stack that resource belongs to, rather than that one
+ * resource. {@code LogicalResourceId} is only a filter on the result, so naming one the stack
+ * does not have is an empty answer; {@code DescribeStackResource}, the singular action where
+ * the resource is required rather than optional, is the one that raises for a miss.
+ *
+ * <p>Both filters being silently ignored is worse than it sounds for a caller that filters and
+ * then reads the first member: it gets whichever resource the stack happens to list first.
+ * Serverless Framework resolves an AppSync API id exactly that way.
+ */
+ public List<StackResource> describeStackResources(String stackName, String logicalResourceId,
+ String physicalResourceId, String region) {
+ return describeStackResourcesView(stackName, logicalResourceId, physicalResourceId, region).resources();
+ }
+
+ /** The stack a call resolved to and the resources it answered with; the stack's own name is
+ * what AWS stamps on every member, and the caller may not have supplied it. */
+ public record StackResourcesView(String stackName, List<StackResource> resources) {
+ }
+
+ /** @see #describeStackResources(String, String, String, String) */
+ public StackResourcesView describeStackResourcesView(String stackName, String logicalResourceId,
+ String physicalResourceId, String region) {
+ boolean hasStackName = stackName != null && !stackName.isBlank();
+ boolean hasPhysicalId = physicalResourceId != null && !physicalResourceId.isBlank();
+ if (!hasStackName && !hasPhysicalId) {
+ throw new AwsException("ValidationError",
+ "Either StackName or PhysicalResourceId must be specified.", 400);
+ }
+ if (hasStackName && hasPhysicalId) {
+ throw new AwsException("ValidationError",
+ "Cannot specify both StackName and PhysicalResourceId.", 400);
+ }
+
+ // 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)
+ : stackContaining(physicalResourceId, region);
+ List<StackResource> resources = new ArrayList<>(stack.resourcesSnapshot().values());
+
+ // Only a filter on the result. The reference documents no error for a logical id the
+ // stack does not have, and DescribeStackResource, the singular action where the resource
+ // is required rather than optional, is the one that raises for a miss.
+ if (logicalResourceId != null && !logicalResourceId.isBlank()) {
+ resources.removeIf(r -> !logicalResourceId.equals(r.getLogicalId()));
+ }
+ return new StackResourcesView(stack.getStackName(), resources);
+ }
+
+ /**
+ * The stack owning a physical id, for the {@code PhysicalResourceId}-only form of the call.
+ *
+ * <p>Live stacks are considered before deleted ones, newest first within each group.
+ * {@code listStacks} answers oldest first and keeps deleted stacks for their retention window,
+ * so walking it directly resolves a redeployed resource to the stack that used to own it.
+ */
+ private Stack stackContaining(String physicalResourceId, String region) {
+ List<Stack> candidates = new ArrayList<>(listStacks(region));
+ candidates.sort(Comparator
+ .comparing((Stack s) -> "DELETE_COMPLETE".equals(s.getStatus()))
+ .thenComparing(Stack::getCreationTime, Comparator.reverseOrder()));
+ for (Stack stack : candidates) {
+ boolean owns = stack.resourcesSnapshot().values().stream()
+ .anyMatch(r -> physicalResourceId.equals(r.getPhysicalId()));
+ if (owns) {
+ return stack;
+ }
+ }
+ throw new AwsException("ValidationError",
+ "Stack for " + physicalResourceId + " does not exist", 400);
}
// ── ListStacks ────────────────────────────────────────────────────────────
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDescribeStackResourcesFilterIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDescribeStackResourcesFilterIntegrationTest.java
new file mode 100644
index 0000000000..ed60ff2fe9
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDescribeStackResourcesFilterIntegrationTest.java
@@ -0,0 +1,190 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+
+/**
+ * The two filters {@code DescribeStackResources} accepts.
+ *
+ * <p>Ignoring them is quiet rather than loud: a caller that filters and reads the first member
+ * gets whichever resource the stack happens to list first, and nothing in the response says the
+ * filter was dropped. Serverless Framework resolves an AppSync API id exactly that way, which is
+ * how this surfaced (issue #5451).
+ */
+@QuarkusTest
+class CloudFormationDescribeStackResourcesFilterIntegrationTest {
+
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
+
+ private String createStack(String suffix) {
+ return createStack("cfn-dsr-" + suffix, suffix);
+ }
+
+ /** Stack name and resource names chosen separately, so two stacks can own the same physical id. */
+ private String createStack(String stackName, String suffix) {
+ String template = """
+ {
+ "Resources": {
+ "MyQueue": {"Type": "AWS::SQS::Queue", "Properties": {"QueueName": "cfn-dsr-q-%s"}},
+ "MyTopic": {"Type": "AWS::SNS::Topic", "Properties": {"TopicName": "cfn-dsr-t-%s"}}
+ }
+ }
+ """.formatted(suffix, suffix);
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ return stackName;
+ }
+
+ private RequestSpecification describe() {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DescribeStackResources");
+ }
+
+ @Test
+ void logicalResourceIdNarrowsToThatOneResource() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = createStack(suffix);
+
+ describe()
+ .formParam("StackName", stackName)
+ .formParam("LogicalResourceId", "MyTopic")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<LogicalResourceId>MyTopic</LogicalResourceId>"))
+ .body(not(containsString("<LogicalResourceId>MyQueue</LogicalResourceId>")))
+ // AWS stamps the stack's own name on every member.
+ .body(containsString("<StackName>" + stackName + "</StackName>"));
+ }
+
+ @Test
+ void aLogicalResourceIdTheStackDoesNotHaveMatchesNothing() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = createStack(suffix);
+
+ // A filter that matches nothing, not an error: DescribeStackResource, the singular action
+ // where the resource is required rather than optional, is the one that raises for a miss.
+ describe()
+ .formParam("StackName", stackName)
+ .formParam("LogicalResourceId", "NoSuchResource")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(not(containsString("<LogicalResourceId>")));
+ }
+
+ @Test
+ void physicalResourceIdNamesTheStackAndReturnsAllOfIt() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = createStack(suffix);
+ String topicName = "cfn-dsr-t-" + suffix;
+
+ // "the associated resources of the stack that the resource belongs to are returned": the
+ // physical id selects the stack, it does not narrow it to the one resource.
+ describe()
+ .formParam("PhysicalResourceId", "arn:aws:sns:us-east-1:000000000000:" + topicName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<LogicalResourceId>MyTopic</LogicalResourceId>"))
+ .body(containsString("<LogicalResourceId>MyQueue</LogicalResourceId>"))
+ .body(containsString("<StackName>" + stackName + "</StackName>"));
+ }
+
+ @Test
+ void bothStackNameAndPhysicalResourceIdIsAValidationError() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = createStack(suffix);
+
+ describe()
+ .formParam("StackName", stackName)
+ .formParam("PhysicalResourceId", "arn:aws:sns:us-east-1:000000000000:cfn-dsr-t-" + suffix)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("ValidationError"))
+ .body(containsString("Cannot specify both StackName and PhysicalResourceId."));
+ }
+
+ @Test
+ void aRedeployedPhysicalIdResolvesToTheLiveStackNotTheDeletedOne() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String topicArn = "arn:aws:sns:us-east-1:000000000000:cfn-dsr-t-" + suffix;
+ String dead = createStack("cfn-dsr-old-" + suffix, suffix);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", dead)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ // DeleteStack answers before the deletion runs. Without this the old stack can still be
+ // DELETE_IN_PROGRESS when the new one is created, which sorts it with the live stacks and
+ // lets the test pass on creation time alone without ever exercising the deleted branch.
+ CfnStackWaits.awaitStackDeleted(dead);
+
+ // The same resource names under a second, live stack. A deleted stack stays listed for its
+ // retention window and listStacks answers oldest first, so the dead one would win on a
+ // straight walk. The two stacks are named differently so the answer is tellable apart.
+ String live = createStack("cfn-dsr-new-" + suffix, suffix);
+
+ describe()
+ .formParam("PhysicalResourceId", topicArn)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackName>" + live + "</StackName>"))
+ .body(not(containsString("<StackName>" + dead + "</StackName>")));
+ }
+
+ @Test
+ void neitherStackNameNorPhysicalResourceIdIsAValidationError() {
+ describe()
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("ValidationError"))
+ .body(containsString("Either StackName or PhysicalResourceId must be specified."));
+ }
+
+ @Test
+ void withoutAFilterEveryResourceStillComesBack() {
+ String suffix = Long.toString(System.nanoTime(), 36);
+ String stackName = createStack(suffix);
+
+ describe()
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<LogicalResourceId>MyQueue</LogicalResourceId>"))
+ .body(containsString("<LogicalResourceId>MyTopic</LogicalResourceId>"));
+ }
+}