Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(cloudformation): resolve a stack id only to the stack carrying it (#4973)

Allen Sanborn8e98c087fdf4
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 b862ac1968..02ea14bc6d 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
@@ -2938,9 +2938,8 @@ public class CloudFormationService implements ResourceProvider {
}
/**
- * Resolves a stack by name or ARN. When an ARN is provided the stack name
- * is extracted from the ARN path segment ({@code …:stack/<name>/<id>}).
- * Falls back to a linear scan matching on stackId for robustness.
+ * Resolves a live stack by name or ARN. An ARN is a stack id and resolves only to the stack
+ * carrying that exact id, never to a newer stack that reused the name.
*/
private Stack resolveStack(String stackNameOrArn, String region) {
return resolveStack(stackNameOrArn, region, currentAccount());
@@ -2966,7 +2965,9 @@ public class CloudFormationService implements ResourceProvider {
String extractedName = extractStackNameFromArn(stackNameOrArn);
if (extractedName != null) {
stack = stacks.get(stackKey(accountId, extractedName, region));
- if (stack != null) {
+ // A stack id names one stack: a live stack that reused the name is a different
+ // stack, so the id resolves to it only when the ids match.
+ if (stack != null && stackNameOrArn.equals(stack.getStackId())) {
return stack;
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java
index 9afc206cf9..2dc9a2996f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java
@@ -102,6 +102,11 @@ public class CloudFormationTemplateEngine {
this.dynamicReferenceResolver = dynamicReferenceResolver;
}
+ /** The id of the stack this engine resolves for, as {@code AWS::StackId} returns it. */
+ public String stackId() {
+ return stackId;
+ }
+
/**
* Resolves a property value, including CloudFormation dynamic reference syntax
* ({@code {{resolve:ssm:...}}}, {@code {{resolve:secretsmanager:...}}}) in the result, the same
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java
index b973ac13a9..279655e316 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CustomResourceCfnProvisioner.java
@@ -45,6 +45,7 @@ public class CustomResourceCfnProvisioner implements CfnResourceProvisioner {
/** Reserved attribute keys used to carry custom-resource state to the later Delete invocation. */
private static final String CR_SERVICE_TOKEN_ATTR = "__FlociServiceToken";
private static final String CR_PROPERTIES_ATTR = "__FlociResourceProperties";
+ private static final String CR_STACK_ID_ATTR = "__FlociStackId";
/**
* How long to wait for the Lambda's ResponseURL callback after the synchronous invoke returns.
* The invoke already blocks until the handler finishes, so this only covers a PUT that lands
@@ -76,8 +77,6 @@ public class CustomResourceCfnProvisioner implements CfnResourceProvisioner {
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
CloudFormationTemplateEngine engine = ctx.engine();
String region = ctx.region();
- String accountId = ctx.accountId();
- String stackName = ctx.stackName();
if (props == null || !props.has("ServiceToken")) {
throw new AwsException("ValidationError",
"Custom resource " + r.getLogicalId() + " is missing ServiceToken", 400);
@@ -119,7 +118,7 @@ public class CustomResourceCfnProvisioner implements CfnResourceProvisioner {
JsonNode response = invokeCustomResourceHandler(serviceToken, requestType, r.getLogicalId(),
r.getResourceType(), priorPhysicalId, resourceProperties, oldResourceProperties,
- region, accountId, stackName);
+ region, engine.stackId());
String status = response.path("Status").asText("FAILED");
if (!"SUCCESS".equals(status)) {
@@ -147,6 +146,7 @@ public class CustomResourceCfnProvisioner implements CfnResourceProvisioner {
// Stash what a later Delete invocation needs (delete() only gets the StackResource).
r.getAttributes().put(CR_SERVICE_TOKEN_ATTR, serviceToken);
r.getAttributes().put(CR_PROPERTIES_ATTR, resourceProperties.toString());
+ r.getAttributes().put(CR_STACK_ID_ATTR, engine.stackId());
}
@Override
@@ -159,9 +159,11 @@ public class CustomResourceCfnProvisioner implements CfnResourceProvisioner {
ObjectNode stashed = readStashedProperties(r);
ObjectNode resourceProperties = stashed != null ? stashed : objectMapper.createObjectNode();
try {
+ // Resources stashed before the stack id was recorded fall back to a synthetic id.
+ String stackId = r.getAttributes().getOrDefault(CR_STACK_ID_ATTR, AwsArnUtils.Arn.of(
+ "cloudformation", region, accountFromArn(serviceToken), "stack//" + UUID.randomUUID()).toString());
JsonNode response = invokeCustomResourceHandler(serviceToken, "Delete", r.getLogicalId(),
- r.getResourceType(), r.getPhysicalId(), resourceProperties, null, region,
- accountFromArn(serviceToken), "");
+ r.getResourceType(), r.getPhysicalId(), resourceProperties, null, region, stackId);
if (!"SUCCESS".equals(response.path("Status").asText("FAILED"))) {
LOG.warnv("Custom resource {0} Delete reported FAILED: {1}",
r.getLogicalId(), response.path("Reason").asText("(no reason given)"));
@@ -192,14 +194,13 @@ public class CustomResourceCfnProvisioner implements CfnResourceProvisioner {
private JsonNode invokeCustomResourceHandler(String serviceToken, String requestType, String logicalId,
String resourceType, String physicalId,
ObjectNode resourceProperties, ObjectNode oldResourceProperties,
- String region, String accountId, String stackName) {
+ String region, String stackId) {
String token = customResourceResponseStore.register();
try {
ObjectNode event = objectMapper.createObjectNode();
event.put("RequestType", requestType);
event.put("ResponseURL", reachableEndpoint.baseUrl() + "/cfn-response/" + token);
- event.put("StackId", AwsArnUtils.Arn.of("cloudformation", region, accountId, "stack/"
- + (stackName == null ? "" : stackName) + "/" + UUID.randomUUID()).toString());
+ event.put("StackId", stackId);
event.put("RequestId", UUID.randomUUID().toString());
event.put("ResourceType", resourceType);
event.put("LogicalResourceId", logicalId);
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeletedStackByNameIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeletedStackByNameIntegrationTest.java
index 50e5d1b4e3..960dc339dc 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeletedStackByNameIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationDeletedStackByNameIntegrationTest.java
@@ -7,6 +7,8 @@ import org.junit.jupiter.api.Test;
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.assertNotEquals;
/**
* What a client polling a deleted stack by name gets back, per operation. The two wordings are
@@ -37,6 +39,44 @@ class CloudFormationDeletedStackByNameIntegrationTest {
.body(containsString("<Message>Stack with id " + stackName + " does not exist</Message>"));
}
+ /**
+ * A stack id names one stack. After the name is reused, the old id still resolves to the
+ * deleted stack (DELETE_COMPLETE) and the name resolves to the live one; a DeleteStack
+ * aimed at the old id must not reach the live stack that took the name.
+ */
+ @Test
+ void oldStackIdResolvesToTheDeletedStackAfterTheNameIsReused() {
+ String stackName = "reused-name-" + Long.toString(System.nanoTime(), 36);
+ String template = "{\"Resources\":{\"P\":{\"Type\":\"AWS::SSM::Parameter\","
+ + "\"Properties\":{\"Type\":\"String\",\"Value\":\"v\"}}}}";
+ String oldId = cfn("CreateStack", stackName, template).then().statusCode(200)
+ .extract().xmlPath().getString("CreateStackResponse.CreateStackResult.StackId");
+ assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
+ cfn("DeleteStack", stackName, null).then().statusCode(200);
+ awaitGone(stackName);
+ String newId = cfn("CreateStack", stackName, template).then().statusCode(200)
+ .extract().xmlPath().getString("CreateStackResponse.CreateStackResult.StackId");
+ assertNotEquals(oldId, newId);
+ assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
+
+ Response byOldId = cfn("DescribeStacks", oldId, null);
+ byOldId.then().statusCode(200);
+ assertEquals(oldId, byOldId.xmlPath().getString(
+ "DescribeStacksResponse.DescribeStacksResult.Stacks.member.StackId"));
+ assertEquals("DELETE_COMPLETE", byOldId.xmlPath().getString(
+ "DescribeStacksResponse.DescribeStacksResult.Stacks.member.StackStatus"));
+
+ cfn("DeleteStack", oldId, null).then().statusCode(200);
+ Response byName = cfn("DescribeStacks", stackName, null);
+ byName.then().statusCode(200);
+ assertEquals(newId, byName.xmlPath().getString(
+ "DescribeStacksResponse.DescribeStacksResult.Stacks.member.StackId"));
+ assertEquals("CREATE_COMPLETE", byName.xmlPath().getString(
+ "DescribeStacksResponse.DescribeStacksResult.Stacks.member.StackStatus"));
+
+ cfn("DeleteStack", stackName, null).then().statusCode(200);
+ }
+
@Test
void describeStackEventsOnAStackThatNeverExistedUsesTheSameWording() {
cfn("DescribeStackEvents", "never-created", null).then().statusCode(400)
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java
index 1b81ca98dc..55932b58a2 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CustomResourceProvisionerTest.java
@@ -35,6 +35,9 @@ class CustomResourceProvisionerTest {
private static final String SERVICE_TOKEN =
"arn:aws:lambda:us-east-1:000000000000:function:MyHandler";
+ private static final String STACK_ID =
+ "arn:aws:cloudformation:us-east-1:000000000000:stack/my-stack/1b2c3d4e-0000-0000-0000-000000000001";
+
private final ObjectMapper mapper = new ObjectMapper();
private LambdaService lambdaService;
private CustomResourceResponseStore store;
@@ -57,7 +60,7 @@ class CustomResourceProvisionerTest {
private CloudFormationTemplateEngine engine() {
return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",
- "stack/id", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper,
+ STACK_ID, Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper,
(Function<String, String>) name -> null);
}
@@ -105,6 +108,8 @@ class CustomResourceProvisionerTest {
eq(InvocationType.RequestResponse));
JsonNode event = readEvent(payload);
assertEquals("Create", event.get("RequestType").asText());
+ // The real stack id, so a handler can DescribeStacks(event.StackId).
+ assertEquals(STACK_ID, event.get("StackId").asText());
assertTrue(event.get("ResponseURL").asText().startsWith("http://floci:4566/cfn-response/"));
assertEquals("hi", event.get("ResourceProperties").get("Message").asText());
// CloudFormation carries ServiceToken both at the top level and inside ResourceProperties.
@@ -137,6 +142,7 @@ class CustomResourceProvisionerTest {
eq(InvocationType.RequestResponse));
JsonNode event = readEvent(payload);
assertEquals("Update", event.get("RequestType").asText());
+ assertEquals(STACK_ID, event.get("StackId").asText());
assertEquals("phys-123", event.get("PhysicalResourceId").asText());
assertEquals("hi", event.get("ResourceProperties").get("Message").asText());
// CloudFormation includes the previous properties on Update so handlers can diff.
@@ -218,6 +224,7 @@ class CustomResourceProvisionerTest {
eq(InvocationType.RequestResponse));
JsonNode deleteEvent = readEvent(() -> payloads.getAllValues().get(1));
assertEquals("Delete", deleteEvent.get("RequestType").asText());
+ assertEquals(STACK_ID, deleteEvent.get("StackId").asText());
assertEquals("phys-123", deleteEvent.get("PhysicalResourceId").asText());
assertEquals("hi", deleteEvent.get("ResourceProperties").get("Message").asText());
}