feat(cloudformation): support AWS::Route53::RecordSetGroup (#6676)

A RecordSetGroup writes all its record sets into one hosted zone in a
single ChangeResourceRecordSets batch, so a record set that cannot be
written, such as a name another owner already holds, leaves the zone
unchanged and fails the stack. Each record set keeps what a RecordSet
keeps, including the routing-policy fields SetIdentifier, Weight,
Region, Failover and HealthCheckId; entries an Fn::If resolves to
AWS::NoValue are dropped, and two record sets with one name, type and
set identifier are refused. Ref returns the group's logical ID and
Fn::GetAtt Id the change ID that GetChange reads, as AWS documents.

The zone comes from the group's HostedZoneId or HostedZoneName, or from
its record sets when the group names neither. A record set that repeats
the group's HostedZoneId is refused, as AWS documents, and so is one
that names another zone.

An update in the same zone deletes the records the group wrote and
creates the new ones in one batch. HostedZoneId and HostedZoneName are
create-only, so a change set reports a zone change as a replacement:
the records are written into the new zone, and the old ones are deleted
once the update commits, or kept under UpdateReplacePolicy: Retain. A
failed update puts back the records the group had; after a zone change
the group first points at its old records again, then deletes the new
zone's. If that delete fails, ContinueUpdateRollback retries it and
DeleteStack deletes those records while the rollback is unfinished;
anything else leaves them in their zone, since Route 53 cannot tell
them apart from an identical record another writer puts there later.
Deletes name the values the group wrote, so a record changed outside
the stack fails the delete rather than being removed.

The docs say what a record set group's failed rollback leaves behind.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-26 17:10:49 -04:00
1 parent 4d0dfe9919
commit f3f8b42200
8 files changed
+1666 -72

No files matched your search

@@ -85,6 +85,15 @@ class CfnCreateOnlyPropertiesTest {
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "LoggingFilter"));
}
@Test
void isCreateOnly_recordSetGroupReplacesOnlyForItsHostedZone() {
String type = "AWS::Route53::RecordSetGroup";
assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "HostedZoneId"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly(type, "HostedZoneName"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "RecordSets"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly(type, "Comment"));
}
@Test
void isCreateOnly_treatsEmptySchemaListAsAuthoritative() {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::ApiGateway::RestApi", "Name"));
@@ -1,11 +1,18 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.route53.Route53Service;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mockito;
import java.time.Duration;
@@ -15,6 +22,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
/**
* {@code AWS::Route53::RecordSet} through the per-service provisioner: {@code Ref} is the record
@@ -34,6 +43,18 @@ class CloudFormationRoute53RecordSetIntegrationTest {
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/route53/aws4_request";
private static final Duration STACK_DELETE_TIMEOUT = Duration.ofSeconds(30);
private static final Duration STACK_DELETE_POLL_INTERVAL = Duration.ofMillis(50);
/** A record set in a zone that does not exist, created after the group, so it fails the update. */
private static final String FAILS_AFTER_GROUP = """
,
"Broken": {
"Type": "AWS::Route53::RecordSet",
"DependsOn": "Group",
"Properties": {"HostedZoneId": "ZNOSUCHZONE00", "Name": "x.example.test.", "Type": "A",
"TTL": "60", "ResourceRecords": ["10.0.0.1"]}
}""";
@InjectSpy
Route53Service route53Service;
@BeforeAll
static void configureRestAssured() {
@@ -447,6 +468,582 @@ class CloudFormationRoute53RecordSetIntegrationTest {
}
}
@Test
void recordGroupCreatesUpdatesAndDeletesItsRecordsUnderAStableRef() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String zoneId = createHostedZone(zoneName, "cfn-group-" + suffix);
String unmanaged = "unmanaged." + zoneName;
changeRecordSet(zoneId, "CREATE", unmanaged, "192.0.2.9");
createStack(stackName, groupTemplate(zoneId,
groupRecord("first." + zoneName, "192.0.2.1") + "," + groupRecord("second." + zoneName, "192.0.2.2")));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
String firstChange;
try {
// AWS documents Ref as the group's name, for example MyRecordSetGroup, and Fn::GetAtt Id as
// the ID GetChange takes.
assertEquals("Group", stackOutput(stackName, "GroupRef"));
assertEquals("Group", physicalId(stackName, "Group"));
firstChange = stackOutput(stackName, "GroupChange");
assertChangeInSync(firstChange);
String created = listResourceRecordSets(zoneId);
assertTrue(created.contains("<Name>first." + zoneName + ".</Name>"), created);
assertTrue(created.contains("<Name>second." + zoneName + ".</Name>"), created);
updateStack(stackName, groupTemplate(zoneId,
groupRecord("first." + zoneName, "192.0.2.3") + ","
+ groupRecord("third." + zoneName, "192.0.2.4")));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertEquals("Group", stackOutput(stackName, "GroupRef"));
String secondChange = stackOutput(stackName, "GroupChange");
assertNotEquals(firstChange, secondChange);
assertChangeInSync(secondChange);
String updated = listResourceRecordSets(zoneId);
assertTrue(updated.contains("192.0.2.3"), updated);
assertFalse(updated.contains("192.0.2.1"), updated);
assertTrue(updated.contains("<Name>third." + zoneName + ".</Name>"), updated);
assertFalse(updated.contains("second." + zoneName), updated);
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
String deleted = listResourceRecordSets(zoneId);
assertFalse(deleted.contains("first." + zoneName), deleted);
assertFalse(deleted.contains("third." + zoneName), deleted);
assertTrue(deleted.contains("192.0.2.9"), "a record the stack never wrote was deleted: " + deleted);
changeRecordSet(zoneId, "DELETE", unmanaged, "192.0.2.9");
deleteHostedZone(zoneId);
}
@Test
void recordGroupKeepsTheRoutingPolicyOfEachRecordSet() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-routing-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.test";
String zoneId = createHostedZone(zoneName, "cfn-group-routing-" + suffix);
String template = """
{
"Parameters": {"BlueWeight": {"Type": "Number"}},
"Resources": {
"Check": {
"Type": "AWS::Route53::HealthCheck",
"Properties": {"HealthCheckConfig": {"Type": "TCP", "IPAddress": "10.0.0.5", "Port": 22}}
},
"Group": {
"Type": "AWS::Route53::RecordSetGroup",
"Properties": {
"HostedZoneName": "%1$s.",
"RecordSets": [
{"Name": "api.%1$s.", "Type": "A", "TTL": "60", "SetIdentifier": "blue",
"Weight": {"Ref": "BlueWeight"}, "HealthCheckId": {"Ref": "Check"},
"ResourceRecords": ["10.0.0.7"]},
{"Name": "api.%1$s.", "Type": "A", "TTL": "60", "SetIdentifier": "green",
"Weight": 30, "ResourceRecords": ["10.0.0.8"]}
]
}
}
}
}
""".formatted(zoneName);
parameterizedStackRequest(stackName, "CreateStack", template, "BlueWeight", "70");
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
try {
String checkId = physicalId(stackName, "Check");
String created = listResourceRecordSets(zoneId);
assertTrue(created.contains("<SetIdentifier>blue</SetIdentifier><Weight>70</Weight>"), created);
assertTrue(created.contains("<SetIdentifier>green</SetIdentifier><Weight>30</Weight>"), created);
assertTrue(created.contains("<HealthCheckId>" + checkId + "</HealthCheckId>"), created);
// The update's DELETE of each record the group wrote must name it exactly, routing
// policy included, or Route 53 refuses the whole batch.
parameterizedStackRequest(stackName, "UpdateStack", template, "BlueWeight", "60");
CfnStackWaits.StackState updated = CfnStackWaits.awaitTerminal(stackName);
assertEquals("UPDATE_COMPLETE", updated.status(), updated.reason());
String records = listResourceRecordSets(zoneId);
assertTrue(records.contains("<SetIdentifier>blue</SetIdentifier><Weight>60</Weight>"), records);
assertFalse(records.contains("<Weight>70</Weight>"), records);
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
String deleted = listResourceRecordSets(zoneId);
assertFalse(deleted.contains("api." + zoneName), deleted);
deleteHostedZone(zoneId);
}
@Test
void recordGroupZoneChangeIsAReplacementThatMovesItsRecords() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-move-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String oldZone = createHostedZone(zoneName, "cfn-group-move-old-" + suffix);
String newZone = createHostedZone(zoneName, "cfn-group-move-new-" + suffix);
String name = "www." + zoneName;
createStack(stackName, groupTemplate(oldZone, groupRecord(name, "192.0.2.1")));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
try {
// HostedZoneId is create-only in the registry schema, so the change set reports the move as
// a replacement.
changeSetRequest("CreateChangeSet", stackName, "move")
.formParam("ChangeSetType", "UPDATE")
.formParam("TemplateBody", groupTemplate(newZone, groupRecord(name, "192.0.2.2")))
.when().post("/").then().statusCode(200);
changeSetRequest("DescribeChangeSet", stackName, "move")
.when().post("/").then().statusCode(200)
.body(containsString("<Replacement>True</Replacement>"));
changeSetRequest("ExecuteChangeSet", stackName, "move")
.when().post("/").then().statusCode(200);
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertFalse(listResourceRecordSets(oldZone).contains(name), "old zone kept the record");
assertTrue(listResourceRecordSets(newZone).contains("192.0.2.2"), "new zone lacks the record");
assertEquals("Group", stackOutput(stackName, "GroupRef"));
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
assertFalse(listResourceRecordSets(newZone).contains(name));
deleteHostedZone(oldZone);
deleteHostedZone(newZone);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void recordGroupIsPutBackWhenALaterResourceFailsTheUpdate(boolean moveZone) {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-rollback-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String oldZone = createHostedZone(zoneName, "cfn-group-rollback-old-" + suffix);
String targetZone = moveZone ? createHostedZone(zoneName, "cfn-group-rollback-new-" + suffix) : oldZone;
String name = "www." + zoneName;
createStack(stackName, groupTemplate(oldZone, groupRecord(name, "192.0.2.1")));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
String change = stackOutput(stackName, "GroupChange");
try {
updateStack(stackName, groupTemplate(targetZone, groupRecord(name, "192.0.2.2"), "", FAILS_AFTER_GROUP));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
String restored = listResourceRecordSets(oldZone);
assertTrue(restored.contains("192.0.2.1"), restored);
assertFalse(restored.contains("192.0.2.2"), restored);
if (moveZone) {
assertFalse(listResourceRecordSets(targetZone).contains(name), "the moved record was left behind");
}
assertEquals(change, stackOutput(stackName, "GroupChange"));
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
assertFalse(listResourceRecordSets(oldZone).contains(name), "the restored record outlived the stack");
deleteHostedZone(oldZone);
if (moveZone) {
deleteHostedZone(targetZone);
}
}
@Test
void retainedRecordGroupLeavesItsOldRecordsWhenItMovesZone() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-retain-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String oldZone = createHostedZone(zoneName, "cfn-group-retain-old-" + suffix);
String newZone = createHostedZone(zoneName, "cfn-group-retain-new-" + suffix);
String name = "www." + zoneName;
String retain = ", \"UpdateReplacePolicy\": \"Retain\"";
createStack(stackName, groupTemplate(oldZone, groupRecord(name, "192.0.2.1"), retain, ""));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
try {
updateStack(stackName, groupTemplate(newZone, groupRecord(name, "192.0.2.2"), retain, ""));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertTrue(listResourceRecordSets(oldZone).contains("192.0.2.1"), "the retained record was deleted");
assertTrue(listResourceRecordSets(newZone).contains("192.0.2.2"), "new zone lacks the record");
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
assertFalse(listResourceRecordSets(newZone).contains(name));
assertTrue(listResourceRecordSets(oldZone).contains("192.0.2.1"), "the stack delete took the retained record");
changeRecordSet(oldZone, "DELETE", name, "192.0.2.1");
deleteHostedZone(oldZone);
deleteHostedZone(newZone);
}
@Test
void recordGroupMoveGivesUpOnAnOldRecordChangedOutsideTheStack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-drift-move-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String oldZone = createHostedZone(zoneName, "cfn-group-drift-old-" + suffix);
String newZone = createHostedZone(zoneName, "cfn-group-drift-new-" + suffix);
String name = "www." + zoneName;
createStack(stackName, groupTemplate(oldZone, groupRecord(name, "192.0.2.1")));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
changeRecordSet(oldZone, "UPSERT", name, "192.0.2.9");
try {
// The cleanup's DELETE names the values the group wrote, so Route 53 refuses it; as for any
// other replaced resource, the update still completes and says what it could not delete.
updateStack(stackName, groupTemplate(newZone, groupRecord(name, "192.0.2.2")));
CfnStackWaits.StackState moved = CfnStackWaits.awaitTerminal(stackName);
assertEquals("UPDATE_COMPLETE", moved.status(), moved.reason());
assertTrue(moved.reason().contains("could not be deleted during update cleanup"), moved.reason());
assertTrue(listResourceRecordSets(oldZone).contains("192.0.2.9"), "the changed record was deleted");
assertTrue(listResourceRecordSets(newZone).contains("192.0.2.2"), "new zone lacks the record");
// The given-up record no longer holds the group back.
updateStack(stackName, groupTemplate(newZone, groupRecord(name, "192.0.2.3")));
CfnStackWaits.StackState next = CfnStackWaits.awaitTerminal(stackName);
assertEquals("UPDATE_COMPLETE", next.status(), next.reason());
assertTrue(listResourceRecordSets(newZone).contains("192.0.2.3"));
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
assertFalse(listResourceRecordSets(newZone).contains(name));
assertTrue(listResourceRecordSets(oldZone).contains("192.0.2.9"), "the stack delete took the changed record");
changeRecordSet(oldZone, "DELETE", name, "192.0.2.9");
deleteHostedZone(oldZone);
deleteHostedZone(newZone);
}
@Test
void recordGroupThatCollidesWritesNothingAndLeavesTheOtherOwnersRecord() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-taken-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String zoneId = createHostedZone(zoneName, "cfn-group-taken-" + suffix);
String taken = "taken." + zoneName;
changeRecordSet(zoneId, "CREATE", taken, "192.0.2.9");
try {
createStack(stackName, groupTemplate(zoneId,
groupRecord("new." + zoneName, "192.0.2.1") + "," + groupRecord(taken, "192.0.2.2")));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
assertEquals("ROLLBACK_COMPLETE", state.status(), state.reason());
String failure = CfnStackWaits.failedResourceReason(stackName);
assertTrue(failure.contains("already exists"), failure);
String records = listResourceRecordSets(zoneId);
assertFalse(records.contains("new." + zoneName), "a partial group was written: " + records);
assertTrue(records.contains("192.0.2.9"), records);
assertFalse(records.contains("192.0.2.2"), records);
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
changeRecordSet(zoneId, "DELETE", taken, "192.0.2.9");
deleteHostedZone(zoneId);
}
@Test
void recordGroupDeleteFailsOnARecordChangedOutsideTheStackUntilItIsPutBack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-drift-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String zoneId = createHostedZone(zoneName, "cfn-group-drift-" + suffix);
String name = "www." + zoneName;
createStack(stackName, groupTemplate(zoneId, groupRecord(name, "192.0.2.1")));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
changeRecordSet(zoneId, "UPSERT", name, "192.0.2.2");
// As on AWS, the DELETE names the values the stack wrote, so a changed record fails it.
deleteStack(stackName);
CfnStackWaits.StackState failed = CfnStackWaits.awaitTerminal(stackName);
assertEquals("DELETE_FAILED", failed.status(), failed.reason());
assertTrue(listResourceRecordSets(zoneId).contains("192.0.2.2"), "the changed record was deleted");
changeRecordSet(zoneId, "UPSERT", name, "192.0.2.1");
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
assertFalse(listResourceRecordSets(zoneId).contains(name));
deleteHostedZone(zoneId);
}
@Test
void recordGroupMoveWhoseRollbackCannotDeleteTheNewRecordsIsFinishedByContinueUpdateRollback() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-retry-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String oldZone = createHostedZone(zoneName, "cfn-group-retry-old-" + suffix);
String newZone = createHostedZone(zoneName, "cfn-group-retry-new-" + suffix);
String name = "www." + zoneName;
createStack(stackName, groupTemplate(oldZone, groupRecord(name, "192.0.2.1")));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
try {
refuseFirstGroupDeleteIn(newZone);
updateStack(stackName, groupTemplate(newZone, groupRecord(name, "192.0.2.2"), "", FAILS_AFTER_GROUP));
assertEquals("UPDATE_ROLLBACK_FAILED", CfnStackWaits.awaitTerminal(stackName).status());
assertTrue(listResourceRecordSets(oldZone).contains("192.0.2.1"), "the old record was touched");
assertTrue(listResourceRecordSets(newZone).contains("192.0.2.2"), "the refused delete went through");
continueUpdateRollback(stackName);
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
assertEquals("UPDATE_ROLLBACK_COMPLETE", state.status(), state.reason());
assertFalse(listResourceRecordSets(newZone).contains(name), "the retry left the moved record");
assertTrue(listResourceRecordSets(oldZone).contains("192.0.2.1"), "the retry touched the old record");
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
assertFalse(listResourceRecordSets(oldZone).contains(name));
deleteHostedZone(oldZone);
deleteHostedZone(newZone);
}
@Test
void skippingAFailedRecordGroupRollbackKeepsTheOldRecordsAndLeavesTheNewOnesInTheirZone() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-skip-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String oldZone = createHostedZone(zoneName, "cfn-group-skip-old-" + suffix);
String newZone = createHostedZone(zoneName, "cfn-group-skip-new-" + suffix);
String name = "www." + zoneName;
String taken = "taken." + zoneName;
String restoredTemplate = groupTemplate(oldZone, groupRecord(name, "192.0.2.1"));
createStack(stackName, restoredTemplate);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
changeRecordSet(oldZone, "CREATE", taken, "192.0.2.9");
try {
refuseFirstGroupDeleteIn(newZone);
updateStack(stackName, groupTemplate(newZone, groupRecord(name, "192.0.2.2"), "", FAILS_AFTER_GROUP));
assertEquals("UPDATE_ROLLBACK_FAILED", CfnStackWaits.awaitTerminal(stackName).status());
continueUpdateRollback(stackName, "Group");
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
// The skipped group names the old zone's record again, as the restored template does, so
// an update of it that fails puts that record back rather than deleting it.
updateStack(stackName, groupTemplate(oldZone,
groupRecord(name, "192.0.2.1") + "," + groupRecord(taken, "192.0.2.3")));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertTrue(listResourceRecordSets(oldZone).contains("192.0.2.1"), "the old record was deleted");
// An update that leaves the group alone commits. As on AWS, the record the skipped rollback
// could not delete stays where it is: nothing tells it apart from one written there later.
updateStack(stackName, restoredTemplate.replace("\"Resources\": {", """
"Resources": {
"Marker": {"Type": "AWS::SSM::Parameter",
"Properties": {"Name": "/r53-group-skip/%s", "Type": "String", "Value": "kept"}},
""".formatted(suffix)));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
assertEquals("UPDATE_COMPLETE", state.status(), state.reason());
assertTrue(listResourceRecordSets(oldZone).contains("192.0.2.1"), "the old record was deleted");
assertTrue(listResourceRecordSets(newZone).contains("192.0.2.2"), "the skipped leftover was deleted");
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
assertFalse(listResourceRecordSets(oldZone).contains(name));
assertTrue(listResourceRecordSets(newZone).contains("192.0.2.2"), "the stack delete took the skipped leftover");
changeRecordSet(newZone, "DELETE", name, "192.0.2.2");
changeRecordSet(oldZone, "DELETE", taken, "192.0.2.9");
deleteHostedZone(oldZone);
deleteHostedZone(newZone);
}
@Test
void reApplyingAMoveAfterASkippedRollbackKeepsTheRecordsItWrites() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-reapply-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String oldZone = createHostedZone(zoneName, "cfn-group-reapply-old-" + suffix);
String newZone = createHostedZone(zoneName, "cfn-group-reapply-new-" + suffix);
String name = "www." + zoneName;
createStack(stackName, groupTemplate(oldZone, groupRecord(name, "192.0.2.1")));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
try {
refuseFirstGroupDeleteIn(newZone);
updateStack(stackName, groupTemplate(newZone, groupRecord(name, "192.0.2.2"), "", FAILS_AFTER_GROUP));
assertEquals("UPDATE_ROLLBACK_FAILED", CfnStackWaits.awaitTerminal(stackName).status());
continueUpdateRollback(stackName, "Group");
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
// The record the failed update left is deleted by hand, and the move is applied again.
changeRecordSet(newZone, "DELETE", name, "192.0.2.2");
updateStack(stackName, groupTemplate(newZone, groupRecord(name, "192.0.2.2")));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
assertEquals("UPDATE_COMPLETE", state.status(), state.reason());
assertTrue(listResourceRecordSets(newZone).contains("192.0.2.2"), "the cleanup deleted the moved record");
assertFalse(listResourceRecordSets(oldZone).contains(name), "the old record was left behind");
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
assertFalse(listResourceRecordSets(newZone).contains(name));
deleteHostedZone(oldZone);
deleteHostedZone(newZone);
}
@Test
void aRecordSetThatRewritesWhatASkippedGroupRollbackLeftKeepsIt() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-sibling-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String oldZone = createHostedZone(zoneName, "cfn-group-sibling-old-" + suffix);
String newZone = createHostedZone(zoneName, "cfn-group-sibling-new-" + suffix);
String name = "www." + zoneName;
String restoredTemplate = groupTemplate(oldZone, groupRecord(name, "192.0.2.1"));
createStack(stackName, restoredTemplate);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
try {
refuseFirstGroupDeleteIn(newZone);
updateStack(stackName, groupTemplate(newZone, groupRecord(name, "192.0.2.2"), "", FAILS_AFTER_GROUP));
assertEquals("UPDATE_ROLLBACK_FAILED", CfnStackWaits.awaitTerminal(stackName).status());
continueUpdateRollback(stackName, "Group");
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
// The leftover is deleted by hand, and a record set of the same stack writes the same record.
changeRecordSet(newZone, "DELETE", name, "192.0.2.2");
updateStack(stackName, restoredTemplate.replace("\"Resources\": {", """
"Resources": {
"Sibling": {"Type": "AWS::Route53::RecordSet",
"Properties": {"HostedZoneId": "%s", "Name": "%s", "Type": "A", "TTL": "300",
"ResourceRecords": ["192.0.2.2"]}},
""".formatted(newZone, name)));
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
assertEquals("UPDATE_COMPLETE", state.status(), state.reason());
assertTrue(listResourceRecordSets(newZone).contains("192.0.2.2"),
"the group's cleanup deleted the record set's record");
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
assertFalse(listResourceRecordSets(newZone).contains(name));
assertFalse(listResourceRecordSets(oldZone).contains(name));
deleteHostedZone(oldZone);
deleteHostedZone(newZone);
}
@Test
void deletingAStackWhoseRecordGroupMoveRollbackFailedDeletesBothZonesRecordsEvenUnderRetain() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-group-failed-delete-" + suffix;
String zoneName = suffix + ".cfn-group-it.example.com";
String oldZone = createHostedZone(zoneName, "cfn-group-failed-delete-old-" + suffix);
String newZone = createHostedZone(zoneName, "cfn-group-failed-delete-new-" + suffix);
String name = "www." + zoneName;
String retain = ", \"UpdateReplacePolicy\": \"Retain\"";
createStack(stackName, groupTemplate(oldZone, groupRecord(name, "192.0.2.1"), retain, ""));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
refuseFirstGroupDeleteIn(newZone);
updateStack(stackName, groupTemplate(newZone, groupRecord(name, "192.0.2.2"), retain, FAILS_AFTER_GROUP));
assertEquals("UPDATE_ROLLBACK_FAILED", CfnStackWaits.awaitTerminal(stackName).status());
assertTrue(listResourceRecordSets(oldZone).contains("192.0.2.1"), "the old record was touched");
assertTrue(listResourceRecordSets(newZone).contains("192.0.2.2"), "the refused delete went through");
// Retain keeps what a committed replacement displaced; this move never committed.
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
assertFalse(listResourceRecordSets(oldZone).contains(name), "the group's own record outlived the stack");
assertFalse(listResourceRecordSets(newZone).contains(name), "the failed update's record outlived the stack");
deleteHostedZone(oldZone);
deleteHostedZone(newZone);
}
private static String groupRecord(String name, String address) {
return """
{"Name": "%s", "Type": "A", "TTL": "300", "ResourceRecords": ["%s"]}""".formatted(name, address);
}
private static String groupTemplate(String zoneId, String recordSets) {
return groupTemplate(zoneId, recordSets, "", "");
}
/**
* One record group in {@code zoneId}, with outputs for its {@code Ref} and {@code Fn::GetAtt Id}.
* {@code policy} is added to the group's definition and {@code extra} after it, each led by a
* comma.
*/
private static String groupTemplate(String zoneId, String recordSets, String policy, String extra) {
return """
{
"Resources": {
"Group": {
"Type": "AWS::Route53::RecordSetGroup"%s,
"Properties": {"HostedZoneId": "%s", "RecordSets": [%s]}
}%s
},
"Outputs": {
"GroupRef": {"Value": {"Ref": "Group"}},
"GroupChange": {"Value": {"Fn::GetAtt": ["Group", "Id"]}}
}
}
""".formatted(policy, zoneId, recordSets, extra);
}
private void parameterizedStackRequest(String stackName, String action, String template, String parameter,
String value) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Parameters.member.1.ParameterKey", parameter)
.formParam("Parameters.member.1.ParameterValue", value)
.when().post("/").then().statusCode(200);
}
private RequestSpecification changeSetRequest(String action, String stackName, String changeSetName) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stackName)
.formParam("ChangeSetName", changeSetName);
}
private String stackOutput(String stackName, String key) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("DescribeStacksResponse.DescribeStacksResult.Stacks.member.Outputs.member"
+ ".find { it.OutputKey == '" + key + "' }.OutputValue");
}
private void assertChangeInSync(String changeId) {
given()
.header("Authorization", ROUTE53_AUTH)
.when().get("/2013-04-01/change/" + changeId.substring(changeId.lastIndexOf('/') + 1))
.then().statusCode(200)
.body(containsString("<Status>INSYNC</Status>"));
}
private void deleteHostedZone(String zoneId) {
given()
.header("Authorization", ROUTE53_AUTH)
.when().delete("/2013-04-01/hostedzone/" + zoneId)
.then().statusCode(200);
}
/**
* Refuses the first DELETE batch the group sends to {@code zoneId}, as Route 53 refuses one whose
* values no longer match a record changed outside the stack; later batches go through.
*/
private void refuseFirstGroupDeleteIn(String zoneId) {
Mockito.doThrow(new AwsException("InvalidChangeBatch",
"Tried to delete resource record set but the values provided do not match the current values",
400))
.doCallRealMethod()
.when(route53Service).changeResourceRecordSets(eq(zoneId), anyList(), eq("CloudFormation delete Group"));
}
private void continueUpdateRollback(String stackName, String... resourcesToSkip) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "ContinueUpdateRollback")
.formParam("StackName", stackName);
for (int i = 0; i < resourcesToSkip.length; i++) {
request.formParam("ResourcesToSkip.member." + (i + 1), resourcesToSkip[i]);
}
request.when().post("/").then().statusCode(200);
}
/**
* One TCP health check; {@code failing} adds a record set in a zone that does not exist, created
* after the check, so the update fails once the check has been replaced.
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.route53.Route53Service;
import io.github.hectorvent.floci.services.route53.model.ChangeInfo;
import io.github.hectorvent.floci.services.route53.model.HealthCheck;
import io.github.hectorvent.floci.services.route53.model.HealthCheckConfig;
import io.github.hectorvent.floci.services.route53.model.HostedZone;
@@ -18,6 +19,7 @@ import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -33,6 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -743,6 +746,546 @@ class Route53CfnProvisionerTest {
+ "\"SetIdentifier\":\"a\",\"Weight\":\"heavy\"}");
}
@Test
void recordGroupWritesEveryRecordSetInOneBatchWithItsRoutingPolicy() throws Exception {
Route53Service service = mock(Route53Service.class);
when(service.changeResourceRecordSets(eq("Z1"), any(), any()))
.thenReturn(new ChangeInfo("C123", "2026-10-23T00:00:00Z", "web tier"));
JsonNode props = new ObjectMapper().readTree("""
{"HostedZoneId": "Z1", "Comment": "web tier", "RecordSets": [
{"Name": "www.example.test", "Type": "A", "TTL": "60", "SetIdentifier": "blue", "Weight": 70,
"HealthCheckId": "hc-1", "ResourceRecords": ["10.0.0.7"]},
{"Name": "www.example.test.", "Type": "A", "TTL": "60", "SetIdentifier": "green", "Weight": 30,
"ResourceRecords": ["10.0.0.8"]}
]}
""");
StackResource resource = recordGroup();
new Route53CfnProvisioner(service).provision(resource, props, groupContext(null));
// Ref is the group's name, and Fn::GetAtt Id the change GetChange reads.
assertEquals("Group", resource.getPhysicalId());
assertEquals(Set.of("Id"), publicAttributes(resource));
assertEquals("C123", resource.getAttributes().get("Id"));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);
verify(service).changeResourceRecordSets(eq("Z1"), captor.capture(), eq("web tier"));
List<Map<String, Object>> changes = captor.getValue();
assertEquals(List.of("CREATE", "CREATE"), changes.stream().map(change -> change.get("action")).toList());
ResourceRecordSet blue = (ResourceRecordSet) changes.get(0).get("rrs");
assertEquals("www.example.test.", blue.getName());
assertEquals(Long.valueOf(60), blue.getTtl());
assertEquals("blue", blue.getSetIdentifier());
assertEquals(Long.valueOf(70), blue.getWeight());
assertEquals("hc-1", blue.getHealthCheckId());
assertEquals(List.of("10.0.0.7"), blue.getRecords().stream().map(ResourceRecord::getValue).toList());
ResourceRecordSet green = (ResourceRecordSet) changes.get(1).get("rrs");
assertEquals("green", green.getSetIdentifier());
assertEquals(Long.valueOf(30), green.getWeight());
}
@Test
void recordGroupValidatesEveryRecordSetBeforeChangingTheZone() throws Exception {
Route53Service service = mock(Route53Service.class);
JsonNode props = new ObjectMapper().readTree("""
{"HostedZoneId": "Z1", "RecordSets": [
{"Name": "valid.example.test", "Type": "A", "TTL": "60", "ResourceRecords": ["192.0.2.1"]},
{"Name": "invalid.example.test"}
]}
""");
StackResource resource = recordGroup();
AwsException failure = assertThrows(AwsException.class,
() -> new Route53CfnProvisioner(service).provision(resource, props, groupContext(null)));
assertEquals("ValidationError", failure.getErrorCode());
assertTrue(failure.getMessage().contains("RecordSets[1]"), failure.getMessage());
verifyNoInteractions(service);
assertNull(resource.getPhysicalId());
assertTrue(resource.getAttributes().isEmpty());
}
@Test
void recordGroupWithoutRecordSetsIsRejected() throws Exception {
assertRecordGroupRejected("{\"HostedZoneId\": \"Z1\", \"RecordSets\": []}");
assertRecordGroupRejected("{\"HostedZoneId\": \"Z1\"}");
}
@Test
void recordGroupWithoutAZoneIsRejected() throws Exception {
assertRecordGroupRejected("""
{"RecordSets": [{"Name": "www.example.test", "Type": "A", "ResourceRecords": ["192.0.2.1"]}]}
""");
}
@Test
void recordGroupRejectsAHostedZoneIdOnBothTheGroupAndARecordSet() throws Exception {
// AWS documents that creation fails when HostedZoneId is defined on the group and a record set.
assertRecordGroupRejected("""
{"HostedZoneId": "Z1", "RecordSets": [
{"HostedZoneId": "Z1", "Name": "www.example.test", "Type": "A", "ResourceRecords": ["192.0.2.1"]}
]}
""");
}
@Test
void recordGroupRejectsARecordSetInAnotherZone() throws Exception {
Route53Service service = mock(Route53Service.class);
when(service.listHostedZonesByName("other.example.test.", 0)).thenReturn(List.of(
new HostedZone("Z2", "other.example.test.", "caller", null, (VpcAssociation) null)));
JsonNode props = new ObjectMapper().readTree("""
{"HostedZoneId": "Z1", "RecordSets": [
{"HostedZoneName": "other.example.test.", "Name": "www.other.example.test", "Type": "A",
"ResourceRecords": ["192.0.2.1"]}
]}
""");
AwsException failure = assertThrows(AwsException.class,
() -> new Route53CfnProvisioner(service).provision(recordGroup(), props, groupContext(null)));
assertEquals("ValidationError", failure.getErrorCode());
verify(service, never()).changeResourceRecordSets(any(), any(), any());
}
@Test
void recordGroupThatNamesNoZoneWritesIntoTheZoneItsRecordSetsName() throws Exception {
Route53Service service = mock(Route53Service.class);
when(service.changeResourceRecordSets(eq("Z2"), any(), any())).thenReturn(new ChangeInfo("C1", "now", null));
JsonNode props = new ObjectMapper().readTree("""
{"RecordSets": [
{"HostedZoneId": "Z2", "Name": "a.example.test", "Type": "A", "ResourceRecords": ["192.0.2.1"]},
{"Name": "b.example.test", "Type": "A", "ResourceRecords": ["192.0.2.2"]}
]}
""");
new Route53CfnProvisioner(service).provision(recordGroup(), props, groupContext(null));
verify(service).changeResourceRecordSets(eq("Z2"), argThat(changes -> changes.size() == 2), any());
}
@Test
void recordGroupUpdateInItsZoneSwapsItsRecordsInOneBatchAndARollbackPutsThemBack() throws Exception {
Route53Service service = mock(Route53Service.class);
ResourceRecordSet kept = aRecord("old.example.test.", "192.0.2.1");
// Written by the last update, then deleted outside the stack: there is nothing to DELETE.
ResourceRecordSet gone = aRecord("gone.example.test.", "192.0.2.5");
when(service.listResourceRecordSets("Z1", null, null, 0)).thenReturn(List.of(kept));
when(service.changeResourceRecordSets(eq("Z1"), any(), any())).thenReturn(new ChangeInfo("C2", "now", null));
StackResource resource = existingGroup("Z1", "C1", kept, gone);
Map<String, String> before = Map.copyOf(resource.getAttributes());
JsonNode props = new ObjectMapper().readTree("""
{"HostedZoneId": "Z1", "RecordSets": [
{"Name": "new.example.test", "Type": "A", "TTL": "300", "ResourceRecords": ["192.0.2.2"]}
]}
""");
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
owner.provision(resource, props, groupContext("Group"));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);
verify(service).changeResourceRecordSets(eq("Z1"), captor.capture(), any());
assertEquals(List.of("DELETE old.example.test.", "CREATE new.example.test."), describe(captor.getValue()));
assertEquals("C2", resource.getAttributes().get("Id"));
assertFalse(owner.hasReplacementUpdate(resource));
assertNull(owner.updateCleanupPhysicalId(resource));
ResourceRecordSet written = (ResourceRecordSet) captor.getValue().get(1).get("rrs");
when(service.listResourceRecordSets("Z1", null, null, 0)).thenReturn(List.of(written));
assertTrue(owner.rollbackUpdate(resource));
verify(service, times(2)).changeResourceRecordSets(eq("Z1"), captor.capture(), any());
assertEquals(List.of("DELETE new.example.test.", "CREATE old.example.test.", "CREATE gone.example.test."),
describe(captor.getValue()));
assertEquals(before, resource.getAttributes());
}
@Test
void recordGroupZoneChangeDeletesTheOldRecordsOnlyOnceTheUpdateCommits() throws Exception {
Route53Service service = mock(Route53Service.class);
ResourceRecordSet old = aRecord("www.example.test.", "192.0.2.1");
when(service.listResourceRecordSets("ZOLD", null, null, 0)).thenReturn(List.of(old));
when(service.changeResourceRecordSets(any(), any(), any())).thenReturn(new ChangeInfo("C2", "now", null));
StackResource resource = existingGroup("ZOLD", "C1", old);
JsonNode props = new ObjectMapper().readTree("""
{"HostedZoneId": "ZNEW", "RecordSets": [
{"Name": "www.example.test", "Type": "A", "TTL": "300", "ResourceRecords": ["192.0.2.2"]}
]}
""");
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
owner.provision(resource, props, groupContext("Group"));
verify(service).changeResourceRecordSets(eq("ZNEW"), argThat(changes -> changes.size() == 1
&& "CREATE".equals(changes.get(0).get("action"))), any());
verify(service, never()).changeResourceRecordSets(eq("ZOLD"), any(), any());
assertTrue(owner.hasReplacementUpdate(resource));
assertEquals("Group", owner.updateCleanupPhysicalId(resource));
UpdateCleanupResult cleanup = owner.completeUpdate(resource);
assertTrue(cleanup.applicable());
assertTrue(cleanup.complete());
verify(service).changeResourceRecordSets(eq("ZOLD"), argThat(changes -> changes.size() == 1
&& "DELETE".equals(changes.get(0).get("action")) && changes.get(0).get("rrs") != null), any());
owner.clearUpdate(resource);
assertFalse(owner.hasReplacementUpdate(resource));
assertEquals(Set.of("Id"), publicAttributes(resource));
}
@Test
void recordGroupCleanupThatGivesUpForgetsTheOldRecords() throws Exception {
Route53Service service = mock(Route53Service.class);
ResourceRecordSet old = aRecord("www.example.test.", "192.0.2.1");
when(service.listResourceRecordSets("ZOLD", null, null, 0)).thenReturn(List.of(old));
when(service.listResourceRecordSets("ZNEW", null, null, 0)).thenReturn(List.of(movedRecord()));
when(service.changeResourceRecordSets(eq("ZOLD"), any(), any()))
.thenThrow(new AwsException("InvalidChangeBatch", "values do not match", 400));
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
StackResource resource = movedGroup(owner, service, old);
for (int attempt = 1; attempt <= 3; attempt++) {
UpdateCleanupResult cleanup = owner.completeUpdate(resource);
assertFalse(cleanup.complete());
assertEquals(attempt, cleanup.attempts());
assertEquals("values do not match", cleanup.failureReason());
}
owner.clearUpdate(resource);
assertFalse(owner.hasReplacementUpdate(resource));
assertNull(owner.updateCleanupPhysicalId(resource));
owner.delete(resource, "us-east-1");
verify(service, times(3)).changeResourceRecordSets(eq("ZOLD"), any(), any());
// The update's write and the delete.
verify(service, times(2)).changeResourceRecordSets(eq("ZNEW"), any(), any());
}
@Test
void deletingARecordGroupMidMoveDeletesTheOldRecordsFirstAndKeepsBothUntilTheyAreGone() throws Exception {
Route53Service service = mock(Route53Service.class);
ResourceRecordSet old = aRecord("www.example.test.", "192.0.2.1");
when(service.listResourceRecordSets("ZOLD", null, null, 0)).thenReturn(List.of(old));
when(service.listResourceRecordSets("ZNEW", null, null, 0)).thenReturn(List.of(movedRecord()));
when(service.changeResourceRecordSets(eq("ZOLD"), any(), any()))
.thenThrow(new AwsException("InvalidChangeBatch", "values do not match", 400))
.thenReturn(null);
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
StackResource resource = movedGroup(owner, service, old);
assertThrows(AwsException.class, () -> owner.delete(resource, "us-east-1"));
verify(service, never()).listResourceRecordSets(eq("ZNEW"), any(), any(), eq(0));
assertTrue(owner.hasReplacementUpdate(resource));
owner.delete(resource, "us-east-1");
verify(service, times(2)).changeResourceRecordSets(eq("ZOLD"), any(), any());
verify(service, times(2)).changeResourceRecordSets(eq("ZNEW"), any(), any());
assertFalse(owner.hasReplacementUpdate(resource));
}
@Test
void zoneChangeRollbackThatCannotDeleteTheNewRecordsPointsBackAtTheOldOnesAndRetries() throws Exception {
Route53Service service = mock(Route53Service.class);
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
ResourceRecordSet old = aRecord("www.example.test.", "192.0.2.1");
StackResource resource = failedMoveRollback(owner, service, old);
// The group already names its old records again, so a skip leaves it matching the template the
// stack rolls back to; only the new zone's records are owed, and Retain never keeps them.
assertEquals("Group", resource.getPhysicalId());
Map<String, String> restored = new HashMap<>(resource.getAttributes());
assertNotNull(restored.remove("__FlociRoute53GroupOwedDeletes"));
assertEquals(existingGroup("ZOLD", "C1", old).getAttributes(), restored);
// Owed records do not make the group a replacement, and no cleanup announces them: a commit
// never deletes them, and the engine announces before it says whether it commits or deletes.
assertFalse(owner.hasReplacementUpdate(resource));
assertNull(owner.updateCleanupPhysicalId(resource));
// ContinueUpdateRollback runs the rollback again, which now only owes that delete.
assertTrue(owner.rollbackUpdate(resource));
assertEquals(existingGroup("ZOLD", "C1", old).getAttributes(), resource.getAttributes());
assertFalse(owner.hasReplacementUpdate(resource));
verify(service, never()).changeResourceRecordSets(eq("ZOLD"), any(), any());
// The update's write, the failed delete and the retried one.
verify(service, times(3)).changeResourceRecordSets(eq("ZNEW"), any(), any());
}
@Test
void recordsAFailedRollbackCouldNotDeleteGoWithTheStackWhileTheRollbackIsUnfinished() throws Exception {
Route53Service service = mock(Route53Service.class);
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
ResourceRecordSet old = aRecord("www.example.test.", "192.0.2.1");
StackResource resource = failedMoveRollback(owner, service, old);
// DeleteStack from UPDATE_ROLLBACK_FAILED: the stack's cleanup runs first, under Retain too.
UpdateCleanupResult cleanup = owner.completeDeleteCleanup(resource);
assertTrue(cleanup.applicable());
assertTrue(cleanup.complete());
assertEquals("Group", cleanup.previousPhysicalId());
owner.clearDeleteCleanup(resource);
assertEquals(existingGroup("ZOLD", "C1", old).getAttributes(), resource.getAttributes());
// The failed delete and this one.
verify(service, times(2)).changeResourceRecordSets(eq("ZNEW"), any(), eq("CloudFormation delete Group"));
verify(service, never()).changeResourceRecordSets(eq("ZOLD"), any(), any());
}
@Test
void aCommitNeverDeletesWhatAFailedRollbackLeftEvenWhileTheGroupIsUpdateFailed() throws Exception {
Route53Service service = mock(Route53Service.class);
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
StackResource resource = failedMoveRollback(owner, service, aRecord("www.example.test.", "192.0.2.1"));
// A nested stack's child is updated while it is still UPDATE_ROLLBACK_FAILED, so its commit can
// meet a group whose rollback is unfinished.
assertFalse(owner.completeUpdate(resource).applicable());
verify(service, times(1)).changeResourceRecordSets(eq("ZNEW"), any(), eq("CloudFormation delete Group"));
assertFalse(resource.getAttributes().containsKey("__FlociRoute53GroupOwedDeletes"));
}
@Test
void removingAGroupNeverDeletesWhatAFailedRollbackLeft() throws Exception {
Route53Service service = mock(Route53Service.class);
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
ResourceRecordSet old = aRecord("www.example.test.", "192.0.2.1");
when(service.listResourceRecordSets("ZOLD", null, null, 0)).thenReturn(List.of(old));
StackResource resource = failedMoveRollback(owner, service, old);
owner.delete(resource, "us-east-1");
verify(service, times(1)).changeResourceRecordSets(eq("ZNEW"), any(), eq("CloudFormation delete Group"));
verify(service).changeResourceRecordSets(eq("ZOLD"), any(), eq("CloudFormation delete Group"));
}
@Test
void aSkippedRollbackLeavesTheRecordsItCouldNotDeleteInTheirZone() throws Exception {
Route53Service service = mock(Route53Service.class);
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
ResourceRecordSet old = aRecord("www.example.test.", "192.0.2.1");
when(service.listResourceRecordSets("ZOLD", null, null, 0)).thenReturn(List.of(old));
StackResource resource = failedMoveRollback(owner, service, old);
// ContinueUpdateRollback skipped the group.
resource.setStatus("UPDATE_COMPLETE");
// Nothing tells the leftover apart from an identical record written there later, so neither the
// next commit's cleanup nor a delete removes it.
assertNull(owner.updateCleanupPhysicalId(resource));
assertFalse(owner.completeUpdate(resource).applicable());
assertFalse(resource.getAttributes().containsKey("__FlociRoute53GroupOwedDeletes"));
owner.delete(resource, "us-east-1");
verify(service, times(1)).changeResourceRecordSets(eq("ZNEW"), any(), eq("CloudFormation delete Group"));
verify(service).changeResourceRecordSets(eq("ZOLD"), any(), eq("CloudFormation delete Group"));
}
@Test
void reApplyingAMoveAfterASkippedRollbackKeepsTheRecordItWrites() throws Exception {
Route53Service service = mock(Route53Service.class);
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
ResourceRecordSet old = aRecord("www.example.test.", "192.0.2.1");
StackResource resource = failedMoveRollback(owner, service, old);
when(service.listResourceRecordSets("ZOLD", null, null, 0)).thenReturn(List.of(old));
resource.setUpdateReplacePolicy(null);
resource.setStatus("UPDATE_COMPLETE");
// ContinueUpdateRollback skipped the group, the leftover record was deleted by hand, and the
// move is applied again, writing the same record into ZNEW.
owner.provision(resource, new ObjectMapper().readTree("""
{"HostedZoneId": "ZNEW", "RecordSets": [
{"Name": "www.example.test", "Type": "A", "TTL": "300", "ResourceRecords": ["192.0.2.2"]}
]}
"""), groupContext("Group"));
UpdateCleanupResult cleanup = owner.completeUpdate(resource);
owner.clearUpdate(resource);
assertTrue(cleanup.complete());
verify(service).changeResourceRecordSets(eq("ZOLD"), any(), eq("CloudFormation delete Group"));
// Only the failed rollback's delete went to ZNEW; the record the move wrote stays.
verify(service, times(1)).changeResourceRecordSets(eq("ZNEW"), any(), eq("CloudFormation delete Group"));
assertFalse(resource.getAttributes().containsKey("__FlociRoute53GroupOwedDeletes"));
assertFalse(owner.hasReplacementUpdate(resource));
}
@Test
void aLaterUpdateForgetsWhatASkippedRollbackLeftSoARetryNeedsOnlyItsOwn() throws Exception {
Route53Service service = mock(Route53Service.class);
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
StackResource resource = failedMoveRollback(owner, service, aRecord("www.example.test.", "192.0.2.1"));
// The ZNEW record stays changed outside the stack, so deleting it keeps failing.
doThrow(new AwsException("InvalidChangeBatch", "values do not match", 400))
.when(service).changeResourceRecordSets(eq("ZNEW"), any(), eq("CloudFormation delete Group"));
// After a skip, a second move, to Z3, fails too, and its rollback cannot delete Z3's record once.
resource.setStatus("UPDATE_COMPLETE");
when(service.changeResourceRecordSets(eq("Z3"), any(), any())).thenReturn(new ChangeInfo("C3", "now", null));
when(service.listResourceRecordSets("Z3", null, null, 0))
.thenReturn(List.of(aRecord("www.example.test.", "192.0.2.3")));
owner.provision(resource, new ObjectMapper().readTree("""
{"HostedZoneId": "Z3", "RecordSets": [
{"Name": "www.example.test", "Type": "A", "TTL": "300", "ResourceRecords": ["192.0.2.3"]}
]}
"""), groupContext("Group"));
doThrow(new AwsException("InvalidChangeBatch", "Z3 values do not match", 400)).doReturn(null)
.when(service).changeResourceRecordSets(eq("Z3"), any(), eq("CloudFormation delete Group"));
assertThrows(AwsException.class, () -> owner.rollbackUpdate(resource));
resource.setStatus("UPDATE_FAILED");
// The skipped rollback's ZNEW record was left behind by the second update, so the retry needs only
// Z3's record, which its own rollback could not delete.
String owed = resource.getAttributes().get("__FlociRoute53GroupOwedDeletes");
assertTrue(owed.contains("Z3") && !owed.contains("ZNEW"), owed);
assertTrue(owner.rollbackUpdate(resource));
verify(service, times(2)).changeResourceRecordSets(eq("Z3"), any(), eq("CloudFormation delete Group"));
verify(service, times(1)).changeResourceRecordSets(eq("ZNEW"), any(), eq("CloudFormation delete Group"));
assertFalse(resource.getAttributes().containsKey("__FlociRoute53GroupOwedDeletes"));
assertFalse(owner.completeUpdate(resource).applicable());
}
@Test
void replacingAStubAnOlderFlociLeftIsNotAZoneChangeAndARollbackPutsTheStubBack() throws Exception {
Route53Service service = mock(Route53Service.class);
when(service.changeResourceRecordSets(eq("Z1"), any(), any())).thenReturn(new ChangeInfo("C1", "now", null));
StackResource resource = recordGroup();
resource.setPhysicalId("Group-0a1b2c3d");
resource.getAttributes().put("Arn", "arn:aws:stub:::Group");
Map<String, String> stub = Map.copyOf(resource.getAttributes());
Route53CfnProvisioner owner = new Route53CfnProvisioner(service);
owner.provision(resource, new ObjectMapper().readTree("""
{"HostedZoneId": "Z1", "RecordSets": [
{"Name": "www.example.test", "Type": "A", "TTL": "300", "ResourceRecords": ["192.0.2.1"]}
]}
"""), groupContext("Group-0a1b2c3d"));
assertEquals("Group", resource.getPhysicalId());
assertFalse(owner.hasReplacementUpdate(resource));
assertNull(owner.updateCleanupPhysicalId(resource));
when(service.listResourceRecordSets("Z1", null, null, 0))
.thenReturn(List.of(aRecord("www.example.test.", "192.0.2.1")));
assertTrue(owner.rollbackUpdate(resource));
assertEquals("Group-0a1b2c3d", resource.getPhysicalId());
assertEquals(stub, resource.getAttributes());
verify(service).changeResourceRecordSets(eq("Z1"), argThat(changes -> describe(changes)
.equals(List.of("DELETE www.example.test."))), any());
}
@Test
void recordGroupRejectsTwoRecordSetsWithOneNameTypeAndSetIdentifier() throws Exception {
assertRecordGroupRejected("""
{"HostedZoneId": "Z1", "RecordSets": [
{"Name": "www.example.test", "Type": "A", "ResourceRecords": ["192.0.2.1"]},
{"Name": "www.example.test.", "Type": "A", "ResourceRecords": ["192.0.2.2"]}
]}
""");
}
@Test
void deletingARecordGroupToleratesAZoneAlreadyGone() throws Exception {
Route53Service service = mock(Route53Service.class);
when(service.listResourceRecordSets("Z1", null, null, 0))
.thenThrow(new AwsException("NoSuchHostedZone", "No hosted zone found with ID: Z1", 404));
StackResource resource = existingGroup("Z1", "C1", aRecord("www.example.test.", "192.0.2.1"));
new Route53CfnProvisioner(service).delete(resource, "us-east-1");
verify(service, never()).changeResourceRecordSets(any(), any(), any());
}
private void assertRecordGroupRejected(String json) throws Exception {
Route53Service service = mock(Route53Service.class);
JsonNode props = new ObjectMapper().readTree(json);
AwsException failure = assertThrows(AwsException.class,
() -> new Route53CfnProvisioner(service).provision(recordGroup(), props, groupContext(null)));
assertEquals("ValidationError", failure.getErrorCode());
verify(service, never()).changeResourceRecordSets(any(), any(), any());
}
private static StackResource recordGroup() {
StackResource resource = new StackResource();
resource.setLogicalId("Group");
resource.setResourceType("AWS::Route53::RecordSetGroup");
return resource;
}
/** A group a create or an earlier update wrote into {@code zoneId} with change {@code changeId}. */
private static StackResource existingGroup(String zoneId, String changeId, ResourceRecordSet... records)
throws Exception {
StackResource resource = recordGroup();
resource.setPhysicalId("Group");
resource.getAttributes().put("Id", changeId);
resource.getAttributes().put("__FlociRoute53RecordZoneId", zoneId);
resource.getAttributes().put("__FlociRoute53GroupRecords",
new ObjectMapper().writeValueAsString(List.of(records)));
return resource;
}
/**
* A group created in ZOLD as {@code old} that an update has just moved to ZNEW, writing
* {@link #movedRecord()} there; the update has neither committed nor rolled back.
*/
private static StackResource movedGroup(Route53CfnProvisioner owner, Route53Service service,
ResourceRecordSet old) throws Exception {
StackResource resource = existingGroup("ZOLD", "C1", old);
when(service.changeResourceRecordSets(eq("ZNEW"), any(), any())).thenReturn(new ChangeInfo("C2", "now", null));
owner.provision(resource, new ObjectMapper().readTree("""
{"HostedZoneId": "ZNEW", "RecordSets": [
{"Name": "www.example.test", "Type": "A", "TTL": "300", "ResourceRecords": ["192.0.2.2"]}
]}
"""), groupContext("Group"));
return resource;
}
private static ResourceRecordSet movedRecord() {
return aRecord("www.example.test.", "192.0.2.2");
}
/**
* A moved group, under {@code UpdateReplacePolicy: Retain}, whose rollback could not delete the
* record it wrote into ZNEW; the next delete there succeeds.
*/
private static StackResource failedMoveRollback(Route53CfnProvisioner owner, Route53Service service,
ResourceRecordSet old) throws Exception {
when(service.listResourceRecordSets("ZNEW", null, null, 0)).thenReturn(List.of(movedRecord()));
StackResource resource = movedGroup(owner, service, old);
resource.setUpdateReplacePolicy("Retain");
doThrow(new AwsException("InvalidChangeBatch", "values do not match", 400)).doReturn(null)
.when(service).changeResourceRecordSets(eq("ZNEW"), any(), eq("CloudFormation delete Group"));
AwsException failure = assertThrows(AwsException.class, () -> owner.rollbackUpdate(resource));
assertEquals("values do not match", failure.getMessage());
// As the rollback walker marks a resource whose rollback failed.
resource.setStatus("UPDATE_FAILED");
return resource;
}
private static ResourceRecordSet aRecord(String name, String address) {
ResourceRecordSet record = new ResourceRecordSet();
record.setName(name);
record.setType("A");
record.setTtl(300L);
record.setRecords(List.of(new ResourceRecord(address)));
return record;
}
private static List<String> describe(List<Map<String, Object>> changes) {
return changes.stream()
.map(change -> change.get("action") + " " + ((ResourceRecordSet) change.get("rrs")).getName())
.toList();
}
private static ProvisionContext groupContext(String priorPhysicalId) {
CloudFormationTemplateEngine engine = recordEngine();
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(invocation -> invocation.getArgument(0));
return priorPhysicalId == null
? new ProvisionContext(engine, "us-east-1", "000000000000", "dns-stack")
: new ProvisionContext(engine, "us-east-1", "000000000000", "dns-stack", priorPhysicalId);
}
@Test
void healthCheckIsCreatedWithItsConfigTagsAndExactAttributes() throws Exception {
Route53Service service = mock(Route53Service.class);