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 3d3cfe5a58..569e554d0d 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -2091,6 +2091,14 @@ public interface EmulatorConfig { */ @WithDefault("51679") int port(); + + /** + * Image for the per-network credentials proxy, reusing the same minimal helper image as + * security-group enforcement: it already carries {@code socat}, and one more single-purpose + * use of an image Floci already builds and pulls is simpler than shipping a second one. + */ + @WithDefault("floci/network-helper:local") + String proxyImage(); } interface ResourceGroupsTaggingServiceConfig { diff --git a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java index 18f5c57161..91d1b46fe4 100644 --- a/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java +++ b/src/main/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycle.java @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.lifecycle.inithook.InitializationHook; import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner; import io.github.hectorvent.floci.services.ec2.Ec2MetadataServer; +import io.github.hectorvent.floci.services.ecs.container.EcsTaskRoleCredentialsServer; import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager; import io.github.hectorvent.floci.services.floci.ui.FlociUiManager; import io.github.hectorvent.floci.services.amazonmq.container.RabbitMqManager; @@ -97,6 +98,7 @@ public class EmulatorLifecycle { private final DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller; private final PipesService pipesService; private final Ec2MetadataServer ec2MetadataServer; + private final EcsTaskRoleCredentialsServer ecsTaskRoleCredentialsServer; private final EcrRegistryManager ecrRegistryManager; private final FlociUiManager flociUiManager; private final InitLifecycleState initLifecycleState; @@ -133,6 +135,7 @@ public class EmulatorLifecycle { DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller, PipesService pipesService, Ec2MetadataServer ec2MetadataServer, + EcsTaskRoleCredentialsServer ecsTaskRoleCredentialsServer, EcrRegistryManager ecrRegistryManager, FlociUiManager flociUiManager, InitLifecycleState initLifecycleState, @@ -168,6 +171,7 @@ public class EmulatorLifecycle { this.dynamodbStreamsPoller = dynamodbStreamsPoller; this.pipesService = pipesService; this.ec2MetadataServer = ec2MetadataServer; + this.ecsTaskRoleCredentialsServer = ecsTaskRoleCredentialsServer; this.ecrRegistryManager = ecrRegistryManager; this.flociUiManager = flociUiManager; this.initLifecycleState = initLifecycleState; @@ -212,6 +216,10 @@ public class EmulatorLifecycle { if (sweptEc2Sessions > 0) { LOG.infov("Removed {0} orphaned EC2 instance session(s)", sweptEc2Sessions); } + int sweptEcsTaskRoleSessions = iamService.sweepOrphanedEcsTaskRoleSessions(); + if (sweptEcsTaskRoleSessions > 0) { + LOG.infov("Removed {0} orphaned ECS task-role session(s)", sweptEcsTaskRoleSessions); + } schemaCreationWorker.recoverOrphans(); schemaCreationWorker.rehydrateSchemas(); stepFunctionsService.abortAbandonedExecutions(); @@ -247,6 +255,12 @@ public class EmulatorLifecycle { return null; }); } + if (config.services().ecs().taskRoleCredentials().enabled()) { + ecsTaskRoleCredentialsServer.start().exceptionally(ex -> { + LOG.warnv("ECS task-role credentials server failed to start: {0}", ex.getMessage()); + return null; + }); + } boolean hasStart = initializationHooksRunner.hasHooks(InitializationHook.START); boolean hasReady = initializationHooksRunner.hasHooks(InitializationHook.READY); @@ -335,6 +349,11 @@ public class EmulatorLifecycle { ec2MetadataServer.stop(); } }); + runCleanup("ECS task-role credentials server", () -> { + if (config.services().ecs().taskRoleCredentials().enabled()) { + ecsTaskRoleCredentialsServer.stop(); + } + }); runCleanup("ElastiCache proxy", elastiCacheProxyManager::stopAll); runCleanup("RDS proxy", rdsProxyManager::stopAll); runCleanup("MemoryDB proxy", memoryDbProxyManager::stopAll); diff --git a/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxy.java b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxy.java new file mode 100644 index 0000000000..f254b72b13 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxy.java @@ -0,0 +1,269 @@ +package io.github.hectorvent.floci.services.ecs.container; + +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.async.ResultCallback; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.Frame; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.ContainerTeardown; +import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; +import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; +import io.github.hectorvent.floci.core.common.docker.ContainerSpec; +import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper; +import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; +import io.github.hectorvent.floci.core.common.docker.LocallyBuiltHelperImage; +import jakarta.annotation.PostConstruct; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Owns the small proxy container, one per Docker network, that holds the ECS container-credentials + * address (169.254.170.2) and forwards to {@link EcsTaskRoleCredentialsServer}. A task container + * needs its own address in 169.254.0.0/16 to reach this proxy at all (see the follow-up wiring + * that gives it one): without a connected route for that range, the kernel routes toward the + * default gateway instead of resolving the peer directly, and the connection is refused before it + * reaches this proxy's socket. + * + *
Docker accepts a link-local address request even on a runtime that then does not honour it
+ * (see the review discussion on #4063), so a bind is never trusted from the API call alone: after
+ * start, the address is confirmed inside the container's own network namespace, and the container
+ * is torn down and the network refused rather than silently issuing credentials task containers
+ * cannot reach.
+ */
+@ApplicationScoped
+public class EcsCredentialsProxy implements ContainerTeardown {
+
+ private static final Logger LOG = Logger.getLogger(EcsCredentialsProxy.class);
+ private static final String CREDENTIALS_ADDRESS = "169.254.170.2";
+ private static final String OWNS_NETWORK_LABEL = "floci.ecs-task-role-credentials-proxy";
+ private static final int VERIFY_ATTEMPTS = 30;
+ private static final long VERIFY_INTERVAL_MILLIS = 200;
+
+ private final DockerClient dockerClient;
+ private final ContainerBuilder containerBuilder;
+ private final ContainerLifecycleManager lifecycleManager;
+ private final DockerHostResolver dockerHostResolver;
+ private final EmulatorConfig config;
+ private final Map Scoped to this instance's own {@code floci_owner_port}, the same convention {@code
+ * SecurityGroupFirewallManager} uses: several Floci processes can share one Docker daemon, and
+ * a label match alone would let one instance's restart tear down another's still-running,
+ * still-in-use proxy.
+ */
+ @PostConstruct
+ void reapSurvivingProxies() {
+ try {
+ dockerClient.listContainersCmd().withShowAll(true)
+ .withLabelFilter(Map.of(OWNS_NETWORK_LABEL, "true"))
+ .exec().stream()
+ .filter(container -> owner().equals(container.getLabels().get("floci_owner_port")))
+ .forEach(container -> lifecycleManager.removeIfExists(container.getId()));
+ } catch (Exception e) {
+ LOG.warnv("Could not reap surviving ECS credentials proxy containers: {0}", e.getMessage());
+ }
+ }
+
+ /** Identifies this Floci process among others that may share the same Docker daemon. */
+ String owner() {
+ String namespace = config.docker().resourceNamespace().orElse("");
+ return namespace.isBlank() ? String.valueOf(config.port()) : namespace + "/" + config.port();
+ }
+
+ /**
+ * {@link #owner()}, valid as a Docker name component. Two Floci instances that share a daemon,
+ * a resource namespace, and a network would otherwise derive the exact same container name:
+ * the ownership check in {@link #removeStaleContainerNamed} then correctly refuses to steal
+ * the other instance's proxy, but leaves the second instance unable to ever create its own
+ * under that name. Folding this into the name itself, not just the label, means the two never
+ * collide in the first place.
+ */
+ String ownerNameSegment() {
+ return owner().replaceAll("[^a-zA-Z0-9_.-]", "-");
+ }
+
+ /**
+ * Ensures the credentials proxy is running on the given network, starting and verifying one
+ * if this is the first task on it. Idempotent per network for the life of the process.
+ *
+ * @throws IllegalStateException if the address cannot be confirmed bound; the caller must not
+ * hand out credentials whose endpoint a task cannot actually reach.
+ */
+ public synchronized void ensureProxyOn(String network) {
+ if (network == null || network.isBlank()) {
+ throw new IllegalStateException(
+ "ECS task-role credentials need a user-defined Docker network, not '" + network + "'");
+ }
+ String existing = proxyIdByNetwork.get(network);
+ if (existing != null && isRunning(existing)) {
+ return;
+ }
+
+ LocallyBuiltHelperImage.ensureBuilt(dockerClient, containerBuilder,
+ config.services().ecs().taskRoleCredentials().proxyImage(), "floci/network-helper:local",
+ "/docker/network-helper.Dockerfile");
+ String name = ContainerStorageHelper.resourceName(
+ config, "ecs-credentials-proxy", null, network + "-" + ownerNameSegment());
+ // A stale proxy from an earlier launch attempt or a crashed process can still hold this
+ // exact name; Docker refuses to create a new container under a name a stopped one still
+ // owns, which would otherwise leave this network's proxy stuck until someone cleans it up
+ // by hand. removeStaleContainerNamed is a no-op when nothing by that name exists, and does
+ // not touch a same-named container another Floci instance owns.
+ removeStaleContainerNamed(name);
+ // Floci itself may be containerized, in which case host.docker.internal names the Docker
+ // host, not Floci's own container: resolve() returns Floci's actual reachable address
+ // either way, the same helper EC2's own IMDS proxy uses for this.
+ String flociHost = dockerHostResolver.resolve();
+ int port = config.services().ecs().taskRoleCredentials().port();
+ ContainerSpec spec = containerBuilder.newContainer(config.services().ecs().taskRoleCredentials().proxyImage())
+ .withName(name)
+ .withDockerNetwork(Optional.of(network))
+ .withLinkLocalIp(CREDENTIALS_ADDRESS)
+ .withHostDockerInternalOnLinux()
+ .withEntrypoint(List.of("socat"))
+ .withCmd(List.of(
+ "TCP-LISTEN:80,bind=" + CREDENTIALS_ADDRESS + ",fork,reuseaddr",
+ "TCP:" + flociHost + ":" + port))
+ .withLabels(Map.of(OWNS_NETWORK_LABEL, "true", "floci_owner_port", owner()))
+ .build();
+
+ String proxyId = null;
+ try {
+ proxyId = lifecycleManager.createAndStart(spec).containerId();
+ requireEndpointReachable(proxyId);
+ proxyIdByNetwork.put(network, proxyId);
+ LOG.infov("ECS task-role credentials proxy {0} holding {1} on network {2}",
+ proxyId, CREDENTIALS_ADDRESS, network);
+ } catch (RuntimeException e) {
+ if (proxyId != null) {
+ lifecycleManager.removeIfExists(proxyId);
+ }
+ throw new IllegalStateException(
+ "Cannot bind the ECS container-credentials address on network " + network
+ + "; refusing to issue task-role credentials tasks there could not reach", e);
+ }
+ }
+
+ /**
+ * Removes every proxy this process launched, on shutdown and on a state reset: nothing about
+ * a proxy container is worth keeping across either, and a reset in particular wipes the same
+ * task/network state a leftover proxy would otherwise have nothing left to serve.
+ */
+ @Override
+ public void stopManagedContainers() {
+ for (String proxyId : proxyIdByNetwork.values()) {
+ lifecycleManager.removeIfExists(proxyId);
+ }
+ proxyIdByNetwork.clear();
+ }
+
+ /**
+ * Removes a container by this exact name only when it is safe to: it must actually be one of
+ * this label's proxy containers, and it must be either unowned (predates the {@code
+ * floci_owner_port} convention) or owned by this same Floci instance. A same-named proxy
+ * belonging to a different instance sharing this daemon is left alone; removing it would
+ * interrupt that instance's tasks mid-flight, which a name collision here does not justify.
+ */
+ private void removeStaleContainerNamed(String name) {
+ try {
+ for (Container candidate : dockerClient.listContainersCmd().withShowAll(true)
+ .withNameFilter(List.of(name)).exec()) {
+ String[] names = candidate.getNames();
+ if (names == null || List.of(names).stream().noneMatch(("/" + name)::equals)) {
+ continue;
+ }
+ Map Skipped without a Docker daemon, like the other {@code *DockerIntegrationTest} classes.
+ */
+@QuarkusTest
+class EcsCredentialsProxyDockerIntegrationTest {
+
+ @Inject
+ DockerClient dockerClient;
+
+ @Inject
+ ContainerBuilder containerBuilder;
+
+ @Inject
+ ContainerLifecycleManager lifecycleManager;
+
+ @Inject
+ DockerHostResolver dockerHostResolver;
+
+ @Inject
+ ContainerDetector containerDetector;
+
+ @Inject
+ IamService iam;
+
+ private String networkId;
+ private String proxyContainerId;
+ private Vertx vertx;
+ private EcsTaskRoleCredentialsServer server;
+ private String taskContainerId;
+
+ @BeforeEach
+ void requireDockerOnTheHost() {
+ Assumptions.assumeTrue(isDockerAvailable(), "Docker daemon must be available");
+ Assumptions.assumeFalse(containerDetector.isRunningInContainer(),
+ "the plain container dials host.docker.internal, which only names a host-side Floci");
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ if (taskContainerId != null) {
+ dockerClient.removeContainerCmd(taskContainerId).withForce(true).exec();
+ }
+ if (server != null) {
+ server.stop();
+ }
+ if (vertx != null) {
+ vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
+ }
+ // EcsCredentialsProxy never removes its own container, by design: it is meant to persist
+ // for the process's life. The test that created it owns tearing it down.
+ if (proxyContainerId != null) {
+ dockerClient.removeContainerCmd(proxyContainerId).withForce(true).exec();
+ }
+ if (networkId != null) {
+ dockerClient.removeNetworkCmd(networkId).exec();
+ }
+ }
+
+ @Test
+ void taskContainerWithItsOwnLinkLocalAddressFetchesRealCredentialsThroughTheProxy() throws Exception {
+ String network = "floci-ecs-credentials-proxy-test-" + UUID.randomUUID();
+ CreateNetworkResponse created = dockerClient.createNetworkCmd().withName(network).exec();
+ networkId = created.getId();
+
+ String account = "987654321098";
+ String suffix = UUID.randomUUID().toString().substring(0, 8);
+ String role = "ecs-task-role-" + suffix;
+ String taskArn = "arn:aws:ecs:us-east-1:" + account + ":task/cluster/" + suffix;
+ String auth = "AWS4-HMAC-SHA256 Credential=" + account
+ + "/20260916/us-east-1/iam/aws4_request, SignedHeaders=host, Signature=abc";
+ given().header("Authorization", auth).contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateRole").formParam("RoleName", role)
+ .formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":"
+ + "[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ecs-tasks.amazonaws.com\"},"
+ + "\"Action\":\"sts:AssumeRole\"}]}")
+ .post("/").then().statusCode(200);
+ String roleArn = "arn:aws:iam::" + account + ":role/" + role;
+
+ int port;
+ try (ServerSocket socket = new ServerSocket(0)) {
+ port = socket.getLocalPort();
+ }
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.services().ecs().taskRoleCredentials().port()).thenReturn(port);
+ when(config.services().ecs().taskRoleCredentials().ttlSeconds()).thenReturn(21600L);
+ when(config.services().ecs().taskRoleCredentials().proxyImage()).thenReturn("floci/network-helper:local");
+
+ vertx = Vertx.vertx();
+ EcsTaskRoleCredentials credentials = new EcsTaskRoleCredentials(iam, config);
+ server = new EcsTaskRoleCredentialsServer(vertx, config, credentials);
+ server.start().get(10, TimeUnit.SECONDS);
+ String path = credentials.issue(taskArn, roleArn, account, Instant.now()).orElseThrow();
+
+ EcsCredentialsProxy proxy = new EcsCredentialsProxy(
+ dockerClient, containerBuilder, lifecycleManager, dockerHostResolver, config);
+ proxy.ensureProxyOn(network);
+ proxyContainerId = dockerClient.listContainersCmd()
+ .withLabelFilter(Map.of("floci.ecs-task-role-credentials-proxy", "true"))
+ .withNetworkFilter(List.of(networkId))
+ .exec().get(0).getId();
+
+ // A stand-in task container needs its own 169.254.0.0/16 address to reach the proxy at
+ // all: without one, its routing table has no connected route for that range and the
+ // kernel routes toward the default gateway instead of ARPing the peer directly, which
+ // never reaches the proxy's socket. The real allocation (unique per task, avoiding the
+ // proxy's own .2) is EcsContainerManager's job; this just proves the proxy's own side.
+ ContainerSpec taskSpec = containerBuilder.newContainer("public.ecr.aws/docker/library/python:3.12-alpine")
+ .withName("floci-ecs-credentials-proxy-test-task-" + suffix)
+ .withDockerNetwork(Optional.of(network))
+ .withLinkLocalIp("169.254.170.5")
+ .withEnv(List.of("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=" + path))
+ .withEntrypoint(List.of("python3", "-c", """
+ import json, os, urllib.request
+ uri = os.environ["AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"]
+ body = urllib.request.urlopen("http://169.254.170.2" + uri, timeout=10).read()
+ creds = json.loads(body)
+ assert creds["AccessKeyId"].startswith("ASIA"), creds
+ assert creds["RoleArn"], creds
+ print(json.dumps(creds))
+ """))
+ .build();
+ ContainerLifecycleManager.ContainerInfo taskInfo = lifecycleManager.createAndStart(taskSpec);
+ taskContainerId = taskInfo.containerId();
+
+ Integer status = dockerClient.waitContainerCmd(taskContainerId)
+ .exec(new WaitContainerResultCallback())
+ .awaitStatusCode(30, TimeUnit.SECONDS);
+ assertEquals(0, status, () -> logs(taskContainerId));
+
+ given().header("Authorization", auth).contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DeleteRole").formParam("RoleName", role)
+ .post("/").then().statusCode(200);
+ }
+
+ /**
+ * Reproduces the exact failure a stale, stopped proxy container used to cause: Docker refuses
+ * to create a new container under a name a stopped one still holds. A crashed process, or a
+ * launch that got this far and then failed later, would leave one of these behind under
+ * {@code EcsCredentialsProxy}'s deterministic per-network name.
+ */
+ @Test
+ void ensureProxyOnRecoversFromAStaleStoppedContainerHoldingItsName() throws Exception {
+ String network = "floci-ecs-credentials-proxy-test-" + UUID.randomUUID();
+ CreateNetworkResponse created = dockerClient.createNetworkCmd().withName(network).exec();
+ networkId = created.getId();
+
+ int port;
+ try (ServerSocket socket = new ServerSocket(0)) {
+ port = socket.getLocalPort();
+ }
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.services().ecs().taskRoleCredentials().proxyImage()).thenReturn("floci/network-helper:local");
+ when(config.services().ecs().taskRoleCredentials().port()).thenReturn(port);
+ EcsCredentialsProxy proxy = new EcsCredentialsProxy(
+ dockerClient, containerBuilder, lifecycleManager, dockerHostResolver, config);
+ String name = ContainerStorageHelper.resourceName(
+ config, "ecs-credentials-proxy", null, network + "-" + proxy.ownerNameSegment());
+
+ // A container that already occupies the name ensureProxyOn will ask for, stopped rather
+ // than removed, exactly what a crashed or killed proxy leaves behind.
+ // Carries the same label ensureProxyOn itself always sets: a real stale proxy is always
+ // one this code (this instance or an earlier run of it) created, never an arbitrary
+ // container that happens to collide on the name.
+ ContainerSpec staleSpec = containerBuilder.newContainer("floci/network-helper:local")
+ .withName(name)
+ .withDockerNetwork(Optional.of(network))
+ .withLabels(Map.of("floci.ecs-task-role-credentials-proxy", "true"))
+ .build();
+ String staleId = lifecycleManager.createAndStart(staleSpec).containerId();
+ dockerClient.stopContainerCmd(staleId).withTimeout(1).exec();
+
+ // ensureProxyOn's endpoint check needs something real to answer through; this recovery
+ // test is not about the credentials response itself, so any server on the reported port
+ // will do.
+ vertx = Vertx.vertx();
+ server = new EcsTaskRoleCredentialsServer(vertx, config, new EcsTaskRoleCredentials(iam, config));
+ server.start().get(10, TimeUnit.SECONDS);
+
+ try {
+ proxy.ensureProxyOn(network);
+ proxyContainerId = dockerClient.listContainersCmd()
+ .withLabelFilter(Map.of("floci.ecs-task-role-credentials-proxy", "true"))
+ .withNetworkFilter(List.of(networkId))
+ .exec().get(0).getId();
+ assertEquals("running", dockerClient.inspectContainerCmd(proxyContainerId)
+ .exec().getState().getStatus());
+ } finally {
+ // ensureProxyOn already replaced the stale container under its own name (a new
+ // container ID), so removing "staleId" itself is expected to find nothing.
+ lifecycleManager.removeIfExists(staleId);
+ }
+ }
+
+ private String logs(String containerId) {
+ StringBuilder out = new StringBuilder();
+ try {
+ dockerClient.logContainerCmd(containerId).withStdOut(true).withStdErr(true)
+ .exec(new ResultCallback.Adapter() {
+ @Override
+ public void onNext(Frame frame) {
+ out.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
+ }
+ }).awaitCompletion(10, TimeUnit.SECONDS);
+ } catch (Exception e) {
+ out.append("(could not read logs: ").append(e.getMessage()).append(')');
+ }
+ return out.toString();
+ }
+
+ 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/EcsCredentialsProxyTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyTest.java
new file mode 100644
index 0000000000..3bc7cc96f6
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyTest.java
@@ -0,0 +1,272 @@
+package io.github.hectorvent.floci.services.ecs.container;
+
+import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.command.InspectContainerCmd;
+import com.github.dockerjava.api.command.InspectContainerResponse;
+import com.github.dockerjava.api.command.InspectContainerResponse.ContainerState;
+import com.github.dockerjava.api.command.ListContainersCmd;
+import com.github.dockerjava.api.model.Container;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
+import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
+import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
+import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.RETURNS_SELF;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Covers the checks that never need a real Docker daemon. The parts that actually launch and
+ * verify a container are proved end to end in
+ * {@code EcsCredentialsProxyDockerIntegrationTest} instead: mocking the exec/callback plumbing
+ * that {@link EcsCredentialsProxy#ensureProxyOn} depends on would mostly test the mock, not the
+ * behaviour a runtime that silently drops {@code LinkLocalIPs} is meant to be caught by.
+ */
+class EcsCredentialsProxyTest {
+
+ private DockerClient dockerClient;
+ private ContainerBuilder containerBuilder;
+ private ContainerLifecycleManager lifecycleManager;
+ private DockerHostResolver dockerHostResolver;
+ private EmulatorConfig config;
+ private EcsCredentialsProxy proxy;
+
+ @BeforeEach
+ void setUp() {
+ dockerClient = mock(DockerClient.class);
+ containerBuilder = mock(ContainerBuilder.class);
+ lifecycleManager = mock(ContainerLifecycleManager.class);
+ dockerHostResolver = mock(DockerHostResolver.class);
+ when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
+ config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ proxy = new EcsCredentialsProxy(dockerClient, containerBuilder, lifecycleManager, dockerHostResolver, config);
+ }
+
+ @Test
+ void rejectsABlankNetworkWithoutTouchingDocker() {
+ assertThrows(IllegalStateException.class, () -> proxy.ensureProxyOn(null));
+ assertThrows(IllegalStateException.class, () -> proxy.ensureProxyOn(""));
+ assertThrows(IllegalStateException.class, () -> proxy.ensureProxyOn(" "));
+
+ verify(dockerClient, never()).createContainerCmd(any());
+ verify(containerBuilder, never()).newContainer(any());
+ }
+
+ @Test
+ void twoInstancesSharingANamespaceAndNetworkGetDistinctProxyNames() {
+ when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
+ when(config.port()).thenReturn(4566);
+ EcsCredentialsProxy first = proxy;
+
+ EmulatorConfig otherConfig = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(otherConfig.docker().resourceNamespace()).thenReturn(Optional.empty());
+ when(otherConfig.port()).thenReturn(4567);
+ EcsCredentialsProxy second = new EcsCredentialsProxy(
+ dockerClient, containerBuilder, lifecycleManager, dockerHostResolver, otherConfig);
+
+ // Same daemon, same resource namespace (none), same network: the only thing that could
+ // tell the two proxies apart is the owner folded into the name itself. If it were not,
+ // the second instance's create() would collide on the first's container name and never
+ // be able to establish its own proxy at all, no matter how the removal is scoped.
+ assertNotEquals(first.ownerNameSegment(), second.ownerNameSegment());
+ }
+
+ @Test
+ void skipsRelaunchingAProxyThatIsStillRunningOnTheSameNetwork() {
+ stubSuccessfulLaunch("proxy-1");
+
+ proxy.ensureProxyOn("floci-net");
+ proxy.ensureProxyOn("floci-net");
+
+ verify(lifecycleManager).createAndStart(any());
+ verify(dockerClient).inspectContainerCmd("proxy-1");
+ // The image check ran once, for the first launch; the second call short-circuits on
+ // isRunning() before it ever reaches the image/launch path again.
+ verify(dockerClient).inspectImageCmd(any());
+ }
+
+ @Test
+ void stopManagedContainersRemovesEveryProxyThisInstanceLaunched() {
+ stubSuccessfulLaunch("proxy-1");
+ proxy.ensureProxyOn("floci-net");
+
+ proxy.stopManagedContainers();
+
+ verify(lifecycleManager).removeIfExists("proxy-1");
+ }
+
+ @Test
+ void stopManagedContainersForgetsProxiesSoALaterEnsureRelaunchesInsteadOfShortCircuiting() {
+ stubSuccessfulLaunch("proxy-1");
+ proxy.ensureProxyOn("floci-net");
+ proxy.stopManagedContainers();
+
+ stubSuccessfulLaunch("proxy-2");
+ proxy.ensureProxyOn("floci-net");
+
+ // A full relaunch, not the isRunning() short-circuit skipsRelaunchingAProxy... covers:
+ // stopManagedContainers must have actually forgotten "floci-net", not just removed the
+ // container while still remembering it as the current one.
+ verify(lifecycleManager, times(2)).createAndStart(any());
+ verify(dockerClient, never()).inspectContainerCmd("proxy-2");
+ }
+
+ /** No container already holds the name {@code ensureProxyOn} is about to ask Docker for. */
+ private void stubNoStaleContainerByName() {
+ ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
+ when(dockerClient.listContainersCmd()).thenReturn(listCmd);
+ when(listCmd.exec()).thenReturn(List.of());
+ }
+
+ /** A container already holds that exact name, reported with the given labels. */
+ private void stubStaleContainerByName(String staleId, Map