Light, fluffy, and always free - The AWS Local Emulator alternative
feat(ecs): hold 169.254.170.2 on the task's network with a small proxy container (#4293)
Priamo Germosen0a4320132dde
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 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.javaindex 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.javanew file mode 100644index 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.+ *+ * <p>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<String, String> proxyIdByNetwork = new ConcurrentHashMap<>();++ @Inject+ public EcsCredentialsProxy(DockerClient dockerClient, ContainerBuilder containerBuilder,+ ContainerLifecycleManager lifecycleManager, DockerHostResolver dockerHostResolver,+ EmulatorConfig config) {+ this.dockerClient = dockerClient;+ this.containerBuilder = containerBuilder;+ this.lifecycleManager = lifecycleManager;+ this.dockerHostResolver = dockerHostResolver;+ this.config = config;+ }++ /**+ * No proxy container survives a Floci restart owning a meaningful state (its only job is to+ * forward to this process), and Docker does not reject a second container claiming the same+ * link-local address on one network: it silently lets both hold it, which would make+ * credential routing depend on which one wins ARP. Remove any surviving one this exact process+ * owned before minting new ones.+ *+ * <p>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<String, String> labels = candidate.getLabels();+ boolean isOurProxy = labels != null && "true".equals(labels.get(OWNS_NETWORK_LABEL));+ String candidateOwner = labels == null ? null : labels.get("floci_owner_port");+ if (isOurProxy && (candidateOwner == null || owner().equals(candidateOwner))) {+ lifecycleManager.removeIfExists(candidate.getId());+ }+ }+ } catch (Exception e) {+ LOG.warnv("Could not check for a stale container named {0}: {1}", name, e.getMessage());+ }+ }++ private boolean isRunning(String containerId) {+ try {+ return Boolean.TRUE.equals(dockerClient.inspectContainerCmd(containerId).exec()+ .getState().getRunning());+ } catch (Exception e) {+ return false;+ }+ }++ /**+ * Confirms the credentials endpoint actually answers through this proxy, end to end, rather+ * than just checking that {@link #CREDENTIALS_ADDRESS} is configured on its interface. The two+ * are not the same thing: a runtime that accepts the connect call but drops {@code+ * LinkLocalIPs} would leave the address missing entirely, but even a proxy that gets the+ * address has a brief window, confirmed while writing this, where the interface is up before+ * socat has finished binding its listener. Only an actual HTTP round trip through the address,+ * socat, and the resolved Floci host to the real server proves a task can reach it.+ */+ private void requireEndpointReachable(String containerId) {+ for (int attempt = 0; attempt < VERIFY_ATTEMPTS; attempt++) {+ String status = execCapture(containerId, "curl", "-s", "-o", "/dev/null",+ "-w", "%{http_code}", "--max-time", "1", "http://" + CREDENTIALS_ADDRESS + "/");+ // Any HTTP status, including a 404 for a path nothing serves, means the request made+ // it all the way through; curl reports "000" when it could not connect at all.+ if (status != null && !status.isBlank() && !status.contains("000")) {+ return;+ }+ try {+ Thread.sleep(VERIFY_INTERVAL_MILLIS);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ break;+ }+ }+ throw new IllegalStateException(+ "The credentials proxy never answered on " + CREDENTIALS_ADDRESS + "; the Docker runtime may be "+ + "ignoring LinkLocalIPs on this network, or the forward to Floci itself is not reachable");+ }++ private String execCapture(String containerId, String... cmd) {+ try {+ String execId = dockerClient.execCreateCmd(containerId)+ .withAttachStdout(true).withAttachStderr(true).withCmd(cmd).exec().getId();+ StringBuilder output = new StringBuilder();+ try (ResultCallback.Adapter<Frame> callback = new ResultCallback.Adapter<>() {+ @Override+ public void onNext(Frame frame) {+ output.append(new String(frame.getPayload(), StandardCharsets.UTF_8));+ }+ }) {+ dockerClient.execStartCmd(execId).exec(callback).awaitCompletion();+ }+ return output.toString();+ } catch (Exception e) {+ return null;+ }+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex ee4f541e27..1e0cfdce15 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -578,6 +578,7 @@ floci:enabled: falsettl-seconds: 21600port: 51679+ proxy-image: floci/network-helper:localappconfig:enabled: trueappconfigdata:diff --git a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.javaindex 51add00aae..bdb65112ff 100644--- a/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java+++ b/src/test/java/io/github/hectorvent/floci/lifecycle/EmulatorLifecycleTest.java@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.lifecycle.inithook.InitializationHooksRunner;import io.github.hectorvent.floci.services.appsync.graphql.SchemaCreationWorker;import io.github.hectorvent.floci.services.docdb.container.DocDbContainerManager;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.elasticache.ElastiCacheMemcachedService;import io.github.hectorvent.floci.services.elasticache.ElastiCacheService;@@ -70,6 +71,8 @@ class EmulatorLifecycleTest {@Mock private EmulatorConfig.StorageConfig storageConfig;@Mock private EmulatorConfig.ServicesConfig servicesConfig;@Mock private EmulatorConfig.Ec2ServiceConfig ec2ServiceConfig;+ @Mock private EmulatorConfig.EcsServiceConfig ecsServiceConfig;+ @Mock private EmulatorConfig.EcsTaskRoleCredentialsConfig ecsTaskRoleCredentialsConfig;@Mock private EmulatorConfig.EksServiceConfig eksServiceConfig;@Mock private EmulatorConfig.ElbV2ServiceConfig elbv2ServiceConfig;@Mock private EmulatorConfig.ElbServiceConfig elbServiceConfig;@@ -100,6 +103,7 @@ class EmulatorLifecycleTest {@Mock private DynamoDbStreamsEventSourcePoller dynamodbStreamsPoller;@Mock private PipesService pipesService;@Mock private Ec2MetadataServer ec2MetadataServer;+ @Mock private EcsTaskRoleCredentialsServer ecsTaskRoleCredentialsServer;@Mock private EcrRegistryManager ecrRegistryManager;@Mock private FlociUiManager flociUiManager;@Mock private InitLifecycleState initLifecycleState;@@ -116,6 +120,9 @@ class EmulatorLifecycleTest {void setUp() {Mockito.lenient().when(config.services()).thenReturn(servicesConfig);Mockito.lenient().when(servicesConfig.ec2()).thenReturn(ec2ServiceConfig);+ Mockito.lenient().when(servicesConfig.ecs()).thenReturn(ecsServiceConfig);+ Mockito.lenient().when(ecsServiceConfig.taskRoleCredentials()).thenReturn(ecsTaskRoleCredentialsConfig);+ Mockito.lenient().when(ecsTaskRoleCredentialsConfig.enabled()).thenReturn(false);Mockito.lenient().when(ec2ServiceConfig.enabled()).thenReturn(false);Mockito.lenient().when(servicesConfig.elbv2()).thenReturn(elbv2ServiceConfig);Mockito.lenient().when(elbv2ServiceConfig.enabled()).thenReturn(false);@@ -143,7 +150,7 @@ class EmulatorLifecycleTest {rabbitMqManager, flinkContainerManager, rdsService, timestreamInfluxDbService,elbV2Service, elbClassicService,initializationHooksRunner, sqsPoller, kinesisPoller, dynamodbStreamsPoller,- pipesService, ec2MetadataServer, ecrRegistryManager, flociUiManager, initLifecycleState,+ pipesService, ec2MetadataServer, ecsTaskRoleCredentialsServer, ecrRegistryManager, flociUiManager, initLifecycleState,schemaCreationWorker, stepFunctionsService, containerTeardowns, persistentPathValidator);Mockito.lenient().when(containerTeardowns.iterator()).thenReturn(java.util.Collections.emptyIterator());@@ -690,4 +697,43 @@ class EmulatorLifecycleTest {emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));verify(ec2MetadataServer, never()).start();}++ @Test+ void shouldStartAndStopEcsTaskRoleCredentialsServerWhenEnabled() {+ stubStorageConfig();+ when(ecsTaskRoleCredentialsConfig.enabled()).thenReturn(true);+ when(ecsTaskRoleCredentialsServer.start()).thenReturn(CompletableFuture.completedFuture(null));+ when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);+ when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);++ emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));+ verify(ecsTaskRoleCredentialsServer).start();++ emulatorLifecycle.onStop(Mockito.mock(ShutdownEvent.class));+ verify(ecsTaskRoleCredentialsServer).stop();+ }++ @Test+ void shouldNotStartEcsTaskRoleCredentialsServerWhenDisabled() {+ stubStorageConfig();+ when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);+ when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);++ emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));+ verify(ecsTaskRoleCredentialsServer, never()).start();++ emulatorLifecycle.onStop(Mockito.mock(ShutdownEvent.class));+ verify(ecsTaskRoleCredentialsServer, never()).stop();+ }++ @Test+ void shouldSweepOrphanedEcsTaskRoleSessionsOnStartup() {+ stubStorageConfig();+ when(initializationHooksRunner.hasHooks(InitializationHook.START)).thenReturn(false);+ when(initializationHooksRunner.hasHooks(InitializationHook.READY)).thenReturn(false);++ emulatorLifecycle.onStart(Mockito.mock(StartupEvent.class));++ verify(iamService).sweepOrphanedEcsTaskRoleSessions();+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyDockerIntegrationTest.javanew file mode 100644index 0000000000..d30a272bed--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ecs/container/EcsCredentialsProxyDockerIntegrationTest.java@@ -0,0 +1,266 @@+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.command.CreateNetworkResponse;+import com.github.dockerjava.api.model.Frame;+import com.github.dockerjava.core.command.WaitContainerResultCallback;+import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;+import io.github.hectorvent.floci.core.common.docker.ContainerDetector;+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.services.iam.IamService;+import io.quarkus.test.junit.QuarkusTest;+import io.vertx.core.Vertx;+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.net.ServerSocket;+import java.nio.charset.StandardCharsets;+import java.time.Instant;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.UUID;+import java.util.concurrent.TimeUnit;++import static io.restassured.RestAssured.given;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.when;++/**+ * Proves the proxy's half of the mechanism this feature depends on. A task container needs its+ * own address in 169.254.0.0/16 to reach the proxy's 169.254.170.2 at all: without one, its+ * routing table has no connected route for that range, so the kernel sends the packet toward the+ * default gateway instead of ARPing the peer directly, and it never reaches the target's socket+ * (confirmed by hand: a plain container got "Connection refused" against a proxy that was+ * genuinely listening and working, the same symptom a completely absent listener produces, which+ * is what made this easy to get wrong). Real task-container addressing is EcsContainerManager's+ * job (a separate piece); this test gives its stand-in task container one directly, the same way+ * that wiring will.+ *+ * <p>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<Frame>() {+ @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.javanew file mode 100644index 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<String, String> labels) {+ ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);+ Container stale = mock(Container.class);+ when(stale.getId()).thenReturn(staleId);+ when(stale.getNames()).thenAnswer(invocation -> new String[] {"/" + ContainerStorageHelper.resourceName(+ config, "ecs-credentials-proxy", null, "floci-net-" + proxy.ownerNameSegment())});+ when(stale.getLabels()).thenReturn(labels);+ when(dockerClient.listContainersCmd()).thenReturn(listCmd);+ when(listCmd.exec()).thenReturn(List.of(stale));+ }++ @Test+ void removesAStaleContainerFromBeforeTheOwnerLabelConventionExisted() {+ stubSuccessfulLaunch("proxy-1");+ stubStaleContainerByName("stale-unlabeled", Map.of("floci.ecs-task-role-credentials-proxy", "true"));++ proxy.ensureProxyOn("floci-net");++ verify(lifecycleManager).removeIfExists("stale-unlabeled");+ }++ @Test+ void removesAStaleContainerThisSameInstanceOwns() {+ stubSuccessfulLaunch("proxy-1");+ when(config.docker().resourceNamespace()).thenReturn(Optional.empty());+ when(config.port()).thenReturn(4566);+ stubStaleContainerByName("stale-own", Map.of(+ "floci.ecs-task-role-credentials-proxy", "true", "floci_owner_port", "4566"));++ proxy.ensureProxyOn("floci-net");++ verify(lifecycleManager).removeIfExists("stale-own");+ }++ @Test+ void leavesASameNamedProxyOwnedByAnotherFlociInstanceAlone() {+ stubSuccessfulLaunch("proxy-1");+ when(config.docker().resourceNamespace()).thenReturn(Optional.empty());+ when(config.port()).thenReturn(4566);+ stubStaleContainerByName("other-instance-proxy", Map.of(+ "floci.ecs-task-role-credentials-proxy", "true", "floci_owner_port", "4567"));++ proxy.ensureProxyOn("floci-net");++ verify(lifecycleManager, never()).removeIfExists("other-instance-proxy");+ }++ @Test+ void leavesAnUnrelatedSameNamedContainerAlone() {+ stubSuccessfulLaunch("proxy-1");+ // Same name, but not one of our proxies at all: no OWNS_NETWORK_LABEL.+ stubStaleContainerByName("unrelated-container", Map.of());++ proxy.ensureProxyOn("floci-net");++ verify(lifecycleManager, never()).removeIfExists("unrelated-container");+ }++ /**+ * Stubs the whole happy path for a single {@code ensureProxyOn} call to succeed against a+ * container with the given id: the image check, the launch, the running check for a repeat+ * call, and the endpoint-reachability exec/callback plumbing.+ */+ private void stubSuccessfulLaunch(String containerId) {+ ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);+ when(builder.build()).thenReturn(new ContainerSpec("floci/network-helper:local"));+ when(containerBuilder.newContainer(any())).thenReturn(builder);+ when(config.services().ecs().taskRoleCredentials().proxyImage()).thenReturn("floci/network-helper:local");+ when(containerBuilder.resolveImage("floci/network-helper:local")).thenReturn("floci/network-helper:local");+ stubNoStaleContainerByName();+ com.github.dockerjava.api.command.InspectImageCmd inspectImageCmd =+ mock(com.github.dockerjava.api.command.InspectImageCmd.class);+ when(dockerClient.inspectImageCmd(any())).thenReturn(inspectImageCmd);+ when(inspectImageCmd.exec()).thenReturn(mock(com.github.dockerjava.api.command.InspectImageResponse.class));+ when(lifecycleManager.createAndStart(any())).thenReturn(+ new ContainerLifecycleManager.ContainerInfo(containerId, Map.of()));+ InspectContainerCmd inspectCmd = mock(InspectContainerCmd.class);+ InspectContainerResponse inspectResponse = mock(InspectContainerResponse.class);+ ContainerState running = mock(ContainerState.class);+ when(dockerClient.inspectContainerCmd(containerId)).thenReturn(inspectCmd);+ when(inspectCmd.exec()).thenReturn(inspectResponse);+ when(inspectResponse.getState()).thenReturn(running);+ when(running.getRunning()).thenReturn(true);++ com.github.dockerjava.api.command.ExecCreateCmd execCreate =+ mock(com.github.dockerjava.api.command.ExecCreateCmd.class, RETURNS_SELF);+ com.github.dockerjava.api.command.ExecCreateCmdResponse execResponse =+ mock(com.github.dockerjava.api.command.ExecCreateCmdResponse.class);+ when(dockerClient.execCreateCmd(containerId)).thenReturn(execCreate);+ when(execCreate.exec()).thenReturn(execResponse);+ when(execResponse.getId()).thenReturn("exec-" + containerId);+ com.github.dockerjava.api.command.ExecStartCmd execStart =+ mock(com.github.dockerjava.api.command.ExecStartCmd.class);+ when(dockerClient.execStartCmd("exec-" + containerId)).thenReturn(execStart);+ when(execStart.exec(any())).thenAnswer(invocation -> {+ com.github.dockerjava.api.async.ResultCallback<com.github.dockerjava.api.model.Frame> callback =+ invocation.getArgument(0);+ callback.onNext(new com.github.dockerjava.api.model.Frame(+ com.github.dockerjava.api.model.StreamType.STDOUT,+ "404".getBytes()));+ callback.onComplete();+ return callback;+ });+ }++ @Test+ void reapSurvivingProxiesRemovesOnlyThisInstancesOwnLeftovers() {+ when(config.docker().resourceNamespace()).thenReturn(Optional.empty());+ when(config.port()).thenReturn(4566);+ ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);+ Container ownLeftover = mock(Container.class);+ when(ownLeftover.getId()).thenReturn("stale-proxy");+ when(ownLeftover.getLabels()).thenReturn(Map.of("floci_owner_port", "4566"));+ // Another Floci process sharing this daemon: same label, different owner. Reaping this+ // one would tear down a proxy a sibling instance is still actively using.+ Container otherInstance = mock(Container.class);+ when(otherInstance.getId()).thenReturn("other-instance-proxy");+ when(otherInstance.getLabels()).thenReturn(Map.of("floci_owner_port", "4567"));+ when(dockerClient.listContainersCmd()).thenReturn(listCmd);+ when(listCmd.exec()).thenReturn(List.of(ownLeftover, otherInstance));++ proxy.reapSurvivingProxies();++ verify(lifecycleManager).removeIfExists("stale-proxy");+ verify(lifecycleManager, never()).removeIfExists("other-instance-proxy");+ }++ @Test+ void reapSurvivingProxiesToleratesADockerFailure() {+ when(dockerClient.listContainersCmd()).thenThrow(new RuntimeException("daemon unreachable"));++ proxy.reapSurvivingProxies();++ verify(lifecycleManager, never()).removeIfExists(any());+ }+}