diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java index b176aff64a..b61c93aee9 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java @@ -151,6 +151,11 @@ public final class CfnRollback { * {@code Route53CfnProvisioner} before its update call and spent by its {@code rollbackUpdate}. */ public static final String HEALTH_CHECK_UPDATE_SNAPSHOT_ATTR = "__FlociRoute53HealthCheckUpdateSnapshot"; + /** + * The record a record set update displaced and the record it wrote, for that update's rollback. The + * commit's cleanup walk reaches every resource, and the record set drops it there. + */ + public static final String ROUTE53_RECORD_UPDATE_SNAPSHOT_ATTR = "__FlociRoute53RecordUpdate"; public static final String S3_BUCKET_UPDATE_SNAPSHOT_ATTR = "__FlociS3BucketUpdateSnapshot"; /** diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/Route53CfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/Route53CfnProvisioner.java index 5561be3532..cee80e0315 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/Route53CfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/Route53CfnProvisioner.java @@ -72,6 +72,7 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { // and attributes before an update, kept until the update commits or rolls back; the records a // failed update wrote that its rollback could not delete; and the cleanup's delete attempts. private static final String GROUP_RECORDS_ATTR = "__FlociRoute53GroupRecords"; + private static final String RECORD_UPDATE_ATTR = CfnRollback.ROUTE53_RECORD_UPDATE_SNAPSHOT_ATTR; private static final String GROUP_UPDATE_ATTR = "__FlociRoute53GroupUpdate"; private static final String GROUP_OWED_ATTR = "__FlociRoute53GroupOwedDeletes"; private static final String GROUP_CLEANUP_ATTEMPTS_ATTR = "__FlociRoute53GroupCleanupAttempts"; @@ -105,6 +106,8 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { } private void provisionRecordSet(StackResource resource, JsonNode props, ProvisionContext ctx) { + // A snapshot an earlier update left is stale: that update committed or its rollback was skipped. + resource.getAttributes().remove(RECORD_UPDATE_ATTR); Map priorAttributes = new HashMap<>(resource.getAttributes()); ResourceRecordSet rrs = recordSet(RECORD_SET, props, ctx); String name = ctx.resolveOptional(props, "Name"); @@ -118,13 +121,30 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { // the stack does not own yet, so it is a CREATE: a record another owner already holds under // that identity fails the stack instead of being taken over. boolean sameIdentity = isPriorIdentity(ctx, priorAttributes, zoneId, name, type, setIdentifier); + String snapshot = ctx.isUpdate() + ? recordSnapshotOf(ctx, priorAttributes, zoneId, name, type, setIdentifier) : null; route53Service.changeResourceRecordSets(zoneId, List.of(change(sameIdentity ? "UPSERT" : "CREATE", rrs)), "CloudFormation " + ctx.stackName() + "/" + resource.getLogicalId()); + if (snapshot != null) { + resource.getAttributes().put(RECORD_UPDATE_ATTR, snapshot); + } // An update that changes the identity leaves the prior record orphaned, so remove it, // otherwise it lingers in the zone and later blocks the zone's own delete. if (!sameIdentity) { - removeSupersededRecord(ctx, priorAttributes); + try { + removeSupersededRecord(ctx, priorAttributes); + } catch (RuntimeException failure) { + // The failed attempt's resource is dropped for the prior one, which never learns the + // record this attempt wrote, so it is removed here. + try { + removeRecord(zoneId, name, type, setIdentifier, + "CloudFormation undo " + resource.getLogicalId(), "NoSuchHostedZone"); + } catch (RuntimeException cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + throw failure; + } } resource.setPhysicalId(name); @@ -137,6 +157,85 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { } } + /** + * The record the update displaces and the resource's physical id and attributes before it, as + * JSON, so a failed stack update can put them back. The record is null when the zone or the + * record is gone. + */ + private String recordSnapshotOf(ProvisionContext ctx, Map priorAttributes, + String writtenZoneId, String writtenName, String writtenType, + String writtenSetIdentifier) { + ObjectNode snapshot = snapshotNode(ctx.priorPhysicalId(), priorAttributes); + // The identity this update writes, kept apart from the resource's attributes, which a failure + // after the write may not have updated yet. + ObjectNode written = snapshot.putObject("written"); + written.put("zoneId", writtenZoneId); + written.put("name", writtenName); + written.put("type", writtenType); + written.put("setIdentifier", writtenSetIdentifier); + ResourceRecordSet record = null; + String zoneId = priorAttributes.get(RECORD_ZONE_ATTR); + String type = priorAttributes.get(RECORD_TYPE_ATTR); + if (isSet(zoneId) && isSet(ctx.priorPhysicalId()) && isSet(type) && zoneExists(zoneId)) { + record = findRecord(zoneId, ctx.priorPhysicalId(), type, priorAttributes.get(RECORD_SET_ID_ATTR)); + } + snapshot.set("record", record == null ? null : MAPPER.valueToTree(record)); + return snapshot.toString(); + } + + /** + * Puts a record set back as the failed update found it: the record the update wrote is deleted + * from its zone, and the record it displaced is written again in the zone it was in, which an + * update that moved the record to a replaced zone leaves standing until the stack commits. In + * one zone this is a single batch, as for a group ({@link #rollbackGroupUpdate}), so a failure + * never leaves the record lost: one UPSERT of the displaced record when both share an identity, + * otherwise a DELETE of the written one beside an UPSERT of the displaced one. Across two zones + * the displaced record is written first, then the written one deleted. A zone already gone has + * no record left to delete. Returns false when this update changed nothing, + * and when the record it displaced was not captured (a resource from before the snapshot, a record + * or zone already gone): the rollback cannot restore it, and deleting the current record would + * report a restore that did not happen. + */ + private boolean rollbackRecordSetUpdate(StackResource resource) { + String raw = resource.getAttributes().get(RECORD_UPDATE_ATTR); + if (raw == null) { + return false; + } + JsonNode snapshot; + try { + snapshot = MAPPER.readTree(raw); + } catch (JsonProcessingException e) { + throw new IllegalStateException("Could not read the update snapshot of " + resource.getLogicalId(), e); + } + GroupSnapshot before = snapshotFrom(snapshot); + ResourceRecordSet prior = snapshot.path("record").isObject() + ? MAPPER.convertValue(snapshot.get("record"), ResourceRecordSet.class) : null; + if (prior == null) { + return false; + } + JsonNode written = snapshot.path("written"); + String comment = "CloudFormation rollback " + resource.getLogicalId(); + String priorZoneId = before.attributes().get(RECORD_ZONE_ATTR); + String writtenZoneId = written.path("zoneId").asText(null); + ResourceRecordSet writtenRecord = writtenZoneId != null && zoneExists(writtenZoneId) + ? findRecord(writtenZoneId, written.path("name").asText(), written.path("type").asText(), + written.path("setIdentifier").asText(null)) + : null; + List> changes = new ArrayList<>(); + boolean sameZone = Objects.equals(writtenZoneId, priorZoneId); + if (writtenRecord != null && sameZone && !Route53Service.sameRecord(writtenRecord, prior)) { + changes.add(change("DELETE", writtenRecord)); + } + changes.add(change("UPSERT", prior)); + route53Service.changeResourceRecordSets(priorZoneId, changes, comment); + if (writtenRecord != null && !sameZone) { + route53Service.changeResourceRecordSets(writtenZoneId, List.of(change("DELETE", writtenRecord)), + comment); + } + restore(resource, before); + return true; + } + /** * The record an {@code AWS::Route53::RecordSet}, or one entry of a group's {@code RecordSets}, * describes. {@code owner} names it in validation errors. @@ -499,7 +598,7 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { return "Retain".equals(resource.getUpdateReplacePolicy()); } - /** A group's physical id and attributes before an update. */ + /** A group's or record set's physical id and attributes before an update. */ private record GroupSnapshot(String physicalId, Map attributes) { } @@ -508,10 +607,20 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { } private static String snapshotOf(StackResource resource) { + return snapshotNode(resource.getPhysicalId(), resource.getAttributes()).toString(); + } + + /** The physical id and attributes every update snapshot keeps; a record set's adds its own fields. */ + private static ObjectNode snapshotNode(String physicalId, Map attributes) { ObjectNode snapshot = MAPPER.createObjectNode(); - snapshot.put("physicalId", resource.getPhysicalId()); - snapshot.set("attributes", MAPPER.valueToTree(resource.getAttributes())); - return snapshot.toString(); + snapshot.put("physicalId", physicalId); + snapshot.set("attributes", MAPPER.valueToTree(attributes)); + return snapshot; + } + + private static GroupSnapshot snapshotFrom(JsonNode snapshot) { + return new GroupSnapshot(snapshot.path("physicalId").asText(null), + MAPPER.convertValue(snapshot.path("attributes"), ATTRIBUTES)); } /** What the group had before the update in flight, or null when none is. */ @@ -521,9 +630,7 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { return null; } try { - JsonNode snapshot = MAPPER.readTree(raw); - return new GroupSnapshot(snapshot.path("physicalId").asText(null), - MAPPER.convertValue(snapshot.path("attributes"), ATTRIBUTES)); + return snapshotFrom(MAPPER.readTree(raw)); } catch (JsonProcessingException | IllegalArgumentException e) { throw new IllegalStateException("Could not read the update snapshot of " + resource.getLogicalId(), e); } @@ -604,7 +711,8 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { || priorType == null || priorType.isBlank()) { return; } - removeRecord(priorZoneId, priorName, priorType, priorSetId, "CloudFormation supersede"); + removeRecord(priorZoneId, priorName, priorType, priorSetId, "CloudFormation supersede", + "NoSuchHostedZone", "InvalidChangeBatch"); } /** @@ -868,7 +976,19 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { } } + /** + * Creates the zone, or updates it in place. {@code Name} and {@code DelegationSetId} are + * create-only, so an update whose change set says {@code Replacement} creates a new zone; the + * displaced zone is deleted once the update commits, or put back when it rolls back, through + * {@link ReplacementCleanup}. AWS refuses to delete a zone that still holds records beyond the + * default NS and SOA, and so does {@link Route53Service#deleteHostedZone}: the cleanup then + * retries and gives up as for any displaced entity. + */ private void provisionHostedZone(StackResource resource, JsonNode props, ProvisionContext ctx) { + if (ctx.isUpdate()) { + ReplacementCleanup.endRollbackRetry(resource); + } + Map attributesBefore = Map.copyOf(resource.getAttributes()); String name = ctx.resolveOptional(props, "Name"); if (name == null || name.isBlank()) { throw new IllegalArgumentException("AWS::Route53::HostedZone requires Name"); @@ -877,9 +997,21 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { JsonNode resolved = ctx.engine().resolveNode(props); String comment = resolved.path("HostedZoneConfig").path("Comment").asText(null); List vpcs = parseVpcs(resolved.path("VPCs")); + String declaredDelegationSet = ctx.resolveOptional(props, "DelegationSetId"); + String delegationSetId = isSet(declaredDelegationSet) ? declaredDelegationSet : null; String callerReference = ctx.stackName() + "/" + resource.getLogicalId(); boolean isTrackedZoneMissing = resource.getPhysicalId() != null && !zoneExists(resource.getPhysicalId()); + // The engine's change decides, as for the change set's Replacement. A tracked zone that is gone + // is recreated below, not replaced: there is nothing to delete or put back. + String priorZoneId = resource.getPhysicalId(); + boolean replacing = ctx.isUpdate() && priorZoneId != null && !isTrackedZoneMissing + && ctx.changes(HOSTED_ZONE, props).requiresReplacement(); + if (replacing) { + // The displaced zone keeps its caller reference, so the new one needs its own. + callerReference = callerReference + "/" + UUID.randomUUID(); + resource.setPhysicalId(null); + } if (isTrackedZoneMissing) { // The tracked physical ID may be a leftover from the retired monolith's HostedZone // stub, which minted a random Z-id with zero Route53Service backing (see commit @@ -888,15 +1020,27 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { resource.setPhysicalId(null); } - String id; - if (resource.getPhysicalId() == null) { + final String id; + final boolean createdHere = resource.getPhysicalId() == null; + if (createdHere) { // CreateHostedZone only accepts a single VPC (a private zone becomes // resolvable from that VPC immediately); any further VPCs in the CFN // template's list are wired in afterward via AssociateVPCWithHostedZone, // matching how a real CloudFormation update converges an existing zone. VpcAssociation firstVpc = vpcs.isEmpty() ? null : vpcs.get(0); - Route53Service.CreateZoneResult created = route53Service.createHostedZone( - name, callerReference, comment, firstVpc); + Route53Service.CreateZoneResult created; + try { + created = delegationSetId == null + ? route53Service.createHostedZone(name, callerReference, comment, firstVpc) + : route53Service.createHostedZone(name, callerReference, comment, firstVpc, + delegationSetId); + } catch (RuntimeException e) { + if (replacing) { + // Nothing was created, so the resource still is the prior zone. + resource.setPhysicalId(priorZoneId); + } + throw e; + } id = created.zone().getId(); // Record the physical ID before any follow-up call that can fail: once the // zone exists, the stack engine must be able to track and clean it up even @@ -905,27 +1049,6 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { // up during stack-create rollback, which keys off that attribute rather than // physicalId alone (see CfnRollback.ROLLBACK_OWNED_ATTR). resource.setPhysicalId(id); - resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); - try { - for (int i = 1; i < vpcs.size(); i++) { - route53Service.associateVpcWithHostedZone(id, vpcs.get(i), comment); - } - } catch (RuntimeException e) { - // An update that recreates a missing legacy zone (isTrackedZoneMissing above) - // fails through CloudFormationService's generic update-rollback path, which - // restores the stack's previous StackResource wholesale and never learns this - // zone's ID - orphaning it, so the next retry reuses the same caller reference - // and fails with HostedZoneAlreadyExists. Since we own this zone (we just - // created it), clean it up ourselves rather than depend on that path. - // Once cleanup succeeds, physical state matches what it was before this update - // started (tracked zone missing), so tell the generic rollback walker this - // resource is restored - otherwise it falls through to "rollback is not - // implemented" and strands the stack in UPDATE_ROLLBACK_FAILED for a resource - // there is nothing left to reconcile. - route53Service.deleteHostedZone(id); - resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true"); - throw e; - } } else { id = resource.getPhysicalId(); for (VpcAssociation vpc : vpcs) { @@ -933,23 +1056,42 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { } } - resource.setPhysicalId(id); - resource.getAttributes().put("Id", id); - resource.getAttributes().put("NameServers", String.join(",", route53Service.getAssignedNameServers(id))); + CfnRollback.guarded(resource, ctx, createdHere, () -> { + // The generic update-rollback restores the previous resource and never learns the + // new zone's ID, so the zone created here is deleted here. Delete first: if it + // fails, the physical id stays on the new zone for the orphan record. + route53Service.deleteHostedZone(id); + resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true"); + if (replacing) { + resource.setPhysicalId(priorZoneId); + restoreZoneAttributes(resource, attributesBefore); + } + }, () -> { }, () -> { + for (int i = 1; createdHere && i < vpcs.size(); i++) { + route53Service.associateVpcWithHostedZone(id, vpcs.get(i), comment); + } + resource.setPhysicalId(id); + resource.getAttributes().put("Id", id); + resource.getAttributes().put("NameServers", + String.join(",", route53Service.getAssignedNameServers(id))); - List> tags = parseTags(resolved.path("HostedZoneTags")); - if (!tags.isEmpty()) { - try { + List> tags = parseTags(resolved.path("HostedZoneTags")); + if (!tags.isEmpty()) { route53Service.changeTagsForResource("hostedzone", id, tags, List.of()); - } catch (RuntimeException e) { - if ("true".equals(resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR))) { - route53Service.deleteHostedZone(id); - resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true"); - } - throw e; + } + }); + ReplacementCleanup.record(resource, ctx, attributesBefore, replacing); + } + + /** Puts back the attributes the new zone overwrote, so the resource describes the prior zone again. */ + private static void restoreZoneAttributes(StackResource resource, Map before) { + for (String key : List.of("Id", "NameServers")) { + if (before.containsKey(key)) { + resource.getAttributes().put(key, before.get(key)); + } else { + resource.getAttributes().remove(key); } } - resource.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); } private boolean zoneExists(String id) { @@ -964,13 +1106,32 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { } } + /** + * The deleter for a displaced entity or a rolled-back replacement. A zone that is already gone + * counts as deleted, as AWS's cleanup of a replaced resource does; the stack delete keeps + * {@link #delete(String, String, String)}, which reports it. + */ + private void deleteDisplaced(String resourceType, String physicalId, String region) { + if (HOSTED_ZONE.equals(resourceType)) { + CfnDeletes.safeDelete("Route53 hosted zone", physicalId, + () -> route53Service.deleteHostedZone(physicalId), "NoSuchHostedZone"); + } else { + delete(resourceType, physicalId, region); + } + } + + /** The types whose replacing update is cleaned up through {@link ReplacementCleanup}. */ + private static boolean replacesWithCleanup(StackResource resource) { + return HEALTH_CHECK.equals(resource.getResourceType()) || HOSTED_ZONE.equals(resource.getResourceType()); + } + @Override public boolean hasReplacementUpdate(StackResource resource) { if (RECORD_SET_GROUP.equals(resource.getResourceType())) { GroupSnapshot prior = groupSnapshot(resource); return prior != null && movedZone(resource, prior); } - return HEALTH_CHECK.equals(resource.getResourceType()) && ReplacementCleanup.hasReplacement(resource); + return replacesWithCleanup(resource) && ReplacementCleanup.hasReplacement(resource); } @Override @@ -978,8 +1139,7 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { if (RECORD_SET_GROUP.equals(resource.getResourceType())) { return groupCleanupPhysicalId(resource); } - return HEALTH_CHECK.equals(resource.getResourceType()) - ? ReplacementCleanup.cleanupPhysicalId(resource) : null; + return replacesWithCleanup(resource) ? ReplacementCleanup.cleanupPhysicalId(resource) : null; } @Override @@ -987,8 +1147,13 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { if (RECORD_SET_GROUP.equals(resource.getResourceType())) { return completeGroupCleanup(resource, false); } - return HEALTH_CHECK.equals(resource.getResourceType()) - ? ReplacementCleanup.complete(resource, this::delete) : UpdateCleanupResult.notApplicable(); + if (RECORD_SET.equals(resource.getResourceType())) { + // The update committed, so there is nothing left to roll back. + resource.getAttributes().remove(RECORD_UPDATE_ATTR); + return UpdateCleanupResult.notApplicable(); + } + return replacesWithCleanup(resource) + ? ReplacementCleanup.complete(resource, this::deleteDisplaced) : UpdateCleanupResult.notApplicable(); } /** @@ -1009,7 +1174,9 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { */ @Override public void clearUpdate(StackResource resource) { - if (HEALTH_CHECK.equals(resource.getResourceType())) { + if (HOSTED_ZONE.equals(resource.getResourceType())) { + ReplacementCleanup.clear(resource); + } else if (HEALTH_CHECK.equals(resource.getResourceType())) { resource.getAttributes().remove(CfnRollback.HEALTH_CHECK_UPDATE_SNAPSHOT_ATTR); ReplacementCleanup.clear(resource); } else if (RECORD_SET_GROUP.equals(resource.getResourceType())) { @@ -1022,14 +1189,21 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { /** * A health check replacement is undone through the cleanup record, and an in-place update from * the snapshot taken before it. With neither on the resource the provision failed before it - * changed anything. A record set group is put back from the snapshot its update kept. Hosted - * zones and record sets keep the engine's default. + * changed anything. A record set group and a record set are put back from the snapshot their + * update kept. A hosted zone's replacement is undone through the cleanup record, and its other + * updates keep the engine's default. */ @Override public boolean rollbackUpdate(StackResource resource) { if (RECORD_SET_GROUP.equals(resource.getResourceType())) { return rollbackGroupUpdate(resource); } + if (RECORD_SET.equals(resource.getResourceType())) { + return rollbackRecordSetUpdate(resource); + } + if (HOSTED_ZONE.equals(resource.getResourceType())) { + return ReplacementCleanup.rollback(resource, this::deleteDisplaced); + } if (!HEALTH_CHECK.equals(resource.getResourceType())) { return false; } @@ -1105,21 +1279,25 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner { String setIdentifier = attributes.get(RECORD_SET_ID_ATTR); // Removing a record the zone no longer has is a no-op, and a zone already gone tolerated; any // other failure must reach the stack as DELETE_FAILED. - removeRecord(zoneId, name, type, setIdentifier, "CloudFormation delete " + resource.getLogicalId()); + removeRecord(zoneId, name, type, setIdentifier, "CloudFormation delete " + resource.getLogicalId(), + "NoSuchHostedZone", "InvalidChangeBatch"); } /** - * Removes a record by its identity, tolerating a zone or record already gone. A zone still + * Removes a record by its identity; a record already gone is a no-op. A zone still * holding the record blocks its own delete, so a superseded or deleted record must actually go. + * Only the {@code tolerated} error codes pass, so a refused DELETE (a record changed outside the + * stack) fails the caller unless it lists that code. */ - private void removeRecord(String zoneId, String name, String type, String setIdentifier, String comment) { + private void removeRecord(String zoneId, String name, String type, String setIdentifier, String comment, + String... tolerated) { CfnDeletes.safeDelete("Route53 record set", name + " " + type, () -> { ResourceRecordSet existing = findRecord(zoneId, name, type, setIdentifier); if (existing == null) { return; } route53Service.changeResourceRecordSets(zoneId, List.of(change("DELETE", existing)), comment); - }, "NoSuchHostedZone", "InvalidChangeBatch"); + }, tolerated); } /** diff --git a/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java index 96999a72a8..91c6d72d98 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CfnReplacementIntegrationTest.java @@ -48,8 +48,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** * An update replaces a resource exactly when its change set said {@code Replacement: True}, and the * change set's {@code Replacement} is the one AWS documents for the changed property ("Update - * requires"). Covered: AppConfig profiles and ElastiCache clusters changed in a create-only and in - * another property; a create-only value that is not plain template text (a dynamic reference + * requires"). Covered: AppConfig profiles, ElastiCache clusters and Route53 hosted zones changed in a + * create-only and in another property; a create-only value that is not plain template text (a dynamic reference * rewritten as the literal it resolves to, a value known only during the update, a value read from * a resource replaced in the same update, an attribute another resource moves while the update * runs); and a stack that holds no record of what its dynamic references resolved to. @@ -123,6 +123,16 @@ class CfnReplacementIntegrationTest { CLUSTER + "\"CacheNodeType\": \"cache.t3.micro\"", CLUSTER + "\"CacheNodeType\": \"cache.t3.small\"", "False", true, null), + createOnlyRow("Route53 zone Name", "", "", "AWS::Route53::HostedZone", + "\"Name\": \"replacement-before.example.test\"", + "\"Name\": \"replacement-after.example.test\"", + "True", false, null), + createOnlyRow("Route53 zone HostedZoneConfig", "", "", "AWS::Route53::HostedZone", + "\"Name\": \"replacement-comment.example.test\"," + + " \"HostedZoneConfig\": {\"Comment\": \"first\"}", + "\"Name\": \"replacement-comment.example.test\"," + + " \"HostedZoneConfig\": {\"Comment\": \"second\"}", + "False", false, null), SUBNET_GROUP_REPLACED, new Row("deployed parameter renamed, same value", locationStack(stringParameter("NameA", HOSTED), "", REF_A, "d"), diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDynamoDbGlobalTableIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDynamoDbGlobalTableIntegrationTest.java index 758bc8c000..605b05bb3e 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDynamoDbGlobalTableIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationDynamoDbGlobalTableIntegrationTest.java @@ -11,6 +11,7 @@ import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.List; +import static io.floci.aws.services.cloudformation.SsmParameterTestSupport.parameterValue; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -33,8 +34,6 @@ class CloudFormationDynamoDbGlobalTableIntegrationTest { "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; private static final String DDB_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/dynamodb/aws4_request"; - private static final String SSM_AUTH = - "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ssm/aws4_request"; private static final Duration STACK_DELETE_TIMEOUT = Duration.ofSeconds(30); private static final Duration STACK_DELETE_POLL_INTERVAL = Duration.ofMillis(50); @@ -156,14 +155,4 @@ class CloudFormationDynamoDbGlobalTableIntegrationTest { .body("Table.TableName", equalTo(tableName)) .extract().response(); } - - private String parameterValue(String name) { - return given() - .contentType("application/x-amz-json-1.1") - .header("Authorization", SSM_AUTH) - .header("X-Amz-Target", "AmazonSSM.GetParameter") - .body("{\"Name\":\"" + name + "\"}") - .when().post("/").then().statusCode(200) - .extract().jsonPath().getString("Parameter.Value"); - } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRoute53RecordSetIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRoute53RecordSetIntegrationTest.java index 04710a1066..41284d5048 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRoute53RecordSetIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationRoute53RecordSetIntegrationTest.java @@ -1,8 +1,10 @@ package io.floci.aws.services.cloudformation; import io.floci.aws.core.common.AwsException; +import io.floci.aws.services.cloudformation.provisioners.CfnRollback; import io.floci.aws.services.route53.Route53HostedZoneTestSupport; import io.floci.aws.services.route53.Route53Service; +import io.floci.aws.testing.AwsTestClients; import io.floci.aws.testing.CfnRequests; import io.floci.aws.testing.CfnStackWaits; import io.floci.aws.testing.RestAssuredJsonUtils; @@ -10,15 +12,23 @@ import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.mockito.InjectSpy; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; +import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.cloudformation.CloudFormationClient; +import software.amazon.awssdk.services.route53.Route53Client; +import software.amazon.awssdk.services.route53.model.RRType; import java.time.Duration; +import java.util.List; +import static io.floci.aws.services.cloudformation.SsmParameterTestSupport.parameterValue; +import static io.floci.aws.services.cloudformation.SsmParameterTestSupport.putParameter; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -40,8 +50,6 @@ class CloudFormationRoute53RecordSetIntegrationTest { private static final String CFN_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request"; - private static final String SSM_AUTH = - "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ssm/aws4_request"; private static final String ROUTE53_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/route53/aws4_request"; private static final Duration STACK_DELETE_TIMEOUT = Duration.ofSeconds(30); @@ -59,6 +67,9 @@ class CloudFormationRoute53RecordSetIntegrationTest { @InjectSpy Route53Service route53Service; + @Inject + CloudFormationService cloudFormationService; + @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); @@ -1209,13 +1220,151 @@ class CloudFormationRoute53RecordSetIntegrationTest { .when().post("/").then().statusCode(200); } - private String parameterValue(String name) { - return given() - .contentType("application/x-amz-json-1.1") - .header("Authorization", SSM_AUTH) - .header("X-Amz-Target", "AmazonSSM.GetParameter") - .body("{\"Name\":\"" + name + "\"}") - .when().post("/").then().statusCode(200) - .extract().jsonPath().getString("Parameter.Value"); + @Test + void aTtlChangeIsPutBackWhenALaterResourceFails() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "r53-record-rb-" + suffix; + String foreign = "/r53-record-rb/" + suffix + "/foreign"; + putParameter(foreign); + + createStack(stackName, recordRollbackTemplate(suffix, "300", null)); + CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE", CFN_AUTH); + try { + String zone = parameterValue("/r53-record-rb/" + suffix + "/zone"); + + updateStack(stackName, recordRollbackTemplate(suffix, "60", foreign)); + CfnStackWaits.awaitStatus(stackName, "UPDATE_ROLLBACK_COMPLETE", CFN_AUTH); + + String records = given().header("Authorization", ROUTE53_AUTH) + .when().get("/2013-04-01/hostedzone/" + zone + "/rrset") + .then().statusCode(200).extract().asString(); + assertTrue(records.contains("300") && !records.contains("60"), + "the record has the TTL it had before the update: " + records); + assertEquals(zone, parameterValue("/r53-record-rb/" + suffix + "/zone")); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + } + } + + @Test + void aCommittedUpdateLeavesNoRollbackSnapshotOnTheRecordSet() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "r53-record-commit-" + suffix; + + createStack(stackName, recordRollbackTemplate(suffix, "300", null)); + CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE", CFN_AUTH); + try { + updateStack(stackName, recordRollbackTemplate(suffix, "60", null)); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH); + + assertFalse(cloudFormationService.describeStacks(stackName, "us-east-1").get(0).getResources() + .get("Www").getAttributes().containsKey(CfnRollback.ROUTE53_RECORD_UPDATE_SNAPSHOT_ATTR)); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + } + } + + private static String recordRollbackTemplate(String suffix, String ttl, String failingParameter) { + String failing = failingParameter == null ? "" : """ + ,"Boom": {"Type": "AWS::SSM::Parameter", "DependsOn": "Www", + "Properties": {"Name": "%s", "Type": "String", "Value": "x"}}""".formatted(failingParameter); + return """ + {"Resources": { + "Zone": {"Type": "AWS::Route53::HostedZone", + "Properties": {"Name": "a.%1$s.cfn-it.example.com"}}, + "Www": {"Type": "AWS::Route53::RecordSet", + "Properties": {"HostedZoneId": {"Ref": "Zone"}, "Name": "www.a.%1$s.cfn-it.example.com", + "Type": "A", "TTL": "%2$s", "ResourceRecords": ["10.0.0.1"]}}, + "ZoneParam": {"Type": "AWS::SSM::Parameter", + "Properties": {"Name": "/r53-record-rb/%1$s/zone", "Type": "String", + "Value": {"Ref": "Zone"}}} + %3$s + }} + """.formatted(suffix, ttl, failing); + } + + @Test + void aReplacedZoneMovesItsRecordSetsAndTheOldZoneIsDeletedEmpty() { + String suffix = Long.toString(System.nanoTime(), 36); + String stackName = "r53-zone-repl-" + suffix; + String zoneParam = "/r53-zone-repl/" + suffix + "/zone"; + + createStack(stackName, zoneReplacementTemplate(suffix, "a")); + CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE", CFN_AUTH); + try { + String oldZone = parameterValue(zoneParam); + assertTrue(listResourceRecordSets(oldZone).contains("www.a." + suffix)); + + updateStack(stackName, zoneReplacementTemplate(suffix, "b")); + CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE", CFN_AUTH); + + String newZone = parameterValue(zoneParam); + assertNotEquals(oldZone, newZone, "a Name change replaces the zone"); + String moved = listResourceRecordSets(newZone); + assertTrue(moved.contains("www.b." + suffix), "the record set is in the new zone: " + moved); + assertEquals(404, given().header("Authorization", ROUTE53_AUTH) + .when().get("/2013-04-01/hostedzone/" + oldZone).statusCode(), + "the old zone was empty and is deleted"); + } finally { + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + } + } + + @Test + void aRenamedZoneThatRollsBackLeavesTheOldZoneWithItsRecordAndTheNewZoneGone() { + String suffix = Long.toString(System.nanoTime(), 36); + String stack = "repl-zone-rollback-" + suffix; + String before = "repl-rb-a-" + suffix + ".example.test"; + String after = "repl-rb-b-" + suffix + ".example.test"; + try (CloudFormationClient cfn = AwsTestClients.create(CloudFormationClient.builder(), "test", Region.US_EAST_1); + Route53Client route53 = AwsTestClients.create(Route53Client.builder(), "test", Region.US_EAST_1)) { + CfnStackWaits.createStack(cfn, stack, zoneRollbackTemplate(before, ""), "CREATE_COMPLETE"); + String oldZone = cfn.describeStackResource(request -> request.stackName(stack) + .logicalResourceId("Zone")).stackResourceDetail().physicalResourceId(); + + CfnStackWaits.updateStack(cfn, stack, zoneRollbackTemplate(after, CfnStackWaits.failingResourceAfter("Record")), + "UPDATE_ROLLBACK_COMPLETE"); + + String zoneNow = cfn.describeStackResource(request -> request.stackName(stack) + .logicalResourceId("Zone")).stackResourceDetail().physicalResourceId(); + assertEquals(oldZone, zoneNow, "the stack points at the old zone again"); + List records = route53.listResourceRecordSets(request -> request.hostedZoneId(oldZone)) + .resourceRecordSets().stream() + .filter(set -> set.type() == RRType.A).map(set -> set.name()).toList(); + assertEquals(List.of("www." + before + "."), records, "the old zone holds the old record"); + List zones = route53.listHostedZones().hostedZones().stream().map(zone -> zone.name()).toList(); + assertTrue(zones.contains(before + ".")); + assertFalse(zones.contains(after + "."), "the zone the update made is deleted"); + } finally { + CfnStackWaits.deleteStack(stack); + } + } + + private static String zoneReplacementTemplate(String suffix, String label) { + return """ + {"Resources": { + "Zone": {"Type": "AWS::Route53::HostedZone", + "Properties": {"Name": "%2$s.%1$s.cfn-it.example.com"}}, + "Www": {"Type": "AWS::Route53::RecordSet", + "Properties": {"HostedZoneId": {"Ref": "Zone"}, "Name": "www.%2$s.%1$s.cfn-it.example.com", + "Type": "A", "TTL": "300", "ResourceRecords": ["10.0.0.1"]}}, + "ZoneParam": {"Type": "AWS::SSM::Parameter", + "Properties": {"Name": "/r53-zone-repl/%1$s/zone", "Type": "String", + "Value": {"Ref": "Zone"}}} + }} + """.formatted(suffix, label); + } + + private static String zoneRollbackTemplate(String zoneName, String later) { + return """ + {"Resources": { + "Zone": {"Type": "AWS::Route53::HostedZone", "Properties": {"Name": "%1$s"}}, + "Record": {"Type": "AWS::Route53::RecordSet", "Properties": {"HostedZoneId": {"Ref": "Zone"}, + "Name": "www.%1$s", "Type": "A", "TTL": "300", "ResourceRecords": ["192.0.2.1"]}}%2$s + }} + """.formatted(zoneName, later); } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/SsmParameterTestSupport.java b/src/test/java/io/floci/aws/services/cloudformation/SsmParameterTestSupport.java new file mode 100644 index 0000000000..546c398aa7 --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/SsmParameterTestSupport.java @@ -0,0 +1,32 @@ +package io.floci.aws.services.cloudformation; + +import static io.restassured.RestAssured.given; + +/** + * What the CloudFormation integration tests share to write an SSM parameter and read back one a stack wrote. + */ +final class SsmParameterTestSupport { + + private static final String SSM_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ssm/aws4_request"; + + private SsmParameterTestSupport() { + } + + static void putParameter(String name) { + given().contentType("application/x-amz-json-1.1").header("Authorization", SSM_AUTH) + .header("X-Amz-Target", "AmazonSSM.PutParameter") + .body("{\"Name\":\"" + name + "\",\"Value\":\"foreign\",\"Type\":\"String\"}") + .when().post("/").then().statusCode(200); + } + + static String parameterValue(String name) { + return given() + .contentType("application/x-amz-json-1.1") + .header("Authorization", SSM_AUTH) + .header("X-Amz-Target", "AmazonSSM.GetParameter") + .body("{\"Name\":\"" + name + "\"}") + .when().post("/").then().statusCode(200) + .extract().jsonPath().getString("Parameter.Value"); + } +} diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/Route53CfnProvisionerTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/Route53CfnProvisionerTest.java index 25a3aedd94..9736d8d4dd 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/provisioners/Route53CfnProvisionerTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/Route53CfnProvisionerTest.java @@ -16,6 +16,7 @@ import io.floci.aws.services.route53.model.ResourceRecordSet; import io.floci.aws.services.route53.model.VpcAssociation; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.NullSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; @@ -135,6 +136,7 @@ class Route53CfnProvisionerTest { new Route53Service.CreateZoneResult(zone, null)); when(service.associateVpcWithHostedZone(eq("Z123456789"), argThat(sameVpc(secondVpc)), any())) .thenThrow(new RuntimeException("boom")); + doThrow(new AwsException("Throttling", "slow", 400)).when(service).deleteHostedZone("Z123456789"); ObjectMapper mapper = new ObjectMapper(); JsonNode props = mapper.createObjectNode().put("Name", "ssm.us-east-1.amazonaws.com"); @@ -150,13 +152,15 @@ class Route53CfnProvisionerTest { resource.setLogicalId("Zone"); resource.setResourceType("AWS::Route53::HostedZone"); - assertThrows(RuntimeException.class, + RuntimeException thrown = assertThrows(RuntimeException.class, () -> new Route53CfnProvisioner(service).provision(resource, props, context)); + assertEquals("boom", thrown.getMessage()); assertEquals("Z123456789", resource.getPhysicalId()); assertTrue("true".equals(resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR)), "a zone that was actually created must stay marked rollback-owned when a " - + "follow-up VPC association fails, so CREATE_FAILED cleanup still deletes it"); + + "follow-up VPC association fails and its own cleanup fails, so CREATE_FAILED " + + "cleanup still deletes it"); } private static ArgumentMatcher sameVpc(VpcAssociation expected) { @@ -1617,6 +1621,85 @@ class Route53CfnProvisionerTest { return engine; } + private static final String ZONE = "AWS::Route53::HostedZone"; + + private static CloudFormationTemplateEngine zoneEngine() { + CloudFormationTemplateEngine engine = recordEngine(); + when(engine.resolveNode(any())).thenAnswer(invocation -> invocation.getArgument(0)); + return engine; + } + + /** A zone the stack made from {@code oldProps}, then an update that applies {@code newProps}. */ + private StackResource updatedZone(Route53Service service, Route53CfnProvisioner owner, String oldProps, + String newProps) throws Exception { + HostedZone old = new HostedZone("ZOLD", "old.example.test.", "dns-stack/Zone", null, (VpcAssociation) null); + HostedZone created = new HostedZone("ZNEW", "new.example.test.", "dns-stack/Zone", null, + (VpcAssociation) null); + when(service.getHostedZone("ZOLD")).thenReturn(old); + when(service.getHostedZone("ZNEW")).thenReturn(created); + when(service.createHostedZone(any(), any(), any(), any())) + .thenReturn(new Route53Service.CreateZoneResult(created, null)); + when(service.getAssignedNameServers(any())).thenReturn(List.of("ns-1.example")); + StackResource resource = trackedZone(); + + owner.provision(resource, MAPPER.readTree(newProps), zoneUpdateContext(oldProps)); + return resource; + } + + @Test + void hostedZoneWithChangedNameIsReplacedAndTheOldZoneDeletedWhenTheUpdateCompletes() throws Exception { + Route53Service service = mock(Route53Service.class); + Route53CfnProvisioner owner = new Route53CfnProvisioner(service); + + StackResource resource = updatedZone(service, owner, "{\"Name\":\"old.example.test\"}", + "{\"Name\":\"new.example.test\"}"); + + verify(service).createHostedZone(eq("new.example.test"), any(), any(), any()); + assertEquals("ZNEW", resource.getPhysicalId()); + assertTrue(owner.hasReplacementUpdate(resource)); + assertEquals("ZOLD", owner.updateCleanupPhysicalId(resource)); + verify(service, never()).deleteHostedZone("ZOLD"); + + UpdateCleanupResult cleanup = owner.completeUpdate(resource); + + assertTrue(cleanup.applicable()); + assertTrue(cleanup.complete()); + verify(service).deleteHostedZone("ZOLD"); + } + + @Test + void hostedZoneReplacementThatRollsBackKeepsTheOldZoneAndPointsBackAtIt() throws Exception { + Route53Service service = mock(Route53Service.class); + Route53CfnProvisioner owner = new Route53CfnProvisioner(service); + StackResource resource = updatedZone(service, owner, "{\"Name\":\"old.example.test\"}", + "{\"Name\":\"new.example.test\"}"); + + assertTrue(owner.rollbackUpdate(resource)); + + assertEquals("ZOLD", resource.getPhysicalId()); + assertEquals("ZOLD", resource.getAttributes().get("Id")); + verify(service, never()).deleteHostedZone("ZOLD"); + verify(service).deleteHostedZone("ZNEW"); + } + + @Test + void hostedZoneWithChangedDelegationSetIsReplaced() throws Exception { + Route53Service service = mock(Route53Service.class); + Route53CfnProvisioner owner = new Route53CfnProvisioner(service); + HostedZone created = new HostedZone("ZNEW", "old.example.test.", "dns-stack/Zone", null, + (VpcAssociation) null); + when(service.createHostedZone(any(), any(), any(), any(), any())) + .thenReturn(new Route53Service.CreateZoneResult(created, null)); + + StackResource resource = updatedZone(service, owner, + "{\"Name\":\"old.example.test\",\"DelegationSetId\":\"N1\"}", + "{\"Name\":\"old.example.test\",\"DelegationSetId\":\"N2\"}"); + + verify(service).createHostedZone(eq("old.example.test"), any(), any(), any(), eq("N2")); + assertEquals("ZNEW", resource.getPhysicalId()); + assertTrue(owner.hasReplacementUpdate(resource)); + } + @Test void deletingAHostedZoneStillDeletesTheZone() { Route53Service service = mock(Route53Service.class); @@ -1625,4 +1708,215 @@ class Route53CfnProvisionerTest { verify(service).deleteHostedZone("Z123456789"); } + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static StackResource trackedZone() { + StackResource resource = new StackResource(); + resource.setLogicalId("Zone"); + resource.setResourceType(ZONE); + resource.setPhysicalId("ZOLD"); + resource.getAttributes().put("Id", "ZOLD"); + resource.getAttributes().put("NameServers", "ns-old"); + return resource; + } + + private static ProvisionContext zoneUpdateContext(String oldProps) throws Exception { + return new ProvisionContext(zoneEngine(), "us-east-1", "000000000000", "dns-stack", "ZOLD", event -> { }, + MAPPER.readTree(oldProps)); + } + + private static Route53Service serviceWithOldZone() { + Route53Service service = mock(Route53Service.class); + when(service.getHostedZone("ZOLD")).thenReturn( + new HostedZone("ZOLD", "old.example.test.", "dns-stack/Zone", null, (VpcAssociation) null)); + return service; + } + + @Test + void aReplacementWhoseCreateFailsStillPointsAtThePriorZone() throws Exception { + Route53Service service = serviceWithOldZone(); + doThrow(new AwsException("InvalidDomainName", "bad", 400)).when(service) + .createHostedZone(any(), any(), any(), any()); + StackResource resource = trackedZone(); + + assertThrows(AwsException.class, () -> new Route53CfnProvisioner(service).provision(resource, + MAPPER.readTree("{\"Name\":\"new.example.test\"}"), + zoneUpdateContext("{\"Name\":\"old.example.test\"}"))); + + assertEquals("ZOLD", resource.getPhysicalId()); + } + + @Test + void aReplacementWhoseTagWriteFailsPutsBackThePriorZoneAndItsAttributes() throws Exception { + Route53Service service = serviceWithOldZone(); + HostedZone created = new HostedZone("ZNEW", "new.example.test.", "caller", null, (VpcAssociation) null); + when(service.createHostedZone(any(), any(), any(), any())) + .thenReturn(new Route53Service.CreateZoneResult(created, null)); + when(service.getAssignedNameServers("ZNEW")).thenReturn(List.of("ns-new")); + doThrow(new AwsException("Throttling", "slow", 400)).when(service) + .changeTagsForResource(eq("hostedzone"), eq("ZNEW"), any(), any()); + StackResource resource = trackedZone(); + + assertThrows(AwsException.class, () -> new Route53CfnProvisioner(service).provision(resource, + MAPPER.readTree("{\"Name\":\"new.example.test\",\"HostedZoneTags\":[{\"Key\":\"k\",\"Value\":\"v\"}]}"), + zoneUpdateContext("{\"Name\":\"old.example.test\"}"))); + + verify(service).deleteHostedZone("ZNEW"); + assertEquals("ZOLD", resource.getPhysicalId()); + assertEquals("ZOLD", resource.getAttributes().get("Id")); + assertEquals("ns-old", resource.getAttributes().get("NameServers")); + } + + @Test + void aReplacementWhoseNameServerLookupFailsDeletesTheNewZoneAndPutsBackThePriorOne() throws Exception { + Route53Service service = serviceWithOldZone(); + HostedZone created = new HostedZone("ZNEW", "new.example.test.", "caller", null, (VpcAssociation) null); + when(service.createHostedZone(any(), any(), any(), any())) + .thenReturn(new Route53Service.CreateZoneResult(created, null)); + when(service.getAssignedNameServers("ZNEW")).thenThrow(new AwsException("NoSuchHostedZone", "gone", 404)); + StackResource resource = trackedZone(); + + assertThrows(AwsException.class, () -> new Route53CfnProvisioner(service).provision(resource, + MAPPER.readTree("{\"Name\":\"new.example.test\"}"), + zoneUpdateContext("{\"Name\":\"old.example.test\"}"))); + + verify(service).deleteHostedZone("ZNEW"); + verify(service, never()).deleteHostedZone("ZOLD"); + assertEquals("ZOLD", resource.getPhysicalId()); + assertEquals("ZOLD", resource.getAttributes().get("Id")); + assertEquals("ns-old", resource.getAttributes().get("NameServers")); + assertEquals("true", resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR)); + } + + @Test + void aBlankDelegationSetIdIsNoDelegationSet() throws Exception { + Route53Service service = serviceWithOldZone(); + HostedZone created = new HostedZone("ZNEW", "new.example.test.", "caller", null, (VpcAssociation) null); + when(service.createHostedZone(any(), any(), any(), any())) + .thenReturn(new Route53Service.CreateZoneResult(created, null)); + when(service.getAssignedNameServers(any())).thenReturn(List.of("ns")); + + new Route53CfnProvisioner(service).provision(trackedZone(), + MAPPER.readTree("{\"Name\":\"new.example.test\",\"DelegationSetId\":\"\"}"), + zoneUpdateContext("{\"Name\":\"old.example.test\"}")); + + verify(service).createHostedZone(eq("new.example.test"), any(), any(), any()); + verify(service, never()).createHostedZone(any(), any(), any(), any(), any()); + } + + private static StackResource trackedRecord(String name, String zoneId) { + StackResource resource = new StackResource(); + resource.setLogicalId("Www"); + resource.setResourceType("AWS::Route53::RecordSet"); + resource.setPhysicalId(name); + resource.getAttributes().put("__FlociRoute53RecordZoneId", zoneId); + resource.getAttributes().put("__FlociRoute53RecordType", "A"); + return resource; + } + + private static ResourceRecordSet listedRecord(String name) { + ResourceRecordSet record = new ResourceRecordSet(); + record.setName(name); + record.setType("A"); + record.setTtl(300L); + return record; + } + + private static ProvisionContext recordUpdateContext(String priorName) { + return new ProvisionContext(zoneEngine(), "us-east-1", "000000000000", "dns-stack", priorName); + } + + private static JsonNode recordProps(String zoneId, String name) { + return MAPPER.createObjectNode().put("HostedZoneId", zoneId).put("Name", name).put("Type", "A"); + } + + private static Route53Service serviceWithAuthAndLoginRecords() { + Route53Service service = mock(Route53Service.class); + when(service.listResourceRecordSets("Z1", null, null, 0)).thenReturn( + List.of(listedRecord("auth.example.com."), listedRecord("login.example.com."))); + when(service.listResourceRecordSets("Z2", null, null, 0)).thenReturn( + List.of(listedRecord("login.example.com."))); + return service; + } + + @Test + void aFailedSupersedeRemovesTheRecordTheAttemptWrote() { + Route53Service service = serviceWithAuthAndLoginRecords(); + doThrow(new AwsException("Throttling", "slow", 400)).when(service).changeResourceRecordSets(eq("Z1"), + argThat(changes -> changes != null && "DELETE".equals(changes.get(0).get("action")) + && ((ResourceRecordSet) changes.get(0).get("rrs")).getName().startsWith("auth")), any()); + + assertThrows(AwsException.class, () -> new Route53CfnProvisioner(service).provision( + trackedRecord("auth.example.com", "Z1"), recordProps("Z1", "login.example.com"), + recordUpdateContext("auth.example.com"))); + + verify(service).changeResourceRecordSets(eq("Z1"), argThat(changes -> changes != null + && "DELETE".equals(changes.get(0).get("action")) + && ((ResourceRecordSet) changes.get(0).get("rrs")).getName().startsWith("login")), any()); + } + + /** + * The update wrote {@code writtenName} in {@code writtenZone}, displacing {@code auth.example.com} in Z1. + * The rollback restores the displaced record in the calls the rule names: one UPSERT when both share an + * identity, one batch of DELETE then UPSERT in the same zone otherwise, and across zones the UPSERT in + * the displaced record's zone before the DELETE in the written one. + */ + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "Z1|auth.example.com|Z1 UPSERT auth.example.com.", + "Z1|login.example.com|Z1 DELETE login.example.com.,UPSERT auth.example.com.", + "Z2|login.example.com|Z1 UPSERT auth.example.com.;Z2 DELETE login.example.com."}) + void aRollbackRestoresTheDisplacedRecordInTheCallsTheRuleNames(String writtenZone, String writtenName, + String expectedCalls) { + Route53Service service = serviceWithAuthAndLoginRecords(); + Route53CfnProvisioner owner = new Route53CfnProvisioner(service); + StackResource resource = trackedRecord("auth.example.com", "Z1"); + owner.provision(resource, recordProps(writtenZone, writtenName), recordUpdateContext("auth.example.com")); + Mockito.clearInvocations(service); + + assertTrue(owner.rollbackUpdate(resource)); + + assertEquals("auth.example.com", resource.getPhysicalId()); + assertEquals("Z1", resource.getAttributes().get("__FlociRoute53RecordZoneId")); + @SuppressWarnings("unchecked") + ArgumentCaptor>> changes = ArgumentCaptor.forClass(List.class); + ArgumentCaptor zones = ArgumentCaptor.forClass(String.class); + verify(service, times(expectedCalls.split(";").length)) + .changeResourceRecordSets(zones.capture(), changes.capture(), any()); + List calls = new ArrayList<>(); + for (int i = 0; i < zones.getAllValues().size(); i++) { + calls.add(zones.getAllValues().get(i) + " " + String.join(",", describe(changes.getAllValues().get(i)))); + } + assertEquals(expectedCalls, String.join(";", calls)); + } + + @Test + void aRefusedDeleteFailsTheRollbackInsteadOfPassing() { + Route53Service service = serviceWithAuthAndLoginRecords(); + Route53CfnProvisioner owner = new Route53CfnProvisioner(service); + StackResource resource = trackedRecord("auth.example.com", "Z1"); + owner.provision(resource, recordProps("Z1", "login.example.com"), recordUpdateContext("auth.example.com")); + doThrow(new AwsException("InvalidChangeBatch", "changed outside", 400)).when(service) + .changeResourceRecordSets(eq("Z1"), argThat(changes -> changes != null + && "DELETE".equals(changes.get(0).get("action"))), any()); + + assertThrows(AwsException.class, () -> owner.rollbackUpdate(resource)); + } + + @Test + void aRollbackThatCannotRestoreTheDisplacedRecordIsNotReportedAsDone() { + Route53Service service = mock(Route53Service.class); + // The prior record is not in its zone when the update starts: nothing to restore. + when(service.listResourceRecordSets("Z1", null, null, 0)).thenReturn(List.of(listedRecord("login.example.com."))); + Route53CfnProvisioner owner = new Route53CfnProvisioner(service); + StackResource resource = trackedRecord("auth.example.com", "Z1"); + owner.provision(resource, recordProps("Z1", "login.example.com"), recordUpdateContext("auth.example.com")); + + assertFalse(owner.rollbackUpdate(resource)); + + verify(service, never()).changeResourceRecordSets(eq("Z1"), argThat(changes -> changes != null + && "DELETE".equals(changes.get(0).get("action")) + && ((ResourceRecordSet) changes.get(0).get("rrs")).getName().startsWith("login")), any()); + } } diff --git a/src/test/resources/cloudformation/writable-property-gaps.tsv b/src/test/resources/cloudformation/writable-property-gaps.tsv index 852366e119..c2e17518a5 100644 --- a/src/test/resources/cloudformation/writable-property-gaps.tsv +++ b/src/test/resources/cloudformation/writable-property-gaps.tsv @@ -596,7 +596,6 @@ AWS::RedshiftServerless::Workgroup SnapshotArn documented as ignored (docs/servi AWS::RedshiftServerless::Workgroup SnapshotName documented as ignored (docs/services/cloudformation.md, Redshift Serverless) AWS::RedshiftServerless::Workgroup SnapshotOwnerAccount documented as ignored (docs/services/cloudformation.md, Redshift Serverless) AWS::RedshiftServerless::Workgroup Workgroup accepted and ignored -AWS::Route53::HostedZone DelegationSetId accepted and ignored AWS::Route53::HostedZone HostedZoneFeatures accepted and ignored AWS::Route53::HostedZone QueryLoggingConfig accepted and ignored AWS::Route53::RecordSet CidrRoutingConfig accepted and ignored