fix(eks): answer IMDS on a node by NAT rules instead of a socat relay (#8856)

* fix(eks): answer IMDS on a node by NAT rules instead of a socat relay
* fix(eks): refuse a pod's IMDS request without the pod network, and probe the instance id
This commit is contained in:
mrfelek authored and GitHub committed 2026-11-18 18:10:38 -04:00
1 parent bbc80c9b51
commit 545006249b
6 files changed
+378 -365

No files matched your search

@@ -2106,13 +2106,10 @@ class EksClusterManagerTest {
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
verify(metadataServer).reconcileClusterNodeAddresses(any(), any());
// imds=true, imdsPodNetwork=false (default): 2 commands (install probe, start proxy)
assertEquals(2, capturedCmds.size());
// First command: install probe
assertTrue(capturedCmds.get(0)[2].contains("command -v socat"));
// Second command: start command with 169.254.169.254
assertTrue(capturedCmds.get(1)[2].contains("169.254.169.254"));
assertTrue(capturedCmds.get(1)[2].contains("TCP:floci-host:9169"));
// imds=true, imdsPodNetwork=false (default): the node's requests alone go to the metadata service
assertEquals(1, capturedCmds.size());
assertArrayEquals(EksPodNetworkRouting.buildImdsForwardCommand(null, false, "floci-host", 9169),
capturedCmds.get(0));
assertNotNull(manager.getRegisteredClusterNodeInstance(cluster));
}
@@ -2127,18 +2124,10 @@ class EksClusterManagerTest {
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
verify(metadataServer).reconcileClusterNodeAddresses(any(), any());
assertEquals(3, capturedCmds.size());
// First command: install probe
assertTrue(capturedCmds.get(0)[2].contains("command -v socat"));
// Second command: start command with 169.254.169.254
assertTrue(capturedCmds.get(1)[2].contains("169.254.169.254"));
assertTrue(capturedCmds.get(1)[2].contains("TCP:floci-host:9169"));
// Third command: pod network routing with iptables
assertTrue(capturedCmds.get(2)[2].contains("FLOCI-LINK-LOCAL"));
assertTrue(capturedCmds.get(2)[2].contains("10.42.0.0/16"));
assertTrue(capturedCmds.get(2)[2].contains("169.254.169.254"));
assertFalse(capturedCmds.get(2)[2].contains("169.254.170.23"),
"IMDS pod routing must not route Pod Identity traffic");
// The node's and the pod network's requests go to the metadata service, in one command
assertEquals(1, capturedCmds.size());
assertArrayEquals(EksPodNetworkRouting.buildImdsForwardCommand(null, true, "floci-host", 9169),
capturedCmds.get(0));
assertNotNull(manager.getRegisteredClusterNodeInstance(cluster));
}
@@ -2435,23 +2424,22 @@ class EksClusterManagerTest {
}
@Test
void podNetworkRoutingFailureLogsWarningAndDoesNotAbort() {
void aForwardThatFailsLogsAWarningAndDoesNotAbort() {
when(eks.imdsPodNetwork()).thenReturn(true);
InspectExecCmd inspectExec = Mockito.mock(InspectExecCmd.class);
InspectExecResponse inspectResponse = Mockito.mock(InspectExecResponse.class);
// Simulate install and start succeeding (0), but routing failing (1)
when(inspectResponse.getExitCodeLong()).thenReturn(0L, 0L, 1L);
when(inspectResponse.getExitCodeLong()).thenReturn(1L);
when(inspectExec.exec()).thenReturn(inspectResponse);
when(dockerClient.inspectExecCmd(anyString())).thenReturn(inspectExec);
Cluster cluster = new Cluster();
cluster.setName("test-cluster");
// Pod network routing failure logs warning and continues without throwing
// The forward's failure logs a warning and continues without throwing
manager.configureLinkLocalMetadataEndpoint(cluster, "container-42");
assertEquals(3, capturedCmds.size());
assertEquals(1, capturedCmds.size());
assertNotNull(manager.getRegisteredClusterNodeInstance(cluster));
}
@@ -3819,6 +3807,24 @@ class EksClusterManagerTest {
return host;
}
/**
* The IMDS forward resolves Floci's host in the node, which on a Linux host is {@code host.docker.internal}
* when Floci runs natively: the node is given that name whenever IMDS is on, as for the ECR mirror and the
* token webhook, which are both off here.
*/
@ParameterizedTest
@ValueSource(booleans = {true, false})
void aNodeWithImdsResolvesFlocisHostOnLinux(boolean imds) {
when(eks.imds()).thenReturn(imds);
stubDockerHost(16L * 1024 * 1024 * 1024, 8);
Cluster cluster = new Cluster();
cluster.setName("imds-host-cluster");
manager.startCluster(cluster);
verify(builder, imds ? Mockito.times(1) : never()).withHostDockerInternalOnLinux();
}
@Test
void hostTooSmallLeavesClusterUnboundedAndStarting() {
DockerClient dockerClient = Mockito.mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);
@@ -1,15 +1,16 @@
package io.floci.aws.services.eks;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.DockerClient;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerExec;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.DockerHostResolver;
import io.floci.aws.services.ec2.Ec2MetadataServer;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.eks.model.Cluster;
import io.floci.aws.testing.CloudFormationSettingsProfile;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.EksTestNode;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
@@ -19,39 +20,32 @@ import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.time.Duration;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Configures the link-local IMDS endpoint on a stand-in cluster container and queries it from the
* node and from a pod network namespace. The settings come from
* {@link CloudFormationSettingsProfile}, which this class shares with
* {@code TimestreamInfluxDbDockerIntegrationTest}.
* IMDS answers on a stock {@code rancher/k3s} node, which has {@code iptables} but no {@code socat}, {@code curl} or
* package manager: the node itself, where a {@code hostNetwork} pod's requests come from, and an ordinary pod both
* read the node's instance from {@code 169.254.169.254}, and with the pod network off the node refuses the pod's
* requests rather than send them on. The settings come from
* {@link CloudFormationSettingsProfile}, which turns on IMDS for the node and its pod network; the node is started
* through {@link EksClusterManager} directly, which runs a k3s container while EKS is mocked too.
*/
@QuarkusTest
@TestProfile(CloudFormationSettingsProfile.class)
class EksImdsDockerIntegrationTest {
private static final Logger LOG = Logger.getLogger(EksImdsDockerIntegrationTest.class);
private static final String TEST_IMAGE = "alpine:3.21";
private static final String ACCOUNT = "000000000000";
private static final String POD = "imds-client";
private static final String IMDS = "http://169.254.169.254/latest/meta-data/";
@Inject
DockerClient dockerClient;
@Inject
ContainerBuilder containerBuilder;
@Inject
ContainerLifecycleManager lifecycleManager;
@Inject
EmulatorConfig config;
@Inject
Ec2MetadataServer metadataServer;
@@ -61,163 +55,80 @@ class EksImdsDockerIntegrationTest {
@Inject
DockerHostResolver dockerHostResolver;
private String containerId;
@Inject
EmulatorConfig config;
private Cluster cluster;
@BeforeEach
void requireDockerAndStartMetadataServer() {
boolean dockerAvailable = isDockerAvailable();
if (!dockerAvailable) {
LOG.warn("Docker daemon is not available; skipping EksImdsDockerIntegrationTest");
}
Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for EKS IMDS integration test");
Assumptions.assumeTrue(DockerAvailability.answers(dockerClient),
"Docker daemon must be available for EKS IMDS integration test");
Assumptions.assumeTrue(dockerHostResolver.isLinuxHost(),
"Link-local IMDS container test requires a Linux host; on macOS/Windows, container-to-host proxy traffic arrives from 127.0.0.1 which collides across clusters");
"Link-local IMDS container test requires a Linux host; on macOS/Windows, container-to-host traffic"
+ " arrives from 127.0.0.1 which collides across clusters");
metadataServer.start().join();
}
@AfterEach
void tearDown() {
if (cluster != null) {
eksClusterManager.unregisterMetadataEndpoint(cluster);
}
if (containerId != null) {
try {
lifecycleManager.stopAndRemove(containerId, null);
} catch (Exception ignored) {
eksClusterManager.stopCluster(cluster);
} catch (Exception e) {
LOG.warnv(e, "Failed to stop test cluster {0}", cluster.getName());
}
}
}
@Test
void linkLocalImdsEndpointAnswersInsideClusterContainer() throws Exception {
String clusterName = "imds-it-" + UUID.randomUUID().toString().substring(0, 8);
cluster = new Cluster();
cluster.setName(clusterName);
cluster.setRoleArn("arn:aws:iam::000000000000:role/eks-it-role");
void theNodeAndAPodReadTheNodesInstanceFromImds() throws Exception {
cluster = EksTestNode.cluster(ACCOUNT, "imds-" + UUID.randomUUID().toString().substring(0, 8));
EksTestNode node = EksTestNode.start(dockerClient, eksClusterManager, cluster, Duration.ofSeconds(60));
Instance instance = eksClusterManager.getRegisteredClusterNodeInstance(cluster);
assertNotNull(instance, "the node must be registered with the metadata server");
ContainerSpec spec = containerBuilder.newContainer(TEST_IMAGE)
.withName("floci-eks-imds-test-" + clusterName)
.withPrivileged(true)
.withHostDockerInternalOnLinux()
// PID 1 gets no default SIGTERM handler, so a bare "sleep 300" sits out the
// whole stopAndRemove grace period when @AfterEach tears the container down.
.withCmd(List.of("sh", "-c", "trap 'exit 0' TERM; sleep 300 & wait"))
.build();
// The node's namespace, with BusyBox's wget: the stock image has no curl.
assertEquals(instance.getInstanceId(), node.execOutput("wget", "-q", "-O", "-", "-T", "3",
IMDS + "instance-id"));
containerId = lifecycleManager.createAndStart(spec).containerId();
assertNotNull(containerId, "Container ID must not be null");
node.apply("""
apiVersion: v1
kind: Pod
metadata:
name: %s
namespace: default
spec:
containers:
- name: client
image: alpine:3.21
command: ["sleep", "3600"]
""".formatted(POD));
node.awaitPodRunning(POD, Duration.ofSeconds(90));
// Ensure curl, iptables, and iproute2 dependencies are installed in the test fixture if absent
execInContainer(containerId, new String[]{"sh", "-c",
"command -v curl >/dev/null 2>&1 && command -v iptables >/dev/null 2>&1 && command -v ip >/dev/null 2>&1 || apk add --no-cache curl iptables iproute2"});
// An ordinary pod, from the pod network: the node's own instance and its instance profile.
assertEquals(instance.getInstanceId(), node.kubectlOutput("exec", POD, "--", "wget", "-q", "-O", "-",
"-T", "3", IMDS + "instance-id"));
String iamInfo = node.kubectlOutput("exec", POD, "--", "wget", "-q", "-O", "-", "-T", "3", IMDS + "iam/info");
assertEquals(instance.getIamInstanceProfileArn(),
new ObjectMapper().readTree(iamInfo).path("InstanceProfileArn").asText(), iamInfo);
eksClusterManager.configureLinkLocalMetadataEndpoint(cluster, containerId);
// Without the pod network the node refuses a pod's request, which would otherwise leave the node for the
// network the Docker host is on and time out here, and still answers its own; with it again, the pod reads
// IMDS once more. Each forward ends only once the node's instance id answers through it.
String flociHost = dockerHostResolver.resolve();
int imdsPort = config.services().ec2().imdsPort();
node.execOutput(EksPodNetworkRouting.buildImdsForwardCommand(cluster.getPodCidr(), false, flociHost, imdsPort));
ContainerExec.Result refused = node.kubectl("exec", POD, "--", "wget", "-q", "-O", "-", "-T", "3",
IMDS + "instance-id");
assertEquals(1, refused.exitCode(), refused.summary());
assertEquals("wget: can't connect to remote host (169.254.169.254): Connection refused\n"
+ "command terminated with exit code 1", refused.stderr().trim());
assertEquals(instance.getInstanceId(), node.execOutput("wget", "-q", "-O", "-", "-T", "3",
IMDS + "instance-id"));
// IMDSv2 token test
String tokenCmd = "curl -s -f -X PUT http://169.254.169.254/latest/api/token -H 'x-aws-ec2-metadata-token-ttl-seconds: 21600'";
String token = execInContainer(containerId, new String[]{"sh", "-c", tokenCmd});
assertNotNull(token, "IMDSv2 token response should not be null");
assertTrue(!token.isBlank(), "IMDSv2 token should not be blank");
// IMDSv2 instance-id metadata test
String instanceIdCmd = "curl -s -f -H 'x-aws-ec2-metadata-token: " + token.trim() + "' http://169.254.169.254/latest/meta-data/instance-id";
String instanceId = execInContainer(containerId, new String[]{"sh", "-c", instanceIdCmd});
assertNotNull(instanceId, "instance-id response should not be null");
assertTrue(instanceId.trim().startsWith("i-"), "Instance ID should start with 'i-': " + instanceId);
// IMDSv1 fallback test using wget (hostNetwork / node namespace regression test)
String imdsv1Cmd = "wget -q -O - http://169.254.169.254/latest/meta-data/instance-id";
String v1InstanceId = execInContainer(containerId, new String[]{"sh", "-c", imdsv1Cmd});
assertEquals(instanceId.trim(), v1InstanceId.trim(), "IMDSv1 and IMDSv2 instance IDs should match");
// Pod network namespace test: ordinary pods in their own network namespace reach link-local IMDS
// via the rules programmed for the pod CIDR (10.42.0.0/16).
String podNetworkSetupCmd = """
set -e
ip link add cni0 type bridge 2>/dev/null || true
ip addr add 10.42.0.1/24 dev cni0 2>/dev/null || true
ip link set cni0 up
ip netns add pod-test 2>/dev/null || true
ip link add veth-host type veth peer name eth0 netns pod-test 2>/dev/null || true
ip link set veth-host master cni0 up
ip netns exec pod-test ip link set lo up
ip netns exec pod-test ip addr add 10.42.0.15/24 dev eth0 2>/dev/null || true
ip netns exec pod-test ip link set eth0 up
ip netns exec pod-test ip route replace default via 10.42.0.1
# Stand-in CNI portmap rule: k3s/flannel installs CNI-HOSTPORT-DNAT matching dst-type LOCAL.
# Simulate a hostPort/ingress binding or redirect on port 80 that intercepts LOCAL traffic.
iptables -t nat -N CNI-HOSTPORT-DNAT 2>/dev/null || true
iptables -t nat -F CNI-HOSTPORT-DNAT 2>/dev/null || true
iptables -t nat -A CNI-HOSTPORT-DNAT -p tcp --dport 80 -j REDIRECT --to-ports 9999
iptables -t nat -D PREROUTING -m addrtype --dst-type LOCAL -j CNI-HOSTPORT-DNAT 2>/dev/null || true
iptables -t nat -A PREROUTING -m addrtype --dst-type LOCAL -j CNI-HOSTPORT-DNAT
""";
execInContainer(containerId, new String[]{"sh", "-c", podNetworkSetupCmd});
try {
// Ordinary pod querying instance-id with FLOCI-LINK-LOCAL preempting CNI-HOSTPORT-DNAT
String podInstanceIdCmd = "ip netns exec pod-test wget -q -O - -T 3 http://169.254.169.254/latest/meta-data/instance-id";
String podInstanceId = execInContainer(containerId, new String[]{"sh", "-c", podInstanceIdCmd});
assertNotNull(podInstanceId, "Pod instance ID response should not be null");
assertEquals(instanceId.trim(), podInstanceId.trim(),
"Pod should receive the same instance ID as the node namespace");
// Ordinary pod querying IAM info
String podIamInfoCmd = "ip netns exec pod-test wget -q -O - -T 3 http://169.254.169.254/latest/meta-data/iam/info";
String podIamInfo = execInContainer(containerId, new String[]{"sh", "-c", podIamInfoCmd});
assertNotNull(podIamInfo, "Pod IAM info response should not be null");
assertTrue(podIamInfo.contains(clusterName + "-node-profile"),
"Pod IAM info should contain instance profile: " + podIamInfo);
// Prove the FLOCI-LINK-LOCAL rule is strictly required:
// Temporarily detach FLOCI-LINK-LOCAL from PREROUTING. The pod request now hits CNI-HOSTPORT-DNAT
// and fails because port 80 is redirected to 9999.
execInContainer(containerId, new String[]{"sh", "-c",
"iptables -t nat -D PREROUTING -j FLOCI-LINK-LOCAL"});
ContainerExec.Result intercepted = execInContainerWithExitCode(containerId, new String[]{"sh", "-c",
"ip netns exec pod-test wget -q -O - -T 2 http://169.254.169.254/latest/meta-data/instance-id"});
assertNotEquals(0, intercepted.exitCode(),
"Without FLOCI-LINK-LOCAL chain, pod request should be intercepted by CNI-HOSTPORT-DNAT and fail");
// Re-insert FLOCI-LINK-LOCAL at rule 1: pod request succeeds again
execInContainer(containerId, new String[]{"sh", "-c",
"iptables -t nat -I PREROUTING 1 -j FLOCI-LINK-LOCAL"});
String restoredInstanceId = execInContainer(containerId, new String[]{"sh", "-c", podInstanceIdCmd});
assertEquals(instanceId.trim(), restoredInstanceId.trim(),
"Restoring FLOCI-LINK-LOCAL rule must restore pod reachability");
} finally {
execInContainerWithExitCode(containerId, new String[]{"sh", "-c", """
ip netns del pod-test 2>/dev/null || true
ip link del cni0 2>/dev/null || true
iptables -t nat -D PREROUTING -j FLOCI-LINK-LOCAL 2>/dev/null || true
iptables -t nat -D PREROUTING -m addrtype --dst-type LOCAL -j CNI-HOSTPORT-DNAT 2>/dev/null || true
iptables -t nat -F CNI-HOSTPORT-DNAT 2>/dev/null || true
iptables -t nat -X CNI-HOSTPORT-DNAT 2>/dev/null || true
"""});
}
}
private boolean isDockerAvailable() {
try {
dockerClient.pingCmd().exec();
return true;
} catch (Exception e) {
return false;
}
}
private ContainerExec.Result execInContainerWithExitCode(String containerId, String[] cmd) {
return ContainerExec.run(dockerClient, containerId, cmd, 30).throwIfTimedOut(containerId);
}
private String execInContainer(String containerId, String[] cmd) throws Exception {
ContainerExec.Result result = execInContainerWithExitCode(containerId, cmd);
if (result.exitCode() != 0) {
throw new RuntimeException("exec failed with code " + result.exitCode() + ": " + result.stderr());
}
return result.stdout();
node.execOutput(EksPodNetworkRouting.buildImdsForwardCommand(cluster.getPodCidr(), true, flociHost, imdsPort));
assertEquals(instance.getInstanceId(), node.kubectlOutput("exec", POD, "--", "wget", "-q", "-O", "-",
"-T", "3", IMDS + "instance-id"));
}
}
@@ -9,6 +9,7 @@ import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
@@ -21,13 +22,12 @@ import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class EksPodNetworkRoutingTest {
/** What the stand-in iptables is asked when it lists a rule for the address in each chain. */
/** What the stand-in iptables is asked when it lists the rules for the address in each chain, and deletes them. */
private static final List<String> EARLIER_RULES_REMOVED = List.of(
"-t nat -S PREROUTING",
"-t nat -D PREROUTING -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT"
@@ -36,10 +36,27 @@ class EksPodNetworkRoutingTest {
"-t nat -D OUTPUT -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.18.0.9:4566",
"-t nat -S FLOCI-LINK-LOCAL",
"-t nat -D FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT"
+ " --to-destination 169.254.170.23:80");
+ " --to-destination 169.254.170.23:80",
"-t filter -S FORWARD");
/** As {@link #EARLIER_RULES_REMOVED}, for IMDS. */
private static final List<String> EARLIER_IMDS_RULES_REMOVED = List.of(
"-t nat -S PREROUTING",
"-t nat -D PREROUTING -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT"
+ " --to-destination 172.18.0.9:9169",
"-t nat -S OUTPUT",
"-t nat -D OUTPUT -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.18.0.9:9169",
"-t nat -S FLOCI-LINK-LOCAL",
"-t nat -D FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT"
+ " --to-destination 169.254.169.254:80",
"-t filter -S FORWARD",
"-t filter -D FORWARD -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j REJECT"
+ " --reject-with tcp-reset");
/** Where the relay an older Floci ran for the address kept its PID. */
private static final Path RELAY_PID_FILE = Path.of("/tmp/floci-pod-identity-proxy.pid");
/** As {@link #RELAY_PID_FILE}, for IMDS. */
private static final Path IMDS_RELAY_PID_FILE = Path.of("/tmp/floci-imds-proxy.pid");
@Test
void linkLocalEndpointValidatesInput() {
@@ -62,66 +79,6 @@ class EksPodNetworkRoutingTest {
assertEquals(80, ep.port());
}
@Test
void buildRoutingCommandRejectsNullOrEmptyEndpoints() {
assertThrows(IllegalArgumentException.class, () ->
EksPodNetworkRouting.buildRoutingCommand(null, null));
assertThrows(IllegalArgumentException.class, () ->
EksPodNetworkRouting.buildRoutingCommand("10.42.0.0/16", List.of()));
}
@Test
void buildRoutingCommandUsesDefaultPodCidrWhenNullOrBlank() {
String[] cmdNull = EksPodNetworkRouting.buildRoutingCommand(null, EksPodNetworkRouting.DEFAULT_ENDPOINTS);
assertEquals(3, cmdNull.length);
assertEquals("sh", cmdNull[0]);
assertEquals("-c", cmdNull[1]);
assertTrue(cmdNull[2].contains(EksPodNetworkRouting.DEFAULT_POD_CIDR));
String[] cmdBlank = EksPodNetworkRouting.buildRoutingCommand(" ", EksPodNetworkRouting.DEFAULT_ENDPOINTS);
assertTrue(cmdBlank[2].contains(EksPodNetworkRouting.DEFAULT_POD_CIDR));
}
@Test
void buildRoutingCommandGeneratesIdempotentChainAndRules() {
String[] cmd = EksPodNetworkRouting.buildRoutingCommand("10.42.0.0/16", List.of(
new LinkLocalEndpoint("169.254.169.254", 80),
new LinkLocalEndpoint("169.254.170.23", 80)
));
String script = cmd[2];
assertNotNull(script);
// Finds iptables binary across standard and k3s aux locations
assertTrue(script.contains("IPTABLES=$(command -v iptables 2>/dev/null || command -v /bin/aux/iptables 2>/dev/null || true)"));
assertTrue(script.contains("iptables not found in container"));
// Creates custom chain idempotently
assertTrue(script.contains("$IPTABLES -t nat -N FLOCI-LINK-LOCAL 2>/dev/null || true"));
// Inserts jump in PREROUTING only if not already present
assertTrue(script.contains("$IPTABLES -t nat -C PREROUTING -j FLOCI-LINK-LOCAL 2>/dev/null || $IPTABLES -t nat -I PREROUTING 1 -j FLOCI-LINK-LOCAL"));
// Adds rule for IMDS endpoint with check before append
String imdsCheck = "$IPTABLES -t nat -C FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.169.254 -p tcp --dport 80 -j DNAT --to-destination 169.254.169.254:80 2>/dev/null";
String imdsAdd = "$IPTABLES -t nat -A FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.169.254 -p tcp --dport 80 -j DNAT --to-destination 169.254.169.254:80";
assertTrue(script.contains(imdsCheck + " || " + imdsAdd));
// Adds rule for Pod Identity endpoint with check before append
String podIdCheck = "$IPTABLES -t nat -C FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.170.23 -p tcp --dport 80 -j DNAT --to-destination 169.254.170.23:80 2>/dev/null";
String podIdAdd = "$IPTABLES -t nat -A FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.170.23 -p tcp --dport 80 -j DNAT --to-destination 169.254.170.23:80";
assertTrue(script.contains(podIdCheck + " || " + podIdAdd));
}
@Test
void buildRoutingCommandSupportsCustomCidr() {
String customCidr = "192.168.0.0/16";
String[] cmd = EksPodNetworkRouting.buildRoutingCommand(customCidr, EksPodNetworkRouting.DEFAULT_ENDPOINTS);
String script = cmd[2];
assertTrue(script.contains("-s 192.168.0.0/16 -d 169.254.169.254"));
}
@ParameterizedTest
@ValueSource(strings = {"", "floci host", "floci;reboot", "$(id)", "floci`id`", "-floci", "floci-", "a'b"})
void podIdentityForwardRefusesAHostTheShellCouldReadAsMore(String host) {
@@ -148,9 +105,10 @@ class EksPodNetworkRoutingTest {
}
/**
* Runs the forward script against stand-ins for a stock k3s node's tools: iptables records what
* it is asked and lists the rules an earlier Floci left for the address, nslookup answers as
* BusyBox's does, and wget gets Floci's 400 for a request without a pod token. There is no curl.
* Runs the forward script against stand-ins for a stock k3s node's tools ({@link #fakeStockNode}):
* iptables records what it is asked and lists the rules an earlier Floci left for the address,
* nslookup answers as BusyBox's does, and wget gets Floci's 400 for a request without a pod token.
* There is no curl.
* The host is resolved from the hosts file first, through DNS when that has no entry, and an
* address is used as it is.
*/
@@ -179,6 +137,79 @@ class EksPodNetworkRoutingTest {
assertEquals(looksUp ? List.of(host) : List.of(), calls(dir.resolve("nslookup-calls")));
}
@Test
void imdsForwardRefusesABadHostOrPodCidr() {
assertThrows(IllegalArgumentException.class,
() -> EksPodNetworkRouting.buildImdsForwardCommand(null, true, "floci;reboot", 9169));
assertThrows(IllegalArgumentException.class,
() -> EksPodNetworkRouting.buildImdsForwardCommand("10.42.0.0/16; id", true, "floci", 9169));
assertThrows(IllegalArgumentException.class,
() -> EksPodNetworkRouting.buildImdsForwardCommand(null, true, "floci", 0));
}
/**
* IMDS goes to Floci's metadata service as the Pod Identity address goes to its credentials endpoint, once the
* rules an earlier Floci left for it are gone: from the node always, and from the pod network when asked. When not,
* the pod network's requests are refused, rather than sent on toward the network the Docker host is on.
*/
@ParameterizedTest
@ValueSource(booleans = {true, false})
void imdsForwardReplacesEarlierRulesAndTakesThePodNetworkOnlyWhenAsked(boolean podNetwork, @TempDir Path dir)
throws Exception {
Path bin = fakeStockNode(dir);
Path hosts = Files.writeString(dir.resolve("hosts"), "172.18.0.7 floci-under-test.internal\n");
int exit = HelperShellFixture.run(EksPodNetworkRouting.buildImdsForwardCommand(null, podNetwork,
"floci-under-test.internal", 9169, hosts.toString()), dir,
Map.of("PATH", bin.toString(), "http_proxy", "http://127.0.0.1:9"));
assertEquals(0, exit, HelperShellFixture.output(dir));
List<String> expected = new ArrayList<>(EARLIER_IMDS_RULES_REMOVED);
if (podNetwork) {
expected.add("-t nat -I PREROUTING 1 -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp --dport 80 -j DNAT"
+ " --to-destination 172.18.0.7:9169");
} else {
expected.add("-t filter -I FORWARD 1 -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp --dport 80 -j REJECT"
+ " --reject-with tcp-reset");
}
expected.add("-t nat -I OUTPUT 1 -d 169.254.169.254/32 -p tcp --dport 80 -j DNAT --to-destination"
+ " 172.18.0.7:9169");
assertEquals(expected, Files.readAllLines(dir.resolve("iptables-calls")));
}
/**
* The IMDS relay an older Floci ran on the node's loopback would keep the address local to the node, so the
* forward stops it, while its PID file still names it, and takes its address off the loopback. The forward runs
* traced, so the test sees the {@code kill} it sends.
*/
@Test
void imdsForwardRetiresTheRelayAnOlderFlociRan(@TempDir Path dir) throws Exception {
Path bin = fakeStockNode(dir);
HelperShellFixture.writeTool(bin, "ip", "echo \"$*\" >> '" + dir.resolve("ip-calls") + "'\n"
+ "if [ \"$*\" = 'addr show dev lo' ]; then\n"
+ " echo ' inet 127.0.0.1/8 scope host lo'\n"
+ " echo ' inet 169.254.169.254/32 scope global lo'\n"
+ "fi\n");
Process relay = startFakeRelay(bin, "169.254.169.254");
try {
Files.writeString(IMDS_RELAY_PID_FILE, relay.pid() + "\n");
int exit = HelperShellFixture.run(
traced(EksPodNetworkRouting.buildImdsForwardCommand(null, true, "172.18.0.7", 9169)), dir,
Map.of("PATH", bin.toString()));
assertEquals(0, exit, HelperShellFixture.output(dir));
assertEquals(List.of("kill " + relay.pid()), tracedKills(dir), HelperShellFixture.output(dir));
assertTrue(relay.waitFor(10, TimeUnit.SECONDS), "the relay is still running");
assertFalse(Files.exists(IMDS_RELAY_PID_FILE));
assertEquals(List.of("addr show dev lo", "addr del 169.254.169.254/32 dev lo"),
calls(dir.resolve("ip-calls")));
} finally {
relay.destroyForcibly();
Files.deleteIfExists(IMDS_RELAY_PID_FILE);
}
}
/** Without the add-on nothing answers on the address: every rule for it goes, the others stay. */
@Test
void podIdentityRemovalDeletesEveryRuleForTheAddressAndAddsNone(@TempDir Path dir) throws Exception {
@@ -265,8 +296,8 @@ class EksPodNetworkRoutingTest {
* Floci answers 400 without a pod token, which still proves the path reaches it. A proxy that
* answered in its place would look the same to the status check, so the probe must not go
* through one, whether it asks with curl or, on a stock {@code rancher/k3s} node, which has
* BusyBox's {@code wget} and no {@code curl}, with wget, reading the status from the error it
* prints.
* BusyBox's {@code wget} and no {@code curl}, with wget, reading the status from the status line
* {@code -S} prints.
*/
@ParameterizedTest
@ValueSource(strings = {"curl", "wget"})
@@ -286,8 +317,8 @@ class EksPodNetworkRoutingTest {
exchange.close();
});
floci.start();
String[] probe = {"sh", "-c",
EksPodNetworkRouting.podIdentityProbeCommand("http://127.0.0.1:" + floci.getAddress().getPort())};
String[] probe = probe(
EksPodNetworkRouting.podIdentityProbeCommand("http://127.0.0.1:" + floci.getAddress().getPort()));
Map<String, String> environment = new HashMap<>(HelperShellFixture.proxyEnvironment(proxy));
environment.put("PATH", bin.toString());
@@ -306,13 +337,51 @@ class EksPodNetworkRoutingTest {
}
}
/**
* The IMDS forward is ready once the node's instance id answers, or 401 for an instance that requires tokens:
* Floci's 404, for a caller it doesn't know by its address, or another server's error leaves it waiting. With
* curl, or with wget, whose status line {@code -S} prints: GNU's prints no status in its own message for a 401.
*/
@ParameterizedTest
@CsvSource({"curl, 200, 0", "curl, 401, 0", "curl, 404, 1", "curl, 500, 1",
"wget, 200, 0", "wget, 401, 0", "wget, 404, 1", "wget, 500, 1"})
void imdsProbeIsReadyOnceTheNodesInstanceIdAnswers(String client, int status, int expectedExit, @TempDir Path dir)
throws Exception {
Path bin = Files.createDirectory(dir.resolve("bin"));
HelperShellFixture.linkHostTools(bin, List.of(client, "env", "grep"));
List<String> asked = new CopyOnWriteArrayList<>();
HttpServer imds = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
try {
imds.createContext("/", exchange -> {
asked.add(exchange.getRequestURI().getPath());
byte[] body = "i-0123456789abcdef0".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
imds.start();
int result = HelperShellFixture.run(
probe(EksPodNetworkRouting.imdsProbeCommand("http://127.0.0.1:" + imds.getAddress().getPort())),
dir, Map.of("PATH", bin.toString()));
assertEquals(expectedExit, result, HelperShellFixture.output(dir));
assertEquals(List.of("/latest/meta-data/instance-id"), asked);
} finally {
imds.stop(0);
}
}
/**
* A bin directory of stand-ins for a stock k3s node's tools, beside the host's awk, sed, grep,
* env, sleep, cat, tr and rm. iptables records its arguments in {@code iptables-calls} and lists,
* in {@code PREROUTING} and {@code OUTPUT}, a rule an earlier Floci on 172.18.0.9 left for the
* address and one rule of another's, and in {@code FLOCI-LINK-LOCAL} the rule an older Floci sent
* the address to its relay with, beside the IMDS one. nslookup records its arguments in
* {@code nslookup-calls} and answers as BusyBox's.
* in {@code PREROUTING} and {@code OUTPUT}, the rules an earlier Floci on 172.18.0.9 left for the
* Pod Identity address and for IMDS and one rule of another's, in {@code FORWARD} the rule an earlier
* Floci refused the pod network's IMDS requests with and one of another's, and in
* {@code FLOCI-LINK-LOCAL} the rules an older Floci sent each address to its relay with. nslookup
* records its arguments in {@code nslookup-calls} and answers as BusyBox's. wget prints the status
* line as BusyBox's does with {@code -S}: a 200 for the node's instance id from IMDS, and Floci's
* 400 for anything else, as for a Pod Identity request without a pod token.
*/
private static Path fakeStockNode(Path dir) throws Exception {
Path bin = Files.createDirectory(dir.resolve("bin"));
@@ -322,13 +391,22 @@ class EksPodNetworkRoutingTest {
+ " echo '-P PREROUTING ACCEPT'\n"
+ " echo '-A PREROUTING -s 10.42.0.0/16 -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT"
+ " --to-destination 172.18.0.9:4566'\n"
+ " echo '-A PREROUTING -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT"
+ " --to-destination 172.18.0.9:9169'\n"
+ " echo '-A PREROUTING -j FLOCI-LINK-LOCAL'\n"
+ "fi\n"
+ "if [ \"$*\" = '-t nat -S OUTPUT' ]; then\n"
+ " echo '-P OUTPUT ACCEPT'\n"
+ " echo '-A OUTPUT -d 169.254.170.23/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.18.0.9:4566'\n"
+ " echo '-A OUTPUT -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 172.18.0.9:9169'\n"
+ " echo '-A OUTPUT -j KUBE-SERVICES'\n"
+ "fi\n"
+ "if [ \"$*\" = '-t filter -S FORWARD' ]; then\n"
+ " echo '-P FORWARD ACCEPT'\n"
+ " echo '-A FORWARD -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j REJECT"
+ " --reject-with tcp-reset'\n"
+ " echo '-A FORWARD -j KUBE-ROUTER-FORWARD'\n"
+ "fi\n"
+ "if [ \"$*\" = '-t nat -S FLOCI-LINK-LOCAL' ]; then\n"
+ " echo '-N FLOCI-LINK-LOCAL'\n"
+ " echo '-A FLOCI-LINK-LOCAL -s 10.42.0.0/16 -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT"
@@ -341,6 +419,9 @@ class EksPodNetworkRoutingTest {
+ "printf 'Server:\\t\\t127.0.0.11\\nAddress:\\t127.0.0.11:53\\n\\nNon-authoritative answer:\\n"
+ "Name:\\tfloci-under-test.internal\\nAddress: 172.18.0.2\\n'\n");
HelperShellFixture.writeTool(bin, "wget", "[ -z \"${http_proxy:-}\" ] || exit 2\n"
+ "case \"$*\" in *' http://169.254.169.254/latest/meta-data/instance-id')\n"
+ " echo ' HTTP/1.1 200 OK' >&2\n exit 0 ;;\nesac\n"
+ "echo ' HTTP/1.1 400 Bad Request' >&2\n"
+ "echo 'wget: server returned error: HTTP/1.1 400 Bad Request' >&2\nexit 1\n");
return bin;
}
@@ -359,6 +440,11 @@ class EksPodNetworkRoutingTest {
"TCP:172.18.0.9:4566").start();
}
/** A probe run on its own: it ends the shell once ready, and otherwise the shell fails. */
private static String[] probe(String probeCommand) {
return new String[]{"sh", "-c", probeCommand + "\nexit 1"};
}
/** {@code command}, an {@code sh -c} one, run with each command it runs printed to its output ({@code sh -x}). */
private static String[] traced(String[] command) {
List<String> arguments = new ArrayList<>(List.of(command));