mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): replace a Route53 hosted zone on a Name or DelegationSetId change and roll back record set updates (#8205)
This commit is contained in:
1 parent
f09468fb19
commit
57c7462846
8 files changed
+742
-86
No files matched your search
+12
-2
@@ -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"),
|
||||
|
||||
+1
-12
@@ -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");
|
||||
}
|
||||
}
|
||||
+159
-10
@@ -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("<TTL>300</TTL>") && !records.contains("<TTL>60</TTL>"),
|
||||
"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<String> 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<String> 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);
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
+296
-2
@@ -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<VpcAssociation> 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<List<Map<String, Object>>> changes = ArgumentCaptor.forClass(List.class);
|
||||
ArgumentCaptor<String> zones = ArgumentCaptor.forClass(String.class);
|
||||
verify(service, times(expectedCalls.split(";").length))
|
||||
.changeResourceRecordSets(zones.capture(), changes.capture(), any());
|
||||
List<String> 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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user