Commit Graph
26 Commits
Author SHA1 Message Date
Allen Sanborn 14f99a5123 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.
2026-09-01 09:32:51 -04:00
Allen Sanborn 41b5148824 fix(ec2): report a reachable EIP address, and run gzipped user-data (#2621)
* fix(ec2): report an address that actually answers, and run gzipped user-data

Two independent bugs, both of which end a Terratest suite the moment it tries
to SSH into an instance.

1. The address the API reports was never an address that works. Launch set
   PublicIpAddress to 127.0.0.1 on the strength of a comment calling it
   "host-reachable", but Docker publishes the guest's SSH on a high host port,
   so :22 there is nothing. AllocateAddress then invents a 54.x.x.x that routes
   nowhere, and that is the value Terraform surfaces as aws_eip.x.public_ip and
   test suites dial. The invariant now is that whatever DescribeInstances and
   DescribeAddresses report accepts a connection on the service's real port.

   Where the container network is routable from Floci's API clients — native
   Linux Docker, OrbStack — that address is the container's own IP: port 22 is
   really port 22 there, with no published mapping to translate, and so is every
   other port the guest listens on. Where it is not — Docker Desktop, whose
   containers sit behind a VM — nothing changes and 127.0.0.1 plus published
   ports remains. Which case applies is detected, never assumed, by a throwaway
   TCP connect towards the container network: a refusal is proof of a route,
   since only the container's network stack could have sent the RST. The one
   case a probe cannot settle is Floci running inside a container itself, where
   it measures container-to-container reachability while the clients that will
   use the answer are on the host; there the Docker backend arbitrates and
   FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE overrides either way.

   AssociateAddress re-points the EIP at that reachable address rather than
   leaving the fictional one. Aliasing instead would need Floci to own routing
   or DNS on the client's machine, and clients that read the address out of the
   API and dial it — Terratest does exactly this — would still get something
   dead. Association is also the first moment the answer is knowable. The cost
   is one deliberate deviation from AWS, an EIP whose public IP changes when it
   is associated; the AllocationId, AssociationId and domain are untouched, and
   disassociation restores the allocated address.

2. Gzipped cloud-init user-data was skipped in silence. The launch path
   recognised a literal "#!" or a plaintext MIME boundary and nothing else, so
   data.cloudinit_config { gzip = true } — the documented way to pass multipart
   user-data — was dropped whole. The instance booted fine and was simply
   missing everything it was supposed to install, which is what made this
   expensive to find. UserData is now unwrapped through gzip, base64, and
   base64-of-gzip before the existing shellscript/MIME handling, and the "no
   executable parts" line is a WARN that says what the consequence is.

* fix(ec2): re-resolve an associated EIP's address on DescribeAddresses

Association can happen before the instance has a container, and Docker hands out
a different bridge IP after a stop/start; either leaves the association naming an
address that no longer answers. DescribeAddresses is the call Terraform refreshes
public_ip from, so it is the last chance to be right.

* test(ec2): cover EIP re-pointing on associate, describe and disassociate

The address rewrite had no test of its own: reverting pointAddressAtInstance
left every existing test green, so nothing was holding the behaviour in place.
These three assert the claim directly — association reports the reachable
address rather than the invented 54.x.x.x one, DescribeAddresses re-resolves it
after the container IP moves, and disassociation hands the allocation back.

* docs(ec2): document container-IP routability and the EIP address rewrite

FLOCI_SERVICES_EC2_CONTAINER_IPS_ROUTABLE was undocumented, and the IMDS table
still promised public-ipv4 always returns 127.0.0.1. The Elastic IP section now
states the one deliberate deviation from AWS — an associated EIP's public IP is
rewritten to something reachable — so it is not discovered by surprise.

* fix(ec2): bound gzipped UserData decompression to stop a heap-exhaustion DoS

GZIPInputStream#readAllBytes() materialized the full decompressed
UserData with no size limit, so a caller-controlled gzip stream (e.g.
via CreateLaunchConfiguration) could expand to gigabytes in the shared
emulator JVM. Bounds it the same way AwsJsonCborController.decodeBody
already does: read in chunks, discard and warn past 10 MB decompressed.

Also documents the container-ips-routable override in both the main
and test application.yml templates, alongside the other ec2 keys.

* fix(ec2): bound aggregate concurrent UserData gzip decompression

The per-payload 10MB decompression cap runs independently per launch
on the unbounded cached launch executor, so it only bounds what a
single launch can allocate. N concurrent RunInstances/
CreateLaunchConfiguration calls, each smuggling a near-cap gzip
payload, could together decompress N * 10MB at once with no aggregate
ceiling.

Add a shared Semaphore(4) that gunzip must acquire before
decompressing and release afterward, budgeting ~40MB of decompressed
UserData in flight at a time - a few multiples of the per-payload cap
rather than 1, so an ordinary burst of legitimate concurrent launches
isn't serialized to one at a time. A launch that can't acquire the
budget blocks briefly rather than failing, mirroring the existing
ContainerLauncher.POPULATE_SEMAPHORE pattern for capping concurrent
code-volume populates.

Adds a concurrency test that drives 12 real concurrent launches with
near-cap gzip UserData through a fixed thread pool and asserts, via a
test-only hook, that peak concurrent decompressions never exceeds 4.
Verified the test fails (peak of 12) when the budget is disabled.
2026-08-28 11:35:06 -04:00
Allen Sanborn f1ad306599 fix(ec2): round-trip launch template data instead of discarding it (#2595)
* fix(ec2): round-trip launch template data instead of discarding it

CreateLaunchTemplate returned 200 and kept only ImageId, InstanceType,
KeyName, UserData, IamInstanceProfile, SecurityGroupIds and
TagSpecifications. Every other member of RequestLaunchTemplateData was
dropped without a word, so Terraform read back its own input missing and
reported "Provider produced inconsistent result after apply", or diffed
forever. MetadataOptions with HttpTokens=required (IMDSv2) and
BlockDeviceMappings appear in most Gruntwork ASG and ECS modules.

The AWS EC2 service model is the reference for what is stored and for the
element names it is read back under: request parameter names are the ones
botocore's EC2 serializer emits (note the singular BlockDeviceMapping.N
and NetworkInterface.N list prefixes, taken from each list member's
locationName), and response elements use ResponseLaunchTemplateData's
locationNames.

Stored and read back unchanged: ImageId, InstanceType, KeyName, UserData,
KernelId, RamDiskId, SecurityGroupIds, IamInstanceProfile,
BlockDeviceMappings, NetworkInterfaces, TagSpecifications, MetadataOptions,
Monitoring, Placement, CpuOptions, CreditSpecification, EnclaveOptions,
HibernationOptions, MaintenanceOptions, PrivateDnsNameOptions,
CapacityReservationSpecification, EbsOptimized, DisableApiTermination,
DisableApiStop, InstanceInitiatedShutdownBehavior.

Two further contradictions in the same call, both fixed:

- IamInstanceProfile keeps the form it was given. A profile submitted as
  Name reads back as Name rather than being rewritten to an Arn, so
  aws_launch_template.iam_instance_profile.name converges. The
  instance-profile ARN is derived at launch time instead.
- NetworkInterfaces survives as a NetworkInterfaces block. Its Groups are
  no longer hoisted into top-level SecurityGroupIds; on AWS the two are
  mutually exclusive, and the promotion made the block vanish from state.
  A launch resolves security groups from whichever of the two is set.

Deliberately out of scope, accepted and ignored rather than rejected:
InstanceMarketOptions, InstanceRequirements, LicenseSpecifications,
ElasticGpuSpecifications, ElasticInferenceAccelerators,
NetworkPerformanceOptions, Operator, SecondaryInterfaces, and
SecurityGroups (groups by name). Within NetworkInterfaces the IPv4/IPv6
address and prefix lists, EnaSrdSpecification,
ConnectionTrackingSpecification, PrimaryIpv6 and EnaQueueCount are also
ignored. A focused subset that round-trips beats a broad partial one.

LaunchTemplate no longer mirrors launch data in flat fields alongside its
version map; it holds one LaunchTemplateData, which removes the
dataFrom/applyData sync and collapses two 11-argument service methods into
a parameter object with explicit merge semantics for version creation.

Fixes a compatibility defect this collapse introduced (flagged by review):
a template persisted before this change stored the IAM instance profile as
a bare iamInstanceProfileArn string and instance tags as a flat
instanceTags list, both directly on LaunchTemplate and, separately, inside
each entry of its versions map. Neither key exists on the new model, so
ignoreUnknown silently dropped both on load - an upgrade would launch from
an existing template with no IAM profile and no instance tags, with
nothing in the logs to say so.

Legacy @JsonSetters on LaunchTemplateData and LaunchTemplate map both old
keys onto the new shape at load time, covering the versions-map entry (the
path DescribeLaunchTemplateVersions and AutoScaling actually read) and the
top-level fields (the path a template with no versions map falls back to).
Deserialize-only, so a file saved by the current code never regains the
old shape. Ec2ServicePersistenceTest#legacyIamProfileAndInstanceTagsSurviveRestart
seeds a hand-built pre-migration ec2-launch-templates.json and asserts both
paths survive a restart; reverting the two model changes alone fails it.

* fix(ec2): correct SourceVersion inheritance and round-trip VersionDescription

Addresses review feedback on the prior commit:

- CreateLaunchTemplateVersion with SourceVersion omitted merged onto the
  latest version instead of following the AWS-documented "no source
  specified, no inheritance" behavior. A version created without
  SourceVersion now starts from an empty LaunchTemplateData, populated
  only by whatever fields the request itself supplies.
- VersionDescription was accepted and silently dropped. It is a
  version-level field on LaunchTemplateVersion, not a member of
  RequestLaunchTemplateData, so it is tracked in a parallel per-version
  map on LaunchTemplate (alongside VersionNumber, CreateTime) rather than
  inside LaunchTemplateData, and round-trips through
  DescribeLaunchTemplateVersions. CreateLaunchTemplate accepts the same
  field for the initial version.
- SecurityGroups (security groups by name) stays out of scope: resolving
  names to IDs would need lookup machinery - store scan, not-found
  handling, ambiguity across VPCs - that no other EC2 action here has
  either (RunInstances itself only accepts SecurityGroupId). Documented
  the reasoning in both the code and docs/services/ec2.md so the ignored
  list stays accurate now that SourceVersion and VersionDescription are
  handled correctly.
2026-08-28 11:08:52 -04:00
Sam Fakhreddine 9563b7ef08 feat(ec2): IPAM with real CIDR allocation, EBS encryption defaults, and transit gateway route export (#2596)
* feat(ec2): add IPAM model, CIDR math and Ec2IpamService

Emulates VPC IPAM: organization admin delegation, IPAMs with default scopes, hierarchical pools with provisioned CIDRs, and netmask/specific-CIDR allocations that skip space held by allocations and child pools. This is the surface LZA needs for Custom::EnableIpamOrganizationAdminAccount (Organization stage) and the get-ipam-subnet-cidr Lambda (Deploy stage).

* feat(ec2): wire IPAM actions into the EC2 query handler

Adds 13 dispatch arms and XML writers: enable/disable org admin, IPAM and pool CRUD, provisioned CIDR reads, and pool CIDR allocate/release/list.

* test(ec2): construct Ec2QueryHandler with the IPAM service

* feat(storage): add OwnedEntry/findAnyAccount helpers

Extracted from 9dfda3cb (fix(s3): resolve buckets cross-account under
a global bucket namespace) — that commit's storage-layer helpers are a
genuine prerequisite for the Route 53 VPC associations work that follows,
but its full diff also carries an unrelated S3 replication feature chain.
This isolates just the additive AccountAwareStorageBackend.OwnedEntry /
findAnyAccount / findAnyAccountEntry helpers those commits need.

* feat(ec2): add owner-account overload for createIpamPool

Adds a createIpamPool overload taking an explicit ownerId, with the 6-arg
form delegating to it using the ambient default account. Purely additive
delegation; existing callers are unaffected.

Provenance: extracted verbatim from 91b93aab ("fix(ec2): stamp IPAM and IPAM
pool ownerId with the resolved account"), which is otherwise CloudFormation
provisioning work and remains on hold. Only the Ec2IpamService method is taken
here — none of that commit's Cfn provisioner files are included. The overload
itself touches no CloudFormation code; it is needed because account-scoped IPAM
tests construct pools for an explicit owning account.

* feat(ec2): add IPAM ASN associations and discovery operations

* fix: preserve shared IPAM pool ownership

* feat(ec2): add ModifyIpamPool

Net-new operation, part of the deferred 16-op EC2 IPAM/TransitGateway
P0 block. IpamPool gains autoImport, allocationMinNetmaskLength,
allocationMaxNetmaskLength, and allocationDefaultNetmaskLength fields
(the CIDR allocation defaults real ModifyIpamPool controls); resource
tag add/remove is out of scope for this pass.

Persists through the existing requireOwnedPool/savePool account-scoped
helpers, matching every other pool mutation in this service.

* feat(ec2): EBS account-level encryption defaults

Adds Get/Enable/DisableEbsEncryptionByDefault and
Get/Modify/ResetEbsDefaultKmsKeyId, region-scoped with the AWS-managed
alias/aws/ebs fallback. LZA's SecurityStack
Custom::EnableEbsEncryptionByDefault Lambda calls these and previously
failed with UnsupportedOperation.

* test(ec2): construct Ec2QueryHandler with the EBS encryption service

* feat(ec2): add GetSecurityGroupsForVpc and ModifyVpcEndpoint

Two of the deferred 16-op EC2 IPAM/TransitGateway P0 block; grouped
together since neither has ties to IPAM or TransitGateway and there
was no existing feature branch for standalone VPC-endpoint/
security-group work.

GetSecurityGroupsForVpc filters the existing security group store by
vpcId, using the simplified SecurityGroupForVpc response shape (no
ipPermissions) per the real API. ModifyVpcEndpoint adds a
policyDocument field to VpcEndpoint plus add/remove-list handling for
route tables, subnets, and security groups; IpAddressType/DnsOptions/
SubnetConfigurations are out of scope for this pass.

New branch cut from main (both ops depend only on core SecurityGroup/
VpcEndpoint infra that already lives there, not on any in-flight
feature branch's work).

* feat(ec2): add ExportTransitGatewayRoutes

No real S3 write happens: the operation validates the route table and
bucket, then returns a deterministic s3:// location string matching the
real operation's export naming convention.

* fix(ec2): honour ClientToken on the IPAM pool creates and allocations

* fix(ec2): keep IPAM and IPAM-pool mutations owner-only

* fix(ec2): return MissingParameter for absent IPAM pool and scope ids

* fix(ec2): store the IPAM delegated administrator organization-wide

* test(ec2): cover IPAM ClientToken idempotency at the wire level

* docs(ec2): document the IPAM operations

* docs(ec2): document the EBS encryption defaults and the other branch-added operations

* fix(ec2): drop the ModifyVpcEndpoint copy superseded by upstream #2526

Upstream landed its own ModifyVpcEndpoint (2e8cbc13d), so the branch
copy became a duplicate case label, a duplicate handler and service
method, and a doubled policyDocument element in vpcEndpointXml. The
branch wire tests now exercise the upstream implementation and pass
unchanged. GetSecurityGroupsForVpc from the same original commit is
not upstream and stays.

* fix(ec2): enforce the modelled IPAM enums on create and modify

Tier, MeteredAccount and AddressFamily are all modelled enums, and all
three were stored verbatim. CreateIpam and ModifyIpam wrote whatever
arrived into the IPAM and DescribeIpams echoed it back; CreateIpamPool did
the same with AddressFamily, which is worse than cosmetic — it is what
decides how the pool's CIDRs are parsed and allocated, so a pool created
with a third address family is a pool whose CIDR math never made sense.

Reject an unmodelled value with InvalidParameterValue, the code the rest
of this service already answers for a bad parameter. An absent value still
falls through to the AWS default, since every one of these members is
optional.

* fix(ec2): report the calling account as IPAM owner and harden IPAM input parsing

- CreateIpam/CreateIpamPool recorded config.defaultAccountId() as owner
  while account-aware storage partitioned by the caller, so a non-default
  account got resources whose ownerId and ARN named the wrong account.
  The handler now passes null and the service resolves null-means-caller
  with the same fallback chain storage uses.
- The ContextNotActiveException fallback in callerAccountId() now logs at
  debug so an unexpected context loss is diagnosable.
- Netmask-length parameters on ModifyIpamPool and AllocateIpamPoolCidr go
  through parseOptionalInt, returning InvalidParameterValue instead of an
  unmapped NumberFormatException on non-integer input.
- ReleaseIpamPoolAllocation's not-found message names the CIDR when no
  allocation id was supplied instead of rendering 'Allocation null'.
- Reworded the ExportTransitGatewayRoutes Javadoc: the S3 location has a
  unique random suffix, it is not deterministic.

* fix(ec2): require management account for IPAM org-admin delegation

EnableIpamOrganizationAdminAccount and DisableIpamOrganizationAdminAccount
never checked the calling account, so any member account could change or
remove the org-wide IPAM delegated administrator. Real AWS restricts both
operations to the organization's management account.

This emulator has no cross-service organization membership to resolve the
true management account from, so the configured default account stands in
for it — the same account launched Lambdas resolve to when calling without
an assumed role, matching how LZA's Organization-stage custom resource
invokes these operations.

* test(ec2): verify the IPAM org-admin gate against the real query path

Confirms EnableIpamOrganizationAdminAccount/DisableIpamOrganizationAdminAccount
succeed over the actual query-protocol endpoint using the same non-12-digit
credential style every other test in this suite uses, which
AccountContextFilter/AccountResolver resolve to the configured default
account -- the same resolution LZA's Organization-stage custom resource
relies on. Verifies 79bc8e251's management-account gate does not regress
that path.

* docs: drop the ec2 docs-drift tracking file, filed as floci-io/floci#2605

pgermosen's review on #2596 correctly flagged this file as a parallel,
invisible issue tracker that introduces a new top-level directory main
doesn't have, cites internal workflow details a maintainer can't act
on, and references a stale commit SHA unreachable from this branch's
history. The underlying finding (ten operations Ec2QueryHandler
dispatches with no docs row, predating this branch) is real and now
tracked as a GitHub issue instead.

* fix(ec2): use UnauthorizedOperation for the IPAM org-admin denial
2026-08-26 23:24:56 -04:00
Allen Sanborn 2e8cbc13d7 feat(ec2): support ModifyVpcEndpoint and persist the endpoint policy (#2526)
* feat(ec2): implement ModifyVpcEndpoint and store the endpoint policy

ModifyVpcEndpoint returned UnsupportedOperation. In a survey that drove 183
Terraform roots against Floci it was the single largest blocker, with 205 recorded
occurrences -- roughly five times the next entry.

A gateway endpoint is normally declared with its route tables, subnets and policy
attached after the endpoint itself exists, so aws_vpc_endpoint reaches for this
action in the ordinary case rather than an exotic one. EC2 is otherwise well
supported, which makes the failure especially expensive: a configuration builds most
of its infrastructure and then loses all of it to one refused call.

    Error: modifying EC2 VPC Endpoint (vpce-...): operation error EC2:
    ModifyVpcEndpoint, https response error StatusCode: 400,
    api error UnsupportedOperation: Operation ModifyVpcEndpoint is not supported.

Nearly all the state was already modelled -- VpcEndpoint carries routeTableIds,
subnetIds, securityGroupIds and privateDnsEnabled -- so this adds the handler, the
add/remove set semantics, and the one missing field.

The update is taken under the endpoint's stripe lock, following the convention
already used for network ACL entries and prefix lists. Terraform declares each
aws_vpc_endpoint_route_table_association as its own resource and applies them in
parallel, so several ModifyVpcEndpoint calls land on one endpoint at once; an
unsynchronized read-modify-write loses all but the last, and the losers' waiters then
poll for an association that was silently dropped:

    Error: waiting for VPC Endpoint Route Table Association (vpce-.../rtb-...) to
    become available: couldn't find resource (21 retries)

PolicyDocument is the missing field. CreateVpcEndpoint accepted it and silently
dropped it, and DescribeVpcEndpoints reported no policy, so an endpoint declared
with a policy read back without one and showed as drift on every plan even when
ModifyVpcEndpoint was never called. It is now honoured on create, on modify, and
cleared by ResetPolicy, which AWS documents as returning the endpoint to the default
full-access policy (modelled here as carrying no document).

Add/remove are set operations. AWS accepts adding an id that is already associated,
or removing one that is not, so both directions are idempotent. Every referenced id
is validated before anything is mutated, so a request naming one bad id cannot leave
the endpoint half-modified -- covered by a test.

Reference: request parameters, their optionality, and the minimal
{return, requestId} response --
https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyVpcEndpoint.html

Not implemented, as nothing in the model backs them yet: DnsOptions, IpAddressType
and SubnetConfiguration.N. They are accepted and ignored rather than rejected, which
matches how the other unmodelled endpoint attributes already behave.

Verified end to end. A Terraform configuration with two
aws_vpc_endpoint_route_table_association resources previously failed with the
"couldn't find resource" wait above, leaving one of the two associations dropped; it
now applies 6 resources with both associated. 378 existing EC2 and CloudFormation
tests still pass.

The concurrency test drives the service directly rather than over HTTP: requests
through the test server are serialized enough that an HTTP-level test passes even
with the lock removed. Driven through the service it fails on every run without the
lock, which is what makes it worth having.

* fix(ec2): honour ModifyVpcEndpoint presence semantics and the CFN endpoint policy

Follow-up corrections to the ModifyVpcEndpoint implementation in the preceding
commit. Three behaviour changes, each with a test that fails without it.

PolicyDocument was treated as absent when blank. The EC2 model gives the member no
`min`, so the only test the request supports is whether it is present; an empty
string is a value the caller supplied, and discarding it is the same silent-drop bug
the previous commit fixed for the create path. Presence is now the test, on create,
on modify, and when rendering DescribeVpcEndpoints.

An omitted VpcEndpointId reported InvalidVpcEndpointId.NotFound for the id "null".
VpcEndpointId is the sole required member of ModifyVpcEndpointRequest, and an absent
required Query parameter is MissingParameter here, as it already is for CreateSubnet
and CreateVpc. A present-but-unknown id still reports NotFound.

Ec2VpcEndpointCfnProvisioner passed null for the new policy parameter, so an
AWS::EC2::VPCEndpoint declaring PolicyDocument still lost it -- the EC2 API path was
fixed while the CloudFormation path kept the original bug. The property is declared
as JSON in the template and so arrives as an object node; it is serialised the way
IamRoleCfnProvisioner already serialises AssumeRolePolicyDocument.

Also tightens two error assertions in Ec2ModifyVpcEndpointTest that checked only for
status 400. UnsupportedOperation is also a 400, so both passed unchanged with the
action unrouted -- they proved nothing about the fix. Asserting the error code takes
the class from 8 of 11 failing to 9 of 11 when ModifyVpcEndpoint is unrouted.

Documents the action in docs/services/ec2.md, including the members accepted and
ignored.

* fix(cfn): resolve intrinsics in the VPC endpoint PolicyDocument

The AWS::EC2::VPCEndpoint provisioner serialised PolicyDocument straight
off the raw template node, so a policy built with Ref, Fn::Sub or
Fn::Join was stored as literal template syntax and DescribeVpcEndpoints
reported it verbatim.

Route it through CloudFormationTemplateEngine.resolveJsonAttribute, the
helper added in #2317 for JSON-valued attributes. It resolves the tree
and then unwraps a textual result instead of re-serialising it, avoiding
the double-encoding a naive resolveNode(...).toString() produces. It
also returns null for a null or missing node, so the old has()/isNull()
guard is redundant and goes away.

The javadoc previously cited IamRoleCfnProvisioner's bare toString() of
AssumeRolePolicyDocument as precedent; that precedent predates #2317 and
is no longer the right one to follow, so it now cites the helper instead.
2026-08-25 22:54:44 -05:00
Michal Schreiber bc0f88c9b1 feat(ec2): support transit gateway route tables, associations and routes (#2348)
* feat(ec2): support transit gateway route tables, associations and routes

CreateTransitGatewayRouteTable, DescribeTransitGatewayRouteTables and
DeleteTransitGatewayRouteTable; Associate, Disassociate and
GetTransitGatewayRouteTableAssociations; Enable, Disable and
GetTransitGatewayRouteTablePropagations; CreateTransitGatewayRoute,
DeleteTransitGatewayRoute and SearchTransitGatewayRoutes.

Part three of #2308, on top of the gateway in #2329 and the attachments
in #2347. Backs aws_ec2_transit_gateway_route_table and the association,
propagation and route resources beside it.

Behaviour taken from a live account rather than the reference:

- a table asked for by name is neither default; only the one a gateway
  mints for itself is
- an attachment associates with exactly one table, so a second attempt is
  Resource.AlreadyAssociated rather than a move
- association reports the transitional associating and disassociating,
  while propagation reports the settled enabled and disabled at once
- enabling propagation twice is
  TransitGatewayRouteTablePropagation.Duplicate
- a blackhole is a static route in the blackhole state rather than a type
  of its own, and carries no attachment
- deleting a table is refused while it is a gateway's default association
  table, and again while attachments are associated, both IncorrectState
  with their own messages
- an id that does not exist is InvalidRouteTableID.NotFound while one of
  the wrong shape is InvalidRouteTableId.Malformed, casing included

Associations live on the attachment record rather than in a store of
their own, since an attachment has at most one; propagations are their
own records, since an attachment may propagate into several tables.

Propagated routes are derived when routes are searched, from each enabled
propagation joined to the attached VPC's CIDR blocks, rather than
written down. Storing them would go stale the moment a VPC's CIDR
associations changed, and would need invalidating from every VPC and
attachment path.

Deleting an attachment removes its propagations and leaves a static route
that named it as a blackhole, which is what the live API does: the
destination stays configured with nowhere to go. Deleting a gateway takes
its tables' propagations, routes and tags with them, so nothing outlives
the table it belongs to. Every mutation runs under the region-scoped
topology lock introduced in #2347.

* fix(ec2): keep route table operations within one gateway and one lock

Three gaps found sweeping the new surface before review rather than after
it, each checked against a live account.

A route table reached attachments of any gateway. Associating,
propagating or routing to another gateway's attachment was accepted and
recorded, leaving a table pointing at something outside its own gateway.
AWS refuses all three as though the attachment did not exist, which is
the same shape a subnet from another VPC gets, and all five call sites
now do the same.

modifyTransitGateway writes route tables through its default-table
markers but held only the gateway's striped lock, so a modify racing a
route table delete could put the deleted table back. It and
createTransitGateway now take the topology lock as well, which makes the
rule exceptionless: every write to a gateway, route table, attachment,
propagation or route happens under that one lock, acquired before any
striped one.

Deleting an attachment left its propagations and any static route naming
it behind. On AWS the propagations go and the route survives as a
blackhole - the destination stays configured with nowhere to go - and
that is now what happens here. Deleting a gateway takes its tables'
propagations, routes and tags with it, so nothing outlives the table it
belongs to.

* feat(ec2): support ReplaceTransitGatewayRoute

Completes the route surface beside create, delete and search. Backs a
provider moving a route between an attachment and a blackhole without
recreating it.

Verified on a live account: replacing a destination the table has never
held writes it rather than reporting it missing, so this is an upsert
rather than an update. The target moves as a unit - a route turned into
a blackhole keeps no attachment, and one pointed back at an attachment
regains its id, resource and resource type together.

It carries the same rules as the rest of the route table surface: the
attachment has to belong to the table's own gateway, the write happens
under the topology lock, and a route it wrote is blackholed like any
other when its attachment is deleted.

* fix(ec2): apply the route search filters instead of ignoring them

SearchTransitGatewayRoutes handled four filter names and let every other
one through a default arm that matched everything, so a search by
route-search.supernet-of-match, subnet-of-match or longest-prefix-match
returned the whole table. A plausible wrong answer rather than an error.

The three take different value forms, which the reference does not spell
out. Observed on a live account, against a table holding 10.0.0.0/8,
10.1.0.0/16, 10.1.1.0/24 and 192.168.0.0/16:

  supernet-of-match 10.1.1.0/24  -> /8, /16 and /24, the exact match included
  subnet-of-match   10.1.0.0/16  -> /16 and /24, the exact match included
  longest-prefix-match 10.1.1.5  -> /24
  longest-prefix-match 10.1.9.9  -> /16
  longest-prefix-match 8.8.8.8   -> nothing

So the containment filters take a CIDR and match inclusively in either
direction, while longest-prefix-match takes a bare address and returns
the one most specific route covering it. Handing either the other's form
returns nothing there, and now here.

An unrecognised filter name is rejected rather than ignored, matching
InvalidParameterValue: Value (nonsense) for parameter Filter is invalid.
Silently accepting one answers a question that was never asked.
2026-08-18 15:59:58 -04:00
Michal Schreiber 74e43a4632 feat(ec2): support transit gateway VPC attachments (#2347)
* feat(ec2): support transit gateway VPC attachments

CreateTransitGatewayVpcAttachment, DescribeTransitGatewayVpcAttachments,
DescribeTransitGatewayAttachments, ModifyTransitGatewayVpcAttachment and
DeleteTransitGatewayVpcAttachment. Part two of #2308, on top of the
gateway itself.

The two describes are separate shapes rather than one being a superset:
the VPC-specific form carries the subnets and options, while the
resource-agnostic form drops both, types the VPC as a resource, and is
the only place the route table association appears.

Behaviour taken from a live account rather than the reference. The
attachment's option defaults are its own: dnsSupport and
securityGroupReferencingSupport enabled, ipv6Support and
applianceModeSupport disabled. The second of those is enabled here while
the gateway that owns the attachment defaults it to disabled, which is
not something the documentation calls out.

An attachment associates with the gateway's default route table only when
the gateway asks for it, and an association already made survives the
gateway later disabling that default: the association belongs to the
attachment from creation, and only later attachments are affected.

Rejections, all as observed: a VPC attached twice to one gateway is
DuplicateTransitGatewayAttachment, two subnets in one zone are
DuplicateSubnetsInSameZone, a subnet from another VPC is reported missing
rather than mismatched, removing a subnet that is not attached is
InvalidSubnetID.NotFound with its own wording, and removing the last one
is InsufficientSubnetsException. A malformed attachment id is rejected
before the lookup, with the terse message the real API uses.

Two changes reach outside the new surface, both deliberate:

DeleteTransitGateway now refuses while attachments exist, reporting
IncorrectState and naming them. Part one could not have hit this, since
nothing could attach then.

parseTagsForResource reads TagSpecifications as well as TagSpecification.
CreateTransitGatewayVpcAttachment declares no locationName on that member
and so serializes the plural, unlike its neighbours; every tag sent by
the AWS CLI was being dropped. The change only adds a spelling, so
actions using the singular are untouched.

State is reported settled rather than transitional, as for the gateway.
Ipv6Support is accepted without checking that the subnets carry IPv6
CIDRs, which real AWS rejects; Floci does not model subnet IPv6
allocation, and inventing that state to enforce it seemed worse than
documenting the gap.

* fix(ec2): make attachment uniqueness atomic and guard attached resources

Two defects in the VPC attachment work, both found in review.

The one-attachment-per-VPC rule scanned for an existing attachment and
then stored the new one without holding a lock between the two, so
concurrent creates for the same VPC could all find nothing and all
persist. Reproduced by disabling the fix: eight threads, eight
attachments, where the API promises one. The check and the write now
share the gateway's lock, and the test asserts one winner, the right
error for every loser, and one stored attachment, over forty trials.

Deleting a VPC or a subnet that an attachment uses left the attachment
naming resources that no longer existed, which surfaced later as a modify
failing on a subnet the caller never touched. Checked on a live account:
both refuse, with the same code and shape of message.

  DependencyViolation: The subnet 'subnet-…' has dependencies and cannot
  be deleted.
  DependencyViolation: The vpc 'vpc-…' has dependencies and cannot be
  deleted.

Both deletes now refuse the same way. A subnet of the attached VPC that
the attachment does not use still deletes, so the guard is no wider than
the dependency it protects.

* test(ec2): lighten the attachment concurrency harness

Forty trials of eight threads was heavier than the race needs — without
the lock it shows on the first trial — and the extra load disturbed two
thread-timing-sensitive tests elsewhere in the suite,
PostgresProtocolHandlerTest and ElbV2HealthCheckerTest, neither of which
this branch touches. Ten trials of six still reproduces it and leaves
those alone.

* fix(ec2): guard everything an attachment depends on under one lock

The previous fix locked the uniqueness check alone, which was too narrow
twice over. The gateway was resolved before the locked section, so a
concurrent DeleteTransitGateway could see no attachments, delete the
gateway, and let the create persist against the object it had already
read. The VPC and subnet checks were outside any shared lock at all, and
lockFor is striped, so a gateway's monitor never guarded a VPC or subnet
delete regardless.

Everything an attachment depends on now resolves and writes under one
region-scoped monitor: the gateway, the VPC, the subnets, and the
uniqueness rule. Deleting a gateway, a VPC or a subnet takes the same
monitor across its dependency check and its delete. Where a gateway lock
is also taken it is acquired inside this one, so the two cannot
interleave in opposite orders.

The test races a create against each delete and asserts the invariant
rather than a winner: whoever wins, the store must never hold an
attachment naming a gateway, VPC or subnet that is gone. It reproduces
both holes — with the create-side lock removed, "attachment outlived its
gateway" fails on the first trial.

* fix(ec2): stop a tag write restoring a deleted transit gateway resource

Tagging is a read-modify-write, so a tag call overlapping a delete could
read the record, lose the race, and put it back afterwards. A resurrected
attachment goes on blocking the VPC and subnets it names; a resurrected
gateway goes on refusing its own deletion. The gateway and route table
branches were as exposed as the attachment one, so all three moved
together rather than only the case reported.

Ordering matters as much as the lock here. The deletes take the topology
lock and then a striped resource lock, so the tag paths have to take them
the same way round; taking the topology lock further down the stack, with
the resource lock already held, deadlocks against a concurrent delete.
That is what the first attempt did, and the race test caught it as a pool
that never drained. createTags and deleteTags now take the topology lock
outermost for tgw- resources and updateResourceTags relies on its callers
for it.

The test races tagging against deletion for an attachment and for a
gateway, asserting neither comes back.
2026-08-18 07:05:24 -04:00
lex00 33d35b2079 feat(ec2): config toggle to report the AWS-faithful private IP (#2024)
* feat(ec2): config toggle to report the AWS-faithful private IP (#1983)

DescribeInstances reported the Docker container's bridge IP as PrivateIpAddress,
disagreeing with CloudFormation's subnet-allocated IP. Rather than force a
fidelity-vs-reachability tradeoff, this adds an opt-in:

  ec2.aws-faithful-private-ip (default false)

Default (false) is unchanged: the reported private IP is the reachable container
bridge IP, so instances can reach each other at that address on the shared
Docker network. When true, the CFN/subnet-allocated private IP set at launch is
reported instead (AWS-faithful); routing and IMDS always use the container
bridge IP (tracked separately as containerBridgeIp) regardless of the flag.

Wired via a new awsFaithful overload of exposeReachablePrivateAddress; the three
call sites pass the config flag. Test covers both modes.

Fixes #1983.

* docs(ec2): list aws-faithful-private-ip in application.yml and the config table

Every other floci.services.ec2 knob appears in both application.yml files and
the docs configuration table; this one was declared only on EmulatorConfig, so a
user-facing flag was undiscoverable.
2026-08-15 18:48:49 -05:00
Michal Schreiber 20470b7f4a feat(ec2): support transit gateways (#2329)
* feat(ec2): support transit gateways

CreateTransitGateway, DescribeTransitGateways, ModifyTransitGateway and
DeleteTransitGateway, as EC2 Query actions alongside the existing VPC and
route table ones. Metadata only: nothing routes packets, and the value is
in ids later resources can reference and describes that round-trip so
plans converge.

Option defaults come from a live AWS account rather than the reference:
amazonSideAsn 64512, dnsSupport, vpnEcmpSupport and both default route
table options enabled, autoAcceptSharedAttachments,
securityGroupReferencingSupport and multicastSupport disabled. The last
of those is the one worth stating, since disable is easy to assume the
other way round. transitGatewayCidrBlocks is omitted entirely when unset
rather than sent empty.

Creating a gateway with either default route table option enabled also
mints the route table AWS mints, and reports its id as both
associationDefaultRouteTableId and propagationDefaultRouteTableId. Both
name the same table, and it is already on the create response rather than
appearing later, so a caller reading either id sees what AWS shows. The
actions that operate on route tables directly are not implemented; nor
are attachments.

State is reported settled rather than transitional. AWS returns a new
gateway as pending and reaches available in about 50 seconds, and reports
deleting for about a minute before deleted; nothing here is slow, so the
settled state is what the caller sees, matching how
createManagedPrefixList already compresses create-in-progress.

Modify and delete echo the gateway without its tagSet while create and
describe include it, which is what the live API does.

Part one of #2308.

* fix(ec2): keep a transit gateway's default route table options coherent

ModifyTransitGateway changed the DefaultRouteTableAssociation and
DefaultRouteTablePropagation flags without touching their route table
ids, so a gateway created with both disabled could be modified into
reporting an option enabled while carrying no id for it.

AWS does not create a route table on that request; it rejects it unless
an existing table is named, and rejects an id supplied alongside a
disable. An unknown table comes back as InvalidRouteTableID.NotFound
rather than a transit-gateway-specific code. Checked on a live account:

  enable DefaultRouteTableAssociation conflicts with
  AssociationDefaultRouteTableId null

  disable DefaultRouteTableAssociation conflicts with
  AssociationDefaultRouteTableId tgw-rtb-0123456789abcdef0

  Transit Gateway Route Table tgw-rtb-0123456789abcdef0 was deleted or
  does not exist.

Validate instead: the flag and its id have to move together in both
directions, and a named table has to exist. The divergent state is now
unreachable and a rejected call leaves the gateway untouched.

* fix(ec2): carry a default route table change through to what it governs

Disabling DefaultRouteTableAssociation or DefaultRouteTablePropagation
changed the flag alone, leaving the id it governs on the gateway and the
matching marker on the route table. A describe then reported the option
disabled while still naming a table, and the table still claimed to be
the default for it.

Checked on a live account. Disabling association on a gateway created
with both defaults enabled drops AssociationDefaultRouteTableId from the
options entirely rather than blanking it, clears DefaultAssociationRouteTable
on the table, and leaves the table itself in place with its propagation
marker and the gateway's PropagationDefaultRouteTableId untouched:

  DefaultRouteTableAssociation  disable      (no AssociationDefaultRouteTableId)
  DefaultRouteTablePropagation  enable       PropagationDefaultRouteTableId tgw-rtb-…
  tgw-rtb-…  available  defAssoc False  defProp True

Apply the same: the id follows its flag, the table's marker follows with
it, and the table survives. Enabling with a named table marks that table
instead.

* fix(ec2): require a default route table to belong to the gateway naming it

The route table named on a ModifyTransitGateway request was only checked
for existence in the region, so a gateway could take another gateway's
table as its default. Worse than a bad reference: applying the change
then rewrote the foreign table's own default marker, leaving the gateway
that actually owns it describing a table that no longer claims to be its
default.

AWS rejects this, under the same code as a table that exists nowhere but
with the gateway named in the message. Checked on a live account, gateway
A naming gateway B's default table:

  Transit Gateway Route Table tgw-rtb-0381f… was deleted or does not
  exist in Transit Gateway tgw-0438f…

Both wordings are now reproduced: unqualified when the table exists
nowhere, gateway-qualified when it exists but belongs elsewhere.

The three rules governing these options - flag and id agreeing in both
directions, and the named table existing and belonging to the gateway -
now sit in one validation block rather than accumulating as separate
guards.

* fix(ec2): judge a default route table change against the stored gateway

Validation looked only at the request, so a route table id arriving
without its flag skipped the coherence check entirely: the id was stored
while the table's default marker was left alone, and a disabled option
could end up naming a table.

AWS judges the pair against the gateway as it stands. Probed the whole
combination surface on a live account rather than the one case reported:

  id alone, option enabled     accepted
  id alone, option disabled    InvalidParameterCombination, and the
                               message quotes the stored flag, not the request
  enable alone, table named    accepted, keeps that table
  enable alone, no table       InvalidParameterCombination
  disable with an id           InvalidParameterCombination
  disable with an unknown id   the combination is reported, not the lookup

So the flag defaults to the stored one when the request omits it, enabling
without an id keeps the table already named rather than dropping it, and an
id on its own marks its table. The lookup still runs after the combination
check, which is the order AWS reports them in.

Two other behaviours from the same pass, both already correct and now
covered: removals apply before additions, so a CIDR added and removed in
one call survives, and removing a CIDR that is not present is accepted.

* fix(ec2): serialize transit gateway CIDR blocks as the string list they are

transitGatewayCidrBlocks is a plain string list, so each item carries the
CIDR as its own text. The items wrapped it in a cidrBlock element
instead, which the AWS CLI parsed as an empty string: a caller that added
a block got it back as "" from create, describe and modify alike.

Caught by the CLI compatibility suite, not by the integration test, which
asserted the same wrong shape the handler produced and so agreed with it.
The bats case now reads the list back through describe as well as modify,
since one helper serializes all three responses.

* fix(ec2): apply tag changes to a transit gateway, not just to the tag store

CreateTags and DeleteTags on a tgw- id updated the tag store but left the
gateway object alone, because updateResourceTags had no branch for it.
DescribeTags saw the change and DescribeTransitGateways did not, so a
gateway kept serving whatever tags its TagSpecification carried at
creation.

That is the path a Terraform tag update takes: the provider sends
CreateTags, then re-reads with DescribeTransitGateways and compares. With
the two disagreeing, aws_ec2_transit_gateway would never converge.

Route tables get the same branch, so their tags behave once part three
can create them.

The AWS CLI cases now cover the tag round trip and CIDR blocks supplied
at creation, both of which were only asserted against shapes this branch
produced itself.
2026-08-15 18:11:24 -04:00
Michal SchreiberandMichal Schreiber dfcd492198 feat(ec2): allow a security group rule to take a prefix list as its source (#2271)
* feat(ec2): allow a security group rule to take a prefix list as its source

AuthorizeSecurityGroupIngress and AuthorizeSecurityGroupEgress now read
IpPermissions.N.PrefixListIds.M, so a rule can name a managed prefix list
instead of a CIDR. The rule carries prefixListId in place of cidrIpv4 and
DescribeSecurityGroups nests the reference under the permission, matching the
shapes AWS returns.

AWS emits one rule per source, so createRules expands a permission across its
CIDRs and its prefix lists rather than treating the two as alternatives; a
permission naming neither still yields the single bare rule it did before. An
unknown list is rejected with InvalidPrefixListID.NotFound before the rule is
stored, so a typo cannot leave a rule pointing at nothing.

Closes #2269

* fix(ec2): resolve every prefix list before writing any security group rule

createRules stored the CIDR rules of a permission before validating its prefix
lists, so a permission naming a valid CIDR alongside an unknown list returned
InvalidPrefixListID.NotFound while leaving the CIDR rule behind. AWS persists
neither, checked against a live account, and rejects the call as a whole rather
than per permission.

Resolve every reference a request names before the first write, across all of
its permissions, so a later bad permission cannot leave an earlier good one
applied. Also brace the new parsing conditional, as AGENTS.md requires.

* style(ec2): brace the conditionals in parseIpPermissions

AGENTS.md is unconditional about braces, and the method held five unbraced
conditionals around the line this branch added. Bracing the whole method rather
than only the new line keeps it internally consistent.

* fix(ec2): scope security group revocation to the sources it names

Revocation compared only protocol and ports, so revoking one source removed
every permission sharing that tuple: revoking a prefix list also dropped a CIDR
rule on the same port. AWS scopes it to the source, verified against a live
account, and leaves the others in place.

Subtract the named sources instead, dropping a permission only once it had
sources and has lost them all. A request naming no source at all still removes
the whole matching permission, which is how a bare protocol and port revoke
behaves.

The permission a revoke names can be the very object authorize stored on the
group, so the source values are snapshotted before either list is mutated.

* fix(ec2): validate prefix lists once per request rather than per permission

Resolving the prefix lists again inside createRules reopened the window the
request-wide check had closed: a list can be deleted between the two, since the
group lock and the prefix list lock are different monitors, so a later
permission could fail after earlier ones had already stored their rules.

Authorize resolves every reference before the first write, so the repeat is
removed. createRules keeps no validation of its own; its other callers pass the
CIDR-only default egress permission.

* fix(ec2): resolve group references when revoking too

Scoped revocation compares the sources a request names against the ones
stored on the permission. Authorize resolves a reference made by group
name to its group id before storing it, so a revoke naming the same
source by name alone carried no id and matched nothing: the rule
survived the revoke that named it.

Resolve on the revoke path as well, mirroring authorize.

This only surfaces once both source-scoped revocation and group
references as a source exist, so the gap is between this branch and
#2266 rather than in either alone.

---------

Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl>
2026-08-15 13:11:53 -04:00
lex00 30a61646ac feat(ec2): support CreateImage (create AMI from instance) (#1979)
* feat(ec2): support CreateImage from an instance

Validates the source instance exists, then registers an image the same
way RegisterImage does. Unblocks AMI-baking flows (e.g. CDK
AwsCustomResource calling ec2:CreateImage on a stack-created instance).

Fixes #1978

* fix(ec2): CreateImage reboots the source and produces a launchable AMI

Two review findings.

CreateImage ignored the default reboot. AWS reboots the source instance unless
NoReboot=true so the image is captured from a quiesced file system; the action
only checked that the instance existed. NoReboot is now parsed and the reboot
runs by default.

The resulting AMI kept nothing of what it was captured from. registerImage was
called with null architecture, root device and block device mappings, so
DescribeImages reported a generic x86_64 /dev/sda1 image with no devices, and
RunInstances on the new id fell through to the catalog default guest because a
generated ami-* is not in the catalog. The image now inherits architecture,
root device name and block device mappings from the source instance's image,
and records the launchable ancestor so RunInstances starts the same guest.
CreateImage on an instance launched from a created AMI follows the chain back.

Tests: unit coverage for the reboot default and its NoReboot opt-out, and for
chained images resolving to the catalog ancestor rather than the generated id;
integration coverage that an arm64 source yields an arm64 AMI that launches.

* fix(ec2): a capture of a catalog AMI reports its root device

CreateImage inherits the source image's block device mappings, but a catalog
entry describes only its root device name and carries no mappings, so an AMI
captured from a catalog-launched instance was registered with no devices and
DescribeImages reported none.

The root device is now rebuilt from the catalog entry, with a snapshot
registered through the existing RegisterImage path.

* fix(ec2): a capture takes its own snapshot of each device

CreateImage handed the source AMI's mappings straight to RegisterImage, so the
captured image reported the source's snapshot ids and the two images shared one
snapshot. The mappings are now copied with fresh snapshot ids, keeping the
device name, size, type and encryption.

* fix(ec2): a capture includes the volumes attached after launch

CreateImage read only the mappings of the AMI the instance was launched from, so
a data volume attached afterwards was missing from the captured image. AWS
records block device mapping information for those volumes as well.

The instance's attached volumes are now added to the capture, each with its
device name, size, type and a fresh snapshot. The root volume is skipped because
the source AMI already describes that device.

Also lists CreateImage and RegisterImage in the AMIs action table. That table is
hand-maintained because Ec2QueryHandler is a deferred handler.

* fix(ec2): a capture reports the root volume type the source actually has

The catalog-source fallback in sourceImageMappings recorded the rebuilt root
device as gp2, while RunInstances creates the source instance's root volume as
gp3. DescribeImages therefore reported a type the instance never had.

Both sites now read one DEFAULT_ROOT_VOLUME_TYPE constant, alongside the
existing DEFAULT_ROOT_VOLUME_SIZE_GIB, so the two cannot drift apart again.
2026-08-14 18:33:46 -04:00
TiM a6f5f12295 fix(ec2): keep the source on security group rules (#2266)
* fix(ec2): keep the source on security group rules

AuthorizeSecurityGroupIngress and -Egress read only
IpPermissions.N.IpRanges.M.CidrIp, so a rule whose source is another
security group was accepted and then silently stripped: it came back with
no source at all on the authorize response, on DescribeSecurityGroups and
on DescribeSecurityGroupRules. "Allow traffic from security group X" is how
an ALB is wired to its backend tasks, so that whole class of wiring could
be created against Floci but never asserted afterwards.

Parse the source types the permission actually carries: group references,
which the EC2 Query protocol serializes under the wire name Groups rather
than the SDK-facing UserIdGroupPairs, and IPv6 ranges. A reference made by
group name resolves to its group id within the target group's VPC, since
names are unique per VPC and ReferencedSecurityGroup has no name field.

Flatten one SecurityGroupRule per source entry, each keeping its own
description, matching the AWS invariant that a rule holds exactly one
source. A permission with no source at all still yields a single sourceless
rule, as before. The reference is returned as referencedGroupInfo on
DescribeSecurityGroupRules and as UserIdGroupPairs on
DescribeSecurityGroups.

An IPv6-only TCP ingress rule now publishes its host port, which it could
not do while the ranges were dropped at the parse; Ec2PortForwardManager
already treats IPv6 ranges as a CIDR source, and group references stay
unpublished.

Revoke still matches on protocol and port range alone and ignores sources,
unchanged by this.

Closes #2190

* style(ec2): brace the conditionals in the new source parsing

AGENTS.md requires braces on every conditional. The new IPv6 and group
source loops and the group-reference resolution used the unbraced form
the surrounding parse loop happens to use.
2026-08-14 11:41:36 -04:00
Michal SchreiberandMichal Schreiber 2d003b52f2 fix(ec2): reject prefix list names AWS reserves for its own lists (#2274)
* fix(ec2): reject prefix list names AWS reserves for its own lists

CreateManagedPrefixList accepted names beginning com.amazonaws., com.amazon. or
com.aws., which AWS refuses with InvalidParameterValue, so a customer list could
shadow a seeded gateway-endpoint one.

The trailing dot is part of each prefix. Checked against a live account:
com.amazonaws-probe and comamazonaws.probe are both accepted there, so matching
without the dot would refuse names AWS allows.

Closes #2273

* fix(ec2): apply the reserved-name rule to a prefix list rename too

ModifyManagedPrefixList persisted any nonblank name, so a list could be renamed
to com.amazonaws.us-east-1.s3 and returned alongside the seeded AWS-managed list
of that name. AWS applies the same rule to a rename, verified against a live
account, and leaves the existing name in place when it rejects one.

Create and rename now share the check.

---------

Co-authored-by: Michal Schreiber <michal.schreiber@benefitsystems.pl>
2026-08-14 09:53:57 -04:00
Michal SchreiberandMichal Schreiber ac4b865a34 feat(ec2): support managed prefix lists (#2105)
* feat(ec2): support managed prefix lists

Implement CreateManagedPrefixList, DescribeManagedPrefixLists,
GetManagedPrefixListEntries, ModifyManagedPrefixList and
DeleteManagedPrefixList.

Entries are versioned: a list starts at version 1 and every modification that
changes entries stores a new version, so GetManagedPrefixListEntries can serve
an earlier TargetVersion. Renaming or raising MaxEntries does not create a
version, CurrentVersion makes a modification conditional, and removals apply
before additions so one call can replace an entry's description.

The AWS-managed gateway-endpoint lists are now built once and served by both
DescribeManagedPrefixLists and the existing DescribePrefixLists, so the two
surfaces cannot report different CIDRs for the same list. They are read-only.

Closes #2100

* fix(ec2): validate prefix list input and keep tag copies in sync

Three defects in the managed prefix list surface:

ModifyManagedPrefixList only checked the resulting entry count against
MaxEntries, so a zero or negative MaxEntries on an empty list passed the check
and persisted an impossible capacity.

CreateTags and DeleteTags update the generic tag store and then mirror the
result onto the resource, but updateResourceTags had no arm for prefix lists,
leaving the copy on the model stale for describe responses and tag filters.

MaxEntries and TargetVersion were converted with Integer/Long.valueOf, so
malformed input escaped as an unchecked NumberFormatException and became a 500
rather than a structured EC2 client error.

* fix(ec2): reject a missing PrefixListId and infer the prefix-list tag type

A null PrefixListId reached List.of() inside describeManagedPrefixLists and
threw NullPointerException, so DeleteManagedPrefixList,
GetManagedPrefixListEntries and ModifyManagedPrefixList answered a request that
never named a list with a 500 rather than a client error. Guard the lookup and
raise MissingParameter.

inferResourceType had no pl- arm, so tags on a prefix list were stored but
reported as resourceType "unknown" and were invisible to a DescribeTags filter
on resource-type. The existing test only covered describe and tag: filters,
which is why this went unnoticed.

Also cover the accepting branch of the address-family check, which until now was
only reached by the rejecting case.

* fix(ec2): treat a blank numeric parameter as malformed rather than absent

intOrNull and longOrNull returned null for a present but blank value, which the
callers read as "parameter not supplied". For CurrentVersion that silently
downgraded a conditional ModifyManagedPrefixList to an unconditional one, so a
request that asked to be gated on a version was applied anyway. Only an absent
parameter is null now; a blank one reaches the parse and surfaces as
InvalidParameterValue.

* fix(ec2): report PrefixListVersionMismatch for a stale CurrentVersion

A conditional ModifyManagedPrefixList that loses the version check returns
PrefixListVersionMismatch on AWS, not IncorrectState; verified against a live
account, which also supplies the message. The Terraform provider keys its retry
handling on that code, so the previous one would have left a caller unable to
recognise a losing conditional update.

---------

Co-authored-by: Michal Schreiber <michal.p.schreiber@gmail.com>
2026-08-10 19:03:26 -05:00
soreavis d943e09a73 feat(ec2): add ReplaceRoute (#2178)
Terraform calls ReplaceRoute whenever an existing route changes target, so
route tables could be created but never updated; the only workaround was
to destroy and recreate the table.

The action replaces the target of the route matching DestinationCidrBlock.
AWS takes exactly one target per call, so the target a request does not name
is cleared rather than carried over; a merge would leave a route holding two
targets at once, which AWS cannot produce.

Only GatewayId and NatGatewayId are modelled by Route, plus LocalTarget,
which needs no new field because `local` is the gateway id a route table's
built-in route already carries. The other ten AWS targets keep the
UnsupportedOperation they returned before this action existed rather than
being accepted and silently clearing the route they were meant to repoint.

Errors follow the EC2 reference: InvalidRoute.NotFound when no route matches
the destination, MissingParameter when DestinationCidrBlock is absent (an
IPv6 or prefix-list request), and InvalidParameterCombination for two
targets or none.

Closes #2087
2026-08-08 22:47:28 -04:00
TiM 321394fea0 docs: fill supported action descriptions (#1819)
* docs: fill supported action descriptions

* docs(elb): describe listener default rule as non-deletable, not immutable

The CreateListener row called the default rule "immutable", which contradicts
the ModifyListener row (updates default actions) and the file's own note that
the rule can be changed via ModifyListener. The rule cannot be deleted or
reprioritized, but its action is mutable, so "non-deletable" is accurate.
2026-07-10 17:45:51 -05:00
Hector Ventura a27971c7d5 feat(ec2): publish security-group TCP ingress ports on the host (#1680)
* feat(ec2): publish security-group TCP ingress ports on the host

For each TCP port opened to a CIDR source by an instance's security
groups, start an alpine/socat sidecar that binds an allocated host port
(default 30000-30999) and forwards to the instance container's IP, so
the app is reachable from localhost. Forwards reconcile at launch, on
authorize/revoke-security-group-ingress, and on ModifyInstanceAttribute
group reassignment (previously ignored). Mappings persist and are
restored across restarts. SSH is never re-forwarded; wide rules and
per-instance totals are capped; disable with
publish-security-group-ports=false.

* fix(ec2): drop stale port mapping when sidecar recreation fails

On restore, a failed socat recreation released the host port but left
the appPort->hostPort entry in publishedPorts, so later reconciles saw
the port as already published and never re-published it, and a later
unpublish could double-release the host port. Remove the entry and
persist on failure. Also null-guard portForwardManager.restore() for
consistency with the setPersister guard. Adds a regression test.

* fix(ec2): skip port-forward reconcile on non-running instances

A reconcile queued by authorize-security-group-ingress could run after
a concurrent stop/terminate had already cleared publishedPorts and
removed the container; it then republished via the stale bridge IP,
leaking an orphaned socat sidecar and a host port that nothing would
release. Stop/terminate flip the instance state before their async
unpublishAll, so guarding reconcileNow on the running state under the
instance lock closes every window. Adds regression tests.
2026-07-01 23:00:27 -05:00
TiM 398100100a docs: add supported action description columns (#1639) 2026-06-29 19:29:43 -05:00
Jason van Zyl ad785f95f6 feat(ec2): add Java-built Ubuntu AMI guest image (#1542) 2026-06-25 00:33:15 -05:00
seyi idowu 7efb280dbc fix(ec2): VPC endpoint compatibility for AWS SDK/Terraform (#1476)
- emit routeTableIdSet/subnetIdSet items as plain text (AWS SDK for Go could not
  deserialize the wrapped form)
- add DescribePrefixLists returning managed S3/DynamoDB prefix lists
- honor private_dns_enabled (default true for interface endpoints)

Adds Ec2IntegrationTest coverage and documents the new actions.
2026-06-23 21:57:37 -05:00
seyi idowu 2301db53c7 feat(ec2): add Network ACL support (#1473)
Implements CreateNetworkAcl, DescribeNetworkAcls (with vpc-id / default /
association.subnet-id filters), CreateNetworkAclEntry, ReplaceNetworkAclEntry,
DeleteNetworkAclEntry, ReplaceNetworkAclAssociation, and DeleteNetworkAcl.
Every VPC is provisioned with a default NACL and each subnet is associated with
it, so aws_network_acl and aws_default_network_acl work via Terraform.

Adds Ec2IntegrationTest coverage and documents the new actions.
2026-06-22 22:57:57 -05:00
Jason van ZylandHector Ventura 56706217d3 feat(autoscaling): support group reconciliation and refresh (#1393)
* feat(autoscaling): support group reconciliation and refresh

* fix(ec2): align instance runtime parity

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
Co-authored-by: Hector Ventura <hectorvent@gmail.com>
2026-06-18 18:14:19 -05:00
Jason van Zyl f9c305b7c6 Add EC2 provisioning primitives (#1252)
* feat(ec2): load AMI catalog metadata

* feat(ec2): add Ubuntu 24.04 AMI metadata

* feat(ec2): add launch template APIs

* feat(ec2): add launch template version APIs

* feat(ec2): add VPC endpoint CRUD

* feat(ec2): add NAT gateways and instance offerings

* fix(ec2): add t4g.medium instance offering

* fix(ec2): preserve launch template version data

* fix(ec2): align subnet helper references

* fix(ec2): keep VPC endpoint services empty
2026-06-11 01:32:17 -05:00
Hector Ventura 832cdf94db feat(ec2): real Docker container execution with SSH, UserData, and IMDS (#658)
* feat(ec2): real Docker container execution with SSH, UserData, and IMDS
* fix: test for ec2
2026-04-30 18:28:17 -05:00
TiM a32b7f1f3b docs: comprehensive audit sweep + CHANGELOG backfill (1.1.0-1.5.2) (#326)
CHANGELOG.md was empty for the 1.1.0-1.5.2 release cycle and service docs
had drifted from code behaviour. This sweep reconciles docs against the
current codebase on upstream/main.

- Backfill CHANGELOG.md for 1.1.0 through 1.5.2 from git history
- Correct exact operation counts in docs/services/index.md: S3 (~30 -> 58),
  Lambda (~25 -> 30), API Gateway v1 (~24 -> 62). Counts now come from the
  actual dispatch handlers rather than @Path annotation counts.
- Rewrite README "Supported Services" table to drop per-service op counts
  (they drift too fast); point readers at docs/services/index.md
- Update 24 service docs for accuracy, add "Not Implemented" sections
  where relevant (s3.md, lambda.md, api-gateway.md)
- Refresh configuration and getting-started docs
- Add EventBridge Scheduler and AppConfig to mkdocs nav
- Add AppConfig / AppConfigData rows to README and services index
  following the 1.5.2 upstream release
2026-04-10 10:52:34 -05:00
Hector Ventura 2859d257b5 feat(ec2): add EC2 service with 61 operations, integration tests, and docs (#213)
* feat(ec2): adding ec2 service
* feat(ec2): add EC2 service with 61 operations, integration tests, and docs
2026-04-06 00:22:53 -05:00