feat(ecs): give task containers their role credentials (#4486)

Wires the pieces together so a task that declares a taskRoleArn actually gets
credentials. EcsContainerManager issues the task's session, stands the proxy
up on the network its containers join, publishes one relative URI to every
container in the task the way real ECS does, and gives each container its own
address in 169.254.0.0/16 so it has a connected route to the endpoint at all.
Credentials and addresses are released when the task stops, exits, or fails
part way through a launch.

EcsTaskLinkLocalAddresses owns the addresses because Docker will not: it
accepts two containers claiming the same link-local address on one network
and then which one answers depends on whose ARP reply wins. Addresses are
tracked per network, since separate networks are separate L2 segments, and
freed with the task.

ContainerBuilder.resolveDockerNetwork exposes the network a spec would land
on, which the allocator needs before the spec exists. withDockerNetwork now
calls the same method rather than keeping a second copy of the resolution.

A security-group protected task is skipped for now and says so: those
containers run in an isolated helper namespace that the proxy's address does
not reach, so issuing credentials there would hand out an endpoint the task
cannot use.

Closes #4483.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-26 16:10:30 -05:00
1 parent 8b9f441bb4
commit 1451693cda
6 files changed
+833 -44

No files matched your search

@@ -67,6 +67,26 @@ public class ContainerBuilder {
return new Builder(resolveImage(image), config, dockerHostResolver, embeddedDnsServer, currentContainerNetworkResolver);
}
/**
* The Docker network a spec built with {@link Builder#withDockerNetwork} would land on: the
* service's own setting, else the global default, else the network Floci itself is attached
* to. Exposed because a caller occasionally needs that name before it has a spec to read it
* from, for instance to allocate an address on the network the container is about to join.
*/
public Optional<String> resolveDockerNetwork(Optional<String> serviceNetwork) {
return resolveDockerNetwork(serviceNetwork, config, currentContainerNetworkResolver);
}
private static Optional<String> resolveDockerNetwork(Optional<String> serviceNetwork, EmulatorConfig config,
CurrentContainerNetworkResolver currentContainerNetworkResolver) {
return serviceNetwork
.or(() -> config.services().dockerNetwork())
.filter(n -> !n.isBlank())
.or(() -> currentContainerNetworkResolver != null
? currentContainerNetworkResolver.resolveNetworkName()
: Optional.empty());
}
public String resolveImage(String image) {
return resolveImage(image, configuredImageRegistryBase(config));
}
@@ -336,13 +356,8 @@ public class ContainerBuilder {
* This is the standard pattern for Floci container services.
*/
public Builder withDockerNetwork(Optional<String> serviceNetwork) {
Optional<String> configuredNetwork = serviceNetwork
.or(() -> config.services().dockerNetwork())
.filter(n -> !n.isBlank())
.or(() -> currentContainerNetworkResolver != null
? currentContainerNetworkResolver.resolveNetworkName()
: Optional.empty());
configuredNetwork.ifPresent(n -> this.networkMode = n);
ContainerBuilder.resolveDockerNetwork(serviceNetwork, config, currentContainerNetworkResolver)
.ifPresent(n -> this.networkMode = n);
return this;
}
@@ -100,6 +100,12 @@ public class EcsContainerManager {
/** How long a container waits for a dependency that has to COMPLETE, SUCCEED or get HEALTHY. */
private static final int DEPENDENCY_WAIT_SECONDS = 60;
private static final long DEPENDENCY_POLL_MILLIS = 200;
/**
* The baseline credential variables that must not reach a container being given task-role
* credentials: the SDK would prefer them over the credential endpoint.
*/
private static final List<String> BASELINE_CREDENTIAL_KEYS =
List.of("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN");
/** How long a killed container gets to register as exited before its code is read. */
private static final int KILL_SETTLE_SECONDS = 5;
/** How long a stats sample gets before the task metadata endpoint answers without one. */
@@ -122,8 +128,11 @@ public class EcsContainerManager {
private final S3Service s3Service;
private final EcrRegistryManager ecrRegistryManager;
private final HostVolumePolicy hostVolumePolicy;
private Ec2Service ec2Service;
private SecurityGroupFirewallManager firewallManager;
private final Ec2Service ec2Service;
private final SecurityGroupFirewallManager firewallManager;
private final EcsTaskRoleCredentials taskRoleCredentials;
private final EcsCredentialsProxy credentialsProxy;
private final EcsTaskLinkLocalAddresses linkLocalAddresses;
@Inject
public EcsContainerManager(ContainerBuilder containerBuilder,
@@ -139,11 +148,27 @@ public class EcsContainerManager {
EcrRegistryManager ecrRegistryManager,
HostVolumePolicy hostVolumePolicy,
Ec2Service ec2Service,
SecurityGroupFirewallManager firewallManager) {
this(containerBuilder, lifecycleManager, logStreamer, containerDetector, config, regionResolver,
awsEnv, ssmService, secretsManagerService, s3Service, ecrRegistryManager, hostVolumePolicy);
SecurityGroupFirewallManager firewallManager,
EcsTaskRoleCredentials taskRoleCredentials,
EcsCredentialsProxy credentialsProxy,
EcsTaskLinkLocalAddresses linkLocalAddresses) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
this.containerDetector = containerDetector;
this.config = config;
this.regionResolver = regionResolver;
this.awsEnv = awsEnv;
this.ssmService = ssmService;
this.secretsManagerService = secretsManagerService;
this.s3Service = s3Service;
this.hostVolumePolicy = hostVolumePolicy;
this.ecrRegistryManager = ecrRegistryManager;
this.ec2Service = ec2Service;
this.firewallManager = firewallManager;
this.taskRoleCredentials = taskRoleCredentials;
this.credentialsProxy = credentialsProxy;
this.linkLocalAddresses = linkLocalAddresses;
}
public EcsContainerManager(ContainerBuilder containerBuilder,
@@ -158,18 +183,13 @@ public class EcsContainerManager {
S3Service s3Service,
EcrRegistryManager ecrRegistryManager,
HostVolumePolicy hostVolumePolicy) {
this.containerBuilder = containerBuilder;
this.lifecycleManager = lifecycleManager;
this.logStreamer = logStreamer;
this.containerDetector = containerDetector;
this.config = config;
this.regionResolver = regionResolver;
this.awsEnv = awsEnv;
this.ssmService = ssmService;
this.secretsManagerService = secretsManagerService;
this.s3Service = s3Service;
this.hostVolumePolicy = hostVolumePolicy;
this.ecrRegistryManager = ecrRegistryManager;
// The dependencies a caller can leave out: EC2 and the firewall for tasks that never use
// an ENI or a security group, and the three credential collaborators for a Floci that
// does not vend task-role credentials. Every call site that needs them uses the
// constructor above; the code paths that touch them all check first.
this(containerBuilder, lifecycleManager, logStreamer, containerDetector, config, regionResolver,
awsEnv, ssmService, secretsManagerService, s3Service, ecrRegistryManager, hostVolumePolicy,
null, null, null, null, null);
}
/**
@@ -213,32 +233,45 @@ public class EcsContainerManager {
}
Map<String, ContainerOverride> overridesByName = overridesByName(containerOverrides);
// Both resolved before any environment is built: whether the task gets role credentials
// decides whether its containers may also carry Floci's baseline static credentials,
// which would otherwise win over the role in the SDK credential chain.
PreparedNetwork protectedNetwork = prepareNetwork(task, taskDef, region, taskId);
TaskRoleCredentialEndpoint taskRoleEndpoint = prepareTaskRoleCredentials(task, taskDef, protectedNetwork);
Map<ContainerDefinition, List<String>> envVarsByContainer = new LinkedHashMap<>();
// Resolved before any container is created, so a registry-startup failure can't leak one already started.
Map<ContainerDefinition, String> imagesByContainer = new LinkedHashMap<>();
// The task metadata id has to exist before the container does: its own environment carries
// the URI, so it cannot be derived from the Docker id the daemon hands back afterwards.
Map<String, String> metadataIdsByContainer = new LinkedHashMap<>();
for (ContainerDefinition def : launchOrder) {
String metadataId = UUID.randomUUID().toString().replace("-", "");
metadataIdsByContainer.put(def.getName(), metadataId);
envVarsByContainer.put(def, buildEnvVars(def, overridesByName.get(def.getName()), region,
metadataId));
imagesByContainer.put(def, ecrRegistryManager.rewriteImageUri(def.getImage()));
}
PreparedNetwork protectedNetwork = prepareNetwork(task, taskDef, region, taskId);
String firelensVolumeName = null;
String firelensSocketAddress = null;
String firelensConfig = null;
String firelensExternalConfig = null;
if (firelensRouter != null) {
firelensConfig = firelensConfig(task, taskDef, firelensRouter, firelensLogOptions);
firelensExternalConfig = s3ExternalConfig(firelensRouter);
firelensVolumeName = ContainerStorageHelper.dockerName(config, "ecs-firelens-" + taskId);
lifecycleManager.ensureVolume(firelensVolumeName);
firelensSocketAddress = unixSocketAddress(firelensVolumeName);
try {
for (ContainerDefinition def : launchOrder) {
String metadataId = UUID.randomUUID().toString().replace("-", "");
metadataIdsByContainer.put(def.getName(), metadataId);
envVarsByContainer.put(def, buildEnvVars(def, overridesByName.get(def.getName()), region,
metadataId, taskRoleEndpoint.vending()));
imagesByContainer.put(def, ecrRegistryManager.rewriteImageUri(def.getImage()));
}
if (firelensRouter != null) {
firelensConfig = firelensConfig(task, taskDef, firelensRouter, firelensLogOptions);
firelensExternalConfig = s3ExternalConfig(firelensRouter);
firelensVolumeName = ContainerStorageHelper.dockerName(config, "ecs-firelens-" + taskId);
lifecycleManager.ensureVolume(firelensVolumeName);
firelensSocketAddress = unixSocketAddress(firelensVolumeName);
}
} catch (RuntimeException e) {
// Anything here can throw before a single container exists: an unresolvable secret,
// a registry that will not start, a FireLens config that will not render. The
// credentials are already issued by now and the caller only marks the task STOPPED,
// so without this they would stay valid with nothing behind them until they expire.
revokeTaskRoleCredentials(task.getTaskArn());
releaseTaskLinkLocalAddresses(task.getTaskArn());
throw e;
}
String fluentHost = null;
@@ -261,6 +294,11 @@ public class EcsContainerManager {
env.add("FLUENT_HOST=" + fluentHost);
env.add("FLUENT_PORT=" + FirelensConfigGenerator.FORWARD_PORT);
}
// Every container in the task is pointed at the same relative URI, the way real
// ECS vends one credential path per task rather than per container.
if (taskRoleEndpoint.vending()) {
env.add("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=" + taskRoleEndpoint.relativeUri());
}
// Build container spec
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(imagesByContainer.get(def))
@@ -279,6 +317,13 @@ public class EcsContainerManager {
specBuilder.withNetworkMode("container:" + protectedNetwork.namespace().helperId());
specBuilder.withLabels(Map.of("floci.security-group-workload", "true"));
}
// Its own address in the credential endpoint's range, so this container has a
// connected route to 169.254.170.2 at all. One per container, not per task: each
// has its own network namespace and so its own routing table.
if (taskRoleEndpoint.vending()) {
specBuilder.withLinkLocalIp(
linkLocalAddresses.allocate(taskRoleEndpoint.network(), task.getTaskArn()));
}
boolean awsFirelens = isAwsFirelens(def);
if (awsFirelens) {
@@ -451,8 +496,11 @@ public class EcsContainerManager {
}
}
} catch (Exception e) {
boolean allRemoved = true;
for (String dockerId : containerIds.values()) {
lifecycleManager.stopAndRemove(dockerId, null);
if (!stopAndConfirmRemoved(dockerId)) {
allRemoved = false;
}
}
if (firelensVolumeName != null) {
lifecycleManager.removeVolume(firelensVolumeName);
@@ -460,6 +508,12 @@ public class EcsContainerManager {
if (protectedNetwork != null) {
releaseTaskNetwork(task, region);
}
revokeTaskRoleCredentials(task.getTaskArn());
// A container left behind by a failed removal is still on the network holding its
// address, exactly as on the stop path.
if (allRemoved) {
releaseTaskLinkLocalAddresses(task.getTaskArn());
}
throw e;
}
@@ -1086,13 +1140,39 @@ public class EcsContainerManager {
if (handle == null) {
return;
}
boolean allRemoved = true;
for (String dockerId : handle.getContainerIds().values()) {
lifecycleManager.stopAndRemove(dockerId, null);
if (!stopAndConfirmRemoved(dockerId)) {
allRemoved = false;
}
}
cleanupProtectedNetwork(handle);
new ArrayList<>(handle.getLogStreamsByContainerId().keySet())
.forEach(dockerId -> finalizeLogStream(handle, dockerId));
removeFirelensVolume(handle);
revokeTaskRoleCredentials(handle.getTaskArn());
if (allRemoved) {
releaseTaskLinkLocalAddresses(handle.getTaskArn());
}
}
/**
* Stops and removes a container, reporting whether it is really gone.
*
* <p>{@code stopAndRemove} logs a failed removal and returns normally, which is the right
* default for callers that only want the container off the machine on a best-effort basis. It
* is not enough here: a container that survived removal still holds its link-local address,
* and releasing it would hand the same address to the next task. The strict variant throws on
* that case, which is the signal this needs.
*/
private boolean stopAndConfirmRemoved(String dockerId) {
try {
lifecycleManager.stopAndRemoveStrict(dockerId, null);
return true;
} catch (RuntimeException e) {
LOG.warnv("Error removing ECS container {0}: {1}", dockerId, e.getMessage());
return false;
}
}
/**
@@ -1160,7 +1240,15 @@ public class EcsContainerManager {
if (handle.allContainersRemoved()) {
cleanupProtectedNetwork(handle);
removeFirelensVolume(handle);
// Only now: a container that survived a failed removal still holds its address.
releaseTaskLinkLocalAddresses(handle.getTaskArn());
}
// Revoked whether or not removal succeeded, unlike everything above. A task being
// stopped must not keep usable credentials just because Docker could not remove one of
// its containers: the retry that would eventually revoke them depends on the handle
// being retained, which only happens while a log stream is still open, so a container
// without one (a FireLens router, say) would strand them for the life of the process.
revokeTaskRoleCredentials(handle.getTaskArn());
return exitCodes;
}
@@ -1445,6 +1533,102 @@ public class EcsContainerManager {
* it belongs to the task, not to its containers, and {@link #releaseTaskNetwork} frees it when
* the task reaches STOPPED.
*/
/**
* Issues the task's role credentials and makes sure the endpoint that serves them is up,
* before any of its containers start.
*
* <p>Empty when the task asks for no role, when the feature is off, when the role cannot be
* resolved, or when the task is security-group protected: those containers join an isolated
* helper namespace rather than the shared network the proxy holds its address on, so a proxy
* there would not be reachable and this refuses rather than handing out an endpoint the task
* cannot use. A proxy that cannot be established at all throws, since credentials whose
* endpoint is unreachable would fail later and further from the cause.
*/
private TaskRoleCredentialEndpoint prepareTaskRoleCredentials(EcsTask task, TaskDefinition taskDef,
PreparedNetwork protectedNetwork) {
String taskRoleArn = taskDef.getTaskRoleArn();
if (taskRoleArn == null || taskRoleArn.isBlank()) {
return TaskRoleCredentialEndpoint.none();
}
if (taskRoleCredentials == null || credentialsProxy == null
|| !config.services().ecs().taskRoleCredentials().enabled()) {
LOG.debugv("Task {0} asks for role {1}, but ECS task-role credentials are disabled",
task.getTaskArn(), taskRoleArn);
return TaskRoleCredentialEndpoint.none();
}
if (protectedNetwork != null) {
LOG.warnv("Task {0} asks for role {1}, but its containers run in a security-group protected "
+ "namespace, which the task-role credential endpoint does not reach yet",
task.getTaskArn(), taskRoleArn);
return TaskRoleCredentialEndpoint.none();
}
Optional<String> network = containerBuilder.resolveDockerNetwork(config.services().ecs().dockerNetwork());
if (network.isEmpty()) {
LOG.warnv("Task {0} asks for role {1}, but no Docker network is configured for ECS tasks, so "
+ "the credential endpoint has nowhere to listen", task.getTaskArn(), taskRoleArn);
return TaskRoleCredentialEndpoint.none();
}
Optional<String> relativeUri = taskRoleCredentials.issue(
task.getTaskArn(), taskRoleArn, regionResolver.getAccountId(), Instant.now());
if (relativeUri.isEmpty()) {
LOG.warnv("Task {0} asks for role {1}, which could not be resolved; its containers start "
+ "without AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", task.getTaskArn(), taskRoleArn);
return TaskRoleCredentialEndpoint.none();
}
try {
credentialsProxy.ensureProxyOn(network.get());
} catch (RuntimeException e) {
// The session is already registered at this point but the task will never start, and
// the launch-failure cleanup below only covers what happens after this method
// returns. Without this the credentials would stay valid with no task behind them.
revokeTaskRoleCredentials(task.getTaskArn());
releaseTaskLinkLocalAddresses(task.getTaskArn());
throw e;
}
return new TaskRoleCredentialEndpoint(relativeUri.get(), network.get());
}
/**
* Invalidates a task's credentials. Safe whenever the task is going away, and deliberately
* not conditional on cleanup having succeeded: a stopping task keeping usable credentials is
* worse than one whose containers are slow to disappear.
*/
private void revokeTaskRoleCredentials(String taskArn) {
if (taskRoleCredentials != null) {
taskRoleCredentials.revoke(taskArn);
}
}
/**
* Returns a task's addresses to the pool. Unlike the credentials above, this is only safe
* once its containers are actually gone: a container that outlived a failed removal still
* holds its address on the network, and handing the same one to the next task would make
* which container answers depend on ARP. An address left reserved is the cheaper mistake,
* the range is a /16 and a restart clears it.
*/
private void releaseTaskLinkLocalAddresses(String taskArn) {
if (linkLocalAddresses != null) {
linkLocalAddresses.releaseAll(taskArn);
}
}
/**
* What a task's containers need to reach the credential endpoint: the relative URI to publish
* to them, and the network to give each of them an address on. Both are set or neither is,
* which {@link #vending()} answers. Absence is a null rather than an {@code Optional} field,
* which this codebase does not use.
*/
private record TaskRoleCredentialEndpoint(String relativeUri, String network) {
static TaskRoleCredentialEndpoint none() {
return new TaskRoleCredentialEndpoint(null, null);
}
/** Whether this task gets credentials at all: both fields are set, or neither is. */
boolean vending() {
return relativeUri != null;
}
}
private void cleanupProtectedNetwork(EcsTaskHandle handle) {
if (firewallManager != null && handle.getNetworkInterfaceId() != null) {
firewallManager.unregister(handle.getNetworkInterfaceId());
@@ -1480,7 +1664,7 @@ public class EcsContainerManager {
}
private List<String> buildEnvVars(ContainerDefinition def, ContainerOverride override, String region,
String metadataId) {
String metadataId, boolean vendingTaskRoleCredentials) {
// AWS SDK baseline (endpoint + region + credentials) first so the task can reach the
// emulator, then the task-def environment, then task-def secrets, then the override
// environment. Later entries win on key conflict, so an explicit task-def value or
@@ -1492,6 +1676,15 @@ public class EcsContainerManager {
envMap.put(kv.substring(0, eq), kv.substring(eq + 1));
}
}
if (vendingTaskRoleCredentials) {
// The SDK credential chain reads the environment before the container-credentials
// endpoint (botocore resolves env_provider ahead of container_provider), so leaving
// the baseline keys in place would silently shadow the task role with Floci's own
// credentials and the role would never be used. Real ECS does not put these in a
// task container either. Removed before the task's own environment is applied, so a
// task that deliberately sets its own credentials still keeps them.
BASELINE_CREDENTIAL_KEYS.forEach(envMap::remove);
}
// The task metadata endpoint, which an application, the ECS SDK integrations and the
// aws-for-fluent-bit init process all read from this variable.
String flociEndpoint = awsEnv.flociEndpoint();
@@ -0,0 +1,85 @@
package io.github.hectorvent.floci.services.ecs.container;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Hands each task container its own address in 169.254.0.0/16, which is what lets it reach the
* credentials endpoint at all: without an address in that range the container's routing table has
* no connected route for it, so the kernel sends the packet to the default gateway instead of
* resolving the peer directly, and the connection is refused before it ever reaches the proxy.
*
* <p>Uniqueness is this class's job because Docker will not do it: two containers can be given the
* same link-local address on one network and the daemon accepts both, after which which one
* answers depends on whose ARP reply wins. Addresses are tracked per network, since separate
* Docker networks are separate L2 segments and can reuse the same address safely, and released
* when the task they belong to goes away so a long-running emulator does not leak the range.
*/
@ApplicationScoped
public class EcsTaskLinkLocalAddresses {
/** Held by the credentials proxy itself, so it is never handed to a task. */
static final String CREDENTIALS_ENDPOINT_ADDRESS = "169.254.170.2";
/**
* Allocation walks the /16 from 169.254.170.1 upward, stepping over the endpoint's own .2, so
* a task's addresses sit next to the proxy where someone debugging will look for them rather
* than somewhere unrelated in the range.
*/
private static final int FIRST_THIRD_OCTET = 170;
private final Map<String, Set<String>> takenByNetwork = new HashMap<>();
private final Map<String, List<Allocation>> byTaskArn = new HashMap<>();
/**
* Reserves an unused address on this network for a container of this task.
*
* @throws IllegalStateException if the whole range is already spoken for on that network,
* which takes more than 16,000 simultaneous task containers on one network
*/
public synchronized String allocate(String network, String taskArn) {
Set<String> taken = takenByNetwork.computeIfAbsent(network, ignored -> new HashSet<>());
// Linear from the start of the range each time rather than a moving cursor: a released
// address becomes immediately reusable, which matters more here than the scan cost at
// these sizes, and it keeps the addresses a person sees while debugging low and stable.
for (int offset = 0; offset < 256; offset++) {
int third = (FIRST_THIRD_OCTET + offset) % 256;
for (int fourth = 1; fourth <= 254; fourth++) {
String candidate = "169.254." + third + "." + fourth;
if (CREDENTIALS_ENDPOINT_ADDRESS.equals(candidate) || taken.contains(candidate)) {
continue;
}
taken.add(candidate);
byTaskArn.computeIfAbsent(taskArn, ignored -> new ArrayList<>())
.add(new Allocation(network, candidate));
return candidate;
}
}
throw new IllegalStateException(
"No link-local address left in 169.254.0.0/16 on network " + network);
}
/** Releases every address held by a task, on stop, exit, or a launch that failed part way. */
public synchronized void releaseAll(String taskArn) {
List<Allocation> allocations = byTaskArn.remove(taskArn);
if (allocations == null) {
return;
}
for (Allocation allocation : allocations) {
Set<String> taken = takenByNetwork.get(allocation.network());
if (taken != null) {
taken.remove(allocation.address());
if (taken.isEmpty()) {
takenByNetwork.remove(allocation.network());
}
}
}
}
private record Allocation(String network, String address) {}
}
@@ -89,7 +89,9 @@ class EcsContainerManagerSecurityGroupTest {
containerDetector, config, regionResolver, awsEnv,
mock(SsmService.class), mock(SecretsManagerService.class), mock(S3Service.class),
ecrRegistryManager, mock(HostVolumePolicy.class),
ec2Service, firewallManager);
ec2Service, firewallManager,
mock(EcsTaskRoleCredentials.class), mock(EcsCredentialsProxy.class),
new EcsTaskLinkLocalAddresses());
}
@Test
@@ -0,0 +1,400 @@
package io.github.hectorvent.floci.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
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.ContainerLifecycleManager.ContainerInfo;
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.KeyValuePair;
import io.github.hectorvent.floci.services.ecs.model.TaskDefinition;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
import io.github.hectorvent.floci.services.ssm.SsmService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doThrow;
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;
/**
* The manager's half of task-role credentials: issuing them for a task that asks for a role,
* standing the endpoint up on the task's network, pointing every container at the same relative
* URI, giving each its own address so it can reach that endpoint, and letting all of it go when
* the task does.
*/
class EcsContainerManagerTaskRoleCredentialsTest {
private static final String TASK_ARN = "arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/ecsTaskRole";
private static final String NETWORK = "floci-ecs-net";
private static final String RELATIVE_URI = "/v2/credentials/0b5f1a6e-8c21-4c2e-9a4c-2f0d2b6c7a10";
private ContainerBuilder.Builder builder;
private ContainerBuilder containerBuilder;
private EmulatorConfig config;
private EcsTaskRoleCredentials taskRoleCredentials;
private EcsCredentialsProxy credentialsProxy;
private EcsTaskLinkLocalAddresses linkLocalAddresses;
private EcsContainerManager manager;
@BeforeEach
void setUp() {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveDockerNetwork(any())).thenReturn(Optional.of(NETWORK));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(true);
LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
when(awsEnv.sdkBaselineEnv(anyString(), any())).thenReturn(List.of(
"AWS_REGION=us-east-1",
"AWS_ACCESS_KEY_ID=test",
"AWS_SECRET_ACCESS_KEY=test",
"AWS_SESSION_TOKEN=baseline-token",
"AWS_ENDPOINT_URL=http://localhost:4566"));
EcrRegistryManager ecrRegistryManager = mock(EcrRegistryManager.class);
when(ecrRegistryManager.rewriteImageUri(anyString())).thenAnswer(inv -> inv.getArgument(0));
taskRoleCredentials = mock(EcsTaskRoleCredentials.class);
when(taskRoleCredentials.issue(any(), any(), any(), any())).thenReturn(Optional.of(RELATIVE_URI));
credentialsProxy = mock(EcsCredentialsProxy.class);
linkLocalAddresses = new EcsTaskLinkLocalAddresses();
manager = new EcsContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config,
mock(RegionResolver.class), awsEnv, mock(SsmService.class),
mock(SecretsManagerService.class), mock(S3Service.class), ecrRegistryManager,
mock(HostVolumePolicy.class), null, null,
taskRoleCredentials, credentialsProxy, linkLocalAddresses);
}
@Test
void pointsEveryContainerOfATaskAtOneCredentialUriOnItsOwnAddress() {
manager.startTask(task(), taskDef(ROLE_ARN, "app", "sidecar"), null, "us-east-1");
verify(credentialsProxy).ensureProxyOn(NETWORK);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> env = ArgumentCaptor.forClass(List.class);
verify(builder, times(2)).withEnv(env.capture());
for (List<String> containerEnv : env.getAllValues()) {
assertTrue(containerEnv.contains("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=" + RELATIVE_URI),
"every container gets the task's relative URI: " + containerEnv);
}
// One address per container, and no two the same: they have separate routing tables, and
// Docker would happily accept a duplicate.
ArgumentCaptor<String> addresses = ArgumentCaptor.forClass(String.class);
verify(builder, times(2)).withLinkLocalIp(addresses.capture());
assertEquals(2, addresses.getAllValues().stream().distinct().count(),
"each container needs its own address: " + addresses.getAllValues());
}
@Test
void dropsTheBaselineCredentialsThatWouldShadowTheRole() {
manager.startTask(task(), taskDef(ROLE_ARN, "app"), null, "us-east-1");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> env = ArgumentCaptor.forClass(List.class);
verify(builder).withEnv(env.capture());
List<String> containerEnv = env.getValue();
// The SDK reads the environment before the container-credentials endpoint, so leaving
// these in place would silently use Floci's own credentials and never the task role.
assertTrue(containerEnv.stream().noneMatch(e -> e.startsWith("AWS_ACCESS_KEY_ID=")), containerEnv.toString());
assertTrue(containerEnv.stream().noneMatch(e -> e.startsWith("AWS_SECRET_ACCESS_KEY=")), containerEnv.toString());
assertTrue(containerEnv.stream().noneMatch(e -> e.startsWith("AWS_SESSION_TOKEN=")), containerEnv.toString());
// Everything else the task needs to reach Floci stays.
assertTrue(containerEnv.contains("AWS_ENDPOINT_URL=http://localhost:4566"), containerEnv.toString());
assertTrue(containerEnv.contains("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=" + RELATIVE_URI), containerEnv.toString());
}
@Test
void keepsTheBaselineCredentialsForATaskWithNoRole() {
manager.startTask(task(), taskDef(null, "app"), null, "us-east-1");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> env = ArgumentCaptor.forClass(List.class);
verify(builder).withEnv(env.capture());
assertTrue(env.getValue().contains("AWS_ACCESS_KEY_ID=test"), env.getValue().toString());
}
@Test
void keepsCredentialsATaskSetsForItselfEvenWhenVendingARole() {
TaskDefinition taskDef = taskDef(ROLE_ARN, "app");
taskDef.getContainerDefinitions().getFirst().setEnvironment(
List.of(new KeyValuePair("AWS_ACCESS_KEY_ID", "AKIAOWN")));
manager.startTask(task(), taskDef, null, "us-east-1");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> env = ArgumentCaptor.forClass(List.class);
verify(builder).withEnv(env.capture());
// Only the baseline is dropped; a credential the task deliberately sets is its own call.
assertTrue(env.getValue().contains("AWS_ACCESS_KEY_ID=AKIAOWN"), env.getValue().toString());
}
@Test
void revokesCredentialsWhenTheProxyCannotBeStarted() {
doThrow(new IllegalStateException("no route"))
.when(credentialsProxy).ensureProxyOn(any());
try {
manager.startTask(task(), taskDef(ROLE_ARN, "app"), null, "us-east-1");
} catch (RuntimeException expected) {
// The proxy failure itself is not what this test is about.
}
// The session was registered before the proxy was asked for, and the task never starts,
// so nothing else would ever revoke it.
verify(taskRoleCredentials).revoke(TASK_ARN);
}
@Test
void revokesCredentialsEvenWhenAContainerCouldNotBeRemoved() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
// Docker refuses the removal, so the task's containers never all come off.
when(dockerClient.removeContainerCmd("docker-id")).thenThrow(new IllegalStateException("in use"));
EcsContainerManager stopping = new EcsContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config,
mock(RegionResolver.class), mock(LaunchedContainerAwsEnv.class), mock(SsmService.class),
mock(SecretsManagerService.class), mock(S3Service.class), mock(EcrRegistryManager.class),
mock(HostVolumePolicy.class), null, null,
taskRoleCredentials, credentialsProxy, linkLocalAddresses);
stopping.stopTaskAndCollectExitCodes(new EcsTaskHandle(TASK_ARN, Map.of("app", "docker-id"), Map.of()));
// A stopping task must not keep usable credentials just because cleanup is unfinished:
// the retry that would release them depends on a handle this path may not retain.
verify(taskRoleCredentials).revoke(TASK_ARN);
}
@Test
void revokesCredentialsWhenPreflightFailsBeforeAnyContainerExists() {
EcrRegistryManager failingRegistry = mock(EcrRegistryManager.class);
when(failingRegistry.rewriteImageUri(anyString())).thenThrow(new IllegalStateException("registry down"));
EcsContainerManager failing = new EcsContainerManager(containerBuilder,
mock(ContainerLifecycleManager.class), mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), config, mock(RegionResolver.class),
baselineAwsEnv(), mock(SsmService.class), mock(SecretsManagerService.class),
mock(S3Service.class), failingRegistry, mock(HostVolumePolicy.class), null, null,
taskRoleCredentials, credentialsProxy, linkLocalAddresses);
try {
failing.startTask(task(), taskDef(ROLE_ARN, "app"), null, "us-east-1");
} catch (RuntimeException expected) {
// The preflight failure itself is not what this test is about.
}
// Issued before the preflight ran, and the caller only marks the task STOPPED, so
// nothing else would ever take these back.
verify(taskRoleCredentials).revoke(TASK_ARN);
}
@Test
void keepsAddressesReservedWhenAContainerCouldNotBeRemoved() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
when(dockerClient.removeContainerCmd("docker-id")).thenThrow(new IllegalStateException("in use"));
EcsContainerManager stopping = new EcsContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config,
mock(RegionResolver.class), baselineAwsEnv(), mock(SsmService.class),
mock(SecretsManagerService.class), mock(S3Service.class), mock(EcrRegistryManager.class),
mock(HostVolumePolicy.class), null, null,
taskRoleCredentials, credentialsProxy, linkLocalAddresses);
String held = linkLocalAddresses.allocate(NETWORK, TASK_ARN);
stopping.stopTaskAndCollectExitCodes(new EcsTaskHandle(TASK_ARN, Map.of("app", "docker-id"), Map.of()));
// That container may still be attached holding this address, so the next task must not
// be handed the same one, even though the credentials are already revoked.
assertNotEquals(held, linkLocalAddresses.allocate(NETWORK, "arn:aws:ecs:us-east-1:000000000000:task/c/next"));
verify(taskRoleCredentials).revoke(TASK_ARN);
}
@Test
void keepsAddressesReservedWhenCleanupCannotRemoveAContainer() {
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
// The reconciler's cleanup path is the other way a task's containers come off, and Docker
// can refuse a removal here just as it can on the stop path.
doThrow(new IllegalStateException("in use"))
.when(lifecycleManager).stopAndRemoveStrict("docker-id", null);
EcsContainerManager stopping = new EcsContainerManager(containerBuilder, lifecycleManager,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config,
mock(RegionResolver.class), baselineAwsEnv(), mock(SsmService.class),
mock(SecretsManagerService.class), mock(S3Service.class), rewritingRegistry(),
mock(HostVolumePolicy.class), null, null,
taskRoleCredentials, credentialsProxy, linkLocalAddresses);
EcsTaskHandle handle = stopping.startTask(task(), taskDef(ROLE_ARN, "app"), null, "us-east-1");
stopping.cleanupStoppedTask(handle);
verify(taskRoleCredentials).revoke(TASK_ARN);
// That container may still be attached holding the address it was given, so the next task
// must not be handed the same one.
assertNotEquals("169.254.170.1",
linkLocalAddresses.allocate(NETWORK, "arn:aws:ecs:us-east-1:000000000000:task/c/next"));
}
@Test
void keepsAddressesReservedWhenAFailedLaunchCannotRemoveAContainer() {
ContainerLifecycleManager failing = mock(ContainerLifecycleManager.class);
// The first container starts and the second does not, so the launch unwinds with one
// container already up and holding an address.
when(failing.createAndStart(any()))
.thenReturn(new ContainerInfo("docker-id", Map.of()))
.thenThrow(new IllegalStateException("no daemon"));
doThrow(new IllegalStateException("in use"))
.when(failing).stopAndRemoveStrict("docker-id", null);
EcsContainerManager failingManager = new EcsContainerManager(containerBuilder, failing,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config,
mock(RegionResolver.class), baselineAwsEnv(), mock(SsmService.class),
mock(SecretsManagerService.class), mock(S3Service.class), rewritingRegistry(),
mock(HostVolumePolicy.class), null, null,
taskRoleCredentials, credentialsProxy, linkLocalAddresses);
try {
failingManager.startTask(task(), taskDef(ROLE_ARN, "app", "sidecar"), null, "us-east-1");
} catch (RuntimeException expected) {
// The launch failure itself is not what this test is about.
}
verify(taskRoleCredentials).revoke(TASK_ARN);
assertNotEquals("169.254.170.1",
linkLocalAddresses.allocate(NETWORK, "arn:aws:ecs:us-east-1:000000000000:task/c/next"));
}
@Test
void issuesNothingForATaskWithNoRole() {
manager.startTask(task(), taskDef(null, "app"), null, "us-east-1");
verify(taskRoleCredentials, never()).issue(any(), any(), any(), any());
verify(credentialsProxy, never()).ensureProxyOn(any());
verify(builder, never()).withLinkLocalIp(any());
}
@Test
void issuesNothingWhenTheFeatureIsDisabled() {
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(false);
manager.startTask(task(), taskDef(ROLE_ARN, "app"), null, "us-east-1");
verify(taskRoleCredentials, never()).issue(any(), any(), any(), any());
verify(credentialsProxy, never()).ensureProxyOn(any());
}
@Test
void startsNoProxyAndPublishesNoUriWhenTheRoleCannotBeResolved() {
when(taskRoleCredentials.issue(any(), any(), any(), any())).thenReturn(Optional.empty());
manager.startTask(task(), taskDef(ROLE_ARN, "app"), null, "us-east-1");
// Issuing failed, so there is nothing to reach: no proxy, no address, no env var.
verify(credentialsProxy, never()).ensureProxyOn(any());
verify(builder, never()).withLinkLocalIp(any());
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> env = ArgumentCaptor.forClass(List.class);
verify(builder).withEnv(env.capture());
assertTrue(env.getValue().stream().noneMatch(e -> e.startsWith("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")),
env.getValue().toString());
}
@Test
void revokesCredentialsAndFreesAddressesWhenTheTaskStops() {
EcsTaskHandle handle = manager.startTask(task(), taskDef(ROLE_ARN, "app", "sidecar"), null, "us-east-1");
manager.cleanupStoppedTask(handle);
verify(taskRoleCredentials).revoke(TASK_ARN);
// The two addresses that task held are back in the pool, so the next task gets them.
String reused = linkLocalAddresses.allocate(NETWORK, "arn:aws:ecs:us-east-1:000000000000:task/c/next");
assertEquals("169.254.170.1", reused);
}
@Test
void revokesCredentialsWhenTheLaunchFailsPartWayThrough() {
ContainerLifecycleManager failing = mock(ContainerLifecycleManager.class);
when(failing.createAndStart(any())).thenThrow(new IllegalStateException("no daemon"));
EcsContainerManager failingManager = new EcsContainerManager(containerBuilder, failing,
mock(ContainerLogStreamer.class), mock(ContainerDetector.class), config,
mock(RegionResolver.class), mock(LaunchedContainerAwsEnv.class), mock(SsmService.class),
mock(SecretsManagerService.class), mock(S3Service.class), rewritingRegistry(),
mock(HostVolumePolicy.class), null, null,
taskRoleCredentials, credentialsProxy, linkLocalAddresses);
try {
failingManager.startTask(task(), taskDef(ROLE_ARN, "app"), null, "us-east-1");
} catch (RuntimeException expected) {
// The launch failure itself is not what this test is about.
}
verify(taskRoleCredentials).revoke(TASK_ARN);
assertEquals("169.254.170.1", linkLocalAddresses.allocate(NETWORK, "arn:aws:ecs:us-east-1:000000000000:task/c/next"));
}
private LaunchedContainerAwsEnv baselineAwsEnv() {
LaunchedContainerAwsEnv env = mock(LaunchedContainerAwsEnv.class);
when(env.sdkBaselineEnv(anyString(), any())).thenReturn(List.of("AWS_ACCESS_KEY_ID=test"));
return env;
}
private EcrRegistryManager rewritingRegistry() {
EcrRegistryManager registry = mock(EcrRegistryManager.class);
when(registry.rewriteImageUri(anyString())).thenAnswer(inv -> inv.getArgument(0));
return registry;
}
private static EcsTask task() {
EcsTask task = new EcsTask();
task.setTaskArn(TASK_ARN);
return task;
}
private static TaskDefinition taskDef(String roleArn, String... containerNames) {
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("test-family");
taskDef.setTaskRoleArn(roleArn);
taskDef.setContainerDefinitions(Arrays.stream(containerNames).map(name -> {
ContainerDefinition def = new ContainerDefinition();
def.setName(name);
def.setImage(name + ":latest");
return def;
}).toList());
return taskDef;
}
}
@@ -0,0 +1,94 @@
package io.github.hectorvent.floci.services.ecs.container;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class EcsTaskLinkLocalAddressesTest {
private static final String NETWORK = "floci-net";
private static final String OTHER_NETWORK = "floci-other-net";
private static final String TASK = "arn:aws:ecs:us-east-1:000000000000:task/cluster/abc";
private static final String OTHER_TASK = "arn:aws:ecs:us-east-1:000000000000:task/cluster/def";
private EcsTaskLinkLocalAddresses addresses;
@BeforeEach
void setUp() {
addresses = new EcsTaskLinkLocalAddresses();
}
@Test
void handsOutDistinctAddressesOnOneNetwork() {
Set<String> seen = new HashSet<>();
for (int i = 0; i < 50; i++) {
assertTrue(seen.add(addresses.allocate(NETWORK, TASK)), "handed out a duplicate at " + i);
}
}
@Test
void neverHandsOutTheAddressTheProxyHolds() {
// Walk past where .2 sits so the skip is actually exercised rather than assumed.
for (int i = 0; i < 20; i++) {
assertNotEquals(EcsTaskLinkLocalAddresses.CREDENTIALS_ENDPOINT_ADDRESS,
addresses.allocate(NETWORK, TASK));
}
}
@Test
void allocatesFromTheProxysOwnSubnetSteppingOverItsAddress() {
assertEquals("169.254.170.1", addresses.allocate(NETWORK, TASK));
// .2 belongs to the proxy, so the next one skips it.
assertEquals("169.254.170.3", addresses.allocate(NETWORK, TASK));
assertEquals("169.254.170.4", addresses.allocate(NETWORK, TASK));
}
@Test
void separateNetworksReuseTheSameAddressesIndependently() {
String first = addresses.allocate(NETWORK, TASK);
String onOtherNetwork = addresses.allocate(OTHER_NETWORK, OTHER_TASK);
// Different L2 segments: the same address on each is not a conflict.
assertEquals(first, onOtherNetwork);
}
@Test
void releasingATaskFreesItsAddressesForReuse() {
String first = addresses.allocate(NETWORK, TASK);
String second = addresses.allocate(NETWORK, TASK);
String heldByAnotherTask = addresses.allocate(NETWORK, OTHER_TASK);
addresses.releaseAll(TASK);
// The other task's address stays held, so the freed ones come back before it.
Set<String> reused = Set.of(addresses.allocate(NETWORK, TASK), addresses.allocate(NETWORK, TASK));
assertEquals(Set.of(first, second), reused);
assertNotEquals(heldByAnotherTask, addresses.allocate(NETWORK, TASK));
}
@Test
void releasingAnUnknownTaskIsANoOp() {
addresses.releaseAll("arn:aws:ecs:us-east-1:000000000000:task/cluster/never-allocated");
}
@Test
void releasingOneTaskLeavesAnotherTasksAddressesAlone() {
String mine = addresses.allocate(NETWORK, TASK);
String theirs = addresses.allocate(NETWORK, OTHER_TASK);
addresses.releaseAll(OTHER_TASK);
Set<String> next = new HashSet<>();
for (int i = 0; i < 3; i++) {
next.add(addresses.allocate(NETWORK, TASK));
}
assertTrue(next.contains(theirs), "the released address should be reusable");
assertTrue(!next.contains(mine), "an address still held must not be handed out again");
}
}