diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java index 5107fbf716..75ac9f3ef6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java @@ -265,7 +265,6 @@ public class CloudFormationResourceProvisioner { "AWS::RDS::DBProxy", "AWS::RDS::DBProxyTargetGroup", "AWS::RDS::DBSubnetGroup", - "AWS::Route53::HostedZone", "AWS::Route53::RecordSet", "AWS::SecretsManager::Secret", "AWS::SecretsManager::SecretTargetAttachment", @@ -423,7 +422,6 @@ public class CloudFormationResourceProvisioner { case "AWS::SecretsManager::Secret" -> provisionSecret(resource, properties, engine, region, accountId, stackName); case "AWS::SecretsManager::SecretTargetAttachment" -> provisionSecretTargetAttachment(resource, properties, engine, region, stackName); - case "AWS::Route53::HostedZone" -> provisionRoute53HostedZone(resource, properties, engine); case "AWS::Route53::RecordSet" -> provisionRoute53RecordSet(resource, properties, engine); case "AWS::Events::Rule" -> provisionEventBridgeRule(resource, properties, engine, region, stackName); case "AWS::Events::EventBus" -> provisionEventBridgeEventBus(resource, properties, engine, region); @@ -4767,11 +4765,6 @@ public class CloudFormationResourceProvisioner { return out; } - private void provisionRoute53HostedZone(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) { - String zoneId = "Z" + UUID.randomUUID().toString().substring(0, 12).toUpperCase(); - r.setPhysicalId(zoneId); - } - private void provisionRoute53RecordSet(StackResource r, JsonNode props, CloudFormationTemplateEngine engine) { String name = resolveOptional(props, "Name", engine); r.setPhysicalId(name != null ? name : "record-" + UUID.randomUUID().toString().substring(0, 8)); diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisioner.java new file mode 100644 index 0000000000..0f31325d7c --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisioner.java @@ -0,0 +1,166 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsException; +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.VpcAssociation; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +@ApplicationScoped +public class Route53CfnProvisioner implements CfnResourceProvisioner { + private final Route53Service route53Service; + + @Inject + public Route53CfnProvisioner(Route53Service route53Service) { + this.route53Service = route53Service; + } + + @Override + public Set resourceTypes() { + return Set.of("AWS::Route53::HostedZone"); + } + + @Override + public void provision(StackResource resource, JsonNode props, ProvisionContext ctx) { + String name = ctx.resolveOptional(props, "Name"); + if (name == null || name.isBlank()) { + throw new IllegalArgumentException("AWS::Route53::HostedZone requires Name"); + } + + JsonNode resolved = ctx.engine().resolveNode(props); + String comment = resolved.path("HostedZoneConfig").path("Comment").asText(null); + List vpcs = parseVpcs(resolved.path("VPCs")); + String callerReference = ctx.stackName() + "/" + resource.getLogicalId(); + boolean isTrackedZoneMissing = resource.getPhysicalId() != null + && !zoneExists(resource.getPhysicalId()); + if (isTrackedZoneMissing) { + // The tracked physical ID may be a leftover from the retired monolith's HostedZone + // stub, which minted a random Z-id with zero Route53Service backing (see commit + // 76228741d). There is no real zone behind it to migrate, so recreate rather than + // fail the update and roll back the stack. + resource.setPhysicalId(null); + } + + String id; + if (resource.getPhysicalId() == null) { + // CreateHostedZone only accepts a single VPC (a private zone becomes + // resolvable from that VPC immediately); any further VPCs in the CFN + // template's list are wired in afterward via AssociateVPCWithHostedZone, + // matching how a real CloudFormation update converges an existing zone. + VpcAssociation firstVpc = vpcs.isEmpty() ? null : vpcs.get(0); + Route53Service.CreateZoneResult created = route53Service.createHostedZone( + name, callerReference, comment, firstVpc); + id = created.zone().getId(); + // Record the physical ID before any follow-up call that can fail: once the + // zone exists, the stack engine must be able to track and clean it up even + // if a later VPC association or tag write throws. Marking it rollback-owned + // too means a CREATE_FAILED status from that later failure still gets cleaned + // up during stack-create rollback, which keys off that attribute rather than + // physicalId alone (see CfnRollback.ROLLBACK_OWNED_ATTR). + resource.setPhysicalId(id); + resource.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true"); + try { + for (int i = 1; i < vpcs.size(); i++) { + route53Service.associateVpcWithHostedZone(id, vpcs.get(i), comment); + } + } catch (RuntimeException e) { + // An update that recreates a missing legacy zone (isTrackedZoneMissing above) + // fails through CloudFormationService's generic update-rollback path, which + // restores the stack's previous StackResource wholesale and never learns this + // zone's ID - orphaning it, so the next retry reuses the same caller reference + // and fails with HostedZoneAlreadyExists. Since we own this zone (we just + // created it), clean it up ourselves rather than depend on that path. + // Once cleanup succeeds, physical state matches what it was before this update + // started (tracked zone missing), so tell the generic rollback walker this + // resource is restored - otherwise it falls through to "rollback is not + // implemented" and strands the stack in UPDATE_ROLLBACK_FAILED for a resource + // there is nothing left to reconcile. + route53Service.deleteHostedZone(id); + resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true"); + throw e; + } + } else { + id = resource.getPhysicalId(); + for (VpcAssociation vpc : vpcs) { + route53Service.associateVpcWithHostedZone(id, vpc, comment); + } + } + + resource.setPhysicalId(id); + resource.getAttributes().put("Id", id); + resource.getAttributes().put("NameServers", String.join(",", route53Service.getNameServers())); + + List> tags = parseTags(resolved.path("HostedZoneTags")); + if (!tags.isEmpty()) { + try { + route53Service.changeTagsForResource("hostedzone", id, tags, List.of()); + } catch (RuntimeException e) { + if ("true".equals(resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR))) { + route53Service.deleteHostedZone(id); + resource.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true"); + } + throw e; + } + } + resource.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); + } + + private boolean zoneExists(String id) { + try { + route53Service.getHostedZone(id); + return true; + } catch (AwsException e) { + if (!"NoSuchHostedZone".equals(e.getErrorCode())) { + throw e; + } + return false; + } + } + + @Override + public void delete(String resourceType, String physicalId, String region) { + route53Service.deleteHostedZone(physicalId); + } + + private List parseVpcs(JsonNode node) { + List vpcs = new ArrayList<>(); + if (node.isArray()) { + for (JsonNode item : node) { + String id = item.path("VPCId").asText(null); + String region = item.path("VPCRegion").asText(null); + if (id == null || id.isBlank() || region == null || region.isBlank()) { + // AWS requires both fields on every VPCs entry; silently dropping an + // incomplete one would create an unassociated public zone while the + // stack still reports CREATE_COMPLETE. + throw new IllegalArgumentException( + "AWS::Route53::HostedZone VPCs entries require both VPCId and VPCRegion"); + } + vpcs.add(new VpcAssociation(id, region)); + } + } + return vpcs; + } + + private List> parseTags(JsonNode node) { + List> tags = new ArrayList<>(); + if (node.isArray()) { + for (JsonNode item : node) { + String key = item.path("Key").asText(null); + // Matches ProvisionContext.resolveTags: a blank key is skipped rather than + // persisted, since Route53Service.changeTagsForResource would otherwise write + // a tag AWS itself would reject for having an empty key. + if (key != null && !key.isBlank()) { + tags.add(Map.of("Key", key, "Value", item.path("Value").asText(""))); + } + } + } + return tags; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisionerTest.java new file mode 100644 index 0000000000..8d9af05201 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Route53CfnProvisionerTest.java @@ -0,0 +1,369 @@ +package io.github.hectorvent.floci.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine; +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.VpcAssociation; +import org.junit.jupiter.api.Test; + +import java.util.List; +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.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.verify; +import static org.mockito.Mockito.when; + +class Route53CfnProvisionerTest { + @Test + void createsBackingPrivateZoneAndExactAttributes() { + Route53Service service = mock(Route53Service.class); + VpcAssociation vpc = new VpcAssociation("vpc-123", "us-east-1"); + HostedZone zone = new HostedZone("Z123456789", "ssm.us-east-1.amazonaws.com.", + "caller", null, vpc); + when(service.createHostedZone(eq("ssm.us-east-1.amazonaws.com"), eq("dns-stack/Zone"), + eq("central endpoint zone"), argThat(sameVpc(vpc)))).thenReturn( + new Route53Service.CreateZoneResult(zone, null)); + when(service.getNameServers()).thenReturn(List.of("ns-1.example", "ns-2.example")); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode props = mapper.createObjectNode() + .put("Name", "ssm.us-east-1.amazonaws.com") + .set("HostedZoneConfig", mapper.createObjectNode().put("Comment", "central endpoint zone")); + ((com.fasterxml.jackson.databind.node.ObjectNode) props).set("VPCs", mapper.createArrayNode() + .add(mapper.createObjectNode().put("VPCId", "vpc-123").put("VPCRegion", "us-east-1"))); + ((com.fasterxml.jackson.databind.node.ObjectNode) props).set("HostedZoneTags", mapper.createArrayNode() + .add(mapper.createObjectNode().put("Key", "Accelerator").put("Value", "AWSAccelerator"))); + + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(invocation -> invocation.getArgument(0).asText()); + when(engine.resolveNode(props)).thenReturn(props); + ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack"); + StackResource resource = new StackResource(); + resource.setLogicalId("Zone"); + resource.setResourceType("AWS::Route53::HostedZone"); + + new Route53CfnProvisioner(service).provision(resource, props, context); + + assertEquals("Z123456789", resource.getPhysicalId()); + assertEquals(Set.of("Id", "NameServers"), resource.getAttributes().keySet()); + assertEquals("Z123456789", resource.getAttributes().get("Id")); + verify(service).createHostedZone(eq("ssm.us-east-1.amazonaws.com"), eq("dns-stack/Zone"), + eq("central endpoint zone"), argThat(sameVpc(vpc))); + verify(service, never()).associateVpcWithHostedZone(any(), any(), any()); + verify(service).changeTagsForResource("hostedzone", "Z123456789", + List.of(java.util.Map.of("Key", "Accelerator", "Value", "AWSAccelerator")), List.of()); + } + + @Test + void associatesAdditionalVpcsBeyondTheFirstOnCreate() { + Route53Service service = mock(Route53Service.class); + VpcAssociation firstVpc = new VpcAssociation("vpc-123", "us-east-1"); + VpcAssociation secondVpc = new VpcAssociation("vpc-456", "us-west-2"); + HostedZone zone = new HostedZone("Z123456789", "ssm.us-east-1.amazonaws.com.", + "caller", null, firstVpc); + when(service.createHostedZone(eq("ssm.us-east-1.amazonaws.com"), eq("dns-stack/Zone"), + eq(null), argThat(sameVpc(firstVpc)))).thenReturn( + new Route53Service.CreateZoneResult(zone, null)); + when(service.getNameServers()).thenReturn(List.of("ns-1.example", "ns-2.example")); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode props = mapper.createObjectNode().put("Name", "ssm.us-east-1.amazonaws.com"); + ((com.fasterxml.jackson.databind.node.ObjectNode) props).set("VPCs", mapper.createArrayNode() + .add(mapper.createObjectNode().put("VPCId", "vpc-123").put("VPCRegion", "us-east-1")) + .add(mapper.createObjectNode().put("VPCId", "vpc-456").put("VPCRegion", "us-west-2"))); + + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(invocation -> invocation.getArgument(0).asText()); + when(engine.resolveNode(props)).thenReturn(props); + ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack"); + StackResource resource = new StackResource(); + resource.setLogicalId("Zone"); + resource.setResourceType("AWS::Route53::HostedZone"); + + new Route53CfnProvisioner(service).provision(resource, props, context); + + verify(service).createHostedZone(eq("ssm.us-east-1.amazonaws.com"), eq("dns-stack/Zone"), + eq(null), argThat(sameVpc(firstVpc))); + verify(service).associateVpcWithHostedZone(eq("Z123456789"), argThat(sameVpc(secondVpc)), eq(null)); + } + + @Test + void recordsPhysicalIdBeforeAssociatingAdditionalVpcsSoAFailureIsStillTrackedForCleanup() { + Route53Service service = mock(Route53Service.class); + VpcAssociation firstVpc = new VpcAssociation("vpc-123", "us-east-1"); + VpcAssociation secondVpc = new VpcAssociation("vpc-456", "us-west-2"); + HostedZone zone = new HostedZone("Z123456789", "ssm.us-east-1.amazonaws.com.", + "caller", null, firstVpc); + when(service.createHostedZone(eq("ssm.us-east-1.amazonaws.com"), eq("dns-stack/Zone"), + eq(null), argThat(sameVpc(firstVpc)))).thenReturn( + new Route53Service.CreateZoneResult(zone, null)); + when(service.associateVpcWithHostedZone(eq("Z123456789"), argThat(sameVpc(secondVpc)), any())) + .thenThrow(new RuntimeException("boom")); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode props = mapper.createObjectNode().put("Name", "ssm.us-east-1.amazonaws.com"); + ((com.fasterxml.jackson.databind.node.ObjectNode) props).set("VPCs", mapper.createArrayNode() + .add(mapper.createObjectNode().put("VPCId", "vpc-123").put("VPCRegion", "us-east-1")) + .add(mapper.createObjectNode().put("VPCId", "vpc-456").put("VPCRegion", "us-west-2"))); + + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(invocation -> invocation.getArgument(0).asText()); + when(engine.resolveNode(props)).thenReturn(props); + ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack"); + StackResource resource = new StackResource(); + resource.setLogicalId("Zone"); + resource.setResourceType("AWS::Route53::HostedZone"); + + assertThrows(RuntimeException.class, + () -> new Route53CfnProvisioner(service).provision(resource, props, context)); + + assertEquals("Z123456789", resource.getPhysicalId()); + assertTrue("true".equals(resource.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR)), + "a zone that was actually created must stay marked rollback-owned when a " + + "follow-up VPC association fails, so CREATE_FAILED cleanup still deletes it"); + } + + private static org.mockito.ArgumentMatcher sameVpc(VpcAssociation expected) { + if (expected == null) { + return java.util.Objects::isNull; + } + return actual -> actual != null + && expected.getVpcId().equals(actual.getVpcId()) + && expected.getVpcRegion().equals(actual.getVpcRegion()); + } + + @Test + void backfillsBackingZoneUsingExistingPhysicalId() { + Route53Service service = mock(Route53Service.class); + HostedZone zone = new HostedZone("Z68119D97-4AB", "ssm.us-east-1.amazonaws.com.", + "dns-stack/Zone", null, (VpcAssociation) null); + when(service.getHostedZone("Z68119D97-4AB")).thenReturn(zone); + when(service.getNameServers()).thenReturn(List.of("ns-1.example", "ns-2.example")); + ObjectMapper mapper = new ObjectMapper(); + JsonNode props = mapper.createObjectNode().put("Name", "ssm.us-east-1.amazonaws.com"); + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(invocation -> invocation.getArgument(0).asText()); + when(engine.resolveNode(props)).thenReturn(props); + ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack"); + StackResource resource = new StackResource(); + resource.setLogicalId("Zone"); + resource.setResourceType("AWS::Route53::HostedZone"); + resource.setPhysicalId("Z68119D97-4AB"); + + new Route53CfnProvisioner(service).provision(resource, props, context); + + verify(service).getHostedZone("Z68119D97-4AB"); + verify(service, never()).createHostedZone(any(), any(), any(), any()); + assertEquals("Z68119D97-4AB", resource.getAttributes().get("Id")); + assertEquals(Set.of("Id", "NameServers"), resource.getAttributes().keySet()); + } + + @Test + void recreatesZoneWhenTheTrackedPhysicalIdNoLongerBacksARealZone() { + // Covers a physical ID left over from the retired monolith's HostedZone stub, which + // minted a random Z-id with zero Route53Service backing (see commit 76228741d) - + // there is no real zone to migrate, so an update recreates rather than failing. + Route53Service service = mock(Route53Service.class); + when(service.getHostedZone("ZLEGACYSTUBID")).thenThrow( + new AwsException("NoSuchHostedZone", "No hosted zone found with ID: ZLEGACYSTUBID", 404)); + VpcAssociation vpc = new VpcAssociation("vpc-123", "us-east-1"); + HostedZone zone = new HostedZone("Z987654321", "ssm.us-east-1.amazonaws.com.", + "dns-stack/Zone", null, vpc); + when(service.createHostedZone(eq("ssm.us-east-1.amazonaws.com"), eq("dns-stack/Zone"), + eq(null), argThat(sameVpc(vpc)))).thenReturn(new Route53Service.CreateZoneResult(zone, null)); + when(service.getNameServers()).thenReturn(List.of("ns-1.example", "ns-2.example")); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode props = mapper.createObjectNode().put("Name", "ssm.us-east-1.amazonaws.com"); + ((com.fasterxml.jackson.databind.node.ObjectNode) props).set("VPCs", mapper.createArrayNode() + .add(mapper.createObjectNode().put("VPCId", "vpc-123").put("VPCRegion", "us-east-1"))); + + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(invocation -> invocation.getArgument(0).asText()); + when(engine.resolveNode(props)).thenReturn(props); + ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack"); + StackResource resource = new StackResource(); + resource.setLogicalId("Zone"); + resource.setResourceType("AWS::Route53::HostedZone"); + resource.setPhysicalId("ZLEGACYSTUBID"); + + new Route53CfnProvisioner(service).provision(resource, props, context); + + verify(service).createHostedZone(eq("ssm.us-east-1.amazonaws.com"), eq("dns-stack/Zone"), + eq(null), argThat(sameVpc(vpc))); + assertEquals("Z987654321", resource.getPhysicalId()); + } + + @Test + void rejectsVpcEntryMissingRegionInsteadOfSilentlyDroppingIt() { + Route53Service service = mock(Route53Service.class); + ObjectMapper mapper = new ObjectMapper(); + JsonNode props = mapper.createObjectNode().put("Name", "ssm.us-east-1.amazonaws.com"); + ((com.fasterxml.jackson.databind.node.ObjectNode) props).set("VPCs", mapper.createArrayNode() + .add(mapper.createObjectNode().put("VPCId", "vpc-123"))); + + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(invocation -> invocation.getArgument(0).asText()); + when(engine.resolveNode(props)).thenReturn(props); + ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack"); + StackResource resource = new StackResource(); + resource.setLogicalId("Zone"); + resource.setResourceType("AWS::Route53::HostedZone"); + + assertThrows(IllegalArgumentException.class, + () -> new Route53CfnProvisioner(service).provision(resource, props, context)); + verify(service, never()).createHostedZone(any(), any(), any(), any()); + } + + @Test + void rejectsVpcEntryWithBlankIdOrRegionInsteadOfSilentlyAccepting() { + Route53Service service = mock(Route53Service.class); + ObjectMapper mapper = new ObjectMapper(); + JsonNode props = mapper.createObjectNode().put("Name", "ssm.us-east-1.amazonaws.com"); + ((com.fasterxml.jackson.databind.node.ObjectNode) props).set("VPCs", mapper.createArrayNode() + .add(mapper.createObjectNode().put("VPCId", "vpc-123").put("VPCRegion", " "))); + + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(invocation -> invocation.getArgument(0).asText()); + when(engine.resolveNode(props)).thenReturn(props); + ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack"); + StackResource resource = new StackResource(); + resource.setLogicalId("Zone"); + resource.setResourceType("AWS::Route53::HostedZone"); + + assertThrows(IllegalArgumentException.class, + () -> new Route53CfnProvisioner(service).provision(resource, props, context)); + verify(service, never()).createHostedZone(any(), any(), any(), any()); + } + + @Test + void skipsBlankTagKeysMatchingProvisionContextResolveTagsConvention() { + Route53Service service = mock(Route53Service.class); + VpcAssociation vpc = new VpcAssociation("vpc-123", "us-east-1"); + HostedZone zone = new HostedZone("Z123456789", "ssm.us-east-1.amazonaws.com.", + "caller", null, vpc); + when(service.createHostedZone(eq("ssm.us-east-1.amazonaws.com"), eq("dns-stack/Zone"), + eq(null), argThat(sameVpc(vpc)))).thenReturn(new Route53Service.CreateZoneResult(zone, null)); + when(service.getNameServers()).thenReturn(List.of("ns-1.example", "ns-2.example")); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode props = mapper.createObjectNode().put("Name", "ssm.us-east-1.amazonaws.com"); + ((com.fasterxml.jackson.databind.node.ObjectNode) props).set("VPCs", mapper.createArrayNode() + .add(mapper.createObjectNode().put("VPCId", "vpc-123").put("VPCRegion", "us-east-1"))); + ((com.fasterxml.jackson.databind.node.ObjectNode) props).set("HostedZoneTags", mapper.createArrayNode() + .add(mapper.createObjectNode().put("Key", "").put("Value", "blank-key-should-be-skipped")) + .add(mapper.createObjectNode().put("Key", "Accelerator").put("Value", "AWSAccelerator"))); + + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(invocation -> invocation.getArgument(0).asText()); + when(engine.resolveNode(props)).thenReturn(props); + ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack"); + StackResource resource = new StackResource(); + resource.setLogicalId("Zone"); + resource.setResourceType("AWS::Route53::HostedZone"); + + new Route53CfnProvisioner(service).provision(resource, props, context); + + verify(service).changeTagsForResource("hostedzone", "Z123456789", + List.of(java.util.Map.of("Key", "Accelerator", "Value", "AWSAccelerator")), List.of()); + } + + @Test + void deletesReplacementZoneWhenVpcAssociationFailsDuringUpdateRecreate() { + // If an update recreates a missing legacy zone (see + // recreatesZoneWhenTheTrackedPhysicalIdNoLongerBacksARealZone) and a later VPC + // association throws, the update-rollback path in CloudFormationService restores the + // stack's previous StackResource wholesale and never learns the new zone's ID - + // orphaning it. The next retry then reuses the same caller reference and fails with + // HostedZoneAlreadyExists. The provisioner must clean up the replacement itself. + Route53Service service = mock(Route53Service.class); + when(service.getHostedZone("ZLEGACYSTUBID")).thenThrow( + new AwsException("NoSuchHostedZone", "No hosted zone found with ID: ZLEGACYSTUBID", 404)); + VpcAssociation firstVpc = new VpcAssociation("vpc-123", "us-east-1"); + VpcAssociation secondVpc = new VpcAssociation("vpc-456", "us-west-2"); + HostedZone zone = new HostedZone("Z987654321", "ssm.us-east-1.amazonaws.com.", + "dns-stack/Zone", null, firstVpc); + when(service.createHostedZone(eq("ssm.us-east-1.amazonaws.com"), eq("dns-stack/Zone"), + eq(null), argThat(sameVpc(firstVpc)))).thenReturn( + new Route53Service.CreateZoneResult(zone, null)); + RuntimeException associateFailure = new AwsException( + "ServiceUnavailable", "throttled", 503); + when(service.associateVpcWithHostedZone(eq("Z987654321"), argThat(sameVpc(secondVpc)), any())) + .thenThrow(associateFailure); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode props = mapper.createObjectNode().put("Name", "ssm.us-east-1.amazonaws.com"); + ((com.fasterxml.jackson.databind.node.ObjectNode) props).set("VPCs", mapper.createArrayNode() + .add(mapper.createObjectNode().put("VPCId", "vpc-123").put("VPCRegion", "us-east-1")) + .add(mapper.createObjectNode().put("VPCId", "vpc-456").put("VPCRegion", "us-west-2"))); + + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(invocation -> invocation.getArgument(0).asText()); + when(engine.resolveNode(props)).thenReturn(props); + ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack"); + StackResource resource = new StackResource(); + resource.setLogicalId("Zone"); + resource.setResourceType("AWS::Route53::HostedZone"); + resource.setPhysicalId("ZLEGACYSTUBID"); + + RuntimeException thrown = assertThrows(RuntimeException.class, + () -> new Route53CfnProvisioner(service).provision(resource, props, context)); + + assertEquals(associateFailure, thrown); + verify(service).deleteHostedZone("Z987654321"); + assertTrue("true".equals(resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR)), + "once the replacement zone is deleted, physical state matches pre-update reality " + + "(tracked zone missing), so the generic rollback walker must treat this " + + "resource as restored instead of failing rollback as unimplemented"); + } + + @Test + void deletesReplacementZoneWhenTagWriteFailsDuringUpdateRecreate() { + Route53Service service = mock(Route53Service.class); + when(service.getHostedZone("ZLEGACYSTUBID")).thenThrow( + new AwsException("NoSuchHostedZone", "No hosted zone found with ID: ZLEGACYSTUBID", 404)); + HostedZone zone = new HostedZone("Z987654321", "ssm.us-east-1.amazonaws.com.", + "dns-stack/Zone", null, (VpcAssociation) null); + when(service.createHostedZone(eq("ssm.us-east-1.amazonaws.com"), eq("dns-stack/Zone"), + eq(null), eq(null))).thenReturn(new Route53Service.CreateZoneResult(zone, null)); + when(service.getNameServers()).thenReturn(List.of("ns-1.example", "ns-2.example")); + RuntimeException tagFailure = new AwsException("ServiceUnavailable", "throttled", 503); + org.mockito.Mockito.doThrow(tagFailure).when(service) + .changeTagsForResource(eq("hostedzone"), eq("Z987654321"), any(), any()); + + ObjectMapper mapper = new ObjectMapper(); + JsonNode props = mapper.createObjectNode().put("Name", "ssm.us-east-1.amazonaws.com"); + ((com.fasterxml.jackson.databind.node.ObjectNode) props).set("HostedZoneTags", mapper.createArrayNode() + .add(mapper.createObjectNode().put("Key", "Accelerator").put("Value", "AWSAccelerator"))); + + CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class); + when(engine.resolve(any())).thenAnswer(invocation -> invocation.getArgument(0).asText()); + when(engine.resolveNode(props)).thenReturn(props); + ProvisionContext context = new ProvisionContext(engine, "us-east-1", "623666680275", "dns-stack"); + StackResource resource = new StackResource(); + resource.setLogicalId("Zone"); + resource.setResourceType("AWS::Route53::HostedZone"); + resource.setPhysicalId("ZLEGACYSTUBID"); + + RuntimeException thrown = assertThrows(RuntimeException.class, + () -> new Route53CfnProvisioner(service).provision(resource, props, context)); + + assertEquals(tagFailure, thrown); + verify(service).deleteHostedZone("Z987654321"); + assertTrue("true".equals(resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR)), + "once the replacement zone is deleted, physical state matches pre-update reality " + + "(tracked zone missing), so the generic rollback walker must treat this " + + "resource as restored instead of failing rollback as unimplemented"); + } +} diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv index fef02467a7..f5baace543 100644 --- a/src/test/resources/cloudformation/supported-resource-types.tsv +++ b/src/test/resources/cloudformation/supported-resource-types.tsv @@ -96,7 +96,7 @@ AWS::RDS::DBParameterGroup LEGACY_SWITCH AWS::RDS::DBProxy LEGACY_SWITCH AWS::RDS::DBProxyTargetGroup LEGACY_SWITCH AWS::RDS::DBSubnetGroup LEGACY_SWITCH -AWS::Route53::HostedZone LEGACY_SWITCH +AWS::Route53::HostedZone Route53CfnProvisioner AWS::Route53::RecordSet LEGACY_SWITCH AWS::S3::Bucket S3CfnProvisioner AWS::S3::BucketPolicy S3CfnProvisioner