feat(ec2): bind the host's /lib/modules read-only into systemd guests (#7354)

A systemd guest shares the Docker host's kernel but ships none of its
modules, so `modprobe br_netfilter` (Kubernetes node setup, e.g. Kubernetes
The Hard Way lab 9) fails with "Module not found in directory
/lib/modules/<kver>" even when the module is built in. kind binds the
host's tree the same way. Docker creates a missing bind source as an empty
directory, so hosts without /lib/modules still launch.

Privileged systemd guests can now load any module in that tree into the
shared host (or Docker Desktop / OrbStack VM) kernel, so docs/services/ec2.md
carries a warning saying so.

test(ec2): prove a systemd guest gets /lib/modules read-only on a real daemon

Ec2SystemdGuestDockerIntegrationTest launches through the real
Ec2ContainerManager container spec against Docker, with an Alpine image
standing in for a systemd cloud image (its busybox /sbin/init stays up as
PID 1), and checks the mount both from the daemon's inspect and from the
guest's /proc/mounts. It is skipped when Docker is unavailable.

docs/services/ec2.md now says that on Docker Desktop or OrbStack the tree
is the VM's and may not match its running kernel, and states exactly when
an instance runs privileged: only with security-group enforcement off. With
enforcement on, the guest joins the protected namespace unprivileged, and a
namespace that cannot be created fails the launch.

docs(ec2): say the read-only modules mount does not bind a privileged guest; keep test cleanup from masking failures

The read-only bind keeps an unprivileged guest from changing the tree, but a
privileged guest can remount it read-write, so the first paragraph no longer
claims the guest cannot load a module the host kernel lacks.

The systemd guest test now logs a failed container removal instead of
throwing it over the assertion error it is reporting.

fix(ec2): bind only the running kernel's /lib/modules dir into systemd guests; tear down the integration test via terminate()

test(ec2): pin that the guest's /lib/modules outside the bound kernel dir stays writable; document missing-dir and linux-modules caveats
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-11-08 18:24:08 -04:00
1 parent 42b28be218
commit 0de5566d22
4 files changed
+166 -1

No files matched your search

