mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
60252c9b7f
commit
17af8368b5
15 files changed
+544
-28
No files matched your search
@@ -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
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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()) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String> 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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> firstDirectoryLambdaCannotEnter(String workingDir, Collection<String> mountPaths,
|
||||
Function<String, PathEntry> entryOf) {
|
||||
if (workingDir == null || workingDir.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
List<String> mounts = mountPaths.stream().map(WorkingDirectoryAccess::withoutTrailingSlash).toList();
|
||||
Deque<String> 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<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-14
@@ -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");
|
||||
|
||||
+90
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user