diff --git a/compatibility-tests/compat-opentofu/test/opentofu.bats b/compatibility-tests/compat-opentofu/test/opentofu.bats index 292fe4c1f8..e7ea0d62f0 100644 --- a/compatibility-tests/compat-opentofu/test/opentofu.bats +++ b/compatibility-tests/compat-opentofu/test/opentofu.bats @@ -359,7 +359,7 @@ sha256_composite_by_sizes() { @test "OpenTofu: Route53 hosted zone created" { ZONE_ID=$(aws_cmd route53 list-hosted-zones \ - --query "HostedZones[?Name=='floci-compat.internal.'].Id | [0]" \ + --query "HostedZones[?Name=='floci-compat.internal.' && !(Config.PrivateZone)].Id | [0]" \ --output text | sed 's|/hostedzone/||') [ -n "$ZONE_ID" ] run aws_cmd route53 get-hosted-zone --id "$ZONE_ID" @@ -369,7 +369,7 @@ sha256_composite_by_sizes() { @test "OpenTofu: Route53 A record created" { ZONE_ID=$(aws_cmd route53 list-hosted-zones \ - --query "HostedZones[?Name=='floci-compat.internal.'].Id | [0]" \ + --query "HostedZones[?Name=='floci-compat.internal.' && !(Config.PrivateZone)].Id | [0]" \ --output text | sed 's|/hostedzone/||') run aws_cmd route53 list-resource-record-sets --hosted-zone-id "$ZONE_ID" assert_success @@ -379,7 +379,7 @@ sha256_composite_by_sizes() { @test "OpenTofu: Route53 zone has auto-created SOA and NS records" { ZONE_ID=$(aws_cmd route53 list-hosted-zones \ - --query "HostedZones[?Name=='floci-compat.internal.'].Id | [0]" \ + --query "HostedZones[?Name=='floci-compat.internal.' && !(Config.PrivateZone)].Id | [0]" \ --output text | sed 's|/hostedzone/||') run aws_cmd route53 list-resource-record-sets --hosted-zone-id "$ZONE_ID" assert_success @@ -400,7 +400,7 @@ sha256_composite_by_sizes() { @test "OpenTofu: Route53 zone tags persisted" { ZONE_ID=$(aws_cmd route53 list-hosted-zones \ - --query "HostedZones[?Name=='floci-compat.internal.'].Id | [0]" \ + --query "HostedZones[?Name=='floci-compat.internal.' && !(Config.PrivateZone)].Id | [0]" \ --output text | sed 's|/hostedzone/||') run aws_cmd route53 list-tags-for-resource \ --resource-type hostedzone --resource-id "$ZONE_ID" diff --git a/compatibility-tests/compat-terraform/test/terraform.bats b/compatibility-tests/compat-terraform/test/terraform.bats index b73c9d94fa..f4f0b1cd83 100644 --- a/compatibility-tests/compat-terraform/test/terraform.bats +++ b/compatibility-tests/compat-terraform/test/terraform.bats @@ -382,7 +382,7 @@ sha256_composite_by_sizes() { @test "Terraform: Route53 hosted zone created" { ZONE_ID=$(aws_cmd route53 list-hosted-zones \ - --query "HostedZones[?Name=='floci-compat.internal.'].Id | [0]" \ + --query "HostedZones[?Name=='floci-compat.internal.' && !(Config.PrivateZone)].Id | [0]" \ --output text | sed 's|/hostedzone/||') [ -n "$ZONE_ID" ] run aws_cmd route53 get-hosted-zone --id "$ZONE_ID" @@ -392,7 +392,7 @@ sha256_composite_by_sizes() { @test "Terraform: Route53 A record created" { ZONE_ID=$(aws_cmd route53 list-hosted-zones \ - --query "HostedZones[?Name=='floci-compat.internal.'].Id | [0]" \ + --query "HostedZones[?Name=='floci-compat.internal.' && !(Config.PrivateZone)].Id | [0]" \ --output text | sed 's|/hostedzone/||') run aws_cmd route53 list-resource-record-sets --hosted-zone-id "$ZONE_ID" assert_success @@ -402,7 +402,7 @@ sha256_composite_by_sizes() { @test "Terraform: Route53 zone has auto-created SOA and NS records" { ZONE_ID=$(aws_cmd route53 list-hosted-zones \ - --query "HostedZones[?Name=='floci-compat.internal.'].Id | [0]" \ + --query "HostedZones[?Name=='floci-compat.internal.' && !(Config.PrivateZone)].Id | [0]" \ --output text | sed 's|/hostedzone/||') run aws_cmd route53 list-resource-record-sets --hosted-zone-id "$ZONE_ID" assert_success @@ -423,7 +423,7 @@ sha256_composite_by_sizes() { @test "Terraform: Route53 zone tags persisted" { ZONE_ID=$(aws_cmd route53 list-hosted-zones \ - --query "HostedZones[?Name=='floci-compat.internal.'].Id | [0]" \ + --query "HostedZones[?Name=='floci-compat.internal.' && !(Config.PrivateZone)].Id | [0]" \ --output text | sed 's|/hostedzone/||') run aws_cmd route53 list-tags-for-resource \ --resource-type hostedzone --resource-id "$ZONE_ID" diff --git a/docs/services/cloudmap.md b/docs/services/cloudmap.md index 3528632abd..e368571d4f 100644 --- a/docs/services/cloudmap.md +++ b/docs/services/cloudmap.md @@ -12,10 +12,14 @@ Asynchronous operations (`CreateHttpNamespace`, `CreatePublicDnsNamespace`, `CreatePrivateDnsNamespace`, `DeleteNamespace`, `RegisterInstance`, `DeregisterInstance`) apply their effect synchronously and return an operation id. The operation reaches `SUCCESS` immediately by default, so a follow-up -`GetOperation` call returns a completed operation without polling. No Route 53 -hosted zones are created: public and private DNS namespaces are assigned a -synthetic `HostedZoneId` so SDK and CLI clients can exercise the full Cloud Map -control flow locally. +`GetOperation` call returns a completed operation without polling. + +Public and private DNS namespaces create a real Route 53 hosted zone named after +the namespace (private zones are associated with the namespace's VPC and region) +and report its id as `HostedZoneId`, so `route53 get-hosted-zone` and +`aws_route53_record` against it work. `DeleteNamespace` deletes the zone with the +namespace; if you added records of your own to the zone, the delete fails with +`HostedZoneNotEmpty` and the namespace is kept. HTTP namespaces have no zone. `ListNamespaces`, `ListServices`, and `ListOperations` accept `MaxResults` from 1 to 100 (default 100) and an opaque `NextToken`. Final and empty collections @@ -84,11 +88,11 @@ containers, not to processes on the host. | Operation | Notes | |-----------|-------| | `CreateHttpNamespace` | Creates an `HTTP` namespace; returns an operation id | -| `CreatePublicDnsNamespace` | Creates a `DNS_PUBLIC` namespace with a synthetic `HostedZoneId` | -| `CreatePrivateDnsNamespace` | Creates a `DNS_PRIVATE` namespace; requires `Vpc`, assigns a `HostedZoneId` | +| `CreatePublicDnsNamespace` | Creates a `DNS_PUBLIC` namespace and a public Route 53 hosted zone, reported as `HostedZoneId` | +| `CreatePrivateDnsNamespace` | Creates a `DNS_PRIVATE` namespace and a private Route 53 hosted zone associated with `Vpc` (required), reported as `HostedZoneId` | | `GetNamespace` | Returns a namespace by `Id` | | `ListNamespaces` | Lists namespaces in the current region | -| `DeleteNamespace` | Deletes an empty namespace; fails with `ResourceInUse` if it still has services | +| `DeleteNamespace` | Deletes an empty namespace and its hosted zone; fails with `ResourceInUse` if it still has services, `HostedZoneNotEmpty` if the zone holds records you added | | `CreateService` | Creates a service (optionally under a namespace), tracks revision and instance count | | `GetService` | Returns a service by `Id` | | `ListServices` | Lists services, optionally filtered by `NamespaceId` | @@ -199,7 +203,7 @@ print(found["Instances"]) ## Out of Scope -- Route 53 hosted zone / record set creation. +- Route 53 record sets managed by Cloud Map. A namespace's hosted zone exists, but instances are answered from Cloud Map state rather than written into it as records. - Route 53 health checks backing `HealthCheckConfig` (custom health status is stored, not actively probed). - `AWS_INIT_HEALTH_STATUS` and `AWS_EC2_INSTANCE_ID` on `RegisterInstance`. Every instance registers `HEALTHY`, which is AWS's own initial status when `AWS_INIT_HEALTH_STATUS` is absent, so only a caller that explicitly asks for `UNHEALTHY` sees a difference. - Cross-region namespace and service discovery. A DNS query carries no region, so a name resolves through whichever namespace copy holds instances. diff --git a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java index 5c41ae94c4..1b20f32114 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java @@ -405,11 +405,22 @@ public class EmbeddedDnsServer { if (recordSources == null) { return Optional.empty(); } + // Two sources can own the same zone (a Cloud Map namespace and the Route 53 zone behind it), + // and bean order is unspecified. An empty answer (NXDOMAIN, or NODATA for a name holding only + // other types) only speaks for that source, so it must not win over another source's records; + // it is returned only if no source has any, an existing name preferred over NXDOMAIN. + Optional empty = Optional.empty(); for (DnsRecordSource source : recordSources) { try { Optional answer = authoritative ? source.resolveAuthoritative(name, type) : source.resolve(name, type); if (answer != null && answer.isPresent()) { + if (answer.get().isEmpty()) { + if (empty.isEmpty() || (!empty.get().nameExists() && answer.get().nameExists())) { + empty = answer; + } + continue; + } return answer; } } catch (Exception e) { @@ -417,7 +428,7 @@ public class EmbeddedDnsServer { source.getClass().getSimpleName(), name, e.getMessage()); } } - return Optional.empty(); + return empty; } byte[] buildEmptyResponse(byte[] query, short txId, int questionOffset, int questionEnd, int responseCode) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java index 9186fd8853..b26d6d1718 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java @@ -22,6 +22,8 @@ import io.github.hectorvent.floci.services.cloudmap.model.Instance; import io.github.hectorvent.floci.services.cloudmap.model.Namespace; import io.github.hectorvent.floci.services.cloudmap.model.Operation; import io.github.hectorvent.floci.services.cloudmap.model.Service; +import io.github.hectorvent.floci.services.route53.Route53Service; +import io.github.hectorvent.floci.services.route53.model.VpcAssociation; import io.netty.util.NetUtil; import jakarta.annotation.PreDestroy; import jakarta.enterprise.context.ApplicationScoped; @@ -69,13 +71,15 @@ public class CloudMapService { private final StorageBackend instanceStore; private final StorageBackend operationStore; private final RegionResolver regionResolver; + private final Route53Service route53Service; private final ObjectMapper objectMapper; private final int completionDelaySeconds; private final ScheduledExecutorService scheduler; @Inject public CloudMapService(StorageFactory storageFactory, EmulatorConfig config, - RegionResolver regionResolver, ObjectMapper objectMapper) { + RegionResolver regionResolver, ObjectMapper objectMapper, + Route53Service route53Service) { this.namespaceStore = storageFactory.create("cloudmap", "cloudmap-namespaces.json", new TypeReference>() {}); this.serviceStore = storageFactory.create("cloudmap", "cloudmap-services.json", @@ -85,6 +89,7 @@ public class CloudMapService { this.operationStore = storageFactory.create("cloudmap", "cloudmap-operations.json", new TypeReference>() {}); this.regionResolver = regionResolver; + this.route53Service = route53Service; this.objectMapper = objectMapper; this.completionDelaySeconds = config.services().cloudmap().operationCompletionDelaySeconds(); this.scheduler = completionDelaySeconds > 0 @@ -115,7 +120,7 @@ public class CloudMapService { public Operation createPublicDnsNamespace(String name, String creatorRequestId, String description, Map tags, String region) { Namespace ns = newNamespace(name, "DNS_PUBLIC", description, creatorRequestId, tags, region); - ns.setHostedZoneId(generateHostedZoneId()); + ns.setHostedZoneId(createZone(ns, null)); namespaceStore.put(ns.getId(), ns); return submitOperation("CREATE_NAMESPACE", "NAMESPACE", ns.getId(), region); } @@ -127,7 +132,7 @@ public class CloudMapService { } Namespace ns = newNamespace(name, "DNS_PRIVATE", description, creatorRequestId, tags, region); ns.setVpc(vpc); - ns.setHostedZoneId(generateHostedZoneId()); + ns.setHostedZoneId(createZone(ns, new VpcAssociation(vpc, region))); namespaceStore.put(ns.getId(), ns); return submitOperation("CREATE_NAMESPACE", "NAMESPACE", ns.getId(), region); } @@ -192,6 +197,20 @@ public class CloudMapService { throw new AwsException("ResourceInUse", "The namespace contains existing services and cannot be deleted.", 400); } + if (ns.getHostedZoneId() != null) { + // The zone goes with the namespace. A zone holding records beyond the default NS/SOA + // is refused (HostedZoneNotEmpty) and the namespace is kept, rather than orphaning records. + try { + route53Service.deleteHostedZone(ns.getHostedZoneId()); + } catch (AwsException e) { + if (!"NoSuchHostedZone".equals(e.getErrorCode())) { + throw e; + } + // Already deleted through Route 53; nothing is orphaned, so the namespace still goes. + LOG.debugv("Hosted zone {0} of Cloud Map namespace {1} was already deleted", + ns.getHostedZoneId(), id); + } + } namespaceStore.delete(id); return submitOperation("DELETE_NAMESPACE", "NAMESPACE", id, region); } @@ -938,12 +957,9 @@ public class CloudMapService { return sb.toString(); } - private String generateHostedZoneId() { - StringBuilder sb = new StringBuilder("Z"); - String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - for (int i = 0; i < 13; i++) { - sb.append(chars.charAt(random.nextInt(chars.length()))); - } - return sb.toString(); + /** Creates the Route 53 zone behind a DNS namespace (private when a VPC association is given). */ + private String createZone(Namespace ns, VpcAssociation vpc) { + return route53Service.createHostedZone(ns.getName(), "cloudmap-" + ns.getId(), + "Created by Cloud Map namespace " + ns.getId(), vpc).zone().getId(); } } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/dns/CloudMapDnsPacketIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/dns/CloudMapDnsPacketIntegrationTest.java index 40e66090d9..671cf505b6 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/dns/CloudMapDnsPacketIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/dns/CloudMapDnsPacketIntegrationTest.java @@ -3,6 +3,10 @@ package io.github.hectorvent.floci.core.common.dns; import io.github.hectorvent.floci.services.cloudmap.CloudMapDnsRecordSource; import io.github.hectorvent.floci.services.cloudmap.CloudMapService; import io.github.hectorvent.floci.services.cloudmap.model.Service; +import io.github.hectorvent.floci.services.route53.Route53DnsRecordSource; +import io.github.hectorvent.floci.services.route53.Route53Service; +import io.github.hectorvent.floci.services.route53.model.ResourceRecord; +import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet; import io.quarkus.test.junit.QuarkusTest; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; @@ -13,6 +17,7 @@ import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -35,6 +40,12 @@ class CloudMapDnsPacketIntegrationTest { @Inject CloudMapDnsRecordSource cloudMapDnsRecordSource; + @Inject + Route53DnsRecordSource route53DnsRecordSource; + + @Inject + Route53Service route53Service; + @Inject Vertx vertx; @@ -58,6 +69,64 @@ class CloudMapDnsPacketIntegrationTest { Arrays.copyOfRange(response, request.length + 12, request.length + 16)); } + /** + * The namespace's Route 53 zone covers the same names, and answers NXDOMAIN for a name it + * has no record for, or NOERROR/NODATA for a name holding only another type (the TXT below). + * With that source consulted first, Cloud Map's A record must still win. + */ + @Test + void cloudMapInstanceResolvesWhenTheRoute53ZoneSourceIsConsultedFirst() throws Exception { + String namespace = uniqueNamespace(); + String namespaceId = privateDnsNamespace(namespace); + Service service = cloudMapService.createService("both", namespaceId, null, null, + "{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":15}]}", null, null, null, Map.of(), REGION); + cloudMapService.registerInstance(service.getId(), "task-1", null, + Map.of("AWS_INSTANCE_IPV4", "172.31.0.7"), REGION); + String zoneId = cloudMapService.getNamespace(namespaceId).getHostedZoneId(); + List> txts = new ArrayList<>(); + for (String txtName : List.of("both." + namespace, "txtonly." + namespace)) { + ResourceRecordSet txt = new ResourceRecordSet(); + txt.setName(txtName); + txt.setType("TXT"); + txt.setTtl(60L); + txt.setRecords(List.of(new ResourceRecord("\"owner=test\""))); + route53Service.changeResourceRecordSets(zoneId, List.of(Map.of("action", "CREATE", "rrs", txt)), null); + txts.add(Map.of("action", "DELETE", "rrs", txt)); + } + try { + assertBothSourceOrdersResolve(namespace); + } finally { + // The namespace's zone must hold only its SOA and NS again, or DeleteNamespace fails. + route53Service.changeResourceRecordSets(zoneId, txts, null); + } + } + + private void assertBothSourceOrdersResolve(String namespace) throws Exception { + for (List sources : List.of( + List.of(route53DnsRecordSource, cloudMapDnsRecordSource), + List.of(cloudMapDnsRecordSource, route53DnsRecordSource))) { + byte[] request = buildQuery("both." + namespace, (short) 1); + byte[] response = query(new EmbeddedDnsServer(List.of(), sources), request); + ByteBuffer packet = ByteBuffer.wrap(response); + + assertEquals(0, packet.getShort(2) & 0x000F); + assertEquals(1, packet.getShort(6)); + assertArrayEquals(new byte[]{(byte) 172, 31, 0, 7}, + Arrays.copyOfRange(response, request.length + 12, request.length + 16)); + + // A name only Route 53 holds (as TXT) is NODATA for A, not Cloud Map's NXDOMAIN. + ByteBuffer txtOnly = ByteBuffer.wrap(query(new EmbeddedDnsServer(List.of(), sources), + buildQuery("txtonly." + namespace, (short) 1))); + assertEquals(0, txtOnly.getShort(2) & 0x000F); + assertEquals(0, txtOnly.getShort(6)); + } + // A name neither source has is still NXDOMAIN. + byte[] missing = query(new EmbeddedDnsServer(List.of(), + List.of(route53DnsRecordSource, cloudMapDnsRecordSource)), + buildQuery("nothere." + namespace, (short) 1)); + assertEquals(3, ByteBuffer.wrap(missing).getShort(2) & 0x000F); + } + @Test void srvOnlyNameReturnsNoDataForAQuery() throws Exception { String namespace = uniqueNamespace(); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java b/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java index 9f70ae7381..1609c21cdb 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java @@ -207,6 +207,46 @@ class EmbeddedDnsServerTest { withSource.resolveARecord("bucket.localhost.floci.io", "172.31.0.2")); } + @Test + void anotherSourcesRecordsWinOverRefused() { + DnsRecordSource refusing = name -> Optional.of(DnsAnswer.refused()); + EmbeddedDnsServer withSources = new EmbeddedDnsServer(List.of(), + List.of(refusing, source("api.sapphire.internal", List.of("172.31.0.6")))); + + DnsAnswer answer = withSources.resolveARecordWithOwnership( + "api.sapphire.internal", "172.31.0.2").orElseThrow(); + assertEquals(List.of("172.31.0.6"), answer.addresses()); + assertEquals(0, answer.responseCode()); + } + + @Test + void refusedWinsOverNxDomainInEitherOrder() { + DnsRecordSource refusing = name -> Optional.of(DnsAnswer.refused()); + DnsRecordSource absent = name -> Optional.of(DnsAnswer.nxDomain()); + for (List sources : List.of(List.of(refusing, absent), List.of(absent, refusing))) { + assertEquals(5, new EmbeddedDnsServer(List.of(), sources).resolveARecordWithOwnership( + "api.sapphire.internal", "172.31.0.2").orElseThrow().responseCode()); + } + } + + // Current behaviour, not a decision: a plain NODATA from one source beats another source's + // NXDOMAIN even when that NXDOMAIN carries a Route 53 SOA, so the SOA authority is dropped. + // Unreachable today, since only one source answers authoritatively. + @Test + void noDataCurrentlyWinsOverNxDomainCarryingAuthority() { + DnsAnswer nxWithSoa = DnsAnswer.nxDomain().withAuthority("sapphire.internal", + new DnsRecord.Soa("ns.example. host.example. 1 7200 900 1209600 30"), 900); + DnsRecordSource authoritative = name -> Optional.of(nxWithSoa); + DnsRecordSource noData = name -> Optional.of(DnsAnswer.noData()); + for (List sources : List.of(List.of(authoritative, noData), + List.of(noData, authoritative))) { + DnsAnswer answer = new EmbeddedDnsServer(List.of(), sources).resolveARecordWithOwnership( + "api.sapphire.internal", "172.31.0.2").orElseThrow(); + assertEquals(0, answer.responseCode()); + assertNull(answer.authority()); + } + } + private static DnsRecordSource source(String owned, List addresses) { return source(owned, addresses, DnsAnswer.DEFAULT_TTL_SECONDS); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudMapCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudMapCfnIntegrationTest.java index 52d8a9c8c1..1f036dcc63 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudMapCfnIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudMapCfnIntegrationTest.java @@ -143,7 +143,8 @@ class CloudMapCfnIntegrationTest { .then().statusCode(200) .extract().asString()) .path("Namespace").path("Properties").path("DnsProperties").path("HostedZoneId").asText(null); - assertThat(hostedZoneId, matchesPattern("Z[A-Z0-9]{13}")); + // A bare Route 53 zone id (no /hostedzone/ prefix); AWS ids vary in length, so none is pinned. + assertThat(hostedZoneId, matchesPattern("Z[A-Z0-9]+")); assertEquals(hostedZoneId, outputValue(outputs, "NsHz")); assertEquals("main", outputValue(outputs, "SvcName")); assertThat(outputValue(outputs, "NoNameName"), matchesPattern("SvcNoName-[0-9a-f]{12}")); diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapIntegrationTest.java index e920cf411d..ec57509083 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapIntegrationTest.java @@ -12,6 +12,7 @@ import org.junit.jupiter.api.TestMethodOrder; import java.util.ArrayList; import java.util.List; +import java.util.Map; import static io.restassured.RestAssured.given; import static org.hamcrest.MatcherAssert.assertThat; @@ -215,6 +216,92 @@ class CloudMapIntegrationTest { call("DeleteNamespace", "{\"Id\":\"" + customNamespaceId + "\"}").then().statusCode(200); } + @Test + void privateDnsNamespaceBacksARealPrivateHostedZone() { + String nsId = createDnsNamespace("CreatePrivateDnsNamespace", + "{\"Name\":\"cm-private.example.com\",\"Vpc\":\"vpc-cm123456\"}"); + String zoneId = hostedZoneId(nsId); + + given().get("/2013-04-01/hostedzone/" + zoneId).then().statusCode(200) + .body("GetHostedZoneResponse.HostedZone.Name", equalTo("cm-private.example.com.")) + .body("GetHostedZoneResponse.HostedZone.Config.PrivateZone", equalTo("true")) + .body("GetHostedZoneResponse.VPCs.VPC.VPCId", equalTo("vpc-cm123456")); + + call("DeleteNamespace", "{\"Id\":\"" + nsId + "\"}").then().statusCode(200); + given().get("/2013-04-01/hostedzone/" + zoneId).then().statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchHostedZone")); + } + + @Test + void publicDnsNamespaceBacksARealPublicHostedZone() { + String nsId = createDnsNamespace("CreatePublicDnsNamespace", "{\"Name\":\"cm-public.example.com\"}"); + String zoneId = hostedZoneId(nsId); + + given().get("/2013-04-01/hostedzone/" + zoneId).then().statusCode(200) + .body("GetHostedZoneResponse.HostedZone.Name", equalTo("cm-public.example.com.")) + .body("GetHostedZoneResponse.HostedZone.Config.PrivateZone", equalTo("false")); + + call("DeleteNamespace", "{\"Id\":\"" + nsId + "\"}").then().statusCode(200); + given().get("/2013-04-01/hostedzone/" + zoneId).then().statusCode(404); + } + + @Test + void deleteNamespaceWithServicesKeepsNamespaceAndZone() { + String nsId = createDnsNamespace("CreatePrivateDnsNamespace", + "{\"Name\":\"cm-inuse.example.com\",\"Vpc\":\"vpc-cm123456\"}"); + String zoneId = hostedZoneId(nsId); + call("CreateService", "{\"Name\":\"s\",\"NamespaceId\":\"" + nsId + "\"}").then().statusCode(200); + + call("DeleteNamespace", "{\"Id\":\"" + nsId + "\"}").then().statusCode(400) + .body("__type", equalTo("ResourceInUse")); + + call("GetNamespace", "{\"Id\":\"" + nsId + "\"}").then().statusCode(200); + given().get("/2013-04-01/hostedzone/" + zoneId).then().statusCode(200); + } + + @Test + void deleteNamespaceToleratesAZoneThatIsAlreadyGone() { + String nsId = createDnsNamespace("CreatePublicDnsNamespace", "{\"Name\":\"cm-nozone.example.com\"}"); + given().delete("/2013-04-01/hostedzone/" + hostedZoneId(nsId)).then().statusCode(200); + + call("DeleteNamespace", "{\"Id\":\"" + nsId + "\"}").then().statusCode(200); + call("GetNamespace", "{\"Id\":\"" + nsId + "\"}").then().statusCode(404) + .body("__type", equalTo("NamespaceNotFound")); + } + + @Test + void deleteNamespaceWithUserRecordsInTheZoneKeepsTheNamespace() { + String nsId = createDnsNamespace("CreatePublicDnsNamespace", "{\"Name\":\"cm-records.example.com\"}"); + String zoneId = hostedZoneId(nsId); + given().contentType("application/xml").body(""" + + CREATE + www.cm-records.example.comA60 + 10.0.0.1 + + """) + .post("/2013-04-01/hostedzone/" + zoneId + "/rrset").then().statusCode(200); + + call("DeleteNamespace", "{\"Id\":\"" + nsId + "\"}").then().statusCode(400) + .body("__type", equalTo("HostedZoneNotEmpty")); + call("GetNamespace", "{\"Id\":\"" + nsId + "\"}").then().statusCode(200); + } + + private static String createDnsNamespace(String action, String body) { + String operationId = call(action, body).then().statusCode(200) + .extract().jsonPath().getString("OperationId"); + return call("GetOperation", "{\"OperationId\":\"" + operationId + "\"}") + .then().statusCode(200).extract().jsonPath().getString("Operation.Targets.NAMESPACE"); + } + + @SuppressWarnings("unchecked") + private static String hostedZoneId(String nsId) { + Map ns = call("GetNamespace", "{\"Id\":\"" + nsId + "\"}").then().statusCode(200) + .extract().jsonPath().getMap("Namespace"); + Map props = (Map) ns.get("Properties"); + return (String) ((Map) props.get("DnsProperties")).get("HostedZoneId"); + } + private static String createCustomHealthService(String name, String nsId, String healthCheckCustomConfig) { return call("CreateService", "{\"Name\":\"" + name + "\",\"NamespaceId\":\"" + nsId + "\",\"HealthCheckCustomConfig\":" + healthCheckCustomConfig + "}")