diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java index 52bc7a4d65..9910ccf42f 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationQueryHandler.java @@ -377,7 +377,7 @@ public class CloudFormationQueryHandler { .elem("PhysicalResourceId", change.physicalResourceId()) .elem("ResourceType", change.resourceType()) .elem("Replacement", change.replacement()) - .raw("
") + .raw(scopeAndDetails(change)) .end("ResourceChange") .end("member"); } @@ -392,6 +392,34 @@ public class CloudFormationQueryHandler { } } + private static String scopeAndDetails(CloudFormationService.ResourceChange change) { + XmlBuilder xml = new XmlBuilder(); + if (change.scope().isEmpty()) { + xml.raw(""); + } else { + xml.start("Scope"); + change.scope().forEach(attribute -> xml.elem("member", attribute)); + xml.end("Scope"); + } + if (change.details().isEmpty()) { + return xml.raw("
").build(); + } + xml.start("Details"); + for (CloudFormationService.ChangeDetail detail : change.details()) { + xml.start("member") + .start("Target") + .elem("Attribute", detail.attribute()) + .elem("Name", detail.name()) + .elem("RequiresRecreation", detail.requiresRecreation()) + .end("Target") + .elem("Evaluation", detail.evaluation()) + .elem("ChangeSource", detail.changeSource()) + .elem("CausingEntity", detail.causingEntity()) + .end("member"); + } + return xml.end("Details").build(); + } + // ── ExecuteChangeSet ────────────────────────────────────────────────────── private Response executeChangeSet(MultivaluedMap params, String region) { diff --git a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java index 5d309d0616..540061ab0e 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/floci/aws/services/cloudformation/CloudFormationService.java @@ -1263,9 +1263,17 @@ public class CloudFormationService implements ResourceProvider { compared[0].path(logicalId).path("Properties"), compared[1].path(logicalId).path("Properties")}); } + JsonNode comparedOld = compared[0] != null ? compared[0].path(logicalId) : null; + JsonNode comparedNew = compared[0] != null ? compared[1].path(logicalId) : null; + // Details are descriptive and only DescribeChangeSet reads them: execution (which passes + // comparedProperties) must not be able to fail on them. + List details = comparedProperties != null ? List.of() + : changeDetails(resourceType, logicalId, oldDef, newDef, comparedOld, comparedNew, + changedParams, changedConditions, replacementDecider); changes.add(new ResourceChange("Modify", logicalId, resourcePhysicalId(stack, logicalId), resourceType, - replacement ? REPLACEMENT_TRUE : REPLACEMENT_FALSE)); + replacement ? REPLACEMENT_TRUE : REPLACEMENT_FALSE, + details.stream().map(ChangeDetail::attribute).distinct().toList(), details)); } }); oldResources.fields().forEachRemaining(e -> { @@ -1400,7 +1408,8 @@ public class CloudFormationService implements ResourceProvider { if (change.logicalResourceId().equals(logicalId) && replacementRank(replacement) > replacementRank(change.replacement())) { changes.set(i, new ResourceChange(change.action(), change.logicalResourceId(), - change.physicalResourceId(), change.resourceType(), replacement)); + change.physicalResourceId(), change.resourceType(), replacement, + change.scope(), change.details())); } } } @@ -1520,10 +1529,9 @@ public class CloudFormationService implements ResourceProvider { } boolean decide(String resourceType, String logicalId, JsonNode oldDef, JsonNode newDef) { - JsonNode oldBlock = withoutMissing(oldDef.path("Properties"), newDef.path("Properties")); - JsonNode newBlock = withoutMissing(newDef.path("Properties"), oldDef.path("Properties")); - JsonNode oldProps = withoutNoValue(logicalId, oldBlock, oldParams, oldConditions, oldTemplate); - JsonNode newProps = withoutNoValue(logicalId, newBlock, newParams, newConditions, newTemplate); + JsonNode[] props = writtenProperties(logicalId, oldDef, newDef); + JsonNode oldProps = props[0]; + JsonNode newProps = props[1]; boolean asWritten = requiresReplacement(resourceType, oldProps, newProps, changedParams, changedConditions); if (!CfnCreateOnlyProperties.hasSchema(resourceType) || !oldProps.isObject() || !newProps.isObject()) { @@ -1542,6 +1550,36 @@ public class CloudFormationService implements ResourceProvider { return resolved; } + /** The old and the new Properties as {@link #decide} reads them: as written, without AWS::NoValue. */ + private JsonNode[] writtenProperties(String logicalId, JsonNode oldDef, JsonNode newDef) { + JsonNode oldBlock = withoutMissing(oldDef.path("Properties"), newDef.path("Properties")); + JsonNode newBlock = withoutMissing(newDef.path("Properties"), oldDef.path("Properties")); + return new JsonNode[] { + withoutNoValue(logicalId, oldBlock, oldParams, oldConditions, oldTemplate), + withoutNoValue(logicalId, newBlock, newParams, newConditions, newTemplate)}; + } + + /** + * Whether the update of one top-level property recreates the resource: {@link #decide}'s rule for + * the create-only pointers at and under that property, between the compared forms when there are any, + * by the template text otherwise. + */ + boolean recreates(String resourceType, String logicalId, String property, JsonNode oldDef, + JsonNode newDef) { + JsonNode[] props = writtenProperties(logicalId, oldDef, newDef); + if (compared != null && compared[0] != null && compared[1] != null + && CfnCreateOnlyProperties.hasSchema(resourceType)) { + return comparedChanged(resourceType, logicalId, props[0], props[1], property); + } + return CfnCreateOnlyProperties.replacementPointers(resourceType).stream() + .filter(pointer -> under(pointer, property)) + .anyMatch(pointer -> writtenPointerChanged(pointer, props[0], props[1])); + } + + private static boolean under(String pointer, String property) { + return property == null || pointer.equals(property) || pointer.startsWith(property + "/"); + } + /** The block as written with every AWS::NoValue member left out, by the side's own conditions. */ private JsonNode withoutNoValue(String logicalId, JsonNode block, Map params, Map conditions, JsonNode template) { @@ -1577,6 +1615,12 @@ public class CloudFormationService implements ResourceProvider { */ private boolean comparedChanged(String resourceType, String logicalId, JsonNode oldProps, JsonNode newProps) { + return comparedChanged(resourceType, logicalId, oldProps, newProps, null); + } + + /** {@link #comparedChanged} for the pointers at and under one top-level property; all when null. */ + private boolean comparedChanged(String resourceType, String logicalId, JsonNode oldProps, + JsonNode newProps, String property) { if (compared == null || compared[0] == null || compared[1] == null || !CfnCreateOnlyProperties.hasSchema(resourceType)) { return false; @@ -1592,6 +1636,9 @@ public class CloudFormationService implements ResourceProvider { JsonNode digestedBefore = digested(before); JsonNode digestedAfter = digested(after); for (String pointer : CfnCreateOnlyProperties.replacementPointers(resourceType)) { + if (!under(pointer, property)) { + continue; + } boolean changed = noEvidence(pointer, before) ? writtenPointerChanged(pointer, oldProps, newProps) : CfnCreateOnlyProperties.createOnlyPointerChanged(pointer, digestedBefore, digestedAfter); @@ -1760,8 +1807,94 @@ public class CloudFormationService implements ResourceProvider { return false; } + /** + * One change of a resource. {@code scope} and {@code details} are those of {@code + * DescribeChangeSet}: filled for a Modify that the template diff found, empty for an Add, a Remove, a nested + * stack and a resource that changes only because it reads a replaced resource or a changed attribute. + */ public record ResourceChange(String action, String logicalResourceId, String physicalResourceId, - String resourceType, String replacement) {} + String resourceType, String replacement, + List scope, List details) { + public ResourceChange(String action, String logicalResourceId, String physicalResourceId, + String resourceType, String replacement) { + this(action, logicalResourceId, physicalResourceId, resourceType, replacement, List.of(), List.of()); + } + } + + /** + * An AWS {@code ResourceChangeDetail}: {@code attribute} and {@code name} are its Target (no name + * unless the attribute is Properties), {@code requiresRecreation} is set for Properties and Tags + * only, {@code causingEntity} is the parameter of a ParameterReference. + */ + public record ChangeDetail(String attribute, String name, String requiresRecreation, String evaluation, + String changeSource, String causingEntity) {} + + private static final List RESOURCE_ATTRIBUTES = List.of( + "Metadata", "DeletionPolicy", "UpdateReplacePolicy", "UpdatePolicy"); + + /** + * The details of a modified resource: one entry per property and per resource-level attribute that + * differs, in the forms the diff compared ({@code comparedOld} and {@code comparedNew}, null when the + * template did not resolve and the definitions as written were diffed). See {@link #addDetails}. + * {@code RequiresRecreation} is {@code Always} when the replacement decision's rule for the create-only + * pointers at and under the property says the update recreates, and {@code Never} otherwise. + * {@code Conditionally} is not produced: floci's create-only table records no conditional replacement, + * which AWS has. + */ + private List changeDetails(String resourceType, String logicalId, JsonNode oldDef, + JsonNode newDef, JsonNode comparedOld, JsonNode comparedNew, + Set changedParams, Set changedConditions, + ReplacementDecider decider) { + List details = new ArrayList<>(); + PropertyChanges.between(resourceType, true, oldDef.path("Properties"), newDef.path("Properties"), + comparedOld != null ? comparedOld.path("Properties") : null, + comparedNew != null ? comparedNew.path("Properties") : null) + .byName().values().stream() + .filter(c -> comparedOld != null + ? !comparedOld.path("Properties").path(c.name()) + .equals(comparedNew.path("Properties").path(c.name())) + : c.kind() != PropertyChanges.Kind.UNCHANGED + || readsChange(c.current(), changedParams, changedConditions)) + .forEach(c -> { + boolean tags = "Tags".equals(c.name()); + addDetails(details, tags ? "Tags" : "Properties", tags ? null : c.name(), + decider.recreates(resourceType, logicalId, c.name(), oldDef, newDef) + ? "Always" : "Never", c.prior(), c.current(), changedParams); + }); + for (String attribute : RESOURCE_ATTRIBUTES) { + JsonNode before = (comparedOld != null ? comparedOld : oldDef).path(attribute); + JsonNode after = (comparedNew != null ? comparedNew : newDef).path(attribute); + if (!before.equals(after) + || comparedOld == null && readsChange(newDef.path(attribute), changedParams, changedConditions)) { + addDetails(details, attribute, null, null, oldDef.path(attribute), newDef.path(attribute), + changedParams); + } + } + return details; + } + + private boolean readsChange(JsonNode written, Set changedParams, Set changedConditions) { + return written != null && (referencesAnyParameter(written, changedParams) + || referencesAnyCondition(written, changedConditions)); + } + + /** + * A difference in the written values is a static DirectModification, one that shows only after the + * parameters or conditions are applied a dynamic one. Each changed parameter the written value reads + * adds a static ParameterReference either way, as AWS reports a Ref of a changed parameter. + */ + private void addDetails(List details, String attribute, String name, String recreation, + JsonNode writtenBefore, JsonNode writtenAfter, Set changedParams) { + boolean written = !Objects.equals(writtenBefore, writtenAfter); + details.add(new ChangeDetail(attribute, name, recreation, written ? "Static" : "Dynamic", + "DirectModification", null)); + for (String parameter : new TreeSet<>(changedParams)) { + if (writtenAfter != null && referencesAnyParameter(writtenAfter, Set.of(parameter))) { + details.add(new ChangeDetail(attribute, name, recreation, "Static", "ParameterReference", + parameter)); + } + } + } private String resourcePhysicalId(Stack stack, String logicalId) { StackResource resource = stack.getResources().get(logicalId); diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationChangeSetDiffIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationChangeSetDiffIntegrationTest.java index dea14ec92c..c9a0daa067 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationChangeSetDiffIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationChangeSetDiffIntegrationTest.java @@ -5,6 +5,7 @@ import io.floci.aws.services.ses.SesReceiptRuleService; import io.floci.aws.testing.CfnStackWaits; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.specification.RequestSpecification; import jakarta.inject.Inject; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -15,6 +16,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import static io.floci.aws.testing.CfnRequests.cfn; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; @@ -1101,33 +1103,152 @@ class CloudFormationChangeSetDiffIntegrationTest { /** Creates an UPDATE change set and returns the Replacement value per logical id. */ private Map previewReplacement(String stackName, String changeSetName, String template) { - given() - .contentType("application/x-www-form-urlencoded") - .formParam("Action", "CreateChangeSet") - .formParam("StackName", stackName) - .formParam("ChangeSetName", changeSetName) - .formParam("ChangeSetType", "UPDATE") - .formParam("TemplateBody", template) - .when() - .post("/") - .then() - .statusCode(200); - - String desc = given() - .contentType("application/x-www-form-urlencoded") - .formParam("Action", "DescribeChangeSet") - .formParam("StackName", stackName) - .formParam("ChangeSetName", changeSetName) - .when() - .post("/") - .then() - .statusCode(200) - .extract().body().asString(); - Map result = new HashMap<>(); - for (Map change : XmlParser.extractGroups(desc, "ResourceChange")) { + for (Map change : XmlParser.extractGroups( + describeChangeSet(stackName, changeSetName, template, null), "ResourceChange")) { result.put(change.get("LogicalResourceId"), change.get("Replacement")); } return result; } + + /** Creates an UPDATE change set (with one "Name=value" parameter when given) and returns the DescribeChangeSet body. */ + private String describeChangeSet(String stackName, String changeSetName, String template, String param) { + RequestSpecification create = cfn("CreateChangeSet", stackName) + .formParam("ChangeSetName", changeSetName) + .formParam("ChangeSetType", "UPDATE") + .formParam("TemplateBody", template); + if (param != null) { + create.formParam("Parameters.member.1.ParameterKey", param.split("=")[0]) + .formParam("Parameters.member.1.ParameterValue", param.split("=")[1]); + } + create.when().post("/").then().statusCode(200); + + return cfn("DescribeChangeSet", stackName) + .formParam("ChangeSetName", changeSetName) + .when().post("/") + .then().statusCode(200) + .extract().body().asString(); + } + + private record DetailsRow(String name, String type, String oldProps, String newProps, String newParam, + List scope, List details, String replacement, boolean exact) { } + + /** Details are "Attribute|Name|RequiresRecreation|ChangeSource|Evaluation|CausingEntity", empty when absent. */ + private static String template(String type, String props, String... extraResources) { + return "{\"Parameters\":{\"P\":{\"Type\":\"String\",\"Default\":\"v1\"},\"Env\":{\"Type\":\"String\",\"Default\":\"prod\"}},\"Conditions\":{\"C\":{\"Fn::Equals\":[{\"Ref\":\"Env\"},\"prod\"]}},\"Resources\":{\"R\":{\"Type\":\"" + + type + "\",\"Properties\":{" + props + "}}" + String.join("", extraResources) + "}}"; + } + + private static String healthCheck(String type) { + return "\"HealthCheckConfig\":{\"Type\":\"" + type + "\",\"IPAddress\":\"192.0.2.10\",\"Port\":80}"; + } + + private static String text(XmlParser.XmlElement parent, String child) { + XmlParser.XmlElement e = parent == null ? null : parent.child(child); + return e == null ? "" : e.text(); + } + + private static XmlParser.XmlElement resourceChange(String body, String logicalId) { + for (XmlParser.XmlElement member : XmlParser.parseDocumentElementTree(body) + .child("DescribeChangeSetResult").child("Changes").children()) { + XmlParser.XmlElement rc = member.child("ResourceChange"); + if (logicalId.equals(text(rc, "LogicalResourceId"))) { + return rc; + } + } + return null; + } + + private static List detailsOf(XmlParser.XmlElement rc) { + List result = new ArrayList<>(); + for (XmlParser.XmlElement d : rc.child("Details").children()) { + XmlParser.XmlElement t = d.child("Target"); + result.add(String.join("|", text(t, "Attribute"), text(t, "Name"), text(t, "RequiresRecreation"), + text(d, "ChangeSource"), text(d, "Evaluation"), text(d, "CausingEntity"))); + } + return result.stream().sorted().toList(); + } + + /** + * Expected values: AWS DescribeChangeSet samples (direct Tags edit, parameter change giving a + * DirectModification/Dynamic and a ParameterReference/Static detail) and the ResourceChangeDetail + * reference (Name only for Properties; Replacement is the most intrusive RequiresRecreation). + */ + @Test + void modifiedResource_reportsScopeAndDetails() { + String direct = "|DirectModification|Static|"; + String ifSet = "{\"Fn::If\":[\"C\",5,{\"Ref\":\"AWS::NoValue\"}]}"; + List rows = List.of( + new DetailsRow("changed", "AWS::SNS::Topic", "\"DisplayName\":\"a\"", "\"DisplayName\":\"b\"", null, + List.of("Properties"), List.of("Properties|DisplayName|Never" + direct), "False", true), + new DetailsRow("added", "AWS::SNS::Topic", "\"TopicName\":\"cs-det-added\"", + "\"TopicName\":\"cs-det-added\",\"DisplayName\":\"b\"", null, + List.of("Properties"), List.of("Properties|DisplayName|Never" + direct), "False", true), + new DetailsRow("dropped", "AWS::SNS::Topic", "\"TopicName\":\"cs-det-dropped\",\"DisplayName\":\"a\"", + "\"TopicName\":\"cs-det-dropped\"", null, + List.of("Properties"), List.of("Properties|DisplayName|Never" + direct), "False", true), + new DetailsRow("create-only", "AWS::SQS::Queue", "\"QueueName\":\"cs-det-q-a\"", "\"QueueName\":\"cs-det-q-b\"", + null, List.of("Properties"), List.of("Properties|QueueName|Always" + direct), "True", true), + new DetailsRow("tags", "AWS::SQS::Queue", + "\"QueueName\":\"cs-det-tags\",\"Tags\":[{\"Key\":\"k\",\"Value\":\"v1\"}]", + "\"QueueName\":\"cs-det-tags\",\"Tags\":[{\"Key\":\"k\",\"Value\":\"v2\"}]", null, + List.of("Tags"), List.of("Tags||Never" + direct), "False", true), + new DetailsRow("parameter", "AWS::SNS::Topic", "\"DisplayName\":{\"Ref\":\"P\"}", + "\"DisplayName\":{\"Ref\":\"P\"}", "P=v2", List.of("Properties"), + List.of("Properties|DisplayName|Never|DirectModification|Dynamic|", + "Properties|DisplayName|Never|ParameterReference|Static|P"), "False", true), + new DetailsRow("no-value", "AWS::SNS::Topic", "\"DisplayName\":\"a\"", + "\"DisplayName\":\"b\",\"KmsMasterKeyId\":{\"Ref\":\"AWS::NoValue\"}", null, + List.of("Properties"), List.of("Properties|DisplayName|Never" + direct), "False", true), + new DetailsRow("edited-and-parameter", "AWS::SQS::Queue", + "\"QueueName\":\"cs-det-both\",\"Tags\":[{\"Key\":\"k\",\"Value\":{\"Ref\":\"P\"}}]", + "\"QueueName\":\"cs-det-both\",\"Tags\":[{\"Key\":\"k2\",\"Value\":{\"Ref\":\"P\"}}]", "P=v2", + List.of("Tags"), List.of("Tags||Never" + direct, "Tags||Never|ParameterReference|Static|P"), "False", true), + new DetailsRow("nested-create-only", "AWS::Route53::HealthCheck", healthCheck("HTTP"), healthCheck("HTTPS"), null, + List.of("Properties"), List.of("Properties|HealthCheckConfig|Always" + direct), "True", true), + new DetailsRow("condition", "AWS::SQS::Queue", "\"QueueName\":\"cs-det-cond\",\"DelaySeconds\":" + ifSet, + "\"QueueName\":\"cs-det-cond\",\"DelaySeconds\":" + ifSet, "Env=dev", List.of("Properties"), + List.of("Properties|DelaySeconds|Never|DirectModification|Dynamic|"), "False", false)); + + List failures = new ArrayList<>(); + for (DetailsRow row : rows) { + String stackName = "cs-details-" + row.name(); + stacksToDelete.add(stackName); + createStack(stackName, template(row.type(), row.oldProps())); + XmlParser.XmlElement rc = resourceChange(describeChangeSet(stackName, row.name() + "-cs", + template(row.type(), row.newProps()), row.newParam()), "R"); + List scope = rc.child("Scope").children().stream().map(XmlParser.XmlElement::text).sorted().toList(); + List details = detailsOf(rc); + boolean recreates = row.details().stream().anyMatch(d -> d.contains("|Always|")); + boolean staticDirect = details.stream().anyMatch(d -> d.endsWith("|DirectModification|Static|")); + boolean detailsOk = row.exact() ? details.equals(row.details().stream().sorted().toList()) + : details.containsAll(row.details()) && !staticDirect; + if (!scope.equals(row.scope()) || !detailsOk + || !row.replacement().equals(text(rc, "Replacement")) || recreates != "True".equals(row.replacement())) { + failures.add(row.name() + ": scope=" + scope + " details=" + details + " replacement=" + text(rc, "Replacement")); + } + } + assertEquals(List.of(), failures); + } + + /** ResourceChange.Scope and Details are documented "for the Modify action" only. */ + @Test + void addedAndRemovedResources_haveNoScopeAndNoDetails() { + String stackName = "cs-details-add-remove"; + stacksToDelete.add(stackName); + String gone = ",\"Gone\":{\"Type\":\"AWS::SNS::Topic\",\"Properties\":{\"TopicName\":\"cs-det-gone\"}}"; + String fresh = ",\"Fresh\":{\"Type\":\"AWS::SNS::Topic\",\"Properties\":{\"TopicName\":\"cs-det-fresh\"}}"; + createStack(stackName, template("AWS::SNS::Topic", "\"TopicName\":\"cs-det-keep\"", gone)); + + String body = describeChangeSet(stackName, "add-remove-cs", + template("AWS::SNS::Topic", "\"TopicName\":\"cs-det-keep\"", fresh), null); + XmlParser.XmlElement removed = resourceChange(body, "Gone"); + XmlParser.XmlElement added = resourceChange(body, "Fresh"); + assertEquals("Remove", text(removed, "Action")); + assertEquals("Add", text(added, "Action")); + for (XmlParser.XmlElement rc : List.of(removed, added)) { + assertEquals(0, rc.child("Scope") == null ? 0 : rc.child("Scope").children().size()); + assertEquals(0, rc.child("Details") == null ? 0 : rc.child("Details").children().size()); + } + } }