Commit Graph
64 Commits
Author SHA1 Message Date
Allen Sanborn e22bd2c59a feat(ec2): support transit gateway peering attachments (#5122)
* feat(ec2): support transit gateway peering attachments

Add CreateTransitGatewayPeeringAttachment, DescribeTransitGatewayPeeringAttachments,
AcceptTransitGatewayPeeringAttachment and DeleteTransitGatewayPeeringAttachment, the
calls the Terraform provider's aws_ec2_transit_gateway_peering_attachment and
_accepter resources make. Previously each answered UnsupportedOperation.

An attachment is created in pendingAcceptance and moves to available when accepted
from the accepter's region. One attachment id serves both sides, so a cross-region
peering is visible from either region and the transit-gateway-id filter matches either
side's gateway, which is how the accepter finds it. Tags come from the shared tag
store, so CreateTags on the accepter side round-trips through describe.

* style(ec2): order the TransitGatewayPeeringAttachment import

* fix(ec2): hold peered transit gateways and accept peerings only as the peer

DeleteTransitGateway now refuses with IncorrectState while a non-deleted
peering attachment names the gateway at either end, as it already does for
VPC attachments; creation takes the same topology lock so neither lands in
between.

A peering is stored under the requester's account, so lookups search every
account's partition and admit only the two parties, as VPC peering does.
Accept requires the caller to be the accepter's account in the accepter's
region, so a requester can no longer accept its own cross-account request,
and the peer account can now see and accept it. The local-owner-id and
remote-owner-id filters are relative to the viewer's side.

* test(ec2): cover transit gateway peering attachments in the AWS CLI compatibility suite

* style(ec2): drop em dashes from the peering attachment comments

* refactor(ec2): make the peering attachment store final and pass it through the constructor

The StorageFactory constructor now hands the factory-backed store to the
terminal constructor, and the hermetic overload passes an InMemoryStorage,
the same way the other EC2 stores are wired.

* fix(ec2): clear both sides' tags when a cross-account peering attachment is deleted

Tags are per account: each party to a peering sees the tags its own account
set. Deleting the attachment cleared only the caller's, so the other
party's tags outlived it.

* fix(ec2): let a pending peering's accepter delete its transit gateway

Anyone can name any gateway as their peer, so a peering that has not been
accepted no longer holds the accepter's gateway. Deleting that gateway
declines the peering, leaving it rejected. Accepted peerings still hold
both ends, and a pending one still holds its requester's.

* fix(ec2): accept a transit gateway peering only for a gateway the accepter owns

The peer gateway is recorded unresolved at create, so an account could name
another account's gateway as the peer with its own account as PeerAccountId,
accept it, and pin that gateway against its real owner's DeleteTransitGateway.
Accepting now requires the peer gateway to exist in the caller's account and
region, the same lookup create makes for the requester's gateway.

* fix(ec2): route transit gateway peering actions to ec2 without a credential scope
2026-10-08 19:59:39 -04:00
Vũ Thế Huy dc41417e79 fix(ec2): avoid Docker waits on the first CreateVpc (#5179)
* fix: avoid Docker waits on first EC2 CreateVpc

* fix(ec2): reseed default VPC resources after a state reset

Ec2Service now implements Resettable: clear() forgets the seeded account
scopes and seeds the default region again, so a reset followed by
DescribeVpcs still returns the default VPC and subnets.

Also run Ec2CreateVpcLatencyTest in the non-mock EC2 compatibility job,
where VPC planning is active and a regression of the first-call Docker
wait would be caught.

* refactor(ec2): share one default-region seeding method between startup and reset

Ec2Startup and Ec2Service.clear() repeated the same enabled check and seed call. Both now go through Ec2Service.seedDefaultRegionIfEnabled() so they cannot drift apart. Also reorder the Resettable import.
2026-10-08 19:25:31 -04:00
Allen Sanborn a4c952db54 feat(ec2): support Dedicated Hosts (AllocateHosts, DescribeHosts, ModifyHosts, ReleaseHosts) (#4816)
* feat(ec2): support Dedicated Hosts (AllocateHosts, DescribeHosts, ModifyHosts, ReleaseHosts)

terraform's aws_ec2_host failed at create with "Operation AllocateHosts is
not supported". Add the four host actions following the Capacity
Reservation pattern: region-scoped store, dedicated-host tags through
TagSpecification and CreateTags, released hosts kept in DescribeHosts with
state "released", and unknown ids as InvalidHostID.NotFound on describe.
ModifyHosts and ReleaseHosts answer per host, putting an unknown, released
or (on release) occupied host in the unsuccessful set rather than failing
the call.

RunInstances now honours Placement.HostId and Placement.Tenancy: the host
must exist, tenancy defaults to "host", the zone defaults to the host's,
and DescribeInstances reports placement.hostId. DescribeHosts lists the
instances placed on each host.

* fix(ec2): default AllocateHosts AutoPlacement to off and drop the non-AWS host-recovery filter

AWS documents AutoPlacement as defaulting to off; the host record defaulted it
to on. host-recovery is not a DescribeHosts filter in the EC2 API, so it is no
longer matched.

* fix(ec2): validate Dedicated Host zone, settings and launch placement, serialise release against launch

RunInstances now rejects a host placement whose zone, tenancy or instance type
contradicts the host, re-checked under a lock shared with ModifyHosts and
ReleaseHosts. AllocateHosts rejects unknown zones; on/off host settings are
validated on allocate and modify. The hosts store is final again, braces and
the Consumer import follow AGENTS.md, and the RunInstances mock matcher in
Ec2RunInstancesPublicIpParamTest gains the two host parameters.

* test(ec2): pin exact host placement error codes and the in-lock host re-check

* fix(ec2): validate AllocateHosts zone against modelled zones, import classes

* style(ec2): fix import order and hostLock indentation, match AWS occupied-host message

* style(ec2): put java.util.Arrays after the non-java imports in the dedicated host test

* style(ec2): brace the host tag update and host tag lookup conditionals
2026-10-02 17:18:58 -04:00
Simone Primarosa c0ec98b43e feat(ec2): return spot price history for known instance types (#4698)
* feat(ec2): return spot price history for known instance types

* fix(ec2): address review feedback on spot price history pagination and platforms

* style(ec2): fix import ordering and inline qualified class names
2026-09-29 22:05:16 -04:00
Hector Ventura 43ed79d15b fix(core): service principals are universal in every partition; accept the legacy forms (#4633)
* fix(core): service principals are universal in every partition; accept the legacy forms

A service principal is <service>.amazonaws.com in every partition, the rule the CDK applies
(region-info.ts, principals.ts). Floci now emits it through ServicePrincipals.of: generated trust
policies, SAM's Lambda permissions, CloudTrail's eventSource, service-linked role paths (Macie,
GuardDuty, Connect, Application Auto Scaling, RAM, SSO) and the Redshift COPY trust check.

Policies may still name a service in the per-partition form AWS accepted before
(elasticmapreduce.amazonaws.com.cn, logs.cn-north-1.amazonaws.com.cn, config.c2s.ic.gov), and AWS
still honours them. ServicePrincipals.canonical folds a published DNS suffix and a regional label
away, and the trust-policy evaluator and CreateServiceLinkedRole compare in that form, so either
spelling matches.

DescribeVpcEndpointServices now lists China's S3 interface service, cn.com.amazonaws.<region>.s3,
beside the com.amazonaws gateway one, each with its own type; where the names agree it stays one
service carrying both types.

Partition literal baseline 34 -> 4 occurrences. The web-identity and pod-identity audiences keep
their commercial literals, escaped for the STS phase.

Part of #4272

* fix(iam): put a legacy-named service-linked role under the universal principal

CreateServiceLinkedRole derived the role name from the universal principal but kept the caller's legacy spelling (es.amazonaws.com.cn) in the path and the trust policy. All three now use the universal principal, so the role lists under /aws-service-role/es.amazonaws.com/ like one created from the universal name.

ServicePrincipals.canonical no longer lower-cases: service-principal matching is exact and case-sensitive since #4555, and AWS matches principals case-sensitively, so only a suffix written the way AWS publishes it folds.
2026-09-29 20:33:07 -04:00
Simone Primarosa d1a9b50cf5 feat(ec2): resize volume backing files and loop devices on ModifyVolume (#4666) 2026-09-29 19:00:10 -05:00
Abhigya 014156a546 fix(ecs): register reachable task addresses in Cloud Map and bound synthesised ENI addresses (#4509)
* fix(ecs): register reachable task addresses in Cloud Map and bound synthesised ENI addresses

ECS service discovery registered an awsvpc task's ENI address, but task
containers never join the subnet's network, so peers resolved a name and
then timed out. Register the address the task container holds on its
Docker network instead, falling back to the ENI address only when there
is no running container.

The synthesised private-address fallback in EC2 counted past the subnet
CIDR (10.70.1.549) and restarted at .10 on every boot. It now allocates
inside the subnet CIDR, skips the AWS-reserved addresses and every address
a persisted ENI, instance or NAT gateway still holds, and reports
InsufficientFreeAddressesInSubnet when the subnet is full.

* fix(ec2): hold the synthesised-address lock until the resource is persisted

The allocator chose a free address under its lock but released it before the
network interface, instance or NAT gateway holding the address was stored, and
it decides what is free from stored resources. Two concurrent creates could
both take the same address, most visibly at the end of a /28 where the cursor
clamps back onto the last one handed out.

A dedicated lock now covers allocation through persistence at each caller:
CreateNetworkInterface, CreateNatGateway and the RunInstances loop, where it
is taken inside imageRegistryLock.

* fix(ecs): advertise the container port for an awsvpc task registered at its container address

* docs(ecs): state which Cloud Map address and port each network mode registers

* fix(ecs): look for stale Cloud Map instances at an awsvpc task's container address

The registrar registers an awsvpc task at the address its container holds on
its Docker network, but the eviction from #4513 resolved the task's addresses
through resolveContainerHost, which is 127.0.0.1 when Floci runs natively, so a
stale instance at the container address was never found. Load balancer target
eviction is unchanged, since targets are still registered through
resolveContainerHost.

* refactor(ec2): nest the address allocation lock visibly inside runInstances

Scope privateIpAllocationLock to the instance-building loop, the only part that
allocates and persists addresses, and indent it under imageRegistryLock.

* fix(ec2): allocate a launch's addresses before storing any of its instances

A RunInstances larger than the subnet's free addresses failed with
InsufficientFreeAddressesInSubnet only after the instances that fit had been
stored with their root volumes. The launch now allocates every address first,
counting the ones it has already picked as taken, and releases any Docker
leases it took when the subnet runs out.
2026-09-29 14:36:28 -04:00
Simone Primarosa 70c1c407bc feat(ec2): support instance and network-interface route targets (#4416)
Support InstanceId and NetworkInterfaceId in CreateRoute, ReplaceRoute,
and DescribeRouteTables, automatically resolving InstanceOwnerId.

- Parse and store InstanceId and NetworkInterfaceId on Route
- Validate instance target existence and set InstanceOwnerId to caller account
- Enforce single-target mutual exclusion across all supported route targets
- Remove InstanceId and NetworkInterfaceId from UNSUPPORTED_ROUTE_TARGETS
- Render instanceId, instanceOwnerId, and networkInterfaceId in DescribeRouteTables
- Add DescribeRouteTables filter support for route.instance-id and route.network-interface-id
- Document route target support in docs/services/ec2.md
- Add integration tests in Ec2RouteTargetIntegrationTest
- Add AWS SDK compatibility tests in Ec2RouteTargetTest
2026-09-27 09:18:29 -04:00
Simone Primarosa 922402210f feat(ec2): attach volumes as real block devices (#4354)
* feat(ec2): attach volumes as real block devices

* fix(ec2): address review feedback on volume block device attachments

* fix(ec2,eks): handle volume deletion failures and node volume re-attachment on restore

* test(eks): verify cluster node instance registration and listener callback

* fix(ec2,eks): address review comments on loop device detachment and config

* fix(ec2): support both util-linux and busybox losetup in volume loop lookup
2026-09-24 21:10:55 -04:00
Simone Primarosa 077b65df5c feat(ec2): implement ModifyVolume and volume modification state (#4320) 2026-09-24 15:14:59 -04:00
Niels Kootstra 06ec4b563a fix(ec2): validate and expire IMDSv2 session tokens (#4303)
* fix(ec2): validate and expire IMDSv2 session tokens

PUT /latest/api/token accepted any TTL and tokens never expired. Require an
integer X-aws-ec2-metadata-token-ttl-seconds between 1 and 21600 (400
otherwise) and reject an expired or unknown token with 401, as IMDS does.
Requests without a token still use IMDSv1.

* test(ec2): use the shared MutableClock in Ec2MetadataTokenTest

Drop the test's private clock in favour of
io.github.hectorvent.floci.testing.MutableClock, which other tests
already share and which starts at the same instant.

* fix(ec2): reject an IMDSv2 token presented from another instance

A valid token won over the caller's IP, so container B presenting
container A's token received A's metadata, credentials included. The
docs say a token is not valid on other instances. Answer 401 when the
caller's IP maps to a different instance than the token's; an
unregistered IP still defers to the token.
2026-09-24 15:04:24 -04:00
Simone Primarosa 876ddc7422 feat(ec2): expose synthesized cluster node instances to the EC2 service (#4262)
* feat(ec2): expose synthesized cluster node instances to the EC2 service

* fix(ec2): enforce account isolation and tag persistence for cluster node instances

* fix(ec2): scope findInstanceById to caller account for external instances

Scope findInstanceById to the caller account when falling back to
external instances instead of matching across all accounts. Thread
the account identifier into SSM direct command execution, ELBv2 target
resolution, and classic ELB health checking so external cluster nodes
remain strictly account-isolated across all instance lookup paths.

* fix(ssm,eks): update test stubs for account-scoped direct execution and harden cluster provider
2026-09-24 08:27:52 -04:00
Harsh Pashine 625bcb80d7 docs(ec2): document ten dispatched operations missing from action tables (#2605) (#3769)
* docs(ec2): document ten dispatched operations missing from action tables (#2605)

AttachVolume, DetachVolume, DescribeSnapshots, CreateFlowLogs,
DeleteFlowLogs, DescribeFlowLogs, RequestSpotInstances,
DescribeSpotInstanceRequests, CancelSpotInstanceRequests,
DescribeVpnGateways are dispatched by Ec2QueryHandler but had no rows
in docs/services/ec2.md. Adds the rows by hand with descriptions drawn
from the handlers; EC2 stays on the docs generator deferred_handlers
allowlist.

Fixes #2605

* docs(ec2): clarify DescribeVpnGateways returns an empty set
2026-09-23 10:25:31 -04:00
Simone Primarosa 7c94f69571 feat(ec2): bound instance containers to their instance type resources (#4189) 2026-09-23 09:08:37 -04:00
Hector Ventura 6fadba8d57 fix(cloudformation): apply EC2 Instance UserData and IamInstanceProfile in place (#4206)
UpdateStack kept a reused AWS::EC2::Instance's prior UserData and
IamInstanceProfile because Ec2Service had no in-place path for either: the
provisioner reconciled only InstanceType and SecurityGroupIds. On AWS both are
mutable, UserData with the "some interruptions" of a stop and a start.

EC2 gains the three association actions, AssociateIamInstanceProfile,
ReplaceIamInstanceProfileAssociation and DisassociateIamInstanceProfile, with
botocore's wire names, all five members of the association including the
timestamp the instance now records, and the errors moto documents
(IncorrectState for a second association, InvalidAssociationID.NotFound for
an unknown id). ModifyInstanceAttribute accepts UserData.Value on a stopped
instance, answering IncorrectInstanceState otherwise, the order Terraform's
provider performs as stop, modify, start. The association id derivation moves
from the handler into Ec2Service so the provisioner can name an association.

Ec2InstanceCfnProvisioner rewrites a changed UserData across a stop and a
start (an already stopped instance stays stopped), resolves the profile name
to its ARN at provision time as the RunInstances handler does, associates or
replaces a changed profile, and disassociates one only when the template
declared it last time, recorded in a __Floci attribute so a profile a launch
template set is never stripped. A dropped UserData is left as it is, the same
rule SecurityGroupIds follows.

Tests: Ec2InstanceCfnProvisionerTest covers the stop/modify/start order, the
stopped case, associate, replace, disassociate and the undeclared-profile
guard; Ec2IamInstanceProfileAssociationIntegrationTest and
Ec2UserDataAttributeIntegrationTest pin the wire behaviour;
CloudFormationEc2InstanceIntegrationTest updates both properties on one
instance and reads them back through EC2.
2026-09-23 08:51:47 -04:00
Simone Primarosa 10eeafad69 feat(ec2): add an arm64 Amazon Linux 2023 image catalog entry (#4163)
Add an arm64 Amazon Linux 2023 entry to the EC2 image catalog paired
with the existing x86_64 image. The new entry provides the official
AWS GA arm64 AMI name and public SSM parameter paths under
/aws/service/ami-amazon-linux-latest/.
2026-09-22 14:49:05 -04:00
luiseterc df68eebaef feat(ec2): support an external image catalog (#4144) 2026-09-22 09:09:42 -04:00
Priamo Germosen 5a11e7f6fb fix(ec2): return DependencyViolation from DeleteVpc while dependents remain (#3916)
DeleteVpc now refuses while the VPC still has a subnet, a security group,
route table or network ACL other than the defaults, or an attached
internet gateway, as AWS does. Creating a subnet, group, route table or
network ACL, or attaching an internet gateway, re-checks the VPC under the
region topology lock, so a concurrent DeleteVpc can no longer leave one
pointing at a VPC that is gone. AttachInternetGateway now rejects a VPC
that does not exist.
2026-09-19 19:38:53 -05:00
Priamo GermosenandJason van Zyl a154470172 feat(ec2): validate DescribeVpnGateways and add DescribeEgressOnlyInternetGateways (#3879)
* feat(ec2): validate DescribeVpnGateways and add DescribeEgressOnlyInternetGateways

* refactor(ec2): drop unused region parameter from empty gateway discovery

* fix(ec2): return an empty set for an unknown egress-only gateway ID

---------

Co-authored-by: Jason van Zyl <jason@vanzyl.ca>
2026-09-19 08:33:08 -05:00
Priamo GermosenandJason van Zyl 75fee00adc fix(ec2): delete VPC default security group, route table and network ACL with the VPC (#3878)
* fix(ec2): delete VPC default security group, route table and network ACL with the VPC

* test(ec2): check deleted VPC defaults by VPC scope instead of by ID

---------

Co-authored-by: Jason van Zyl <jason@vanzyl.ca>
2026-09-18 23:48:38 -05:00
luiseterc 5ec3fb67a8 fix(ec2): resolve instance profile names through IAM (#3856) 2026-09-18 08:46:22 -04:00
Mohamed Amine ALOUINI 7e539155e1 fix(ec2): report the calling account as resource owner (#3814)
EC2 froze every resource's owner to the configured default account at
construction time, so OwnerId came back as 000000000000 no matter which
account the request resolved to. Per-account isolation itself worked, but
the reported owner contradicted what STS returns for the same credentials
and what SQS embeds in its ARNs.

The visible consequence was DescribeImages --owners: the filter was honored
but matched against the frozen value, so filtering on the account actually
in use returned nothing, and the common Terraform pattern of pinning an AMI
to a known owner account failed with "Your query returned no results".

Resolve the owner per request through callerAccountId() instead, for the
ownerId fields, the generated ARNs and the self owner alias. Callers outside
a request scope (startup seeding, internal provisioning) still fall back to
the configured default account.

Closes #3775
2026-09-17 13:36:30 -04:00
Hector Ventura 996a680cdc fix(ec2): reject key pair requests without KeyName (#3727)
* fix(ec2): reject key pair requests without KeyName

CreateKeyPair accepted a request with no KeyName and stored a nameless key
pair; the duplicate check then dereferenced that name on every later
CreateKeyPair, and the Query catch-all reported it as
"Unexpected error: null". CreateKeyPair and ImportKeyPair now answer
MissingParameter, ImportKeyPair answers InvalidKeyPair.Format instead of an
InternalFailure for material that is not base64, DeleteKeyPair requires a
name or an id and returns the deleted keyPairId, and the name comparisons
tolerate a nameless record already sitting in a persistent store. The EC2
docs still described the placeholder key material that #3307 replaced.

Closes #3356

* fix(ec2): return InvalidKey.Format for malformed key material on ImportKeyPair

The EC2 API error reference lists InvalidKey.Format as the key pair not being in a valid OpenSSH public key format, which is the message this branch sends. InvalidKeyPair.Format is a separate documented code for a different failure.
2026-09-16 19:06:32 -04:00
luiseterc 03603aeacd fix(ec2): stage user data outside guest temporary mounts (#3736)
* fix(ec2): stage user data outside guest temporary mounts

* docs(ec2): correct user-data script staging path
2026-09-16 18:34:54 -04:00
luiseterc d4a96913df fix(ec2): issue instance-profile role credentials through IMDS (#3742)
* fix(ec2): issue instance-profile role credentials through IMDS

* test(ec2): cover null IMDS unregister and shutdown revocation
2026-09-16 18:23:51 -04:00
Alexy GrabovandAlexy Grabov 7813d14ee4 feat(network): add opt-in security group enforcement (#3681)
* feat(network): add opt-in security group enforcement

* fix(ec2): make security group tests order independent

* fix(network): emit valid ICMP nft rules and restart protected instances

Three review findings on the opt-in security-group enforcement foundation:

- SecurityGroupNftCompiler built "icmp type 8 code 0 accept" for an AWS
  ICMP rule carrying both FromPort (type) and ToPort (code). nftables
  header fields are separate expressions, so nft rejected the whole
  compiled policy and the manager then quarantined every endpoint. Each
  field now repeats the protocol keyword, and a protocol rule with no
  type or code becomes "meta l4proto icmp accept", which was equally
  invalid as a bare "icmp accept".
- StartInstances followed the legacy restart path for a protected
  workload and waited for a Docker bridge IP on a container that shares
  the helper's network namespace and so has no attachment of its own.
  The helper survives the workload's stop, so start now reuses its
  transport address exactly as launch does, and skips the reachable
  private address rewrite the same way.
- Replaced the newly introduced var declarations with explicit types and
  imported the inline java.util/model FQCNs, per AGENTS.md.

* fix(network): scope the firewall helper to CAP_NET_ADMIN

The helper only has to program nftables inside the namespace Docker already
gave it, so full --privileged granted far more than the feature needs.
ContainerLifecycleManager now adds CAP_NET_ADMIN for the container carrying
the floci.security-group-helper label, mirroring the capability drop already
applied to protected workloads at the same choke point, and the helper spec
no longer asks for privileged mode.

Also replaces the inline java.util FQCNs the previous commit missed in
Ec2Service with imports, per AGENTS.md.

---------

Co-authored-by: Alexy Grabov <Alexy.Grabov@cyberark.com>
2026-09-15 14:30:49 -04:00
lex00 043167793b feat(ec2): carry the remaining launch template data fields (#3493)
* feat(ec2): carry the remaining launch template data fields

InstanceMarketOptions, InstanceRequirements and a network interface's
ConnectionTrackingSpecification were the last three RequestLaunchTemplateData
groups Floci accepted and threw away. A Terraform aws_launch_template that
declared any of them read back nothing, so it reported an inconsistent result
after apply or diffed forever.

Ec2QueryHandler now parses all three off the Query wire and renders them into
ResponseLaunchTemplateData, and LaunchTemplateData stores them. All 26 members
of InstanceRequirementsRequest are covered, including the nested
BaselinePerformanceFactors. CreateLaunchTemplateVersion inherits the new
members the same way it inherits the existing ones.

* fix(ec2): validate launch template instance requirements and connection tracking

InstanceRequirements and ConnectionTrackingSpecification became writable in the
previous commit, but nothing checked them. A block carrying only
BurstablePerformance was stored, and so was a network interface asking for a
one second TCP established timeout.

The EC2 service model declares VCpuCount and MemoryMiB required on
InstanceRequirementsRequest, and Min required on each of their range shapes, so
a request missing any of them now fails with MissingParameter. The connection
tracking timeouts have no min or max keys in the model; the ranges live in each
member's documentation string, which gives TcpEstablishedTimeout 60 to 432000
seconds, UdpTimeout 30 to 60 and UdpStreamTimeout 60 to 180. A value outside
one of those fails with InvalidParameterValue, matching the existing hop limit
check. CreateLaunchTemplate and CreateLaunchTemplateVersion both validate
before anything is stored.

* fix(ec2): reject the launch template combinations InstanceRequirements forbids

InstanceRequirements became writable two commits ago, and validation covered the
required members and the connection tracking ranges but not the combinations the
EC2 API reference rules out. Three of them were storable.

The service model documents each rule in a member documentation string rather
than in its constraints. RequestLaunchTemplateData says "If you specify
InstanceRequirements, you can't specify InstanceType". InstanceRequirementsRequest
says "If you specify AllowedInstanceTypes, you can't specify ExcludedInstanceTypes"
and "Only one of SpotMaxPricePercentageOverLowestPrice or
MaxSpotPriceAsPercentageOfOptimalOnDemandPrice can be specified". All three now
fail with InvalidParameterCombination from the shared validation path, so
CreateLaunchTemplate and CreateLaunchTemplateVersion are covered alike.

CreateLaunchTemplateVersion validates the merged version as well as the request it
received. The merge inherits every member the request does not restate and has no
way to express removal, so a version naming only InstanceType against a source
carrying InstanceRequirements would otherwise store a version holding both. That
merged version is what AutoScaling and the fleet APIs read, so it is rejected
rather than stored. Omitting SourceVersion starts from empty data and remains the
way to move a template between the two selection modes.

The instanceRequirementsRoundTrips test set both halves of two of these pairs. Its
assertions are unchanged; the members that cannot share a template moved to a
second template of their own.
2026-09-13 00:32:07 -04:00
lex00 325bdfb30e feat(ec2): report instance credit specifications (#3492)
* feat(ec2): report instance credit specifications

DescribeInstanceCreditSpecifications was not implemented, so the action
Terraform's aws_instance resource reads credit_specification from always came
back empty and every plan after an apply showed a credit_specification diff for
an instance nobody had touched. CreditSpecification is not a member of the
Instance shape DescribeInstances returns, per botocore's ec2 2016-11-15 model,
so this dedicated action is the only way that value can reach a client.

The credit option is the launch's explicit CreditSpecification.CpuCredits when
the request named one, and the instance type family's documented default
otherwise: standard for t2, unlimited for t3, t3a and t4g. The model's own
InstanceType enum lists t1, t2, t3, t3a and t4g as the only T families, and t1
predates the credit model, so that table is complete. The default is resolved on
read rather than frozen at launch, so a resize moves the instance onto its new
family's default.

The two request shapes mean different things and both are implemented. Naming
instance ids reports exactly those instances, and an id with no credit option is
an error rather than an omission, which is what the model documents for "an
instance that is not a burstable performance instance". Naming no ids reports
only the instances running unlimited, paginated by MaxResults and NextToken;
AWS rejects MaxResults together with instance ids and so does this.

DescribeInstanceTypes now reports burstablePerformanceSupported. Terraform
checks that flag before it reads a credit specification at all, so without it
the new action would never be called.

ModifyInstanceCreditSpecification is deliberately left out. Describe stands on
its own here: it fixes the read that produced the perpetual diff, and a launch
can already set the option through RunInstances or launch template data. The
modify path is a separate change.

Tests: Ec2InstanceCreditSpecificationsIntegrationTest covers each burstable
family default, a non-burstable type, an explicit launch-time override, an
unknown instance id, the unfiltered form and the MaxResults combination error
on the real Query wire. Ec2InstanceTypeCatalogTest covers the family table.
Ec2RunInstancesPublicIpParamTest's mocked signature gains the new parameter.

* fix(ec2): persist the instance credit option and report standard for non-burstable ids

The first cut of DescribeInstanceCreditSpecifications had the documented behaviour
backwards on two points. Both come from the operation's own documentation string in
botocore's ec2 2016-11-15 model, which the constraint keys alone do not carry.

"If you specify an instance ID that is not a burstable performance instance, Amazon
EC2 returns the standard credit option." A named m5 was answered with
InvalidInstanceID.NotFound, because effectiveCpuCredits() returned null for a type
with no credit model and the named-id path treated that as an unknown id. It now
reports standard. An id that names no instance at all is still
InvalidInstanceID.NotFound, which is the only error that path raises.

The unfiltered form returns burstable instances on the unlimited option "as well as
instances that were previously configured as T2, T3, and T3a with the unlimited
credit option. For example, if you resize a T2 instance, while it is configured as
unlimited, to an M4 instance, Amazon EC2 returns the M4 instance." A launch without
an explicit CreditSpecification stored null and the credit option was recomputed from
the instance's current type on every read, so a t3 that defaulted to unlimited lost
that option the moment it was resized onto an m5. The option is now resolved once, at
the point the instance acquires it, and stored on the instance:
Instance.creditSpecificationCpuCredits, written in runInstances from the request or
the family default, and written again in modifyInstanceAttribute when a resize moves
an instance with no option yet onto a burstable type. Reads return the stored value.
The family default stays on the read path only as a fallback for instance records
written before the option was stored.

Tests: aNonBurstableInstanceIdReportsStandard replaces the regression that locked in
the error. theUnlimitedOptionSurvivesAResizeOntoANonBurstableType,
aResizeOntoABurstableTypeAcquiresTheFamilyDefault and
aStandardOptionSurvivesAResizeOntoAnotherBurstableFamily cover the resize paths, and
the unfiltered-form test now also asserts a non-burstable instance is absent.

* fix(ec2): honor DryRun, Filter.N and the MaxResults range on DescribeInstanceCreditSpecifications

The EC2 model declares more request behavior for this action than the handler
accepted. All three gaps come from local/model-preflight.py ec2
DescribeInstanceCreditSpecifications, which prints the constraint keys and the
documentation prose together.

DryRun is a modeled member and the handler never probed it, so DryRun=true
returned a normal response instead of DryRunOperation. The pagination parameters
are now validated before the probe, matching the order the snapshot block public
access handlers use, since AWS reports an invalid parameter ahead of
DryRunOperation and only returns DryRunOperation once the request could
otherwise succeed.

Filter.N is a modeled member and was parsed nowhere. The model declares one
filter name here, instance-id, which Ec2Service.matchesFilter already resolves
for an Instance, so both request shapes now run their candidates through
matchesFilters. Named ids still decide the base set and are still validated for
existence, then the filters narrow that set with an AND, which is what the
Filters member documents. An unrecognised filter name matches everything,
following the default arm every other filtered EC2 Describe action in this
service already takes.

DescribeInstanceCreditSpecificationsMaxResults carries a min of 5 and a max of
1000, and any positive integer was accepted, so 1 and 1001 were treated as page
sizes. Out of range now raises InvalidMaxResults with the message
describeNetworkInterfaces already uses for the same range.

Tests: maxResultsHonorsItsModeledRange covers 5, 1000, 4 and 1001,
dryRunReturnsDryRunOperation and anInvalidMaxResultsIsReportedAheadOfDryRun
cover the probe and its ordering, and four filter tests cover the unfiltered
form, named ids, an unknown named id under a filter and an unrecognised filter
name.
2026-09-13 00:26:47 -04:00
lex00andlex00 5d0b0b44b1 fix(ec2): store and validate CreateVpcEndpoint SubnetConfiguration (#3491)
* fix(ec2): store and validate CreateVpcEndpoint SubnetConfiguration

CreateVpcEndpoint accepted SubnetConfiguration.N and dropped it, so an
interface endpoint took floci's own synthesized address in each subnet rather
than the one the caller pinned. Terraform's aws_vpc_endpoint sends the
subnet_configuration block on create and reads it back by following the
endpoint to its network interfaces, so every plan after the apply saw an
address it never asked for and proposed replacing the endpoint.

SubnetConfiguration is request-only in ec2/2016-11-15. No output shape carries
it, so the addresses are stored on the endpoint and consumed when its
interfaces are built, and DescribeVpcEndpoints echoes nothing new.

Ec2QueryHandler parses the flattened SubnetConfiguration.N list for
CreateVpcEndpoint and for ModifyVpcEndpoint, which takes the same parameter.
Ec2Service validates each entry against the named subnet, rejecting an IPv4
address outside its CIDR with InvalidParameterValue, and keeps the pinned
address on the endpoint's interface in that subnet. A subnet named only
through its configuration joins the endpoint's subnet set. Ipv6 is stored as
given, since floci's subnets carry no IPv6 CIDR to validate against and its
network interfaces have no IPv6 field yet.

Adds Ec2VpcEndpointSubnetConfigurationIntegrationTest over the query wire and
three Ec2ServiceTest cases for the create, modify and rejection paths.

* fix(ec2): reject the subnet-reserved addresses in SubnetConfiguration

validateSubnetConfigurations only checked that SubnetConfiguration.Ipv4 parsed
and fell inside the named subnet's CIDR. For a 10.61.1.0/24 subnet that let
10.61.1.0, .1, .2, .3 and .255 through, and each became the private address of
the endpoint's network interface. AWS keeps those five for itself, so none of
them can be assigned to a resource and no real endpoint could ever report one.

The rule is in ec2/2016-11-15 itself, in the CreateSubnet documentation:
"Amazon Web Services reserves both the first four and the last IPv4 address in
each subnet's CIDR block. They're not available for your use." CreateSecondarySubnet
says the same for secondary subnets. No constraint key carries it, and no shape
in the model states it for SubnetConfiguration.

Ipv4Cidrs.isSubnetReserved is new; the EC2 service had no reserved-address helper
to reuse. VpcNetworkManager.firstHostOffset looks close but is not the same rule:
it reserves ten addresses of Docker-network headroom at the bottom of a block and
nothing at the top, for allocation readability rather than AWS semantics.

Small blocks need no special case. A /28, the smallest subnet AWS accepts, keeps
11 of its 16 addresses and a /29 keeps three. Both ends are clamped so they cannot
cross in a block of four addresses or fewer, where every address is reserved.

The check sits in the shared validator, so CreateVpcEndpoint and ModifyVpcEndpoint
both refuse a reserved address with the InvalidParameterValue the containment check
already raises. Tests cover all five reserved addresses and one ordinary host
address on the create path, the modify path, a /28 subnet, and the query wire.

---------

Co-authored-by: lex00 <artigues.dev@gmail.com>
2026-09-12 22:32:12 -04:00
lex00 fe40e06938 feat(ec2): support snapshot block public access (#3490)
* feat(ec2): support snapshot block public access

Adds EnableSnapshotBlockPublicAccess, DisableSnapshotBlockPublicAccess and
GetSnapshotBlockPublicAccessState over the EC2 Query protocol.

The setting is account-level state scoped to one region, so it lives in a small
Ec2SnapshotBlockPublicAccessService keyed by region, mirroring
Ec2EbsEncryptionService. The account-aware storage backend namespaces the keys by
the calling credential's account. A region that was never configured reads back
unblocked.

Enable accepts only block-all-sharing and block-new-sharing, per the EC2 model,
and rejects unblocked with InvalidParameterValue. Disable returns the resulting
unblocked rather than the prior state. Only the Get response carries managedBy,
always account, since Floci has no declarative-policy layer.

* fix(ec2): honor DryRun on snapshot block public access

EnableSnapshotBlockPublicAccess, DisableSnapshotBlockPublicAccess and
GetSnapshotBlockPublicAccessState all model the standard DryRun parameter, but
none of the three handlers checked it. Enable persisted the requested state,
Disable persisted unblocked and Get answered 200, so DryRun=true had real side
effects on both write paths.

All three handlers now take the parameter map and call the existing
checkDryRun(params). Enable validates State first, through a new
validateEnableState on the service, because AWS reports an invalid parameter
ahead of DryRunOperation and only returns DryRunOperation once the request
would otherwise have succeeded. So State=unblocked with DryRun=true still
fails with InvalidParameterValue, and a missing State still fails with
MissingParameter.
2026-09-12 20:21:34 -04:00
Allen Sanborn cf1aabce39 feat(ec2): back each VPC with a real Docker network in RFC 1918 space (#3272)
* feat(ec2): back each VPC with a real Docker network in RFC 1918 space

An instance's private IP was a plausible-looking number nothing could
connect to. Every VPC now gets its own Docker network, created lazily on
the first launch into it, with the VPC CIDR as the network's IPAM pool
and each subnet allocating static addresses from its own slice. The
address Floci reports is one the container actually holds, and instances
in different VPCs sit on different bridges.

One network per VPC, not per subnet: subnets inside a VPC route to each
other in AWS, so a network per subnet would manufacture a partition AWS
does not have and break the two-tier app/database topologies this corpus
is full of.

The declared CIDR is used verbatim wherever it can be. It cannot be when
it is absent, malformed, outside RFC 1918, or already claimed on the
Docker daemon, which includes another Floci VPC: two VPCs may legally
declare the same CIDR in AWS but one daemon cannot route two identical
ranges. Only then is an equivalent block drawn from the configured
fallback pool, and the substitution is logged at WARN. A reported private
IP that does not mean what the caller declared is either true or it is in
the log.

Leases are given back on every exit: a launch that never attaches, a
launch that fails, and terminate. Detach precedes release, because Docker
holds the address while the endpoint stands and would refuse the next
launch handed the same one. Startup reconciles this emulator's own
orphaned networks first (scoped by API port, so instances sharing a
daemon never touch each other's), then re-declares the plan from
persisted VPCs and subnets and re-reserves the addresses restored
instances still hold.

Between-VPC isolation is the Docker daemon's, not Floci's, and OrbStack
does not enforce it. On such a host the VPC boundary is an addressing
boundary only. docs/services/ec2.md says so.

Off with FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED=false, and off whenever
ec2 mock is on.

* fix(ec2): do not adopt a leftover VPC network that routes another range

materialise() treated any network under the VPC's own name as its own: a
successful inspect set created=true and returned. A network left by a
previous run that declared a different CIDR was therefore adopted, after
which addresses were handed out of vpc.effective while the bridge routed
something else entirely.

Compare the leftover's IPAM subnet to vpc.effective. A match is adopted as
before. A mismatch is removed and recreated on the planned range rather
than re-planned onto the leftover's subnet: by the time materialise runs,
addresses have already been allocated from vpc.effective, and after a
restart some are leases held by live containers, so the plan cannot move
under them. The network name carries this emulator's own port and region,
so recreating it cannot destroy a user's network. If the removal fails the
instance stays on the shared bridge, which is a documented degradation,
instead of holding an address nothing routes.

Also make small blocks work or refuse out loud. FIRST_HOST_OFFSET was a
flat 10, so a /29 (eight addresses) and a /30 (four) allocated nothing at
all and said nothing about it, and fallback-prefix-length had no upper
bound to stop a /30 being configured. The offset now scales down to 2 for
blocks that cannot spare ten addresses, a block with no room for a host is
refused at plan time with a WARN, and the fallback prefix is clamped into
the range that can serve hosts.

* fix(ec2): keep the IMDS source address current across start and restore

Ec2MetadataServer resolves an instance from the source address of the
request, and a container's default route is the bridge, so a VPC-attached
instance's metadata requests arrive from its bridge address rather than
from the VPC address Floci reports. launch() registered both. start() and
restoreMetadataRegistration() registered only the address
getContainerBridgeIp returns, which for a VPC-attached container is the
VPC address: neither refreshed imdsSourceIp nor registered the bridge.

Docker hands out a fresh bridge address when a stopped container starts
again, and an emulator restart rebuilds the registration map empty, so
after either the instance's IMDS requests arrived from an address nothing
knew about, while the address from the previous run stayed registered.

Both paths now unregister the stale source address and register the
current one. A bridge-only instance is unaffected: its reported address
and its bridge address are the same, so there is no second registration.

* fix(ec2): keep the IMDS source registration when inspect fails

bridgeNetworkIp swallowed every inspect failure and returned null, the same
answer it gives for a container that genuinely has no bridge address.
refreshImdsSourceRegistration acts on that null by unregistering the instance's
recorded IMDS source address, so one transient Docker hiccup permanently dropped
a healthy instance's registration and put nothing in its place: its metadata
requests stopped resolving until some later start or restore happened to
succeed.

Split the two answers apart. bridgeNetworkIp now lets the exception propagate,
so null means only "no bridge address"; refreshImdsSourceRegistration catches it
and returns early, leaving the existing registration exactly as it was.

* docs(ec2): drop the em dashes this branch added

AGENTS.md forbids em dashes in all content. The enforcing check runs with
--diff-filter=A, so it only scans files a PR adds and stayed green on these, but a
check that cannot see a violation is not a licence for it. Six of them are in lines
this branch adds: four in docs/services/ec2.md, one in an Ec2ContainerManager javadoc,
one in an Instance javadoc.

Replaced with colons and commas. Wording is otherwise unchanged, and the em dashes
already present in these files are left alone: they predate this branch, and
rewriting them here would bury the actual change in unrelated churn.
2026-09-09 18:12:40 -05:00
Matheus André f77cf4da77 fix(ec2,ssm): explain missing IMDS registration for SSM-only managed instances (#3283) 2026-09-09 00:26:30 -05:00
Sam Fakhreddine f30ba77ac0 fix(ec2): answer DescribeTransitGatewayConnects with an empty list (#3274)
* fix(ec2): answer DescribeTransitGatewayConnects with an empty list

LZA's tgw-associations-and-propagations module calls this unconditionally
alongside DescribeTransitGatewayVpcAttachments. floci does not yet support
creating Connect attachments, so the action was entirely unhandled and the
module failed with "Operation DescribeTransitGatewayConnects is not
supported", found while running LZA phase2 against parent 1176.

Since floci has no Connect attachments to return, an empty list is the
wire-faithful answer for every account. Requested attachment ids still
validate against the shared tgw-attach- id namespace: malformed ids reuse
the existing InvalidTransitGatewayAttachmentID.Malformed check, well-formed
but unknown ids get InvalidTransitGatewayConnectID.NotFound.

* test(ec2): cover DescribeTransitGatewayConnects over the Query protocol and make the service hook void

The service method only validates the request; the handler always renders
an empty transitGatewayConnectSet, so returning a List of VPC attachments
suggested a resource type it never produces. It is void now. Two
integration tests drive the action through the EC2 Query dispatch and pin
the response wire shape (EC2 namespace, requestId, empty
transitGatewayConnectSet) and the Malformed / Connect NotFound error codes.
2026-09-09 00:20:28 -05:00
lex00 5eacd01636 fix(ec2): store instance metadata options and add ModifyInstanceMetadataOptions (#3215)
RunInstances stores the MetadataOptions it is given, with AWS's launch
defaults for anything left out, and DescribeInstances reads the stored
values back instead of a hardcoded block. A launch template's metadata
options seed the launch and explicit request fields override them.
ModifyInstanceMetadataOptions changes only the fields it names and
returns the instanceMetadataOptions shape. Values outside the AWS
enumerations and a hop limit outside 1 to 64 are InvalidParameterValue.

Ported from lex00/floci#116, whose SSM half is floci-io/floci#3173.
2026-09-07 21:50:06 -05:00
Allen Sanborn 94b9665c32 fix(ec2): reclaim instance containers orphaned by a hard restart (#3031)
* fix(ec2): reclaim instance containers orphaned by a hard restart

TerminateInstances flips the record to shutting-down synchronously and removes
the container on the async executor; launch persists the container id only once
Docker has created it. A process killed across either edge -- SIGKILL, OOM,
`docker kill` -- leaves a container on the daemon that no surviving record refers
to, so nothing on the next run ever collects it.

Neither existing path reaches these. `Ec2Service.stopManagedContainers` only runs
on the graceful ShutdownEvent, and the startup restore loop's
`needsMetadataRegistration` deliberately skips records in terminated or
shutting-down. Once `pruneTerminatedInstances` drops the record an hour later,
the container is unreferenced for good.

Sweep them on startup, right after the restore loop so anything legitimately
revived is already accounted for. Containers are matched on the existing
`io.floci.service=ec2` identity label and removed only when no live record claims
them. Stopped instances are explicitly not orphans -- their containers are what
StartInstances revives -- so a record in any non-terminal state keeps its
container.

The sweep is scoped by a new `floci_owner_port` label to this Floci's own API
port. Several emulators can share one Docker daemon, and an unscoped sweep would
reap a sibling's live instances; `floci_namespace` is the documented mechanism
for that but is absent unless a resource namespace is configured, so it cannot
scope the default configuration. Containers created before this label existed
carry no owner and are never swept.

Off with FLOCI_SERVICES_EC2_RECONCILE_CONTAINERS_ON_STARTUP=false.

Upstream's #2029 (createAndStartContainer/failLaunch/isLaunchCancelled)
independently landed the launch-cleanup half of the original floci-5ie fix, so
this rewrite carries only the reconciler, which upstream still lacks.

* fix(ec2): scope the orphan sweep by account and deployment, not port alone

Review on #3031 found two ways the startup sweep could delete a container that is
still in use, plus a missing config entry. All three are addressed here.

Account identity was dropped on the record lookup. reconcileOrphanedContainers runs
from @PostConstruct, outside any request, where an AccountAwareStorageBackend resolves
to the default account. A container belonging to a non-default account looked up as
absent, so the sweep classified it an orphan and removed it, leaving a live persisted
instance with no Docker runtime. findAnyInstance() now consults every account, using
the same instanceof-and-fall-back shape findAnyVpcEntry() already uses in this class.
The lookup is read-only, so a cross-account hit stays in its owner's partition.

Ownership keyed on the API port alone collided. Two independently namespaced Floci
processes sharing a Docker daemon on the same internal port stamped the same
floci_owner_port label, so starting either one reaped the other's live containers.
ownerIdentity() composes docker.resource-namespace -- the documented mechanism for
exactly this arrangement -- in front of the port. An unnamespaced single Floci keeps
the bare port it already stamped, so nothing changes for the common case.

Adds reconcile-containers-on-startup to the main application.yml, which AGENTS.md
requires for any new configuration and which the original commit omitted.

The new test fails with the old port-only ownership and passes with the fix.

* fix(ec2): put reconcile-containers-on-startup under services, not storage

The previous commit added the key to floci.storage.services.ec2. Ec2ServiceConfig
maps to floci.services.ec2, as its own env var name says
(FLOCI_SERVICES_EC2_RECONCILE_CONTAINERS_ON_STARTUP), and application.yml has an
ec2 block under each root. SmallRye rejects a key that maps to no root rather than
ignoring it, so this was not a quietly inert setting: every @QuarkusTest failed to
boot with SRCFG00050, and the native images built but could not start, which is why
the compat and sdk-test jobs timed out at exit 124.

Verified by running a @QuarkusTest rather than only compiling: Ec2ImageCatalogTest
now boots and passes, and no SRCFG00050 remains.
2026-09-06 14:28:12 -05:00
luiseterc 1f87f7c482 feat(ec2): implement instant CreateFleet (#2956)
* feat(ec2): implement instant CreateFleet

* fix(ec2): address CreateFleet review feedback

* fix(ec2): harden CreateFleet placement rollback

* test(ec2): isolate CreateFleet dry-run fixture

* fix(ec2): group CreateFleet response instances

* fix(ec2): report incomplete fleet rollback

* fix(ec2): resolve fleet placement from subnet overrides
2026-09-04 10:06:44 -04:00
lex00 0c33ef234b feat(ec2): Capacity Reservation CRUD (#2974)
* feat(ec2): Capacity Reservation CRUD

CreateCapacityReservation, DescribeCapacityReservations,
ModifyCapacityReservation and CancelCapacityReservation were
unimplemented, so any aws_ec2_capacity_reservation resource failed with
UnsupportedOperation. Wire shapes follow botocore's ec2/2016-11-15
service model: synchronous creation (active on the create response),
TagSpecification support on create, the documented Describe filters,
and cancel marks the record cancelled with zero available capacity
rather than deleting it, matching AWS's retain-but-cancel behaviour.

* fix(ec2): match the AWS required fields and filters for Capacity Reservations

InstancePlatform and InstanceCount are required and AvailabilityZone is optional, with AvailabilityZoneId accepted. A non-positive InstanceCount is rejected on create and modify. The describe filters drop capacity-reservation-id and add instance-match-criteria and end-date-type.
2026-09-04 09:40:15 -04:00
Allen Sanborn 906af8c632 feat(ec2): support standalone network interface create/attach/detach (#2843)
* feat(ec2): support standalone network interface create/attach/detach

CreateNetworkInterface returned UnsupportedOperation unconditionally,
blocking every root that attaches a standalone ENI: the attach-eni and
override-default-eni examples in terraform-aws-server, the with-elb
example in terraform-aws-asg, and vpc-blackhole-routes in
terraform-aws-service-catalog (floci-kt9 in the floci-harness compat
survey).

Adds CreateNetworkInterface, DeleteNetworkInterface,
AttachNetworkInterface and DetachNetworkInterface, backed by a new
standalone ENI store separate from the implicit primary interface each
instance already carries. DescribeNetworkInterfaces now merges both
without double-counting. RunInstances also accepts a pre-existing
standalone ENI as an instance's primary interface via
NetworkInterface.1.NetworkInterfaceId, the shape Terraform's
network_interface { network_interface_id = ... } block sends for
override-default-eni.

* fix(ec2): keep a standalone ENI's own record when it is attached

Review found two ways the attachment state ended up recorded on only one side.

AttachNetworkInterface updated the standalone ENI and stopped there, so
DescribeNetworkInterfaces reported an attachment that DescribeInstances denied —
and the device-index conflict check, which reads the instance's own interface
list, could never see anything this operation had attached: two interfaces could
take device index 1 on the same instance. The instance now carries the interface
too, and DetachNetworkInterface removes it again.

RunInstances took the opposite approach and deleted the standalone record,
leaving the interface represented only inside the instance. Terminating that
instance then made a caller-created ENI vanish -- InvalidNetworkInterfaceID.
NotFound rather than returning to "available" -- so it could not be reused. AWS
attaches a pre-existing interface with deleteOnTermination false precisely so it
outlives the instance. The standalone record is now kept and marked attached,
and terminate releases it; describeNetworkInterfaces skips the instance-side
copy of any id the standalone store owns, so it is still reported exactly once,
from the side that knows its real attach time and its deleteOnTermination.

Also braces a single-line conditional, per AGENTS.md.

* fix(ec2): release an ENI whose instance died without TerminateInstances

TerminateInstances is not the only way an instance reaches "terminated": a
container-backed launch that fails or is cancelled ends there asynchronously,
inside Ec2ContainerManager, which has no access to the interface store. An ENI
the launch had already marked in-use therefore stayed pinned to an instance that
no longer runs, and every later attempt to reuse it failed with
InvalidNetworkInterface.InUse.

Rather than chase each terminal transition, the attachment is reconciled when
the interface is next read: an attachment naming an instance that is gone or
terminated is cleared, and the interface reports "available" again. That covers
attach, launch, delete and describe through the one path they share.

* fix(ec2): let a dead instance release its copy of a reclaimed ENI

Releasing the standalone record alone left the terminated instance still
reporting the interface, so once the ENI was reused two instance records claimed
it and nothing in DescribeInstances picks a winner. Reclaiming now clears both
sides, and the unit test asserts the instance no longer lists it.

Also drops the em-dashes from the comments and docs this branch adds, per
AGENTS.md.

* fix(ec2): drop the instance's copy on the TerminateInstances path too

The previous commit fixed only the reclaim-on-read path. TerminateInstances
released the standalone record while leaving the mirrored interface on the
terminated instance, so reusing the ENI still produced two instance records
claiming it. Both paths now clear the instance's copy, and the integration test
asserts DescribeInstances no longer mentions the interface before the same ENI
is handed to a second launch.
2026-09-01 18:21:57 -04:00
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