mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(ecs): hold 169.254.170.2 on the task's network with a small proxy container (#4293)
Adds EcsCredentialsProxy, which launches one small socat container per Docker network, on first use, holding the address AWS SDKs hardcode for container credentials and forwarding to EcsTaskRoleCredentialsServer over host.docker.internal. Reuses the same floci/network-helper:local image and build-on-first-use logic as security-group enforcement (now factored into LocallyBuiltHelperImage, shared by both). Docker accepts a link-local address request even when the runtime then drops it (the review discussion on #4063), so the bind is never trusted from the API call alone: after start, an actual HTTP round trip through the address, socat, and to the real server is required before the proxy is considered ready, not just that the address shows up on the interface. A prior version of this checked only the interface, which has a real race between the address appearing and socat finishing its bind; the end-to-end check is what catches both that and a genuinely dropped LinkLocalIPs. Proven against a real Docker daemon: a plain container with its own 169.254.0.0/16 address (what the follow-up EcsContainerManager wiring gives each task container) fetches real credentials through the proxy end to end. That same test corrects an assumption from earlier discussion: a task container needs an address in that range to reach the proxy at all. Without one, its routing table has no connected route for 169.254.0.0/16, so the kernel routes toward the default gateway instead of resolving the peer directly, and the connection is refused before it reaches the proxy's socket, the same symptom a completely absent listener produces. This is exactly why the original design in #2987 gave every task container its own link-local address; that part of the design was right. EmulatorLifecycle now starts and stops the credentials server, and runs the session sweep, gated on the same enabled() flag: previously the flag did nothing at all, since nothing in main called it after three merged PRs. EcsCredentialsProxy also implements ContainerTeardown, so its proxy containers are removed on shutdown and on /state/reset instead of outliving either indefinitely. Full task wiring (EcsContainerManager actually issuing credentials and giving task containers their own link-local address) is still a separate follow-up.
This commit is contained in:
1 parent
f29c2b1c95
commit
0a4320132d
7 files changed
+882
-1
No files matched your search
@@ -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();
|
||||
}
|
||||
}
|
||||
+266
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+272
@@ -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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user