perf(lambda): read the working directory's mode without streaming the archive (#9361)

The image function working directory check now reads each parent's mode and symlink target from HEAD /containers/{id}/archive, whose X-Docker-Container-Path-Stat header answers in a few bytes, instead of reading the first tar entry of a GET archive that Docker compressed and streamed in full when it was closed. An image function's first invoke no longer scans all of /var. The probe runs on a small control-plane transport pool of its own, behind the Docker circuit breaker.

Closes #9244
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-11-24 14:48:02 -04:00
1 parent a99d83dcd9
commit d42f29579c
9 files changed
+344 -48

No files matched your search

@@ -58,6 +58,9 @@ public class DockerClientProducer {
/** Bounds the connect and the answer of the Docker circuit breaker's confirming ping. */
static final Duration PING_TIMEOUT = Duration.ofSeconds(5);
/** The stat probe pool's connections: one HEAD per working directory parent, so a handful. */
private static final int STAT_POOL_MAX_CONNECTIONS = 4;
private final EmulatorConfig config;
private final DockerPoolGaugeLogger gaugeLogger;
private final DockerCircuitBreaker breaker;
@@ -477,6 +480,30 @@ public class DockerClientProducer {
validateMaxConnections(config.docker().maxConnections()), "control-plane");
}
/**
* A small pool of its own for the archive stat probes issued beside the control-plane client's
* commands: docker-java has no command for the HEAD the working directory check needs, so the
* transport is called directly. Not the {@link #dockerClient()} bean's own pool: each produced
* client owns its connection evictor thread, whose release on CDI disposal the
* {@code DockerClientDisposalIntegrationTest} asserts, and sharing one transport between two
* beans would take the thread's context classloader from whichever built it first.
*/
@Produces
@ApplicationScoped
public DockerHttpClient controlPlaneHttpClient() {
DefaultDockerClientConfig clientConfig = buildClientConfig();
Duration apiTimeout = Duration.ofSeconds(validateApiTimeoutSeconds(config.docker().apiTimeoutSeconds()));
FlociDockerHttpClient transport = newHttpClient(clientConfig, STAT_POOL_MAX_CONNECTIONS, apiTimeout,
Duration.ofSeconds(validateConnectionRequestTimeoutSeconds(
config.docker().connectionRequestTimeoutSeconds())));
return wrapForRole(transport, "control-plane", apiTimeout, breaker, 0,
Duration.ofSeconds(config.docker().connectionRequestTimeoutSeconds()));
}
void disposeControlPlaneHttpClient(@Disposes DockerHttpClient client) throws IOException {
client.close();
}
/**
* Streaming DockerClient: container log-follow ({@link ContainerLogStreamer}), Lambda
* extension execs and Lambda exit watchers, Lambda Web attach streams, and the output of
@@ -3,6 +3,7 @@ package io.floci.aws.services.lambda.launcher;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.ExecCreateCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.transport.DockerHttpClient;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.Digests;
@@ -123,6 +124,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
private final DockerClient streamingDocker;
private final DockerHttpClient controlPlaneHttp;
private final ContainerLogStreamer logStreamer;
private final ImageResolver imageResolver;
private final RuntimeApiServerFactory runtimeApiServerFactory;
@@ -144,6 +146,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
public ContainerLauncher(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
@StreamingDocker DockerClient streamingDocker,
DockerHttpClient controlPlaneHttp,
ContainerLogStreamer logStreamer,
ImageResolver imageResolver,
RuntimeApiServerFactory runtimeApiServerFactory,
@@ -160,6 +163,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.streamingDocker = streamingDocker;
this.controlPlaneHttp = controlPlaneHttp;
this.logStreamer = logStreamer;
this.imageResolver = imageResolver;
this.runtimeApiServerFactory = runtimeApiServerFactory;
@@ -459,7 +463,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
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);
WorkingDirectoryAccess.requireLambdaUserCanEnter(dockerClient, controlPlaneHttp, containerId, mountPaths);
}
// Now start the container with code in place
@@ -1,18 +1,20 @@
package io.floci.aws.services.lambda.launcher;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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 com.github.dockerjava.transport.DockerHttpClient;
import com.google.common.net.UrlEscapers;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
@@ -30,6 +32,14 @@ final class WorkingDirectoryAccess {
/** Linux's own limit on the symlinks one path lookup follows. */
private static final int MAX_SYMLINKS = 40;
/** Go's FileMode type bit for a directory, as the archive stat header reports the mode. */
private static final int GO_MODE_DIR = 1 << 31;
/** Go's FileMode type bit for a symlink, as the archive stat header reports the mode. */
private static final int GO_MODE_SYMLINK = 1 << 27;
private static final ObjectMapper STAT_JSON = new ObjectMapper();
private WorkingDirectoryAccess() {
}
@@ -48,11 +58,13 @@ final class WorkingDirectoryAccess {
/**
* 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.
* the check stops at its mount path. The mode of each folder comes from {@code http}, the control
* plane transport the container was created on.
*/
static void requireLambdaUserCanEnter(DockerClient docker, String containerId, Collection<String> mountPaths) {
static void requireLambdaUserCanEnter(DockerClient docker, DockerHttpClient http, String containerId,
Collection<String> mountPaths) {
String workingDir = docker.inspectContainerCmd(containerId).exec().getConfig().getWorkingDir();
firstDirectoryLambdaCannotEnter(workingDir, mountPaths, path -> pathEntry(docker, containerId, path))
firstDirectoryLambdaCannotEnter(workingDir, mountPaths, path -> pathEntry(http, containerId, path))
.ifPresent(closed -> {
throw new LambdaInitException("Runtime.InvalidEntrypoint",
"Lambda's default user cannot enter the working directory " + workingDir
@@ -113,25 +125,81 @@ final class WorkingDirectoryAccess {
}
/**
* 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.
* A path in the container, from {@code HEAD /containers/{id}/archive}. The stat header answers the
* mode and symlink target without Docker archiving the whole directory tree, which for a parent
* such as {@code /var} means streaming hundreds of megabytes to read one entry.
*/
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) {
private static PathEntry pathEntry(DockerHttpClient http, String containerId, String path) {
String requestPath = "/containers/" + containerId + "/archive?path="
+ UrlEscapers.urlFormParameterEscaper().escape(path);
try (DockerHttpClient.Response response = http.execute(new HeadRequest(requestPath))) {
if (response.getStatusCode() == 404) {
return null;
}
if (entry.isSymbolicLink()) {
return PathEntry.symlink(entry.getLinkName());
if (response.getStatusCode() >= 300) {
throw new IllegalStateException("HEAD " + requestPath + " returned " + response.getStatusCode());
}
return entry.isDirectory() ? PathEntry.directory(entry.getMode()) : null;
} catch (NotFoundException e) {
return entryOf(response.getHeader("X-Docker-Container-Path-Stat"));
}
}
/**
* The path's entry from the base64 JSON the stat header carries, or null for a path that is
* neither a directory nor a symlink. The mode is Go's FileMode: type in the high bits,
* permissions in the low nine.
*/
private static PathEntry entryOf(String encodedStat) {
if (encodedStat == null) {
return null;
}
JsonNode stat;
try {
stat = STAT_JSON.readTree(Base64.getDecoder().decode(encodedStat));
} catch (IOException e) {
throw new UncheckedIOException("Could not read the mode of " + path, e);
throw new IllegalStateException("Malformed archive stat header: " + e.getMessage(), e);
}
int mode = stat.path("mode").asInt(0);
if ((mode & GO_MODE_SYMLINK) != 0) {
return PathEntry.symlink(stat.path("linkTarget").asText(""));
}
if ((mode & GO_MODE_DIR) == 0) {
return null;
}
return PathEntry.directory(mode & 07777);
}
/** A request docker-java's enum has no constant for: the archive API's path stat probe. */
private static final class HeadRequest extends DockerHttpClient.Request {
private final String path;
HeadRequest(String path) {
this.path = path;
}
@Override
public String method() {
return "HEAD";
}
@Override
public String path() {
return path;
}
@Override
public byte[] bodyBytes() {
return null;
}
@Override
public InputStream hijackedInput() {
return null;
}
@Override
public Map<String, String> headers() {
return Map.of();
}
}
}
@@ -3,6 +3,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 com.github.dockerjava.transport.DockerHttpClient;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
@@ -259,7 +260,7 @@ class LambdaImageConfigTest {
new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, null, 4566);
LaunchedContainerAwsEnv awsEnv = new LaunchedContainerAwsEnv(reachableEndpoint);
launcher = new ContainerLauncher(containerBuilder, lifecycleManager, mock(DockerClient.class),
logStreamer, imageResolver,
mock(DockerHttpClient.class), logStreamer, imageResolver,
runtimeApiServerFactory, dockerHostResolver, config,
new RegionResolver("us-east-1", "000000000000"), ecrRegistryManager,
mock(LambdaLayerService.class), awsEnv,
@@ -2,6 +2,7 @@ package io.floci.aws.services.lambda.launcher;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.transport.DockerHttpClient;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerBuilder;
@@ -67,7 +68,7 @@ class ContainerLauncherCodeVolumeReuseTest {
RecordingLauncher(ContainerLifecycleManager lifecycleManager, EmulatorConfig config) {
super(mock(ContainerBuilder.class), lifecycleManager, mock(DockerClient.class),
mock(ContainerLogStreamer.class),
mock(DockerHttpClient.class), mock(ContainerLogStreamer.class),
mock(ImageResolver.class), mock(RuntimeApiServerFactory.class),
mock(DockerHostResolver.class), config, new RegionResolver("us-east-1", "000000000000"),
mock(EcrRegistryManager.class),
@@ -284,7 +285,7 @@ class ContainerLauncherCodeVolumeReuseTest {
when(containerBuilder.newContainer("img")).thenReturn(builder);
when(builder.build()).thenThrow(new IllegalStateException("stop before Docker"));
ContainerLauncher real = new ContainerLauncher(containerBuilder, lifecycleManager,
mock(DockerClient.class), mock(ContainerLogStreamer.class), mock(ImageResolver.class),
mock(DockerClient.class), mock(DockerHttpClient.class), mock(ContainerLogStreamer.class), mock(ImageResolver.class),
mock(RuntimeApiServerFactory.class), mock(DockerHostResolver.class), config,
new RegionResolver("us-east-1", "000000000000"),
mock(EcrRegistryManager.class), mock(LambdaLayerService.class),
@@ -34,8 +34,8 @@ class ContainerLauncherCopyRetryTest {
// no longer builds; the copy paths under test read nothing else from it.
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().lambda().codeVolumePopulateConcurrency()).thenReturn(Optional.empty());
return new ContainerLauncher(null, null, null, null, null, null, null, config, null, null, null, null, null,
null, mock(DockerExitEvents.class));
return new ContainerLauncher(null, null, null, null, null, null, null, null, config, null, null, null, null,
null, null, mock(DockerExitEvents.class));
}
@Test
@@ -19,6 +19,8 @@ import com.github.dockerjava.api.model.Mount;
import com.github.dockerjava.api.model.MountType;
import com.github.dockerjava.api.model.StreamType;
import com.github.dockerjava.api.model.VersionComponent;
import com.github.dockerjava.transport.DockerHttpClient;
import com.google.common.net.UrlEscapers;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
@@ -70,6 +72,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -94,6 +97,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.*;
@@ -112,6 +116,7 @@ class ContainerLauncherTest {
@Mock RuntimeApiServer runtimeApiServer;
@Mock DockerClient dockerClient;
@Mock DockerClient streamingDockerClient;
@Mock DockerHttpClient dockerHttp;
@Mock LambdaExecutionRoleCredentials executionRoleCredentials;
@Mock LambdaLayerService layerService;
@Mock Ec2Service ec2Service;
@@ -260,7 +265,7 @@ class ContainerLauncherTest {
new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, null, 4566);
ContainerLauncher backgroundLauncher = new ContainerLauncher(
new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer),
lifecycleManager, streamingDockerClient, logStreamer, imageResolver, runtimeApiServerFactory,
lifecycleManager, streamingDockerClient, dockerHttp, logStreamer, imageResolver, runtimeApiServerFactory,
dockerHostResolver, config, regionResolver, ecrRegistryManager, layers,
new LaunchedContainerAwsEnv(endpoint), executionRoleCredentials, ec2Service,
mock(DockerExitEvents.class));
@@ -514,7 +519,7 @@ class ContainerLauncherTest {
networkResolver, new ContainerEngineDetector(dockerClient));
ContainerReachableEndpoint endpoint =
new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, null, 4566);
return new ContainerLauncher(builder, lifecycleManager, streamingDockerClient, logStreamer, selectedResolver,
return new ContainerLauncher(builder, lifecycleManager, streamingDockerClient, dockerHttp, logStreamer, selectedResolver,
runtimeApiServerFactory, dockerHostResolver, config, regionResolver, ecrRegistryManager,
layerService, new LaunchedContainerAwsEnv(endpoint),
executionRoleCredentials, ec2Service, mock(DockerExitEvents.class));
@@ -998,17 +1003,37 @@ class ContainerLauncherTest {
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 void directoryMode(String path, int mode) {
lenient().when(dockerHttp.execute(argThat(request -> request != null
&& ("/containers/container-123/archive?path="
+ UrlEscapers.urlFormParameterEscaper().escape(path)).equals(request.path()))))
.thenReturn(statResponse(1 << 31 | mode));
}
/** The stat answer Docker's {@code HEAD /containers/{id}/archive} sends in its header. */
private static DockerHttpClient.Response statResponse(int goMode) {
String stat = Base64.getEncoder().encodeToString(
("{\"mode\":" + goMode + ",\"linkTarget\":\"\"}").getBytes(StandardCharsets.UTF_8));
return new DockerHttpClient.Response() {
@Override
public int getStatusCode() {
return 200;
}
@Override
public Map<String, List<String>> getHeaders() {
return Map.of("X-Docker-Container-Path-Stat", List.of(stat));
}
@Override
public InputStream getBody() {
return InputStream.nullInputStream();
}
@Override
public void close() {
}
};
}
private static LambdaFunction imageFunction() {
@@ -2557,6 +2582,7 @@ class ContainerLauncherTest {
new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer),
lifecycleManager,
streamingDockerClient,
dockerHttp,
new ContainerLogStreamer(streamingDockerClient, cloudWatchLogs),
imageResolver, runtimeApiServerFactory, dockerHostResolver, config, regionResolver,
ecrRegistryManager,
@@ -3,6 +3,7 @@ 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 com.github.dockerjava.transport.DockerHttpClient;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.docker.DockerBuildContext;
import io.floci.aws.core.common.docker.DockerClientProducer;
@@ -40,33 +41,35 @@ class WorkingDirectoryAccessDockerIntegrationTest {
@Test
void aWorkingDirectoryOnlyTheImageUserCanEnterFailsInitAsAnInvalidEntrypoint() throws Exception {
withContainer(null, (docker, containerId) -> {
withContainer(null, (docker, http, containerId) -> {
LambdaInitException error = assertThrows(LambdaInitException.class,
() -> WorkingDirectoryAccess.requireLambdaUserCanEnter(docker, containerId, List.of()));
() -> WorkingDirectoryAccess.requireLambdaUserCanEnter(docker, http, 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())));
withContainer("/app", (docker, http, containerId) -> assertThrows(LambdaInitException.class,
() -> WorkingDirectoryAccess.requireLambdaUserCanEnter(docker, http, containerId, List.of())));
}
@Test
void aWorkingDirectoryEveryoneCanEnterStartsAsBefore() throws Exception {
withContainer("/srv/open", (docker, containerId) -> assertDoesNotThrow(
() -> WorkingDirectoryAccess.requireLambdaUserCanEnter(docker, containerId, List.of())));
withContainer("/srv/open", (docker, http, containerId) -> assertDoesNotThrow(
() -> WorkingDirectoryAccess.requireLambdaUserCanEnter(docker, http, containerId, List.of())));
}
private interface ContainerTest {
void run(DockerClient docker, String containerId) throws Exception;
void run(DockerClient docker, DockerHttpClient http, 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()) {
DockerClientProducer producer = new DockerClientProducer(config);
try (DockerClient docker = producer.dockerClient();
DockerHttpClient http = producer.controlPlaneHttpClient()) {
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));
@@ -81,7 +84,7 @@ class WorkingDirectoryAccessDockerIntegrationTest {
}
String containerId = create.exec().getId();
try {
test.run(docker, containerId);
test.run(docker, http, containerId);
} finally {
docker.removeContainerCmd(containerId).withForce(true).exec();
}
@@ -0,0 +1,166 @@
package io.floci.aws.services.lambda.launcher;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.ContainerConfig;
import com.github.dockerjava.transport.DockerHttpClient;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The wire contract of the archive stat probe behind the working directory check: one HEAD per
* path, the mode read from the base64 JSON of the stat header, and a 404 or a file answered with
* an unknown entry rather than a failure.
*/
class WorkingDirectoryAccessStatTest {
private static final String STAT_HEADER = "X-Docker-Container-Path-Stat";
@Test
void theCheckProbesEachPathWithAHeadArchiveRequest() {
DockerHttpClient http = statHttp(Map.of(
"/var", missing(),
"/var/task", missing()));
require("/var/task", http);
ArgumentCaptor<DockerHttpClient.Request> requests =
ArgumentCaptor.forClass(DockerHttpClient.Request.class);
verify(http, times(2)).execute(requests.capture());
assertEquals(List.of("HEAD", "HEAD"), requests.getAllValues().stream()
.map(DockerHttpClient.Request::method).toList());
assertEquals(List.of("/containers/c-1/archive?path=%2Fvar", "/containers/c-1/archive?path=%2Fvar%2Ftask"),
requests.getAllValues().stream().map(DockerHttpClient.Request::path).toList());
requests.getAllValues().forEach(request -> {
assertEquals(Map.of(), request.headers());
assertEquals(null, request.bodyBytes());
assertEquals(null, request.hijackedInput());
});
}
@Test
void aDirectoryStatStopsLambdasUserWhenOthersCannotEnter() {
DockerHttpClient http = statHttp(Map.of(
"/var", stat(1 << 31 | 0755),
"/var/task", stat(1 << 31 | 0700)));
LambdaInitException error = assertThrows(LambdaInitException.class,
() -> require("/var/task", http));
assertEquals("Runtime.InvalidEntrypoint", error.errorType());
}
@Test
void aDirectoryStatEveryoneCanEnterPassesTheCheck() {
DockerHttpClient http = statHttp(Map.of(
"/var", stat(1 << 31 | 0755),
"/var/task", stat(1 << 31 | 0711)));
assertDoesNotThrow(() -> require("/var/task", http));
}
@Test
void aFileStatIsNotHeldAgainstTheFunction() {
DockerHttpClient http = statHttp(Map.of(
"/var", stat(0755),
"/var/task", stat(0755)));
assertDoesNotThrow(() -> require("/var/task", http));
}
@Test
void aMissingPathStatIsNotHeldAgainstTheFunction() {
DockerHttpClient http = statHttp(Map.of(
"/var", missing(),
"/var/task", missing()));
assertDoesNotThrow(() -> require("/var/task", http));
}
@Test
void aSymlinkStatIsFollowedToItsTarget() {
DockerHttpClient http = statHttp(Map.of(
"/app", symlink("/home/nonroot"),
"/home", stat(1 << 31 | 0755),
"/home/nonroot", stat(1 << 31 | 0700)));
assertThrows(LambdaInitException.class, () -> require("/app", http));
}
private static void require(String workingDir, DockerHttpClient http) {
InspectContainerResponse inspected = mock(InspectContainerResponse.class);
ContainerConfig config = mock(ContainerConfig.class);
when(config.getWorkingDir()).thenReturn(workingDir);
when(inspected.getConfig()).thenReturn(config);
InspectContainerCmd inspect = mock(InspectContainerCmd.class);
when(inspect.exec()).thenReturn(inspected);
DockerClient docker = mock(DockerClient.class);
when(docker.inspectContainerCmd("c-1")).thenReturn(inspect);
WorkingDirectoryAccess.requireLambdaUserCanEnter(docker, http, "c-1", List.of());
}
/** A control plane transport whose archive probes answer from {@code answers}, by path. */
private static DockerHttpClient statHttp(Map<String, DockerHttpClient.Response> answers) {
DockerHttpClient http = mock(DockerHttpClient.class);
when(http.execute(any())).thenAnswer(invocation -> {
DockerHttpClient.Request request = invocation.getArgument(0);
String path = request.path();
String probe = path.substring(path.indexOf("path=") + "path=".length());
return answers.get(URLDecoder.decode(probe, StandardCharsets.UTF_8));
});
return http;
}
private static DockerHttpClient.Response stat(int goMode) {
return statResponse(200, "{\"mode\":" + goMode + ",\"linkTarget\":\"\"}");
}
private static DockerHttpClient.Response symlink(String target) {
return statResponse(200, "{\"mode\":" + (1 << 27) + ",\"linkTarget\":\"" + target + "\"}");
}
private static DockerHttpClient.Response missing() {
return statResponse(404, "{}");
}
private static DockerHttpClient.Response statResponse(int status, String json) {
String stat = Base64.getEncoder().encodeToString(json.getBytes(StandardCharsets.UTF_8));
return new DockerHttpClient.Response() {
@Override
public int getStatusCode() {
return status;
}
@Override
public Map<String, List<String>> getHeaders() {
return status == 200 ? Map.of(STAT_HEADER, List.of(stat)) : Map.of();
}
@Override
public InputStream getBody() {
return InputStream.nullInputStream();
}
@Override
public void close() {
}
};
}
}