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

+1 -1
View File
@@ -236,7 +236,7 @@ Guests with an instance profile receive endpoint and region settings without Flo
### IMDS and SSM managed instances
IMDS only knows about containers that Floci itself launched through `RunInstances`. That launch is what installs the link-local `169.254.169.254` proxy inside the container and maps the container's IP to its instance record.
IMDS only knows about containers that Floci itself launched through `RunInstances`. That launch is what installs the link-local `169.254.169.254` proxy inside the container and maps the container's IP to its instance record. A restarted container (`StopInstances` then `StartInstances`) has a new network namespace, so once the instance is `running` `StartInstances` sets the proxy up again; an instance under security-group enforcement keeps its helper container's namespace, and the proxy with it.
Registering a container with SSM is independent of this: an SSM agent that calls `UpdateInstanceInformation` becomes a managed instance, but that does not create an EC2 instance record, does not install the IMDS proxy, and does not register the container with IMDS. From such a container, `curl http://169.254.169.254/...` fails outright (no proxy), and a request sent straight to the host IMDS port returns `404` with a message explaining that no EC2 instance is registered for the source IP. Floci also logs a warning when an SSM agent registers from a container that is not backed by a Floci EC2 instance.
@@ -62,6 +62,7 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiPredicate;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -87,6 +88,8 @@ public class Ec2ContainerManager {
private static final int LAUNCH_CORE_THREADS = 4;
private static final int LAUNCH_MAX_THREADS = 8;
private static final int LAUNCH_QUEUE_CAPACITY = 64;
// ponytail: a fixed cap on concurrent post-start IMDS setups; a start beyond it skips the setup.
private static final int METADATA_SETUP_CONCURRENCY = 16;
private static final long USER_DATA_EXECUTION_TIMEOUT_MINUTES = 30;
// Wait for capacity so accepted launches are not dropped, but never run launch work on callers.
static final RejectedExecutionHandler BLOCKING_BACKPRESSURE = (runnable, executor) -> {
@@ -154,6 +157,7 @@ public class Ec2ContainerManager {
private final Ec2InstanceTypeCatalog instanceTypeCatalog;
private SecurityGroupFirewallManager firewallManager;
private final ExecutorService executor;
private final Semaphore metadataSetupSlots = new Semaphore(METADATA_SETUP_CONCURRENCY);
private final Map<String, CompletableFuture<Void>> lifecycleOperations = new ConcurrentHashMap<>();
private final Duration userDataExecutionTimeout;
private final Set<ResultCallback<Frame>> activeUserDataCallbacks = ConcurrentHashMap.newKeySet();
@@ -1003,6 +1007,7 @@ public class Ec2ContainerManager {
InstanceState pending = InstanceState.pending();
instance.setState(pending);
submitLifecycleOperation(containerId, () -> {
boolean setUpMetadataEndpoint = false;
try {
dockerClient.startContainerCmd(containerId).exec();
boolean running = false;
@@ -1036,6 +1041,11 @@ public class Ec2ContainerManager {
metadataServer.registerContainer(containerIp, instanceId, instance);
refreshImdsSourceRegistration(instance, containerId, containerIp);
refreshMetadataAddresses(instance, containerId);
// A restarted container has a new network namespace: the link-local IMDS
// address launch configured is gone, and without it the guest cannot reach
// 169.254.169.254 (instance credentials, user data, EC2 Instance Connect keys).
// A protected instance's helper kept its namespace, and the address with it.
setUpMetadataEndpoint = namespace == null;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
@@ -1046,7 +1056,8 @@ public class Ec2ContainerManager {
instance.compareAndSetState(pending, InstanceState.stopped());
return;
}
if (!instance.compareAndSetState(pending, InstanceState.running())) {
InstanceState running = InstanceState.running();
if (!instance.compareAndSetState(pending, running)) {
return;
}
if (postStart != null) {
@@ -1057,9 +1068,48 @@ public class Ec2ContainerManager {
instance.getInstanceId(), e.getMessage());
}
}
if (setUpMetadataEndpoint) {
setUpMetadataEndpointWhileRunning(instance, containerId, running);
}
});
}
/**
* Best effort with its own bounded commands, as at launch, and off the container's lifecycle
* queue: a slow setup holds neither the instance pending nor a stop queued behind this start.
* It goes ahead only while {@code running} is still the instance's state, so a stop, terminate
* or later start makes it stand down; an exec against a container already stopped just fails.
*
* <p>Not on {@link #executor}: the start runs on one of its workers, and its backpressure
* blocks a submitter while the queue is full, so with every worker submitting nothing would
* drain it. A setup that finds no free slot is skipped and logged rather than waited for.
*/
private void setUpMetadataEndpointWhileRunning(Instance instance, String containerId, InstanceState running) {
String instanceId = instance.getInstanceId();
if (!metadataSetupSlots.tryAcquire()) {
LOG.warnv("Skipped link-local IMDS setup for EC2 instance {0}: {1} setups already running",
instanceId, METADATA_SETUP_CONCURRENCY);
return;
}
BooleanSupplier stillRunning = () -> instance.getState() == running;
try {
Thread.ofVirtual().name("ec2-imds-setup-" + instanceId).start(() -> {
try {
configureLinkLocalMetadataEndpoint(containerId, instanceId, dockerHostResolver.resolve(),
config.services().ec2().imdsPort(), stillRunning);
} catch (RuntimeException e) {
LOG.warnv("Could not configure link-local IMDS endpoint for EC2 instance {0}: {1}",
instanceId, e.getMessage());
} finally {
metadataSetupSlots.release();
}
});
} catch (RuntimeException e) {
metadataSetupSlots.release();
LOG.warnv("Could not schedule link-local IMDS setup for EC2 instance {0}: {1}", instanceId, e.getMessage());
}
}
boolean isContainerRunning(String containerId) {
return containerId != null && !containerId.isBlank() && lifecycleManager.isContainerRunning(containerId);
}
@@ -1701,13 +1751,24 @@ public class Ec2ContainerManager {
}
private void configureLinkLocalMetadataEndpoint(String containerId, String instanceId, String flociHost, int imdsPort) {
configureLinkLocalMetadataEndpoint(containerId, instanceId, flociHost, imdsPort, () -> true);
}
private void configureLinkLocalMetadataEndpoint(String containerId, String instanceId, String flociHost, int imdsPort,
BooleanSupplier stillWanted) {
try {
if (!stillWanted.getAsBoolean()) {
return;
}
ContainerExec.Result install = execInContainerForResult(containerId, metadataProxyInstallCommand(), 180);
if (install.exitCode() != 0) {
LOG.warnv("Could not install IMDS proxy dependencies for EC2 instance {0}: {1}",
instanceId, install.summary());
return;
}
if (!stillWanted.getAsBoolean()) {
return;
}
ContainerExec.Result start = execInContainerForResult(containerId, metadataProxyStartCommand(flociHost, imdsPort), 30);
if (start.exitCode() != 0) {
@@ -93,7 +93,14 @@ public final class Ec2MetadataProxy {
"set -eu",
CLEAR_APPLICATION_PATHS,
"ip addr show dev lo | grep -q '" + bindIp + "/32' || ip addr add " + bindIp + "/32 dev lo",
"if [ -f " + pidFile + " ] && kill -0 \"$(cat " + pidFile + ")\" 2>/dev/null; then",
// The pid file is on the container's writable layer, so it outlives a restart while
// the PID namespace does not: only a pid that is still this socat listener counts.
// The command name matters as well as the arguments: the shell running this script
// carries the listener string in its own command line.
"if [ -f " + pidFile + " ] && pid=\"$(cat " + pidFile + ")\""
+ " && [ \"$(cat \"/proc/$pid/comm\" 2>/dev/null)\" = socat ]"
+ " && tr '\\0' ' ' 2>/dev/null <\"/proc/$pid/cmdline\""
+ " | grep -q 'TCP-LISTEN:" + bindPort + ",bind=" + bindIp + ",'; then",
" exit 0",
"fi",
"nohup socat TCP-LISTEN:" + bindPort + ",bind=" + bindIp + ",fork,reuseaddr TCP:"
@@ -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