Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(cloudformation): honor UsePreviousTemplate on updates (#5015)

Matheus Oliveiraf9a65581beec
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 6289d321d5..2a4c2c0c18 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
@@ -145,12 +145,18 @@ public class CloudFormationQueryHandler {
String stackName = params.getFirst("StackName");
String templateBody = params.getFirst("TemplateBody");
String templateUrl = params.getFirst("TemplateURL");
+ boolean usePreviousTemplate = Boolean.parseBoolean(params.getFirst("UsePreviousTemplate"));
+ cfnService.validateTemplateSource(templateBody, templateUrl, usePreviousTemplate);
Map<String, String> parameters =
extractParameters(params, cfnService.currentParameters(stackName, region));
List<String> capabilities = extractList(params, "Capabilities.member.");
- ChangeSet cs = cfnService.createChangeSet(stackName, "update-" + UUID.randomUUID().toString().substring(0, 8),
- "UPDATE", templateBody, templateUrl, parameters, capabilities, Map.of(), region);
+ String changeSetName = "update-" + UUID.randomUUID().toString().substring(0, 8);
+ ChangeSet cs = usePreviousTemplate
+ ? cfnService.createChangeSetFromPreviousTemplate(stackName, changeSetName,
+ parameters, capabilities, Map.of(), region)
+ : cfnService.createChangeSet(stackName, changeSetName,
+ "UPDATE", templateBody, templateUrl, parameters, capabilities, Map.of(), region);
awaitExecution(cfnService.executeChangeSet(stackName, cs.getChangeSetName(), region));
Stack stack = cfnService.describeStacks(stackName, region).get(0);
@@ -211,6 +217,12 @@ public class CloudFormationQueryHandler {
String changeSetType = params.getFirst("ChangeSetType");
String templateBody = params.getFirst("TemplateBody");
String templateUrl = params.getFirst("TemplateURL");
+ boolean usePreviousTemplate = Boolean.parseBoolean(params.getFirst("UsePreviousTemplate"));
+ if (usePreviousTemplate && "CREATE".equalsIgnoreCase(changeSetType)) {
+ throw new AwsException("ValidationError",
+ "UsePreviousTemplate cannot be specified for a CREATE change set", 400);
+ }
+ cfnService.validateTemplateSource(templateBody, templateUrl, usePreviousTemplate);
Map<String, String> parameters =
extractParameters(params, cfnService.currentParameters(stackName, region));
List<String> capabilities = extractList(params, "Capabilities.member.");
@@ -218,8 +230,11 @@ public class CloudFormationQueryHandler {
// The CreateChangeSet operation, unlike the change sets CreateStack/UpdateStack build
// internally, may attach a CREATE change set to a stack still in REVIEW_IN_PROGRESS.
- ChangeSet cs = cfnService.createChangeSetForRequest(stackName, changeSetName, changeSetType,
- templateBody, templateUrl, parameters, capabilities, tags, region);
+ ChangeSet cs = usePreviousTemplate
+ ? cfnService.createChangeSetFromPreviousTemplate(stackName, changeSetName,
+ parameters, capabilities, tags, region)
+ : cfnService.createChangeSetForRequest(stackName, changeSetName, changeSetType,
+ templateBody, templateUrl, parameters, capabilities, tags, region);
String xml = new XmlBuilder()
.start("CreateChangeSetResponse", CF_NS)
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 af028ef0a7..055918d7b8 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
@@ -242,6 +242,54 @@ public class CloudFormationService implements ResourceProvider {
&& (status.endsWith("_IN_PROGRESS") || "ROLLBACK_COMPLETE".equals(status));
}
+ /**
+ * Validates the template source of an {@code UpdateStack} or {@code CreateChangeSet} request:
+ * {@code UsePreviousTemplate} excludes {@code TemplateBody} and {@code TemplateURL}, and
+ * without it one of the two is required.
+ */
+ public void validateTemplateSource(String templateBody, String templateUrl, boolean usePreviousTemplate) {
+ boolean hasTemplate = (templateBody != null && !templateBody.isBlank())
+ || (templateUrl != null && !templateUrl.isBlank());
+ if (usePreviousTemplate && hasTemplate) {
+ throw new AwsException("ValidationError",
+ "UsePreviousTemplate cannot be specified together with TemplateBody or TemplateURL", 400);
+ }
+ if (!usePreviousTemplate && !hasTemplate) {
+ throw new AwsException("ValidationError",
+ "Either Template URL or Template Body must be specified.", 400);
+ }
+ }
+
+ /**
+ * Creates an UPDATE change set from the template the stack currently holds, as submitted
+ * rather than SAM- or Include-expanded, so executing it keeps {@code GetTemplate}'s Original
+ * stage intact. The template is read outside the stack's lock, so the change set is only
+ * recorded if no other update replaced it in the meantime; otherwise it is read again.
+ */
+ public ChangeSet createChangeSetFromPreviousTemplate(String stackName, String changeSetName,
+ Map<String, String> parameters,
+ List<String> capabilities,
+ Map<String, String> tags, String region) {
+ ChangeSet created = null;
+ while (created == null) {
+ Stack stack = resolveStack(stackName, region);
+ if (stack == null) {
+ throw new AwsException("ValidationError",
+ "Stack with id " + stackName + " does not exist", 400);
+ }
+ String previousTemplate = previousTemplateOf(stack);
+ created = createChangeSet(stackName, changeSetName, "UPDATE", previousTemplate, null,
+ parameters, capabilities, tags, region, currentAccount(), false, true);
+ }
+ return created;
+ }
+
+ private static String previousTemplateOf(Stack stack) {
+ return stack.getOriginalTemplateBody() != null
+ ? stack.getOriginalTemplateBody()
+ : stack.getTemplateBody();
+ }
+
// ── CreateChangeSet ───────────────────────────────────────────────────────
public ChangeSet createChangeSet(String stackName, String changeSetName, String changeSetType,
@@ -249,7 +297,7 @@ public class CloudFormationService implements ResourceProvider {
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region) {
return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
- parameters, capabilities, tags, region, regionResolver.getAccountId(), false);
+ parameters, capabilities, tags, region, regionResolver.getAccountId(), false, false);
}
/**
@@ -273,7 +321,7 @@ public class CloudFormationService implements ResourceProvider {
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region) {
return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
- parameters, capabilities, tags, region, regionResolver.getAccountId(), true);
+ parameters, capabilities, tags, region, regionResolver.getAccountId(), true, false);
}
/**
@@ -291,14 +339,14 @@ public class CloudFormationService implements ResourceProvider {
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region, String accountId) {
return createChangeSet(stackName, changeSetName, changeSetType, templateBody, templateUrl,
- parameters, capabilities, tags, region, accountId, false);
+ parameters, capabilities, tags, region, accountId, false, false);
}
private ChangeSet createChangeSet(String stackName, String changeSetName, String changeSetType,
String templateBody, String templateUrl,
Map<String, String> parameters, List<String> capabilities,
Map<String, String> tags, String region, String accountId,
- boolean attachToReviewInProgressStack) {
+ boolean attachToReviewInProgressStack, boolean fromPreviousTemplate) {
String resolvedTemplate = resolveTemplate(templateBody, templateUrl);
// Real CloudFormation runs a declared macro (here, only AWS::Serverless-2016-10-31)
@@ -380,6 +428,9 @@ public class CloudFormationService implements ResourceProvider {
"Stack:" + existing.getStackId() + " is in " + existing.getStatus()
+ " state and can not be updated.", 400);
}
+ if (fromPreviousTemplate && !Objects.equals(templateBody, previousTemplateOf(existing))) {
+ return existing;
+ }
target = existing;
}
@@ -405,7 +456,9 @@ public class CloudFormationService implements ResourceProvider {
return target;
});
- persistStack(stack);
+ if (created[0] != null) {
+ persistStack(stack);
+ }
return created[0];
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationUsePreviousTemplateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationUsePreviousTemplateIntegrationTest.java
new file mode 100644
index 0000000000..3a0b7570b5
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationUsePreviousTemplateIntegrationTest.java
@@ -0,0 +1,185 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.Response;
+import org.junit.jupiter.api.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+
+/**
+ * UpdateStack and CreateChangeSet with {@code UsePreviousTemplate=true} reuse the template the
+ * stack currently holds instead of falling back to an empty one.
+ */
+@QuarkusTest
+class CloudFormationUsePreviousTemplateIntegrationTest {
+
+ private static final String FORM = "application/x-www-form-urlencoded";
+
+ private static final String TEMPLATE = """
+ {"Parameters":{"Timeout":{"Type":"Number","Default":"30"}},
+ "Resources":{"Queue":{"Type":"AWS::SQS::Queue",
+ "Properties":{"QueueName":"%s","VisibilityTimeout":{"Ref":"Timeout"}}}}}
+ """;
+
+ private void createStack(String stackName, String queueName) {
+ given().contentType(FORM)
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .formParam("TemplateBody", TEMPLATE.formatted(queueName))
+ .when().post("/")
+ .then().statusCode(200);
+ }
+
+ private String visibilityTimeout(String queueName) {
+ Response url = given().contentType(FORM)
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", queueName)
+ .when().post("/");
+ String queueUrl = url.xmlPath().getString("GetQueueUrlResponse.GetQueueUrlResult.QueueUrl");
+ return given().contentType(FORM)
+ .formParam("Action", "GetQueueAttributes")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("AttributeName.1", "VisibilityTimeout")
+ .when().post("/")
+ .xmlPath().getString("GetQueueAttributesResponse.GetQueueAttributesResult.Attribute.Value");
+ }
+
+ @Test
+ void updateStack_usePreviousTemplate_appliesNewParametersAndKeepsTemplate() {
+ createStack("use-prev-update", "use-prev-update-q");
+
+ given().contentType(FORM)
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", "use-prev-update")
+ .formParam("UsePreviousTemplate", "true")
+ .formParam("Parameters.member.1.ParameterKey", "Timeout")
+ .formParam("Parameters.member.1.ParameterValue", "60")
+ .when().post("/")
+ .then().statusCode(200);
+
+ assertEquals("60", visibilityTimeout("use-prev-update-q"));
+
+ given().contentType(FORM)
+ .formParam("Action", "GetTemplate")
+ .formParam("StackName", "use-prev-update")
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("use-prev-update-q"))
+ .body(containsString("VisibilityTimeout"));
+ }
+
+ @Test
+ void updateStack_usePreviousTemplateOnSamStack_keepsSubmittedTemplateAsOriginal() {
+ String samTemplate = """
+ {"Transform":"AWS::Serverless-2016-10-31",
+ "Parameters":{"Memory":{"Type":"Number","Default":"128"}},
+ "Resources":{"Fn":{"Type":"AWS::Serverless::Function",
+ "Properties":{"Handler":"index.handler","Runtime":"nodejs22.x",
+ "InlineCode":"exports.handler = async () => {};",
+ "MemorySize":{"Ref":"Memory"}}}}}
+ """;
+ given().contentType(FORM)
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", "use-prev-sam")
+ .formParam("TemplateBody", samTemplate)
+ .when().post("/")
+ .then().statusCode(200);
+
+ given().contentType(FORM)
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", "use-prev-sam")
+ .formParam("UsePreviousTemplate", "true")
+ .formParam("Parameters.member.1.ParameterKey", "Memory")
+ .formParam("Parameters.member.1.ParameterValue", "256")
+ .when().post("/")
+ .then().statusCode(200);
+
+ given().contentType(FORM)
+ .formParam("Action", "GetTemplate")
+ .formParam("StackName", "use-prev-sam")
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("AWS::Serverless::Function"))
+ .body(not(containsString("AWS::Lambda::Function")));
+ }
+
+ @Test
+ void createChangeSet_usePreviousTemplate_previewsModifyNotRemove() {
+ createStack("use-prev-cs", "use-prev-cs-q");
+
+ given().contentType(FORM)
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", "use-prev-cs")
+ .formParam("ChangeSetName", "parameter-only")
+ .formParam("ChangeSetType", "UPDATE")
+ .formParam("UsePreviousTemplate", "true")
+ .formParam("Parameters.member.1.ParameterKey", "Timeout")
+ .formParam("Parameters.member.1.ParameterValue", "60")
+ .when().post("/")
+ .then().statusCode(200);
+
+ given().contentType(FORM)
+ .formParam("Action", "DescribeChangeSet")
+ .formParam("StackName", "use-prev-cs")
+ .formParam("ChangeSetName", "parameter-only")
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("<Action>Modify</Action>"))
+ .body(not(containsString("<Action>Remove</Action>")));
+ }
+
+ @Test
+ void updateStack_usePreviousTemplateWithTemplateBody_returnsValidationError() {
+ createStack("use-prev-both", "use-prev-both-q");
+
+ given().contentType(FORM)
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", "use-prev-both")
+ .formParam("UsePreviousTemplate", "true")
+ .formParam("TemplateBody", TEMPLATE.formatted("use-prev-both-q"))
+ .when().post("/")
+ .then().statusCode(400)
+ .body(containsString("<Code>ValidationError</Code>"));
+ }
+
+ @Test
+ void updateStack_withoutAnyTemplateSource_returnsValidationError() {
+ createStack("use-prev-none", "use-prev-none-q");
+
+ given().contentType(FORM)
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", "use-prev-none")
+ .when().post("/")
+ .then().statusCode(400)
+ .body(containsString("<Code>ValidationError</Code>"))
+ .body(containsString("Either Template URL or Template Body must be specified."));
+ }
+
+ @Test
+ void createChangeSet_usePreviousTemplateOnCreateType_returnsValidationError() {
+ given().contentType(FORM)
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", "use-prev-create-type")
+ .formParam("ChangeSetName", "cs")
+ .formParam("ChangeSetType", "CREATE")
+ .formParam("UsePreviousTemplate", "true")
+ .when().post("/")
+ .then().statusCode(400)
+ .body(containsString("<Code>ValidationError</Code>"));
+ }
+
+ @Test
+ void updateStack_usePreviousTemplateOnMissingStack_returnsValidationError() {
+ given().contentType(FORM)
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", "use-prev-missing")
+ .formParam("UsePreviousTemplate", "true")
+ .when().post("/")
+ .then().statusCode(400)
+ .body(containsString("<Code>ValidationError</Code>"))
+ .body(containsString("does not exist"));
+ }
+}