fix(route53): require exact match for ChangeResourceRecordSets DELETE (#3565)

* fix(route53): require exact match for ChangeResourceRecordSets DELETE

DELETE validation only compared record name and type, so a DELETE
naming the wrong TTL, values, alias target, routing fields or set
identifier could remove an existing record set as long as the name
and type happened to match. AWS requires a DELETE to specify every
value used to create the record; a mismatch on any of them fails
with InvalidChangeBatch, using one of two different messages, with
no trailing period: "not found" when no record shares the same
name, type and set identifier, or "the values provided do not match
the current values" when one does but another field differs. Both
messages include the set identifier when the deleted record
specifies one.

Add an exact-match comparison covering TTL, resource record values
(order-independent), alias target, weight, region, failover, health
check ID and set identifier, and use it for both the DELETE
existence check and the removal itself.

Batch changes are now validated and applied sequentially against a
running copy of the zone's records, rather than validated as a whole
against the pre-batch snapshot and then applied. This matches two
documented AWS behaviors: deleting the same record set twice in one
batch now fails with InvalidChangeBatch, and a DELETE followed by a
CREATE of the same name and type in one batch (the standard replace
pattern) now succeeds. The batch is still applied atomically: the
running copy is a local list and the stores are only written once
every change in the batch has succeeded.

Also stop silently swallowing ChangeBatch parsing errors: malformed
XML, a Change missing its Action or ResourceRecordSet, an action
outside CREATE/DELETE/UPSERT, and a non-numeric TTL or Weight now
fail with InvalidInput instead of being ignored or dropped. A
ResourceRecordSet must also specify exactly one of AliasTarget or
TTL and ResourceRecords, matching AWS's structural requirement: real
AWS only rejects a ResourceRecordSet as having more than one shape
when AliasTarget and ResourceRecords are both present, so AliasTarget
combined with TTL alone remains valid. A ChangeBatch with no Changes
is rejected with InvalidInput instead of returning success and
applying nothing, using AWS's own schema-validation wire message for
an empty Changes element, built from the same Route53 namespace
constant used elsewhere in these responses.

* fix(route53): reject AliasTarget combined with TTL
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-14 15:18:53 -04:00
1 parent 2f76640aa8
commit 9da589568d
4 files changed
+814 -26

No files matched your search

@@ -61,6 +61,8 @@ public class Route53Controller {
"af-south-1", "eu-south-1", "eu-south-2",
"il-central-1", "mx-central-1");
private static final Set<String> CHANGE_ACTIONS = Set.of("CREATE", "DELETE", "UPSERT");
@Inject
Route53Service service;
@@ -893,14 +895,42 @@ public class Route53Controller {
}
}
private static void requireExactlyOneRecordShape(String action, ResourceRecordSet rrs, boolean hasRecords) {
boolean hasAlias = rrs.getAliasTarget() != null;
boolean hasTtl = rrs.getTtl() != null;
String found;
if (hasAlias && (hasTtl || hasRecords)) {
found = "more than one";
} else if (!hasAlias && !(hasTtl && hasRecords)) {
found = "none";
} else {
return;
}
throw new AwsException("InvalidInput",
"Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], "
+ "or TrafficPolicyInstanceId], but found " + found + " in Change with [Action=" + action
+ ", Name=" + rrs.getName() + ", Type=" + rrs.getType()
+ ", SetIdentifier=" + rrs.getSetIdentifier() + "]", 400);
}
/**
* Parses the ChangeBatch XML using StAX to correctly handle multiple Change elements,
* each containing a ResourceRecordSet with its own set of ResourceRecord/Value children.
*/
private List<Map<String, Object>> parseChangeBatch(String body) {
List<Map<String, Object>> result = new ArrayList<>();
if (body == null || body.isEmpty()) return result;
if (body != null && !body.isEmpty()) {
parseChangeBatchInto(body, result);
}
if (result.isEmpty()) {
throw new AwsException("InvalidInput",
"Invalid XML ; cvc-complex-type.2.4.b: The content of element 'Changes' is not complete. "
+ "One of '{\"" + NS + "\":Change}' is expected.", 400);
}
return result;
}
private void parseChangeBatchInto(String body, List<Map<String, Object>> result) {
try {
XMLStreamReader r = XmlParser.newStreamReader(body);
String currentAction = null;
@@ -930,7 +960,14 @@ public class Route53Controller {
}
}
case "Action" -> {
if (inChange && !inRrs) currentAction = r.getElementText();
if (inChange && !inRrs) {
currentAction = r.getElementText();
if (!CHANGE_ACTIONS.contains(currentAction)) {
throw new AwsException("InvalidInput",
"Invalid value '" + currentAction + "' at 'Action' failed to satisfy "
+ "constraint: Member must satisfy enum value set.", 400);
}
}
}
case "ResourceRecordSet" -> {
if (inChange) {
@@ -960,8 +997,14 @@ public class Route53Controller {
}
case "TTL" -> {
if (inRrs && currentRrs != null) {
try { currentRrs.setTtl(Long.parseLong(r.getElementText())); }
catch (NumberFormatException ignored) {}
String ttl = r.getElementText();
try {
currentRrs.setTtl(Long.parseLong(ttl));
} catch (NumberFormatException e) {
throw new AwsException("InvalidInput",
"Invalid value '" + ttl + "' at 'TTL' failed to satisfy constraint: "
+ "Member must be a valid long.", 400);
}
}
}
case "Value" -> {
@@ -974,8 +1017,14 @@ public class Route53Controller {
}
case "Weight" -> {
if (inRrs && currentRrs != null) {
try { currentRrs.setWeight(Long.parseLong(r.getElementText())); }
catch (NumberFormatException ignored) {}
String weight = r.getElementText();
try {
currentRrs.setWeight(Long.parseLong(weight));
} catch (NumberFormatException e) {
throw new AwsException("InvalidInput",
"Invalid value '" + weight + "' at 'Weight' failed to satisfy "
+ "constraint: Member must be a valid long.", 400);
}
}
}
case "Region" -> {
@@ -1013,13 +1062,26 @@ public class Route53Controller {
currentAlias = null;
}
case "ResourceRecordSet" -> {
if (inRrs && currentRrs != null && currentRecords != null) {
if (!currentRecords.isEmpty()) currentRrs.setRecords(currentRecords);
if (inRrs && currentRrs != null) {
if (currentRrs.getName() == null || currentRrs.getType() == null) {
throw new AwsException("InvalidInput",
"ResourceRecordSet is missing a required Name or Type element.", 400);
}
boolean hasRecords = currentRecords != null && !currentRecords.isEmpty();
if (hasRecords) {
currentRrs.setRecords(currentRecords);
}
requireExactlyOneRecordShape(currentAction, currentRrs, hasRecords);
}
inRrs = false;
}
case "Change" -> {
if (inChange && currentAction != null && currentRrs != null) {
if (inChange) {
if (currentAction == null || currentRrs == null) {
throw new AwsException("InvalidInput",
"Change is missing a required Action or ResourceRecordSet element.",
400);
}
Map<String, Object> change = new HashMap<>();
change.put("action", currentAction);
change.put("rrs", currentRrs);
@@ -1034,8 +1096,11 @@ public class Route53Controller {
}
}
r.close();
} catch (Exception ignored) {}
return result;
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("InvalidInput", "The XML you provided was not well-formed.", 400);
}
}
private HealthCheckConfig parseHealthCheckConfig(String body) {
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.route53.model.AliasTarget;
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;
@@ -25,6 +26,7 @@ import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@@ -385,17 +387,10 @@ public class Route53Service {
List<ResourceRecordSet> current = new ArrayList<>(
recordStore.get(zoneId).orElse(new ArrayList<>()));
// Validate all changes before applying any
for (Map<String, Object> change : changes) {
String action = (String) change.get("action");
ResourceRecordSet rrs = (ResourceRecordSet) change.get("rrs");
validateChange(action, rrs, current, zone.getName());
}
// Apply all changes
for (Map<String, Object> change : changes) {
String action = (String) change.get("action");
ResourceRecordSet rrs = (ResourceRecordSet) change.get("rrs");
applyChange(action, rrs, current);
}
@@ -774,12 +769,16 @@ public class Route53Service {
}
}
if ("DELETE".equals(action)) {
boolean found = current.stream().anyMatch(r ->
r.getName().equals(rrs.getName()) && r.getType().equals(rrs.getType()));
if (!found) {
ResourceRecordSet existing = findByNameTypeAndSetIdentifier(current, rrs);
if (existing == null) {
throw new AwsException("InvalidChangeBatch",
"Tried to delete resource record set [name='" + rrs.getName() +
"', type='" + rrs.getType() + "'] but it was not found.", 400);
"Tried to delete resource record set " + deleteTargetDescription(rrs)
+ " but it was not found", 400);
}
if (!recordSetsMatch(existing, rrs)) {
throw new AwsException("InvalidChangeBatch",
"Tried to delete resource record set " + deleteTargetDescription(rrs)
+ " but the values provided do not match the current values", 400);
}
}
}
@@ -787,9 +786,7 @@ public class Route53Service {
private void applyChange(String action, ResourceRecordSet rrs, List<ResourceRecordSet> current) {
switch (action) {
case "CREATE" -> current.add(rrs);
case "DELETE" -> current.removeIf(r ->
r.getName().equals(rrs.getName()) && r.getType().equals(rrs.getType()) &&
equalOrNull(r.getSetIdentifier(), rrs.getSetIdentifier()));
case "DELETE" -> current.removeIf(r -> recordSetsMatch(r, rrs));
case "UPSERT" -> {
current.removeIf(r ->
r.getName().equals(rrs.getName()) && r.getType().equals(rrs.getType()) &&
@@ -804,4 +801,50 @@ public class Route53Service {
if (a == null || b == null) return false;
return a.equals(b);
}
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);
}
private static String deleteTargetDescription(ResourceRecordSet rrs) {
String description = "[name='" + rrs.getName() + "', type='" + rrs.getType() + "'";
if (rrs.getSetIdentifier() != null) {
description += ", set-identifier='" + rrs.getSetIdentifier() + "'";
}
return description + "]";
}
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())
&& Objects.equals(a.getTtl(), b.getTtl())
&& Objects.equals(a.getWeight(), b.getWeight())
&& Objects.equals(a.getRegion(), b.getRegion())
&& Objects.equals(a.getFailover(), b.getFailover())
&& Objects.equals(a.getHealthCheckId(), b.getHealthCheckId())
&& aliasTargetsMatch(a.getAliasTarget(), b.getAliasTarget())
&& recordValuesMatch(a.getRecords(), b.getRecords());
}
private static boolean aliasTargetsMatch(AliasTarget a, AliasTarget b) {
if (a == null || b == null) {
return a == b;
}
return Objects.equals(a.getHostedZoneId(), b.getHostedZoneId())
&& Objects.equals(a.getDnsName(), b.getDnsName())
&& a.isEvaluateTargetHealth() == b.isEvaluateTargetHealth();
}
private static boolean recordValuesMatch(List<ResourceRecord> a, List<ResourceRecord> b) {
List<String> av = a == null ? List.of() : a.stream().map(ResourceRecord::getValue).sorted().toList();
List<String> bv = b == null ? List.of() : b.stream().map(ResourceRecord::getValue).sorted().toList();
return av.equals(bv);
}
}
@@ -0,0 +1,414 @@
package io.github.hectorvent.floci.services.route53;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
@QuarkusTest
class Route53ChangeResourceRecordSetsIntegrationTest {
private static final String XML = "application/xml";
@Test
void malformedChangeBatchIsRejectedAsInvalidInput() {
String zoneId = createZone("malformed.example.com.", "ref-malformed");
String body = """
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
<Name>www.malformed.example.com.</Name>
<Type>A
""";
given().contentType(XML)
.body(body)
.when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
given().get("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then().statusCode(200)
.body(not(containsString("www.malformed.example.com.")));
}
@Test
void incompleteChangeMissingResourceRecordSetIsRejectedAsInvalidInput() {
String zoneId = createZone("incomplete.example.com.", "ref-incomplete");
String body = """
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
<Change>
<Action>CREATE</Action>
</Change>
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""";
given().contentType(XML)
.body(body)
.when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
}
@Test
void unknownActionIsRejectedAsInvalidInput() {
String zoneId = createZone("unknownaction.example.com.", "ref-unknown-action");
String body = """
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
<Change>
<Action>REPLACE</Action>
<ResourceRecordSet>
<Name>www.unknownaction.example.com.</Name>
<Type>A</Type>
<TTL>300</TTL>
<ResourceRecords>
<ResourceRecord><Value>1.2.3.4</Value></ResourceRecord>
</ResourceRecords>
</ResourceRecordSet>
</Change>
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""";
given().contentType(XML)
.body(body)
.when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"));
given().get("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then().statusCode(200)
.body(not(containsString("www.unknownaction.example.com.")));
}
@Test
void deleteWithMismatchedValueIsRejectedAsInvalidChangeBatchOnTheWire() {
String zoneId = createZone("wiremismatch.example.com.", "ref-wire-mismatch");
String create = """
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
<Name>www.wiremismatch.example.com.</Name>
<Type>A</Type>
<TTL>300</TTL>
<ResourceRecords>
<ResourceRecord><Value>1.2.3.4</Value></ResourceRecord>
</ResourceRecords>
</ResourceRecordSet>
</Change>
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""";
given().contentType(XML).body(create)
.post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then().statusCode(200);
String deleteWrongValue = create
.replace("<Action>CREATE</Action>", "<Action>DELETE</Action>")
.replace("<Value>1.2.3.4</Value>", "<Value>9.9.9.9</Value>");
given().contentType(XML).body(deleteWrongValue)
.post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then().statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidChangeBatch"));
given().get("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then().statusCode(200)
.body(containsString("<Value>1.2.3.4</Value>"));
}
@ParameterizedTest
@MethodSource("malformedNumericFieldCases")
void malformedNumericFieldIsRejectedAsInvalidInput(String elementName, String fieldXml) {
String zoneId = createZone("badnum-" + elementName.toLowerCase() + ".example.com.",
"ref-badnum-" + elementName);
String body = """
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
<Name>www.badnum.example.com.</Name>
<Type>A</Type>
%s
</ResourceRecordSet>
</Change>
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""".formatted(fieldXml);
given().contentType(XML)
.body(body)
.when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message", containsString("at '" + elementName + "'"));
}
private static Stream<Arguments> malformedNumericFieldCases() {
return Stream.of(
Arguments.of("TTL", "<TTL>not-a-number</TTL>"),
Arguments.of("Weight", "<Weight>not-a-number</Weight>"));
}
@ParameterizedTest
@MethodSource("missingRequiredElementCases")
void resourceRecordSetMissingRequiredElementIsRejectedAsInvalidInput(String nameXml, String typeXml) {
String body = """
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
%s
%s
<TTL>300</TTL>
<ResourceRecords>
<ResourceRecord><Value>1.2.3.4</Value></ResourceRecord>
</ResourceRecords>
</ResourceRecordSet>
</Change>
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""".formatted(nameXml, typeXml);
String zoneId = createZone("missing.example.com.", "ref-missing-" + nameXml.hashCode());
given().contentType(XML)
.body(body)
.when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message", containsString("missing a required Name or Type"));
}
private static Stream<Arguments> missingRequiredElementCases() {
return Stream.of(
Arguments.of("", "<Type>A</Type>"),
Arguments.of("<Name>www.missing.example.com.</Name>", ""));
}
@Test
void resourceRecordSetWithNeitherAliasTargetNorTtlAndRecordsIsRejectedAsInvalidInput() {
String zoneId = createZone("www.example.com.", "ref-no-shape");
String body = """
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
<Name>www.example.com.</Name>
<Type>A</Type>
</ResourceRecordSet>
</Change>
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""";
given().contentType(XML)
.body(body)
.when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message", equalTo(
"Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], "
+ "or TrafficPolicyInstanceId], but found none in Change with [Action=CREATE, "
+ "Name=www.example.com., Type=A, SetIdentifier=null]"));
}
@Test
void resourceRecordSetWithBothAliasTargetAndTtlAndRecordsIsRejectedAsInvalidInput() {
String zoneId = createZone("bothshapes.example.com.", "ref-both-shapes");
String body = """
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
<Name>www.example.com.</Name>
<Type>A</Type>
<TTL>300</TTL>
<ResourceRecords>
<ResourceRecord><Value>1.2.3.4</Value></ResourceRecord>
</ResourceRecords>
<AliasTarget>
<HostedZoneId>Z1</HostedZoneId>
<DNSName>alias.example.com.</DNSName>
<EvaluateTargetHealth>false</EvaluateTargetHealth>
</AliasTarget>
</ResourceRecordSet>
</Change>
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""";
given().contentType(XML)
.body(body)
.when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message", equalTo(
"Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], "
+ "or TrafficPolicyInstanceId], but found more than one in Change with "
+ "[Action=CREATE, Name=www.example.com., Type=A, SetIdentifier=null]"));
}
@ParameterizedTest
@MethodSource("recordShapeCases")
void resourceRecordSetWithWrongNumberOfShapesIsRejectedAsInvalidInput(String caseName, String rrsFieldsXml,
String expectedFound) {
String zoneId = createZone("shape-" + caseName.toLowerCase() + ".example.com.", "ref-shape-" + caseName);
String body = """
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes>
<Change>
<Action>CREATE</Action>
<ResourceRecordSet>
<Name>www.shape.example.com.</Name>
<Type>A</Type>
%s
</ResourceRecordSet>
</Change>
</Changes>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""".formatted(rrsFieldsXml);
given().contentType(XML)
.body(body)
.when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message", equalTo(
"Invalid request: Expected exactly one of [AliasTarget, all of [TTL, and ResourceRecords], "
+ "or TrafficPolicyInstanceId], but found " + expectedFound + " in Change with "
+ "[Action=CREATE, Name=www.shape.example.com., Type=A, SetIdentifier=null]"));
}
private static Stream<Arguments> recordShapeCases() {
String alias = """
<AliasTarget>
<HostedZoneId>Z1</HostedZoneId>
<DNSName>alias.example.com.</DNSName>
<EvaluateTargetHealth>false</EvaluateTargetHealth>
</AliasTarget>
""";
String ttl = "<TTL>300</TTL>";
String records = """
<ResourceRecords>
<ResourceRecord><Value>1.2.3.4</Value></ResourceRecord>
</ResourceRecords>
""";
return Stream.of(
Arguments.of("AliasAndResourceRecords", alias + records, "more than one"),
Arguments.of("AliasAndTtl", alias + ttl, "more than one"),
Arguments.of("TtlOnly", ttl, "none"),
Arguments.of("ResourceRecordsOnly", records, "none"));
}
@ParameterizedTest
@MethodSource("emptyChangeBatchCases")
void emptyChangeBatchIsRejectedAsInvalidInput(String caseName, String requestBody) {
String zoneId = createZone("empty-" + caseName.toLowerCase() + ".example.com.", "ref-empty-" + caseName);
given().contentType(XML)
.body(requestBody)
.when().post("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then()
.statusCode(400)
.body("ErrorResponse.Error.Code", equalTo("InvalidInput"))
.body("ErrorResponse.Error.Message", equalTo(
"Invalid XML ; cvc-complex-type.2.4.b: The content of element 'Changes' is not complete. "
+ "One of '{\"https://route53.amazonaws.com/doc/2013-04-01/\":Change}' is "
+ "expected."));
}
private static Stream<Arguments> emptyChangeBatchCases() {
String emptyChanges = """
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<ChangeBatch>
<Changes/>
</ChangeBatch>
</ChangeResourceRecordSetsRequest>
""";
String noChangeBatch = """
<?xml version="1.0" encoding="UTF-8"?>
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<Comment>no ChangeBatch element</Comment>
</ChangeResourceRecordSetsRequest>
""";
return Stream.of(
Arguments.of("EmptyChanges", emptyChanges),
Arguments.of("NoChangeBatch", noChangeBatch));
}
private static String createZone(String name, String callerReference) {
String create = """
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<Name>%s</Name>
<CallerReference>%s</CallerReference>
</CreateHostedZoneRequest>
""".formatted(name, callerReference);
String location = given().contentType(XML).body(create)
.post("/2013-04-01/hostedzone")
.then().statusCode(201).extract().header("Location");
return location.substring(location.lastIndexOf('/') + 1);
}
}
@@ -0,0 +1,266 @@
package io.github.hectorvent.floci.services.route53;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.route53.model.AliasTarget;
import io.github.hectorvent.floci.services.route53.model.ResourceRecord;
import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class Route53ServiceTest {
private static final String ACCOUNT = "000000000000";
private Route53Service newService() {
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
Mockito.when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT));
EmulatorConfig config = Mockito.mock(EmulatorConfig.class);
EmulatorConfig.ServicesConfig servicesConfig = Mockito.mock(EmulatorConfig.ServicesConfig.class);
EmulatorConfig.Route53ServiceConfig route53Config =
Mockito.mock(EmulatorConfig.Route53ServiceConfig.class);
Mockito.when(config.defaultAccountId()).thenReturn(ACCOUNT);
Mockito.when(config.services()).thenReturn(servicesConfig);
Mockito.when(servicesConfig.route53()).thenReturn(route53Config);
Mockito.when(route53Config.defaultNameserver1()).thenReturn("ns-1.awsdns-00.com.");
Mockito.when(route53Config.defaultNameserver2()).thenReturn("ns-2.awsdns-00.net.");
Mockito.when(route53Config.defaultNameserver3()).thenReturn("ns-3.awsdns-00.org.");
Mockito.when(route53Config.defaultNameserver4()).thenReturn("ns-4.awsdns-00.co.uk.");
Mockito.when(route53Config.vpcAssociationControlPlaneDelayMs()).thenReturn(0L);
Ec2Service ec2Service = Mockito.mock(Ec2Service.class);
RegionResolver regionResolver = new RegionResolver("us-east-1", ACCOUNT);
return new Route53Service(storageFactory, config, regionResolver, ec2Service);
}
private static Map<String, Object> change(String action, ResourceRecordSet rrs) {
Map<String, Object> m = new HashMap<>();
m.put("action", action);
m.put("rrs", rrs);
return m;
}
private static ResourceRecordSet aRecord(String name, long ttl, String... values) {
ResourceRecordSet rrs = new ResourceRecordSet();
rrs.setName(name);
rrs.setType("A");
rrs.setTtl(ttl);
List<ResourceRecord> records = new ArrayList<>();
for (String value : values) {
records.add(new ResourceRecord(value));
}
rrs.setRecords(records);
return rrs;
}
private static ResourceRecordSet aliasRecord(String name, String dnsName, boolean evaluateTargetHealth) {
ResourceRecordSet rrs = new ResourceRecordSet();
rrs.setName(name);
rrs.setType("A");
AliasTarget alias = new AliasTarget();
alias.setHostedZoneId("Z1ALIASZONE");
alias.setDnsName(dnsName);
alias.setEvaluateTargetHealth(evaluateTargetHealth);
rrs.setAliasTarget(alias);
return rrs;
}
private static ResourceRecordSet weightedRecord(String name, long ttl, String setIdentifier, long weight,
String... values) {
ResourceRecordSet rrs = aRecord(name, ttl, values);
rrs.setSetIdentifier(setIdentifier);
rrs.setWeight(weight);
return rrs;
}
@Test
void deleteFailsWithNotFoundMessageWhenNoRecordWithMatchingNameAndTypeExists() {
Route53Service service = newService();
String zoneId = service.createHostedZone("example.com.", "ref-missing", null, null).zone().getId();
AwsException e = assertThrows(AwsException.class, () -> service.changeResourceRecordSets(zoneId,
List.of(change("DELETE", aRecord("missing.example.com.", 300, "1.2.3.4"))), null));
assertEquals("InvalidChangeBatch", e.getErrorCode());
assertEquals("Tried to delete resource record set [name='missing.example.com.', type='A'] "
+ "but it was not found", e.getMessage());
}
@Test
void deleteFailsWhenResourceRecordValueDoesNotMatch() {
Route53Service service = newService();
String zoneId = service.createHostedZone("example.com.", "ref-value", null, null).zone().getId();
service.changeResourceRecordSets(zoneId,
List.of(change("CREATE", aRecord("www.example.com.", 300, "1.2.3.4"))), null);
AwsException e = assertThrows(AwsException.class, () -> service.changeResourceRecordSets(zoneId,
List.of(change("DELETE", aRecord("www.example.com.", 300, "5.6.7.8"))), null));
assertEquals("InvalidChangeBatch", e.getErrorCode());
assertEquals("Tried to delete resource record set [name='www.example.com.', type='A'] "
+ "but the values provided do not match the current values", e.getMessage());
List<ResourceRecordSet> records = service.listResourceRecordSets(zoneId, "www.example.com.", "A", 1);
assertThat(records, hasSize(1));
assertThat(records.get(0).getRecords().get(0).getValue(), equalTo("1.2.3.4"));
}
@Test
void deleteFailsWhenTtlDoesNotMatch() {
Route53Service service = newService();
String zoneId = service.createHostedZone("example.com.", "ref-ttl", null, null).zone().getId();
service.changeResourceRecordSets(zoneId,
List.of(change("CREATE", aRecord("www.example.com.", 300, "1.2.3.4"))), null);
AwsException e = assertThrows(AwsException.class, () -> service.changeResourceRecordSets(zoneId,
List.of(change("DELETE", aRecord("www.example.com.", 60, "1.2.3.4"))), null));
assertEquals("InvalidChangeBatch", e.getErrorCode());
assertEquals("Tried to delete resource record set [name='www.example.com.', type='A'] "
+ "but the values provided do not match the current values", e.getMessage());
List<ResourceRecordSet> records = service.listResourceRecordSets(zoneId, "www.example.com.", "A", 1);
assertThat(records, hasSize(1));
assertEquals(300L, records.get(0).getTtl());
}
@Test
void deleteFailsWhenAliasTargetDoesNotMatch() {
Route53Service service = newService();
String zoneId = service.createHostedZone("example.com.", "ref-alias", null, null).zone().getId();
service.changeResourceRecordSets(zoneId,
List.of(change("CREATE", aliasRecord("alias.example.com.", "target1.example.com.", true))), null);
AwsException e = assertThrows(AwsException.class, () -> service.changeResourceRecordSets(zoneId,
List.of(change("DELETE", aliasRecord("alias.example.com.", "target2.example.com.", true))), null));
assertEquals("InvalidChangeBatch", e.getErrorCode());
assertEquals("Tried to delete resource record set [name='alias.example.com.', type='A'] "
+ "but the values provided do not match the current values", e.getMessage());
List<ResourceRecordSet> records = service.listResourceRecordSets(zoneId, "alias.example.com.", "A", 1);
assertThat(records, hasSize(1));
assertEquals("target1.example.com.", records.get(0).getAliasTarget().getDnsName());
}
@Test
void deleteFailsWhenSetIdentifierDoesNotMatch() {
Route53Service service = newService();
String zoneId = service.createHostedZone("example.com.", "ref-setid", null, null).zone().getId();
service.changeResourceRecordSets(zoneId,
List.of(change("CREATE",
weightedRecord("weighted.example.com.", 60, "primary", 10, "1.1.1.1"))), null);
AwsException e = assertThrows(AwsException.class, () -> service.changeResourceRecordSets(zoneId,
List.of(change("DELETE",
weightedRecord("weighted.example.com.", 60, "secondary", 10, "1.1.1.1"))), null));
assertEquals("InvalidChangeBatch", e.getErrorCode());
assertEquals("Tried to delete resource record set [name='weighted.example.com.', type='A', "
+ "set-identifier='secondary'] but it was not found", e.getMessage());
List<ResourceRecordSet> records = service.listResourceRecordSets(zoneId, "weighted.example.com.", "A", 1);
assertThat(records, hasSize(1));
assertEquals("primary", records.get(0).getSetIdentifier());
}
@Test
void deleteSucceedsWhenAllValuesMatchExactly() {
Route53Service service = newService();
String zoneId = service.createHostedZone("example.com.", "ref-exact", null, null).zone().getId();
service.changeResourceRecordSets(zoneId,
List.of(change("CREATE",
weightedRecord("weighted.example.com.", 60, "primary", 10, "1.1.1.1"))), null);
service.changeResourceRecordSets(zoneId,
List.of(change("DELETE",
weightedRecord("weighted.example.com.", 60, "primary", 10, "1.1.1.1"))), null);
List<ResourceRecordSet> records = service.listResourceRecordSets(zoneId, "weighted.example.com.", "A", 1);
assertThat(records, empty());
}
@Test
void changeBatchLeavesRecordsUnchangedWhenALaterChangeFails() {
Route53Service service = newService();
String zoneId = service.createHostedZone("example.com.", "ref-atomic", null, null).zone().getId();
service.changeResourceRecordSets(zoneId, List.of(
change("CREATE", aRecord("a.example.com.", 60, "1.1.1.1")),
change("CREATE", aRecord("b.example.com.", 60, "2.2.2.2"))
), null);
AwsException e = assertThrows(AwsException.class, () -> service.changeResourceRecordSets(zoneId, List.of(
change("DELETE", aRecord("a.example.com.", 60, "1.1.1.1")),
change("DELETE", aRecord("b.example.com.", 60, "9.9.9.9"))
), null));
assertEquals("InvalidChangeBatch", e.getErrorCode());
assertEquals("Tried to delete resource record set [name='b.example.com.', type='A'] "
+ "but the values provided do not match the current values", e.getMessage());
List<ResourceRecordSet> aRecords = service.listResourceRecordSets(zoneId, "a.example.com.", "A", 1);
List<ResourceRecordSet> bRecords = service.listResourceRecordSets(zoneId, "b.example.com.", "A", 1);
assertThat(aRecords, hasSize(1));
assertThat(bRecords, hasSize(1));
assertEquals("1.1.1.1", aRecords.get(0).getRecords().get(0).getValue());
assertEquals("2.2.2.2", bRecords.get(0).getRecords().get(0).getValue());
}
@Test
void deletingTheSameRecordSetTwiceInOneBatchFailsWithInvalidChangeBatch() {
Route53Service service = newService();
String zoneId = service.createHostedZone("example.com.", "ref-double-delete", null, null).zone().getId();
service.changeResourceRecordSets(zoneId,
List.of(change("CREATE", aRecord("dup.example.com.", 60, "1.1.1.1"))), null);
AwsException e = assertThrows(AwsException.class, () -> service.changeResourceRecordSets(zoneId, List.of(
change("DELETE", aRecord("dup.example.com.", 60, "1.1.1.1")),
change("DELETE", aRecord("dup.example.com.", 60, "1.1.1.1"))
), null));
assertEquals("InvalidChangeBatch", e.getErrorCode());
assertEquals("Tried to delete resource record set [name='dup.example.com.', type='A'] "
+ "but it was not found", e.getMessage());
List<ResourceRecordSet> records = service.listResourceRecordSets(zoneId, "dup.example.com.", "A", 1);
assertThat(records, hasSize(1));
}
@Test
void deleteThenCreateOfSameNameAndTypeInOneBatchSucceeds() {
Route53Service service = newService();
String zoneId = service.createHostedZone("example.com.", "ref-replace", null, null).zone().getId();
service.changeResourceRecordSets(zoneId,
List.of(change("CREATE", aRecord("www.example.com.", 300, "1.2.3.4"))), null);
service.changeResourceRecordSets(zoneId, List.of(
change("DELETE", aRecord("www.example.com.", 300, "1.2.3.4")),
change("CREATE", aRecord("www.example.com.", 300, "5.6.7.8"))
), null);
List<ResourceRecordSet> records = service.listResourceRecordSets(zoneId, "www.example.com.", "A", 1);
assertThat(records, hasSize(1));
assertEquals("5.6.7.8", records.get(0).getRecords().get(0).getValue());
}
}