From 17af8368b53826b62467e97e14769ce3be5bc74b Mon Sep 17 00:00:00 2001 From: Niels Kootstra <545768+nkootstra@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:15:36 +0100 Subject: [PATCH] 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. --- docs/services/lambda.md | 4 + .../common/docker/DockerBuildContext.java | 29 ++++ .../docker/LocallyBuiltHelperImage.java | 14 +- .../lambda/LambdaExecutorService.java | 22 ++- .../lambda/launcher/ContainerLauncher.java | 9 ++ .../lambda/launcher/LambdaInitException.java | 16 ++ .../launcher/WorkingDirectoryAccess.java | 137 ++++++++++++++++++ ...sServiceRouteCollisionIntegrationTest.java | 2 +- .../common/docker/DockerBuildContextTest.java | 28 ++++ ...nagerVolumesFromDockerIntegrationTest.java | 17 +-- .../lambda/LambdaImageConfigTest.java | 3 + .../lambda/LambdaInitFailureMessageTest.java | 16 ++ .../launcher/ContainerLauncherTest.java | 65 +++++++++ ...gDirectoryAccessDockerIntegrationTest.java | 90 ++++++++++++ .../launcher/WorkingDirectoryAccessTest.java | 120 +++++++++++++++ 15 files changed, 544 insertions(+), 28 deletions(-) create mode 100644 src/main/java/io/floci/aws/core/common/docker/DockerBuildContext.java create mode 100644 src/main/java/io/floci/aws/services/lambda/launcher/LambdaInitException.java create mode 100644 src/main/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccess.java create mode 100644 src/test/java/io/floci/aws/core/common/docker/DockerBuildContextTest.java create mode 100644 src/test/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccessDockerIntegrationTest.java create mode 100644 src/test/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccessTest.java diff --git a/docs/services/lambda.md b/docs/services/lambda.md index 440c1eb8e9..fa2c7cfa33 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -1199,6 +1199,10 @@ A container image function whose `ImageUri` names an image already present on th Container image functions (`"PackageType": "Image"`) that pull from private registries need Docker credentials. See [Docker Configuration → Private Registry Authentication](../configuration/docker.md#private-registry-authentication) for the full guide. +### Image user and working directory + +AWS runs a container image function as its own least-privileged user, not the image's `USER`. Floci keeps running the container as the image's user, but before it starts the container it checks that Lambda's user could enter the working directory (`ImageConfig.WorkingDirectory`, or the image's `WORKDIR`). Lambda's user owns nothing in the image, so a directory on that path must be executable by other users. Symlinks on the path are followed, and the check stops at a file system the function mounts from EFS, which Lambda enters as the access point's user. When a directory is not executable by other users, such as a `0700` home directory owned by the image's user, the invocation fails with `Runtime.InvalidEntrypoint`, as on AWS. Set `WORKDIR` to a directory everyone can enter, such as `/`. + ## Examples ```bash diff --git a/src/main/java/io/floci/aws/core/common/docker/DockerBuildContext.java b/src/main/java/io/floci/aws/core/common/docker/DockerBuildContext.java new file mode 100644 index 0000000000..c05d372171 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/docker/DockerBuildContext.java @@ -0,0 +1,29 @@ +package io.floci.aws.core.common.docker; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; + +/** The tar build context Docker's build API takes, for an image built from a Dockerfile alone. */ +public final class DockerBuildContext { + + private DockerBuildContext() { + } + + public static byte[] ofDockerfile(byte[] dockerfile) { + ByteArrayOutputStream archive = new ByteArrayOutputStream(dockerfile.length + 1024); + try (TarArchiveOutputStream tar = new TarArchiveOutputStream(archive)) { + TarArchiveEntry entry = new TarArchiveEntry("Dockerfile"); + entry.setSize(dockerfile.length); + tar.putArchiveEntry(entry); + tar.write(dockerfile); + tar.closeArchiveEntry(); + } catch (IOException e) { + throw new UncheckedIOException("Cannot write the Docker build context", e); + } + return archive.toByteArray(); + } +} diff --git a/src/main/java/io/floci/aws/core/common/docker/LocallyBuiltHelperImage.java b/src/main/java/io/floci/aws/core/common/docker/LocallyBuiltHelperImage.java index 332791c893..5986c4a9c1 100644 --- a/src/main/java/io/floci/aws/core/common/docker/LocallyBuiltHelperImage.java +++ b/src/main/java/io/floci/aws/core/common/docker/LocallyBuiltHelperImage.java @@ -5,11 +5,8 @@ import com.github.dockerjava.api.command.BuildImageResultCallback; import com.github.dockerjava.api.command.InspectImageResponse; import com.github.dockerjava.api.exception.NotFoundException; import io.floci.aws.core.common.Digests; -import org.apache.commons.compress.archivers.tar.TarArchiveEntry; -import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; @@ -61,16 +58,9 @@ public final class LocallyBuiltHelperImage { } catch (NotFoundException missing) { // Build the current Floci recipe in the daemon used for workloads. } - ByteArrayOutputStream archive = new ByteArrayOutputStream(content.length + 1024); - try (TarArchiveOutputStream tar = new TarArchiveOutputStream(archive)) { - TarArchiveEntry entry = new TarArchiveEntry("Dockerfile"); - entry.setSize(content.length); - tar.putArchiveEntry(entry); - tar.write(content); - tar.closeArchiveEntry(); - } try (BuildImageResultCallback callback = new BuildImageResultCallback()) { - String built = dockerClient.buildImageCmd(new ByteArrayInputStream(archive.toByteArray())) + String built = dockerClient.buildImageCmd( + new ByteArrayInputStream(DockerBuildContext.ofDockerfile(content))) .withTags(Set.of(image)).withPlatform(platform).withPull(true) .withLabels(Map.of(RECIPE_LABEL, recipe)).exec(callback).awaitImageId(); if (built == null || built.isBlank()) { diff --git a/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java b/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java index 7826884fcf..d4d6dec23e 100644 --- a/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java +++ b/src/main/java/io/floci/aws/services/lambda/LambdaExecutorService.java @@ -7,6 +7,7 @@ import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.Resettable; import io.floci.aws.services.lambda.launcher.ContainerHandle; +import io.floci.aws.services.lambda.launcher.LambdaInitException; import io.floci.aws.services.lambda.model.FunctionEventInvokeConfig; import io.floci.aws.services.lambda.model.InvocationType; import io.floci.aws.services.lambda.model.InvokeResult; @@ -363,6 +364,10 @@ public class LambdaExecutorService implements Resettable { * message. */ static String initFailureMessage(Exception e, boolean dockerExecutor) { + LambdaInitException initFailure = initException(e); + if (initFailure != null) { + return initFailure.getMessage(); + } for (Throwable cause = e; dockerExecutor && cause != null; cause = cause.getCause()) { if (cause instanceof SocketException || cause instanceof UnknownHostException) { return "Failed to start Lambda container: Docker is not reachable (" + cause.getMessage() @@ -372,6 +377,21 @@ public class LambdaExecutorService implements Resettable { return "Failed to start Lambda container: " + e.getMessage(); } + /** The error type an init failure reports: the runtime's own when it has one, else {@code Lambda.InitError}. */ + static String initFailureType(Exception e) { + LambdaInitException initFailure = initException(e); + return initFailure != null ? initFailure.errorType() : "Lambda.InitError"; + } + + private static LambdaInitException initException(Throwable e) { + for (Throwable cause = e; cause != null; cause = cause.getCause()) { + if (cause instanceof LambdaInitException initFailure) { + return initFailure; + } + } + return null; + } + private InvokeResult executeSync(LambdaFunction fn, byte[] payload, String requestId, String clientContext, String invokedQualifier, ResponseStreamListener listener) { @@ -384,7 +404,7 @@ public class LambdaExecutorService implements Resettable { } catch (Exception e) { LOG.warnv("Failed to acquire container for function {0}: {1}", fn.getFunctionName(), e.getMessage()); return new InvokeResult(200, "Unhandled", - buildErrorPayload(initFailureMessage(e, dockerExecutor), "Lambda.InitError"), + buildErrorPayload(initFailureMessage(e, dockerExecutor), initFailureType(e)), null, requestId); } long deadlineMs = System.currentTimeMillis() + (long) fn.getTimeout() * 1000; diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java index 872941a358..0d9b70ef7b 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/ContainerLauncher.java @@ -21,6 +21,7 @@ import io.floci.aws.services.iam.model.SessionCreds; import io.floci.aws.services.lambda.LambdaLayerService; import io.floci.aws.services.lambda.LambdaLogDestinations; import io.floci.aws.services.lambda.model.ContainerState; +import io.floci.aws.services.lambda.model.LambdaFileSystemConfig; import io.floci.aws.services.lambda.model.LambdaFunction; import io.floci.aws.services.lambda.model.LambdaLayerVersion; import io.floci.aws.services.lambda.runtime.RuntimeApiServer; @@ -460,6 +461,14 @@ public class ContainerLauncher implements LambdaRuntimeLauncher { COPY_MAX_ATTEMPTS, COPY_RETRY_BACKOFF_MS); } + // AWS runs an image as its own user, not the image's USER; init fails when that user + // cannot enter the working directory. + if ("Image".equals(fn.getPackageType())) { + List mountPaths = fn.getFileSystemConfigs() == null ? List.of() + : fn.getFileSystemConfigs().stream().map(LambdaFileSystemConfig::getLocalMountPath).toList(); + WorkingDirectoryAccess.requireLambdaUserCanEnter(dockerClient, containerId, mountPaths); + } + // Now start the container with code in place joinVpcNetwork(fn, containerId, lambdaAccountId, lambdaRegion); lifecycleManager.startCreated(containerId, spec); diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/LambdaInitException.java b/src/main/java/io/floci/aws/services/lambda/launcher/LambdaInitException.java new file mode 100644 index 0000000000..451e0789c4 --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/launcher/LambdaInitException.java @@ -0,0 +1,16 @@ +package io.floci.aws.services.lambda.launcher; + +/** An init failure AWS reports with its own error type, such as {@code Runtime.InvalidEntrypoint}. */ +public class LambdaInitException extends RuntimeException { + + private final String errorType; + + public LambdaInitException(String errorType, String message) { + super(message); + this.errorType = errorType; + } + + public String errorType() { + return errorType; + } +} diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccess.java b/src/main/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccess.java new file mode 100644 index 0000000000..697d5ed1ab --- /dev/null +++ b/src/main/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccess.java @@ -0,0 +1,137 @@ +package io.floci.aws.services.lambda.launcher; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.exception.NotFoundException; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.util.ArrayDeque; +import java.util.Arrays; +import java.util.Collection; +import java.util.Deque; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +/** + * Whether Lambda's default user can enter an image function's working directory. AWS runs an image + * as its own least-privileged user rather than the image's {@code USER}, and that user owns nothing in + * the image, so it passes a directory only through the directory's "other" execute permission. Init + * fails with {@code Runtime.InvalidEntrypoint} when it cannot. Floci keeps running the container as the + * image's user, so it checks the path itself before starting the container. + */ +final class WorkingDirectoryAccess { + + private static final int OTHERS_EXECUTE = 0001; + + /** Linux's own limit on the symlinks one path lookup follows. */ + private static final int MAX_SYMLINKS = 40; + + private WorkingDirectoryAccess() { + } + + /** A path in the container: a directory with its mode, or a symlink with its target. */ + record PathEntry(int mode, String linkTarget) { + + static PathEntry directory(int mode) { + return new PathEntry(mode, null); + } + + static PathEntry symlink(String target) { + return new PathEntry(0, target); + } + } + + /** + * Fails with {@code Runtime.InvalidEntrypoint} when Lambda's user cannot enter the created container's + * working directory. A file system mounted for the function is entered as its access point's user, so + * the check stops at its mount path. + */ + static void requireLambdaUserCanEnter(DockerClient docker, String containerId, Collection mountPaths) { + String workingDir = docker.inspectContainerCmd(containerId).exec().getConfig().getWorkingDir(); + firstDirectoryLambdaCannotEnter(workingDir, mountPaths, path -> pathEntry(docker, containerId, path)) + .ifPresent(closed -> { + throw new LambdaInitException("Runtime.InvalidEntrypoint", + "Lambda's default user cannot enter the working directory " + workingDir + + ": " + closed + " is not executable by other users"); + }); + } + + /** + * The first directory on the path to {@code workingDir} that Lambda's user cannot enter, following + * symlinks the way the kernel does. {@code entryOf} answers {@code null} for a path it does not know. + */ + static Optional firstDirectoryLambdaCannotEnter(String workingDir, Collection mountPaths, + Function entryOf) { + if (workingDir == null || workingDir.isBlank()) { + return Optional.empty(); + } + List mounts = mountPaths.stream().map(WorkingDirectoryAccess::withoutTrailingSlash).toList(); + Deque remaining = new ArrayDeque<>(Arrays.asList(workingDir.split("/"))); + String resolved = ""; + int links = 0; + while (!remaining.isEmpty()) { + String segment = remaining.removeFirst(); + if (segment.isEmpty() || ".".equals(segment)) { + continue; + } + if ("..".equals(segment)) { + resolved = resolved.substring(0, Math.max(resolved.lastIndexOf('/'), 0)); + continue; + } + String path = resolved + "/" + segment; + if (mounts.contains(path)) { + return Optional.empty(); + } + PathEntry entry = entryOf.apply(path); + if (entry != null && entry.linkTarget() != null) { + if (++links > MAX_SYMLINKS) { + return Optional.empty(); + } + List target = Arrays.asList(entry.linkTarget().split("/")); + for (int i = target.size() - 1; i >= 0; i--) { + remaining.addFirst(target.get(i)); + } + if (entry.linkTarget().startsWith("/")) { + resolved = ""; + } + continue; + } + if (entry != null && (entry.mode() & OTHERS_EXECUTE) == 0) { + return Optional.of(path); + } + resolved = path; + } + return Optional.empty(); + } + + private static String withoutTrailingSlash(String path) { + return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length() - 1) : path; + } + + /** + * A path in the container, from the first entry of the archive Docker returns for it, which is the + * path itself and not what a symlink points to. Read through the archive API so it works on an image + * with no shell, and on a container that has not started. + */ + private static PathEntry pathEntry(DockerClient docker, String containerId, String path) { + try (InputStream stream = docker.copyArchiveFromContainerCmd(containerId, path).exec(); + TarArchiveInputStream tar = new TarArchiveInputStream(stream)) { + TarArchiveEntry entry = tar.getNextEntry(); + if (entry == null) { + return null; + } + if (entry.isSymbolicLink()) { + return PathEntry.symlink(entry.getLinkName()); + } + return entry.isDirectory() ? PathEntry.directory(entry.getMode()) : null; + } catch (NotFoundException e) { + return null; + } catch (IOException e) { + throw new UncheckedIOException("Could not read the mode of " + path, e); + } + } +} diff --git a/src/test/java/io/floci/aws/core/common/RestCrossServiceRouteCollisionIntegrationTest.java b/src/test/java/io/floci/aws/core/common/RestCrossServiceRouteCollisionIntegrationTest.java index cab3cf1d17..21f724302d 100644 --- a/src/test/java/io/floci/aws/core/common/RestCrossServiceRouteCollisionIntegrationTest.java +++ b/src/test/java/io/floci/aws/core/common/RestCrossServiceRouteCollisionIntegrationTest.java @@ -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() diff --git a/src/test/java/io/floci/aws/core/common/docker/DockerBuildContextTest.java b/src/test/java/io/floci/aws/core/common/docker/DockerBuildContextTest.java new file mode 100644 index 0000000000..02fe332bcb --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/docker/DockerBuildContextTest.java @@ -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()); + } + } +} diff --git a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerVolumesFromDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerVolumesFromDockerIntegrationTest.java index 9bcdf25c03..4bfa8f3d19 100644 --- a/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerVolumesFromDockerIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/ecs/container/EcsContainerManagerVolumesFromDockerIntegrationTest.java @@ -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) diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java index 2eb460097b..dbdf3965bd 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaImageConfigTest.java @@ -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); diff --git a/src/test/java/io/floci/aws/services/lambda/LambdaInitFailureMessageTest.java b/src/test/java/io/floci/aws/services/lambda/LambdaInitFailureMessageTest.java index ceb5d4a771..3547ccb456 100644 --- a/src/test/java/io/floci/aws/services/lambda/LambdaInitFailureMessageTest.java +++ b/src/test/java/io/floci/aws/services/lambda/LambdaInitFailureMessageTest.java @@ -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")); + } } diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java index 1b08ccb6e1..ac87dca305 100644 --- a/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java +++ b/src/test/java/io/floci/aws/services/lambda/launcher/ContainerLauncherTest.java @@ -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"); diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccessDockerIntegrationTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccessDockerIntegrationTest.java new file mode 100644 index 0000000000..1c6e118012 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccessDockerIntegrationTest.java @@ -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(); + } + } + } +} diff --git a/src/test/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccessTest.java b/src/test/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccessTest.java new file mode 100644 index 0000000000..b59e952d2f --- /dev/null +++ b/src/test/java/io/floci/aws/services/lambda/launcher/WorkingDirectoryAccessTest.java @@ -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 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 paths = Map.of( + "/srv", PathEntry.directory(0750), + "/srv/app", PathEntry.directory(0755)); + + assertEquals(Optional.of("/srv"), firstClosed("/srv/app", paths)); + } + + @Test + void directoriesEveryoneCanEnterLetLambdasUserThrough() { + Map paths = Map.of( + "/var", PathEntry.directory(0755), + "/var/task", PathEntry.directory(0711)); + + assertEquals(Optional.empty(), firstClosed("/var/task/", paths)); + } + + @Test + void theRootAndAnUnsetWorkingDirectoryAreNotChecked() { + Map 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 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 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 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 paths = Map.of( + "/a", PathEntry.symlink("/b"), + "/b", PathEntry.symlink("/a")); + + assertEquals(Optional.empty(), firstClosed("/a", paths)); + } + + @Test + void aFileSystemMountedForTheFunctionIsNotChecked() { + Map 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 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 firstClosed(String workingDir, Map paths) { + return WorkingDirectoryAccess.firstDirectoryLambdaCannotEnter(workingDir, List.of(), paths::get); + } +}