feat(cloudformation): write Route53 RecordSet records into the zone (#4132)

AWS::Route53::RecordSet was a name-only resource: it set a physical id and wrote
nothing, so the record never existed. Now the declared record is applied to its
hosted zone via ChangeResourceRecordSets and removed on stack delete.

- Validate the schema-required Type and Name, and reject a non-numeric TTL (the
  schema types TTL as a string) with a ValidationError rather than letting a raw
  NumberFormatException escape.
- Resolve the zone from HostedZoneId (a Ref resolves to the real id) or by an
  exact name match against HostedZoneName. listHostedZonesByName is a starts-at
  paginator, so the result is filtered to the zone whose name equals the request,
  rejecting when none or more than one matches, rather than writing into whatever
  zone sorts first.
- Apply the record as an UPSERT so create and update both converge; delete
  reconstructs a matching DELETE change from the zone id and type recorded at
  create time, tolerating a zone or record already gone.
- When an update changes the record's identity (zone, Name, Type or
  SetIdentifier), remove the record the prior provision wrote so it does not
  linger in the zone and later block the zone's own delete.

Ref stays the record name; no Fn::GetAtt attribute is published (Id remains
gapped, as before).
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-22 13:29:07 -04:00
1 parent e8b03538e6
commit 32856bfee0
3 files changed
+445 -33

No files matched your search

