fix(ec2): refuse an explicit CreateNetworkInterface address that is already in use (#6908)

This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-29 07:47:55 -04:00
1 parent 772b444850
commit 146ba44c92
3 files changed
+224 -13

No files matched your search

@@ -4662,22 +4662,37 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
* case the instance keeps it the way it keeps a synthesised address.
*/
private void claimRequestedPrivateIp(String region, String subnetId, String address) {
if (requireRequestedPrivateIpFree(region, subnetId, address)) {
vpcNetworkManager.claimPrivateIp(region, subnetId, address);
}
}
/**
* The in-use half of {@link #claimRequestedPrivateIp}, without the lease. CreateNetworkInterface
* uses it alone: an interface has no container to hold the address on the VPC network, and
* DeleteNetworkInterface returns no lease, so one taken here would keep the address from
* automatic allocation after the interface is gone. {@link #assignPrivateIp} already steps
* around addresses stored interfaces hold. Callers must hold {@link #privateIpAllocationLock}.
*
* @return whether the address lies in a Docker-backed range, where a lease could be taken
*/
private boolean requireRequestedPrivateIpFree(String region, String subnetId, String address) {
if (privateIpsTaken(region, subnetId).contains(address)) {
throw new AwsException("InvalidIPAddress.InUse", "Address " + address + " is in use.", 400);
}
if (vpcNetworkManager == null || subnetId == null) {
return;
return false;
}
boolean leasable = vpcNetworkManager.effectiveSubnetCidr(region, subnetId)
.filter(cidr -> Ipv4Cidrs.contains(cidr, address + "/32"))
.isPresent();
if (!leasable) {
return;
return false;
}
if (privateIpsInUseInEveryAccount(region, subnetId).contains(address)) {
throw new AwsException("InvalidIPAddress.InUse", "Address " + address + " is in use.", 400);
}
vpcNetworkManager.claimPrivateIp(region, subnetId, address);
return true;
}
/** {@link #privateIpsInUse}, across every account rather than only the caller's. */
@@ -4777,8 +4792,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
private static void addIfSet(Set<String> addresses, String address) {
if (address != null && !address.isBlank()) {
// CreateNetworkInterface keeps its address as given, so a zero-padded octet has to be
// folded here for the in-use checks to see one address rather than two.
// An interface persisted before CreateNetworkInterface canonicalised its address may
// still hold a zero-padded octet, so it is folded here for the in-use checks to see
// one address rather than two.
addresses.add(canonicalIpv4(address).orElse(address));
}
}
@@ -14430,10 +14446,17 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
}
}
// An explicit address is checked the way RunInstances checks its PrivateIpAddress: it must be
// one the subnet can assign, in canonical form, and no other resource may hold it. Unlike a
// launch it takes no lease on the VPC network (see requireRequestedPrivateIpFree).
String requestedIp = (privateIpAddress != null && !privateIpAddress.isBlank())
? validateRequestedPrivateIp(privateIpAddress, subnet, null, 1) : null;
synchronized (privateIpAllocationLock) {
String eniId = "eni-" + randomHex(17);
String primaryIp = (privateIpAddress != null && !privateIpAddress.isBlank())
? privateIpAddress : assignPrivateIp(region, subnetId);
if (requestedIp != null) {
requireRequestedPrivateIpFree(region, subnetId, requestedIp);
}
String primaryIp = requestedIp != null ? requestedIp : assignPrivateIp(region, subnetId);
String primaryDns = AwsRegions.ec2PrivateIpDnsName(primaryIp, region);
NetworkInterface ni = new NetworkInterface();
@@ -578,4 +578,60 @@ class Ec2NetworkInterfaceIntegrationTest {
Assertions.assertTrue(replacement.startsWith("i-"));
}
@Test
@Order(19)
void anExplicitAddressAnotherInterfaceHoldsIsRefused() {
String holder = given()
.formParam("Action", "CreateNetworkInterface")
.formParam("SubnetId", subnetId)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("CreateNetworkInterfaceResponse.networkInterface.networkInterfaceId");
String held = given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("NetworkInterfaceId.1", holder)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.extract().path("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.privateIpAddress");
given()
.formParam("Action", "CreateNetworkInterface")
.formParam("SubnetId", subnetId)
.formParam("PrivateIpAddress", held)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidIPAddress.InUse"))
.body("Response.Errors.Error.Message", equalTo("Address " + held + " is in use."));
given()
.formParam("Action", "DescribeNetworkInterfaces")
.formParam("Filter.1.Name", "private-ip-address")
.formParam("Filter.1.Value.1", held)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200)
.body("DescribeNetworkInterfacesResponse.networkInterfaceSet.item.networkInterfaceId",
equalTo(holder));
given()
.formParam("Action", "DeleteNetworkInterface")
.formParam("NetworkInterfaceId", holder)
.header("Authorization", AUTH_HEADER)
.when()
.post("/")
.then()
.statusCode(200);
}
}
@@ -476,9 +476,12 @@ class Ec2ServiceTest {
@Test
void subnetAvailableAddressesTrackAllocationsAndRelease() {
AccountAwareStorageBackend<NetworkInterface> interfaceStore =
AccountAwareStorageBackend.inMemory("000000000000");
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory(Map.of("ec2-network-interfaces.json", interfaceStore)));
String region = "us-east-1";
String vpcId = service.createVpc(region, "10.97.0.0/16", false).getVpcId();
Subnet small = service.createSubnet(region, vpcId, "10.97.0.0/28", region + "a");
@@ -502,8 +505,13 @@ class Ec2ServiceTest {
assertEquals(251, service.describeSubnets(region, List.of(large.getSubnetId()), Map.of())
.getFirst().getAvailableIpAddressCount());
// Legacy records can contain invalid addresses; they do not consume usable subnet space.
service.createNetworkInterface(region, small.getSubnetId(), "legacy-addresses",
"10.98.0.4", List.of("10.97.0.0", "10.97.0.15"), List.of(), List.of());
// CreateNetworkInterface now refuses an out-of-subnet primary, so the record is persisted
// the way an older build left it.
NetworkInterface legacy = service.createNetworkInterface(region, small.getSubnetId(), "legacy-addresses",
null, List.of("10.97.0.0", "10.97.0.15"), List.of(), List.of());
legacy.setPrivateIpAddress("10.98.0.4");
legacy.getPrivateIpAddresses().getFirst().setPrivateIpAddress("10.98.0.4");
interfaceStore.put(region + "::" + legacy.getNetworkInterfaceId(), legacy);
assertEquals(11, service.describeSubnets(region, List.of(small.getSubnetId()), Map.of())
.getFirst().getAvailableIpAddressCount());
}
@@ -4203,8 +4211,8 @@ class Ec2ServiceTest {
@Test
void aZeroPaddedAddressAnInterfaceWasCreatedWithStillHoldsTheRequestedPrivateIp() {
// CreateNetworkInterface keeps its address as given, so the in-use check compares
// canonical forms or a zero-padded octet would make one address look like two.
// CreateNetworkInterface folds a zero-padded octet the way RunInstances does, so the stored
// address is the canonical one and still conflicts with a launch naming it plainly.
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
@@ -4216,10 +4224,134 @@ class Ec2ServiceTest {
() -> launchWithPrivateIp(service, subnetId, 1, "10.50.1.50"));
assertEquals("InvalidIPAddress.InUse", error.getErrorCode());
assertEquals("10.50.1.050", padded.getPrivateIpAddress());
assertEquals("10.50.1.50", padded.getPrivateIpAddress());
assertTrue(instancesIn(service, subnetId).isEmpty(), "a rejected launch must store nothing");
}
@Test
void aLegacyInterfaceStoredWithAZeroPaddedAddressStillHoldsItsPlainForm() {
// An interface persisted before CreateNetworkInterface canonicalised its address can still
// carry a zero-padded octet, so the in-use checks must fold it.
AccountAwareStorageBackend<NetworkInterface> interfaceStore =
AccountAwareStorageBackend.inMemory("000000000000");
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory(Map.of("ec2-network-interfaces.json", interfaceStore)));
String subnetId = privateIpSubnet(service);
NetworkInterface legacy = service.createNetworkInterface("us-east-1", subnetId, "legacy", null,
List.of(), List.of(), List.of());
legacy.setPrivateIpAddress("10.50.1.050");
legacy.getPrivateIpAddresses().getFirst().setPrivateIpAddress("10.50.1.050");
interfaceStore.put("us-east-1::" + legacy.getNetworkInterfaceId(), legacy);
assertEquals("InvalidIPAddress.InUse", assertThrows(AwsException.class, () -> service.createNetworkInterface(
"us-east-1", subnetId, "clash", "10.50.1.50", List.of(), List.of(), List.of())).getErrorCode());
assertEquals("InvalidIPAddress.InUse", assertThrows(AwsException.class,
() -> launchWithPrivateIp(service, subnetId, 1, "10.50.1.50")).getErrorCode());
}
@Test
void aDeletedInterfacesExplicitAddressGoesBackToTheVpcNetworksAllocator() {
// An interface created with its own address takes no lease on the VPC network, so deleting
// it leaves nothing behind that would keep automatic allocation off the address.
Ec2Service service = realVpcNetworkService(new RequestContext());
String subnetId = Ec2Service.defaultSubnetId("us-east-1", "a");
service.describeSubnets("us-east-1", List.of(), Map.of());
String first = service.createNetworkInterface("us-east-1", subnetId, null, null,
List.of(), List.of(), List.of()).getPrivateIpAddress();
int dot = first.lastIndexOf('.');
String next = first.substring(0, dot + 1) + (Integer.parseInt(first.substring(dot + 1)) + 1);
String explicit = service.createNetworkInterface("us-east-1", subnetId, "explicit", next,
List.of(), List.of(), List.of()).getNetworkInterfaceId();
service.deleteNetworkInterface("us-east-1", explicit);
assertEquals(next, service.createNetworkInterface("us-east-1", subnetId, null, null,
List.of(), List.of(), List.of()).getPrivateIpAddress());
}
@Test
void createNetworkInterfaceRefusesAnExplicitAddressAnotherInterfaceHolds() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
String subnetId = privateIpSubnet(service);
String first = service.createNetworkInterface("us-east-1", subnetId, "first", "10.50.1.70",
List.of(), List.of(), List.of()).getNetworkInterfaceId();
for (String sameAddress : List.of("10.50.1.70", "10.50.1.070")) {
AwsException error = assertThrows(AwsException.class, () -> service.createNetworkInterface(
"us-east-1", subnetId, "second", sameAddress, List.of(), List.of(), List.of()));
assertEquals("InvalidIPAddress.InUse", error.getErrorCode());
assertEquals("Address 10.50.1.70 is in use.", error.getMessage());
}
assertEquals(List.of(first), service.describeNetworkInterfaces("us-east-1", List.of(),
Map.of("subnet-id", List.of(subnetId))).networkInterfaces().stream()
.map(NetworkInterface::getNetworkInterfaceId).toList());
}
@Test
void createNetworkInterfaceRefusesAnExplicitAddressAnInstanceHolds() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
String subnetId = privateIpSubnet(service);
launchWithPrivateIp(service, subnetId, 1, "10.50.1.50");
String assigned = launchAddresses(service, subnetId, 1).getFirst();
for (String taken : List.of("10.50.1.50", assigned)) {
AwsException error = assertThrows(AwsException.class, () -> service.createNetworkInterface(
"us-east-1", subnetId, "clash", taken, List.of(), List.of(), List.of()));
assertEquals("InvalidIPAddress.InUse", error.getErrorCode());
}
}
@Test
void createNetworkInterfaceRefusesAnExplicitAddressTheSubnetCannotAssign() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
String subnetId = privateIpSubnet(service);
for (String unassignable : List.of("10.50.2.10", "10.50.1.1", "10.50.1.255", "not-an-ip")) {
AwsException error = assertThrows(AwsException.class, () -> service.createNetworkInterface(
"us-east-1", subnetId, "bad", unassignable, List.of(), List.of(), List.of()));
assertEquals("InvalidParameterValue", error.getErrorCode(), unassignable);
}
}
@Test
void anExplicitAddressADeletedInterfaceHeldCanBeTakenAgain() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
String subnetId = privateIpSubnet(service);
String first = service.createNetworkInterface("us-east-1", subnetId, "first", "10.50.1.70",
List.of(), List.of(), List.of()).getNetworkInterfaceId();
service.deleteNetworkInterface("us-east-1", first);
assertEquals("10.50.1.70", service.createNetworkInterface("us-east-1", subnetId, "again", "10.50.1.70",
List.of(), List.of(), List.of()).getPrivateIpAddress());
}
@Test
void anAddressPickedForAnInterfaceStepsAroundAnExplicitOne() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory());
String subnetId = privateIpSubnet(service);
// A fresh subnet hands out .10, .11, .12 on its own.
service.createNetworkInterface("us-east-1", subnetId, "explicit", "10.50.1.11",
List.of(), List.of(), List.of());
assertEquals("10.50.1.10", service.createNetworkInterface("us-east-1", subnetId, null, null,
List.of(), List.of(), List.of()).getPrivateIpAddress());
assertEquals("10.50.1.12", service.createNetworkInterface("us-east-1", subnetId, null, null,
List.of(), List.of(), List.of()).getPrivateIpAddress());
}
@Test
void aRequestedPrivateIpNeedsASingleInstanceThatCreatesItsOwnInterface() {
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),