@@ -6,6 +6,7 @@ import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.ExecStartCmd;
import com.github.dockerjava.api.command.InfoCmd;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectExecCmd;
@@ -21,6 +22,7 @@ import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.Info;
import com.github.dockerjava.api.model.NetworkSettings;
import com.github.dockerjava.api.model.StreamType;
import io.floci.aws.config.EmulatorConfig;
@@ -1728,6 +1730,11 @@ class Ec2ContainerManagerTest {
Ec2ContainerManager.containerBridgeIpAttempts = 1;
Ec2ContainerManager.containerBridgeIpPollMillis = 1;
LaunchHarness harness = launchHarness();
InfoCmd infoCmd = mock(InfoCmd.class);
Info info = mock(Info.class);
when(harness.dockerClient.infoCmd()).thenReturn(infoCmd);
when(infoCmd.exec()).thenReturn(info);
when(info.getKernelVersion()).thenReturn("6.8.0-test");
when(harness.lifecycleManager.create(any(ContainerSpec.class), eq("linux/arm64")))
.thenReturn(TEST_CONTAINER_ID);
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
@@ -1748,6 +1755,8 @@ class Ec2ContainerManagerTest {
verify(harness.builder).withCmd(List.of("/sbin/init"));
verify(harness.builder).withCgroupnsMode("host");
verify(harness.builder).withBind("/sys/fs/cgroup", "/sys/fs/cgroup");
verify(harness.builder).withReadOnlyBind("/lib/modules/6.8.0-test", "/lib/modules/6.8.0-test");
verify(harness.builder, never()).withReadOnlyBind(eq("/lib/modules"), anyString());
// User data runs after the sshd step, so once it has started that step is settled.
awaitUntil(() -> commandIndex(harness.executedCommands, "/var/lib/user-data.sh") >= 0, Duration.ofSeconds(2));
assertEquals(-1, commandIndex(harness.executedCommands, "/usr/sbin/sshd"),
@@ -0,0 +1,129 @@
package io.floci.aws.services.ec2;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectContainerResponse;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerDetector;
import io.floci.aws.core.common.docker.ContainerExec;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLogStreamer;
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
import io.floci.aws.core.common.docker.DockerHostResolver;
import io.floci.aws.core.common.docker.PortAllocator;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.net.VpcNetworkManager;
import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.TestImages;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.Mockito.mock;
/**
* A systemd guest sees the Docker host's module tree, read-only. The launch goes through the real
* {@link Ec2ContainerManager} container spec and a real Docker daemon. The image is Alpine rather
* than a systemd cloud image, which is too heavy to pull in CI: the systemd runtime only decides
* the container's command and mounts, and Alpine's busybox {@code /sbin/init} stays up as PID 1.
*/
@QuarkusTest
class Ec2SystemdGuestDockerIntegrationTest {
private static final String REGION = "us-east-1";
private static final Logger LOG = Logger.getLogger(Ec2SystemdGuestDockerIntegrationTest.class);
@Inject
DockerClient docker;
@Inject
ContainerBuilder containerBuilder;
@Inject
ContainerLifecycleManager lifecycleManager;
@Inject
DockerHostResolver dockerHostResolver;
@Inject
PortAllocator portAllocator;
@Inject
EmulatorConfig config;
@Inject
RegionResolver regionResolver;
@Inject
ContainerReachableEndpoint reachableEndpoint;
@BeforeEach
void requireDocker() {
assumeTrue(DockerAvailability.answers(docker), "Docker must be available for EC2 systemd guest tests");
}
@Test
void systemdGuestSeesHostModulesReadOnly() {
Ec2ContainerManager manager = new Ec2ContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), dockerHostResolver, docker,
portAllocator, config, mock(Ec2MetadataServer.class), mock(Ec2PortForwardManager.class),
regionResolver, mock(ContainerNetworkReachability.class), mock(VpcNetworkManager.class),
reachableEndpoint);
Instance instance = new Instance();
instance.setInstanceId("i-systemd" + UUID.randomUUID().toString().replace("-", "").substring(0, 8));
instance.setRegion(REGION);
String modulesDir = "/lib/modules/" + docker.infoCmd().exec().getKernelVersion();
try {
manager.launch(instance,
new ResolvedAmiImage(TestImages.PYTHON_ALPINE, ResolvedAmiImage.SYSTEMD_RUNTIME, false, null),
null, REGION);
await().atMost(Duration.ofSeconds(60)).until(() -> instance.getDockerContainerId() != null
&& lifecycleManager.isContainerRunning(instance.getDockerContainerId()));
String containerId = instance.getDockerContainerId();
InspectContainerResponse.Mount modules = docker.inspectContainerCmd(containerId).exec().getMounts()
.stream().filter(m -> m.getDestination() != null
&& modulesDir.equals(m.getDestination().getPath()))
.findFirst().orElse(null);
assertNotNull(modules, "systemd guest has no " + modulesDir + " mount");
assertFalse(modules.getRW(), modulesDir + " must be mounted read-only");
ContainerExec.Result inside = ContainerExec.runMerged(docker, containerId,
new String[]{"sh", "-c", "grep ' " + modulesDir + " ' /proc/mounts"}, 30);
assertEquals(0, inside.exitCode(), "guest cannot see " + modulesDir + ": " + inside.summary());
assertTrue(inside.stdout().matches("(?s).* " + Pattern.quote(modulesDir) + " \\S+ ro[, ].*"),
"guest's " + modulesDir + " is not read-only: " + inside.stdout());
// The rest of the guest's /lib/modules must stay writable (package managers own it).
ContainerExec.Result writable = ContainerExec.runMerged(docker, containerId,
new String[]{"sh", "-c", "touch /lib/modules/.floci-w && rm /lib/modules/.floci-w"}, 30);
assertEquals(0, writable.exitCode(),
"guest's /lib/modules outside " + modulesDir + " is not writable: " + writable.summary());
} finally {
// terminate() removes the container and releases the SSH port in the shared allocator.
CountDownLatch torndown = new CountDownLatch(1);
manager.terminate(instance, torndown::countDown);
try {
torndown.await(60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}