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 3e2d580b80..a4dd0050c3 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 @@ -1524,12 +1524,20 @@ public class EcsJsonHandler { Integer transitEncryptionPort = node.path("transitEncryptionPort").isNumber() ? node.path("transitEncryptionPort").asInt() : null; JsonNode auth = node.path("authorizationConfig"); + String rootDirectory = node.path("rootDirectory").asText(null); + String accessPointId = auth.path("accessPointId").asText(null); + if (accessPointId != null && !accessPointId.isBlank() + && rootDirectory != null && !rootDirectory.isBlank() && !"/".equals(rootDirectory)) { + throw new AwsException("InvalidParameterException", + "Root directory must either be omitted or set to '/' when an EFS access point " + + "is specified in authorizationConfig.accessPointId.", 400); + } return new EfsVolumeConfiguration( fileSystemId, - node.path("rootDirectory").asText(null), + rootDirectory, node.path("transitEncryption").asText(null), transitEncryptionPort, - auth.path("accessPointId").asText(null), + accessPointId, auth.path("iam").asText(null)); } 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 4ea6f41d87..2b3791111c 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 @@ -35,9 +35,13 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.io.Closeable; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.util.ArrayList; import java.util.HashSet; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -206,30 +210,7 @@ public class EcsContainerManager { specBuilder.withBind(sourcePath, mp.containerPath()); } } else if (efs != null) { - // 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). 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))); + mountEfsVolume(specBuilder, efs, mp); } else { LOG.warnv("Skipping mountPoint with unresolved volume {0} on container {1}", mp.sourceVolume(), def.getName()); @@ -594,9 +575,75 @@ public class EcsContainerManager { return slash >= 0 ? taskArn.substring(slash + 1) : taskArn; } - /** Name of the local Docker named volume backing an EFS file system. */ - private static String efsVolumeName(String fileSystemId) { - return "floci-efs-" + fileSystemId; + /** + * Materialises an EFS-configured task volume as a shared local Docker named volume scoped to + * both the file system and the mount's effective root (see {@link #efsVolumeName}), then + * initialises the volume root's POSIX ownership to emulate the EFS access point's + * RootDirectory.CreationInfo (no-op unless {@code floci.storage.efs} configures owner/permissions) + * and applies the configured PosixUser emulation (uid[:gid] and/or supplementary group) so a + * non-root task image can read/write the shared volume. + */ + private void mountEfsVolume(ContainerBuilder.Builder specBuilder, EfsVolumeConfiguration efs, MountPoint mp) { + String efsVolumeName = efsVolumeName(efs.fileSystemId(), efs.accessPointId(), efs.rootDirectory()); + var efsCfg = config.storage().efs(); + lifecycleManager.ensureSharedVolume(efsVolumeName, + efsCfg.ownerUid(), efsCfg.ownerGid(), efsCfg.rootPermissions(), + efsCfg.initImage()); + specBuilder.withNamedVolume(efsVolumeName, mp.containerPath(), mp.readOnly()); + efsCfg.mountUser().ifPresent(u -> { + 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))); + } + + /** + * Name of the local Docker named volume backing an EFS-configured task volume, scoped to + * both the file system and the mount's effective root so two mounts of the same file system + * with a different {@code rootDirectory}/{@code accessPointId} land on isolated volumes + * while identical configurations keep sharing one, matching how AWS scopes an EFS mount to + * a subpath. When {@code accessPointId} is set, it determines the effective root: on real + * AWS an access point's own root directory takes precedence over any {@code rootDirectory} + * on the volume. + */ + static String efsVolumeName(String fileSystemId, String accessPointId, String rootDirectory) { + if (accessPointId != null && !accessPointId.isBlank()) { + return "floci-efs-" + fileSystemId + "-" + sha256Hex("accessPoint:" + accessPointId); + } + String normalizedRoot = normalizeRootDirectory(rootDirectory); + if ("/".equals(normalizedRoot)) { + return "floci-efs-" + fileSystemId; + } + return "floci-efs-" + fileSystemId + "-" + sha256Hex(normalizedRoot); + } + + /** + * Canonicalises a {@code rootDirectory} path so syntactically different but equivalent + * paths (missing/blank, a missing leading slash, repeated slashes, a trailing slash) resolve + * to the same effective root instead of silently splitting shared storage across local + * volumes that AWS would treat as identical. + */ + private static String normalizeRootDirectory(String rootDirectory) { + if (rootDirectory == null || rootDirectory.isBlank()) { + return "/"; + } + String collapsed = rootDirectory.trim().replaceAll("/+", "/"); + if (collapsed.length() > 1 && collapsed.endsWith("/")) { + collapsed = collapsed.substring(0, collapsed.length() - 1); + } + return collapsed.startsWith("/") ? collapsed : "/" + collapsed; + } + + private static String sha256Hex(String value) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is required but not available", e); + } } // Inner enum to avoid import cycle — mirrors model.TaskStatus for readability diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EfsVolumeConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EfsVolumeConfiguration.java index e4788306ea..ca5b34fad8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ecs/model/EfsVolumeConfiguration.java +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/model/EfsVolumeConfiguration.java @@ -9,13 +9,17 @@ import io.quarkus.runtime.annotations.RegisterForReflection; * *

A container references the owning {@link Volume} by name via a {@link MountPoint}. * Docker cannot mount a real Amazon EFS file system, so Floci materialises an EFS-backed - * volume as a shared local Docker named volume ({@code floci-efs-}): - * every container that mounts the same file system shares persistent storage that survives - * task restarts — the local equivalent of an EFS mount. + * volume as a shared local Docker named volume: every container that mounts the same + * file system with the same effective root (its {@code rootDirectory}, or the access point's + * own root directory when {@code authorizationConfig.accessPointId} is set) shares persistent + * storage that survives task restarts, the local equivalent of an EFS mount, while a different + * {@code rootDirectory} or {@code accessPointId} on the same file system lands on an isolated + * volume, matching how AWS scopes an EFS mount to a subpath. * - *

{@code rootDirectory}, {@code transitEncryption}, {@code transitEncryptionPort} and - * {@code authorizationConfig} are modelled for RegisterTaskDefinition/DescribeTaskDefinition - * round-trip fidelity (so Terraform sees no drift) but have no effect on the local mount. + *

{@code transitEncryption} and {@code transitEncryptionPort} are modelled for + * RegisterTaskDefinition/DescribeTaskDefinition round-trip fidelity (so Terraform sees no + * drift) but have no effect on the local mount, since Docker has no notion of an encrypted + * NFS transport to emulate. */ @RegisterForReflection public record EfsVolumeConfiguration( 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 a2eb3d3af3..ee02e3404b 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,6 +2,7 @@ package io.github.hectorvent.floci.services.ecs; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition; import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; import jakarta.ws.rs.core.Response; @@ -12,6 +13,7 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -116,7 +118,7 @@ class EcsJsonHandlerVolumesTest { "name": "customer-data", "efsVolumeConfiguration": { "fileSystemId": "fs-0123456789abcdef0", - "rootDirectory": "/dps", + "rootDirectory": "/", "transitEncryption": "ENABLED", "transitEncryptionPort": 2999, "authorizationConfig": {"accessPointId": "fsap-0abc", "iam": "ENABLED"} @@ -136,10 +138,112 @@ class EcsJsonHandlerVolumesTest { assertTrue(vol.path("host").isMissingNode(), "EFS volume must not carry a host shape"); JsonNode efs = vol.path("efsVolumeConfiguration"); assertEquals("fs-0123456789abcdef0", efs.path("fileSystemId").asText()); - assertEquals("/dps", efs.path("rootDirectory").asText()); + assertEquals("/", efs.path("rootDirectory").asText()); assertEquals("ENABLED", efs.path("transitEncryption").asText()); assertEquals(2999, efs.path("transitEncryptionPort").asInt()); assertEquals("fsap-0abc", efs.path("authorizationConfig").path("accessPointId").asText()); assertEquals("ENABLED", efs.path("authorizationConfig").path("iam").asText()); } + + @Test + void registerTaskDefinitionRejectsAccessPointWithNonDefaultRootDirectory() throws Exception { + String requestJson = """ + { + "family": "efs-invalid-family", + "containerDefinitions": [ + { + "name": "app", + "image": "alpine:latest", + "mountPoints": [ + {"sourceVolume": "customer-data", "containerPath": "/mnt/efs", "readOnly": false} + ] + } + ], + "volumes": [ + { + "name": "customer-data", + "efsVolumeConfiguration": { + "fileSystemId": "fs-0123456789abcdef0", + "rootDirectory": "/dps", + "authorizationConfig": {"accessPointId": "fsap-0abc"} + } + } + ] + } + """; + JsonNode request = objectMapper.readTree(requestJson); + + AwsException ex = assertThrows(AwsException.class, + () -> handler.handle("RegisterTaskDefinition", request, "us-east-1")); + assertEquals("InvalidParameterException", ex.getErrorCode()); + } + + @Test + void registerTaskDefinitionAllowsAccessPointWithOmittedRootDirectory() throws Exception { + String requestJson = """ + { + "family": "efs-valid-access-point-family", + "containerDefinitions": [ + { + "name": "app", + "image": "alpine:latest", + "mountPoints": [ + {"sourceVolume": "customer-data", "containerPath": "/mnt/efs", "readOnly": false} + ] + } + ], + "volumes": [ + { + "name": "customer-data", + "efsVolumeConfiguration": { + "fileSystemId": "fs-0123456789abcdef0", + "authorizationConfig": {"accessPointId": "fsap-0abc"} + } + } + ] + } + """; + JsonNode request = objectMapper.readTree(requestJson); + + Response response = handler.handle("RegisterTaskDefinition", request, "us-east-1"); + JsonNode efs = objectMapper.valueToTree(response.getEntity()) + .path("taskDefinition").path("volumes").get(0).path("efsVolumeConfiguration"); + assertEquals("fsap-0abc", efs.path("authorizationConfig").path("accessPointId").asText()); + assertTrue(efs.path("rootDirectory").isMissingNode(), "rootDirectory should not be set"); + } + + @Test + void registerTaskDefinitionAllowsNonDefaultRootDirectoryWithoutAccessPoint() throws Exception { + String requestJson = """ + { + "family": "efs-valid-root-directory-family", + "containerDefinitions": [ + { + "name": "app", + "image": "alpine:latest", + "mountPoints": [ + {"sourceVolume": "customer-data", "containerPath": "/mnt/efs", "readOnly": false} + ] + } + ], + "volumes": [ + { + "name": "customer-data", + "efsVolumeConfiguration": { + "fileSystemId": "fs-0123456789abcdef0", + "rootDirectory": "/dps" + } + } + ] + } + """; + JsonNode request = objectMapper.readTree(requestJson); + + Response response = handler.handle("RegisterTaskDefinition", request, "us-east-1"); + JsonNode efs = objectMapper.valueToTree(response.getEntity()) + .path("taskDefinition").path("volumes").get(0).path("efsVolumeConfiguration"); + assertEquals("/dps", efs.path("rootDirectory").asText()); + assertTrue(efs.path("authorizationConfig").path("accessPointId").isMissingNode(), + "accessPointId should not be set"); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerEfsIsolationDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerEfsIsolationDockerIntegrationTest.java new file mode 100644 index 0000000000..50f6711a88 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerEfsIsolationDockerIntegrationTest.java @@ -0,0 +1,169 @@ +package io.github.hectorvent.floci.services.ecs.container; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.core.command.WaitContainerResultCallback; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; +import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition; +import io.github.hectorvent.floci.services.ecs.model.EcsTask; +import io.github.hectorvent.floci.services.ecs.model.EfsVolumeConfiguration; +import io.github.hectorvent.floci.services.ecs.model.MountPoint; +import io.github.hectorvent.floci.services.ecs.model.TaskDefinition; +import io.github.hectorvent.floci.services.ecs.model.Volume; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Docker-backed proof that an EFS-configured task volume's local mount is scoped to + * {@code (fileSystemId, rootDirectory, accessPointId)}, not just {@code fileSystemId} (#2563). + * Each scenario runs a real busybox container against the same {@code fileSystemId}, writing + * and checking marker files under {@code /mnt/efs} with a shell one-liner whose exit code + * proves whether the previous task's data was visible. + */ +@QuarkusTest +class EcsContainerManagerEfsIsolationDockerIntegrationTest { + + private static final String IMAGE = "public.ecr.aws/docker/library/busybox:latest"; + + @Inject + EcsContainerManager containerManager; + + @Inject + ContainerLifecycleManager lifecycleManager; + + @Inject + DockerClient dockerClient; + + private final List volumesToCleanUp = new ArrayList<>(); + + @BeforeEach + void requireDocker() { + Assumptions.assumeTrue(isDockerAvailable(), + "Docker daemon must be available for ECS EFS isolation integration tests"); + } + + @AfterEach + void cleanUpVolumes() { + volumesToCleanUp.forEach(lifecycleManager::removeVolume); + volumesToCleanUp.clear(); + } + + /** + * Task A writes a marker under {@code rootDirectory} {@code /team-a}; task B, on the same + * file system but a different root, must not see it (if the bug were still present, one + * shared volume keyed only by {@code fileSystemId} would leak team-a's marker into team-b's + * task before it ever reaches its own write); a third task back on {@code /team-a} must + * likewise not see what team-b wrote. + */ + @Test + void differentRootDirectoriesOnSameFileSystemAreIsolated() { + String fileSystemId = "fs-" + UUID.randomUUID().toString().substring(0, 8); + + assertEquals(0, runEfsCommand(fileSystemId, "/team-a", null, + "echo team-a > /mnt/efs/only-a.txt"), + "task A should write its marker cleanly"); + + assertEquals(0, runEfsCommand(fileSystemId, "/team-b", null, + "test ! -e /mnt/efs/only-a.txt && echo team-b > /mnt/efs/only-b.txt"), + "task B must not see task A's rootDirectory-scoped data"); + + assertEquals(0, runEfsCommand(fileSystemId, "/team-a", null, + "test ! -e /mnt/efs/only-b.txt"), + "task on /team-a must not see /team-b's data"); + } + + /** + * A second task using the identical {@code rootDirectory} must see the first task's data: + * sharing an identical configuration is existing, desired behaviour. + */ + @Test + void sameRootDirectoryOnSameFileSystemStillShares() { + String fileSystemId = "fs-" + UUID.randomUUID().toString().substring(0, 8); + + assertEquals(0, runEfsCommand(fileSystemId, "/shared", null, + "echo hello > /mnt/efs/shared.txt"), + "first task should write its marker cleanly"); + + assertEquals(0, runEfsCommand(fileSystemId, "/shared", null, + "grep -qx hello /mnt/efs/shared.txt"), + "a second task with the same rootDirectory must share the first task's data"); + } + + /** + * A plain {@code rootDirectory} mount (no {@code accessPointId}) on the same file system + * must not see access-point-scoped data and vice versa, while a second task through the + * same access point must still share its data. + */ + @Test + void accessPointIdIsolatesFromRootDirectoryOnSameFileSystem() { + String fileSystemId = "fs-" + UUID.randomUUID().toString().substring(0, 8); + String accessPointId = "fsap-" + UUID.randomUUID().toString().substring(0, 8); + + assertEquals(0, runEfsCommand(fileSystemId, null, accessPointId, + "echo via-ap > /mnt/efs/via-ap.txt"), + "task mounted through the access point should write its marker cleanly"); + + assertEquals(0, runEfsCommand(fileSystemId, "/", null, + "test ! -e /mnt/efs/via-ap.txt"), + "a plain rootDirectory mount must not see access-point-scoped data"); + + assertEquals(0, runEfsCommand(fileSystemId, null, accessPointId, + "grep -qx via-ap /mnt/efs/via-ap.txt"), + "a second task through the same access point must share its data"); + } + + /** + * Runs a single-container ECS task that mounts {@code fileSystemId} (scoped by + * {@code rootDirectory}/{@code accessPointId}) at {@code /mnt/efs} and executes + * {@code shellCommand}, then blocks until the container exits and returns its exit code. + */ + private int runEfsCommand(String fileSystemId, String rootDirectory, String accessPointId, String shellCommand) { + String suffix = UUID.randomUUID().toString().substring(0, 8); + + ContainerDefinition app = new ContainerDefinition(); + app.setName("app"); + app.setImage(IMAGE); + app.setCommand(List.of("sh", "-c", shellCommand)); + app.setMountPoints(List.of(new MountPoint("efs-data", "/mnt/efs", false))); + + TaskDefinition taskDef = new TaskDefinition(); + taskDef.setFamily("efs-isolation-" + suffix); + taskDef.setContainerDefinitions(List.of(app)); + taskDef.setVolumes(List.of(new Volume("efs-data", null, + new EfsVolumeConfiguration(fileSystemId, rootDirectory, null, null, accessPointId, null)))); + + EcsTask task = new EcsTask(); + task.setTaskArn("arn:aws:ecs:us-east-1:000000000000:task/efs-isolation/" + suffix); + + volumesToCleanUp.add(EcsContainerManager.efsVolumeName(fileSystemId, accessPointId, rootDirectory)); + + EcsTaskHandle handle = containerManager.startTask(task, taskDef, List.of(), "us-east-1"); + String dockerId = handle.getContainerIds().get("app"); + try { + return dockerClient.waitContainerCmd(dockerId) + .exec(new WaitContainerResultCallback()) + .awaitStatusCode(60, TimeUnit.SECONDS); + } finally { + containerManager.stopTask(handle); + } + } + + private boolean isDockerAvailable() { + try { + dockerClient.pingCmd().exec(); + return true; + } catch (Exception e) { + return false; + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerEfsVolumeNamingTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerEfsVolumeNamingTest.java new file mode 100644 index 0000000000..451f7b8625 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsContainerManagerEfsVolumeNamingTest.java @@ -0,0 +1,87 @@ +package io.github.hectorvent.floci.services.ecs.container; + +import org.junit.jupiter.api.Test; + +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Unit tests for {@link EcsContainerManager#efsVolumeName}, the naming logic that scopes an + * EFS-backed task volume's shared Docker named volume to both {@code fileSystemId} and its + * effective root (#2563). The name must be stable for a given (fileSystemId, rootDirectory, + * accessPointId) combination (so identical mounts keep sharing one volume), distinct across + * different roots on the same file system (so mounts do not collide on the same tree), and + * always a legal Docker volume name. + */ +class EcsContainerManagerEfsVolumeNamingTest { + + private static final Pattern DOCKER_VOLUME_NAME = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9_.-]*$"); + + @Test + void defaultsToPlainFileSystemNameWhenNoRootOrAccessPointIsSet() { + assertEquals("floci-efs-fs-abc", EcsContainerManager.efsVolumeName("fs-abc", null, null)); + assertEquals("floci-efs-fs-abc", EcsContainerManager.efsVolumeName("fs-abc", null, "")); + assertEquals("floci-efs-fs-abc", EcsContainerManager.efsVolumeName("fs-abc", null, "/")); + } + + @Test + void differentRootDirectoriesOnSameFileSystemYieldDifferentVolumes() { + String rootA = EcsContainerManager.efsVolumeName("fs-shared", null, "/team-a"); + String rootB = EcsContainerManager.efsVolumeName("fs-shared", null, "/team-b"); + String rootNone = EcsContainerManager.efsVolumeName("fs-shared", null, null); + + assertNotEquals(rootA, rootB, "different rootDirectory values must isolate the volume"); + assertNotEquals(rootA, rootNone, "a non-root rootDirectory must not collapse to the plain name"); + assertTrue(DOCKER_VOLUME_NAME.matcher(rootA).matches(), "must be docker-safe, was: " + rootA); + assertTrue(DOCKER_VOLUME_NAME.matcher(rootB).matches(), "must be docker-safe, was: " + rootB); + } + + @Test + void sameRootDirectoryOnSameFileSystemStillShares() { + String first = EcsContainerManager.efsVolumeName("fs-shared", null, "/team-a"); + String second = EcsContainerManager.efsVolumeName("fs-shared", null, "/team-a"); + + assertEquals(first, second, "identical (fileSystemId, rootDirectory) must keep sharing one volume"); + } + + @Test + void accessPointIdTakesPrecedenceOverRootDirectory() { + String viaAccessPoint = EcsContainerManager.efsVolumeName("fs-shared", "fsap-111", "/ignored"); + String viaRootOnly = EcsContainerManager.efsVolumeName("fs-shared", null, "/ignored"); + + assertNotEquals(viaAccessPoint, viaRootOnly, + "an access point's own root must take precedence over rootDirectory, not merge with it"); + } + + @Test + void differentAccessPointsOnSameFileSystemYieldDifferentVolumes() { + String apOne = EcsContainerManager.efsVolumeName("fs-shared", "fsap-111", null); + String apTwo = EcsContainerManager.efsVolumeName("fs-shared", "fsap-222", null); + + assertNotEquals(apOne, apTwo, "different accessPointId values must isolate the volume"); + } + + @Test + void sameAccessPointStillShares() { + String first = EcsContainerManager.efsVolumeName("fs-shared", "fsap-111", null); + String second = EcsContainerManager.efsVolumeName("fs-shared", "fsap-111", "/whatever-is-ignored"); + + assertEquals(first, second, + "the same accessPointId must keep sharing one volume regardless of rootDirectory"); + } + + @Test + void equivalentRootDirectorySpellingsShareTheSameVolume() { + String canonical = EcsContainerManager.efsVolumeName("fs-shared", null, "/team-a"); + + assertEquals(canonical, EcsContainerManager.efsVolumeName("fs-shared", null, "/team-a/"), + "a trailing slash must not create a distinct volume for the same directory"); + assertEquals(canonical, EcsContainerManager.efsVolumeName("fs-shared", null, "//team-a"), + "a repeated leading slash must not create a distinct volume for the same directory"); + assertEquals(canonical, EcsContainerManager.efsVolumeName("fs-shared", null, "team-a"), + "a missing leading slash must not create a distinct volume for the same directory"); + } +} 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 36c7b7a1dd..0f5fe10e5d 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 @@ -123,6 +123,11 @@ class EcsContainerManagerVolumesTest { verify(builder, never()).withBind("/app/nope", "/app/nope"); } + /** + * Each EFS volume resolves to a shared local Docker named volume keyed by file system id + * AND effective root (here: rootDirectory, since neither volume sets an accessPointId), + * read-write or read-only per the mountPoint. + */ @Test void efsVolumeMountPointsResolveToSharedNamedVolumesByAccessMode() { ContainerDefinition app = new ContainerDefinition(); @@ -146,10 +151,10 @@ class EcsContainerManagerVolumesTest { manager.startTask(task, taskDef, List.of(), "us-east-1"); - // Each EFS volume -> a shared local Docker named volume keyed by file system id, - // read-write or read-only per the mountPoint. - verify(builder, times(1)).withNamedVolume("floci-efs-fs-0123456789abcdef0", "/mnt/efs", false); - verify(builder, times(1)).withNamedVolume("floci-efs-fs-00000000000000001", "/mnt/shared", true); + verify(builder, times(1)).withNamedVolume( + EcsContainerManager.efsVolumeName("fs-0123456789abcdef0", null, "/dps"), "/mnt/efs", false); + verify(builder, times(1)).withNamedVolume( + EcsContainerManager.efsVolumeName("fs-00000000000000001", null, null), "/mnt/shared", true); // EFS volumes are never bind-mounted as host paths. verify(builder, never()).withBind(any(), any()); @@ -188,7 +193,8 @@ class EcsContainerManagerVolumesTest { configured.startTask(task, taskDef, List.of(), "us-east-1"); - verify(lifecycleManager, times(1)).ensureSharedVolume("floci-efs-fs-abc", + verify(lifecycleManager, times(1)).ensureSharedVolume( + EcsContainerManager.efsVolumeName("fs-abc", null, "/dps"), OptionalInt.of(1001), OptionalInt.of(1001), Optional.of("2775"), "busybox:stable"); }