Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(ecs): enforce host-volume bind-mount safety fail-closed at register and run time (#3543)

Niels Kootstra126af7314168
diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md
index 58ad5a8bdc..01005e6f8f 100644
--- a/docs/configuration/advanced/application-yml.md
+++ b/docs/configuration/advanced/application-yml.md
@@ -307,6 +307,8 @@ All keys in this table are declared on `EmulatorConfig` and accept environment v
| `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | *(unset)* | Docker network for ECS task containers |
| `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default memory (MB) when task definition omits it |
| `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default CPU units when task definition omits it |
+| `FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS` | *(unset)* | Comma-separated allowlist of parent directories for host volume bind mounts; by default (unset, and `ALLOW_UNSAFE_HOST_VOLUMES=false`) every host volume `sourcePath` is rejected |
+| `FLOCI_SERVICES_ECS_ALLOW_UNSAFE_HOST_VOLUMES` | `false` | Allow any host path, bypassing the host-volume-roots allowlist (traversal, bare root, and the Docker socket or an ancestor directory of it are still always rejected) |
| `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` | `false` | Enforce IAM identity-based policies on every request when `true` |
| `FLOCI_SERVICES_OPENSEARCH_MOCK` | `false` | Skip Docker; domains appear active immediately (useful for CI) |
| `FLOCI_SERVICES_OPENSEARCH_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave OpenSearch containers running after Floci stops |
diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md
index 7470b2e9c9..040438c624 100644
--- a/docs/configuration/environment-variables.md
+++ b/docs/configuration/environment-variables.md
@@ -447,6 +447,8 @@ These services spawn Docker containers. They require access to the Docker socket
| `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default task memory when not specified in the task definition |
| `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default task CPU units when not specified in the task definition |
| `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | _(none)_ | Docker network for ECS task containers |
+| `FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS` | _(none)_ | Comma-separated allowlist of parent directories host volume `sourcePath`s must resolve under. By default (unset, and `ALLOW_UNSAFE_HOST_VOLUMES=false`) every host volume `sourcePath` is rejected |
+| `FLOCI_SERVICES_ECS_ALLOW_UNSAFE_HOST_VOLUMES` | `false` | Allow any host path, bypassing `HOST_VOLUME_ROOTS`; traversal, the bare root, and the Docker socket (or an ancestor directory of it, e.g. `/var/run`) are still always rejected |
### EC2
diff --git a/docs/services/ecs.md b/docs/services/ecs.md
index ef272706f4..eac56df605 100644
--- a/docs/services/ecs.md
+++ b/docs/services/ecs.md
@@ -206,6 +206,34 @@ unchanged.
| `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | *(unset)* | Docker network for task containers |
| `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default memory (MB) when the task definition omits it |
| `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default CPU units when the task definition omits it |
+| `FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS` | *(unset)* | Approved parent directories for host volume bind mounts (`volumes[].host.sourcePath`) |
+| `FLOCI_SERVICES_ECS_ALLOW_UNSAFE_HOST_VOLUMES` | `false` | Allow any host path, bypassing the `HOST_VOLUME_ROOTS` allowlist; traversal, the bare root, and the Docker socket are still always rejected |
+
+### Host volume safety
+
+A task definition's `volumes[].host.sourcePath` is a caller-controlled filesystem path that Floci bind-mounts straight into the launched container, so both `RegisterTaskDefinition` and the actual bind mount at `RunTask` time validate it (the second check narrows the window between validation and mount, and also covers task definitions registered before this policy existed).
+
+Always rejected, regardless of configuration:
+
+- Relative paths, and any path containing a `..` segment.
+- The bare filesystem root (`/`).
+- The Docker daemon socket and any directory that contains it (e.g. `/var/run`, `/run`, `/var`), including via a symlink that resolves onto one of these paths. The protected socket is the one Floci's own Docker client connects to, resolved the same way the client resolves it: `floci.docker.docker-host`, then `DOCKER_HOST`, then the active Docker context (Colima, OrbStack, Rancher Desktop, Podman), then `/var/run/docker.sock`. The conventional locations `/var/run/docker.sock` and `/run/docker.sock` are always protected as well.
+
+**By default, with no configuration, every host `sourcePath` is rejected.** You must explicitly opt in with one of:
+
+- `FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS`: a comma-separated allowlist of approved parent directories. A `sourcePath` must resolve (symlinks included) under one of them:
+
+ ```yaml
+ services:
+ floci:
+ image: floci/floci:latest
+ environment:
+ FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS: /srv/floci/volumes,/data
+ ```
+
+- `FLOCI_SERVICES_ECS_ALLOW_UNSAFE_HOST_VOLUMES=true`: allow any host path (for local development where any host path should be mountable). The traversal, bare-root, and Docker socket blocks above are never bypassed by this flag.
+
+A rejected `sourcePath` fails `RegisterTaskDefinition` with `InvalidParameterException`; a rejection caught again at `RunTask` time (e.g. a task definition registered before this policy existed) stops the task with that message as its `stoppedReason`. Named Docker volumes, EFS volumes, and host volumes with no `sourcePath` (ephemeral, container-local storage) are unaffected by these checks.
### EFS volume ownership
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 45d064687c..745373b938 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -1753,6 +1753,23 @@ public interface EmulatorConfig {
@WithDefault("256")
int defaultCpuUnits();
+
+ /**
+ * Approved parent directories for task definition host volume bind mounts
+ * (volumes[].host.sourcePath). A sourcePath must resolve under one of these roots.
+ * Empty (the default) rejects every host volume sourcePath unless
+ * {@link #allowUnsafeHostVolumes()} is set, subject to the always-on traversal,
+ * bare-root, and Docker socket blocks below.
+ */
+ Optional<List<String>> hostVolumeRoots();
+
+ /**
+ * When true, bypasses the {@link #hostVolumeRoots()} allowlist check for host volumes,
+ * allowing any absolute path. Traversal segments, the bare root "/", and the Docker
+ * socket (or any ancestor directory that contains it) are still always rejected.
+ */
+ @WithDefault("false")
+ boolean allowUnsafeHostVolumes();
}
interface ResourceGroupsTaggingServiceConfig {
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java
index e9f957f612..f65e8ff81a 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java
@@ -30,6 +30,7 @@ import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.Optional;
+import java.util.function.Function;
/**
* CDI producer for the DockerClient singleton bean.
@@ -100,7 +101,24 @@ public class DockerClientProducer {
* validated against the context's CA, matching what the Docker CLI itself does for such
* a context.
*/
- record ResolvedDockerConnection(String host, Optional<Path> tlsCertPath, boolean skipTlsVerify) {
+ public record ResolvedDockerConnection(String host, Optional<Path> tlsCertPath, boolean skipTlsVerify) {
+ }
+
+ /**
+ * Resolves the Docker endpoint this process connects to, from {@code floci.docker.*} and the
+ * process environment ({@code DOCKER_HOST}, {@code DOCKER_CONFIG}, {@code DOCKER_CONTEXT}).
+ * This is the single resolution behind the {@link DockerClient} bean; anything that needs to
+ * know where the daemon lives, such as the ECS host-volume policy protecting the daemon
+ * socket, must derive it from here rather than re-implement part of the precedence.
+ *
+ * @param environment lookup for the standard Docker variables; {@code System::getenv} in
+ * production, a map lookup in tests
+ */
+ public static ResolvedDockerConnection resolveDockerConnection(
+ EmulatorConfig.DockerConfig docker, Function<String, String> environment) {
+ Path dockerConfigDir = resolveDockerConfigDir(docker.dockerConfigPath(), environment.apply("DOCKER_CONFIG"));
+ return resolveDockerConnection(docker.dockerHost(), environment.apply("DOCKER_HOST"), isWindows(),
+ dockerConfigDir, environment.apply("DOCKER_CONTEXT"));
}
/**
@@ -381,11 +399,7 @@ public class DockerClientProducer {
@Produces
@ApplicationScoped
public DockerClient dockerClient() {
- Path dockerConfigDir =
- resolveDockerConfigDir(config.docker().dockerConfigPath(), System.getenv("DOCKER_CONFIG"));
- ResolvedDockerConnection connection = resolveDockerConnection(
- config.docker().dockerHost(), System.getenv("DOCKER_HOST"), isWindows(),
- dockerConfigDir, System.getenv("DOCKER_CONTEXT"));
+ ResolvedDockerConnection connection = resolveDockerConnection(config.docker(), System::getenv);
String dockerHost = connection.host();
LOG.infov("Creating DockerClient for host: {0}", dockerHost);
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java
index a4dd0050c3..6f6e8b8927 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandler.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ecs;
import io.github.hectorvent.floci.core.common.AwsErrorResponse;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.Attribute;
import io.github.hectorvent.floci.services.ecs.model.AwsVpcConfiguration;
import io.github.hectorvent.floci.services.ecs.model.CapacityProvider;
@@ -52,11 +53,13 @@ public class EcsJsonHandler {
private final EcsService service;
private final ObjectMapper objectMapper;
+ private final HostVolumePolicy hostVolumePolicy;
@Inject
- public EcsJsonHandler(EcsService service, ObjectMapper objectMapper) {
+ public EcsJsonHandler(EcsService service, ObjectMapper objectMapper, HostVolumePolicy hostVolumePolicy) {
this.service = service;
this.objectMapper = objectMapper;
+ this.hostVolumePolicy = hostVolumePolicy;
}
public Response handle(String action, JsonNode request, String region) {
@@ -1507,6 +1510,9 @@ public class EcsJsonHandler {
}
for (JsonNode item : node) {
String hostSourcePath = item.path("host").path("sourcePath").asText(null);
+ if (hostSourcePath != null && !hostSourcePath.isBlank()) {
+ hostVolumePolicy.validate(hostSourcePath);
+ }
EfsVolumeConfiguration efs = parseEfsVolumeConfiguration(item.path("efsVolumeConfiguration"));
result.add(new Volume(item.path("name").asText(), hostSourcePath, efs));
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
index 2b3791111c..e3505c2aa1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManager.java
@@ -67,6 +67,7 @@ public class EcsContainerManager {
private final SsmService ssmService;
private final SecretsManagerService secretsManagerService;
private final EcrRegistryManager ecrRegistryManager;
+ private final HostVolumePolicy hostVolumePolicy;
@Inject
public EcsContainerManager(ContainerBuilder containerBuilder,
@@ -78,7 +79,8 @@ public class EcsContainerManager {
LaunchedContainerAwsEnv awsEnv,
SsmService ssmService,
SecretsManagerService secretsManagerService,
- EcrRegistryManager ecrRegistryManager) {
+ EcrRegistryManager ecrRegistryManager,
+ HostVolumePolicy hostVolumePolicy) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
@@ -88,6 +90,7 @@ public class EcsContainerManager {
this.awsEnv = awsEnv;
this.ssmService = ssmService;
this.secretsManagerService = secretsManagerService;
+ this.hostVolumePolicy = hostVolumePolicy;
this.ecrRegistryManager = ecrRegistryManager;
}
@@ -203,7 +206,13 @@ public class EcsContainerManager {
String sourcePath = volumeSourcePaths.get(mp.sourceVolume());
EfsVolumeConfiguration efs = efsVolumes.get(mp.sourceVolume());
if (sourcePath != null) {
- // Host volume: bind-mount an absolute path on the Docker host.
+ // Host volume: bind-mount an absolute path on the Docker host. Re-validate
+ // here (not just at RegisterTaskDefinition time): this narrows the window
+ // between validation and mount for a symlink swapped in afterward, and
+ // also covers task definitions persisted before this policy existed. A
+ // rejection is not swallowed, it propagates out of startTask and is
+ // surfaced by EcsService as the task's stoppedReason.
+ hostVolumePolicy.validate(sourcePath);
if (mp.readOnly()) {
specBuilder.withReadOnlyBind(sourcePath, mp.containerPath());
} else {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/HostVolumePolicy.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/HostVolumePolicy.java
new file mode 100644
index 0000000000..983aba6b56
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/HostVolumePolicy.java
@@ -0,0 +1,223 @@
+package io.github.hectorvent.floci.services.ecs.container;
+
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.docker.DockerClientProducer;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.io.IOException;
+import java.nio.file.InvalidPathException;
+import java.nio.file.Path;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.List;
+import java.util.function.Function;
+
+/**
+ * Guards task-definition {@code volumes[].host.sourcePath} against the unsafe bind mounts a
+ * caller-controlled task definition could otherwise request: relative/traversal paths, the bare
+ * filesystem root, anything that reaches the Docker daemon socket, and (unless
+ * {@code floci.services.ecs.allow-unsafe-host-volumes} is set) paths outside the configured
+ * {@code floci.services.ecs.host-volume-roots} allowlist.
+ *
+ * <p>Traversal segments, the bare root, and the Docker socket (or any ancestor directory that
+ * contains it, e.g. {@code /var/run}) are always rejected, even with the unsafe-host-volumes
+ * escape hatch enabled, since there is no legitimate task definition that needs them.
+ *
+ * <p>Shared between {@link io.github.hectorvent.floci.services.ecs.EcsJsonHandler}, which runs
+ * this check once at RegisterTaskDefinition time, and {@link EcsContainerManager}, which runs it
+ * again immediately before every bind mount at RunTask time. The second check narrows the
+ * TOCTOU window between validation and mount (a symlink swapped in after registration) and also
+ * covers task definitions that were persisted before this policy existed.
+ */
+@ApplicationScoped
+public class HostVolumePolicy {
+
+ private static final List<String> LITERAL_DOCKER_SOCKET_PATHS = List.of(
+ "/var/run/docker.sock",
+ "/run/docker.sock");
+
+ private final EmulatorConfig config;
+ private final Function<String, String> environment;
+ // Resolved once on first use: the environment and Docker context files do not change for
+ // the life of the process, and the resolver logs when it picks a context endpoint.
+ private volatile String effectiveDockerHost;
+
+ @Inject
+ public HostVolumePolicy(EmulatorConfig config) {
+ this(config, System::getenv);
+ }
+
+ /**
+ * @param environment lookup for the {@code DOCKER_HOST}, {@code DOCKER_CONFIG} and
+ * {@code DOCKER_CONTEXT} variables; {@code System::getenv} in production
+ */
+ public HostVolumePolicy(EmulatorConfig config, Function<String, String> environment) {
+ this.config = config;
+ this.environment = environment;
+ }
+
+ public void validate(String sourcePath) {
+ Path rawPath;
+ try {
+ rawPath = Path.of(sourcePath);
+ } catch (InvalidPathException e) {
+ throw new AwsException("InvalidParameterException",
+ "volumes[].host.sourcePath is not a valid filesystem path: " + sourcePath, 400);
+ }
+ if (!rawPath.isAbsolute()) {
+ throw new AwsException("InvalidParameterException",
+ "volumes[].host.sourcePath must be an absolute path: " + sourcePath, 400);
+ }
+ for (Path segment : rawPath) {
+ if ("..".equals(segment.toString())) {
+ throw new AwsException("InvalidParameterException",
+ "volumes[].host.sourcePath must not contain '..' segments: " + sourcePath, 400);
+ }
+ }
+ Path normalized = rawPath.normalize();
+ if (normalized.getNameCount() == 0) {
+ throw new AwsException("InvalidParameterException",
+ "volumes[].host.sourcePath must not be the filesystem root: " + sourcePath, 400);
+ }
+
+ Path canonical = canonicalizeForContainment(normalized);
+ if (exposesDockerSocket(normalized, canonical)) {
+ throw new AwsException("InvalidParameterException",
+ "volumes[].host.sourcePath must not target or contain the Docker socket: "
+ + sourcePath, 400);
+ }
+
+ EmulatorConfig.EcsServiceConfig ecsConfig = config.services().ecs();
+ if (ecsConfig.allowUnsafeHostVolumes()) {
+ return;
+ }
+ List<String> roots = ecsConfig.hostVolumeRoots().orElse(List.of());
+ if (roots.isEmpty()) {
+ throw new AwsException("InvalidParameterException",
+ "volumes[].host.sourcePath is rejected by default: " + sourcePath
+ + ". Configure floci.services.ecs.host-volume-roots"
+ + " (FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS) with approved parent"
+ + " directories, or set floci.services.ecs.allow-unsafe-host-volumes"
+ + " (FLOCI_SERVICES_ECS_ALLOW_UNSAFE_HOST_VOLUMES) to true to allow"
+ + " any host path.", 400);
+ }
+ for (String root : roots) {
+ Path rootCanonical = canonicalizeForContainment(Path.of(root).normalize());
+ if (canonical.equals(rootCanonical) || canonical.startsWith(rootCanonical)) {
+ return;
+ }
+ }
+ throw new AwsException("InvalidParameterException",
+ "volumes[].host.sourcePath is not within an approved host-volume root: " + sourcePath, 400);
+ }
+
+ /**
+ * True when {@code normalized} (or its canonical form) is the Docker socket itself, or is an
+ * ancestor directory that contains it (e.g. {@code /var/run}, {@code /run}, or {@code /var}
+ * all expose {@code docker.sock} just as directly as naming the socket file outright).
+ */
+ private boolean exposesDockerSocket(Path normalized, Path canonical) {
+ for (String candidate : dockerSocketCandidates()) {
+ Path candidateNormalized;
+ try {
+ candidateNormalized = Path.of(candidate).normalize();
+ } catch (InvalidPathException e) {
+ continue;
+ }
+ if (normalized.equals(candidateNormalized)) {
+ return true;
+ }
+ Path candidateCanonical = canonicalizeCandidateForContainment(candidateNormalized);
+ if (candidateCanonical.equals(canonical) || candidateCanonical.startsWith(canonical)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Candidate Docker socket paths: the socket Floci's own Docker client connects to, plus the
+ * two conventional Linux/macOS locations and Docker Desktop's per-user rootless socket as
+ * defence in depth. The first comes from the same resolution {@link DockerClientProducer}
+ * uses to build the client ({@code floci.docker.docker-host}, then {@code DOCKER_HOST}, then
+ * the active Docker context), so a daemon reached through, say, {@code DOCKER_HOST=unix:///tmp/x.sock}
+ * or a Colima context is protected too. Only a {@code unix://} endpoint names a filesystem
+ * path; {@code tcp://} and Windows named pipes have nothing a bind mount could expose.
+ */
+ private List<String> dockerSocketCandidates() {
+ List<String> candidates = new ArrayList<>(LITERAL_DOCKER_SOCKET_PATHS);
+ String userHome = System.getProperty("user.home");
+ if (userHome != null && !userHome.isBlank()) {
+ candidates.add(userHome + "/.docker/run/docker.sock");
+ }
+ String daemonHost = effectiveDockerHost();
+ if (daemonHost.startsWith("unix://")) {
+ String path = daemonHost.substring("unix://".length());
+ if (!path.isBlank()) {
+ candidates.add(path);
+ }
+ }
+ return candidates;
+ }
+
+ private String effectiveDockerHost() {
+ String host = effectiveDockerHost;
+ if (host == null) {
+ String resolved = DockerClientProducer.resolveDockerConnection(config.docker(), environment).host();
+ host = resolved == null ? "" : resolved;
+ effectiveDockerHost = host;
+ }
+ return host;
+ }
+
+ /**
+ * Canonicalizes a Docker-socket candidate by resolving symlinks in its parent directory only,
+ * then re-appending the literal socket file name. Docker Desktop for Mac makes
+ * {@code /var/run/docker.sock} itself a symlink to a per-user path (e.g. under
+ * {@code ~/.docker/run/}); fully resolving the candidate would follow that symlink and land
+ * outside {@code /var/run}, which would defeat the ancestor check for exactly the case it
+ * exists to catch (a caller mounting {@code /var/run} or {@code /run} wholesale). Resolving
+ * only the parent still catches a symlinked ancestor directory, while leaving the socket's own
+ * leaf symlink (if any) out of the comparison, since containment is about what a bind mount of
+ * the caller's path would literally expose, not where the socket's target ultimately lives.
+ */
+ private static Path canonicalizeCandidateForContainment(Path normalizedAbsolutePath) {
+ Path parent = normalizedAbsolutePath.getParent();
+ Path fileName = normalizedAbsolutePath.getFileName();
+ if (parent == null || fileName == null) {
+ return canonicalizeForContainment(normalizedAbsolutePath);
+ }
+ return canonicalizeForContainment(parent).resolve(fileName);
+ }
+
+ /**
+ * Resolves symlinks on the nearest existing ancestor of {@code normalizedAbsolutePath} (via
+ * {@link Path#toRealPath}) and re-appends the remaining, not-yet-existing path segments. This
+ * catches a symlinked parent directory that escapes an approved root, or that resolves onto
+ * the Docker socket, even when the leaf itself does not exist yet (as with a host volume
+ * Docker will create on first use).
+ */
+ private static Path canonicalizeForContainment(Path normalizedAbsolutePath) {
+ Path candidate = normalizedAbsolutePath;
+ Deque<String> unresolvedSuffix = new ArrayDeque<>();
+ while (candidate != null) {
+ try {
+ Path real = candidate.toRealPath();
+ for (String segment : unresolvedSuffix) {
+ real = real.resolve(segment);
+ }
+ return real;
+ } catch (IOException e) {
+ Path fileName = candidate.getFileName();
+ if (fileName != null) {
+ unresolvedSuffix.addFirst(fileName.toString());
+ }
+ candidate = candidate.getParent();
+ }
+ }
+ return normalizedAbsolutePath;
+ }
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index d8c76b39be..7487b8c81c 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -491,6 +491,8 @@ floci:
ecs:
enabled: true
mock: false
+ host-volume-roots: []
+ allow-unsafe-host-volumes: false
appconfig:
enabled: true
appconfigdata:
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerCommandEntryPointTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerCommandEntryPointTest.java
index 3439295bd8..c68f1e124b 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerCommandEntryPointTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerCommandEntryPointTest.java
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.ecs;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
@@ -13,6 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -50,7 +53,8 @@ class EcsJsonHandlerCommandEntryPointTest {
return td;
});
- handler = new EcsJsonHandler(service, objectMapper);
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ handler = new EcsJsonHandler(service, objectMapper, new HostVolumePolicy(config));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerRuntimePlatformLogConfigurationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerRuntimePlatformLogConfigurationTest.java
index b17eed954c..ed573d0d8d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerRuntimePlatformLogConfigurationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerRuntimePlatformLogConfigurationTest.java
@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.ecs;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
@@ -13,6 +15,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -45,7 +48,8 @@ class EcsJsonHandlerRuntimePlatformLogConfigurationTest {
return td;
});
- handler = new EcsJsonHandler(service, objectMapper);
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ handler = new EcsJsonHandler(service, objectMapper, new HostVolumePolicy(config));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerTaskDefinitionPersistenceTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerTaskDefinitionPersistenceTest.java
index 9ead08b2a6..97e4548ed0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerTaskDefinitionPersistenceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerTaskDefinitionPersistenceTest.java
@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.PersistentStorage;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
+import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import jakarta.ws.rs.core.Response;
@@ -47,7 +48,13 @@ class EcsJsonHandlerTaskDefinitionPersistenceTest {
FileStorageFactory storage = new FileStorageFactory(dataDir);
ObjectMapper objectMapper = new ObjectMapper();
- EcsJsonHandler handler = new EcsJsonHandler(serviceWithStorage(storage), objectMapper);
+ // This test exercises persistence round-tripping, not host-volume safety, so the fixed
+ // literal sourcePath "/host/data" below needs an explicit opt-in under the new
+ // fail-closed default: allow any host path for this handler instance.
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.services().ecs().allowUnsafeHostVolumes()).thenReturn(true);
+ EcsJsonHandler handler = new EcsJsonHandler(serviceWithStorage(storage), objectMapper,
+ new HostVolumePolicy(config));
JsonNode request = objectMapper.readTree("""
{
"family": "restart-family",
@@ -91,7 +98,8 @@ class EcsJsonHandlerTaskDefinitionPersistenceTest {
FileStorageFactory storage = new FileStorageFactory(dataDir);
ObjectMapper objectMapper = new ObjectMapper();
EcsService service = serviceWithStorage(storage);
- EcsJsonHandler handler = new EcsJsonHandler(service, objectMapper);
+ EcsJsonHandler handler = new EcsJsonHandler(service, objectMapper,
+ new HostVolumePolicy(mock(EmulatorConfig.class, RETURNS_DEEP_STUBS)));
JsonNode registerReq = objectMapper.readTree("""
{
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerVolumesTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerVolumesTest.java
index ee02e3404b..f304c5c00c 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerVolumesTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/EcsJsonHandlerVolumesTest.java
@@ -2,14 +2,26 @@ package io.github.hectorvent.floci.services.ecs;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.util.HexFormat;
import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -18,6 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -34,6 +47,7 @@ class EcsJsonHandlerVolumesTest {
private EcsService service;
private ObjectMapper objectMapper;
+ private EmulatorConfig config;
private EcsJsonHandler handler;
@BeforeEach
@@ -51,11 +65,40 @@ class EcsJsonHandlerVolumesTest {
return td;
});
- handler = new EcsJsonHandler(service, objectMapper);
+ // Deep-stubbed: unstubbed leaf methods return Optional.empty()/false, the same
+ // fail-closed defaults as production, so host-volume-roots is empty and
+ // allow-unsafe-host-volumes is false unless a test stubs otherwise. That means any
+ // test registering a host-volume sourcePath must explicitly opt in (a root or the
+ // unsafe flag) or expect the default rejection.
+ config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ handler = new EcsJsonHandler(service, objectMapper, new HostVolumePolicy(config));
+ }
+
+ private static String registerRequestWithHostVolume(String sourcePath) {
+ return """
+ {
+ "family": "host-volume-family",
+ "containerDefinitions": [
+ {
+ "name": "app",
+ "image": "alpine:latest",
+ "mountPoints": [
+ {"sourceVolume": "vol", "containerPath": "/app/data", "readOnly": false}
+ ]
+ }
+ ],
+ "volumes": [
+ {"name": "vol", "host": {"sourcePath": "%s"}}
+ ]
+ }
+ """.formatted(sourcePath.replace("\\", "\\\\"));
}
@Test
void registerTaskDefinitionRoundTripsVolumesAndMountPoints() throws Exception {
+ // This test is about JSON round-trip fidelity, not host-volume safety, so opt out of
+ // the fail-closed default explicitly.
+ when(config.services().ecs().allowUnsafeHostVolumes()).thenReturn(true);
String requestJson = """
{
"family": "volumes-family",
@@ -246,4 +289,199 @@ class EcsJsonHandlerVolumesTest {
assertTrue(efs.path("authorizationConfig").path("accessPointId").isMissingNode(),
"accessPointId should not be set");
}
+
+ // ── Host-volume safety ──────────────────────────────────────────────────
+
+ @Test
+ void registerTaskDefinitionRejectsRelativeHostSourcePath() throws Exception {
+ JsonNode request = objectMapper.readTree(registerRequestWithHostVolume("relative/path"));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", request, "us-east-1"));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void registerTaskDefinitionRejectsTraversalHostSourcePath() throws Exception {
+ JsonNode request = objectMapper.readTree(registerRequestWithHostVolume("/host/abs/../../etc"));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", request, "us-east-1"));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void registerTaskDefinitionRejectsBareRootHostSourcePath() throws Exception {
+ JsonNode request = objectMapper.readTree(registerRequestWithHostVolume("/"));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", request, "us-east-1"));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void registerTaskDefinitionRejectsDockerSocketHostVolume() throws Exception {
+ // Allow any host path so a rejection here can only come from the Docker-socket check
+ // itself, not the fail-closed default (proving the socket-specific rule fires).
+ when(config.services().ecs().allowUnsafeHostVolumes()).thenReturn(true);
+
+ JsonNode varRun = objectMapper.readTree(registerRequestWithHostVolume("/var/run/docker.sock"));
+ AwsException varRunEx = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", varRun, "us-east-1"));
+ assertEquals("InvalidParameterException", varRunEx.getErrorCode());
+
+ JsonNode run = objectMapper.readTree(registerRequestWithHostVolume("/run/docker.sock"));
+ AwsException runEx = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", run, "us-east-1"));
+ assertEquals("InvalidParameterException", runEx.getErrorCode());
+ }
+
+ @Test
+ void registerTaskDefinitionRejectsDockerSocketAncestorDirectories() throws Exception {
+ // Mounting a directory that CONTAINS the socket (/var/run, /run) exposes docker.sock
+ // just as directly as naming the socket file outright, and must be blocked even when
+ // allow-unsafe-host-volumes is true.
+ when(config.services().ecs().allowUnsafeHostVolumes()).thenReturn(true);
+
+ JsonNode varRun = objectMapper.readTree(registerRequestWithHostVolume("/var/run"));
+ AwsException varRunEx = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", varRun, "us-east-1"));
+ assertEquals("InvalidParameterException", varRunEx.getErrorCode());
+
+ JsonNode run = objectMapper.readTree(registerRequestWithHostVolume("/run"));
+ AwsException runEx = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", run, "us-east-1"));
+ assertEquals("InvalidParameterException", runEx.getErrorCode());
+ }
+
+ @Test
+ void registerTaskDefinitionRejectsHostSourcePathByDefault() throws Exception {
+ // With host-volume-roots empty and allow-unsafe-host-volumes false (the shipped
+ // defaults, unstubbed here), any host sourcePath is rejected fail-closed and the
+ // message names both config keys so an operator knows how to opt in.
+ JsonNode request = objectMapper.readTree(registerRequestWithHostVolume("/some/data"));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", request, "us-east-1"));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ assertTrue(ex.getMessage().contains("floci.services.ecs.host-volume-roots"),
+ "message must name the roots config key: " + ex.getMessage());
+ assertTrue(ex.getMessage().contains("FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS"),
+ "message must name the roots env var: " + ex.getMessage());
+ assertTrue(ex.getMessage().contains("floci.services.ecs.allow-unsafe-host-volumes"),
+ "message must name the unsafe-flag config key: " + ex.getMessage());
+ assertTrue(ex.getMessage().contains("FLOCI_SERVICES_ECS_ALLOW_UNSAFE_HOST_VOLUMES"),
+ "message must name the unsafe-flag env var: " + ex.getMessage());
+ }
+
+ @Test
+ void registerTaskDefinitionRejectsHostSourcePathOutsideConfiguredRoots() throws Exception {
+ when(config.services().ecs().hostVolumeRoots()).thenReturn(Optional.of(List.of("/approved")));
+ JsonNode request = objectMapper.readTree(registerRequestWithHostVolume("/not-approved/data"));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", request, "us-east-1"));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void registerTaskDefinitionAllowsHostSourcePathInsideConfiguredRoots() throws Exception {
+ when(config.services().ecs().hostVolumeRoots()).thenReturn(Optional.of(List.of("/approved")));
+ JsonNode request = objectMapper.readTree(registerRequestWithHostVolume("/approved/sub/data"));
+
+ Response response = handler.handle("RegisterTaskDefinition", request, "us-east-1");
+ JsonNode td = objectMapper.valueToTree(response.getEntity()).path("taskDefinition");
+ assertEquals("/approved/sub/data",
+ td.path("volumes").get(0).path("host").path("sourcePath").asText());
+ }
+
+ @Test
+ void registerTaskDefinitionAllowUnsafeHostVolumesBypassesRootCheckButNotDockerSocket() throws Exception {
+ when(config.services().ecs().hostVolumeRoots()).thenReturn(Optional.of(List.of("/approved")));
+ when(config.services().ecs().allowUnsafeHostVolumes()).thenReturn(true);
+
+ JsonNode outsideRoot = objectMapper.readTree(registerRequestWithHostVolume("/anywhere/else"));
+ Response response = handler.handle("RegisterTaskDefinition", outsideRoot, "us-east-1");
+ JsonNode td = objectMapper.valueToTree(response.getEntity()).path("taskDefinition");
+ assertEquals("/anywhere/else",
+ td.path("volumes").get(0).path("host").path("sourcePath").asText());
+
+ JsonNode socket = objectMapper.readTree(registerRequestWithHostVolume("/var/run/docker.sock"));
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", socket, "us-east-1"));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void registerTaskDefinitionRejectsTheSocketNamedByDockerHostEnv(@TempDir Path tempDir) throws Exception {
+ // With floci.docker.docker-host at its default, Floci's own Docker client connects to
+ // whatever DOCKER_HOST names, so that socket is the live daemon socket and must be
+ // protected exactly like /var/run/docker.sock, even with allow-unsafe-host-volumes.
+ Path daemonSocket = tempDir.resolve("floci-docker.sock");
+ when(config.docker().dockerHost()).thenReturn("unix:///var/run/docker.sock");
+ when(config.docker().dockerConfigPath())
+ .thenReturn(Optional.of(tempDir.resolve("no-docker-config").toString()));
+ when(config.services().ecs().allowUnsafeHostVolumes()).thenReturn(true);
+ handler = new EcsJsonHandler(service, objectMapper, new HostVolumePolicy(config,
+ environment(Map.of("DOCKER_HOST", "unix://" + daemonSocket))));
+
+ JsonNode request = objectMapper.readTree(registerRequestWithHostVolume(daemonSocket.toString()));
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", request, "us-east-1"));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ @Test
+ void registerTaskDefinitionRejectsTheDirectoryHoldingTheActiveContextSocket(@TempDir Path tempDir)
+ throws Exception {
+ // Colima, OrbStack and Rancher Desktop publish their daemon socket through a Docker
+ // context rather than DOCKER_HOST. Floci's client follows the active context, so the
+ // directory holding that socket exposes the daemon just like /var/run does.
+ Path dockerConfigDir = tempDir.resolve("docker-config");
+ Path socketDir = tempDir.resolve("colima");
+ writeContextFixture(dockerConfigDir, "colima", "unix://" + socketDir.resolve("docker.sock"));
+ when(config.docker().dockerHost()).thenReturn("unix:///var/run/docker.sock");
+ when(config.docker().dockerConfigPath()).thenReturn(Optional.of(dockerConfigDir.toString()));
+ when(config.services().ecs().allowUnsafeHostVolumes()).thenReturn(true);
+ handler = new EcsJsonHandler(service, objectMapper, new HostVolumePolicy(config, environment(Map.of())));
+
+ JsonNode request = objectMapper.readTree(registerRequestWithHostVolume(socketDir.toString()));
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", request, "us-east-1"));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
+
+ private static Function<String, String> environment(Map<String, String> variables) {
+ return variables::get;
+ }
+
+ /** Lays out {@code config.json} and a context's {@code meta.json} the way the Docker CLI does. */
+ private static void writeContextFixture(Path dockerConfigDir, String contextName, String host) throws Exception {
+ Files.createDirectories(dockerConfigDir);
+ Files.writeString(dockerConfigDir.resolve("config.json"), "{\"currentContext\":\"" + contextName + "\"}");
+ byte[] nameHash = MessageDigest.getInstance("SHA-256").digest(contextName.getBytes(StandardCharsets.UTF_8));
+ Path metaDir = dockerConfigDir.resolve("contexts").resolve("meta").resolve(HexFormat.of().formatHex(nameHash));
+ Files.createDirectories(metaDir);
+ Files.writeString(metaDir.resolve("meta.json"),
+ "{\"Name\":\"" + contextName + "\",\"Metadata\":{},"
+ + "\"Endpoints\":{\"docker\":{\"Host\":\"" + host + "\",\"SkipTLSVerify\":false}}}");
+ }
+
+ @Test
+ void registerTaskDefinitionRejectsSymlinkEscapeOutsideConfiguredRoot(@TempDir Path tempDir) throws IOException {
+ Path approvedRoot = tempDir.resolve("approved");
+ Path outsideTarget = tempDir.resolve("outside");
+ Files.createDirectories(approvedRoot);
+ Files.createDirectories(outsideTarget);
+ Path escapeLink = approvedRoot.resolve("escape");
+ Files.createSymbolicLink(escapeLink, outsideTarget);
+
+ when(config.services().ecs().hostVolumeRoots())
+ .thenReturn(Optional.of(List.of(approvedRoot.toString())));
+ JsonNode request = objectMapper.readTree(registerRequestWithHostVolume(escapeLink.toString()));
+
+ AwsException ex = assertThrows(AwsException.class,
+ () -> handler.handle("RegisterTaskDefinition", request, "us-east-1"));
+ assertEquals("InvalidParameterException", ex.getErrorCode());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerAwsBaselineTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerAwsBaselineTest.java
index 04e035d16e..3c7e0393c3 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerAwsBaselineTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerAwsBaselineTest.java
@@ -79,7 +79,7 @@ class EcsContainerManagerAwsBaselineTest {
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, mock(SsmService.class),
- mock(SecretsManagerService.class), ecrRegistryManager);
+ mock(SecretsManagerService.class), ecrRegistryManager, mock(HostVolumePolicy.class));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerEcrRewriteTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerEcrRewriteTest.java
index 63561e4952..9d06f06487 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerEcrRewriteTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerEcrRewriteTest.java
@@ -80,7 +80,7 @@ class EcsContainerManagerEcrRewriteTest {
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService,
- ecrRegistryManager);
+ ecrRegistryManager, mock(HostVolumePolicy.class));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerLifecycleTest.java
index 985763882c..2818da51ab 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerLifecycleTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerLifecycleTest.java
@@ -118,6 +118,6 @@ class EcsContainerManagerLifecycleTest {
mock(ContainerBuilder.class), lifecycleManager, mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), mock(EmulatorConfig.class), mock(RegionResolver.class),
mock(LaunchedContainerAwsEnv.class), mock(SsmService.class), mock(SecretsManagerService.class),
- mock(EcrRegistryManager.class));
+ mock(EcrRegistryManager.class), mock(HostVolumePolicy.class));
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerOverridesTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerOverridesTest.java
index 4bc9bf50b2..b6297b55ad 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerOverridesTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerOverridesTest.java
@@ -76,7 +76,7 @@ class EcsContainerManagerOverridesTest {
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService,
- ecrRegistryManager);
+ ecrRegistryManager, mock(HostVolumePolicy.class));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerPortMappingsTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerPortMappingsTest.java
index 853e32706a..b92404c563 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerPortMappingsTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerPortMappingsTest.java
@@ -91,7 +91,7 @@ class EcsContainerManagerPortMappingsTest {
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService,
- ecrRegistryManager);
+ ecrRegistryManager, mock(HostVolumePolicy.class));
}
private void startWith(List<PortMapping> portMappings) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java
index 84ce2f7d66..da37574d8d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerSecretsTest.java
@@ -70,7 +70,7 @@ class EcsContainerManagerSecretsTest {
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService,
- ecrRegistryManager);
+ ecrRegistryManager, mock(HostVolumePolicy.class));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerVolumesTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerVolumesTest.java
index 0f5fe10e5d..8fb31968ae 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerVolumesTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerVolumesTest.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.ecs.container;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
@@ -27,6 +28,7 @@ import java.util.Optional;
import java.util.OptionalInt;
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.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
@@ -78,9 +80,14 @@ class EcsContainerManagerVolumesTest {
ecrRegistryManager = mock(EcrRegistryManager.class);
when(ecrRegistryManager.rewriteImageUri(anyString())).thenAnswer(inv -> inv.getArgument(0));
+ // These tests bind-mount hand-built "/host/abs/..." paths that don't sit under any
+ // real approved root, so opt out of the fail-closed default explicitly; the Docker
+ // socket ancestor block still applies regardless (see the rejection test below).
+ when(config.services().ecs().allowUnsafeHostVolumes()).thenReturn(true);
+
manager = new EcsContainerManager(containerBuilder, lifecycleManager, logStreamer,
containerDetector, config, regionResolver, awsEnv, ssmService, secretsManagerService,
- ecrRegistryManager);
+ ecrRegistryManager, new HostVolumePolicy(config));
}
@Test
@@ -175,7 +182,7 @@ class EcsContainerManagerVolumesTest {
EcsContainerManager configured = new EcsContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), cfg,
mock(RegionResolver.class), awsEnv, mock(SsmService.class),
- mock(SecretsManagerService.class), ecrRegistryManager);
+ mock(SecretsManagerService.class), ecrRegistryManager, new HostVolumePolicy(cfg));
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
@@ -210,7 +217,7 @@ class EcsContainerManagerVolumesTest {
EcsContainerManager configured = new EcsContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), cfg,
mock(RegionResolver.class), awsEnv, mock(SsmService.class),
- mock(SecretsManagerService.class), ecrRegistryManager);
+ mock(SecretsManagerService.class), ecrRegistryManager, new HostVolumePolicy(cfg));
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
@@ -231,4 +238,33 @@ class EcsContainerManagerVolumesTest {
verify(builder, times(1)).withUser("1001:1001");
verify(builder, times(1)).withGroupAdd("2000");
}
+
+ /**
+ * The host-volume policy is enforced again at mount time, immediately before the bind
+ * call, not only once at RegisterTaskDefinition time. A mount whose source is an ancestor
+ * of the Docker socket (here {@code /var/run}, which contains {@code docker.sock}) must be
+ * rejected even though this test class's setUp already allows unsafe host volumes: the
+ * socket-ancestor block applies unconditionally. The rejection must propagate out of
+ * startTask (not be swallowed) and no bind must have been issued for it.
+ */
+ @Test
+ void startTaskRejectsMountThatExposesDockerSocketEvenWhenUnsafeVolumesAllowed() {
+ ContainerDefinition app = new ContainerDefinition();
+ app.setName("app");
+ app.setImage("app:latest");
+ app.setMountPoints(List.of(new MountPoint("run-vol", "/host-run", false)));
+
+ TaskDefinition taskDef = new TaskDefinition();
+ taskDef.setFamily("socket-family");
+ taskDef.setContainerDefinitions(List.of(app));
+ taskDef.setVolumes(List.of(new Volume("run-vol", "/var/run")));
+
+ EcsTask task = new EcsTask();
+ task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/socket1");
+
+ assertThrows(AwsException.class, () -> manager.startTask(task, taskDef, List.of(), "us-east-1"));
+
+ verify(builder, never()).withBind(any(), any());
+ verify(builder, never()).withReadOnlyBind(any(), any());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvokerTest.java
index 2721505028..091d69128e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvokerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvokerTest.java
@@ -55,6 +55,9 @@ class EventBridgeInvokerTest {
when(regionResolver.getAccountId()).thenReturn("000000000000");
when(eventBridgeService.putEvents(anyList(), anyString(), any()))
.thenReturn(new EventBridgeService.PutEventsResult(0, List.of()));
+ io.github.hectorvent.floci.config.EmulatorConfig emulatorConfig =
+ mock(io.github.hectorvent.floci.config.EmulatorConfig.class,
+ org.mockito.Mockito.RETURNS_DEEP_STUBS);
invoker = new EventBridgeInvoker(
lambdaService,
sqsService,
@@ -63,10 +66,11 @@ class EventBridgeInvokerTest {
firehoseService,
eventBridgeService,
ecsService,
- new io.github.hectorvent.floci.services.ecs.EcsJsonHandler(ecsService, new ObjectMapper()),
+ new io.github.hectorvent.floci.services.ecs.EcsJsonHandler(ecsService, new ObjectMapper(),
+ new io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy(emulatorConfig)),
regionResolver,
new ObjectMapper(),
- mock(io.github.hectorvent.floci.config.EmulatorConfig.class)
+ emulatorConfig
);
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java
index 9cf128a114..c7b6762e4e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorEcsRunTaskModeTest.java
@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.ecs.EcsJsonHandler;
import io.github.hectorvent.floci.services.ecs.EcsService;
+import io.github.hectorvent.floci.services.ecs.container.HostVolumePolicy;
import io.github.hectorvent.floci.services.ecs.model.NetworkConfiguration;
import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;
@@ -28,6 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -57,7 +59,8 @@ class AslExecutorEcsRunTaskModeTest {
void setUp() {
ecsService = mock(EcsService.class);
// A real handler so parseNetworkConfiguration / parseContainerOverrides actually run.
- EcsJsonHandler ecsJsonHandler = new EcsJsonHandler(ecsService, objectMapper);
+ EcsJsonHandler ecsJsonHandler = new EcsJsonHandler(ecsService, objectMapper,
+ new HostVolumePolicy(mock(EmulatorConfig.class, RETURNS_DEEP_STUBS)));
executor = new AslExecutor(
mock(LambdaExecutorService.class),
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 12d055e730..882ce44a47 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -272,6 +272,8 @@ floci:
ecs:
enabled: true
mock: true
+ host-volume-roots: []
+ allow-unsafe-host-volumes: false
appconfig:
enabled: true
appconfigdata: