Light, fluffy, and always free - The AWS Local Emulator alternative
fix(route53): store CloudFormation record names fully qualified (#4734)
Mario Toffia7ebbe868ca0f
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisioner.javaindex f253e779b5..b25d173ae5 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisioner.java@@ -23,14 +23,16 @@ import java.util.Set;/*** Provisions {@code AWS::Route53::HostedZone} and {@code AWS::Route53::RecordSet}.*- * <p>A record set is written into its hosted zone through {@code ChangeResourceRecordSets}: the- * declared record is applied as an UPSERT so create and update both converge, {@code Ref} is the- * record name, and stack delete removes the record with a matching DELETE change. The schema-required- * {@code Type} and {@code Name} are validated, and the zone is taken from {@code HostedZoneId} (or- * resolved from {@code HostedZoneName}), since a record cannot be written without one. No- * {@code Fn::GetAtt} attribute is published: the registry lists {@code Id} as read-only, but the- * type has no registry handlers and the resource specification gives it no attributes, so- * {@code Ref} is its only reference.+ * <p>A record set is written into its hosted zone through {@code ChangeResourceRecordSets}. On stack+ * create, and on an update that changes the record's identity (zone, Name, Type or SetIdentifier), the+ * record is sent as a CREATE, so a record another owner already holds at that identity fails the+ * stack. An update that keeps the identity is sent as an UPSERT, which replaces whatever record holds+ * that identity. {@code Ref} is the record name, and stack delete removes the record with a matching+ * DELETE change. The schema-required {@code Type} and {@code Name} are validated, and the zone is+ * taken from {@code HostedZoneId} (or resolved from {@code HostedZoneName}), since a record cannot be+ * written without one. No {@code Fn::GetAtt} attribute is published: the registry lists {@code Id} as+ * read-only, but the type has no registry handlers and the resource specification gives it no+ * attributes, so {@code Ref} is its only reference.*/@ApplicationScopedpublic class Route53CfnProvisioner implements CfnResourceProvisioner {@@ -82,7 +84,7 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner {String zoneId = resolveZoneId(props, ctx);ResourceRecordSet rrs = new ResourceRecordSet();- rrs.setName(name);+ rrs.setName(Route53Service.normalizeName(name));rrs.setType(type);String ttl = ctx.resolveOptional(props, "TTL");if (ttl != null && !ttl.isBlank()) {@@ -96,23 +98,29 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner {"AWS::Route53::RecordSet TTL must be an integer: " + ttl, 400);}}- String setIdentifier = ctx.resolveOptional(props, "SetIdentifier");+ // Route 53 requires a set identifier of at least one character, so a blank one means none.+ String setIdentifier = ctx.resolveOrDefault(props, "SetIdentifier", null);rrs.setSetIdentifier(setIdentifier);rrs.setRecords(parseResourceRecords(props, ctx));rrs.setAliasTarget(parseAliasTarget(props, ctx));- // UPSERT: provision serves create and update, and re-applying the same record must not fail- // with "already exists" the way a CREATE would on the second UpdateStack.+ // The record's identity is Name + Type + SetIdentifier within a zone. Re-applying the identity+ // this resource wrote last time is an UPSERT, which replaces whatever record holds that+ // identity. Any other identity, on stack create or on an update that changes it, is a record+ // the stack does not own yet, so it is a CREATE: a record another owner already holds under+ // that identity fails the stack instead of being taken over.+ boolean sameIdentity = isPriorIdentity(ctx, priorAttributes, zoneId, name, type, setIdentifier);Map<String, Object> change = new HashMap<>();- change.put("action", "UPSERT");+ change.put("action", sameIdentity ? "UPSERT" : "CREATE");change.put("rrs", rrs);route53Service.changeResourceRecordSets(zoneId, List.of(change),"CloudFormation " + ctx.stackName() + "/" + resource.getLogicalId());- // The record's identity is Name + Type + SetIdentifier within a zone. When an update changes- // any of them, the UPSERT writes a new record and the prior one is orphaned, so remove it,+ // An update that changes the identity leaves the prior record orphaned, so remove it,// otherwise it lingers in the zone and later blocks the zone's own delete.- removeSupersededRecord(ctx, priorAttributes, zoneId, name, type, setIdentifier);+ if (!sameIdentity) {+ removeSupersededRecord(ctx, priorAttributes);+ }resource.setPhysicalId(name);resource.getAttributes().put(RECORD_ZONE_ATTR, zoneId);@@ -125,13 +133,27 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner {}/**- * Removes the record a prior provision wrote when this update changed the record's identity- * (zone, Name, Type or SetIdentifier). Reads the prior identity from the attributes the last- * provision recorded plus the prior physical id (the prior Name). A no-op on create, and when- * the identity is unchanged the UPSERT already replaced the record in place.+ * Whether the last provision of this resource wrote the same record identity: zone, Name, Type+ * and SetIdentifier. Names are compared fully qualified, so a change that only adds or drops the+ * trailing dot is the same record. Reads the prior identity from the attributes the last+ * provision recorded plus the prior physical id (the prior Name). False on create.+ */+ private static boolean isPriorIdentity(ProvisionContext ctx, Map<String, String> priorAttributes,+ String zoneId, String name, String type, String setIdentifier) {+ return ctx.isUpdate()+ && zoneId.equals(priorAttributes.get(RECORD_ZONE_ATTR))+ && Route53Service.normalizeName(name).equals(Route53Service.normalizeName(ctx.priorPhysicalId()))+ && type.equals(priorAttributes.get(RECORD_TYPE_ATTR))+ && Objects.equals(priorAttributes.get(RECORD_SET_ID_ATTR), setIdentifier);+ }++ /**+ * Removes the record a prior provision wrote, once this update has changed the record's+ * identity. Reads the prior identity from the attributes the last provision recorded plus the+ * prior physical id (the prior Name). A no-op on create, and when no prior zone or type was+ * recorded.*/- private void removeSupersededRecord(ProvisionContext ctx, Map<String, String> priorAttributes,- String zoneId, String name, String type, String setIdentifier) {+ private void removeSupersededRecord(ProvisionContext ctx, Map<String, String> priorAttributes) {if (!ctx.isUpdate()) {return;}@@ -143,11 +165,6 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner {|| priorType == null || priorType.isBlank()) {return;}- boolean sameIdentity = priorZoneId.equals(zoneId) && priorName.equals(name)- && priorType.equals(type) && Objects.equals(priorSetId, setIdentifier);- if (sameIdentity) {- return;- }removeRecord(priorZoneId, priorName, priorType, priorSetId, "CloudFormation supersede");}@@ -373,14 +390,23 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner {}, "NoSuchHostedZone", "InvalidChangeBatch");}+ /**+ * The physical id keeps the name as the template wrote it, so the lookup matches by Route 53's+ * record identity, which ignores the trailing dot. An earlier version stored that name as written+ * and could leave another owner's copy in the other form beside it, so prefer the exact name.+ */private ResourceRecordSet findRecord(String zoneId, String name, String type, String setIdentifier) {- for (ResourceRecordSet rrs : route53Service.listResourceRecordSets(zoneId, null, null, 0)) {- if (name.equals(rrs.getName()) && type.equals(rrs.getType())- && Objects.equals(setIdentifier, rrs.getSetIdentifier())) {- return rrs;- }- }- return null;+ ResourceRecordSet wanted = new ResourceRecordSet();+ wanted.setName(name);+ wanted.setType(type);+ wanted.setSetIdentifier(setIdentifier);+ List<ResourceRecordSet> matches = route53Service.listResourceRecordSets(zoneId, null, null, 0).stream()+ .filter(rrs -> Route53Service.sameRecord(rrs, wanted))+ .toList();+ return matches.stream()+ .filter(rrs -> rrs.getName().equals(name))+ .findFirst()+ .orElse(matches.isEmpty() ? null : matches.get(0));}private List<VpcAssociation> parseVpcs(JsonNode node) {diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.javaindex e9b45205de..0ceac25227 100644--- a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java@@ -919,10 +919,7 @@ public class Route53Service implements Resettable {"Invalid resource record set: Deleting the SOA or NS record at the zone apex is not permitted.", 400);}if ("CREATE".equals(action)) {- boolean exists = current.stream().anyMatch(r ->- r.getName().equals(rrs.getName()) &&- r.getType().equals(rrs.getType()) &&- equalOrNull(r.getSetIdentifier(), rrs.getSetIdentifier()));+ boolean exists = current.stream().anyMatch(r -> sameRecord(r, rrs));if (exists) {throw new AwsException("InvalidChangeBatch","Tried to create resource record set [name='" + rrs.getName() +@@ -930,13 +927,13 @@ public class Route53Service implements Resettable {}}if ("DELETE".equals(action)) {- ResourceRecordSet existing = findByNameTypeAndSetIdentifier(current, rrs);- if (existing == null) {+ List<ResourceRecordSet> existing = current.stream().filter(r -> sameRecord(r, rrs)).toList();+ if (existing.isEmpty()) {throw new AwsException("InvalidChangeBatch","Tried to delete resource record set " + deleteTargetDescription(rrs)+ " but it was not found", 400);}- if (!recordSetsMatch(existing, rrs)) {+ if (existing.stream().noneMatch(r -> recordSetsMatch(r, rrs))) {throw new AwsException("InvalidChangeBatch","Tried to delete resource record set " + deleteTargetDescription(rrs)+ " but the values provided do not match the current values", 400);@@ -947,30 +944,37 @@ public class Route53Service implements Resettable {private void applyChange(String action, ResourceRecordSet rrs, List<ResourceRecordSet> current) {switch (action) {case "CREATE" -> current.add(rrs);- case "DELETE" -> current.removeIf(r -> recordSetsMatch(r, rrs));+ case "DELETE" -> current.remove(deleteTarget(current, rrs));case "UPSERT" -> {- current.removeIf(r ->- r.getName().equals(rrs.getName()) && r.getType().equals(rrs.getType()) &&- equalOrNull(r.getSetIdentifier(), rrs.getSetIdentifier()));+ current.removeIf(r -> sameRecord(r, rrs));current.add(rrs);}}}- private static boolean equalOrNull(String a, String b) {- if (a == null && b == null) return true;- if (a == null || b == null) return false;- return a.equals(b);+ /**+ * Whether two record sets share an identity: name, type and set identifier. Route 53 treats a+ * name with or without the trailing dot as the same, and requires a set identifier of at least one+ * character, so a blank one is none. That also matches a record an earlier CloudFormation+ * provisioner stored with the template's undotted Name or empty SetIdentifier.+ */+ public static boolean sameRecord(ResourceRecordSet a, ResourceRecordSet b) {+ return normalizeName(a.getName()).equals(normalizeName(b.getName()))+ && a.getType().equals(b.getType())+ && Objects.equals(blankToNull(a.getSetIdentifier()), blankToNull(b.getSetIdentifier()));+ }++ private static String blankToNull(String value) {+ return value == null || value.isBlank() ? null : value;}- private static ResourceRecordSet findByNameTypeAndSetIdentifier(List<ResourceRecordSet> current,- ResourceRecordSet rrs) {- return current.stream()- .filter(r -> r.getName().equals(rrs.getName())- && r.getType().equals(rrs.getType())- && Objects.equals(r.getSetIdentifier(), rrs.getSetIdentifier()))- .findFirst()- .orElse(null);+ /**+ * One DELETE removes one record. An earlier version could store the same record both undotted and+ * dotted, possibly for two owners, so prefer the copy named exactly as the request names it.+ */+ private static ResourceRecordSet deleteTarget(List<ResourceRecordSet> current, ResourceRecordSet rrs) {+ List<ResourceRecordSet> matches = current.stream().filter(r -> recordSetsMatch(r, rrs)).toList();+ return matches.stream().filter(r -> r.getName().equals(rrs.getName())).findFirst().orElse(matches.get(0));}private static String deleteTargetDescription(ResourceRecordSet rrs) {@@ -982,9 +986,7 @@ public class Route53Service implements Resettable {}private static boolean recordSetsMatch(ResourceRecordSet a, ResourceRecordSet b) {- return a.getName().equals(b.getName())- && a.getType().equals(b.getType())- && Objects.equals(a.getSetIdentifier(), b.getSetIdentifier())+ return sameRecord(a, b)&& Objects.equals(a.getTtl(), b.getTtl())&& Objects.equals(a.getWeight(), b.getWeight())&& Objects.equals(a.getRegion(), b.getRegion())diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRoute53RecordSetIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRoute53RecordSetIntegrationTest.javaindex 2264c498a4..a1abec149b 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRoute53RecordSetIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationRoute53RecordSetIntegrationTest.java@@ -10,11 +10,13 @@ import java.time.Duration;import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.containsString;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.assertTrue;/*** {@code AWS::Route53::RecordSet} through the per-service provisioner: {@code Ref} is the record- * name. It is read back through an SSM parameter the template writes, because a stack status+ * name as the template wrote it, while the zone stores and lists the name fully qualified. It is+ * read back through an SSM parameter the template writes, because a stack status* alone proves nothing: an unowned type is stubbed CREATE_COMPLETE with an {@code arn:aws:stub}* physical id, which the parameter would expose.*/@@ -86,6 +88,178 @@ class CloudFormationRoute53RecordSetIntegrationTest {}}+ @Test+ void recordSetNameIsStoredFullyQualifiedAcrossCreateUpdateAndDelete() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "r53-recordset-fqdn-" + suffix;+ String zoneName = suffix + ".cfn-fqdn-it.example.com";+ String firstName = "www." + zoneName;+ String secondName = "api." + zoneName;+ String template = """+ {+ "Parameters": {+ "RecordName": {"Type": "String"},+ "Address": {"Type": "String"}+ },+ "Resources": {+ "Zone": {+ "Type": "AWS::Route53::HostedZone",+ "Properties": {"Name": "%s"}+ },+ "Record": {+ "Type": "AWS::Route53::RecordSet",+ "Properties": {+ "HostedZoneId": {"Ref": "Zone"},+ "Name": {"Ref": "RecordName"},+ "Type": "A",+ "TTL": "300",+ "ResourceRecords": [{"Ref": "Address"}]+ }+ },+ "ZoneParam": {+ "Type": "AWS::SSM::Parameter",+ "Properties": {"Name": "/r53-recordset/%s/fqdn-zone", "Type": "String", "Value": {"Ref": "Zone"}}+ }+ }+ }+ """.formatted(zoneName, suffix);++ stackRequest("CreateStack", stackName, template, firstName, "10.0.0.1");+ assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());+ String zoneId = parameterValue("/r53-recordset/" + suffix + "/fqdn-zone");+ String created = listResourceRecordSets(zoneId);+ assertTrue(created.contains("<Name>" + firstName + ".</Name>"), "name not fully qualified: " + created);+ assertFalse(created.contains("<Name>" + firstName + "</Name>"), "name stored as written: " + created);++ // A rename is a new record identity, so the update must also find and remove the old record.+ stackRequest("UpdateStack", stackName, template, secondName, "10.0.0.2");+ assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());+ String updated = listResourceRecordSets(zoneId);+ assertTrue(updated.contains("<Name>" + secondName + ".</Name>"), "renamed record missing: " + updated);+ assertTrue(updated.contains("10.0.0.2"), "updated value missing: " + updated);+ assertFalse(updated.contains(firstName), "superseded record left in zone: " + updated);++ // The zone refuses to delete while it still holds the record, so a clean stack delete and a+ // zone that is gone prove the stack delete found the fully-qualified record and removed it.+ deleteStack(stackName);+ CfnStackWaits.awaitStackDeleted(stackName);+ given()+ .header("Authorization", ROUTE53_AUTH)+ .when().get("/2013-04-01/hostedzone/" + zoneId)+ .then().statusCode(404);+ }++ @Test+ void createStackFailsRatherThanTakeOverARecordTheRoute53ApiCreated() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "r53-recordset-taken-" + suffix;+ String zoneName = suffix + ".cfn-taken-it.example.com";+ String recordName = "www." + zoneName;+ String zoneId = createHostedZone(zoneName, "cfn-taken-" + suffix);+ changeRecordSet(zoneId, "CREATE", recordName + ".", "192.0.2.10");+ String template = """+ {+ "Resources": {+ "Www": {+ "Type": "AWS::Route53::RecordSet",+ "Properties": {+ "HostedZoneId": "%s",+ "Name": "%s",+ "Type": "A",+ "TTL": "300",+ "ResourceRecords": ["192.0.2.20"]+ }+ }+ }+ }+ """.formatted(zoneId, recordName);++ try {+ createStack(stackName, template);+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);+ // AWS sends CREATE for a record the stack does not own yet, so the name being taken+ // fails the create and the rollback leaves the other owner's record alone.+ assertEquals("ROLLBACK_COMPLETE", state.status(), state.reason());+ assertTrue(state.reason().contains("already exists"), state.reason());+ String afterCreate = listResourceRecordSets(zoneId);+ assertTrue(afterCreate.contains("192.0.2.10"), "API record overwritten: " + afterCreate);+ assertFalse(afterCreate.contains("192.0.2.20"), "stack value written: " + afterCreate);+ } finally {+ deleteStack(stackName);+ CfnStackWaits.awaitStackDeleted(stackName);+ }++ String afterDelete = listResourceRecordSets(zoneId);+ assertTrue(afterDelete.contains("<Name>" + recordName + ".</Name>"), "API record deleted: " + afterDelete);+ assertTrue(afterDelete.contains("192.0.2.10"), "API record value lost: " + afterDelete);++ // A DELETE must name the record's current values, so it succeeding proves them unchanged.+ changeRecordSet(zoneId, "DELETE", recordName + ".", "192.0.2.10");+ given()+ .header("Authorization", ROUTE53_AUTH)+ .when().delete("/2013-04-01/hostedzone/" + zoneId)+ .then().statusCode(200);+ }++ private String createHostedZone(String zoneName, String callerReference) {+ String location = given()+ .contentType("application/xml")+ .header("Authorization", ROUTE53_AUTH)+ .body("""+ <?xml version="1.0" encoding="UTF-8"?>+ <CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">+ <Name>%s</Name>+ <CallerReference>%s</CallerReference>+ </CreateHostedZoneRequest>+ """.formatted(zoneName, callerReference))+ .when().post("/2013-04-01/hostedzone")+ .then().statusCode(201)+ .extract().header("Location");+ return location.substring(location.lastIndexOf('/') + 1);+ }++ private void changeRecordSet(String zoneId, String action, String name, String address) {+ given()+ .contentType("application/xml")+ .header("Authorization", ROUTE53_AUTH)+ .body("""+ <?xml version="1.0" encoding="UTF-8"?>+ <ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">+ <ChangeBatch>+ <Changes>+ <Change>+ <Action>%s</Action>+ <ResourceRecordSet>+ <Name>%s</Name>+ <Type>A</Type>+ <TTL>300</TTL>+ <ResourceRecords>+ <ResourceRecord><Value>%s</Value></ResourceRecord>+ </ResourceRecords>+ </ResourceRecordSet>+ </Change>+ </Changes>+ </ChangeBatch>+ </ChangeResourceRecordSetsRequest>+ """.formatted(action, name, address))+ .when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")+ .then().statusCode(200);+ }++ private void stackRequest(String action, String stackName, String template, String recordName, String address) {+ 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", "RecordName")+ .formParam("Parameters.member.1.ParameterValue", recordName)+ .formParam("Parameters.member.2.ParameterKey", "Address")+ .formParam("Parameters.member.2.ParameterValue", address)+ .when().post("/").then().statusCode(200);+ }+private String listResourceRecordSets(String zoneId) {return given().header("Authorization", ROUTE53_AUTH)diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisionerTest.javaindex 2fe9eddcde..9cf7b53d1e 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisionerTest.java@@ -21,6 +21,7 @@ import java.util.Set;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertNull;import static org.junit.jupiter.api.Assertions.assertSame;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;@@ -377,7 +378,7 @@ class Route53CfnProvisionerTest {}@Test- void recordSetIsUpsertedIntoItsZoneAndRefIsTheRecordName() {+ void recordSetIsCreatedInItsZoneAndRefIsTheRecordName() {Route53Service service = mock(Route53Service.class);ObjectMapper mapper = new ObjectMapper();JsonNode props = mapper.createObjectNode()@@ -404,9 +405,12 @@ class Route53CfnProvisionerTest {ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);verify(service).changeResourceRecordSets(eq("Z123456789"), captor.capture(), any());Map<String, Object> change = captor.getValue().get(0);- assertEquals("UPSERT", change.get("action"));+ // A CREATE, not an UPSERT: the stack does not own the record yet, so a record another owner+ // already holds under this name must fail the stack rather than be overwritten.+ assertEquals("CREATE", change.get("action"));ResourceRecordSet rrs = (ResourceRecordSet) change.get("rrs");- assertEquals("www.example.com", rrs.getName());+ // Route 53 stores and lists every record name fully qualified, whatever the template wrote.+ assertEquals("www.example.com.", rrs.getName());assertEquals("A", rrs.getType());assertEquals(Long.valueOf(300), rrs.getTtl());assertEquals(List.of("10.0.0.1"), rrs.getRecords().stream().map(ResourceRecord::getValue).toList());@@ -502,7 +506,7 @@ class Route53CfnProvisionerTest {void renamingARecordSetOnUpdateRemovesTheSupersededRecord() {Route53Service service = mock(Route53Service.class);ResourceRecordSet priorRecord = new ResourceRecordSet();- priorRecord.setName("auth.example.com");+ priorRecord.setName("auth.example.com.");priorRecord.setType("A");when(service.listResourceRecordSets("Z1", null, null, 0)).thenReturn(List.of(priorRecord));ObjectMapper mapper = new ObjectMapper();@@ -522,21 +526,82 @@ class Route53CfnProvisionerTest {new Route53CfnProvisioner(service).provision(resource, props, context);assertEquals("login.example.com", resource.getPhysicalId());- // Two changes: an UPSERT for the new name and a DELETE removing the record left under the old.+ // Two changes: a CREATE for the new name, which the stack does not own yet, and a DELETE+ // removing the record left under the old.@SuppressWarnings("unchecked")ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);verify(service, times(2)).changeResourceRecordSets(eq("Z1"), captor.capture(), any());List<String> actions = captor.getAllValues().stream().map(changes -> (String) changes.get(0).get("action")).toList();- assertTrue(actions.contains("UPSERT"), actions.toString());- assertTrue(actions.contains("DELETE"), actions.toString());+ assertEquals(List.of("CREATE", "DELETE"), actions);+ }++ @Test+ void anUpdateThatOnlyAddsTheTrailingDotKeepsTheRecord() {+ Route53Service service = mock(Route53Service.class);+ ResourceRecordSet stored = new ResourceRecordSet();+ stored.setName("www.example.com.");+ stored.setType("A");+ when(service.listResourceRecordSets("Z1", null, null, 0)).thenReturn(List.of(stored));+ ObjectMapper mapper = new ObjectMapper();+ JsonNode props = mapper.createObjectNode()+ .put("HostedZoneId", "Z1")+ .put("Name", "www.example.com.")+ .put("Type", "A");+ ProvisionContext context = new ProvisionContext(recordEngine(), "us-east-1", "623666680275",+ "dns-stack", "www.example.com");+ StackResource resource = new StackResource();+ resource.setLogicalId("Www");+ resource.setResourceType("AWS::Route53::RecordSet");+ resource.setPhysicalId("www.example.com");+ resource.getAttributes().put("__FlociRoute53RecordZoneId", "Z1");+ resource.getAttributes().put("__FlociRoute53RecordType", "A");++ new Route53CfnProvisioner(service).provision(resource, props, context);++ // Both names are the same record once fully qualified, so the UPSERT is the only change: a+ // DELETE of the "prior" name would remove the record the UPSERT just wrote.+ @SuppressWarnings("unchecked")+ ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);+ verify(service).changeResourceRecordSets(eq("Z1"), captor.capture(), any());+ assertEquals("UPSERT", captor.getValue().get(0).get("action"));+ }++ @Test+ void anUpdateWithABlankSetIdentifierKeepsTheRecordWithoutOne() {+ Route53Service service = mock(Route53Service.class);+ ObjectMapper mapper = new ObjectMapper();+ JsonNode props = mapper.createObjectNode()+ .put("HostedZoneId", "Z1")+ .put("Name", "www.example.com")+ .put("Type", "A")+ .put("SetIdentifier", "");+ ProvisionContext context = new ProvisionContext(recordEngine(), "us-east-1", "623666680275",+ "dns-stack", "www.example.com");+ StackResource resource = new StackResource();+ resource.setLogicalId("Www");+ resource.setResourceType("AWS::Route53::RecordSet");+ resource.setPhysicalId("www.example.com");+ resource.getAttributes().put("__FlociRoute53RecordZoneId", "Z1");+ resource.getAttributes().put("__FlociRoute53RecordType", "A");++ new Route53CfnProvisioner(service).provision(resource, props, context);++ // Route 53 requires a set identifier of at least one character, so a blank one is no+ // identifier: the record is the one the last provision wrote, re-applied in place.+ @SuppressWarnings("unchecked")+ ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);+ verify(service).changeResourceRecordSets(eq("Z1"), captor.capture(), any());+ Map<String, Object> change = captor.getValue().get(0);+ assertEquals("UPSERT", change.get("action"));+ assertNull(((ResourceRecordSet) change.get("rrs")).getSetIdentifier());}@Testvoid deletingARecordSetViaTheResourceIssuesAMatchingDeleteChange() {Route53Service service = mock(Route53Service.class);ResourceRecordSet existing = new ResourceRecordSet();- existing.setName("www.example.com");+ existing.setName("www.example.com.");existing.setType("A");when(service.listResourceRecordSets("Z123456789", null, null, 0)).thenReturn(List.of(existing));StackResource resource = new StackResource();@@ -556,6 +621,59 @@ class Route53CfnProvisionerTest {assertSame(existing, change.get("rrs"));}+ @Test+ void deletingFindsTheRecordAnEarlierVersionStoredAsWritten() {+ Route53Service service = mock(Route53Service.class);+ // An earlier version stored the template's undotted Name and blank SetIdentifier as written.+ ResourceRecordSet legacy = new ResourceRecordSet();+ legacy.setName("www.example.com");+ legacy.setType("A");+ legacy.setSetIdentifier("");+ when(service.listResourceRecordSets("Z1", null, null, 0)).thenReturn(List.of(legacy));+ StackResource resource = new StackResource();+ resource.setLogicalId("Www");+ resource.setResourceType("AWS::Route53::RecordSet");+ resource.setPhysicalId("www.example.com");+ resource.getAttributes().put("__FlociRoute53RecordZoneId", "Z1");+ resource.getAttributes().put("__FlociRoute53RecordType", "A");++ new Route53CfnProvisioner(service).delete(resource, "us-east-1");++ @SuppressWarnings("unchecked")+ ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);+ verify(service).changeResourceRecordSets(eq("Z1"), captor.capture(), any());+ Map<String, Object> change = captor.getValue().get(0);+ assertEquals("DELETE", change.get("action"));+ assertSame(legacy, change.get("rrs"));+ }++ @Test+ void deletingPrefersTheCopyNamedAsThePhysicalIdWhenAnEarlierVersionStoredBoth() {+ Route53Service service = mock(Route53Service.class);+ // An earlier version compared names literally, so another owner's undotted record and this+ // stack's dotted one can both be stored. The listing sorts the undotted one first.+ ResourceRecordSet otherOwners = new ResourceRecordSet();+ otherOwners.setName("www.example.com");+ otherOwners.setType("A");+ ResourceRecordSet own = new ResourceRecordSet();+ own.setName("www.example.com.");+ own.setType("A");+ when(service.listResourceRecordSets("Z1", null, null, 0)).thenReturn(List.of(otherOwners, own));+ StackResource resource = new StackResource();+ resource.setLogicalId("Www");+ resource.setResourceType("AWS::Route53::RecordSet");+ resource.setPhysicalId("www.example.com.");+ resource.getAttributes().put("__FlociRoute53RecordZoneId", "Z1");+ resource.getAttributes().put("__FlociRoute53RecordType", "A");++ new Route53CfnProvisioner(service).delete(resource, "us-east-1");++ @SuppressWarnings("unchecked")+ ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);+ verify(service).changeResourceRecordSets(eq("Z1"), captor.capture(), any());+ assertSame(own, captor.getValue().get(0).get("rrs"));+ }+@Testvoid deletingARecordSetToleratesAZoneAlreadyGone() {Route53Service service = mock(Route53Service.class);diff --git a/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.javaindex fcde0fef51..643d9e48f7 100644--- a/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.java@@ -31,10 +31,16 @@ class Route53ServiceTest {private static final String ACCOUNT = "000000000000";+ private final Map<String, AccountAwareStorageBackend<?>> stores = new HashMap<>();+private Route53Service newService() {StorageFactory storageFactory = Mockito.mock(StorageFactory.class);Mockito.when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))- .thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT));+ .thenAnswer(invocation -> {+ AccountAwareStorageBackend<Object> store = AccountAwareStorageBackend.inMemory(ACCOUNT);+ stores.put(invocation.getArgument(1), store);+ return store;+ });EmulatorConfig config = Mockito.mock(EmulatorConfig.class);EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);@@ -249,6 +255,66 @@ class Route53ServiceTest {assertThat(records, hasSize(1));}+ @Test+ void aNameWithOrWithoutTheTrailingDotAndABlankSetIdentifierAreTheSameRecord() {+ Route53Service service = newService();+ String zoneId = service.createHostedZone("example.com.", "ref-fqdn", null, null).zone().getId();+ // How an earlier CloudFormation provisioner stored a record: the template's undotted Name and+ // empty SetIdentifier, as written.+ ResourceRecordSet legacy = aRecord("www.example.com", 300, "1.2.3.4");+ legacy.setSetIdentifier("");+ service.changeResourceRecordSets(zoneId, List.of(change("CREATE", legacy)), null);++ AwsException e = assertThrows(AwsException.class, () -> service.changeResourceRecordSets(zoneId,+ List.of(change("CREATE", aRecord("www.example.com.", 300, "5.6.7.8"))), null));+ assertEquals("InvalidChangeBatch", e.getErrorCode());++ service.changeResourceRecordSets(zoneId,+ List.of(change("UPSERT", aRecord("www.example.com.", 300, "5.6.7.8"))), null);+ List<ResourceRecordSet> records = typeARecords(service, zoneId);+ assertThat(records, hasSize(1));+ assertEquals("www.example.com.", records.get(0).getName());+ assertEquals("5.6.7.8", records.get(0).getRecords().get(0).getValue());++ ResourceRecordSet undotted = aRecord("www.example.com", 300, "5.6.7.8");+ undotted.setSetIdentifier("");+ service.changeResourceRecordSets(zoneId, List.of(change("DELETE", undotted)), null);+ assertThat(typeARecords(service, zoneId), empty());+ }++ @Test+ void aDeleteRemovesOneRecordWhenAnEarlierVersionLeftItStoredBothWays() {+ Route53Service service = newService();+ String zoneId = service.createHostedZone("example.com.", "ref-twins", null, null).zone().getId();+ // An earlier version compared names literally, so a stack's undotted record and an API caller's+ // dotted one could both be stored, with the same values.+ ResourceRecordSet legacy = aRecord("www.example.com", 300, "1.2.3.4");+ legacy.setSetIdentifier("");+ @SuppressWarnings("unchecked")+ AccountAwareStorageBackend<List<ResourceRecordSet>> recordStore =+ (AccountAwareStorageBackend<List<ResourceRecordSet>>) stores.get("route53-records.json");+ List<ResourceRecordSet> seeded = new ArrayList<>(recordStore.get(zoneId).orElseThrow());+ seeded.add(legacy);+ seeded.add(aRecord("www.example.com.", 300, "1.2.3.4"));+ recordStore.put(zoneId, seeded);++ service.changeResourceRecordSets(zoneId,+ List.of(change("DELETE", aRecord("www.example.com.", 300, "1.2.3.4"))), null);+ List<ResourceRecordSet> records = typeARecords(service, zoneId);+ assertThat(records, hasSize(1));+ assertEquals("www.example.com", records.get(0).getName());++ service.changeResourceRecordSets(zoneId,+ List.of(change("DELETE", aRecord("www.example.com.", 300, "1.2.3.4"))), null);+ assertThat(typeARecords(service, zoneId), empty());+ }++ private static List<ResourceRecordSet> typeARecords(Route53Service service, String zoneId) {+ return service.listResourceRecordSets(zoneId, null, null, 0).stream()+ .filter(rrs -> "A".equals(rrs.getType()))+ .toList();+ }+@Testvoid deleteThenCreateOfSameNameAndTypeInOneBatchSucceeds() {Route53Service service = newService();