Light, fluffy, and always free - The AWS Local Emulator alternative
fix(route53): normalize record name case identity (#6374)
Andre Kurait18910223e1ca
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Route53RecordCaseTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Route53RecordCaseTest.javanew file mode 100644index 0000000000..121fc5a8b4--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Route53RecordCaseTest.java@@ -0,0 +1,70 @@+package com.floci.test;++import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.route53.Route53Client;+import software.amazon.awssdk.services.route53.model.Change;+import software.amazon.awssdk.services.route53.model.ChangeAction;+import software.amazon.awssdk.services.route53.model.ResourceRecord;+import software.amazon.awssdk.services.route53.model.ResourceRecordSet;+import software.amazon.awssdk.services.route53.model.Route53Exception;++import java.util.List;+import java.util.Locale;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.catchThrowableOfType;++class Route53RecordCaseTest {++ @Test+ void changeBatchUsesLowercaseNameIdentityAndPreservesValues() {+ try (Route53Client client = TestFixtures.route53Client()) {+ String zoneName = TestFixtures.uniqueName("record-case") + ".example.com";+ String zoneId = client.createHostedZone(request -> request.name(zoneName)+ .callerReference(TestFixtures.uniqueName("record-case-ref"))).hostedZone().id();+ try {+ String name = "www." + zoneName + ".";+ ResourceRecordSet initial = record(name.toUpperCase(Locale.ROOT), "192.0.2.1");+ change(client, zoneId, ChangeAction.CREATE, initial);+ assertThat(records(client, zoneId)).singleElement()+ .satisfies(actual -> assertThat(actual.name()).isEqualTo(name));+ Route53Exception duplicate = catchThrowableOfType(() -> change(client, zoneId,+ ChangeAction.CREATE, record(name, "192.0.2.2")), Route53Exception.class);+ assertThat(duplicate).isNotNull();+ assertThat(duplicate.awsErrorDetails().errorCode()).isEqualTo("InvalidChangeBatch");+ change(client, zoneId, ChangeAction.UPSERT, record(name, "192.0.2.2"));+ assertThat(records(client, zoneId)).singleElement().satisfies(actual -> {+ assertThat(actual.name()).isEqualTo(name);+ assertThat(actual.resourceRecords()).extracting(ResourceRecord::value).containsExactly("192.0.2.2");+ });+ Route53Exception mismatch = catchThrowableOfType(() -> change(client, zoneId,+ ChangeAction.DELETE, initial), Route53Exception.class);+ assertThat(mismatch).isNotNull();+ assertThat(mismatch.awsErrorDetails().errorCode()).isEqualTo("InvalidChangeBatch");+ change(client, zoneId, ChangeAction.DELETE,+ record(name.toUpperCase(Locale.ROOT), "192.0.2.2"));+ assertThat(records(client, zoneId)).isEmpty();+ } finally {+ for (ResourceRecordSet record : records(client, zoneId)) {+ change(client, zoneId, ChangeAction.DELETE, record);+ }+ client.deleteHostedZone(request -> request.id(zoneId));+ }+ }+ }++ private static ResourceRecordSet record(String name, String value) {+ return ResourceRecordSet.builder().name(name).type("A").ttl(60L)+ .resourceRecords(ResourceRecord.builder().value(value).build()).build();+ }++ private static List<ResourceRecordSet> records(Route53Client client, String zoneId) {+ return client.listResourceRecordSets(request -> request.hostedZoneId(zoneId))+ .resourceRecordSets().stream().filter(record -> "A".equals(record.typeAsString())).toList();+ }++ private static void change(Route53Client client, String zoneId, ChangeAction action, ResourceRecordSet record) {+ client.changeResourceRecordSets(request -> request.hostedZoneId(zoneId)+ .changeBatch(batch -> batch.changes(Change.builder().action(action).resourceRecordSet(record).build())));+ }+}diff --git a/docs/services/route53.md b/docs/services/route53.mdindex 354e1955ad..c64d2c7c81 100644--- a/docs/services/route53.md+++ b/docs/services/route53.md@@ -167,6 +167,11 @@ aws route53 disassociate-vpc-from-hosted-zone \aws route53 delete-hosted-zone --id Z1PA6795UKMFR9```+Record names in change batches are stored with lowercase ASCII letters and a trailing dot.+CREATE, UPSERT, and DELETE use that name identity while keeping the record type and+routing set identifier distinct. A case-only CloudFormation record-name update retains+the record. DELETE still requires matching record values and routing properties.+## Not Supported (Phase 2)- Reusable delegation setsdiff --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 6a58b7ae05..1b4ff8fbc8 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@@ -173,7 +173,8 @@ public class Route53CfnProvisioner implements CfnResourceProvisioner {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()))+ && Route53Service.normalizeRecordName(name)+ .equals(Route53Service.normalizeRecordName(ctx.priorPhysicalId()))&& type.equals(priorAttributes.get(RECORD_TYPE_ATTR))&& Objects.equals(priorAttributes.get(RECORD_SET_ID_ATTR), setIdentifier);}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 89f2196c42..89c29b7dd4 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@@ -430,17 +430,17 @@ public class Route53Service implements Resettable {recordStore.get(zoneId).orElse(List.of()));records.sort((a, b) -> {- int cmp = a.getName().compareTo(b.getName());+ int cmp = normalizeRecordName(a.getName()).compareTo(normalizeRecordName(b.getName()));if (cmp != 0) return cmp;return a.getType().compareTo(b.getType());});if (startName != null && !startName.isEmpty()) {- String normalizedStart = normalizeName(startName);+ String normalizedStart = normalizeRecordName(startName);final String finalStartType = startType;records = records.stream().filter(r -> {- int cmp = r.getName().compareTo(normalizedStart);+ int cmp = normalizeRecordName(r.getName()).compareTo(normalizedStart);if (cmp > 0) return true;if (cmp == 0 && finalStartType != null && !finalStartType.isEmpty()) {return r.getType().compareTo(finalStartType) >= 0;@@ -889,6 +889,18 @@ public class Route53Service implements Resettable {return name.endsWith(".") ? name : name + ".";}+ public static String normalizeRecordName(String name) {+ String normalized = normalizeName(name);+ if (normalized == null) {+ return null;+ }+ StringBuilder result = new StringBuilder(normalized.length());+ for (int i = 0; i < normalized.length(); i++) {+ result.append(asciiLower(normalized.charAt(i)));+ }+ return result.toString();+ }+private static String generateZoneId() {StringBuilder sb = new StringBuilder("Z");for (int i = 0; i < 14; i++) {@@ -936,7 +948,7 @@ public class Route53Service implements Resettable {}private boolean isApexSoaOrNs(ResourceRecordSet rrs, String zoneName) {- return rrs.getName().equals(zoneName) &&+ return normalizeRecordName(rrs.getName()).equals(normalizeRecordName(zoneName)) &&("SOA".equals(rrs.getType()) || "NS".equals(rrs.getType()));}@@ -975,23 +987,29 @@ public class Route53Service implements Resettable {private void applyChange(String action, ResourceRecordSet rrs, List<ResourceRecordSet> current) {switch (action) {- case "CREATE" -> current.add(rrs);+ case "CREATE" -> {+ ResourceRecordSet normalized = new ResourceRecordSet(rrs);+ normalized.setName(normalizeRecordName(rrs.getName()));+ current.add(normalized);+ }case "DELETE" -> current.remove(deleteTarget(current, rrs));case "UPSERT" -> {current.removeIf(r -> sameRecord(r, rrs));- current.add(rrs);+ ResourceRecordSet normalized = new ResourceRecordSet(rrs);+ normalized.setName(normalizeRecordName(rrs.getName()));+ current.add(normalized);}}}/*** 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+ * name with ASCII case differences 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()))+ return normalizeRecordName(a.getName()).equals(normalizeRecordName(b.getName()))&& a.getType().equals(b.getType())&& Objects.equals(blankToNull(a.getSetIdentifier()), blankToNull(b.getSetIdentifier()));}@@ -1038,20 +1056,7 @@ public class Route53Service implements Resettable {}private static boolean aliasDnsNamesMatch(String a, String b) {- if (a == null || b == null) {- return a == b;- }- String left = normalizeName(a);- String right = normalizeName(b);- if (left.length() != right.length()) {- return false;- }- for (int i = 0; i < left.length(); i++) {- if (asciiLower(left.charAt(i)) != asciiLower(right.charAt(i))) {- return false;- }- }- return true;+ return Objects.equals(normalizeRecordName(a), normalizeRecordName(b));}private static char asciiLower(char c) {diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/model/ResourceRecordSet.java b/src/main/java/io/github/hectorvent/floci/services/route53/model/ResourceRecordSet.javaindex f51b1a43c7..4f17679c76 100644--- a/src/main/java/io/github/hectorvent/floci/services/route53/model/ResourceRecordSet.java+++ b/src/main/java/io/github/hectorvent/floci/services/route53/model/ResourceRecordSet.java@@ -20,6 +20,19 @@ public class ResourceRecordSet {public ResourceRecordSet() {}+ public ResourceRecordSet(ResourceRecordSet source) {+ name = source.name;+ type = source.type;+ ttl = source.ttl;+ records = source.records;+ aliasTarget = source.aliasTarget;+ weight = source.weight;+ region = source.region;+ setIdentifier = source.setIdentifier;+ failover = source.failover;+ healthCheckId = source.healthCheckId;+ }+public String getName() { return name; }public void setName(String name) { this.name = name; }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 32399f88d4..fe6a83da5f 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@@ -134,6 +134,13 @@ class CloudFormationRoute53RecordSetIntegrationTest {assertTrue(created.contains("<Name>" + firstName + ".</Name>"), "name not fully qualified: " + created);assertFalse(created.contains("<Name>" + firstName + "</Name>"), "name stored as written: " + created);+ stackRequest("UpdateStack", stackName, template, "WWW." + zoneName, "10.0.0.3");+ assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());+ String caseUpdated = listResourceRecordSets(zoneId);+ assertTrue(caseUpdated.contains("<Name>" + firstName + ".</Name>"),+ "case-only update lost its record: " + caseUpdated);+ assertTrue(caseUpdated.contains("10.0.0.3"), "case-only update lost its value: " + caseUpdated);+// 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());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 08b2fa59e5..8113837576 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@@ -13,6 +13,8 @@ import io.github.hectorvent.floci.services.route53.model.ResourceRecord;import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet;import io.github.hectorvent.floci.services.route53.model.VpcAssociation;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;import org.mockito.ArgumentCaptor;import java.util.ArrayList;@@ -540,8 +542,9 @@ class Route53CfnProvisionerTest {assertEquals(List.of("CREATE", "DELETE"), actions);}- @Test- void anUpdateThatOnlyAddsTheTrailingDotKeepsTheRecord() {+ @ParameterizedTest+ @ValueSource(strings = {"www.example.com.", "WWW.EXAMPLE.COM."})+ void anUpdateThatOnlyChangesNameIdentityKeepsTheRecord(String recordName) {Route53Service service = mock(Route53Service.class);ResourceRecordSet stored = new ResourceRecordSet();stored.setName("www.example.com.");@@ -550,7 +553,7 @@ class Route53CfnProvisionerTest {ObjectMapper mapper = new ObjectMapper();JsonNode props = mapper.createObjectNode().put("HostedZoneId", "Z1")- .put("Name", "www.example.com.")+ .put("Name", recordName).put("Type", "A");ProvisionContext context = new ProvisionContext(recordEngine(), "us-east-1", "623666680275","dns-stack", "www.example.com");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 9dbed52c3e..b7877b7cb8 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@@ -66,6 +66,25 @@ class Route53ServiceTest {return new Route53Service(storageFactory, config, regionResolver, ec2Service);}+ @Test+ void rejectedBatchDoesNotRenameSharedStoredRecord() {+ Route53Service service = newService();+ String zone = service.createHostedZone("EXAMPLE.COM", "shared-record", null, null).zone().getId();+ ResourceRecordSet stored = service.listResourceRecordSets(zone, null, null, 100).stream()+ .filter(record -> "NS".equals(record.getType())).findFirst().orElseThrow();+ String originalName = stored.getName();+ assertEquals("EXAMPLE.COM.", originalName);+ assertThrows(AwsException.class, () -> service.changeResourceRecordSets(zone,+ List.of(change("UPSERT", stored), change("DELETE", aRecord("missing.example.com.", 60, "192.0.2.1"))), null));+ assertEquals(originalName, stored.getName());+ assertEquals(originalName, service.listResourceRecordSets(zone, null, null, 100).stream()+ .filter(record -> "NS".equals(record.getType())).findFirst().orElseThrow().getName());+ service.changeResourceRecordSets(zone, List.of(change("UPSERT", stored)), null);+ assertEquals(originalName, stored.getName());+ assertEquals("example.com.", service.listResourceRecordSets(zone, null, null, 100).stream()+ .filter(record -> "NS".equals(record.getType())).findFirst().orElseThrow().getName());+ }+@Testvoid publicZoneIndexAvoidsStorageScansOutsideOwnedNamesAndTracksDeletion() {Route53Service service = newService();@@ -87,6 +106,81 @@ class Route53ServiceTest {Mockito.verifyNoInteractions(zones);}+ @Test+ void recordIdentityFoldsOnlyAsciiLettersAndPreservesPolicyIdentity() {+ ResourceRecordSet upper = weightedRecord("WWW.example.com", 60, "Blue", 1, "192.0.2.1");+ ResourceRecordSet lower = weightedRecord("www.example.com.", 60, "Blue", 1, "192.0.2.1");+ assertTrue(Route53Service.sameRecord(upper, lower));+ lower.setSetIdentifier("blue");+ assertFalse(Route53Service.sameRecord(upper, lower));+ lower.setSetIdentifier("Blue");+ lower.setType("AAAA");+ assertFalse(Route53Service.sameRecord(upper, lower));+ assertFalse(Route53Service.sameRecord(aRecord("Ä.example", 60), aRecord("ä.example", 60)));+ assertFalse(Route53Service.sameRecord(aRecord("\\127.example", 60), aRecord("w.example", 60)));+ }++ @Test+ void caseVariantCreateCannotDuplicateOrPartiallyCommitBatch() {+ Route53Service service = newService();+ String zone = service.createHostedZone("example.com", "case-duplicate", null, null).zone().getId();+ service.changeResourceRecordSets(zone, List.of(change("CREATE", aRecord("www.example.com", 60, "192.0.2.1"))), null);+ AwsException error = assertThrows(AwsException.class, () -> service.changeResourceRecordSets(zone, List.of(+ change("CREATE", aRecord("other.example.com", 60, "192.0.2.2")),+ change("CREATE", aRecord("WWW.EXAMPLE.COM.", 60, "192.0.2.3"))), null));+ assertEquals("InvalidChangeBatch", error.getErrorCode());+ assertEquals(3, service.listResourceRecordSets(zone, null, null, 100).size());+ }++ @Test+ void caseVariantUpsertAndDeleteRetainWeightedSiblingAndRejectWrongValue() {+ Route53Service service = newService();+ String zone = service.createHostedZone("example.com", "case-weight", null, null).zone().getId();+ service.changeResourceRecordSets(zone, List.of(+ change("CREATE", weightedRecord("WWW.example.com", 60, "Blue", 1, "192.0.2.1")),+ change("CREATE", weightedRecord("www.example.com", 60, "blue", 2, "192.0.2.2"))), null);+ service.changeResourceRecordSets(zone, List.of(change("UPSERT",+ weightedRecord("WwW.example.com", 60, "Blue", 3, "192.0.2.3"))), null);+ assertEquals(4, service.listResourceRecordSets(zone, null, null, 100).size());+ assertThrows(AwsException.class, () -> service.changeResourceRecordSets(zone, List.of(change("DELETE",+ weightedRecord("WWW.example.com", 60, "Blue", 3, "192.0.2.4"))), null));+ service.changeResourceRecordSets(zone, List.of(change("DELETE",+ weightedRecord("WWW.example.com", 60, "Blue", 3, "192.0.2.3"))), null);+ List<ResourceRecordSet> remaining = service.listResourceRecordSets(zone, "www.example.com", "A", 100);+ assertEquals(1, remaining.size());+ assertEquals("blue", remaining.getFirst().getSetIdentifier());+ assertEquals("www.example.com.", remaining.getFirst().getName());+ }++ @Test+ void caseVariantApexDeleteRemainsForbidden() {+ Route53Service service = newService();+ String zone = service.createHostedZone("Example.COM", "case-apex", null, null).zone().getId();+ ResourceRecordSet ns = service.listResourceRecordSets(zone, null, null, 100).stream()+ .filter(record -> "NS".equals(record.getType())).findFirst().orElseThrow();+ ResourceRecordSet request = new ResourceRecordSet();+ request.setName("EXAMPLE.com");+ request.setType("NS");+ request.setTtl(ns.getTtl());+ request.setRecords(ns.getRecords());+ AwsException error = assertThrows(AwsException.class, () -> service.changeResourceRecordSets(+ zone, List.of(change("DELETE", request)), null));+ assertTrue(error.getMessage().contains("apex"));+ assertEquals(2, service.listResourceRecordSets(zone, null, null, 100).size());+ }++ @Test+ void recordListingSortsAndFiltersWithTheSameNormalizedName() {+ Route53Service service = newService();+ String zone = service.createHostedZone("EXAMPLE.com", "case-page", null, null).zone().getId();+ service.changeResourceRecordSets(zone, List.of(change("CREATE",+ aRecord("a.example.com", 60, "192.0.2.1"))), null);+ List<ResourceRecordSet> page = service.listResourceRecordSets(zone, "A.EXAMPLE.COM", "A", 1);+ assertEquals(1, page.size());+ assertEquals("a.example.com.", page.getFirst().getName());+ assertEquals("A", page.getFirst().getType());+ }+private static Map<String, Object> change(String action, ResourceRecordSet rrs) {Map<String, Object> m = new HashMap<>();m.put("action", action);