mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 14:30:28 -05:00
0f4f59bbbbbc706644de2ccf7aea033a9c7dcfaf
86
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
456ae15684 |
fix(ec2): apply the AWS public address rules and displace earlier Elastic IPs (#5963)
* fix(ec2): assign mock public addresses and displace earlier Elastic IPs In mock mode an instance never received a public IPv4 address, whatever its subnet's MapPublicIpOnLaunch or its launch's AssociatePublicIpAddress said, and an associated Elastic IP never reached DescribeInstances. - A mock instance that asks for a public address gets one when it reaches running, whether DescribeInstances, DescribeInstanceStatus or StartInstances completes the launch. Stop and termination release it. An associated Elastic IP replaces it and survives a stop; disassociating it gives a running instance a new automatic address when its launch asked for one. - AssociateAddress disassociates the Elastic IP an instance already has, including one a retained interface carried onto it, as the AssociateAddress reference describes. - Launches from a template take AssociatePublicIpAddress from its device-index-0 interface (RunInstances, CreateFleet, Auto Scaling), and RunInstances and CreateFleet also take that interface's subnet. - RunInstances refuses an instance-level SubnetId combined with network interfaces, on the request or in its launch template, with InvalidParameterCombination. Split out of #5671 at review. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): scope Elastic IP displacement and automatic addresses as AWS does - AssociateAddress ignored PrivateIpAddress, so an Elastic IP meant for a secondary private address displaced the one on the primary. The address is now recorded on the private address it names, only an address already on that private address is displaced, the interface shows it there, and in mock mode only the primary's address becomes the instance's public address. - An instance launched on an existing network interface got an automatic public address; AWS assigns one only to an interface the launch creates. - A released automatic address was replaced while a second interface was attached; AWS does not replace it then. - An Elastic IP that a retained interface carried to a new instance stayed without an instance. It now names that instance, which shows the address and keeps it across a stop. - A mock launch could complete over a concurrent stop or termination, and DescribeAddresses could write back an address disassociated meanwhile; both now re-check under the instance's lock. The tests also cover a request's own network interfaces with an instance-level SubnetId, and the template interface docs now say which launches take the subnet. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): settle second-review findings on mock public addresses - DescribeAddresses re-points associated addresses under the allocation lock, and a mock launch, start or stop reads the instance's Elastic IP under it, so none of them acts on an association written halfway or changed meanwhile. - An Elastic IP that a retained interface carries is found through that interface, also when it is disassociated, instead of being rebound to the next instance at launch, which left a dead InstanceId behind when a container launch failed. - StartInstances leaves a running mock instance alone. - In container mode too, an address on a secondary private address no longer becomes the instance's public address. - The second-interface test associates its address before attaching the interface, since AssociateAddress by InstanceId needs exactly one. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): keep terminated mock instances down and address reads unblocked - StopInstances leaves a terminated or shutting-down mock instance as it is, re-checked under the lock, so terminate, stop and start no longer revives it with a public address. - DescribeAddresses waits for the allocation lock only when an address is associated with an instance, and the container re-point no longer rewrites an unchanged instance. - A mock start treats a state without a name as settled instead of throwing. Tests now cover the terminated instance and, with a reachable container address, an Elastic IP on a secondary private address leaving the instance's public address alone. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): settle Qodo findings on mock public addresses - AssociateAddress refuses a PrivateIpAddress that is neither the instance's primary private address nor a secondary address of its primary interface, with InvalidParameterValue and before any association changes, instead of treating it as the primary and displacing the Elastic IP already there. - RunInstances from a launch template whose device-index-0 interface names an existing NetworkInterfaceId launches on that interface, in its subnet and without an automatic public address, as a request naming it would, instead of on a new interface in the default subnet. - The SubnetId-with-interfaces refusal test now launches against a real subnet and checks that the refused request leaves no instance or interface behind. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): accept a container instance's launch address in AssociateAddress In container mode without AWS-faithful private addresses, the container manager replaces the instance's reported private address with its Docker bridge address once the container runs, and nothing keeps the subnet address RunInstances returned. The new PrivateIpAddress check therefore refused that address with InvalidParameterValue, though callers may still name it. Only mock mode and the AWS-faithful mode, which keep the launch address, now refuse a stray PrivateIpAddress; elsewhere any value means the primary address, as before. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): decide automatic public addresses the same way with containers The public IPv4 rules were applied to mock instances only. A container-backed instance kept its address after a stop and a termination, got one on an existing network interface, kept its reachable address after its Elastic IP was disassociated even when the launch never asked for one, and had a released address replaced while a second interface was attached. One rule, AutomaticPublicAddress, now decides whether an instance has an automatic address in both modes: the launch asked for one on an interface the launch created (recorded when the instance is built), a stop, a termination or a disassociated Elastic IP releases it, and a replacement is held back while a second interface is attached. An Elastic IP on the primary private address still takes precedence. Only the value differs by mode: the container's reachable address, or an invented one where there is no container. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): settle review findings on the shared public address rule - DisassociateAddress decides by the association, not by comparing addresses: only an Elastic IP on the instance's primary private address gives way to another one left there, or to an automatic address when one is due. With a container, every Elastic IP points at the one reachable address, so disassociating a secondary one no longer clears the instance's public address, and one a restart moved no longer survives its disassociation. - StartInstances on a stopped container instance releases an automatic address that a stop outside StopInstances, such as Floci's shutdown, left in place, so the start decides afresh. - With a container, these writes no longer wait on the instance's lock while holding the allocation lock, since the port-forward manager holds that lock across Docker calls. - A start test case now keeps an address distinct from the one it expects, and two comments describe the flag as it now is. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): release only the primary interface's Elastic IP on disassociation - DisassociateAddress treats an Elastic IP as the instance's public one only when it sits on the primary interface, not on a retained interface attached at another device index, so disassociating that one no longer clears the instance's automatic address. - With a container, DescribeAddresses no longer writes a re-pointed address back onto a terminated or shutting-down instance. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): show a carried Elastic IP on a container instance's launch - An instance launched on a retained interface that still carries an Elastic IP records that address at RunInstances, and the container launch re-points it once the container runs. With containers, such an instance had no public address until a stop and start, since the shared rule gives an existing interface no automatic address. - With a container, TerminateInstances clears the public address under the allocation lock, so a DescribeAddresses re-point already under way cannot write it back onto the terminated instance. - The secondary-interface disassociation test checks the address was still associated before the call and is not after it. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): re-point a carried Elastic IP at its new instance - DescribeAddresses re-points an Elastic IP that a retained interface carries at the instance that interface is now the primary interface of. With containers, the address otherwise kept the previous container's address for good, since termination clears its instance id. - With a container, StopInstances leaves a terminated or shutting-down instance alone, as mock mode does, instead of stopping it into a startable state and writing its Elastic IP back. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): give mock instances no invented public address by default Mock instances due an automatic public IPv4 address got a random 54.x.x.x one, a real AWS range, so a tool that connected to it reached someone else's host. The new floci.services.ec2.mock-public-addresses setting (FLOCI_SERVICES_EC2_MOCK_PUBLIC_ADDRESSES) chooses the address: none (the default) gives none, documentation draws distinct addresses from 203.0.113.0/24 as Lightsail and EMR do, and fixed gives every instance mock-public-address (default 127.0.0.1), an address the caller can reach. Only the value changes. The launch still records whether it asked for an address, so the shared rule and Elastic IP precedence work as before, and instances with containers keep reporting their reachable address. Elastic IP allocation still draws from 54.x.x.x, as on main. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): settle review findings on the mock public address setting A configured mock-public-address with surrounding spaces was reported as is; it is now stripped. The docs and the AutomaticPublicAddress Javadoc no longer describe every mock instance as getting an address, and the test configurations that launch mock instances name the setting instead of leaving it null. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): allocate Elastic IPs from the documentation range AllocateAddress handed out random 54.x.x.x addresses, a real AWS range, and this branch shows an associated Elastic IP as a mock instance's public address, so even with mock-public-addresses at none a client could reach someone else's host through one. Elastic IPs now come from 203.0.113.0/24 in every mode, distinct from the account's other Elastic IPs and its instances' public addresses; once all 254 are taken AllocateAddress fails with AddressLimitExceeded rather than repeat one, since callers name an Elastic IP by its address. Under mock-public-addresses: fixed, an Elastic IP on a mock instance's primary private address is re-pointed at the configured address, as one on a container instance is at the container's reachable address, and disassociation restores the allocated address. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): settle review findings on documentation-range Elastic IPs An Elastic IP re-pointed at the fixed address kept it after a restart under another setting; the next read now shows its allocated address again. The re-point Javadoc and the Elastic IP docs no longer claim a 54.x.x.x allocation or addresses that never repeat, the docs say that earlier allocations keep their address until released, and a test now proves an allocation skips the addresses instances hold. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> |
||
|
|
1eb402d623 |
fix(ec2): keep tags in the region of the resource they label (#5973)
* fix(ec2): keep tags in the region of the resource they label DescribeTags listed every region's tags because the tag store was keyed by the bare resource id. Tags are now stored per region, so DescribeTags, DeleteTags, CreateTags and the aws:ResourceTag IAM condition only see the request region's tags. Each side of a cross-region transit gateway or VPC peering connection keeps its own tags in its own region. Tags stored by bare id are moved under their resource's region at startup, for every account; a tag whose resource no region holds is dropped. DescribeTags now reports image, volume, snapshot, network-acl, vpc-peering-connection and spot-instances-request instead of "unknown". Tags given when a volume or peering connection is created reach the store, and DescribeVolumes, DescribeSnapshots and DescribeSpotInstanceRequests show later CreateTags and DeleteTags changes. Signed-off-by: Hector Ventura <hectorvent@gmail.com> * fix(ec2): remove tags with their resource and keep node and catalog AMI tags on upgrade Deleting a volume (directly or as a delete-on-termination volume of a terminated instance), a snapshot with its image or a VPC peering connection, and pruning a terminated instance, now removes the resource's tags, both peering sides included. The startup migration no longer drops tags it cannot place in a store: a catalog AMI's tags move to the default region, and an instance's are kept until its EKS node is found in a region, which then claims them. Signed-off-by: Hector Ventura <hectorvent@gmail.com> * fix(ec2): file a cluster node's legacy tags under its own region A region-less findInstanceById reaches the EKS provider, which answers from any region, so the claim moved the node's legacy tags under a null region where DescribeTags never finds them. The claim now uses the instance's own region, and with no region known it reads the legacy tags in place for a regional lookup to claim. Signed-off-by: Hector Ventura <hectorvent@gmail.com> * fix(ec2): pass the region in the query GET resource-tag stub Signed-off-by: Hector Ventura <hectorvent@gmail.com> --------- Signed-off-by: Hector Ventura <hectorvent@gmail.com> |
||
|
|
5a4413d63a |
fix(ec2): detach Floci before deleting VPC networks (#5869)
* fix(ec2): detach Floci before deleting VPC networks * refactor(ec2): share VPC endpoint disconnection |
||
|
|
5fc58a9a9c |
fix(ec2): preserve elastic IP pool and border group (#5821)
* fix(ec2): preserve elastic IP pool and border group * test(ec2): share account-scoped query requests |
||
|
|
0be4581d4e |
fix(ec2): preserve IAM instance profile identity (#5671)
* fix(ec2): preserve IAM instance profile identity Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): probe metadata readiness with IMDSv2 Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(autoscaling): preserve launch profiles and metadata options Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): preserve automatic public addresses across launch paths Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): honor metadata token requirements and profile identity Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): keep synthesized node identity and mock addresses consistent - IMDS iam/info serves the instance profile identity EKS synthesizes for its cluster nodes while IAM holds no such profile. The node carries a stable IAM-shaped profile id, which DescribeInstances now copies too. - Mock instances get their automatic public address however the launch completes, DescribeInstanceStatus included. An associated Elastic IP replaces it, disassociating gives a running instance a new one, and termination leaves none. - CreateFleet forwards the launch template's metadata options and its primary interface AssociatePublicIpAddress. - Launch templates store a profile name and ARN pair as given and the launch from them rejects it, since AWS does not fully validate template parameters at creation. - CloudFormation launch-configuration MetadataOptions resolve Fn::If and AWS::NoValue. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): refuse profile pairs for groups and keep Elastic IPs exclusive - Auto Scaling refuses a group whose launch template, directly or through its mixed instances policy, names both an instance profile name and an ARN, with ValidationError, instead of accepting a group that can never launch. - AssociateAddress disassociates the Elastic IP an instance already has, as AWS documents. In mock mode a terminated instance takes no address, and an unchanged address is not written again. - IMDS iam/info falls back to a cluster node's synthesized identity only while IAM holds no profile at that ARN; a held profile without a role answers 404. - CreateFleet takes the subnet of the device-index-0 interface first, as RunInstances does. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): assert profile ids and launch configuration metadata via the SDK Ec2InstanceProfilePathTest now checks that direct, template, override and fleet launches report IAM's InstanceProfileId, and AutoScalingTest round-trips launch configuration MetadataOptions through the AWS SDK for Java v2, including the absent structure and a rejected hop limit. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): displace an Elastic IP a retained interface carries - AssociateAddress also disassociates an Elastic IP held by the instance's primary interface, which a retained network interface carries from an earlier instance, so one instance never holds two. - Mock stop and terminate change the instance's state and public address under its lock, like the launch and Elastic IP writes. - Docs and comments say where the profile pair fails and when CreateFleet falls back to another interface's subnet. - Tests cover the retained-interface address, the group update path, the full refusal message and the fleet's availability zone, and the SDK launch configuration test cleans up on failure. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(ec2): refuse reserved RunInstances tags before resolving the profile Resolving the instance profile called the EC2 service before tag parsing, so a reserved aws: tag was refused only after that lookup. Parse tags first, as the reserved-tag check requires. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(autoscaling): assert the refresh launched the replacement Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(autoscaling): describe what the refresh assertion checks Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(cloudformation): cover invalid launch-configuration metadata options Invalid HttpTokens, invalid HttpEndpoint, hop limits of 0 and 65 and a non-integer hop limit each fail the AWS::AutoScaling::LaunchConfiguration resource with the validation message, roll the stack back and leave no launch configuration behind. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(cloudformation): pin metadata failure reasons and accepted hop limits Assert the exact resource failure reason, and cover hop limits of 1 and 64, a string hop limit and one from a Number parameter. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(ec2): leave IMDS token enforcement to a separate change HttpTokens=required enforcement, the IMDSv2 readiness probe and the helper shell environment reset move to their own pull request, so this change keeps only the instance profile identity. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(ec2): leave mock public addresses to a separate change Mock public IPv4 assignment, primary-interface public IP and subnet handling and Elastic IP displacement move to their own pull request. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(autoscaling): leave launch metadata options to a separate change Launch-configuration MetadataOptions over Query and CloudFormation, and metadata options forwarded from launch templates and EC2 Fleet, move to their own pull request. Launch-configuration profile resolution stays. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): use the shared metadata and authorization fixtures Ec2MetadataProfileIntegrationTest starts its metadata server and requests tokens through Ec2MetadataTestFixture, and it and Ec2InstanceProfileIdentityIntegrationTest build their Authorization header with EnforcementFixtures.auth. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(ec2): close the Auto Scaling profile paragraph's code fence Removes a stray fence that rendered the launch-configuration profile paragraph as code, and a doubled blank line before the iam/info paragraph. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(ec2): find profile identity launches by a run tag Each launch carries a tag unique to the test run, and the tests look their instances up by that tag rather than by client token. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(ec2): leave the client-token filter to a separate change The instance filter is not part of the profile identity, and this copy let a wildcard match instances launched without a token. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> |
||
|
|
708dc32fa1 |
feat(ec2): support egress-only internet gateways (#5822)
* feat(ec2): support egress-only internet gateways CreateEgressOnlyInternetGateway fell through to UnsupportedOperation, so aws_egress_only_internet_gateway could not be created, and DescribeEgressOnlyInternetGateways always answered an empty set. Egress-only gateways are now stored (ec2-egress-only-internet-gateways.json, through StorageFactory) and created attached to an existing VPC, with TagSpecification and CreateTags applied. Describe filters by ID, egress-only-internet-gateway-id, attachment.vpc-id, attachment.state and tags; Delete returns returnCode. DeleteVpc reports DependencyViolation while one is attached. The three actions are added to EC2 query routing, which removes DescribeEgressOnlyInternetGateways from the known gaps. * fix(ec2): settle Qodo findings on egress-only internet gateways - CreateEgressOnlyInternetGateway validates TagSpecification tags before it creates anything, so an aws: key no longer leaves an attached gateway behind. Tags are applied with the gateway, under the topology lock. - A ClientToken replay compares the creation tags as well as VpcId: changed tags fail with IdempotentParameterMismatch, and a matching replay returns the gateway unchanged instead of re-tagging it. - DescribeEgressOnlyInternetGateways honours MaxResults (5 to 255 in the EC2 model) and NextToken, ordered by ID, using the service's existing token codec. - DeleteEgressOnlyInternetGateway takes the resource lock createSystemTags takes, and leaves routes that targeted the gateway in place as blackhole, the state AWS documents for a route whose target is gone. * fix(ec2): DeleteEgressOnlyInternetGateway without an id is MissingParameter The EC2 model marks EgressOnlyInternetGatewayId required. A request without it answered InvalidGatewayID.NotFound for 'null'; it now gets the same MissingParameter the other EC2 handlers return. An unknown id still fails with InvalidGatewayID.NotFound. |
||
|
|
5544a119d3 |
fix(ec2): ignore NoDevice block device mappings at launch (#5739)
A RunInstances or CreateFleet BlockDeviceMapping with NoDevice set removes its device regardless of the other values it carries. The root volume type resolution and the VolumeType validation read Ebs on such entries, so a request that removed a template's gp3 root still got gp3, and a removed mapping naming an unknown VolumeType failed with InvalidParameterValue. Drop NoDevice entries before both, on the request-only and template-merged paths alike. |
||
|
|
1e423420ed |
fix(ec2): resolve a NAT gateway's network interface and mark its Elastic IP associated (#5622)
* fix(ec2): resolve a NAT gateway's network interface and mark its Elastic IP associated CreateNatGateway gave each gateway address a networkInterfaceId of "eni-" + randomHex(17), but nothing else knew about that interface: DescribeNetworkInterfaces had no NAT arm, so the id DescribeNatGateways publishes (aws_nat_gateway.network_interface_id) answered InvalidNetworkInterfaceID.NotFound. The Elastic IP the gateway took was also never marked associated, so DescribeAddresses showed a held allocation as free. The interface id is now derived from the gateway id, as endpoint ENIs are, and DescribeNetworkInterfaces reports one requester-managed nat_gateway interface per gateway address, built from the stored address so the two reads cannot disagree. CreateNatGateway records the association, interface and private address on the allocation (no instanceId), and DeleteNatGateway clears them if the association is still the gateway's. * fix(ec2): refuse a NAT gateway on an occupied Elastic IP, keep its association, scope its ENI lookup to the account CreateNatGateway rejects an allocation already held by an instance or another gateway (Resource.AlreadyAssociated) under the lock that writes the association. DisassociateAddress rejects an association owned by a NAT gateway. The NAT arm of DescribeNetworkInterfaces reads gateways and subnets for the account asked about. * fix(ec2): lock NAT gateway EIP release, treat a legacy gateway's EIP as held DeleteNatGateway releases the Elastic IP under the lock CreateNatGateway takes. CreateNatGateway also refuses an allocation any live gateway references, covering gateways persisted before Address records were marked. The CloudFormation networking test gives the replacement NAT gateway a new EIP: replacement creates before it deletes, and AWS's CreateNatGateway refuses an EIP still associated elsewhere. * fix(ec2): AssociateAddress refuses a NAT gateway's Elastic IP; legacy gateways hold theirs AssociateAddress checks for a gateway holding the allocation and writes under the allocation lock CreateNatGateway and DeleteNatGateway take, so an instance cannot take over an address the gateway still claims. The gateway scan behind that check, and CreateNatGateway's, now includes unmigrated pre-account-isolation gateway records for the default account, never another account's. * fix(ec2): scope NAT gateway ownership checks to the caller's records callerNatGateways scanned every account's gateways before filtering. Read the caller's own records, plus unprefixed legacy records only for the default account. * fix(ec2): create a NAT gateway failed on an Elastic IP already in use CreateNatGateway with an allocation another gateway or an instance holds no longer answers 400. As the NatGateway shape documents, the gateway is created in state failed with FailureCode Resource.AlreadyAssociated and FailureMessage "Elastic IP address <alloc> is already associated". It gets no interface, claims nothing, and does not count as a holder. AWS::EC2::NatGateway fails the resource and deletes the failed gateway. ReleaseAddress on an allocation a NAT gateway holds, legacy gateways included, answers InvalidIPAddress.InUse. DisassociateAddress and ReleaseAddress run under privateIpAllocationLock. The NAT interface lookup reads legacy unprefixed gateways and subnets for the default account. It also loads the interface's tags, and DeleteNatGateway deletes them. endpointEniId and natEniId become one helper, eniIdFromSeed. * test(cloudformation): say why the replacement template keeps NatEip The replacement template keeps NatEip for two reasons. On AWS a gateway given an Elastic IP the displaced gateway still holds is created failed. And Floci update cleanup deletes removed resources before the old copies of replaced ones, so dropping the EIP while replacing its gateway would try to release it while it is still held. * fix(ec2): a failed NAT gateway does not pin its subnet or VPC #5503 made DeleteSubnet and DeleteVpc refuse while a NAT gateway that is not deleted sits in the subnet. A failed gateway was never created and holds no interface, so it no longer counts, matching the Elastic IP holder check. |
||
|
|
fa682b2d62 |
fix(cloudformation): clean up, roll back and delete AWS::EC2::VPC like the other EC2 types (#5503)
* fix(cloudformation): clean up, roll back and delete AWS::EC2::VPC like the other EC2 types A CidrBlock change, or a tenancy change other than dedicated to default, replaces the VPC, but the provisioner never recorded the displaced one and had no delete arm, so the old VPC was left behind; in-place Tags, EnableDnsSupport and EnableDnsHostnames changes were not snapshotted, so a later failing resource left the VPC changed and reported rollback as not implemented. Ec2VpcCfnProvisioner now follows Ec2NetworkCfnProvisioner: ReplacementCleanup records the displaced VPC and deletes it after the update commits or restores it on rollback; a prior-state snapshot restores DNS attributes, tags and a dedicated-to-default tenancy change on rollback, eagerly when provision itself fails; and a delete arm through CfnDeletes.safeDelete removes the VPC on stack teardown, tolerating only InvalidVpcID.NotFound so stack-external dependents fail the delete with DependencyViolation, as on AWS. * refactor(cloudformation): use the shared CfnRollback.guarded in the VPC provisioner * fix(ec2): count instances and NAT gateways as subnet and VPC dependents DeleteSubnet and DeleteVpc checked subnets, security groups, route tables, ACLs, gateways and endpoints but not the instances and NAT gateways living in a subnet, so a stack teardown could remove a subnet and its VPC out from under an instance launched into it out of band. Both now fail with DependencyViolation while an instance that is not terminated (shutting-down still holds its interface) or a NAT gateway that is not deleted sits in the subnet, as on AWS. The rollback integration test also pins Boom after the VPC with DependsOn so the scenario cannot pass by ordering alone. * fix(cloudformation): keep the VPC and subnet rollback snapshot until the restore succeeds rollbackUpdate removed the in-place snapshot before restoring; a restore that threw left the resource persisted as UPDATE_FAILED with no prior state for a ContinueUpdateRollback retry. Ec2VpcCfnProvisioner and the pre-existing Ec2NetworkCfnProvisioner now restore first and remove after, as the AgentCore provisioner already did. The describeTags loop shared by Ec2Tags.reconcile and the VPC snapshot moves to Ec2Tags.current. * fix(ec2): count standalone network interfaces and interface endpoints as subnet dependents A subnet is pinned by any network interface in it, not only the ones an instance or NAT gateway owns: a standalone interface from CreateNetworkInterface and an interface or Gateway Load Balancer endpoint keep DeleteSubnet at DependencyViolation on AWS too. The endpoint test that deleted a subnet out from under a live endpoint relied on that state being reachable; it now asserts the refusal and that the published interface ids are unchanged. * fix(cloudformation): wait for terminated on instance delete and resolve VPC properties before creating With real containers an instance is still shutting-down when the stack's instance delete returns, so the subnet delete that follows was refused by the new resident check and the stack ended DELETE_FAILED. The instance provisioner now polls until the instance is terminated or gone, as CloudFormation does. The VPC provisioner created the VPC before EnableDnsSupport, EnableDnsHostnames and Tags were resolved, so a resolution failure left it untracked; the resolves now run first, as the subnet provisioner does. Ec2Tags.current drops reserved aws: keys so a rollback snapshot never tries to write one, and the replacement integration test waits in the stack's own region. |
||
|
|
340e727ede |
fix(ec2): prevent deleting the local VPC route and return InvalidRoute.NotFound for missing routes (#5603)
DeleteRoute removed the local route CreateRouteTable seeds for the VPC CIDR and reported success. Since CreateRoute answers RouteAlreadyExists for that destination, the route table was left without intra-VPC routing and with no way to put the route back. DeleteRoute also reported success for a destination the table does not hold, hiding caller mistakes. Reject the seeded local route with InvalidParameterValue and report an unknown destination with InvalidRoute.NotFound, matching AWS. The route is identified by its CreateRouteTable origin, so a route repointed by ReplaceRoute stays undeletable while repointed. The CloudFormation route restore path now tolerates the already-gone InvalidRoute.NotFound case through CfnDeletes.safeDelete. Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
025af9d215 |
fix(rds): list Aurora engines in DescribeOrderableDBInstanceOptions (#5585)
* fix(rds): list Aurora engines in DescribeOrderableDBInstanceOptions DescribeOrderableDBInstanceOptions returned nothing for aurora-mysql or aurora-postgresql, so clients that pick an instance class from the orderable list could not create Aurora cluster instances. Add the default Aurora MySQL (8.0.mysql_aurora.3.05.2) and Aurora PostgreSQL (16.3) versions with db.t3.medium, db.t4g.medium, db.r5.large and db.r6g.large. * fix(ec2): honour block-device-mapping.volume-type in DescribeImages The filter fell through to the default case and matched every image. Registered images now match on any block device mapping's EBS volume type, mirroring block-device-mapping.snapshot-id. Catalog images model no block devices, so an optional rootVolumeType catalog field carries the type where the AMI name states it (gp2 for the Amazon Linux 2 image, gp3 for the hvm-ssd-gp3 Ubuntu images); images without it match no value. DescribeImages output is unchanged. * fix(rds): report general-public-license for aurora-mysql orderable options * fix(ec2): carry catalog root volume type into the image's EBS mapping * fix(ec2,rds): address review on catalog AMI mappings and Aurora default version - Catalog AMI root mappings no longer advertise an invented SnapshotId that DescribeSnapshots cannot resolve (EbsBlockDevice.SnapshotId is optional); a copy or capture still mints a real root snapshot. - RunInstances sizes the root volume type from the AMI's root mapping, falling back to gp3, so the gp2 catalog AMI launches a gp2 root. - aurora-mysql defaults to 8.0.mysql_aurora.3.05.2, the version DescribeOrderableDBInstanceOptions lists. * test(ec2): assert the volume-type filter, not a single gp2 volume Instances launched earlier in the class now get gp2 roots from the gp2 catalog AMI, so filtering on gp2 returns several volumes. Check every result is gp2 and the created volume is among them. * test(rds): read EngineVersion with XmlPath, import RequestSpecification * fix(ec2): honour a RunInstances root BlockDeviceMapping volume type A request BlockDeviceMapping naming the AMI's root device overrides the AMI's root VolumeType, as on AWS; previously the launch always took the AMI mapping, so a gp3 root on the gp2 Amazon Linux 2 AMI came out gp2. * test: explicit RequestSpecification type in Ec2IntegrationTest (NoVar checkstyle rule) * refactor(ec2): fold RunInstances BlockDeviceMappings into the placement overload Adds the mappings parameter to the existing hostId/tenancy overload instead of a new one, and updates the two callers that named that signature: Ec2RunInstancesPublicIpParamTest's stub/verify (whose unmatched stub returned null and NPE'd the handler) and the dedicated-host race test. * fix(ec2): apply launch template block device mappings and capture the real root type RunInstances and CreateFleet now layer the request's BlockDeviceMappings over the launch template's (a request entry for a device replaces the template's), so a template asking for a gp3 root is honoured instead of the AMI's gp2. CreateImage records the instance's actual root volume type on the new AMI's root mapping rather than the source AMI's. A mapping naming a VolumeType outside the model's enum (standard, io1, io2, gp2, sc1, st1, gp3) is rejected with the same InvalidParameterValue ModifyVolume returns, through one shared check. The RunInstances-only parser is gone: request mappings are read by the launch template parser, which already treats every member as optional. * test(rds): fold the Aurora default-version orderable check into RdsCatalogueReadIntegrationTest * fix(autoscaling): launch group instances with the template's block device mappings Auto Scaling scale-out now hands the launch template's BlockDeviceMappings to runInstances, as RunInstances and CreateFleet do, so a group launched from a template that asks for a gp3 root gets a gp3 root instead of the AMI's type. Mixed-instances templates take the same path; launch configurations pass none. * test(ec2): template devices the request does not name still apply Covers a launch whose request maps only a data device: the template's root mapping still sets the root volume type. Also covers a template naming an unknown VolumeType, which CreateLaunchTemplate stores and the launch rejects; the EC2 docs paragraph now says so and is rewrapped to the file's width. * fix(ec2): merge launch template block device mappings field by field EC2 documents template block device overrides per member: a request entry for a DeviceName the template maps changes only what it sets, and every other member keeps the template's value. The merge replaced the whole entry, so a request that only resized the root dropped a template's gp3. The merged entry is now built from a copy of the template's, overlaid member by member, leaving the stored template untouched. |
||
|
|
6442d75115 |
fix(autoscaling): balance scale-out across zones and subnets (#5525)
Signed-off-by: Andre Kurait <akurait@amazon.com> |
||
|
|
90b9d37fd2 |
fix(ec2): preserve reserved tags during API and stack updates (#5611)
Signed-off-by: Andre Kurait <akurait@amazon.com> |
||
|
|
04dd78d0f6 |
fix(ec2): filter network interfaces by primary address association (#5531)
* fix(ec2): filter network interfaces by primary address association Signed-off-by: Andre Kurait <akurait@amazon.com> * fix(ec2): synchronize EIP associations on supplied interfaces Signed-off-by: Andre Kurait <akurait@amazon.com> * fix(ec2): require disassociation before release in nondefault VPCs Signed-off-by: Andre Kurait <akurait@amazon.com> * fix(ec2): keep Elastic IP associations aligned with interface lifecycle Signed-off-by: Andre Kurait <akurait@amazon.com> * fix(ec2): preserve retained interface association metadata Signed-off-by: Andre Kurait <akurait@amazon.com> --------- Signed-off-by: Andre Kurait <akurait@amazon.com> |
||
|
|
ec5692dfa2 |
fix(ec2): remove the volume helper container on shutdown (#5551)
* fix(ec2): remove the volume helper container on shutdown The privileged helper that manages loop devices for EBS volumes was started on the first volume operation and never stopped or removed, so it kept running after Floci exited and stayed in the container list. Ec2VolumeBlockDeviceManager now implements ContainerTeardown. On shutdown and on a state reset it looks the helper up by name, detaches the loop devices behind the backing files and removes the container. It never creates a helper only to remove it, and it also collects one left behind by an earlier process. Backing files stay in storage and the next volume operation recreates the helper. Signed-off-by: Hector Ventura <hectorvent@gmail.com> * fix(ec2): leave no volume helper after a reset and report failed loop detaches A state reset removed the helper in the container teardown and then started it again to delete the backing files, so the reset ended with a running helper. clear() now removes the helper once the files are gone. The script that releases loop devices before the helper is removed discarded every losetup failure, so the warning that follows could only fire when the exec itself failed. It now records each loop device that would not detach and exits non-zero, while still trying every device and still removing the helper. Signed-off-by: Hector Ventura <hectorvent@gmail.com> --------- Signed-off-by: Hector Ventura <hectorvent@gmail.com> |
||
|
|
2cade5cd21 |
fix(cloudformation): apply Tags, DNS attributes and InstanceTenancy on AWS::EC2::VPC (#5224)
* fix(cloudformation): apply Tags, DNS attributes and InstanceTenancy on AWS::EC2::VPC Ec2VpcCfnProvisioner read only CidrBlock, so a VPC from a template had no tags and DescribeVpcs with a tag:Name filter (CDK Vpc.from_lookup) never found it. EnableDnsSupport, EnableDnsHostnames and InstanceTenancy were dropped as well. Tags are now reconciled through Ec2Tags on create and on update (keys removed from the template are deleted), the DNS attributes are applied with the AWS defaults when omitted, and InstanceTenancy is passed to CreateVpc, with the dedicated-to-default change applied in place through a new modifyVpcTenancy and any other change treated as a replacement. CreateVpc on the EC2 Query API now honours InstanceTenancy too so the two paths agree. Fn::GetAtt gains CidrBlockAssociations, DefaultNetworkAcl and Ipv6CidrBlocks. * fix(cloudformation): validate VPC tenancy and treat blank DNS properties as omitted EnableDnsSupport/EnableDnsHostnames resolving blank (Fn::If with AWS::NoValue) now take the AWS default instead of false. CreateVpc rejects an InstanceTenancy outside default/dedicated/host with InvalidParameterValue, and ModifyVpcTenancy requires the VPC to be dedicated, as on AWS; the provisioner replaces on any other tenancy change. The integration test reads outputs with XmlPath, and the query-handler test stub follows the new createVpc overload. * style(cloudformation): no final on the VPC local; compare tag sets unordered in the test * fix(ec2): CreateVpc accepts default or dedicated tenancy only * fix(ec2): share the enumerated-parameter check for VPC tenancy and cover it on the Query API requireMetadataOptionValue becomes requireParameterValue and requireVpcTenancy uses it, so the InvalidParameterValue wording lives in one place. A Query API test sends InstanceTenancy to CreateVpc and reads it back from DescribeVpcs, the provisioner test no longer turns DNS hostnames on with DNS support off, and the CreateVpc docs row names the accepted tenancies. * fix(ec2): only an absent InstanceTenancy defaults; order the test static imports |
||
|
|
1aabc8b4fe |
fix(ec2): give availability-zone ids AWS's shape, shared by EC2, flow logs and EFS (#5486)
* fix(efs): report the zone id EC2 reports for the same zone EFS derived its own availability-zone id (use1-az1) by splitting the region on hyphens, while EC2 publishes <region>-az<n> for subnets and zones, so a mount target and its subnet disagreed. The abbreviation also only worked for three-part regions: us-gov-west-1a and eusc-de-east-1a kept the whole region. EFS now takes the id from the helper EC2 and VPC flow logs use. Also drops an allowlist pattern for flow-log region abbreviations that matches no source line since flow logs moved to the same helper. Signed-off-by: Hector Ventura <hectorvent@gmail.com> * fix(ec2): give availability-zone ids AWS's shape, shared by EC2, flow logs and EFS EC2 published <region>-az<n> as a zone id and EFS its own abbreviation, so a mount target and its subnet disagreed and neither matched AWS in every region. AvailabilityZoneIds in core.common now derives the id for all three: AWS's short region prefix and -az<n> (use1-az1, apne1-az1, usgw1-az1, cnn1-az1). The prefix rule is attested for the commercial, China and GovCloud regions; AWS publishes no zone id for an ISO or EUSC region, so those keep the whole region as the prefix instead of a guessed one. Zone a is still az1, b az2, and so on: AWS maps names to ids per account, which Floci does not model. CreateSubnet resolves AvailabilityZoneId in the new shape and refuses the old one. Signed-off-by: Hector Ventura <hectorvent@gmail.com> --------- Signed-off-by: Hector Ventura <hectorvent@gmail.com> |
||
|
|
b86268e459 |
fix(ec2): preserve original Spot instance user data (#5468)
* fix(ec2): preserve original Spot instance user data * fix(ec2): omit whitespace-only Spot user data * docs(ec2): clarify Spot user-data encoding * refactor(ec2): simplify Spot user-data handling |
||
|
|
80e8b7465d |
fix(ec2): preserve endpoint IP types across updates and templates (#5438)
* fix(ec2): preserve endpoint IP types across updates and templates * fix(ec2): honor omitted endpoint address types in templates |
||
|
|
f4bce30269 |
fix(ec2): preserve original user-data bytes in instance metadata (#5437)
* fix(ec2): preserve original user-data bytes in instance metadata * fix(ec2): recover malformed saved user data |
||
|
|
47d1e10e5c |
fix(ec2): preserve VPC endpoint IP address types (#5427)
* fix(ec2): preserve SDK endpoint compatibility Return endpoint states that AWS SDK clients recognize and preserve the requested address family, so endpoint create and describe responses round-trip correctly. Keep documented state-filter values working. * fix(ec2): preserve saved endpoint states and reject invalid IP types * fix(ec2): reject unsupported endpoint IP types safely * fix(ec2): retain endpoint states and address-type metadata --------- Co-authored-by: Jason van Zyl <jason@vanzyl.ca> |
||
|
|
8502565287 |
fix(ec2): serve IMDS instance identity credentials (#5289)
Adds identity-credentials/ec2/info, ec2-instance credentials and listings. * Fix #5264 Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com> |
||
|
|
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 |
||
|
|
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. |
||
|
|
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 |
||
|
|
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 |
||
|
|
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. |
||
|
|
d1a9b50cf5 | feat(ec2): resize volume backing files and loop devices on ModifyVolume (#4666) | ||
|
|
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. |
||
|
|
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 |
||
|
|
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 |
||
|
|
077b65df5c | feat(ec2): implement ModifyVolume and volume modification state (#4320) | ||
|
|
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. |
||
|
|
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 |
||
|
|
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 |
||
|
|
7c94f69571 | feat(ec2): bound instance containers to their instance type resources (#4189) | ||
|
|
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. |
||
|
|
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/. |
||
|
|
df68eebaef | feat(ec2): support an external image catalog (#4144) | ||
|
|
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. |
||
|
|
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> |
||
|
|
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> |
||
|
|
5ec3fb67a8 | fix(ec2): resolve instance profile names through IAM (#3856) | ||
|
|
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 |
||
|
|
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. |
||
|
|
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 |
||
|
|
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 |
||
|
|
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> |
||
|
|
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. |
||
|
|
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. |