mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user