mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(ecs): apply EFS access point POSIX ownership to shared local volumes (#1686)
* feat(ecs): apply EFS access point POSIX ownership to shared local volumes #1569 materialises an ECS task's efsVolumeConfiguration volume as a shared local Docker named volume (floci-efs-<fileSystemId>). Docker creates a named volume root:root 0755, so a task whose image runs as a non-root USER — as containers mounting an EFS access point typically do — cannot create files on it and fails with EACCES. Real EFS initialises an access point's root directory per RootDirectory.CreationInfo {OwnerUid, OwnerGid, Permissions} and applies the access point's PosixUser to all I/O regardless of the process uid. This change emulates that mechanism for the shared local volume, driven by generic config: - New floci.storage.efs.* block (owner-uid, owner-gid, root-permissions, setgid, init-image, mount-user, mount-group-add). Every value is empty/false by default, so a shared volume behaves exactly as before (a plain named volume, no ownership change) unless explicitly configured. - ContainerLifecycleManager.ensureSharedVolume(...) ensures the volume then, if ownership is configured, chowns/chmods the mount root once (run-once guard; optional setgid so subdirectories inherit the owner gid) inside a short-lived helper container. - ContainerSpec/ContainerBuilder gain withUser/withGroupAdd; wired into createContainerCmd.withUser and HostConfig.withGroupAdd. - EcsContainerManager initialises the EFS volume root via ensureSharedVolume before mounting it. Unit tests cover the no-op default (no helper container, no image pull), the one-off chown/chmod/setgid helper with the run-once guard, the builder round-trip, and the EcsContainerManager wiring. * fix(ecs): apply configured EFS PosixUser to containers mounting a shared volume Wire the previously-inert floci.storage.efs.mount-user / mount-group-add config into the ECS container spec: a container mounting an EFS-backed shared volume now runs under the configured uid[:gid] and adds the supplementary group, emulating the access point's PosixUser squashing. Without this a non-root image USER could not write a volume owned by owner-uid/owner-gid. Also add the floci.storage.efs.* section to application.yml (the source of truth for effective defaults) and correct the root-permissions Javadoc, which implied leaving it empty always skips volume init even when owner/setgid are set. * docs: regenerate action tables
This commit is contained in:
1 parent
312fe377fc
commit
45ed00ebc7
11 files changed
+475
-4
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+118
@@ -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());
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+19
-1
@@ -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());
|
||||
|
||||
Reference in new issue
Block a user