@@ -27,6 +27,8 @@ class CloudFormationRoute53RecordSetIntegrationTest {
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
private static final String SSM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ssm/aws4_request";
private static final String ROUTE53_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/route53/aws4_request";
private static final Duration STACK_DELETE_TIMEOUT = Duration.ofSeconds(30);
private static final Duration STACK_DELETE_POLL_INTERVAL = Duration.ofMillis(50);
@@ -60,21 +62,40 @@ class CloudFormationRoute53RecordSetIntegrationTest {
"RefParam": {
"Type": "AWS::SSM::Parameter",
"Properties": {"Name": "/r53-recordset/%s/ref", "Type": "String", "Value": {"Ref": "Www"}}
},
"ZoneParam": {
"Type": "AWS::SSM::Parameter",
"Properties": {"Name": "/r53-recordset/%s/zone", "Type": "String", "Value": {"Ref": "Zone"}}
}
}
}
""".formatted(suffix, recordName, suffix);
""".formatted(suffix, recordName, suffix, suffix);
createStack(stackName, template);
assertStackStatus(stackName, "CREATE_COMPLETE");
try {
assertEquals(recordName, parameterValue("/r53-recordset/" + suffix + "/ref"));
// A stack status proves nothing on its own: read the record back from the zone to
// confirm the provisioner wrote it (not stubbed) rather than leaving the zone empty.
String zoneId = parameterValue("/r53-recordset/" + suffix + "/zone");
String records = listResourceRecordSets(zoneId);
assertTrue(records.contains(recordName), "record not written to zone: " + records);
assertTrue(records.contains("10.0.0.1"), "record value not written to zone: " + records);
} finally {
deleteStack(stackName);
awaitStackGone(stackName);
}
}
private String listResourceRecordSets(String zoneId) {
return given()
.header("Authorization", ROUTE53_AUTH)
.when().get("/2013-04-01/hostedzone/" + zoneId + "/rrset")
.then().statusCode(200)
.extract().asString();
}
private void createStack(String stackName, String template) {
given()
.contentType("application/x-www-form-urlencoded")
@@ -7,21 +7,28 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplate
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.route53.Route53Service;
import io.github.hectorvent.floci.services.route53.model.HostedZone;
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.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -370,49 +377,204 @@ class Route53CfnProvisionerTest {
}
@Test
void recordSetUsesItsNameAsRefPublishesNoAttributesAndWritesNothingToTheZone() {
void recordSetIsUpsertedIntoItsZoneAndRefIsTheRecordName() {
Route53Service service = mock(Route53Service.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode props = mapper.createObjectNode()
.put("HostedZoneId", "Z123456789")
.put("Name", "www.example.com")
.put("Type", "A");
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(invocation -> invocation.<JsonNode>getArgument(0).asText());
.put("Type", "A")
.put("TTL", "300");
((com.fasterxml.jackson.databind.node.ObjectNode) props).set("ResourceRecords",
mapper.createArrayNode().add("10.0.0.1"));
CloudFormationTemplateEngine engine = recordEngine();
ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack");
StackResource resource = new StackResource();
resource.setLogicalId("Alias");
resource.setLogicalId("Www");
resource.setResourceType("AWS::Route53::RecordSet");
new Route53CfnProvisioner(service).provision(resource, props, context);
assertEquals("www.example.com", resource.getPhysicalId());
assertEquals(Set.of(), resource.getAttributes().keySet());
verifyNoInteractions(service);
// The internal zone/type record survives for delete, but no schema attribute is published.
assertEquals(Set.of("__FlociRoute53RecordZoneId", "__FlociRoute53RecordType"),
resource.getAttributes().keySet());
@SuppressWarnings("unchecked")
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"));
ResourceRecordSet rrs = (ResourceRecordSet) change.get("rrs");
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());
}
@Test
void recordSetWithoutANameGetsAGeneratedRecordId() {
void recordSetResolvesTheZoneFromHostedZoneNameByExactMatch() {
Route53Service service = mock(Route53Service.class);
// listHostedZonesByName is a starts-at paginator: it also returns zones that sort after the
// requested name, so the provisioner must pick the exact match, not the first result.
when(service.listHostedZonesByName("example.com.", 0)).thenReturn(List.of(
new HostedZone("Z999", "example.com.", "caller", null, (VpcAssociation) null),
new HostedZone("Zzzz", "zzz.internal.", "caller", null, (VpcAssociation) null)));
ObjectMapper mapper = new ObjectMapper();
JsonNode props = mapper.createObjectNode().put("Type", "A");
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(invocation -> invocation.<JsonNode>getArgument(0).asText());
ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack");
JsonNode props = mapper.createObjectNode()
.put("HostedZoneName", "example.com.")
.put("Name", "www.example.com")
.put("Type", "A");
ProvisionContext context = new ProvisionContext(recordEngine(), "us-east-1", "623666680275", "dns-stack");
StackResource resource = new StackResource();
resource.setLogicalId("Alias");
resource.setLogicalId("Www");
resource.setResourceType("AWS::Route53::RecordSet");
new Route53CfnProvisioner(service).provision(resource, props, context);
assertNotNull(resource.getPhysicalId());
assertTrue(resource.getPhysicalId().matches("record-[0-9a-f]{8}"), resource.getPhysicalId());
assertTrue(resource.getAttributes().isEmpty(), resource.getAttributes().toString());
verifyNoInteractions(service);
verify(service).changeResourceRecordSets(eq("Z999"), any(), any());
}
@Test
void deletingARecordSetLeavesHostedZonesAlone() {
void recordSetRejectsAHostedZoneNameThatMatchesNoZone() {
Route53Service service = mock(Route53Service.class);
// The paginator returns a later-sorting zone, but none whose name actually equals the request.
when(service.listHostedZonesByName("app.example.com.", 0)).thenReturn(List.of(
new HostedZone("Zzzz", "zzz.internal.", "caller", null, (VpcAssociation) null)));
ObjectMapper mapper = new ObjectMapper();
JsonNode props = mapper.createObjectNode()
.put("HostedZoneName", "app.example.com.")
.put("Name", "www.app.example.com")
.put("Type", "A");
ProvisionContext context = new ProvisionContext(recordEngine(), "us-east-1", "623666680275", "dns-stack");
StackResource resource = new StackResource();
resource.setLogicalId("Www");
resource.setResourceType("AWS::Route53::RecordSet");
AwsException failure = assertThrows(AwsException.class,
() -> new Route53CfnProvisioner(service).provision(resource, props, context));
assertEquals("InvalidChangeBatch", failure.getErrorCode());
verify(service, never()).changeResourceRecordSets(any(), any(), any());
}
@Test
void recordSetWithANonNumericTtlIsRejected() {
assertRecordSetRejected("{\"HostedZoneId\": \"Z1\", \"Name\": \"www.example.com\", "
+ "\"Type\": \"A\", \"TTL\": \"5 minutes\"}");
}
@Test
void recordSetWithoutANameIsRejected() {
assertRecordSetRejected("{\"HostedZoneId\": \"Z1\", \"Type\": \"A\"}");
}
@Test
void recordSetWithoutATypeIsRejected() {
assertRecordSetRejected("{\"HostedZoneId\": \"Z1\", \"Name\": \"www.example.com\"}");
}
@Test
void recordSetWithoutAZoneIsRejected() {
assertRecordSetRejected("{\"Name\": \"www.example.com\", \"Type\": \"A\"}");
}
private void assertRecordSetRejected(String json) {
Route53Service service = mock(Route53Service.class);
ObjectMapper mapper = new ObjectMapper();
JsonNode props;
try {
props = mapper.readTree(json);
} catch (Exception e) {
throw new RuntimeException(e);
}
ProvisionContext context = new ProvisionContext(recordEngine(), "us-east-1", "623666680275", "dns-stack");
StackResource resource = new StackResource();
resource.setLogicalId("Www");
resource.setResourceType("AWS::Route53::RecordSet");
AwsException failure = assertThrows(AwsException.class,
() -> new Route53CfnProvisioner(service).provision(resource, props, context));
assertEquals("ValidationError", failure.getErrorCode());
verify(service, never()).changeResourceRecordSets(any(), any(), any());
}
@Test
void renamingARecordSetOnUpdateRemovesTheSupersededRecord() {
Route53Service service = mock(Route53Service.class);
ResourceRecordSet priorRecord = new ResourceRecordSet();
priorRecord.setName("auth.example.com");
priorRecord.setType("A");
when(service.listResourceRecordSets("Z1", null, null, 0)).thenReturn(List.of(priorRecord));
ObjectMapper mapper = new ObjectMapper();
JsonNode props = mapper.createObjectNode()
.put("HostedZoneId", "Z1")
.put("Name", "login.example.com")
.put("Type", "A");
ProvisionContext context = new ProvisionContext(recordEngine(), "us-east-1", "623666680275",
"dns-stack", "auth.example.com");
StackResource resource = new StackResource();
resource.setLogicalId("Www");
resource.setResourceType("AWS::Route53::RecordSet");
resource.setPhysicalId("auth.example.com");
resource.getAttributes().put("__FlociRoute53RecordZoneId", "Z1");
resource.getAttributes().put("__FlociRoute53RecordType", "A");
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.
@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());
}
@Test
void deletingARecordSetViaTheResourceIssuesAMatchingDeleteChange() {
Route53Service service = mock(Route53Service.class);
ResourceRecordSet existing = new ResourceRecordSet();
existing.setName("www.example.com");
existing.setType("A");
when(service.listResourceRecordSets("Z123456789", null, null, 0)).thenReturn(List.of(existing));
StackResource resource = new StackResource();
resource.setLogicalId("Www");
resource.setResourceType("AWS::Route53::RecordSet");
resource.setPhysicalId("www.example.com");
resource.getAttributes().put("__FlociRoute53RecordZoneId", "Z123456789");
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("Z123456789"), captor.capture(), any());
Map<String, Object> change = captor.getValue().get(0);
assertEquals("DELETE", change.get("action"));
assertSame(existing, change.get("rrs"));
}
@Test
void deletingARecordSetToleratesAZoneAlreadyGone() {
Route53Service service = mock(Route53Service.class);
when(service.listResourceRecordSets("Z123456789", null, null, 0))
.thenThrow(new AwsException("NoSuchHostedZone", "gone", 404));
StackResource resource = new StackResource();
resource.setLogicalId("Www");
resource.setResourceType("AWS::Route53::RecordSet");
resource.setPhysicalId("www.example.com");
resource.getAttributes().put("__FlociRoute53RecordZoneId", "Z123456789");
resource.getAttributes().put("__FlociRoute53RecordType", "A");
new Route53CfnProvisioner(service).delete(resource, "us-east-1");
verify(service, never()).changeResourceRecordSets(any(), any(), any());
}
@Test
void deletingARecordSetByIdAloneLeavesTheZoneUntouched() {
Route53Service service = mock(Route53Service.class);
new Route53CfnProvisioner(service).delete("AWS::Route53::RecordSet", "www.example.com", "us-east-1");
@@ -420,6 +582,23 @@ class Route53CfnProvisionerTest {
verifyNoInteractions(service);
}
private static CloudFormationTemplateEngine recordEngine() {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(invocation -> {
JsonNode node = invocation.getArgument(0);
return node == null ? null : node.asText();
});
when(engine.resolveStringList(any())).thenAnswer(invocation -> {
JsonNode node = invocation.getArgument(0);
List<String> out = new ArrayList<>();
if (node != null && node.isArray()) {
node.forEach(element -> out.add(element.asText()));
}
return out;
});
return engine;
}
@Test
void deletingAHostedZoneStillDeletesTheZone() {
Route53Service service = mock(Route53Service.class);