feat(route53): support cross-account VPC associations (#3116)

* feat(route53): support cross-account VPC associations

* test(route53): add SDK cross-account compatibility coverage

* fix(route53): harden cross-account VPC ownership

* fix(ec2): scope default resources by account
This commit is contained in:
Franklin G. Mendoza authored and GitHub committed 2026-09-06 00:05:31 -04:00
1 parent 3927c66040
commit 162211de0c
14 files changed
+962 -48

No files matched your search

@@ -704,10 +704,15 @@ public final class TestFixtures {
}
public static Route53Client route53Client() {
return route53Client("test");
}
public static Route53Client route53Client(String accessKeyId) {
return Route53Client.builder()
.endpointOverride(ENDPOINT)
.region(REGION)
.credentialsProvider(CREDENTIALS)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(accessKeyId, "test")))
.build();
}
@@ -853,10 +858,15 @@ public final class TestFixtures {
}
public static Ec2Client ec2Client() {
return ec2Client("test");
}
public static Ec2Client ec2Client(String accessKeyId) {
return Ec2Client.builder()
.endpointOverride(ENDPOINT)
.region(REGION)
.credentialsProvider(CREDENTIALS)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(accessKeyId, "test")))
.build();
}
@@ -4,16 +4,28 @@ import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.CreateVpcRequest;
import software.amazon.awssdk.services.ec2.model.DeleteVpcRequest;
import software.amazon.awssdk.services.route53.Route53Client;
import software.amazon.awssdk.services.route53.model.CreateHostedZoneRequest;
import software.amazon.awssdk.services.route53.model.AssociateVpcWithHostedZoneRequest;
import software.amazon.awssdk.services.route53.model.CreateHostedZoneResponse;
import software.amazon.awssdk.services.route53.model.CreateVpcAssociationAuthorizationRequest;
import software.amazon.awssdk.services.route53.model.DeleteHostedZoneRequest;
import software.amazon.awssdk.services.route53.model.DeleteVpcAssociationAuthorizationRequest;
import software.amazon.awssdk.services.route53.model.DisassociateVpcFromHostedZoneRequest;
import software.amazon.awssdk.services.route53.model.GetHostedZoneRequest;
import software.amazon.awssdk.services.route53.model.GetHostedZoneResponse;
import software.amazon.awssdk.services.route53.model.ListHostedZonesByVpcRequest;
import software.amazon.awssdk.services.route53.model.ListVpcAssociationAuthorizationsRequest;
import software.amazon.awssdk.services.route53.model.Route53Exception;
import software.amazon.awssdk.services.route53.model.VPC;
import software.amazon.awssdk.services.route53.model.VPCRegion;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowableOfType;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
@DisplayName("Route 53")
class Route53Test {
@@ -32,6 +44,156 @@ class Route53Test {
}
}
@Test
void crossAccountVpcAssociationLifecycleUsesAwsSdkWireContract() {
assumeFalse(TestFixtures.isRealAws(),
"Cross-account compatibility uses Floci account-routing credentials");
String zoneAccount = "000000000401";
String vpcAccount = "000000000402";
try (Route53Client zoneRoute53 = TestFixtures.route53Client(zoneAccount);
Route53Client vpcRoute53 = TestFixtures.route53Client(vpcAccount);
Ec2Client zoneEc2 = TestFixtures.ec2Client(zoneAccount);
Ec2Client vpcEc2 = TestFixtures.ec2Client(vpcAccount)) {
String zoneVpcId = zoneEc2.createVpc(CreateVpcRequest.builder()
.cidrBlock("10.91.0.0/16")
.build()).vpc().vpcId();
String spokeVpcId = vpcEc2.createVpc(CreateVpcRequest.builder()
.cidrBlock("10.92.0.0/16")
.build()).vpc().vpcId();
assertThat(zoneEc2.describeVpcs().vpcs())
.anySatisfy(vpc -> {
assertThat(vpc.isDefault()).isTrue();
assertThat(vpc.ownerId()).isEqualTo(zoneAccount);
});
assertThat(vpcEc2.describeVpcs().vpcs())
.anySatisfy(vpc -> {
assertThat(vpc.isDefault()).isTrue();
assertThat(vpc.ownerId()).isEqualTo(vpcAccount);
});
try (Ec2Client defaultEc2 = TestFixtures.ec2Client()) {
assertThat(defaultEc2.describeVpcs().vpcs())
.anySatisfy(vpc -> assertThat(vpc.isDefault()).isTrue());
}
String zoneId = null;
try {
VPC zoneVpc = VPC.builder()
.vpcId(zoneVpcId)
.vpcRegion(VPCRegion.US_EAST_1)
.build();
VPC spokeVpc = VPC.builder()
.vpcId(spokeVpcId)
.vpcRegion(VPCRegion.US_EAST_1)
.build();
zoneId = zoneRoute53.createHostedZone(CreateHostedZoneRequest.builder()
.name(TestFixtures.uniqueName("cross-account") + ".example.com")
.callerReference(TestFixtures.uniqueName("cross-account-ref"))
.vpc(zoneVpc)
.build()).hostedZone().id();
final String activeZoneId = zoneId;
Route53Exception notAuthorized = catchThrowableOfType(
() -> vpcRoute53.associateVPCWithHostedZone(
AssociateVpcWithHostedZoneRequest.builder()
.hostedZoneId(activeZoneId)
.vpc(spokeVpc)
.build()),
Route53Exception.class);
assertThat(notAuthorized).isNotNull();
assertThat(notAuthorized.statusCode()).isEqualTo(401);
assertThat(notAuthorized.awsErrorDetails().errorCode())
.isEqualTo("NotAuthorizedException");
zoneRoute53.createVPCAssociationAuthorization(
CreateVpcAssociationAuthorizationRequest.builder()
.hostedZoneId(activeZoneId)
.vpc(spokeVpc)
.build());
assertThat(zoneRoute53.listVPCAssociationAuthorizations(
ListVpcAssociationAuthorizationsRequest.builder()
.hostedZoneId(activeZoneId)
.build()).vpCs())
.singleElement()
.satisfies(vpc -> {
assertThat(vpc.vpcId()).isEqualTo(spokeVpcId);
assertThat(vpc.vpcRegion()).isEqualTo(VPCRegion.US_EAST_1);
});
vpcRoute53.associateVPCWithHostedZone(
AssociateVpcWithHostedZoneRequest.builder()
.hostedZoneId(activeZoneId)
.vpc(spokeVpc)
.build());
assertThat(vpcRoute53.listHostedZonesByVPC(
ListHostedZonesByVpcRequest.builder()
.vpcId(spokeVpcId)
.vpcRegion(VPCRegion.US_EAST_1)
.build()).hostedZoneSummaries())
.singleElement()
.satisfies(summary -> {
assertThat(summary.hostedZoneId()).isEqualTo(stripHostedZonePrefix(activeZoneId));
assertThat(summary.owner().owningAccount()).isEqualTo(zoneAccount);
});
zoneRoute53.deleteVPCAssociationAuthorization(
DeleteVpcAssociationAuthorizationRequest.builder()
.hostedZoneId(activeZoneId)
.vpc(spokeVpc)
.build());
assertThat(zoneRoute53.listVPCAssociationAuthorizations(
ListVpcAssociationAuthorizationsRequest.builder()
.hostedZoneId(activeZoneId)
.build()).vpCs()).isEmpty();
assertThat(vpcRoute53.listHostedZonesByVPC(
ListHostedZonesByVpcRequest.builder()
.vpcId(spokeVpcId)
.vpcRegion(VPCRegion.US_EAST_1)
.build()).hostedZoneSummaries())
.singleElement();
vpcRoute53.disassociateVPCFromHostedZone(
DisassociateVpcFromHostedZoneRequest.builder()
.hostedZoneId(activeZoneId)
.vpc(spokeVpc)
.build());
Route53Exception requiresNewAuthorization = catchThrowableOfType(
() -> vpcRoute53.associateVPCWithHostedZone(
AssociateVpcWithHostedZoneRequest.builder()
.hostedZoneId(activeZoneId)
.vpc(spokeVpc)
.build()),
Route53Exception.class);
assertThat(requiresNewAuthorization).isNotNull();
assertThat(requiresNewAuthorization.awsErrorDetails().errorCode())
.isEqualTo("NotAuthorizedException");
} finally {
if (zoneId != null) {
zoneRoute53.deleteHostedZone(DeleteHostedZoneRequest.builder().id(zoneId).build());
}
vpcEc2.deleteVpc(DeleteVpcRequest.builder().vpcId(spokeVpcId).build());
zoneEc2.deleteVpc(DeleteVpcRequest.builder().vpcId(zoneVpcId).build());
}
}
}
private static String stripHostedZonePrefix(String hostedZoneId) {
String prefix = "/hostedzone/";
return hostedZoneId != null && hostedZoneId.startsWith(prefix)
? hostedZoneId.substring(prefix.length())
: hostedZoneId;
}
@Test
void createAndGetPrivateHostedZonePreservesVpcAssociation() {
VPC vpc = VPC.builder()
@@ -457,6 +457,7 @@ These services spawn Docker containers. They require access to the Docker socket
| `FLOCI_SERVICES_TEXTRACT_ENABLED` | `true` | Enable the Textract service |
| `FLOCI_SERVICES_TRANSFER_ENABLED` | `true` | Enable the Transfer Family service |
| `FLOCI_SERVICES_ROUTE53_ENABLED` | `true` | Enable the Route 53 service |
| `FLOCI_SERVICES_ROUTE53_VPC_ASSOCIATION_CONTROL_PLANE_DELAY_MS` | `0` | Simulated processing window for Route 53 VPC association/auth mutations; positive values make documented overlap errors (`PriorRequestNotComplete` / `ConcurrentModification`) reproducible for retry tests |
| `FLOCI_SERVICES_ELBV2_ENABLED` | `true` | Enable the ELBv2 (ALB/NLB) service |
| `FLOCI_SERVICES_ELBV2_MOCK` | `false` | When `true`, load balancers are registered but no containers are spawned |
| `FLOCI_SERVICES_AUTOSCALING_ENABLED` | `true` | Enable the Auto Scaling service |
+9 -4
View File
@@ -12,10 +12,11 @@ Route53 management-plane emulation. Supports hosted zones, resource record sets,
| `DeleteHostedZone` | `DELETE /2013-04-01/hostedzone/{Id}` |
| `ListHostedZones` | `GET /2013-04-01/hostedzone` |
| `ListHostedZonesByName` | `GET /2013-04-01/hostedzonesbyname` |
| `AssociateVPCWithHostedZone` | `POST /2013-04-01/hostedzone/{Id}/associatevpc`. Private zones only; re-associating an attached VPC is a no-op. |
| `AssociateVPCWithHostedZone` | `POST /2013-04-01/hostedzone/{Id}/associatevpc`. Private zones only; cross-account associations require prior authorization. |
| `DisassociateVPCFromHostedZone` | `POST /2013-04-01/hostedzone/{Id}/disassociatevpc`. Refuses to remove the last association (`LastVPCAssociation`). |
| `CreateVPCAssociationAuthorization` | `POST /2013-04-01/hostedzone/{Id}/authorizevpcassociation`. Validates and echoes the VPC; zones are not account-scoped, so no authorization is enforced. |
| `DeleteVPCAssociationAuthorization` | `POST /2013-04-01/hostedzone/{Id}/deauthorizevpcassociation` |
| `CreateVPCAssociationAuthorization` | `POST /2013-04-01/hostedzone/{Id}/authorizevpcassociation`. Must be called by the hosted-zone owner. |
| `DeleteVPCAssociationAuthorization` | `POST /2013-04-01/hostedzone/{Id}/deauthorizevpcassociation`. Must be called by the hosted-zone owner; success has an empty response body. |
| `ListVPCAssociationAuthorizations` | `GET /2013-04-01/hostedzone/{Id}/authorizevpcassociation`. Paginates with `maxresults` / `nexttoken`. |
| `ListHostedZonesByVPC` | `GET /2013-04-01/hostedzonesbyvpc?vpcid=…&vpcregion=…`. Paginates with `maxitems` / `nexttoken`. |
| `GetHostedZoneCount` | `GET /2013-04-01/hostedzonecount` |
| `ChangeResourceRecordSets` | `POST /2013-04-01/hostedzone/{Id}/rrset` |
@@ -47,6 +48,10 @@ Route53 management-plane emulation. Supports hosted zones, resource record sets,
- A hosted zone is private when `CreateHostedZone` carries a `<VPC>` element; `HostedZoneConfig.PrivateZone` is response-only.
- `AssociateVPCWithHostedZone` rejects public zones with `PublicZoneVPCAssociation`, and `DisassociateVPCFromHostedZone` rejects removing the last VPC with `LastVPCAssociation`.
- Associating a VPC that is already attached to another zone with the same name fails with `ConflictingDomainExists`.
- Cross-account association follows the Route 53 authorization lifecycle: the hosted-zone owner authorizes the VPC, the VPC account associates it, and the hosted-zone owner can then delete the authorization without removing the association.
- A cross-account association without a matching authorization fails with `NotAuthorizedException`.
- Private hosted zones support up to 300 VPC associations and up to 1000 outstanding cross-account VPC association authorizations, matching the documented Route 53 default quotas.
- Set `FLOCI_SERVICES_ROUTE53_VPC_ASSOCIATION_CONTROL_PLANE_DELAY_MS` above `0` to emulate a short in-flight control-plane window for retry testing. During that window, a subsequent `AssociateVPCWithHostedZone` for the same hosted zone returns `PriorRequestNotComplete`; overlapping create/delete authorization requests return `ConcurrentModification`. These are the retryable overlap errors documented by Route 53 for those operations.
## Default Nameservers
@@ -68,6 +73,7 @@ ns-4.awsdns-04.co.uk
| `FLOCI_SERVICES_ROUTE53_DEFAULT_NAMESERVER2` | `ns-2.awsdns-02.net` | Second default nameserver |
| `FLOCI_SERVICES_ROUTE53_DEFAULT_NAMESERVER3` | `ns-3.awsdns-03.com` | Third default nameserver |
| `FLOCI_SERVICES_ROUTE53_DEFAULT_NAMESERVER4` | `ns-4.awsdns-04.co.uk` | Fourth default nameserver |
| `FLOCI_SERVICES_ROUTE53_VPC_ASSOCIATION_CONTROL_PLANE_DELAY_MS` | `0` | Optional VPC association/auth processing window used to reproduce documented retryable overlap errors |
## CLI Examples
@@ -141,7 +147,6 @@ aws route53 delete-hosted-zone --id Z1PA6795UKMFR9
- Reusable delegation sets
- Traffic policies and traffic policy instances
- Cross-account VPC association authorization (zones are not account-scoped, so `CreateVPCAssociationAuthorization` is accepted but not enforced)
- Query logging configs
- DNSSEC (key signing keys, enabling/disabling)
- `TestDNSAnswer`
@@ -890,6 +890,14 @@ public interface EmulatorConfig {
@WithDefault("ns-4.awsdns-04.co.uk")
String defaultNameserver4();
/**
* Optional control-plane processing window for VPC association mutations. A positive
* value makes documented Route 53 retryable overlap errors reproducible; zero preserves
* the default immediate-completion behavior.
*/
@WithDefault("0")
long vpcAssociationControlPlaneDelayMs();
}
interface ConfigServiceConfig {
@@ -181,7 +181,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
// resourceId → List<Tag>
private final StorageBackend<String, List<Tag>> tags;
private final StorageBackend<String, CapacityReservation> capacityReservations;
private final Set<String> seededRegions = ConcurrentHashMap.newKeySet();
private final Set<String> seededAccountRegions = ConcurrentHashMap.newKeySet();
// subnetId → counter for IP assignment (runtime-only, not persisted)
private final Map<String, AtomicInteger> subnetIpCounters = new ConcurrentHashMap<>();
@@ -428,7 +428,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
// ─── Default resource seeding ──────────────────────────────────────────────
public void ensureDefaultResources(String region) {
if (!seededRegions.add(region)) {
String ownerAccountId = callerAccountId();
String seedScope = ownerAccountId + "::" + region;
if (!seededAccountRegions.add(seedScope)) {
return;
}
// Already provisioned in a previous run and reloaded from persistent storage: the default
@@ -445,7 +447,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
defaultVpc.setCidrBlock("172.31.0.0/16");
defaultVpc.setState("available");
defaultVpc.setDefault(true);
defaultVpc.setOwnerId(accountId);
defaultVpc.setOwnerId(ownerAccountId);
defaultVpc.setRegion(region);
defaultVpc.getCidrBlockAssociationSet().add(
new VpcCidrBlockAssociation("vpc-cidr-assoc-default", "172.31.0.0/16"));
@@ -469,9 +471,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
subnet.setAvailableIpAddressCount(4091);
subnet.setDefaultForAz(true);
subnet.setMapPublicIpOnLaunch(true);
subnet.setOwnerId(accountId);
subnet.setOwnerId(ownerAccountId);
subnet.setRegion(region);
subnet.setSubnetArn(AwsArnUtils.Arn.of("ec2", region, accountId, "subnet/" + subnetIds[i]).toString());
subnet.setSubnetArn(AwsArnUtils.Arn.of("ec2", region, ownerAccountId, "subnet/" + subnetIds[i]).toString());
subnets.put(key(region, subnetIds[i]), subnet);
}
@@ -495,7 +497,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
String igwId = "igw-default";
InternetGateway igw = new InternetGateway();
igw.setInternetGatewayId(igwId);
igw.setOwnerId(accountId);
igw.setOwnerId(ownerAccountId);
igw.setRegion(region);
igw.getAttachments().add(new InternetGatewayAttachment(vpcId, "available"));
internetGateways.put(key(region, igwId), igw);
@@ -514,7 +516,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
defaultSg.setGroupName("default");
defaultSg.setDescription("default VPC security group");
defaultSg.setVpcId(vpcId);
defaultSg.setOwnerId(accountId);
defaultSg.setOwnerId(callerAccountId());
defaultSg.setRegion(region);
// Default egress: all traffic
@@ -532,7 +534,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
RouteTable mainRt = new RouteTable();
mainRt.setRouteTableId(routeTableId);
mainRt.setVpcId(vpc.getVpcId());
mainRt.setOwnerId(accountId);
mainRt.setOwnerId(callerAccountId());
mainRt.setRegion(region);
mainRt.getRoutes().add(new Route(vpc.getCidrBlock(), "local", "CreateRouteTable"));
@@ -563,7 +565,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
NetworkAcl acl = new NetworkAcl();
acl.setNetworkAclId(networkAclId);
acl.setVpcId(vpcId);
acl.setOwnerId(accountId);
acl.setOwnerId(callerAccountId());
acl.setRegion(region);
acl.setDefault(true);
acl.getEntries().add(naclEntry(100, "-1", "allow", false, "0.0.0.0/0"));
@@ -594,7 +596,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
NetworkAcl acl = new NetworkAcl();
acl.setNetworkAclId(networkAclId);
acl.setVpcId(vpcId);
acl.setOwnerId(accountId);
acl.setOwnerId(callerAccountId());
acl.setRegion(region);
acl.setDefault(false);
acl.getEntries().add(naclEntry(32767, "-1", "deny", false, "0.0.0.0/0"));
@@ -2874,7 +2876,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
vpc.setCidrBlock(cidrBlock);
vpc.setState("available");
vpc.setDefault(isDefault);
vpc.setOwnerId(accountId);
vpc.setOwnerId(callerAccountId());
vpc.setRegion(region);
vpc.getCidrBlockAssociationSet().add(
new VpcCidrBlockAssociation("vpc-cidr-assoc-" + randomHex(8), cidrBlock));
@@ -5411,6 +5413,15 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return vpcs.get(key(region, vpcId)).map(v -> new AccountAwareStorageBackend.OwnedEntry<>(null, v));
}
/**
* Resolves the owning account of a VPC across account partitions when the VPC exists in Floci.
* Cross-service consumers such as Route 53 use this to enforce AWS ownership rules without
* changing the public EC2 API surface. An empty result means the VPC is not modelled locally.
*/
public Optional<String> findVpcOwnerAccount(String region, String vpcId) {
return findAnyVpcEntry(region, vpcId).map(AccountAwareStorageBackend.OwnedEntry::account);
}
public List<VpcPeeringConnection> describeVpcPeeringConnections(String region, List<String> ids,
Map<String, List<String>> filters) {
ensureDefaultResources(region);
@@ -244,17 +244,13 @@ public class Route53Controller {
}
}
/**
* 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.
*/
/** Creates the authorization required before a different account associates its VPC. */
@POST
@Path("/hostedzone/{Id}/authorizevpcassociation")
public Response createVpcAssociationAuthorization(@PathParam("Id") String id, String body) {
try {
VpcAssociation vpc = requireVpcAssociation(body);
service.getHostedZone(id);
service.createVpcAssociationAuthorization(id, vpc);
String xml = new XmlBuilder()
.start("CreateVPCAssociationAuthorizationResponse", NS)
.elem("HostedZoneId", id)
@@ -267,21 +263,59 @@ public class Route53Controller {
}
}
/**
* Counterpart to {@link #createVpcAssociationAuthorization}; the response has no members,
* so this returns the response's root element with nothing inside it.
*/
/** Counterpart to {@link #createVpcAssociationAuthorization}; AWS returns an empty body. */
@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();
VpcAssociation vpc = requireVpcAssociation(body);
service.deleteVpcAssociationAuthorization(id, vpc);
return Response.ok().build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
}
@GET
@Path("/hostedzone/{Id}/authorizevpcassociation")
public Response listVpcAssociationAuthorizations(@PathParam("Id") String id,
@QueryParam("maxresults") @DefaultValue("50") int maxResults,
@QueryParam("nexttoken") String nextToken) {
try {
if (maxResults <= 0) {
throw new AwsException("InvalidInput", "MaxResults must be a positive integer.", 400);
}
List<VpcAssociation> authorizations = service.listVpcAssociationAuthorizations(id);
int start = 0;
if (nextToken != null && !nextToken.isEmpty()) {
start = -1;
for (int i = 0; i < authorizations.size(); i++) {
if (authorizationToken(authorizations.get(i)).equals(nextToken)) {
start = i + 1;
break;
}
}
if (start < 0) {
throw new AwsException("InvalidPaginationToken",
"Invalid value for NextToken: " + nextToken, 400);
}
}
int end = Math.min(authorizations.size(), start + maxResults);
List<VpcAssociation> page = authorizations.subList(start, end);
XmlBuilder xml = new XmlBuilder()
.start("ListVPCAssociationAuthorizationsResponse", NS)
.elem("HostedZoneId", id)
.start("VPCs");
for (VpcAssociation vpc : page) {
xml.raw(xmlVpcAssociation(vpc));
}
xml.end("VPCs");
if (end < authorizations.size() && !page.isEmpty()) {
xml.elem("NextToken", authorizationToken(page.get(page.size() - 1)));
}
xml.end("ListVPCAssociationAuthorizationsResponse");
return Response.ok(xml.build(), XML).build();
} catch (AwsException e) {
return xmlErrorResponse(e);
}
@@ -730,13 +764,17 @@ public class Route53Controller {
return xml.end("VPCs").build();
}
private static String authorizationToken(VpcAssociation association) {
return association.getVpcId() + ":" + association.getVpcRegion();
}
private String xmlHostedZoneSummary(HostedZone zone) {
return new XmlBuilder()
.start("HostedZoneSummary")
.elem("HostedZoneId", zone.getId())
.elem("Name", zone.getName())
.start("Owner")
.elem("OwningAccount", service.getDefaultAccountId())
.elem("OwningAccount", service.ownerAccountId(zone))
.end("Owner")
.end("HostedZoneSummary")
.build();
@@ -3,8 +3,11 @@ package io.github.hectorvent.floci.services.route53;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.route53.model.ChangeInfo;
import io.github.hectorvent.floci.services.route53.model.HealthCheck;
import io.github.hectorvent.floci.services.route53.model.HealthCheckConfig;
@@ -23,25 +26,37 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
@ApplicationScoped
public class Route53Service {
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static final SecureRandom RANDOM = new SecureRandom();
private static final int MAX_VPC_ASSOCIATIONS_PER_ZONE = 300;
private static final int MAX_VPC_ASSOCIATION_AUTHORIZATIONS = 1000;
public record CreateZoneResult(HostedZone zone, ChangeInfo change) {}
private record OwnedZone(String accountId, HostedZone zone) {}
private final StorageBackend<String, HostedZone> zoneStore;
private final StorageBackend<String, List<ResourceRecordSet>> recordStore;
private final StorageBackend<String, HealthCheck> healthCheckStore;
private final StorageBackend<String, ChangeInfo> changeStore;
private final StorageBackend<String, Map<String, String>> tagStore;
private final StorageBackend<String, List<VpcAssociation>> vpcAuthorizationStore;
private final List<String> nameServers;
private final String defaultAccountId;
private final RegionResolver regionResolver;
private final Ec2Service ec2Service;
private final long vpcAssociationControlPlaneDelayMs;
private final Map<String, Long> hostedZoneMutationBusyUntilNanos = new ConcurrentHashMap<>();
private final Map<String, Long> authorizationMutationBusyUntilNanos = new ConcurrentHashMap<>();
@Inject
public Route53Service(StorageFactory factory, EmulatorConfig config) {
public Route53Service(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver,
Ec2Service ec2Service) {
this.zoneStore = factory.create("route53", "route53-zones.json",
new TypeReference<Map<String, HostedZone>>() {});
this.recordStore = factory.create("route53", "route53-records.json",
@@ -52,6 +67,8 @@ public class Route53Service {
new TypeReference<Map<String, ChangeInfo>>() {});
this.tagStore = factory.create("route53", "route53-tags.json",
new TypeReference<Map<String, Map<String, String>>>() {});
this.vpcAuthorizationStore = factory.create("route53", "route53-vpc-association-authorizations.json",
new TypeReference<Map<String, List<VpcAssociation>>>() {});
EmulatorConfig.Route53ServiceConfig r53 = config.services().route53();
this.nameServers = List.of(
@@ -61,6 +78,9 @@ public class Route53Service {
r53.defaultNameserver4()
);
this.defaultAccountId = config.defaultAccountId();
this.regionResolver = regionResolver;
this.ec2Service = ec2Service;
this.vpcAssociationControlPlaneDelayMs = Math.max(0, r53.vpcAssociationControlPlaneDelayMs());
}
// ── Hosted Zones ──────────────────────────────────────────────────────────
@@ -77,7 +97,13 @@ public class Route53Service {
}
String id = generateZoneId();
String callerAccountId = callerAccountId();
validateVpcOwnershipIfKnown(vpcAssociation, callerAccountId);
HostedZone zone = new HostedZone(id, normalizedName, callerReference, comment, vpcAssociation);
zone.setOwnerAccountId(callerAccountId);
if (vpcAssociation != null) {
vpcAssociation.setOwnerAccountId(callerAccountId);
}
zoneStore.put(id, zone);
recordStore.put(id, buildDefaultRecords(normalizedName));
ChangeInfo change = newChange(null);
@@ -105,6 +131,7 @@ public class Route53Service {
zoneStore.delete(id);
recordStore.delete(id);
tagStore.delete("hostedzone/" + id);
vpcAuthorizationStore.delete(id);
return newChange(null);
}
@@ -155,19 +182,90 @@ public class Route53Service {
// ── 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 VpcAssociation createVpcAssociationAuthorization(String zoneId, VpcAssociation vpc) {
getHostedZoneOwnedByCaller(zoneId);
rejectAuthorizationMutationOverlap(zoneId);
resolveVpcOwnerAccount(vpc).ifPresent(vpc::setOwnerAccountId);
List<VpcAssociation> authorizations = new ArrayList<>(vpcAuthorizationStore.get(zoneId).orElse(List.of()));
if (findAssociation(authorizations, vpc) == null) {
if (authorizations.size() >= MAX_VPC_ASSOCIATION_AUTHORIZATIONS) {
throw new AwsException("TooManyVPCAssociationAuthorizations",
"The maximum number of VPC association authorizations has been reached for hosted zone " + zoneId + ".", 400);
}
authorizations.add(vpc);
vpcAuthorizationStore.put(zoneId, authorizations);
markMutationBusy(authorizationMutationBusyUntilNanos, zoneId);
}
return vpc;
}
public synchronized void deleteVpcAssociationAuthorization(String zoneId, VpcAssociation vpc) {
getHostedZoneOwnedByCaller(zoneId);
rejectAuthorizationMutationOverlap(zoneId);
List<VpcAssociation> authorizations = new ArrayList<>(vpcAuthorizationStore.get(zoneId).orElse(List.of()));
VpcAssociation existing = findAssociation(authorizations, vpc);
if (existing == null) {
throw new AwsException("VPCAssociationAuthorizationNotFound",
"The VPC that you specified is not authorized to be associated with the hosted zone.", 404);
}
authorizations.remove(existing);
if (authorizations.isEmpty()) {
vpcAuthorizationStore.delete(zoneId);
} else {
vpcAuthorizationStore.put(zoneId, authorizations);
}
markMutationBusy(authorizationMutationBusyUntilNanos, zoneId);
}
public List<VpcAssociation> listVpcAssociationAuthorizations(String zoneId) {
getHostedZoneOwnedByCaller(zoneId);
List<VpcAssociation> authorizations = new ArrayList<>(vpcAuthorizationStore.get(zoneId).orElse(List.of()));
authorizations.sort((a, b) -> {
int id = a.getVpcId().compareTo(b.getVpcId());
return id != 0 ? id : a.getVpcRegion().compareTo(b.getVpcRegion());
});
return authorizations;
}
/** Associates a VPC with a private hosted zone. */
public synchronized ChangeInfo associateVpcWithHostedZone(String zoneId, VpcAssociation vpc,
String comment) {
HostedZone zone = getHostedZone(zoneId);
OwnedZone ownedZone = getHostedZoneAcrossAccounts(zoneId);
HostedZone zone = ownedZone.zone();
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);
}
rejectHostedZoneMutationOverlap(zoneId);
if (findAssociation(zone, vpc) == null) {
String callerAccountId = callerAccountId();
validateVpcOwnershipIfKnown(vpc, callerAccountId);
List<VpcAssociation> authorizations = new ArrayList<>(
getVpcAuthorizationsForAccount(ownedZone.accountId(), zoneId));
VpcAssociation authorization = findAssociation(authorizations, vpc);
boolean crossAccount = !callerAccountId.equals(ownerAccountId(zone));
if (crossAccount && authorization == null) {
throw new AwsException("NotAuthorizedException",
"Associating the specified VPC with the specified hosted zone has not been authorized.", 401);
}
if (crossAccount && authorization.getOwnerAccountId() == null) {
String resolvedOwner = resolveVpcOwnerAccount(vpc).orElseThrow(() ->
new AwsException("InvalidVPCId",
"The VPC ID that you specified either isn't a valid ID or the current account is not authorized to access this VPC.",
400));
authorization.setOwnerAccountId(resolvedOwner);
putVpcAuthorizationsForAccount(ownedZone.accountId(), zoneId, authorizations);
}
if (authorization != null && authorization.getOwnerAccountId() != null
&& !authorization.getOwnerAccountId().equals(callerAccountId)) {
throw new AwsException("NotAuthorizedException",
"Associating the specified VPC with the specified hosted zone has not been authorized.", 401);
}
if (zone.getVpcAssociations().size() >= MAX_VPC_ASSOCIATIONS_PER_ZONE) {
throw new AwsException("LimitsExceeded",
"The maximum number of VPCs that can be associated with this hosted zone has been reached.", 400);
}
for (HostedZone other : listHostedZonesByVpc(vpc.getVpcId(), vpc.getVpcRegion())) {
if (!other.getId().equals(zoneId) && other.getName().equals(zone.getName())) {
throw new AwsException("ConflictingDomainExists",
@@ -176,8 +274,10 @@ public class Route53Service {
400);
}
}
vpc.setOwnerAccountId(resolveVpcOwnerAccount(vpc).orElse(callerAccountId));
zone.getVpcAssociations().add(vpc);
zoneStore.put(zoneId, zone);
putZoneForAccount(ownedZone.accountId(), zoneId, zone);
markMutationBusy(hostedZoneMutationBusyUntilNanos, zoneId);
}
return newChange(comment);
}
@@ -188,20 +288,45 @@ public class Route53Service {
*/
public synchronized ChangeInfo disassociateVpcFromHostedZone(String zoneId, VpcAssociation vpc,
String comment) {
HostedZone zone = getHostedZone(zoneId);
OwnedZone ownedZone = getHostedZoneAcrossAccounts(zoneId);
HostedZone zone = ownedZone.zone();
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);
}
String associationOwner = existing.getOwnerAccountId();
String callerAccountId = callerAccountId();
String zoneOwner = ownerAccountId(zone);
if (associationOwner == null && !zoneOwner.equals(callerAccountId)) {
associationOwner = resolveVpcOwnerAccount(existing).orElseThrow(() ->
new AwsException("InvalidVPCId",
"The VPC ID that you specified either isn't a valid ID or the current account is not authorized to access this VPC.",
400));
if (!associationOwner.equals(callerAccountId)) {
throw new AwsException("InvalidVPCId",
"The VPC ID that you specified either isn't a valid ID or the current account is not authorized to access this VPC.",
400);
}
existing.setOwnerAccountId(associationOwner);
putZoneForAccount(ownedZone.accountId(), zoneId, zone);
}
if (associationOwner != null
&& !associationOwner.equals(callerAccountId)
&& !zoneOwner.equals(callerAccountId)) {
throw new AwsException("InvalidVPCId",
"The VPC ID that you specified either isn't a valid ID or the current account is not authorized to access this VPC.",
400);
}
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);
putZoneForAccount(ownedZone.accountId(), zoneId, zone);
markMutationBusy(hostedZoneMutationBusyUntilNanos, zoneId);
return newChange(comment);
}
@@ -211,9 +336,12 @@ public class Route53Service {
*/
public List<HostedZone> listHostedZonesByVpc(String vpcId, String vpcRegion) {
List<HostedZone> matches = new ArrayList<>();
for (HostedZone zone : zoneStore.scan(k -> true)) {
for (OwnedZone owned : allHostedZonesAcrossAccounts()) {
HostedZone zone = owned.zone();
if (findAssociation(zone, new VpcAssociation(vpcId, vpcRegion)) != null) {
zone.setResourceRecordSetCount(recordCount(zone.getId()));
if (zone.getOwnerAccountId() == null) {
zone.setOwnerAccountId(owned.accountId());
}
matches.add(zone);
}
}
@@ -235,7 +363,11 @@ public class Route53Service {
if (zone.getVpcAssociations() == null) {
return null;
}
for (VpcAssociation candidate : zone.getVpcAssociations()) {
return findAssociation(zone.getVpcAssociations(), vpc);
}
private static VpcAssociation findAssociation(List<VpcAssociation> associations, VpcAssociation vpc) {
for (VpcAssociation candidate : associations) {
if (vpc.getVpcId().equals(candidate.getVpcId())
&& vpc.getVpcRegion().equals(candidate.getVpcRegion())) {
return candidate;
@@ -401,6 +533,169 @@ public class Route53Service {
return defaultAccountId;
}
public String ownerAccountId(HostedZone zone) {
return zone.getOwnerAccountId() != null ? zone.getOwnerAccountId() : defaultAccountId;
}
private OwnedZone getHostedZoneAcrossAccounts(String zoneId) {
if (zoneStore instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<HostedZone> accountAware =
(AccountAwareStorageBackend<HostedZone>) rawAccountAware;
AccountAwareStorageBackend.OwnedEntry<HostedZone> entry = accountAware.findAnyAccountEntry(zoneId)
.orElseThrow(() -> new AwsException("NoSuchHostedZone",
"No hosted zone found with ID: " + zoneId, 404));
if (entry.value().getOwnerAccountId() == null) {
entry.value().setOwnerAccountId(entry.account());
}
return new OwnedZone(entry.account(), entry.value());
}
HostedZone zone = getHostedZone(zoneId);
return new OwnedZone(ownerAccountId(zone), zone);
}
private List<OwnedZone> allHostedZonesAcrossAccounts() {
if (zoneStore instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<HostedZone> accountAware =
(AccountAwareStorageBackend<HostedZone>) rawAccountAware;
return accountAware.scanAllAccountEntries(k -> true).stream()
.map(entry -> new OwnedZone(entry.accountId(), entry.value()))
.toList();
}
return zoneStore.scan(k -> true).stream()
.map(zone -> new OwnedZone(ownerAccountId(zone), zone))
.toList();
}
private void putZoneForAccount(String accountId, String zoneId, HostedZone zone) {
if (zoneStore instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<HostedZone> accountAware =
(AccountAwareStorageBackend<HostedZone>) rawAccountAware;
accountAware.putForAccount(accountId, zoneId, zone);
return;
}
zoneStore.put(zoneId, zone);
}
private List<VpcAssociation> getVpcAuthorizationsForAccount(String accountId, String zoneId) {
if (vpcAuthorizationStore instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<List<VpcAssociation>> accountAware =
(AccountAwareStorageBackend<List<VpcAssociation>>) rawAccountAware;
return accountAware.getForAccount(accountId, zoneId).orElse(List.of());
}
return vpcAuthorizationStore.get(zoneId).orElse(List.of());
}
private void putVpcAuthorizationsForAccount(String accountId, String zoneId,
List<VpcAssociation> authorizations) {
if (vpcAuthorizationStore instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<List<VpcAssociation>> accountAware =
(AccountAwareStorageBackend<List<VpcAssociation>>) rawAccountAware;
accountAware.putForAccount(accountId, zoneId, authorizations);
return;
}
vpcAuthorizationStore.put(zoneId, authorizations);
}
private HostedZone getHostedZoneOwnedByCaller(String zoneId) {
String callerAccountId = callerAccountId();
if (zoneStore instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<HostedZone> accountAware =
(AccountAwareStorageBackend<HostedZone>) rawAccountAware;
HostedZone zone = accountAware.getForAccount(callerAccountId, zoneId).orElse(null);
if (zone == null && callerAccountId.equals(defaultAccountId)) {
// Only the configured default account can claim pre-account-isolation unscoped data.
// AccountAwareStorageBackend#get migrates that legacy shape into the caller partition.
zone = accountAware.get(zoneId).orElse(null);
}
if (zone == null) {
throw new AwsException("NoSuchHostedZone",
"No hosted zone found with ID: " + zoneId, 404);
}
if (zone.getOwnerAccountId() == null) {
zone.setOwnerAccountId(callerAccountId);
accountAware.putForAccount(callerAccountId, zoneId, zone);
}
if (!callerAccountId.equals(zone.getOwnerAccountId())) {
throw new AwsException("NoSuchHostedZone",
"No hosted zone found with ID: " + zoneId, 404);
}
return zone;
}
HostedZone zone = getHostedZone(zoneId);
if (!ownerAccountId(zone).equals(callerAccountId)) {
throw new AwsException("NoSuchHostedZone",
"No hosted zone found with ID: " + zoneId, 404);
}
return zone;
}
private String callerAccountId() {
return regionResolver != null ? regionResolver.getAccountId() : defaultAccountId;
}
private java.util.Optional<String> resolveVpcOwnerAccount(VpcAssociation vpc) {
if (vpc == null || ec2Service == null) {
return java.util.Optional.empty();
}
return ec2Service.findVpcOwnerAccount(vpc.getVpcRegion(), vpc.getVpcId());
}
private void validateVpcOwnershipIfKnown(VpcAssociation vpc, String callerAccountId) {
if (vpc == null) {
return;
}
java.util.Optional<String> owner = resolveVpcOwnerAccount(vpc);
if (owner.isPresent() && !owner.get().equals(callerAccountId)) {
throw new AwsException("InvalidVPCId",
"The VPC ID that you specified either isn't a valid ID or the current account is not authorized to access this VPC.",
400);
}
}
private void rejectHostedZoneMutationOverlap(String zoneId) {
if (isMutationBusy(hostedZoneMutationBusyUntilNanos, zoneId)) {
throw new AwsException("PriorRequestNotComplete",
"A previous request for this hosted zone is still being processed.", 400);
}
}
private void rejectAuthorizationMutationOverlap(String zoneId) {
if (isMutationBusy(authorizationMutationBusyUntilNanos, zoneId)) {
throw new AwsException("ConcurrentModification",
"Another VPC association authorization mutation is still being processed.", 400);
}
}
private boolean isMutationBusy(Map<String, Long> busyUntilNanos, String zoneId) {
if (vpcAssociationControlPlaneDelayMs <= 0) {
return false;
}
Long deadline = busyUntilNanos.get(zoneId);
if (deadline == null) {
return false;
}
if (System.nanoTime() >= deadline) {
busyUntilNanos.remove(zoneId, deadline);
return false;
}
return true;
}
private void markMutationBusy(Map<String, Long> busyUntilNanos, String zoneId) {
if (vpcAssociationControlPlaneDelayMs <= 0) {
return;
}
busyUntilNanos.put(zoneId, System.nanoTime()
+ TimeUnit.MILLISECONDS.toNanos(vpcAssociationControlPlaneDelayMs));
}
private static String normalizeName(String name) {
if (name == null || name.isEmpty()) return name;
return name.endsWith(".") ? name : name + ".";
@@ -12,6 +12,7 @@ public class HostedZone {
private String name;
private String callerReference;
private String comment;
private String ownerAccountId;
private boolean privateZone;
private int resourceRecordSetCount;
private List<VpcAssociation> vpcAssociations = new ArrayList<>();
@@ -48,6 +49,9 @@ public class HostedZone {
public String getComment() { return comment; }
public void setComment(String comment) { this.comment = comment; }
public String getOwnerAccountId() { return ownerAccountId; }
public void setOwnerAccountId(String ownerAccountId) { this.ownerAccountId = ownerAccountId; }
public boolean isPrivateZone() { return privateZone; }
public void setPrivateZone(boolean privateZone) { this.privateZone = privateZone; }
@@ -7,6 +7,7 @@ public class VpcAssociation {
private String vpcId;
private String vpcRegion;
private String ownerAccountId;
public VpcAssociation() {}
@@ -20,4 +21,7 @@ public class VpcAssociation {
public String getVpcRegion() { return vpcRegion; }
public void setVpcRegion(String vpcRegion) { this.vpcRegion = vpcRegion; }
public String getOwnerAccountId() { return ownerAccountId; }
public void setOwnerAccountId(String ownerAccountId) { this.ownerAccountId = ownerAccountId; }
}
+1
View File
@@ -534,6 +534,7 @@ floci:
enabled: true
route53:
enabled: true
vpc-association-control-plane-delay-ms: 0
transfer:
enabled: true
textract:
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.route53;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.route53.model.VpcAssociation;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
@@ -9,11 +10,15 @@ 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;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
class Route53VpcAssociationIntegrationTest {
private static final String XML = "application/xml";
private static final String ZONE_ACCOUNT = "000000000301";
private static final String VPC_ACCOUNT = "000000000302";
private static final String OTHER_ACCOUNT = "000000000303";
@Inject
Route53Service service;
@@ -158,7 +163,7 @@ class Route53VpcAssociationIntegrationTest {
}
@Test
void createAndDeleteVpcAssociationAuthorization() {
void createListAndDeleteVpcAssociationAuthorization() {
String zoneId = createPrivateZone("authz.internal.", "vpc-assoc-authorization", "vpc-authz-primary");
given().contentType(XML)
@@ -170,10 +175,26 @@ class Route53VpcAssociationIntegrationTest {
.body(containsString("<VPCId>vpc-authz-guest</VPCId>"))
.body(containsString("<VPCRegion>us-east-1</VPCRegion>"));
given().get("/2013-04-01/hostedzone/" + zoneId + "/authorizevpcassociation")
.then().statusCode(200)
.body(containsString("<ListVPCAssociationAuthorizationsResponse"))
.body(containsString("<HostedZoneId>" + zoneId + "</HostedZoneId>"))
.body(containsString("<VPCId>vpc-authz-guest</VPCId>"));
given().contentType(XML)
.body(vpcRequest("DeleteVPCAssociationAuthorizationRequest", "vpc-authz-guest", ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/deauthorizevpcassociation")
.then().statusCode(200);
given().get("/2013-04-01/hostedzone/" + zoneId + "/authorizevpcassociation")
.then().statusCode(200)
.body(not(containsString("<VPCId>vpc-authz-guest</VPCId>")));
given().contentType(XML)
.body(vpcRequest("DeleteVPCAssociationAuthorizationRequest", "vpc-authz-guest", ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/deauthorizevpcassociation")
.then().statusCode(404)
.body(containsString("<Code>VPCAssociationAuthorizationNotFound</Code>"));
}
@Test
@@ -374,6 +395,240 @@ class Route53VpcAssociationIntegrationTest {
.body(containsString("<DisassociateVPCFromHostedZoneResponse"));
}
@Test
void crossAccountAuthorizationEnforcesVpcOwnershipAndCleanupLifecycle() {
String zoneVpc = createVpcForAccount(ZONE_ACCOUNT, "10.81.0.0/16");
String spokeVpc = createVpcForAccount(VPC_ACCOUNT, "10.82.0.0/16");
String zoneId = createPrivateZoneForAccount(
ZONE_ACCOUNT, "cross-account.internal.", "vpc-assoc-cross-account", zoneVpc);
// AWS requires the VPC owner to associate, and requires the hosted-zone owner to
// authorize first. A different account without authorization gets NotAuthorizedException.
given().contentType(XML)
.header("Authorization", route53Auth(VPC_ACCOUNT))
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", spokeVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(401)
.body(containsString("<Code>NotAuthorizedException</Code>"));
given().contentType(XML)
.header("Authorization", route53Auth(ZONE_ACCOUNT))
.body(vpcRequest("CreateVPCAssociationAuthorizationRequest", spokeVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/authorizevpcassociation")
.then().statusCode(200);
// The authorization is specifically for the account that owns this VPC. A third account
// cannot reuse the hosted-zone owner's authorization by copying the VPC id.
given().contentType(XML)
.header("Authorization", route53Auth(OTHER_ACCOUNT))
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", spokeVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(400)
.body(containsString("<Code>InvalidVPCId</Code>"));
given().contentType(XML)
.header("Authorization", route53Auth(VPC_ACCOUNT))
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", spokeVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(200);
// ListHostedZonesByVPC is cross-account and reports the account that owns the zone.
given().header("Authorization", route53Auth(VPC_ACCOUNT))
.get("/2013-04-01/hostedzonesbyvpc?vpcid=" + spokeVpc + "&vpcregion=us-east-1")
.then().statusCode(200)
.body(containsString("<HostedZoneId>" + zoneId + "</HostedZoneId>"))
.body(containsString("<OwningAccount>" + ZONE_ACCOUNT + "</OwningAccount>"));
// AWS documents ListHostedZonesByVPC as cross-account discovery: callers can list
// associations for a VPC regardless of which account owns the VPC or hosted zone.
given().header("Authorization", route53Auth(OTHER_ACCOUNT))
.get("/2013-04-01/hostedzonesbyvpc?vpcid=" + spokeVpc + "&vpcregion=us-east-1")
.then().statusCode(200)
.body(containsString("<HostedZoneId>" + zoneId + "</HostedZoneId>"))
.body(containsString("<OwningAccount>" + ZONE_ACCOUNT + "</OwningAccount>"));
// AWS recommends deleting the authorization after association. Success has an empty body,
// and deleting it must not remove the established association.
given().contentType(XML)
.header("Authorization", route53Auth(ZONE_ACCOUNT))
.body(vpcRequest("DeleteVPCAssociationAuthorizationRequest", spokeVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/deauthorizevpcassociation")
.then().statusCode(200)
.body(org.hamcrest.Matchers.emptyOrNullString());
given().header("Authorization", route53Auth(VPC_ACCOUNT))
.get("/2013-04-01/hostedzonesbyvpc?vpcid=" + spokeVpc + "&vpcregion=us-east-1")
.then().statusCode(200)
.body(containsString("<HostedZoneId>" + zoneId + "</HostedZoneId>"));
// AWS permits either the hosted-zone owner or the VPC owner to disassociate.
given().contentType(XML)
.header("Authorization", route53Auth(ZONE_ACCOUNT))
.body(vpcRequest("DisassociateVPCFromHostedZoneRequest", spokeVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/disassociatevpc")
.then().statusCode(200);
// With the authorization cleaned up, a later reassociation requires a new authorization.
given().contentType(XML)
.header("Authorization", route53Auth(VPC_ACCOUNT))
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", spokeVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(401)
.body(containsString("<Code>NotAuthorizedException</Code>"));
}
@Test
void unownedAuthorizationCannotBeConsumedCrossAccount() {
String zoneVpc = createVpcForAccount(ZONE_ACCOUNT, "10.83.0.0/16");
String zoneId = createPrivateZoneForAccount(
ZONE_ACCOUNT, "unowned-auth.internal.", "vpc-assoc-unowned-auth", zoneVpc);
String unknownVpc = "vpc-unmodelled-cross-account";
given().contentType(XML)
.header("Authorization", route53Auth(ZONE_ACCOUNT))
.body(vpcRequest("CreateVPCAssociationAuthorizationRequest", unknownVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/authorizevpcassociation")
.then().statusCode(200);
given().contentType(XML)
.header("Authorization", route53Auth(OTHER_ACCOUNT))
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", unknownVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(400)
.body(containsString("<Code>InvalidVPCId</Code>"));
}
@Test
void legacyAssociationWithoutOwnerStillRequiresVpcOrZoneOwner() {
String zoneVpc = createVpcForAccount(ZONE_ACCOUNT, "10.84.0.0/16");
String spokeVpc = createVpcForAccount(VPC_ACCOUNT, "10.85.0.0/16");
String zoneId = createPrivateZoneForAccount(
ZONE_ACCOUNT, "legacy-association.internal.", "vpc-assoc-legacy-owner", zoneVpc);
given().contentType(XML)
.header("Authorization", route53Auth(ZONE_ACCOUNT))
.body(vpcRequest("CreateVPCAssociationAuthorizationRequest", spokeVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/authorizevpcassociation")
.then().statusCode(200);
given().contentType(XML)
.header("Authorization", route53Auth(VPC_ACCOUNT))
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", spokeVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then().statusCode(200);
var zone = service.listHostedZonesByVpc(spokeVpc, "us-east-1").stream()
.filter(candidate -> candidate.getId().equals(zoneId))
.findFirst().orElseThrow();
zone.getVpcAssociations().stream()
.filter(association -> spokeVpc.equals(association.getVpcId()))
.findFirst().orElseThrow()
.setOwnerAccountId(null);
given().contentType(XML)
.header("Authorization", route53Auth(OTHER_ACCOUNT))
.body(vpcRequest("DisassociateVPCFromHostedZoneRequest", spokeVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/disassociatevpc")
.then().statusCode(400)
.body(containsString("<Code>InvalidVPCId</Code>"));
given().contentType(XML)
.header("Authorization", route53Auth(VPC_ACCOUNT))
.body(vpcRequest("DisassociateVPCFromHostedZoneRequest", spokeVpc, ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/disassociatevpc")
.then().statusCode(200);
}
@Test
void legacyNonDefaultZoneInfersOwnerFromStoragePartition() {
String zoneVpc = createVpcForAccount(ZONE_ACCOUNT, "10.86.0.0/16");
String zoneId = createPrivateZoneForAccount(
ZONE_ACCOUNT, "legacy-zone.internal.", "vpc-assoc-legacy-zone", zoneVpc);
var legacyZone = service.listHostedZonesByVpc(zoneVpc, "us-east-1").stream()
.filter(candidate -> candidate.getId().equals(zoneId))
.findFirst().orElseThrow();
legacyZone.setOwnerAccountId(null);
given().contentType(XML)
.header("Authorization", route53Auth(ZONE_ACCOUNT))
.body(vpcRequest("CreateVPCAssociationAuthorizationRequest", "vpc-legacy-zone-guest", ""))
.post("/2013-04-01/hostedzone/" + zoneId + "/authorizevpcassociation")
.then().statusCode(200);
given().header("Authorization", route53Auth(ZONE_ACCOUNT))
.get("/2013-04-01/hostedzone/" + zoneId + "/authorizevpcassociation")
.then().statusCode(200)
.body(containsString("<VPCId>vpc-legacy-zone-guest</VPCId>"));
}
@Test
void documentedVpcAssociationQuotaReturnsLimitsExceeded() {
String zoneId = createPrivateZone(
"association-limit.internal.", "vpc-assoc-limit", "vpc-limit-primary");
for (int i = 1; i < 300; i++) {
service.associateVpcWithHostedZone(
zoneId, new VpcAssociation("vpc-limit-" + i, "us-east-1"), null);
}
AwsException error = assertThrows(AwsException.class, () ->
service.associateVpcWithHostedZone(
zoneId, new VpcAssociation("vpc-limit-overflow", "us-east-1"), null));
assertEquals("LimitsExceeded", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
@Test
void documentedAuthorizationQuotaReturnsTooManyAuthorizations() {
String zoneId = createPrivateZone(
"authorization-limit.internal.", "vpc-authz-limit", "vpc-authz-limit-primary");
for (int i = 0; i < 1000; i++) {
service.createVpcAssociationAuthorization(
zoneId, new VpcAssociation("vpc-authz-limit-" + i, "us-east-1"));
}
AwsException error = assertThrows(AwsException.class, () ->
service.createVpcAssociationAuthorization(
zoneId, new VpcAssociation("vpc-authz-limit-overflow", "us-east-1")));
assertEquals("TooManyVPCAssociationAuthorizations", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
private static String createVpcForAccount(String accountId, String cidr) {
return given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", cidr)
.header("Authorization", ec2Auth(accountId))
.post("/")
.then().statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
}
private static String createPrivateZoneForAccount(String accountId, 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)
.header("Authorization", route53Auth(accountId))
.body(create)
.post("/2013-04-01/hostedzone")
.then().statusCode(201).extract().header("Location"));
}
private static String route53Auth(String accountId) {
return "AWS4-HMAC-SHA256 Credential=" + accountId
+ "/20260905/us-east-1/route53/aws4_request, SignedHeaders=host, Signature=abc";
}
private static String ec2Auth(String accountId) {
return "AWS4-HMAC-SHA256 Credential=" + accountId
+ "/20260905/us-east-1/ec2/aws4_request, SignedHeaders=host, Signature=abc";
}
private static String createPrivateZone(String name, String callerReference, String vpcId) {
String create = """
<CreateHostedZoneRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
@@ -0,0 +1,119 @@
package io.github.hectorvent.floci.services.route53;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.containsString;
@QuarkusTest
@TestProfile(Route53VpcAssociationTransientErrorIntegrationTest.DelayProfile.class)
class Route53VpcAssociationTransientErrorIntegrationTest {
private static final String XML = "application/xml";
public static final class DelayProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.storage.mode", "memory",
"floci.services.route53.vpc-association-control-plane-delay-ms", "150");
}
}
@Test
void associationOverlapReturnsPriorRequestNotCompleteThenRetrySucceeds() {
String zoneId = createPrivateZone(
"retry-association.internal.", "retry-association", "vpc-retry-primary");
associate(zoneId, "vpc-retry-secondary")
.statusCode(200);
associate(zoneId, "vpc-retry-tertiary")
.statusCode(400)
.body(containsString("<Code>PriorRequestNotComplete</Code>"));
await().atMost(Duration.ofSeconds(2))
.pollInterval(Duration.ofMillis(25))
.untilAsserted(() -> associate(zoneId, "vpc-retry-tertiary")
.statusCode(200));
}
@Test
void authorizationOverlapReturnsConcurrentModificationThenRetrySucceeds() {
String zoneId = createPrivateZone(
"retry-authorization.internal.", "retry-authorization", "vpc-authz-primary");
authorize(zoneId, "vpc-authz-one")
.statusCode(200);
authorize(zoneId, "vpc-authz-two")
.statusCode(400)
.body(containsString("<Code>ConcurrentModification</Code>"));
await().atMost(Duration.ofSeconds(2))
.pollInterval(Duration.ofMillis(25))
.untilAsserted(() -> authorize(zoneId, "vpc-authz-two")
.statusCode(200));
deauthorize(zoneId, "vpc-authz-one")
.statusCode(400)
.body(containsString("<Code>ConcurrentModification</Code>"));
await().atMost(Duration.ofSeconds(2))
.pollInterval(Duration.ofMillis(25))
.untilAsserted(() -> deauthorize(zoneId, "vpc-authz-one")
.statusCode(200));
}
private static io.restassured.response.ValidatableResponse associate(String zoneId, String vpcId) {
return given().contentType(XML)
.body(vpcRequest("AssociateVPCWithHostedZoneRequest", vpcId))
.post("/2013-04-01/hostedzone/" + zoneId + "/associatevpc")
.then();
}
private static io.restassured.response.ValidatableResponse authorize(String zoneId, String vpcId) {
return given().contentType(XML)
.body(vpcRequest("CreateVPCAssociationAuthorizationRequest", vpcId))
.post("/2013-04-01/hostedzone/" + zoneId + "/authorizevpcassociation")
.then();
}
private static io.restassured.response.ValidatableResponse deauthorize(String zoneId, String vpcId) {
return given().contentType(XML)
.body(vpcRequest("DeleteVPCAssociationAuthorizationRequest", vpcId))
.post("/2013-04-01/hostedzone/" + zoneId + "/deauthorizevpcassociation")
.then();
}
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);
String location = given().contentType(XML)
.body(create)
.post("/2013-04-01/hostedzone")
.then().statusCode(201)
.extract().header("Location");
return location.substring(location.lastIndexOf('/') + 1);
}
private static String vpcRequest(String root, String vpcId) {
return """
<%s xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
<VPC><VPCRegion>us-east-1</VPCRegion><VPCId>%s</VPCId></VPC>
</%s>
""".formatted(root, vpcId, root);
}
}
+1
View File
@@ -187,6 +187,7 @@ services:
DisassociateVpcFromHostedZone: DisassociateVPCFromHostedZone
CreateVpcAssociationAuthorization: CreateVPCAssociationAuthorization
DeleteVpcAssociationAuthorization: DeleteVPCAssociationAuthorization
ListVpcAssociationAuthorizations: ListVPCAssociationAuthorizations
ListHostedZonesByVpc: ListHostedZonesByVPC
GetDnssec: GetDNSSEC
- service: route53resolver