* 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>
* 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.
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.
* 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.
* 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.
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>
* 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.
* 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>
* 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>
* 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
* 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>
* 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>
* 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
* 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.
* 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
* 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
* 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.
* 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.
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
* 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.
* 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
* 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
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.
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/.
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.
* 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>
* 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>
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
* 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.
* 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>
* 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.
* 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.
* 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>
* 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.