mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(route53): store CloudFormation record names fully qualified (#4734)
* fix(route53): store CloudFormation record names fully qualified Route 53 always stores and lists a record name fully qualified, ending in a dot, even when the request leaves the dot off. Floci's ChangeResourceRecordSets API already adds the dot, but an AWS::Route53::RecordSet created through CloudFormation was stored exactly as the template wrote it, so ListResourceRecordSets returned it without the dot. The CloudFormation provisioner now stores the dotted name and compares dotted names when it looks up a record to replace on update or remove on stack delete. The resource's Ref is unchanged and still returns the name as the template wrote it. * fix(route53): create CloudFormation record sets instead of upserting them An AWS::Route53::RecordSet was always written with an UPSERT, on stack create as well as update. A stack could therefore overwrite a record that someone had already created through the Route 53 API under the same name, and deleting the stack then removed that record too. Real CloudFormation sends CREATE for a record the resource does not own yet, so the stack fails with "already exists" and the other record is left alone. The provisioner now does the same: it sends CREATE on stack create and on an update that changes the record's zone, name, type or set identifier, and keeps UPSERT when an update re-applies the record it already wrote. A failed create records no zone and no physical id, so neither the rollback nor a later DeleteStack touches the existing record. * fix(route53): treat a blank CloudFormation SetIdentifier as no identifier A record set whose template gave SetIdentifier as an empty string was written with that empty identifier, but the value saved for later updates and deletes dropped it. The next ordinary UpdateStack therefore saw a different record, sent CREATE, and failed as a duplicate. DeleteStack also looked for a record without an identifier and left the empty-identifier record in the zone. Route 53 requires a set identifier of at least one character, so the provisioner now reads a blank SetIdentifier as absent. The written record, the saved value and the update comparison then agree. The class and change comments now also say that an update keeping the same record sends UPSERT, which replaces whatever record holds that identity. * fix(route53): match CloudFormation records an earlier version stored as written Before this branch, the provisioner stored a record set with the template's Name and SetIdentifier as written, so an undotted name or an empty identifier. With persistent storage that record survives an upgrade, and the stricter lookup no longer matched it: DeleteStack and a rename left it in the zone, where it blocks the zone's own delete. An update keeping the same identity sent a fully qualified UPSERT, which the zone stored beside the old copy instead of replacing it. The lookup now compares names fully qualified on both sides and reads a blank SetIdentifier as none, so it finds the old record. After a same-identity UPSERT, the provisioner deletes any copy of the identity that is not stored in the canonical form it just wrote. * fix(route53): treat a trailing dot and a blank set identifier as the same record Route 53 treats a record name with or without the trailing dot as the same record, and requires a set identifier of at least one character. The service compared both literally, so a record an earlier CloudFormation provisioner stored with the template's undotted Name or empty SetIdentifier could sit beside the fully qualified form: a CREATE of the dotted name succeeded instead of failing as a duplicate, and an UPSERT added a second record instead of replacing the first. The CREATE, UPSERT and DELETE checks now share one identity comparison, sameRecord, which compares names fully qualified and reads a blank set identifier as none. The CloudFormation provisioner's record lookup uses it too, so DeleteStack and a rename find a record stored either way. This replaces the provisioner's own legacy-copy cleanup, which deleted any non-canonical copy without knowing who owned it, and could remove another stack's record. * fix(route53): remove one record per DELETE An earlier version compared record names literally, so persistent storage can hold the same record both undotted and dotted, possibly for two owners, with the same values. Now that DELETE matches both forms, removing every match would also delete the other owner's copy. A DELETE now removes a single record, preferring the copy named exactly as the request names it. * fix(route53): find the CloudFormation record named as its physical id first An earlier version stored a record's name as the template wrote it, and could leave another owner's copy in the other form beside it. The lookup for stack delete and rename took the first record with the same identity, and the zone listing sorts the undotted copy first, so it could delete the other owner's record. It now prefers the record named exactly as the physical id, and falls back to the identity match for records this version wrote fully qualified.
This commit is contained in:
1 parent
8c1364e6ad
commit
7ebbe868ca
5 files changed
+456
-70
No files matched your search
+60
-34
@@ -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.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public 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 void removeSupersededRecord(ProvisionContext ctx, Map<String, String> priorAttributes,
|
||||
String zoneId, String name, String type, String setIdentifier) {
|
||||
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) {
|
||||
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) {
|
||||
|
||||
@@ -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 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 blankToNull(String value) {
|
||||
return value == null || value.isBlank() ? null : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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())
|
||||
|
||||
+175
-1
@@ -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)
|
||||
|
||||
+126
-8
@@ -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());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingARecordSetToleratesAZoneAlreadyGone() {
|
||||
Route53Service service = mock(Route53Service.class);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteThenCreateOfSameNameAndTypeInOneBatchSucceeds() {
|
||||
Route53Service service = newService();
|
||||
|
||||
Reference in new issue
Block a user