Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(ecs): apply EFS access point POSIX ownership to shared local volumes (#1686)

Alex Banna45ed00ebc7a8
diff --git a/docs/configuration/advanced/application-yml.md b/docs/configuration/advanced/application-yml.md
index 896b7f858b..17ee5a24d0 100644
--- a/docs/configuration/advanced/application-yml.md
+++ b/docs/configuration/advanced/application-yml.md
@@ -45,6 +45,16 @@ floci:
storage:
mode: memory # memory | persistent | hybrid | wal
persistent-path: ./data
+ # EFS access-point emulation for the shared local Docker volumes that back ECS
+ # efsVolumeConfiguration mounts. All opt-in; with no overrides a shared volume is a plain
+ # named volume (root:root 0755), so existing behaviour is unchanged. See docs/services/ecs.md.
+ efs:
+ # owner-uid: 1001 # CreationInfo.OwnerUid (set together with owner-gid)
+ # owner-gid: 1001 # CreationInfo.OwnerGid (set together with owner-uid)
+ # root-permissions: "2775" # CreationInfo.Permissions; 3-4 octal digits (4-digit carries setgid/sticky)
+ init-image: busybox:stable # image for the one-off chown/chmod of the volume root
+ # mount-user: "1001:1001" # PosixUser: run mounting containers as uid[:gid]
+ # mount-group-add: 2000 # supplementary gid added to mounting containers
wal:
compaction-interval-ms: 30000
services:
diff --git a/docs/services/ecs.md b/docs/services/ecs.md
index e275869cfb..601d62a965 100644
--- a/docs/services/ecs.md
+++ b/docs/services/ecs.md
@@ -130,6 +130,21 @@ ECS emulates clusters, task definitions, tasks, and services. In the default con
| `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 |
+### EFS volume ownership
+
+A task's `efsVolumeConfiguration` volumes are backed by shared local Docker volumes (Floci cannot mount a real EFS file system). A Docker named volume is created `root:root 0755`, so a task whose image runs as a non-root `USER` cannot write it. To emulate an [EFS access point](https://docs.aws.amazon.com/efs/latest/ug/efs-access-points.html)'s `RootDirectory.CreationInfo` and `PosixUser`, configure `floci.storage.efs.*` (all opt-in; the default is a plain named volume, so existing behaviour is unchanged):
+
+| Key (`floci.storage.efs.`) | Env | AWS equivalent | Description |
+|---|---|---|---|
+| `owner-uid` | `FLOCI_STORAGE_EFS_OWNER_UID` | `CreationInfo.OwnerUid` | Owner uid of the volume root (set together with `owner-gid`) |
+| `owner-gid` | `FLOCI_STORAGE_EFS_OWNER_GID` | `CreationInfo.OwnerGid` | Owner gid of the volume root (set together with `owner-uid`) |
+| `root-permissions` | `FLOCI_STORAGE_EFS_ROOT_PERMISSIONS` | `CreationInfo.Permissions` | 3-4 octal digits, e.g. `0777`, or `2775` for the setgid bit |
+| `mount-user` | `FLOCI_STORAGE_EFS_MOUNT_USER` | `PosixUser {Uid,Gid}` | Run mounting containers as `uid[:gid]` |
+| `mount-group-add` | `FLOCI_STORAGE_EFS_MOUNT_GROUP_ADD` | `PosixUser` supplementary | Supplementary gid added to mounting containers |
+| `init-image` | `FLOCI_STORAGE_EFS_INIT_IMAGE` | — | Image for the one-off `chown`/`chmod` of the volume root (default `busybox:stable`) |
+
+`owner-uid` and `owner-gid` must be set together (a partial `CreationInfo` is not valid on AWS). The volume root is initialised once per volume; express the setgid bit through a 4-digit `root-permissions` (e.g. `2775`) so subdirectories inherit the owner gid.
+
### Mock mode
Set `FLOCI_SERVICES_ECS_MOCK=true` to run without Docker. In this mode tasks skip container launch and immediately transition to `RUNNING`, then to `STOPPED` when stopped. This is the recommended mode for unit/integration tests and CI pipelines where Docker-in-Docker is unavailable.
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 cd9e3ecf9c..6c0678f8c3 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -4,6 +4,7 @@ import io.smallrye.config.ConfigMapping;
import io.smallrye.config.WithDefault;
import java.util.List;
import java.util.Optional;
+import java.util.OptionalInt;
@ConfigMapping(prefix = "floci")
public interface EmulatorConfig {
@@ -177,6 +178,59 @@ public interface EmulatorConfig {
WalConfig wal();
ServiceStorageOverrides services();
+
+ EfsSharingConfig efs();
+ }
+
+ /**
+ * Emulates an Amazon EFS access point's POSIX ownership for the shared local Docker volumes
+ * that stand in for EFS file systems. A Docker named volume is created {@code root:root 0755},
+ * so a container whose image runs as a non-root {@code USER} (as ECS tasks and
+ * access-point-mounted workloads typically do) then cannot create files on it. Real EFS
+ * applies the access point's {@code PosixUser} to all I/O and initialises the root directory
+ * per {@code RootDirectory.CreationInfo}. These settings reproduce that: Floci initialises the
+ * shared volume root's owner/permissions once and can run the mounting containers under a
+ * fixed identity, so the emulated file system is writable by the intended uid/gid.
+ *
+ * <p>Every value is empty/false by default, so a shared volume behaves exactly as before —
+ * a plain named volume with no ownership change — unless explicitly configured.
+ */
+ interface EfsSharingConfig {
+ /** Owner uid applied to the volume root (EFS {@code RootDirectory.CreationInfo.OwnerUid}). */
+ OptionalInt ownerUid();
+
+ /** Owner gid applied to the volume root (EFS {@code RootDirectory.CreationInfo.OwnerGid}). */
+ OptionalInt ownerGid();
+
+ /**
+ * Octal permissions applied to the volume root (EFS {@code RootDirectory.CreationInfo.Permissions}),
+ * e.g. {@code "0777"}. A 4-digit value carries the special bits exactly as AWS does — e.g.
+ * {@code "2775"} sets the setgid bit so subdirectories inherit the owner gid (the standard
+ * POSIX pattern for a group-shared tree). When empty, no {@code chmod} for the permission
+ * bits is performed; however the init helper container still runs if {@link #ownerUid()} or
+ * {@link #ownerGid()} is set. Volume-root initialisation is skipped entirely only when all of
+ * {@code owner-uid}, {@code owner-gid}, and {@code root-permissions} are left at their
+ * defaults (plain named volume).
+ */
+ Optional<String> rootPermissions();
+
+ /** Lightweight image used for the one-off {@code chown}/{@code chmod} of the volume root. */
+ @WithDefault("busybox:stable")
+ String initImage();
+
+ /**
+ * Run containers that mount a shared volume as this {@code "uid[:gid]"}, emulating the
+ * access point's {@code PosixUser} that squashes all file-system I/O to a fixed identity.
+ * Empty leaves the container's image {@code USER} in effect.
+ */
+ Optional<String> mountUser();
+
+ /**
+ * Supplementary group id added to containers that mount a shared volume, so a process
+ * running under a different primary uid can still write a group-shared tree owned by
+ * {@link #ownerGid()}. Empty adds no supplementary group.
+ */
+ OptionalInt mountGroupAdd();
}
interface ServiceStorageOverrides {
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java
index 8a033ba280..2905e65b07 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java
@@ -123,6 +123,8 @@ public class ContainerBuilder {
private LogConfig logConfig;
private boolean privileged;
private String cgroupnsMode;
+ private String user;
+ private final List<String> groupAdd = new ArrayList<>();
private final List<String> dnsServers = new ArrayList<>();
Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver,
@@ -362,6 +364,28 @@ public class ContainerBuilder {
return this;
}
+ /**
+ * Sets the user the container process runs as, formatted {@code "uid[:gid]"}
+ * (Docker's top-level container user). Null or blank leaves the image {@code USER}
+ * in effect.
+ */
+ public Builder withUser(String user) {
+ this.user = user;
+ return this;
+ }
+
+ /**
+ * Adds a supplementary group id to the container process (Docker {@code --group-add}),
+ * so it can access group-owned resources without changing its primary uid/gid. Blank
+ * ids are ignored.
+ */
+ public Builder withGroupAdd(String groupId) {
+ if (groupId != null && !groupId.isBlank()) {
+ this.groupAdd.add(groupId);
+ }
+ return this;
+ }
+
/**
* Injects Floci's embedded DNS server into the container so virtual-hosted
* S3 hostnames (my-bucket.localhost.floci.io) resolve to Floci's Docker
@@ -406,7 +430,9 @@ public class ContainerBuilder {
privileged,
cgroupnsMode,
List.copyOf(dnsServers),
- workingDir
+ workingDir,
+ user,
+ List.copyOf(groupAdd)
);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
index 355eafd251..e19d0114d8 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
@@ -12,7 +12,10 @@ import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
+import com.github.dockerjava.api.model.Mount;
+import com.github.dockerjava.api.model.MountType;
import com.github.dockerjava.api.model.Ports;
+import com.github.dockerjava.core.command.WaitContainerResultCallback;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -23,6 +26,8 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
/**
* Manages Docker container lifecycle operations including create, start, stop, and remove.
@@ -38,6 +43,9 @@ public class ContainerLifecycleManager {
private final ContainerDetector containerDetector;
private final PortAllocator portAllocator;
+ /** Volumes whose shared-ownership root has already been initialised this process (run-once guard). */
+ private final ConcurrentHashMap<String, Boolean> initializedSharedVolumes = new ConcurrentHashMap<>();
+
@Inject
public ContainerLifecycleManager(DockerClient dockerClient,
ImageCacheService imageCacheService,
@@ -83,6 +91,9 @@ public class ContainerLifecycleManager {
if (spec.name() != null) {
createCmd.withName(spec.name());
}
+ if (spec.user() != null && !spec.user().isBlank()) {
+ createCmd.withUser(spec.user());
+ }
if (spec.env() != null && !spec.env().isEmpty()) {
createCmd.withEnv(spec.env());
}
@@ -190,6 +201,107 @@ public class ContainerLifecycleManager {
}
}
+ /**
+ * Ensures the named volume exists (see {@link #ensureVolume}) and, when POSIX ownership is
+ * requested, initialises the volume root once to emulate an Amazon EFS access point's
+ * {@code RootDirectory.CreationInfo}. A Docker named volume is created {@code root:root 0755},
+ * so a container whose image runs as a non-root {@code USER} (as ECS tasks and
+ * access-point-mounted workloads typically do) cannot create files on it. This chowns/chmods
+ * the mount root inside a short-lived helper container. A 4-digit octal
+ * {@code rootPermissions} (e.g. {@code "2775"}) carries the setgid bit, so subdirectories
+ * inherit the owner gid — matching {@code CreationInfo.Permissions} exactly.
+ *
+ * <p>The initialisation runs at most once per volume name per process. When no ownership is
+ * configured (all of {@code ownerUid}/{@code ownerGid}/{@code rootPermissions} empty) this
+ * degrades to a plain {@link #ensureVolume}, so the default behaviour is unchanged.
+ *
+ * @param volumeName the named volume
+ * @param ownerUid owner uid for the volume root (EFS {@code CreationInfo.OwnerUid})
+ * @param ownerGid owner gid for the volume root (EFS {@code CreationInfo.OwnerGid})
+ * @param rootPermissions octal permissions for the volume root (e.g. {@code "0777"}); empty skips init
+ * @param initImage lightweight image used for the one-off chown/chmod helper
+ */
+ public void ensureSharedVolume(String volumeName, OptionalInt ownerUid, OptionalInt ownerGid,
+ Optional<String> rootPermissions, String initImage) {
+ ensureVolume(volumeName);
+ if (rootPermissions.isEmpty() && ownerUid.isEmpty() && ownerGid.isEmpty()) {
+ return;
+ }
+ // An EFS access point's CreationInfo requires OwnerUid and OwnerGid together; reject a
+ // partial ownership config rather than emitting a malformed `chown uid:` (whose trailing
+ // colon makes chown resolve the login group and fail in busybox for an unknown uid).
+ if (ownerUid.isPresent() != ownerGid.isPresent()) {
+ throw new IllegalArgumentException(
+ "floci.storage.efs owner-uid and owner-gid must be set together");
+ }
+ // Validate before splicing into the helper's `sh -c`, matching CreationInfo.Permissions
+ // (^[0-7]{3,4}$), so a typo can't produce a mangled script that soft-fails.
+ rootPermissions.ifPresent(p -> {
+ if (!p.matches("^[0-7]{3,4}$")) {
+ throw new IllegalArgumentException(
+ "floci.storage.efs root-permissions must be 3-4 octal digits (e.g. \"0777\","
+ + " or \"2775\" for setgid): " + p);
+ }
+ });
+ // computeIfAbsent runs the one-off init under a per-volume lock, so a concurrent launch for
+ // the same volume waits for it to finish rather than mounting a still root:root 0755 root.
+ // Returning null on failure leaves the volume unmemoised, so the next launch retries.
+ initializedSharedVolumes.computeIfAbsent(volumeName, k -> {
+ try {
+ initSharedVolumeRoot(volumeName, ownerUid, ownerGid, rootPermissions, initImage);
+ return Boolean.TRUE;
+ } catch (RuntimeException e) {
+ LOG.warnv("Failed to initialise shared volume {0} ownership: {1}", volumeName, e.getMessage());
+ return null;
+ }
+ });
+ }
+
+ private void initSharedVolumeRoot(String volumeName, OptionalInt ownerUid, OptionalInt ownerGid,
+ Optional<String> rootPermissions, String initImage) {
+ String mount = "/floci-shared-volume";
+ StringBuilder script = new StringBuilder();
+ // ownerUid and ownerGid are validated to be present together by the caller, so the chown
+ // always has both operands (no trailing colon). setgid is expressed via a 4-digit octal
+ // rootPermissions (e.g. "2775"), matching CreationInfo.Permissions.
+ if (ownerUid.isPresent() && ownerGid.isPresent()) {
+ script.append("chown ").append(ownerUid.getAsInt()).append(':').append(ownerGid.getAsInt())
+ .append(' ').append(mount).append(" && ");
+ }
+ rootPermissions.ifPresent(p -> script.append("chmod ").append(p).append(' ').append(mount).append(" && "));
+ script.append("true");
+
+ String image = (initImage != null && !initImage.isBlank()) ? initImage : "busybox:stable";
+ imageCacheService.ensureImageExists(image);
+
+ HostConfig hostConfig = HostConfig.newHostConfig().withMounts(List.of(
+ new Mount().withType(MountType.VOLUME).withSource(volumeName).withTarget(mount)));
+ CreateContainerResponse created = dockerClient.createContainerCmd(image)
+ .withHostConfig(hostConfig)
+ .withCmd("sh", "-c", script.toString())
+ .exec();
+ String helperId = created.getId();
+ try {
+ dockerClient.startContainerCmd(helperId).exec();
+ Integer status = dockerClient.waitContainerCmd(helperId)
+ .exec(new WaitContainerResultCallback())
+ .awaitStatusCode(60, TimeUnit.SECONDS);
+ if (status == null || status != 0) {
+ // Throw so the caller leaves the volume unmemoised and retries on the next launch,
+ // rather than leaving it root:root 0755 with no further attempt.
+ throw new IllegalStateException("shared-volume init for " + volumeName
+ + " exited with status " + status + " (cmd: " + script + ")");
+ }
+ LOG.infov("Initialised shared volume {0} root (cmd: {1})", volumeName, script);
+ } finally {
+ try {
+ dockerClient.removeContainerCmd(helperId).withForce(true).exec();
+ } catch (Exception ignore) {
+ // best-effort cleanup of the one-off helper
+ }
+ }
+ }
+
/**
* Removes a named Docker volume, ignoring errors if it does not exist or is still in use.
*/
@@ -399,6 +511,12 @@ public class ContainerLifecycleManager {
hostConfig.withCgroupnsMode(spec.cgroupnsMode());
}
+ // Supplementary groups (Docker --group-add), e.g. to give a process access to a
+ // group-shared volume without changing its primary uid/gid.
+ if (spec.groupAdd() != null && !spec.groupAdd().isEmpty()) {
+ hostConfig.withGroupAdd(spec.groupAdd());
+ }
+
// Memory limit
if (spec.hasMemoryLimit()) {
hostConfig.withMemory(spec.memoryBytes());
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java
index 9ba5f4f467..755f2ecfbc 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java
@@ -28,6 +28,8 @@ import java.util.Map;
* @param cgroupnsMode Docker cgroup namespace mode (for example, "host")
* @param dnsServers DNS server IPs to inject into the container (e.g. Floci's embedded DNS)
* @param workingDir Working directory inside the container (overrides image WORKDIR)
+ * @param user User the container process runs as, formatted "uid[:gid]" (null = image USER)
+ * @param groupAdd Supplementary group IDs added to the container process
*/
public record ContainerSpec(
String image,
@@ -46,14 +48,16 @@ public record ContainerSpec(
boolean privileged,
String cgroupnsMode,
List<String> dnsServers,
- String workingDir
+ String workingDir,
+ String user,
+ List<String> groupAdd
) {
/**
* Creates a minimal spec with just the image name.
* All other fields will be null or empty lists.
*/
public ContainerSpec(String image) {
- this(image, null, List.of(), null, null, null, Map.of(), List.of(), null, List.of(), List.of(), List.of(), null, false, null, List.of(), null);
+ this(image, null, List.of(), null, null, null, Map.of(), List.of(), null, List.of(), List.of(), List.of(), null, false, null, List.of(), null, null, List.of());
}
/**
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 14a3e31934..8818ffc944 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
@@ -174,9 +174,27 @@ public class EcsContainerManager {
// EFS volume: a shared local Docker named volume, so every task
// container that mounts the same EFS file system shares persistent
// storage — the local stand-in for an EFS mount (Docker cannot mount
- // a real EFS file system).
+ // a real EFS file system). Initialise the volume root's POSIX ownership
+ // to emulate the EFS access point's RootDirectory.CreationInfo, so a
+ // non-root task image USER can write to it (no-op unless configured).
+ var efsCfg = config.storage().efs();
+ lifecycleManager.ensureSharedVolume(efsVolumeName(efs.fileSystemId()),
+ efsCfg.ownerUid(), efsCfg.ownerGid(), efsCfg.rootPermissions(),
+ efsCfg.initImage());
specBuilder.withNamedVolume(efsVolumeName(efs.fileSystemId()),
mp.containerPath(), mp.readOnly());
+ // Emulate the access point's PosixUser: run the container under the
+ // configured uid[:gid] and/or add the supplementary group, so a non-root
+ // image can read/write the shared volume owned by ownerUid/ownerGid.
+ efsCfg.mountUser().ifPresent(u -> {
+ // Validate the access point PosixUser format before applying it.
+ if (!u.matches("^\\d+(:\\d+)?$")) {
+ throw new IllegalArgumentException(
+ "floci.storage.efs.mount-user must be \"uid\" or \"uid:gid\": " + u);
+ }
+ specBuilder.withUser(u);
+ });
+ efsCfg.mountGroupAdd().ifPresent(gid -> specBuilder.withGroupAdd(String.valueOf(gid)));
} else {
LOG.warnv("Skipping mountPoint with unresolved volume {0} on container {1}",
mp.sourceVolume(), def.getName());
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 4ab03672fd..830ae55d88 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -72,6 +72,18 @@ floci:
persistent-path: ./data
host-persistent-path: ./data
prune-volumes-on-delete: false
+ # EFS access-point emulation for the shared local Docker volumes that stand in for EFS file
+ # systems. All opt-in; with the defaults below (and no owner/permission overrides) volumes are
+ # plain named volumes, so existing behaviour is unchanged. Emulates an access point's
+ # RootDirectory.CreationInfo (owner-uid/owner-gid/root-permissions) and PosixUser
+ # (mount-user/mount-group-add).
+ efs:
+ # owner-uid: # RootDirectory.CreationInfo.OwnerUid applied to the volume root (set with owner-gid)
+ # owner-gid: # RootDirectory.CreationInfo.OwnerGid applied to the volume root (set with owner-uid)
+ # root-permissions: # CreationInfo.Permissions, 3-4 octal digits; e.g. "0777", or "2775" for setgid
+ init-image: busybox:stable
+ # mount-user: # run mounting containers as "uid[:gid]" (access point PosixUser)
+ # mount-group-add: # supplementary gid added to mounting containers
wal:
compaction-interval-ms: 30000
services:
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java
index 3b09b25b56..df19a086ee 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java
@@ -8,6 +8,7 @@ import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -98,6 +99,31 @@ class ContainerBuilderTest {
assertEquals("host", spec.cgroupnsMode());
}
+ @Test
+ void withUserAndGroupAddRoundTripIntoSpec() {
+ TestFixture fixture = new TestFixture();
+
+ ContainerSpec spec = fixture.builder.newContainer("alpine")
+ .withUser("1001:1001")
+ .withGroupAdd("1001")
+ .withGroupAdd("2000")
+ .withGroupAdd(" ") // blank ignored
+ .build();
+
+ assertEquals("1001:1001", spec.user());
+ assertEquals(List.of("1001", "2000"), spec.groupAdd());
+ }
+
+ @Test
+ void userAndGroupAddDefaultToUnset() {
+ TestFixture fixture = new TestFixture();
+
+ ContainerSpec spec = fixture.builder.newContainer("alpine").build();
+
+ assertNull(spec.user());
+ assertEquals(List.of(), spec.groupAdd());
+ }
+
@Test
void imageRegistryBasePrefixesEveryContainerImage() {
TestFixture fixture = new TestFixture();
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java
index 7fbd4bf0b8..df5ce106e0 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerVolumeTest.java
@@ -1,10 +1,16 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.command.CreateContainerCmd;
+import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InspectVolumeCmd;
import com.github.dockerjava.api.command.InspectVolumeResponse;
+import com.github.dockerjava.api.command.RemoveContainerCmd;
+import com.github.dockerjava.api.command.StartContainerCmd;
+import com.github.dockerjava.api.command.WaitContainerCmd;
import com.github.dockerjava.api.exception.DockerException;
import com.github.dockerjava.api.exception.NotFoundException;
+import com.github.dockerjava.core.command.WaitContainerResultCallback;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -12,6 +18,9 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
+import java.util.Optional;
+import java.util.OptionalInt;
+
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@@ -99,5 +108,114 @@ class ContainerLifecycleManagerVolumeTest {
assertFalse(manager.volumeExists("some-volume"));
}
+
+ @Test
+ void ensureSharedVolume_noOwnershipConfig_createsVolumeButNoHelperContainer() {
+ InspectVolumeCmd cmd = mock(InspectVolumeCmd.class);
+ when(dockerClient.inspectVolumeCmd("shared")).thenReturn(cmd);
+ when(cmd.exec()).thenReturn(mock(InspectVolumeResponse.class)); // volume already exists
+
+ manager.ensureSharedVolume("shared", OptionalInt.empty(), OptionalInt.empty(),
+ Optional.empty(), "busybox:stable");
+
+ // No ownership requested -> degrades to a plain named volume: no helper container is
+ // spun up and no init image is pulled (proves the clean-source default is a no-op).
+ verify(dockerClient, never()).createContainerCmd(anyString());
+ verifyNoInteractions(imageCacheService);
+ }
+
+ @Test
+ void ensureSharedVolume_withOwnership_runsChownChmodHelperExactlyOnce() {
+ InspectVolumeCmd ivc = mock(InspectVolumeCmd.class);
+ when(dockerClient.inspectVolumeCmd("shared")).thenReturn(ivc);
+ when(ivc.exec()).thenReturn(mock(InspectVolumeResponse.class));
+
+ CreateContainerCmd ccc = mock(CreateContainerCmd.class, RETURNS_SELF);
+ when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(ccc);
+ CreateContainerResponse resp = mock(CreateContainerResponse.class);
+ when(resp.getId()).thenReturn("helper-id");
+ when(ccc.exec()).thenReturn(resp);
+
+ StartContainerCmd scc = mock(StartContainerCmd.class);
+ when(dockerClient.startContainerCmd("helper-id")).thenReturn(scc);
+
+ WaitContainerCmd wcc = mock(WaitContainerCmd.class);
+ when(dockerClient.waitContainerCmd("helper-id")).thenReturn(wcc);
+ WaitContainerResultCallback wcb = mock(WaitContainerResultCallback.class);
+ when(wcc.exec(any(WaitContainerResultCallback.class))).thenReturn(wcb);
+ when(wcb.awaitStatusCode(anyLong(), any())).thenReturn(0);
+
+ RemoveContainerCmd rcc = mock(RemoveContainerCmd.class, RETURNS_SELF);
+ when(dockerClient.removeContainerCmd("helper-id")).thenReturn(rcc);
+
+ manager.ensureSharedVolume("shared", OptionalInt.of(1001), OptionalInt.of(1001),
+ Optional.of("2775"), "busybox:stable");
+ // Second call is a no-op thanks to the run-once guard.
+ manager.ensureSharedVolume("shared", OptionalInt.of(1001), OptionalInt.of(1001),
+ Optional.of("2775"), "busybox:stable");
+
+ verify(imageCacheService, times(1)).ensureImageExists("busybox:stable");
+ // The setgid bit is carried by the 4-digit octal (2775) rather than a separate chmod g+s.
+ verify(ccc, times(1)).withCmd("sh", "-c",
+ "chown 1001:1001 /floci-shared-volume && chmod 2775 /floci-shared-volume && true");
+ verify(dockerClient, times(1)).createContainerCmd("busybox:stable");
+ verify(dockerClient, times(1)).removeContainerCmd("helper-id");
+ }
+
+ @Test
+ void ensureSharedVolume_partialOwnershipConfig_isRejected() {
+ InspectVolumeCmd cmd = mock(InspectVolumeCmd.class);
+ when(dockerClient.inspectVolumeCmd("shared")).thenReturn(cmd);
+ when(cmd.exec()).thenReturn(mock(InspectVolumeResponse.class));
+
+ // owner-uid without owner-gid is not a valid CreationInfo — reject rather than emit
+ // a malformed `chown 1001:` that fails in busybox.
+ assertThrows(IllegalArgumentException.class, () ->
+ manager.ensureSharedVolume("shared", OptionalInt.of(1001), OptionalInt.empty(),
+ Optional.empty(), "busybox:stable"));
+ verify(dockerClient, never()).createContainerCmd(anyString());
+ }
+
+ @Test
+ void ensureSharedVolume_invalidRootPermissions_isRejected() {
+ InspectVolumeCmd cmd = mock(InspectVolumeCmd.class);
+ when(dockerClient.inspectVolumeCmd("shared")).thenReturn(cmd);
+ when(cmd.exec()).thenReturn(mock(InspectVolumeResponse.class));
+
+ // Non-octal permissions must be rejected before being spliced into the helper's sh -c.
+ assertThrows(IllegalArgumentException.class, () ->
+ manager.ensureSharedVolume("shared", OptionalInt.of(1001), OptionalInt.of(1001),
+ Optional.of("999"), "busybox:stable"));
+ verify(dockerClient, never()).createContainerCmd(anyString());
+ }
+
+ @Test
+ void ensureSharedVolume_helperNonZeroExit_retriesOnNextLaunch() {
+ InspectVolumeCmd ivc = mock(InspectVolumeCmd.class);
+ when(dockerClient.inspectVolumeCmd("shared")).thenReturn(ivc);
+ when(ivc.exec()).thenReturn(mock(InspectVolumeResponse.class));
+
+ CreateContainerCmd ccc = mock(CreateContainerCmd.class, RETURNS_SELF);
+ when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(ccc);
+ CreateContainerResponse resp = mock(CreateContainerResponse.class);
+ when(resp.getId()).thenReturn("helper-id");
+ when(ccc.exec()).thenReturn(resp);
+ when(dockerClient.startContainerCmd("helper-id")).thenReturn(mock(StartContainerCmd.class));
+ WaitContainerCmd wcc = mock(WaitContainerCmd.class);
+ when(dockerClient.waitContainerCmd("helper-id")).thenReturn(wcc);
+ WaitContainerResultCallback wcb = mock(WaitContainerResultCallback.class);
+ when(wcc.exec(any(WaitContainerResultCallback.class))).thenReturn(wcb);
+ when(wcb.awaitStatusCode(anyLong(), any())).thenReturn(1); // helper fails
+ when(dockerClient.removeContainerCmd("helper-id")).thenReturn(mock(RemoveContainerCmd.class, RETURNS_SELF));
+
+ // A non-zero helper exit must not memoise the volume as initialised — the next launch
+ // retries rather than leaving the root root:root 0755 forever.
+ manager.ensureSharedVolume("shared", OptionalInt.of(1001), OptionalInt.of(1001),
+ Optional.of("0777"), "busybox:stable");
+ manager.ensureSharedVolume("shared", OptionalInt.of(1001), OptionalInt.of(1001),
+ Optional.of("0777"), "busybox:stable");
+
+ verify(dockerClient, times(2)).createContainerCmd("busybox:stable");
+ }
}
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 82d0c2dae9..7bba2de20c 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
@@ -19,6 +19,8 @@ import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalInt;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
@@ -140,4 +142,72 @@ class EcsContainerManagerVolumesTest {
verify(builder, never()).withBind(any(), any());
verify(builder, never()).withReadOnlyBind(any(), any());
}
+
+ @Test
+ void efsVolumesInitialiseSharedVolumeOwnershipFromConfig() {
+ // Rebuild the manager with an EFS config that emulates an access point's CreationInfo +
+ // PosixUser (owner 1001:1001, "2775" — 0775 plus the setgid special bit via the 4-digit
+ // octal). The EFS mount must initialise the shared volume root with exactly those values
+ // before mounting it.
+ EmulatorConfig cfg = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(cfg.storage().efs().ownerUid()).thenReturn(OptionalInt.of(1001));
+ when(cfg.storage().efs().ownerGid()).thenReturn(OptionalInt.of(1001));
+ when(cfg.storage().efs().rootPermissions()).thenReturn(Optional.of("2775"));
+ when(cfg.storage().efs().initImage()).thenReturn("busybox:stable");
+ EcsContainerManager configured = new EcsContainerManager(containerBuilder, lifecycleManager,
+ mock(ContainerLogStreamer.class), mock(ContainerDetector.class), cfg,
+ mock(RegionResolver.class));
+
+ ContainerDefinition app = new ContainerDefinition();
+ app.setName("app");
+ app.setImage("app:latest");
+ app.setMountPoints(List.of(new MountPoint("customer-data", "/mnt/efs", false)));
+
+ TaskDefinition taskDef = new TaskDefinition();
+ taskDef.setFamily("efs-family");
+ taskDef.setContainerDefinitions(List.of(app));
+ taskDef.setVolumes(List.of(new Volume("customer-data", null,
+ new EfsVolumeConfiguration("fs-abc", "/dps", "ENABLED", null, null, null))));
+
+ EcsTask task = new EcsTask();
+ task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/efsown");
+
+ configured.startTask(task, taskDef, List.of(), "us-east-1");
+
+ verify(lifecycleManager, times(1)).ensureSharedVolume("floci-efs-fs-abc",
+ OptionalInt.of(1001), OptionalInt.of(1001), Optional.of("2775"), "busybox:stable");
+ }
+
+ @Test
+ void efsMountAppliesConfiguredPosixUserAndGroupToContainer() {
+ // Rebuild with an EFS config carrying a PosixUser (mount-user 1001:1001) and a supplementary
+ // group (mount-group-add 2000). A container mounting the EFS volume must run under that user
+ // and add that group, emulating the access point's PosixUser squashing — otherwise the
+ // container keeps its image USER and cannot write the volume owned by ownerUid/ownerGid.
+ EmulatorConfig cfg = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(cfg.storage().efs().mountUser()).thenReturn(Optional.of("1001:1001"));
+ when(cfg.storage().efs().mountGroupAdd()).thenReturn(OptionalInt.of(2000));
+ EcsContainerManager configured = new EcsContainerManager(containerBuilder, lifecycleManager,
+ mock(ContainerLogStreamer.class), mock(ContainerDetector.class), cfg,
+ mock(RegionResolver.class));
+
+ ContainerDefinition app = new ContainerDefinition();
+ app.setName("app");
+ app.setImage("app:latest");
+ app.setMountPoints(List.of(new MountPoint("customer-data", "/mnt/efs", false)));
+
+ TaskDefinition taskDef = new TaskDefinition();
+ taskDef.setFamily("efs-family");
+ taskDef.setContainerDefinitions(List.of(app));
+ taskDef.setVolumes(List.of(new Volume("customer-data", null,
+ new EfsVolumeConfiguration("fs-abc", "/dps", "ENABLED", null, null, null))));
+
+ EcsTask task = new EcsTask();
+ task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/efsposix");
+
+ configured.startTask(task, taskDef, List.of(), "us-east-1");
+
+ verify(builder, times(1)).withUser("1001:1001");
+ verify(builder, times(1)).withGroupAdd("2000");
+ }
}