diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventBusTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventBusTest.java index 769d60578a..4516304093 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventBusTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventBusTest.java @@ -84,10 +84,13 @@ class CloudFormationEventBusTest { .containsEntry("keep", "old") .containsEntry("remove", "old"); - cloudFormation.updateStack(r -> r + // An update with nothing to change is refused, as CloudFormation refuses it. + assertThatThrownBy(() -> cloudFormation.updateStack(r -> r .stackName(stackName) - .templateBody(template("before", "old", "remove"))); - assertThat(waitForTerminal(stackName, 30)).isEqualTo("UPDATE_COMPLETE"); + .templateBody(template("before", "old", "remove")))) + .isInstanceOf(CloudFormationException.class) + .hasMessageContaining("No updates are to be performed."); + assertThat(waitForTerminal(stackName, 30)).isEqualTo("CREATE_COMPLETE"); cloudFormation.updateStack(r -> r .stackName(stackName) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationRdsDynamicReferenceTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationRdsDynamicReferenceTest.java index 921c1c30fa..13f7a0c6ef 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationRdsDynamicReferenceTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationRdsDynamicReferenceTest.java @@ -8,6 +8,7 @@ import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.cloudformation.model.CloudFormationException; import software.amazon.awssdk.services.cloudformation.model.CreateStackRequest; import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest; import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest; @@ -30,6 +31,7 @@ import java.util.List; import java.util.Properties; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assumptions.assumeTrue; @DisplayName("CloudFormation RDS credential dynamic references") @@ -145,6 +147,12 @@ class CloudFormationRdsDynamicReferenceTest { try (Connection connection = awaitPostgresConnection(port)) { assertThat(connection.isValid(5)).isTrue(); } + + // The password compares by the value it resolves to, as any dynamic reference does, so + // resubmitting the template has nothing to change. + assertThatThrownBy(() -> cloudFormation.updateStack(r -> r.stackName(stackName).templateBody(template))) + .isInstanceOf(CloudFormationException.class) + .hasMessageContaining("No updates are to be performed."); } @Test diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackTagsUpdateTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackTagsUpdateTest.java index 1f587ceeac..450ca76deb 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackTagsUpdateTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationStackTagsUpdateTest.java @@ -5,6 +5,7 @@ import org.junit.jupiter.api.BeforeAll; 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.Stack; import software.amazon.awssdk.services.cloudformation.model.Tag; @@ -13,6 +14,7 @@ import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class CloudFormationStackTagsUpdateTest { @@ -68,9 +70,12 @@ class CloudFormationStackTagsUpdateTest { assertThat(awaitStatus("UPDATE_COMPLETE")).isEqualTo("UPDATE_COMPLETE"); assertThat(tags()).containsExactlyInAnyOrderEntriesOf(Map.of("Env", "final")); - cloudFormation.updateStack(request -> request.stackName(stackName) - .usePreviousTemplate(true)); - assertThat(awaitStatus("UPDATE_COMPLETE")).isEqualTo("UPDATE_COMPLETE"); + // Without Tags an update keeps the stack's, so with the same template it changes nothing + // and CloudFormation refuses it. + assertThatThrownBy(() -> cloudFormation.updateStack(request -> request.stackName(stackName) + .usePreviousTemplate(true))) + .isInstanceOf(CloudFormationException.class) + .hasMessageContaining("No updates are to be performed."); assertThat(tags()).containsExactlyInAnyOrderEntriesOf(Map.of("Env", "final")); } diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 7f1da752d1..0939febd0e 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -383,6 +383,40 @@ the same validation the Auto Scaling API applies. The resource schema requires enables all of them), and on `UpdateStack` the group's enabled metrics are set to exactly what the template lists. Removing the property leaves collection as it was. +## Updates With Nothing to Change + +An `UpdateStack` that changes none of the stack's resources and outputs is refused with +`ValidationError` `No updates are to be performed.` and changes nothing, as on AWS. What is compared +is what CloudFormation compares (measured on AWS): of each active resource its `Type`, `Properties`, +`Metadata`, `DeletionPolicy`, `UpdateReplacePolicy` and `UpdatePolicy`, and of each active output its +`Value`, `Description` and `Export`, with whatever does not depend on a resource resolved first: +parameters, mappings, conditions, pseudo parameters, and dynamic references, whose stored value is +compared with the one the stack was deployed with. A literal written as `Fn::Join`, a parameter +written as `Fn::Sub`, or an `Fn::If` whose other branch changed is therefore no change, while a used +mapping value, a used `AWS::SSM::Parameter::Value` parameter whose stored value moved, or a dynamic +reference whose value moved is. A `Ref` or `Fn::GetAtt` of a resource, `Fn::ImportValue` and +`Fn::GetStackOutput` are compared as written. A new `Description`, template `Metadata` or `Rules`, +an unused parameter, mapping or condition, a `DependsOn`, a `CreationPolicy`, or an output whose +condition is false is not an update; tags that differ from the stack's are, and a template with a +nested stack is always updated, since its child template is read again. The template is processed +as CloudFormation processes it: `AWS::Include` fragments are read again and merged and the SAM +transform is applied with the stack's parameter values. The same comparison decides which resources +a change set modifies. + +What each dynamic reference resolved to is kept on the stack when an operation completes, as an +HMAC-SHA256 under a random key of the stack's own, so no resolved value is stored. An update that +fails and rolls back keeps the values of the last deployment. A stack set instance whose stack has +nothing to change is left as it is and succeeds, and the change set that found it so is not kept. + +A `CreateChangeSet` for such an update is created `FAILED`, `UNAVAILABLE`, with `The submitted +information didn't contain changes. Submit different information to create a change set.`, which is +what the AWS CLI's `deploy` and the CDK read as "no changes". + +The CDK then deletes that change set, and before its next deploy deletes it again by name. A +`DeleteChangeSet` for a change set the stack does not have succeeds, as on AWS, whatever the stack's +status, named with its stack or by its ARN alone; a `StackName` that names no stack is still a +`ValidationError`. + ## Lambda Stack Updates `AWS::Lambda::Function` resources are reconciled during `UpdateStack` in the same shape as CloudFormation/CDK deployments: 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 74e0aa96ff..5257268059 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 @@ -159,6 +159,12 @@ public class CloudFormationQueryHandler { parameters, capabilities, tags, region) : cfnService.createChangeSet(stackName, changeSetName, "UPDATE", templateBody, templateUrl, parameters, capabilities, tags, region); + // An update that submits what the stack already has is refused, and leaves no change set + // behind, as UpdateStack does on AWS. + if (CloudFormationService.NO_CHANGES_REASON.equals(cs.getStatusReason())) { + cfnService.deleteChangeSet(stackName, cs.getChangeSetName(), region); + return xmlError("ValidationError", "No updates are to be performed.", 400); + } awaitExecution(cfnService.executeChangeSet(stackName, cs.getChangeSetName(), region)); Stack stack = cfnService.describeStacks(stackName, region).get(0); 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 cf392280e2..1022e7357b 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 @@ -36,7 +36,11 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; import java.time.Clock; import java.time.Instant; import java.util.*; @@ -52,6 +56,7 @@ import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.function.UnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -64,6 +69,13 @@ public class CloudFormationService implements ResourceProvider { private static final Logger LOG = Logger.getLogger(CloudFormationService.class); + /** + * The reason CloudFormation gives a change set that submits what the stack already has, and + * the condition under which UpdateStack answers "No updates are to be performed." + */ + static final String NO_CHANGES_REASON = + "The submitted information didn't contain changes. Submit different information to create a change set."; + private static final int MAX_OPERATION_THREADS = 16; private static final int MAX_QUEUED_OPERATIONS = 128; @@ -456,7 +468,14 @@ 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. String canonicalStackName = live == null ? stackName : live.getStackName(); + // Whether the update has nothing to change is decided here, outside compute(): it reads + // AWS::Include fragments from S3, runs the SAM transform and resolves SSM parameters. Inside, + // the verdict stands only if the stack still holds what it was reached against. + DeployedState checked = isCreateType || live == null ? null : DeployedState.of(live); + boolean unchangedWhenChecked = checked != null + && submitsWhatTheStackHas(live, resolvedTemplate, parameters, tags, region); ChangeSet[] created = new ChangeSet[1]; + boolean[] unchanged = new boolean[1]; Stack stack = stacks.compute(stackKey(accountId, canonicalStackName, region), (k, existing) -> { Stack target; if (existing == null) { @@ -500,6 +519,8 @@ public class CloudFormationService implements ResourceProvider { return existing; } target = existing; + unchanged[0] = unchangedWhenChecked && existing == live + && checked.equals(DeployedState.of(existing)); } ChangeSet cs = new ChangeSet(); @@ -516,6 +537,10 @@ public class CloudFormationService implements ResourceProvider { cs.setStatus("FAILED"); cs.setExecutionStatus("UNAVAILABLE"); cs.setStatusReason(samTransformFailureReason); + } else if (unchanged[0]) { + cs.setStatus("FAILED"); + cs.setExecutionStatus("UNAVAILABLE"); + cs.setStatusReason(NO_CHANGES_REASON); } else { cs.setStatus("CREATE_COMPLETE"); cs.setExecutionStatus("AVAILABLE"); @@ -531,6 +556,15 @@ public class CloudFormationService implements ResourceProvider { return created[0]; } + /** What {@link #submitsWhatTheStackHas} compares an update against. */ + private record DeployedState(String template, Map parameters, + Map resolvedParameters, Map tags) { + static DeployedState of(Stack stack) { + return new DeployedState(stack.getTemplateBody(), stack.parametersSnapshot(), + stack.resolvedParametersSnapshot(), stack.tagsSnapshot()); + } + } + private static AwsException cannotBeUpdated(String stackId, String status) { return new AwsException("ValidationError", UPDATE_REFUSED.formatted(stackId, status), 400); } @@ -545,6 +579,158 @@ public class CloudFormationService implements ResourceProvider { return new AwsException("ValidationError", "Stack with id " + stackName + " does not exist", 400); } + /** + * Whether an UPDATE has nothing to change: the template it submits comes to the same + * {@link ComparedTemplate} as the stack's, with the values each is given, the stack's own tags + * or none are sent, and the stack has no nested stack. CloudFormation then answers "No updates + * are to be performed." A new Description, Metadata, Rules or an unused parameter, mapping or + * condition is therefore not an update, while a change to an active output is, as on AWS. + */ + private boolean submitsWhatTheStackHas(Stack stack, String templateBody, Map parameters, + Map tags, String region) { + if (stack.getTemplateBody() == null || templateBody == null) { + return false; + } + // Tags are compared as a set. An update that sends none keeps the stack's, and so has + // nothing to change; an empty set removes them, which is a change only for a tagged stack. + if (tags != null && !tags.equals(stack.tagsSnapshot())) { + return false; + } + JsonNode submittedTemplate = parsedOrNull(templateBody); + JsonNode deployedTemplate = parsedOrNull(stack.getTemplateBody()); + if (submittedTemplate == null || deployedTemplate == null) { + return false; + } + Map given = parameters == null ? Map.of() : parameters; + try { + // Compared as execution stores it: AWS::Include fragments read again and merged, then + // the SAM transform applied with the stack's parameter values, which it can resolve + // into the expansion. A fragment that changed in S3 is a change. + JsonNode template = awsIncludeProcessor.mergeIncludes(submittedTemplate); + if (samTransformProcessor.hasSamTransform(template)) { + template = samTransformProcessor.expandSamTemplate(template, + samTransformParameters(template, given, region)); + } + // A nested stack is always updated, whether or not its template changed: AWS reads the + // child template again and reports the nested stack as a change on every update. + for (JsonNode resource : template.path("Resources")) { + if ("AWS::CloudFormation::Stack".equals(resource.path("Type").asText())) { + return false; + } + } + Map submitted = resolveSsmParameters(template, + resolveDefaultParameters(template, given), region); + return comparedDeployedTemplate(stack, deployedTemplate, region) + .equals(comparedTemplate(template, submitted, stack, region, currentDynamicReferences(stack, region))); + } catch (AwsException e) { + // An AWS::Include fragment, the SAM transform or an SSM parameter the update cannot + // process fails the update itself, which reports it as AWS does: it goes ahead rather + // than being refused as having nothing to change. + LOG.debugv("Treating an update as a change; its template did not process: {0}", e.getMessage()); + return false; + } + } + + /** + * {@code templateBody} parsed, or {@code null} when it does not parse: as for + * validateResourceDependencies, the operation that processes it reports the parser's error. + */ + private JsonNode parsedOrNull(String templateBody) { + try { + return parseTemplate(templateBody); + } catch (Exception e) { + LOG.debugv("Not comparing a template that did not parse: {0}", e.getMessage()); + return null; + } + } + + /** + * The stack's deployed template as {@link ComparedTemplate} compares it, with the parameter + * values and the dynamic reference values it was deployed with. A stack persisted before + * resolved parameter values or dynamic reference digests were kept compares as different from + * any update, which converges it and records them for the next time. + */ + private ObjectNode comparedDeployedTemplate(Stack stack, JsonNode deployedTemplate, String region) { + Map digests = stack.dynamicReferenceDigestsSnapshot(); + return comparedTemplate(deployedTemplate, deployedParameters(stack), stack, region, + value -> digests.getOrDefault(value, "unrecorded " + UUID.randomUUID())); + } + + /** The parameter values the stack's template was deployed with. */ + private static Map deployedParameters(Stack stack) { + return stack.resolvedParametersSnapshot().isEmpty() + ? stack.parametersSnapshot() : stack.resolvedParametersSnapshot(); + } + + /** + * What each dynamic reference resolves to now, as the stack keeps it. An ssm-secure reference + * resolves too, wherever it is, since only the digest is kept: AWS::RDS::DBInstance resolves its + * master credentials with them. + */ + private UnaryOperator currentDynamicReferences(Stack stack, String region) { + return value -> { + try { + return dynamicReferenceDigest(stack, dynamicReferences.resolveDynamicReferences(value, region, true)); + } catch (AwsException | IllegalStateException e) { + // What CfnDynamicReferences cannot resolve fails the operation when it runs; until + // then it is something to change. + return "unresolvable " + UUID.randomUUID(); + } + }; + } + + /** + * Keeps, for the next update to compare against, what each dynamic reference in the template + * the stack now has resolves to, keyed as {@link ComparedTemplate} hands them over. Run when an + * operation commits, so one that fails and rolls back records nothing and the stack keeps what + * its last deployment recorded; a reference the template no longer has is dropped. + */ + private void recordDynamicReferenceDigests(Stack stack, JsonNode template, String region) { + UnaryOperator current = currentDynamicReferences(stack, region); + Map digests = new LinkedHashMap<>(); + try { + comparedTemplate(template, deployedParameters(stack), stack, region, value -> { + String digest = current.apply(value); + digests.put(value, digest); + return digest; + }); + } catch (AwsException e) { + // Nothing recorded compares as a change, which the next update converges and records. + LOG.debugv("Recording no dynamic reference values for stack {0}: {1}", stack.getStackName(), + e.getMessage()); + digests.clear(); + } + stack.replaceDynamicReferenceDigests(digests); + } + + /** + * What a dynamic reference resolved to, as the stack keeps it: an HMAC-SHA256 under a random + * key of the stack's own, so no value is stored, and the same value on two stacks does not + * compare equal. + */ + private static String dynamicReferenceDigest(Stack stack, String resolved) { + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(stack.dynamicReferenceKey().getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + return HexFormat.of().formatHex(mac.doFinal(resolved.getBytes(StandardCharsets.UTF_8))); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("HmacSHA256 is not available", e); + } + } + + private ObjectNode comparedTemplate(JsonNode template, Map params, Stack stack, + String region, UnaryOperator dynamicReferenceValue) { + String accountId = ownerAccount(stack); + Map conditions = resolveConditions(template, params, stack, region, accountId); + Map mappings = new HashMap<>(); + template.path("Mappings").fields().forEachRemaining(e -> mappings.put(e.getKey(), e.getValue())); + // No dynamic reference resolver: ComparedTemplate hands each reference to dynamicReferenceValue. + CloudFormationTemplateEngine engine = new CloudFormationTemplateEngine(accountId, region, + stack.getStackName(), stack.getStackId(), params, Map.of(), Map.of(), conditions, mappings, + objectMapper, name -> null); + return ComparedTemplate.of(template, objectMapper, engine, conditions, dynamicReferenceValue); + } + /** * 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. @@ -701,6 +887,25 @@ public class CloudFormationService implements ResourceProvider { }); Set deployedIds = stack.resourcesSnapshot().keySet(); + // A resource is modified when what CloudFormation compares of it differs (see + // ComparedTemplate): a DependsOn, or a literal rewritten as a function, is no change, + // while a used mapping value or a dynamic reference whose stored value moved is. A + // template that cannot be brought to that form falls back to its definitions as written + // and the parameters and conditions they read. + JsonNode[] compared = new JsonNode[2]; + if (oldTemplate != null) { + try { + compared[0] = comparedDeployedTemplate(stack, oldTemplate, region).path("Resources"); + compared[1] = comparedTemplate(newTemplate, newResolvedParams, stack, region, + currentDynamicReferences(stack, region)).path("Resources"); + } catch (AwsException e) { + // A condition or a mapping the comparison cannot resolve fails the execution + // with its own error; the preview diffs the definitions as written until then. + LOG.debugv("Diffing a change set as written; a template did not resolve: {0}", e.getMessage()); + compared[0] = null; + } + } + Set replacedResourceIds = new HashSet<>(); List changes = new ArrayList<>(); newResources.fields().forEachRemaining(e -> { @@ -728,10 +933,12 @@ public class CloudFormationService implements ResourceProvider { // it now. changes.add(new ResourceChange("Add", logicalId, null, resourceType, null)); } else if (newActive - && (!oldDef.equals(newDef) - || ("AWS::CloudFormation::Stack".equals(resourceType) && isNestedStackChanged(stack, logicalId, newDef, region, accountId)) - || referencesAnyParameter(newDef, changedParams) - || referencesAnyCondition(newDef, changedConditions))) { + && ((compared[0] != null + ? !compared[0].path(logicalId).equals(compared[1].path(logicalId)) + : !oldDef.equals(newDef) + || referencesAnyParameter(newDef, changedParams) + || referencesAnyCondition(newDef, changedConditions)) + || ("AWS::CloudFormation::Stack".equals(resourceType) && isNestedStackChanged(stack, logicalId, newDef, region, accountId)))) { boolean typeChanged = !oldDef.path("Type").asText().equals(resourceType); boolean replacement = typeChanged || requiresReplacement(resourceType, oldDef.path("Properties"), newDef.path("Properties"), changedParams, changedConditions); @@ -1052,8 +1259,20 @@ public class CloudFormationService implements ResourceProvider { public void deleteChangeSet(String stackName, String changeSetName, String region) { String accountId = currentAccount(); - Stack stack = getStackForChangeSet(stackName, changeSetName, region, accountId); - ChangeSet cs = getChangeSetOrThrow(stack, changeSetName, region, accountId); + boolean byArnAlone = (stackName == null || stackName.isBlank()) + && changeSetName != null && changeSetName.startsWith("arn:"); + Stack stack = byArnAlone + ? findStackForChangeSetArn(changeSetName, region, accountId) + : getStackForChangeSet(stackName, changeSetName, region, accountId); + ChangeSet cs = stack == null ? null : findChangeSet(stack, changeSetName, region, accountId); + if (cs == null) { + // CloudFormation answers success for a change set the stack does not have, whatever + // the stack's status, named by its stack and name or by its ARN alone (measured, + // eu-west-1, 2026-10-04 and 2026-10-17). The AWS CDK deletes its + // change set by name before every deploy and relies on it, since it deletes the one + // that had nothing to change. + return; + } stack.getChangeSets().remove(cs.getChangeSetName()); persistStack(stack); } @@ -1978,6 +2197,7 @@ public class CloudFormationService implements ResourceProvider { stack.replaceOutputs(newOutputs); stack.replaceExports(newExports); stack.replaceOutputExportNames(newOutputExportNames); + recordDynamicReferenceDigests(stack, template, region); newExports.forEach((exportName, value) -> { String logicalKey = region + ":" + exportName; String exportKey = accountExportKey(accountId, logicalKey); @@ -3582,30 +3802,48 @@ public class CloudFormationService implements ResourceProvider { if (changeSetNameOrArn == null || !changeSetNameOrArn.startsWith("arn:")) { throw new AwsException("ValidationError", "StackName is required when ChangeSetName is not an ARN", 400); } + Stack stack = findStackForChangeSetArn(changeSetNameOrArn, region, accountId); + if (stack == null) { + throw new AwsException("ChangeSetNotFoundException", + "ChangeSet [" + changeSetNameOrArn + "] does not exist", 400); + } + return stack; + } + + /** The stack holding the change set {@code changeSetArn} names, or {@code null}. */ + private Stack findStackForChangeSetArn(String changeSetArn, String region, String accountId) { // A change-set ARN contains its name and UUID, but not its stack name. Search only // stacks in the caller's account and region, and match the complete ARN so another // stack's change set with the same short name cannot be selected accidentally. - String changeSetName = resolveChangeSetName(changeSetNameOrArn, region, accountId); + String changeSetName = resolveChangeSetName(changeSetArn, region, accountId); for (Stack stack : stacks.values()) { if (accountId.equals(ownerAccount(stack)) && region.equals(stack.getRegion())) { ChangeSet changeSet = stack.getChangeSets().get(changeSetName); - if (changeSet != null && changeSetNameOrArn.equals(changeSet.getChangeSetId())) { + if (changeSet != null && changeSetArn.equals(changeSet.getChangeSetId())) { return stack; } } } - throw new AwsException("ChangeSetNotFoundException", - "ChangeSet [" + changeSetNameOrArn + "] does not exist", 400); + return null; } private ChangeSet getChangeSetOrThrow(Stack stack, String changeSetNameOrArn, String region, String accountId) { + ChangeSet changeSet = findChangeSet(stack, changeSetNameOrArn, region, accountId); + if (changeSet == null) { + throw new AwsException("ChangeSetNotFoundException", + "ChangeSet [" + changeSetNameOrArn + "] does not exist", 400); + } + return changeSet; + } + + private ChangeSet findChangeSet(Stack stack, String changeSetNameOrArn, + String region, String accountId) { ChangeSet changeSet = stack.getChangeSets().get( resolveChangeSetName(changeSetNameOrArn, region, accountId)); if (changeSet == null || (changeSetNameOrArn != null && changeSetNameOrArn.startsWith("arn:") && !changeSetNameOrArn.equals(changeSet.getChangeSetId()))) { - throw new AwsException("ChangeSetNotFoundException", - "ChangeSet [" + changeSetNameOrArn + "] does not exist", 400); + return null; } return changeSet; } diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/ComparedTemplate.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/ComparedTemplate.java new file mode 100644 index 0000000000..d392481273 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/ComparedTemplate.java @@ -0,0 +1,262 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.UnaryOperator; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * A template in the form CloudFormation compares when it decides what an update changes. Measured + * against CloudFormation (eu-west-1, 2026-10-16): of each active resource it compares the Type, + * Properties, Metadata, DeletionPolicy, UpdateReplacePolicy and UpdatePolicy, and of each active + * output the Value, Description and Export. Whatever does not depend on a resource is resolved + * first, so a literal written as {@code Fn::Join}, a parameter written as {@code Fn::Sub} or an + * {@code Fn::If} whose other branch changed compares equal, while a {@code Ref} or + * {@code Fn::GetAtt} of a resource, {@code Fn::ImportValue} and {@code Fn::GetStackOutput} compare + * as written: {@code Ref A} rewritten as {@code Fn::Sub "${A}"} is a change. A dynamic reference + * compares as the value it resolves to, through the function given. DependsOn, CreationPolicy, the + * name of a resource's Condition, an output whose Condition is false and every section but + * Resources and Outputs are not compared. + */ +final class ComparedTemplate { + + private static final List RESOURCE_KEYS = List.of( + "Type", "Properties", "Metadata", "DeletionPolicy", "UpdateReplacePolicy", "UpdatePolicy"); + private static final List OUTPUT_KEYS = List.of("Value", "Description", "Export"); + private static final Pattern SUB_VARIABLE = Pattern.compile("\\$\\{([^}]*)}"); + private static final String DYNAMIC_REFERENCE = "{{resolve:"; + + private final ObjectMapper objectMapper; + private final CloudFormationTemplateEngine engine; + private final Map conditions; + private final Set resourceIds = new HashSet<>(); + private final UnaryOperator dynamicReferenceValue; + + /** + * @param engine resolves what does not depend on a resource: built with the + * template's parameter values, mappings and conditions, and without + * a dynamic reference resolver, so a dynamic reference reaches + * {@code dynamicReferenceValue} as written + * @param dynamicReferenceValue the value a string holding a dynamic reference compares as + */ + private ComparedTemplate(ObjectMapper objectMapper, CloudFormationTemplateEngine engine, + Map conditions, UnaryOperator dynamicReferenceValue) { + this.objectMapper = objectMapper; + this.engine = engine; + this.conditions = conditions; + this.dynamicReferenceValue = dynamicReferenceValue; + } + + /** + * The compared form of {@code template}: an object with a {@code Resources} and an + * {@code Outputs} member, each keyed by logical id. Two deployments of a stack change nothing + * when their forms are equal; one resource changes when its member differs. + */ + static ObjectNode of(JsonNode template, ObjectMapper objectMapper, CloudFormationTemplateEngine engine, + Map conditions, UnaryOperator dynamicReferenceValue) { + ComparedTemplate compared = new ComparedTemplate(objectMapper, engine, conditions, dynamicReferenceValue); + template.path("Resources").fieldNames().forEachRemaining(compared.resourceIds::add); + ObjectNode result = objectMapper.createObjectNode(); + result.set("Resources", compared.section(template.path("Resources"), RESOURCE_KEYS)); + result.set("Outputs", compared.section(template.path("Outputs"), OUTPUT_KEYS)); + return result; + } + + private ObjectNode section(JsonNode entries, List keys) { + ObjectNode section = objectMapper.createObjectNode(); + entries.fields().forEachRemaining(entry -> { + JsonNode definition = entry.getValue(); + String condition = definition.path("Condition").asText(null); + if (condition != null && !conditions.getOrDefault(condition, false)) { + return; + } + ObjectNode compared = objectMapper.createObjectNode(); + for (String key : keys) { + JsonNode value = definition.get(key); + if (value != null) { + compared.set(key, compared(value, false)); + } + } + section.set(entry.getKey(), compared); + }); + return section; + } + + /** + * @param asWritten whether {@code node} is inside a function compared as written, where an + * {@code AWS::NoValue} is part of what is written rather than an absent value + */ + private JsonNode compared(JsonNode node, boolean asWritten) { + if (node.isTextual()) { + return dynamicReferencesIn(node); + } + if (node.isArray()) { + ArrayNode array = objectMapper.createArrayNode(); + node.forEach(element -> { + JsonNode compared = compared(element, asWritten); + if (asWritten || !isNoValue(compared)) { + array.add(compared); + } + }); + return array; + } + if (!node.isObject()) { + return node; + } + String function = intrinsicName(node); + if (function != null) { + JsonNode argument = node.get(function); + if ("Fn::If".equals(function) && argument.isArray() && argument.size() == 3) { + return compared(conditions.getOrDefault(argument.get(0).asText(), false) + ? argument.get(1) : argument.get(2), asWritten); + } + if (isNoValue(node)) { + return node; + } + if (!dependsOnResource(node)) { + return dynamicReferencesIn(engine.resolveNode(node)); + } + if ("Fn::Sub".equals(function) && argument.isTextual()) { + ObjectNode sub = objectMapper.createObjectNode(); + sub.put("Fn::Sub", substituteStaticVariables(argument.asText(), objectMapper.createObjectNode())); + return sub; + } + if ("Fn::Sub".equals(function) && argument.isArray() && argument.size() == 2 + && argument.get(0).isTextual()) { + ObjectNode sub = objectMapper.createObjectNode(); + sub.putArray("Fn::Sub") + .add(substituteStaticVariables(argument.get(0).asText(), argument.get(1))) + .add(compared(argument.get(1), true)); + return sub; + } + ObjectNode kept = objectMapper.createObjectNode(); + kept.set(function, compared(argument, true)); + return kept; + } + ObjectNode object = objectMapper.createObjectNode(); + node.fields().forEachRemaining(field -> { + JsonNode compared = compared(field.getValue(), asWritten); + if (asWritten || !isNoValue(compared)) { + object.set(field.getKey(), compared); + } + }); + return object; + } + + /** + * Whether {@code node} reads a resource, an export or another stack's output, which are + * compared as written. An {@code Fn::If} depends only on the branch its condition chooses. + */ + private boolean dependsOnResource(JsonNode node) { + if (node.isArray()) { + for (JsonNode element : node) { + if (dependsOnResource(element)) { + return true; + } + } + return false; + } + if (!node.isObject()) { + return false; + } + String function = intrinsicName(node); + JsonNode argument = function == null ? null : node.get(function); + if ("Ref".equals(function)) { + return resourceIds.contains(argument.asText()); + } + if ("Fn::GetAtt".equals(function) || "Fn::ImportValue".equals(function) + || "Fn::GetStackOutput".equals(function)) { + return true; + } + if ("Fn::If".equals(function) && argument.isArray() && argument.size() == 3) { + return dependsOnResource(conditions.getOrDefault(argument.get(0).asText(), false) + ? argument.get(1) : argument.get(2)); + } + if ("Fn::Sub".equals(function)) { + JsonNode variables = argument.isArray() ? argument.path(1) : objectMapper.createObjectNode(); + String text = (argument.isArray() ? argument.path(0) : argument).asText(); + return subReadsResource(text, variables) || dependsOnResource(variables); + } + for (JsonNode child : node) { + if (dependsOnResource(child)) { + return true; + } + } + return false; + } + + private boolean subReadsResource(String text, JsonNode variables) { + Matcher matcher = SUB_VARIABLE.matcher(text); + while (matcher.find()) { + String name = matcher.group(1); + if (!name.startsWith("!") && !variables.has(name)) { + int dot = name.indexOf('.'); + if (resourceIds.contains(dot < 0 ? name : name.substring(0, dot))) { + return true; + } + } + } + return false; + } + + /** + * An {@code Fn::Sub} string that reads a resource, with every other variable (a parameter, a + * pseudo parameter) replaced by its value, so only the resource reads remain as written. A + * variable its own map defines stays as written: the map is compared beside it. + */ + private String substituteStaticVariables(String text, JsonNode variables) { + Matcher matcher = SUB_VARIABLE.matcher(text); + StringBuilder result = new StringBuilder(); + while (matcher.find()) { + String name = matcher.group(1); + int dot = name.indexOf('.'); + boolean readsResource = !name.startsWith("!") + && resourceIds.contains(dot < 0 ? name : name.substring(0, dot)); + String replacement = name.startsWith("!") || readsResource || variables.has(name) + ? matcher.group() + : engine.resolve(objectMapper.createObjectNode().put("Ref", name)); + matcher.appendReplacement(result, Matcher.quoteReplacement(replacement)); + } + matcher.appendTail(result); + return dynamicReferencesIn(TextNode.valueOf(result.toString())).asText(); + } + + private JsonNode dynamicReferencesIn(JsonNode node) { + if (node.isTextual()) { + String text = node.asText(); + return text.contains(DYNAMIC_REFERENCE) ? TextNode.valueOf(dynamicReferenceValue.apply(text)) : node; + } + if (node.isArray()) { + ArrayNode array = objectMapper.createArrayNode(); + node.forEach(element -> array.add(dynamicReferencesIn(element))); + return array; + } + if (node.isObject()) { + ObjectNode object = objectMapper.createObjectNode(); + node.fields().forEachRemaining(field -> object.set(field.getKey(), dynamicReferencesIn(field.getValue()))); + return object; + } + return node; + } + + private static String intrinsicName(JsonNode node) { + if (node.size() != 1) { + return null; + } + String name = node.fieldNames().next(); + return "Ref".equals(name) || name.startsWith("Fn::") ? name : null; + } + + private static boolean isNoValue(JsonNode node) { + return node.isObject() && node.size() == 1 && "AWS::NoValue".equals(node.path("Ref").asText(null)); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java index 48250830e9..f2456126a5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/StackSetService.java @@ -4,9 +4,11 @@ import com.fasterxml.jackson.core.type.TypeReference; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.RequestScopes; import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.cloudformation.model.ChangeSet; import io.github.hectorvent.floci.services.cloudformation.model.Stack; import io.github.hectorvent.floci.services.cloudformation.model.StackInstance; import io.github.hectorvent.floci.services.cloudformation.model.StackSet; @@ -644,9 +646,18 @@ public class StackSetService { // Preflight the change set in the target account so AWS::AccountId-based conditions are // evaluated against the same account the instance executes in (createChangeSet otherwise runs // in the administrator request scope). - cfnService.createChangeSet(stackName, changeSetName, changeSetType, ss.getTemplateBody(), null, - ss.getParameters(), ss.getCapabilities(), ss.getTags(), region, account); - await(cfnService.executeChangeSet(stackName, changeSetName, region, account)); + ChangeSet changeSet = cfnService.createChangeSet(stackName, changeSetName, changeSetType, + ss.getTemplateBody(), null, ss.getParameters(), ss.getCapabilities(), ss.getTags(), region, account); + // An instance whose stack already has what the stack set describes is left as it is, as on + // AWS: executing its change set, which has nothing to change, would update the stack anyway. + // That change set is the engine's own and is not left behind. + boolean nothingToChange = changeSet != null && "FAILED".equals(changeSet.getStatus()) + && CloudFormationService.NO_CHANGES_REASON.equals(changeSet.getStatusReason()); + if (nothingToChange) { + RequestScopes.runAs(account, region, () -> cfnService.deleteChangeSet(stackName, changeSetName, region)); + } else { + await(cfnService.executeChangeSet(stackName, changeSetName, region, account)); + } StackInstance inst = new StackInstance(); inst.setStackSetId(ss.getStackSetId()); @@ -659,8 +670,12 @@ public class StackSetService { String stackStatus = stacks.isEmpty() ? null : stacks.get(0).getStatus(); // Only a clean create/update is a success. A failed resource rolls the stack back, so its // terminal status is ROLLBACK_COMPLETE (not *_FAILED) — treat anything that is not COMPLETE - // as a failed instance so the operation status reflects it. - if (!"CREATE_COMPLETE".equals(stackStatus) && !"UPDATE_COMPLETE".equals(stackStatus)) { + // as a failed instance so the operation status reflects it. A stack with nothing to change + // accepted the preflight and already has what the stack set describes, whatever status an + // earlier rolled-back update left it in. + if (nothingToChange) { + inst.setDetailedStatus("SUCCEEDED"); + } else if (!"CREATE_COMPLETE".equals(stackStatus) && !"UPDATE_COMPLETE".equals(stackStatus)) { inst.setStatus("INOPERABLE"); inst.setDetailedStatus("FAILED"); inst.setStatusReason(stacks.isEmpty() ? null : stacks.get(0).getStatusReason()); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.java index 14f0e4d0d9..565c037496 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/model/Stack.java @@ -11,6 +11,7 @@ import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; /** @@ -55,6 +56,13 @@ public class Stack { // executeTemplate — used to detect drift in the live SSM value between deploys even when the // referencing parameter (name) is unchanged, so change-set previews agree with execution. private Map resolvedParameters = orderedMap(); + // A keyed digest of what each string holding a dynamic reference resolved to when the stack's + // last operation committed, keyed by the string as the comparison of an update sees it. An + // update compares what the string resolves to now against it, so a stored value that moved is a + // change, as on AWS; the digest keeps a secret the reference resolves to out of the stored stack. + private Map dynamicReferenceDigests = orderedMap(); + // The stack's own random key for those digests. + private String dynamicReferenceKey; private Map outputs = orderedMap(); private Map exports = orderedMap(); // Maps output key to its export name (when Export.Name is defined on an output) @@ -109,6 +117,25 @@ public class Stack { public void setResolvedParameters(Map resolvedParameters) { this.resolvedParameters = orderedMap(resolvedParameters); } @JsonProperty("resolvedParameters") public Map resolvedParametersSnapshot() { return snapshot(resolvedParameters); } + public void replaceDynamicReferenceDigests(Map source) { replace(dynamicReferenceDigests, source); } + @JsonProperty("dynamicReferenceDigests") + public void setDynamicReferenceDigests(Map dynamicReferenceDigests) { + this.dynamicReferenceDigests = orderedMap(dynamicReferenceDigests); + } + @JsonProperty("dynamicReferenceDigests") + public Map dynamicReferenceDigestsSnapshot() { return snapshot(dynamicReferenceDigests); } + /** The key of the stack's dynamic reference digests, made the first time one is needed. */ + @JsonProperty("dynamicReferenceKey") + public synchronized String dynamicReferenceKey() { + if (dynamicReferenceKey == null) { + dynamicReferenceKey = UUID.randomUUID().toString(); + } + return dynamicReferenceKey; + } + @JsonProperty("dynamicReferenceKey") + public synchronized void setDynamicReferenceKey(String dynamicReferenceKey) { + this.dynamicReferenceKey = dynamicReferenceKey; + } @JsonIgnore public Map getOutputs() { return outputs; } @JsonProperty("outputs") diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnUpdates.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnUpdates.java new file mode 100644 index 0000000000..3561416b3f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnUpdates.java @@ -0,0 +1,37 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +/** + * An UpdateStack whose template changes none of the stack's resources and outputs is refused with + * "No updates are to be performed.", as on AWS, a new Description included. A test that re-applies + * the same resources to exercise an update adds an output instead: on AWS that is an update which + * leaves every resource as it is (measured on CloudFormation, eu-west-1, 2026-10-16). + */ +final class CfnUpdates { + + /** The output {@link #forceUpdate} adds, for a test that compares a stack's outputs. */ + static final String FORCED_OUTPUT = "FlociForcedUpdate"; + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private CfnUpdates() { + } + + /** {@code template}, JSON or YAML, as JSON with an output no deployed template carries. */ + static String forceUpdate(String template) { + try { + JsonNode parsed = template.stripLeading().startsWith("{") + ? MAPPER.readTree(template) + : new CloudFormationYamlParser(MAPPER).parse(template); + ObjectNode node = (ObjectNode) parsed; + ObjectNode outputs = node.has("Outputs") ? (ObjectNode) node.get("Outputs") : node.putObject("Outputs"); + outputs.putObject(FORCED_OUTPUT).put("Value", String.valueOf(System.nanoTime())); + return MAPPER.writeValueAsString(node); + } catch (Exception e) { + throw new IllegalArgumentException("not a CloudFormation template", e); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java index 051ac841e0..efc0f16a70 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2NetworkingIntegrationTest.java @@ -197,8 +197,9 @@ class CloudFormationEc2NetworkingIntegrationTest { assertTrue(ec2("DescribeInternetGateways").contains(out.get("IgwId"))); // The same template again: every id survives (the switch re-created all seven). - cloudFormation("UpdateStack", template(vpcId, "10.40.0.0/24")); + cloudFormation("UpdateStack", CfnUpdates.forceUpdate(template(vpcId, "10.40.0.0/24"))); Map again = XmlParser.extractPairs(describeStacks("UPDATE_COMPLETE"), "Outputs", "OutputKey", "OutputValue"); + again.remove(CfnUpdates.FORCED_OUTPUT); assertEquals(out, again, "an unchanged update must keep every networking resource"); // Tags are mutable: a dropped key goes, a changed value is written, the subnet stays. diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventBusIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventBusIntegrationTest.java index 24fc079ebc..6a9ad743ab 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventBusIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventBusIntegrationTest.java @@ -424,7 +424,7 @@ class CloudFormationEventBusIntegrationTest { createStack(stackName, originalTemplate); assertStackStatus(stackName, "CREATE_COMPLETE"); - updateStack(stackName, originalTemplate); + updateStack(stackName, CfnUpdates.forceUpdate(originalTemplate)); assertStackStatus(stackName, "UPDATE_COMPLETE"); updateStack(stackName, eventBusAndNamedRuleTemplate(busName, "after")); @@ -621,7 +621,7 @@ class CloudFormationEventBusIntegrationTest { createStack(stackName, originalTemplate); assertStackStatus(stackName, "CREATE_COMPLETE"); - updateStack(stackName, originalTemplate); + updateStack(stackName, CfnUpdates.forceUpdate(originalTemplate)); assertStackStatus(stackName, "UPDATE_COMPLETE"); updateStack(stackName, eventBusWithPolicyTemplate(busName, "After")); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java index 1901d0fcfc..e572647b16 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java @@ -870,7 +870,7 @@ class CloudFormationIntegrationTest { .contentType("application/x-www-form-urlencoded") .formParam("Action", "UpdateStack") .formParam("StackName", stackName) - .formParam("TemplateBody", template) + .formParam("TemplateBody", CfnUpdates.forceUpdate(template)) .when() .post("/") .then() @@ -2765,8 +2765,10 @@ class CloudFormationIntegrationTest { return xml.substring(xml.lastIndexOf("", idAt), xml.indexOf("", idAt)); } + // Measured against CloudFormation (eu-west-1, 2026-10-04): a change set the stack does not + // have, on a stack in REVIEW_IN_PROGRESS as on one in CREATE_COMPLETE, is deleted with success. @Test - void deleteChangeSet_nonExistentChangeSet_returnsError() { + void deleteChangeSet_nonExistentChangeSet_succeeds() { String template = """ { "Resources": { @@ -2793,7 +2795,6 @@ class CloudFormationIntegrationTest { .then() .statusCode(200); - // Attempt to delete a changeset that does not exist given() .contentType("application/x-www-form-urlencoded") .formParam("Action", "DeleteChangeSet") @@ -2802,8 +2803,18 @@ class CloudFormationIntegrationTest { .when() .post("/") .then() - .statusCode(400) - .body(containsString("ChangeSetNotFoundException")); + .statusCode(200) + .body(containsString("")); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeChangeSet") + .formParam("StackName", "cs-error-stack") + .formParam("ChangeSetName", "existing-changeset") + .when() + .post("/") + .then() + .statusCode(200); } @Test @@ -2930,7 +2941,7 @@ class CloudFormationIntegrationTest { .contentType("application/x-www-form-urlencoded") .formParam("Action", "UpdateStack") .formParam("StackName", stackName) - .formParam("TemplateBody", template) + .formParam("TemplateBody", CfnUpdates.forceUpdate(template)) .when() .post("/") .then() @@ -8397,13 +8408,14 @@ class CloudFormationIntegrationTest { .statusCode(200) .body("Items.findAll { it.ApiId == '" + apiId + "' }.Name", hasItem("cfn-apigwv2-api-v2")); - // Idempotent re-deploy with no changes is a no-op (criterion #3): counts/ids unchanged + // Re-deploying the same resources is a no-op for them (criterion #3): counts/ids unchanged. + // An identical template is refused outright, so a new output forces the update. given() .contentType("application/x-www-form-urlencoded") .formParam("Action", "UpdateStack") .formParam("StackName", stackName) - .formParam("TemplateBody", - template.formatted("cfn-apigwv2-api-v2", "https://example.com/v2", "GET /things", "true")) + .formParam("TemplateBody", CfnUpdates.forceUpdate( + template.formatted("cfn-apigwv2-api-v2", "https://example.com/v2", "GET /things", "true"))) .when() .post("/") .then() @@ -10766,7 +10778,7 @@ class CloudFormationIntegrationTest { .contentType("application/x-www-form-urlencoded") .formParam("Action", "UpdateStack") .formParam("StackName", stackName) - .formParam("TemplateBody", template) + .formParam("TemplateBody", CfnUpdates.forceUpdate(template)) .when() .post("/") .then() diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationNoChangesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationNoChangesIntegrationTest.java new file mode 100644 index 0000000000..662078445f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationNoChangesIntegrationTest.java @@ -0,0 +1,577 @@ +package io.github.hectorvent.floci.services.cloudformation; + +import io.github.hectorvent.floci.core.common.XmlParser; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.ssm.SsmService; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * An update that changes none of the stack's resources and outputs. Measured against + * CloudFormation (eu-west-1, 2026-10-03 and 2026-10-16): UpdateStack answers ValidationError "No + * updates are to be performed." and changes nothing; a CreateChangeSet for it is created FAILED, + * UNAVAILABLE, with "The submitted information didn't contain changes. Submit different information + * to create a change set.". What is compared is each active resource's Type, Properties, Metadata, + * DeletionPolicy, UpdateReplacePolicy and UpdatePolicy, and each active output, with whatever does + * not depend on a resource resolved: a new Description, template Metadata, an unused parameter, + * mapping or condition, a DependsOn, a literal written as Fn::Join, a parameter written as Fn::Sub + * or an output whose condition is false is no change; a change to an active output, a resource's + * Metadata, a used mapping value, a Ref of a resource rewritten as Fn::Sub, or a dynamic reference + * whose stored value moved is an update. The CDK deletes the FAILED change set and deletes it again + * by name before its next deploy; DeleteChangeSet answers success for a change set the stack does + * not have, by name or by ARN, and ValidationError for a stack that does not exist (measured + * 2026-10-04). Tags are part of what an update submits (measured 2026-10-16): the stack's own tags + * in another order, or no Tags, change nothing; different tags, or an empty set on a tagged stack, + * are an update that replaces them. + */ +@QuarkusTest +class CloudFormationNoChangesIntegrationTest { + + private static final String TEMPLATE = """ + {"Resources": {"Topic": {"Type": "AWS::SNS::Topic", "Properties": {"TopicName": "%s"}}}, + "Outputs": {"Out": {"Value": "1"}}}"""; + + @Inject + S3Service s3Service; + + @Inject + SsmService ssmService; + + private final String suffix = Long.toString(System.nanoTime(), 36); + private final List stacksToDelete = new ArrayList<>(); + private final List parametersToDelete = new ArrayList<>(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @AfterEach + void cleanUp() { + for (String stackName : stacksToDelete) { + request("DeleteStack", stackName).when().post("/"); + } + stacksToDelete.clear(); + for (String parameter : parametersToDelete) { + ssmService.deleteParameter(parameter, "us-east-1"); + } + parametersToDelete.clear(); + } + + @Test + void anIdenticalUpdateIsRefusedAndChangesNothing() { + String stackName = name("no-change"); + String template = TEMPLATE.formatted(name("no-change-topic")); + create(stackName, template); + String changeSetsBefore = listChangeSets(stackName).extract().asString(); + + update(stackName, template) + .statusCode(400) + .body(containsString("ValidationError")) + .body(containsString("No updates are to be performed.")); + update(stackName, template.replace("\n", "\n ").replace(": ", ": ")) + .statusCode(400) + .body(containsString("No updates are to be performed.")); + + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + listChangeSets(stackName).body(not(containsString("update-"))); + assertEquals(changeSetsBefore.replaceAll("[^<]*", ""), + listChangeSets(stackName).extract().asString().replaceAll("[^<]*", "")); + } + + @Test + void aChangeToTheOutputsAloneIsAnUpdate() { + String stackName = name("outputs-only"); + String template = TEMPLATE.formatted(name("outputs-only-topic")); + create(stackName, template); + + update(stackName, template.replace("\"Value\": \"1\"", "\"Value\": \"2\"")).statusCode(200); + + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200) + .body(containsString("Out")) + .body(containsString("2")); + } + + /** + * What does not change a resource or an output is no update: a new Description, template + * Metadata, an unused parameter, mapping or condition, a DependsOn, a literal written as + * Fn::Join, a parameter written as Fn::Sub, an Fn::If whose other branch changed, and an output + * whose condition is false. + */ + @Test + void whatChangesNoResourceOrOutputIsNoUpdate() { + String template = """ + {"Parameters": {"P": {"Type": "String", "Default": "x"}}, + "Conditions": {"Never": {"Fn::Equals": ["a", "b"]}}, + "Resources": { + "A": {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", "Value": "v"}}, + "B": {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", "Value": {"Ref": "P"}}}}, + "Outputs": {"Out": {"Value": "o"}, "Gated": {"Condition": "Never", "Value": "g"}}}"""; + String stackName = name("no-change-forms"); + create(stackName, template); + + for (String same : new String[] { + template.replace("{\"Parameters\"", "{\"Description\": \"new\", \"Metadata\": {\"k\": \"v\"}, \"Parameters\""), + template.replace("\"Default\": \"x\"}}", "\"Default\": \"x\"}, \"Unused\": {\"Type\": \"String\", \"Default\": \"u\"}}, " + + "\"Mappings\": {\"M\": {\"k\": {\"v\": \"m\"}}}"), + template.replace("\"Type\": \"String\", \"Value\": \"v\"}}", "\"Type\": \"String\", \"Value\": \"v\"}, \"DependsOn\": \"B\"}"), + template.replace("\"Value\": \"v\"", "\"Value\": {\"Fn::Join\": [\"\", [\"v\"]]}"), + template.replace("{\"Ref\": \"P\"}", "{\"Fn::Sub\": \"${P}\"}"), + template.replace("\"Value\": \"v\"", "\"Value\": {\"Fn::If\": [\"Never\", \"other\", \"v\"]}"), + template.replace("\"Value\": \"g\"", "\"Value\": \"g2\""), + }) { + update(stackName, same) + .statusCode(400) + .body(containsString("No updates are to be performed.")); + } + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + } + + /** + * A Ref of a resource is compared as written: rewritten as Fn::Sub, it is an update, as a new + * Metadata on a resource is. + */ + @Test + void whatReadsAResourceIsComparedAsWritten() { + String template = """ + {"Resources": { + "A": {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", "Value": "a"}}, + "B": {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", "Value": {"Ref": "A"}}}}}"""; + String stackName = name("as-written"); + create(stackName, template); + + String rewritten = template.replace("{\"Ref\": \"A\"}", "{\"Fn::Sub\": \"${A}\"}"); + update(stackName, rewritten).statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + + update(stackName, rewritten.replace("\"Value\": \"a\"}}", "\"Value\": \"a\"}, \"Metadata\": {\"k\": \"v\"}}")) + .statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + } + + /** A mapping value a resource uses is resolved: changed, the resource is modified. */ + @Test + void aUsedMappingValueIsAChange() { + String template = """ + {"Mappings": {"M": {"k": {"v": "%s"}}}, + "Resources": {"B": {"Type": "AWS::SSM::Parameter", + "Properties": {"Type": "String", "Value": {"Fn::FindInMap": ["M", "k", "v"]}}}}}"""; + String stackName = name("used-mapping"); + create(stackName, template.formatted("first")); + + changeSet(stackName, "mapping", template.formatted("second")).when().post("/").then().statusCode(200); + describeChangeSet(stackName, "mapping") + .body(containsString("CREATE_COMPLETE")) + .body(containsString("Modify")) + .body(containsString("B")); + } + + /** + * A dynamic reference compares as the value it resolves to: identical, the template is an + * update once the stored value moved, and the resource takes the new value. + */ + @Test + void aDynamicReferenceWhoseValueMovedIsAChange() { + String source = "/no-change/source-" + suffix; + ssmService.putParameter(source, "first", "String", null, true, "us-east-1"); + parametersToDelete.add(source); + String template = """ + {"Resources": {"Copy": {"Type": "AWS::SSM::Parameter", + "Properties": {"Name": "%s-copy", "Type": "String", "Value": "{{resolve:ssm:%s}}"}}}}""" + .formatted(source, source); + String stackName = name("moved-reference"); + create(stackName, template); + + update(stackName, template) + .statusCode(400) + .body(containsString("No updates are to be performed.")); + + ssmService.putParameter(source, "second", "String", null, true, "us-east-1"); + update(stackName, template).statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals("second", ssmService.getParameter(source + "-copy", "us-east-1").getValue()); + } + + /** + * A dynamic reference inside an Fn::Sub that reads a resource compares as the value it resolves + * to, the resource read left as written: unchanged, the template is no update; once the stored + * value moved, it is one. + */ + @Test + void aDynamicReferenceBesideAResourceReadComparesByItsValue() { + String source = "/no-change/beside-" + suffix; + ssmService.putParameter(source, "first", "String", null, true, "us-east-1"); + parametersToDelete.add(source); + String template = """ + {"Resources": { + "A": {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", "Value": "a"}}, + "B": {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", + "Value": {"Fn::Sub": "${A}-{{resolve:ssm:%s}}"}}}}}""".formatted(source); + String stackName = name("beside-resource"); + create(stackName, template); + + update(stackName, template) + .statusCode(400) + .body(containsString("No updates are to be performed.")); + + ssmService.putParameter(source, "second", "String", null, true, "us-east-1"); + update(stackName, template).statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + } + + /** + * An update that fails rolls back to what the stack had, the dynamic reference values it was + * deployed with included: retried after a stored value moved, it is still an update. + */ + @Test + void aFailedUpdateLeavesTheDeployedDynamicReferenceValues() { + String source = "/no-change/rolled-back-" + suffix; + ssmService.putParameter(source, "first", "String", null, true, "us-east-1"); + parametersToDelete.add(source); + String copy = """ + "Copy": {"Type": "AWS::SSM::Parameter", + "Properties": {"Type": "String", "Value": "{{resolve:ssm:%s}}"}}""".formatted(source); + String template = "{\"Resources\": {" + copy + "}}"; + // A nested stack without a TemplateURL fails once Copy took the new value. + String failing = "{\"Resources\": {" + copy + ", \"Nested\": {\"Type\": \"AWS::CloudFormation::Stack\"," + + " \"DependsOn\": \"Copy\", \"Properties\": {}}}}"; + String stackName = name("rolled-back"); + create(stackName, template); + + ssmService.putParameter(source, "second", "String", null, true, "us-east-1"); + update(stackName, failing).statusCode(200); + assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + + update(stackName, template).statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + } + + /** + * What reads a resource is compared as written, an AWS::NoValue in it included: an Fn::Join that + * drops one is an update. + */ + @Test + void aNoValueInsideAResourceReadIsPartOfWhatIsWritten() { + String template = """ + {"Resources": { + "A": {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", "Value": "a"}}, + "B": {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", + "Value": {"Fn::Join": ["-", [{"Ref": "A"}, "x", {"Ref": "AWS::NoValue"}]]}}}}}"""; + String stackName = name("novalue-written"); + create(stackName, template); + + update(stackName, template.replace(", {\"Ref\": \"AWS::NoValue\"}", "")).statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + } + + /** + * The array form of an Fn::Sub that reads a resource has its other variables replaced by their + * values too, those its own map defines left as written: an AWS::Region written as its value is + * no update. + */ + @Test + void anFnSubArrayReadingAResourceComparesItsOtherVariablesByValue() { + String template = """ + {"Resources": { + "A": {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", "Value": "a"}}, + "B": {"Type": "AWS::SSM::Parameter", "Properties": {"Type": "String", + "Value": {"Fn::Sub": ["${A}-${AWS::Region}-${X}", {"X": "x"}]}}}}}"""; + String stackName = name("sub-array"); + create(stackName, template); + + update(stackName, template.replace("${AWS::Region}", "us-east-1")) + .statusCode(400) + .body(containsString("No updates are to be performed.")); + update(stackName, template.replace("{\"X\": \"x\"}", "{\"X\": \"y\"}")).statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + } + + /** + * A transformed template is compared as CloudFormation processes it: the SAM transform applied, + * so resubmitting an unchanged SAM template is not an update either. + */ + @Test + void anUnchangedSamTemplateIsRefused() { + String template = """ + {"Transform": "AWS::Serverless-2016-10-31", + "Resources": {"Table": {"Type": "AWS::Serverless::SimpleTable", + "Properties": {"TableName": "%s"}}}}""".formatted(name("sam-table")); + String stackName = name("no-change-sam"); + create(stackName, template); + + update(stackName, template) + .statusCode(400) + .body(containsString("No updates are to be performed.")); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + } + + /** + * The SAM transform is applied with the stack's parameter values, as execution applies it: a + * version SAM names after a hash of its code, which a parameter given a value other than its + * default changes, compares equal, and resubmitting the template with the same values is not an + * update. + */ + @Test + void anUnchangedSamTemplateIsComparedWithItsParameterValues() { + String template = """ + {"Transform": "AWS::Serverless-2016-10-31", + "Parameters": {"Release": {"Type": "String", "Default": "first"}}, + "Resources": {"Function": {"Type": "AWS::Serverless::Function", + "Properties": {"FunctionName": "%s", "Handler": "index.handler", + "Runtime": "nodejs20.x", "AutoPublishAlias": "live", + "InlineCode": {"Fn::Sub": "exports.handler = async () => '${Release}';"}}}}}""" + .formatted(name("sam-params-func")); + String stackName = name("no-change-sam-params"); + request("CreateStack", stackName).formParam("TemplateBody", template) + .formParam("Capabilities.member.1", "CAPABILITY_IAM") + .formParam("Parameters.member.1.ParameterKey", "Release") + .formParam("Parameters.member.1.ParameterValue", "second") + .when().post("/").then().statusCode(200); + stacksToDelete.add(stackName); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + + request("UpdateStack", stackName).formParam("TemplateBody", template) + .formParam("Capabilities.member.1", "CAPABILITY_IAM") + .formParam("Parameters.member.1.ParameterKey", "Release") + .formParam("Parameters.member.1.ParameterValue", "second") + .when().post("/").then() + .statusCode(400) + .body(containsString("No updates are to be performed.")); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + } + + /** + * AWS::Include fragments are merged before the comparison, and read again: the same template + * with the same fragment is not an update, and with the fragment changed in S3 it is. + */ + @Test + void anIncludeIsComparedWithItsFragmentReadAgain() { + String bucket = name("include"); + s3Service.createBucket(bucket, "us-east-1"); + putFragment(bucket, "Description: first\n"); + String template = """ + Resources: + Topic: + Type: AWS::SNS::Topic + Metadata: + Fn::Transform: + Name: AWS::Include + Parameters: + Location: s3://%s/fragment.yaml + Properties: + TopicName: %s + """.formatted(bucket, name("include-topic")); + String stackName = name("no-change-include"); + try { + create(stackName, template); + + update(stackName, template) + .statusCode(400) + .body(containsString("No updates are to be performed.")); + + putFragment(bucket, "Description: second\n"); + update(stackName, template).statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + } finally { + s3Service.deleteObject(bucket, "fragment.yaml"); + s3Service.deleteBucket(bucket); + } + } + + private void putFragment(String bucket, String content) { + s3Service.putObject(bucket, "fragment.yaml", content.getBytes(StandardCharsets.UTF_8), "text/yaml", Map.of()); + } + + @Test + void aChangeSetWithNothingToChangeIsCreatedFailed() { + String stackName = name("change-set-same"); + String template = TEMPLATE.formatted(name("change-set-same-topic")); + create(stackName, template); + + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "same") + .formParam("ChangeSetType", "UPDATE") + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200); + + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "same") + .when().post("/").then() + .statusCode(200) + .body(containsString("FAILED")) + .body(containsString("UNAVAILABLE")) + .body(containsString("The submitted information didn")) + .body(containsString("t contain changes. Submit different information to create a change set.")); + } + + @Test + void tagsArePartOfWhatAnUpdateSubmits() { + String stackName = name("tags"); + String template = TEMPLATE.formatted(name("tags-topic")); + withTags(request("CreateStack", stackName).formParam("TemplateBody", template), "Env", "a", "Team", "x") + .when().post("/").then().statusCode(200); + stacksToDelete.add(stackName); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + + withTags(request("UpdateStack", stackName).formParam("TemplateBody", template), "Team", "x", "Env", "a") + .when().post("/").then() + .statusCode(400) + .body(containsString("No updates are to be performed.")); + update(stackName, template) + .statusCode(400) + .body(containsString("No updates are to be performed.")); + assertEquals(Map.of("Env", "a", "Team", "x"), tags(stackName)); + + withTags(changeSet(stackName, "same-tags", template), "Env", "a", "Team", "x") + .when().post("/").then().statusCode(200); + describeChangeSet(stackName, "same-tags").body(containsString("FAILED")); + withTags(changeSet(stackName, "other-tags", template), "Env", "b") + .when().post("/").then().statusCode(200); + describeChangeSet(stackName, "other-tags") + .body(containsString("CREATE_COMPLETE")) + .body(containsString("AVAILABLE")); + + withTags(request("UpdateStack", stackName).formParam("TemplateBody", template), "Env", "b") + .when().post("/").then().statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals(Map.of("Env", "b"), tags(stackName)); + + request("UpdateStack", stackName).formParam("TemplateBody", template).formParam("Tags", "") + .when().post("/").then().statusCode(200); + assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + assertEquals(Map.of(), tags(stackName)); + request("UpdateStack", stackName).formParam("TemplateBody", template).formParam("Tags", "") + .when().post("/").then() + .statusCode(400) + .body(containsString("No updates are to be performed.")); + } + + @Test + void theChangeSetTheCdkDeletedCanBeDeletedAgain() { + String stackName = name("delete-again"); + String template = TEMPLATE.formatted(name("delete-again-topic")); + create(stackName, template); + String id = given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateChangeSet") + .formParam("StackName", stackName) + .formParam("ChangeSetName", "cdk-deploy-change-set") + .formParam("ChangeSetType", "UPDATE") + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200) + .extract().xmlPath().getString("CreateChangeSetResponse.CreateChangeSetResult.Id"); + + deleteChangeSet(stackName, "cdk-deploy-change-set").statusCode(200); + deleteChangeSet(stackName, "cdk-deploy-change-set") + .statusCode(200) + .body(containsString("")); + deleteChangeSet(stackName, id).statusCode(200); + // By its ARN alone too, with no StackName (measured 2026-10-17). + deleteChangeSet(null, id) + .statusCode(200) + .body(containsString("")); + deleteChangeSet(name("delete-again-missing"), "cdk-deploy-change-set") + .statusCode(400) + .body(containsString("ValidationError")); + + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + } + + /** {@code stackName} null sends none: the change set is named by its ARN alone. */ + private static ValidatableResponse deleteChangeSet(String stackName, String changeSetName) { + RequestSpecification request = given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "DeleteChangeSet") + .formParam("ChangeSetName", changeSetName); + if (stackName != null) { + request.formParam("StackName", stackName); + } + return request.when().post("/").then(); + } + + /** A name unique to this run, so a rerun in the same JVM never meets a stack of an earlier one. */ + private String name(String base) { + return "no-change-" + base + "-" + suffix; + } + + private void create(String stackName, String template) { + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when().post("/").then().statusCode(200); + stacksToDelete.add(stackName); + assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); + } + + private static ValidatableResponse update(String stackName, String template) { + return given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "UpdateStack") + .formParam("StackName", stackName) + .formParam("TemplateBody", template) + .when().post("/").then(); + } + + private static RequestSpecification request(String action, String stackName) { + return given().contentType("application/x-www-form-urlencoded") + .formParam("Action", action) + .formParam("StackName", stackName); + } + + private static RequestSpecification changeSet(String stackName, String changeSetName, String template) { + return request("CreateChangeSet", stackName) + .formParam("ChangeSetName", changeSetName) + .formParam("ChangeSetType", "UPDATE") + .formParam("TemplateBody", template); + } + + private static ValidatableResponse describeChangeSet(String stackName, String changeSetName) { + return request("DescribeChangeSet", stackName) + .formParam("ChangeSetName", changeSetName) + .when().post("/").then().statusCode(200); + } + + private static RequestSpecification withTags(RequestSpecification request, String... keysAndValues) { + for (int i = 0; i < keysAndValues.length; i += 2) { + int member = i / 2 + 1; + request.formParam("Tags.member." + member + ".Key", keysAndValues[i]) + .formParam("Tags.member." + member + ".Value", keysAndValues[i + 1]); + } + return request; + } + + private static Map tags(String stackName) { + String xml = request("DescribeStacks", stackName).when().post("/") + .then().statusCode(200).extract().asString(); + return XmlParser.extractPairs(xml, "member", "Key", "Value"); + } + + private static ValidatableResponse listChangeSets(String stackName) { + return given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListChangeSets") + .formParam("StackName", stackName) + .when().post("/").then().statusCode(200); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationPipesCleanupIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationPipesCleanupIntegrationTest.java index 7e2c2ff6d3..60a673b064 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationPipesCleanupIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationPipesCleanupIntegrationTest.java @@ -410,7 +410,9 @@ class CloudFormationPipesCleanupIntegrationTest { assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status()); Mockito.doCallRealMethod().when(pipesService).deletePipe(eq(replacementName), anyString()); - updateStack(stackName, renameRollbackTemplate(priorName, "")); + // The rollback left the stack on this very template, which AWS refuses to update to with + // "No updates are to be performed.": a new output makes it an update. + updateStack(stackName, CfnUpdates.forceUpdate(renameRollbackTemplate(priorName, ""))); given() .contentType("application/json") diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRdsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRdsIntegrationTest.java index 9e130a2c1b..de21c33dd4 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRdsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRdsIntegrationTest.java @@ -128,7 +128,7 @@ class CloudFormationRdsIntegrationTest { .header("Authorization", CFN_AUTH) .formParam("Action", "UpdateStack") .formParam("StackName", stackName) - .formParam("TemplateBody", dbSubnetGroupTemplate(groupName)) + .formParam("TemplateBody", CfnUpdates.forceUpdate(dbSubnetGroupTemplate(groupName))) .when() .post("/") .then() diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRollbackCompleteUpdateIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRollbackCompleteUpdateIntegrationTest.java index 667b05e67f..ce7698b7e3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRollbackCompleteUpdateIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRollbackCompleteUpdateIntegrationTest.java @@ -159,7 +159,7 @@ class CloudFormationRollbackCompleteUpdateIntegrationTest { .contentType("application/x-www-form-urlencoded") .formParam("Action", "UpdateStack") .formParam("StackName", stackName) - .formParam("TemplateBody", topicTemplate(topicName)) + .formParam("TemplateBody", CfnUpdates.forceUpdate(topicTemplate(topicName))) .when() .post("/") .then() diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupRulesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupRulesIntegrationTest.java index 2fe78aec9f..47bb528e35 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupRulesIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationSecurityGroupRulesIntegrationTest.java @@ -235,7 +235,7 @@ class CloudFormationSecurityGroupRulesIntegrationTest { assertEquals(1, occurrences(describeGroup(groupId), "10.3.0.0/16")); // Unchanged template: the append-only authorize API would double the permission. - updateStack(stackName, standaloneIngressTemplate(groupId, "10.3.0.0/16")); + updateStack(stackName, CfnUpdates.forceUpdate(standaloneIngressTemplate(groupId, "10.3.0.0/16"))); assertEquals(1, occurrences(describeGroup(groupId), "10.3.0.0/16"), "update duplicated an unchanged standalone rule"); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java index 8463b391b2..ac0fc7d24c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationStackSetsIntegrationTest.java @@ -287,6 +287,147 @@ class CloudFormationStackSetsIntegrationTest { .then().statusCode(200); } + /** + * An UpdateStackSet that changes nothing for an instance leaves its stack as it is: the + * instance succeeds and its stack is not updated. + */ + @Test + void anUpdateStackSetWithNothingToChangeLeavesTheInstanceStackAsItIs() { + String setName = "same-" + UUID.randomUUID().toString().substring(0, 8); + String queue = "same-" + UUID.randomUUID().toString().substring(0, 8); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", queueTemplate(queue)) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackInstances") + .formParam("StackSetName", setName) + .formParam("Accounts.member.1", ACCOUNT_B) + .formParam("Regions.member.1", REGION) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + assertQueueVisible(ACCOUNT_B, queue); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "UpdateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", queueTemplate(queue)) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "StackSet-" + setName + "-" + ACCOUNT_B) + .header("Authorization", auth(ACCOUNT_B, "cloudformation")) + .when().post("/") + .then().statusCode(200) + .body(containsString("CREATE_COMPLETE")); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListStackSetOperations") + .formParam("StackSetName", setName) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200) + .body(containsString("UPDATE")) + .body(not(containsString("FAILED"))); + // The change set that found nothing to change is not left on the instance's stack. + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ListChangeSets") + .formParam("StackName", "StackSet-" + setName + "-" + ACCOUNT_B) + .header("Authorization", auth(ACCOUNT_B, "cloudformation")) + .when().post("/") + .then().statusCode(200) + .body(not(containsString("FAILED"))); + } + + /** + * An update that failed rolls the instance's stack back to its template. Updating the stack set + * back to that template has nothing to change, and the instance succeeds. + */ + @Test + void anUpdateStackSetBackToARolledBackInstancesTemplateSucceeds() { + String setName = "back-" + UUID.randomUUID().toString().substring(0, 8); + String queue = "back-" + UUID.randomUUID().toString().substring(0, 8); + String failing = """ + {"Resources":{"Q":{"Type":"AWS::SQS::Queue","Properties":{"QueueName":"%s"}}, + "Nested":{"Type":"AWS::CloudFormation::Stack","Properties":{}}}} + """.formatted(queue); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", queueTemplate(queue)) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateStackInstances") + .formParam("StackSetName", setName) + .formParam("Accounts.member.1", ACCOUNT_B) + .formParam("Regions.member.1", REGION) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "UpdateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", failing) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStacks") + .formParam("StackName", "StackSet-" + setName + "-" + ACCOUNT_B) + .header("Authorization", auth(ACCOUNT_B, "cloudformation")) + .when().post("/") + .then().statusCode(200) + .body(containsString("UPDATE_ROLLBACK_COMPLETE")); + + String operationId = given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "UpdateStackSet") + .formParam("StackSetName", setName) + .formParam("TemplateBody", queueTemplate(queue)) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200) + .extract().path("UpdateStackSetResponse.UpdateStackSetResult.OperationId"); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackSetOperation") + .formParam("StackSetName", setName) + .formParam("OperationId", operationId) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200) + .body(containsString("SUCCEEDED")); + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "DescribeStackInstance") + .formParam("StackSetName", setName) + .formParam("StackInstanceAccount", ACCOUNT_B) + .formParam("StackInstanceRegion", REGION) + .header("Authorization", auth(ADMIN, "cloudformation")) + .when().post("/") + .then().statusCode(200) + .body(containsString("SUCCEEDED")); + } + @Test void updateStackSetReappliesToExistingInstances() { String setName = "upd-" + UUID.randomUUID().toString().substring(0, 8);