fix(lambda): fail an image function's init when Lambda's user cannot enter its working directory (#8047)

Closes #7979

Resolve symlinks on the working directory's path, relative or absolute,
and check every directory on the resolved path. Stop the check at a
function's EFS mount path, which Lambda enters as the access point's user.

Build the Dockerfile-only build context in one place,
DockerBuildContext.ofDockerfile, for the helper image and the two Docker
tests that built it by hand.

It created an application named test-app, which AppConfigIntegrationTest looks up by name when both run in one shard.
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-11-12 09:15:36 -04:00
1 parent 60252c9b7f
commit 17af8368b5
15 files changed
+544 -28

No files matched your search

@@ -100,7 +100,7 @@ class RestCrossServiceRouteCollisionIntegrationTest {
given()
.header("Authorization", PartitionMatrix.sigV4Auth("us-east-1", "appconfig"))
.contentType("application/json")
.body("{\"Name\":\"test-app\"}")
.body("{\"Name\":\"route-collision-app\"}")
.when()
.post("/applications")
.then()
@@ -0,0 +1,28 @@
package io.floci.aws.core.common.docker;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class DockerBuildContextTest {
@Test
void theContextHoldsOnlyTheDockerfile() throws IOException {
byte[] dockerfile = "FROM busybox:stable\n".getBytes(StandardCharsets.UTF_8);
try (TarArchiveInputStream tar = new TarArchiveInputStream(
new ByteArrayInputStream(DockerBuildContext.ofDockerfile(dockerfile)))) {
TarArchiveEntry entry = tar.getNextEntry();
assertEquals("Dockerfile", entry.getName());
assertEquals("FROM busybox:stable\n", new String(tar.readAllBytes(), StandardCharsets.UTF_8));
assertNull(tar.getNextEntry());
}
}
}
@@ -14,6 +14,7 @@ import com.github.dockerjava.core.command.WaitContainerResultCallback;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.docker.ContainerStorageHelper;
import io.floci.aws.core.common.docker.DockerBuildContext;
import io.floci.aws.services.ecs.model.Container;
import io.floci.aws.services.ecs.model.ContainerDefinition;
import io.floci.aws.services.ecs.model.ContainerDependency;
@@ -23,15 +24,12 @@ import io.floci.aws.services.ecs.model.VolumeFrom;
import io.floci.aws.testing.TestImages;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
@@ -365,18 +363,9 @@ class EcsContainerManagerVolumesFromDockerIntegrationTest {
VOLUME ["/shared"]
""".formatted(TestImages.BUSYBOX);
byte[] dockerfileBytes = dockerfile.getBytes(StandardCharsets.UTF_8);
ByteArrayOutputStream context = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(context)) {
TarArchiveEntry entry = new TarArchiveEntry("Dockerfile");
entry.setSize(dockerfileBytes.length);
tar.putArchiveEntry(entry);
tar.write(dockerfileBytes);
tar.closeArchiveEntry();
}
byte[] context = DockerBuildContext.ofDockerfile(dockerfile.getBytes(StandardCharsets.UTF_8));
try (BuildImageResultCallback callback = new BuildImageResultCallback()) {
String imageId = dockerClient.buildImageCmd(new ByteArrayInputStream(context.toByteArray()))
String imageId = dockerClient.buildImageCmd(new ByteArrayInputStream(context))
.withTags(Set.of(tag))
.withRemove(true)
.exec(callback)
@@ -2,6 +2,7 @@ package io.floci.aws.services.lambda;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.command.InspectContainerCmd;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
@@ -264,6 +265,8 @@ class LambdaImageConfigTest {
when(lifecycleManager.startCreated(eq("container-123"), any()))
.thenReturn(new ContainerLifecycleManager.ContainerInfo("container-123", Map.of()));
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
lenient().when(dockerClient.inspectContainerCmd(any()))
.thenReturn(mock(InspectContainerCmd.class, RETURNS_DEEP_STUBS));
lenient().when(dockerClient.copyArchiveToContainerCmd(any())).thenAnswer(inv -> {
CopyArchiveToContainerCmd cmd = mock(CopyArchiveToContainerCmd.class);
@@ -1,5 +1,6 @@
package io.floci.aws.services.lambda;
import io.floci.aws.services.lambda.launcher.LambdaInitException;
import org.junit.jupiter.api.Test;
import java.net.SocketException;
@@ -43,4 +44,19 @@ class LambdaInitFailureMessageTest {
assertThat(LambdaExecutorService.initFailureMessage(e, false),
equalTo("Failed to start Lambda container: connect failed"));
}
@Test
void aRuntimeInitFailureKeepsItsTypeAndMessage() {
Exception e = new IllegalStateException("launch failed",
new LambdaInitException("Runtime.InvalidEntrypoint", "cannot enter /home/nonroot"));
assertThat(LambdaExecutorService.initFailureType(e), equalTo("Runtime.InvalidEntrypoint"));
assertThat(LambdaExecutorService.initFailureMessage(e, true), equalTo("cannot enter /home/nonroot"));
}
@Test
void otherFailuresAreLambdaInitErrors() {
assertThat(LambdaExecutorService.initFailureType(new IllegalStateException("image pull failed")),
equalTo("Lambda.InitError"));
}
}
@@ -7,9 +7,12 @@ 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.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.AccessMode;
import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.Mount;
import com.github.dockerjava.api.model.MountType;
@@ -177,6 +180,7 @@ class ContainerLauncherTest {
new ContainerLifecycleManager.ContainerInfo("container-123", Map.of());
lenient().when(lifecycleManager.startCreated(eq("container-123"), any())).thenReturn(info);
lenient().when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
workingDirectory("");
ListContainersCmd inventory = mock(ListContainersCmd.class, RETURNS_SELF);
lenient().when(dockerClient.listContainersCmd()).thenReturn(inventory);
lenient().when(inventory.exec()).thenReturn(List.of());
@@ -941,6 +945,67 @@ class ContainerLauncherTest {
verify(lifecycleManager, never()).createAndStart(any());
}
@Test
void launchFunction_imageWorkingDirectoryLambdasUserCannotEnter_failsInitWithoutStarting() throws Exception {
workingDirectory("/home/nonroot");
directoryMode("/home", 0755);
directoryMode("/home/nonroot", 0700);
LambdaInitException error = assertThrows(LambdaInitException.class, () -> launcher.launch(imageFunction()));
assertEquals("Runtime.InvalidEntrypoint", error.errorType());
verify(lifecycleManager, never()).startCreated(any(), any());
}
@Test
void launchFunction_imageWorkingDirectoryEveryoneCanEnter_starts() throws Exception {
workingDirectory("/srv/app");
directoryMode("/srv", 0755);
directoryMode("/srv/app", 0755);
launcher.launch(imageFunction());
verify(lifecycleManager).startCreated(eq("container-123"), any());
}
@Test
void launchFunction_imageWorkingDirectoryOnAMountedFileSystem_starts() throws Exception {
workingDirectory("/mnt/efs/app");
directoryMode("/mnt", 0755);
directoryMode("/mnt/efs", 0700);
LambdaFunction fn = imageFunction();
fn.setFileSystemConfigs(List.of(new LambdaFileSystemConfig(
"arn:aws:elasticfilesystem:us-east-1:222233334444:access-point/fsap-0123456789abcdef0",
"/mnt/efs")));
launcher.launch(fn);
verify(lifecycleManager).startCreated(eq("container-123"), any());
}
private void workingDirectory(String workingDir) {
ContainerConfig containerConfig = mock(ContainerConfig.class);
lenient().when(containerConfig.getWorkingDir()).thenReturn(workingDir);
InspectContainerResponse inspected = mock(InspectContainerResponse.class);
lenient().when(inspected.getConfig()).thenReturn(containerConfig);
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
lenient().when(inspect.exec()).thenReturn(inspected);
lenient().when(dockerClient.inspectContainerCmd("container-123")).thenReturn(inspect);
}
private void directoryMode(String path, int mode) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(bos)) {
TarArchiveEntry dir = new TarArchiveEntry(path.substring(path.lastIndexOf('/') + 1) + "/");
dir.setMode(040000 | mode);
tar.putArchiveEntry(dir);
tar.closeArchiveEntry();
}
CopyArchiveFromContainerCmd copy = mock(CopyArchiveFromContainerCmd.class);
lenient().when(copy.exec()).thenReturn(new ByteArrayInputStream(bos.toByteArray()));
lenient().when(dockerClient.copyArchiveFromContainerCmd("container-123", path)).thenReturn(copy);
}
private static LambdaFunction imageFunction() {
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName("image-function");
@@ -0,0 +1,90 @@
package io.floci.aws.services.lambda.launcher;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.BuildImageResultCallback;
import com.github.dockerjava.api.command.CreateContainerCmd;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.DockerBuildContext;
import io.floci.aws.core.common.docker.DockerClientProducer;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.TestImages;
import io.smallrye.config.SmallRyeConfigBuilder;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** Reads the working directory's permissions from a created, unstarted container of a real image. */
class WorkingDirectoryAccessDockerIntegrationTest {
private static final String DOCKERFILE = """
FROM %s
RUN mkdir -p /home/nonroot /srv/open \\
&& chown 65532:65532 /home/nonroot && chmod 0700 /home/nonroot \\
&& chmod 0755 /srv/open \\
&& ln -s /home/nonroot /app
USER 65532
WORKDIR /home/nonroot
""".formatted(TestImages.BUSYBOX);
@Test
void aWorkingDirectoryOnlyTheImageUserCanEnterFailsInitAsAnInvalidEntrypoint() throws Exception {
withContainer(null, (docker, containerId) -> {
LambdaInitException error = assertThrows(LambdaInitException.class,
() -> WorkingDirectoryAccess.requireLambdaUserCanEnter(docker, containerId, List.of()));
assertEquals("Runtime.InvalidEntrypoint", error.errorType());
});
}
@Test
void aSymlinkToADirectoryOnlyTheImageUserCanEnterFailsInit() throws Exception {
withContainer("/app", (docker, containerId) -> assertThrows(LambdaInitException.class,
() -> WorkingDirectoryAccess.requireLambdaUserCanEnter(docker, containerId, List.of())));
}
@Test
void aWorkingDirectoryEveryoneCanEnterStartsAsBefore() throws Exception {
withContainer("/srv/open", (docker, containerId) -> assertDoesNotThrow(
() -> WorkingDirectoryAccess.requireLambdaUserCanEnter(docker, containerId, List.of())));
}
private interface ContainerTest {
void run(DockerClient docker, String containerId) throws Exception;
}
private static void withContainer(String workingDir, ContainerTest test) throws Exception {
EmulatorConfig config = new SmallRyeConfigBuilder().withMapping(EmulatorConfig.class)
.build().getConfigMapping(EmulatorConfig.class);
try (DockerClient docker = new DockerClientProducer(config).dockerClient()) {
Assumptions.assumeTrue(DockerAvailability.answers(docker), "Docker daemon is unavailable");
String image = "floci/lambda-workdir-test:" + UUID.randomUUID();
byte[] context = DockerBuildContext.ofDockerfile(DOCKERFILE.getBytes(StandardCharsets.UTF_8));
try (BuildImageResultCallback callback = new BuildImageResultCallback()) {
docker.buildImageCmd(new ByteArrayInputStream(context))
.withTags(Set.of(image)).exec(callback).awaitImageId();
}
try {
CreateContainerCmd create = docker.createContainerCmd(image);
if (workingDir != null) {
create.withWorkingDir(workingDir);
}
String containerId = create.exec().getId();
try {
test.run(docker, containerId);
} finally {
docker.removeContainerCmd(containerId).withForce(true).exec();
}
} finally {
docker.removeImageCmd(image).withForce(true).exec();
}
}
}
}
@@ -0,0 +1,120 @@
package io.floci.aws.services.lambda.launcher;
import io.floci.aws.services.lambda.launcher.WorkingDirectoryAccess.PathEntry;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
class WorkingDirectoryAccessTest {
@Test
void aDirectoryOnlyItsOwnerCanEnterStopsLambdasUser() {
Map<String, PathEntry> paths = Map.of(
"/home", PathEntry.directory(0755),
"/home/nonroot", PathEntry.directory(0700));
assertEquals(Optional.of("/home/nonroot"), firstClosed("/home/nonroot", paths));
}
@Test
void theFirstClosedDirectoryOnThePathIsTheOneReported() {
Map<String, PathEntry> paths = Map.of(
"/srv", PathEntry.directory(0750),
"/srv/app", PathEntry.directory(0755));
assertEquals(Optional.of("/srv"), firstClosed("/srv/app", paths));
}
@Test
void directoriesEveryoneCanEnterLetLambdasUserThrough() {
Map<String, PathEntry> paths = Map.of(
"/var", PathEntry.directory(0755),
"/var/task", PathEntry.directory(0711));
assertEquals(Optional.empty(), firstClosed("/var/task/", paths));
}
@Test
void theRootAndAnUnsetWorkingDirectoryAreNotChecked() {
Map<String, PathEntry> paths = Map.of("/", PathEntry.directory(0700));
assertEquals(Optional.empty(), firstClosed("/", paths));
assertEquals(Optional.empty(), firstClosed("", paths));
assertEquals(Optional.empty(), firstClosed(null, paths));
}
@Test
void aDirectoryWhoseModeIsUnknownIsNotHeldAgainstTheFunction() {
assertEquals(Optional.empty(), firstClosed("/missing", Map.of()));
}
@Test
void aSymlinkToADirectoryOnlyItsOwnerCanEnterStopsLambdasUser() {
Map<String, PathEntry> paths = Map.of(
"/app", PathEntry.symlink("/home/nonroot"),
"/home", PathEntry.directory(0755),
"/home/nonroot", PathEntry.directory(0700));
assertEquals(Optional.of("/home/nonroot"), firstClosed("/app", paths));
}
@Test
void aRelativeSymlinkIsFollowedFromItsOwnDirectory() {
Map<String, PathEntry> paths = Map.of(
"/srv", PathEntry.directory(0755),
"/srv/current", PathEntry.symlink("releases/1"),
"/srv/releases", PathEntry.directory(0700),
"/srv/releases/1", PathEntry.directory(0755));
assertEquals(Optional.of("/srv/releases"), firstClosed("/srv/current", paths));
}
@Test
void aSymlinkToAnOpenDirectoryUnderAClosedOneStopsLambdasUser() {
Map<String, PathEntry> paths = Map.of(
"/app", PathEntry.symlink("../opt/closed/open"),
"/opt", PathEntry.directory(0755),
"/opt/closed", PathEntry.directory(0700),
"/opt/closed/open", PathEntry.directory(0755));
assertEquals(Optional.of("/opt/closed"), firstClosed("/app", paths));
}
@Test
void aSymlinkLoopEndsTheCheck() {
Map<String, PathEntry> paths = Map.of(
"/a", PathEntry.symlink("/b"),
"/b", PathEntry.symlink("/a"));
assertEquals(Optional.empty(), firstClosed("/a", paths));
}
@Test
void aFileSystemMountedForTheFunctionIsNotChecked() {
Map<String, PathEntry> paths = Map.of(
"/mnt", PathEntry.directory(0755),
"/mnt/efs", PathEntry.directory(0700),
"/mnt/efs/app", PathEntry.directory(0700));
assertEquals(Optional.empty(), WorkingDirectoryAccess.firstDirectoryLambdaCannotEnter(
"/mnt/efs/app", List.of("/mnt/efs/"), paths::get));
}
@Test
void theDirectoriesAboveAFileSystemMountAreStillChecked() {
Map<String, PathEntry> paths = Map.of(
"/mnt", PathEntry.directory(0700),
"/mnt/efs", PathEntry.directory(0755));
assertEquals(Optional.of("/mnt"), WorkingDirectoryAccess.firstDirectoryLambdaCannotEnter(
"/mnt/efs", List.of("/mnt/efs"), paths::get));
}
private static Optional<String> firstClosed(String workingDir, Map<String, PathEntry> paths) {
return WorkingDirectoryAccess.firstDirectoryLambdaCannotEnter(workingDir, List.of(), paths::get);
}
}