From 31a19df6f50271e96e75fa373f6df5db42e592a5 Mon Sep 17 00:00:00 2001 From: Simone Primarosa Date: Mon, 21 Sep 2026 22:04:20 +0200 Subject: [PATCH] feat(eks): enable IMDS and link-local metadata access from pod network (#4039) Pods running without hostNetwork: true run in isolated network namespaces managed by the CNI plugin (e.g. flannel in k3s). When pods send requests to link-local addresses such as IMDS (169.254.169.254:80), the packets reach the host node network namespace where CNI portmap installed -A PREROUTING -m addrtype --dst-type LOCAL -j CNI-HOSTPORT-DNAT. Because 169.254.169.254 is assigned to lo, the kernel evaluates its addrtype as LOCAL, causing non-host-network pods to misroute or drop link-local traffic if an ingress controller binds the same port. This introduces EksPodNetworkRouting and an opt-in configuration setting floci.services.eks.imds-pod-network (defaulting to false to preserve default pod network isolation). When enabled alongside floci.services.eks.imds, DNAT iptables rules are programmed in a dedicated FLOCI-LINK-LOCAL chain inserted at rule 1 of PREROUTING. Requests originating from the cluster pod CIDR targeting configured link-local endpoints (such as IMDS at 169.254.169.254:80, and extensible for Pod Identity at 169.254.170.23:80) are explicitly DNATed to the node's loopback listener, preempting CNI-HOSTPORT-DNAT without conflicting with CNI portmap or flannel routing. LinkLocalEndpoint strictly validates IPv4 literal format to reject non-IPs or malformed strings. Rules are idempotent and degrade gracefully if iptables configuration fails, ensuring cluster startup is never aborted. --- docs/services/eks.md | 5 +- .../floci/config/EmulatorConfig.java | 7 ++ .../floci/services/eks/EksClusterManager.java | 24 +++++ .../services/eks/EksPodNetworkRouting.java | 59 ++++++++++++ .../floci/services/eks/LinkLocalEndpoint.java | 49 ++++++++++ src/main/resources/application.yml | 1 + .../services/eks/EksClusterManagerTest.java | 47 +++++++++ .../eks/EksImdsDockerIntegrationTest.java | 96 +++++++++++++++---- .../eks/EksPodNetworkRoutingTest.java | 94 ++++++++++++++++++ 9 files changed, 363 insertions(+), 19 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/eks/EksPodNetworkRouting.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/eks/LinkLocalEndpoint.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/eks/EksPodNetworkRoutingTest.java diff --git a/docs/services/eks.md b/docs/services/eks.md index b73c1ac6a8..916d307424 100644 --- a/docs/services/eks.md +++ b/docs/services/eks.md @@ -400,12 +400,15 @@ curl -s -H "x-aws-ec2-metadata-token: $TOKEN" \ The link-local proxy attaches to the loopback interface of the k3s container network namespace (the node network namespace). - **Reachable from node network namespace:** Workloads configured with `hostNetwork: true` share the node network namespace and can reach `169.254.169.254:80`. This allows local testing of host-network security policies, intrusion-detection rules, and credential exfiltration defenses. -- **Not reachable from ordinary pods:** Pods running in separate pod network namespaces cannot reach `169.254.169.254` through this loopback alias because link-local addresses are non-routable across network namespaces. Pod-CIDR DNAT routing is not implemented. +- **Default isolation for ordinary pods:** By default, pods running in separate pod network namespaces cannot reach `169.254.169.254`. CNI portmap rules on the node intercept local traffic, preserving node credential isolation for multi-tenant or untrusted workloads. +- **Opt-in pod network routing:** When `floci.services.eks.imds-pod-network=true` is set alongside `floci.services.eks.imds=true`, iptables DNAT rules are programmed in a custom `FLOCI-LINK-LOCAL` chain at the head of `PREROUTING`. Traffic originating from the pod CIDR (`10.42.0.0/16`) targeting `169.254.169.254:80` matches first and is routed directly to the local node listener, preempting CNI portmap rules. This enables standard AWS SDK credential resolution inside ordinary pods without requiring `hostNetwork: true`. ### Configuration IMDS proxy initialization is disabled by default (`floci.services.eks.imds=false`). Set `FLOCI_SERVICES_EKS_IMDS=true` to enable the proxy setup inside the k3s container. +Pod network reachability is also disabled by default (`floci.services.eks.imds-pod-network=false`) to maintain pod isolation. Set `FLOCI_SERVICES_EKS_IMDS_POD_NETWORK=true` together with `FLOCI_SERVICES_EKS_IMDS=true` to route pod traffic to the link-local proxy. + A failure to configure the proxy (for example on custom minimal images lacking network utilities) logs a warning and allows cluster startup to continue. ### Hop limits diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index 5c8c72383c..f5fd5beb6d 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -2871,6 +2871,13 @@ public interface EmulatorConfig { @WithDefault("false") boolean imds(); + /** + * When true, routes link-local IMDS traffic from ordinary pod network namespaces to the node's + * link-local listener. Requires {@code imds()} to be enabled. + */ + @WithDefault("false") + boolean imdsPodNetwork(); + /** * When true, configures k3s with the cluster's per-cluster OIDC signing keypair and * advertises Floci's OIDC issuer URL, enabling in-cluster IAM Roles for Service Accounts (IRSA). diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java index 070dae1882..94308e2adc 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java @@ -1057,6 +1057,10 @@ public class EksClusterManager { return; } + if (config.services().eks().imdsPodNetwork()) { + configurePodNetworkRouting(cluster, containerId); + } + LOG.infov("Configured link-local IMDS endpoint for EKS cluster {0}", cluster.getName()); } catch (Exception e) { LOG.warnv("Could not configure link-local IMDS endpoint for EKS cluster {0}: {1}", @@ -1064,6 +1068,26 @@ public class EksClusterManager { } } + void configurePodNetworkRouting(Cluster cluster, String containerId) { + configurePodNetworkRouting(cluster, containerId, EksPodNetworkRouting.DEFAULT_ENDPOINTS); + } + + void configurePodNetworkRouting(Cluster cluster, String containerId, List endpoints) { + try { + String[] routingCmd = EksPodNetworkRouting.buildRoutingCommand( + EksPodNetworkRouting.DEFAULT_POD_CIDR, + endpoints); + ContainerExecResult routing = execInContainerForResult(containerId, routingCmd, 15); + if (routing.exitCode() != 0) { + LOG.warnv("Could not configure link-local pod network routing for EKS cluster {0}: {1}", + cluster.getName(), routing.summary()); + } + } catch (Exception e) { + LOG.warnv("Could not configure link-local pod network routing for EKS cluster {0}: {1}", + cluster.getName(), e.getMessage()); + } + } + void unregisterMetadataEndpoint(Cluster cluster) { Instance nodeInstance = clusterNodeInstances.remove(clusterResourceName(cluster)); if (metadataServer != null && nodeInstance != null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodNetworkRouting.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodNetworkRouting.java new file mode 100644 index 0000000000..a9234590f8 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodNetworkRouting.java @@ -0,0 +1,59 @@ +package io.github.hectorvent.floci.services.eks; + +import java.util.ArrayList; +import java.util.List; + +/** + * Generates iptables routing rules for link-local endpoints inside an EKS cluster container. + *

+ * Programs DNAT rules in the node network namespace nat table so traffic originating + * from the cluster pod CIDR directed at link-local addresses (such as IMDS 169.254.169.254:80 + * and EKS Pod Identity 169.254.170.23:80) reaches Floci's node listener rather than being + * dropped by the Linux kernel or hijacked by CNI hostPort ingress rules. + */ +public final class EksPodNetworkRouting { + + public static final String DEFAULT_POD_CIDR = "10.42.0.0/16"; + public static final String CHAIN_NAME = "FLOCI-LINK-LOCAL"; + public static final LinkLocalEndpoint IMDS_ENDPOINT = new LinkLocalEndpoint("169.254.169.254", 80); + public static final List DEFAULT_ENDPOINTS = List.of(IMDS_ENDPOINT); + + private EksPodNetworkRouting() {} + + /** + * Builds a POSIX sh command array that idempotently programs iptables DNAT rules + * in the node container nat table for the specified link-local endpoints. + * + * @param podCidr pod network CIDR (defaults to {@link #DEFAULT_POD_CIDR} if null or blank) + * @param endpoints link-local endpoints to route from the pod network + * @return command array suitable for container exec (["sh", "-c", "..."]) + */ + public static String[] buildRoutingCommand(String podCidr, List endpoints) { + String cidr = (podCidr != null && !podCidr.isBlank()) ? podCidr : DEFAULT_POD_CIDR; + if (endpoints == null || endpoints.isEmpty()) { + throw new IllegalArgumentException("endpoints cannot be null or empty"); + } + + List lines = new ArrayList<>(); + lines.add("set -eu"); + lines.add("IPTABLES=$(command -v iptables 2>/dev/null || command -v /bin/aux/iptables 2>/dev/null || true)"); + lines.add("if [ -z \"$IPTABLES\" ]; then"); + lines.add(" echo 'iptables not found in container' >&2"); + lines.add(" exit 1"); + lines.add("fi"); + lines.add("$IPTABLES -t nat -N " + CHAIN_NAME + " 2>/dev/null || true"); + lines.add("$IPTABLES -t nat -C PREROUTING -j " + CHAIN_NAME + " 2>/dev/null || $IPTABLES -t nat -I PREROUTING 1 -j " + CHAIN_NAME); + + for (LinkLocalEndpoint ep : endpoints) { + String check = String.format( + "$IPTABLES -t nat -C %s -s %s -d %s -p tcp --dport %d -j DNAT --to-destination %s:%d 2>/dev/null", + CHAIN_NAME, cidr, ep.ip(), ep.port(), ep.ip(), ep.port()); + String add = String.format( + "$IPTABLES -t nat -A %s -s %s -d %s -p tcp --dport %d -j DNAT --to-destination %s:%d", + CHAIN_NAME, cidr, ep.ip(), ep.port(), ep.ip(), ep.port()); + lines.add(check + " || " + add); + } + + return new String[]{"sh", "-c", String.join("\n", lines)}; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/LinkLocalEndpoint.java b/src/main/java/io/github/hectorvent/floci/services/eks/LinkLocalEndpoint.java new file mode 100644 index 0000000000..48d2091a85 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eks/LinkLocalEndpoint.java @@ -0,0 +1,49 @@ +package io.github.hectorvent.floci.services.eks; + +import java.util.Objects; + +/** + * Represents a link-local network endpoint (IP address and TCP port) + * routed from pod network namespaces to local node listeners. + */ +public record LinkLocalEndpoint(String ip, int port) { + + public LinkLocalEndpoint { + Objects.requireNonNull(ip, "ip cannot be null"); + if (ip.isBlank()) { + throw new IllegalArgumentException("ip cannot be blank"); + } + if (!isValidIpv4Literal(ip.trim())) { + throw new IllegalArgumentException("ip must be a valid IPv4 address literal: " + ip); + } + if (port <= 0 || port > 65535) { + throw new IllegalArgumentException("port must be between 1 and 65535"); + } + ip = ip.trim(); + } + + private static boolean isValidIpv4Literal(String ip) { + String[] parts = ip.split("\\.", -1); + if (parts.length != 4) { + return false; + } + for (String part : parts) { + if (part.isEmpty() || part.length() > 3) { + return false; + } + for (int i = 0; i < part.length(); i++) { + if (!Character.isDigit(part.charAt(i))) { + return false; + } + } + int val = Integer.parseInt(part); + if (val < 0 || val > 255) { + return false; + } + if (part.length() > 1 && part.startsWith("0")) { + return false; + } + } + return true; + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 736b909aff..9fd286fcec 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -602,6 +602,7 @@ floci: ecr-registry-mirror: true # inject a registries.yaml so pods can pull images pushed to Floci ECR disable-cni: false # start k3s without its bundled flannel/kube-proxy so a real CNI (e.g. Cilium) can take over imds: false # expose link-local IMDS (169.254.169.254) inside the cluster container + imds-pod-network: false # route link-local IMDS traffic from ordinary pod network namespaces (requires imds: true) irsa-signing-key: true # sign k3s service account tokens with the cluster OIDC key mwaa: enabled: true diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java index ce52ad3a3d..f5f6c72946 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java @@ -775,6 +775,7 @@ class EksClusterManagerTest { manager.configureLinkLocalMetadataEndpoint(cluster, "container-42"); verify(metadataServer).reconcileContainerAddresses(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")); @@ -785,9 +786,34 @@ class EksClusterManagerTest { assertNotNull(manager.getRegisteredClusterNodeInstance(cluster)); } + @Test + void configuresPodNetworkRoutingWhenImdsPodNetworkEnabled() { + when(eks.imdsPodNetwork()).thenReturn(true); + + Cluster cluster = new Cluster(); + cluster.setName("test-cluster"); + + manager.configureLinkLocalMetadataEndpoint(cluster, "container-42"); + + verify(metadataServer).reconcileContainerAddresses(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")); + + assertNotNull(manager.getRegisteredClusterNodeInstance(cluster)); + } + @Test void skipsWhenImdsIsDisabled() { when(eks.imds()).thenReturn(false); + when(eks.imdsPodNetwork()).thenReturn(true); Cluster cluster = new Cluster(); cluster.setName("test-cluster"); @@ -810,6 +836,27 @@ class EksClusterManagerTest { manager.configureLinkLocalMetadataEndpoint(cluster, "container-42"); } + @Test + void podNetworkRoutingFailureLogsWarningAndDoesNotAbort() { + 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(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 + manager.configureLinkLocalMetadataEndpoint(cluster, "container-42"); + + assertEquals(3, capturedCmds.size()); + assertNotNull(manager.getRegisteredClusterNodeInstance(cluster)); + } + @Test void unregisterMetadataEndpointRemovesInstance() { Cluster cluster = new Cluster(); diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksImdsDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksImdsDockerIntegrationTest.java index e9a7361848..afb55bfdc1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksImdsDockerIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksImdsDockerIntegrationTest.java @@ -8,6 +8,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; import io.github.hectorvent.floci.core.common.docker.ContainerSpec; +import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer; import io.github.hectorvent.floci.services.eks.model.Cluster; import io.quarkus.test.junit.QuarkusTest; @@ -38,7 +39,9 @@ class EksImdsDockerIntegrationTest { public static final class Profile implements QuarkusTestProfile { @Override public Map getConfigOverrides() { - return Map.of("floci.services.eks.imds", "true"); + return Map.of( + "floci.services.eks.imds", "true", + "floci.services.eks.imds-pod-network", "true"); } } @@ -63,6 +66,9 @@ class EksImdsDockerIntegrationTest { @Inject EksClusterManager eksClusterManager; + @Inject + DockerHostResolver dockerHostResolver; + private String containerId; private Cluster cluster; @@ -73,6 +79,8 @@ class EksImdsDockerIntegrationTest { LOG.warn("Docker daemon is not available; skipping EksImdsDockerIntegrationTest"); } Assumptions.assumeTrue(dockerAvailable, "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"); metadataServer.start().join(); } @@ -106,9 +114,9 @@ class EksImdsDockerIntegrationTest { containerId = lifecycleManager.createAndStart(spec).containerId(); assertNotNull(containerId, "Container ID must not be null"); - // Ensure curl dependency is installed in the test fixture if absent + // 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 || apk add --no-cache curl"}); + "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"}); eksClusterManager.configureLinkLocalMetadataEndpoint(cluster, containerId); @@ -124,26 +132,78 @@ class EksImdsDockerIntegrationTest { 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 (tool guaranteed by alpine:3.21 image) + // 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-isolation test: ordinary pods in their own network namespace cannot reach link-local IMDS - // Tested using wget (tool guaranteed by alpine:3.21 image) - String podIsolationCmd = """ - if command -v unshare >/dev/null 2>&1; then - unshare -n wget -q -O - -T 2 http://169.254.169.254/latest/meta-data/instance-id - else - ip netns add pod-test 2>/dev/null || true - ip netns exec pod-test wget -q -O - -T 2 http://169.254.169.254/latest/meta-data/instance-id - ret=$? - ip netns del pod-test 2>/dev/null || true - exit $ret - fi + // 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 """; - ExecResult podResult = execInContainerWithExitCode(containerId, new String[]{"sh", "-c", podIsolationCmd}); - assertNotEquals(0L, podResult.exitCode(), "IMDS should not be reachable from an isolated pod network namespace"); + 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"}); + ExecResult 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() { diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodNetworkRoutingTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodNetworkRoutingTest.java new file mode 100644 index 0000000000..40d3f9852a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodNetworkRoutingTest.java @@ -0,0 +1,94 @@ +package io.github.hectorvent.floci.services.eks; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +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 { + + @Test + void linkLocalEndpointValidatesInput() { + assertThrows(NullPointerException.class, () -> new LinkLocalEndpoint(null, 80)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint("", 80)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint(" ", 80)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint("invalid-ip", 80)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint("169.254.169.256", 80)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint("-1.0.0.0", 80)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint("169.254.169", 80)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint("169.254.169.254.1", 80)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint("169.254.01.1", 80)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint("; rm -rf / ;", 80)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint("169.254.169.254", 0)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint("169.254.169.254", -1)); + assertThrows(IllegalArgumentException.class, () -> new LinkLocalEndpoint("169.254.169.254", 65536)); + + LinkLocalEndpoint ep = new LinkLocalEndpoint("169.254.169.254", 80); + assertEquals("169.254.169.254", ep.ip()); + 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")); + } +}