fix(ec2): set the link-local IMDS endpoint up again when an instance starts (#6873)

This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-10-31 13:21:38 -04:00
1 parent 7569a9a8ec
commit e3cdb72171
5 files changed
+358 -6

No files matched your search

@@ -94,6 +94,7 @@ import static org.mockito.Mockito.after;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -427,6 +428,7 @@ class Ec2ContainerManagerTest {
when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
DockerClient dockerClient = mock(DockerClient.class);
List<String[]> execs = recordExecs(dockerClient);
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.
@@ -454,6 +456,223 @@ class Ec2ContainerManagerTest {
assertEquals("172.17.0.9", instance.getImdsSourceIp(),
"the stale address would otherwise stay registered while IMDS requests arrive "
+ "from an address nothing knows about");
// The restarted container's namespace is new: the link-local IMDS endpoint is set up again.
awaitUntil(() -> execs.stream().anyMatch(cmd -> Arrays.equals(cmd,
Ec2ContainerManager.metadataProxyInstallCommand())), Duration.ofSeconds(2));
}
@Test
void startSetsTheImdsEndpointUpOnlyAfterTheInstanceIsRunning() throws Exception {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
Instance instance = new Instance();
instance.setInstanceId("i-imds-after-running");
instance.setDockerContainerId(TEST_CONTAINER_ID);
instance.setContainerBridgeIp("10.0.1.10");
// Setup is best effort and can take minutes on a slow image; it must not hold the
// instance pending or delay the post-start hook.
List<String> events = new CopyOnWriteArrayList<>();
DockerClient dockerClient = mock(DockerClient.class);
recordExecs(dockerClient, () -> events.add("exec while " + instance.getState().getName()));
when(dockerClient.startContainerCmd(TEST_CONTAINER_ID))
.thenReturn(mock(StartContainerCmd.class, RETURNS_SELF));
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);
Ec2ContainerManager manager = managerWith(lifecycleManager, dockerClient, mock(Ec2MetadataServer.class));
manager.start(instance, () -> events.add("postStart"));
awaitUntil(() -> events.stream().anyMatch(event -> event.startsWith("exec")), Duration.ofSeconds(5));
assertEquals(List.of("postStart", "exec while running"), events.subList(0, 2), events.toString());
}
@Test
void stopDuringASlowImdsSetupAfterStartDoesNotWaitForTheSetup() throws Exception {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
DockerClient dockerClient = mock(DockerClient.class);
// The package install hangs, as it can on a slow mirror, until the test lets it fail.
CountDownLatch setupEntered = new CountDownLatch(1);
CountDownLatch releaseSetup = new CountDownLatch(1);
ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
when(dockerClient.execCreateCmd(TEST_CONTAINER_ID)).thenReturn(execCreate);
when(execCreate.exec()).thenAnswer(invocation -> {
setupEntered.countDown();
releaseSetup.await(10, TimeUnit.SECONDS);
throw new IllegalStateException("no exec in this test");
});
when(dockerClient.startContainerCmd(TEST_CONTAINER_ID))
.thenReturn(mock(StartContainerCmd.class, RETURNS_SELF));
when(dockerClient.stopContainerCmd(TEST_CONTAINER_ID)).thenReturn(mock(StopContainerCmd.class, RETURNS_SELF));
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);
Ec2ContainerManager manager = managerWith(lifecycleManager, dockerClient, mock(Ec2MetadataServer.class));
Instance instance = new Instance();
instance.setInstanceId("i-stop-during-imds-setup");
instance.setDockerContainerId(TEST_CONTAINER_ID);
instance.setContainerBridgeIp("10.0.1.10");
try {
manager.start(instance);
assertTrue(setupEntered.await(5, TimeUnit.SECONDS), "the IMDS setup never began");
manager.stop(instance);
awaitUntil(() -> "stopped".equals(instance.getState().getName()), Duration.ofSeconds(3));
verify(dockerClient).stopContainerCmd(TEST_CONTAINER_ID);
} finally {
releaseSetup.countDown();
}
}
/**
* The start runs on a launch-executor worker. Handing the IMDS setup to that same executor
* while its queue is full blocks the worker in backpressure, and with every worker doing so
* nothing drains the queue: here one worker and a one-slot queue stand in for eight and 64.
*/
@Test
void startHandsTheImdsSetupOffWithoutBlockingALaunchWorkerOnAFullQueue() throws Exception {
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
when(lifecycle.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
DockerClient docker = mock(DockerClient.class);
List<String[]> execs = recordExecs(docker);
when(docker.startContainerCmd(TEST_CONTAINER_ID)).thenReturn(mock(StartContainerCmd.class, RETURNS_SELF));
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
when(docker.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
InspectContainerResponse response = vpcAttachedInspectResponse("10.0.1.10", "172.17.0.9");
when(inspect.exec()).thenReturn(response);
ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1), Ec2ContainerManager.BLOCKING_BACKPRESSURE);
try {
Ec2ContainerManager manager = new Ec2ContainerManager(mock(ContainerBuilder.class), lifecycle,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), mock(DockerHostResolver.class),
docker, mock(PortAllocator.class), mock(EmulatorConfig.class, RETURNS_DEEP_STUBS),
mock(Ec2MetadataServer.class), mock(Ec2PortForwardManager.class), mock(RegionResolver.class),
mock(ContainerNetworkReachability.class), mock(VpcNetworkManager.class),
mock(ContainerReachableEndpoint.class), executor, Duration.ofSeconds(5));
Instance instance = new Instance();
instance.setInstanceId("i-full-launch-queue");
instance.setDockerContainerId(TEST_CONTAINER_ID);
instance.setContainerBridgeIp("10.0.1.10");
CountDownLatch postStartEntered = new CountDownLatch(1);
CountDownLatch queueFull = new CountDownLatch(1);
CountDownLatch queuedWorkRan = new CountDownLatch(1);
manager.start(instance, () -> {
postStartEntered.countDown();
try {
queueFull.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
assertTrue(postStartEntered.await(5, TimeUnit.SECONDS), "the start never reached its post-start hook");
executor.execute(queuedWorkRan::countDown);
queueFull.countDown();
assertTrue(queuedWorkRan.await(3, TimeUnit.SECONDS),
"the launch worker running the start never came back to drain its queue");
awaitUntil(() -> execs.stream().anyMatch(cmd -> Arrays.equals(cmd,
Ec2ContainerManager.metadataProxyInstallCommand())), Duration.ofSeconds(3));
} finally {
executor.shutdownNow();
}
}
@Test
void startOfAProtectedInstanceDoesNotSetTheImdsEndpointUpAgain() throws Exception {
// The helper container kept its network namespace across the stop, and the address with it.
DockerClient dockerClient = mock(DockerClient.class);
List<String[]> execs = recordExecs(dockerClient);
Instance instance = startProtectedInstance(mock(Ec2MetadataServer.class), Map.of(
"floci.security-group-helper", "true",
"io.floci.service", "ec2",
"io.floci.resource-id", "i-protected",
"floci_owner_port", "4566"), dockerClient);
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(5));
assertTrue(execs.stream().noneMatch(cmd -> Arrays.equals(cmd,
Ec2ContainerManager.metadataProxyInstallCommand())), "no IMDS setup exec for a protected start");
}
@Test
void startRunsTheImdsProxyAgainOnceItsDependenciesInstall() throws Exception {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
DockerClient dockerClient = mock(DockerClient.class);
List<String[]> execs = recordExecs(dockerClient);
// Unlike recordExecs alone, every exec here completes with exit 0, so the install
// succeeds and the setup goes on to start the proxy.
ExecCreateCmd execCreate = dockerClient.execCreateCmd(TEST_CONTAINER_ID);
ExecCreateCmdResponse created = mock(ExecCreateCmdResponse.class);
when(created.getId()).thenReturn("imds-exec");
doReturn(created).when(execCreate).exec();
ExecStartCmd execStart = mock(ExecStartCmd.class);
when(dockerClient.execStartCmd("imds-exec")).thenReturn(execStart);
when(execStart.exec(any())).thenAnswer(invocation -> {
ResultCallback<?> callback = invocation.getArgument(0);
callback.onComplete();
return callback;
});
InspectExecCmd inspectExec = mock(InspectExecCmd.class);
InspectExecResponse inspectExecResponse = mock(InspectExecResponse.class);
when(inspectExecResponse.getExitCodeLong()).thenReturn(0L);
when(inspectExec.exec()).thenReturn(inspectExecResponse);
when(dockerClient.inspectExecCmd("imds-exec")).thenReturn(inspectExec);
when(dockerClient.startContainerCmd(TEST_CONTAINER_ID))
.thenReturn(mock(StartContainerCmd.class, RETURNS_SELF));
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
when(dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect);
InspectContainerResponse response = vpcAttachedInspectResponse("10.0.1.10", "172.17.0.9");
when(inspect.exec()).thenReturn(response);
DockerHostResolver hostResolver = mock(DockerHostResolver.class);
when(hostResolver.resolve()).thenReturn("floci-imds-host");
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ec2().imdsPort()).thenReturn(9169);
Ec2ContainerManager manager = new Ec2ContainerManager(
mock(ContainerBuilder.class), lifecycleManager, mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), hostResolver, dockerClient, mock(PortAllocator.class), config,
mock(Ec2MetadataServer.class), mock(Ec2PortForwardManager.class), mock(RegionResolver.class),
mock(ContainerNetworkReachability.class), mock(VpcNetworkManager.class),
mock(ContainerReachableEndpoint.class));
Instance instance = new Instance();
instance.setInstanceId("i-imds-proxy-restart");
instance.setDockerContainerId(TEST_CONTAINER_ID);
instance.setContainerBridgeIp("10.0.1.10");
manager.start(instance);
String[] proxyStart = Ec2ContainerManager.metadataProxyStartCommand("floci-imds-host", 9169);
awaitUntil(() -> execs.stream().anyMatch(cmd -> Arrays.equals(cmd, proxyStart)), Duration.ofSeconds(5));
}
/** Records every command exec'd in the test container; each exec then fails, which start tolerates. */
private static List<String[]> recordExecs(DockerClient dockerClient) {
return recordExecs(dockerClient, () -> { });
}
/** As {@link #recordExecs(DockerClient)}, running {@code onExec} as each exec is created. */
private static List<String[]> recordExecs(DockerClient dockerClient, Runnable onExec) {
List<String[]> execs = new CopyOnWriteArrayList<>();
ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
when(dockerClient.execCreateCmd(TEST_CONTAINER_ID)).thenReturn(execCreate);
when(execCreate.withCmd(any(String[].class))).thenAnswer(invocation -> {
Object[] args = invocation.getArguments();
execs.add(args.length == 1 && args[0] instanceof String[] cmd
? cmd : Arrays.copyOf(args, args.length, String[].class));
onExec.run();
return execCreate;
});
when(execCreate.exec()).thenThrow(new IllegalStateException("no exec in this test"));
return execs;
}
@ParameterizedTest
@@ -551,10 +770,14 @@ class Ec2ContainerManagerTest {
}
private Instance startProtectedInstance(Ec2MetadataServer metadataServer, Map<String, String> helperLabels) {
return startProtectedInstance(metadataServer, helperLabels, mock(DockerClient.class));
}
private Instance startProtectedInstance(Ec2MetadataServer metadataServer, Map<String, String> helperLabels,
DockerClient dockerClient) {
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));
// A workload in the helper's namespace has no Docker attachment of its own, so there is
@@ -24,6 +24,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
class Ec2MetadataProxyTest {
@@ -53,7 +54,8 @@ class Ec2MetadataProxyTest {
// Attaches address if missing
assertTrue(script.contains("ip addr show dev lo | grep -q '169.254.169.254/32' || ip addr add 169.254.169.254/32 dev lo"));
// Idempotent when pid file exists and process is alive
assertTrue(script.contains("if [ -f /tmp/floci-imds-proxy.pid ] && kill -0 \"$(cat /tmp/floci-imds-proxy.pid)\" 2>/dev/null; then\n exit 0\nfi"));
assertTrue(script.contains("if [ -f /tmp/floci-imds-proxy.pid ] && pid=\"$(cat /tmp/floci-imds-proxy.pid)\" && [ \"$(cat \"/proc/$pid/comm\" 2>/dev/null)\" = socat ]"
+ " && tr '\\0' ' ' 2>/dev/null <\"/proc/$pid/cmdline\" | grep -q 'TCP-LISTEN:80,bind=169.254.169.254,'; then\n exit 0\nfi"));
// Targets configured Floci host and IMDS port
assertTrue(script.contains("nohup socat TCP-LISTEN:80,bind=169.254.169.254,fork,reuseaddr TCP:10.0.0.1:9169 >/tmp/floci-imds-proxy.log 2>&1 &"));
// Verifies through an IMDSv2 token even when tokenless access is refused.
@@ -71,7 +73,8 @@ class Ec2MetadataProxyTest {
String script = command[2];
assertTrue(script.contains("ip addr show dev lo | grep -q '169.254.170.23/32' || ip addr add 169.254.170.23/32 dev lo"));
assertTrue(script.contains("if [ -f /tmp/floci-pod-identity-proxy.pid ] && kill -0 \"$(cat /tmp/floci-pod-identity-proxy.pid)\" 2>/dev/null; then\n exit 0\nfi"));
assertTrue(script.contains("if [ -f /tmp/floci-pod-identity-proxy.pid ] && pid=\"$(cat /tmp/floci-pod-identity-proxy.pid)\" && [ \"$(cat \"/proc/$pid/comm\" 2>/dev/null)\" = socat ]"
+ " && tr '\\0' ' ' 2>/dev/null <\"/proc/$pid/cmdline\" | grep -q 'TCP-LISTEN:80,bind=169.254.170.23,'; then\n exit 0\nfi"));
assertTrue(script.contains("nohup socat TCP-LISTEN:80,bind=169.254.170.23,fork,reuseaddr TCP:10.0.0.1:4566 >/tmp/floci-pod-identity-proxy.log 2>&1 &"));
assertTrue(script.contains("http://169.254.170.23/v1/credentials"));
}
@@ -269,6 +272,64 @@ class Ec2MetadataProxyTest {
}
}
/**
* A stop and start keeps the container's writable layer, pid file included, but not its PID
* namespace: the recorded pid can belong to an unrelated process by then, and the proxy must
* still start.
*/
@Test
void startScriptStartsTheProxyWhenThePidFileNamesAnUnrelatedLiveProcess(@TempDir Path directory)
throws Exception {
Path bin = Files.createDirectory(directory.resolve("bin"));
Path proxyStarted = directory.resolve("proxy-started");
HelperShellFixture.writeTool(bin, "ip", "printf '127.0.0.1/32\\n'\n");
HelperShellFixture.writeTool(bin, "socat", ": > '" + proxyStarted + "'\n");
String name = "unit-" + UUID.randomUUID();
try {
// This JVM is alive, and it is not the proxy.
Files.writeString(Path.of("/tmp/floci-" + name + "-proxy.pid"), ProcessHandle.current().pid() + "\n");
String[] command = Ec2MetadataProxy.startCommand(name, "127.0.0.1", 80, "127.0.0.1", 9169,
"[ -f '" + proxyStarted + "' ] && exit 0");
int result = HelperShellFixture.run(command, directory, Map.of("PATH", bin + ":" + System.getenv("PATH")));
assertEquals(0, result, HelperShellFixture.output(directory));
assertTrue(Files.exists(proxyStarted), "socat was never started: " + HelperShellFixture.output(directory));
} finally {
deleteProxyFiles(name);
}
}
/**
* After a restart the recorded pid can be the shell running this very script, whose command
* line holds the listener string the check looks for. That shell is not the proxy. Needs a
* Linux {@code /proc}; elsewhere no pid is ever taken for the proxy.
*/
@Test
void startScriptStartsTheProxyWhenThePidFileNamesTheStartShellItself(@TempDir Path directory)
throws Exception {
assumeTrue(Files.isDirectory(Path.of("/proc/self")), "needs a Linux /proc");
Path bin = Files.createDirectory(directory.resolve("bin"));
Path proxyStarted = directory.resolve("proxy-started");
HelperShellFixture.writeTool(bin, "ip", "printf '127.0.0.1/32\\n'\n");
HelperShellFixture.writeTool(bin, "socat", ": > '" + proxyStarted + "'\n");
String name = "unit-" + UUID.randomUUID();
String pidFile = "/tmp/floci-" + name + "-proxy.pid";
try {
String[] command = Ec2MetadataProxy.startCommand(name, "127.0.0.1", 80, "127.0.0.1", 9169,
"[ -f '" + proxyStarted + "' ] && exit 0");
// The script's own shell takes the recorded pid, as a reused pid would after a restart.
command[2] = command[2].replaceFirst("set -eu\n", "set -eu\necho \\$\\$ > " + pidFile + "\n");
int result = HelperShellFixture.run(command, directory, Map.of("PATH", bin + ":" + System.getenv("PATH")));
assertEquals(0, result, HelperShellFixture.output(directory));
assertTrue(Files.exists(proxyStarted), "socat was never started: " + HelperShellFixture.output(directory));
} finally {
deleteProxyFiles(name);
}
}
/**
* Answers token requests with the status {@code tokenStatus} picks for each attempt, serves the
* instance ID to the issued token and, as an instance allowing IMDSv1 would, to a tokenless