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

@@ -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; }
}