feat(ec2): support VPC peering connections (#2654)

* feat(ec2): support VPC peering connections

CreateVpcPeeringConnection was entirely unimplemented, returning
UnsupportedOperation and blocking all three VPC-peering examples in
terraform-aws-vpc (vpc-peering, vpc-peering-cross-accounts,
vpc-peering-external).

Adds CreateVpcPeeringConnection, AcceptVpcPeeringConnection,
DescribeVpcPeeringConnections, ModifyVpcPeeringConnectionOptions and
DeleteVpcPeeringConnection, matching the resources those examples
actually use (aws_vpc_peering_connection,
aws_vpc_peering_connection_accepter, aws_vpc_peering_connection_options).
Connections start pending-acceptance and only move to active via an
explicit accept, same as real AWS; Terraform's auto_accept convenience
is provider-side, not API-side, so no same-account special-casing is
needed here.

CreateRoute now also accepts VpcPeeringConnectionId as a target and
reports it back on DescribeRouteTables - every one of the three
examples routes traffic through the peering connection via aws_route,
and without this the provider would see permanent drift on the route
resource it just created.

* fix(ec2): enforce cross-account peering identity and fix route target bugs

Addresses Greptile's 0/5 review of #2654:

- AcceptVpcPeeringConnection now resolves the connection across every
  account's storage partition (findAnyAccountEntry, same pattern as
  Ec2IpamService's RAM-shared IPAM lookups) and rejects a caller that is
  not the connection's accepter, instead of only ever finding a
  connection the accepting account itself created.
- DescribeVpcPeeringConnections, ModifyVpcPeeringConnectionOptions and
  DeleteVpcPeeringConnection get the same cross-account resolution, and
  Describe now filters to connections visible from the caller's account
  and region instead of leaking every account's connections in every
  region.
- CreateRoute rejects a VpcPeeringConnectionId combined with another
  target, matching the existing EgressOnlyInternetGatewayId check.
- ReplaceRoute accepts VpcPeeringConnectionId as a target, so a peering
  route created by CreateRoute can actually be repointed.

Adds a cross-account integration test covering acceptance identity,
region-scoped visibility, and the two route-target fixes.

* fix(ec2): record the actual caller as peering requester, enforce region on mutations

Two more issues from Greptile's re-review of #2654:

- CreateVpcPeeringConnection recorded requesterVpcInfo.ownerId as the
  emulator's configured default account rather than the account that
  actually made the request. A non-default requester could never
  describe, modify or delete its own connection, while the unrelated
  default account was treated as the requester and granted those
  operations. Same fix applied to the accepter-owner fallback when
  PeerOwnerId is omitted (same-account peering).
- AcceptVpcPeeringConnection, ModifyVpcPeeringConnectionOptions and
  DeleteVpcPeeringConnection now enforce the same regional-visibility
  invariant Describe already did: an endpoint in a region belonging to
  neither side of the connection reports it as absent instead of acting
  on it.

Extends the cross-account integration test to cover both: the actual
requester managing its own connection while the default account cannot,
and mutations issued from an unrelated region being rejected.

* fix(ec2): enforce per-endpoint ownership on ModifyVpcPeeringConnectionOptions

Greptile's third pass on #2654: a participant that is legitimately part of a
connection could still set the *other* side's DNS-resolution option, e.g. the
requester setting AccepterPeeringConnectionOptions. AWS scopes each option
block to that side's own VPC owner, not to participation in the connection
generally.

ModifyVpcPeeringConnectionOptions now checks the caller against the specific
side's owner for whichever option block(s) the request actually sets, and
rejects a cross-endpoint attempt with OperationNotPermitted. Adds a test
covering both directions (requester setting the accepter's option and vice
versa).

* fix(ec2): resolve the peer VPC's real owner instead of trusting PeerOwnerId

Greptile's fourth pass on #2654: CreateVpcPeeringConnection recorded the
requester-supplied PeerOwnerId as the accepter's identity without checking it
against the peer VPC's actual owner. Since AcceptVpcPeeringConnection
authorizes against that recorded value, a requester could name another
account's real VPC while claiming itself (or anyone) as PeerOwnerId and
self-authorize acceptance of a connection it doesn't actually control.

The peer VPC is now resolved across every account's partition, same as a
peering connection's own id lookup. When it's known locally, that storage
partition is authoritative and overrides any conflicting PeerOwnerId; the
claim is trusted only for a genuinely external/cross-account peer this store
never seeded, where there's nothing to validate against.

Adds a test creating the peer VPC under a real "victim" account and
confirming the forging account can't accept the connection while the real
owner can.

* fix(ec2): take the per-connection lock in DeleteVpcPeeringConnection

Greptile's fifth pass on #2654: accept and modify already synchronized on
lockFor(vpcPeeringConnectionId) before loading and saving the connection, but
delete did not take that lock at all. A delete could run between one of those
mutations' load and its unconditional save, and that save would resurrect the
row delete just removed.

Wraps delete's lookup, visibility check, and removal in the same lock.

* fix(ec2): surface peeringOptions in VPC peering connection responses

CreateVpcPeeringConnection, AcceptVpcPeeringConnection, and
DescribeVpcPeeringConnections never echoed the DNS-resolution setting
under requesterVpcInfo/accepterVpcInfo, even though it's a real field
there in AWS's own examples. ModifyVpcPeeringConnectionOptions stored
it correctly, but Terraform's aws_vpc_peering_connection_options
resource reads the value back via Describe on every plan, not by
re-issuing Modify, so a config setting DNS resolution would show
permanent drift. Flagged in review:
https://github.com/floci-io/floci/pull/2654#pullrequestreview-5054115075

* fix(ec2): reject a peer VPC named with the wrong PeerRegion

CreateVpcPeeringConnection resolved the peer VPC only within the region the
requester supplied, and treated a miss as "external peer, trust PeerOwnerId".
That left the ownership forgery closed on the previous commit reachable again:
name another account's real VPC, point PeerRegion at a region that VPC is not
in, and the requester's own claimed PeerOwnerId is recorded unchallenged --
after which AcceptVpcPeeringConnection authorizes the requester against it.

Real AWS resolves the peer VPC globally and answers InvalidVpcID.NotFound when
the named region is not the one it lives in, so a lookup miss now falls back to
trusting PeerOwnerId only when the id is absent from every region. A genuinely
external peer VPC -- one this emulator has never seen -- behaves as before.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-01 09:32:51 -04:00
1 parent b4aab999f7
commit 14f99a5123
11 files changed
+1559 -18

No files matched your search

+35 -1
View File
@@ -257,10 +257,44 @@ Floci seeds the following resources on first use in each region so Terraform, th
| DeleteRouteTable | Deletes a route table from the local EC2 store. |
| AssociateRouteTable | Associates a route table with a subnet. |
| DisassociateRouteTable | Removes a route table association. |
| CreateRoute | Adds a route to a route table. |
| CreateRoute | Adds a route to a route table. Accepts `VpcPeeringConnectionId` as a target (alongside `GatewayId`/`NatGatewayId`/`EgressOnlyInternetGatewayId`) and reports it back on `DescribeRouteTables`. |
| ReplaceRoute | Replaces the target of an existing route. |
| DeleteRoute | Removes a route from a route table. |
### VPC Peering Connections
| Action | Description |
|--------|-------------|
| CreateVpcPeeringConnection | Creates a peering connection between the local VPC and a peer VPC, in status `pending-acceptance`. |
| AcceptVpcPeeringConnection | Transitions a `pending-acceptance` connection to `active`. |
| DescribeVpcPeeringConnections | Lists or returns stored peering connections. |
| ModifyVpcPeeringConnectionOptions | Sets `allow_remote_vpc_dns_resolution` independently per side. |
| DeleteVpcPeeringConnection | Deletes a peering connection from the local EC2 store. |
Real AWS never auto-accepts a connection, same-account or not: every `CreateVpcPeeringConnection`
starts `pending-acceptance` and stays there until an explicit `AcceptVpcPeeringConnection`. The
`auto_accept` convenience on Terraform's `aws_vpc_peering_connection` and
`aws_vpc_peering_connection_accepter` resources is implemented by the *provider*, which simply
issues that second call itself — so this emulator does not special-case same-account peers.
A connection is stored keyed by its id alone, not `region::id` like every other EC2 resource here.
It is meaningfully addressable from both the requester's and the accepter's side, which can be a
different region (`peer_region`/`accepter_region`); region-scoped storage would leave the accepter's
`AcceptVpcPeeringConnection`/`DescribeVpcPeeringConnections` calls unable to find a connection
created under the requester's region key. `RejectVpcPeeringConnection` is not implemented — no
Gruntwork VPC-peering example exercises it (they use `auto_accept`, not manual rejection).
The accepter VPC named by `PeerVpcId` may belong to another account or region and not be modelled
in this store at all (a cross-account or "external" peer). Its `cidrBlock` is reported only when
that VPC happens to exist locally; the request still succeeds either way, and no CIDR is fabricated.
A connection's storage entry lives under whichever account's request created it, but lookups
(`AcceptVpcPeeringConnection`, `DescribeVpcPeeringConnections`, `ModifyVpcPeeringConnectionOptions`,
`DeleteVpcPeeringConnection`) resolve it across every account's partition, the same pattern used for
RAM-shared IPAM resources. `AcceptVpcPeeringConnection` additionally enforces that the caller is the
connection's accepter — reporting a connection it cannot see as absent, not as a permission error,
matching how AWS itself responds.
### Network ACLs
| Action | Description |
@@ -840,8 +840,10 @@ public class CloudFormationResourceProvisioner {
String gatewayId = resolveOptional(props, "GatewayId", engine);
String natGatewayId = resolveOptional(props, "NatGatewayId", engine);
String egressOnlyInternetGatewayId = resolveOptional(props, "EgressOnlyInternetGatewayId", engine);
String vpcPeeringConnectionId = resolveOptional(props, "VpcPeeringConnectionId", engine);
ec2Service.createRoute(region, routeTableId, destinationCidr, destinationIpv6Cidr,
destinationPrefixListId, gatewayId, natGatewayId, egressOnlyInternetGatewayId);
destinationPrefixListId, gatewayId, natGatewayId, egressOnlyInternetGatewayId,
vpcPeeringConnectionId);
r.setPhysicalId(r.getLogicalId() + "-" + UUID.randomUUID().toString().substring(0, 8));
}
@@ -32,7 +32,7 @@ public class Ec2QueryHandler {
private static final List<String> UNSUPPORTED_ROUTE_TARGETS = List.of(
"CarrierGatewayId", "CoreNetworkArn", "EgressOnlyInternetGatewayId", "InstanceId",
"LocalGatewayId", "NetworkInterfaceId", "OdbNetworkArn",
"TransitGatewayId", "VpcEndpointId", "VpcPeeringConnectionId");
"TransitGatewayId", "VpcEndpointId");
/** The gateway id a route table's built-in route carries (see Ec2Service#createRouteTable). */
private static final String LOCAL_GATEWAY_ID = "local";
@@ -188,6 +188,12 @@ public class Ec2QueryHandler {
case "DeleteRouteTable" -> handleDeleteRouteTable(params, region);
case "AssociateRouteTable" -> handleAssociateRouteTable(params, region);
case "DisassociateRouteTable" -> handleDisassociateRouteTable(params, region);
case "CreateVpcPeeringConnection" -> handleCreateVpcPeeringConnection(params, region);
case "AcceptVpcPeeringConnection" -> handleAcceptVpcPeeringConnection(params, region);
case "DescribeVpcPeeringConnections" -> handleDescribeVpcPeeringConnections(params, region);
case "ModifyVpcPeeringConnectionOptions" -> handleModifyVpcPeeringConnectionOptions(params, region);
case "DeleteVpcPeeringConnection" -> handleDeleteVpcPeeringConnection(params, region);
case "CreateRoute" -> handleCreateRoute(params, region);
case "ReplaceRoute" -> handleReplaceRoute(params, region);
case "DeleteRoute" -> handleDeleteRoute(params, region);
@@ -2915,7 +2921,8 @@ public class Ec2QueryHandler {
// unimplemented), but the id the caller sent is stored and reported back so an IPv6
// egress route is not silently rewritten into a targetless one.
String eigwId = p.getFirst("EgressOnlyInternetGatewayId");
service.createRoute(region, rtId, dest, destIpv6, destPrefixList, gwId, natGwId, eigwId);
String pcxId = p.getFirst("VpcPeeringConnectionId");
service.createRoute(region, rtId, dest, destIpv6, destPrefixList, gwId, natGwId, eigwId, pcxId);
return booleanResponse("CreateRoute");
}
@@ -2935,16 +2942,17 @@ public class Ec2QueryHandler {
String destPrefixList = p.getFirst("DestinationPrefixListId");
String gwId = p.getFirst("GatewayId");
String natGwId = p.getFirst("NatGatewayId");
String pcxId = p.getFirst("VpcPeeringConnectionId");
// Resetting a route to the local target is expressible: `local` is the gateway id the
// route table's built-in route already carries, so it needs no new field on Route.
if (Boolean.parseBoolean(p.getFirst("LocalTarget"))) {
if (gwId != null || natGwId != null) {
if (gwId != null || natGwId != null || pcxId != null) {
throw new AwsException("InvalidParameterCombination",
"ReplaceRoute takes exactly one target.", 400);
}
gwId = LOCAL_GATEWAY_ID;
}
service.replaceRoute(region, rtId, dest, destIpv6, destPrefixList, gwId, natGwId);
service.replaceRoute(region, rtId, dest, destIpv6, destPrefixList, gwId, natGwId, pcxId);
return booleanResponse("ReplaceRoute");
}
@@ -2957,6 +2965,113 @@ public class Ec2QueryHandler {
return booleanResponse("DeleteRoute");
}
// ─── VPC Peering Connection handlers ────────────────────────────────────────
private Response handleCreateVpcPeeringConnection(MultivaluedMap<String, String> p, String region) {
String vpcId = p.getFirst("VpcId");
String peerVpcId = p.getFirst("PeerVpcId");
String peerOwnerId = p.getFirst("PeerOwnerId");
String peerRegion = p.getFirst("PeerRegion");
List<Tag> pcxTags = parseTagsForResource(p, "vpc-peering-connection");
VpcPeeringConnection pcx = service.createVpcPeeringConnection(region, vpcId, peerVpcId, peerOwnerId,
peerRegion, pcxTags);
XmlBuilder xml = new XmlBuilder()
.start("CreateVpcPeeringConnectionResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("vpcPeeringConnection").raw(vpcPeeringConnectionXml(pcx)).end("vpcPeeringConnection")
.end("CreateVpcPeeringConnectionResponse");
return xmlResponse(xml.build());
}
private Response handleAcceptVpcPeeringConnection(MultivaluedMap<String, String> p, String region) {
VpcPeeringConnection pcx = service.acceptVpcPeeringConnection(region, p.getFirst("VpcPeeringConnectionId"));
XmlBuilder xml = new XmlBuilder()
.start("AcceptVpcPeeringConnectionResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("vpcPeeringConnection").raw(vpcPeeringConnectionXml(pcx)).end("vpcPeeringConnection")
.end("AcceptVpcPeeringConnectionResponse");
return xmlResponse(xml.build());
}
private Response handleDescribeVpcPeeringConnections(MultivaluedMap<String, String> p, String region) {
List<String> ids = getList(p, "VpcPeeringConnectionId");
Map<String, List<String>> filters = getFilters(p);
List<VpcPeeringConnection> connections = service.describeVpcPeeringConnections(region, ids, filters);
XmlBuilder xml = new XmlBuilder()
.start("DescribeVpcPeeringConnectionsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("vpcPeeringConnectionSet");
for (VpcPeeringConnection pcx : connections) {
xml.start("item").raw(vpcPeeringConnectionXml(pcx)).end("item");
}
xml.end("vpcPeeringConnectionSet").end("DescribeVpcPeeringConnectionsResponse");
return xmlResponse(xml.build());
}
private Response handleModifyVpcPeeringConnectionOptions(MultivaluedMap<String, String> p, String region) {
String pcxId = p.getFirst("VpcPeeringConnectionId");
Boolean accepterDns = parseOptionalBoolean(
p.getFirst("AccepterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc"),
"AccepterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc");
Boolean requesterDns = parseOptionalBoolean(
p.getFirst("RequesterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc"),
"RequesterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc");
VpcPeeringConnection pcx = service.modifyVpcPeeringConnectionOptions(region, pcxId, accepterDns, requesterDns);
XmlBuilder xml = new XmlBuilder()
.start("ModifyVpcPeeringConnectionOptionsResponse", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("accepterPeeringConnectionOptions")
.elem("allowDnsResolutionFromRemoteVpc", String.valueOf(pcx.isAccepterAllowRemoteVpcDnsResolution()))
.end("accepterPeeringConnectionOptions")
.start("requesterPeeringConnectionOptions")
.elem("allowDnsResolutionFromRemoteVpc", String.valueOf(pcx.isRequesterAllowRemoteVpcDnsResolution()))
.end("requesterPeeringConnectionOptions")
.end("ModifyVpcPeeringConnectionOptionsResponse");
return xmlResponse(xml.build());
}
private Response handleDeleteVpcPeeringConnection(MultivaluedMap<String, String> p, String region) {
service.deleteVpcPeeringConnection(region, p.getFirst("VpcPeeringConnectionId"));
return booleanResponse("DeleteVpcPeeringConnection");
}
private String vpcPeeringConnectionXml(VpcPeeringConnection pcx) {
XmlBuilder xml = new XmlBuilder()
.elem("vpcPeeringConnectionId", pcx.getVpcPeeringConnectionId());
xml.raw(vpcPeeringConnectionVpcInfoXml("requesterVpcInfo", pcx.getRequesterVpcInfo(),
pcx.isRequesterAllowRemoteVpcDnsResolution()));
xml.raw(vpcPeeringConnectionVpcInfoXml("accepterVpcInfo", pcx.getAccepterVpcInfo(),
pcx.isAccepterAllowRemoteVpcDnsResolution()));
if (pcx.getStatus() != null) {
xml.start("status")
.elem("code", pcx.getStatus().getCode())
.elem("message", pcx.getStatus().getMessage())
.end("status");
}
xml.raw(tagSetXml(pcx.getTags()));
return xml.build();
}
private String vpcPeeringConnectionVpcInfoXml(String elementName, VpcPeeringConnectionVpcInfo info,
boolean allowRemoteVpcDnsResolution) {
if (info == null) {
return "";
}
XmlBuilder xml = new XmlBuilder()
.start(elementName)
.elem("vpcId", info.getVpcId())
.elem("ownerId", info.getOwnerId())
.elem("region", info.getRegion());
if (info.getCidrBlock() != null) {
xml.elem("cidrBlock", info.getCidrBlock());
}
xml.start("peeringOptions")
.elem("allowDnsResolutionFromRemoteVpc", String.valueOf(allowRemoteVpcDnsResolution))
.end("peeringOptions");
xml.end(elementName);
return xml.build();
}
// ─── Network ACL handlers ─────────────────────────────────────────────────
private Response handleCreateNetworkAcl(MultivaluedMap<String, String> p, String region) {
@@ -3700,6 +3815,7 @@ public class Ec2QueryHandler {
.elem("gatewayId", r.getGatewayId())
.elem("natGatewayId", r.getNatGatewayId())
.elem("egressOnlyInternetGatewayId", r.getEgressOnlyInternetGatewayId())
.elem("vpcPeeringConnectionId", r.getVpcPeeringConnectionId())
.elem("state", r.getState())
.elem("origin", r.getOrigin())
.end("item");
@@ -28,6 +28,7 @@ import org.jboss.logging.Logger;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
@@ -36,6 +37,7 @@ import io.github.hectorvent.floci.core.common.ContainerTeardown;
import io.github.hectorvent.floci.core.resource.ExplorerResource;
import io.github.hectorvent.floci.core.resource.ResourceProvider;
import io.github.hectorvent.floci.core.resource.SupportedResourceType;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -93,10 +95,14 @@ import io.github.hectorvent.floci.services.ec2.model.VolumeAttachment;
import io.github.hectorvent.floci.services.ec2.model.Vpc;
import io.github.hectorvent.floci.services.ec2.model.VpcCidrBlockAssociation;
import io.github.hectorvent.floci.services.ec2.model.VpcEndpoint;
import io.github.hectorvent.floci.services.ec2.model.VpcPeeringConnection;
import io.github.hectorvent.floci.services.ec2.model.VpcPeeringConnectionStateReason;
import io.github.hectorvent.floci.services.ec2.model.VpcPeeringConnectionVpcInfo;
import jakarta.annotation.PostConstruct;
import io.github.hectorvent.floci.services.ec2.model.LaunchSpecification;
import io.github.hectorvent.floci.services.ec2.model.SpotInstanceRequest;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.ContextNotActiveException;
import jakarta.inject.Inject;
@ApplicationScoped
@@ -123,6 +129,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
private static final long CONTAINER_LAUNCH_POLL_MILLIS = 50;
private final String accountId;
private final jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance;
private final EmulatorConfig config;
private final Ec2ContainerManager containerManager;
private final Ec2PortForwardManager portForwardManager;
@@ -156,17 +163,30 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
private final StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments;
private final StorageBackend<String, TransitGatewayRouteTablePropagation> transitGatewayPropagations;
private final StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes;
// Keyed by id alone, not region::id — see VpcPeeringConnection's class Javadoc.
private final StorageBackend<String, VpcPeeringConnection> vpcPeeringConnections;
// resourceId → List<Tag>
private final StorageBackend<String, List<Tag>> tags;
private final Set<String> seededRegions = ConcurrentHashMap.newKeySet();
// subnetId → counter for IP assignment (runtime-only, not persisted)
private final Map<String, AtomicInteger> subnetIpCounters = new ConcurrentHashMap<>();
@Inject
// Public, no request context — for callers (and tests) that construct this service directly
// without CDI. Caller-identity resolution falls back to the configured default account.
public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
Ec2PortForwardManager portForwardManager,
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog, StorageFactory storageFactory) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog,
instanceTypeCatalog, storageFactory, null);
}
@Inject
public Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
Ec2PortForwardManager portForwardManager,
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog, StorageFactory storageFactory,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
storageFactory.create("ec2", "ec2-vpcs.json", new TypeReference<Map<String, Vpc>>() {}),
storageFactory.create("ec2", "ec2-subnets.json", new TypeReference<Map<String, Subnet>>() {}),
@@ -195,7 +215,10 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
storageFactory.create("ec2", "ec2-transit-gateway-propagations.json",
new TypeReference<Map<String, TransitGatewayRouteTablePropagation>>() {}),
storageFactory.create("ec2", "ec2-transit-gateway-routes.json",
new TypeReference<Map<String, TransitGatewayRoute>>() {}));
new TypeReference<Map<String, TransitGatewayRoute>>() {}),
storageFactory.create("ec2", "ec2-vpc-peering-connections.json",
new TypeReference<Map<String, VpcPeeringConnection>>() {}),
requestContextInstance);
}
// Package-private for hermetic tests (pass in-memory or temp-dir-backed StorageBackends directly).
@@ -227,7 +250,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(),
new InMemoryStorage<>(), new InMemoryStorage<>());
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), null);
}
// Package-private for hermetic tests, transit-gateway-aware. The shorter overload above keeps its
@@ -259,8 +282,50 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables,
StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments,
StorageBackend<String, TransitGatewayRouteTablePropagation> transitGatewayPropagations,
StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes) {
StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes,
StorageBackend<String, VpcPeeringConnection> vpcPeeringConnections) {
this(config, containerManager, portForwardManager, amiImageResolver, imageCatalog, instanceTypeCatalog,
vpcs, subnets, securityGroups, securityGroupRules, internetGateways, routeTables, keyPairs,
addresses, instances, volumes, registeredImages, snapshots, launchTemplates, vpcEndpoints,
natGateways, spotInstanceRequests, networkAcls, managedPrefixLists, tags,
transitGateways, transitGatewayRouteTables, transitGatewayVpcAttachments,
transitGatewayPropagations, transitGatewayRoutes, vpcPeeringConnections, null);
}
// Package-private for hermetic tests that also need to control which account a caller resolves
// to (e.g. cross-account VPC peering scenarios), without touching every other test fixture's arity.
Ec2Service(EmulatorConfig config, Ec2ContainerManager containerManager,
Ec2PortForwardManager portForwardManager,
AmiImageResolver amiImageResolver, Ec2ImageCatalog imageCatalog,
Ec2InstanceTypeCatalog instanceTypeCatalog,
StorageBackend<String, Vpc> vpcs,
StorageBackend<String, Subnet> subnets,
StorageBackend<String, SecurityGroup> securityGroups,
StorageBackend<String, SecurityGroupRule> securityGroupRules,
StorageBackend<String, InternetGateway> internetGateways,
StorageBackend<String, RouteTable> routeTables,
StorageBackend<String, KeyPair> keyPairs,
StorageBackend<String, Address> addresses,
StorageBackend<String, Instance> instances,
StorageBackend<String, Volume> volumes,
StorageBackend<String, Image> registeredImages,
StorageBackend<String, Snapshot> snapshots,
StorageBackend<String, LaunchTemplate> launchTemplates,
StorageBackend<String, VpcEndpoint> vpcEndpoints,
StorageBackend<String, NatGateway> natGateways,
StorageBackend<String, SpotInstanceRequest> spotInstanceRequests,
StorageBackend<String, NetworkAcl> networkAcls,
StorageBackend<String, ManagedPrefixList> managedPrefixLists,
StorageBackend<String, List<Tag>> tags,
StorageBackend<String, TransitGateway> transitGateways,
StorageBackend<String, TransitGatewayRouteTable> transitGatewayRouteTables,
StorageBackend<String, TransitGatewayVpcAttachment> transitGatewayVpcAttachments,
StorageBackend<String, TransitGatewayRouteTablePropagation> transitGatewayPropagations,
StorageBackend<String, TransitGatewayRoute> transitGatewayRoutes,
StorageBackend<String, VpcPeeringConnection> vpcPeeringConnections,
jakarta.enterprise.inject.Instance<RequestContext> requestContextInstance) {
this.accountId = config.defaultAccountId();
this.requestContextInstance = requestContextInstance;
this.config = config;
this.containerManager = containerManager;
this.portForwardManager = portForwardManager;
@@ -291,6 +356,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
this.transitGatewayVpcAttachments = transitGatewayVpcAttachments;
this.transitGatewayPropagations = transitGatewayPropagations;
this.transitGatewayRoutes = transitGatewayRoutes;
this.vpcPeeringConnections = vpcPeeringConnections;
}
@PostConstruct
@@ -4704,13 +4770,34 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
}
}
/**
* A peering connection is a target in its own right, same as an egress-only gateway. Without
* this check CreateRoute would silently accept both a gateway/NAT-gateway target and a
* VpcPeeringConnectionId on the same route, storing an AWS-invalid multi-target route that
* DescribeRouteTables would then echo back and ReplaceRoute could never reconcile.
*/
private static void requireVpcPeeringConnectionIsTheOnlyTarget(String gatewayId, String natGatewayId,
String egressOnlyInternetGatewayId,
String vpcPeeringConnectionId) {
if (!isSet(vpcPeeringConnectionId)) {
return;
}
if (isSet(gatewayId) || isSet(natGatewayId) || isSet(egressOnlyInternetGatewayId)) {
throw new AwsException("InvalidParameterCombination",
"VpcPeeringConnectionId cannot be combined with GatewayId, NatGatewayId or "
+ "EgressOnlyInternetGatewayId; a route takes one target.", 400);
}
}
public void createRoute(String region, String routeTableId, String destinationCidrBlock,
String destinationIpv6CidrBlock, String destinationPrefixListId,
String gatewayId, String natGatewayId,
String egressOnlyInternetGatewayId) {
String egressOnlyInternetGatewayId, String vpcPeeringConnectionId) {
requireExactlyOneDestination("CreateRoute", destinationCidrBlock, destinationIpv6CidrBlock,
destinationPrefixListId);
requireEgressOnlyGatewayIsTheOnlyTarget(gatewayId, natGatewayId, egressOnlyInternetGatewayId);
requireVpcPeeringConnectionIsTheOnlyTarget(gatewayId, natGatewayId, egressOnlyInternetGatewayId,
vpcPeeringConnectionId);
final String canonicalDestinationCidrBlock = canonicalizeIpv4Cidr(destinationCidrBlock);
ensureDefaultResources(region);
synchronized (lockFor(key(region, routeTableId))) {
@@ -4733,6 +4820,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
route.setDestinationPrefixListId(destinationPrefixListId);
route.setNatGatewayId(natGatewayId);
route.setEgressOnlyInternetGatewayId(egressOnlyInternetGatewayId);
route.setVpcPeeringConnectionId(vpcPeeringConnectionId);
next.add(route);
current.setRoutes(next);
routeTables.put(key(region, routeTableId), current);
@@ -4741,17 +4829,19 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
public void replaceRoute(String region, String routeTableId, String destinationCidrBlock,
String destinationIpv6CidrBlock, String destinationPrefixListId,
String gatewayId, String natGatewayId) {
String gatewayId, String natGatewayId, String vpcPeeringConnectionId) {
requireExactlyOneDestination("ReplaceRoute", destinationCidrBlock, destinationIpv6CidrBlock,
destinationPrefixListId);
// AWS takes exactly one target. Rejecting both-or-neither also keeps the targets this
// emulator cannot model (transit gateway, network interface, peering connection, ...) from
// silently clearing the route and reporting success.
// emulator cannot model (transit gateway, network interface, ...) from silently clearing
// the route and reporting success.
boolean hasGateway = isSet(gatewayId);
boolean hasNatGateway = isSet(natGatewayId);
if (hasGateway == hasNatGateway) {
boolean hasPeeringConnection = isSet(vpcPeeringConnectionId);
if ((hasGateway ? 1 : 0) + (hasNatGateway ? 1 : 0) + (hasPeeringConnection ? 1 : 0) != 1) {
throw new AwsException("InvalidParameterCombination",
"ReplaceRoute takes exactly one target, and only GatewayId or NatGatewayId is supported.", 400);
"ReplaceRoute takes exactly one target, and only GatewayId, NatGatewayId or "
+ "VpcPeeringConnectionId is supported.", 400);
}
final String canonicalDestinationCidrBlock = canonicalizeIpv4Cidr(destinationCidrBlock);
@@ -4775,6 +4865,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
replacement.setDestinationIpv6CidrBlock(destinationIpv6CidrBlock);
replacement.setDestinationPrefixListId(destinationPrefixListId);
replacement.setNatGatewayId(hasNatGateway ? natGatewayId : null);
replacement.setVpcPeeringConnectionId(hasPeeringConnection ? vpcPeeringConnectionId : null);
next.set(next.indexOf(existing), replacement);
current.setRoutes(next);
routeTables.put(key(region, routeTableId), current);
@@ -4805,6 +4896,298 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return rt;
}
// ─── VPC Peering Connections ─────────────────────────────────────────────────
//
// Real AWS never auto-accepts a connection, same-account or not (#floci-k41): every
// CreateVpcPeeringConnection starts "pending-acceptance" and stays there until an explicit
// AcceptVpcPeeringConnection. Terraform's own `auto_accept` convenience (on
// aws_vpc_peering_connection and aws_vpc_peering_connection_accepter) is implemented by the
// *provider*, which simply issues that second call itself — so the emulator does not need to
// special-case same-account peers to satisfy it.
public VpcPeeringConnection createVpcPeeringConnection(String region, String vpcId, String peerVpcId,
String peerOwnerId, String peerRegion,
List<Tag> peeringTags) {
ensureDefaultResources(region);
Vpc vpc = getRequiredVpc(region, vpcId);
String pcxId = "pcx-" + randomHex(17);
VpcPeeringConnection pcx = new VpcPeeringConnection();
pcx.setVpcPeeringConnectionId(pcxId);
pcx.setRegion(region);
String callerAccountId = callerAccountId();
VpcPeeringConnectionVpcInfo requester = new VpcPeeringConnectionVpcInfo();
requester.setVpcId(vpcId);
requester.setOwnerId(callerAccountId);
requester.setRegion(region);
requester.setCidrBlock(vpc.getCidrBlock());
pcx.setRequesterVpcInfo(requester);
String accepterRegion = isSet(peerRegion) ? peerRegion : region;
// The accepter VPC may be a cross-account or "external" peer that this store never seeded
// (vpc-peering-cross-accounts, vpc-peering-external), in which case there is nothing to
// validate PeerOwnerId against and the caller's claim is trusted. But when the peer VPC
// *is* known locally, its storage partition — not the requester-supplied PeerOwnerId — is
// authoritative: otherwise a requester could name another account's VPC and claim itself
// as that account, which AcceptVpcPeeringConnection would then let it self-authorize.
Optional<AccountAwareStorageBackend.OwnedEntry<Vpc>> accepterVpcEntry =
findAnyVpcEntry(accepterRegion, peerVpcId);
if (accepterVpcEntry.isEmpty() && vpcKnownInSomeOtherRegion(peerVpcId)) {
// The peer VPC is real, but it does not live in the region the requester named. Trusting
// PeerOwnerId here would reopen the forgery the block above closes: a requester could
// name another account's VPC, point PeerRegion at a region that VPC is absent from, and
// have its own claimed ownership recorded unchallenged. Real AWS resolves the peer VPC
// globally and rejects the mismatch outright, so do the same.
throw new AwsException("InvalidVpcID.NotFound",
"The vpc ID '" + peerVpcId + "' does not exist in region " + accepterRegion, 400);
}
String accepterOwnerId = accepterVpcEntry.map(AccountAwareStorageBackend.OwnedEntry::account)
.orElseGet(() -> isSet(peerOwnerId) ? peerOwnerId : callerAccountId);
Vpc accepterVpc = accepterVpcEntry.map(AccountAwareStorageBackend.OwnedEntry::value).orElse(null);
VpcPeeringConnectionVpcInfo accepter = new VpcPeeringConnectionVpcInfo();
accepter.setVpcId(peerVpcId);
accepter.setOwnerId(accepterOwnerId);
accepter.setRegion(accepterRegion);
accepter.setCidrBlock(accepterVpc != null ? accepterVpc.getCidrBlock() : null);
pcx.setAccepterVpcInfo(accepter);
pcx.setStatus(new VpcPeeringConnectionStateReason("pending-acceptance",
"Pending Acceptance by " + accepterOwnerId));
if (peeringTags != null) {
pcx.setTags(new ArrayList<>(peeringTags));
}
vpcPeeringConnections.put(pcxId, pcx);
return pcx;
}
/**
* A peering connection is visible from a region only if that region is the requester's or the
* accepter's — same as real AWS, where a cross-region connection shows up in exactly the two
* endpoints that are actually party to it. An unfiltered Describe against every other region
* must not leak it.
*/
private static boolean visibleFromRegion(VpcPeeringConnection pcx, String region) {
String requesterRegion = pcx.getRequesterVpcInfo() != null ? pcx.getRequesterVpcInfo().getRegion() : null;
String accepterRegion = pcx.getAccepterVpcInfo() != null ? pcx.getAccepterVpcInfo().getRegion() : null;
return region.equals(requesterRegion) || region.equals(accepterRegion);
}
/**
* A peering connection is visible to an account only if that account is the requester or the
* accepter — same as real AWS, where a connection never shows up in a describe issued by an
* unrelated third account.
*/
private static boolean visibleToAccount(VpcPeeringConnection pcx, String callerAccountId) {
return callerAccountId.equals(ownerId(pcx.getRequesterVpcInfo()))
|| callerAccountId.equals(ownerId(pcx.getAccepterVpcInfo()));
}
private static String ownerId(VpcPeeringConnectionVpcInfo side) {
return side != null ? side.getOwnerId() : null;
}
/**
* Resolves a VPC across every account's partition, the same pattern used to resolve a
* peering connection by id — {@code vpcs} is otherwise scoped to the caller's own account,
* so a plain {@code get} could never find a peer VPC that belongs to a different account.
*/
/**
* Reports whether a VPC id is stored under <em>any</em> region, in any account's partition.
* Only used to tell "this peer VPC is external and was never seeded here" — where trusting the
* requester's PeerOwnerId is the modelled behaviour — apart from "this peer VPC exists, but not
* in the region you named", which must not be trusted.
*/
private boolean vpcKnownInSomeOtherRegion(String vpcId) {
String suffix = "::" + vpcId;
if (vpcs instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<Vpc> accountAware = (AccountAwareStorageBackend<Vpc>) rawAccountAware;
return !accountAware.scanAllAccountEntries(k -> k.endsWith(suffix)).isEmpty();
}
return vpcs.keys().stream().anyMatch(k -> k.endsWith(suffix));
}
private Optional<AccountAwareStorageBackend.OwnedEntry<Vpc>> findAnyVpcEntry(String region, String vpcId) {
if (vpcs instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<Vpc> accountAware = (AccountAwareStorageBackend<Vpc>) rawAccountAware;
return accountAware.findAnyAccountEntry(key(region, vpcId));
}
return vpcs.get(key(region, vpcId)).map(v -> new AccountAwareStorageBackend.OwnedEntry<>(null, v));
}
public List<VpcPeeringConnection> describeVpcPeeringConnections(String region, List<String> ids,
Map<String, List<String>> filters) {
ensureDefaultResources(region);
String caller = callerAccountId();
return allVpcPeeringConnections().stream()
.filter(pcx -> visibleToAccount(pcx, caller))
.filter(pcx -> visibleFromRegion(pcx, region))
.filter(pcx -> ids.isEmpty() || ids.contains(pcx.getVpcPeeringConnectionId()))
.filter(pcx -> matchesFilters(pcx, filters, region))
.collect(Collectors.toList());
}
public VpcPeeringConnection acceptVpcPeeringConnection(String region, String vpcPeeringConnectionId) {
synchronized (lockFor(vpcPeeringConnectionId)) {
OwnedVpcPeeringConnection owned = getRequiredOwnedVpcPeeringConnection(vpcPeeringConnectionId);
VpcPeeringConnection current = owned.pcx();
String accepterOwnerId = current.getAccepterVpcInfo() != null
? current.getAccepterVpcInfo().getOwnerId() : null;
// Reported as absent, not as a permission error: AWS does not confirm the existence
// of a connection the caller cannot see, whether that's because it belongs to another
// account or because this endpoint's region isn't party to it (same invariant Describe
// enforces).
if (!callerAccountId().equals(accepterOwnerId) || !visibleFromRegion(current, region)) {
throw vpcPeeringConnectionNotFound(vpcPeeringConnectionId);
}
String code = current.getStatus() != null ? current.getStatus().getCode() : null;
if (!"pending-acceptance".equals(code)) {
throw new AwsException("InvalidStateTransition",
"VPC Peering Connection " + vpcPeeringConnectionId
+ " is not eligible for acceptance (state: " + code + ")", 400);
}
current.setStatus(new VpcPeeringConnectionStateReason("active", "Active"));
saveVpcPeeringConnection(owned);
return current;
}
}
public VpcPeeringConnection modifyVpcPeeringConnectionOptions(String region, String vpcPeeringConnectionId,
Boolean accepterAllowRemoteVpcDnsResolution,
Boolean requesterAllowRemoteVpcDnsResolution) {
synchronized (lockFor(vpcPeeringConnectionId)) {
OwnedVpcPeeringConnection owned = getRequiredOwnedVpcPeeringConnection(vpcPeeringConnectionId);
VpcPeeringConnection current = owned.pcx();
if (!visibleToAccount(current, callerAccountId()) || !visibleFromRegion(current, region)) {
throw vpcPeeringConnectionNotFound(vpcPeeringConnectionId);
}
String caller = callerAccountId();
// Each side's options block is that side's own VPC setting: only its owner may change
// it. A participant setting only its own side (the normal case) never trips this; it
// rejects the cross-account case where one side reaches into the other's block.
if (accepterAllowRemoteVpcDnsResolution != null
&& !caller.equals(ownerId(current.getAccepterVpcInfo()))) {
throw new AwsException("OperationNotPermitted",
"You do not have permission to modify accepterPeeringConnectionOptions on "
+ vpcPeeringConnectionId + "; only the accepter VPC's owner may.", 400);
}
if (requesterAllowRemoteVpcDnsResolution != null
&& !caller.equals(ownerId(current.getRequesterVpcInfo()))) {
throw new AwsException("OperationNotPermitted",
"You do not have permission to modify requesterPeeringConnectionOptions on "
+ vpcPeeringConnectionId + "; only the requester VPC's owner may.", 400);
}
if (accepterAllowRemoteVpcDnsResolution != null) {
current.setAccepterAllowRemoteVpcDnsResolution(accepterAllowRemoteVpcDnsResolution);
}
if (requesterAllowRemoteVpcDnsResolution != null) {
current.setRequesterAllowRemoteVpcDnsResolution(requesterAllowRemoteVpcDnsResolution);
}
saveVpcPeeringConnection(owned);
return current;
}
}
public void deleteVpcPeeringConnection(String region, String vpcPeeringConnectionId) {
// Same lock accept/modify take: without it, delete can run between one of those loading
// the connection and saving it back, and that unconditional save resurrects the row this
// call just removed.
synchronized (lockFor(vpcPeeringConnectionId)) {
OwnedVpcPeeringConnection owned = getRequiredOwnedVpcPeeringConnection(vpcPeeringConnectionId);
if (!visibleToAccount(owned.pcx(), callerAccountId()) || !visibleFromRegion(owned.pcx(), region)) {
throw vpcPeeringConnectionNotFound(vpcPeeringConnectionId);
}
deleteVpcPeeringConnection(owned);
}
}
/** A peering connection together with the account partition its storage entry lives under. */
private record OwnedVpcPeeringConnection(String storageAccountId, VpcPeeringConnection pcx) {}
/**
* A peering connection is a globally-addressable id, like an S3 bucket name, but is stored
* under whichever account created it (see the class Javadoc on {@link #vpcPeeringConnections}).
* The accepter — and, cross-region, either side — can be a different account than the one that
* created it, so lookups by id must search every account's partition rather than only the
* caller's own, the same pattern {@code Ec2IpamService} uses for RAM-shared IPAM resources.
*/
private List<VpcPeeringConnection> allVpcPeeringConnections() {
if (vpcPeeringConnections instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<VpcPeeringConnection> accountAware =
(AccountAwareStorageBackend<VpcPeeringConnection>) rawAccountAware;
return accountAware.scanAllAccounts();
}
return vpcPeeringConnections.scan(k -> true);
}
private OwnedVpcPeeringConnection getRequiredOwnedVpcPeeringConnection(String vpcPeeringConnectionId) {
if (vpcPeeringConnections instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<VpcPeeringConnection> accountAware =
(AccountAwareStorageBackend<VpcPeeringConnection>) rawAccountAware;
var entry = accountAware.findAnyAccountEntry(vpcPeeringConnectionId)
.orElseThrow(() -> vpcPeeringConnectionNotFound(vpcPeeringConnectionId));
return new OwnedVpcPeeringConnection(entry.account(), entry.value());
}
VpcPeeringConnection pcx = vpcPeeringConnections.get(vpcPeeringConnectionId)
.orElseThrow(() -> vpcPeeringConnectionNotFound(vpcPeeringConnectionId));
return new OwnedVpcPeeringConnection(null, pcx);
}
private void saveVpcPeeringConnection(OwnedVpcPeeringConnection owned) {
if (owned.storageAccountId() != null
&& vpcPeeringConnections instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<VpcPeeringConnection> accountAware =
(AccountAwareStorageBackend<VpcPeeringConnection>) rawAccountAware;
accountAware.putForAccount(owned.storageAccountId(), owned.pcx().getVpcPeeringConnectionId(), owned.pcx());
return;
}
vpcPeeringConnections.put(owned.pcx().getVpcPeeringConnectionId(), owned.pcx());
}
private void deleteVpcPeeringConnection(OwnedVpcPeeringConnection owned) {
if (owned.storageAccountId() != null
&& vpcPeeringConnections instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<VpcPeeringConnection> accountAware =
(AccountAwareStorageBackend<VpcPeeringConnection>) rawAccountAware;
accountAware.deleteForAccount(owned.storageAccountId(), owned.pcx().getVpcPeeringConnectionId());
return;
}
vpcPeeringConnections.delete(owned.pcx().getVpcPeeringConnectionId());
}
private static AwsException vpcPeeringConnectionNotFound(String vpcPeeringConnectionId) {
return new AwsException("InvalidVpcPeeringConnectionID.NotFound",
"The VPC peering connection ID '" + vpcPeeringConnectionId + "' does not exist", 400);
}
/**
* The account making the current request, resolved the same way {@code AccountAwareStorageBackend}
* derives its key prefix, so an identity comparison against a resolved peering connection's
* requester/accepter owner id is meaningful both in and out of a request scope.
*/
private String callerAccountId() {
if (requestContextInstance != null) {
try {
String caller = requestContextInstance.get().getAccountId();
if (caller != null) {
return caller;
}
} catch (ContextNotActiveException e) {
// Tolerated: callers outside a request scope (startup, internal provisioning)
// legitimately fall through to the default account.
LOG.debugv("No active request context — resolving caller as default account {0}", accountId);
}
}
return accountId;
}
// ─── NAT Gateways ─────────────────────────────────────────────────────────
public NatGateway createNatGateway(String region, String subnetId, String allocationId,
@@ -5230,6 +5613,25 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
default -> true;
};
}
if (resource instanceof VpcPeeringConnection pcx) {
return switch (filterName) {
case "vpc-peering-connection-id" -> matchesValue(values, pcx.getVpcPeeringConnectionId());
case "status-code" -> pcx.getStatus() != null && matchesValue(values, pcx.getStatus().getCode());
case "requester-vpc-info.vpc-id" -> pcx.getRequesterVpcInfo() != null
&& matchesValue(values, pcx.getRequesterVpcInfo().getVpcId());
case "requester-vpc-info.owner-id" -> pcx.getRequesterVpcInfo() != null
&& matchesValue(values, pcx.getRequesterVpcInfo().getOwnerId());
case "requester-vpc-info.region" -> pcx.getRequesterVpcInfo() != null
&& matchesValue(values, pcx.getRequesterVpcInfo().getRegion());
case "accepter-vpc-info.vpc-id" -> pcx.getAccepterVpcInfo() != null
&& matchesValue(values, pcx.getAccepterVpcInfo().getVpcId());
case "accepter-vpc-info.owner-id" -> pcx.getAccepterVpcInfo() != null
&& matchesValue(values, pcx.getAccepterVpcInfo().getOwnerId());
case "accepter-vpc-info.region" -> pcx.getAccepterVpcInfo() != null
&& matchesValue(values, pcx.getAccepterVpcInfo().getRegion());
default -> true;
};
}
if (resource instanceof Instance inst) {
return switch (filterName) {
case "instance-id" -> matchesValue(values, inst.getInstanceId());
@@ -5405,6 +5807,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
if (resource instanceof TransitGateway gateway) return gateway.getTags();
if (resource instanceof TransitGatewayRouteTable routeTable) return routeTable.getTags();
if (resource instanceof TransitGatewayVpcAttachment attachment) return attachment.getTags();
if (resource instanceof VpcPeeringConnection pcx) return pcx.getTags();
return Collections.emptyList();
}
@@ -14,6 +14,7 @@ public class Route {
private String gatewayId;
private String natGatewayId;
private String egressOnlyInternetGatewayId;
private String vpcPeeringConnectionId;
private String state = "active";
private String origin;
@@ -66,6 +67,9 @@ public class Route {
public String getEgressOnlyInternetGatewayId() { return egressOnlyInternetGatewayId; }
public void setEgressOnlyInternetGatewayId(String egressOnlyInternetGatewayId) { this.egressOnlyInternetGatewayId = egressOnlyInternetGatewayId; }
public String getVpcPeeringConnectionId() { return vpcPeeringConnectionId; }
public void setVpcPeeringConnectionId(String vpcPeeringConnectionId) { this.vpcPeeringConnectionId = vpcPeeringConnectionId; }
public String getState() { return state; }
public void setState(String state) { this.state = state; }
@@ -0,0 +1,65 @@
package io.github.hectorvent.floci.services.ec2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.List;
/**
* Stored keyed by id alone rather than {@code region::id} like every other EC2 resource here
* (see Ec2Service#createVpcPeeringConnection) — a deliberate simplification. A peering connection
* is meaningfully addressable from both the requester's and the accepter's side, which can be a
* different region (the {@code vpc-peering-cross-accounts} example sets {@code accepter_region}
* independently of the requester region). Region-scoped storage would make the accepter's
* {@code AcceptVpcPeeringConnection}/{@code DescribeVpcPeeringConnections} calls unable to find a
* connection created under the requester's region key.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class VpcPeeringConnection {
private String vpcPeeringConnectionId;
// The region the connection was created in (the requester's region). Informational only —
// lookups are by id, not region::id; see the class Javadoc.
private String region;
private VpcPeeringConnectionVpcInfo requesterVpcInfo;
private VpcPeeringConnectionVpcInfo accepterVpcInfo;
private VpcPeeringConnectionStateReason status;
// aws_vpc_peering_connection_options models one boolean per side here (allow_remote_vpc_dns_resolution),
// the only PeeringConnectionOptions field the vpc-peering / vpc-peering-cross-accounts examples set.
// The ClassicLink-era options (long deprecated) are not modelled.
private boolean accepterAllowRemoteVpcDnsResolution;
private boolean requesterAllowRemoteVpcDnsResolution;
private List<Tag> tags = new ArrayList<>();
public VpcPeeringConnection() {}
public String getVpcPeeringConnectionId() { return vpcPeeringConnectionId; }
public void setVpcPeeringConnectionId(String vpcPeeringConnectionId) { this.vpcPeeringConnectionId = vpcPeeringConnectionId; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public VpcPeeringConnectionVpcInfo getRequesterVpcInfo() { return requesterVpcInfo; }
public void setRequesterVpcInfo(VpcPeeringConnectionVpcInfo requesterVpcInfo) { this.requesterVpcInfo = requesterVpcInfo; }
public VpcPeeringConnectionVpcInfo getAccepterVpcInfo() { return accepterVpcInfo; }
public void setAccepterVpcInfo(VpcPeeringConnectionVpcInfo accepterVpcInfo) { this.accepterVpcInfo = accepterVpcInfo; }
public VpcPeeringConnectionStateReason getStatus() { return status; }
public void setStatus(VpcPeeringConnectionStateReason status) { this.status = status; }
public boolean isAccepterAllowRemoteVpcDnsResolution() { return accepterAllowRemoteVpcDnsResolution; }
public void setAccepterAllowRemoteVpcDnsResolution(boolean accepterAllowRemoteVpcDnsResolution) {
this.accepterAllowRemoteVpcDnsResolution = accepterAllowRemoteVpcDnsResolution;
}
public boolean isRequesterAllowRemoteVpcDnsResolution() { return requesterAllowRemoteVpcDnsResolution; }
public void setRequesterAllowRemoteVpcDnsResolution(boolean requesterAllowRemoteVpcDnsResolution) {
this.requesterAllowRemoteVpcDnsResolution = requesterAllowRemoteVpcDnsResolution;
}
public List<Tag> getTags() { return tags; }
public void setTags(List<Tag> tags) { this.tags = tags; }
}
@@ -0,0 +1,25 @@
package io.github.hectorvent.floci.services.ec2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class VpcPeeringConnectionStateReason {
private String code;
private String message;
public VpcPeeringConnectionStateReason() {}
public VpcPeeringConnectionStateReason(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() { return code; }
public void setCode(String code) { this.code = code; }
public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }
}
@@ -0,0 +1,34 @@
package io.github.hectorvent.floci.services.ec2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* One side (requester or accepter) of a {@link VpcPeeringConnection}. The accepter side may name a
* VPC that does not exist in this store at all — a cross-account or "external" peer, per the
* {@code vpc-peering-cross-accounts} and {@code vpc-peering-external} examples — so {@code cidrBlock}
* is best-effort and can be {@code null}.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class VpcPeeringConnectionVpcInfo {
private String vpcId;
private String ownerId;
private String region;
private String cidrBlock;
public VpcPeeringConnectionVpcInfo() {}
public String getVpcId() { return vpcId; }
public void setVpcId(String vpcId) { this.vpcId = vpcId; }
public String getOwnerId() { return ownerId; }
public void setOwnerId(String ownerId) { this.ownerId = ownerId; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public String getCidrBlock() { return cidrBlock; }
public void setCidrBlock(String cidrBlock) { this.cidrBlock = cidrBlock; }
}
@@ -225,12 +225,12 @@ class Ec2ServicePersistenceTest {
// (b) CreateRoute with an equivalent-but-differently-spelled destination is a duplicate,
// not a new route, of the legacy one.
AwsException duplicate = assertThrows(AwsException.class, () -> restarted.createRoute(
REGION, routeTableId, "100.68.63.255/18", null, null, "igw-other00000000000", null, null));
REGION, routeTableId, "100.68.63.255/18", null, null, "igw-other00000000000", null, null, null));
assertEquals("RouteAlreadyExists", duplicate.getErrorCode());
// (c) ReplaceRoute against the legacy route's original, non-canonical spelling finds the
// same route rather than throwing InvalidRoute.NotFound.
restarted.replaceRoute(REGION, routeTableId, "100.68.0.18/18", null, null, "igw-replaced0000000", null);
restarted.replaceRoute(REGION, routeTableId, "100.68.0.18/18", null, null, "igw-replaced0000000", null, null);
RouteTable afterReplace =
restarted.describeRouteTables(REGION, List.of(routeTableId), Map.of()).getFirst();
assertEquals(1, afterReplace.getRoutes().size(), "replace must update the existing route in place");
@@ -0,0 +1,533 @@
package io.github.hectorvent.floci.services.ec2;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import io.quarkus.test.junit.QuarkusTest;
/**
* Covers the cross-account and multi-target scenarios the same-account lifecycle test
* (Ec2VpcPeeringConnectionIntegrationTest) cannot exercise on its own: only the actual accepter
* account may accept a connection, a describe issued from an unrelated region must not see it,
* ReplaceRoute must accept a peering connection as a target, and CreateRoute must reject a
* peering connection combined with another target.
*
* <p>Uses 12-digit numeric access key IDs so they resolve directly to distinct account IDs
* (see AccountIsolationIntegrationTest for the same pattern).
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class Ec2VpcPeeringConnectionCrossAccountIntegrationTest {
// 000000000000 is the emulator's configured default account — distinct from every account
// below, so it stands in for "an unrelated account that happens to be the default".
private static final String DEFAULT_ACCOUNT = "000000000000";
private static final String REQUESTER_ACCOUNT = "000000000101";
private static final String ACCEPTER_ACCOUNT = "000000000102";
private static final String OTHER_ACCOUNT = "000000000103";
private static final String DEFAULT_ACCOUNT_AUTH =
"AWS4-HMAC-SHA256 Credential=" + DEFAULT_ACCOUNT + "/20260215/us-east-1/ec2/aws4_request";
private static final String REQUESTER_AUTH =
"AWS4-HMAC-SHA256 Credential=" + REQUESTER_ACCOUNT + "/20260215/us-east-1/ec2/aws4_request";
private static final String ACCEPTER_AUTH =
"AWS4-HMAC-SHA256 Credential=" + ACCEPTER_ACCOUNT + "/20260215/us-east-1/ec2/aws4_request";
private static final String OTHER_ACCOUNT_AUTH =
"AWS4-HMAC-SHA256 Credential=" + OTHER_ACCOUNT + "/20260215/us-east-1/ec2/aws4_request";
// Same requester account, different region — used to prove a describe (and, below, a
// mutation) issued from a region unrelated to either side of the connection does not see it.
private static final String REQUESTER_AUTH_OTHER_REGION =
"AWS4-HMAC-SHA256 Credential=" + REQUESTER_ACCOUNT + "/20260215/us-west-2/ec2/aws4_request";
private static String requesterVpcId;
private static String pcxId;
@Test
@Order(1)
void requesterCreatesAConnectionAddressedToTheAccepterAccount() {
requesterVpcId = given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.40.0.0/16")
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
pcxId = given()
.formParam("Action", "CreateVpcPeeringConnection")
.formParam("VpcId", requesterVpcId)
.formParam("PeerVpcId", "vpc-accepter00000000")
.formParam("PeerOwnerId", ACCEPTER_ACCOUNT)
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.accepterVpcInfo.ownerId",
equalTo(ACCEPTER_ACCOUNT))
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.status.code",
equalTo("pending-acceptance"))
.extract().path("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.vpcPeeringConnectionId");
}
/** The requester created the connection but is not the accepter and cannot activate it. */
@Test
@Order(2)
void requesterCannotAcceptItsOwnConnection() {
given()
.formParam("Action", "AcceptVpcPeeringConnection")
.formParam("VpcPeeringConnectionId", pcxId)
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidVpcPeeringConnectionID.NotFound"));
}
/** An unrelated third account cannot see or accept the connection either. */
@Test
@Order(3)
void anUnrelatedAccountCannotSeeOrAcceptTheConnection() {
given()
.formParam("Action", "DescribeVpcPeeringConnections")
.formParam("VpcPeeringConnectionId.1", pcxId)
.header("Authorization", OTHER_ACCOUNT_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeVpcPeeringConnectionsResponse.vpcPeeringConnectionSet", emptyOrNullString());
given()
.formParam("Action", "AcceptVpcPeeringConnection")
.formParam("VpcPeeringConnectionId", pcxId)
.header("Authorization", OTHER_ACCOUNT_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidVpcPeeringConnectionID.NotFound"));
}
/** A describe issued from a region that is neither side of the connection must not see it. */
@Test
@Order(4)
void describeFromAnUnrelatedRegionDoesNotSeeTheConnection() {
given()
.formParam("Action", "DescribeVpcPeeringConnections")
.formParam("VpcPeeringConnectionId.1", pcxId)
.header("Authorization", REQUESTER_AUTH_OTHER_REGION)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeVpcPeeringConnectionsResponse.vpcPeeringConnectionSet", emptyOrNullString());
}
/** The actual accepter account can see and accept it. */
@Test
@Order(5)
void theAccepterAccountCanAcceptTheConnection() {
given()
.formParam("Action", "DescribeVpcPeeringConnections")
.formParam("VpcPeeringConnectionId.1", pcxId)
.header("Authorization", ACCEPTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeVpcPeeringConnectionsResponse.vpcPeeringConnectionSet.item.vpcPeeringConnectionId",
equalTo(pcxId));
given()
.formParam("Action", "AcceptVpcPeeringConnection")
.formParam("VpcPeeringConnectionId", pcxId)
.header("Authorization", ACCEPTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("AcceptVpcPeeringConnectionResponse.vpcPeeringConnection.status.code", equalTo("active"));
}
/**
* CreateRoute must reject a route that names both a peering connection and another target
* (here: GatewayId) — AWS accepts exactly one target per route.
*/
@Test
@Order(6)
void createRouteRejectsAPeeringConnectionCombinedWithAnotherTarget() {
String routeTableId = given()
.formParam("Action", "CreateRouteTable")
.formParam("VpcId", requesterVpcId)
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateRouteTableResponse.routeTable.routeTableId");
given()
.formParam("Action", "CreateRoute")
.formParam("RouteTableId", routeTableId)
.formParam("DestinationCidrBlock", "10.50.0.0/16")
.formParam("VpcPeeringConnectionId", pcxId)
.formParam("GatewayId", "igw-conflicting00000")
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"));
}
/**
* ReplaceRoute must accept a peering connection as the replacement target — the peering
* examples repoint a route at the connection after it goes active, same as CreateRoute.
*/
@Test
@Order(7)
void replaceRouteAcceptsThePeeringConnectionAsTheTarget() {
String routeTableId = given()
.formParam("Action", "CreateRouteTable")
.formParam("VpcId", requesterVpcId)
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateRouteTableResponse.routeTable.routeTableId");
given()
.formParam("Action", "CreateRoute")
.formParam("RouteTableId", routeTableId)
.formParam("DestinationCidrBlock", "10.60.0.0/16")
.formParam("GatewayId", "igw-replaceable00000")
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "ReplaceRoute")
.formParam("RouteTableId", routeTableId)
.formParam("DestinationCidrBlock", "10.60.0.0/16")
.formParam("VpcPeeringConnectionId", pcxId)
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("ReplaceRouteResponse.return", equalTo("true"));
given()
.formParam("Action", "DescribeRouteTables")
.formParam("RouteTableId.1", routeTableId)
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeRouteTablesResponse.routeTableSet.item.routeSet.item"
+ ".find { it.destinationCidrBlock == '10.60.0.0/16' }.vpcPeeringConnectionId",
equalTo(pcxId));
}
/**
* The requester account (not the emulator's configured default account) must be able to
* describe and modify the connection it created. Recording requesterVpcInfo.ownerId as the
* fixed default account, rather than the account that actually made the request, would deny
* the real requester while handing an unrelated account participant-level access.
*/
@Test
@Order(8)
void theRequesterAccountCanManageItsOwnConnectionButTheDefaultAccountCannot() {
given()
.formParam("Action", "DescribeVpcPeeringConnections")
.formParam("VpcPeeringConnectionId.1", pcxId)
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeVpcPeeringConnectionsResponse.vpcPeeringConnectionSet.item.vpcPeeringConnectionId",
equalTo(pcxId));
given()
.formParam("Action", "DescribeVpcPeeringConnections")
.formParam("VpcPeeringConnectionId.1", pcxId)
.header("Authorization", DEFAULT_ACCOUNT_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeVpcPeeringConnectionsResponse.vpcPeeringConnectionSet", emptyOrNullString());
given()
.formParam("Action", "ModifyVpcPeeringConnectionOptions")
.formParam("VpcPeeringConnectionId", pcxId)
.formParam("RequesterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc", "true")
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("ModifyVpcPeeringConnectionOptionsResponse.requesterPeeringConnectionOptions"
+ ".allowDnsResolutionFromRemoteVpc", equalTo("true"));
given()
.formParam("Action", "ModifyVpcPeeringConnectionOptions")
.formParam("VpcPeeringConnectionId", pcxId)
.formParam("RequesterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc", "false")
.header("Authorization", DEFAULT_ACCOUNT_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidVpcPeeringConnectionID.NotFound"));
}
/**
* Each side's DNS-resolution option is that side's own setting: being a legitimate
* participant in the connection is not enough to change the *other* side's option, only
* your own — same as AWS, where accepterPeeringConnectionOptions is the accepter VPC
* owner's setting and requesterPeeringConnectionOptions is the requester VPC owner's.
*/
@Test
@Order(9)
void aParticipantCannotModifyTheOppositeEndpointsOptions() {
// The requester may set its own side...
given()
.formParam("Action", "ModifyVpcPeeringConnectionOptions")
.formParam("VpcPeeringConnectionId", pcxId)
.formParam("RequesterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc", "true")
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200);
// ...but not the accepter's side, even though it is a legitimate participant.
given()
.formParam("Action", "ModifyVpcPeeringConnectionOptions")
.formParam("VpcPeeringConnectionId", pcxId)
.formParam("AccepterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc", "true")
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("OperationNotPermitted"));
// Symmetrically, the accepter may set its own side but not the requester's.
given()
.formParam("Action", "ModifyVpcPeeringConnectionOptions")
.formParam("VpcPeeringConnectionId", pcxId)
.formParam("AccepterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc", "true")
.header("Authorization", ACCEPTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200);
given()
.formParam("Action", "ModifyVpcPeeringConnectionOptions")
.formParam("VpcPeeringConnectionId", pcxId)
.formParam("RequesterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc", "false")
.header("Authorization", ACCEPTER_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("OperationNotPermitted"));
}
/**
* Accept, modify and delete must enforce the same regional-visibility invariant Describe
* does: an endpoint in a region belonging to neither side must not be able to act on the
* connection, even when the caller's account is a legitimate participant.
*/
@Test
@Order(10)
void mutationsFromAnUnrelatedRegionAreRejected() {
given()
.formParam("Action", "ModifyVpcPeeringConnectionOptions")
.formParam("VpcPeeringConnectionId", pcxId)
.formParam("RequesterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc", "true")
.header("Authorization", REQUESTER_AUTH_OTHER_REGION)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidVpcPeeringConnectionID.NotFound"));
given()
.formParam("Action", "DeleteVpcPeeringConnection")
.formParam("VpcPeeringConnectionId", pcxId)
.header("Authorization", REQUESTER_AUTH_OTHER_REGION)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidVpcPeeringConnectionID.NotFound"));
// Still there, and still manageable from the correct region.
given()
.formParam("Action", "DeleteVpcPeeringConnection")
.formParam("VpcPeeringConnectionId", pcxId)
.header("Authorization", REQUESTER_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("DeleteVpcPeeringConnectionResponse.return", equalTo("true"));
}
/**
* A requester cannot forge accepter ownership by naming another account's real VPC while
* claiming a different PeerOwnerId (e.g. its own account) — the peer VPC's actual storage
* partition must win, or the requester could self-authorize AcceptVpcPeeringConnection for a
* connection it does not actually control.
*/
@Test
@Order(11)
void creationCannotForgeAccepterOwnershipForALocallyKnownPeerVpc() {
String victimAccount = "000000000199";
String victimAuth =
"AWS4-HMAC-SHA256 Credential=" + victimAccount + "/20260215/us-east-1/ec2/aws4_request";
String victimVpcId = given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.70.0.0/16")
.header("Authorization", victimAuth)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
String forgingVpcId = given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.71.0.0/16")
.header("Authorization", OTHER_ACCOUNT_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
// OTHER_ACCOUNT names the victim's real VPC but falsely claims itself as PeerOwnerId.
String forgedPcxId = given()
.formParam("Action", "CreateVpcPeeringConnection")
.formParam("VpcId", forgingVpcId)
.formParam("PeerVpcId", victimVpcId)
.formParam("PeerOwnerId", OTHER_ACCOUNT)
.header("Authorization", OTHER_ACCOUNT_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
// The recorded accepter owner is the VPC's real account, not the claimed one.
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.accepterVpcInfo.ownerId",
equalTo(victimAccount))
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.accepterVpcInfo.cidrBlock",
equalTo("10.70.0.0/16"))
.extract().path("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.vpcPeeringConnectionId");
// The requester cannot self-authorize acceptance despite its false claim.
given()
.formParam("Action", "AcceptVpcPeeringConnection")
.formParam("VpcPeeringConnectionId", forgedPcxId)
.header("Authorization", OTHER_ACCOUNT_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidVpcPeeringConnectionID.NotFound"));
// The real owner of the peer VPC can accept it.
given()
.formParam("Action", "AcceptVpcPeeringConnection")
.formParam("VpcPeeringConnectionId", forgedPcxId)
.header("Authorization", victimAuth)
.when()
.post("/")
.then()
.statusCode(200)
.body("AcceptVpcPeeringConnectionResponse.vpcPeeringConnection.status.code", equalTo("active"));
}
/**
* The same forgery, hidden behind a mismatched PeerRegion: naming another account's real VPC
* but pointing PeerRegion at a region that VPC is absent from must not degrade into trusting
* the requester-supplied PeerOwnerId. Real AWS resolves the peer VPC globally and answers
* InvalidVpcID.NotFound, so nothing is created for the requester to then self-accept.
*/
@Test
@Order(12)
void creationCannotForgeAccepterOwnershipByNamingTheWrongPeerRegion() {
String victimAccount = "000000000198";
String victimAuth =
"AWS4-HMAC-SHA256 Credential=" + victimAccount + "/20260215/us-east-1/ec2/aws4_request";
String victimVpcId = given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.72.0.0/16")
.header("Authorization", victimAuth)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
String forgingVpcId = given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.73.0.0/16")
.header("Authorization", OTHER_ACCOUNT_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
// The victim's VPC is in us-east-1; PeerRegion names eu-west-1, where it does not exist.
given()
.formParam("Action", "CreateVpcPeeringConnection")
.formParam("VpcId", forgingVpcId)
.formParam("PeerVpcId", victimVpcId)
.formParam("PeerRegion", "eu-west-1")
.formParam("PeerOwnerId", OTHER_ACCOUNT)
.header("Authorization", OTHER_ACCOUNT_AUTH)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidVpcID.NotFound"));
// A genuinely external peer VPC — one this emulator has never seen in any region — is
// still accepted on the requester's word, as before.
given()
.formParam("Action", "CreateVpcPeeringConnection")
.formParam("VpcId", forgingVpcId)
.formParam("PeerVpcId", "vpc-0f00d0f00d0f00d00")
.formParam("PeerRegion", "eu-west-1")
.formParam("PeerOwnerId", "000000000197")
.header("Authorization", OTHER_ACCOUNT_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.accepterVpcInfo.ownerId",
equalTo("000000000197"));
}
}
@@ -0,0 +1,325 @@
package io.github.hectorvent.floci.services.ec2;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import io.quarkus.test.junit.QuarkusTest;
import static io.restassured.RestAssured.given;
/**
* CreateVpcPeeringConnection was entirely unimplemented (floci-k41), blocking all three VPC-peering
* examples in terraform-aws-vpc (vpc-peering, vpc-peering-cross-accounts, vpc-peering-external).
* These tests walk the lifecycle those examples actually exercise: create -> accept -> describe ->
* route via the peering connection -> options -> delete.
*
* <p>Real AWS never auto-accepts a connection (same-account or not); every connection starts
* "pending-acceptance" until an explicit AcceptVpcPeeringConnection. Terraform's own `auto_accept`
* convenience is implemented by the *provider* re-issuing that call, not by the API — so that is
* what these tests pin at the API layer.
*/
@QuarkusTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class Ec2VpcPeeringConnectionIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static String requesterVpcId;
private static String accepterVpcId;
private static String pcxId;
private static String routeTableId;
@Test
@Order(1)
void createVpcPeeringConnectionStartsPendingAcceptance() {
requesterVpcId = given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.20.0.0/16")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
accepterVpcId = given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.30.0.0/16")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
pcxId = given()
.formParam("Action", "CreateVpcPeeringConnection")
.formParam("VpcId", requesterVpcId)
.formParam("PeerVpcId", accepterVpcId)
.formParam("TagSpecification.1.ResourceType", "vpc-peering-connection")
.formParam("TagSpecification.1.Tag.1.Key", "Name")
.formParam("TagSpecification.1.Tag.1.Value", "pcx-example")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.requesterVpcInfo.vpcId",
equalTo(requesterVpcId))
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.requesterVpcInfo.cidrBlock",
equalTo("10.20.0.0/16"))
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.accepterVpcInfo.vpcId",
equalTo(accepterVpcId))
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.accepterVpcInfo.cidrBlock",
equalTo("10.30.0.0/16"))
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.status.code",
equalTo("pending-acceptance"))
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.tagSet.item.value",
equalTo("pcx-example"))
.extract().path("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.vpcPeeringConnectionId");
}
@Test
@Order(2)
void describeReflectsThePendingConnection() {
given()
.formParam("Action", "DescribeVpcPeeringConnections")
.formParam("VpcPeeringConnectionId.1", pcxId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeVpcPeeringConnectionsResponse.vpcPeeringConnectionSet.item.vpcPeeringConnectionId",
equalTo(pcxId))
.body("DescribeVpcPeeringConnectionsResponse.vpcPeeringConnectionSet.item.status.code",
equalTo("pending-acceptance"));
}
@Test
@Order(3)
void acceptTransitionsTheConnectionToActive() {
given()
.formParam("Action", "AcceptVpcPeeringConnection")
.formParam("VpcPeeringConnectionId", pcxId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("AcceptVpcPeeringConnectionResponse.vpcPeeringConnection.status.code", equalTo("active"));
given()
.formParam("Action", "DescribeVpcPeeringConnections")
.formParam("VpcPeeringConnectionId.1", pcxId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeVpcPeeringConnectionsResponse.vpcPeeringConnectionSet.item.status.code",
equalTo("active"));
}
/** Accepting an already-active connection is not a valid state transition. */
@Test
@Order(4)
void acceptingAnAlreadyActiveConnectionIsRejected() {
given()
.formParam("Action", "AcceptVpcPeeringConnection")
.formParam("VpcPeeringConnectionId", pcxId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidStateTransition"));
}
/**
* aws_vpc_peering_connection_options: both modules/vpc-peering and
* modules/vpc-peering-cross-accounts-accepter set allow_remote_vpc_dns_resolution on one or
* both sides.
*/
@Test
@Order(5)
void modifyPeeringConnectionOptionsSetsDnsResolutionPerSide() {
given()
.formParam("Action", "ModifyVpcPeeringConnectionOptions")
.formParam("VpcPeeringConnectionId", pcxId)
.formParam("AccepterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc", "true")
.formParam("RequesterPeeringConnectionOptions.AllowDnsResolutionFromRemoteVpc", "true")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("ModifyVpcPeeringConnectionOptionsResponse.accepterPeeringConnectionOptions"
+ ".allowDnsResolutionFromRemoteVpc", equalTo("true"))
.body("ModifyVpcPeeringConnectionOptionsResponse.requesterPeeringConnectionOptions"
+ ".allowDnsResolutionFromRemoteVpc", equalTo("true"));
// Terraform's aws_vpc_peering_connection_options resource reads this back via Describe on
// every plan, not by re-issuing Modify — it must round-trip here or the provider sees
// permanent drift on a value it just set.
given()
.formParam("Action", "DescribeVpcPeeringConnections")
.formParam("VpcPeeringConnectionId.1", pcxId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeVpcPeeringConnectionsResponse.vpcPeeringConnectionSet.item"
+ ".accepterVpcInfo.peeringOptions.allowDnsResolutionFromRemoteVpc", equalTo("true"))
.body("DescribeVpcPeeringConnectionsResponse.vpcPeeringConnectionSet.item"
+ ".requesterVpcInfo.peeringOptions.allowDnsResolutionFromRemoteVpc", equalTo("true"));
}
/**
* modules/vpc-peering routes traffic to the peer over the connection via aws_route with
* vpc_peering_connection_id as the target — this must round-trip on DescribeRouteTables or the
* provider sees permanent drift on the route resource it just created.
*/
@Test
@Order(6)
void createRouteWithThePeeringConnectionAsTargetRoundTrips() {
routeTableId = given()
.formParam("Action", "CreateRouteTable")
.formParam("VpcId", requesterVpcId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateRouteTableResponse.routeTable.routeTableId");
given()
.formParam("Action", "CreateRoute")
.formParam("RouteTableId", routeTableId)
.formParam("DestinationCidrBlock", "10.30.0.0/16")
.formParam("VpcPeeringConnectionId", pcxId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateRouteResponse.return", equalTo("true"));
given()
.formParam("Action", "DescribeRouteTables")
.formParam("RouteTableId.1", routeTableId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeRouteTablesResponse.routeTableSet.item.routeSet.item"
+ ".find { it.destinationCidrBlock == '10.30.0.0/16' }.vpcPeeringConnectionId",
equalTo(pcxId));
}
@Test
@Order(7)
void deleteRemovesTheConnection() {
given()
.formParam("Action", "DeleteVpcPeeringConnection")
.formParam("VpcPeeringConnectionId", pcxId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DeleteVpcPeeringConnectionResponse.return", equalTo("true"));
given()
.formParam("Action", "DescribeVpcPeeringConnections")
.formParam("VpcPeeringConnectionId.1", pcxId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeVpcPeeringConnectionsResponse.vpcPeeringConnectionSet", emptyOrNullString());
}
@Test
@Order(8)
void deletingAnUnknownConnectionIsRejected() {
given()
.formParam("Action", "DeleteVpcPeeringConnection")
.formParam("VpcPeeringConnectionId", "pcx-0000000000000dead")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidVpcPeeringConnectionID.NotFound"));
}
/**
* vpc-peering-cross-accounts and vpc-peering-external both peer against a VPC id this account
* never seeded (a different account/region's VPC). The accepter side must still be reported —
* without a fabricated CIDR — rather than the request failing outright.
*/
@Test
@Order(9)
void peeringToAnUnknownAccepterVpcSucceedsWithNoAccepterCidr() {
String vpcId = given()
.formParam("Action", "CreateVpc")
.formParam("CidrBlock", "10.2.0.0/16")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
String response = given()
.formParam("Action", "CreateVpcPeeringConnection")
.formParam("VpcId", vpcId)
.formParam("PeerVpcId", "vpc-external0000000")
.formParam("PeerOwnerId", "999999999999")
.formParam("PeerRegion", "us-west-2")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.accepterVpcInfo.vpcId",
equalTo("vpc-external0000000"))
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.accepterVpcInfo.ownerId",
equalTo("999999999999"))
.body("CreateVpcPeeringConnectionResponse.vpcPeeringConnection.accepterVpcInfo.region",
equalTo("us-west-2"))
.extract().asString();
// The requester side (a VPC this account did seed) does carry a cidrBlock; only the
// accepter side — a VPC never seeded here — must not have one fabricated.
String accepterInfo = response.substring(response.indexOf("<accepterVpcInfo>"));
assertThat(accepterInfo, not(containsString("<cidrBlock>")));
}
@Test
@Order(10)
void createOnAnUnknownVpcIsRejected() {
given()
.formParam("Action", "CreateVpcPeeringConnection")
.formParam("VpcId", "vpc-0000000000000dead")
.formParam("PeerVpcId", "vpc-0000000000000beef")
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidVpcID.NotFound"));
}
}