mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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.
This commit is contained in:
1 parent
d3fce14256
commit
1e423420ed
10 files changed
+806
-51
No files matched your search
+39
-4
@@ -86,6 +86,28 @@ class CloudFormationEc2NetworkingIntegrationTest {
|
||||
ec2("DeleteVpc", Map.of("VpcId", vpcId));
|
||||
}
|
||||
|
||||
/**
|
||||
* CreateNatGateway with an Elastic IP another gateway holds succeeds on AWS and leaves the
|
||||
* gateway failed; CloudFormation must still fail the resource rather than report it created.
|
||||
*/
|
||||
@Test
|
||||
void aNatGatewayGivenAnAlreadyHeldElasticIpFailsTheStack() {
|
||||
String vpcId = between(ec2("CreateVpc", Map.of("CidrBlock", "10.42.0.0/16")), "<vpcId>", "</vpcId>");
|
||||
String nat = "{\"Type\": \"AWS::EC2::NatGateway\", %s\"Properties\": {\"SubnetId\": {\"Ref\": \"Subnet\"},"
|
||||
+ " \"AllocationId\": {\"Fn::GetAtt\": [\"Eip\", \"AllocationId\"]}}}";
|
||||
cloudFormation("ec2-nat-shared-eip-it", "CreateStack", """
|
||||
{"Resources": {
|
||||
"Subnet": {"Type": "AWS::EC2::Subnet", "Properties": {"VpcId": "%s", "CidrBlock": "10.42.0.0/24"}},
|
||||
"Eip": {"Type": "AWS::EC2::EIP", "Properties": {"Domain": "vpc"}},
|
||||
"NatA": %s,
|
||||
"NatB": %s
|
||||
}}
|
||||
""".formatted(vpcId, nat.formatted(""), nat.formatted("\"DependsOn\": \"NatA\", ")));
|
||||
|
||||
describeStacks("ec2-nat-shared-eip-it", "ROLLBACK_COMPLETE");
|
||||
assertFalse(ec2("DescribeNatGateways").contains(vpcId), "no gateway, failed or not, is left behind");
|
||||
}
|
||||
|
||||
private static String subnetXml(String subnetId) {
|
||||
return ec2("DescribeSubnets", Map.of("SubnetId.1", subnetId));
|
||||
}
|
||||
@@ -187,14 +209,27 @@ class CloudFormationEc2NetworkingIntegrationTest {
|
||||
assertFalse(retagged.contains("<key>tier</key>"), "the dropped tag must be removed");
|
||||
|
||||
// CidrBlock is createOnly: the public subnet is replaced, and with it the NAT gateway and the
|
||||
// association that name it; the gateway, EIP and route tables stay.
|
||||
cloudFormation("UpdateStack", template(vpcId, "10.40.2.0/24"));
|
||||
// association that name it; the gateway and route tables stay. The replacement gateway gets a
|
||||
// new EIP: CloudFormation creates it before deleting the old one, and on AWS a gateway given
|
||||
// an Elastic IP the displaced gateway still holds is created failed. The old EIP stays in
|
||||
// the template for a second reason: Floci's update cleanup deletes removed resources before
|
||||
// the old copies of replaced ones (AWS deletes in reverse dependency order), so dropping the
|
||||
// EIP while replacing its gateway would try to release it while the old gateway still holds
|
||||
// it. Keeping NatEip sidesteps that; the cleanup order is a separate issue. The old EIP is
|
||||
// free once the displaced gateway is gone. oldEip is NatEip: out is NatEipB's outputs below.
|
||||
cloudFormation("UpdateStack", template(vpcId, "10.40.2.0/24").replace("NatEip", "NatEipB")
|
||||
.replace("\"NatEipB\": {\"Type\"",
|
||||
"\"NatEip\": {\"Type\": \"AWS::EC2::EIP\", \"Properties\": {\"Domain\": \"vpc\"}},\n"
|
||||
+ " \"NatEipB\": {\"Type\""));
|
||||
Map<String, String> replaced = XmlParser.extractPairs(describeStacks("UPDATE_COMPLETE"), "Outputs", "OutputKey", "OutputValue");
|
||||
assertFalse(out.get("SubnetId").equals(replaced.get("SubnetId")), "a changed CIDR must replace the subnet");
|
||||
assertFalse(out.get("NatId").equals(replaced.get("NatId")), "the NAT gateway follows its subnet");
|
||||
assertFalse(out.get("AssocId").equals(replaced.get("AssocId")), "the association follows its subnet");
|
||||
assertEquals(out.get("IgwId"), replaced.get("IgwId"));
|
||||
assertEquals(out.get("EipAllocationId"), replaced.get("EipAllocationId"));
|
||||
assertFalse(out.get("EipAllocationId").equals(replaced.get("EipAllocationId")), "the gateway takes the new EIP");
|
||||
assertFalse(ec2("DescribeAddresses", Map.of("AllocationId.1", out.get("EipAllocationId"))).contains("<associationId>"),
|
||||
"the displaced gateway's EIP must be free");
|
||||
String oldEip = out.get("EipAllocationId");
|
||||
assertEquals(out.get("PublicRtId"), replaced.get("PublicRtId"));
|
||||
assertEquals(out.get("PrivateRtId"), replaced.get("PrivateRtId"));
|
||||
assertFalse(ec2("DescribeSubnets").contains(out.get("SubnetId")), "the displaced subnet must be gone");
|
||||
@@ -206,7 +241,7 @@ class CloudFormationEc2NetworkingIntegrationTest {
|
||||
CfnStackWaits.awaitStackDeleted(STACK);
|
||||
|
||||
for (String id : List.of(out.get("SubnetId"), out.get("PublicRtId"), out.get("PrivateRtId"),
|
||||
out.get("AssocId"), out.get("NatId"), out.get("EipAllocationId"), out.get("IgwId"))) {
|
||||
out.get("AssocId"), out.get("NatId"), out.get("EipAllocationId"), oldEip, out.get("IgwId"))) {
|
||||
String everything = ec2("DescribeSubnets") + ec2("DescribeRouteTables") + ec2("DescribeNatGateways")
|
||||
+ ec2("DescribeAddresses") + ec2("DescribeInternetGateways");
|
||||
assertFalse(everything.contains(id), "stack delete must remove " + id);
|
||||
|
||||
+259
@@ -89,6 +89,105 @@ class Ec2NatGatewayAddressIntegrationTest {
|
||||
startsWith("eni-"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The interface id DescribeNatGateways publishes has to resolve through
|
||||
* DescribeNetworkInterfaces, and the Elastic IP the gateway holds has to read as associated
|
||||
* through DescribeAddresses. Deleting the gateway releases both.
|
||||
*/
|
||||
@Test
|
||||
void aGatewaysInterfaceResolvesAndItsElasticIpReadsAsAssociated() {
|
||||
String subnetId = subnetId();
|
||||
String allocationId = given()
|
||||
.formParam("Action", "AllocateAddress")
|
||||
.formParam("Domain", "vpc")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().path("AllocateAddressResponse.allocationId");
|
||||
|
||||
String natGatewayId = given()
|
||||
.formParam("Action", "CreateNatGateway")
|
||||
.formParam("SubnetId", subnetId)
|
||||
.formParam("AllocationId", allocationId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().path("CreateNatGatewayResponse.natGateway.natGatewayId");
|
||||
|
||||
io.restassured.response.Response described = given()
|
||||
.formParam("Action", "DescribeNatGateways")
|
||||
.formParam("NatGatewayId.1", natGatewayId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200).extract().response();
|
||||
String prefix = "DescribeNatGatewaysResponse.natGatewaySet.item.";
|
||||
String eniId = described.path(prefix + "natGatewayAddressSet.item.networkInterfaceId");
|
||||
String privateIp = described.path(prefix + "natGatewayAddressSet.item.privateIp");
|
||||
String associationId = described.path(prefix + "natGatewayAddressSet.item.associationId");
|
||||
String vpcId = described.path(prefix + "vpcId");
|
||||
|
||||
// Twice: the id must be stable, not re-minted per read.
|
||||
for (int i = 0; i < 2; i++) {
|
||||
given()
|
||||
.formParam("Action", "DescribeNetworkInterfaces")
|
||||
.formParam("NetworkInterfaceId.1", eniId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.networkInterfaceId",
|
||||
equalTo(eniId))
|
||||
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.interfaceType",
|
||||
equalTo("nat_gateway"))
|
||||
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.subnetId",
|
||||
equalTo(subnetId))
|
||||
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.vpcId",
|
||||
equalTo(vpcId))
|
||||
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.privateIpAddress",
|
||||
equalTo(privateIp))
|
||||
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item"
|
||||
+ ".privateIpAddressesSet.item.association.allocationId", equalTo(allocationId));
|
||||
}
|
||||
|
||||
given()
|
||||
.formParam("Action", "DescribeAddresses")
|
||||
.formParam("AllocationId.1", allocationId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DescribeAddressesResponse.addressesSet.item.associationId", equalTo(associationId))
|
||||
.body("DescribeAddressesResponse.addressesSet.item.networkInterfaceId", equalTo(eniId))
|
||||
.body("DescribeAddressesResponse.addressesSet.item.privateIpAddress", equalTo(privateIp));
|
||||
|
||||
given()
|
||||
.formParam("Action", "DeleteNatGateway")
|
||||
.formParam("NatGatewayId", natGatewayId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
given()
|
||||
.formParam("Action", "DescribeNetworkInterfaces")
|
||||
.formParam("NetworkInterfaceId.1", eniId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidNetworkInterfaceID.NotFound"));
|
||||
|
||||
given()
|
||||
.formParam("Action", "DescribeAddresses")
|
||||
.formParam("AllocationId.1", allocationId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DescribeAddressesResponse.addressesSet.item.allocationId", equalTo(allocationId))
|
||||
.body(not(containsString("<associationId>")))
|
||||
.body(not(containsString("<networkInterfaceId>")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPrivateGatewayHasAPrivateAddressAndNoElasticIp() {
|
||||
given()
|
||||
@@ -134,4 +233,164 @@ class Ec2NatGatewayAddressIntegrationTest {
|
||||
.statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidParameterCombination"));
|
||||
}
|
||||
|
||||
private String allocate() {
|
||||
return given()
|
||||
.formParam("Action", "AllocateAddress")
|
||||
.formParam("Domain", "vpc")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().path("AllocateAddressResponse.allocationId");
|
||||
}
|
||||
|
||||
private io.restassured.response.Response createNat(String allocationId) {
|
||||
return given()
|
||||
.formParam("Action", "CreateNatGateway")
|
||||
.formParam("SubnetId", subnetId())
|
||||
.formParam("AllocationId", allocationId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/");
|
||||
}
|
||||
|
||||
/**
|
||||
* As on AWS, CreateNatGateway with an Elastic IP another gateway or an instance holds
|
||||
* succeeds, but the gateway is failed: no interface, and the holder keeps the address.
|
||||
*/
|
||||
@Test
|
||||
void aGatewayGivenAnAssociatedElasticIpIsCreatedFailed() {
|
||||
String heldByGateway = allocate();
|
||||
createNat(heldByGateway).then().statusCode(200);
|
||||
String failedId = createNat(heldByGateway).then().statusCode(200)
|
||||
.body("CreateNatGatewayResponse.natGateway.state", equalTo("failed"))
|
||||
.extract().path("CreateNatGatewayResponse.natGateway.natGatewayId");
|
||||
given()
|
||||
.formParam("Action", "DescribeNatGateways")
|
||||
.formParam("NatGatewayId.1", failedId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("DescribeNatGatewaysResponse.natGatewaySet.item.state", equalTo("failed"))
|
||||
.body("DescribeNatGatewaysResponse.natGatewaySet.item.failureCode",
|
||||
equalTo("Resource.AlreadyAssociated"))
|
||||
.body("DescribeNatGatewaysResponse.natGatewaySet.item.failureMessage",
|
||||
equalTo("Elastic IP address " + heldByGateway + " is already associated"))
|
||||
.body(not(containsString("<networkInterfaceId>")));
|
||||
|
||||
String heldByInstance = allocate();
|
||||
given()
|
||||
.formParam("Action", "AssociateAddress")
|
||||
.formParam("AllocationId", heldByInstance)
|
||||
.formParam("InstanceId", "i-0123456789abcdef0")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
createNat(heldByInstance).then().statusCode(200)
|
||||
.body("CreateNatGatewayResponse.natGateway.state", equalTo("failed"))
|
||||
.body("CreateNatGatewayResponse.natGateway.failureCode", equalTo("Resource.AlreadyAssociated"));
|
||||
String instanceAssociation = given()
|
||||
.formParam("Action", "DescribeAddresses")
|
||||
.formParam("AllocationId.1", heldByInstance)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("DescribeAddressesResponse.addressesSet.item.instanceId", equalTo("i-0123456789abcdef0"))
|
||||
.extract().path("DescribeAddressesResponse.addressesSet.item.associationId");
|
||||
// The failed gateway does not hold the address: once the instance lets go it can be released.
|
||||
given()
|
||||
.formParam("Action", "DisassociateAddress")
|
||||
.formParam("AssociationId", instanceAssociation)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
given()
|
||||
.formParam("Action", "ReleaseAddress")
|
||||
.formParam("AllocationId", heldByInstance)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
|
||||
// The failed gateway claimed nothing, and deleting it leaves the first gateway's association alone.
|
||||
String held = given()
|
||||
.formParam("Action", "DescribeAddresses")
|
||||
.formParam("AllocationId.1", heldByGateway)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("DescribeAddressesResponse.addressesSet.item.associationId", startsWith("eipassoc-"))
|
||||
.extract().path("DescribeAddressesResponse.addressesSet.item.associationId");
|
||||
given()
|
||||
.formParam("Action", "DeleteNatGateway")
|
||||
.formParam("NatGatewayId", failedId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
given()
|
||||
.formParam("Action", "DescribeAddresses")
|
||||
.formParam("AllocationId.1", heldByGateway)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("DescribeAddressesResponse.addressesSet.item.associationId", equalTo(held));
|
||||
}
|
||||
|
||||
/** The association a gateway publishes is released by deleting the gateway, not by disassociating. */
|
||||
@Test
|
||||
void aGatewaysElasticIpCannotBeDisassociated() {
|
||||
String allocationId = allocate();
|
||||
String natGatewayId = createNat(allocationId).then().statusCode(200)
|
||||
.extract().path("CreateNatGatewayResponse.natGateway.natGatewayId");
|
||||
String associationId = given()
|
||||
.formParam("Action", "DescribeAddresses")
|
||||
.formParam("AllocationId.1", allocationId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().path("DescribeAddressesResponse.addressesSet.item.associationId");
|
||||
|
||||
given()
|
||||
.formParam("Action", "DisassociateAddress")
|
||||
.formParam("AssociationId", associationId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
|
||||
|
||||
given()
|
||||
.formParam("Action", "DescribeAddresses")
|
||||
.formParam("AllocationId.1", allocationId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("DescribeAddressesResponse.addressesSet.item.associationId", equalTo(associationId));
|
||||
|
||||
// Nor released out from under the gateway: AWS answers InvalidIPAddress.InUse.
|
||||
given()
|
||||
.formParam("Action", "ReleaseAddress")
|
||||
.formParam("AllocationId", allocationId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(400)
|
||||
.body("Response.Errors.Error.Code", equalTo("InvalidIPAddress.InUse"));
|
||||
given()
|
||||
.formParam("Action", "DescribeAddresses")
|
||||
.formParam("AllocationId.1", allocationId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.body("DescribeAddressesResponse.addressesSet.item.associationId", equalTo(associationId));
|
||||
|
||||
given()
|
||||
.formParam("Action", "DeleteNatGateway")
|
||||
.formParam("NatGatewayId", natGatewayId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
given()
|
||||
.formParam("Action", "ReleaseAddress")
|
||||
.formParam("AllocationId", allocationId)
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RequestContext;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Address;
|
||||
@@ -24,6 +25,7 @@ import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NatGateway;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NatGatewayAddress;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkInterface;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkInterfaceAssociation;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkInterfaceListResult;
|
||||
@@ -463,6 +465,54 @@ class Ec2ServiceTest {
|
||||
.noneMatch(subnet -> subnetId.equals(subnet.getSubnetId())));
|
||||
}
|
||||
|
||||
/**
|
||||
* A failed NAT gateway was never created and holds no interface, so it does not pin its subnet.
|
||||
* The gateway fails because its Elastic IP is already held by a gateway in the default VPC.
|
||||
*/
|
||||
@Test
|
||||
void deleteSubnetIgnoresAFailedNatGateway() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
String region = "us-east-1";
|
||||
String defaultSubnetId = service.describeSubnets(region, List.of(), Map.of()).getFirst().getSubnetId();
|
||||
String allocationId = service.allocateAddress(region).getAllocationId();
|
||||
service.createNatGateway(region, defaultSubnetId, allocationId, null, null);
|
||||
String vpcId = service.createVpc(region, "10.85.0.0/16", false).getVpcId();
|
||||
String subnetId = service.createSubnet(region, vpcId, "10.85.1.0/24", "us-east-1a").getSubnetId();
|
||||
NatGateway failed = service.createNatGateway(region, subnetId, allocationId, null, null);
|
||||
assertEquals("failed", failed.getState());
|
||||
|
||||
service.deleteSubnet(region, subnetId);
|
||||
assertTrue(service.describeSubnets(region, List.of(), Map.of()).stream()
|
||||
.noneMatch(subnet -> subnetId.equals(subnet.getSubnetId())));
|
||||
}
|
||||
|
||||
/** DeleteVpc checks the same subnet residents, so a failed NAT gateway does not pin the VPC either. */
|
||||
@Test
|
||||
void deleteVpcIgnoresAFailedNatGatewayInOneOfItsSubnets() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
String region = "us-east-1";
|
||||
String defaultSubnetId = service.describeSubnets(region, List.of(), Map.of()).getFirst().getSubnetId();
|
||||
String allocationId = service.allocateAddress(region).getAllocationId();
|
||||
service.createNatGateway(region, defaultSubnetId, allocationId, null, null);
|
||||
String vpcId = service.createVpc(region, "10.86.0.0/16", false).getVpcId();
|
||||
String subnetId = service.createSubnet(region, vpcId, "10.86.1.0/24", "us-east-1a").getSubnetId();
|
||||
NatGateway failed = service.createNatGateway(region, subnetId, allocationId, null, null);
|
||||
assertEquals("failed", failed.getState());
|
||||
|
||||
// DeleteVpc refuses while any subnet remains, so the resident check runs in DeleteSubnet;
|
||||
// after that the failed gateway must not keep the VPC either.
|
||||
service.deleteSubnet(region, subnetId);
|
||||
service.deleteVpc(region, vpcId);
|
||||
assertTrue(service.describeVpcs(region, List.of(), Map.of()).stream()
|
||||
.noneMatch(vpc -> vpcId.equals(vpc.getVpcId())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSubnetFailsUntilItsStandaloneNetworkInterfaceIsDeleted() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
@@ -1117,6 +1167,216 @@ class Ec2ServiceTest {
|
||||
.anyMatch(n -> eni.getNetworkInterfaceId().equals(n.getNetworkInterfaceId())));
|
||||
}
|
||||
|
||||
/**
|
||||
* The NAT arm of DescribeNetworkInterfaces reads gateways for the account it was asked about.
|
||||
* A gateway made under the default account resolves for that account and is NotFound for
|
||||
* another one named explicitly.
|
||||
*/
|
||||
@Test
|
||||
void natGatewayInterfaceResolvesOnlyForTheAccountThatOwnsTheGateway() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = service.describeSubnets("us-east-1", List.of(), Map.of())
|
||||
.getFirst().getSubnetId();
|
||||
String eniId = service.createNatGateway("us-east-1", subnetId, null, "private", null)
|
||||
.getNatGatewayAddresses().getFirst().getNetworkInterfaceId();
|
||||
|
||||
String owner = service.callerAccountId();
|
||||
assertEquals(eniId, service.describeNetworkInterfaces(owner, "us-east-1", List.of(eniId), Map.of())
|
||||
.networkInterfaces().getFirst().getNetworkInterfaceId());
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.describeNetworkInterfaces(
|
||||
"999999999999", "us-east-1", List.of(eniId), Map.of()));
|
||||
assertEquals("InvalidNetworkInterfaceID.NotFound", e.getErrorCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* A gateway persisted before Address records were marked has an allocation that looks free.
|
||||
* The gateway still holds it, so a second gateway is created failed and claims nothing.
|
||||
*/
|
||||
@Test
|
||||
void natGatewayGivenAnElasticIpHeldByALegacyGatewayWithAnUnmarkedAddressIsFailed() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = service.describeSubnets("us-east-1", List.of(), Map.of()).getFirst().getSubnetId();
|
||||
String allocationId = service.allocateAddress("us-east-1").getAllocationId();
|
||||
service.createNatGateway("us-east-1", subnetId, allocationId, null, null);
|
||||
// Simulate the pre-change record: in-memory storage hands back the stored object.
|
||||
Address legacy = service.describeAddresses("us-east-1", List.of(allocationId), Map.of()).getFirst();
|
||||
legacy.setAssociationId(null);
|
||||
legacy.setNetworkInterfaceId(null);
|
||||
legacy.setPrivateIpAddress(null);
|
||||
|
||||
NatGateway failed = service.createNatGateway("us-east-1", subnetId, allocationId, null, null);
|
||||
assertEquals("failed", failed.getState());
|
||||
assertEquals("Resource.AlreadyAssociated", failed.getFailureCode());
|
||||
assertTrue(failed.getNatGatewayAddresses().isEmpty());
|
||||
assertNull(service.describeAddresses("us-east-1", List.of(allocationId), Map.of())
|
||||
.getFirst().getAssociationId(), "a failed gateway must not claim the allocation");
|
||||
}
|
||||
|
||||
/** AssociateAddress refuses an allocation a NAT gateway holds; the gateway keeps it. */
|
||||
@Test
|
||||
void associateAddressRefusesANatGatewaysElasticIp() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = service.describeSubnets("us-east-1", List.of(), Map.of()).getFirst().getSubnetId();
|
||||
String allocationId = service.allocateAddress("us-east-1").getAllocationId();
|
||||
NatGateway nat = service.createNatGateway("us-east-1", subnetId, allocationId, null, null);
|
||||
String gatewayAssociation = nat.getNatGatewayAddresses().getFirst().getAssociationId();
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.associateAddress("us-east-1", allocationId, "i-0123456789abcdef0"));
|
||||
assertEquals("Resource.AlreadyAssociated", e.getErrorCode());
|
||||
|
||||
Address after = service.describeAddresses("us-east-1", List.of(allocationId), Map.of()).getFirst();
|
||||
assertEquals(gatewayAssociation, after.getAssociationId());
|
||||
assertNull(after.getInstanceId());
|
||||
service.deleteNatGateway("us-east-1", nat.getNatGatewayId());
|
||||
assertNull(service.describeAddresses("us-east-1", List.of(allocationId), Map.of())
|
||||
.getFirst().getAssociationId(), "delete must still release the gateway's Elastic IP");
|
||||
}
|
||||
|
||||
/**
|
||||
* A gateway persisted before account isolation (unprefixed key) still holds its Elastic IP:
|
||||
* a second gateway is created failed, and ReleaseAddress answers InvalidIPAddress.InUse.
|
||||
*/
|
||||
@Test
|
||||
void aLegacyUnprefixedGatewaysElasticIpCannotBeTakenOrReleased() {
|
||||
InMemoryStorage<String, NatGateway> rawGateways = new InMemoryStorage<>();
|
||||
Map<String, AccountAwareStorageBackend<?>> stores = Map.of("ec2-nat-gateways.json",
|
||||
new AccountAwareStorageBackend<>(rawGateways, null, "000000000000"));
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(stores));
|
||||
String subnetId = service.describeSubnets("us-east-1", List.of(), Map.of()).getFirst().getSubnetId();
|
||||
String allocationId = service.allocateAddress("us-east-1").getAllocationId();
|
||||
NatGateway legacy = new NatGateway();
|
||||
legacy.setNatGatewayId("nat-0legacy000000000");
|
||||
legacy.setSubnetId(subnetId);
|
||||
legacy.setAllocationId(allocationId);
|
||||
legacy.setState("available");
|
||||
legacy.setRegion("us-east-1");
|
||||
rawGateways.put("us-east-1::nat-0legacy000000000", legacy);
|
||||
|
||||
NatGateway failed = service.createNatGateway("us-east-1", subnetId, allocationId, null, null);
|
||||
assertEquals("failed", failed.getState());
|
||||
assertEquals("Resource.AlreadyAssociated", failed.getFailureCode());
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> service.releaseAddress("us-east-1", allocationId));
|
||||
assertEquals("InvalidIPAddress.InUse", e.getErrorCode());
|
||||
assertEquals(1, service.describeAddresses("us-east-1", List.of(allocationId), Map.of()).size());
|
||||
}
|
||||
|
||||
/** A legacy unprefixed gateway in a legacy unprefixed subnet resolves its interface for the default account. */
|
||||
@Test
|
||||
void aLegacyUnprefixedGatewaysInterfaceResolvesForTheDefaultAccount() {
|
||||
InMemoryStorage<String, NatGateway> rawGateways = new InMemoryStorage<>();
|
||||
InMemoryStorage<String, Subnet> rawSubnets = new InMemoryStorage<>();
|
||||
Map<String, AccountAwareStorageBackend<?>> stores = Map.of(
|
||||
"ec2-nat-gateways.json", new AccountAwareStorageBackend<>(rawGateways, null, "000000000000"),
|
||||
"ec2-subnets.json", new AccountAwareStorageBackend<>(rawSubnets, null, "000000000000"));
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(stores));
|
||||
service.describeSubnets("us-east-1", List.of(), Map.of());
|
||||
Subnet subnet = new Subnet();
|
||||
subnet.setSubnetId("subnet-0legacy00000000");
|
||||
subnet.setVpcId("vpc-0legacy000000000");
|
||||
subnet.setAvailabilityZone("us-east-1a");
|
||||
subnet.setRegion("us-east-1");
|
||||
rawSubnets.put("us-east-1::subnet-0legacy00000000", subnet);
|
||||
NatGateway legacy = new NatGateway();
|
||||
legacy.setNatGatewayId("nat-0legacy000000000");
|
||||
legacy.setSubnetId("subnet-0legacy00000000");
|
||||
legacy.setVpcId("vpc-0legacy000000000");
|
||||
legacy.setRegion("us-east-1");
|
||||
NatGatewayAddress address = new NatGatewayAddress();
|
||||
address.setNetworkInterfaceId("eni-0legacy000000000");
|
||||
address.setPrivateIp("10.0.0.5");
|
||||
legacy.getNatGatewayAddresses().add(address);
|
||||
rawGateways.put("us-east-1::nat-0legacy000000000", legacy);
|
||||
|
||||
NetworkInterface ni = service.describeNetworkInterfaces(service.callerAccountId(), "us-east-1",
|
||||
List.of("eni-0legacy000000000"), Map.of()).networkInterfaces().getFirst();
|
||||
assertEquals("nat_gateway", ni.getInterfaceType());
|
||||
assertEquals("us-east-1a", ni.getAvailabilityZone());
|
||||
AwsException e = assertThrows(AwsException.class, () -> service.describeNetworkInterfaces(
|
||||
"999999999999", "us-east-1", List.of("eni-0legacy000000000"), Map.of()));
|
||||
assertEquals("InvalidNetworkInterfaceID.NotFound", e.getErrorCode());
|
||||
}
|
||||
|
||||
/** Tags on a NAT gateway's interface read back through DescribeNetworkInterfaces and go with the gateway. */
|
||||
@Test
|
||||
void aNatGatewayInterfacesTagsReadBackAndAreDeletedWithTheGateway() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = service.describeSubnets("us-east-1", List.of(), Map.of()).getFirst().getSubnetId();
|
||||
NatGateway nat = service.createNatGateway("us-east-1", subnetId, null, "private", null);
|
||||
String eniId = nat.getNatGatewayAddresses().getFirst().getNetworkInterfaceId();
|
||||
service.createTags("us-east-1", List.of(eniId), List.of(new Tag("Name", "nat-eni")));
|
||||
|
||||
NetworkInterface ni = service.describeNetworkInterfaces(service.callerAccountId(), "us-east-1",
|
||||
List.of(eniId), Map.of()).networkInterfaces().getFirst();
|
||||
assertEquals("nat-eni", ni.getTagSet().getFirst().getValue());
|
||||
|
||||
service.deleteNatGateway("us-east-1", nat.getNatGatewayId());
|
||||
assertTrue(service.describeTags("us-east-1", Map.of("resource-id", List.of(eniId))).isEmpty());
|
||||
}
|
||||
|
||||
/** DisassociateAddress checks and clears under the lock NAT create and delete take. */
|
||||
@Test
|
||||
void disassociateAddressWaitsForTheAllocationLock() throws Exception {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String allocationId = service.allocateAddress("us-east-1").getAllocationId();
|
||||
String associationId = service.associateAddress("us-east-1", allocationId, "i-0123456789abcdef0")
|
||||
.getAssociationId();
|
||||
Field field = Ec2Service.class.getDeclaredField("privateIpAllocationLock");
|
||||
field.setAccessible(true);
|
||||
Object lock = field.get(service);
|
||||
|
||||
Thread disassociator = new Thread(() -> service.disassociateAddress("us-east-1", associationId));
|
||||
synchronized (lock) {
|
||||
disassociator.start();
|
||||
disassociator.join(500);
|
||||
assertTrue(disassociator.isAlive(), "disassociate must wait for the allocation lock");
|
||||
}
|
||||
disassociator.join(5000);
|
||||
assertFalse(disassociator.isAlive());
|
||||
assertNull(service.describeAddresses("us-east-1", List.of(allocationId), Map.of())
|
||||
.getFirst().getAssociationId());
|
||||
}
|
||||
|
||||
/** DeleteNatGateway releases the Elastic IP under the lock CreateNatGateway takes. */
|
||||
@Test
|
||||
void deleteNatGatewayReleasesTheElasticIpUnderTheAllocationLock() throws Exception {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
|
||||
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
|
||||
String subnetId = service.describeSubnets("us-east-1", List.of(), Map.of()).getFirst().getSubnetId();
|
||||
String allocationId = service.allocateAddress("us-east-1").getAllocationId();
|
||||
String natId = service.createNatGateway("us-east-1", subnetId, allocationId, null, null).getNatGatewayId();
|
||||
Field field = Ec2Service.class.getDeclaredField("privateIpAllocationLock");
|
||||
field.setAccessible(true);
|
||||
Object lock = field.get(service);
|
||||
|
||||
Thread deleter = new Thread(() -> service.deleteNatGateway("us-east-1", natId));
|
||||
synchronized (lock) {
|
||||
deleter.start();
|
||||
deleter.join(500);
|
||||
assertTrue(deleter.isAlive(), "delete must wait for the allocation lock");
|
||||
}
|
||||
deleter.join(5000);
|
||||
assertFalse(deleter.isAlive());
|
||||
assertNull(service.describeAddresses("us-east-1", List.of(allocationId), Map.of())
|
||||
.getFirst().getAssociationId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void runInstancesRequiresImageIdInsteadOfDefaulting() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
|
||||
Reference in new issue
Block a user