feat(ec2): back each VPC with a real Docker network in RFC 1918 space (#3272)

* feat(ec2): back each VPC with a real Docker network in RFC 1918 space

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Replaced with colons and commas. Wording is otherwise unchanged, and the em dashes
already present in these files are left alone: they predate this branch, and
rewriting them here would bury the actual change in unrelated churn.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-09 18:12:40 -05:00
1 parent 4cb9314a2d
commit cf1aabce39
13 files changed
+2281 -20

No files matched your search

@@ -11,6 +11,8 @@ import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectExecCmd;
import com.github.dockerjava.api.command.InspectExecResponse;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.command.StartContainerCmd;
import com.github.dockerjava.api.exception.DockerException;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.Frame;
@@ -18,6 +20,7 @@ import com.github.dockerjava.api.model.StreamType;
import java.nio.charset.StandardCharsets;
import com.github.dockerjava.api.model.NetworkSettings;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.ec2.net.VpcNetworkManager;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
@@ -65,6 +68,7 @@ import static org.mockito.Answers.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.after;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
@@ -153,7 +157,8 @@ class Ec2ContainerManagerTest {
metadataServer,
mock(Ec2PortForwardManager.class),
mock(RegionResolver.class),
mock(ContainerNetworkReachability.class));
mock(ContainerNetworkReachability.class),
mock(VpcNetworkManager.class));
Instance instance = new Instance();
instance.setInstanceId("i-restored");
@@ -168,6 +173,154 @@ class Ec2ContainerManagerTest {
verify(metadataServer).registerContainer("192.168.215.42", "i-restored", instance);
}
@Test
void restoreMetadataRegistrationAlsoRegistersTheAddressImdsRequestsArriveFrom() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
DockerClient dockerClient = mock(DockerClient.class);
InspectContainerResponse response = vpcAttachedInspectResponse("10.0.1.10", "172.17.0.4");
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
when(dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
when(inspect.exec()).thenReturn(response);
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
Ec2ContainerManager manager = managerWith(lifecycleManager, dockerClient, metadataServer);
Instance instance = new Instance();
instance.setInstanceId("i-vpc-restored");
instance.setDockerContainerId(TEST_CONTAINER_ID);
instance.setContainerBridgeIp("10.0.1.10");
instance.setImdsSourceIp("172.17.0.2");
assertTrue(manager.restoreMetadataRegistration(instance));
// The VPC address is what Floci reports, but the container's default route is the bridge,
// so that is the source address Ec2MetadataServer resolves the instance by.
verify(metadataServer).registerContainer("10.0.1.10", "i-vpc-restored", instance);
verify(metadataServer).registerContainer("172.17.0.4", "i-vpc-restored", instance);
verify(metadataServer).unregisterContainer("172.17.0.2", instance);
assertEquals("172.17.0.4", instance.getImdsSourceIp());
}
@Test
void restoreMetadataRegistrationLeavesABridgeOnlyInstanceWithNoSeparateImdsSource() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
DockerClient dockerClient = mock(DockerClient.class);
InspectContainerResponse response = inspectResponse("172.17.0.4");
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
when(dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
when(inspect.exec()).thenReturn(response);
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
Ec2ContainerManager manager = managerWith(lifecycleManager, dockerClient, metadataServer);
Instance instance = new Instance();
instance.setInstanceId("i-bridge-only");
instance.setDockerContainerId(TEST_CONTAINER_ID);
instance.setContainerBridgeIp("172.17.0.4");
assertTrue(manager.restoreMetadataRegistration(instance));
assertNull(instance.getImdsSourceIp(), "one address means one registration");
verify(metadataServer).registerContainer("172.17.0.4", "i-bridge-only", instance);
verify(metadataServer, never()).unregisterContainer(anyString(), any(Instance.class));
}
@Test
void restoreMetadataRegistrationKeepsTheImdsSourceWhenTheContainerCannotBeInspected() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
DockerClient dockerClient = mock(DockerClient.class);
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
when(dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
when(inspect.exec()).thenThrow(new DockerException("dial unix /var/run/docker.sock: EOF", 500));
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
Ec2ContainerManager manager = managerWith(lifecycleManager, dockerClient, metadataServer);
Instance instance = new Instance();
instance.setInstanceId("i-inspect-failed");
instance.setDockerContainerId(TEST_CONTAINER_ID);
instance.setContainerBridgeIp("10.0.1.10");
instance.setImdsSourceIp("172.17.0.4");
assertTrue(manager.restoreMetadataRegistration(instance));
// A failed inspect leaves the bridge attachment unknown, not known to be absent. Tearing
// the registration down here would stop this healthy instance's metadata requests
// resolving, with nothing registered in place of what was removed.
verify(metadataServer, never()).unregisterContainer("172.17.0.4", instance);
assertEquals("172.17.0.4", instance.getImdsSourceIp(),
"a transient Docker failure must not drop an existing IMDS source registration");
}
@Test
void startRegistersTheNewBridgeAddressDockerHandsOutOnRestart() throws Exception {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
DockerClient dockerClient = mock(DockerClient.class);
when(dockerClient.startContainerCmd(TEST_CONTAINER_ID))
.thenReturn(mock(StartContainerCmd.class, RETURNS_SELF));
// The VPC address is static, so it survives the stop; the bridge address does not.
InspectContainerResponse response = vpcAttachedInspectResponse("10.0.1.10", "172.17.0.9");
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
when(dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
when(inspect.exec()).thenReturn(response);
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
Ec2ContainerManager manager = managerWith(lifecycleManager, dockerClient, metadataServer);
Instance instance = new Instance();
instance.setInstanceId("i-vpc-started");
instance.setDockerContainerId(TEST_CONTAINER_ID);
instance.setContainerBridgeIp("10.0.1.10");
instance.setImdsSourceIp("172.17.0.4");
manager.start(instance);
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(5));
verify(metadataServer, timeout(2000)).registerContainer("172.17.0.9", "i-vpc-started", instance);
verify(metadataServer, timeout(2000)).unregisterContainer("172.17.0.4", instance);
assertEquals("172.17.0.9", instance.getImdsSourceIp(),
"the stale address would otherwise stay registered while IMDS requests arrive "
+ "from an address nothing knows about");
}
private static Ec2ContainerManager managerWith(ContainerLifecycleManager lifecycleManager,
DockerClient dockerClient,
Ec2MetadataServer metadataServer) {
return new Ec2ContainerManager(
mock(ContainerBuilder.class),
lifecycleManager,
mock(ContainerLogStreamer.class),
mock(ContainerDetector.class),
mock(DockerHostResolver.class),
dockerClient,
mock(PortAllocator.class),
mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
metadataServer,
mock(Ec2PortForwardManager.class),
mock(RegionResolver.class),
mock(ContainerNetworkReachability.class),
mock(VpcNetworkManager.class));
}
/** A container on both its VPC network and the default bridge, which is what launch leaves. */
private static InspectContainerResponse vpcAttachedInspectResponse(String vpcIp, String bridgeIp) {
InspectContainerResponse inspect = mock(InspectContainerResponse.class);
NetworkSettings networkSettings = mock(NetworkSettings.class);
when(inspect.getNetworkSettings()).thenReturn(networkSettings);
when(networkSettings.getNetworks()).thenReturn(Map.of(
"floci-vpc-4566-us-west-2-vpc-1", new ContainerNetwork().withIpv4Address(vpcIp),
"bridge", new ContainerNetwork().withIpv4Address(bridgeIp)));
return inspect;
}
@Test
void userDataExecutionCommandRunsScriptDirectlySoShebangIsHonored() {
assertArrayEquals(new String[]{"/tmp/user-data.sh"}, Ec2ContainerManager.userDataExecutionCommand());
@@ -418,7 +571,8 @@ class Ec2ContainerManagerTest {
mock(Ec2MetadataServer.class),
mock(Ec2PortForwardManager.class),
mock(RegionResolver.class),
reachability);
reachability,
mock(VpcNetworkManager.class));
}
@Test
@@ -438,6 +592,53 @@ class Ec2ContainerManagerTest {
assertTrue(Ec2ContainerManager.userDataShellScripts(userData).isEmpty());
}
@Test
void launchReturnsTheLeaseWhenTheContainerNeverJoinsTheVpcNetwork() throws Exception {
Ec2ContainerManager.containerBridgeIpAttempts = 2;
Ec2ContainerManager.containerBridgeIpPollMillis = 1;
LaunchHarness harness = launchHarness();
InspectContainerResponse noIp = inspectResponse(null);
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
when(inspect.exec()).thenReturn(noIp);
// attach() returns empty: nothing holds the address, and the instance is about to start
// reporting its bridge address instead, so the lease is no longer findable from it.
Instance instance = leasedInstance("i-noattach");
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
awaitUntil(() -> "terminated".equals(instance.getState().getName()), Duration.ofSeconds(2));
verify(harness.vpcNetworkManager, timeout(2000).atLeastOnce())
.releasePrivateIp("us-west-2", "subnet-lease", "10.0.1.10");
}
@Test
void launchReturnsTheLeaseWhenTheLaunchThrows() throws Exception {
LaunchHarness harness = launchHarness();
when(harness.builder.build()).thenThrow(new IllegalStateException("daemon went away"));
Instance instance = leasedInstance("i-throws");
harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2");
awaitUntil(() -> "terminated".equals(instance.getState().getName()), Duration.ofSeconds(2));
// Detach before release: Docker holds the address while the endpoint stands, so handing it
// to the next launch before disconnecting would have the daemon refuse it.
verify(harness.vpcNetworkManager, timeout(2000)).detach("us-west-2", "vpc-lease", null);
verify(harness.vpcNetworkManager, timeout(2000))
.releasePrivateIp("us-west-2", "subnet-lease", "10.0.1.10");
}
private static Instance leasedInstance(String instanceId) {
Instance instance = instance(instanceId);
instance.setRegion("us-west-2");
instance.setVpcId("vpc-lease");
instance.setSubnetId("subnet-lease");
instance.setPrivateIpAddress("10.0.1.10");
return instance;
}
@Test
void launchInstanceUserDataStreamToCloudWatch() throws Exception {
LaunchHarness harness = launchHarness();
@@ -1078,6 +1279,7 @@ class Ec2ContainerManagerTest {
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
Ec2PortForwardManager portForwardManager = mock(Ec2PortForwardManager.class);
VpcNetworkManager vpcNetworkManager = mock(VpcNetworkManager.class);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
Ec2ContainerManager manager = executor == null
@@ -1093,7 +1295,8 @@ class Ec2ContainerManagerTest {
metadataServer,
portForwardManager,
regionResolver,
mock(ContainerNetworkReachability.class))
mock(ContainerNetworkReachability.class),
vpcNetworkManager)
: new Ec2ContainerManager(
containerBuilder,
lifecycleManager,
@@ -1107,10 +1310,11 @@ class Ec2ContainerManagerTest {
portForwardManager,
regionResolver,
mock(ContainerNetworkReachability.class),
vpcNetworkManager,
executor,
userDataTimeout);
return new LaunchHarness(manager, lifecycleManager, dockerClient, metadataServer, logStreamer, builder,
portAllocator, portForwardManager, config, new CopyOnWriteArrayList<>());
portAllocator, portForwardManager, config, vpcNetworkManager, new CopyOnWriteArrayList<>());
}
// ── startup reconciliation of EC2 containers orphaned by a previous run ──────
@@ -1401,6 +1605,7 @@ class Ec2ContainerManagerTest {
PortAllocator portAllocator,
Ec2PortForwardManager portForwardManager,
EmulatorConfig config,
VpcNetworkManager vpcNetworkManager,
List<String[]> executedCommands) {
void stubSuccessfulExecs(CountDownLatch userDataStarted, CountDownLatch finishUserData) throws Exception {
AtomicReference<String[]> currentCommand = new AtomicReference<>();
@@ -19,6 +19,7 @@ import io.github.hectorvent.floci.services.ec2.model.KeyPair;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
import io.github.hectorvent.floci.services.ec2.net.VpcNetworkManager;
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;
@@ -64,6 +65,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -1207,6 +1209,59 @@ class Ec2ServiceTest {
assertNotNull(attached.getEbs().getSnapshotId());
}
@Test
void restoreReReservesThePrivateAddressesOfInstancesThatSurvivedTheRestart() {
// The lease table is in-memory, so a restart rebuilds it empty while the containers of
// persisted instances still hold their addresses. Without the re-reservation the next
// RunInstances is handed an address a live container already answers on.
AccountAwareStorageBackend<Instance> instanceStore = AccountAwareStorageBackend.inMemory("000000000000");
instanceStore.put("us-east-1::i-alive", persistedInstance("i-alive", "10.0.1.10", InstanceState.running()));
instanceStore.put("us-east-1::i-gone", persistedInstance("i-gone", "10.0.1.11", InstanceState.terminated()));
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
when(vpcNetworks.enabled()).thenReturn(true);
Ec2Service service = new Ec2Service(mockConfig(false), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory(Map.of("ec2-instances.json", instanceStore)), vpcNetworks);
service.restoreMetadataRegistrations();
verify(vpcNetworks).reservePrivateIp("us-east-1", "subnet-a", "10.0.1.10");
verify(vpcNetworks, never()).reservePrivateIp("us-east-1", "subnet-a", "10.0.1.11");
}
@Test
void restoreSurvivesAnAddressItCannotReserve() {
AccountAwareStorageBackend<Instance> instanceStore = AccountAwareStorageBackend.inMemory("000000000000");
instanceStore.put("us-east-1::i-one", persistedInstance("i-one", "10.0.1.10", InstanceState.running()));
instanceStore.put("us-east-1::i-two", persistedInstance("i-two", "10.0.1.10", InstanceState.running()));
VpcNetworkManager vpcNetworks = mock(VpcNetworkManager.class);
when(vpcNetworks.enabled()).thenReturn(true);
// Second claim on the same address is refused; startup must not abort over it.
when(vpcNetworks.reservePrivateIp(anyString(), anyString(), anyString()))
.thenReturn(true).thenReturn(false);
Ec2Service service = new Ec2Service(mockConfig(false), mock(Ec2ContainerManager.class),
mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class),
new Ec2InstanceTypeCatalog(),
new InMemoryStorageFactory(Map.of("ec2-instances.json", instanceStore)), vpcNetworks);
assertDoesNotThrow(service::restoreMetadataRegistrations);
verify(vpcNetworks, times(2)).reservePrivateIp("us-east-1", "subnet-a", "10.0.1.10");
}
private static Instance persistedInstance(String instanceId, String privateIp, InstanceState state) {
Instance instance = new Instance();
instance.setInstanceId(instanceId);
instance.setRegion("us-east-1");
instance.setVpcId("vpc-a");
instance.setSubnetId("subnet-a");
instance.setPrivateIpAddress(privateIp);
instance.setState(state);
return instance;
}
private static String runOne(Ec2Service service, String imageId) {
return service.runInstances("us-east-1", imageId, "t3.micro", 1, 1, null,
List.of(), null, null, List.of(), null, null)
@@ -0,0 +1,69 @@
package io.github.hectorvent.floci.services.ec2.net;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class Cidr4Test {
@Test
void parsesAndNormalisesToTheNetworkAddress() {
assertEquals("10.0.1.0/24", Cidr4.parse("10.0.1.37/24").orElseThrow().toString());
assertEquals(256L, Cidr4.parse("10.0.1.0/24").orElseThrow().size());
assertEquals("10.0.1.255", Cidr4.format(Cidr4.parse("10.0.1.0/24").orElseThrow().broadcast()));
}
@Test
void rejectsMalformedInput() {
for (String bad : new String[]{null, "", "10.0.0.0", "10.0.0.0/33", "10.0.0.256/24", "not-a-cidr"}) {
assertEquals(Optional.empty(), Cidr4.parse(bad), "should reject " + bad);
}
}
@Test
void recognisesTheThreeRfc1918Ranges() {
assertTrue(Cidr4.parse("10.0.0.0/16").orElseThrow().isRfc1918());
assertTrue(Cidr4.parse("172.16.0.0/12").orElseThrow().isRfc1918());
assertTrue(Cidr4.parse("172.31.0.0/16").orElseThrow().isRfc1918());
assertTrue(Cidr4.parse("192.168.215.0/24").orElseThrow().isRfc1918());
assertFalse(Cidr4.parse("172.15.0.0/16").orElseThrow().isRfc1918());
assertFalse(Cidr4.parse("172.32.0.0/16").orElseThrow().isRfc1918());
assertFalse(Cidr4.parse("11.0.0.0/8").orElseThrow().isRfc1918());
assertFalse(Cidr4.parse("100.64.0.0/10").orElseThrow().isRfc1918(), "carrier-grade NAT is not RFC 1918");
assertFalse(Cidr4.parse("0.0.0.0/0").orElseThrow().isRfc1918());
}
@Test
void containmentAndOverlapAreExactAtTheBoundaries() {
Cidr4 vpc = Cidr4.parse("10.0.0.0/16").orElseThrow();
assertTrue(vpc.contains(Cidr4.parse("10.0.255.0/24").orElseThrow()));
assertFalse(vpc.contains(Cidr4.parse("10.1.0.0/24").orElseThrow()));
assertFalse(vpc.contains(Cidr4.parse("10.0.0.0/8").orElseThrow()), "a supernet is not contained");
assertTrue(vpc.overlaps(Cidr4.parse("10.0.0.0/8").orElseThrow()));
assertFalse(vpc.overlaps(Cidr4.parse("10.1.0.0/16").orElseThrow()));
}
@Test
void comparesCorrectlyAboveTheSignedIntBoundary() {
// 192.168.x as an int is negative; arithmetic that forgot to widen breaks exactly here.
Cidr4 orbstack = Cidr4.parse("192.168.215.0/24").orElseThrow();
assertTrue(orbstack.overlaps(Cidr4.parse("192.168.0.0/16").orElseThrow()));
assertFalse(orbstack.overlaps(Cidr4.parse("192.168.216.0/24").orElseThrow()));
assertEquals("192.168.215.10", orbstack.addressAt(10).orElseThrow());
}
@Test
void addressAtStaysInsideTheBlock() {
Cidr4 subnet = Cidr4.parse("10.0.1.0/24").orElseThrow();
assertEquals("10.0.1.10", subnet.addressAt(10).orElseThrow());
assertEquals("10.0.1.255", subnet.addressAt(255).orElseThrow());
assertEquals(Optional.empty(), subnet.addressAt(256));
assertEquals(Optional.empty(), subnet.addressAt(-1));
}
}
@@ -0,0 +1,497 @@
package io.github.hectorvent.floci.services.ec2.net;
import io.github.hectorvent.floci.config.EmulatorConfig;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ConnectToNetworkCmd;
import com.github.dockerjava.api.command.CreateNetworkCmd;
import com.github.dockerjava.api.command.CreateNetworkResponse;
import com.github.dockerjava.api.command.DisconnectFromNetworkCmd;
import com.github.dockerjava.api.command.InspectNetworkCmd;
import com.github.dockerjava.api.command.ListNetworksCmd;
import com.github.dockerjava.api.command.RemoveNetworkCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Network;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class VpcNetworkManagerTest {
private static final String REGION = "us-east-1";
private DockerClient docker;
private EmulatorConfig config;
private VpcNetworkManager manager;
private List<Network> existingNetworks;
private List<String> removedNetworks;
@BeforeEach
void setUp() {
existingNetworks = new ArrayList<>();
removedNetworks = new ArrayList<>();
docker = mock(DockerClient.class);
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.port()).thenReturn(4650);
when(config.services().ec2().mock()).thenReturn(false);
when(config.services().ec2().vpcNetworks().enabled()).thenReturn(true);
when(config.services().ec2().vpcNetworks().fallbackPool()).thenReturn("10.240.0.0/12");
when(config.services().ec2().vpcNetworks().fallbackPrefixLength()).thenReturn(16);
when(config.services().ec2().vpcNetworks().reconcileOnStartup()).thenReturn(true);
when(config.services().ec2().vpcNetworks().driver()).thenReturn("bridge");
when(config.docker().extraLabels()).thenReturn(List.of());
when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
ListNetworksCmd list = mock(ListNetworksCmd.class, RETURNS_SELF);
when(list.exec()).thenAnswer(invocation -> List.copyOf(existingNetworks));
when(docker.listNetworksCmd()).thenReturn(list);
// Inspect resolves against the same fixture list, so a network with live endpoints can be
// told apart from one that does not exist yet.
when(docker.inspectNetworkCmd()).thenAnswer(listCall -> {
InspectNetworkCmd inspect = mock(InspectNetworkCmd.class);
String[] requested = new String[1];
when(inspect.withNetworkId(anyString())).thenAnswer(call -> {
requested[0] = call.getArgument(0);
return inspect;
});
when(inspect.exec()).thenAnswer(call -> existingNetworks.stream()
.filter(n -> n.getId().equals(requested[0]) || n.getName().equals(requested[0]))
.findFirst()
.orElseThrow(() -> new NotFoundException("no such network")));
return inspect;
});
CreateNetworkCmd create = mock(CreateNetworkCmd.class, RETURNS_SELF);
when(create.exec()).thenReturn(new CreateNetworkResponse());
when(docker.createNetworkCmd()).thenReturn(create);
ConnectToNetworkCmd connect = mock(ConnectToNetworkCmd.class, RETURNS_SELF);
when(docker.connectToNetworkCmd()).thenReturn(connect);
when(docker.disconnectFromNetworkCmd())
.thenReturn(mock(DisconnectFromNetworkCmd.class, RETURNS_SELF));
when(docker.removeNetworkCmd(anyString())).thenAnswer(invocation -> {
removedNetworks.add(invocation.getArgument(0));
return mock(RemoveNetworkCmd.class, RETURNS_SELF);
});
manager = new VpcNetworkManager(config, docker);
}
private void existingNetwork(String name, String subnet, Map<String, String> labels) {
existingNetwork(name, subnet, labels, Map.of());
}
private void existingNetwork(String name, String subnet, Map<String, String> labels,
Map<String, Network.ContainerNetworkConfig> containers) {
Network network = mock(Network.class);
when(network.getContainers()).thenReturn(containers);
when(network.getName()).thenReturn(name);
when(network.getId()).thenReturn(name);
when(network.getLabels()).thenReturn(labels);
when(network.getIpam()).thenReturn(new Network.Ipam()
.withConfig(new Network.Ipam.Config().withSubnet(subnet)));
existingNetworks.add(network);
}
// ─── The ordinary case: the declared CIDR is what the instance gets ───────
@Test
void usesTheDeclaredCidrAndAllocatesInsideTheDeclaredSubnet() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
assertFalse(manager.isSubstituted(REGION, "vpc-1"));
assertEquals("10.0.0.0/16", manager.effectiveVpcCidr(REGION, "vpc-1").orElseThrow());
assertEquals("10.0.1.0/24", manager.effectiveSubnetCidr(REGION, "subnet-a").orElseThrow());
Cidr4 declared = Cidr4.parse("10.0.1.0/24").orElseThrow();
for (int i = 0; i < 5; i++) {
String address = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow();
long value = Cidr4.parse(address + "/32").orElseThrow().network();
assertTrue(declared.containsAddress(value), address + " should be inside 10.0.1.0/24");
assertNotEquals("10.0.1.0", address, "never the network address");
assertNotEquals("10.0.1.1", address, "never the Docker gateway");
}
}
@Test
void handsOutADistinctAddressEachTime() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
String first = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow();
String second = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow();
assertNotEquals(first, second);
}
@Test
void aReleasedAddressIsHandedOutAgainRatherThanExhaustingTheSubnet() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-tiny", "10.0.9.0/28");
List<String> allocated = new ArrayList<>();
Optional<String> next;
while ((next = manager.allocatePrivateIp(REGION, "subnet-tiny")).isPresent()) {
allocated.add(next.get());
}
assertTrue(allocated.size() >= 4, "a /28 should yield several usable addresses");
assertTrue(manager.allocatePrivateIp(REGION, "subnet-tiny").isEmpty(), "and then be exhausted");
manager.releasePrivateIp(REGION, "subnet-tiny", allocated.get(0));
assertEquals(allocated.get(0), manager.allocatePrivateIp(REGION, "subnet-tiny").orElseThrow(),
"a terminated instance's address must come back into circulation");
}
// ─── Restart: addresses persisted instances still hold ───────────────────
@Test
void aReservedAddressIsNeverHandedOutAgain() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
// What a restart looks like: the lease table is empty, but a live container holds .10.
assertTrue(manager.reservePrivateIp(REGION, "subnet-a", "10.0.1.10"));
for (int i = 0; i < 20; i++) {
assertNotEquals("10.0.1.10", manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow(),
"the address a restored instance still holds must not be re-allocated");
}
}
@Test
void reservingTheSameAddressTwiceRefusesTheSecondClaimWithoutThrowing() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
assertTrue(manager.reservePrivateIp(REGION, "subnet-a", "10.0.1.11"));
assertFalse(manager.reservePrivateIp(REGION, "subnet-a", "10.0.1.11"),
"two instances claiming one address is reported, not thrown");
}
@Test
void reservingAnAddressOutsideTheSubnetRangeRefusesWithoutThrowing() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
assertFalse(manager.reservePrivateIp(REGION, "subnet-a", "172.31.4.9"),
"an address from a range this subnet no longer uses cannot be reserved");
assertFalse(manager.reservePrivateIp(REGION, "subnet-a", "not-an-address"));
assertFalse(manager.reservePrivateIp(REGION, "subnet-unknown", "10.0.1.10"),
"a subnet with no Docker-backed range has nothing to reserve in");
// None of that poisoned the pool.
assertTrue(manager.allocatePrivateIp(REGION, "subnet-a").isPresent());
}
@Test
void aReservedAddressComesBackAfterRelease() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-tiny", "10.0.9.0/28");
assertTrue(manager.reservePrivateIp(REGION, "subnet-tiny", "10.0.9.10"));
manager.releasePrivateIp(REGION, "subnet-tiny", "10.0.9.10");
List<String> allocated = new ArrayList<>();
Optional<String> next;
while ((next = manager.allocatePrivateIp(REGION, "subnet-tiny")).isPresent()) {
allocated.add(next.get());
}
assertTrue(allocated.contains("10.0.9.10"),
"a terminated restored instance's address must return to circulation");
}
@Test
void subnetsInTheSameVpcGetDisjointRangesOnOneNetwork() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
manager.declareSubnet(REGION, "vpc-1", "subnet-b", "10.0.2.0/24");
assertEquals("10.0.1.0/24", manager.effectiveSubnetCidr(REGION, "subnet-a").orElseThrow());
assertEquals("10.0.2.0/24", manager.effectiveSubnetCidr(REGION, "subnet-b").orElseThrow());
// Same VPC, so the same Docker network: subnets inside a VPC route to each other in AWS.
assertEquals(manager.networkNameFor(REGION, "vpc-1"), manager.networkNameFor(REGION, "vpc-1"));
}
// ─── The three substitution triggers ─────────────────────────────────────
@Test
void substitutesWhenTheDeclaredCidrIsOutsideRfc1918() {
manager.declareVpc(REGION, "vpc-public", "54.0.0.0/16");
assertTrue(manager.isSubstituted(REGION, "vpc-public"));
Cidr4 effective = Cidr4.parse(manager.effectiveVpcCidr(REGION, "vpc-public").orElseThrow()).orElseThrow();
assertTrue(effective.isRfc1918());
assertTrue(Cidr4.parse("10.240.0.0/12").orElseThrow().contains(effective));
}
@Test
void substitutesWhenNoCidrIsDeclared() {
manager.declareVpc(REGION, "vpc-blank", null);
assertTrue(manager.isSubstituted(REGION, "vpc-blank"));
assertTrue(manager.effectiveVpcCidr(REGION, "vpc-blank").isPresent());
}
@Test
void substitutesWhenTheDeclaredCidrCollidesWithAnExistingDockerNetwork() {
// OrbStack's default bridge on this machine.
existingNetwork("orbstack", "192.168.215.0/24", Map.of());
manager.declareVpc(REGION, "vpc-clash", "192.168.215.0/24");
assertTrue(manager.isSubstituted(REGION, "vpc-clash"));
Cidr4 effective = Cidr4.parse(manager.effectiveVpcCidr(REGION, "vpc-clash").orElseThrow()).orElseThrow();
assertFalse(effective.overlaps(Cidr4.parse("192.168.215.0/24").orElseThrow()));
}
@Test
void twoVpcsMayDeclareTheSameCidrAndBothKeepWorking() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-1", "10.0.1.0/24");
manager.declareVpc(REGION, "vpc-2", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-2", "subnet-2", "10.0.1.0/24");
assertFalse(manager.isSubstituted(REGION, "vpc-1"), "the first claim keeps the declared range");
assertTrue(manager.isSubstituted(REGION, "vpc-2"), "the second is substituted, not rejected");
Cidr4 first = Cidr4.parse(manager.effectiveVpcCidr(REGION, "vpc-1").orElseThrow()).orElseThrow();
Cidr4 second = Cidr4.parse(manager.effectiveVpcCidr(REGION, "vpc-2").orElseThrow()).orElseThrow();
assertFalse(first.overlaps(second));
// Both still allocate: a duplicate CIDR must not leave a VPC unusable.
String a = manager.allocatePrivateIp(REGION, "subnet-1").orElseThrow();
String b = manager.allocatePrivateIp(REGION, "subnet-2").orElseThrow();
assertTrue(first.containsAddress(Cidr4.parse(a + "/32").orElseThrow().network()));
assertTrue(second.containsAddress(Cidr4.parse(b + "/32").orElseThrow().network()));
}
@Test
void aSubnetOutsideItsVpcRangeIsRemappedInsideIt() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-stray", "172.16.5.0/24");
Cidr4 effective = Cidr4.parse(manager.effectiveSubnetCidr(REGION, "subnet-stray").orElseThrow()).orElseThrow();
assertTrue(Cidr4.parse("10.0.0.0/16").orElseThrow().contains(effective),
"an address must be routable on the VPC's own network to mean anything");
}
// ─── Materialisation and attachment ──────────────────────────────────────
@Test
void createsTheNetworkWithTheEffectiveCidrOnFirstAttach() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
String address = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow();
assertTrue(manager.attach(REGION, "vpc-1", "subnet-a", "container-1", address).isPresent());
ArgumentCaptor<Network.Ipam> ipam = ArgumentCaptor.forClass(Network.Ipam.class);
verify(docker.createNetworkCmd()).withIpam(ipam.capture());
assertEquals("10.0.0.0/16", ipam.getValue().getConfig().get(0).getSubnet());
verify(docker.connectToNetworkCmd()).withContainerId("container-1");
}
@Test
void refusesToAttachAnAddressItDidNotPlan() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
// The synthesised address Ec2Service falls back to: outside the network's IPAM pool.
assertTrue(manager.attach(REGION, "vpc-1", "subnet-a", "container-1", "172.31.0.11").isEmpty());
verify(docker, never()).connectToNetworkCmd();
}
@Test
void adoptsALeftoverNetworkOnlyWhenItsSubnetIsTheOneThisVpcAllocatesFrom() {
// A Floci restart: the bridge for vpc-1 survived, on the range vpc-1 still plans from.
existingNetwork(manager.networkName(REGION, "vpc-1"), "10.0.0.0/16", ourLabels("vpc-1", "4650"));
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
String address = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow();
assertTrue(manager.attach(REGION, "vpc-1", "subnet-a", "container-1", address).isPresent());
verify(docker, never()).createNetworkCmd();
assertTrue(removedNetworks.isEmpty(), "a matching network is reused, not churned");
}
@Test
void recreatesALeftoverNetworkWhoseSubnetIsNotTheRangeThisVpcAllocatesFrom() {
// What a previous run with a different declaration leaves behind: this VPC's own network
// name, carrying a range that has nothing to do with the addresses now being handed out.
String networkName = manager.networkName(REGION, "vpc-1");
existingNetwork(networkName, "172.20.0.0/16", ourLabels("vpc-1", "4650"));
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
String address = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow();
assertTrue(Cidr4.parse("10.0.1.0/24").orElseThrow()
.containsAddress(Cidr4.parse(address + "/32").orElseThrow().network()));
assertTrue(manager.attach(REGION, "vpc-1", "subnet-a", "container-1", address).isPresent());
assertEquals(List.of(networkName), removedNetworks,
"a network routing 172.20/16 cannot carry a 10.0.1.x address, so it is not adopted");
ArgumentCaptor<Network.Ipam> ipam = ArgumentCaptor.forClass(Network.Ipam.class);
verify(docker.createNetworkCmd()).withIpam(ipam.capture());
assertEquals("10.0.0.0/16", ipam.getValue().getConfig().get(0).getSubnet(),
"the network is recreated on the range the addresses actually come from");
}
@Test
void keepsInstancesOnTheBridgeWhenAStaleNetworkCannotBeRemoved() {
String networkName = manager.networkName(REGION, "vpc-1");
existingNetwork(networkName, "172.20.0.0/16", ourLabels("vpc-1", "4650"));
when(docker.removeNetworkCmd(anyString())).thenThrow(new RuntimeException("has active endpoints"));
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
String address = manager.allocatePrivateIp(REGION, "subnet-a").orElseThrow();
assertTrue(manager.attach(REGION, "vpc-1", "subnet-a", "container-1", address).isEmpty(),
"an unreachable private IP is a documented degradation; an address the network "
+ "does not route is a wrong answer");
verify(docker, never()).connectToNetworkCmd();
}
// ─── Small blocks: usable, or refused out loud ───────────────────────────
@Test
void aSubnetTooSmallForTenAddressesOfHeadroomStillAllocates() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
// A /29 holds eight addresses in total, so the usual .10 offset falls off the end of it.
manager.declareSubnet(REGION, "vpc-1", "subnet-tiny", "10.0.9.0/29");
assertEquals("10.0.9.0/29", manager.effectiveSubnetCidr(REGION, "subnet-tiny").orElseThrow());
List<String> allocated = new ArrayList<>();
Optional<String> next;
while ((next = manager.allocatePrivateIp(REGION, "subnet-tiny")).isPresent()) {
allocated.add(next.get());
}
assertEquals(List.of("10.0.9.2", "10.0.9.3", "10.0.9.4", "10.0.9.5", "10.0.9.6"), allocated,
"past the network address and the Docker gateway, and short of the broadcast address");
}
@Test
void aSubnetWithNoRoomForAnyHostIsRefusedRatherThanAllocatingNothing() {
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-nothing", "10.0.9.0/31");
assertTrue(manager.effectiveSubnetCidr(REGION, "subnet-nothing").isEmpty(),
"a subnet that can never hand out an address must not claim a Docker-backed range: "
+ "the caller has to fall back rather than read empty as exhaustion");
assertTrue(manager.allocatePrivateIp(REGION, "subnet-nothing").isEmpty());
}
@Test
void anUnusableFallbackPrefixLengthIsClampedToOneThatCanServeHosts() {
// Nothing bounds this config value, and a /30 block has no room for an instance at all.
when(config.services().ec2().vpcNetworks().fallbackPrefixLength()).thenReturn(30);
manager.declareVpc(REGION, "vpc-public", "54.0.0.0/16");
manager.declareSubnet(REGION, "vpc-public", "subnet-a", "54.0.1.0/24");
Cidr4 effective = Cidr4.parse(manager.effectiveVpcCidr(REGION, "vpc-public").orElseThrow()).orElseThrow();
assertTrue(effective.prefix() <= VpcNetworkManager.MAX_ALLOCATABLE_PREFIX,
"a configured-but-unusable prefix must not leave every substituted VPC empty");
assertTrue(manager.allocatePrivateIp(REGION, "subnet-a").isPresent(),
"the substituted VPC has to be able to hand out an address");
}
@Test
void doesNothingWhenDisabled() {
when(config.services().ec2().vpcNetworks().enabled()).thenReturn(false);
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
manager.declareSubnet(REGION, "vpc-1", "subnet-a", "10.0.1.0/24");
assertTrue(manager.allocatePrivateIp(REGION, "subnet-a").isEmpty());
assertTrue(manager.effectiveVpcCidr(REGION, "vpc-1").isEmpty());
}
// ─── Startup reconciliation ──────────────────────────────────────────────
@Test
void reconcileRemovesOnlyThisEmulatorsOwnOrphans() {
existingNetwork("floci-vpc-4650-us-east-1-vpc-dead", "10.7.0.0/16", ourLabels("vpc-dead", "4650"));
existingNetwork("floci-vpc-4650-us-east-1-vpc-live", "10.8.0.0/16", ourLabels("vpc-live", "4650"));
existingNetwork("floci-vpc-4620-us-east-1-vpc-other", "10.9.0.0/16", ourLabels("vpc-other", "4620"));
existingNetwork("some-users-network", "10.10.0.0/16", Map.of());
manager.reconcileOrphans((region, vpcId) -> "vpc-live".equals(vpcId));
assertEquals(List.of("floci-vpc-4650-us-east-1-vpc-dead"), removedNetworks,
"a live VPC keeps its network, another emulator's networks are never touched, "
+ "and networks Floci did not create are out of scope entirely");
}
@Test
void reconcileDetachesAContainerTheCrashedRunLeftOnTheNetwork() {
Map<String, Network.ContainerNetworkConfig> attached =
Map.of("container-from-a-dead-run", new Network.ContainerNetworkConfig());
existingNetwork("floci-vpc-4650-us-east-1-vpc-dead", "10.7.0.0/16",
ourLabels("vpc-dead", "4650"), attached);
manager.reconcileOrphans((region, vpcId) -> false);
// Without the disconnect Docker refuses removal with "has active endpoints", and the
// stale IPAM reservation then pushes the next run's identical CIDR into the fallback pool.
verify(docker).disconnectFromNetworkCmd();
assertEquals(List.of("floci-vpc-4650-us-east-1-vpc-dead"), removedNetworks);
}
@Test
void reconcileIsSkippedWhenTurnedOff() {
when(config.services().ec2().vpcNetworks().reconcileOnStartup()).thenReturn(false);
existingNetwork("floci-vpc-4650-us-east-1-vpc-dead", "10.7.0.0/16", ourLabels("vpc-dead", "4650"));
manager.reconcileOrphans((region, vpcId) -> false);
assertTrue(removedNetworks.isEmpty());
}
@Test
void aSurvivingNetworkForTheSameVpcIsNotReadAsACollision() {
// What a Floci restart sees: its own bridge for vpc-1 is still up.
existingNetwork(manager.networkName(REGION, "vpc-1"), "10.0.0.0/16", ourLabels("vpc-1", "4650"));
manager.declareVpc(REGION, "vpc-1", "10.0.0.0/16");
assertFalse(manager.isSubstituted(REGION, "vpc-1"),
"re-planning a VPC must not collide with that VPC's own surviving network");
assertEquals("10.0.0.0/16", manager.effectiveVpcCidr(REGION, "vpc-1").orElseThrow());
}
private static Map<String, String> ourLabels(String vpcId, String ownerPort) {
Map<String, String> labels = new LinkedHashMap<>();
labels.put(VpcNetworkManager.LABEL_COMPONENT, VpcNetworkManager.COMPONENT_VALUE);
labels.put(VpcNetworkManager.LABEL_VPC_ID, vpcId);
labels.put(VpcNetworkManager.LABEL_VPC_REGION, REGION);
labels.put(VpcNetworkManager.LABEL_OWNER_PORT, ownerPort);
return labels;
}
@Test
void subBlockAllocationSkipsTakenRanges() {
Cidr4 parent = Cidr4.parse("10.0.0.0/16").orElseThrow();
Cidr4 taken = Cidr4.parse("10.0.0.0/24").orElseThrow();
assertEquals("10.0.1.0/24",
VpcNetworkManager.allocateSubBlock(parent, 24, List.of(taken)).toString());
assertEquals(null,
VpcNetworkManager.allocateSubBlock(parent, 16, List.of(parent)),
"a fully claimed parent yields nothing rather than an overlapping block");
}
}