Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(cloudformation): accept the stack ID in UpdateStack and CreateChangeSet (#4846)

Mario Toffiaefd951257877
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackIdTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackIdTest.java
new file mode 100644
index 0000000000..965f0f2bd6
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackIdTest.java
@@ -0,0 +1,217 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
+import software.amazon.awssdk.services.cloudformation.model.ChangeSetType;
+import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
+import software.amazon.awssdk.services.cloudformation.model.CreateChangeSetResponse;
+import software.amazon.awssdk.services.cloudformation.model.DescribeChangeSetResponse;
+import software.amazon.awssdk.services.cloudformation.model.Parameter;
+import software.amazon.awssdk.services.cloudformation.model.Stack;
+import software.amazon.awssdk.services.cloudformation.model.UpdateStackResponse;
+import software.amazon.awssdk.services.ssm.SsmClient;
+
+import java.util.List;
+import java.util.function.BooleanSupplier;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+@DisplayName("CloudFormation StackName given as the stack ID")
+class CloudFormationStackIdTest {
+
+ private static final String TEMPLATE = """
+ {
+ "Parameters": {
+ "ParameterName": {"Type": "String"},
+ "ParameterValue": {"Type": "String"}
+ },
+ "Resources": {
+ "Param": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": {"Ref": "ParameterName"},
+ "Type": "String",
+ "Value": {"Ref": "ParameterValue"}
+ }
+ }
+ }
+ }
+ """;
+
+ private static CloudFormationClient cfn;
+ private static SsmClient ssm;
+ private String stackName;
+ private String parameterName;
+ private boolean stackCreated;
+
+ @BeforeAll
+ static void clients() {
+ cfn = TestFixtures.cloudFormationClient();
+ ssm = TestFixtures.ssmClient();
+ }
+
+ @BeforeEach
+ void setup() {
+ stackName = TestFixtures.uniqueName("compat-cfn-stack-id");
+ parameterName = "/" + stackName;
+ }
+
+ @AfterEach
+ void cleanup() throws InterruptedException {
+ deleteStack();
+ }
+
+ @AfterAll
+ static void closeClients() {
+ cfn.close();
+ ssm.close();
+ }
+
+ @Test
+ @DisplayName("UpdateStack accepts the stack ID as StackName")
+ void updateStackByStackId() throws InterruptedException {
+ String stackId = createStack("first");
+
+ UpdateStackResponse updated = cfn.updateStack(r -> r.stackName(stackId).templateBody(TEMPLATE)
+ .parameters(parameters("second")));
+
+ assertThat(updated.stackId()).isEqualTo(stackId);
+ awaitStatus("UPDATE_COMPLETE");
+ assertThat(parameterValue()).isEqualTo("second");
+ }
+
+ @Test
+ @DisplayName("CreateChangeSet of type UPDATE accepts the stack ID as StackName")
+ void createUpdateChangeSetByStackId() throws InterruptedException {
+ String stackId = createStack("first");
+
+ CreateChangeSetResponse created = cfn.createChangeSet(r -> r.stackName(stackId)
+ .changeSetName("update-by-stack-id").changeSetType(ChangeSetType.UPDATE)
+ .templateBody(TEMPLATE).parameters(parameters("second")));
+
+ assertThat(created.stackId()).isEqualTo(stackId);
+ await(() -> "CREATE_COMPLETE".equals(describeChangeSet(created.id(), stackId).statusAsString()),
+ "change set CREATE_COMPLETE");
+ DescribeChangeSetResponse described = describeChangeSet(created.id(), stackId);
+ assertThat(described.stackName()).isEqualTo(stackName);
+ assertThat(described.stackId()).isEqualTo(stackId);
+
+ cfn.executeChangeSet(r -> r.changeSetName(created.id()).stackName(stackId));
+ awaitStatus("UPDATE_COMPLETE");
+ assertThat(parameterValue()).isEqualTo("second");
+ }
+
+ @Test
+ @DisplayName("A deleted stack's ID does not update a new stack of the same name")
+ void staleStackIdIsRejected() throws InterruptedException {
+ String staleStackId = createStack("first");
+ String refusal = "Stack:" + staleStackId + " is in DELETE_COMPLETE state and can not be updated.";
+ deleteStack();
+ assertThatThrownBy(() -> cfn.updateStack(r -> r.stackName(staleStackId).templateBody(TEMPLATE)
+ .parameters(parameters("second"))))
+ .isInstanceOfSatisfying(CloudFormationException.class, e -> {
+ assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError");
+ assertThat(e.awsErrorDetails().errorMessage()).isEqualTo(refusal);
+ });
+ String currentStackId = createStack("first");
+ assertThat(currentStackId).isNotEqualTo(staleStackId);
+
+ assertThatThrownBy(() -> cfn.updateStack(r -> r.stackName(staleStackId).templateBody(TEMPLATE)
+ .parameters(parameters("second"))))
+ .isInstanceOfSatisfying(CloudFormationException.class, e -> {
+ assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError");
+ assertThat(e.awsErrorDetails().errorMessage()).isEqualTo(refusal);
+ });
+ assertThatThrownBy(() -> cfn.createChangeSet(r -> r.stackName(staleStackId)
+ .changeSetName("update-by-stale-stack-id").changeSetType(ChangeSetType.UPDATE)
+ .templateBody(TEMPLATE).parameters(parameters("second"))))
+ .isInstanceOfSatisfying(CloudFormationException.class, e -> {
+ assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError");
+ assertThat(e.awsErrorDetails().errorMessage()).isEqualTo(refusal);
+ });
+
+ Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);
+ assertThat(stack.stackId()).isEqualTo(currentStackId);
+ assertThat(stack.stackStatusAsString()).isEqualTo("CREATE_COMPLETE");
+ assertThat(parameterValue()).isEqualTo("first");
+ }
+
+ private String createStack(String value) throws InterruptedException {
+ String stackId = cfn.createStack(r -> r.stackName(stackName).templateBody(TEMPLATE)
+ .parameters(parameters(value))).stackId();
+ stackCreated = true;
+ awaitStatus("CREATE_COMPLETE");
+ assertThat(parameterValue()).isEqualTo(value);
+ return stackId;
+ }
+
+ private List<Parameter> parameters(String value) {
+ return List.of(
+ Parameter.builder().parameterKey("ParameterName").parameterValue(parameterName).build(),
+ Parameter.builder().parameterKey("ParameterValue").parameterValue(value).build());
+ }
+
+ private DescribeChangeSetResponse describeChangeSet(String changeSetId, String stackId) {
+ return cfn.describeChangeSet(r -> r.changeSetName(changeSetId).stackName(stackId));
+ }
+
+ private String parameterValue() {
+ return ssm.getParameter(r -> r.name(parameterName)).parameter().value();
+ }
+
+ private void awaitStatus(String expected) throws InterruptedException {
+ await(() -> {
+ Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);
+ String status = stack.stackStatusAsString();
+ if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) {
+ throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason());
+ }
+ return expected.equals(status);
+ }, expected);
+ }
+
+ private void deleteStack() throws InterruptedException {
+ if (!stackCreated) {
+ return;
+ }
+ cfn.deleteStack(r -> r.stackName(stackName));
+ await(() -> {
+ try {
+ List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks();
+ if (stacks.isEmpty()) {
+ return true;
+ }
+ Stack stack = stacks.get(0);
+ if ("DELETE_FAILED".equals(stack.stackStatusAsString())) {
+ throw new AssertionError(stackName + " deletion failed: " + stack.stackStatusReason());
+ }
+ // The name is free only once DescribeStacks no longer finds it.
+ return false;
+ } catch (CloudFormationException e) {
+ if ("ValidationError".equals(e.awsErrorDetails().errorCode())
+ && e.getMessage().contains("does not exist")) {
+ return true;
+ }
+ throw e;
+ }
+ }, "stack deletion");
+ stackCreated = false;
+ }
+
+ private void await(BooleanSupplier condition, String expected) throws InterruptedException {
+ long deadline = System.nanoTime() + (TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L);
+ while (System.nanoTime() < deadline) {
+ if (condition.getAsBoolean()) {
+ return;
+ }
+ Thread.sleep(TestFixtures.isRealAws() ? 5_000 : 100);
+ }
+ throw new AssertionError(stackName + " timed out waiting for " + expected);
+ }
+}
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 bcfeba4334..bd0b6a1381 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
@@ -392,13 +392,16 @@ public class CloudFormationService implements ResourceProvider {
// persistStack() stays outside: it is storage I/O, and compute()'s contract is that the
// remapping function does short, non-blocking work.
boolean isCreateType = changeSetType == null || "CREATE".equalsIgnoreCase(changeSetType);
+ // An update names its stack by name or stack ID; the map is keyed by name. One that names no
+ // live stack is keyed as given, so it lands in the missing-stack branch below.
+ Stack live = isCreateType ? null : resolveStack(stackName, region, accountId);
+ String canonicalStackName = live == null ? stackName : live.getStackName();
ChangeSet[] created = new ChangeSet[1];
- Stack stack = stacks.compute(stackKey(accountId, stackName, region), (k, existing) -> {
+ Stack stack = stacks.compute(stackKey(accountId, canonicalStackName, region), (k, existing) -> {
Stack target;
if (existing == null) {
if (!isCreateType) {
- throw new AwsException("ValidationError",
- "Stack with id " + stackName + " does not exist", 400);
+ throw noStackToUpdate(stackName, region, accountId);
}
target = newStack(stackName, region, accountId);
if (tags != null) target.getTags().putAll(tags);
@@ -412,19 +415,24 @@ public class CloudFormationService implements ResourceProvider {
"AWS::CloudFormation::Stack", "REVIEW_IN_PROGRESS", "User Initiated");
}
} else {
+ String status = existing.getStatus();
boolean reusableReviewPlaceholder =
- attachToReviewInProgressStack && "REVIEW_IN_PROGRESS".equals(existing.getStatus());
+ attachToReviewInProgressStack && "REVIEW_IN_PROGRESS".equals(status);
if (isCreateType && !reusableReviewPlaceholder) {
throw new AwsException("AlreadyExistsException",
"Stack [" + stackName + "] already exists", 400);
}
+ // A name whose stack has finished deleting names no live stack, even before it leaves the
+ // map, and neither does a stack ID that is not the live stack's.
+ if (!isCreateType && !stackName.equals(existing.getStackId())
+ && ("DELETE_COMPLETE".equals(status) || AwsArnUtils.isArn(stackName))) {
+ throw noStackToUpdate(stackName, region, accountId);
+ }
// The message is the one real CloudFormation emits, down to its own "can not"
// spelling and the stack id carried as "Stack:<arn>" with no space: clients match
// on this string.
- if (!isCreateType && refusesUpdate(existing.getStatus())) {
- throw new AwsException("ValidationError",
- "Stack:" + existing.getStackId() + " is in " + existing.getStatus()
- + " state and can not be updated.", 400);
+ if (!isCreateType && (refusesUpdate(status) || "DELETE_COMPLETE".equals(status))) {
+ throw cannotBeUpdated(existing.getStackId(), status);
}
if (fromPreviousTemplate && !Objects.equals(templateBody, previousTemplateOf(existing))) {
return existing;
@@ -435,7 +443,7 @@ public class CloudFormationService implements ResourceProvider {
ChangeSet cs = new ChangeSet();
cs.setChangeSetId(AwsArnUtils.Arn.of("cloudformation", region, accountId, "changeSet/" + changeSetName + "/" + UUID.randomUUID()).toString());
cs.setChangeSetName(changeSetName);
- cs.setStackName(stackName);
+ cs.setStackName(canonicalStackName);
cs.setStackId(target.getStackId());
cs.setChangeSetType(changeSetType != null ? changeSetType : "CREATE");
cs.setTemplateBody(resolvedTemplate);
@@ -461,6 +469,21 @@ public class CloudFormationService implements ResourceProvider {
return created[0];
}
+ private static AwsException cannotBeUpdated(String stackId, String status) {
+ return new AwsException("ValidationError",
+ "Stack:" + stackId + " is in " + status + " state and can not be updated.", 400);
+ }
+
+ // AWS refuses a deleted stack's ID by its state, while a name, or an ID it never issued,
+ // does not exist.
+ private AwsException noStackToUpdate(String stackName, String region, String accountId) {
+ Stack deleted = resolveDeletedStack(stackName, region, accountId);
+ if (deleted != null) {
+ return cannotBeUpdated(deleted.getStackId(), deleted.getStatus());
+ }
+ return new AwsException("ValidationError", "Stack with id " + stackName + " does not exist", 400);
+ }
+
/**
* Returns the change set's {@code StatusReason} when {@code templateBody} declares the SAM
* transform and that transform fails, {@code null} when the transform is absent or succeeds.
@@ -2883,6 +2906,10 @@ public class CloudFormationService implements ResourceProvider {
if (stack != null) {
return stack;
}
+ return resolveDeletedStack(stackNameOrArn, region, accountId);
+ }
+
+ private Stack resolveDeletedStack(String stackNameOrArn, String region, String accountId) {
if (stackNameOrArn != null && stackNameOrArn.startsWith("arn:")) {
DeletedStackEntry deleted = deletedStacks.get(stackNameOrArn);
if (deleted != null) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java
index 1e1e89ffb0..985a9c2d67 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationServiceRollbackTest.java
@@ -19,6 +19,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Clock;
+import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -37,7 +38,8 @@ import static org.mockito.Mockito.when;
/**
* Covers rollback cleanup when another actor removes a resource after its create succeeded, and
- * which resources a stack delete walks after a failed operation left them in a failed status.
+ * which resources a stack delete walks after a failed operation left them in a failed status, and
+ * that a stack which finished deleting is no longer updatable.
*/
class CloudFormationServiceRollbackTest {
@@ -171,6 +173,27 @@ class CloudFormationServiceRollbackTest {
assertEquals("DELETE_FAILED", bucket.getStatus());
}
+ @Test
+ void updateChangeSet_onStackThatFinishedDeleting_refusesItsIdAndMissesItsName() {
+ String template = "{\"Resources\":{\"Queue\":{\"Type\":\"AWS::SQS::Queue\"}}}";
+ service.createChangeSet("finished-deleting", "create", "CREATE", template, null,
+ Map.of(), List.of(), Map.of(), REGION, ACCOUNT);
+ Stack stack = service.describeStacks("finished-deleting", REGION, ACCOUNT).getFirst();
+ // A delete marks the stack DELETE_COMPLETE before it leaves the live map.
+ stack.setStatus("DELETE_COMPLETE");
+
+ for (String nameOrId : List.of(stack.getStackName(), stack.getStackId())) {
+ AwsException error = assertThrows(AwsException.class, () -> service.createChangeSet(
+ nameOrId, "update", "UPDATE", template, null, Map.of(), List.of(), Map.of(),
+ REGION, ACCOUNT));
+ assertEquals("ValidationError", error.getErrorCode());
+ assertEquals(nameOrId.equals(stack.getStackId())
+ ? "Stack:" + nameOrId + " is in DELETE_COMPLETE state and can not be updated."
+ : "Stack with id " + nameOrId + " does not exist", error.getMessage());
+ }
+ assertEquals(Set.of("create"), stack.getChangeSets().keySet());
+ }
+
private static StackResource resource(String logicalId, String physicalId, String resourceType, String status) {
StackResource resource = new StackResource();
resource.setLogicalId(logicalId);
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackIdUpdateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackIdUpdateIntegrationTest.java
new file mode 100644
index 0000000000..f27628bc47
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackIdUpdateIntegrationTest.java
@@ -0,0 +1,258 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.path.xml.XmlPath;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.not;
+
+/**
+ * UpdateStack and CreateChangeSet take "the name or the unique stack ID" as StackName. An UPDATE
+ * change set given the stack ID has to land on the stack that ID names, not on a new key spelled
+ * like the ARN (floci-io/floci#4842).
+ */
+@QuarkusTest
+class CloudFormationStackIdUpdateIntegrationTest {
+
+ private static final String TEMPLATE = """
+ {
+ "Parameters": {
+ "ParameterName": {"Type": "String"},
+ "ParameterValue": {"Type": "String"}
+ },
+ "Resources": {
+ "Param": {
+ "Type": "AWS::SSM::Parameter",
+ "Properties": {
+ "Name": {"Ref": "ParameterName"},
+ "Type": "String",
+ "Value": {"Ref": "ParameterValue"}
+ }
+ }
+ }
+ }
+ """;
+
+ private final Set<String> stacksToDelete = new LinkedHashSet<>();
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @AfterEach
+ void deleteStacks() {
+ for (String stackName : stacksToDelete) {
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/");
+ }
+ stacksToDelete.clear();
+ }
+
+ @Test
+ void updateStackAcceptsTheStackId() {
+ String stackName = "stack-id-update-" + Long.toString(System.nanoTime(), 36);
+ String stackId = createStack(stackName);
+
+ withParameters(stackName, "second")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackId)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("<StackId>" + stackId + "</StackId>"));
+
+ assertThat(CfnStackWaits.awaitTerminal(stackName).status(), equalTo("UPDATE_COMPLETE"));
+ assertThat(parameterValue(stackName), equalTo("second"));
+ }
+
+ @Test
+ void updateChangeSetAcceptsTheStackId() {
+ String stackName = "stack-id-changeset-" + Long.toString(System.nanoTime(), 36);
+ String stackId = createStack(stackName);
+
+ XmlPath created = withParameters(stackName, "second")
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", stackId)
+ .formParam("ChangeSetName", "update-by-stack-id")
+ .formParam("ChangeSetType", "UPDATE")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath();
+ assertThat(created.getString("CreateChangeSetResponse.CreateChangeSetResult.StackId"), equalTo(stackId));
+ String changeSetId = created.getString("CreateChangeSetResponse.CreateChangeSetResult.Id");
+
+ XmlPath described = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeChangeSet")
+ .formParam("StackName", stackId)
+ .formParam("ChangeSetName", changeSetId)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath();
+ assertThat(described.getString("DescribeChangeSetResponse.DescribeChangeSetResult.StackName"),
+ equalTo(stackName));
+ assertThat(described.getString("DescribeChangeSetResponse.DescribeChangeSetResult.StackId"),
+ equalTo(stackId));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ExecuteChangeSet")
+ .formParam("StackName", stackId)
+ .formParam("ChangeSetName", changeSetId)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ assertThat(CfnStackWaits.awaitTerminal(stackName).status(), equalTo("UPDATE_COMPLETE"));
+ assertThat(parameterValue(stackName), equalTo("second"));
+ }
+
+ @Test
+ void updateStackWithTheArnOfAnUnknownStackIsAValidationError() {
+ String stackId = "arn:aws:cloudformation:us-east-1:000000000000:stack/stack-id-missing-"
+ + Long.toString(System.nanoTime(), 36) + "/00000000-0000-0000-0000-000000000000";
+
+ withParameters("stack-id-missing", "second")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", stackId)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("<Code>ValidationError</Code>"))
+ .body(containsString("Stack with id " + stackId + " does not exist"));
+ }
+
+ @Test
+ void aDeletedStackIdDoesNotUpdateANewStackOfTheSameName() {
+ String stackName = "stack-id-stale-" + Long.toString(System.nanoTime(), 36);
+ String staleStackId = createStack(stackName);
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteStack")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+ CfnStackWaits.awaitStackDeleted(stackName);
+ String refusal = "Stack:" + staleStackId + " is in DELETE_COMPLETE state and can not be updated.";
+ withParameters(stackName, "second")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", staleStackId)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("<Code>ValidationError</Code>"))
+ .body(containsString(refusal));
+ String currentStackId = createStack(stackName);
+
+ withParameters(stackName, "second")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", staleStackId)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("<Code>ValidationError</Code>"))
+ .body(containsString(refusal));
+ withParameters(stackName, "second")
+ .formParam("Action", "CreateChangeSet")
+ .formParam("StackName", staleStackId)
+ .formParam("ChangeSetName", "update-by-stale-stack-id")
+ .formParam("ChangeSetType", "UPDATE")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(400)
+ .body(containsString("<Code>ValidationError</Code>"))
+ .body(containsString(refusal));
+
+ assertThat(CfnStackWaits.awaitTerminal(stackName).status(), equalTo("CREATE_COMPLETE"));
+ assertThat(stackId(stackName), equalTo(currentStackId));
+ assertThat(parameterValue(stackName), equalTo("first"));
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListChangeSets")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(not(containsString("update-by-stale-stack-id")));
+ }
+
+ private String createStack(String stackName) {
+ stacksToDelete.add(stackName);
+ String stackId = withParameters(stackName, "first")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath()
+ .getString("CreateStackResponse.CreateStackResult.StackId");
+ assertThat(CfnStackWaits.awaitTerminal(stackName).status(), equalTo("CREATE_COMPLETE"));
+ assertThat(parameterValue(stackName), equalTo("first"));
+ return stackId;
+ }
+
+ private static RequestSpecification withParameters(String stackName, String value) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("TemplateBody", TEMPLATE)
+ .formParam("Parameters.member.1.ParameterKey", "ParameterName")
+ .formParam("Parameters.member.1.ParameterValue", "/" + stackName)
+ .formParam("Parameters.member.2.ParameterKey", "ParameterValue")
+ .formParam("Parameters.member.2.ParameterValue", value);
+ }
+
+ private static String stackId(String stackName) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", stackName)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().xmlPath()
+ .getString("DescribeStacksResponse.DescribeStacksResult.Stacks.member.StackId");
+ }
+
+ private static String parameterValue(String stackName) {
+ return given()
+ .header("X-Amz-Target", "AmazonSSM.GetParameter")
+ .contentType("application/x-amz-json-1.1")
+ .body("{\"Name\":\"/" + stackName + "\"}")
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .extract().jsonPath().getString("Parameter.Value");
+ }
+}