feat(route53): VPC association lifecycle actions (#2638)

* feat(route53): add VPC association lifecycle actions

Zone creation already persists VPC associations, but the lifecycle
operations that manage them afterwards were missing. Adds, on top of the
existing VpcAssociation model:

- AssociateVPCWithHostedZone   POST /hostedzone/{Id}/associatevpc
- DisassociateVPCFromHostedZone POST /hostedzone/{Id}/disassociatevpc
- CreateVPCAssociationAuthorization POST /hostedzone/{Id}/authorizevpcassociation
- DeleteVPCAssociationAuthorization POST /hostedzone/{Id}/deauthorizevpcassociation
- ListHostedZonesByVPC          GET  /hostedzonesbyvpc

Request paths, XML element names and response shapes follow the Route 53
2013-04-01 rest-xml model, including HostedZoneSummary's HostedZoneId and
Owner members, and ListHostedZonesByVPC honours maxitems/nexttoken.
Associate is idempotent; disassociate raises VPCAssociationNotFound for
an unknown VPC and LastVPCAssociation when it would remove the only
remaining association, and associating a public zone raises
PublicZoneVPCAssociation.

VpcAssociation has no value equality, so associations are matched on VPC
ID and region rather than object identity.

The two authorization endpoints are shape-only: hosted zones are not
account-scoped here, so an authorization cannot gate a later associate
call. They validate the request and echo the VPC back.

* fix(route53): enforce the VPCRegion enum on the VPC association actions

AssociateVPCWithHostedZone, DisassociateVPCFromHostedZone, the two
authorization actions and ListHostedZonesByVPC all read VPCRegion and
stored or matched on it verbatim. A region outside the modelled enum was
accepted, so the association was written under a region that could never
be matched again: the associate reported INSYNC while the later
disassociate answered VPCAssociationNotFound and ListHostedZonesByVPC
silently omitted the zone.

Reject an unmodelled VPCRegion with InvalidInput, which the model lists
for every one of these operations. The check carries the enum from the
model rather than reusing AwsRegions.KNOWN_IDS, because the enum admits
the ISO and European Sovereign partitions the emulator never advertises.

* fix(route53): reject unmodelled VPC regions on create and fix VPC-list pagination

CreateHostedZone stored a VPC association's region without checking it
against the modelled VPCRegion enum, so an association created that way
could never be found again by the later disassociate/list lifecycle
actions, which do check it. ListHostedZonesByVPC also silently restarted
pagination on an unrecognized NextToken and ignored a non-positive
MaxItems instead of rejecting both with InvalidInput.

* fix(route53): don't strand legacy VPC regions, and stabilize equal-name pagination

Two review findings from the latest re-review:
- ListHostedZonesByVPC and DisassociateVPCFromHostedZone rejected any VPCRegion outside the
  modelled enum before ever touching storage, so an association persisted under a region since
  retired from the enum (or from before this check existed) could never be listed or removed —
  only a full hosted-zone deletion could get rid of it. The enum check now applies only to the
  paths that create a new association (AssociateVPCWithHostedZone, CreateHostedZone,
  CreateVPCAssociationAuthorization); lookups and removal accept whatever region is on record.
- ListHostedZonesByVPC sorted matches by name only, so two zones with the same name were ordered
  however the backing store happened to iterate them, which can differ between the page-1 and
  page-2 scans and desync the id-based NextToken continuation point. The sort now tie-breaks by
  id so the total order is fixed regardless of iteration order.

* fix(route53): use the modeled InvalidPaginationToken and ConflictingDomainExists errors

ListHostedZonesByVPC returned the generic InvalidInput for an
unrecognized NextToken instead of the purpose-built
InvalidPaginationToken the model declares for exactly this operation.
AssociateVPCWithHostedZone also let the same VPC attach to two
different hosted zones sharing a name, something the model documents
as ConflictingDomainExists; the existing listHostedZonesByVpc lookup
now scans for that conflict before storing a new association.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-28 08:19:14 -04:00
1 parent c4050936a8
commit e471946f44
3 files changed
+713

No files matched your search

@@ -33,6 +33,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Path("/2013-04-01")
public class Route53Controller {
@@ -40,6 +41,28 @@ public class Route53Controller {
private static final String NS = AwsNamespaces.ROUTE53;
private static final String XML = "application/xml";
/**
* The {@code VPCRegion} enum, verbatim from the Route 53 model. Deliberately not
* {@code AwsRegions.KNOWN_IDS}: the enum admits the ISO and European Sovereign
* partitions that this emulator never advertises, and rejecting those would refuse
* requests AWS accepts.
*/
private static final Set<String> VPC_REGIONS = Set.of(
"us-east-1", "us-east-2", "us-west-1", "us-west-2",
"eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", "eu-central-2",
"ap-east-1", "ap-east-2", "me-south-1", "me-central-1",
"us-gov-west-1", "us-gov-east-1",
"us-iso-east-1", "us-iso-west-1", "us-isob-east-1", "us-isob-west-1",
"us-isof-south-1", "us-isof-east-1", "eu-isoe-west-1", "eusc-de-east-1",
"ap-southeast-1", "ap-southeast-2", "ap-southeast-3", "ap-southeast-4",
"ap-southeast-5", "ap-southeast-6", "ap-southeast-7",
"ap-south-1", "ap-south-2",
"ap-northeast-1", "ap-northeast-2", "ap-northeast-3",
"eu-north-1", "sa-east-1", "ca-central-1", "ca-west-1",
"cn-north-1", "cn-northwest-1",
"af-south-1", "eu-south-1", "eu-south-2",
"il-central-1", "mx-central-1");
private static final XMLInputFactory XML_FACTORY;
static {
@@ -62,6 +85,9 @@ public class Route53Controller {
String callerRef = XmlParser.extractFirst(body, "CallerReference", null);
String comment = XmlParser.extractFirst(body, "Comment", null);
VpcAssociation vpcAssociation = parseVpcAssociation(body);
if (vpcAssociation != null) {
requireModelledVpcRegion(vpcAssociation.getVpcRegion());
}
if (name == null || callerRef == null) {
throw new AwsException("InvalidInput", "Name and CallerReference are required.", 400);
@@ -180,6 +206,146 @@ public class Route53Controller {
}
}
// ── VPC Associations ──────────────────────────────────────────────────────
@POST
@Path("/hostedzone/{Id}/associatevpc")
public Response associateVpcWithHostedZone(@PathParam("Id") String id, String body) {
try {
VpcAssociation vpc = requireVpcAssociation(body);
String comment = XmlParser.extractFirst(body, "Comment", null);
ChangeInfo change = service.associateVpcWithHostedZone(id, vpc, comment);
String xml = new XmlBuilder()
.start("AssociateVPCWithHostedZoneResponse", NS)
.raw(xmlChangeInfo(change))
.end("AssociateVPCWithHostedZoneResponse")
.build();
return Response.ok(xml, XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@POST
@Path("/hostedzone/{Id}/disassociatevpc")
public Response disassociateVpcFromHostedZone(@PathParam("Id") String id, String body) {
try {
VpcAssociation vpc = requireVpcAssociationWithoutRegionCheck(body);
String comment = XmlParser.extractFirst(body, "Comment", null);
ChangeInfo change = service.disassociateVpcFromHostedZone(id, vpc, comment);
String xml = new XmlBuilder()
.start("DisassociateVPCFromHostedZoneResponse", NS)
.raw(xmlChangeInfo(change))
.end("DisassociateVPCFromHostedZoneResponse")
.build();
return Response.ok(xml, XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
/**
* Authorization is only meaningful when the zone and the VPC belong to different
* accounts. Zones are not account-scoped here, so this validates the request and
* echoes the authorized VPC back without gating a later associate call.
*/
@POST
@Path("/hostedzone/{Id}/authorizevpcassociation")
public Response createVpcAssociationAuthorization(@PathParam("Id") String id, String body) {
try {
VpcAssociation vpc = requireVpcAssociation(body);
service.getHostedZone(id);
String xml = new XmlBuilder()
.start("CreateVPCAssociationAuthorizationResponse", NS)
.elem("HostedZoneId", id)
.raw(xmlVpcAssociation(vpc))
.end("CreateVPCAssociationAuthorizationResponse")
.build();
return Response.ok(xml, XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
/**
* Counterpart to {@link #createVpcAssociationAuthorization}; the response has no members,
* so this returns the response's root element with nothing inside it.
*/
@POST
@Path("/hostedzone/{Id}/deauthorizevpcassociation")
public Response deleteVpcAssociationAuthorization(@PathParam("Id") String id, String body) {
try {
requireVpcAssociation(body);
service.getHostedZone(id);
String xml = new XmlBuilder()
.start("DeleteVPCAssociationAuthorizationResponse", NS)
.end("DeleteVPCAssociationAuthorizationResponse")
.build();
return Response.ok(xml, XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@GET
@Path("/hostedzonesbyvpc")
public Response listHostedZonesByVpc(@QueryParam("vpcid") String vpcId,
@QueryParam("vpcregion") String vpcRegion,
@QueryParam("maxitems") @DefaultValue("100") int maxItems,
@QueryParam("nexttoken") String nextToken) {
try {
if (vpcId == null || vpcId.isEmpty()) {
throw new AwsException("InvalidInput", "VPCId is required.", 400);
}
if (vpcRegion == null || vpcRegion.isEmpty()) {
throw new AwsException("InvalidInput", "VPCRegion is required.", 400);
}
// Deliberately not enum-gated: an association persisted under a region since
// retired from VPC_REGIONS (or from before this check existed) must remain listable.
if (maxItems <= 0) {
throw new AwsException("InvalidInput", "MaxItems must be a positive integer.", 400);
}
List<HostedZone> zones = service.listHostedZonesByVpc(vpcId, vpcRegion);
if (nextToken != null && !nextToken.isEmpty()) {
int idx = -1;
for (int i = 0; i < zones.size(); i++) {
if (zones.get(i).getId().equals(nextToken)) {
idx = i + 1;
break;
}
}
if (idx < 0) {
throw new AwsException("InvalidPaginationToken",
"Invalid value for NextToken: " + nextToken, 400);
}
zones = zones.subList(idx, zones.size());
}
boolean truncated = zones.size() > maxItems;
if (truncated) {
zones = zones.subList(0, maxItems);
}
XmlBuilder xml = new XmlBuilder()
.start("ListHostedZonesByVPCResponse", NS)
.start("HostedZoneSummaries");
for (HostedZone zone : zones) {
xml.raw(xmlHostedZoneSummary(zone));
}
xml.end("HostedZoneSummaries")
.elem("MaxItems", String.valueOf(maxItems));
if (truncated) {
xml.elem("NextToken", zones.get(zones.size() - 1).getId());
}
xml.end("ListHostedZonesByVPCResponse");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@GET
@Path("/hostedzonecount")
public Response getHostedZoneCount() {
@@ -564,6 +730,18 @@ public class Route53Controller {
return xml.end("VPCs").build();
}
private String xmlHostedZoneSummary(HostedZone zone) {
return new XmlBuilder()
.start("HostedZoneSummary")
.elem("HostedZoneId", zone.getId())
.elem("Name", zone.getName())
.start("Owner")
.elem("OwningAccount", service.getDefaultAccountId())
.end("Owner")
.end("HostedZoneSummary")
.build();
}
private String xmlResourceRecordSet(ResourceRecordSet rrs) {
XmlBuilder xml = new XmlBuilder()
.start("ResourceRecordSet")
@@ -651,6 +829,43 @@ public class Route53Controller {
return new VpcAssociation(vpcId, vpcRegion);
}
/**
* Parses the VPC element for the association operations, where AWS marks VPC as a
* required member — unlike CreateHostedZone, where its absence just means a public zone.
*/
private VpcAssociation requireVpcAssociation(String body) {
VpcAssociation vpc = requireVpcAssociationWithoutRegionCheck(body);
requireModelledVpcRegion(vpc.getVpcRegion());
return vpc;
}
/**
* Same as {@link #requireVpcAssociation}, but skips the enum check: used by disassociate,
* where the target may be a legacy-persisted association whose region has since left
* VPC_REGIONS (or predates the enum check entirely). Rejecting the lookup here would strand
* that association — impossible to remove without deleting the whole hosted zone.
*/
private VpcAssociation requireVpcAssociationWithoutRegionCheck(String body) {
VpcAssociation vpc = parseVpcAssociation(body);
if (vpc == null) {
throw new AwsException("InvalidInput", "VPC is required.", 400);
}
return vpc;
}
/**
* Rejects a VPCRegion outside the modelled enum. Without this the association is stored
* under a region that can never be matched again, so the associate reports success while
* the later disassociate and ListHostedZonesByVPC silently miss it.
*/
private static void requireModelledVpcRegion(String vpcRegion) {
if (!VPC_REGIONS.contains(vpcRegion)) {
throw new AwsException("InvalidInput",
"Invalid value '" + vpcRegion + "' at 'VPCRegion' failed to satisfy constraint: "
+ "Member must satisfy enum value set.", 400);
}
}
/**
* Parses the ChangeBatch XML using StAX to correctly handle multiple Change elements,
* each containing a ResourceRecordSet with its own set of ResourceRecord/Value children.
@@ -38,6 +38,7 @@ public class Route53Service {
private final StorageBackend<String, ChangeInfo> changeStore;
private final StorageBackend<String, Map<String, String>> tagStore;
private final List<String> nameServers;
private final String defaultAccountId;
@Inject
public Route53Service(StorageFactory factory, EmulatorConfig config) {
@@ -59,6 +60,7 @@ public class Route53Service {
r53.defaultNameserver3(),
r53.defaultNameserver4()
);
this.defaultAccountId = config.defaultAccountId();
}
// ── Hosted Zones ──────────────────────────────────────────────────────────
@@ -151,6 +153,97 @@ public class Route53Service {
return zoneStore.keys().size();
}
// ── VPC Associations ──────────────────────────────────────────────────────
/**
* Associates a VPC with a private hosted zone. Re-associating a VPC that is
* already attached is a no-op, matching the idempotent AWS behaviour.
*/
public synchronized ChangeInfo associateVpcWithHostedZone(String zoneId, VpcAssociation vpc,
String comment) {
HostedZone zone = getHostedZone(zoneId);
if (!zone.isPrivateZone()) {
throw new AwsException("PublicZoneVPCAssociation",
"You're trying to associate a VPC with a public hosted zone. "
+ "Public hosted zones can't be associated with a VPC.", 400);
}
if (findAssociation(zone, vpc) == null) {
for (HostedZone other : listHostedZonesByVpc(vpc.getVpcId(), vpc.getVpcRegion())) {
if (!other.getId().equals(zoneId) && other.getName().equals(zone.getName())) {
throw new AwsException("ConflictingDomainExists",
"The VPC that you chose, " + vpc.getVpcId() + " in region " + vpc.getVpcRegion()
+ ", is already associated with another hosted zone that has the same name.",
400);
}
}
zone.getVpcAssociations().add(vpc);
zoneStore.put(zoneId, zone);
}
return newChange(comment);
}
/**
* Disassociates a VPC from a private hosted zone. AWS refuses to remove the
* only remaining association — the zone would become unresolvable.
*/
public synchronized ChangeInfo disassociateVpcFromHostedZone(String zoneId, VpcAssociation vpc,
String comment) {
HostedZone zone = getHostedZone(zoneId);
VpcAssociation existing = findAssociation(zone, vpc);
if (existing == null) {
throw new AwsException("VPCAssociationNotFound",
"The VPC " + vpc.getVpcId() + " in region " + vpc.getVpcRegion()
+ " is not associated with hosted zone " + zoneId + ".", 404);
}
if (zone.getVpcAssociations().size() == 1) {
throw new AwsException("LastVPCAssociation",
"The VPC that you chose, " + vpc.getVpcId() + " in region " + vpc.getVpcRegion()
+ ", is the last VPC that is associated with the hosted zone.", 400);
}
zone.getVpcAssociations().remove(existing);
zoneStore.put(zoneId, zone);
return newChange(comment);
}
/**
* Returns every hosted zone associated with the given VPC, regardless of the
* account that created the zone.
*/
public List<HostedZone> listHostedZonesByVpc(String vpcId, String vpcRegion) {
List<HostedZone> matches = new ArrayList<>();
for (HostedZone zone : zoneStore.scan(k -> true)) {
if (findAssociation(zone, new VpcAssociation(vpcId, vpcRegion)) != null) {
zone.setResourceRecordSetCount(recordCount(zone.getId()));
matches.add(zone);
}
}
// Tie-break by id: name alone leaves equal-named zones ordered by the backing store's
// own iteration, which can differ between the page-1 and page-2 scans and desync the
// id-based NextToken continuation point (skipping or repeating an entry).
matches.sort((a, b) -> {
int cmp = a.getName().compareTo(b.getName());
return cmp != 0 ? cmp : a.getId().compareTo(b.getId());
});
return matches;
}
/**
* {@link VpcAssociation} has no value equality, so associations are matched on
* their ID and region rather than by object identity.
*/
private static VpcAssociation findAssociation(HostedZone zone, VpcAssociation vpc) {
if (zone.getVpcAssociations() == null) {
return null;
}
for (VpcAssociation candidate : zone.getVpcAssociations()) {
if (vpc.getVpcId().equals(candidate.getVpcId())
&& vpc.getVpcRegion().equals(candidate.getVpcRegion())) {
return candidate;
}
}
return null;
}
// ── Resource Record Sets ──────────────────────────────────────────────────
public synchronized ChangeInfo changeResourceRecordSets(String zoneId,
@@ -304,6 +397,10 @@ public class Route53Service {
return nameServers;
}
public String getDefaultAccountId() {
return defaultAccountId;
}
private static String normalizeName(String name) {
if (name == null || name.isEmpty()) return name;
return name.endsWith(".") ? name : name + ".";
@@ -0,0 +1,401 @@
package io.github.hectorvent.floci.services.route53;
import io.github.hectorvent.floci.services.route53.model.VpcAssociation;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class Route53VpcAssociationIntegrationTest {
private static final String XML = "application/xml";
@Inject
Route53Service service;
@Test
void associateListAndDisassociateRoundTrip() {
String zoneId = createPrivateZone("roundtrip.internal.", "vpc-assoc-roundtrip", "vpc-roundtrip-primary");
given().contentType(XML)
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", "vpc-roundtrip-secondary",
"<Comment>central endpoints</Comment>"))
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(200)
.body(containsString("<AssociateVPCWithHostedZoneResponse"))
.body(containsString("<ChangeInfo>"))
.body(containsString("<Status>INSYNC</Status>"));
given().get("/2013-04-01/hostedzone/" + zoneId)
.then().statusCode(200)
.body(containsString("<VPCId>vpc-roundtrip-primary</VPCId>"))
.body(containsString("<VPCId>vpc-roundtrip-secondary</VPCId>"));
given().get("/2013-04-01/hostedzonesbyvpc?vpcid=vpc-roundtrip-secondary&vpcregion=us-east-1")
.then().statusCode(200)
.body(containsString("<ListHostedZonesByVPCResponse"))
.body(containsString("<HostedZoneSummary>"))
.body(containsString("<HostedZoneId>" + zoneId + "</HostedZoneId>"))
.body(containsString("<Name>roundtrip.internal.</Name>"))
.body(containsString("<OwningAccount>"))
.body(containsString("<MaxItems>"));
given().contentType(XML)
.body(vpcRequest("DisassociateVPCFromHostedZoneRequest", "vpc-roundtrip-secondary", ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/disassociatevpc")
.then().statusCode(200)
.body(containsString("<DisassociateVPCFromHostedZoneResponse"))
.body(containsString("<Status>INSYNC</Status>"));
given().get("/2013-04-01/hostedzone/" + zoneId)
.then().statusCode(200)
.body(containsString("<VPCId>vpc-roundtrip-primary</VPCId>"))
.body(not(containsString("<VPCId>vpc-roundtrip-secondary</VPCId>")));
given().get("/2013-04-01/hostedzonesbyvpc?vpcid=vpc-roundtrip-secondary&vpcregion=us-east-1")
.then().statusCode(200)
.body(not(containsString("<HostedZoneId>" + zoneId + "</HostedZoneId>")));
}
@Test
void associateIsIdempotentForAnAlreadyAssociatedVpc() {
String zoneId = createPrivateZone("idempotent.internal.", "vpc-assoc-idempotent", "vpc-idempotent-primary");
given().contentType(XML)
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", "vpc-idempotent-primary", ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(200);
// The zone must still carry exactly one association, so removing it is the
// last-association case rather than leaving a duplicate behind.
given().contentType(XML)
.body(vpcRequest("DisassociateVPCFromHostedZoneRequest", "vpc-idempotent-primary", ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/disassociatevpc")
.then().statusCode(400)
.body(containsString("<Code>LastVPCAssociation</Code>"));
}
@Test
void listHostedZonesByVpcPaginatesWithNextToken() {
String shared = "vpc-paginated-shared";
String firstZone = createPrivateZone("aaa-paged.internal.", "vpc-assoc-paged-a", shared);
String secondZone = createPrivateZone("bbb-paged.internal.", "vpc-assoc-paged-b", shared);
String token = given().get("/2013-04-01/hostedzonesbyvpc?vpcid=" + shared
+ "&vpcregion=us-east-1&maxitems=1")
.then().statusCode(200)
.body(containsString("<HostedZoneId>" + firstZone + "</HostedZoneId>"))
.body(not(containsString("<HostedZoneId>" + secondZone + "</HostedZoneId>")))
.body(containsString("<NextToken>"))
.extract().path("ListHostedZonesByVPCResponse.NextToken").toString();
// Following the token must advance the page rather than repeat the first one.
given().get("/2013-04-01/hostedzonesbyvpc?vpcid=" + shared
+ "&vpcregion=us-east-1&maxitems=1&nexttoken=" + token)
.then().statusCode(200)
.body(containsString("<HostedZoneId>" + secondZone + "</HostedZoneId>"))
.body(not(containsString("<HostedZoneId>" + firstZone + "</HostedZoneId>")))
.body(not(containsString("<NextToken>")));
}
@Test
void associateWithPublicZoneIsRejected() {
String create = """
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<Name>public-assoc.example.com</Name>
<CallerReference>vpc-assoc-public-zone</CallerReference>
</CreateHostedZoneRequest>
""";
String zoneId = zoneIdFrom(given().contentType(XML).body(create)
.post("/2013-04-01/hostedzone")
.then().statusCode(201).extract().header("Location"));
given().contentType(XML)
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", "vpc-public-reject", ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(400)
.body(containsString("<Code>PublicZoneVPCAssociation</Code>"));
}
@Test
void disassociateUnknownVpcReturnsVpcAssociationNotFound() {
String zoneId = createPrivateZone("notfound.internal.", "vpc-assoc-notfound", "vpc-notfound-primary");
given().contentType(XML)
.body(vpcRequest("DisassociateVPCFromHostedZoneRequest", "vpc-never-associated", ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/disassociatevpc")
.then().statusCode(404)
.body(containsString("<Code>VPCAssociationNotFound</Code>"));
}
@Test
void associateWithoutVpcElementIsInvalidInput() {
String zoneId = createPrivateZone("novpc.internal.", "vpc-assoc-missing-vpc", "vpc-missing-primary");
String body = """
<AssociateVPCWithHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<Comment>no vpc supplied</Comment>
</AssociateVPCWithHostedZoneRequest>
""";
given().contentType(XML).body(body)
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(400)
.body(containsString("<Code>InvalidInput</Code>"));
}
@Test
void associateWithUnknownHostedZoneReturnsNoSuchHostedZone() {
given().contentType(XML)
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", "vpc-orphan", ""))
.post("/2013-04-01/hostedzone/ZNOSUCHZONE123/associatevpc")
.then().statusCode(404)
.body(containsString("<Code>NoSuchHostedZone</Code>"));
}
@Test
void createAndDeleteVpcAssociationAuthorization() {
String zoneId = createPrivateZone("authz.internal.", "vpc-assoc-authorization", "vpc-authz-primary");
given().contentType(XML)
.body(vpcRequest("CreateVPCAssociationAuthorizationRequest", "vpc-authz-guest", ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/authorizevpcassociation")
.then().statusCode(200)
.body(containsString("<CreateVPCAssociationAuthorizationResponse"))
.body(containsString("<HostedZoneId>" + zoneId + "</HostedZoneId>"))
.body(containsString("<VPCId>vpc-authz-guest</VPCId>"))
.body(containsString("<VPCRegion>us-east-1</VPCRegion>"));
given().contentType(XML)
.body(vpcRequest("DeleteVPCAssociationAuthorizationRequest", "vpc-authz-guest", ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/deauthorizevpcassociation")
.then().statusCode(200);
}
@Test
void authorizeVpcAssociationOnUnknownZoneReturnsNoSuchHostedZone() {
given().contentType(XML)
.body(vpcRequest("CreateVPCAssociationAuthorizationRequest", "vpc-authz-orphan", ""))
.post("/2013-04-01/hostedzone/ZNOSUCHZONE456/authorizevpcassociation")
.then().statusCode(404)
.body(containsString("<Code>NoSuchHostedZone</Code>"));
}
@Test
void listHostedZonesByVpcRequiresVpcIdAndRegion() {
given().get("/2013-04-01/hostedzonesbyvpc?vpcregion=us-east-1")
.then().statusCode(400)
.body(containsString("<Code>InvalidInput</Code>"))
.body(containsString("VPCId is required"));
given().get("/2013-04-01/hostedzonesbyvpc?vpcid=vpc-no-region")
.then().statusCode(400)
.body(containsString("<Code>InvalidInput</Code>"))
.body(containsString("VPCRegion is required"));
}
@Test
void associateWithAnUnmodelledVpcRegionIsRejected() {
String zoneId = createPrivateZone("badregion.internal.", "vpc-assoc-bad-region", "vpc-badregion-primary");
String body = """
<AssociateVPCWithHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<VPC><VPCRegion>us-east-99</VPCRegion><VPCId>vpc-badregion-secondary</VPCId></VPC>
</AssociateVPCWithHostedZoneRequest>
""";
given().contentType(XML).body(body)
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(400)
.body(containsString("<Code>InvalidInput</Code>"))
.body(containsString("VPCRegion"));
// The rejected association must not have been stored.
given().get("/2013-04-01/hostedzone/" + zoneId)
.then().statusCode(200)
.body(not(containsString("<VPCId>vpc-badregion-secondary</VPCId>")));
}
@Test
void authorizeVpcAssociationWithAnUnmodelledVpcRegionIsRejected() {
String zoneId = createPrivateZone("authzregion.internal.", "vpc-assoc-authz-region", "vpc-authzregion-primary");
String body = """
<CreateVPCAssociationAuthorizationRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<VPC><VPCRegion>not-a-region</VPCRegion><VPCId>vpc-authzregion-guest</VPCId></VPC>
</CreateVPCAssociationAuthorizationRequest>
""";
given().contentType(XML).body(body)
.post("/2013-04-01/hostedzone/" + zoneId + "/authorizevpcassociation")
.then().statusCode(400)
.body(containsString("<Code>InvalidInput</Code>"))
.body(containsString("VPCRegion"));
}
@Test
void listHostedZonesByVpcAcceptsAnUnmodelledVpcRegionAndReturnsNoMatches() {
// Deliberately not enum-gated (see legacyAssociationWithAnUnmodelledRegionCanStillBeListedAndRemoved):
// an unrecognized region with no associations simply yields an empty result, the same as
// any other vpcid/vpcregion pair nothing is associated with.
given().get("/2013-04-01/hostedzonesbyvpc?vpcid=vpc-anything&vpcregion=us-east-99")
.then().statusCode(200)
.body(not(containsString("<HostedZoneSummary>")));
}
/**
* The VPCRegion enum covers partitions this emulator does not advertise, so the check
* must follow the model rather than the DescribeRegions catalog.
*/
@Test
void associateAcceptsAModelledNonCommercialVpcRegion() {
String zoneId = createPrivateZone("isoregion.internal.", "vpc-assoc-iso-region", "vpc-isoregion-primary");
String body = """
<AssociateVPCWithHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<VPC><VPCRegion>us-iso-east-1</VPCRegion><VPCId>vpc-isoregion-secondary</VPCId></VPC>
</AssociateVPCWithHostedZoneRequest>
""";
given().contentType(XML).body(body)
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(200)
.body(containsString("<AssociateVPCWithHostedZoneResponse"));
}
@Test
void createHostedZoneRejectsAnUnmodelledVpcRegion() {
String create = """
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<Name>createregion.internal.</Name>
<CallerReference>vpc-assoc-create-bad-region</CallerReference>
<VPC><VPCRegion>us-east-99</VPCRegion><VPCId>vpc-createregion-primary</VPCId></VPC>
</CreateHostedZoneRequest>
""";
given().contentType(XML).body(create)
.post("/2013-04-01/hostedzone")
.then().statusCode(400)
.body(containsString("<Code>InvalidInput</Code>"))
.body(containsString("VPCRegion"));
}
@Test
void listHostedZonesByVpcWithAnUnknownNextTokenIsInvalidPaginationToken() {
String zoneId = createPrivateZone("badtoken.internal.", "vpc-assoc-bad-token", "vpc-badtoken-primary");
given().get("/2013-04-01/hostedzonesbyvpc?vpcid=vpc-badtoken-primary&vpcregion=us-east-1"
+ "&nexttoken=" + zoneId + "-does-not-exist")
.then().statusCode(400)
.body(containsString("<Code>InvalidPaginationToken</Code>"))
.body(containsString("NextToken"));
}
@Test
void associateWithAVpcAlreadyOnAnotherZoneOfTheSameNameIsConflictingDomainExists() {
String shared = "vpc-domain-conflict-shared";
String firstZone = createPrivateZone("domainconflict.internal.", "vpc-assoc-domain-conflict-a", shared);
String secondZone = createPrivateZone("domainconflict.internal.", "vpc-assoc-domain-conflict-b",
"vpc-domain-conflict-other");
given().contentType(XML)
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", shared, ""))
.post("/2013-04-01/hostedzone/" + secondZone + "/associatevpc")
.then().statusCode(400)
.body(containsString("<Code>ConflictingDomainExists</Code>"));
// The rejected association must not have been stored on the second zone.
given().get("/2013-04-01/hostedzone/" + secondZone)
.then().statusCode(200)
.body(not(containsString("<VPCId>" + shared + "</VPCId>")));
}
@Test
void listHostedZonesByVpcWithANonPositiveMaxItemsIsInvalidInput() {
given().get("/2013-04-01/hostedzonesbyvpc?vpcid=vpc-anything&vpcregion=us-east-1&maxitems=0")
.then().statusCode(400)
.body(containsString("<Code>InvalidInput</Code>"))
.body(containsString("MaxItems"));
}
@Test
void listHostedZonesByVpcPaginationIsStableAcrossEqualNames() {
// Sorting only by name leaves the relative order of equal-named zones dependent on the
// backing store's own iteration order, which can differ between the page-1 and page-2
// fetch calls (each re-scans the store), skipping or repeating an entry at the
// ID-based continuation point. Tie-breaking by ID as well makes the total order fixed
// regardless of iteration order, so this asserts the walk is a stable ID-ascending walk.
String shared = "vpc-tiebreak-shared";
java.util.List<String> zoneIds = new java.util.ArrayList<>();
for (int i = 0; i < 4; i++) {
zoneIds.add(createPrivateZone("tiebreak.internal.", "vpc-tiebreak-" + i, shared));
}
java.util.List<String> expectedOrder = new java.util.ArrayList<>(zoneIds);
java.util.Collections.sort(expectedOrder);
java.util.List<String> walked = new java.util.ArrayList<>();
String token = null;
for (int page = 0; page < zoneIds.size(); page++) {
String url = "/2013-04-01/hostedzonesbyvpc?vpcid=" + shared + "&vpcregion=us-east-1&maxitems=1"
+ (token != null ? "&nexttoken=" + token : "");
io.restassured.response.Response resp = given().get(url).then().statusCode(200).extract().response();
io.restassured.path.xml.XmlPath xml = resp.xmlPath();
walked.add(xml.getString("ListHostedZonesByVPCResponse.HostedZoneSummaries.HostedZoneSummary.HostedZoneId"));
String next = xml.getString("ListHostedZonesByVPCResponse.NextToken");
token = (next == null || next.isEmpty()) ? null : next;
}
assertEquals(expectedOrder, walked,
"pagination across equal-named zones must follow a stable ID-ascending tie-break");
}
@Test
void legacyAssociationWithAnUnmodelledRegionCanStillBeListedAndRemoved() {
// Simulates a VPC association persisted before requireModelledVpcRegion existed (or by a
// region since retired from the enum): seed it directly through the service, bypassing
// the controller's enum check entirely, the way an upgrade would inherit it from disk.
String zoneId = createPrivateZone(
"legacy-region.internal.", "vpc-legacy-region", "vpc-legacy-primary");
service.associateVpcWithHostedZone(zoneId,
new VpcAssociation("vpc-legacy-secondary", "legacy-unmodelled-region-1"), null);
given().get("/2013-04-01/hostedzonesbyvpc?vpcid=vpc-legacy-secondary&vpcregion=legacy-unmodelled-region-1")
.then().statusCode(200)
.body(containsString("<HostedZoneId>" + zoneId + "</HostedZoneId>"));
given().contentType(XML)
.body("""
<DisassociateVPCFromHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<VPC><VPCRegion>legacy-unmodelled-region-1</VPCRegion><VPCId>vpc-legacy-secondary</VPCId></VPC>
</DisassociateVPCFromHostedZoneRequest>
""")
.post("/2013-04-01/hostedzone/" + zoneId + "/disassociatevpc")
.then().statusCode(200)
.body(containsString("<DisassociateVPCFromHostedZoneResponse"));
}
private static String createPrivateZone(String name, String callerReference, String vpcId) {
String create = """
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<Name>%s</Name>
<CallerReference>%s</CallerReference>
<VPC><VPCRegion>us-east-1</VPCRegion><VPCId>%s</VPCId></VPC>
</CreateHostedZoneRequest>
""".formatted(name, callerReference, vpcId);
return zoneIdFrom(given().contentType(XML).body(create)
.post("/2013-04-01/hostedzone")
.then().statusCode(201).extract().header("Location"));
}
private static String vpcRequest(String rootElement, String vpcId, String extra) {
return """
<%s xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<VPC><VPCRegion>us-east-1</VPCRegion><VPCId>%s</VPCId></VPC>%s
</%s>
""".formatted(rootElement, vpcId, extra, rootElement);
}
private static String zoneIdFrom(String location) {
return location.substring(location.lastIndexOf('/') + 1);
}
}