mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ec2): keep guest port 80 available with IMDS (#8225)
The in-guest IMDS relay listened on 169.254.169.254:80, so Apache and other wildcard port-80 listeners could not start in an EC2 guest. The relay now listens on its own port, 42169, and an iptables or nft NAT rule routes local link-local port-80 traffic to it. The guest's own nft rules are kept, and only Floci's relay rule is added or removed. With no working NAT backend, the older port-80 listener keeps IMDS available. A protected instance's restart retires a retained older listener before the workload starts, and a failed start rolls back the IMDS registration it made. The network helper image now includes iptables. Closes #7937
This commit is contained in:
1 parent
63607e899d
commit
045ecc4eeb
9 files changed
+777
-60
No files matched your search
@@ -79,6 +79,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
@@ -592,19 +593,119 @@ class Ec2ContainerManagerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void startOfAProtectedInstanceDoesNotSetTheImdsEndpointUpAgain() throws Exception {
|
||||
// The helper container kept its network namespace across the stop, and the address with it.
|
||||
void startOfAProtectedInstanceMigratesTheImdsEndpointInItsHelper() throws Exception {
|
||||
// The helper and its old TCP/80 listener survive a workload stop and an emulator upgrade.
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
List<String[]> execs = recordExecs(dockerClient);
|
||||
List<String> events = new CopyOnWriteArrayList<>();
|
||||
List<String[]> execs = recordExecs(dockerClient, "helper-1", () -> events.add("helper setup"));
|
||||
Instance instance = startProtectedInstance(mock(Ec2MetadataServer.class), Map.of(
|
||||
"floci.security-group-helper", "true",
|
||||
"io.floci.service", "ec2",
|
||||
"io.floci.resource-id", "i-protected",
|
||||
"floci_owner_port", "4566"), dockerClient);
|
||||
"floci_owner_port", "4566"), dockerClient, () -> events.add("workload start"));
|
||||
|
||||
awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(5));
|
||||
assertTrue(execs.stream().noneMatch(cmd -> Arrays.equals(cmd,
|
||||
Ec2ContainerManager.metadataProxyInstallCommand())), "no IMDS setup exec for a protected start");
|
||||
awaitUntil(() -> execs.stream().anyMatch(cmd -> Arrays.equals(cmd,
|
||||
Ec2ContainerManager.metadataProxyInstallCommand())), Duration.ofSeconds(5));
|
||||
assertEquals(List.of("helper setup", "workload start"), events,
|
||||
"the retained TCP/80 listener must be migrated before the workload can bind port 80");
|
||||
verify(dockerClient, never()).execCreateCmd(TEST_CONTAINER_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedProtectedStartRemovesNewMetadataRegistration() throws Exception {
|
||||
Ec2MetadataServer metadataServer = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null);
|
||||
Instance instance = startProtectedInstance(metadataServer, Map.of(
|
||||
"floci.security-group-helper", "true",
|
||||
"io.floci.service", "ec2",
|
||||
"io.floci.resource-id", "i-protected",
|
||||
"floci_owner_port", "4566"), mock(DockerClient.class),
|
||||
() -> {
|
||||
throw new IllegalStateException("Docker start failed");
|
||||
});
|
||||
|
||||
awaitUntil(() -> "stopped".equals(instance.getState().getName())
|
||||
&& metadataServer.registeredContainer("172.17.0.7").isEmpty(), Duration.ofSeconds(5));
|
||||
assertTrue(metadataServer.registeredContainer("172.17.0.7").isEmpty(),
|
||||
"a failed Docker start must not leave a new IMDS mapping to a stopped workload");
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedProtectedStartKeepsExistingMetadataRegistration() throws Exception {
|
||||
Ec2MetadataServer metadataServer = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null);
|
||||
Instance instance = startProtectedInstance(metadataServer, Map.of(
|
||||
"floci.security-group-helper", "true",
|
||||
"io.floci.service", "ec2",
|
||||
"io.floci.resource-id", "i-protected",
|
||||
"floci_owner_port", "4566"), mock(DockerClient.class),
|
||||
() -> {
|
||||
throw new IllegalStateException("Docker start failed");
|
||||
},
|
||||
existing -> metadataServer.registerContainer("172.17.0.7", "i-protected", existing));
|
||||
|
||||
awaitUntil(() -> "stopped".equals(instance.getState().getName()), Duration.ofSeconds(5));
|
||||
assertEquals(instance, metadataServer.registeredContainer("172.17.0.7").orElseThrow(),
|
||||
"a failed restart must retain the mapping left by an earlier successful run");
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedProtectedStartDoesNotRestorePreviousInstanceAtReusedHelperAddress() throws Exception {
|
||||
Ec2MetadataServer metadataServer = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null);
|
||||
Instance previous = new Instance();
|
||||
previous.setInstanceId("i-old-helper-owner");
|
||||
Instance instance = startProtectedInstance(metadataServer, Map.of(
|
||||
"floci.security-group-helper", "true",
|
||||
"io.floci.service", "ec2",
|
||||
"io.floci.resource-id", "i-protected",
|
||||
"floci_owner_port", "4566"), mock(DockerClient.class),
|
||||
() -> {
|
||||
throw new IllegalStateException("Docker start failed");
|
||||
},
|
||||
ignored -> metadataServer.registerContainer("172.17.0.7", previous.getInstanceId(), previous));
|
||||
|
||||
awaitUntil(() -> "stopped".equals(instance.getState().getName())
|
||||
&& metadataServer.registeredContainer("172.17.0.7").isEmpty(), Duration.ofSeconds(5));
|
||||
assertTrue(metadataServer.registeredContainer("172.17.0.7").isEmpty(),
|
||||
"rollback must not resurrect a previous instance after Docker reuses its helper address");
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedProtectedStartKeepsOtherMetadataAddressesForTheInstance() throws Exception {
|
||||
Ec2MetadataServer metadataServer = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null);
|
||||
Instance instance = startProtectedInstance(metadataServer, Map.of(
|
||||
"floci.security-group-helper", "true",
|
||||
"io.floci.service", "ec2",
|
||||
"io.floci.resource-id", "i-protected",
|
||||
"floci_owner_port", "4566"), mock(DockerClient.class),
|
||||
() -> {
|
||||
throw new IllegalStateException("Docker start failed");
|
||||
},
|
||||
existing -> metadataServer.registerContainer("172.17.0.8", "i-protected", existing));
|
||||
|
||||
awaitUntil(() -> "stopped".equals(instance.getState().getName())
|
||||
&& metadataServer.registeredContainer("172.17.0.7").isEmpty(), Duration.ofSeconds(5));
|
||||
assertEquals(instance, metadataServer.registeredContainer("172.17.0.8").orElseThrow(),
|
||||
"rolling back the new helper address must preserve other retained addresses");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cancelledProtectedStartRemovesNewMetadataRegistration() throws Exception {
|
||||
Ec2MetadataServer metadataServer = new Ec2MetadataServer(null, null, null, (InstanceConnectKeys) null);
|
||||
AtomicReference<Instance> startingInstance = new AtomicReference<>();
|
||||
CountDownLatch dockerStarted = new CountDownLatch(1);
|
||||
Instance instance = startProtectedInstance(metadataServer, Map.of(
|
||||
"floci.security-group-helper", "true",
|
||||
"io.floci.service", "ec2",
|
||||
"io.floci.resource-id", "i-protected",
|
||||
"floci_owner_port", "4566"), mock(DockerClient.class),
|
||||
() -> {
|
||||
startingInstance.get().setState(InstanceState.stopping());
|
||||
dockerStarted.countDown();
|
||||
}, startingInstance::set);
|
||||
|
||||
assertTrue(dockerStarted.await(5, TimeUnit.SECONDS));
|
||||
awaitUntil(() -> metadataServer.registeredContainer("172.17.0.7").isEmpty(), Duration.ofSeconds(5));
|
||||
assertEquals("stopping", instance.getState().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -661,14 +762,22 @@ class Ec2ContainerManagerTest {
|
||||
|
||||
/** Records every command exec'd in the test container; each exec then fails, which start tolerates. */
|
||||
private static List<String[]> recordExecs(DockerClient dockerClient) {
|
||||
return recordExecs(dockerClient, () -> { });
|
||||
return recordExecs(dockerClient, TEST_CONTAINER_ID, () -> { });
|
||||
}
|
||||
|
||||
private static List<String[]> recordExecs(DockerClient dockerClient, String containerId) {
|
||||
return recordExecs(dockerClient, containerId, () -> { });
|
||||
}
|
||||
|
||||
/** As {@link #recordExecs(DockerClient)}, running {@code onExec} as each exec is created. */
|
||||
private static List<String[]> recordExecs(DockerClient dockerClient, Runnable onExec) {
|
||||
return recordExecs(dockerClient, TEST_CONTAINER_ID, onExec);
|
||||
}
|
||||
|
||||
private static List<String[]> recordExecs(DockerClient dockerClient, String containerId, Runnable onExec) {
|
||||
List<String[]> execs = new CopyOnWriteArrayList<>();
|
||||
ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF));
|
||||
when(dockerClient.execCreateCmd(TEST_CONTAINER_ID)).thenReturn(execCreate);
|
||||
when(dockerClient.execCreateCmd(containerId)).thenReturn(execCreate);
|
||||
when(execCreate.withCmd(any(String[].class))).thenAnswer(invocation -> {
|
||||
Object[] args = invocation.getArguments();
|
||||
execs.add(args.length == 1 && args[0] instanceof String[] cmd
|
||||
@@ -780,11 +889,25 @@ class Ec2ContainerManagerTest {
|
||||
|
||||
private Instance startProtectedInstance(Ec2MetadataServer metadataServer, Map<String, String> helperLabels,
|
||||
DockerClient dockerClient) {
|
||||
return startProtectedInstance(metadataServer, helperLabels, dockerClient, () -> { });
|
||||
}
|
||||
|
||||
private Instance startProtectedInstance(Ec2MetadataServer metadataServer, Map<String, String> helperLabels,
|
||||
DockerClient dockerClient, Runnable onStart) {
|
||||
return startProtectedInstance(metadataServer, helperLabels, dockerClient, onStart, ignored -> { });
|
||||
}
|
||||
|
||||
private Instance startProtectedInstance(Ec2MetadataServer metadataServer, Map<String, String> helperLabels,
|
||||
DockerClient dockerClient, Runnable onStart, Consumer<Instance> beforeStart) {
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.isContainerRunning(TEST_CONTAINER_ID)).thenReturn(true);
|
||||
|
||||
when(dockerClient.startContainerCmd(TEST_CONTAINER_ID))
|
||||
.thenReturn(mock(StartContainerCmd.class, RETURNS_SELF));
|
||||
StartContainerCmd start = mock(StartContainerCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.startContainerCmd(TEST_CONTAINER_ID)).thenReturn(start);
|
||||
doAnswer(invocation -> {
|
||||
onStart.run();
|
||||
return null;
|
||||
}).when(start).exec();
|
||||
// A workload in the helper's namespace has no Docker attachment of its own, so there is
|
||||
// no bridge address on it to rediscover after the restart.
|
||||
InspectContainerResponse workload = mock(InspectContainerResponse.class);
|
||||
@@ -832,6 +955,7 @@ class Ec2ContainerManagerTest {
|
||||
instance.setInstanceId("i-protected");
|
||||
instance.setDockerContainerId(TEST_CONTAINER_ID);
|
||||
|
||||
beforeStart.accept(instance);
|
||||
manager.start(instance);
|
||||
return instance;
|
||||
}
|
||||
@@ -1568,6 +1692,7 @@ class Ec2ContainerManagerTest {
|
||||
assertTrue(command[2].contains("iproute2"));
|
||||
assertTrue(command[2].contains("socat"));
|
||||
assertTrue(command[2].contains("curl"));
|
||||
assertTrue(command[2].contains("iptables"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1645,6 +1770,7 @@ class Ec2ContainerManagerTest {
|
||||
|
||||
assertTrue(script.contains("command -v yum"), script);
|
||||
assertTrue(script.contains("yum install -y iproute socat curl ca-certificates"), script);
|
||||
assertTrue(script.contains("yum install -y iptables >/dev/null || true"), script);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1659,17 +1785,21 @@ class Ec2ContainerManagerTest {
|
||||
// instance was left with no link-local IMDS endpoint.
|
||||
String script = Ec2ContainerManager.metadataProxyInstallCommand()[2];
|
||||
|
||||
assertTrue(script.contains("dnf install -y --allowerasing iproute socat curl ca-certificates"),
|
||||
script);
|
||||
assertTrue(script.contains("dnf install -y --allowerasing iproute socat curl ca-certificates"), script);
|
||||
assertTrue(script.contains("dnf install -y --allowerasing iptables-nft >/dev/null || true"), script);
|
||||
}
|
||||
|
||||
@Test
|
||||
void metadataProxyStartCommandBindsAwsLinkLocalMetadataAddress() {
|
||||
void metadataProxyStartCommandRoutesAwsLinkLocalMetadataWithoutReservingPort80() {
|
||||
String[] command = Ec2ContainerManager.metadataProxyStartCommand("floci", 9169);
|
||||
|
||||
assertEquals("sh", command[0]);
|
||||
assertTrue(command[2].contains("169.254.169.254/32"));
|
||||
assertTrue(command[2].contains("TCP-LISTEN:80,bind=169.254.169.254"));
|
||||
assertTrue(command[2].contains("TCP-LISTEN:42169,bind=169.254.169.254"));
|
||||
assertTrue(command[2].contains("-d 169.254.169.254/32 -p tcp --dport 80 -j DNAT"
|
||||
+ " --to-destination 169.254.169.254:42169"));
|
||||
assertTrue(command[2].contains("if [ -z \"$rule_backend\" ]; then"));
|
||||
assertTrue(command[2].contains("nohup socat TCP-LISTEN:80,bind=169.254.169.254"));
|
||||
assertTrue(command[2].contains("TCP:floci:9169"));
|
||||
assertTrue(command[2].contains("http://169.254.169.254/latest/meta-data/instance-id"));
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
|
||||
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.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
@@ -40,7 +41,9 @@ class Ec2MetadataProxyTest {
|
||||
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),
|
||||
Ec2MetadataProxy.podIdentityStartCommand("10.0.0.1", 4566)}) {
|
||||
assertTrue(command[2].startsWith("set -eu\n" + prelude + "\n"), command[2]);
|
||||
}
|
||||
@@ -91,11 +94,13 @@ class Ec2MetadataProxyTest {
|
||||
assertEquals("-c", command[1]);
|
||||
|
||||
String script = command[2];
|
||||
assertTrue(script.contains("command -v ip >/dev/null 2>&1 && command -v socat >/dev/null 2>&1 && command -v curl >/dev/null 2>&1; then exit 0; fi"));
|
||||
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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -109,8 +114,9 @@ class Ec2MetadataProxyTest {
|
||||
// Attaches address if missing
|
||||
assertTrue(script.contains("ip addr show dev lo | grep -q '169.254.169.254/32' || ip addr add 169.254.169.254/32 dev lo"));
|
||||
// Idempotent when pid file exists and process is alive
|
||||
assertTrue(script.contains("if [ -f /tmp/floci-imds-proxy.pid ] && pid=\"$(cat /tmp/floci-imds-proxy.pid)\" && [ \"$(cat \"/proc/$pid/comm\" 2>/dev/null)\" = socat ]"
|
||||
+ " && tr '\\0' ' ' 2>/dev/null <\"/proc/$pid/cmdline\" | grep -q 'TCP-LISTEN:80,bind=169.254.169.254,'; then\n exit 0\nfi"));
|
||||
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);
|
||||
// Targets configured Floci host and IMDS port
|
||||
assertTrue(script.contains("nohup socat TCP-LISTEN:80,bind=169.254.169.254,fork,reuseaddr TCP:10.0.0.1:9169 >/tmp/floci-imds-proxy.log 2>&1 &"));
|
||||
// Verifies through an IMDSv2 token even when tokenless access is refused.
|
||||
@@ -119,6 +125,33 @@ class Ec2MetadataProxyTest {
|
||||
assertTrue(script.contains("-H \"X-aws-ec2-metadata-token: $token\" http://169.254.169.254/latest/meta-data/instance-id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void imdsStartPrefersRoutedRelay() {
|
||||
String script = Ec2ContainerManager.metadataProxyStartCommand("10.0.0.1", 9169)[2];
|
||||
|
||||
assertTrue(script.contains("if [ -z \"$rule_backend\" ]; then"), script);
|
||||
assertTrue(script.contains("nohup socat TCP-LISTEN:42169,bind=169.254.169.254,fork,reuseaddr"
|
||||
+ " TCP:10.0.0.1:9169"), script);
|
||||
assertTrue(script.contains("iptables -t nat -C OUTPUT -d 169.254.169.254/32 -p tcp --dport 80"
|
||||
+ " -j DNAT --to-destination 169.254.169.254:42169"), script);
|
||||
assertTrue(script.contains("iptables -t nat -I OUTPUT 1 -d 169.254.169.254/32 -p tcp --dport 80"
|
||||
+ " -j DNAT --to-destination 169.254.169.254:42169"), script);
|
||||
assertTrue(script.contains("/tmp/floci-imds-proxy-42169.pid"), script);
|
||||
assertTrue(script.contains("cleanup_new_proxy"), script);
|
||||
}
|
||||
|
||||
@Test
|
||||
void imdsStartUsesOneSocatListenerCheckAndNoObsoleteRuleCleanup() {
|
||||
String script = Ec2ContainerManager.metadataProxyStartCommand("10.0.0.1", 9169)[2];
|
||||
|
||||
assertTrue(script.contains("is_socat_listener() {"), script);
|
||||
assertEquals(1L, script.lines().filter(line -> line.contains("/comm")).count(), script);
|
||||
assertEquals(1L, script.lines().filter(line -> line.contains("/cmdline")).count(), script);
|
||||
assertEquals(5L, script.lines().filter(line -> line.contains("is_socat_listener ")).count(), script);
|
||||
assertTrue(script.contains("remove_nft_rule \"$nft_rule_marker\" || true"), script);
|
||||
assertFalse(script.contains("remove_nft_rule floci-imds-relay-42169"), script);
|
||||
}
|
||||
|
||||
@Test
|
||||
void podIdentityStartCommandAttachesAddressIdempotentlyAndTargetsHostAndPort() {
|
||||
String[] command = Ec2MetadataProxy.podIdentityStartCommand("10.0.0.1", 4566);
|
||||
@@ -128,8 +161,8 @@ class Ec2MetadataProxyTest {
|
||||
|
||||
String script = command[2];
|
||||
assertTrue(script.contains("ip addr show dev lo | grep -q '169.254.170.23/32' || ip addr add 169.254.170.23/32 dev lo"));
|
||||
assertTrue(script.contains("if [ -f /tmp/floci-pod-identity-proxy.pid ] && pid=\"$(cat /tmp/floci-pod-identity-proxy.pid)\" && [ \"$(cat \"/proc/$pid/comm\" 2>/dev/null)\" = socat ]"
|
||||
+ " && tr '\\0' ' ' 2>/dev/null <\"/proc/$pid/cmdline\" | grep -q 'TCP-LISTEN:80,bind=169.254.170.23,'; then\n exit 0\nfi"));
|
||||
assertTrue(script.contains("is_socat_listener \"$pid\" 'TCP-LISTEN:80,bind=169.254.170.23,'; then"
|
||||
+ "\n exit 0\nfi"), script);
|
||||
assertTrue(script.contains("nohup socat TCP-LISTEN:80,bind=169.254.170.23,fork,reuseaddr TCP:10.0.0.1:4566 >/tmp/floci-pod-identity-proxy.log 2>&1 &"));
|
||||
assertTrue(script.contains("http://169.254.170.23/v1/credentials"));
|
||||
}
|
||||
@@ -181,6 +214,167 @@ class Ec2MetadataProxyTest {
|
||||
Files.readString(arguments));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2InstallUsesExistingNftWithoutNetworkOrPackageManager(@TempDir Path directory) throws Exception {
|
||||
Path bin = Files.createDirectory(directory.resolve("bin"));
|
||||
for (String tool : List.of("ip", "socat", "curl", "nft")) {
|
||||
HelperShellFixture.writeTool(bin, tool, "exit 0\n");
|
||||
}
|
||||
|
||||
assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.installEc2Command(), directory,
|
||||
Map.of("PATH", bin.toString())), HelperShellFixture.output(directory));
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2InstallKeepsExistingImdsToolsWhenOfflineAndNoNatBackend(@TempDir Path directory) throws Exception {
|
||||
Path bin = Files.createDirectory(directory.resolve("bin"));
|
||||
Path packageCalls = directory.resolve("package-calls");
|
||||
for (String tool : List.of("ip", "socat", "curl")) {
|
||||
HelperShellFixture.writeTool(bin, tool, "exit 0\n");
|
||||
}
|
||||
HelperShellFixture.writeTool(bin, "apk", "printf '%s\\n' apk >> \"$TEST_RECORD\"\nexit 1\n");
|
||||
|
||||
assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.installEc2Command(), directory,
|
||||
Map.of("PATH", bin.toString(), "TEST_RECORD", packageCalls.toString())),
|
||||
HelperShellFixture.output(directory));
|
||||
assertFalse(Files.exists(packageCalls), "a guest with core IMDS tools must not wait on a package repository");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2StartTriesNftWhenIptablesCannotInsertNatRule(@TempDir Path directory) throws Exception {
|
||||
Path bin = Files.createDirectory(directory.resolve("bin"));
|
||||
Path record = directory.resolve("nft-commands");
|
||||
writeEc2StartTools(bin);
|
||||
HelperShellFixture.writeTool(bin, "iptables", "exit 1\n");
|
||||
HelperShellFixture.writeTool(bin, "nft", "printf '%s\\n' \"$*\" >> \"$TEST_RECORD\"\n"
|
||||
+ "case \"$*\" in\n"
|
||||
+ " '-f -') cat >> \"$TEST_RECORD\" ;;\n"
|
||||
+ " 'list table ip floci_imds') exit 1 ;;\n"
|
||||
+ "esac\n");
|
||||
|
||||
try {
|
||||
assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169),
|
||||
directory, Map.of("PATH", bin + ":/usr/bin:/bin", "TEST_RECORD", record.toString())),
|
||||
HelperShellFixture.output(directory));
|
||||
assertTrue(Files.readString(record).contains("insert rule ip floci_imds output"));
|
||||
} finally {
|
||||
deleteEc2ProxyFiles();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2StartReusesIptablesRuleDespiteEmptyNftTable(@TempDir Path directory) throws Exception {
|
||||
Path bin = Files.createDirectory(directory.resolve("bin"));
|
||||
Path record = directory.resolve("iptables-commands");
|
||||
writeEc2StartTools(bin);
|
||||
HelperShellFixture.writeTool(bin, "iptables", "printf '%s\\n' \"$*\" >> \"$TEST_RECORD\"\n"
|
||||
+ "case \"$*\" in\n"
|
||||
+ " *' -C OUTPUT '*) exit 0 ;;\n"
|
||||
+ " *) exit 1 ;;\n"
|
||||
+ "esac\n");
|
||||
HelperShellFixture.writeTool(bin, "nft", "case \"$*\" in\n"
|
||||
+ " 'list table ip floci_imds') exit 0 ;;\n"
|
||||
+ " *) exit 1 ;;\n"
|
||||
+ "esac\n");
|
||||
|
||||
try {
|
||||
assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169),
|
||||
directory, Map.of("PATH", bin + ":/usr/bin:/bin", "TEST_RECORD", record.toString())),
|
||||
HelperShellFixture.output(directory));
|
||||
String commands = Files.readString(record);
|
||||
assertTrue(commands.contains("-C OUTPUT"), commands);
|
||||
assertFalse(commands.contains("-I OUTPUT"), commands);
|
||||
} finally {
|
||||
deleteEc2ProxyFiles();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2StartTriesIptablesWhenNftCannotCreateChain(@TempDir Path directory) throws Exception {
|
||||
Path bin = Files.createDirectory(directory.resolve("bin"));
|
||||
Path record = directory.resolve("iptables-commands");
|
||||
writeEc2StartTools(bin);
|
||||
HelperShellFixture.writeTool(bin, "iptables", "printf '%s\\n' \"$*\" >> \"$TEST_RECORD\"\n"
|
||||
+ "case \"$*\" in\n"
|
||||
+ " *' -C OUTPUT '*) exit 1 ;;\n"
|
||||
+ " *' -I OUTPUT '*) exit 0 ;;\n"
|
||||
+ "esac\n");
|
||||
HelperShellFixture.writeTool(bin, "nft", "case \"$*\" in\n"
|
||||
+ " 'list table ip floci_imds') exit 0 ;;\n"
|
||||
+ " *) exit 1 ;;\n"
|
||||
+ "esac\n");
|
||||
|
||||
try {
|
||||
assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169),
|
||||
directory, Map.of("PATH", bin + ":/usr/bin:/bin", "TEST_RECORD", record.toString())),
|
||||
HelperShellFixture.output(directory));
|
||||
assertTrue(Files.readString(record).contains("-I OUTPUT"));
|
||||
} finally {
|
||||
deleteEc2ProxyFiles();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2StartPreservesOtherRulesInExistingNftTable(@TempDir Path directory) throws Exception {
|
||||
Path bin = Files.createDirectory(directory.resolve("bin"));
|
||||
Path record = directory.resolve("nft-commands");
|
||||
writeEc2StartTools(bin);
|
||||
HelperShellFixture.writeTool(bin, "nft", "printf '%s\\n' \"$*\" >> \"$TEST_RECORD\"\n"
|
||||
+ "case \"$*\" in\n"
|
||||
+ " 'list chain ip floci_imds output') printf '%s\\n'"
|
||||
+ " 'ip daddr 192.0.2.1 accept comment \"guest-rule\" # handle 7' ;;\n"
|
||||
+ " '-f -') cat >> \"$TEST_RECORD\" ;;\n"
|
||||
+ "esac\n");
|
||||
|
||||
try {
|
||||
assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169),
|
||||
directory, Map.of("PATH", bin + ":/usr/bin:/bin", "TEST_RECORD", record.toString())),
|
||||
HelperShellFixture.output(directory));
|
||||
String commands = Files.readString(record);
|
||||
assertFalse(commands.contains("delete table ip floci_imds"), commands);
|
||||
assertTrue(commands.contains("insert rule ip floci_imds output"), commands);
|
||||
} finally {
|
||||
deleteEc2ProxyFiles();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void ec2StartFallsBackToLegacyListenerWhenNoNatBackendExists(@TempDir Path directory) throws Exception {
|
||||
Path bin = Files.createDirectory(directory.resolve("bin"));
|
||||
Path record = directory.resolve("listeners");
|
||||
writeEc2StartTools(bin);
|
||||
HelperShellFixture.writeTool(bin, "socat", "printf '%s\\n' \"$*\" >> \"$TEST_RECORD\"\n");
|
||||
HelperShellFixture.writeTool(bin, "curl", "grep -q 'TCP-LISTEN:80' \"$TEST_RECORD\" || 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");
|
||||
|
||||
try {
|
||||
assertEquals(0, HelperShellFixture.run(Ec2MetadataProxy.startEc2Command("127.0.0.1", 9169),
|
||||
directory, Map.of("PATH", bin + ":/usr/bin:/bin", "TEST_RECORD", record.toString())),
|
||||
HelperShellFixture.output(directory));
|
||||
assertTrue(Files.readString(record).contains("TCP-LISTEN:80,bind=169.254.169.254"));
|
||||
} finally {
|
||||
deleteEc2ProxyFiles();
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeEc2StartTools(Path bin) throws Exception {
|
||||
HelperShellFixture.writeTool(bin, "ip", "printf '%s\\n' 'inet 169.254.169.254/32'\n");
|
||||
HelperShellFixture.writeTool(bin, "socat", "exit 0\n");
|
||||
HelperShellFixture.writeTool(bin, "curl", "case \"$*\" in\n"
|
||||
+ " *'/latest/api/token') printf '%s' fixture-token ;;\n"
|
||||
+ " *'/latest/meta-data/instance-id') printf '%s' i-fixture ;;\n"
|
||||
+ "esac\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("/tmp/floci-imds-proxy.log"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void startCommandClearsApplicationPathsBeforeAddressProxyAndProbeTools(@TempDir Path directory)
|
||||
throws Exception {
|
||||
|
||||
@@ -45,7 +45,7 @@ class Ec2StartRequestScopeIntegrationTest {
|
||||
void backgroundStartUsesOwnerOrCallerAndClearsItsScopeAfterFailure(boolean ownerless) throws Exception {
|
||||
try (ExecutorService worker = Executors.newSingleThreadExecutor();
|
||||
ExecutorService retries = Executors.newSingleThreadExecutor()) {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS);
|
||||
Ec2ContainerManager manager = manager(docker, mock(ContainerLifecycleManager.class), worker, retries);
|
||||
Scope caller = new Scope("999900001111", "ap-southeast-1", "aws");
|
||||
for (Scope owner : List.of(new Scope("111122223333", "eu-west-1", "aws"),
|
||||
|
||||
+168
@@ -4,10 +4,12 @@ import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
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.services.ec2.model.IpPermission;
|
||||
import io.floci.aws.services.ec2.model.IpRange;
|
||||
import io.floci.aws.services.ec2.model.SecurityGroup;
|
||||
import io.floci.aws.testing.TestImages;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
@@ -24,10 +26,59 @@ import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class SecurityGroupFirewallDockerIntegrationTest {
|
||||
|
||||
private static final String METADATA_AND_WEB_SERVERS = """
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from sys import argv
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def respond(self, body):
|
||||
payload = body.encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
def do_PUT(self):
|
||||
if self.path == "/latest/api/token" and self.headers.get(
|
||||
"X-aws-ec2-metadata-token-ttl-seconds"):
|
||||
self.respond("fixture-token")
|
||||
else:
|
||||
self.send_error(400)
|
||||
|
||||
def do_GET(self):
|
||||
if self.server.server_port == 80:
|
||||
self.respond("web-ok")
|
||||
elif self.path == "/latest/meta-data/instance-id" and self.headers.get(
|
||||
"X-aws-ec2-metadata-token") == "fixture-token":
|
||||
self.respond("i-fixture")
|
||||
else:
|
||||
self.send_error(401)
|
||||
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
if argv[1] == "metadata":
|
||||
ThreadingHTTPServer(("127.0.0.1", 9169), Handler).serve_forever()
|
||||
else:
|
||||
ThreadingHTTPServer(("0.0.0.0", 80), Handler).serve_forever()
|
||||
""";
|
||||
private static final String IMDS_CLIENT = """
|
||||
from urllib.request import ProxyHandler, Request, build_opener
|
||||
opener = build_opener(ProxyHandler({}))
|
||||
endpoint = "http://169.254.169.254"
|
||||
token = opener.open(Request(endpoint + "/latest/api/token", method="PUT",
|
||||
headers={"X-aws-ec2-metadata-token-ttl-seconds": "60"}), timeout=2).read().decode()
|
||||
instance = opener.open(Request(endpoint + "/latest/meta-data/instance-id",
|
||||
headers={"X-aws-ec2-metadata-token": token}), timeout=2).read().decode()
|
||||
print(token)
|
||||
print(instance)
|
||||
""";
|
||||
|
||||
// A denied connection is dropped without a reply, so it only ends when nc's timeout expires;
|
||||
// a permitted one connects in tens of milliseconds, so one second is ample to call it denied.
|
||||
private static final int PERMITTED_TIMEOUT_SECONDS = 2;
|
||||
@@ -38,6 +89,123 @@ class SecurityGroupFirewallDockerIntegrationTest {
|
||||
@Inject ContainerBuilder builder;
|
||||
@Inject DockerClient docker;
|
||||
|
||||
@Test
|
||||
void legacyImdsRelayMigratesOfflineAndLeavesWildcardHttpPortAvailable() throws Exception {
|
||||
Assumptions.assumeTrue(firewall.enabled());
|
||||
try {
|
||||
Assumptions.assumeTrue("linux".equalsIgnoreCase(docker.infoCmd().exec().getOsType()));
|
||||
} catch (Exception e) {
|
||||
Assumptions.abort("Docker daemon is unavailable");
|
||||
}
|
||||
|
||||
String suffix = UUID.randomUUID().toString().substring(0, 8);
|
||||
String eniId = "eni-imds-" + suffix;
|
||||
SecurityGroupFirewallManager.Namespace namespace = null;
|
||||
String fixtureContainer = null;
|
||||
String worker = null;
|
||||
try {
|
||||
namespace = firewall.createNamespace("ec2", "imds-" + suffix, "000000000000",
|
||||
"us-east-1", Optional.empty(), Map.of());
|
||||
SecurityGroup group = group("sg-imds-" + suffix, false, "0.0.0.0/0");
|
||||
firewall.register(endpoint(eniId, "10.0.0.2", namespace, group), namespace.helperId(), Map.of());
|
||||
fixtureContainer = lifecycle.createAndStart(builder.newContainer(TestImages.PYTHON_ALPINE)
|
||||
.withName("floci-imds-fixture-" + suffix)
|
||||
.withNetworkMode("container:" + namespace.helperId())
|
||||
.withEntrypoint(List.of("python", "-c"))
|
||||
.withCmd(List.of(METADATA_AND_WEB_SERVERS, "metadata"))
|
||||
.build()).containerId();
|
||||
|
||||
ContainerExec.Result fixture = pollCurl(docker, namespace.helperId(), "--noproxy", "*",
|
||||
"-fsS", "--max-time", "1", "-X", "PUT", "-H",
|
||||
"X-aws-ec2-metadata-token-ttl-seconds: 60",
|
||||
"http://127.0.0.1:9169/latest/api/token");
|
||||
assertEquals(0, fixture.exitCode(), "IMDS fixture did not start: " + fixture.summary());
|
||||
assertEquals("fixture-token", fixture.stdout().trim());
|
||||
|
||||
ContainerExec.Result legacy = ContainerExec.runMerged(docker, namespace.helperId(),
|
||||
Ec2MetadataProxy.startCommand("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(),
|
||||
new String[]{"apk", "del", "iptables"}, 10);
|
||||
assertEquals(0, removed.exitCode(), "Could not simulate the old helper image: " + removed.summary());
|
||||
ContainerExec.Result missing = ContainerExec.runMerged(docker, namespace.helperId(),
|
||||
new String[]{"sh", "-c", "! command -v iptables && command -v nft"}, 5);
|
||||
assertEquals(0, missing.exitCode(), "Old helper tool state is wrong: " + missing.summary());
|
||||
|
||||
ContainerExec.Result install = ContainerExec.runMerged(docker, namespace.helperId(),
|
||||
Ec2ContainerManager.metadataProxyInstallCommand(), 20);
|
||||
assertEquals(0, install.exitCode(), "Offline IMDS dependencies are unavailable: " + install.summary());
|
||||
String[] start = Ec2ContainerManager.metadataProxyStartCommand("127.0.0.1", 9169);
|
||||
ContainerExec.Result proxy = ContainerExec.runMerged(docker, namespace.helperId(), start, 30);
|
||||
assertEquals(0, proxy.exitCode(), "IMDS proxy did not start: " + proxy.summary());
|
||||
|
||||
worker = lifecycle.createAndStart(builder.newContainer(TestImages.PYTHON_ALPINE)
|
||||
.withName("floci-imds-web-test-" + suffix)
|
||||
.withNetworkMode("container:" + namespace.helperId())
|
||||
.withEntrypoint(List.of("python", "-c"))
|
||||
.withCmd(List.of(METADATA_AND_WEB_SERVERS, "web"))
|
||||
.build()).containerId();
|
||||
ContainerExec.Result web = pollCurl(docker, namespace.helperId(), "--noproxy", "*",
|
||||
"-fsS", "--max-time", "1", "http://127.0.0.1:80/");
|
||||
assertEquals(0, web.exitCode(), "Wildcard port 80 did not serve HTTP: " + web.summary());
|
||||
assertEquals("web-ok", web.stdout().trim());
|
||||
|
||||
ContainerExec.Result imds = ContainerExec.runMerged(docker, worker,
|
||||
new String[]{"python", "-c", IMDS_CLIENT}, 10);
|
||||
assertEquals(0, imds.exitCode(), "Workload could not reach IMDSv2: " + imds.summary());
|
||||
assertEquals("fixture-token\ni-fixture", imds.stdout().trim().replace("\r", ""));
|
||||
|
||||
ContainerExec.Result reapplied = ContainerExec.runMerged(docker, namespace.helperId(), start, 30);
|
||||
assertEquals(0, reapplied.exitCode(), reapplied.summary());
|
||||
ContainerExec.Result stale = ContainerExec.runMerged(docker, namespace.helperId(),
|
||||
new String[]{"nft", "flush", "chain", "ip", "floci_imds", "output"}, 5);
|
||||
assertEquals(0, stale.exitCode(), stale.summary());
|
||||
ContainerExec.Result otherRule = ContainerExec.runMerged(docker, namespace.helperId(),
|
||||
new String[]{"sh", "-c", "printf '%s\\n'"
|
||||
+ " 'add rule ip floci_imds output ip daddr 192.0.2.1 counter"
|
||||
+ " comment \"guest-preserved\"' | nft -f -"}, 5);
|
||||
assertEquals(0, otherRule.exitCode(), otherRule.summary());
|
||||
ContainerExec.Result repaired = ContainerExec.runMerged(docker, namespace.helperId(), start, 30);
|
||||
assertEquals(0, repaired.exitCode(), "A stale nft table was not repaired: " + repaired.summary());
|
||||
ContainerExec.Result rules = ContainerExec.runMerged(docker, namespace.helperId(),
|
||||
new String[]{"nft", "list", "chain", "ip", "floci_imds", "output"}, 5);
|
||||
assertEquals(0, rules.exitCode(), rules.summary());
|
||||
assertEquals(1L, rules.stdout().lines()
|
||||
.filter(line -> line.contains("floci-imds-relay-42169")
|
||||
&& line.contains("169.254.169.254:42169")).count());
|
||||
assertTrue(rules.stdout().contains("guest-preserved"), rules.summary());
|
||||
assertTrue(Boolean.TRUE.equals(docker.inspectContainerCmd(worker).exec().getState().getRunning()));
|
||||
} finally {
|
||||
if (worker != null) {
|
||||
lifecycle.removeIfExists(worker);
|
||||
}
|
||||
if (fixtureContainer != null) {
|
||||
lifecycle.removeIfExists(fixtureContainer);
|
||||
}
|
||||
firewall.unregister(eniId);
|
||||
if (namespace != null) {
|
||||
lifecycle.removeIfExists(namespace.helperId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ContainerExec.Result pollCurl(DockerClient docker, String helperId, String... curlArgs)
|
||||
throws Exception {
|
||||
String[] command = new String[curlArgs.length + 1];
|
||||
command[0] = "curl";
|
||||
System.arraycopy(curlArgs, 0, command, 1, curlArgs.length);
|
||||
ContainerExec.Result result = null;
|
||||
for (int attempt = 0; attempt < 30; attempt++) {
|
||||
result = ContainerExec.runMerged(docker, helperId, command, 3);
|
||||
if (result.exitCode() == 0) {
|
||||
break;
|
||||
}
|
||||
Thread.sleep(100);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Test
|
||||
void deniedLogicalCidrBlocksManagedPeerThenRuleUpdatePermitsIt() throws Exception {
|
||||
Assumptions.assumeTrue(firewall.enabled());
|
||||
|
||||
Reference in new issue
Block a user