From 6871348ea65b9500064c47c665ccfca055b71f16 Mon Sep 17 00:00:00 2001 From: mrfelek <17274927+mrfelek@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:01:02 +0100 Subject: [PATCH] refactor(ec2): remove the metadata proxy commands only tests call (#8925) --- .../aws/services/ec2/Ec2MetadataProxy.java | 324 ++++++++---------- .../services/ec2/Ec2MetadataProxyTest.java | 119 ++++--- ...ityGroupFirewallDockerIntegrationTest.java | 20 +- 3 files changed, 224 insertions(+), 239 deletions(-) diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2MetadataProxy.java b/src/main/java/io/floci/aws/services/ec2/Ec2MetadataProxy.java index 096d7f2c51..ed706360e0 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2MetadataProxy.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2MetadataProxy.java @@ -52,15 +52,7 @@ public final class Ec2MetadataProxy { + " { mkdir -p /sys/fs/cgroup/floci && echo $$ >/sys/fs/cgroup/floci/cgroup.procs; } 2>/dev/null || true;" + " fi"; - public static String[] installCommand() { - return installCommand(false); - } - static String[] installEc2Command() { - return installCommand(true); - } - - private static String[] installCommand(boolean requireIptables) { List lines = new ArrayList<>(List.of( "set -eu", LEAVE_ROOT_CGROUP, @@ -90,33 +82,26 @@ public final class Ec2MetadataProxy { " echo 'No supported package manager found for IMDS proxy dependencies' >&2", " exit 1", "fi")); - if (requireIptables) { - // A guest without a NAT tool can still use the pre-upgrade TCP/80 relay. - lines.add("if ! command -v iptables >/dev/null 2>&1 && ! command -v nft >/dev/null 2>&1; then"); - lines.add(" if command -v apt-get >/dev/null 2>&1; then"); - lines.add(" { apt-get update -qq >/dev/null" - + " && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends" - + " iptables >/dev/null; } || true"); - lines.add(" elif command -v dnf >/dev/null 2>&1; then"); - lines.add(" dnf install -y --allowerasing iptables-nft >/dev/null || true"); - lines.add(" elif command -v yum >/dev/null 2>&1; then"); - lines.add(" yum install -y iptables >/dev/null || true"); - lines.add(" elif command -v apk >/dev/null 2>&1; then"); - lines.add(" apk add --no-cache iptables >/dev/null || true"); - lines.add(" fi"); - lines.add("fi"); - } + // A guest without a NAT tool can still use the pre-upgrade TCP/80 relay. + lines.add("if ! command -v iptables >/dev/null 2>&1 && ! command -v nft >/dev/null 2>&1; then"); + lines.add(" if command -v apt-get >/dev/null 2>&1; then"); + lines.add(" { apt-get update -qq >/dev/null" + + " && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends" + + " iptables >/dev/null; } || true"); + lines.add(" elif command -v dnf >/dev/null 2>&1; then"); + lines.add(" dnf install -y --allowerasing iptables-nft >/dev/null || true"); + lines.add(" elif command -v yum >/dev/null 2>&1; then"); + lines.add(" yum install -y iptables >/dev/null || true"); + lines.add(" elif command -v apk >/dev/null 2>&1; then"); + lines.add(" apk add --no-cache iptables >/dev/null || true"); + lines.add(" fi"); + lines.add("fi"); return new String[]{"sh", "-c", String.join("\n", lines)}; } - public static String[] startCommand(String flociHost, int imdsPort) { - return startCommand("imds", "169.254.169.254", 80, flociHost, imdsPort, - imdsProbeCommand("http://169.254.169.254")); - } - static String[] startEc2Command(String flociHost, int imdsPort) { return startCommand("imds", "169.254.169.254", EC2_IMDS_RELAY_PORT, flociHost, imdsPort, - imdsProbeCommand("http://169.254.169.254"), true); + imdsProbeCommand("http://169.254.169.254")); } /** @@ -133,16 +118,10 @@ public final class Ec2MetadataProxy { + endpoint + "/latest/meta-data/instance-id >/dev/null && exit 0"; } - public static String[] startCommand(String name, String bindIp, int bindPort, - String targetHost, int targetPort, String probeCommand) { - return startCommand(name, bindIp, bindPort, targetHost, targetPort, probeCommand, false); - } - private static String[] startCommand(String name, String bindIp, int bindPort, - String targetHost, int targetPort, String probeCommand, - boolean routeImdsPort) { + String targetHost, int targetPort, String probeCommand) { String legacyPidFile = relayPidFile(name); - String pidFile = routeImdsPort ? "/tmp/floci-" + name + "-proxy-" + bindPort + ".pid" : legacyPidFile; + String pidFile = "/tmp/floci-" + name + "-proxy-" + bindPort + ".pid"; String logFile = "/tmp/floci-" + name + "-proxy.log"; String listener = "TCP-LISTEN:" + bindPort + ",bind=" + bindIp + ","; String ruleMatch = "-d " + bindIp + "/32 -p tcp --dport 80 -j DNAT --to-destination " @@ -157,161 +136,142 @@ public final class Ec2MetadataProxy { // The writable-layer PID file survives a container restart, so verify the process name and // listener arguments before reusing it or retiring a pre-upgrade TCP/80 listener. - if (routeImdsPort) { - lines.add("legacy_pid="); - lines.add(socatPidCheck(legacyPidFile, "TCP-LISTEN:80,bind=" + bindIp + ",")); - lines.add(" legacy_pid=$pid"); - lines.add("fi"); - lines.add("proxy_running=0"); - lines.add("new_pid="); - lines.add("rule_added=0"); - lines.add("rule_backend="); - lines.add("nft_chain_created=0"); - lines.add("nft_rule_marker=" + nftRuleMarker + "-$$"); - lines.add("legacy_new_pid="); - lines.add("fallback_legacy=0"); - lines.add("remove_nft_rule() {"); - lines.add(" nft -a list chain ip floci_imds output 2>/dev/null" - + " | grep -F \"comment \\\"$1\\\"\" | while IFS= read -r rule; do"); - lines.add(" case \"$rule\" in"); - lines.add(" *'# handle '*) nft delete rule ip floci_imds output" - + " handle \"${rule##*# handle }\" 2>/dev/null || true ;;"); - lines.add(" esac"); - lines.add(" done"); - lines.add("}"); - lines.add("cleanup_new_proxy() {"); - lines.add(" if [ -n \"$new_pid\" ]; then"); - lines.add(" if is_socat_listener \"$new_pid\" '" + listener + "'; then"); - lines.add(" kill \"$new_pid\" 2>/dev/null || true"); - lines.add(" fi"); - lines.add(" if [ \"$(cat " + pidFile + " 2>/dev/null)\" = \"$new_pid\" ]; then"); - lines.add(" rm -f " + pidFile); - lines.add(" fi"); - lines.add(" fi"); - lines.add(" if [ \"$rule_added\" -eq 1 ]; then"); - lines.add(" if [ \"$rule_backend\" = nft ]; then"); - lines.add(" remove_nft_rule \"$nft_rule_marker\" || true"); - lines.add(" else"); - lines.add(" iptables -t nat -D OUTPUT " + ruleMatch + " 2>/dev/null || true"); - lines.add(" fi"); - lines.add(" fi"); - lines.add(" if [ \"$nft_chain_created\" -eq 1 ]; then"); - lines.add(" nft delete chain ip floci_imds output 2>/dev/null || true"); - lines.add(" fi"); - lines.add(" if [ -n \"$legacy_new_pid\" ]; then"); - lines.add(" if is_socat_listener \"$legacy_new_pid\" 'TCP-LISTEN:80,bind=" + bindIp + ",'; then"); - lines.add(" kill \"$legacy_new_pid\" 2>/dev/null || true"); - lines.add(" fi"); - lines.add(" if [ \"$(cat " + legacyPidFile + " 2>/dev/null)\" = \"$legacy_new_pid\" ]; then"); - lines.add(" rm -f " + legacyPidFile); - lines.add(" fi"); - lines.add(" fi"); - lines.add("}"); - } + lines.add("legacy_pid="); + lines.add(socatPidCheck(legacyPidFile, "TCP-LISTEN:80,bind=" + bindIp + ",")); + lines.add(" legacy_pid=$pid"); + lines.add("fi"); + lines.add("proxy_running=0"); + lines.add("new_pid="); + lines.add("rule_added=0"); + lines.add("rule_backend="); + lines.add("nft_chain_created=0"); + lines.add("nft_rule_marker=" + nftRuleMarker + "-$$"); + lines.add("legacy_new_pid="); + lines.add("fallback_legacy=0"); + lines.add("remove_nft_rule() {"); + lines.add(" nft -a list chain ip floci_imds output 2>/dev/null" + + " | grep -F \"comment \\\"$1\\\"\" | while IFS= read -r rule; do"); + lines.add(" case \"$rule\" in"); + lines.add(" *'# handle '*) nft delete rule ip floci_imds output" + + " handle \"${rule##*# handle }\" 2>/dev/null || true ;;"); + lines.add(" esac"); + lines.add(" done"); + lines.add("}"); + lines.add("cleanup_new_proxy() {"); + lines.add(" if [ -n \"$new_pid\" ]; then"); + lines.add(" if is_socat_listener \"$new_pid\" '" + listener + "'; then"); + lines.add(" kill \"$new_pid\" 2>/dev/null || true"); + lines.add(" fi"); + lines.add(" if [ \"$(cat " + pidFile + " 2>/dev/null)\" = \"$new_pid\" ]; then"); + lines.add(" rm -f " + pidFile); + lines.add(" fi"); + lines.add(" fi"); + lines.add(" if [ \"$rule_added\" -eq 1 ]; then"); + lines.add(" if [ \"$rule_backend\" = nft ]; then"); + lines.add(" remove_nft_rule \"$nft_rule_marker\" || true"); + lines.add(" else"); + lines.add(" iptables -t nat -D OUTPUT " + ruleMatch + " 2>/dev/null || true"); + lines.add(" fi"); + lines.add(" fi"); + lines.add(" if [ \"$nft_chain_created\" -eq 1 ]; then"); + lines.add(" nft delete chain ip floci_imds output 2>/dev/null || true"); + lines.add(" fi"); + lines.add(" if [ -n \"$legacy_new_pid\" ]; then"); + lines.add(" if is_socat_listener \"$legacy_new_pid\" 'TCP-LISTEN:80,bind=" + bindIp + ",'; then"); + lines.add(" kill \"$legacy_new_pid\" 2>/dev/null || true"); + lines.add(" fi"); + lines.add(" if [ \"$(cat " + legacyPidFile + " 2>/dev/null)\" = \"$legacy_new_pid\" ]; then"); + lines.add(" rm -f " + legacyPidFile); + lines.add(" fi"); + lines.add(" fi"); + lines.add("}"); lines.add(socatPidCheck(pidFile, listener)); - if (routeImdsPort) { - lines.add(" proxy_running=1"); - lines.add("fi"); - lines.add("if [ \"$proxy_running\" -eq 0 ]; then"); - } else { - lines.add(" exit 0"); - lines.add("fi"); - } - lines.add((routeImdsPort ? " " : "") + "nohup socat " + listener + "fork,reuseaddr TCP:" + lines.add(" proxy_running=1"); + lines.add("fi"); + lines.add("if [ \"$proxy_running\" -eq 0 ]; then"); + lines.add(" nohup socat " + listener + "fork,reuseaddr TCP:" + targetHost + ":" + targetPort + " >" + logFile + " 2>&1 &"); - if (routeImdsPort) { - lines.add(" new_pid=$!"); - lines.add(" echo \"$new_pid\" > " + pidFile); - } else { - lines.add("echo $! > " + pidFile); - } - if (routeImdsPort) { - lines.add("fi"); - lines.add("if command -v nft >/dev/null 2>&1" - + " && nft list chain ip floci_imds output 2>/dev/null" - + " | grep -F 'comment \"" + nftRuleMarker + "'" - + " | grep -Fq 'ip daddr " + bindIp + " tcp dport 80 dnat to " - + bindIp + ":" + bindPort + "'; then"); - lines.add(" rule_backend=nft"); - lines.add("fi"); - lines.add("if [ -z \"$rule_backend\" ] && command -v iptables >/dev/null 2>&1; then"); - lines.add(" if iptables -t nat -C OUTPUT " + ruleMatch + " 2>/dev/null; then"); - lines.add(" rule_backend=iptables"); - lines.add(" elif ! { command -v nft >/dev/null 2>&1" - + " && nft list table ip floci_imds >/dev/null 2>&1; }" - + " && iptables -t nat -I OUTPUT 1 " + ruleMatch + "; then"); - lines.add(" rule_backend=iptables"); - lines.add(" rule_added=1"); - lines.add(" fi"); - lines.add("fi"); - lines.add("if [ -z \"$rule_backend\" ] && command -v nft >/dev/null 2>&1; then"); - lines.add(" nft_ready=1"); - lines.add(" if ! nft list table ip floci_imds >/dev/null 2>&1; then"); - lines.add(" nft add table ip floci_imds || nft_ready=0"); - lines.add(" fi"); - lines.add(" if [ \"$nft_ready\" -eq 1 ]" - + " && ! nft list chain ip floci_imds output >/dev/null 2>&1; then"); - lines.add(" if printf '%s\\n'" - + " 'add chain ip floci_imds output { type nat hook output priority -100; policy accept; }'" - + " | nft -f -; then"); - lines.add(" nft_chain_created=1"); - lines.add(" else"); - lines.add(" nft_ready=0"); - lines.add(" fi"); - lines.add(" fi"); - lines.add(" if [ \"$nft_ready\" -eq 1 ]; then"); - lines.add(" if printf '%s\\n' \"insert rule ip floci_imds output ip daddr " + bindIp - + " tcp dport 80 dnat to " + bindIp + ":" + bindPort - + " comment \\\"$nft_rule_marker\\\"\" | nft -f -; then"); - lines.add(" rule_backend=nft"); - lines.add(" rule_added=1"); - lines.add(" fi"); - lines.add(" fi"); - lines.add("fi"); - lines.add("if [ -z \"$rule_backend\" ] && command -v iptables >/dev/null 2>&1" - + " && iptables -t nat -I OUTPUT 1 " + ruleMatch + "; then"); - lines.add(" rule_backend=iptables"); - lines.add(" rule_added=1"); - lines.add("fi"); - lines.add("if [ -z \"$rule_backend\" ]; then"); - lines.add(" cleanup_new_proxy"); - lines.add(" fallback_legacy=1"); - lines.add(" if [ -z \"$legacy_pid\" ]; then"); - lines.add(" nohup socat TCP-LISTEN:80,bind=" + bindIp + ",fork,reuseaddr TCP:" - + targetHost + ":" + targetPort + " >" + logFile + " 2>&1 &"); - lines.add(" legacy_new_pid=$!"); - lines.add(" echo \"$legacy_new_pid\" > " + legacyPidFile); - lines.add(" fi"); - lines.add("fi"); - } + lines.add(" new_pid=$!"); + lines.add(" echo \"$new_pid\" > " + pidFile); + lines.add("fi"); + lines.add("if command -v nft >/dev/null 2>&1" + + " && nft list chain ip floci_imds output 2>/dev/null" + + " | grep -F 'comment \"" + nftRuleMarker + "'" + + " | grep -Fq 'ip daddr " + bindIp + " tcp dport 80 dnat to " + + bindIp + ":" + bindPort + "'; then"); + lines.add(" rule_backend=nft"); + lines.add("fi"); + lines.add("if [ -z \"$rule_backend\" ] && command -v iptables >/dev/null 2>&1; then"); + lines.add(" if iptables -t nat -C OUTPUT " + ruleMatch + " 2>/dev/null; then"); + lines.add(" rule_backend=iptables"); + lines.add(" elif ! { command -v nft >/dev/null 2>&1" + + " && nft list table ip floci_imds >/dev/null 2>&1; }" + + " && iptables -t nat -I OUTPUT 1 " + ruleMatch + "; then"); + lines.add(" rule_backend=iptables"); + lines.add(" rule_added=1"); + lines.add(" fi"); + lines.add("fi"); + lines.add("if [ -z \"$rule_backend\" ] && command -v nft >/dev/null 2>&1; then"); + lines.add(" nft_ready=1"); + lines.add(" if ! nft list table ip floci_imds >/dev/null 2>&1; then"); + lines.add(" nft add table ip floci_imds || nft_ready=0"); + lines.add(" fi"); + lines.add(" if [ \"$nft_ready\" -eq 1 ]" + + " && ! nft list chain ip floci_imds output >/dev/null 2>&1; then"); + lines.add(" if printf '%s\\n'" + + " 'add chain ip floci_imds output { type nat hook output priority -100; policy accept; }'" + + " | nft -f -; then"); + lines.add(" nft_chain_created=1"); + lines.add(" else"); + lines.add(" nft_ready=0"); + lines.add(" fi"); + lines.add(" fi"); + lines.add(" if [ \"$nft_ready\" -eq 1 ]; then"); + lines.add(" if printf '%s\\n' \"insert rule ip floci_imds output ip daddr " + bindIp + + " tcp dport 80 dnat to " + bindIp + ":" + bindPort + + " comment \\\"$nft_rule_marker\\\"\" | nft -f -; then"); + lines.add(" rule_backend=nft"); + lines.add(" rule_added=1"); + lines.add(" fi"); + lines.add(" fi"); + lines.add("fi"); + lines.add("if [ -z \"$rule_backend\" ] && command -v iptables >/dev/null 2>&1" + + " && iptables -t nat -I OUTPUT 1 " + ruleMatch + "; then"); + lines.add(" rule_backend=iptables"); + lines.add(" rule_added=1"); + lines.add("fi"); + lines.add("if [ -z \"$rule_backend\" ]; then"); + lines.add(" cleanup_new_proxy"); + lines.add(" fallback_legacy=1"); + lines.add(" if [ -z \"$legacy_pid\" ]; then"); + lines.add(" nohup socat TCP-LISTEN:80,bind=" + bindIp + ",fork,reuseaddr TCP:" + + targetHost + ":" + targetPort + " >" + logFile + " 2>&1 &"); + lines.add(" legacy_new_pid=$!"); + lines.add(" echo \"$legacy_new_pid\" > " + legacyPidFile); + lines.add(" fi"); + lines.add("fi"); lines.add("for i in 1 2 3 4 5 6 7 8 9 10 11 12; do"); - if (routeImdsPort) { - lines.add(" if (" + probeCommand + "); then"); - lines.add(" if [ \"$fallback_legacy\" -eq 0 ] && [ -n \"$legacy_pid\" ]" - + " && is_socat_listener \"$legacy_pid\" 'TCP-LISTEN:80,bind=" + bindIp + ",'; then"); - lines.add(" kill \"$legacy_pid\" 2>/dev/null || true"); - lines.add(" if [ \"$(cat " + legacyPidFile + " 2>/dev/null)\" = \"$legacy_pid\" ]; then"); - lines.add(" rm -f " + legacyPidFile); - lines.add(" fi"); - lines.add(" fi"); - lines.add(" exit 0"); - lines.add(" fi"); - } else { - lines.add(" " + probeCommand); - } + lines.add(" if (" + probeCommand + "); then"); + lines.add(" if [ \"$fallback_legacy\" -eq 0 ] && [ -n \"$legacy_pid\" ]" + + " && is_socat_listener \"$legacy_pid\" 'TCP-LISTEN:80,bind=" + bindIp + ",'; then"); + lines.add(" kill \"$legacy_pid\" 2>/dev/null || true"); + lines.add(" if [ \"$(cat " + legacyPidFile + " 2>/dev/null)\" = \"$legacy_pid\" ]; then"); + lines.add(" rm -f " + legacyPidFile); + lines.add(" fi"); + lines.add(" fi"); + lines.add(" exit 0"); + lines.add(" fi"); lines.add(" sleep 1"); lines.add("done"); - if (routeImdsPort) { - lines.add("cleanup_new_proxy"); - } + lines.add("cleanup_new_proxy"); lines.add("cat " + logFile + " >&2 || true"); lines.add("exit 1"); return new String[]{"sh", "-c", String.join("\n", lines)}; } /** - * Shell lines that retire the relay {@link #startCommand(String, String, int, String, int, String)} started as - * {@code name} on {@code bindIp}, port 80: the socat its PID file names, while that is still the relay, then the + * Shell lines that retire the relay an older Floci ran as {@code name} on {@code bindIp}, port 80, on an EKS + * node: the socat its PID file names, while that is still the relay, then the * PID file and the loopback address the relay was given. A node without the relay, or without {@code ip}, is * left as it is. */ diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2MetadataProxyTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2MetadataProxyTest.java index 987037bac9..1e1fc20934 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2MetadataProxyTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2MetadataProxyTest.java @@ -18,7 +18,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; -import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; @@ -30,6 +29,9 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; class Ec2MetadataProxyTest { + /** Where the relay {@link Ec2MetadataProxy#startEc2Command} starts keeps its PID. */ + private static final String EC2_RELAY_PID_FILE = "/tmp/floci-imds-proxy-42169.pid"; + @Test void everyProxyCommandLeavesTheRootCgroupBeforeItStartsAnything() { // A process left in the root of a systemd guest's private cgroup namespace keeps cgroup v2 @@ -41,9 +43,7 @@ class Ec2MetadataProxyTest { // Best effort: a read-only cgroupfs must not abort a script running under set -e. assertTrue(prelude.contains("2>/dev/null || true;")); for (String[] command : new String[][]{ - Ec2MetadataProxy.installCommand(), Ec2MetadataProxy.installEc2Command(), - Ec2MetadataProxy.startCommand("10.0.0.1", 9169), Ec2MetadataProxy.startEc2Command("10.0.0.1", 9169)}) { assertTrue(command[2].startsWith("set -eu\n" + prelude + "\n"), command[2]); } @@ -88,24 +88,26 @@ class Ec2MetadataProxyTest { @Test void installCommandContainsSupportedPackageManagers() { - String[] command = Ec2MetadataProxy.installCommand(); + String[] command = Ec2MetadataProxy.installEc2Command(); assertEquals(3, command.length); assertEquals("sh", command[0]); assertEquals("-c", command[1]); String script = command[2]; assertTrue(script.contains("command -v curl >/dev/null 2>&1; then exit 0; fi")); - assertFalse(script.contains("command -v iptables")); assertTrue(script.contains("apt-get install -y --no-install-recommends iproute2 socat curl ca-certificates")); assertTrue(script.contains("dnf install -y --allowerasing iproute socat curl ca-certificates")); assertTrue(script.contains("yum install -y iproute socat curl ca-certificates")); assertTrue(script.contains("apk add --no-cache iproute2 socat curl ca-certificates")); - assertFalse(script.contains("iptables-nft")); + // A NAT tool for the routed relay, only where the guest has neither. + assertTrue(script.contains( + "if ! command -v iptables >/dev/null 2>&1 && ! command -v nft >/dev/null 2>&1; then")); + assertTrue(script.contains("apk add --no-cache iptables >/dev/null || true")); } @Test void startCommandAttachesAddressIdempotentlyAndTargetsHostAndPort() { - String[] command = Ec2MetadataProxy.startCommand("10.0.0.1", 9169); + String[] command = Ec2MetadataProxy.startEc2Command("10.0.0.1", 9169); assertEquals(3, command.length); assertEquals("sh", command[0]); assertEquals("-c", command[1]); @@ -115,10 +117,10 @@ class Ec2MetadataProxyTest { 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("is_socat_listener() {"), script); - assertTrue(script.contains("is_socat_listener \"$pid\" 'TCP-LISTEN:80,bind=169.254.169.254,'; then" - + "\n exit 0\nfi"), script); + assertTrue(script.contains("is_socat_listener \"$pid\" 'TCP-LISTEN:42169,bind=169.254.169.254,'; then" + + "\n proxy_running=1\nfi"), script); // 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 &")); + assertTrue(script.contains("nohup socat TCP-LISTEN:42169,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. assertTrue(script.contains("-X PUT -H 'X-aws-ec2-metadata-token-ttl-seconds: 60'")); assertTrue(script.contains("http://169.254.169.254/latest/api/token")); @@ -187,16 +189,16 @@ class Ec2MetadataProxyTest { Path record = directory.resolve("tools"); Path arguments = directory.resolve("arguments"); HelperShellFixture.writeTool(bin, "dnf", HelperShellFixture.checkedToolEnvironment() - + "printf '%s\\n' \"$*\" > \"$TEST_ARGUMENTS\"\n"); + + "printf '%s\\n' \"$*\" >> \"$TEST_ARGUMENTS\"\n"); - assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.installCommand(), directory, + assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.installEc2Command(), directory, HelperShellFixture.applicationEnvironment(Map.of("PATH", bin.toString(), "TEST_RECORD", record.toString(), "TEST_ARGUMENTS", arguments.toString()))), HelperShellFixture.output(directory)); - assertEquals("dnf\n", Files.readString(record)); - assertEquals("install -y --allowerasing iproute socat curl ca-certificates\n", - Files.readString(arguments)); + assertEquals("dnf\ndnf\n", Files.readString(record)); + assertEquals("install -y --allowerasing iproute socat curl ca-certificates\n" + + "install -y --allowerasing iptables-nft\n", Files.readString(arguments)); } @Test @@ -354,9 +356,21 @@ class Ec2MetadataProxyTest { + "esac\n"); } + /** {@link #writeEc2StartTools}, with a socat that leaves {@code proxyStarted} and IMDS answering only after it. */ + private static void writeEc2StartToolsReadyOnceSocatRuns(Path bin, Path proxyStarted) throws Exception { + writeEc2StartTools(bin); + HelperShellFixture.writeTool(bin, "socat", ": > '" + proxyStarted + "'\n"); + HelperShellFixture.writeTool(bin, "curl", "[ -f '" + proxyStarted + "' ] || exit 1\n" + + "case \"$*\" in\n" + + " *'/latest/api/token') printf '%s' fixture-token ;;\n" + + " *'/latest/meta-data/instance-id') printf '%s' i-fixture ;;\n" + + "esac\n"); + HelperShellFixture.writeTool(bin, "iptables", "exit 0\n"); + } + private static void deleteEc2ProxyFiles() throws Exception { Files.deleteIfExists(Path.of("/tmp/floci-imds-proxy.pid")); - Files.deleteIfExists(Path.of("/tmp/floci-imds-proxy-42169.pid")); + Files.deleteIfExists(Path.of(EC2_RELAY_PID_FILE)); Files.deleteIfExists(Path.of("/tmp/floci-imds-proxy.log")); } @@ -367,25 +381,23 @@ class Ec2MetadataProxyTest { Path record = directory.resolve("tools"); Path proxyReady = directory.resolve("proxy-ready"); HelperShellFixture.writeTool(bin, "ip", HelperShellFixture.checkedToolEnvironment() - + "printf '127.0.0.1/32\\n'\n"); + + "printf '%s\\n' 'inet 169.254.169.254/32'\n"); HelperShellFixture.writeTool(bin, "socat", HelperShellFixture.checkedToolEnvironment() + ": > \"$TEST_PROXY_READY\"\n"); + HelperShellFixture.writeTool(bin, "iptables", HelperShellFixture.checkedToolEnvironment()); HelperShellFixture.writeTool(bin, "curl", HelperShellFixture.checkedToolEnvironment() + "for attempt in 1 2 3 4 5 6 7 8 9 10; do\n" - + " [ -f \"$TEST_PROXY_READY\" ] && exit 0\n" + + " [ -f \"$TEST_PROXY_READY\" ] && printf '%s' fixture-token && exit 0\n" + " /bin/sleep 0.1\n" + "done\nexit 1\n"); - String name = "unit-" + UUID.randomUUID(); try { - String[] command = Ec2MetadataProxy.startCommand( - name, "127.0.0.1", 80, "127.0.0.1", 9169, "curl fixture && exit 0"); - assertEquals(0, HelperShellFixture.run(command, directory, - HelperShellFixture.applicationEnvironment(Map.of("PATH", bin + ":" + System.getenv("PATH"), + assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169), directory, + HelperShellFixture.applicationEnvironment(Map.of("PATH", bin + ":/usr/bin:/bin", "TEST_RECORD", record.toString(), "TEST_PROXY_READY", proxyReady.toString()))), HelperShellFixture.output(directory)); - assertEquals(Set.of("ip", "socat", "curl"), Set.copyOf(Files.readAllLines(record))); + assertEquals(Set.of("ip", "socat", "iptables", "curl"), Set.copyOf(Files.readAllLines(record))); } finally { - deleteProxyFiles(name); + deleteEc2ProxyFiles(); } } @@ -446,25 +458,32 @@ class Ec2MetadataProxyTest { */ @Test void startScriptRetriesTheTokenProbeUntilATokenIsIssued(@TempDir Path directory) throws Exception { + Path curl = HelperShellFixture.onPath("curl").orElseThrow(); Path bin = Files.createDirectory(directory.resolve("bin")); - HelperShellFixture.writeTool(bin, "ip", "printf '127.0.0.1/32\\n'\n"); - HelperShellFixture.writeTool(bin, "socat", "exit 0\n"); + writeEc2StartTools(bin); + HelperShellFixture.writeTool(bin, "iptables", "exit 0\n"); List requests = new CopyOnWriteArrayList<>(); HttpServer server = metadataStandIn(requests, attempt -> attempt == 1 ? 403 : 200, "fixture-token"); - String name = "unit-" + UUID.randomUUID(); + // The host's curl, with the probe's link-local address sent to the stand-in instead. + HelperShellFixture.writeTool(bin, "curl", "for argument do\n" + + " shift\n" + + " case \"$argument\" in\n" + + " http://169.254.169.254/*) argument=\"http://127.0.0.1:" + server.getAddress().getPort() + + "${argument#http://169.254.169.254}\" ;;\n" + + " esac\n" + + " set -- \"$@\" \"$argument\"\n" + + "done\n" + + "exec '" + curl + "' \"$@\"\n"); try { - String[] command = Ec2MetadataProxy.startCommand(name, "127.0.0.1", 80, "127.0.0.1", 9169, - Ec2MetadataProxy.imdsProbeCommand("http://127.0.0.1:" + server.getAddress().getPort())); - - int result = HelperShellFixture.run(command, directory, - Map.of("PATH", bin + ":" + System.getenv("PATH"))); + int result = HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169), directory, + Map.of("PATH", bin + ":/usr/bin:/bin")); assertEquals(0, result, HelperShellFixture.output(directory)); assertEquals(List.of("PUT token 60", "PUT token 60", "GET metadata fixture-token"), requests, HelperShellFixture.output(directory)); } finally { server.stop(0); - deleteProxyFiles(name); + deleteEc2ProxyFiles(); } } @@ -478,21 +497,18 @@ class Ec2MetadataProxyTest { 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(); + writeEc2StartToolsReadyOnceSocatRuns(bin, proxyStarted); 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"); + Files.writeString(Path.of(EC2_RELAY_PID_FILE), ProcessHandle.current().pid() + "\n"); - int result = HelperShellFixture.run(command, directory, Map.of("PATH", bin + ":" + System.getenv("PATH"))); + int result = HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169), directory, + Map.of("PATH", bin + ":/usr/bin:/bin")); assertEquals(0, result, HelperShellFixture.output(directory)); assertTrue(Files.exists(proxyStarted), "socat was never started: " + HelperShellFixture.output(directory)); } finally { - deleteProxyFiles(name); + deleteEc2ProxyFiles(); } } @@ -507,22 +523,18 @@ class Ec2MetadataProxyTest { 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"; + writeEc2StartToolsReadyOnceSocatRuns(bin, proxyStarted); try { - String[] command = Ec2MetadataProxy.startCommand(name, "127.0.0.1", 80, "127.0.0.1", 9169, - "[ -f '" + proxyStarted + "' ] && exit 0"); + String[] command = Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169); // 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"); + command[2] = command[2].replaceFirst("set -eu\n", "set -eu\necho \\$\\$ > " + EC2_RELAY_PID_FILE + "\n"); - int result = HelperShellFixture.run(command, directory, Map.of("PATH", bin + ":" + System.getenv("PATH"))); + int result = HelperShellFixture.run(command, directory, Map.of("PATH", bin + ":/usr/bin:/bin")); assertEquals(0, result, HelperShellFixture.output(directory)); assertTrue(Files.exists(proxyStarted), "socat was never started: " + HelperShellFixture.output(directory)); } finally { - deleteProxyFiles(name); + deleteEc2ProxyFiles(); } } @@ -572,9 +584,4 @@ class Ec2MetadataProxyTest { options.setHttpTokens("required"); instance.setMetadataOptions(options); } - - private static void deleteProxyFiles(String name) throws Exception { - Files.deleteIfExists(Path.of("/tmp/floci-" + name + "-proxy.pid")); - Files.deleteIfExists(Path.of("/tmp/floci-" + name + "-proxy.log")); - } } diff --git a/src/test/java/io/floci/aws/services/ec2/SecurityGroupFirewallDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/ec2/SecurityGroupFirewallDockerIntegrationTest.java index f4433e91dc..7d1dad0ebe 100644 --- a/src/test/java/io/floci/aws/services/ec2/SecurityGroupFirewallDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ec2/SecurityGroupFirewallDockerIntegrationTest.java @@ -123,7 +123,7 @@ class SecurityGroupFirewallDockerIntegrationTest { assertEquals("fixture-token", fixture.stdout().trim()); ContainerExec.Result legacy = ContainerExec.runMerged(docker, namespace.helperId(), - Ec2MetadataProxy.startCommand("127.0.0.1", 9169), 30); + preUpgradeImdsRelay("127.0.0.1", 9169), 30); assertEquals(0, legacy.exitCode(), "Old IMDS proxy did not start: " + legacy.summary()); ContainerExec.Result removed = ContainerExec.runMerged(docker, namespace.helperId(), @@ -190,6 +190,24 @@ class SecurityGroupFirewallDockerIntegrationTest { } } + /** + * The relay an older Floci started on an instance: socat on port 80 of the link-local address, with its PID in + * the file the routed relay retires it by, ready once an IMDSv2 token reads the instance ID through it. + */ + private static String[] preUpgradeImdsRelay(String flociHost, int imdsPort) { + return new String[]{"sh", "-c", String.join("\n", + "set -eu", + "ip addr show dev lo | grep -q '169.254.169.254/32' || ip addr add 169.254.169.254/32 dev lo", + "nohup socat TCP-LISTEN:80,bind=169.254.169.254,fork,reuseaddr TCP:" + flociHost + ":" + imdsPort + + " >/tmp/floci-imds-proxy.log 2>&1 &", + "echo $! > /tmp/floci-imds-proxy.pid", + "for i in 1 2 3 4 5 6 7 8 9 10 11 12; do", + " " + Ec2MetadataProxy.imdsProbeCommand("http://169.254.169.254"), + " sleep 1", + "done", + "exit 1")}; + } + private static ContainerExec.Result pollCurl(DockerClient docker, String helperId, String... curlArgs) throws Exception { String[] command = new String[curlArgs.length + 1];